@flopay/react 1.14.0 → 1.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -1
- package/dist/chunk-MSABDKVT.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-ULXLO3FW.mjs +1 -0
- package/package.json +3 -3
- package/dist/chunk-H4MQCBX4.mjs +0 -22
- package/dist/payment-method-setup-stripe-6O2YE4RY.mjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Lc=Object.create;var Wa=Object.defineProperty;var Nc=Object.getOwnPropertyDescriptor;var Uc=Object.getOwnPropertyNames;var zc=Object.getPrototypeOf,qc=Object.prototype.hasOwnProperty;var jc=(e,t)=>{for(var r in t)Wa(e,r,{get:t[r],enumerable:!0})},cl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Uc(t))!qc.call(e,a)&&a!==r&&Wa(e,a,{get:()=>t[a],enumerable:!(n=Nc(t,a))||n.enumerable});return e};var Wi=(e,t,r)=>(r=e!=null?Lc(zc(e)):{},cl(t||!e||!e.__esModule?Wa(r,"default",{value:e,enumerable:!0}):r,e)),Vc=e=>cl(Wa({},"__esModule",{value:!0}),e);var hu={};jc(hu,{DirectPayPalButton:()=>ha,FloPayAutomaticPaymentButton:()=>ac,FloPayCardSetup:()=>ic,FloPayCardSetupError:()=>xa,FloPayCheckout:()=>vi,FloPayPaymentMethodSetup:()=>hc,FloPayProvider:()=>va,SplitCardForm:()=>fi,VaultCardFields:()=>co,dropThirdPartyOnlyError:()=>vc.dropThirdPartyOnlyError,useCheckout:()=>Cl,useFloPay:()=>Qn,usePayPalFloPay:()=>Ga});module.exports=Vc(hu);var vc=require("@flopay/shared");var Ci=require("@flopay/js"),gn=require("@flopay/shared"),yt=require("react");var Kt=require("react/jsx-runtime");function Wc(){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 $c(){return(0,Kt.jsx)(Kt.Fragment,{children:"Go back"})}function Hc(){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)(Wc,{}):e})}function Oo({content:e}){return(0,Kt.jsx)(Kt.Fragment,{children:e===void 0?(0,Kt.jsx)($c,{}):e})}function ua({content:e}){return(0,Kt.jsx)(Kt.Fragment,{children:e===void 0?(0,Kt.jsx)(Hc,{}):e})}var Pt=require("@flopay/shared"),kn=require("@flopay/shared"),Uo=require("@flopay/shared"),vo=require("@flopay/shared"),Kc="Checkout is temporarily unavailable. Please try again later.";function $i(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Pt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Gc(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 dl(){return new Pt.FloPayError(Kc,"api_error",{code:"CheckoutInitializationFailed"})}function ul(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,Pt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,Pt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function pl(e,t){if(t&&(!(e instanceof Pt.FloPayError)||e.type==="authentication_error"))return $i(e);if(!(e instanceof Pt.FloPayError&&Gc(e))){if(!t&&!(e instanceof Pt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Pt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Pt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Pt.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,Pt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,Pt.isValidEmail)(l.email))return Promise.reject(new Pt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[P,E]of Object.entries(l)){if(u&&P.endsWith("Name")||typeof E!="string")continue;let S=E.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 yl(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 fl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function $a(e){let t=fl(e);return new Pt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Ha(e){return e instanceof Pt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function No(e){return fl(e)?new Pt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Pt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Pt.FloPayError(Pt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function pa(e,t){return e==="processing"||(0,Pt.isMoneySettledOutcome)(e,t)}function gl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function hl(e,t){let r=e;if((0,Pt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:i,error:l}=await r.retrieveSetupIntent(t);if(l)throw new Pt.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 Pt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var Yc=["apple_pay","google_pay"];function Pl(e,t="automatic",r){let n=(0,Pt.resolveSetupFutureUsage)(r,Yc,"wallet");return{...(0,Pt.resolveWalletModeOptions)(e,t),paymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Xc=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:Xc.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"),Ke=require("@flopay/shared"),C=Wi(require("react"),1);var Yi=require("react"),dn=(0,Yi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Rn=(0,Yi.createContext)({session:null,loading:!1,error:null});var Za=require("@flopay/js"),rt=require("@flopay/shared"),kl=require("@paypal/paypal-js"),R=require("react");var Ka=require("@flopay/shared"),En=require("react"),un=require("@flopay/shared"),Zn=require("react/jsx-runtime");function zo(){let[e,t]=(0,En.useState)(null),r=(0,En.useRef)(null),n=(0,En.useRef)(0),a=(0,En.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,En.useCallback)(l=>{let u=r.current;r.current=null,t(null),u?.(l)},[]);return(0,En.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,En.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 Se=require("@flopay/shared");var vl=require("@flopay/shared"),ya=require("react");function Qn(){return(0,ya.useContext)(dn).flopay}function Ga(){return(0,ya.useContext)(dn).paypalFlopay??null}function Cl(){return(0,ya.useContext)(Rn)}function bl(){return(0,ya.useContext)(dn).billingApiUrl||(0,vl.resolveBillingApiUrl)()}var Jc=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 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 tt=require("@flopay/shared");var Sl=require("react"),fa=(0,Sl.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 Zc=Symbol.for("@flopay/js.telemetry.bridge.v1"),Qc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ed(){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 td(e){let t=ed(),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[Qc];return td(t?.(e)??{})}function Pr(e){if(e)return e[Zc]}var dr=require("react");function ga(e,t){let r=(0,dr.useRef)(0),n=(0,dr.useRef)(null),a=(0,dr.useRef)(null),i=(0,dr.useRef)(e),l=(0,dr.useRef)(t?.onHandoffObserved),u=(0,dr.useRef)(t?.defersMissingTerminal),p=(0,dr.useRef)(t?.onMissingTerminalDeferred);(0,dr.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,dr.useCallback)((y=a.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),E=(0,dr.useCallback)(y=>{P();let v=r.current+1;return r.current=v,n.current=null,a.current={generation:v,method:y,timer:null,yieldedControl:!1},v},[P]),S=(0,dr.useCallback)(y=>{let v=a.current;return y!==void 0&&v?.generation!==y?!1:(P(v),a.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[P]),I=(0,dr.useCallback)(y=>{let v=a.current,pe=y??v?.generation??r.current;(y===void 0||v?.generation===y)&&(P(v),a.current=null),n.current=pe},[P]),K=(0,dr.useCallback)(y=>n.current===(y??r.current),[]),_=(0,dr.useCallback)(y=>a.current?.generation===y&&n.current!==y,[]),X=(0,dr.useCallback)(()=>{let y=a.current;y&&(P(y),!y.yieldedControl&&(y.yieldedControl=!0,l.current?.(y.method)))},[P]),T=(0,dr.useCallback)(()=>{let y=a.current;!y?.yieldedControl||document.visibilityState!=="visible"||(P(y),y.timer=setTimeout(()=>{if(y.timer=null,a.current?.generation===y.generation){if(u.current?.(y.method)){p.current?.(y.method,y.generation);return}a.current=null,n.current=y.generation,i.current(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},Se.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[P]);return(0,dr.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?T():X()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",X),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",X),window.removeEventListener("focus",T),P()}},[P,X,T]),{startAttempt:E,finishAttempt:S,invalidateAttempt:I,isAttemptInvalidated:K,isAttemptCurrent:_,generationRef:r}}var pn=require("react/jsx-runtime"),Qa=45,rd=1e3,nd=11e3,od={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"},ad={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 id(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:ad[e.kind]??null}}function wl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,Se.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function sd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Rl({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:i,clientId:l,environment:u,currency:p,isSubscription:P,providerObjectType:E,approvalPresentation:S,onTokenizedBody:I,onComplete:K,onErrorChange:_,onDecline:X,onCancel:T,onTechnicalFailure:y,isProcessing:v=!1,onLoadStateChange:pe,onInitializationStateChange:b,allowAutomaticRetry:Te=!0,onButtonClick:B,runBeforeButtonClick:ae,session:me,existingOrderId:ue,telemetry:Ae,telemetryContext:ct,onInstrument:Ge,debug:D=!1}){let bt=Qn(),Xe=Vo(Ge,e),Le=(0,R.useMemo)(()=>{if(bt)return null;let Y=Ja({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:rt.SDK_VERSION,enabled:Ae!==!1});return Y.setCheckoutContext(ct??{}),Y.beginCheckout(ct??{}),Y},[r,bt,Ae,ct?.checkoutMode,ct?.layout]),fe=(0,R.useMemo)(()=>Pr(bt),[bt]);(0,R.useEffect)(()=>()=>{Le&&Le.flush().catch(()=>{}).finally(()=>Le.destroy())},[Le]);let J=(0,R.useMemo)(()=>({error:Y=>{fe?fe.error(Y):Le?.error(Y),Xe({class:"technical_error",errorCode:Y.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":Y.errorCode,requestCategory:Y.requestCategory,provider:Y.provider})},log:Y=>{fe?fe.log(Y):Le?.log(Y),Xe({class:"lifecycle",name:Y.name,provider:Y.provider})},performance:Y=>{fe?fe.performance(Y):Le?.performance(Y)},terminal:Y=>{fe?fe.terminal(Y):Le?.terminal(Y)},startTiming:()=>fe?.now()??Le?.now()??0,elapsed:Y=>fe?.elapsed(Y)??Math.max(0,(Le?.now()??Y)-Y)}),[Xe,fe,Le]),G=(0,R.useRef)(null),Fe=(0,R.useRef)(0),je=(0,R.useRef)(null),Je=(0,R.useRef)(null),re=(0,R.useRef)(null),Q=(0,R.useContext)(fa),se=(0,R.useRef)(null);se.current||(se.current=Xa());let W=Q??se.current,We=(0,R.useRef)(null),Be=(0,R.useRef)(!1),[ge,N]=(0,R.useState)(!1),[Ce,dt]=(0,R.useState)(!1),[Ne,at]=(0,R.useState)(0),Me=(0,R.useRef)(0),[nt,it]=(0,R.useState)(!1),ar=(0,R.useRef)(!1),Dt=(0,R.useRef)(!1),[St,we]=(0,R.useState)(!1),[M,ft]=(0,R.useState)(!1),{request:ut,collect:z,finish:ke}=zo(),Nt=(0,R.useRef)({sessionId:e,required:(0,rt.paypalProviderIdentityRequired)(n,me)});Nt.current.sessionId!==e&&(Nt.current={sessionId:e,required:(0,rt.paypalProviderIdentityRequired)(n,me)});let Ue=Nt.current.required,Mt=(0,R.useMemo)(()=>r.replace(/\/+$/,""),[r]),O=me?.gateways?.paypal?.providerObjectType??E,$e=O??(P?"subscription":"order"),[Re]=(0,R.useState)(Un.detectPayPalEnvironment),h=me?.gateways?.paypal?.approvalPresentation??S,ce=(0,zn.resolvePayPalPresentationMode)(Re,h==="app_switch"?"app_switch":void 0,$e),q=(0,rt.usesPayPalVaultedChannel)(O),V=(0,R.useMemo)(()=>JSON.stringify([Mt,l,p,u??"",$e,q,ce,e,ue??""]),[Mt,l,p,u,ue,$e,q,ce,e]),De=(0,R.useRef)(V),f=De.current!==V,he=(0,R.useRef)(D),ye=(0,R.useRef)(null),[gt,x]=(0,R.useState)([]),be=(0,R.useCallback)(Y=>{he.current&&x(Z=>[...Z,`${new Date().toISOString().slice(11,23)} ${Y}`])},[]);(0,R.useEffect)(()=>{he.current=D,D&&be("debug:enabled"),ye.current?.setEnabled(D)},[be,D]);let Gt=(0,R.useRef)(I),br=(0,R.useRef)(K),Tr=(0,R.useRef)(_),xt=(0,R.useRef)(X),Kr=(0,R.useRef)(T),Lr=(0,R.useRef)(y),Sr=(0,R.useRef)(B),ir=(0,R.useRef)(pe),Nr=(0,R.useRef)(b),Yt=(0,R.useRef)(i),Mn=(0,R.useRef)(ae),Wt=(0,R.useRef)(me),vt=(0,R.useRef)(n),_t=(0,R.useRef)(a),yr=(0,R.useRef)(t),jt=(0,R.useRef)(null),Jt=(0,R.useRef)(new Map),nn=(0,R.useRef)(new Map),Ur=(0,R.useRef)(!1);(0,R.useEffect)(()=>(Ur.current=!0,()=>{Ur.current=!1}),[]),(0,R.useEffect)(()=>{Gt.current=I},[I]),(0,R.useEffect)(()=>{Yt.current=i},[i]),(0,R.useEffect)(()=>{br.current=K},[K]),(0,R.useEffect)(()=>{Tr.current=_},[_]),(0,R.useEffect)(()=>{xt.current=X},[X]),(0,R.useEffect)(()=>{Kr.current=T},[T]),(0,R.useEffect)(()=>{Lr.current=y},[y]),(0,R.useEffect)(()=>{Sr.current=B},[B]),(0,R.useEffect)(()=>{ir.current=pe},[pe]),(0,R.useEffect)(()=>{Nr.current=b},[b]),(0,R.useEffect)(()=>{Mn.current=ae},[ae]),(0,R.useEffect)(()=>{Wt.current=me},[me]),(0,R.useEffect)(()=>{vt.current=n},[n]),(0,R.useEffect)(()=>{_t.current=a},[a]),(0,R.useEffect)(()=>{yr.current=t},[t]),(0,R.useEffect)(()=>{Me.current=Ne},[Ne]),(0,R.useEffect)(()=>{nt&&We.current?.focus()},[nt,Ne]);let wr=(0,R.useCallback)(()=>{window.setTimeout(()=>{We.current?.focus()},0)},[]),kr=(0,R.useCallback)(()=>{N(!1),at(Y=>Y+1)},[]),fr=(0,R.useCallback)(()=>{it(!1),(G.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??G.current)?.focus?.()},[]);(0,R.useEffect)(()=>{!ge||!Be.current||(Be.current=!1,fr())},[fr,ge,Ne]);let Zt=(0,R.useCallback)((Y,Z)=>{let te=Z?.popupBlocked??(0,Se.isPopupBlockedError)(Y);te&&W.markBlocked();let Lt=(0,Se.buildExternalMethodRecoveryMessage)("PayPal",te,Re.inAppBrowser),Tt=Lr.current;if(Tt){let Bt=te&&Re.inAppBrowser?new rt.FloPayError(Lt,"api_error",{code:Z?.code??"paypal_popup_blocked"}):Y;Tt("paypal",Bt,Z);return}Tr.current?.(Lt)},[W,Re.inAppBrowser]),Ft=(0,R.useCallback)(Y=>{let Z=je.current,te=Je.current;Z===null||!te||(J.log({...te,popupCapability:W.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Y}),J.performance({...te,popupCapability:W.current(),stage:"overlay_return",durationMs:J.elapsed(Z),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Y}),je.current=null)},[W,J]),pr=(0,R.useCallback)((Y,Z,te)=>{let Lt=Je.current;Ft("overlay_timeout"),Lt&&J.error({...Lt,popupCapability:W.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Zt(Z,{...te,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ce,terminalReason:"overlay_timeout"}),it(!0),kr(),wr()},[Ft,wr,Zt,W,ce,kr,J]),Rr=(0,R.useCallback)(()=>{W.markAvailable();let Y=Je.current;Y&&(re.current=Y.attempt,J.log({...Y,popupCapability:W.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[W,J]),{finishAttempt:$t,generationRef:Ze,invalidateAttempt:zr,isAttemptCurrent:Gr,isAttemptInvalidated:Ar,startAttempt:sr}=ga(pr,{onHandoffObserved:Rr}),hn=(0,R.useCallback)(()=>(it(!1),sr("paypal")),[sr]),xn=(0,R.useCallback)(Y=>{zr(Y?.generation),Y?.showRetry&&it(!0),Y?.remount&&kr(),Y?.focus!==!1&&wr()},[wr,zr,kr]),on=Y=>{let Z=jt.current;return Z&&nn.current.set(Y,Z),Y};(0,R.useEffect)(()=>{De.current!==V&&(De.current=V,ar.current=!1,Dt.current=!1,N(!1),dt(!1),we(!1),Nr.current?.("loading"))},[V]),(0,R.useEffect)(()=>{(0,tt.invokeMerchantCallback)(()=>ir.current?.(ge&&!St))},[ge,St]);let Ot=(0,rt.normalizeGatewayEnvironment)(u);(0,R.useEffect)(()=>{let Y={attempt:Ze.current+1,inAppBrowser:Re.inAppBrowser,appFamily:Re.appFamily,popupCapability:W.current(),presentationMode:ce},Z=()=>({...Je.current??Y,popupCapability:W.current()}),te={error:g=>J.error({...g,...Z()}),log:g=>J.log({...g,...Z()}),performance:g=>J.performance({...g,...Z()}),terminal:g=>J.terminal({...g,...Z()}),startTiming:J.startTiming,elapsed:J.elapsed},Lt=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Tt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(be(`mount clientId=${Lt} env=${u??"(unset)"}\u2192${Ot??"live"} ccy=${p} sub=${P}`),be(`ua=${Tt.slice(0,80)}${Tt.length>80?"\u2026":""}`),!l){be("FAIL: clientId empty \u2014 gateway misconfigured"),we(!0),te.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){be("FAIL: containerRef not attached");return}Fe.current=te.startTiming(),te.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Bt=!1,Fr=!1,kt=()=>Bt||Fr,oo=q?$e:void 0,Ut,Yr=!1,An=()=>{Ut=(0,rt.generateIdempotencyKey)(),Ut||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Yr=!0},an=null,Qt=!1,Pn=null,$n=!1,Fn=()=>{!Pn||$n||($n=!0,Pn.close().catch(()=>{}))},Br=!1,ao=!1,sn=G.current,Hn=null,Xr=null,vn=[],Bn=null,zt=!1,Jr=!1,Zr=null,qr=g=>{if(!g||typeof g.getBoundingClientRect!="function")return"(no rect)";let m=g.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},Cn=g=>{if(!g)return"(empty)";try{let m=new URL(g,typeof window>"u"?"https://localhost":window.location.href),H=m.pathname.toLowerCase();return H.includes("checkcaptcha")||H.includes("captcha")?`CAPTCHA(${m.host}${H})`:H.includes("risk")||H.includes("challenge")?`RISK(${m.host}${H})`:H.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${H}`.slice(0,100)}catch{return g.slice(0,80)}},Ct=g=>{let m=g.getAttribute("src"),H=g.getAttribute("srcdoc"),Ie=g.getAttribute("name"),Qe=g.getAttribute("sandbox"),pt=[];return m&&pt.push(`src=${Cn(m)}`),H&&pt.push(`srcdoc[${H.length}ch]`),!m&&!H&&pt.push("src=(empty) srcdoc=(empty)"),Ie&&pt.push(`name=${Ie.slice(0,40)}`),Qe!==null&&pt.push(`sandbox="${Qe.slice(0,40)}"`),pt.join(" ")},Er=g=>{if(!(g instanceof HTMLIFrameElement))return"";try{let m=g.contentDocument;if(!m)return"cd=null";let H=m.body?.children.length??0,Ie=m.body?.innerHTML.length??0,Qe=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${H}children,${Ie}ch] head[${Qe}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},lr=[],jr=g=>{if(kt())return;let m=g.message??String(g.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(be(`window:error ${m.slice(0,140)}`),lr.push(m))},mo=g=>{if(kt())return;let m=g.reason instanceof Error?g.reason.message:String(g.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(be(`window:rejection ${m.slice(0,140)}`),lr.push(m))},bn={value:0},Kn=()=>{Hn?.disconnect(),Hn=null,Xr?.disconnect(),Xr=null;for(let g of vn.splice(0))clearTimeout(g);Jr=!1,zt&&typeof window<"u"&&(window.removeEventListener("error",jr),window.removeEventListener("unhandledrejection",mo)),zt=!1},Qr=()=>{if(!(zt||kt()||Br)){if(zt=!0,lr.length=0,bn.value=0,typeof window<"u"&&(window.addEventListener("error",jr),window.addEventListener("unhandledrejection",mo)),typeof PerformanceObserver<"u")try{Xr=new PerformanceObserver(g=>{if(!kt())for(let m of g.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;bn.value+=1;let H=Math.round(m.duration);be(`net ${H}ms ${m.name.slice(0,90)}`)}}),Xr.observe({type:"resource",buffered:!0})}catch{}Zr?.()}},Ir=()=>{Bn&&(clearTimeout(Bn),Bn=null)},Dn=()=>{Kn(),Ir()},Mr={setEnabled:g=>{g?Qr():Kn()}};ye.current=Mr,he.current&&Qr();let L=rt.isPayPalTeardownMessage,U=g=>{if(kt()||L(g))return;let m=(0,vo.applyFriendlyMessageOverride)(g)??g;(0,tt.invokeMerchantCallback)(()=>Tr.current?.(m))},ee=(g,m)=>{if(Bt||Qt)return;Qt=!0,Fr=!0,Dn(),Fn();let H=id({kind:g,generationActive:!0,automaticRetryAllowed:Te,automaticRetryUsed:ar.current});if(H.action==="retry"){ar.current=!0,N(!1),ft(!1),dt(!0),Nr.current?.("retrying"),an=setTimeout(()=>{Bt||at(Ie=>Ie+1)},rd);return}if(N(!1),ft(!1),dt(!1),we(!0),H.action!=="ignore"){if(Nr.current?.("exhausted"),H.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",m);return}if(H.report){let Ie=(0,Se.classifyExternalMethodFailure)({code:wl(g,m),message:m},{inAppBrowser:Re.inAppBrowser,handoffObserved:!1});Ie.popupBlocked&&W.markBlocked(),te.error({errorCode:Ie.popupBlocked?Ie.errorCode:H.report.errorCode,stage:H.report.stage,operationOutcome:H.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:Ie.terminalReason})}Dt.current||(Dt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",wl(g,m)))}};we(!1);let Ee=async(g,m=jt.current)=>{if(kt())return;let H=m?.sessionId??e;if(Gt.current){await Gt.current(g,{sessionId:H,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let Ie=te.startTiming();te.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Qe=()=>{te.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"processing",durationMs:te.elapsed(Ie),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let pt=(0,rt.buildPayPalProcessPaymentRequest)({body:g,sessionId:H,nonce:m?.nonce??yr.current,accountPatch:m?.accountPatch,session:Wt.current,email:vt.current}),Oe=await new Za.PaymentAPI(Mt,{telemetry:!1}).processPayment(pt.userId,pt.params);if(Oe.ok){if(Fr||Bt&&Ur.current)return;Qe(),te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,tt.invokeMerchantCallback)(()=>br.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(kt())return;let st=await Oe.json().catch(()=>null),wt=(0,rt.describePayPalProcessFailure)(st),Et=wt.message;Qe(),Oe.status===400&&(typeof st?.declineCode=="string"||!Array.isArray(st?.fields))?te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Oe.status===400||Oe.status===422?te.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):te.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:sd(Oe.status),failureCategory:Oe.status>=500?"server_error":void 0}),U(Et),(0,tt.invokeMerchantCallback)(()=>xt.current?.(hr("paypal",Et,{code:wt.code,declineCode:wt.declineCode})));return}catch(pt){if(kt())return;Qe(),te.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let qe=(0,rt.friendlyPayPalFailureMessage)(pt instanceof Error?pt.message:void 0);U(qe),(0,tt.invokeMerchantCallback)(()=>xt.current?.(hr("paypal",qe)));return}},Rt=()=>new rt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),er=g=>kt()?Promise.reject(Rt()):Promise.resolve(g),ze=async g=>{if(kt())throw Rt();Yr||An();let m=jt.current,H=m?.sessionId??e,Ie=m?.nonce??yr.current;te.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Qe;try{Qe=await new Za.PaymentAPI(Mt,{telemetry:!1}).createSessionIntent(H,Ie??"",(0,rt.buildPayPalSessionIntentRequest)(oo),{idempotencyKey:Ut})}catch(pt){throw te.error({...(0,rt.classifyTelemetryFailure)(pt,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),pt}if(kt())throw Rt();if(Qe.provider!=="paypal"||Qe.providerObjectType!==$e)throw new Error(g);return te.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Qe.providerObjectId},le=(g,m)=>{let H=m?.nonce??yr.current;if(!H)return;let Ie=m?.sessionId??e,Qe=(0,rt.resolvePayPalDeclineReason)(g);new Za.PaymentAPI(Mt,{telemetry:!1}).reportSessionIntentDecline(Ie,H,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Qe}).catch(()=>{})},j=Ne;be("loadScript:scheduled (deferred 1 tick)");let $=null,de=setTimeout(()=>{if(Bt){be("loadScript:skipped (cancelled before defer ran)");return}be("loadScript:start");let g=Ot==="live"?"production":Ot,m={};$e==="subscription"?m={intent:"subscription",vault:!0}:$e==="order"&&(m={intent:"capture"}),$=(0,kl.loadScript)({clientId:l,currency:p,...m,...g?{environment:g}:{},...g==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let H=!1;$.then(Ie=>{if(H=!0,be(`loadScript:resolved inactive=${kt()} ns=${!!Ie} buttons=${!!Ie?.Buttons}`),kt())return;if(!Ie?.Buttons){be("FAIL: namespace missing Buttons factory"),ee("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}te.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"provider_ready",durationMs:te.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),te.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Qe=async(A,Pe)=>{if(kt()||Me.current!==j)return;let et=A.vaultSetupToken??A.subscriptionID??A.orderID??"",ot=et?nn.current.get(et):Jt.current.get(j);if(!(!ot||!Gr(ot.generation))&&$t(ot.generation)){nn.current.delete(et),Jt.current.delete(ot.surfaceKey),Ft("approved");try{if(ft(!0),(0,tt.invokeMerchantCallback)(()=>Tr.current?.(null)),!et)throw new rt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let oe=(0,rt.resolvePayPalApprovalIdentity)({accountPatch:ot.accountPatch,email:vt.current,billingName:_t.current,session:Wt.current});if((0,rt.needsPayPalPayerDetails)(oe))try{oe=(0,rt.mergePayPalPayerIdentity)(oe,await Pe?.order?.get?.())}catch{}if((Yt.current||Ue)&&!(0,rt.isValidEmail)(oe.email)){let ve=await z("PayPal",oe);if(!ve)return;oe=ve}(0,rt.isValidEmail)(oe.email)&&(ot.accountPatch=(0,un.compactBuyerIdentity)({...ot.accountPatch,...oe}),await Yt.current?.(oe));let cr=(0,rt.buildPayPalTokenizedBody)(et,oo);await Ee(cr,ot)}catch(oe){U(oe instanceof Error?oe.message:"PayPal capture failed.")}finally{kt()||ft(!1)}}},pt=A=>{let Pe=ue?()=>er(ue):()=>ze(A);return async()=>on(await Pe())},qe=Ie.Buttons({style:{layout:"horizontal",height:Qa,tagline:!1},...ce==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(A,Pe)=>{if(kt()){await Pe.reject();return}An();let et=Mn.current,ot={};if(et)try{let ve=await et("paypal");if(kt()){await Pe.reject();return}if(!ve.proceed){jt.current=null,Jt.current.delete(j),await Pe.reject();return}ot={sessionId:ve.sessionId,accountPatch:ve.accountPatch,nonce:ve.nonce}}catch(ve){be(`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,tt.invokeMerchantCallback)(()=>Sr.current?.("paypal"));let oe=hn(),cr={generation:oe,surfaceKey:j,...ot};jt.current=cr,Jt.current.set(j,cr),Je.current={...Y,attempt:oe},await Pe.resolve(),te.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),je.current=te.startTiming()},createOrder:$e==="order"?pt("Failed to create PayPal order."):void 0,createSubscription:$e==="subscription"?pt("Failed to create PayPal subscription."):void 0,createVaultSetupToken:$e==="setup_token"?async()=>on(await ze("Failed to create PayPal setup token.")):void 0,onApprove:Qe,onCancel:()=>{if(kt())return;let A=Jt.current.get(j)??jt.current,Pe=A&&Gr(A.generation)?(0,rt.buildPayPalCancelEvent)(A.sessionId??e,oo):null;A&&Jt.current.delete(A.surfaceKey),jt.current=null,Ft("cancelled"),te.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Be.current=!0,xn({generation:A?.generation,remount:!0,focus:!1}),Pe&&(0,tt.invokeMerchantCallback)(()=>Kr.current?.(Pe))},onError:A=>{if(kt()||Me.current!==j)return;let Pe=A instanceof Error?A.message:"PayPal failed to render.";if(be(`onError rendered=${Br} msg=${Pe.slice(0,120)}`),Br){let et=Jt.current.get(j)??jt.current;if(et&&!Gr(et.generation)||!et&&Ar())return;if(L(Pe)){$t(et?.generation);return}let{errorCode:ot,popupBlocked:oe,providerDeclined:cr,terminalReason:ve}=(0,Se.classifyExternalMethodFailure)(A,{inAppBrowser:Re.inAppBrowser,handoffObserved:et!=null&&re.current===et.generation});if(oe&&W.markBlocked(),Ft(ve),cr){te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:ve}),le(A,et),(0,tt.invokeMerchantCallback)(()=>xt.current?.(hr("paypal",Pe))),et&&Jt.current.delete(et.surfaceKey),jt.current=null,$t(et?.generation);return}te.error({errorCode:ot,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:ve}),et&&Jt.current.delete(et.surfaceKey),jt.current=null,xn({generation:et?.generation,remount:!0,showRetry:!0,focus:!0}),Zt(A,{code:"paypal_runtime_failed",popupBlocked:oe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ce,terminalReason:ve});return}ee(L(Pe)?"teardown":"pre_ready_callback",Pe)}}),Oe=qe.isEligible();if(be(`isEligible=${Oe}`),te.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Oe){N(!1),ee("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}ao=!0,Pn=qe,Zr=()=>{if(!zt||Jr||kt()||Br)return;Jr=!0,be(`container:dims ${qr(sn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Hn=new MutationObserver(Pe=>{if(!kt()){for(let et of Pe)if(et.type==="childList")et.addedNodes.forEach(ot=>{if(!(ot instanceof Element))return;let oe=ot.tagName.toLowerCase(),cr=(ot.getAttribute("title")??"").slice(0,40),ve=oe==="iframe"?` ${Ct(ot)}`:"";be(`child+ ${oe}${cr?` title="${cr}"`:""}${ve} dims=${qr(ot)}`)});else if(et.type==="attributes"&&et.target instanceof Element){let ot=et.target;if(ot.tagName.toLowerCase()!=="iframe")continue;let oe=et.attributeName;(oe==="src"||oe==="srcdoc")&&be(`attr~ iframe ${oe}=${oe==="srcdoc"?`[${(ot.getAttribute("srcdoc")??"").length}ch]`:Cn(ot.getAttribute("src"))} dims=${qr(ot)}`)}}}),Hn.observe(sn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let A=Pe=>{if(kt()||Br)return;let et=sn.querySelectorAll("iframe"),ot=typeof document<"u"&&"hasStorageAccess"in document;be(`watchdog:${Pe} container=${qr(sn)} children=${sn.childElementCount} iframes=${et.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ot} paypalNetRequests=${bn.value}`),et.forEach((oe,cr)=>{let ve=(oe.getAttribute("title")??"").slice(0,40);be(` iframe[${cr}] ${qr(oe)}${ve?` title="${ve}"`:""} ${Ct(oe)}`);let Gn=Er(oe);Gn&&be(` ${Gn}`)}),lr.length===0&&be(" (no PayPal/zoid window errors captured)")};vn.push(setTimeout(()=>A("3s"),3e3)),vn.push(setTimeout(()=>A("8s"),8e3)),vn.push(setTimeout(()=>A("15s"),15e3))},Zr(),be("render:start");let wt=te.startTiming();Bn=setTimeout(()=>{kt()||Br||(be("watchdog:11s retryable render timeout"),ee("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},nd);let Et=qe.render(sn);(async()=>{try{if(await Et,be(`render:resolved inactive=${kt()}`),Dn(),kt()){Fn();return}Br=!0,N(!0),dt(!1),Nr.current?.("ready"),te.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"checkout_render",durationMs:te.elapsed(wt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(A){let Pe=A instanceof Error?A.message:"PayPal failed to render.";be(`render:rejected msg=${Pe.slice(0,120)}`),Dn(),ee(L(Pe)?"teardown":"render_rejected",Pe)}})()}).catch(Ie=>{let Qe=Ie instanceof Error?Ie.message:"PayPal operation failed.";be(`provider:failed msg=${Qe.slice(0,120)}`);let pt="script_rejected";H&&L(Qe)?pt="teardown":H&&ao&&(pt="render_rejected"),ee(pt,Qe)})},0);return()=>{Bt=!0,clearTimeout(de),an&&clearTimeout(an),Dn(),ye.current===Mr&&(ye.current=null),Fn(),je.current=null,Je.current=null}},[Te,Mt,l,p,u,$e,ce,q,e,ue,Ne,J,z,Ue,be,Ft]);let xe=D?(0,pn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:St?"#fef2f2":"#f3f4f6",border:`1px solid ${St?"#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=${ge} failed=${St})`,gt.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"),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?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return
|
|
3
|
+
${rt.join(`
|
|
4
|
+
`)}`]}):null;return wt&&!m?D?(0,dn.jsx)("div",{children:fe}):null:(0,dn.jsxs)("div",{children:[fe,pt&&(0,dn.jsx)(qo,{identity:pt.identity,methodLabel:pt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:we,onCancel:()=>we(null)}),(0,dn.jsxs)("div",{"aria-hidden":Ce||pt?!0:void 0,style:Ce||pt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Qa},children:[!he&&!Ce&&(0,dn.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,dn.jsx)("div",{ref:G,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Qa,display:"flex",opacity:he?1:0},"aria-busy":x||v},Le)]},Le),tt&&(0,dn.jsx)("button",{ref:Ve,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:fr,style:ad,children:"Try PayPal again"})]})}function ha(e){return(0,dn.jsx)(El,{...e})}function Il(e){return(0,dn.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 yr=require("react/jsx-runtime");var cd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function Hr({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:u=cd}){let p={fontSize:13,color:u.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,yr.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,yr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...u.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,yr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,yr.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,yr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:u.spinnerTrackColor,strokeWidth:"3"}),(0,yr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:u.spinnerAccentColor})]}),e==="success"&&(0,yr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,yr.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,yr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,yr.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,yr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,yr.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,yr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,yr.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,yr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:u.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&l!==null&&(0,yr.jsx)("p",{style:p,children:l}),e==="error"&&t&&(0,yr.jsx)("p",{style:p,children:t}),(0,yr.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 Il=require("@flopay/shared"),_r=require("react");var _l=require("react/jsx-runtime");function va({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[i,l]=(0,_r.useState)(e instanceof Promise?null:e),[u,p]=(0,_r.useState)(t instanceof Promise||!t?null:t),P=(0,_r.useRef)(null),E=(0,_r.useRef)(null),S=Vo(n);(0,_r.useEffect)(()=>{S({class:"lifecycle",name:"checkout.mount"})},[S]),(0,_r.useEffect)(()=>{i&&S({class:"lifecycle",name:"sdk.initialize.ready"})},[S,i]),(0,_r.useEffect)(()=>{if(i)return Pr(i)?.subscribe?.(S)},[S,i]),(0,_r.useEffect)(()=>{if(!(!u||u===i))return Pr(u)?.subscribe?.(S)},[S,i,u]),(0,_r.useEffect)(()=>{if(!i)return;let _=Pr(i);return P.current=_?.beginCheckout()??_?.now()??0,_?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{_?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,_r.useEffect)(()=>{let _=!1;return e instanceof Promise?e.then(X=>{_||l(X)},()=>{_||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{_=!0}},[S,e]),(0,_r.useEffect)(()=>{let _=!1;if(!t){p(null);return}return t instanceof Promise?t.then(X=>{_||p(X)},()=>{_||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{_=!0}},[S,t]),(0,_r.useEffect)(()=>{if(!i||E.current===i)return;E.current=i;let _=Pr(i);_?.log({name:"checkout.rendered",stage:"checkout_render"}),S({class:"lifecycle",name:"checkout.rendered"}),_?.performance({stage:"checkout_render",durationMs:_.elapsed(P.current??0),durationMode:"machine"})},[S,i]);let I=(0,Il.resolveBillingApiUrl)(r?.billingApiUrl),K=(0,_r.useMemo)(()=>({flopay:i,paypalFlopay:u,billingApiUrl:I,emitInstrument:S}),[i,u,I,S]);return(0,_l.jsx)(dn.Provider,{value:K,children:a})}var In=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 mn=require("@flopay/js"),lt=require("@flopay/shared");var ba="card";async function cd(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 dd(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 ud(){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 Ml(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 xl(e){return(0,mn.runSavedCardChallenge)(e)}async function Ho(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,i=t.nonce??t.session.clientSecret,l=new mn.PaymentAPI(r,{telemetry:!1}),u=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,p;try{p=await(0,mn.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:E=>qn({type:E.declineReason??"authorization_declined",gatewayErrorCode:E.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(E){if(a.aborted||E instanceof Error&&E.name==="AbortError")throw E instanceof lt.FloPayError&&E.code==="three_ds_aborted"?E:$o(E);if(!(E instanceof lt.FloPayError)||E.code!=="three_ds_timeout"&&E.code!=="checkout_processing_timeout")throw E;try{p=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:i,statusUrl:u,timeoutMs:5e3,signal:a})}catch(I){if(a.aborted)throw $o(I);if(!(I instanceof lt.FloPayError)||I.code!=="checkout_processing_timeout")throw I}let S=p&&lo(p,t.session);if(!Jn(S)&&S?.status!=="expired"){if(t.telemetry){let I=new mn.PaymentAPI(r);try{I.reportThreeDsAbandoned(n)}finally{I.destroy()}}throw ud()}}let P=p&&lo(p,t.session);if(!Jn(P))throw No(P);return{...Xn(P,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 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 Al(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 E of P)if(typeof E=="string"&&E.length>0&&(!t?.requirePaymentIntentClientSecret||ti(E)))return E}}}}async function pd({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Al(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 mn.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,E=r.customer?.id??r.accountData?.userId??"",S=r.customer?.email??r.accountData?.email??"",I=r.customer?.firstName??r.accountData?.firstName??"",K=r.customer?.lastName??r.accountData?.lastName??"",_=r.customer?.country??r.accountData?.country??void 0,X=r.customer?.zip??r.accountData?.zip??void 0,y=await new mn.PaymentAPI(u,l===!1?{telemetry:!1}:void 0).processPayment(E,{sessionId:p,nonce:P,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:E,email:S,firstName:I,lastName:K,country:_,zip:X},returnUrl:i??Ji(r)});if(y.ok){let b=typeof y.json=="function"?await y.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:ma(a),checkoutMethod:Tl(a,r)}};let Te=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Te?{paymentIntentId:Te}:{},paymentMethodId:ma(a),checkoutMethod:Tl(a,r)}}}let v;try{v=await y.json()}catch(b){throw new lt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.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=Al(v);if(!b)throw new lt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status});return{type:v.type,threeDSecureToken:b,paymentMethodId:v.paymentMethodId}}if(v?.gatewayErrorCode==="authentication_required"){let b=await pd({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 pe=new lt.FloPayError(v?.message??"Payment failed. Please try again.","api_error",{code:v?.code??v?.gatewayErrorCode,declineCode:v?.declineCode??v?.gatewayDeclineReason,statusCode:y.status});throw Object.assign(pe,{telemetryOutcome:(0,lt.classifyPaymentRejection)(y.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 E=t?.getRawProvider();if(!E)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),I=null,K=e.paymentMethodId,_=await Ca(()=>cd(E,e.threeDSecureToken,S),"card");if(_){if(_.error)throw eo(new lt.FloPayError(_.error.message??`Failed to retrieve 3DS ${S?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let T=_.intent;!K&&T?.payment_method&&(typeof T.payment_method=="string"?K=T.payment_method:"id"in T.payment_method&&(K=T.payment_method.id??void 0))}let X=K?await Ca(()=>dd(E,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");I=X.intent}else{let T=await Ca(()=>E.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(T.error)throw eo(new lt.FloPayError(T.error.message??"3DS authentication failed.","api_error",{code:T.error.code}),"card");I=(S?T.setupIntent:T.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let T=await Ko({billingApiUrl:a,sessionId:i,session:l,telemetry:p,tokenizedData:{id:I.id,type:"card",threeDSecureActionResultTokenId:I.id},returnUrl:u});return T.type==="success"?{...T.result,paymentIntentId:T.result.paymentIntentId??I.id,paymentMethodId:T.result.paymentMethodId??K}:T.type==="next_action_required"?Ho(T,{billingApiUrl:a,sessionId:i??l.id,session:l,signal:P}):ri(T,{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:I}=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(I)throw eo(new lt.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.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,kn.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 Tl(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,kn.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,mn.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),i?(0,mn.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 Tn=require("@flopay/js"),c=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"),Bl=require("react");var Fl={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"),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=`
|
|
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 @@ ${gt.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:E,fontFamily:S}){let I=(0,to.resolveStripeMethodBrandVariant)(e,t),K=Fl[e],[_,X]=(0,Bl.useState)(!1),T=!!K&&!_,y=I?.backgroundColor??u??"#ffffff",v=I?.borderColor??p??"#d1d5db",pe=I?.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:y,color:pe,border:`1px solid ${v}`,borderRadius:E??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:[T?(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,!T&&I?.logoSvg?(0,vr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:I.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: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,vr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function ai(e){let t=new Set(e.map(to.stripeExpressMethodToOptionKey)),r=n=>n==="applePay"||n==="googlePay"?"always":"auto";return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(n=>[n,t.has(n)?r(n):"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"),yd=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 fd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return yd.has(t.charAt(0).toLowerCase()+t.slice(1))}function gd(e,t){return typeof t=="number"&&t!==0&&!fd(e)?`${t}px`:String(t).trim()}function Dl(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]=gd(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:E}){let S=(0,rn.useRef)(null),I=(0,rn.useRef)(p),K=(0,rn.useRef)(P),_=(0,rn.useRef)(E);I.current=p,K.current=P,_.current=E;let X=(0,rn.useRef)(i);X.current=i;let T=(0,rn.useRef)(null),y=l??void 0,v=(0,rn.useRef)(y);v.current=y;let pe=(0,rn.useRef)(void 0);return(0,rn.useEffect)(()=>{let b=S.current;if(!b)return;let Te=!0,B=!1,ae=()=>{!Te||B||(B=!0,I.current?.())},me=e.on("ready",()=>{ae()}),ue=e.on("error",D=>{K.current?.(D.message??"There was a problem loading the secure card form.")}),Ae=e.on("validation",D=>{_.current?.(D.message??null)}),ct=v.current??(rs.has(e)?null:void 0),Ge={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...X.current?{theme:X.current}:{},...ct===void 0?{}:{submitLabel:ct}};return T.current=X.current??null,pe.current=v.current,v.current!==void 0&&rs.add(e),e.mount(b,Ge).then(()=>{ae()}).catch(D=>{Te&&K.current?.(D instanceof Error?D.message:"Failed to load the secure card form.")}),()=>{Te=!1,me(),ue(),Ae(),e.unmount()}},[e,t,r,n,a]),Co(()=>{let b=S.current;b&&Dl(b,u)},[u]),(0,rn.useEffect)(()=>{i!==void 0&&(i===null&&T.current===null||(T.current=i,e.applyTheme?.(i)))},[e,i]),(0,rn.useEffect)(()=>{y!==pe.current&&(pe.current=y,y!==void 0&&rs.add(e),e.setSubmitLabel?.(y??null))},[e,y]),(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 ps=require("@flopay/shared"),d=require("react/jsx-runtime"),jn="flopay_stripe_resume",Ol="flopay_wallet_resume",Kl="fw1",hd="fw2",Gl=300*1e3,Pd=900,vd=25e3,Cd=25e3,bd=1e4,_n={provider:"paypal",paymentMethodCategory:"paypal"},Sd="x-flopay-process-result-source",wd="status";async function kd(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 Rd(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 cs(e){return`${hd}:${e}`}function ui(e){return nr(cs(e))}function pi(e,t){if(typeof window>"u")return null;let r=cs(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 Ed(e){return nr(cs(e.sessionId),e)}function Ll(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 Id(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=Id(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Nl(e,t,r){let n=null;try{return await Promise.race([hl(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},bd),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function _d(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 mi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Tn.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,Td=250,Ul="Just a moment \u2014 we are finalizing your order. Please press pay again.",Md="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function ds(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 Tn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function xd(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,un.compactBuyerIdentity)({email:(0,c.isValidEmail)(a)?a:n?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Ad({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,zl=`flopay-card-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,ql=`flopay-card-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Fd=`flopay-buttons-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,Bd=`flopay-buttons-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Dd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function us(e){return(0,c.derivePrimaryTileStyle)(e)}var Od={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ld(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 is={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 jl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ss(e){return e==="paypal"?"PayPal":(0,c.getStripeMethodDisplayName)(e)}function Nd(e){let t=(0,c.getPostalCodeExample)(e);return`Enter a valid ${(0,c.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Ud(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 zd(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 qd(e){return typeof e=="number"?`${e}px`:e}function fi(e){return(0,d.jsx)(Wd,{...e})}function Vl({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:i,isProcessing:l=!1,onButtonClick:u,onDecline:p,onTechnicalFailure:P,runBeforeButtonClick:E,billingName:S,onBuyerIdentityReady:I,onLoadStateChange:K,placeholderBorderRadius:_,popupCapabilityOwner:X,externalTelemetryContext:T,presentationMode:y}){let v=Qn(),{emitInstrument:pe}=(0,o.useContext)(dn),b=(0,rr.useStripe)(),Te=(0,rr.useElements)(),B=(0,o.useMemo)(()=>ni(Pr(v),T),[T,v]),[ae,me]=(0,o.useState)("loading");(0,o.useEffect)(()=>{K?.(ae)},[ae,K]);let[ue,Ae]=(0,o.useState)(!1),ct=(0,o.useRef)(!1),Ge=!(0,c.isValidEmail)(r?.trim())||!S?.trim(),{request:D,collect:bt,finish:Xe}=zo(),Le=(0,o.useRef)(!1),fe=(0,o.useRef)(null),J=(0,o.useRef)(null),[G,Fe]=(0,o.useState)(0),[je,Je]=(0,o.useState)(!1),re=(0,o.useRef)(!1),Q=(0,o.useRef)(new Map),{startAttempt:se,finishAttempt:W,invalidateAttempt:We,isAttemptInvalidated:Be,isAttemptCurrent:ge,generationRef:N}=ga((we,M,ft)=>{P?.(we,M,{...ft,popupBlocked:ft?.popupBlocked??(0,Se.isPopupBlockedError)(M),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y,terminalReason:"overlay_timeout"}),Je(!0),Fe(ut=>ut+1)},{onHandoffObserved:()=>{X.markAvailable(),B?.log({name:"provider.popup.opened",stage:"overlay_open",..._n,attempt:N.current})}});(0,o.useEffect)(()=>{je&&J.current?.focus()},[je,G]);let Ce=(0,o.useCallback)(()=>{Fe(we=>we+1)},[]),dt=(0,o.useCallback)((we,M,ft)=>{We(ft),P?.("paypal",we,{code:M,popupBlocked:(0,Se.isPopupBlockedError)(we),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y}),Je(!0),Ce()},[We,P,y,Ce]),Ne=(0,o.useCallback)(()=>{window.setTimeout(()=>{(fe.current?.querySelector("iframe")??fe.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{re.current&&(re.current=!1,Ne())},[Ne,G]);let at=(0,o.useCallback)(()=>{Je(!1),i?.(null),Ne()},[Ne,i]);(0,o.useEffect)(()=>{if(!b||Le.current)return;let[we,M,ft]=(0,c.readStripeRedirectParams)();if(!we||!M)return;let ut=(0,c.readMatchingStripePayPalContinuation)(M);if(!ut)return;Le.current=!0;let z=!0,ke=Ea.get(M);ke||(ke=ft==="failed"?Promise.resolve(null):Promise.resolve().then(()=>b.retrievePaymentIntent(M)),Ea.set(M,ke));let Nt={accountPatch:ut.accountPatch,sessionId:ut.sessionId,nonce:ut.nonce},Ue=()=>{B?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",..._n,requestCategory:"provider_sdk"})};return B?.log({name:"provider.redirect.resumed",stage:"redirect_resume",..._n}),(async()=>{try{Ae(!0);let w=await ke;if(!z)return;if(w?.error){Ea.delete(M),Ue(),i?.(w.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),Ea.delete(M),ft==="failed"){let $e="PayPal payment was declined. Please try again.";B?.terminal({outcome:"payment_declined",..._n,terminalReason:"provider_declined"}),i?.($e),p?.(hr("paypal",$e));return}let O=w?.paymentIntent;if(O&&O.id!==we){Ue(),i?.("Failed to match the returned PayPal payment.");return}if(O&&(O.status==="requires_capture"||O.status==="succeeded")){let $e=typeof O.payment_method=="string"?O.payment_method:O.payment_method?.id;a({id:$e??O.id,type:"card",threeDSecureActionResultTokenId:O.id,isPaypal:!0},{...Nt,presentationMode:"redirect"})}else{let $e="PayPal payment was not completed. Please try again.";B?.terminal({outcome:O?.status==="canceled"?"payment_cancelled":"payment_declined",..._n,terminalReason:O?.status==="canceled"?"cancelled":"provider_declined"}),i?.($e),p?.(hr("paypal",$e))}}catch(w){if(!z)return;Ea.delete(M),Ue(),i?.(w instanceof Error?w.message:"Failed to complete PayPal payment.")}finally{z&&Ae(!1)}})(),()=>{z=!1,Le.current=!1}},[b,a,i,p,B]);let Me=(0,o.useCallback)(async(we=!1)=>{let M=E?await E("paypal"):{proceed:!0};if(!M.proceed)return Q.current.delete(G),!1;let ft=se("paypal");return Q.current.set(G,{generation:ft,accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}),Je(!1),B?.log({name:`provider.${we?"redirect.started":"handoff.requested"}`,stage:we?"redirect":"overlay_open",..._n,attempt:ft}),u?.("paypal"),!0},[u,B,E,se,G]),nt=(0,o.useCallback)(async we=>{if(l||ue||!await Me()){we.reject();return}we.resolve()},[l,Me,ue]),it=(0,o.useCallback)(async we=>{if(!b||!Te)return;let M=Q.current.get(G);if(M&&!ge(M.generation)){Q.current.delete(G);return}if(!M&&Be()||M&&!W(M.generation))return;M||W();let ft=M??null;if(Q.current.delete(G),!ft&&E){let Mt=await E("paypal");if(!Mt.proceed){we.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ft={accountPatch:Mt.accountPatch,sessionId:Mt.sessionId,nonce:Mt.nonce}}let ut=ft?.sessionId??e,z=ft?.nonce??t,ke=await Ad({event:we,prepared:ft,email:r,billingName:S,methodLabel:"PayPal",collect:bt});if(!ke){we.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Nt=ke.email,Ue={...ft?.accountPatch,...(0,un.compactBuyerIdentity)(ke,!0)};try{if(Ae(!0),i?.(null),!ut||!(0,c.isValidEmail)(Nt))throw new Error("Missing sessionId or email for PayPal payment");await I?.(ke);let Mt=b.createPaymentMethod,{error:w,paymentMethod:O}=await Mt({type:"paypal"});if(w){dt(w,"stripe_paypal_create_payment_method_failed",M?.generation),we.paymentFailed({reason:"fail"});return}let $e=await mi(n,pe,ut,z??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:O?.id??null,intentKind:"payment"});if($e.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Re=$e.clientSecret,h={return_url:(0,c.stripeRedirectReturnUrl)()};if(O?.id&&(h.payment_method=O.id),!nr(as,{clientSecret:Re,sessionId:ut,nonce:z,accountPatch:Ue})&&y==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:q,paymentIntent:V}=await b.confirmPayment({clientSecret:Re,confirmParams:h,redirect:"if_required"});if(q){if(nr(as),(0,Se.isProviderDecline)(q)){let f=q.message??"Your payment was declined.";B?.terminal({outcome:"payment_declined",..._n,terminalReason:"provider_declined"}),i?.(f),p?.(hr("paypal",f,{code:(0,Se.getProviderErrorCode)(q),declineCode:(0,Se.getProviderDeclineCode)(q)})),await yi({billingApiUrl:n,sessionId:ut,nonce:z,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,Se.getProviderErrorCode)(q)??"provider_declined"}})}else dt(q,"stripe_paypal_confirm_failed",M?.generation);return}nr(as);let De=typeof V?.payment_method=="string"?V.payment_method:V?.payment_method?.id;a({id:De??V?.id,type:"card",threeDSecureActionResultTokenId:V?.id,isPaypal:!0},{accountPatch:Ue,paymentMethodCategory:"paypal",presentationMode:y,sessionId:ut,nonce:z});return}catch(Mt){dt(Mt,"stripe_paypal_failed",M?.generation)}finally{Ae(!1)}},[b,Te,e,t,r,S,bt,I,n,pe,a,i,p,E,dt,W,ge,Be,B,y,G]),ar=(0,o.useCallback)(async()=>{if(!(ct.current||l||ue||!b||!Te)){ct.current=!0,Ae(!0);try{if(!await Me(!0))return;await it({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{ct.current=!1,Ae(!1)}}},[Te,it,l,Me,b,ue]),Dt=y==="redirect"?(0,d.jsx)("button",{type:"button",disabled:l||ue,onClick:()=>{ar()},style:{width:"100%",minHeight:Yo,border:"1px solid #d1d5db",borderRadius:_??8,background:"#ffc439",color:"#111827",cursor:l||ue?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(rr.ExpressCheckoutElement,{onReady:we=>me(wa(we,["paypal"])),onLoadError:()=>{me("load_error"),ds(B,"paypal","paypal","provider_error")},onClick:nt,onConfirm:it,onCancel:()=>{let we=Q.current.get(G);Q.current.delete(G),B?.terminal({outcome:"payment_cancelled",..._n,terminalReason:"cancelled",...we?{attempt:we.generation}:{}}),We(we?.generation),Je(!1),re.current=!0,Ce()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Ge,emailRequired:Ge,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},G),St=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:fe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[je&&(0,d.jsx)("button",{ref:J,type:"button","data-testid":"flopay-paypal-retry-button",onClick:at,style:is,children:"Try PayPal again"}),D&&(0,d.jsx)(qo,{identity:D.identity,methodLabel:D.methodLabel,onComplete:Xe,onCancel:()=>Xe(null)},D.id),(0,d.jsx)("div",{style:{display:D?"none":void 0},children:Dt})]}),ue&&!D&&(0,d.jsx)($r,{status:"processing"})]});return y==="redirect"?St:(0,d.jsx)(ka,{state:ae,placeholderTestId:"flopay-paypal-placeholder",borderRadius:_,children:St})}function Wl(e){return e==="apple_pay"||e==="google_pay"}var jd=200;function Vd({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:E,runBeforeButtonClick:S,billingName:I,onBuyerIdentityReady:K,onLoadStateChange:_,placeholderBorderRadius:X,popupCapabilityOwner:T,externalTelemetryContext:y}){let v=Qn(),{emitInstrument:pe}=(0,o.useContext)(dn),b=(0,rr.useStripe)(),Te=(0,rr.useElements)(),B=(0,o.useMemo)(()=>ni(Pr(v),y),[y,v]),[ae,me]=(0,o.useState)("loading");(0,o.useEffect)(()=>{_?.(ae)},[ae,_]);let[ue,Ae]=(0,o.useState)(!1);(0,o.useEffect)(()=>{Je.current=ue},[ue]);let ct=(0,o.useRef)(!(0,c.isValidEmail)(r?.trim())||!I?.trim()).current,{request:Ge,collect:D,finish:bt}=zo(),Xe=(0,o.useRef)(null),Le=(0,o.useRef)(null),[fe,J]=(0,o.useState)(0),[G,Fe]=(0,o.useState)(()=>(0,c.shouldPreferWalletPopup)()),je=(0,o.useRef)(G),Je=(0,o.useRef)(!1),[re,Q]=(0,o.useState)(!1),[se,W]=(0,o.useState)(()=>pi(e,t)?"blocked":"idle"),[We,Be]=(0,o.useState)("google_pay"),ge=(0,o.useRef)(null),N=(0,o.useRef)(!0),Ce=(0,o.useRef)(!1),dt=(0,o.useRef)("google_pay"),Ne=(0,o.useRef)("google_pay"),at=(0,o.useRef)(null),Me=(0,o.useRef)(null),nt=(0,o.useRef)(new Set),it=(0,o.useRef)(null),ar=(0,o.useRef)(null);(0,o.useEffect)(()=>(N.current=!0,()=>{N.current=!1;for(let h of nt.current)window.clearTimeout(h);nt.current.clear()}),[]);let Dt=(0,o.useRef)(new Map),{startAttempt:St,finishAttempt:we,invalidateAttempt:M,isAttemptInvalidated:ft,isAttemptCurrent:ut,generationRef:z}=ga((h,ce,q)=>{E?.(h,ce,{...q,popupBlocked:q?.popupBlocked??(0,Se.isPopupBlockedError)(ce),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Be(h),Q(!0),J(V=>V+1)},{onHandoffObserved:h=>{ar.current=z.current,T.markAvailable(),B?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:z.current,...h==="apple_pay"||h==="google_pay"?{walletType:h}:{}})},defersMissingTerminal:Wl,onMissingTerminalDeferred:(h,ce)=>{let q=B?.now()??globalThis.performance?.now()??Date.now(),V=it.current,De=V?.generation===ce?V.startedAt:q;B?.performance({stage:"overlay_return",durationMs:Math.max(0,q-De),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:ce,...Wl(h)?{walletType:h}:{}}),B?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{re&&Le.current?.focus()},[re,fe]);let ke=(0,o.useCallback)(()=>{J(h=>h+1)},[]),Nt=(0,o.useCallback)((h,ce,q,V,De=!1)=>{M(V),E?.(h,ce,{code:q,popupBlocked:(0,Se.isPopupBlockedError)(ce),telemetryReported:De,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Be(h),Q(!0),ke()},[M,E,ke]),Ue=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Xe.current?.querySelector("iframe")??Xe.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Ce.current&&(Ce.current=!1,Ue())},[Ue,fe]);let Mt=(0,o.useCallback)(()=>{Q(!1),u?.(null),Ue()},[Ue,u]),w=(0,o.useCallback)(()=>{ge.current?.()},[]);(0,o.useEffect)(()=>{let h=null,ce=()=>{h=null;let V=(0,c.shouldPreferWalletPopup)();V!==je.current&&(je.current=V,Fe(V),!Je.current&&!ut(z.current)&&ke())},q=()=>{h!==null&&window.clearTimeout(h),h=window.setTimeout(ce,jd)};return window.addEventListener("resize",q),()=>{window.removeEventListener("resize",q),h!==null&&window.clearTimeout(h)}},[z,ut,ke]),(0,o.useEffect)(()=>{let h=pi(e,t);if(!h)return;let ce=!1,q=!1,V=async()=>{if(!q){q=!0,ce||W("checking");try{let De=await Nl(b,h.clientSecret,nt.current);if(ce)return;let f=os(De,h.providerObjectId,(0,c.isSetupIntentClientSecret)(h.clientSecret));if(f.kind==="confirmed"){if(!Ll(e,t,h.clientSecret))return;ge.current=null,W("idle"),l({id:f.paymentMethodId,type:"card",threeDSecureActionResultTokenId:f.intentId},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(f.kind==="terminal"){ns(e,t,h.clientSecret),ge.current=null,W("idle"),Be(h.paymentMethodType),Q(!0),ke();return}W("blocked")}catch{ce||W("blocked")}finally{q=!1}}};return ge.current=V,W("blocked"),()=>{ce=!0,ge.current===V&&(ge.current=null)}},[t,l,ke,e,b]);let O=(0,o.useCallback)(async h=>{let ce=!1,q=vt=>{ce||(ce=!0,h.paymentFailed({reason:"fail",...vt?{message:vt}:{}}))};if(!b||!Te){q();return}let V=Dt.current.get(fe);if(V&&!ut(V.generation)){Dt.current.delete(fe),q();return}if(!V&&ft()){q();return}if(V&&!we(V.generation)){q();return}V||we();let De=h.expressPaymentType??V?.method??dt.current,f=V??null,he=jl(De),ye;De==="apple_pay"?ye="apple_pay":De==="google_pay"&&(ye="google_pay");let gt=V?.generation??z.current,x=B,be=x?.now()??globalThis.performance?.now()??Date.now(),Gt=new AbortController,br=!1,Tr=!1,xt=null,Kr=e,Lr="processing",Sr="other",ir="provider_runtime",Nr,Yt=new Promise((vt,_t)=>{Nr=_t}),Mn=window.setTimeout(()=>{br=!0,Gt.abort(),Nr(di)},vd),Wt=async(vt,_t,yr)=>{Lr=vt,Sr=_t,ir=_t==="intent_create"||_t==="session_claim"?"transport_error":"provider_runtime";let jt=x?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([yr,Yt])}finally{let Jt=x?.now()??globalThis.performance?.now()??Date.now();x?.performance({stage:vt,durationMs:Math.max(0,Jt-jt),durationMode:"machine",requestCategory:_t,paymentMethodCategory:"wallet",provider:"stripe",...br?{statusClass:"timeout"}:{}})}};try{if(Ae(!0),u?.(null),!f&&S){let Z=await Wt("processing","other",S(he));if(!Z.proceed){q();return}f={accountPatch:Z.accountPatch,sessionId:Z.sessionId,nonce:Z.nonce}}let vt=f?.sessionId??e;Kr=vt;let _t=f?.nonce??t,yr=at.current??f?.accountPatch,jt=Xl({event:h,fallbackEmail:yr?.email??r,fallbackName:[yr?.firstName,yr?.lastName].join(" ").trim()||I});if(!(0,c.isValidEmail)(jt.email)){q("Buyer details are required."),D(ss(De),jt).then(Z=>{Z&&(at.current=Z)});return}at.current=null;let Jt={...f?.accountPatch,...(0,un.compactBuyerIdentity)(jt,!0)};await Wt("processing","session_claim",Promise.resolve(K?.(jt)));let{error:nn}=await Wt("tokenization","provider_sdk",Te.submit());if(nn){q(),Nt(De,nn,"stripe_wallet_submit_failed",V?.generation);return}if(!vt)throw new Error("Missing sessionId or email for payment.");let Ur={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:De,paymentMethodId:null,intentKind:a},wr=JSON.stringify({sessionId:vt,nonce:_t??"",request:Ur}),kr=Me.current,fr=kr?.retryIdentity===wr?kr.authorizationAttemptId:(0,c.randomUuidV4)();Me.current={authorizationAttemptId:fr,retryIdentity:wr};let Zt=await Wt("processing","intent_create",mi(n,pe,vt,_t??"",{...Ur,authorizationAttemptId:fr},{signal:Gt.signal}));if(Zt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ft=Zt.clientSecret,pr=Ed({createdAt:Date.now(),sessionId:vt,..._t?{nonce:_t}:{},clientSecret:Ft,providerObjectId:Zt.providerObjectId,paymentMethodType:De,accountPatch:Jt});window.clearTimeout(Mn),Tr=!0,x?.performance({stage:"callback",durationMs:Math.max(0,(x?.now()??globalThis.performance?.now()??Date.now())-be),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Rr=x?.now()??globalThis.performance?.now()??Date.now(),$t={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...ye?{walletType:ye}:{},attempt:gt},Ze=!1,zr=null;x?.log({name:"payment.provider_confirmation.started",...$t}),xt=window.setTimeout(()=>{xt!==null&&nt.current.delete(xt),Ze=!0;let Z=x?.now()??globalThis.performance?.now()??Date.now();x?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...$t,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Z-Rr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),x?.flush?.().catch(()=>{}),zr?.()},Cd),nt.current.add(xt);let Gr=(Z,te)=>{xt!==null&&(window.clearTimeout(xt),nt.current.delete(xt),xt=null);let Lt=x?.now()??globalThis.performance?.now()??Date.now(),Tt=Math.max(0,Lt-Rr),Bt=Z;Ze&&(Z==="resolved"?Bt="resolved_late":Z==="returned_error"?Bt="returned_error_late":Bt="rejected_late");let Fr=te??(Z==="resolved"?"approved":"provider_error");return x?.log({name:"payment.provider_confirmation.returned",...$t,operationOutcome:Bt,terminalReason:Fr}),x?.performance({...$t,durationMs:Tt,durationMode:"buyer",operationOutcome:Bt,terminalReason:Fr}),{durationMs:Tt,operationOutcome:Bt,terminalReason:Fr}},Ar=!1,sr=!1,hn=Z=>{if(!Z||typeof Z!="object")return null;let te=Z;if(te.error)return null;let Lt=te.setupIntent??te.paymentIntent,Tt=os(Lt??null,void 0,!!te.setupIntent);return Tt.kind==="confirmed"?Tt:null},xn=Z=>{if(Ar||V&&z.current!==V.generation)return;let te=hn(Z);if(!te)return;if(pr&&!Ll(vt,_t,Ft)){Ar=!0;return}let{intentId:Lt,paymentMethodId:Tt}=te;Ar=!0,sr=!0,Me.current=null,ge.current=null,N.current&&(W("idle"),Ae(!1));let Bt=`${Kl}:${vt}`;nr(Bt,{createdAt:Date.now(),sessionId:vt,nonce:_t,accountPatch:Jt,paymentMethodId:Tt,providerIntentId:Lt,paymentMethodType:De});try{l({id:Tt,type:"card",threeDSecureActionResultTokenId:Lt},{accountPatch:Jt,paymentMethodCategory:"wallet",sessionId:vt,nonce:_t})}finally{nr(Bt)}},on=!1;zr=async()=>{if(!(on||Ar||sr)){on=!0,N.current&&W("checking");try{let Z=await Nl(b,Ft,nt.current);if(Ar||sr)return;let te=(0,c.isSetupIntentClientSecret)(Ft),Lt=os(Z,Zt.providerObjectId,te);if(Lt.kind==="confirmed"){xn(te?{setupIntent:Z}:{paymentIntent:Z});return}if(Lt.kind==="terminal"){if(sr=!0,ns(vt,_t,Ft),Me.current=null,ge.current=null,!N.current)return;W("idle"),q(),Nt(De,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",V?.generation,!0);return}N.current&&!sr&&(W("blocked"),Ae(!1))}catch{N.current&&!sr&&(W("blocked"),Ae(!1))}finally{on=!1}}},ge.current=zr;let Ot,xe;try{let Z=await((0,c.isSetupIntentClientSecret)(Ft)?b.confirmSetup({elements:Te,clientSecret:Ft,redirect:"if_required"}):b.confirmPayment({elements:Te,clientSecret:Ft,redirect:"if_required"}));if(!Z||typeof Z!="object")throw new Ia(Rd(Z));if(Ot=Z,!Ot.error&&!hn(Ot))throw new Ia("confirmation_result_unconfirmed");xe=Gr(Ot.error?"returned_error":"resolved",Ot.error&&(0,Se.isProviderDecline)(Ot.error)?"provider_declined":void 0)}catch(Z){let te=Z instanceof Ia?Z.reason:void 0,Lt=te!==void 0,Tt=Gr(Lt?"returned_error":"rejected");if(x?.error({...Lt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:te}:Gi(Z),...$t,operationOutcome:Tt.operationOutcome,durationMs:Tt.durationMs,statusClass:"unknown",terminalReason:Tt.terminalReason}),!N.current||Ar)return;await zr?.();return}let Y=Ot.error;if(Y){if(!N.current||Ar)return;if((0,Se.isProviderDecline)(Y)){sr=!0,ns(vt,_t,Ft),Me.current=null,ge.current=null,W("idle");let Z=Y.message??"Your payment was declined.";q(Z),u?.(Z),P?.(hr(he,Z,{code:(0,Se.getProviderErrorCode)(Y),declineCode:(0,Se.getProviderDeclineCode)(Y)})),yi({billingApiUrl:n,sessionId:vt,nonce:_t,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:De,providerDeclineReason:(0,Se.getProviderErrorCode)(Y)??"provider_declined",...Zt.intentKind==="payment"&&Zt.providerObjectId.startsWith("pi_")?{providerIntentId:Zt.providerObjectId}:{}}})}else x?.error({...Gi(Y),...$t,operationOutcome:xe.operationOutcome,durationMs:xe.durationMs,statusClass:"unknown",terminalReason:xe.terminalReason}),await zr?.();return}if(xn(Ot),!Ar)throw new Error("Invalid provider returned for APM intent")}catch(vt){if(vt===di){let _t=x?.now()??globalThis.performance?.now()??Date.now();x?.error({errorCode:_d(Sr),stage:Lr,requestCategory:Sr,paymentMethodCategory:"wallet",provider:"stripe",...ye?{walletType:ye}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Kr,durationMs:Math.max(0,_t-be),statusClass:"timeout",failureCategory:ir,attempt:gt,terminalReason:"provider_error"}),x?.flush?.().catch(()=>{})}q(),Nt(De,vt,vt===di?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",V?.generation,vt===di)}finally{if(window.clearTimeout(Mn),xt!==null&&(window.clearTimeout(xt),nt.current.delete(xt)),!Tr){let vt=x?.now()??globalThis.performance?.now()??Date.now();x?.performance({stage:"callback",durationMs:Math.max(0,vt-be),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...br?{statusClass:"timeout"}:{}})}N.current&&Ae(!1)}},[b,Te,e,t,r,I,D,K,n,pe,a,l,u,P,S,Nt,we,ut,ft,z,B,fe]),$e=(0,o.useMemo)(()=>ai(i),[i]),Re=(0,o.useMemo)(()=>i.map(c.stripeExpressMethodToOptionKey),[i]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(ka,{state:ae,placeholderTestId:"flopay-wallet-placeholder",borderRadius:X,children:(0,d.jsxs)("div",{ref:Xe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[re&&(0,d.jsxs)("button",{ref:Le,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Mt,style:is,children:["Try ",ss(We)," again"]}),se!=="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:w,disabled:se==="checking",style:is,children:se==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ge&&(0,d.jsx)(qo,{identity:Ge.identity,methodLabel:Ge.methodLabel,onComplete:bt,onCancel:()=>bt(null)},Ge.id),se==="idle"&&(0,d.jsxs)("div",{style:{display:Ge?"none":void 0},children:[(0,d.jsx)(Vd,{active:G}),(0,d.jsx)(rr.ExpressCheckoutElement,{onReady:h=>{me(wa(h,Re))},onLoadError:h=>{me("load_error"),ds(B,"stripe","wallet","provider_error")},onClick:async h=>{let ce=B?.now()??globalThis.performance?.now()??Date.now();dt.current=h.expressPaymentType,Ne.current=jl(h.expressPaymentType);let q=!0,V=window.setTimeout(()=>{q=!1,h.reject()},Pd),De=S?await S(Ne.current):{proceed:!0};if(window.clearTimeout(V),!q)return;if(!De.proceed){Dt.current.delete(fe),h.reject();return}let f=St(h.expressPaymentType);it.current={generation:f,startedAt:ce},Dt.current.set(fe,{generation:f,method:h.expressPaymentType,accountPatch:De.accountPatch,sessionId:De.sessionId,nonce:De.nonce}),Q(!1),B?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:f,...h.expressPaymentType==="apple_pay"||h.expressPaymentType==="google_pay"?{walletType:h.expressPaymentType}:{}}),p?.(Ne.current),h.resolve()},onConfirm:O,onCancel:()=>{let h=Dt.current.get(fe);Dt.current.delete(fe);let ce=it.current,q=B?.now()??globalThis.performance?.now()??Date.now();if(h&&ce?.generation===h.generation&&(0,c.isWalletSheetRefusedForWindowSize)({method:h.method,elapsedMs:q-ce.startedAt,handoffObserved:ar.current===h.generation})){B?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:h.generation,walletType:"google_pay"}),Me.current=null,Nt(h.method,new Error("The browser window is too small for the Google Pay sheet."),c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,h.generation,!0);return}B?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...h?{attempt:h.generation}:{}}),M(h?.generation),Me.current=null,Q(!1),Ce.current=!0,ke()},options:{...ii,paymentMethods:$e,emailRequired:ct,billingAddressRequired:ct}},fe)]})]})}),ue&&(0,d.jsx)($r,{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 ls({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:u,onErrorChange:p,onDecline:P,onCancel:E,runBeforeButtonClick:S,onButtonClick:I,isProcessing:K,submitButtonColor:_,submitButtonBorderRadius:X,submitButtonStyle:T,errorText:y}){let v=Qn(),{emitInstrument:pe}=(0,o.useContext)(dn),b=(0,rr.useStripe)(),Te=(0,rr.useElements)(),[B,ae]=(0,o.useState)(!1),me=(0,o.useRef)(!1),[ue,Ae]=(0,o.useState)(!1),[ct,Ge]=(0,o.useState)("loading"),[D,bt]=(0,o.useState)(""),Xe=!(0,c.isValidEmail)(n?.trim()),Le=!Xe||(0,c.isValidEmail)(D.trim()),fe=(0,o.useCallback)(async()=>{if(!b||!Te||K||me.current||!ue)return;me.current=!0,ae(!0);let J=S?await S("card"):{proceed:!0};if(!J.proceed){me.current=!1,ae(!1);return}I?.("card");let G=J.sessionId??t,Fe=J.nonce??r,je=(0,Uo.splitFullName)(a?.trim()),Je=(0,un.compactBuyerIdentity)({email:J.accountPatch?.email?.trim()||n?.trim()||D.trim(),firstName:J.accountPatch?.firstName?.trim()||je.firstName,lastName:J.accountPatch?.lastName?.trim()||je.lastName}),re=Je.email,Q=(0,un.compactBuyerIdentity)({...J.accountPatch,...Je});try{if(p?.(null),!(0,c.isValidEmail)(re))throw new Error("A valid email address is required for payment.");await i?.(Je);let se=await Te.submit();if(se.error){p?.(se.error.message??"Payment failed.");return}let W=[Je.firstName,Je.lastName].filter(Boolean).join(" "),We=await b.createPaymentMethod({elements:Te,params:{billing_details:{email:re,...W?{name:W}:{}}}});if(We.error||!We.paymentMethod){p?.(We.error?.message??"Failed to create payment method.");return}let Be=We.paymentMethod;if(!G||!re)throw new Error("Missing sessionId or email for payment.");let ge=Be.type||e,N=await mi(l,pe,G,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ge,paymentMethodId:null,intentKind:"payment"});if(N.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ce=N.clientSecret;nr(jn,{clientSecret:Ce,sessionId:G,nonce:Fe,accountPatch:Q,paymentMethodId:Be.id,paymentMethodType:Be.type??e,gateway:"stripe"});let{error:dt,paymentIntent:Ne}=await b.confirmPayment({clientSecret:Ce,confirmParams:{return_url:window.location.href,payment_method:Be.id},redirect:"if_required"});if(dt){nr(jn);let nt=dt.message??"Payment failed.";p?.(nt),P?.(hr("card",nt,{code:dt.code})),await yi({billingApiUrl:l,sessionId:G,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:dt.code??"provider_declined"}});return}let at=Ne?.status;if(!pa(at)){nr(jn);let nt=at==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(nt),P?.(hr("card",nt,{code:at??"missing_payment_intent"}));return}nr(jn);let Me=typeof Ne?.payment_method=="string"?Ne.payment_method:Ne?.payment_method?.id;u({id:Me??Be.id,type:"card",threeDSecureActionResultTokenId:Ne?.id,gateway:"stripe",paymentMethodType:Be.type??e},{accountPatch:Q,paymentMethodCategory:"apm",sessionId:G,nonce:Fe})}catch(se){p?.(se instanceof Error?se.message:"Payment failed. Please try again.")}finally{me.current=!1,ae(!1)}},[b,Te,K,ue,S,I,t,r,n,a,D,i,l,pe,e,u,p,P]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Xe&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Xe&&(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:J=>bt(J.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(rr.PaymentElement,{onReady:()=>Ge("ready"),onLoadError:()=>{Ge("load_error"),ds(Pr(v),"stripe","apm")},onChange:J=>{Ae(!!J.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:()=>{fe()},disabled:!ue||!Le||B||K||ct!=="ready",color:_,borderRadius:X,style:T,children:B?"Processing\u2026":`Pay with ${(0,c.getStripeMethodDisplayName)(e)}`}),y&&(0,d.jsx)(Wo,{margin:"0.75rem 0 0",children:y})]})}function Hl({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:l,stripeInstance:u,paymentElementBaseOptions:p,futureUseSession:P,onTokenizedBody:E,onErrorChange:S,onButtonClick:I,onDecline:K,runBeforeButtonClick:_,onLoadStateChange:X,isProcessing:T=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:v=8,submitButtonStyle:pe,buttonAppearance:b,themeId:Te,onExpandApm:B,expandedApmMethod:ae}){let{emitInstrument:me}=(0,o.useContext)(dn),[ue,Ae]=(0,o.useState)(null),[ct,Ge]=(0,o.useState)(null),D=(0,o.useRef)(!1),{request:bt,collect:Xe,finish:Le}=zo();(0,o.useEffect)(()=>{l.length>0&&u?X?.("ready"):u||X?.("loading")},[l.length,u,X]);let fe=(0,o.useCallback)(async re=>{if(!u||D.current||T)return;D.current=!0,Ge(re);let Q=_?await _("card"):{proceed:!0};if(!Q.proceed){D.current=!1,Ge(null);return}I?.("card");let se=Q.sessionId??e,W=Q.nonce??t,We=(0,Uo.splitFullName)([Q.accountPatch?.firstName,Q.accountPatch?.lastName].filter(Boolean).join(" ")||n),Be=(0,un.compactBuyerIdentity)({email:Q.accountPatch?.email?.trim()||r?.trim(),firstName:Q.accountPatch?.firstName?.trim()||We.firstName,lastName:Q.accountPatch?.lastName?.trim()||We.lastName});if(!(0,c.isValidEmail)(Be.email)){Ge(null);let Ce=await Xe((0,c.getStripeMethodDisplayName)(re),Be);if(!Ce){D.current=!1;return}Be=Ce,Ge(re)}let ge=Be.email,N=(0,un.compactBuyerIdentity)({...Q.accountPatch,...Be});try{if(S?.(null),!se||!(0,c.isValidEmail)(ge))throw new Error("Missing sessionId or email for payment.");await a?.(Be);let Ce=await mi(i,me,se,W??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,paymentMethodId:null,intentKind:"payment"});if(Ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let dt=Ce.clientSecret;nr(jn,{clientSecret:dt,sessionId:se,nonce:W,accountPatch:N,paymentMethodType:re,gateway:"stripe"});let{error:Ne,paymentIntent:at}=await u.confirmPayment({clientSecret:dt,confirmParams:{return_url:window.location.href,payment_method_data:{type:re,billing_details:{name:[Be.firstName,Be.lastName].filter(Boolean).join(" "),...ge?{email:ge}:{}}}},redirect:"if_required"});if(Ne){nr(jn);let it=Ne.message??"Payment failed.";S?.(it),K?.(hr("card",it,{code:Ne.code})),await yi({billingApiUrl:i,sessionId:se,nonce:W,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,providerDeclineReason:Ne.code??"provider_declined"}});return}let Me=at?.status;if(!pa(Me)){nr(jn);let it=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(it),K?.(hr("card",it,{code:Me??"missing_payment_intent"}));return}nr(jn);let nt=typeof at?.payment_method=="string"?at.payment_method:at?.payment_method?.id;E({id:nt??at?.id,type:"card",threeDSecureActionResultTokenId:at?.id,gateway:"stripe",paymentMethodType:re},{accountPatch:N,paymentMethodCategory:"apm",sessionId:se,nonce:W})}catch(Ce){S?.(Ce instanceof Error?Ce.message:"Payment failed. Please try again.")}finally{D.current=!1,Ge(null)}},[u,T,_,I,e,t,r,Xe,i,me,n,a,E,S,K]),[J,G]=(0,o.useState)(null),Fe=B?ae??null:J,je=(0,o.useCallback)(re=>{D.current||T||Fe&&Fe!==re||((0,c.needsStripeMethodExplicitConfirm)(re)?B?B(re):G(re):fe(re))},[Fe,T,fe,B]),Je=(0,o.useMemo)(()=>J?Jl(p,J,P):null,[J,p,P]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:bt?(0,d.jsx)(qo,{identity:bt.identity,methodLabel:bt.methodLabel,onComplete:Le,onCancel:()=>Le(null)},bt.id):l.map(re=>{let Q=ae===re,se=ct===re,W=ct!==null&&ct!==re||ae!=null&&ae!==re;return(0,d.jsxs)(o.default.Fragment,{children:[(0,d.jsx)(oi,{method:re,themeId:Te,submitting:se,disabled:W,highlighted:Q,hasNextStep:(0,c.needsStripeMethodExplicitConfirm)(re),onClick:()=>je(re),backgroundColor:b?.backgroundColor,borderColor:b?.borderColor,textColor:b?.textColor,borderRadius:b?.borderRadius,fontFamily:b?.fontFamily}),!B&&J===re&&Je&&u&&(0,d.jsx)(rr.Elements,{stripe:u,options:Je,children:(0,d.jsx)(ls,{method:re,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:E,onErrorChange:S,onDecline:K,onCancel:()=>G(null),runBeforeButtonClick:_,onButtonClick:I,isProcessing:T,submitButtonColor:y,submitButtonBorderRadius:v,submitButtonStyle:pe})},re)]},re)})})}function Wd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:i,onComplete:l,onError:u,onDecline:p,onCancel:P,onTokenizedBody:E,firstName:S,lastName:I,chv:K,className:_,submitLabel:X,isProcessing:T,error:y,onErrorChange:v,showPayPal:pe=!0,showStripe:b=!0,walletPresentation:Te="auto",enabledPaymentMethods:B,enabledPaymentMethodCountries:ae,showApplePay:me=!0,showGooglePay:ue=!0,layout:Ae="default",theme:ct,buttonsTheme:Ge,buttonsStyles:D,appearance:bt,cardButtonContent:Xe,cardBackButtonContent:Le,cardTitleContent:fe,showSecurityFooter:J,onButtonClick:G,onBeforeButtonClick:Fe,onBuyerIdentityReady:je,enableAVS:Je,cardFieldOrder:re,cardPreFormSlot:Q,avsLayout:se="row",country:W,zip:We,addressLine1:Be,addressLine2:ge,city:N,state:Ce,onCountryChange:dt,onZipChange:Ne,avsCheck:at,checkoutType:Me,checkoutLayout:nt,totalAmount:it=0,currency:ar="usd",initialCardOpen:Dt=!1,directPaypal:St,isSubscription:we=!1,session:M,dataAttachmentPending:ft=!1,dataAttachmentRequiresIdentity:ut=!1,debug:z=!1}){let ke=Qn(),Nt=Ga(),Ue=(0,o.useContext)(Rn),{emitInstrument:Mt}=(0,o.useContext)(dn),w=(0,o.useRef)(null);w.current||(w.current=Xa());let O=w.current,[,$e]=(0,o.useState)(0),Re=(0,o.useRef)(null);Re.current||(Re.current=(0,Un.detectPayPalEnvironment)());let h=Re.current,ce=(0,o.useMemo)(()=>({browser:h,capability:O,presentationMode:"popup"}),[h,O]),q=M??Ue.session,V=(0,o.useMemo)(()=>({futureUse:q?.futureUse,futureUseUnsupported:q?.futureUseUnsupported}),[q?.futureUse,q?.futureUseUnsupported]),De=q?.gateways?.paypal?.providerObjectType??St?.providerObjectType,f=ft||Ue.claimPending===!0,he=ut||Ue.claimRequiresIdentity===!0,ye=f&&!he,gt=bl(),x=r||gt,[be,Gt]=(0,o.useState)(!1),[br,Tr]=(0,o.useState)(null),[xt,Kr]=(0,o.useState)(W??""),[Lr,Sr]=(0,o.useState)(We??""),[ir,Nr]=(0,o.useState)(Be??""),[Yt,Mn]=(0,o.useState)(ge??""),[Wt,vt]=(0,o.useState)(N??""),[_t,yr]=(0,o.useState)(Ce??""),[jt,Jt]=(0,o.useState)(""),[nn,Ur]=(0,o.useState)({}),wr=(0,o.useRef)(We??""),kr=(0,o.useRef)(W??""),fr=(0,o.useRef)(Be??""),Zt=(0,o.useRef)(ge??""),Ft=(0,o.useRef)(N??""),pr=(0,o.useRef)(Ce??""),Rr=(0,o.useRef)(""),$t=(0,o.useRef)({});(0,o.useEffect)(()=>{let s=(k,ie,He,ne,_e)=>{if($t.current[k])return;let qt=ie?.trim();!qt||qt===He.current||(He.current=qt,ne(qt),_e?.(qt))};s("country",W,kr,Kr,dt),s("zip",We,wr,Sr,Ne),s("addressLine1",Be,fr,Nr),s("addressLine2",ge,Zt,Mn),s("city",N,Ft,vt),s("state",Ce,pr,yr)},[W,We,Be,ge,N,Ce,dt,Ne]);let Ze=(0,o.useMemo)(()=>(0,c.resolveAVSConfig)(Je),[Je]),zr=Ze!==null,Gr=(0,o.useMemo)(()=>(0,c.isAuthorizationOnlySession)(M),[M]),Ar=(0,c.isMountableVaultBlock)(M?.vault),sr=!!M?.gateways?.pcivault,hn=(0,kn.hasServerSideCardGateway)(M),on=!!(M?.gateways?.stripe?.enabledPaymentMethods??B)?.includes("card")||(0,kn.canRecoverHostedCardForm)(M),Ot=Ar||on||sr,xe=!!(b&&Ot&&e),[Y,Z]=(0,o.useState)(()=>Ae!=="buttons"||Dt?e??null:null),[te,Lt]=(0,o.useState)(0),Tt=Ae!=="buttons"||Dt||!!e&&Y===e,Bt=M?.captureMethod,Fr=(0,o.useRef)(ke);(0,o.useEffect)(()=>{Fr.current=ke},[ke]);let[kt,oo]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!xe||!e||!Tt){oo(null);return}let s=Fr.current?Fr.current.cardCapture({sessionId:e,captureMethod:Bt}):new Tn.PciVaultCardCapture({sessionId:e,captureMethod:Bt,billingApiUrl:x,telemetry:n});return oo({sessionId:e,captureMethod:Bt,billingApiUrl:x,telemetry:n,capture:s}),()=>{s.unmount()}},[xe,e,Tt,Bt,x,n]);let Ut=xe&&e&&Tt&&kt?.sessionId===e&&kt.captureMethod===Bt&&kt.billingApiUrl===x&&kt.telemetry===n?kt.capture:null,Yr=(0,o.useMemo)(()=>{let s=xt,k=Ze?(0,c.isAVSFieldVisible)(Ze.postal_code,s):!1;return Ud(s,Lr,k)},[Ze,xt,Lr]),{avsInvalid:An,invalidAvsFields:an}=(0,o.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!xe||!Ze)return{avsInvalid:!1,invalidAvsFields:s};let k=xt,ie=(_e,qt)=>(0,c.isAVSFieldVisible)(_e,k)&&!qt.trim(),He={line1:ie(Ze.address_line_1,ir),city:ie(Ze.city,Wt),state:ie(Ze.state,_t),zip:Yr.empty||Yr.malformed};return{avsInvalid:He.line1||He.city||He.state||He.zip,invalidAvsFields:He}},[xe,Ze,xt,ir,Wt,_t,Yr]),[Qt,Pn]=(0,o.useState)(!1),[$n,Fn]=(0,o.useState)(!1),[Br,ao]=(0,o.useState)(!1),[sn,Hn]=(0,o.useState)({line1:!1,city:!1,state:!1}),Xr=(0,o.useRef)(!1),vn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Bn=(0,o.useRef)(!1),zt=(0,o.useCallback)(s=>{vn.current[s]=!0,Bn.current=!0},[]),Jr=(0,o.useCallback)(s=>!Xr.current&&vn.current[s],[]),Zr=(0,o.useCallback)(s=>{Jr(s)&&Hn(k=>k[s]?k:{...k,[s]:!0})},[Jr]),[qr,Cn]=(0,o.useState)(()=>(0,c.resolveVaultMountOptions)(M?.vault,{billingApiUrl:x,sessionId:e,nonce:t})),[Ct,Er]=(0,o.useState)(Dt&&Ot?"card":"buttons"),[lr,jr]=(0,o.useState)(null),mo=Ct==="expanding"||Ct==="card",bn=M?.gateways?.stripe&&!hn?"stripe":void 0,Kn=(0,o.useCallback)(()=>{Mt?.({class:"card_surface",provider:bn})},[bn,Mt]),Qr=(0,o.useRef)(null),Ir=(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 Dn=(0,o.useRef)(!1),[Mr,L]=(0,o.useState)(0),U=(0,o.useRef)(null),ee=(0,o.useCallback)(()=>{Kn(),Z(e??null),Dn.current&&(Dn.current=!1,L(s=>s+1)),Lt(s=>s+1),Er("expanding"),Ir(()=>Er("card"))},[Ir,Kn,e]),Ee=(0,o.useCallback)(()=>{Er("collapsing"),Ir(()=>Er("buttons"))},[Ir]),Rt=(0,o.useCallback)(s=>{jr(s),Er("apm-expanding"),Ir(()=>Er("apm-form"))},[Ir]),er=(0,o.useCallback)(()=>{Er("apm-collapsing"),Ir(()=>{Er("buttons"),jr(null)})},[Ir]);(0,o.useEffect)(()=>{Ae==="buttons"&&Dt&&Ot&&(Z(e??null),Er("card"))},[Ae,Dt,Ot,e]);let[ze,le]=(0,o.useState)(null),j=(0,o.useRef)(!1),$=(0,o.useRef)(null),de=(0,o.useRef)("idle"),[g,m]=(0,o.useState)(!1),H=(0,o.useRef)(g);H.current=g;let[Ie,Qe]=(0,o.useState)(()=>St?.existingOrderId?{orderId:St.existingOrderId,attempts:1}:null),pt=(0,o.useRef)(Ie);(0,o.useEffect)(()=>{pt.current=Ie},[Ie]);let qe=(0,o.useRef)(null),Oe=(0,o.useMemo)(()=>{if(je||Ue.claimBuyerIdentity||M?.buyerIdentified!==!1||!e||!t)return;let s=`${x}|${e}|${t}`;qe.current?.key!==s&&(qe.current={key:s,claim:Lo(new Tn.PaymentAPI(x,{telemetry:!1}),e,t,{...i?{userId:i}:{},...S?{firstName:S}:{},...I?{lastName:I}:{}})});let k=qe.current.claim;return async ie=>{await k(ie)}},[je,Ue.claimBuyerIdentity,M?.buyerIdentified,e,t,x,i,S,I]),st=je??Ue.claimBuyerIdentity??Oe,wt=y??br,Et=(0,o.useMemo)(()=>(0,c.resolveTheme)(ct),[ct]),A=(0,o.useMemo)(()=>{let s=Et?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(Ge);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},[Et,Ge,D]),Pe=bt??Et?.appearance,et=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:Pe,buttonsStyles:A,layout:Ae}),[Pe,A,Ae]),ot=Ue.inlineSessionPatchProcessing??!1,oe=(T??be)||ot,cr=x.replace(/\/+$/,""),ve=(0,o.useMemo)(()=>Ki({userId:i,email:a,firstName:S,lastName:I,country:W,zip:We},nn),[i,a,S,I,W,We,nn]),Gn=[ve.firstName,ve.lastName].filter(s=>!!s?.trim()).join(" "),ws=!(0,c.isValidEmail)(ve.email?.trim()),ki=(0,o.useRef)(null);xe&&ki.current===null&&(ki.current=ws);let io=xe&&(ki.current??ws),Ri=(0,o.useMemo)(()=>zd(jt,io),[jt,io]),ko=Ri.empty||Ri.malformed,en=(0,o.useMemo)(()=>ke?ke.getRawProvider():null,[ke]),ks=(0,o.useMemo)(()=>Nt?Nt.getRawProvider():null,[Nt]),Qo=it||100,Ro=ar.toLowerCase(),Ei=(0,o.useMemo)(()=>Pe?(0,Tn.toStripeAppearance)(Pe):null,[Pe]),Eo=Ei,Rs=(0,o.useMemo)(()=>{let s=Ei??{},k=s.rules??{};return{...s,rules:{...k,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...k[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...k[".AccordionItemContents"]??{}}}}},[Ei]),Es=(0,o.useMemo)(()=>({...Pl(it,q?.captureMethod,V),currency:Ro,...Eo?{appearance:Eo}:null}),[it,Ro,q?.captureMethod,V,Eo]),Ii=(0,c.resolveSetupFutureUsage)(V,"paypal","paypal"),Is=(0,o.useMemo)(()=>({mode:"payment",amount:Qo,currency:Ro,captureMethod:"manual",...Ii?{setupFutureUsage:Ii}:null,...Eo?{appearance:Eo}:null}),[Qo,Ro,Ii,Eo]),Ve=(0,o.useCallback)(s=>{Tr(s),v?.(s)},[v]),_s=(0,o.useRef)(0);(0,o.useEffect)(()=>{Mr!==_s.current&&(_s.current=Mr,Ve(null))},[Mr,Ve]);let _i=(0,o.useRef)(""),[Ts,Cc]=(0,o.useState)(!1),Ti=(0,o.useCallback)(()=>{Cc(!0)},[]);(0,o.useEffect)(()=>{if(!xe||!io||!st||!Ts||ko||_i.current)return;let s=(0,un.compactBuyerIdentity)({email:(0,c.isValidEmail)(ve.email?.trim())?ve.email?.trim():Rr.current.trim(),firstName:ve.firstName?.trim(),lastName:ve.lastName?.trim()});_i.current=JSON.stringify(s),Ur(k=>({...k,...s})),Promise.resolve(st(s)).catch(k=>{_i.current="",Ve(k instanceof Error?k.message:"Failed to attach buyer details.")})},[xe,io,st,Ts,ko,ve.email,ve.firstName,ve.lastName,Ve]),(0,o.useEffect)(()=>{!xe||!Ut||Ut.setCardFieldOrder?.(re??null,Ze==null&&!io)},[xe,Ut,re,Ze,io]),(0,o.useEffect)(()=>{(Ct==="expanding"||Ct==="collapsing"||Ct==="apm-expanding"||Ct==="apm-collapsing")&&Ve(null)},[Ct,Ve]);let On=(0,o.useCallback)((s,k,ie)=>{p?.(hr(s,k,ie))},[p]),Io=(0,o.useCallback)((s,k,ie)=>{let He=ie?.popupBlocked??(0,Se.isPopupBlockedError)(k);He&&O.markBlocked()&&$e(It=>It+1);let ne=ss(s),_e=ie?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(ne):(0,Se.buildExternalMethodRecoveryMessage)(ne,He,h.inAppBrowser),qt=(0,Se.getProviderErrorCode)(k),cn=(qt?.toLowerCase()==="error"?void 0:qt)??(0,Se.sanitizeExternalFailureCode)(ie?.code)??"external_payment_method_failed",ht=new c.FloPayError(_e,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:cn,popupBlocked:He,inAppBrowser:h.inAppBrowser,appFamily:h.appFamily,popupCapability:O.current(),presentationMode:ie?.presentationMode??"popup"}});ie?.telemetryReported||Pr(ke)?.error(Go({...ce,presentationMode:ie?.presentationMode??"popup"},{errorCode:He?"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??(He?"popup_blocked":"provider_error")})),le(null),Ae==="buttons"&&(Er("buttons"),jr(null)),Ve(_e),u?.(ht),console.error("[FloPay] External payment method failed:",{method:s,code:cn,popupBlocked:He})},[h,ce,ke,Ae,u,O,Ve]);(0,o.useEffect)(()=>{if(!xe||!e){Cn(null);return}let s={billingApiUrl:cr,sessionId:e,nonce:t},k=(0,c.resolveVaultMountOptions)(M?.vault,s);if(k){Cn(k);return}if(!Tt){Cn(null);return}let ie=`${cr}\0${e}\0${t??""}`,He=U.current;if(He&&He.key===ie){Cn(He.mount);return}Cn(null);let ne=!0;return new Tn.PaymentAPI(cr).getVaultCapture(e,t).then(_e=>{if(!ne)return;let qt=(0,c.resolveVaultMountOptions)(_e,s);qt?.verificationRequired&&!_e.html&&(U.current={key:ie,mount:qt}),qt?Cn(qt):Ve("Failed to load the secure card form.")}).catch(_e=>{ne&&Ve(_e instanceof Error?_e.message:"Failed to load the secure card form.")}),()=>{ne=!1}},[xe,Tt,te,e,M?.vault,cr,t,Ve]);let Sn=(0,o.useRef)({onComplete:l,onError:u,updateError:Ve,emitDecline:On,resolvedAccount:ve,avsConfig:Ze,avsCheckProp:at,sessionId:e,nonce:t,baseUrl:cr,captureMethod:M?.captureMethod,paymentId:M?.paymentId,authorizationExpiresAt:M?.authorizationExpiresAt,serverSideCardGateway:hn});Sn.current={onComplete:l,onError:u,updateError:Ve,emitDecline:On,resolvedAccount:ve,avsConfig:Ze,avsCheckProp:at,sessionId:e,nonce:t,baseUrl:cr,captureMethod:M?.captureMethod,paymentId:M?.paymentId,authorizationExpiresAt:M?.authorizationExpiresAt,serverSideCardGateway:hn};let Mi=(0,o.useRef)(!1),Ms=(0,o.useCallback)(()=>{let s=Sn.current,k=s.resolvedAccount.email?.trim(),ie=(0,c.isValidEmail)(k)?k:Rr.current.trim();if(!(0,c.isValidEmail)(ie))return null;let He=s.resolvedAccount.firstName?.trim(),ne=s.resolvedAccount.lastName?.trim(),_e=kr.current.trim()||s.resolvedAccount.country?.trim()||"",qt=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.state,_e):!1,cn=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.address_line_1,_e):!1,ht=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.postal_code,_e):!1,It=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.city,_e):!1,At=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.address_line_2,_e):!1,Ht=cn&&!qt&&ht?(0,c.getStateFromPostalCode)(_e,(wr.current??"").trim()):null,go=qt?pr.current:Ht;return{accountData:{userId:s.resolvedAccount.userId??"",email:ie,...He?{firstName:He}:{},...ne?{lastName:ne}:{},...ht&&wr.current?{zip:wr.current}:{},...It&&Ft.current?{city:Ft.current}:{},...go?{state:go}:{},...cn&&fr.current?{addressLine1:fr.current}:{},...At&&Zt.current?{addressLine2:Zt.current}:{},..._e?{country:_e}:{}},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,c.isAVSFieldVisible)(s.avsConfig.country,_e),postal_code:ht,address_line_1:cn,address_line_2:At,city:It,state:qt}}:{}}},[]),xs=(0,o.useRef)(f);xs.current=f,(0,o.useEffect)(()=>{f||wt!==Ul||Sn.current.updateError(null)},[f,wt]),(0,o.useEffect)(()=>{!xe||!Ut||Ut.setSubmitGate?.(An||f||ko||g)},[xe,Ut,An,f,ko,g]),(0,o.useEffect)(()=>{if(!xe||!Ut)return;Mi.current=!1;let s=null,k=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,de.current="idle",le(null)},400)},ie=Ut.on("submitting",()=>{Pn(!0),$.current&&clearTimeout($.current),de.current="validation-window",$.current=setTimeout(()=>{$.current=null,de.current==="validation-window"&&(de.current="processing")},Td),le("processing");let ht=Sn.current;if(!ht.sessionId||!ht.nonce)return;let It=Ms();if(!It){ht.updateError("Enter a valid email address."),de.current="idle",le(null);return}new Tn.PaymentAPI(ht.baseUrl).patchAccountSnapshot(ht.sessionId,ht.nonce,It,{telemetryMode:"best_effort"}).catch(At=>{if(!xd(At))return;let Ht=At instanceof Error?At.message:"Please check your billing address and try again.";ht.updateError(Ht),de.current="idle",le(null),ht.onError?.(At instanceof c.FloPayError?At:new c.FloPayError(Ht,"api_error"))})}),He=Ut.on("complete",ht=>{(0,In.markSessionRecentlyCompleted)(ht.sessionId??Sn.current.sessionId),de.current="terminal",m(!1),le("success"),setTimeout(()=>{if(Mi.current)return;Mi.current=!0;let It=Sn.current,At=(0,c.isAuthorizationOnlySession)(It)||ht.outcome==="authorized",Ht=It.serverSideCardGateway?{}:{paymentIntentId:ht.intentId};Sn.current.onComplete?.(At?{status:"authorized",...Ht,paymentId:ht.paymentId??It.paymentId,sessionId:ht.sessionId??It.sessionId,authorizationExpiresAt:ht.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Ht,checkoutMethod:"card"})},600)}),ne=Ut.on("decline",ht=>{let It=Sn.current,At=ht.message??"Your payment was declined. Please try another card or contact your bank.";de.current="terminal",m(!1),It.updateError(At),le("error");let Ht=ht.failureOutcome??(0,c.normalizeCheckoutFailureOutcome)(ht.declineReason)??"authorization_declined";It.emitDecline("card",At,{code:Ht,declineCode:Ht}),k()}),_e=Ut.on("error",ht=>{let It=Sn.current,At=ht.message??"There was a problem processing your payment. Please try again.";de.current="terminal",m(!1),It.updateError(At),le("error"),It.onError?.(new c.FloPayError(At,"api_error",{code:ht.failureOutcome??"capture_failed"})),k()}),qt=Ut.on("challenge_dismissed",()=>{$.current&&(clearTimeout($.current),$.current=null),de.current="processing",m(!0),le(null)}),cn=Ut.on("blocked",()=>{if(H.current){Sn.current.updateError(Md);return}if(!xs.current){Pn(!0);return}Ti(),Sn.current.updateError(Ul)});return()=>{s&&(clearTimeout(s),s=null),$.current&&(clearTimeout($.current),$.current=null),de.current="idle",m(!1),le(null),ie(),He(),ne(),_e(),qt(),cn()}},[xe,Ut,Ti,Ms]);let Ln=!!St?.clientId,ea=Array.isArray(B),Fa=ea&&B.length>0,As=ea&&B.includes("paypal"),Ba=(0,o.useRef)(null);Ba.current===null&&(Ba.current=(0,c.hasMatchingStripePayPalReturn)());let _o=Ba.current?"redirect":(0,zn.resolveStripePayPalPresentation)(h,Te,O.current()),{expressMethods:Da,paymentElementMethods:xi}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(B,{excludePaypal:Ln}),[B,Ln]),Fs=Ln||!!Nt||As&&_o==="redirect",bc=(0,o.useMemo)(()=>Fs?Da.filter(s=>s!=="paypal"):Da,[Da,Fs]),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,Bs=zr?xt:W,Oa=(0,o.useMemo)(()=>(0,c.filterStripeMethodsByCountryGate)(xi,Bs,ae),[xi,Bs,ae]),Ai=(0,o.useMemo)(()=>({mode:"payment",amount:Qo,currency:Ro,paymentMethodCreation:"manual",appearance:Rs}),[Qo,Ro,Rs]),[Ds,Os]=(0,o.useState)("loading"),[Ls,Ns]=(0,o.useState)("loading"),[Us,zs]=(0,o.useState)("loading"),[kc,Fi]=(0,o.useState)(!1),[qs,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,St?.approvalPresentation,De??(we?"subscription":"order")):"popup",js=pe&&(Ln||(ea?As:La===!1)),Vs=b&&wc,ta=(!ye||!!Ue.waitForDataAttachment)&&js&&Ln,Ws=qs==="retrying"||qs==="exhausted",ra=null;b&&(Nt?ra=ks:_o==="redirect"&&(ra=en));let $s=(0,o.useMemo)(()=>({...ce,presentationMode:_o}),[ce,_o]),na=!ye&&js&&!!ra&&(!Ln||Ws),Mo=!ye&&Vs&&!!en,oa=!ye&&b&&Fa&&Oa.length>0&&!!en,Ec=ta&&!Ws?kc:na&&ts(Ds),Ic=Mo&&ts(Ls),_c=oa&&Us!=="load_error",Hs=s=>s==="loading"||s==="ready",Ks=ta||na&&Hs(Ds)||Mo&&Hs(Ls)||oa&&Us!=="load_error",Ua=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Ua.current){if(!b&&!pe){Ua.current=!0;let s=new c.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(s),Ve(s.message)}else if(!b&&pe&&!Ln){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),Ve(s.message)}else if(La!==void 0&&!ye&&!Ot&&!Ks){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),Ve(s.message)}}},[b,pe,Ln,La,ye,Ot,Ks,u,Ve]);let Gs=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(Gs.current||!Fa)return;let s=[];me!==!0&&s.push("showApplePay"),ue!==!0&&s.push("showGooglePay"),s.length!==0&&(Gs.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 Ys=(0,o.useCallback)((s,k)=>Ue.applyInlineSessionPatch?Ue.applyInlineSessionPatch(s).then(ie=>({error:null,sessionId:ie.sessionId||e,nonce:ie.session?.clientSecret||t})).catch(ie=>{let He=(0,c.normalizeBeforeButtonClickError)(k,ie);return Ve(He.message),u?.(He),{error:He,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ue.applyInlineSessionPatch,t,u,e,Ve]),wn=(0,o.useCallback)(async s=>{if(s!=="card"&&ye&&await Ue.waitForDataAttachment?.(),!Fe)return{proceed:!0};try{let k=await Fe({method:s,sessionId:e||void 0,createSession:Ue.inlineSessionDraft});if(k===!1)return{proceed:!1};if(k&&typeof k=="object"){k.account&&Ur(He=>({...He??{},...k.account}));let ie=await Ys(k,s);return ie.error?{proceed:!1,accountPatch:k.account}:{proceed:!0,accountPatch:k.account,sessionId:ie.sessionId,nonce:ie.nonce}}return{proceed:!0}}catch(k){let ie=(0,c.normalizeBeforeButtonClickError)(s,k);return Ve(ie.message),u?.(ie),{proceed:!1}}},[Ys,Ue.inlineSessionDraft,Ue.waitForDataAttachment,ye,Fe,u,e,Ve]),Xs=(0,o.useCallback)(async(s,k)=>{if(j.current)return;j.current=!0,Gt(!0),le("processing"),Ve(null);let ie=k?.sessionId??e,He=k?.nonce??t,ne=Ki(ve,k?.accountPatch),_e=k?.completionPaymentMethodId??ma(s),qt=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,cn=Dd(s),ht=k?.presentationMode?ni(Pr(ke),{...ce,presentationMode:k.presentationMode}):void 0,It=()=>{Mt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:cn}),ht?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",..._n,requestCategory:"process_payment"})};try{let At=new Tn.PaymentAPI(cr),Ht=await At.processPayment(ne.userId??"",{sessionId:ie,nonce:He,paymentMethodCategory:k?.paymentMethodCategory??Ld(s),tokenizedData:qt,accountData:{...k?.accountPatch,userId:ne.userId??"",email:ne.email??"",firstName:ne.firstName||void 0,lastName:ne.lastName||void 0,...(0,c.buildProcessPaymentAvsAccount)({avsConfig:Ze,country:kr.current,zip:wr.current,city:Ft.current,state:pr.current,addressLine1:fr.current,addressLine2:Zt.current})},...(0,c.buildCheckoutProcessMetadata)({chv:K,avsCheck:at,checkoutType:Me,checkoutLayout:nt,avsConfig:Ze,country:kr.current})}),go=async gr=>{let ho=(0,c.isAuthorizationOnlySession)(M)||gr?.status==="authorized";(0,In.markSessionRecentlyCompleted)(ie),ht?.terminal({outcome:"payment_succeeded",..._n}),le("success"),Qe(null),await new Promise(da=>setTimeout(da,600));let Nn;typeof gr?.paymentId=="string"?Nn=gr.paymentId:M?.paymentId&&(Nn=M.paymentId);let Po;typeof gr?.authorizationExpiresAt=="string"?Po=gr.authorizationExpiresAt:M?.authorizationExpiresAt&&(Po=M.authorizationExpiresAt),l?.(ho?{status:"authorized",...Nn===void 0?{}:{paymentId:Nn},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(!ke||!gr){le("error"),Ve("PayPal authorization required but no token provided.");return}try{let Nn=Nt?.getRawProvider();if(!Nn){Ve("PayPal is not available.");return}let Po={return_url:window.location.href};ho&&(Po.payment_method=ho);let{error:da}=await Nn.confirmPayment({clientSecret:gr,confirmParams:Po,redirect:"if_required"});if(da){le("error");let ll=da.message??"PayPal payment failed.";Ve(ll),On("paypal",ll,{code:da.code})}}catch(Nn){le("error"),Ve(Nn instanceof Error?Nn.message:"PayPal authorization failed.")}return}if(tn?.type==="paypal_direct_required"){let gr=tn.orderId;if(!gr){le("error"),Ve("PayPal retry required but no order id provided.");return}let ho=pt.current?.attempts??0;if(ho>=2){le("error"),Ve("PayPal payment could not be completed after multiple attempts."),On("paypal","paypal_direct_required retry limit exceeded");return}Fi(!1),Bi("loading"),Qe({orderId:gr,attempts:ho+1}),le(null);return}if(Ht.headers.get(Sd)===wd){let gr=await kd(At,ie,He);if(gr!==void 0){await go(gr);return}}(0,c.classifyPaymentRejection)(Ht.status,tn)?ht?.terminal({outcome:"payment_declined",..._n,terminalReason:"provider_declined"}):It(),le("error");let sl=tn?.message??"Payment failed. Please try again.";Ve(sl),On(s.isPaypal?"paypal":"card",sl,{code:tn?.code??tn?.gatewayErrorCode,declineCode:tn?.declineCode??tn?.gatewayDeclineReason}),await new Promise(gr=>setTimeout(gr,400))}catch(At){Yl(At)||It(),le("error"),Ve(At instanceof Error?At.message:"An unexpected error occurred"),await new Promise(Ht=>setTimeout(Ht,400))}finally{Gt(!1),le(null),j.current=!1}},[cr,e,t,ve,Ze,at,Me,nt,K,ke,Nt,M,l,Ve,On,Mt,ce]),Vr=(0,o.useCallback)((s,k)=>{E?E(s):Xs(s,k)},[E,Xs]),aa=`${Kl}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(aa);if(!s)return;let k;try{k=JSON.parse(s)}catch{nr(aa);return}if(!k||typeof k.createdAt!="number"||Date.now()-k.createdAt<0||Date.now()-k.createdAt>Gl||typeof k.paymentMethodId!="string"||typeof k.providerIntentId!="string"||typeof k.paymentMethodType!="string"||k.sessionId!==e||!t||k.nonce!==t||!To.includes(k.paymentMethodType)){nr(aa);return}nr(aa),Vr({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.providerIntentId,gateway:"stripe",paymentMethodType:k.paymentMethodType},{...k.accountPatch?{accountPatch:k.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Vr,t,e,aa,To]);let Js=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Js.current)return;let[s,k,ie]=(0,c.readStripeRedirectParams)();if(!s||!k||Ba.current||!ke)return;let He=ke.getRawProvider();if(!He)return;let ne=It=>{let At=localStorage.getItem(It);if(!At)return null;try{return JSON.parse(At)}catch{return nr(It),null}},_e=ne(jn)??ne(Ol),qt;if(_e?.clientSecret){if(_e.clientSecret!==k)return;qt={..._e.accountPatch?{accountPatch:_e.accountPatch}:{},..._e.sessionId?{sessionId:_e.sessionId}:{},..._e.nonce?{nonce:_e.nonce}:{}}}else if(_e?.sessionId&&_e.sessionId!==e)return;Js.current=!0,nr(jn),nr(Ol),window.history.replaceState({},"",(0,c.stripeRedirectReturnUrl)());let cn=_e?.paymentMethodType??_e?.tokenType??"card",ht="card";(async()=>{if(ie==="failed"){let Yn="Payment was declined. Please try again.";Ve(Yn),On(ht,Yn);return}let{paymentIntent:It,error:At}=await He.retrievePaymentIntent(k);if(At){let Yn=At.message??"Failed to retrieve payment status.";Ve(Yn),On(ht,Yn,{code:At.code});return}let Ht=It?.status,go=pa(Ht);if(!It||!go){let Yn=Ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ve(Yn),On(ht,Yn,{code:Ht??"missing_payment_intent"});return}let tn=typeof It.payment_method=="string"?It.payment_method:It.payment_method?.id;Vr({id:tn??_e?.paymentMethodId??_e?.tokenId??It.id,type:"card",threeDSecureActionResultTokenId:It.id,gateway:_e?.gateway??"stripe",paymentMethodType:cn},qt)})()},[e,Vr,ke,Ve,On]);let Oi=(0,o.useCallback)(s=>{s.preventDefault()},[]);if(!(xe||ke!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ia=Ae==="buttons",Wr=Pe?.variables,Tc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Li=Wr?.colorBackground,Mc=Li&&!Tc.has(Li)?Li:void 0,sa=A.cardInputBorder??(ia?"#e5e7eb":"#A4A4FF"),Zs=Wr?.colorDanger??"#dc2626",Xt=s=>an[s]&&(sn[s]||Qt),za=ko&&(Br||Qt),ln=s=>s?Zs:sa,qa=(Yr.malformed||Yr.empty)&&($n||Qt),xc=ln(qa),Ni=A.cardFormContainer?.backgroundColor??Mc??(ia?"white":"#EDEDFF"),xo=A.cardInputBackground??Wr?.colorBackground??"white",Ui=Bo(Le),Qs=Bo(fe),Ao=A.nameInput,el=A.cardInputFontSize??qd(Ao?.fontSize)??Wr?.fontSizeBase??"16px",tl=typeof Ao?.fontFamily=="string"?Ao.fontFamily:Wr?.fontFamily??"Poppins, sans-serif",rl=(0,c.toCssWeight)(Ao?.fontWeight)??400,Ac=A.cardInputColor??(typeof Ao?.color=="string"?Ao.color:void 0)??Wr?.colorText??"#262833",Fc=A.cardInputPlaceholderColor??"#9ca3af",tr=Wr?.borderRadius??"8px",yo=Wr?.borderRadius??A.cardButton?.borderRadius??tr,fo=Wr?.colorPrimary??"#4A49FF",Bc=Wr?.colorPrimaryHover??(0,c.darkenHex)(fo,.12),zi=Wr?.colorText??"#262833",qi={fontSize:el,fontFamily:tl,fontWeight:rl,color:Ac,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},la={marginTop:"0.375rem",...qi,fontSize:"0.75rem",lineHeight:1.4,color:Zs},Dc={"--flopay-input-placeholder-color":Fc,"--flopay-input-font-size":el,"--flopay-input-font-family":tl,"--flopay-input-font-weight":String(rl)},ca=A.cardFormContainer??{},ji=ca.padding??(ia?"0":"1rem"),Vi=ca.borderRadius??tr,Oc=Ut&&qr?(0,d.jsx)(co,{capture:Ut,html:qr.html,messageToken:qr.messageToken,expectedOrigin:qr.expectedOrigin,verificationRequired:qr.verificationRequired,theme:et,submitLabel:X,onReady:()=>{if(!io&&!Ze||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}}};Bn.current||s()},onError:s=>{s&&qr.verificationRequired&&de.current==="idle"&&(Dn.current=!0),Ve(s)},onValidation:s=>{let k=de.current;(k==="idle"||k==="validation-window")&&(Ve(s),s&&de.current==="validation-window"&&($.current&&(clearTimeout($.current),$.current=null),de.current="idle",le(null)))}},Mr):(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"}),nl=(0,d.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&Kn()},style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji,...Dc,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
|
|
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:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
|
@@ -35,13 +35,13 @@ ${gt.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),ia&&mo&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:xe?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:Ee,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,d.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,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:Le})]}),Qs?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...A.title},children:(0,d.jsx)(ua,{content:fe})})]}),!ia&&!Qs&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:zi,order:xe?-3:0,...A.title},children:(0,d.jsx)(ua,{content:fe})}),xe&&Q&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:Q}),xe&&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 ${ln(za)}`,borderRadius:tr,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=>{zt("email"),Rr.current=s.target.value,Jt(s.target.value)},onPointerDown:()=>zt("email"),onKeyDown:()=>zt("email"),onBlur:()=>{Jr("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,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"})]}),Ze&&(0,d.jsx)("div",{style:{order:xe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=xt,k=(ne=!1)=>({backgroundColor:xo,border:`1px solid ${ln(ne)}`,borderRadius:tr,marginTop:"0.5rem",padding:"10px"}),ie=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...qi}),He=(0,c.getStateOptions)(s);return(0,d.jsxs)(d.Fragment,{children:[(0,c.isAVSFieldVisible)(Ze.address_line_1,s)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:k(Xt("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:ir,onChange:ne=>{zt("line1"),$t.current.addressLine1=!0,fr.current=ne.target.value,Nr(ne.target.value)},onPointerDown:()=>zt("line1"),onKeyDown:()=>zt("line1"),onBlur:()=>Zr("line1"),disabled:oe,required:!0,"aria-invalid":Xt("line1")||void 0,"aria-describedby":Xt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:ie()})}),Xt("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)(Ze.address_line_2,s)&&(0,d.jsx)("div",{style:k(),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:Yt,onChange:ne=>{$t.current.addressLine2=!0,Zt.current=ne.target.value,Mn(ne.target.value)},disabled:oe,"data-testid":"flopay-address-line2",style:ie()})}),((0,c.isAVSFieldVisible)(Ze.city,s)||(0,c.isAVSFieldVisible)(Ze.state,s))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(Ze.city,s)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${ln(Xt("city"))}`,borderRight:`1px solid ${ln(Xt("city"))}`,borderBottom:`1px solid ${ln(Xt("city"))}`,borderLeft:`1px solid ${ln(Xt("city"))}`,padding:"10px",borderTopLeftRadius:tr,borderBottomLeftRadius:tr,...(0,c.isAVSFieldVisible)(Ze.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:tr}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Wt,onChange:ne=>{zt("city"),$t.current.city=!0,Ft.current=ne.target.value,vt(ne.target.value)},onPointerDown:()=>zt("city"),onKeyDown:()=>zt("city"),onBlur:()=>Zr("city"),disabled:oe,required:!0,"aria-invalid":Xt("city")||void 0,"aria-describedby":Xt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:ie()})}),(0,c.isAVSFieldVisible)(Ze.state,s)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${ln(Xt("state"))}`,borderRight:`1px solid ${ln(Xt("state"))}`,borderBottom:`1px solid ${ln(Xt("state"))}`,borderLeft:`1px solid ${ln(Xt("state"))}`,padding:"10px",borderTopRightRadius:tr,borderBottomRightRadius:tr,...(0,c.isAVSFieldVisible)(Ze.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${ln(Xt("state")||Xt("city"))}`}:{borderRadius:tr}},children:He?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:_t,onChange:ne=>{zt("state"),$t.current.state=!0,pr.current=ne.target.value,yr(ne.target.value)},onPointerDown:()=>zt("state"),onKeyDown:()=>zt("state"),onBlur:()=>Zr("state"),disabled:oe,autoComplete:"billing address-level1",required:!0,"aria-invalid":Xt("state")||void 0,"aria-describedby":Xt("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)}),He.map(ne=>(0,d.jsx)("option",{value:ne.code,children:ne.name},ne.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:_t,onChange:ne=>{zt("state"),$t.current.state=!0,pr.current=ne.target.value,yr(ne.target.value)},onPointerDown:()=>zt("state"),onKeyDown:()=>zt("state"),onBlur:()=>Zr("state"),disabled:oe,required:!0,"aria-invalid":Xt("state")||void 0,"aria-describedby":Xt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:ie()})})]}),Xt("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:la,children:"City is required"}),Xt("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)(Ze.country,s)||(0,c.isAVSFieldVisible)(Ze.postal_code,s))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:se==="column"?"column":"row",gap:se==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(Ze.country,s)&&(0,d.jsx)("div",{style:{flex:se==="row"?1:void 0,backgroundColor:xo,borderTop:`1px solid ${sa}`,borderRight:`1px solid ${sa}`,borderBottom:`1px solid ${sa}`,borderLeft:`1px solid ${sa}`,padding:"10px",...se==="row"&&(0,c.isAVSFieldVisible)(Ze.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:tr,borderBottomLeftRadius:tr,borderRight:"none"}:{borderRadius:tr}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:xt,onChange:ne=>{$t.current.country=!0,kr.current=ne.target.value,Kr(ne.target.value),dt?.(ne.target.value),pr.current="",yr("")},disabled:oe,autoComplete:"billing country","data-testid":"flopay-country",style:{...ie(),cursor:"pointer"},children:[xt===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,c.COUNTRY_OPTIONS.map(ne=>(0,d.jsxs)("option",{value:ne.code,children:[ne.flag," ",ne.name]},ne.code))]})}),(0,c.isAVSFieldVisible)(Ze.postal_code,s)&&(0,d.jsx)("div",{style:{flex:se==="row"?1:void 0,backgroundColor:xo,border:`1px solid ${xc}`,padding:"10px",...se==="row"&&(0,c.isAVSFieldVisible)(Ze.country,s)?{borderRadius:"0",borderTopRightRadius:tr,borderBottomRightRadius:tr}:{borderRadius:tr}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,c.getPostalCodeLabel)(xt),autoComplete:"billing postal-code",value:Lr,onChange:ne=>{zt("zip"),$t.current.zip=!0,wr.current=ne.target.value,Sr(ne.target.value),Ne?.(ne.target.value)},onPointerDown:()=>zt("zip"),onKeyDown:()=>zt("zip"),onBlur:()=>{Jr("zip")&&Fn(!0)},disabled:oe,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`:Nd(s)})]})})()}),xe&&Oc,wt&&(0,d.jsx)(Wo,{margin:"0.75rem 0",styleOverride:A.errorBanner,children:wt})]}),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"},ol=s=>z?!pe||!Ln?(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=${pe}`,` directPaypalConfigured=${Ln}`,` inAppBrowserDetected=${String(La)}`,` shouldRenderDirectPayPal=${ta}`,` shouldRenderStripePayPal=${na}`,` hasPaypalStripeInstance=${!!ks}`].join(`
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,il=Ct==="apm-expanding"||Ct==="apm-form"||Ct==="apm-collapsing",Fo;Ct==="apm-expanding"?Fo=zl:Ct==="apm-collapsing"&&(Fo=ql);let Va=lr?Jl(Ai,lr,V):null;if(Ae==="buttons"){let s=Ct==="buttons"||Ct==="expanding"||Ct==="apm-expanding",k=Ct==="expanding"||Ct==="card"||Ct==="collapsing",ie=Xe===void 0?{boxSizing:"border-box",height:Yo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},He;Ct==="expanding"||Ct==="apm-expanding"?He=Bd:(Ct==="collapsing"||Ct==="apm-collapsing")&&(He=Fd);let ne;return Ct==="expanding"?ne=zl:Ct==="collapsing"&&(ne=ql),(0,d.jsxs)("form",{onSubmit:Oi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Xo,{}),ze&&(0,d.jsx)($r,{status:ze,errorMessage:wt,authorized:Gr}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!He?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!He?Od:{},...He?{animation:He,pointerEvents:"none"}:{}},children:[ol("flopay-direct-paypal-gate-debug"),al("flopay-stripe-gate-debug"),ta&&St&&(0,d.jsxs)(d.Fragment,{children:[Ie&&(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:O,children:(0,d.jsx)(ha,{sessionId:e,nonce:t,billingApiUrl:x,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,clientId:St.clientId,environment:St.environment,currency:ar.toUpperCase(),isSubscription:we,providerObjectType:De,approvalPresentation:Na==="popup"?void 0:Na,onTokenizedBody:Vr,onComplete:l,onErrorChange:Ve,onDecline:p,onCancel:P,onTechnicalFailure:Io,onButtonClick:G,runBeforeButtonClick:wn,isProcessing:oe,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:q,existingOrderId:Ie?.orderId,debug:z},Ie?.orderId??"fresh")})]}),na&&(0,d.jsx)(rr.Elements,{stripe:ra,options:Is,children:(0,d.jsx)(Vl,{sessionId:e,nonce:t,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,billingApiUrl:x,onTokenizedBody:Vr,onErrorChange:Ve,isProcessing:oe,onButtonClick:G,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:wn,onLoadStateChange:Os,placeholderBorderRadius:yo,popupCapabilityOwner:O,externalTelemetryContext:$s,presentationMode:_o})}),Mo?(0,d.jsx)(rr.Elements,{stripe:en,options:Es,children:(0,d.jsx)($l,{sessionId:e,nonce:t,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,billingApiUrl:x,intentKind:it>0?"payment":"setup",expressMethods:To,onTokenizedBody:Vr,onErrorChange:Ve,onButtonClick:G,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:wn,onLoadStateChange:Ns,placeholderBorderRadius:yo,popupCapabilityOwner:O,externalTelemetryContext:ce})}):null,!Mo&&Vs?(0,d.jsx)("div",{style:{height:Yo,borderRadius:yo,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:x,paymentElementMethods:Oa,stripeInstance:en,paymentElementBaseOptions:Ai,futureUseSession:V,onTokenizedBody:Vr,onErrorChange:Ve,onButtonClick:G,onDecline:p,runBeforeButtonClick:wn,onLoadStateChange:zs,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,onExpandApm:Rt,expandedApmMethod:lr,themeId:ct,buttonAppearance:{backgroundColor:A.cardButton?.backgroundColor,borderColor:A.cardInputBorder,textColor:A.cardButton?.color,borderRadius:yo}}),xe&&(0,d.jsx)("button",{type:"button",onClick:async()=>{oe||!(await wn("card")).proceed||(G?.("card"),ee())},disabled:oe,style:{width:"100%",...ie,...A.cardButton,...us({themeBundle:Et,resolvedPrimaryColor:fo,resolvedBorderRadius:tr,submitButtonStyle:A.submitButton,explicitPrimaryColor:Wr?.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:_e=>{!oe&&(Et||Wr?.colorPrimary)&&(_e.currentTarget.style.backgroundColor=Bc)},onMouseLeave:_e=>{(Et||Wr?.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:Xe})}),wt&&Ct==="buttons"&&(0,d.jsx)(Wo,{margin:"0.25rem 0",styleOverride:A.errorBanner,children:wt})]}),xe&&k&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...ne?{animation:ne}:{},...Ct==="collapsing"?{pointerEvents:"none"}:{}},children:nl}),b&&il&&lr&&Va&&en&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Fo?{animation:Fo}:{},...Ct==="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: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,d.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,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:Le})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:zi,paddingRight:80,...A.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(lr)}`})]}),(0,d.jsx)(rr.Elements,{stripe:en,options:Va,children:(0,d.jsx)(ls,{method:lr,sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:st,billingApiUrl:x,onTokenizedBody:Vr,onErrorChange:Ve,onDecline:p,onCancel:er,runBeforeButtonClick:wn,onButtonClick:G,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,errorText:wt})},lr)]})})]})]})}return il&&lr&&Va&&en&&b?(0,d.jsxs)("form",{onSubmit:Oi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Xo,{}),ze&&(0,d.jsx)($r,{status:ze,errorMessage:wt,authorized:Gr}),(0,d.jsx)("div",{style:{...Fo?{animation:Fo}:{},...Ct==="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: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,d.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,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:Le})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:zi,paddingRight:80,...A.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(lr)}`})]}),(0,d.jsx)(rr.Elements,{stripe:en,options:Va,children:(0,d.jsx)(ls,{method:lr,sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:st,billingApiUrl:x,onTokenizedBody:Vr,onErrorChange:Ve,onDecline:p,onCancel:er,runBeforeButtonClick:wn,onButtonClick:G,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,errorText:wt})},lr)]})})]}):(0,d.jsxs)("form",{onSubmit:Oi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Xo,{}),ze&&(0,d.jsx)($r,{status:ze,errorMessage:wt,authorized:Gr}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ol("flopay-direct-paypal-gate-debug-default"),al("flopay-stripe-gate-debug-default"),ta&&St&&(0,d.jsxs)(d.Fragment,{children:[Ie&&(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:O,children:(0,d.jsx)(ha,{sessionId:e,nonce:t,billingApiUrl:x,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,clientId:St.clientId,environment:St.environment,currency:ar.toUpperCase(),isSubscription:we,providerObjectType:De,approvalPresentation:Na==="popup"?void 0:Na,onTokenizedBody:Vr,onComplete:l,onErrorChange:Ve,onDecline:p,onCancel:P,onTechnicalFailure:Io,onButtonClick:G,runBeforeButtonClick:wn,isProcessing:oe,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:q,existingOrderId:Ie?.orderId,debug:z},Ie?.orderId??"fresh")})]}),na&&(0,d.jsx)(rr.Elements,{stripe:ra,options:Is,children:(0,d.jsx)(Vl,{sessionId:e,nonce:t,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,billingApiUrl:x,onTokenizedBody:Vr,onErrorChange:Ve,isProcessing:oe,onButtonClick:G,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:wn,onLoadStateChange:Os,placeholderBorderRadius:yo,popupCapabilityOwner:O,externalTelemetryContext:$s,presentationMode:_o})}),Mo&&(0,d.jsx)(rr.Elements,{stripe:en,options:Es,children:(0,d.jsx)($l,{sessionId:e,nonce:t,email:ve.email,billingName:Gn||void 0,onBuyerIdentityReady:st,billingApiUrl:x,intentKind:it>0?"payment":"setup",expressMethods:To,onTokenizedBody:Vr,onErrorChange:Ve,onButtonClick:G,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:wn,onLoadStateChange:Ns,placeholderBorderRadius:yo,popupCapabilityOwner:O,externalTelemetryContext:ce})}),oa&&(0,d.jsx)(Hl,{sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:x,paymentElementMethods:Oa,stripeInstance:en,paymentElementBaseOptions:Ai,futureUseSession:V,onTokenizedBody:Vr,onErrorChange:Ve,onButtonClick:G,onDecline:p,runBeforeButtonClick:wn,onLoadStateChange:zs,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,themeId:ct,onExpandApm:Rt,expandedApmMethod:lr,buttonAppearance:{backgroundColor:A.cardButton?.backgroundColor,borderColor:A.cardInputBorder,textColor:A.cardButton?.color,borderRadius:yo}})]}),xe&&(Ic||Ec||_c)&&(0,d.jsx)(ci,{label:"or pay with card"}),xe&&nl]})}var F=require("react/jsx-runtime"),Jo=44,Ps="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 $d(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:Ke.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,Ke.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 Ke.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Ke.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 ys(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,Ke.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var Hd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Kd(e){return new ro.FloPay(Hd,{publishableKey:"provider_unavailable",...e})}async function fs(e,t){let{publishableKey:r,paypalPublishableKey:n}=Qi(e);return{...await es({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function vs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Gd(){if(!vs())return null;try{let e=window.sessionStorage.getItem(Ps);return e?JSON.parse(e):null}catch{return null}}function tc(e){if(vs())try{window.sessionStorage.setItem(Ps,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function gs(){if(vs())try{window.sessionStorage.removeItem(Ps)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Yd(){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 hs(e,t){return(0,Ke.resolveCheckoutLogLayout)(!!e,t)}function Xd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function nc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Jd(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:E,onInstrument:S,onDecline:I,onCancel:K,onCountryChange:_,onZipChange:X,showPayPal:T=!0,showStripe:y=!0,walletPresentation:v="auto",enabledPaymentMethods:pe,showApplePay:b=!0,showGooglePay:Te=!0,debug:B=!1,layout:ae,theme:me,buttonsTheme:ue,buttonsStyles:Ae,cardButtonContent:ct,cardBackButtonContent:Ge,cardTitleContent:D,showSecurityFooter:bt,onButtonClick:Xe,onBeforeButtonClick:Le,enableAVS:fe,cardFieldOrder:J,cardPreFormSlot:G,avsLayout:Fe,submitLabel:je,className:Je,initialErrorMessage:re=null,initialPayPalOrderId:Q,children:se,checkoutMode:W,confirmLabel:We,renderConfirmButton:Be,onSessionCompleted:ge}){let N=(0,Ke.resolveBillingApiUrl)(n),Ce=(0,C.useMemo)(()=>(0,Ke.resolveTheme)(me),[me]),dt=i??Ce?.appearance,Ne=r?"embedded_checkout":"standard_checkout",at=hs(se,ae),[Me,nt]=(0,C.useState)(null),[it,ar]=(0,C.useState)(null),Dt=(0,C.useRef)(null),St=(0,C.useRef)(null),we=(0,C.useRef)(0),[M,ft]=(0,C.useState)(null),ut=(0,C.useRef)(null),[z,ke]=(0,C.useState)(null),Nt=(0,C.useMemo)(()=>r?(0,mt.serializeCreateParams)(r):"",[r]),Ue=r?`create:${Nt}`:`session:${e??""}`,Mt=nc(z),w=(0,C.useRef)(new Set),O=(0,C.useRef)(Ue),$e=(0,C.useRef)(Ue);Co(()=>{$e.current=Ue,O.current!==Ue&&(O.current=Ue,w.current.clear())},[Ue]);let Re=(0,C.useCallback)(L=>{if($e.current===Ue){if(Xi.FLO_INSTRUMENT_ONCE_NAMES.has(L.name)){if(w.current.has(L.name))return;w.current.add(L.name)}(0,tt.invokeMerchantCallback)(()=>S?.(L))}},[Ue,S]),h=Vo(Re,Ue),ce=(0,C.useRef)(!1),q=(0,C.useCallback)(L=>{if(ce.current)return;let U=L.gateway||!Mt?L:{...L,gateway:Mt};Re(U)},[Re,Mt]);(0,C.useEffect)(()=>{h({class:"lifecycle",name:"checkout.mount"})},[h]);let[V,De]=(0,C.useState)(e??""),f=e??V,he=r?"":f,[ye,gt]=(0,C.useState)(!0),[x,be]=(0,C.useState)(null),[Gt,br]=(0,C.useState)(0),[Tr,xt]=(0,C.useState)("full"),[Kr,Lr]=(0,C.useState)(!1),[Sr,ir]=(0,C.useState)(re),[Nr,Yt]=(0,C.useState)(null),[Mn,Wt]=(0,C.useState)(null),[vt,_t]=(0,C.useState)(!1),[yr,jt]=(0,C.useState)(void 0),[Jt,nn]=(0,C.useState)(""),[Ur,wr]=(0,C.useState)(!1),[kr,fr]=(0,C.useState)(!1),[Zt,Ft]=(0,C.useState)(!1),pr=(0,C.useRef)(null),Rr=(0,C.useRef)(0),$t=(0,C.useRef)(void 0),[Ze,zr]=(0,C.useState)("loading"),[Gr,Ar]=(0,C.useState)(0),sr=(0,C.useRef)(!1),hn=(0,C.useRef)(!1),xn=(0,C.useRef)(!1),on=(0,C.useRef)(null),Ot=(0,C.useRef)(null),xe=(0,C.useMemo)(()=>({checkoutMode:W??Tr,layout:Xd(se,ae)}),[W,se,Tr,ae]),Y=(0,C.useRef)(P);Y.current=P;let Z=(0,C.useRef)(E);Z.current=E;let te=(0,C.useRef)(I);te.current=I;let Lt=(0,C.useCallback)(L=>ei(on,async U=>{try{return await L(U)}catch(ee){throw U.aborted?$o(ee):ee}}),[]);(0,C.useEffect)(()=>()=>{on.current?.abort(),on.current=null},[]);let Tt=(0,C.useCallback)((L,U)=>{Dt.current=L,ar(L),ut.current=U,ft(U)},[]),Bt=(0,C.useCallback)(()=>{let L=St.current;L&&(St.current=null,L.destroy())},[]);(0,C.useEffect)(()=>{Pr(it)?.setCheckoutContext(xe),M&&M!==it&&Pr(M)?.setCheckoutContext(xe)},[it,M,xe]);let Fr=(0,C.useRef)(ge);Fr.current=ge;let kt=(0,C.useCallback)(L=>{zr(L),!(L!=="exhausted"||xn.current)&&(xn.current=!0,Z.current?.(new Ke.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),oo=(0,C.useCallback)(()=>{zr("retrying"),Ar(L=>L+1)},[]);(0,C.useEffect)(()=>{zr("loading"),Ar(0),xn.current=!1},[f]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ke.SDK_VERSION,checkout_type:Ne,checkout_layout:at,billing_api_url:N})},[at,Ne,N]);let Ut=(0,C.useMemo)(()=>r?(0,mt.serializeCreateParams)(r,!0):"",[r]),Yr=(0,C.useMemo)(()=>Jt===Ut?yr:void 0,[yr,Jt,Ut]),An=(0,C.useMemo)(()=>r?Hi(r,Yr):void 0,[r,Yr]),an=W??An?.checkoutMode??"full",Qt=(0,C.useMemo)(()=>An?{...An,checkoutMode:an}:void 0,[An,an]);(0,C.useEffect)(()=>{jt(void 0),nn(Ut),$t.current=void 0,pr.current=null,Ft(!1)},[Ut]),(0,C.useEffect)(()=>{ir(re)},[re]);let Pn=(0,C.useCallback)((L,U,ee)=>{(0,tt.invokeMerchantCallback)(()=>{te.current?.(hr(L,U,ee))})},[]),$n=(0,C.useCallback)(async(L,U)=>{ir(null),Wt(null),_t(!1),Yt("processing");let ee=U?.sessionId??L.id,Ee=L.clientSecret||t,Rt=nc(L),er=Dt.current??ut.current,ze=Pr(er),le=er?null:hi(N,a,xe),j={log:qe=>{ze?ze.log(qe):le?.log(qe)},error:qe=>{ze?ze.error(qe):le?.error(qe)},terminal:qe=>{ze?ze.terminal(qe):le?.terminal(qe)},performance:qe=>{ze?ze.performance(qe):le?.performance(qe)},now:()=>ze?.now()??le?.now()??0,elapsed:qe=>ze?.elapsed(qe)??Math.max(0,(le?.now()??qe)-qe)},$=j.now(),de=!!(U?.initialAutoProcessingError||U?.initialAutoProcessingPending),g=!1,m,H=()=>{g||(g=!0,de=!0,m=j.now(),j.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),j.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ie=!1,Qe=()=>{Ie||(Ie=!0,j.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),j.performance({stage:"processing",durationMs:j.elapsed($),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),m!==void 0&&j.performance({stage:"recovery",durationMs:j.elapsed(m),durationMode:"machine",paymentMethodCategory:"saved"}))};j.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ce.current=!0;try{j.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ce.current=!1}h({class:"lifecycle",name:"payment.processing.started",provider:Rt}),de&&H();let pt;try{let qe=Ml(U?.initialAutoProcessingError),Oe=U?.initialAutoProcessingError?.type==="3ds_required"&&!U.initialAutoProcessingError.threeDSecureToken&&U.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:U.initialAutoProcessingError.nextActionRedirectUrl}:null,st,wt=Et=>(H(),Lt(A=>Ho(Et,{billingApiUrl:N,sessionId:ee,nonce:Ee,session:L,signal:A})));if(Oe)st=await wt(Oe);else if(qe)H(),qe.type==="paypal_redirect_required"&&Ot.current?.publishableKey&&tc({sessionId:ee,publishableKey:Ot.current.publishableKey,paypalPublishableKey:Ot.current.paypalPublishableKey}),st=await Lt(Et=>ri(qe,{flopay:Dt.current,paypalFlopay:ut.current,attempt3DS:U?.attempt3DS,billingApiUrl:N,sessionId:ee,session:L,telemetry:!1,signal:Et})),qe.type==="paypal_redirect_required"&&gs();else if(U?.initialAutoProcessingPending){let Et=U.initialAutoProcessingPending,A=new ro.PaymentAPI(N,{telemetry:!1}),Pe=await Lt(oe=>A.waitForCheckoutSessionCompletion(Et.sessionId,{initialDelayMs:Et.retryAfterMs,nonce:Ee,statusUrl:Et.statusUrl,signal:oe})),et=lo(Pe,L),ot=Pe.autoProcessingError?.type==="3ds_required"&&Pe.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Pe.autoProcessingError.nextActionRedirectUrl}:null;if(ot)st=await wt(ot);else{if(!Jn(et))throw No(et);st=Xn(et,ee)}}else{if(U?.initialAutoProcessingError)throw qn(U.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:U.initialAutoProcessingError.checkoutMethod});if(U?.fromCreateSession)return U?.fallbackToFull&&(xt("full"),rc("full")),!1;{let Et=await Ko({billingApiUrl:N,sessionId:ee,session:L,nonce:Ee,telemetry:!1});Et.type==="success"?st=Et.result:Et.type==="next_action_required"?st=await wt(Et):(H(),Et.type==="paypal_redirect_required"&&Ot.current?.publishableKey&&tc({sessionId:ee,publishableKey:Ot.current.publishableKey,paypalPublishableKey:Ot.current.paypalPublishableKey}),st=await Lt(A=>ri(Et,{flopay:Dt.current,paypalFlopay:ut.current,attempt3DS:U?.attempt3DS,billingApiUrl:N,sessionId:ee,session:L,telemetry:!1,signal:A})),Et.type==="paypal_redirect_required"&&gs())}}ee&&(0,In.markSessionRecentlyCompleted)(ee),Qe(),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"}),_t(st.status==="authorized"),Yt("success"),await Ta(600),pt=()=>Y.current?.(st)}catch(qe){let Oe=so(Sa(qe),ee);if(Oe.code==="three_ds_aborted")return!1;let st=Oe.checkoutMethod??ba;ir(Oe.message),Wt(Oe.message),_t(!1),U?.fallbackToFull&&(j.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),xt("full"),rc("full")),Qe();let wt=Oe.statusCode===void 0?void 0:(0,Ke.telemetryStatusClass)(Oe.statusCode,"unknown"),Et=wt==="4xx"?{requestCategory:"process_payment",statusClass:wt}:{},A=wt===void 0||wt==="4xx";if(A&&(Oe.telemetryOutcome==="payment_declined"||!!(Oe.declineCode||Oe.code?.toLowerCase().includes("declin"))))j.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Et});else if(A&&(Oe.telemetryOutcome==="validation_rejected"||Oe.type==="validation_error"))j.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Et});else{let ot=(0,Ke.classifyTelemetryFailure)(qe,de?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),oe=Oe.telemetryRequestCategory??"process_payment";ce.current=!0;try{j.error({...ot,...Oe.telemetryFailureCategory?{failureCategory:Oe.telemetryFailureCategory}:{},stage:de?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:oe})}finally{ce.current=!1}h({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:oe,provider:Rt})}return(0,tt.invokeMerchantCallback)(()=>Z.current?.(Oe)),Pn(st,Oe,{code:Oe.code,declineCode:Oe.declineCode}),Yt("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{Qe(),le&&Ma(le),Yt(null),Wt(null)}return(0,tt.invokeMerchantCallback)(pt),!0},[Pn,h,t,N,Lt,a,xe]);(0,C.useEffect)(()=>{if(typeof window>"u"||hn.current)return;let L=new URLSearchParams(window.location.search),U=L.get("payment_intent_client_secret");if(!U)return;let ee=Gd();ee&&(hn.current=!0,(async()=>{let Ee,Rt=0;ir(null),Wt(null),Yt("processing"),Lr(!0);try{if(L.get("redirect_status")==="failed")throw Object.assign(new Ke.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:er,paypalFlopay:ze}=await es({publishableKey:ee.publishableKey,paypalPublishableKey:ee.paypalPublishableKey,billingApiUrl:N,locale:l,telemetry:a});Ee=Pr(ze??er),Ee?.setCheckoutContext(xe),Rt=Ee?.now()??0,Ee?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Ee?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let le=(ze??er)?.getRawProvider();if(!le)throw Object.assign(new Ke.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:j,error:$}=await le.retrievePaymentIntent(U);if($)throw Object.assign(new Ke.FloPayError($.message??"Failed to retrieve PayPal payment status.","api_error",{code:$.code}),{checkoutMethod:"paypal"});let de=gl(j?.status);if(!j||de==="failed")throw Object.assign(new Ke.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let g=typeof j.payment_method=="string"?j.payment_method:j.payment_method?.id,m=de;if(ee.sessionId){let Qe=(await new ro.PaymentAPI(N,{telemetry:!1}).getUnifiedCheckoutSession(ee.sessionId)).data.session;if(Qe&&Qe.status!=="complete"){let pt=await Ko({billingApiUrl:N,sessionId:ee.sessionId,session:Qe,telemetry:!1,tokenizedData:{id:g??j.id,type:"card",threeDSecureActionResultTokenId:j.id,isPaypal:!0}});if(pt.type!=="success")throw Object.assign(new Ke.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});m=pt.result.status}}ee.sessionId&&(0,In.markSessionRecentlyCompleted)(ee.sessionId),Ee?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Ee?.performance({stage:"redirect_resume",durationMs:Ee.elapsed(Rt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Ee?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Yt("success"),await Ta(600),(0,tt.invokeMerchantCallback)(()=>Y.current?.({status:m,paymentIntentId:j.id,paymentMethodId:g,checkoutMethod:"paypal"}))}catch(er){let ze=so(Sa(er),ee.sessionId),le=ze.checkoutMethod??"paypal",j=!!(ze.declineCode||ze.code?.toLowerCase().includes("declin"));if(Ee)Ee.performance({stage:"redirect_resume",durationMs:Ee.elapsed(Rt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),j?Ee.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Ee.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(j){let $=hi(N,a,xe);$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ma($)}else ms(N,a,xe,"REDIRECT_RESUME_FAILED","redirect_resume");ir(ze.message),Wt(ze.message),(0,tt.invokeMerchantCallback)(()=>Z.current?.(ze)),Pn(le,ze,{code:ze.code,declineCode:ze.declineCode}),Yt("error"),await Ta(400)}finally{gs(),Yd(),Yt(null),Wt(null),Lr(!1)}})())},[Pn,l,N,a,xe]);let Fn=(0,C.useRef)(null),Br=(0,C.useMemo)(()=>Qt?(0,mt.serializeCreateParams)(Qt):"",[Qt]),ao=(0,C.useRef)(Qt);ao.current=Qt,(0,C.useEffect)(()=>{De(e??"")},[e]),(0,C.useEffect)(()=>{sr.current=!1,ir(re),Wt(null),_t(!1),Yt(null)},[Br,re,e]);async function sn(L,U,ee){let Ee=hi(N,a,xe),Rt=new ro.PaymentAPI(N,{telemetry:!1}),er=!1;try{let ze=L.idempotencyKey===void 0?void 0:(0,Ke.resolveIdempotencyKey)(L.idempotencyKey),le=(0,mt.readCachedInlineSession)(U,ee),j=(0,mt.readCachedInlineIdempotencyKey)(U,ee);le?.canonicalIdentity===ee&&j&&j.canonicalIdentity===void 0&&((0,mt.persistCachedInlineIdempotencyKey)(U,ee,j.idempotencyKey),j={...j,canonicalIdentity:ee});let $=ze??(j?.canonicalIdentity===ee?j.idempotencyKey:void 0),de,g=!1;Ee.log({name:le?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let m=le?.sid??null,H=null,Ie,Qe,pt=!1;if(m)try{H=await Rt.getUnifiedCheckoutSession(m,le?.nonce),le&&le.canonicalIdentity===void 0&&((0,mt.legacyCachedSessionMatchesDraft)(H.data.session,L)?((0,mt.persistCachedInlineSession)(U,ee,m,le.nonce??H.data.session?.clientSecret),j&&j.canonicalIdentity===void 0&&((0,mt.persistCachedInlineIdempotencyKey)(U,ee,j.idempotencyKey),$??($=j.idempotencyKey))):((0,mt.clearCachedInlineCheckout)(U,ee),j=null,$=ze,m=null,H=null));let Oe=H?.data.session?.status,st=H?.data.session,wt=st?.clientSecret||le?.nonce;if(m&&st?.buyerIdentified===!1&&wt&&(Qe=Lo(Rt,m,wt,L.account)),m&&H&&Oe==="complete"){if((0,In.wasSessionRecentlyCompleted)(m))return{sid:m,result:H};(0,mt.clearCachedInlineCheckout)(U,ee),m=null,H=null,g=!0}}catch{Ee.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),le?.canonicalIdentity===void 0?((0,mt.clearCachedInlineCheckout)(U,ee),$=ze):(0,mt.clearCachedInlineSession)(U,ee),m=null}if(!m){!ze&&(g||!$)&&($=(0,Ke.resolveIdempotencyKey)(),de=$),$&&(0,mt.persistCachedInlineIdempotencyKey)(U,ee,$);let Oe=Ee.now(),st=0;Ee.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let wt={...L,idempotencyKey:$,avsCheck:!!fe,avsConfig:typeof fe=="object"?fe:void 0,checkoutType:"embedded_checkout",checkoutLayout:hs(se,ae)};Object.defineProperty(wt,ro.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Pe=>{st=Math.max(st,Pe)}}});let Et=()=>{Ql(Ee,"session_create",Oe,st)},A=Pe=>{ec(Ee,Pe,"session_create",Oe,st)&&h({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Ke.isDetachedSessionEligible)(wt)){let Pe=await Rt.createDetachedSession(wt);Pe.claimed.catch(()=>{}),H=Pe.shell,m=Pe.sessionId,Qe=Pe.claim;let et=Ee.now();Ee.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Ie=Pe.claimed.then(ot=>{let oe=ot.data.session?.id??Pe.sessionId;return oe&&(0,mt.persistCachedInlineSession)(U,ee,oe,ot.data.session?.clientSecret??Pe.nonce),Ql(Ee,"session_claim",et),Et(),ot},ot=>{throw(0,mt.clearCachedInlineSession)(U,ee),ec(Ee,ot,"session_claim",et,0)&&h({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),ot}).finally(()=>Ma(Ee)),Ie.catch(()=>{}),er=!0,Ee.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Ee.performance({stage:"session_shell",durationMs:Ee.now()-Oe,durationMode:"machine",requestCategory:"session_create",attempt:st,statusClass:"2xx",paymentMethodCategory:"card"})}else H=await Rt.createAndFetchSession(wt),Et()}catch(Pe){throw A(Pe),Pe}m=H.data.session?.id??m??"",m&&!Ie&&(0,mt.persistCachedInlineSession)(U,ee,m,H.data.session?.clientSecret)}let qe=H?.data.session;return!Qe&&m&&qe?.buyerIdentified===!1&&qe.clientSecret&&(Qe=Lo(Rt,m,qe.clientSecret,L.account)),{sid:m??"",result:H,sdkGeneratedIdempotencyKey:de,...Ie?{claimed:Ie}:{},...Qe?{claim:Qe}:{},...pt?{claimRequiresIdentity:!0}:{}}}finally{er||Ma(Ee)}}let Hn=(0,C.useRef)(sn);Co(()=>{Hn.current=sn},[sn]);let Xr=(0,C.useCallback)(async(L,U)=>{let ee=ao.current;if(!ee)throw new Ke.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Ee=Hi(ee,L),Rt=(0,mt.serializeCreateParams)(Ee),er=(0,mt.hashCreateParams)(Ee),ze=Pi.get(Rt);if(!ze){let $={canonicalIdentity:Rt,promise:Hn.current(Ee,er,Rt),consumers:0,settled:!1};ze=$,Pi.set(Rt,$);let de=()=>{$.settled=!0,Zl(Rt,$)};$.promise.then(de,de)}ze.consumers+=1;let le=!1,j=()=>{le||(le=!0,ze.consumers-=1,Zl(Rt,ze))};U?.(j);try{let $=await ze.promise;Fn.current=Rt,L&&(nn(Ut),jt(qe=>ml(qe,L)));let{sid:de,result:g,claimed:m,claim:H,claimRequiresIdentity:Ie}=$;if($t.current=H,Ft(Ie===!0),nt(g),g.data.session&&ke(g.data.session),de&&De(de),m){Rr.current+=1;let qe=Rr.current;pr.current=m,fr(!0),m.then(Oe=>{Rr.current===qe&&(pr.current===m&&(pr.current=null),nt(Oe),Oe.data.session&&ke(Oe.data.session),fr(!1),Ft(!1))},Oe=>{Rr.current===qe&&(pr.current===m&&(pr.current=null),fr(!1),Ft(!1),be(Oe instanceof Ke.FloPayError?Oe:new Ke.FloPayError(Oe instanceof Error?Oe.message:"Failed to create session","api_error")))})}else Rr.current+=1,pr.current=null,fr(!1),Ft(!1);let{flopay:Qe,paypalFlopay:pt}=await fs(g,{billingApiUrl:N,locale:l,telemetry:a});return Tt(Qe,pt),gt(!1),$}catch($){throw Fn.current===Rt&&(Fn.current=null),$}finally{U||j()}},[Ut,Tt,l,N,a]),vn=(0,C.useRef)($n);vn.current=$n;let Bn=(0,C.useRef)(Xr);Bn.current=Xr;let zt=(0,C.useCallback)(async L=>{if(!Jd(L)||Ur)return{sessionId:V,session:z};wr(!0);try{let U=await Xr(L);return{sessionId:U.sid,session:U.result.data.session??null}}finally{wr(!1)}},[Xr,Ur,V,z]),Jr=(0,C.useCallback)(async L=>{let U=$t.current;if(!U)return;let ee=Rr.current,Ee=await U(L);Rr.current===ee&&(nt(Ee),Ee.data.session&&ke(Ee.data.session))},[]),Zr=(0,C.useCallback)(async()=>{await pr.current},[]),qr=(0,C.useCallback)(async()=>(await Zr(),{proceed:!0}),[Zr]);(0,C.useEffect)(()=>{let L=!1,U,ee=++we.current;Bt(),be(null),br(0);let Ee=()=>{L=!0,we.current===ee&&(we.current+=1,Bt())},Rt=ao.current;if(Br&&Rt)return xt(an),gt(!1),Fn.current===Br?Ee:(ke(yl(Rt,W)),(async()=>{let le=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),j=an==="auto"&&!sr.current&&!le;j&&(ir(null),Wt(null),Yt("processing"));try{let $=await Bn.current(void 0,H=>{U=H}),de=$.result.data.session??null;Ot.current=Qi($.result);let g=ys($.result),m=(0,In.wasSessionRecentlyCompleted)($.sid||de?.id);if(!L&&j&&de&&!g&&!m){sr.current=!0,await $d(Br,$.sdkGeneratedIdempotencyKey,()=>vn.current(de,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:$.result.autoProcessingError,initialAutoProcessingPending:$.result.autoProcessingPending,autoProcessingAttempted:$.result.autoProcessingAttempted,sessionId:$.sid||de.id}));return}!L&&j&&((g||m)&&(sr.current=!0),Yt(null),Wt(null))}catch($){if(L)return;let de=Ha($);if(j&&de==="session_auto_completed"){sr.current=!0,Yt("success"),await Ta(600),L||((0,tt.invokeMerchantCallback)(()=>{Y.current?.({status:"succeeded"})}),Yt(null),Wt(null));return}j&&(Yt(null),Wt(null));let g=$ instanceof Ke.FloPayError?$:new Ke.FloPayError($ instanceof Error?$.message:"Failed to create session","api_error");be(g)}finally{U?.(),U=void 0}})(),()=>{Ee(),U?.()});gt(!0);async function er(){let le=!1,j=null;try{let $=new ro.PaymentAPI(N,{telemetry:!1}),de=await $.getUnifiedCheckoutSession(f,t);if(j=de,L)return;nt(de);let g=de.data.session??null;if(ke(g),!g)throw new Ke.FloPayError("No session data returned","api_error");let m=g.checkoutMode;if(m==="setup")throw new Ke.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(g.status==="authorized"){gt(!1),(0,tt.invokeMerchantCallback)(()=>{Y.current?.(Xn(g,f)),Fr.current?.(g.successUrl??"")});return}if(g.status==="complete"){gt(!1),(0,tt.invokeMerchantCallback)(()=>{Fr.current?.(g.successUrl??"")});return}if(g.status==="expired")throw $a(g);le=!0;let H=W??m??"full";xt(H),Rr.current+=1;let Ie=g.clientSecret||t;$t.current=g.buyerIdentified===!1&&Ie?Lo($,f,Ie,{...g.customer?.id?{userId:g.customer.id}:{}}):void 0,fr(!1),Ft(!1);let Qe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),pt=ys(de);if(H==="auto"&&!sr.current&&!Qe&&!pt){sr.current=!0;let qe=ze(de);try{if(await vn.current(g,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>qe,sessionId:f||g.id}),L)return;await qe,L||gt(!1);return}catch{if(L)return;await qe,L||gt(!1);return}}await ze(de),L||gt(!1)}catch($){if(L)return;let de=pl($,le);if(le&&h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),de){let{errorCode:m,stage:H,...Ie}=de;ms(N,a,xe,m,H,Ie)}if(de?.stage==="provider_load"&&(W??j?.data.session?.checkoutMode??"full")==="full"&&ul(j,T,y)){let m=Kd({billingApiUrl:N,locale:l,telemetry:a});St.current=m,Tt(m,null),br(1),gt(!1);return}let g=$ instanceof Ke.FloPayError&&de?.stage!=="provider_load"?$:dl();g!==$&&(0,tt.invokeMerchantCallback)(()=>Z.current?.(g)),be(g),gt(!1)}}async function ze(le){let{flopay:j,paypalFlopay:$,...de}=await fs(le,{billingApiUrl:N,locale:l,telemetry:a});Ot.current={publishableKey:de.publishableKey,paypalPublishableKey:de.paypalPublishableKey},Tt(j,$),br(0)}return er(),Ee},[W,Br,an,he,t,T,y]);let Cn=(0,C.useCallback)(async()=>{if(!Me||Gt!==1)return;let L=we.current;br(2);try{let{flopay:U,paypalFlopay:ee}=await fs(Me,{billingApiUrl:N,locale:l,telemetry:a});if(we.current!==L)return;Bt(),Tt(U,ee),br(0)}catch(U){if(we.current!==L)return;let{errorCode:ee,stage:Ee,...Rt}=$i(U);ms(N,a,xe,ee,Ee,Rt)}},[Bt,Tt,l,Gt,N,a,xe,Me]),Ct=!!(f&&(z?.clientSecret||t)),Er=Kr||!Ct,lr=(0,C.useCallback)(async()=>{if(!(Kr||!Ct||!z)){Lr(!0),ir(null);try{await $n(z,{attempt3DS:!0,fallbackToFull:!0,sessionId:f||z.id})}finally{Lr(!1)}}},[f,Kr,Ct,$n,z]),jr=(0,Ke.resolveDirectPaypalConfig)(Me?.data.paypal,Q),mo=ys(Me),bn=(0,C.useMemo)(()=>{if(!(!Me||!z||!Me.data.stripe?.publishableKey))return{billingApiUrl:N}},[Me,z,N]),Kn=!!(r&&!se&&ae==="buttons"&&Le&&an==="full"),Qr=!!(f&&((0,Ke.isMountableVaultBlock)(z?.vault)||(0,kn.canRecoverHostedCardForm)(z))),Ir=(0,C.useMemo)(()=>({session:z,loading:ye,error:x,checkoutMode:Tr,inlineSessionDraft:Qt,applyInlineSessionPatch:Kn?zt:void 0,inlineSessionPatchProcessing:Ur,claimPending:kr,claimRequiresIdentity:Zt,claimBuyerIdentity:Jr,waitForDataAttachment:Zr}),[z,ye,x,Tr,Qt,Kn,zt,Ur,kr,Zt,Jr,Zr]),Dn=!!r&&ae==="buttons"&&!mo&&!Qr&&(!it||!bn),Mr=Nr?(0,F.jsx)($r,{status:Nr,errorMessage:Mn,authorized:vt}):null;if(ye&&!Qr){if(u)return(0,F.jsxs)(F.Fragment,{children:[u,Mr]});if(ae==="buttons"){let L=Ce?.buttonsLayout?.cardButton?.borderRadius??Ce?.appearance.variables?.borderRadius??8,U=ee=>(0,F.jsx)("div",{style:{height:ee,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:[T&&U(Jo),y&&(b||Te)&&U(Jo),y&&U(Jo),(0,F.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Mr]})}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); } }"})]}),Mr]})}return x?p?(0,F.jsx)(Rn.Provider,{value:Ir,children:p(x)}):(0,F.jsx)(Rn.Provider,{value:Ir,children:(0,F.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:x.message})}):Dn?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Rn.Provider,{value:Ir,children:(0,F.jsx)(Qd,{onButtonClick:Xe,showPayPal:T,showStripe:y,showApplePay:b,showGooglePay:Te,theme:me,buttonsTheme:ue,buttonsStyles:Ae,cardButtonContent:ct,cardBackButtonContent:Ge,cardTitleContent:D})}),Mr]}):mo&&z&&jr?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Rn.Provider,{value:Ir,children:(0,F.jsxs)("div",{className:Je,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Sr&&(0,F.jsx)(Wo,{icon:!1,children:Sr}),Ze==="retrying"&&(0,F.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ze==="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:oo,children:"Retry PayPal"})]}),Ze!=="exhausted"&&(0,F.jsx)("div",{"aria-hidden":Ze==="retrying"?!0:void 0,style:Ze==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,F.jsx)(El,{sessionId:f,nonce:z.clientSecret||void 0,billingApiUrl:N,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:Jr,clientId:jr.clientId,environment:jr.environment,currency:(z.currency??"usd").toUpperCase(),isSubscription:z.mode==="subscription",providerObjectType:jr.providerObjectType,approvalPresentation:jr.approvalPresentation,existingOrderId:jr.existingOrderId,onComplete:P,onErrorChange:ir,onDecline:I,onCancel:K,onButtonClick:Xe,runBeforeButtonClick:qr,onInitializationStateChange:kt,allowAutomaticRetry:Gr===0,session:z,telemetry:a,telemetryContext:xe,onInstrument:q,debug:B},`${Ue}:paypal-init-${Gr}`)})]})}),Mr]}):Tr==="confirm"?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Rn.Provider,{value:Ir,children:(0,F.jsx)(va,{flopay:it,paypalFlopay:M,options:bn??{billingApiUrl:N},onInstrument:q,children:(0,F.jsxs)("div",{className:Je,children:[Sr&&(0,F.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Sr}),Be?Be({onConfirm:lr,isProcessing:Er}):(0,F.jsx)("button",{type:"button",onClick:lr,disabled:Er,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Er?"not-allowed":"pointer",opacity:Er?.6:1},children:Kr?"Processing...":We??"Confirm Purchase"})]})},Ue)}),Mr]}):(!it||!bn)&&!(Qr&&Tr==="full")?(0,F.jsx)(F.Fragment,{children:Mr}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Rn.Provider,{value:Ir,children:(0,F.jsxs)(va,{flopay:it,paypalFlopay:M,options:bn??{billingApiUrl:N},onInstrument:q,children:[Gt===1&&(0,F.jsx)("button",{type:"button",onClick:Cn,children:"Retry payment methods"}),se?(0,F.jsxs)(F.Fragment,{children:[Sr&&(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:Sr}),(0,F.jsx)(Zd,{sessionId:f,nonce:z?.clientSecret||void 0,billingApiUrl:N,session:z,submitLabel:je,walletPresentation:v,children:se})]}):(0,F.jsx)(fi,{sessionId:f,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,Ke.buildCheckoutDisplayData)(z).total*100):0,currency:z?.currency?.toLowerCase()??"usd",onComplete:P,onError:E,onDecline:I,onCancel:K,error:Sr,onErrorChange:ir,showPayPal:T,showStripe:y,walletPresentation:v,enabledPaymentMethods:Gt?[]:pe??Me?.data.stripe?.enabledPaymentMethods??z?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Me?.data.stripe?.enabledPaymentMethodCountries,showApplePay:b,showGooglePay:Te,layout:ae,theme:me,buttonsTheme:ue,buttonsStyles:Ae,appearance:dt,cardButtonContent:ct,cardBackButtonContent:Ge,cardTitleContent:D,onButtonClick:Xe,onBeforeButtonClick:Le,onBuyerIdentityReady:Jr,enableAVS:fe,...J?{cardFieldOrder:J}:{},...G?{cardPreFormSlot:G}:{},avsLayout:Fe,country:z?.customer?.country,city:z?.customer?.city,state:z?.customer?.state,onCountryChange:_,onZipChange:X,avsCheck:!!fe,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:hs(se,ae),className:Je,submitLabel:je,directPaypal:jr,isSubscription:z?.mode==="subscription",session:z,dataAttachmentPending:kr,dataAttachmentRequiresIdentity:Zt,debug:B})]},Ue)}),Mr]})}function Zd({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:i,children:l}){return(0,F.jsx)(F.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 Qd({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:i,buttonsTheme:l,buttonsStyles:u,cardButtonContent:p,cardBackButtonContent:P,cardTitleContent:E}){let[S,I]=(0,C.useState)(!1),K=(0,C.useMemo)(()=>(0,Ke.resolveTheme)(i),[i]),_=(0,C.useMemo)(()=>{let v=K?.buttonsLayout??(0,Ke.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,T=v=>(0,F.jsx)("div",{style:{height:v,borderRadius:X,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),y=p===void 0?{boxSizing:"border-box",height:Jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(S){let v=_.cardInputBorder??"#e5e7eb",pe=_.cardInputBackground??"white",b=Bo(P),Te=Bo(E);return(0,F.jsxs)("div",{style:{backgroundColor:_.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",..._.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:()=>I(!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",..._.backButton},children:[(0,F.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",..._.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:P})]}),Te?(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,..._.title},children:(0,F.jsx)(ua,{content:E})})]}),(0,F.jsx)("div",{style:{backgroundColor:pe,border:`1px solid ${v}`,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 ${v}`,borderLeft:`1px solid ${v}`,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 ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,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 ${v}`,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",..._.submitButton,opacity:.5}}),(0,F.jsx)("style",{children:`
|
|
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||!en?(0,d.jsx)("pre",{"data-testid":s,style:ja,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":s,style:ja,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${b}`,` currency=${lr}`,` amountInCents=${Qo}`,` enabledPaymentMethods: ${JSON.stringify(T??[])}`,` enabledPaymentMethodsProvided=${ea}`,` hasEnabledMethods=${Fa}`,` expressMethods: ${JSON.stringify(Da)}`,` walletExpressMethods: ${JSON.stringify(To)}`,` paymentElementMethods: ${JSON.stringify(xi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Oa)}`,` hasStripeInstance=${!!en}`,` 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=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:`
|
|
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,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&T(Jo),r&&(n||a)&&T(Jo),r&&(0,F.jsx)("button",{type:"button",onClick:()=>{e?.("card"),I(!0)},style:{width:"100%",...y,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:_.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,..._.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:(0,F.jsx)(Do,{content:p})}),(0,F.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var fn=require("react/jsx-runtime"),eu=44;function oc(e){return new Promise(t=>setTimeout(t,e))}function tu(e,t){return e instanceof gn.FloPayError?e:new gn.FloPayError(e instanceof Error?e.message:t,"api_error")}function ru(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function nu(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:E,cancelUrl:S,couponCodes:I,tagsData:K,utmMetadata:_,billingApiUrl:X,locale:T,theme:y,appearance:v,buttonsTheme:pe,buttonsStyles:b,onSuccess:Te,onError:B,onDecline:ae,children:me,disabled:ue=!1,type:Ae="button",style:ct,...Ge}){let D=(0,yt.useMemo)(()=>(0,gn.resolveBillingApiUrl)(X),[X]),bt=(0,yt.useMemo)(()=>nu({createSession:r,clientId:i,products:l,items:u,subscriptions:p,account:P,successUrl:E,cancelUrl:S,couponCodes:I,tagsData:K,utmMetadata:_}),[P,S,i,I,r,l,u,p,E,K,_]),[Xe,Le]=(0,yt.useState)(!1),[fe,J]=(0,yt.useState)(null),[G,Fe]=(0,yt.useState)(null),[je,Je]=(0,yt.useState)(!1),[re,Q]=(0,yt.useState)(null),[se,W]=(0,yt.useState)(null),We=(0,yt.useRef)(!0),Be=(0,yt.useRef)(null),ge=(0,yt.useRef)(se),N=(0,yt.useRef)(Te),Ce=(0,yt.useRef)(B),dt=(0,yt.useRef)(ae),Ne=(0,yt.useCallback)(w=>ei(Be,async O=>{try{return await w(O)}catch($e){throw O.aborted?$o($e):$e}}),[]);(0,yt.useEffect)(()=>{ge.current=se},[se]),(0,yt.useEffect)(()=>{N.current=Te},[Te]),(0,yt.useEffect)(()=>{Ce.current=B},[B]),(0,yt.useEffect)(()=>{dt.current=ae},[ae]),(0,yt.useEffect)(()=>(We.current=!0,()=>{We.current=!1,Be.current?.abort()}),[]),(0,yt.useEffect)(()=>{if(typeof window>"u")return;let w=O=>{O.key==="Escape"&&W(null)};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[]);let at=(0,yt.useCallback)((w,O=ba)=>{dt.current?.(hr(O,w,{code:w.code,declineCode:w.declineCode}))},[]),Me=(0,yt.useCallback)(async w=>{We.current&&(Fe(null),Je(w.result.status==="authorized"),J("success"),await oc(600),We.current&&(0,tt.invokeMerchantCallback)(()=>N.current?.(w)))},[]),nt=(0,yt.useCallback)(async(w,O)=>{We.current&&(Ce.current?.(w),O?.emitDecline&&at(w,O.method),Fe(w.message),Je(!1),J("error"),await oc(400))},[at]),it=(0,yt.useCallback)(async(w,O,$e)=>{let Re=w.data.session??null;if(!Re)throw so(new gn.FloPayError("No session data returned","api_error"),O);let h=Re.clientSecret||t;if(Jn(Re)){await Me({result:Xn(Re,O),session:Re,sessionId:Re.id||O,autoCompleted:!1});return}if(Re.status==="expired")throw so($a(Re),Re.id||O);try{if(w.autoProcessingPending){let q=w.autoProcessingPending,V=new Ci.PaymentAPI(D),De=await Ne(ye=>V.waitForCheckoutSessionCompletion(q.sessionId,{initialDelayMs:q.retryAfterMs,nonce:h,statusUrl:q.statusUrl,signal:ye})),f=lo(De,Re),he=De.autoProcessingError?.type==="3ds_required"&&De.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:De.autoProcessingError.nextActionRedirectUrl}:null;if(he&&O&&h){let ye=await Ne(gt=>Ho(he,{billingApiUrl:D,sessionId:O,nonce:h,session:Re,signal:gt,telemetry:!0}));await Me({result:ye,session:Re,sessionId:Re.id||O,autoCompleted:!1});return}if(De.autoProcessingError)throw qn(De.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:De.autoProcessingError.checkoutMethod});if(!Jn(f))throw No(f);await Me({result:Xn(f,O),session:f,sessionId:f.id||O,autoCompleted:!1});return}if(w.autoProcessingError){let q=w.autoProcessingError.nextActionRedirectUrl;if(w.autoProcessingError.type==="3ds_required"&&q&&O&&h){let V=await Ne(ye=>xl({billingApiUrl:D,sessionId:O,nonce:h,nextActionRedirectUrl:q,signal:ye}));if(V.status==="declined")throw qn({type:V.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:V.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:w.autoProcessingError.checkoutMethod});let f=await new Ci.PaymentAPI(D).waitForCheckoutSessionCompletion(O,{initialDelayMs:0,nonce:h}),he=lo(f,Re);if(!Jn(he))throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:w.autoProcessingError.checkoutMethod});await Me({result:Xn(he,O),session:he,sessionId:he.id||O,autoCompleted:!1});return}throw qn(w.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:w.autoProcessingError.checkoutMethod})}if($e?.fromCreateSession&&w.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ce=await Ko({billingApiUrl:D,sessionId:O??Re.id,session:Re,nonce:h});if(ce.type==="next_action_required"&&h){let q=O??Re.id,V=await Ne(De=>Ho(ce,{billingApiUrl:D,sessionId:q,nonce:h,session:Re,signal:De,telemetry:!0}));await Me({result:V,session:Re,sessionId:Re.id||q,autoCompleted:!1});return}if(ce.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Me({result:ce.result,session:Re,sessionId:Re.id||O,autoCompleted:!1})}catch(ce){let q=Re.id||O,V=so(Sa(ce),q);if(V.code==="three_ds_aborted")return;if(V.code==="checkout_processing_timeout"){if(!We.current)return;Q(V.message),(0,tt.invokeMerchantCallback)(()=>Ce.current?.(V));return}await nt(V,{emitDecline:!0,method:V.checkoutMethod??ba}),ru(V,q)&&q&&We.current&&W({sessionId:q,errorMessage:V.message,nonce:h||void 0,payPalOrderId:V.orderId})}},[t,D,Ne,nt,Me]),ar=(0,yt.useCallback)(async w=>{if(Ge.onClick?.(w),!(w.defaultPrevented||ue||Xe)){if(W(null),Q(null),e&&bt){let O=new gn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await nt(O),We.current&&(J(null),Fe(null));return}if(!e&&!bt){let O=new gn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await nt(O),We.current&&(J(null),Fe(null));return}Le(!0),Fe(null),Je(!1),J("processing");try{let O=new Ci.PaymentAPI(D);if(e){let $e=await O.getUnifiedCheckoutSession(e,t);await it($e,e);return}try{let $e=await O.createAndFetchSession({...bt});await it($e,$e.data.session?.id??null,{fromCreateSession:!0})}catch($e){if(Ha($e)==="session_auto_completed"){await Me({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw $e}}catch(O){await nt(so(tu(O,"Automatic payment failed. Please try again."),e))}finally{We.current&&(J(null),Fe(null),Le(!1))}}},[Ge.onClick,bt,ue,Xe,t,it,D,e,nt,Me]),Dt=(0,yt.useCallback)(w=>{let O=ge.current;W(null),N.current?.({result:w,session:null,sessionId:O?.sessionId??null,autoCompleted:!1})},[]),St=(0,yt.useCallback)(w=>{Ce.current?.(w)},[]),we=(0,yt.useCallback)(w=>{dt.current?.(w)},[]),M=(0,yt.useMemo)(()=>(0,gn.resolveTheme)(y),[y]),ft=(0,yt.useMemo)(()=>{let w=M?.buttonsLayout??(0,gn.resolveButtonsLayoutTheme)(pe);return b?{...w,...b,cardButton:{...w.cardButton,...b.cardButton}}:w},[M,pe,b]),ut=(0,yt.useMemo)(()=>{let w=M?.appearance;return v?w?{...w,...v,variables:{...w.variables,...v.variables}}:v:w},[v,M]),z=ut?.variables,ke=z?.colorPrimary??"#4A49FF",Nt=z?.colorPrimaryHover??(0,ps.darkenHex)(ke,.12),Ue=z?.borderRadius??"8px";return(0,fn.jsxs)(fn.Fragment,{children:[(0,fn.jsx)("button",{...Ge,type:Ae,onClick:ar,disabled:ue||Xe,"aria-busy":Xe,style:{width:"100%",...me===void 0?{boxSizing:"border-box",height:eu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...ft.cardButton,...us({themeBundle:M,resolvedPrimaryColor:ke,resolvedBorderRadius:Ue,submitButtonStyle:ft.submitButton,explicitPrimaryColor:z?.colorPrimary}),fontSize:ft.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ue||Xe?"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||Xe?.6:1,...ct},onMouseEnter:w=>{Ge.onMouseEnter?.(w),!w.defaultPrevented&&!ue&&!Xe&&(M||z?.colorPrimary)&&(w.currentTarget.style.backgroundColor=Nt)},onMouseLeave:w=>{Ge.onMouseLeave?.(w),!w.defaultPrevented&&(M||z?.colorPrimary)&&(w.currentTarget.style.backgroundColor=ke)},onMouseDown:w=>{Ge.onMouseDown?.(w),w.defaultPrevented||(w.currentTarget.style.transform="scale(0.985)")},onMouseUp:w=>{Ge.onMouseUp?.(w),w.defaultPrevented||(w.currentTarget.style.transform="scale(1)")},children:(0,fn.jsx)(Do,{content:me})}),re&&(0,fn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:re}),fe&&(0,fn.jsx)($r,{status:fe,errorMessage:G,authorized:je}),se&&(0,fn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:w=>{w.target===w.currentTarget&&W(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,fn.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,fn.jsx)(vi,{sessionId:se.sessionId,nonce:se.nonce,checkoutMode:"full",billingApiUrl:D,locale:T,theme:y,...ut?{appearance:ut}:{},buttonsTheme:pe,buttonsStyles:b,initialErrorMessage:se.errorMessage,initialPayPalOrderId:se.payPalOrderId,cardTitleContent:null,onComplete:Dt,onError:St,onDecline:we})})})]})}var Si=require("@flopay/js/card-setup"),Dr=require("@flopay/shared"),Vt=require("react");var Cs=require("@flopay/shared"),ou=require("@flopay/shared");function bi(e){let t=(0,Cs.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Vn=require("react/jsx-runtime"),xa=class extends Dr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function no(e,t={}){let r=e instanceof Dr.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:E,onDecline:S,onCancel:I,onValidation:K,onError:_}){let[X,T]=(0,Vt.useState)(null),[y,v]=(0,Vt.useState)(null),[pe,b]=(0,Vt.useState)(null),[Te,B]=(0,Vt.useState)(null),[ae,me]=(0,Vt.useState)(null),ue=(0,Vt.useRef)(!1),Ae=(0,Vt.useRef)(!1),{vaultTheme:ct,surface:Ge,overlayTheme:D}=(0,Vt.useMemo)(()=>bi({theme:a,appearance:l,buttonsStyles:u}),[a,l,u]),bt=(0,Vt.useMemo)(()=>(0,Ra.mergeCardSetupSurface)(Ge,i),[Ge,i]),Xe=(0,Vt.useRef)(P),Le=(0,Vt.useRef)(_),fe=(0,Vt.useRef)(E),J=(0,Vt.useRef)(S),G=(0,Vt.useRef)(I),Fe=(0,Vt.useRef)(K),je=(0,Vt.useRef)(!1),Je=(0,Vt.useRef)(!1),re=(0,Vt.useRef)(0);return Xe.current=P,Le.current=_,fe.current=E,J.current=S,G.current=I,Fe.current=K,(0,Vt.useEffect)(()=>{let Q=re.current+1;return re.current=Q,()=>{queueMicrotask(()=>{re.current===Q&&(je.current||Je.current||(Je.current=!0,(0,tt.invokeMerchantCallback)(()=>{G.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Vt.useEffect)(()=>{let Q=!0,se=(0,Dr.resolveBillingApiUrl)(r),W=new Si.PaymentAPI(se,{telemetry:n});return T(null),v(null),b(null),je.current=!1,Je.current=!1,(async()=>{try{if(!e.trim())throw new Dr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Dr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let We=await W.getUnifiedCheckoutSession(e,t);if(!Q)return;let Be=We.data.session;if(!Be||!(0,Dr.isCardSetupCheckoutSession)(Be))throw new Dr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let ge=Be.vault;(0,Dr.isMountableVaultBlock)(ge)||(ge=await W.getVaultCapture(e,t));let N=(0,Dr.resolveVaultMountOptions)(ge,{billingApiUrl:se,sessionId:e,nonce:t});if(!N)throw new Dr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!Q)return;v(N),T(new Si.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(We){if(!Q)return;let Be=no(We);je.current=!0,b(Be),(0,tt.invokeMerchantCallback)(()=>Le.current?.(Be))}})(),()=>{Q=!1,W.destroy()}},[r,t,e,n]),(0,Vt.useEffect)(()=>{if(!X)return;let Q=!1;Ae.current=!1,ue.current=!1;let se=X.on("submitting",()=>{ue.current=!0,me(null),B("processing")}),W=X.on("complete",ge=>{je.current=!0,ue.current=!1,B("success"),(async()=>(await new Promise(N=>setTimeout(N,600)),!Ae.current&&(Ae.current=!0,(0,tt.invokeMerchantCallback)(()=>{fe.current?.({status:"succeeded",sessionId:e,...ge.paymentMethod?{paymentMethod:ge.paymentMethod}:{}})}),Q||B(null))))()}),We=X.on("decline",ge=>{je.current=!0,ue.current=!1,me(ge.message??null),B("error"),(0,tt.invokeMerchantCallback)(()=>{J.current?.({status:"declined",sessionId:e,...ge.declineReason?{reason:ge.declineReason}:{},...ge.message?{message:ge.message}:{}})}),(async()=>(await new Promise(N=>setTimeout(N,400)),Q||B(null)))()}),Be=X.on("challenge_dismissed",()=>{B(null)});return()=>{Q=!0,se(),W(),We(),Be()}},[X,e]),pe?(0,Vn.jsx)("div",{role:"alert",children:pe.message}):!X||!y?.html?(0,Vn.jsx)(Vn.Fragment,{children:p}):(0,Vn.jsxs)(Vn.Fragment,{children:[Te&&(0,Vn.jsx)($r,{status:Te,errorMessage:ae,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...D?{theme:D}:{}}),(0,Vn.jsx)(co,{capture:X,html:y.html,messageToken:y.messageToken,expectedOrigin:y.expectedOrigin,verificationRequired:y.verificationRequired,theme:ct,containerStyle:bt,onReady:()=>{(0,tt.invokeMerchantCallback)(()=>Xe.current?.())},onValidation:Q=>{(0,tt.invokeMerchantCallback)(()=>Fe.current?.(Q))},onError:Q=>{if(!Q)return;ue.current&&(ue.current=!1,me(Q),B("error"),setTimeout(()=>B(null),400));let se=no(new Error(Q),{code:"card_setup_widget_failed",retryable:!0});(0,tt.invokeMerchantCallback)(()=>Le.current?.(se))}})]})}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:E,onFailed:S,onAbandoned:I}){let K=(0,wo.useRef)(null),_=(0,wo.useRef)({onSubmitting:P,onConfirmed:E,onFailed:S,onAbandoned:I});_.current={onSubmitting:P,onConfirmed:E,onFailed:S,onAbandoned:I};let[X]=(0,wo.useState)(()=>(0,Un.detectPayPalEnvironment)().inAppBrowser);return(0,wo.useEffect)(()=>{let T=!0,y,v=new sc.PaymentAPI(i,{telemetry:l}),pe={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(!T||!Te)return;if(!b?.Buttons)throw new uo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let B=b.Buttons({createVaultSetupToken:async()=>{_.current.onSubmitting();let ae=await v.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(ae.provider!=="paypal"||ae.providerObjectType!=="setup_token")throw new uo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ae.providerObjectId},onApprove:async ae=>{let me=ae.vaultSetupToken;if(!me)throw new uo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let ue=await v.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});T&&_.current.onConfirmed()},onCancel:()=>{T&&_.current.onAbandoned()},onError:ae=>{if(!T)return;let{popupBlocked:me}=(0,Se.classifyExternalMethodFailure)(ae,{inAppBrowser:X,handoffObserved:!1});_.current.onFailed(me?new Error((0,Se.buildExternalMethodRecoveryMessage)("PayPal",!0,X)):ae,{code:me?"popup_blocked":"paypal_setup_failed",retryable:!0})}});y=()=>B.close(),await B.render(Te)}catch(b){if(!T)return;_.current.onFailed(b,{code:"paypal_unavailable",retryable:!0})}})(),()=>{T=!1,y?.().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"),Wn=require("@stripe/react-stripe-js"),mc=require("@stripe/stripe-js"),Or=require("react");var xr=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"}},bs=new Map;function au(e){let t=bs.get(e);if(t)return t;let r=(0,mc.loadStripe)(e).catch(n=>{throw bs.delete(e),n});return bs.set(e,r),r}function iu(e){return e?(0,po.toStripeAppearance)(e):void 0}function su(e){return(0,Se.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 lu(){return typeof window>"u"?"":window.location.href}var cu={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,Or.useState)(()=>au(t)),p=(0,Or.useMemo)(()=>{let P=iu(l),E=(0,po.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:i},r,"setup");return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:yc[r]?.types??[r],...E?{setupFutureUsage:E}:{},...P?{appearance:P}:{}}},[l,n,a,i,r]);return(0,xr.jsx)(Wn.Elements,{stripe:u,options:p,children:(0,xr.jsx)(du,{...e})})}function du({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,appearance:l,themeId:u,buttonsLayout:p,onSubmitting:P,onConfirmed:E,onDeclined:S,onFailed:I,onValidation:K,onUnavailable:_}){let X=(0,Wn.useStripe)(),T=(0,Wn.useElements)(),[y,v]=(0,Or.useState)(!1),[pe,b]=(0,Or.useState)("loading"),[Te,B]=(0,Or.useState)(!1),[ae,me]=(0,Or.useState)(!1),ue=(0,Or.useRef)(!1),[Ae]=(0,Or.useState)(()=>(0,Un.detectPayPalEnvironment)()),[ct,Ge]=(0,Or.useState)(!1),D=(0,Or.useCallback)((G,Fe)=>{if((0,Se.classifyExternalMethodFailure)(G,{inAppBrowser:Ae.inAppBrowser,handoffObserved:!1}).popupBlocked){Ge(!0),I(new Error((0,Se.buildExternalMethodRecoveryMessage)(uc(e),!0,Ae.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}I(Fe.message===void 0?G:new Error(Fe.message),{code:Fe.code,retryable:!0})},[Ae.inAppBrowser,e,I]),bt=(0,Or.useCallback)(async()=>{if(!(!X||!T||ue.current)){ue.current=!0,v(!0);try{let G=await T.submit();if(G.error){K(G.error.message??null);return}P();let Fe=await new pc.PaymentAPI(a,{telemetry:i}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(Fe.provider!=="stripe"||Fe.intentKind!=="setup")throw new po.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let je=await X.confirmSetup({elements:T,clientSecret:Fe.clientSecret,confirmParams:{return_url:lu()},redirect:"if_required"});if(je.error){su(je.error)?S({...je.error.decline_code||je.error.code?{reason:je.error.decline_code??je.error.code}:{},...je.error.message?{message:je.error.message}:{}}):D(je.error,{code:"payment_method_setup_provider_failed",message:je.error.message??"The payment method could not be saved."});return}E()}catch(G){D(G,{code:"payment_method_setup_failed"})}finally{ue.current=!1,v(!1)}}},[a,t,T,e,n,E,S,P,K,D,r,X,i]),Xe=yc[e]?.wallet,Le=Xe==="paypal"&&(0,zn.resolveStripePayPalPresentation)(Ae,"auto",ct?"blocked":Ae.popupCapability)==="redirect",fe=l?.variables?.borderRadius??p?.cardButton?.borderRadius??8;if(t==="wallet"&&Xe&&!Le)return(0,xr.jsxs)(xr.Fragment,{children:[(0,xr.jsx)(Xo,{}),(0,xr.jsx)(ka,{state:pe,borderRadius:fe,children:(0,xr.jsx)(Wn.ExpressCheckoutElement,{options:{...ii,paymentMethods:ai([e])},onReady:G=>{let Fe=wa(G,[Xe]);b(Fe),Fe==="unavailable"&&_()},onLoadError:()=>{b("load_error"),_()},onConfirm:()=>{bt()}})})]});let J=uc(e);return(0,xr.jsxs)(xr.Fragment,{children:[Te?(0,xr.jsx)(oi,{method:e,themeId:u,hasNextStep:!0,highlighted:ae,disabled:y,onClick:()=>me(G=>!G),backgroundColor:p?.cardButton?.backgroundColor,borderColor:p?.cardInputBorder,textColor:p?.cardButton?.color,borderRadius:fe}):null,(0,xr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ae,style:ae?{display:"flex",flexDirection:"column"}:cu,children:[(0,xr.jsx)(Wn.PaymentElement,{options:{layout:si},onReady:()=>B(!0),onLoadError:()=>_(),onChange:G=>{G.complete&&K(null)}}),(0,xr.jsx)(li,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!X||!T||y||!ae,onClick:()=>{bt()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:p?.submitButton,children:y?"Saving\u2026":`Save ${J}`})]})]})}var Aa=require("@flopay/js/card-setup"),mr=require("@flopay/shared"),Ye=Wi(require("react"),1);var Zo=require("@flopay/js/card-setup"),Cr=require("@flopay/shared");var or=require("react/jsx-runtime"),uu=15,pu=2e3;function mu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Ss(e){return new Promise(t=>setTimeout(t,e))}async function yu(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 fu(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 Ye.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:E=null,onReady:S,onComplete:I,onDecline:K,onCancel:_,onValidation:X,onError:T}){let[y]=(0,Ye.useState)(Zo.readSetupRedirectReturn),[v,pe]=(0,Ye.useState)(null),[b,Te]=(0,Ye.useState)(!1),[B,ae]=(0,Ye.useState)(null),[me,ue]=(0,Ye.useState)(null),[Ae,ct]=(0,Ye.useState)(null),[Ge,D]=(0,Ye.useState)(null),[bt,Xe]=(0,Ye.useState)(()=>new Set),Le=(0,Ye.useRef)(bt),fe=(0,Ye.useRef)(null);fe.current=v;let J=(0,Ye.useRef)(!1),G=(0,Ye.useRef)(!1),Fe=(0,Ye.useRef)(!1),je=(0,Ye.useRef)(!1),Je=(0,Ye.useRef)(0),re=(0,Ye.useRef)(0),Q=(0,Ye.useRef)(!1),{vaultTheme:se,surface:W,overlayTheme:We,appearance:Be,buttonsLayout:ge}=(0,Ye.useMemo)(()=>bi({theme:l,appearance:p,buttonsStyles:P}),[l,p,P]),N=(0,Ye.useMemo)(()=>(0,Ra.mergeCardSetupSurface)(W,u),[W,u]),Ce=(0,Ye.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,onReady:S,onComplete:I,onDecline:K,onCancel:_,onValidation:X,onError:T});Ce.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,onReady:S,onComplete:I,onDecline:K,onCancel:_,onValidation:X,onError:T},(0,Ye.useEffect)(()=>{Q.current=!0;let f=Je.current+1;return Je.current=f,()=>{Q.current=!1,re.current+=1,queueMicrotask(()=>{Je.current===f&&(Fe.current||je.current||(je.current=!0,(0,tt.invokeMerchantCallback)(()=>{Ce.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let dt=(0,Ye.useCallback)((f,he)=>{Fe.current=!0,J.current=!1,D({status:"success",wording:f,message:null}),(async()=>(await Ss(600),!G.current&&(G.current=!0,(0,tt.invokeMerchantCallback)(()=>{Ce.current.onComplete?.({status:"succeeded",sessionId:Ce.current.sessionId,...he?{paymentMethod:he}:{}})}),Q.current&&D(null))))()},[]),Ne=(0,Ye.useCallback)((f,he)=>{Fe.current=!0,J.current=!1,D({status:"error",wording:f,message:he.message??null}),(0,tt.invokeMerchantCallback)(()=>{Ce.current.onDecline?.({status:"declined",sessionId:Ce.current.sessionId,...he.reason?{reason:he.reason}:{},...he.message?{message:he.message}:{}})}),(async()=>(await Ss(400),Q.current&&D(null)))()},[]),at=(0,Ye.useCallback)((f,he)=>{J.current?(J.current=!1,D({status:"error",wording:f,message:he.message}),setTimeout(()=>{Q.current&&D(null)},400)):D(null),(0,tt.invokeMerchantCallback)(()=>Ce.current.onError?.(he))},[]),Me=(0,Ye.useCallback)(async f=>{let he=re.current+1;re.current=he;let ye=()=>!Q.current||he!==re.current;J.current=!0,D({status:"processing",wording:"payment_method",message:null});let gt=new Aa.PaymentAPI((0,mr.resolveBillingApiUrl)(Ce.current.billingApiUrl),{telemetry:Ce.current.telemetry});try{for(let x=0;x<uu;x+=1){if((x>0||f.waitFirst)&&await Ss(pu),ye())return;let be=await gt.getUnifiedCheckoutSession(Ce.current.sessionId,Ce.current.nonce);if(ye())return;let Gt=be.data.session?.status;if(Gt==="complete"){Te(!0),dt("payment_method");return}if(Gt==="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(x){if(ye())return;let be=x instanceof mr.FloPayError&&x.code==="payment_method_setup_unverified";at("payment_method",no(x,be?{retryable:!0}:{}))}finally{gt.destroy()}},[at,dt]);(0,Ye.useEffect)(()=>{let f=!0,he=(0,mr.resolveBillingApiUrl)(a),ye=new Aa.PaymentAPI(he,{telemetry:i});pe(null),Te(!1),ae(null),ue(null),ct(null);let gt=new Set;return Le.current=gt,Xe(gt),Fe.current=!1,je.current=!1,G.current=!1,(async()=>{try{let{session:x,advertisement:be}=await yu(ye,r,n);if(!f)return;let Gt={advertisement:be,customer:mu(x),...x.futureUse?{futureUse:x.futureUse}:{},...x.futureUseUnsupported?{futureUseUnsupported:x.futureUseUnsupported}:{}};if(y){if((0,Zo.clearSetupRedirectParams)(),x.status==="complete"){Te(!0),pe(Gt),dt("payment_method");return}y.failed?Ne("payment_method",{reason:"redirect_failed"}):Me({waitFirst:!0})}let br=be.card?await fu(ye,x,r,n,he):null;if(!f)return;pe(Gt),br&&(ue(br),ae(new Aa.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:i})))}catch(x){if(!f)return;let be=no(x);Fe.current=!0,ct(be),(0,tt.invokeMerchantCallback)(()=>Ce.current.onError?.(be))}})(),()=>{f=!1,ye.destroy()}},[a,n,y,Ne,dt,r,i,Me]),(0,Ye.useEffect)(()=>{if(!B)return;J.current=!1;let f=B.on("submitting",()=>{J.current=!0,D({status:"processing",wording:"card",message:null})}),he=B.on("complete",x=>{dt("card",x.paymentMethod)}),ye=B.on("decline",x=>{Ne("card",{...x.declineReason?{reason:x.declineReason}:{},...x.message?{message:x.message}:{}})}),gt=B.on("challenge_dismissed",()=>{D(null)});return()=>{f(),he(),ye(),gt()}},[B,Ne,dt]);let nt=(0,Ye.useCallback)((f,he,ye)=>{if(ye.retryable){at("payment_method",no(he,ye));return}if(Le.current.has(f))return;let gt=new Set(Le.current);gt.add(f),Le.current=gt,Xe(gt);let x=fe.current?.advertisement,be=x?(0,Cr.advertisedMethodKeys)(x).some(Gt=>!gt.has(Gt)):!1;at("payment_method",no(he,{code:ye.code,retryable:be}))},[at]),it=(0,Ye.useMemo)(()=>({onSubmitting:()=>{J.current=!0,D({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Me({waitFirst:!1})},onDeclined:f=>Ne("payment_method",f),onValidation:f=>{(0,tt.invokeMerchantCallback)(()=>Ce.current.onValidation?.(f))},onAbandoned:()=>{J.current=!1,D(null)}}),[Ne,Me]),ar=(0,Ye.useRef)(nt);ar.current=nt;let Dt=(0,Ye.useRef)(new Map),St=f=>{let he=Dt.current.get(f);if(he)return he;let ye=(gt,x)=>ar.current(f,gt,x);return Dt.current.set(f,ye),ye},we=(0,Ye.useCallback)(f=>{if(Le.current.has(f))return;let he=new Set(Le.current);he.add(f),Le.current=he,Xe(he);let ye=fe.current?.advertisement;ye&&(0,Cr.advertisedMethodKeys)(ye).some(x=>!he.has(x))||at("payment_method",no(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[at]),M=(0,Ye.useRef)(we);M.current=we;let ft=(0,Ye.useRef)(new Map),ut=f=>{let he=ft.current.get(f);if(he)return he;let ye=()=>M.current(f);return ft.current.set(f,ye),ye},z=Ge?(0,or.jsx)($r,{status:Ge.status,errorMessage:Ge.message,...(0,Cr.setupOverlayLabels)(Ge.wording),successNote:null,...We?{theme:We}:{}}):null;if(Ae)return(0,or.jsx)("div",{role:"alert",children:Ae.message});if(!v||b)return(0,or.jsxs)(or.Fragment,{children:[z,v?null:E]});let{advertisement:ke,customer:Nt,futureUse:Ue,futureUseUnsupported:Mt}=v,w=(0,mr.resolveBillingApiUrl)(a),O=i===void 0?{}:{telemetry:i},$e=ke.stripe.filter(({method:f})=>!bt.has(f)),Re=bt.has("paypal")?null:ke.paypal,h=!!(ke.card&&B&&me?.html),ce=({method:f,publishableKey:he,currency:ye})=>(0,or.jsx)("div",{"data-flopay-payment-method":f,style:{display:"contents"},children:(0,or.jsx)(wi,{onFailed:St(f),children:(0,or.jsx)(Ye.Suspense,{fallback:null,children:(0,or.jsx)(e,{method:f,category:(0,Cr.stripeMethodCategory)(f),publishableKey:he,currency:ye,...Ue?{futureUse:Ue}:{},...Mt?{futureUseUnsupported:Mt}:{},sessionId:r,nonce:n,billingApiUrl:w,...O,...Be?{appearance:Be}:{},...ge?{buttonsLayout:ge}:{},...typeof l=="string"?{themeId:l}:{},...it,onFailed:St(f),onUnavailable:ut(f)})})})},f),q=$e.filter(({method:f})=>(0,Cr.stripeMethodCategory)(f)==="wallet"),V=$e.filter(({method:f})=>(0,Cr.stripeMethodCategory)(f)!=="wallet"),De=$e.length>0||Re!==null;return(0,or.jsxs)(or.Fragment,{children:[z,De?(0,or.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[q.map(ce),Re?(0,or.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,or.jsx)(wi,{onFailed:St("paypal"),children:(0,or.jsx)(Ye.Suspense,{fallback:null,children:(0,or.jsx)(t,{clientId:Re.clientId,...Re.environment?{environment:Re.environment}:{},...ke.currency?{currency:ke.currency}:{},sessionId:r,nonce:n,billingApiUrl:w,customer:Nt,...O,...it,onFailed:St("paypal"),onUnavailable:ut("paypal")})})})}):null,V.map(ce)]}):null,h&&De?(0,or.jsx)(ci,{label:"or add a card"}):null,h&&B&&me?.html?(0,or.jsx)("div",{"data-flopay-payment-method":"card",children:(0,or.jsx)(co,{capture:B,html:me.html,messageToken:me.messageToken,expectedOrigin:me.expectedOrigin,verificationRequired:me.verificationRequired,theme:se,containerStyle:N,onReady:()=>{(0,tt.invokeMerchantCallback)(()=>Ce.current.onReady?.())},onValidation:f=>{(0,tt.invokeMerchantCallback)(()=>Ce.current.onValidation?.(f))},onError:f=>{f&&at("card",no(new Error(f),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Pc=require("react/jsx-runtime"),gu={StripeSetupMethod:fc,PayPalSetupMethod:cc};function hc(e){return(0,Pc.jsx)(gc,{...e,branches:gu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
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});
|