@flopay/react 1.14.8 → 1.14.9
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 +4 -2
- package/dist/checkout-utils.d.ts +12 -3
- package/dist/chunk-BU7THP6H.mjs +1 -0
- package/dist/{chunk-JCJFICSM.mjs → chunk-FGCZOMML.mjs} +2 -2
- 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-paypal-CLV7JDJH.mjs +1 -0
- package/dist/payment-method-setup-stripe-526L4P5X.mjs +1 -0
- package/package.json +5 -5
- package/dist/chunk-HSYSKQPT.mjs +0 -1
- package/dist/payment-method-setup-paypal-AGIJIZDK.mjs +0 -1
- package/dist/payment-method-setup-stripe-AAZGNGQO.mjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var $c=Object.create;var Ka=Object.defineProperty;var Hc=Object.getOwnPropertyDescriptor;var Kc=Object.getOwnPropertyNames;var Gc=Object.getPrototypeOf,Yc=Object.prototype.hasOwnProperty;var Xc=(e,t)=>{for(var r in t)Ka(e,r,{get:t[r],enumerable:!0})},hl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Kc(t))!Yc.call(e,a)&&a!==r&&Ka(e,a,{get:()=>t[a],enumerable:!(n=Hc(t,a))||n.enumerable});return e};var Gi=(e,t,r)=>(r=e!=null?$c(Gc(e)):{},hl(t||!e||!e.__esModule?Ka(r,"default",{value:e,enumerable:!0}):r,e)),Jc=e=>hl(Ka({},"__esModule",{value:!0}),e);var Eu={};Xc(Eu,{DirectPayPalButton:()=>Ca,FloPayAutomaticPaymentButton:()=>pc,FloPayCardSetup:()=>mc,FloPayCardSetupError:()=>Ba,FloPayCheckout:()=>ki,FloPayPaymentMethodSetup:()=>kc,FloPayProvider:()=>Sa,SplitCardForm:()=>Ci,VaultCardFields:()=>po,dropThirdPartyOnlyError:()=>Ec.dropThirdPartyOnlyError,useCheckout:()=>_l,useFloPay:()=>ro,usePayPalFloPay:()=>Ja});module.exports=Jc(Eu);var Ec=require("@flopay/shared");var Ri=require("@flopay/js"),Sn=require("@flopay/shared"),gt=require("react");var Gt=require("react/jsx-runtime");function Zc(){return(0,Gt.jsxs)(Gt.Fragment,{children:[(0,Gt.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,Gt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Gt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Gt.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,Gt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Qc(){return(0,Gt.jsx)(Gt.Fragment,{children:"Go back"})}function ed(){return(0,Gt.jsx)(Gt.Fragment,{children:"Secure card checkout"})}function No(e){return e!==void 0&&(e===""||e===null||e===!1)}function Uo({content:e}){return(0,Gt.jsx)(Gt.Fragment,{children:e===void 0?(0,Gt.jsx)(Zc,{}):e})}function zo({content:e}){return(0,Gt.jsx)(Gt.Fragment,{children:e===void 0?(0,Gt.jsx)(Qc,{}):e})}function ya({content:e}){return(0,Gt.jsx)(Gt.Fragment,{children:e===void 0?(0,Gt.jsx)(ed,{}):e})}var Ct=require("@flopay/shared"),En=require("@flopay/shared"),Vo=require("@flopay/shared"),bo=require("@flopay/shared"),td="Checkout is temporarily unavailable. Please try again later.";function Yi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Ct.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function rd(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 Pl(){return new Ct.FloPayError(td,"api_error",{code:"CheckoutInitializationFailed"})}function vl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,Ct.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,Ct.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function Cl(e,t){if(t&&(!(e instanceof Ct.FloPayError)||e.type==="authentication_error"))return Yi(e);if(!(e instanceof Ct.FloPayError&&rd(e))){if(!t&&!(e instanceof Ct.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Ct.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Ct.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Ct.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function qo(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let l={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,Ct.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,Ct.isValidEmail)(l.email))return Promise.reject(new Ct.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[f,S]of Object.entries(l)){if(p&&f.endsWith("Name")||typeof S!="string")continue;let C=S.trim();C&&(m[f]=C)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function bl(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 Xi(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 Sl(e,t){let r=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],n=r.reduce((s,l)=>s+(l.overrideAmount??l.totalAmount??0),0),a=e.currency??r.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(s=>s.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((s,l)=>({uuid:`synthetic-${s.type??"item"}-${l}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??a,metadata:s.metadata??null}))}}function Ji(e,t){return t?{...e,...t}:e}function _r(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,s=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}:{},...s?{declineCode:s}:{},...l?{sessionId:l}:{}}}function co(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Qn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function eo(e){return e?.status==="authorized"||e?.status==="complete"}function uo(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 wl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ga(e){let t=wl(e);return new Ct.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Ya(e){return e instanceof Ct.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function jo(e){return wl(e)?new Ct.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Ct.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Ct.FloPayError(Ct.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function fa(e,t){return e==="processing"||(0,Ct.isMoneySettledOutcome)(e,t)}function kl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Rl(e,t){let r=e;if((0,Ct.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:l}=await r.retrieveSetupIntent(t);if(l)throw new Ct.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new Ct.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var nd=["apple_pay","google_pay"];function El(e,t="automatic",r){let n=(0,Ct.resolveSetupFutureUsage)(r,nd,"wallet");return{...(0,Ct.resolveWalletModeOptions)(e,t),paymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var od=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Zi(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:od.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function ga(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var ao=require("@flopay/js"),He=require("@flopay/shared"),h=Gi(require("react"),1);var Qi=require("react"),gn=(0,Qi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),In=(0,Qi.createContext)({session:null,loading:!1,error:null});var ni=require("@flopay/js"),Qe=require("@flopay/shared"),Al=require("@paypal/paypal-js"),b=require("react");var Xa=require("@flopay/shared"),_n=require("react"),hn=require("@flopay/shared"),to=require("react/jsx-runtime");function Wo(){let[e,t]=(0,_n.useState)(null),r=(0,_n.useRef)(null),n=(0,_n.useRef)(0),a=(0,_n.useCallback)((l,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:l,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,_n.useCallback)(l=>{let p=r.current;r.current=null,t(null),p?.(l)},[]);return(0,_n.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function $o({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[l,p]=(0,_n.useState)(e.email?.trim()??""),m=(0,Xa.isValidEmail)(l.trim());return(0,to.jsxs)("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,to.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,to.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,to.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:f=>p(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,to.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,to.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,to.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,Xa.compactBuyerIdentity)({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var ke=require("@flopay/shared");var Il=require("@flopay/shared"),ha=require("react");function ro(){return(0,ha.useContext)(gn).flopay}function Ja(){return(0,ha.useContext)(gn).paypalFlopay??null}function _l(){return(0,ha.useContext)(In)}function Tl(){return(0,ha.useContext)(gn).billingApiUrl||(0,Il.resolveBillingApiUrl)()}var ad=require("@flopay/shared"),zn=require("@flopay/shared"),qn=require("@flopay/shared");var Ho=require("@flopay/shared"),wo=require("react");var Za=require("react"),So=typeof window>"u"?Za.useEffect:Za.useLayoutEffect;var es=require("@flopay/shared");function Ko(e,t){let r=(0,wo.useRef)(e);r.current=e;let n=(0,wo.useRef)(new Set),a=(0,wo.useRef)(t),s=(0,wo.useRef)(t);return So(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,wo.useCallback)(l=>{if(s.current!==t)return;let p=(0,Ho.projectFloInstrument)(l);if(p){if(Ho.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,Ho.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ze=require("@flopay/shared");var Ml=require("react"),Pa=(0,Ml.createContext)(null);function Qa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ei="provider.callback.ignored";function ti(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var id=Symbol.for("@flopay/js.telemetry.bridge.v1"),sd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ld(){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 cd(e){let t=ld(),r=(a,s)=>a?a.bind(e):s,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 ri(e){let t=globalThis[sd];return cd(t?.(e)??{})}function vr(e){if(e)return e[id]}var mr=require("react");function va(e,t){let r=(0,mr.useRef)(0),n=(0,mr.useRef)(null),a=(0,mr.useRef)(null),s=(0,mr.useRef)(e),l=(0,mr.useRef)(t?.onHandoffObserved),p=(0,mr.useRef)(t?.defersMissingTerminal),m=(0,mr.useRef)(t?.onMissingTerminalDeferred);(0,mr.useEffect)(()=>{s.current=e,l.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let f=(0,mr.useCallback)((y=a.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),S=(0,mr.useCallback)(y=>{f();let g=r.current+1;return r.current=g,n.current=null,a.current={generation:g,method:y,timer:null,yieldedControl:!1},g},[f]),C=(0,mr.useCallback)(y=>{let g=a.current;return y!==void 0&&g?.generation!==y?!1:(f(g),a.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[f]),R=(0,mr.useCallback)(y=>{let g=a.current,he=y??g?.generation??r.current;(y===void 0||g?.generation===y)&&(f(g),a.current=null),n.current=he},[f]),H=(0,mr.useCallback)(y=>n.current===(y??r.current),[]),E=(0,mr.useCallback)(y=>a.current?.generation===y&&n.current!==y,[]),Z=(0,mr.useCallback)(()=>{let y=a.current;y&&(f(y),!y.yieldedControl&&(y.yieldedControl=!0,l.current?.(y.method)))},[f]),M=(0,mr.useCallback)(()=>{let y=a.current;!y?.yieldedControl||document.visibilityState!=="visible"||(f(y),y.timer=setTimeout(()=>{if(y.timer=null,a.current?.generation===y.generation){if(p.current?.(y.method)){m.current?.(y.method,y.generation);return}a.current=null,n.current=y.generation,s.current(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},ke.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[f]);return(0,mr.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?M():Z()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",Z),window.addEventListener("focus",M),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",Z),window.removeEventListener("focus",M),f()}},[f,Z,M]),{startAttempt:S,finishAttempt:C,invalidateAttempt:R,isAttemptInvalidated:H,isAttemptCurrent:E,generationRef:r}}var Pn=require("react/jsx-runtime"),oi=45,dd=1e3,ud=11e3,pd={width:"100%",minHeight:oi,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"},md={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 yd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:md[e.kind]??null}}function xl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,ke.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function fd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Fl({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:l,environment:p,currency:m,isSubscription:f,providerObjectType:S,approvalPresentation:C,onTokenizedBody:R,onComplete:H,onErrorChange:E,onDecline:Z,onCancel:M,onTechnicalFailure:y,isProcessing:g=!1,onLoadStateChange:he,onInitializationStateChange:v,allowAutomaticRetry:xe=!0,onButtonClick:I,runBeforeButtonClick:se,session:Pe,existingOrderId:fe,telemetry:Ae,telemetryContext:st,onInstrument:Ke,debug:B=!1}){let St=ro(),Xe=Ko(Ke,e),Ne=(0,b.useMemo)(()=>{if(St)return null;let le=ri({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:Qe.SDK_VERSION,enabled:Ae!==!1});return le.setCheckoutContext(st??{}),le.beginCheckout(st??{}),le},[r,St,Ae,st?.checkoutMode,st?.layout]),me=(0,b.useMemo)(()=>vr(St),[St]);(0,b.useEffect)(()=>()=>{Ne&&Ne.flush().catch(()=>{}).finally(()=>Ne.destroy())},[Ne]);let ee=(0,b.useMemo)(()=>({error:le=>{me?me.error(le):Ne?.error(le),Xe({class:"technical_error",errorCode:le.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":le.errorCode,requestCategory:le.requestCategory,provider:le.provider})},log:le=>{me?me.log(le):Ne?.log(le),Xe({class:"lifecycle",name:le.name,provider:le.provider})},performance:le=>{me?me.performance(le):Ne?.performance(le)},terminal:le=>{me?me.terminal(le):Ne?.terminal(le)},startTiming:()=>me?.now()??Ne?.now()??0,elapsed:le=>me?.elapsed(le)??Math.max(0,(Ne?.now()??le)-le)}),[Xe,me,Ne]),K=(0,b.useRef)(null),Ue=(0,b.useRef)(0),tt=(0,b.useRef)(null),qe=(0,b.useRef)(null),Q=(0,b.useRef)(null),G=(0,b.useContext)(Pa),$=(0,b.useRef)(null);$.current||($.current=Qa());let q=G??$.current,Ve=(0,b.useRef)(null),Oe=(0,b.useRef)(!1),[Ce,O]=(0,b.useState)(!1),[Se,ut]=(0,b.useState)(!1),[ze,rt]=(0,b.useState)(0),Fe=(0,b.useRef)(0),[et,nt]=(0,b.useState)(!1),cr=(0,b.useRef)(!1),xt=(0,b.useRef)(!1),[bt,Re]=(0,b.useState)(!1),[_,ht]=(0,b.useState)(!1),{request:pt,collect:N,finish:Be}=Wo(),Lt=(0,b.useRef)({sessionId:e,required:(0,Qe.paypalProviderIdentityRequired)(n,Pe)});Lt.current.sessionId!==e&&(Lt.current={sessionId:e,required:(0,Qe.paypalProviderIdentityRequired)(n,Pe)});let Ee=Lt.current.required,It=(0,b.useMemo)(()=>r.replace(/\/+$/,""),[r]),T=Pe?.gateways?.paypal?.providerObjectType??S,Le=T??(f?"subscription":"order"),[Ie]=(0,b.useState)(zn.detectPayPalEnvironment),lt=Pe?.gateways?.paypal?.approvalPresentation??C,ot=(0,qn.resolvePayPalPresentationMode)(Ie,lt==="app_switch"?"app_switch":void 0,Le),We=(0,Qe.usesPayPalVaultedChannel)(T),Ge=(0,b.useMemo)(()=>JSON.stringify([It,l,m,p??"",Le,We,ot,e,fe??""]),[It,l,m,p,fe,Le,We,ot,e]),Dt=(0,b.useRef)(Ge),c=Dt.current!==Ge,L=(0,b.useRef)(B),j=(0,b.useRef)(null),[ue,k]=(0,b.useState)([]),V=(0,b.useCallback)(le=>{L.current&&k(At=>[...At,`${new Date().toISOString().slice(11,23)} ${le}`])},[]);(0,b.useEffect)(()=>{L.current=B,B&&V("debug:enabled"),j.current?.setEnabled(B)},[V,B]);let Ut=(0,b.useRef)(R),Br=(0,b.useRef)(H),dr=(0,b.useRef)(E),Yt=(0,b.useRef)(Z),_t=(0,b.useRef)(M),qr=(0,b.useRef)(y),Dr=(0,b.useRef)(I),tr=(0,b.useRef)(he),Gr=(0,b.useRef)(v),Tt=(0,b.useRef)(s),An=(0,b.useRef)(se),Xt=(0,b.useRef)(Pe),pn=(0,b.useRef)(n),jr=(0,b.useRef)(a),Vr=(0,b.useRef)(t),ur=(0,b.useRef)(null),br=(0,b.useRef)(new Map),Yr=(0,b.useRef)(new Map),at=(0,b.useRef)(!1),kt=(0,b.useRef)(e);kt.current=e;let[xr]=(0,b.useState)(ti);(0,b.useEffect)(()=>(at.current=!0,()=>{at.current=!1}),[]),(0,b.useEffect)(()=>{Ut.current=R},[R]),(0,b.useEffect)(()=>{Tt.current=s},[s]),(0,b.useEffect)(()=>{Br.current=H},[H]),(0,b.useEffect)(()=>{dr.current=E},[E]),(0,b.useEffect)(()=>{Yt.current=Z},[Z]),(0,b.useEffect)(()=>{_t.current=M},[M]),(0,b.useEffect)(()=>{qr.current=y},[y]),(0,b.useEffect)(()=>{Dr.current=I},[I]),(0,b.useEffect)(()=>{tr.current=he},[he]),(0,b.useEffect)(()=>{Gr.current=v},[v]),(0,b.useEffect)(()=>{An.current=se},[se]),(0,b.useEffect)(()=>{Xt.current=Pe},[Pe]),(0,b.useEffect)(()=>{pn.current=n},[n]),(0,b.useEffect)(()=>{jr.current=a},[a]),(0,b.useEffect)(()=>{Vr.current=t},[t]),(0,b.useEffect)(()=>{Fe.current=ze},[ze]),(0,b.useEffect)(()=>{et&&Ve.current?.focus()},[et,ze]);let Wt=(0,b.useCallback)(()=>{window.setTimeout(()=>{Ve.current?.focus()},0)},[]),pr=(0,b.useCallback)(()=>{O(!1),rt(le=>le+1)},[]),fr=(0,b.useCallback)(()=>{nt(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);(0,b.useEffect)(()=>{!Ce||!Oe.current||(Oe.current=!1,fr())},[fr,Ce,ze]);let Jt=(0,b.useCallback)((le,At)=>{let te=At?.popupBlocked??(0,ke.isPopupBlockedError)(le);te&&q.markBlocked();let $t=(0,ke.buildExternalMethodRecoveryMessage)("PayPal",te,Ie.inAppBrowser),nr=qr.current;if(nr){let be=te&&Ie.inAppBrowser?new Qe.FloPayError($t,"api_error",{code:At?.code??"paypal_popup_blocked"}):le;nr("paypal",be,At);return}dr.current?.($t)},[q,Ie.inAppBrowser]),Zt=(0,b.useCallback)(le=>{let At=tt.current,te=qe.current;At===null||!te||(ee.log({...te,popupCapability:q.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:le}),ee.performance({...te,popupCapability:q.current(),stage:"overlay_return",durationMs:ee.elapsed(At),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:le}),tt.current=null)},[q,ee]),Sr=(0,b.useCallback)((le,At,te)=>{let $t=qe.current;Zt("overlay_timeout"),$t&&ee.error({...$t,popupCapability:q.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Jt(At,{...te,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ot,terminalReason:"overlay_timeout"}),nt(!0),pr(),Wt()},[Zt,Wt,Jt,q,ot,pr,ee]),Je=(0,b.useCallback)(()=>{q.markAvailable();let le=qe.current;le&&(Q.current=le.attempt,ee.log({...le,popupCapability:q.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[q,ee]),{finishAttempt:wr,generationRef:kr,invalidateAttempt:Hn,isAttemptCurrent:Or,isAttemptInvalidated:Lr,startAttempt:Fn}=va(Sr,{onHandoffObserved:Je}),an=(0,b.useCallback)(()=>(nt(!1),Fn("paypal")),[Fn]),rr=(0,b.useCallback)(le=>{Hn(le?.generation),le?.showRetry&&nt(!0),le?.remount&&pr(),le?.focus!==!1&&Wt()},[Wt,Hn,pr]),ve=le=>{let At=ur.current;return At&&Yr.current.set(le,At),le};(0,b.useEffect)(()=>{Dt.current!==Ge&&(Dt.current=Ge,cr.current=!1,xt.current=!1,O(!1),ut(!1),Re(!1),Gr.current?.("loading"))},[Ge]),(0,b.useEffect)(()=>{(0,Ze.invokeMerchantCallback)(()=>tr.current?.(Ce&&!bt))},[Ce,bt]);let gr=(0,Qe.normalizeGatewayEnvironment)(p);(0,b.useEffect)(()=>{let le={attempt:kr.current+1,inAppBrowser:Ie.inAppBrowser,appFamily:Ie.appFamily,popupCapability:q.current(),presentationMode:ot},At=()=>({...qe.current??le,popupCapability:q.current()}),te={error:x=>ee.error({...x,...At()}),log:x=>ee.log({...x,...At()}),performance:x=>ee.performance({...x,...At()}),terminal:x=>ee.terminal({...x,...At()}),startTiming:ee.startTiming,elapsed:ee.elapsed},$t=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",nr=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(V(`mount clientId=${$t} env=${p??"(unset)"}\u2192${gr??"live"} ccy=${m} sub=${f}`),V(`ua=${nr.slice(0,80)}${nr.length>80?"\u2026":""}`),!l){V("FAIL: clientId empty \u2014 gateway misconfigured"),Re(!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(!K.current){V("FAIL: containerRef not attached");return}Ue.current=te.startTiming(),te.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let be=!1,Vt=!1,ae=()=>be||Vt,Nt=x=>{let A=at.current,D=A?x:"torn_down";A&&V(`onError ignored reason=${D}`),xr.take(kt.current)&&te.log({name:ei,stage:"provider_ready",reason:D,provider:"paypal",paymentMethodCategory:"paypal"})},hr=()=>kt.current===e?"stale_attempt":"session_changed",Nr=We?Le:void 0,Qt,Bn=!1,Kn=()=>{Qt=(0,Qe.generateIdempotencyKey)(),Qt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Bn=!0},Dn=null,On=!1,Gn=null,so=!1,lo=()=>{!Gn||so||(so=!0,Gn.close().catch(()=>{}))},Ar=!1,Yn=!1,mn=K.current,zt=null,Jr=null,Zr=[],sn=null,Qr=!1,ct=!1,Pr=null,or=x=>{if(!x||typeof x.getBoundingClientRect!="function")return"(no rect)";let A=x.getBoundingClientRect();return`${Math.round(A.width)}\xD7${Math.round(A.height)}`},en=x=>{if(!x)return"(empty)";try{let A=new URL(x,typeof window>"u"?"https://localhost":window.location.href),D=A.pathname.toLowerCase();return D.includes("checkcaptcha")||D.includes("captcha")?`CAPTCHA(${A.host}${D})`:D.includes("risk")||D.includes("challenge")?`RISK(${A.host}${D})`:D.includes("smart/buttons")?`smart-buttons(${A.host})`:`${A.host}${D}`.slice(0,100)}catch{return x.slice(0,80)}},fo=x=>{let A=x.getAttribute("src"),D=x.getAttribute("srcdoc"),re=x.getAttribute("name"),ge=x.getAttribute("sandbox"),De=[];return A&&De.push(`src=${en(A)}`),D&&De.push(`srcdoc[${D.length}ch]`),!A&&!D&&De.push("src=(empty) srcdoc=(empty)"),re&&De.push(`name=${re.slice(0,40)}`),ge!==null&&De.push(`sandbox="${ge.slice(0,40)}"`),De.join(" ")},Xn=x=>{if(!(x instanceof HTMLIFrameElement))return"";try{let A=x.contentDocument;if(!A)return"cd=null";let D=A.body?.children.length??0,re=A.body?.innerHTML.length??0,ge=A.head?.innerHTML.length??0;return`cd=same-origin readyState=${A.readyState} body[${D}children,${re}ch] head[${ge}ch]`}catch(A){return`cd=cross-origin(${A.message.slice(0,30)})`}},wn=[],ln=x=>{if(ae())return;let A=x.message??String(x.error??"(no message)");A&&(A.toLowerCase().includes("paypal")||A.toLowerCase().includes("zoid")||A.toLowerCase().includes("postrobot")||A.toLowerCase().includes("storage"))&&(V(`window:error ${A.slice(0,140)}`),wn.push(A))},Rr=x=>{if(ae())return;let A=x.reason instanceof Error?x.reason.message:String(x.reason??"(no reason)");A&&(A.toLowerCase().includes("paypal")||A.toLowerCase().includes("zoid")||A.toLowerCase().includes("postrobot")||A.toLowerCase().includes("storage"))&&(V(`window:rejection ${A.slice(0,140)}`),wn.push(A))},Jn={value:0},Ur=()=>{zt?.disconnect(),zt=null,Jr?.disconnect(),Jr=null;for(let x of Zr.splice(0))clearTimeout(x);ct=!1,Qr&&typeof window<"u"&&(window.removeEventListener("error",ln),window.removeEventListener("unhandledrejection",Rr)),Qr=!1},U=()=>{if(!(Qr||ae()||Ar)){if(Qr=!0,wn.length=0,Jn.value=0,typeof window<"u"&&(window.addEventListener("error",ln),window.addEventListener("unhandledrejection",Rr)),typeof PerformanceObserver<"u")try{Jr=new PerformanceObserver(x=>{if(!ae())for(let A of x.getEntries()){if(!A.name.toLowerCase().includes("paypal"))continue;Jn.value+=1;let D=Math.round(A.duration);V(`net ${D}ms ${A.name.slice(0,90)}`)}}),Jr.observe({type:"resource",buffered:!0})}catch{}Pr?.()}},z=()=>{sn&&(clearTimeout(sn),sn=null)},ie=()=>{Ur(),z()},we={setEnabled:x=>{x?U():Ur()}};j.current=we,L.current&&U();let mt=Qe.isPayPalTeardownMessage,Ht=x=>{if(ae()||mt(x))return;let A=(0,bo.applyFriendlyMessageOverride)(x)??x;(0,Ze.invokeMerchantCallback)(()=>dr.current?.(A))},_e=(x,A)=>{if(be||On)return;On=!0,Vt=!0,ie(),lo();let D=yd({kind:x,generationActive:!0,automaticRetryAllowed:xe,automaticRetryUsed:cr.current});if(D.action==="retry"){cr.current=!0,O(!1),ht(!1),ut(!0),Gr.current?.("retrying"),Dn=setTimeout(()=>{be||rt(re=>re+1)},dd);return}if(O(!1),ht(!1),ut(!1),Re(!0),D.action!=="ignore"){if(Gr.current?.("exhausted"),D.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",A);return}if(D.report){let re=(0,ke.classifyExternalMethodFailure)({code:xl(x,A),message:A},{inAppBrowser:Ie.inAppBrowser,handoffObserved:!1});re.popupBlocked&&q.markBlocked(),te.error({errorCode:re.popupBlocked?re.errorCode:D.report.errorCode,stage:D.report.stage,operationOutcome:D.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:re.terminalReason})}xt.current||(xt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",xl(x,A)))}};Re(!1);let pe=async(x,A=ur.current)=>{if(ae())return;let D=A?.sessionId??e;if(Ut.current){await Ut.current(x,{sessionId:D,accountPatch:A?.accountPatch,nonce:A?.nonce});return}let re=te.startTiming();te.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ge=()=>{te.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"processing",durationMs:te.elapsed(re),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let De=(0,Qe.buildPayPalProcessPaymentRequest)({body:x,sessionId:D,nonce:A?.nonce??Vr.current,accountPatch:A?.accountPatch,session:Xt.current,email:pn.current}),ne=await new ni.PaymentAPI(It,{telemetry:!1}).processPayment(De.userId,De.params);if(ne.ok){if(Vt||be&&at.current)return;ge(),te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ze.invokeMerchantCallback)(()=>Br.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ae())return;let Mt=await ne.json().catch(()=>null),Wr=(0,Qe.describePayPalProcessFailure)(Mt),Er=Wr.message;ge(),ne.status===400&&(typeof Mt?.declineCode=="string"||!Array.isArray(Mt?.fields))?te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ne.status===400||ne.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:fd(ne.status),failureCategory:ne.status>=500?"server_error":void 0}),Ht(Er),(0,Ze.invokeMerchantCallback)(()=>Yt.current?.(_r("paypal",Er,{code:Wr.code,declineCode:Wr.declineCode})));return}catch(De){if(ae())return;ge(),te.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Pt=(0,Qe.friendlyPayPalFailureMessage)(De instanceof Error?De.message:void 0);Ht(Pt),(0,Ze.invokeMerchantCallback)(()=>Yt.current?.(_r("paypal",Pt)));return}},X=()=>new Qe.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),W=x=>ae()?Promise.reject(X()):Promise.resolve(x),ce=async x=>{if(ae())throw X();Bn||Kn();let A=ur.current,D=A?.sessionId??e,re=A?.nonce??Vr.current;te.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ge;try{ge=await new ni.PaymentAPI(It,{telemetry:!1}).createSessionIntent(D,re??"",(0,Qe.buildPayPalSessionIntentRequest)(Nr),{idempotencyKey:Qt})}catch(De){throw te.error({...(0,Qe.classifyTelemetryFailure)(De,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),De}if(ae())throw X();if(ge.provider!=="paypal"||ge.providerObjectType!==Le)throw new Error(x);return te.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ge.providerObjectId},$e=(x,A)=>{let D=A?.nonce??Vr.current;if(!D)return;let re=A?.sessionId??e,ge=(0,Qe.resolvePayPalDeclineReason)(x);new ni.PaymentAPI(It,{telemetry:!1}).reportSessionIntentDecline(re,D,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ge}).catch(()=>{})},de=ze;V("loadScript:scheduled (deferred 1 tick)");let yt=null,Ot=setTimeout(()=>{if(be){V("loadScript:skipped (cancelled before defer ran)");return}V("loadScript:start");let x=gr==="live"?"production":gr,A={};Le==="subscription"?A={intent:"subscription",vault:!0}:Le==="order"&&(A={intent:"capture"}),yt=(0,Al.loadScript)({clientId:l,currency:m,...A,...x?{environment:x}:{},...x==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let D=!1;yt.then(re=>{if(D=!0,V(`loadScript:resolved inactive=${ae()} ns=${!!re} buttons=${!!re?.Buttons}`),ae())return;if(!re?.Buttons){V("FAIL: namespace missing Buttons factory"),_e("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(Ue.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),te.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ge=async(ye,dt)=>{if(ae()||Fe.current!==de)return;let oe=ye.vaultSetupToken??ye.subscriptionID??ye.orderID??"",Rt=oe?Yr.current.get(oe):br.current.get(de);if(!(!Rt||!Or(Rt.generation))&&wr(Rt.generation)){Yr.current.delete(oe),br.current.delete(Rt.surfaceKey),Zt("approved");try{if(ht(!0),(0,Ze.invokeMerchantCallback)(()=>dr.current?.(null)),!oe)throw new Qe.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let wt=(0,Qe.resolvePayPalApprovalIdentity)({accountPatch:Rt.accountPatch,email:pn.current,billingName:jr.current,session:Xt.current});if((0,Qe.needsPayPalPayerDetails)(wt))try{wt=(0,Qe.mergePayPalPayerIdentity)(wt,await dt?.order?.get?.())}catch{}if((Tt.current||Ee)&&!(0,Qe.isValidEmail)(wt.email)){let Ft=await N("PayPal",wt);if(!Ft)return;wt=Ft}(0,Qe.isValidEmail)(wt.email)&&(Rt.accountPatch=(0,hn.compactBuyerIdentity)({...Rt.accountPatch,...wt}),await Tt.current?.(wt));let $r=(0,Qe.buildPayPalTokenizedBody)(oe,Nr);await pe($r,Rt)}catch(wt){Ht(wt instanceof Error?wt.message:"PayPal capture failed.")}finally{ae()||ht(!1)}}},De=ye=>{let dt=fe?()=>W(fe):()=>ce(ye);return async()=>ve(await dt())},Pt=re.Buttons({style:{layout:"horizontal",height:oi,tagline:!1},...ot==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ye,dt)=>{if(ae()){await dt.reject();return}Kn();let oe=An.current,Rt={};if(oe)try{let Ft=await oe("paypal");if(ae()){await dt.reject();return}if(!Ft.proceed){ur.current=null,br.current.delete(de),await dt.reject();return}Rt={sessionId:Ft.sessionId,accountPatch:Ft.accountPatch,nonce:Ft.nonce}}catch(Ft){V(`onClick:runBeforeButtonClick rejected msg=${(Ft instanceof Error?Ft.message:String(Ft)).slice(0,120)}`),ur.current=null,br.current.delete(de),await dt.reject();return}(0,Ze.invokeMerchantCallback)(()=>Dr.current?.("paypal"));let wt=an(),$r={generation:wt,surfaceKey:de,...Rt};ur.current=$r,br.current.set(de,$r),qe.current={...le,attempt:wt},await dt.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"}),tt.current=te.startTiming()},createOrder:Le==="order"?De("Failed to create PayPal order."):void 0,createSubscription:Le==="subscription"?De("Failed to create PayPal subscription."):void 0,createVaultSetupToken:Le==="setup_token"?async()=>ve(await ce("Failed to create PayPal setup token.")):void 0,onApprove:ge,onCancel:()=>{if(ae())return;let ye=br.current.get(de)??ur.current,dt=ye&&Or(ye.generation)?(0,Qe.buildPayPalCancelEvent)(ye.sessionId??e,Nr):null;ye&&br.current.delete(ye.surfaceKey),ur.current=null,Zt("cancelled"),te.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Oe.current=!0,rr({generation:ye?.generation,remount:!0,focus:!1}),dt&&(0,Ze.invokeMerchantCallback)(()=>_t.current?.(dt))},onError:ye=>{let dt=ye instanceof Error?ye.message:"PayPal failed to render.";if(ae()||Fe.current!==de){mt(dt)||Nt(hr());return}if(Ar){let oe=br.current.get(de)??ur.current;if(!oe||!Or(oe.generation)){if(mt(dt)){!oe&&!Lr()&&wr();return}Nt(oe||Lr()?"stale_attempt":"no_current_attempt");return}if(V(`onError rendered=${Ar} msg=${dt.slice(0,120)}`),mt(dt)){wr(oe.generation);return}let{errorCode:Rt,popupBlocked:wt,providerDeclined:$r,terminalReason:Ft}=(0,ke.classifyExternalMethodFailure)(ye,{inAppBrowser:Ie.inAppBrowser,handoffObserved:Q.current===oe.generation});if(wt&&q.markBlocked(),Zt(Ft),$r){te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ft}),$e(ye,oe),(0,Ze.invokeMerchantCallback)(()=>Yt.current?.(_r("paypal",dt))),br.current.delete(oe.surfaceKey),ur.current=null,wr(oe.generation);return}te.error({errorCode:Rt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ft}),br.current.delete(oe.surfaceKey),ur.current=null,rr({generation:oe.generation,remount:!0,showRetry:!0,focus:!0}),Jt(ye,{code:"paypal_runtime_failed",popupBlocked:wt,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ot,terminalReason:Ft});return}V(`onError rendered=${Ar} msg=${dt.slice(0,120)}`),_e(mt(dt)?"teardown":"pre_ready_callback",dt)}}),ne=Pt.isEligible();if(V(`isEligible=${ne}`),te.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ne){O(!1),_e("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Yn=!0,Gn=Pt,Pr=()=>{if(!Qr||ct||ae()||Ar)return;ct=!0,V(`container:dims ${or(mn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(zt=new MutationObserver(dt=>{if(!ae()){for(let oe of dt)if(oe.type==="childList")oe.addedNodes.forEach(Rt=>{if(!(Rt instanceof Element))return;let wt=Rt.tagName.toLowerCase(),$r=(Rt.getAttribute("title")??"").slice(0,40),Ft=wt==="iframe"?` ${fo(Rt)}`:"";V(`child+ ${wt}${$r?` title="${$r}"`:""}${Ft} dims=${or(Rt)}`)});else if(oe.type==="attributes"&&oe.target instanceof Element){let Rt=oe.target;if(Rt.tagName.toLowerCase()!=="iframe")continue;let wt=oe.attributeName;(wt==="src"||wt==="srcdoc")&&V(`attr~ iframe ${wt}=${wt==="srcdoc"?`[${(Rt.getAttribute("srcdoc")??"").length}ch]`:en(Rt.getAttribute("src"))} dims=${or(Rt)}`)}}}),zt.observe(mn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ye=dt=>{if(ae()||Ar)return;let oe=mn.querySelectorAll("iframe"),Rt=typeof document<"u"&&"hasStorageAccess"in document;V(`watchdog:${dt} container=${or(mn)} children=${mn.childElementCount} iframes=${oe.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Rt} paypalNetRequests=${Jn.value}`),oe.forEach((wt,$r)=>{let Ft=(wt.getAttribute("title")??"").slice(0,40);V(` iframe[${$r}] ${or(wt)}${Ft?` title="${Ft}"`:""} ${fo(wt)}`);let Io=Xn(wt);Io&&V(` ${Io}`)}),wn.length===0&&V(" (no PayPal/zoid window errors captured)")};Zr.push(setTimeout(()=>ye("3s"),3e3)),Zr.push(setTimeout(()=>ye("8s"),8e3)),Zr.push(setTimeout(()=>ye("15s"),15e3))},Pr(),V("render:start");let Wr=te.startTiming();sn=setTimeout(()=>{ae()||Ar||(V("watchdog:11s retryable render timeout"),_e("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},ud);let Er=Pt.render(mn);(async()=>{try{if(await Er,V(`render:resolved inactive=${ae()}`),ie(),ae()){lo();return}Ar=!0,O(!0),ut(!1),Gr.current?.("ready"),te.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"checkout_render",durationMs:te.elapsed(Wr),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ye){let dt=ye instanceof Error?ye.message:"PayPal failed to render.";V(`render:rejected msg=${dt.slice(0,120)}`),ie(),_e(mt(dt)?"teardown":"render_rejected",dt)}})()}).catch(re=>{let ge=re instanceof Error?re.message:"PayPal operation failed.";V(`provider:failed msg=${ge.slice(0,120)}`);let De="script_rejected";D&&mt(ge)?De="teardown":D&&Yn&&(De="render_rejected"),_e(De,ge)})},0);return()=>{be=!0,clearTimeout(Ot),Dn&&clearTimeout(Dn),ie(),j.current===we&&(j.current=null),lo(),tt.current=null,qe.current=null}},[xe,It,l,m,p,Le,ot,We,e,fe,ze,ee,N,Ee,V,Zt]);let Xr=B?(0,Pn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:bt?"#fef2f2":"#f3f4f6",border:`1px solid ${bt?"#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=${Ce} failed=${bt})`,ue.length===0?`
|
|
1
|
+
"use strict";var Gc=Object.create;var Ga=Object.defineProperty;var Yc=Object.getOwnPropertyDescriptor;var Xc=Object.getOwnPropertyNames;var Jc=Object.getPrototypeOf,Zc=Object.prototype.hasOwnProperty;var Qc=(e,t)=>{for(var r in t)Ga(e,r,{get:t[r],enumerable:!0})},hl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Xc(t))!Zc.call(e,a)&&a!==r&&Ga(e,a,{get:()=>t[a],enumerable:!(n=Yc(t,a))||n.enumerable});return e};var Gi=(e,t,r)=>(r=e!=null?Gc(Jc(e)):{},hl(t||!e||!e.__esModule?Ga(r,"default",{value:e,enumerable:!0}):r,e)),ed=e=>hl(Ga({},"__esModule",{value:!0}),e);var _u={};Qc(_u,{DirectPayPalButton:()=>va,FloPayAutomaticPaymentButton:()=>fc,FloPayCardSetup:()=>gc,FloPayCardSetupError:()=>Fa,FloPayCheckout:()=>Ri,FloPayPaymentMethodSetup:()=>Ic,FloPayProvider:()=>ba,SplitCardForm:()=>bi,VaultCardFields:()=>go,dropThirdPartyOnlyError:()=>Tc.dropThirdPartyOnlyError,useCheckout:()=>Ml,useFloPay:()=>io,usePayPalFloPay:()=>Za});module.exports=ed(_u);var Tc=require("@flopay/shared");var Ei=require("@flopay/js"),kn=require("@flopay/shared"),ft=require("react");var Yt=require("react/jsx-runtime");function td(){return(0,Yt.jsxs)(Yt.Fragment,{children:[(0,Yt.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,Yt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Yt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Yt.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,Yt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function rd(){return(0,Yt.jsx)(Yt.Fragment,{children:"Go back"})}function nd(){return(0,Yt.jsx)(Yt.Fragment,{children:"Secure card checkout"})}function Lo(e){return e!==void 0&&(e===""||e===null||e===!1)}function No({content:e}){return(0,Yt.jsx)(Yt.Fragment,{children:e===void 0?(0,Yt.jsx)(td,{}):e})}function Uo({content:e}){return(0,Yt.jsx)(Yt.Fragment,{children:e===void 0?(0,Yt.jsx)(rd,{}):e})}function ma({content:e}){return(0,Yt.jsx)(Yt.Fragment,{children:e===void 0?(0,Yt.jsx)(nd,{}):e})}var St=require("@flopay/shared"),xn=require("@flopay/shared"),jo=require("@flopay/shared"),So=require("@flopay/shared");function Yi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof St.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function od(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 Pl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,St.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,St.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function vl(e,t){if(t&&(!(e instanceof St.FloPayError)||e.type==="authentication_error"))return Yi(e);if(!(e instanceof St.FloPayError&&od(e))){if(!t&&!(e instanceof St.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,St.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof St.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof St.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function zo(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let l={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,St.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,St.isValidEmail)(l.email))return Promise.reject(new St.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[h,R]of Object.entries(l)){if(p&&h.endsWith("Name")||typeof R!="string")continue;let w=R.trim();w&&(m[h]=w)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function Cl(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 Xi(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 bl(e,t){let r=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],n=r.reduce((s,l)=>s+(l.overrideAmount??l.totalAmount??0),0),a=e.currency??r.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(s=>s.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((s,l)=>({uuid:`synthetic-${s.type??"item"}-${l}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??a,metadata:s.metadata??null}))}}function Ji(e,t){return t?{...e,...t}:e}function Sr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,s=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}:{},...s?{declineCode:s}:{},...l?{sessionId:l}:{}}}var Sl=new WeakMap;function wl(e,t){return typeof e=="object"&&e!==null&&Sl.set(e,t?{sessionId:t}:{}),e}function kl(e){return typeof e=="object"&&e!==null?Sl.get(e):void 0}function yo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function no(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function oo(e){return e?.status==="authorized"||e?.status==="complete"}function fo(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 Rl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ya(e){let t=Rl(e);return new St.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Xa(e){return e instanceof St.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function qo(e){return Rl(e)?new St.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new St.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new St.FloPayError(St.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ya(e,t){return e==="processing"||(0,St.isMoneySettledOutcome)(e,t)}function El(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Il(e,t){let r=e;if((0,St.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:l}=await r.retrieveSetupIntent(t);if(l)throw new St.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new St.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var ad=["apple_pay","google_pay"];function _l(e,t="automatic",r){let n=(0,St.resolveSetupFutureUsage)(r,ad,"wallet");return{...(0,St.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var id=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Zi(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:id.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function fa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var co=require("@flopay/js"),Oe=require("@flopay/shared"),v=Gi(require("react"),1);var Qi=require("react"),Pn=(0,Qi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),An=(0,Qi.createContext)({session:null,loading:!1,error:null});var oi=require("@flopay/js"),qe=require("@flopay/shared"),Dl=require("@paypal/paypal-js"),k=require("react");var Ja=require("@flopay/shared"),Fn=require("react"),vn=require("@flopay/shared"),ao=require("react/jsx-runtime");function Vo(){let[e,t]=(0,Fn.useState)(null),r=(0,Fn.useRef)(null),n=(0,Fn.useRef)(0),a=(0,Fn.useCallback)((l,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:l,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,Fn.useCallback)(l=>{let p=r.current;r.current=null,t(null),p?.(l)},[]);return(0,Fn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function Wo({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[l,p]=(0,Fn.useState)(e.email?.trim()??""),m=(0,Ja.isValidEmail)(l.trim());return(0,ao.jsxs)("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,ao.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,ao.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,ao.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:h=>p(h.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,ao.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,ao.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,ao.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,Ja.compactBuyerIdentity)({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var ke=require("@flopay/shared");var Tl=require("@flopay/shared"),ga=require("react");function io(){return(0,ga.useContext)(Pn).flopay}function Za(){return(0,ga.useContext)(Pn).paypalFlopay??null}function Ml(){return(0,ga.useContext)(An)}function xl(){return(0,ga.useContext)(Pn).billingApiUrl||(0,Tl.resolveBillingApiUrl)()}var sd=require("@flopay/shared"),$n=require("@flopay/shared"),Hn=require("@flopay/shared");var $o=require("@flopay/shared"),ko=require("react");var Qa=require("react"),wo=typeof window>"u"?Qa.useEffect:Qa.useLayoutEffect;var es=require("@flopay/shared");function Ho(e,t){let r=(0,ko.useRef)(e);r.current=e;let n=(0,ko.useRef)(new Set),a=(0,ko.useRef)(t),s=(0,ko.useRef)(t);return wo(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,ko.useCallback)(l=>{if(s.current!==t)return;let p=(0,$o.projectFloInstrument)(l);if(p){if($o.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,$o.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ke=require("@flopay/shared");var Al=require("react"),ha=(0,Al.createContext)(null);function ei(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ti="provider.callback.ignored";function ri(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var ld=Symbol.for("@flopay/js.telemetry.bridge.v1"),cd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function dd(){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 ud(e){let t=dd(),r=(a,s)=>a?a.bind(e):s,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 ni(e){let t=globalThis[cd];return ud(t?.(e)??{})}function wr(e){if(e)return e[ld]}var gr=require("react");function Pa(e,t){let r=(0,gr.useRef)(0),n=(0,gr.useRef)(null),a=(0,gr.useRef)(null),s=(0,gr.useRef)(e),l=(0,gr.useRef)(t?.onHandoffObserved),p=(0,gr.useRef)(t?.defersMissingTerminal),m=(0,gr.useRef)(t?.onMissingTerminalDeferred);(0,gr.useEffect)(()=>{s.current=e,l.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let h=(0,gr.useCallback)((y=a.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),R=(0,gr.useCallback)(y=>{h();let P=r.current+1;return r.current=P,n.current=null,a.current={generation:P,method:y,timer:null,yieldedControl:!1},P},[h]),w=(0,gr.useCallback)(y=>{let P=a.current;return y!==void 0&&P?.generation!==y?!1:(h(P),a.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[h]),I=(0,gr.useCallback)(y=>{let P=a.current,me=y??P?.generation??r.current;(y===void 0||P?.generation===y)&&(h(P),a.current=null),n.current=me},[h]),Y=(0,gr.useCallback)(y=>n.current===(y??r.current),[]),_=(0,gr.useCallback)(y=>a.current?.generation===y&&n.current!==y,[]),Z=(0,gr.useCallback)(()=>{let y=a.current;y&&(h(y),!y.yieldedControl&&(y.yieldedControl=!0,l.current?.(y.method)))},[h]),A=(0,gr.useCallback)(()=>{let y=a.current;!y?.yieldedControl||document.visibilityState!=="visible"||(h(y),y.timer=setTimeout(()=>{if(y.timer=null,a.current?.generation===y.generation){if(p.current?.(y.method)){m.current?.(y.method,y.generation);return}a.current=null,n.current=y.generation,s.current(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},ke.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[h]);return(0,gr.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?A():Z()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",Z),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",Z),window.removeEventListener("focus",A),h()}},[h,Z,A]),{startAttempt:R,finishAttempt:w,invalidateAttempt:I,isAttemptInvalidated:Y,isAttemptCurrent:_,generationRef:r}}var Cn=require("react/jsx-runtime"),ai=45,pd=1e3,md=11e3,Fl="paypal_intent_settled",yd={width:"100%",minHeight:ai,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"},fd={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 gd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:fd[e.kind]??null}}function Bl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,ke.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function hd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Ol({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:l,environment:p,currency:m,isSubscription:h,providerObjectType:R,approvalPresentation:w,onTokenizedBody:I,onComplete:Y,onErrorChange:_,onDecline:Z,onCancel:A,onTechnicalFailure:y,isProcessing:P=!1,onLoadStateChange:me,onInitializationStateChange:S,allowAutomaticRetry:xe=!0,onButtonClick:T,runBeforeButtonClick:le,session:ye,existingOrderId:pe,telemetry:Re,telemetryContext:lt,onInstrument:$e,debug:B=!1}){let wt=io(),Ye=Ho($e,e),Ne=(0,k.useMemo)(()=>{if(wt)return null;let oe=ni({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:qe.SDK_VERSION,enabled:Re!==!1});return oe.setCheckoutContext(lt??{}),oe.beginCheckout(lt??{}),oe},[r,wt,Re,lt?.checkoutMode,lt?.layout]),ue=(0,k.useMemo)(()=>wr(wt),[wt]);(0,k.useEffect)(()=>()=>{Ne&&Ne.flush().catch(()=>{}).finally(()=>Ne.destroy())},[Ne]);let ne=(0,k.useMemo)(()=>({error:oe=>{ue?ue.error(oe):Ne?.error(oe),Ye({class:"technical_error",errorCode:oe.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":oe.errorCode,requestCategory:oe.requestCategory,provider:oe.provider})},log:oe=>{ue?ue.log(oe):Ne?.log(oe),Ye({class:"lifecycle",name:oe.name,provider:oe.provider})},performance:oe=>{ue?ue.performance(oe):Ne?.performance(oe)},terminal:oe=>{ue?ue.terminal(oe):Ne?.terminal(oe)},startTiming:()=>ue?.now()??Ne?.now()??0,elapsed:oe=>ue?.elapsed(oe)??Math.max(0,(Ne?.now()??oe)-oe)}),[Ye,ue,Ne]),K=(0,k.useRef)(null),Le=(0,k.useRef)(0),nt=(0,k.useRef)(null),je=(0,k.useRef)(null),X=(0,k.useRef)(null),$=(0,k.useContext)(ha),H=(0,k.useRef)(null);H.current||(H.current=ei());let V=$??H.current,Ve=(0,k.useRef)(null),De=(0,k.useRef)(!1),[fe,D]=(0,k.useState)(!1),[ge,pt]=(0,k.useState)(!1),[Ue,ot]=(0,k.useState)(0),Ae=(0,k.useRef)(0),[Qe,at]=(0,k.useState)(!1),pr=(0,k.useRef)(!1),Mt=(0,k.useRef)(!1),[vt,be]=(0,k.useState)(!1),[M,gt]=(0,k.useState)(!1),{request:ct,collect:N,finish:Fe}=Vo(),Lt=(0,k.useRef)({sessionId:e,required:(0,qe.paypalProviderIdentityRequired)(n,ye)});Lt.current.sessionId!==e&&(Lt.current={sessionId:e,required:(0,qe.paypalProviderIdentityRequired)(n,ye)});let Se=Lt.current.required,It=(0,k.useMemo)(()=>r.replace(/\/+$/,""),[r]),x=ye?.gateways?.paypal?.providerObjectType??R,Be=x??(h?"subscription":"order"),[Ee]=(0,k.useState)($n.detectPayPalEnvironment),dt=ye?.gateways?.paypal?.approvalPresentation??w,it=(0,Hn.resolvePayPalPresentationMode)(Ee,dt==="app_switch"?"app_switch":void 0,Be),We=(0,qe.usesPayPalVaultedChannel)(x),He=(0,k.useMemo)(()=>JSON.stringify([It,l,m,p??"",Be,We,it,e,pe??""]),[It,l,m,p,pe,Be,We,it,e]),Dt=(0,k.useRef)(He),c=Dt.current!==He,U=(0,k.useRef)(B),W=(0,k.useRef)(null),[ce,E]=(0,k.useState)([]),z=(0,k.useCallback)(oe=>{U.current&&E(xt=>[...xt,`${new Date().toISOString().slice(11,23)} ${oe}`])},[]);(0,k.useEffect)(()=>{U.current=B,B&&z("debug:enabled"),W.current?.setEnabled(B)},[z,B]);let Ut=(0,k.useRef)(I),Fr=(0,k.useRef)(Y),tr=(0,k.useRef)(_),Wt=(0,k.useRef)(Z),_t=(0,k.useRef)(A),$r=(0,k.useRef)(y),Nr=(0,k.useRef)(T),rr=(0,k.useRef)(me),Qr=(0,k.useRef)(S),Tt=(0,k.useRef)(s),Ln=(0,k.useRef)(le),Xt=(0,k.useRef)(ye),yn=(0,k.useRef)(n),Hr=(0,k.useRef)(a),Kr=(0,k.useRef)(t),Jt=(0,k.useRef)(null),Pr=(0,k.useRef)(new Map),en=(0,k.useRef)(new Map),et=(0,k.useRef)(!1),kt=(0,k.useRef)(e);kt.current=e;let[Br]=(0,k.useState)(ri);(0,k.useEffect)(()=>(et.current=!0,()=>{et.current=!1}),[]),(0,k.useEffect)(()=>{Ut.current=I},[I]),(0,k.useEffect)(()=>{Tt.current=s},[s]),(0,k.useEffect)(()=>{Fr.current=Y},[Y]),(0,k.useEffect)(()=>{tr.current=_},[_]),(0,k.useEffect)(()=>{Wt.current=Z},[Z]),(0,k.useEffect)(()=>{_t.current=A},[A]),(0,k.useEffect)(()=>{$r.current=y},[y]),(0,k.useEffect)(()=>{Nr.current=T},[T]),(0,k.useEffect)(()=>{rr.current=me},[me]),(0,k.useEffect)(()=>{Qr.current=S},[S]),(0,k.useEffect)(()=>{Ln.current=le},[le]),(0,k.useEffect)(()=>{Xt.current=ye},[ye]),(0,k.useEffect)(()=>{yn.current=n},[n]),(0,k.useEffect)(()=>{Hr.current=a},[a]),(0,k.useEffect)(()=>{Kr.current=t},[t]),(0,k.useEffect)(()=>{Ae.current=Ue},[Ue]),(0,k.useEffect)(()=>{Qe&&Ve.current?.focus()},[Qe,Ue]);let $t=(0,k.useCallback)(()=>{window.setTimeout(()=>{Ve.current?.focus()},0)},[]),nr=(0,k.useCallback)(()=>{D(!1),ot(oe=>oe+1)},[]),vr=(0,k.useCallback)(()=>{at(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);(0,k.useEffect)(()=>{!fe||!De.current||(De.current=!1,vr())},[vr,fe,Ue]);let Zt=(0,k.useCallback)((oe,xt)=>{let Q=xt?.popupBlocked??(0,ke.isPopupBlockedError)(oe);Q&&V.markBlocked();let Kt=(0,ke.buildExternalMethodRecoveryMessage)("PayPal",Q,Ee.inAppBrowser),ir=$r.current;if(ir){let Pe=Q&&Ee.inAppBrowser?new qe.FloPayError(Kt,"api_error",{code:xt?.code??"paypal_popup_blocked"}):oe;ir("paypal",Pe,xt);return}if(oe instanceof qe.FloPayError&&oe.code==="checkout_processing_timeout"){tr.current?.(oe.message);return}tr.current?.(Kt)},[V,Ee.inAppBrowser]),Ht=(0,k.useCallback)(oe=>{let xt=nt.current,Q=je.current;xt===null||!Q||(ne.log({...Q,popupCapability:V.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:oe}),ne.performance({...Q,popupCapability:V.current(),stage:"overlay_return",durationMs:ne.elapsed(xt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:oe}),nt.current=null)},[V,ne]),Rr=(0,k.useCallback)((oe,xt,Q)=>{let Kt=je.current;Ht("overlay_timeout"),Kt&&ne.error({...Kt,popupCapability:V.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Zt(xt,{...Q,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:"overlay_timeout"}),at(!0),nr(),$t()},[Ht,$t,Zt,V,it,nr,ne]),Xe=(0,k.useCallback)(()=>{V.markAvailable();let oe=je.current;oe&&(X.current=oe.attempt,ne.log({...oe,popupCapability:V.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[V,ne]),{finishAttempt:or,generationRef:Er,invalidateAttempt:Jn,isAttemptCurrent:Ur,isAttemptInvalidated:zr,startAttempt:Nn}=Pa(Rr,{onHandoffObserved:Xe}),cn=(0,k.useCallback)(()=>(at(!1),Nn("paypal")),[Nn]),ar=(0,k.useCallback)(oe=>{Jn(oe?.generation),oe?.showRetry&&at(!0),oe?.remount&&nr(),oe?.focus!==!1&&$t()},[$t,Jn,nr]),he=oe=>{let xt=Jt.current;return xt&&en.current.set(oe,xt),oe};(0,k.useEffect)(()=>{Dt.current!==He&&(Dt.current=He,pr.current=!1,Mt.current=!1,D(!1),pt(!1),be(!1),Qr.current?.("loading"))},[He]),(0,k.useEffect)(()=>{(0,Ke.invokeMerchantCallback)(()=>rr.current?.(fe&&!vt))},[fe,vt]);let Cr=(0,qe.normalizeGatewayEnvironment)(p);(0,k.useEffect)(()=>{let oe={attempt:Er.current+1,inAppBrowser:Ee.inAppBrowser,appFamily:Ee.appFamily,popupCapability:V.current(),presentationMode:it},xt=()=>({...je.current??oe,popupCapability:V.current()}),Q={error:g=>ne.error({...g,...xt()}),log:g=>ne.log({...g,...xt()}),performance:g=>ne.performance({...g,...xt()}),terminal:g=>ne.terminal({...g,...xt()}),startTiming:ne.startTiming,elapsed:ne.elapsed},Kt=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",ir=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(z(`mount clientId=${Kt} env=${p??"(unset)"}\u2192${Cr??"live"} ccy=${m} sub=${h}`),z(`ua=${ir.slice(0,80)}${ir.length>80?"\u2026":""}`),!l){z("FAIL: clientId empty \u2014 gateway misconfigured"),be(!0),Q.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(!K.current){z("FAIL: containerRef not attached");return}Le.current=Q.startTiming(),Q.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=!1,Vt=!1,ae=()=>Pe||Vt,Nt=g=>{let f=et.current,O=f?g:"torn_down";f&&z(`onError ignored reason=${O}`),Br.take(kt.current)&&Q.log({name:ti,stage:"provider_ready",reason:O,provider:"paypal",paymentMethodCategory:"paypal"})},br=()=>kt.current===e?"stale_attempt":"session_changed",qr=We?Be:void 0,Qt,Un=!1,Zn=()=>{Qt=(0,qe.generateIdempotencyKey)(),Qt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Un=!0},zn=null,qn=!1,Qn=null,po=!1,mo=()=>{!Qn||po||(po=!0,Qn.close().catch(()=>{}))},Dr=!1,eo=!1,fn=K.current,zt=null,tn=null,rn=[],dn=null,nn=!1,ut=!1,mr=null,sr=g=>{if(!g||typeof g.getBoundingClientRect!="function")return"(no rect)";let f=g.getBoundingClientRect();return`${Math.round(f.width)}\xD7${Math.round(f.height)}`},Yr=g=>{if(!g)return"(empty)";try{let f=new URL(g,typeof window>"u"?"https://localhost":window.location.href),O=f.pathname.toLowerCase();return O.includes("checkcaptcha")||O.includes("captcha")?`CAPTCHA(${f.host}${O})`:O.includes("risk")||O.includes("challenge")?`RISK(${f.host}${O})`:O.includes("smart/buttons")?`smart-buttons(${f.host})`:`${f.host}${O}`.slice(0,100)}catch{return g.slice(0,80)}},ho=g=>{let f=g.getAttribute("src"),O=g.getAttribute("srcdoc"),Ce=g.getAttribute("name"),_e=g.getAttribute("sandbox"),L=[];return f&&L.push(`src=${Yr(f)}`),O&&L.push(`srcdoc[${O.length}ch]`),!f&&!O&&L.push("src=(empty) srcdoc=(empty)"),Ce&&L.push(`name=${Ce.slice(0,40)}`),_e!==null&&L.push(`sandbox="${_e.slice(0,40)}"`),L.join(" ")},to=g=>{if(!(g instanceof HTMLIFrameElement))return"";try{let f=g.contentDocument;if(!f)return"cd=null";let O=f.body?.children.length??0,Ce=f.body?.innerHTML.length??0,_e=f.head?.innerHTML.length??0;return`cd=same-origin readyState=${f.readyState} body[${O}children,${Ce}ch] head[${_e}ch]`}catch(f){return`cd=cross-origin(${f.message.slice(0,30)})`}},In=[],un=g=>{if(ae())return;let f=g.message??String(g.error??"(no message)");f&&(f.toLowerCase().includes("paypal")||f.toLowerCase().includes("zoid")||f.toLowerCase().includes("postrobot")||f.toLowerCase().includes("storage"))&&(z(`window:error ${f.slice(0,140)}`),In.push(f))},Ir=g=>{if(ae())return;let f=g.reason instanceof Error?g.reason.message:String(g.reason??"(no reason)");f&&(f.toLowerCase().includes("paypal")||f.toLowerCase().includes("zoid")||f.toLowerCase().includes("postrobot")||f.toLowerCase().includes("storage"))&&(z(`window:rejection ${f.slice(0,140)}`),In.push(f))},ro={value:0},jr=()=>{zt?.disconnect(),zt=null,tn?.disconnect(),tn=null;for(let g of rn.splice(0))clearTimeout(g);ut=!1,nn&&typeof window<"u"&&(window.removeEventListener("error",un),window.removeEventListener("unhandledrejection",Ir)),nn=!1},q=()=>{if(!(nn||ae()||Dr)){if(nn=!0,In.length=0,ro.value=0,typeof window<"u"&&(window.addEventListener("error",un),window.addEventListener("unhandledrejection",Ir)),typeof PerformanceObserver<"u")try{tn=new PerformanceObserver(g=>{if(!ae())for(let f of g.getEntries()){if(!f.name.toLowerCase().includes("paypal"))continue;ro.value+=1;let O=Math.round(f.duration);z(`net ${O}ms ${f.name.slice(0,90)}`)}}),tn.observe({type:"resource",buffered:!0})}catch{}mr?.()}},j=()=>{dn&&(clearTimeout(dn),dn=null)},ie=()=>{jr(),j()},we={setEnabled:g=>{g?q():jr()}};W.current=we,U.current&&q();let mt=qe.isPayPalTeardownMessage,Gt=g=>{if(ae()||mt(g))return;let f=(0,So.applyFriendlyMessageOverride)(g)??g;(0,Ke.invokeMerchantCallback)(()=>tr.current?.(f))},Ie=(g,f)=>{if(Pe||qn)return;qn=!0,Vt=!0,ie(),mo();let O=gd({kind:g,generationActive:!0,automaticRetryAllowed:xe,automaticRetryUsed:pr.current});if(O.action==="retry"){pr.current=!0,D(!1),gt(!1),pt(!0),Qr.current?.("retrying"),zn=setTimeout(()=>{Pe||ot(Ce=>Ce+1)},pd);return}if(D(!1),gt(!1),pt(!1),be(!0),O.action!=="ignore"){if(Qr.current?.("exhausted"),O.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",f);return}if(O.report){let Ce=(0,ke.classifyExternalMethodFailure)({code:Bl(g,f),message:f},{inAppBrowser:Ee.inAppBrowser,handoffObserved:!1});Ce.popupBlocked&&V.markBlocked(),Q.error({errorCode:Ce.popupBlocked?Ce.errorCode:O.report.errorCode,stage:O.report.stage,operationOutcome:O.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:Ce.terminalReason})}Mt.current||(Mt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Bl(g,f)))}};be(!1);let de=async(g,f=Jt.current)=>{if(ae())return;let O=f?.sessionId??e;if(Ut.current){await Ut.current(g,{sessionId:O,accountPatch:f?.accountPatch,nonce:f?.nonce});return}let Ce=Q.startTiming();Q.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let _e=()=>{Q.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"processing",durationMs:Q.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let L=(0,qe.buildPayPalProcessPaymentRequest)({body:g,sessionId:O,nonce:f?.nonce??Kr.current,accountPatch:f?.accountPatch,session:Xt.current,email:yn.current}),yr=await new oi.PaymentAPI(It,{telemetry:!1}).processPayment(L.userId,L.params);if(yr.ok){if(Vt||Pe&&et.current)return;_e(),Q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ke.invokeMerchantCallback)(()=>Fr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ae())return;let Tr=await yr.json().catch(()=>null),bt=(0,qe.describePayPalProcessFailure)(Tr),pn=bt.message;_e(),yr.status===400&&(typeof Tr?.declineCode=="string"||!Array.isArray(Tr?.fields))?Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):yr.status===400||yr.status===422?Q.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):Q.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:hd(yr.status),failureCategory:yr.status>=500?"server_error":void 0}),Gt(pn),(0,Ke.invokeMerchantCallback)(()=>Wt.current?.(Sr("paypal",pn,{code:bt.code,declineCode:bt.declineCode})));return}catch(L){if(ae())return;_e(),Q.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ct=(0,qe.friendlyPayPalFailureMessage)(L instanceof Error?L.message:void 0);Gt(Ct),(0,Ke.invokeMerchantCallback)(()=>Wt.current?.(Sr("paypal",Ct)));return}},ee=()=>new qe.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ve=g=>ae()?Promise.reject(ee()):Promise.resolve(g),te=async g=>{if(g.ok){Q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ke.invokeMerchantCallback)(()=>Fr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let f=await g.json().catch(()=>null),O=(0,qe.describePayPalProcessFailure)(f);Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ke.invokeMerchantCallback)(()=>Wt.current?.(Sr("paypal",O.message,{code:O.code,declineCode:O.declineCode})))},tt=()=>{let g=Jt.current;Ht("approved"),g&&(Pr.current.delete(g.surfaceKey),or(g.generation)),Jt.current=null},re=async g=>{if(ae())throw ee();Un||Zn();let f=Jt.current,O=f?.sessionId??e,Ce=f?.nonce??Kr.current;Q.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let _e;try{_e=await new oi.PaymentAPI(It,{telemetry:!1}).createSessionIntent(O,Ce??"",(0,qe.buildPayPalSessionIntentRequest)(qr),{idempotencyKey:Qt})}catch(L){throw Q.error({...(0,qe.classifyTelemetryFailure)(L,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),L}if(ae())throw ee();if((0,qe.isSettledSessionIntent)(_e))throw await te(_e.response),tt(),new qe.FloPayError("PayPal checkout already settled.","api_error",{code:Fl});if(_e.provider!=="paypal"||_e.providerObjectType!==Be)throw new Error(g);return Q.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),_e.providerObjectId},Je=(g,f)=>{let O=f?.nonce??Kr.current;if(!O)return;let Ce=f?.sessionId??e,_e=(0,qe.resolvePayPalDeclineReason)(g);new oi.PaymentAPI(It,{telemetry:!1}).reportSessionIntentDecline(Ce,O,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:_e}).catch(()=>{})},Ze=Ue;z("loadScript:scheduled (deferred 1 tick)");let At=null,_r=setTimeout(()=>{if(Pe){z("loadScript:skipped (cancelled before defer ran)");return}z("loadScript:start");let g=Cr==="live"?"production":Cr,f={};Be==="subscription"?f={intent:"subscription",vault:!0}:Be==="order"&&(f={intent:"capture"}),At=(0,Dl.loadScript)({clientId:l,currency:m,...f,...g?{environment:g}:{},...g==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let O=!1;At.then(Ce=>{if(O=!0,z(`loadScript:resolved inactive=${ae()} ns=${!!Ce} buttons=${!!Ce?.Buttons}`),ae())return;if(!Ce?.Buttons){z("FAIL: namespace missing Buttons factory"),Ie("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}Q.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"provider_ready",durationMs:Q.elapsed(Le.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Q.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let _e=async(se,ht)=>{if(ae()||Ae.current!==Ze)return;let Rt=se.vaultSetupToken??se.subscriptionID??se.orderID??"",Ft=Rt?en.current.get(Rt):Pr.current.get(Ze);if(!(!Ft||!Ur(Ft.generation))&&or(Ft.generation)){en.current.delete(Rt),Pr.current.delete(Ft.surfaceKey),Ht("approved");try{if(gt(!0),(0,Ke.invokeMerchantCallback)(()=>tr.current?.(null)),!Rt)throw new qe.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let rt=(0,qe.resolvePayPalApprovalIdentity)({accountPatch:Ft.accountPatch,email:yn.current,billingName:Hr.current,session:Xt.current});if((0,qe.needsPayPalPayerDetails)(rt))try{rt=(0,qe.mergePayPalPayerIdentity)(rt,await ht?.order?.get?.())}catch{}if((Tt.current||Se)&&!(0,qe.isValidEmail)(rt.email)){let Ot=await N("PayPal",rt);if(!Ot)return;rt=Ot}(0,qe.isValidEmail)(rt.email)&&(Ft.accountPatch=(0,vn.compactBuyerIdentity)({...Ft.accountPatch,...rt}),await Tt.current?.(rt));let Xr=(0,qe.buildPayPalTokenizedBody)(Rt,qr);await de(Xr,Ft)}catch(rt){Gt(rt instanceof Error?rt.message:"PayPal capture failed.")}finally{ae()||gt(!1)}}},L=se=>{let ht=pe?()=>ve(pe):()=>re(se);return async()=>he(await ht())},Ct=Ce.Buttons({style:{layout:"horizontal",height:ai,tagline:!1},...it==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(se,ht)=>{if(ae()){await ht.reject();return}Zn();let Rt=Ln.current,Ft={};if(Rt)try{let Ot=await Rt("paypal");if(ae()){await ht.reject();return}if(!Ot.proceed){Jt.current=null,Pr.current.delete(Ze),await ht.reject();return}Ft={sessionId:Ot.sessionId,accountPatch:Ot.accountPatch,nonce:Ot.nonce}}catch(Ot){z(`onClick:runBeforeButtonClick rejected msg=${(Ot instanceof Error?Ot.message:String(Ot)).slice(0,120)}`),Jt.current=null,Pr.current.delete(Ze),await ht.reject();return}(0,Ke.invokeMerchantCallback)(()=>Nr.current?.("paypal"));let rt=cn(),Xr={generation:rt,surfaceKey:Ze,...Ft};Jt.current=Xr,Pr.current.set(Ze,Xr),je.current={...oe,attempt:rt},await ht.resolve(),Q.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Q.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nt.current=Q.startTiming()},createOrder:Be==="order"?L("Failed to create PayPal order."):void 0,createSubscription:Be==="subscription"?L("Failed to create PayPal subscription."):void 0,createVaultSetupToken:Be==="setup_token"?async()=>he(await re("Failed to create PayPal setup token.")):void 0,onApprove:_e,onCancel:()=>{if(ae())return;let se=Pr.current.get(Ze)??Jt.current,ht=se&&Ur(se.generation)?(0,qe.buildPayPalCancelEvent)(se.sessionId??e,qr):null;se&&Pr.current.delete(se.surfaceKey),Jt.current=null,Ht("cancelled"),Q.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),De.current=!0,ar({generation:se?.generation,remount:!0,focus:!1}),ht&&(0,Ke.invokeMerchantCallback)(()=>_t.current?.(ht))},onError:se=>{if(se instanceof qe.FloPayError&&se.code===Fl)return;let ht=se instanceof Error?se.message:"PayPal failed to render.";if(ae()||Ae.current!==Ze){mt(ht)||Nt(br());return}if(Dr){let Rt=Pr.current.get(Ze)??Jt.current;if(!Rt||!Ur(Rt.generation)){if(mt(ht)){!Rt&&!zr()&&or();return}Nt(Rt||zr()?"stale_attempt":"no_current_attempt");return}if(z(`onError rendered=${Dr} msg=${ht.slice(0,120)}`),mt(ht)){or(Rt.generation);return}let{errorCode:Ft,popupBlocked:rt,providerDeclined:Xr,terminalReason:Ot}=(0,ke.classifyExternalMethodFailure)(se,{inAppBrowser:Ee.inAppBrowser,handoffObserved:X.current===Rt.generation});if(rt&&V.markBlocked(),Ht(Ot),Xr){Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ot}),Je(se,Rt),(0,Ke.invokeMerchantCallback)(()=>Wt.current?.(Sr("paypal",ht))),Pr.current.delete(Rt.surfaceKey),Jt.current=null,or(Rt.generation);return}Q.error({errorCode:Ft,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ot}),Pr.current.delete(Rt.surfaceKey),Jt.current=null,ar({generation:Rt.generation,remount:!0,showRetry:!0,focus:!0}),Zt(se,{code:"paypal_runtime_failed",popupBlocked:rt,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:Ot});return}z(`onError rendered=${Dr} msg=${ht.slice(0,120)}`),Ie(mt(ht)?"teardown":"pre_ready_callback",ht)}}),yr=Ct.isEligible();if(z(`isEligible=${yr}`),Q.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!yr){D(!1),Ie("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}eo=!0,Qn=Ct,mr=()=>{if(!nn||ut||ae()||Dr)return;ut=!0,z(`container:dims ${sr(fn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(zt=new MutationObserver(ht=>{if(!ae()){for(let Rt of ht)if(Rt.type==="childList")Rt.addedNodes.forEach(Ft=>{if(!(Ft instanceof Element))return;let rt=Ft.tagName.toLowerCase(),Xr=(Ft.getAttribute("title")??"").slice(0,40),Ot=rt==="iframe"?` ${ho(Ft)}`:"";z(`child+ ${rt}${Xr?` title="${Xr}"`:""}${Ot} dims=${sr(Ft)}`)});else if(Rt.type==="attributes"&&Rt.target instanceof Element){let Ft=Rt.target;if(Ft.tagName.toLowerCase()!=="iframe")continue;let rt=Rt.attributeName;(rt==="src"||rt==="srcdoc")&&z(`attr~ iframe ${rt}=${rt==="srcdoc"?`[${(Ft.getAttribute("srcdoc")??"").length}ch]`:Yr(Ft.getAttribute("src"))} dims=${sr(Ft)}`)}}}),zt.observe(fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let se=ht=>{if(ae()||Dr)return;let Rt=fn.querySelectorAll("iframe"),Ft=typeof document<"u"&&"hasStorageAccess"in document;z(`watchdog:${ht} container=${sr(fn)} children=${fn.childElementCount} iframes=${Rt.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Ft} paypalNetRequests=${ro.value}`),Rt.forEach((rt,Xr)=>{let Ot=(rt.getAttribute("title")??"").slice(0,40);z(` iframe[${Xr}] ${sr(rt)}${Ot?` title="${Ot}"`:""} ${ho(rt)}`);let Vr=to(rt);Vr&&z(` ${Vr}`)}),In.length===0&&z(" (no PayPal/zoid window errors captured)")};rn.push(setTimeout(()=>se("3s"),3e3)),rn.push(setTimeout(()=>se("8s"),8e3)),rn.push(setTimeout(()=>se("15s"),15e3))},mr(),z("render:start");let bt=Q.startTiming();dn=setTimeout(()=>{ae()||Dr||(z("watchdog:11s retryable render timeout"),Ie("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},md);let pn=Ct.render(fn);(async()=>{try{if(await pn,z(`render:resolved inactive=${ae()}`),ie(),ae()){mo();return}Dr=!0,D(!0),pt(!1),Qr.current?.("ready"),Q.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"checkout_render",durationMs:Q.elapsed(bt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(se){let ht=se instanceof Error?se.message:"PayPal failed to render.";z(`render:rejected msg=${ht.slice(0,120)}`),ie(),Ie(mt(ht)?"teardown":"render_rejected",ht)}})()}).catch(Ce=>{let _e=Ce instanceof Error?Ce.message:"PayPal operation failed.";z(`provider:failed msg=${_e.slice(0,120)}`);let L="script_rejected";O&&mt(_e)?L="teardown":O&&eo&&(L="render_rejected"),Ie(L,_e)})},0);return()=>{Pe=!0,clearTimeout(_r),zn&&clearTimeout(zn),ie(),W.current===we&&(W.current=null),mo(),nt.current=null,je.current=null}},[xe,It,l,m,p,Be,it,We,e,pe,Ue,ne,N,Se,z,Ht]);let Gr=B?(0,Cn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:vt?"#fef2f2":"#f3f4f6",border:`1px solid ${vt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${fe} failed=${vt})`,ce.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return
|
|
3
|
+
${ce.join(`
|
|
4
|
+
`)}`]}):null;return vt&&!c?B?(0,Cn.jsx)("div",{children:Gr}):null:(0,Cn.jsxs)("div",{children:[Gr,ct&&(0,Cn.jsx)(Wo,{identity:ct.identity,methodLabel:ct.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Fe,onCancel:()=>Fe(null)}),(0,Cn.jsxs)("div",{"aria-hidden":ge||ct?!0:void 0,style:ge||ct?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ai},children:[!fe&&!ge&&(0,Cn.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,Cn.jsx)("div",{ref:K,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ai,display:"flex",opacity:fe?1:0},"aria-busy":M||P},Ue)]},Ue),Qe&&(0,Cn.jsx)("button",{ref:Ve,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:vr,style:yd,children:"Try PayPal again"})]})}function va(e){return(0,Cn.jsx)(Ol,{...e})}function Ll(e){return(0,Cn.jsx)(Ol,{...e})}var Ca=require("react/jsx-runtime");function Ko({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,Ca.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,Ca.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Ca.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 yt=require("@flopay/shared");var hr=require("react/jsx-runtime");var Pd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function sn({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:s="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:p=Pd}){let m={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,hr.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,hr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...p.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,hr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,hr.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,hr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,hr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,hr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,hr.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,hr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,hr.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,hr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,hr.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,hr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,hr.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,hr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:p.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&s]}),e==="success"&&l!==null&&(0,hr.jsx)("p",{style:m,children:l}),e==="error"&&t&&(0,hr.jsx)("p",{style:m,children:t}),(0,hr.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 Dl=require("@flopay/shared"),Fr=require("react");var Ol=require("react/jsx-runtime");function Sa({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,l]=(0,Fr.useState)(e instanceof Promise?null:e),[p,m]=(0,Fr.useState)(t instanceof Promise||!t?null:t),f=(0,Fr.useRef)(null),S=(0,Fr.useRef)(null),C=Ko(n);(0,Fr.useEffect)(()=>{C({class:"lifecycle",name:"checkout.mount"})},[C]),(0,Fr.useEffect)(()=>{s&&C({class:"lifecycle",name:"sdk.initialize.ready"})},[C,s]),(0,Fr.useEffect)(()=>{if(s)return vr(s)?.subscribe?.(C)},[C,s]),(0,Fr.useEffect)(()=>{if(!(!p||p===s))return vr(p)?.subscribe?.(C)},[C,s,p]),(0,Fr.useEffect)(()=>{if(!s)return;let E=vr(s);return f.current=E?.beginCheckout()??E?.now()??0,E?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{E?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Fr.useEffect)(()=>{let E=!1;return e instanceof Promise?e.then(Z=>{E||l(Z)},()=>{E||C({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{E=!0}},[C,e]),(0,Fr.useEffect)(()=>{let E=!1;if(!t){m(null);return}return t instanceof Promise?t.then(Z=>{E||m(Z)},()=>{E||C({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{E=!0}},[C,t]),(0,Fr.useEffect)(()=>{if(!s||S.current===s)return;S.current=s;let E=vr(s);E?.log({name:"checkout.rendered",stage:"checkout_render"}),C({class:"lifecycle",name:"checkout.rendered"}),E?.performance({stage:"checkout_render",durationMs:E.elapsed(f.current??0),durationMode:"machine"})},[C,s]);let R=(0,Dl.resolveBillingApiUrl)(r?.billingApiUrl),H=(0,Fr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:R,emitInstrument:C}),[s,p,R,C]);return(0,Ol.jsx)(gn.Provider,{value:H,children:a})}var Tn=require("@flopay/shared");async function ai(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 vn=require("@flopay/js"),it=require("@flopay/shared");var ka="card";async function hd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:s??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 Pd(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:s}=await e.confirmCardPayment(t,r);return{error:s,intent:a??null}}function Yo(e){return new it.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function vd(){return new it.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function rs(e,t){return Object.assign(e,{checkoutMethod:t})}function no(e,t){let r=e instanceof it.FloPayError?e:new it.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 wa(e,t){try{return await e()}catch(r){throw no(r,t)}}function Nl(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 Ul(e){return(0,vn.runSavedCardChallenge)(e)}async function Xo(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,l=new vn.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,vn.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:S=>jn({type:S.declineReason??"authorization_declined",gatewayErrorCode:S.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(S){if(a.aborted||S instanceof Error&&S.name==="AbortError")throw S instanceof it.FloPayError&&S.code==="three_ds_aborted"?S:Yo(S);if(!(S instanceof it.FloPayError)||S.code!=="three_ds_timeout"&&S.code!=="checkout_processing_timeout")throw S;try{m=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(R){if(a.aborted)throw Yo(R);if(!(R instanceof it.FloPayError)||R.code!=="checkout_processing_timeout")throw R}let C=m&&uo(m,t.session);if(!eo(C)&&C?.status!=="expired"){if(t.telemetry){let R=new vn.PaymentAPI(r);try{R.reportThreeDsAbandoned(n)}finally{R.destroy()}}throw vd()}}let f=m&&uo(m,t.session);if(!eo(f))throw jo(f);return{...Qn(f,n),checkoutMethod:"card"}}function jn(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,s=(0,bo.applyFriendlyMessageOverride)(a)??a,l=rs(new it.FloPayError(s,"api_error",{code:e?.code??(0,it.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,it.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(l.orderId=e.orderId),l}function ts(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ii(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function zl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ii(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,s=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let p of s)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||ii(p)))return p;let l=a.gateways;if(l&&typeof l=="object"){let p=l.stripe;if(p&&typeof p=="object"){let m=p,f=[m.stripeClientSecret,m.clientSecret];for(let S of f)if(typeof S=="string"&&S.length>0&&(!t?.requirePaymentIntentClientSecret||ii(S)))return S}}}}async function Cd({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=zl(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let p=(await new vn.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(ii(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function Jo({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:l}){let p=e.replace(/\/+$/,""),m=t??r.id,f=n??r.clientSecret,S=r.customer?.id??r.accountData?.userId??"",C=r.customer?.email??r.accountData?.email??"",R=r.customer?.firstName??r.accountData?.firstName??"",H=r.customer?.lastName??r.accountData?.lastName??"",E=r.customer?.country??r.accountData?.country??void 0,Z=r.customer?.zip??r.accountData?.zip??void 0,y=await new vn.PaymentAPI(p,l===!1?{telemetry:!1}:void 0).processPayment(S,{sessionId:m,nonce:f,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:S,email:C,firstName:R,lastName:H,country:E,zip:Z},returnUrl:s??ts(r)});if(y.ok){let v=typeof y.json=="function"?await y.json().catch(()=>null):null;if((0,it.isAuthorizationOnlySession)(r)||v?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof v?.paymentId=="string"?v.paymentId:r.paymentId,sessionId:typeof v?.sessionId=="string"?v.sessionId:m,authorizationExpiresAt:typeof v?.authorizationExpiresAt=="string"?v.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:ga(a),checkoutMethod:Ll(a,r)}};let xe=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...xe?{paymentIntentId:xe}:{},paymentMethodId:ga(a),checkoutMethod:Ll(a,r)}}}let g;try{g=await y.json()}catch(v){throw new it.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status,cause:v})}if(g?.type==="3ds_required"&&typeof g.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:g.nextActionRedirectUrl};if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let v=zl(g);if(!v)throw new it.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status});return{type:g.type,threeDSecureToken:v,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let v=await Cd({billingApiUrl:p,sessionId:m,nonce:f,responseJson:g});if(v)return v;throw rs(new it.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let he=new it.FloPayError(g?.message??"Payment failed. Please try again.","api_error",{code:g?.code??g?.gatewayErrorCode,declineCode:g?.declineCode??g?.gatewayDeclineReason,statusCode:y.status});throw Object.assign(he,{telemetryOutcome:(0,it.classifyPaymentRejection)(y.status,g)})}async function si(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:l,returnUrl:p,telemetry:m,signal:f}){let S=t?.getRawProvider();if(!S)throw no(new it.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw rs(new it.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let C=(0,it.isSetupIntentClientSecret)(e.threeDSecureToken),R=null,H=e.paymentMethodId,E=await wa(()=>hd(S,e.threeDSecureToken,C),"card");if(E){if(E.error)throw no(new it.FloPayError(E.error.message??`Failed to retrieve 3DS ${C?"setup":"payment"} status.`,"api_error",{code:E.error.code}),"card");let M=E.intent;!H&&M?.payment_method&&(typeof M.payment_method=="string"?H=M.payment_method:"id"in M.payment_method&&(H=M.payment_method.id??void 0))}let Z=H?await wa(()=>Pd(S,e.threeDSecureToken,{payment_method:H,return_url:p??ts(l)??window.location.href},C),"card"):null;if(Z){if(Z.error)throw no(new it.FloPayError(Z.error.message??"3DS authentication failed.","api_error",{code:Z.error.code}),"card");R=Z.intent}else{let M=await wa(()=>S.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(M.error)throw no(new it.FloPayError(M.error.message??"3DS authentication failed.","api_error",{code:M.error.code}),"card");R=(C?M.setupIntent:M.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let M=await Jo({billingApiUrl:a,sessionId:s,session:l,telemetry:m,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:p});return M.type==="success"?{...M.result,paymentIntentId:M.result.paymentIntentId??R.id,paymentMethodId:M.result.paymentMethodId??H}:M.type==="next_action_required"?Xo(M,{billingApiUrl:a,sessionId:s??l.id,session:l,signal:f}):si(M,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:l,returnUrl:p,telemetry:m,signal:f})}throw no(new it.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let C=(r??t)?.getRawProvider();if(!C)throw no(new it.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:H}=await wa(()=>C.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(H)throw no(new it.FloPayError(H.message??"PayPal authorization failed.","api_error",{code:H.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await wa(()=>C.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??ts(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(R)throw no(new it.FloPayError(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new it.FloPayError("Unsupported payment redirect state.","api_error")}function Ra(e){if(e instanceof it.FloPayError){let n=(0,bo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new it.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,bo.applyFriendlyMessageOverride)(t)??t;return new it.FloPayError(r,"api_error")}function ns(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,it.isMountableVaultBlock)(e.data.session?.vault)||(0,En.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new it.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 Ll(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,En.canRecoverHostedCardForm)(t)?"card":void 0}async function os({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let s=t&&t!==e?t:void 0,[l,p]=await Promise.all([(0,vn.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,vn.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(f=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",f),null)):Promise.resolve(null)]);if(!l)throw new it.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=l),{flopay:l,paypalFlopay:m}}var xn=require("@flopay/js"),d=require("@flopay/shared"),ir=require("@stripe/react-stripe-js"),o=Gi(require("react"),1);function ko(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function li(e,t){if(e)return{error:r=>e.error(ko(t,r)),log:r=>e.log(ko(t,r)),performance:r=>e.performance(ko(t,r)),terminal:r=>e.terminal(ko(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 oo=require("@flopay/shared"),jl=require("react");var ql={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 Tr=require("react/jsx-runtime"),bd=`
|
|
9
|
+
`})]})})}var Nl=require("@flopay/shared"),Lr=require("react");var Ul=require("react/jsx-runtime");function ba({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,l]=(0,Lr.useState)(e instanceof Promise?null:e),[p,m]=(0,Lr.useState)(t instanceof Promise||!t?null:t),h=(0,Lr.useRef)(null),R=(0,Lr.useRef)(null),w=Ho(n);(0,Lr.useEffect)(()=>{w({class:"lifecycle",name:"checkout.mount"})},[w]),(0,Lr.useEffect)(()=>{s&&w({class:"lifecycle",name:"sdk.initialize.ready"})},[w,s]),(0,Lr.useEffect)(()=>{if(s)return wr(s)?.subscribe?.(w)},[w,s]),(0,Lr.useEffect)(()=>{if(!(!p||p===s))return wr(p)?.subscribe?.(w)},[w,s,p]),(0,Lr.useEffect)(()=>{if(!s)return;let _=wr(s);return h.current=_?.beginCheckout()??_?.now()??0,_?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{_?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Lr.useEffect)(()=>{let _=!1;return e instanceof Promise?e.then(Z=>{_||l(Z)},()=>{_||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{_=!0}},[w,e]),(0,Lr.useEffect)(()=>{let _=!1;if(!t){m(null);return}return t instanceof Promise?t.then(Z=>{_||m(Z)},()=>{_||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{_=!0}},[w,t]),(0,Lr.useEffect)(()=>{if(!s||R.current===s)return;R.current=s;let _=wr(s);_?.log({name:"checkout.rendered",stage:"checkout_render"}),w({class:"lifecycle",name:"checkout.rendered"}),_?.performance({stage:"checkout_render",durationMs:_.elapsed(h.current??0),durationMode:"machine"})},[w,s]);let I=(0,Nl.resolveBillingApiUrl)(r?.billingApiUrl),Y=(0,Lr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:I,emitInstrument:w}),[s,p,I,w]);return(0,Ul.jsx)(Pn.Provider,{value:Y,children:a})}var Bn=require("@flopay/shared");async function ii(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 bn=require("@flopay/js"),st=require("@flopay/shared");var wa="card";async function vd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:s??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 Cd(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:s}=await e.confirmCardPayment(t,r);return{error:s,intent:a??null}}function Go(e){return new st.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function bd(){return new st.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function rs(e,t){return Object.assign(e,{checkoutMethod:t})}function so(e,t){let r=e instanceof st.FloPayError?e:new st.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Sa(e,t){try{return await e()}catch(r){throw so(r,t)}}function ql(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 jl(e){return(0,bn.runSavedCardChallenge)(e)}async function Yo(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,l=new bn.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,bn.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:R=>Kn({type:R.declineReason??"authorization_declined",gatewayErrorCode:R.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(R){if(a.aborted||R instanceof Error&&R.name==="AbortError")throw R instanceof st.FloPayError&&R.code==="three_ds_aborted"?R:Go(R);if(!(R instanceof st.FloPayError)||R.code!=="three_ds_timeout"&&R.code!=="checkout_processing_timeout")throw R;try{m=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(I){if(a.aborted)throw Go(I);if(!(I instanceof st.FloPayError)||I.code!=="checkout_processing_timeout")throw I}let w=m&&fo(m,t.session);if(!oo(w)&&w?.status!=="expired"){if(t.telemetry){let I=new bn.PaymentAPI(r);try{I.reportThreeDsAbandoned(n)}finally{I.destroy()}}throw bd()}}let h=m&&fo(m,t.session);if(!oo(h))throw qo(h);return{...no(h,n),checkoutMethod:"card"}}function Kn(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,s=(0,So.applyFriendlyMessageOverride)(a)??a,l=rs(new st.FloPayError(s,"api_error",{code:e?.code??(0,st.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,st.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(l.orderId=e.orderId),l}function ts(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function si(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Vl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||si(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,s=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let p of s)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||si(p)))return p;let l=a.gateways;if(l&&typeof l=="object"){let p=l.stripe;if(p&&typeof p=="object"){let m=p,h=[m.stripeClientSecret,m.clientSecret];for(let R of h)if(typeof R=="string"&&R.length>0&&(!t?.requirePaymentIntentClientSecret||si(R)))return R}}}}async function Sd({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Vl(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let p=(await new bn.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(si(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function Xo({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:l}){let p=e.replace(/\/+$/,""),m=t??r.id,h=n??r.clientSecret,R=r.customer?.id??r.accountData?.userId??"",w=r.customer?.email??r.accountData?.email??"",I=r.customer?.firstName??r.accountData?.firstName??"",Y=r.customer?.lastName??r.accountData?.lastName??"",_=r.customer?.country??r.accountData?.country??void 0,Z=r.customer?.zip??r.accountData?.zip??void 0,y=await new bn.PaymentAPI(p,l===!1?{telemetry:!1}:void 0).processPayment(R,{sessionId:m,nonce:h,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:R,email:w,firstName:I,lastName:Y,country:_,zip:Z},returnUrl:s??ts(r)});if(y.ok){let S=typeof y.json=="function"?await y.json().catch(()=>null):null;if((0,st.isAuthorizationOnlySession)(r)||S?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof S?.paymentId=="string"?S.paymentId:r.paymentId,sessionId:typeof S?.sessionId=="string"?S.sessionId:m,authorizationExpiresAt:typeof S?.authorizationExpiresAt=="string"?S.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:fa(a),checkoutMethod:zl(a,r)}};let xe=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...xe?{paymentIntentId:xe}:{},paymentMethodId:fa(a),checkoutMethod:zl(a,r)}}}let P;try{P=await y.json()}catch(S){throw new st.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status,cause:S})}if(P?.type==="3ds_required"&&typeof P.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:P.nextActionRedirectUrl};if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let S=Vl(P);if(!S)throw new st.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status});return{type:P.type,threeDSecureToken:S,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let S=await Sd({billingApiUrl:p,sessionId:m,nonce:h,responseJson:P});if(S)return S;throw rs(new st.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new st.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:y.status});throw Object.assign(me,{telemetryOutcome:(0,st.classifyPaymentRejection)(y.status,P)})}async function li(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:l,returnUrl:p,telemetry:m,signal:h}){let R=t?.getRawProvider();if(!R)throw so(new st.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw rs(new st.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let w=(0,st.isSetupIntentClientSecret)(e.threeDSecureToken),I=null,Y=e.paymentMethodId,_=await Sa(()=>vd(R,e.threeDSecureToken,w),"card");if(_){if(_.error)throw so(new st.FloPayError(_.error.message??`Failed to retrieve 3DS ${w?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let A=_.intent;!Y&&A?.payment_method&&(typeof A.payment_method=="string"?Y=A.payment_method:"id"in A.payment_method&&(Y=A.payment_method.id??void 0))}let Z=Y?await Sa(()=>Cd(R,e.threeDSecureToken,{payment_method:Y,return_url:p??ts(l)??window.location.href},w),"card"):null;if(Z){if(Z.error)throw so(new st.FloPayError(Z.error.message??"3DS authentication failed.","api_error",{code:Z.error.code}),"card");I=Z.intent}else{let A=await Sa(()=>R.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(A.error)throw so(new st.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");I=(w?A.setupIntent:A.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let A=await Xo({billingApiUrl:a,sessionId:s,session:l,telemetry:m,tokenizedData:{id:I.id,type:"card",threeDSecureActionResultTokenId:I.id},returnUrl:p});return A.type==="success"?{...A.result,paymentIntentId:A.result.paymentIntentId??I.id,paymentMethodId:A.result.paymentMethodId??Y}:A.type==="next_action_required"?Yo(A,{billingApiUrl:a,sessionId:s??l.id,session:l,signal:h}):li(A,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:l,returnUrl:p,telemetry:m,signal:h})}throw so(new st.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let w=(r??t)?.getRawProvider();if(!w)throw so(new st.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:Y}=await Sa(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(Y)throw so(new st.FloPayError(Y.message??"PayPal authorization failed.","api_error",{code:Y.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:I}=await Sa(()=>w.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??ts(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(I)throw so(new st.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new st.FloPayError("Unsupported payment redirect state.","api_error")}function ka(e){if(e instanceof st.FloPayError){let n=(0,So.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new st.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,So.applyFriendlyMessageOverride)(t)??t;return new st.FloPayError(r,"api_error")}function ns(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,st.isMountableVaultBlock)(e.data.session?.vault)||(0,xn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new st.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function zl(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,xn.canRecoverHostedCardForm)(t)?"card":void 0}async function os({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let s=t&&t!==e?t:void 0,[l,p]=await Promise.all([(0,bn.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,bn.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(h=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",h),null)):Promise.resolve(null)]);if(!l)throw new st.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=l),{flopay:l,paypalFlopay:m}}var On=require("@flopay/js"),d=require("@flopay/shared"),cr=require("@stripe/react-stripe-js"),o=Gi(require("react"),1);function Ro(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ci(e,t){if(e)return{error:r=>e.error(Ro(t,r)),log:r=>e.log(Ro(t,r)),performance:r=>e.performance(Ro(t,r)),terminal:r=>e.terminal(Ro(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 lo=require("@flopay/shared"),$l=require("react");var Wl={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 xr=require("react/jsx-runtime"),wd=`
|
|
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 @@ ${ue.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
|
-
`,Zo=44;function Qo(){return(0,Tr.jsx)("style",{children:bd})}function Ea(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function Ia({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Tr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Tr.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,Tr.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 as(e){return e!=="unavailable"&&e!=="load_error"}function ci({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:l,backgroundColor:p,borderColor:m,textColor:f,borderRadius:S,fontFamily:C}){let R=(0,oo.resolveStripeMethodBrandVariant)(e,t),H=ql[e],[E,Z]=(0,jl.useState)(!1),M=!!H&&!E,y=R?.backgroundColor??p??"#ffffff",g=R?.borderColor??m??"#d1d5db",he=R?.textColor??f??"#262833";return(0,Tr.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:Zo,padding:"0 1rem",backgroundColor:y,color:he,border:`1px solid ${g}`,borderRadius:S??8,fontSize:"0.95rem",fontWeight:600,fontFamily:C,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,Tr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,oo.getStripeMethodDisplayName)(e)}\u2026`}):(0,Tr.jsxs)(Tr.Fragment,{children:[(0,Tr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,oo.hasVendoredStripeMethodLogo)(e)?8:0},children:[M?(0,Tr.jsx)("img",{src:H,alt:"","aria-hidden":"true",onError:()=>Z(!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&&R?.logoSvg?(0,Tr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:R.logoSvg}}):null,(0,Tr.jsx)("span",{children:(0,oo.getStripeMethodDisplayName)(e)})]}),s&&(0,Tr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:he,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,Tr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function di(e){let t=new Set(e.map(oo.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var ui={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},pi={type:"accordion",defaultCollapsed:!1,radios:"never"};function mi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:l,children:p}){return(0,Tr.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:s,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...l??{}},children:p})}var un=require("react");var _a=require("@flopay/shared"),Sd=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 wd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Sd.has(t.charAt(0).toLowerCase()+t.slice(1))}function kd(e,t){return typeof t=="number"&&t!==0&&!wd(e)?`${t}px`:String(t).trim()}function Vl(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]=kd(r,n)}}}var Ro=require("react/jsx-runtime"),is=new WeakSet;function po({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:l,containerStyle:p,onReady:m,onError:f,onValidation:S}){let C=(0,un.useRef)(null),R=(0,un.useRef)(m),H=(0,un.useRef)(f),E=(0,un.useRef)(S);R.current=m,H.current=f,E.current=S;let Z=(0,un.useRef)(s);Z.current=s;let M=(0,un.useRef)(null),y=l??void 0,g=(0,un.useRef)(y);g.current=y;let he=(0,un.useRef)(void 0);return(0,un.useEffect)(()=>{let v=C.current;if(!v)return;let xe=!0,I=!1,se=()=>{!xe||I||(I=!0,R.current?.())},Pe=e.on("ready",()=>{se()}),fe=e.on("error",B=>{H.current?.(B.message??"There was a problem loading the secure card form.")}),Ae=e.on("validation",B=>{E.current?.(B.message??null)}),st=g.current??(is.has(e)?null:void 0),Ke={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...Z.current?{theme:Z.current}:{},...st===void 0?{}:{submitLabel:st}};return M.current=Z.current??null,he.current=g.current,g.current!==void 0&&is.add(e),e.mount(v,Ke).then(()=>{se()}).catch(B=>{xe&&H.current?.(B instanceof Error?B.message:"Failed to load the secure card form.")}),()=>{xe=!1,Pe(),fe(),Ae(),e.unmount()}},[e,t,r,n,a]),So(()=>{let v=C.current;v&&Vl(v,p)},[p]),(0,un.useEffect)(()=>{s!==void 0&&(s===null&&M.current===null||(M.current=s,e.applyTheme?.(s)))},[e,s]),(0,un.useEffect)(()=>{y!==he.current&&(he.current=y,y!==void 0&&is.add(e),e.setSubmitLabel?.(y??null))},[e,y]),(0,Ro.jsx)("div",{ref:C,"data-testid":"flopay-vault-card-fields"})}function yi({label:e}){return(0,Ro.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,Ro.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,Ro.jsx)("span",{children:e}),(0,Ro.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var hs=require("@flopay/shared"),u=require("react/jsx-runtime"),Vn="flopay_stripe_resume",Wl="flopay_wallet_resume",ec="fw1",Rd="fw2",tc=300*1e3,Ed=900,Id="express_checkout_click_timeout",_d=25e3,Td=25e3,Md=1e4,Mn={provider:"paypal",paymentMethodCategory:"paypal"},xd="x-flopay-process-result-source",Ad="status";async function Fd(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 fi={},Ma=class{constructor(t){this.reason=t}};function Bd(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function sr(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 ys(e){return`${Rd}:${e}`}function gi(e){return sr(ys(e))}function hi(e,t){if(typeof window>"u")return null;let r=ys(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>tc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(gi(e),null):a}catch{return gi(e),null}}function Dd(e){return sr(ys(e.sessionId),e)}function $l(e,t,r){let n=hi(e,t);return!n||n.clientSecret!==r?!1:gi(e)}function ss(e,t,r){if(typeof window>"u")return;hi(e,t)?.clientSecret===r&&gi(e)}function Od(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ls(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":fa(e.status),a=Od(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Hl(e,t,r){let n=null;try{return await Promise.race([Rl(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Md),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Ld(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function rc(e){return e instanceof d.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Pi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new xn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw rc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var cs=d.STRIPE_PAYPAL_RESUME_KEY,Ta=new Map,Nd=250,Kl="Just a moment \u2014 we are finalizing your order. Please press pay again.",Ud="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function fs(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 vi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new xn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function zd(e){return e instanceof d.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function nc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,Vo.splitFullName)(r),l=s.firstName?s:(0,Vo.splitFullName)(n?.name);return(0,hn.compactBuyerIdentity)({email:(0,d.isValidEmail)(a)?a:n?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function qd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let l=nc({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,d.isValidEmail)(l.email)?l:s(a,l)}var xa=180,Gl=`flopay-card-enter ${xa}ms cubic-bezier(0, 0, 0.2, 1) both`,Yl=`flopay-card-exit ${xa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,jd=`flopay-buttons-enter ${xa}ms cubic-bezier(0, 0, 0.2, 1) both`,Vd=`flopay-buttons-exit ${xa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Wd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function gs(e){return(0,d.derivePrimaryTileStyle)(e)}var $d={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Hd(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 us={width:"100%",minHeight:Zo,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 Xl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ps(e){return e==="paypal"?"PayPal":(0,d.getStripeMethodDisplayName)(e)}function Kd(e){let t=(0,d.getPostalCodeExample)(e);return`Enter a valid ${(0,d.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Gd(e,t,r){let n=(0,d.isPostalCodeSupported)(e),a=t.trim(),s=r&&n,l=s&&!a,p=s&&!!a&&!(0,d.isValidPostalCode)(e,a);return{visible:r,supported:n,required:s,empty:l,malformed:p}}function Yd(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,d.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function Xd(e){return typeof e=="number"?`${e}px`:e}function Ci(e){return(0,u.jsx)(Qd,{...e})}function Jl({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:l=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:f,runBeforeButtonClick:S,billingName:C,onBuyerIdentityReady:R,onLoadStateChange:H,placeholderBorderRadius:E,popupCapabilityOwner:Z,externalTelemetryContext:M,presentationMode:y}){let g=ro(),{emitInstrument:he}=(0,o.useContext)(gn),v=(0,ir.useStripe)(),xe=(0,ir.useElements)(),I=(0,o.useMemo)(()=>li(vr(g),M),[M,g]),[se,Pe]=(0,o.useState)("loading");(0,o.useEffect)(()=>{H?.(se)},[se,H]);let[fe,Ae]=(0,o.useState)(!1),st=(0,o.useRef)(!1),Ke=!(0,d.isValidEmail)(r?.trim())||!C?.trim(),{request:B,collect:St,finish:Xe}=Wo(),Ne=(0,o.useRef)(!1),me=(0,o.useRef)(null),ee=(0,o.useRef)(null),[K,Ue]=(0,o.useState)(0),[tt,qe]=(0,o.useState)(!1),Q=(0,o.useRef)(!1),G=(0,o.useRef)(new Map),{startAttempt:$,finishAttempt:q,invalidateAttempt:Ve,isAttemptInvalidated:Oe,isAttemptCurrent:Ce,generationRef:O}=va((Re,_,ht)=>{f?.(Re,_,{...ht,popupBlocked:ht?.popupBlocked??(0,ke.isPopupBlockedError)(_),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y,terminalReason:"overlay_timeout"}),qe(!0),Ue(pt=>pt+1)},{onHandoffObserved:()=>{Z.markAvailable(),I?.log({name:"provider.popup.opened",stage:"overlay_open",...Mn,attempt:O.current})}});(0,o.useEffect)(()=>{tt&&ee.current?.focus()},[tt,K]);let Se=(0,o.useCallback)(()=>{Ue(Re=>Re+1)},[]),ut=(0,o.useCallback)((Re,_,ht)=>{Ve(ht),f?.("paypal",Re,{code:_,popupBlocked:(0,ke.isPopupBlockedError)(Re),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y}),qe(!0),Se()},[Ve,f,y,Se]),ze=(0,o.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Q.current&&(Q.current=!1,ze())},[ze,K]);let rt=(0,o.useCallback)(()=>{qe(!1),s?.(null),ze()},[ze,s]);(0,o.useEffect)(()=>{if(!v||Ne.current)return;let[Re,_,ht]=(0,d.readStripeRedirectParams)();if(!Re||!_)return;let pt=(0,d.readMatchingStripePayPalContinuation)(_);if(!pt)return;Ne.current=!0;let N=!0,Be=Ta.get(_);Be||(Be=ht==="failed"?Promise.resolve(null):Promise.resolve().then(()=>v.retrievePaymentIntent(_)),Ta.set(_,Be));let Lt={accountPatch:pt.accountPatch,sessionId:pt.sessionId,nonce:pt.nonce},Ee=()=>{I?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Mn,requestCategory:"provider_sdk"})};return I?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Mn}),(async()=>{try{Ae(!0);let P=await Be;if(!N)return;if(P?.error){Ta.delete(_),Ee(),s?.(P.error.message??"Failed to retrieve PayPal payment status.");return}if((0,d.clearStripePayPalReturn)(),Ta.delete(_),ht==="failed"){let Le="PayPal payment was declined. Please try again.";I?.terminal({outcome:"payment_declined",...Mn,terminalReason:"provider_declined"}),s?.(Le),m?.(_r("paypal",Le));return}let T=P?.paymentIntent;if(T&&T.id!==Re){Ee(),s?.("Failed to match the returned PayPal payment.");return}if(T&&(T.status==="requires_capture"||T.status==="succeeded")){let Le=typeof T.payment_method=="string"?T.payment_method:T.payment_method?.id;a({id:Le??T.id,type:"card",threeDSecureActionResultTokenId:T.id,isPaypal:!0},{...Lt,presentationMode:"redirect"})}else{let Le="PayPal payment was not completed. Please try again.";I?.terminal({outcome:T?.status==="canceled"?"payment_cancelled":"payment_declined",...Mn,terminalReason:T?.status==="canceled"?"cancelled":"provider_declined"}),s?.(Le),m?.(_r("paypal",Le))}}catch(P){if(!N)return;Ta.delete(_),Ee(),s?.(P instanceof Error?P.message:"Failed to complete PayPal payment.")}finally{N&&Ae(!1)}})(),()=>{N=!1,Ne.current=!1}},[v,a,s,m,I]);let Fe=(0,o.useCallback)(async(Re=!1)=>{let _=S?await S("paypal"):{proceed:!0};if(!_.proceed)return G.current.delete(K),!1;let ht=$("paypal");return G.current.set(K,{generation:ht,accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}),qe(!1),I?.log({name:`provider.${Re?"redirect.started":"handoff.requested"}`,stage:Re?"redirect":"overlay_open",...Mn,attempt:ht}),p?.("paypal"),!0},[p,I,S,$,K]),et=(0,o.useCallback)(async Re=>{if(l||fe||!await Fe()){Re.reject();return}Re.resolve()},[l,Fe,fe]),nt=(0,o.useCallback)(async Re=>{if(!v||!xe)return;let _=G.current.get(K);if(_&&!Ce(_.generation)){G.current.delete(K);return}if(!_&&Oe()||_&&!q(_.generation))return;_||q();let ht=_??null;if(G.current.delete(K),!ht&&S){let It=await S("paypal");if(!It.proceed){Re.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ht={accountPatch:It.accountPatch,sessionId:It.sessionId,nonce:It.nonce}}let pt=ht?.sessionId??e,N=ht?.nonce??t,Be=await qd({event:Re,prepared:ht,email:r,billingName:C,methodLabel:"PayPal",collect:St});if(!Be){Re.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Lt=Be.email,Ee={...ht?.accountPatch,...(0,hn.compactBuyerIdentity)(Be,!0)};try{if(Ae(!0),s?.(null),!pt||!(0,d.isValidEmail)(Lt))throw new Error("Missing sessionId or email for PayPal payment");await R?.(Be);let It=v.createPaymentMethod,{error:P,paymentMethod:T}=await It({type:"paypal"});if(P){ut(P,"stripe_paypal_create_payment_method_failed",_?.generation),Re.paymentFailed({reason:"fail"});return}let Le=await Pi(n,he,pt,N??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:T?.id??null,intentKind:"payment"});if(Le.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ie=Le.clientSecret,lt={return_url:(0,d.stripeRedirectReturnUrl)()};if(T?.id&&(lt.payment_method=T.id),!sr(cs,{clientSecret:Ie,sessionId:pt,nonce:N,accountPatch:Ee})&&y==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:We,paymentIntent:Ge}=await v.confirmPayment({clientSecret:Ie,confirmParams:lt,redirect:"if_required"});if(We){if(sr(cs),(0,ke.isProviderDecline)(We)){let c=We.message??"Your payment was declined.";I?.terminal({outcome:"payment_declined",...Mn,terminalReason:"provider_declined"}),s?.(c),m?.(_r("paypal",c,{code:(0,ke.getProviderErrorCode)(We),declineCode:(0,ke.getProviderDeclineCode)(We)})),await vi({billingApiUrl:n,sessionId:pt,nonce:N,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,ke.getProviderErrorCode)(We)??"provider_declined"}})}else ut(We,"stripe_paypal_confirm_failed",_?.generation);return}sr(cs);let Dt=typeof Ge?.payment_method=="string"?Ge.payment_method:Ge?.payment_method?.id;a({id:Dt??Ge?.id,type:"card",threeDSecureActionResultTokenId:Ge?.id,isPaypal:!0},{accountPatch:Ee,paymentMethodCategory:"paypal",presentationMode:y,sessionId:pt,nonce:N});return}catch(It){ut(It,"stripe_paypal_failed",_?.generation)}finally{Ae(!1)}},[v,xe,e,t,r,C,St,R,n,he,a,s,m,S,ut,q,Ce,Oe,I,y,K]),cr=(0,o.useCallback)(async()=>{if(!(st.current||l||fe||!v||!xe)){st.current=!0,Ae(!0);try{if(!await Fe(!0))return;await nt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{st.current=!1,Ae(!1)}}},[xe,nt,l,Fe,v,fe]),xt=y==="redirect"?(0,u.jsx)("button",{type:"button",disabled:l||fe,onClick:()=>{cr()},style:{width:"100%",minHeight:Zo,border:"1px solid #d1d5db",borderRadius:E??8,background:"#ffc439",color:"#111827",cursor:l||fe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,u.jsx)(ir.ExpressCheckoutElement,{onReady:Re=>Pe(Ea(Re,["paypal"])),onLoadError:()=>{Pe("load_error"),fs(I,"paypal","paypal","provider_error")},onClick:et,onConfirm:nt,onCancel:()=>{let Re=G.current.get(K);G.current.delete(K),I?.terminal({outcome:"payment_cancelled",...Mn,terminalReason:"cancelled",...Re?{attempt:Re.generation}:{}}),Ve(Re?.generation),qe(!1),Q.current=!0,Se()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Ke,emailRequired:Ke,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},K),bt=(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[tt&&(0,u.jsx)("button",{ref:ee,type:"button","data-testid":"flopay-paypal-retry-button",onClick:rt,style:us,children:"Try PayPal again"}),B&&(0,u.jsx)($o,{identity:B.identity,methodLabel:B.methodLabel,onComplete:Xe,onCancel:()=>Xe(null)},B.id),(0,u.jsx)("div",{style:{display:B?"none":void 0},children:xt})]}),fe&&!B&&(0,u.jsx)(nn,{status:"processing"})]});return y==="redirect"?bt:(0,u.jsx)(Ia,{state:se,placeholderTestId:"flopay-paypal-placeholder",borderRadius:E,children:bt})}function ds(e){return e==="apple_pay"||e==="google_pay"}var Jd=200;function Zd({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,d.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function Zl({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:l,onErrorChange:p,onButtonClick:m,onDecline:f,onTechnicalFailure:S,runBeforeButtonClick:C,billingName:R,onBuyerIdentityReady:H,onLoadStateChange:E,placeholderBorderRadius:Z,popupCapabilityOwner:M,externalTelemetryContext:y}){let g=ro(),{emitInstrument:he}=(0,o.useContext)(gn),v=(0,ir.useStripe)(),xe=(0,ir.useElements)(),I=(0,o.useMemo)(()=>li(vr(g),y),[y,g]),[se,Pe]=(0,o.useState)("loading");(0,o.useEffect)(()=>{E?.(se)},[se,E]);let[fe,Ae]=(0,o.useState)(!1);(0,o.useEffect)(()=>{qe.current=fe},[fe]);let st=(0,o.useRef)(!(0,d.isValidEmail)(r?.trim())||!R?.trim()).current,{request:Ke,collect:B,finish:St}=Wo(),Xe=(0,o.useRef)(null),Ne=(0,o.useRef)(null),[me,ee]=(0,o.useState)(0),[K,Ue]=(0,o.useState)(()=>(0,d.shouldPreferWalletPopup)()),tt=(0,o.useRef)(K),qe=(0,o.useRef)(!1),[Q,G]=(0,o.useState)(!1),[$,q]=(0,o.useState)(()=>hi(e,t)?"blocked":"idle"),[Ve,Oe]=(0,o.useState)("google_pay"),Ce=(0,o.useRef)(null),O=(0,o.useRef)(!0),Se=(0,o.useRef)(!1),ut=(0,o.useRef)("google_pay"),ze=(0,o.useRef)("google_pay"),rt=(0,o.useRef)(null),Fe=(0,o.useRef)(null),et=(0,o.useRef)(new Set),nt=(0,o.useRef)(null),cr=(0,o.useRef)(null);(0,o.useEffect)(()=>(O.current=!0,()=>{O.current=!1;for(let c of et.current)window.clearTimeout(c);et.current.clear()}),[]);let xt=(0,o.useRef)(new Map),{startAttempt:bt,finishAttempt:Re,invalidateAttempt:_,isAttemptInvalidated:ht,isAttemptCurrent:pt,generationRef:N}=va((c,L,j)=>{S?.(c,L,{...j,popupBlocked:j?.popupBlocked??(0,ke.isPopupBlockedError)(L),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Oe(c),G(!0),ee(ue=>ue+1)},{onHandoffObserved:c=>{cr.current=N.current,M.markAvailable(),I?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:N.current,...c==="apple_pay"||c==="google_pay"?{walletType:c}:{}})},defersMissingTerminal:ds,onMissingTerminalDeferred:(c,L)=>{let j=I?.now()??globalThis.performance?.now()??Date.now(),ue=nt.current,k=ue?.generation===L?ue.startedAt:j;I?.performance({stage:"overlay_return",durationMs:Math.max(0,j-k),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:L,...ds(c)?{walletType:c}:{}}),I?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{Q&&Ne.current?.focus()},[Q,me]);let Be=(0,o.useRef)(0),Lt=(0,o.useRef)(!1),Ee=(0,o.useCallback)(()=>{if(Be.current>0){Lt.current=!0;return}ee(c=>c+1)},[]),It=(0,o.useCallback)(()=>{Be.current-=1,!(Be.current>0||!Lt.current)&&(Lt.current=!1,O.current&&ee(c=>c+1))},[]),P=(0,o.useCallback)((c,L,j,ue,k=!1)=>{_(ue),S?.(c,L,{code:j,popupBlocked:(0,ke.isPopupBlockedError)(L),telemetryReported:k,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Oe(c),G(!0),Ee()},[_,S,Ee]),T=(0,o.useCallback)(c=>{I?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...ds(c)?{walletType:c}:{}}),S?.(c,new Error("The wallet click was not ready within the time the wallet allows."),{code:Id,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Oe(c),G(!0)},[S,I]),Le=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Xe.current?.querySelector("iframe")??Xe.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Se.current&&(Se.current=!1,Le())},[Le,me]);let Ie=(0,o.useCallback)(()=>{G(!1),p?.(null),Le()},[Le,p]),lt=(0,o.useCallback)(()=>{Ce.current?.()},[]);(0,o.useEffect)(()=>{let c=null,L=()=>{c=null;let ue=(0,d.shouldPreferWalletPopup)();ue!==tt.current&&(tt.current=ue,Ue(ue),!qe.current&&!pt(N.current)&&Ee())},j=()=>{c!==null&&window.clearTimeout(c),c=window.setTimeout(L,Jd)};return window.addEventListener("resize",j),()=>{window.removeEventListener("resize",j),c!==null&&window.clearTimeout(c)}},[N,pt,Ee]),(0,o.useEffect)(()=>{let c=hi(e,t);if(!c)return;let L=!1,j=!1,ue=async()=>{if(!j){j=!0,L||q("checking");try{let k=await Hl(v,c.clientSecret,et.current);if(L)return;let V=ls(k,c.providerObjectId,(0,d.isSetupIntentClientSecret)(c.clientSecret));if(V.kind==="confirmed"){if(!$l(e,t,c.clientSecret))return;Ce.current=null,q("idle"),l({id:V.paymentMethodId,type:"card",threeDSecureActionResultTokenId:V.intentId},{...c.accountPatch?{accountPatch:c.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(V.kind==="terminal"){ss(e,t,c.clientSecret),Ce.current=null,q("idle"),Oe(c.paymentMethodType),G(!0),Ee();return}q("blocked")}catch{L||q("blocked")}finally{j=!1}}};return Ce.current=ue,q("blocked"),()=>{L=!0,Ce.current===ue&&(Ce.current=null)}},[t,l,Ee,e,v]);let ot=(0,o.useCallback)(async c=>{let L=!1,j=!1,ue=at=>{L||j||(L=!0,c.paymentFailed({reason:"fail",...at?{message:at}:{}}))};if(!v||!xe){ue();return}let k=xt.current.get(me);if(k&&!pt(k.generation)){xt.current.delete(me),ue();return}if(!k&&ht()){ue();return}if(k&&!Re(k.generation)){ue();return}k||(Re(),Lt.current=!1);let V=c.expressPaymentType??k?.method??ut.current,Ut=k??null,Br=Xl(V),dr;V==="apple_pay"?dr="apple_pay":V==="google_pay"&&(dr="google_pay");let Yt=k?.generation??N.current,_t=I,qr=_t?.now()??globalThis.performance?.now()??Date.now(),Dr=new AbortController,tr=!1,Gr=!1,Tt=null,An=e,Xt="processing",pn="other",jr="provider_runtime",Vr,ur=new Promise((at,kt)=>{Vr=kt}),br=window.setTimeout(()=>{tr=!0,Dr.abort(),Vr(fi)},_d),Yr=async(at,kt,xr)=>{Xt=at,pn=kt,jr=kt==="intent_create"||kt==="session_claim"?"transport_error":"provider_runtime";let Wt=_t?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([xr,ur])}finally{let pr=_t?.now()??globalThis.performance?.now()??Date.now();_t?.performance({stage:at,durationMs:Math.max(0,pr-Wt),durationMode:"machine",requestCategory:kt,paymentMethodCategory:"wallet",provider:"stripe",...tr?{statusClass:"timeout"}:{}})}};try{if(Ae(!0),p?.(null),!Ut&&C){let be=await Yr("processing","other",C(Br));if(!be.proceed){ue();return}Ut={accountPatch:be.accountPatch,sessionId:be.sessionId,nonce:be.nonce}}let at=Ut?.sessionId??e;An=at;let kt=Ut?.nonce??t,xr=rt.current??Ut?.accountPatch,Wt=nc({event:c,fallbackEmail:xr?.email??r,fallbackName:[xr?.firstName,xr?.lastName].join(" ").trim()||R});if(!(0,d.isValidEmail)(Wt.email)){ue("Buyer details are required."),B(ps(V),Wt).then(be=>{be&&(rt.current=be)});return}rt.current=null;let pr={...Ut?.accountPatch,...(0,hn.compactBuyerIdentity)(Wt,!0)};await Yr("processing","session_claim",Promise.resolve(H?.(Wt)));let{error:fr}=await Yr("tokenization","provider_sdk",xe.submit());if(fr){ue(),P(V,fr,"stripe_wallet_submit_failed",k?.generation);return}if(!at)throw new Error("Missing sessionId or email for payment.");let Jt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:V,paymentMethodId:null,intentKind:a},Zt=JSON.stringify({sessionId:at,nonce:kt??"",request:Jt}),Sr=Fe.current,Je=Sr?.retryIdentity===Zt?Sr.authorizationAttemptId:(0,d.randomUuidV4)();Fe.current={authorizationAttemptId:Je,retryIdentity:Zt};let wr=await Yr("processing","intent_create",Pi(n,he,at,kt??"",{...Jt,authorizationAttemptId:Je},{signal:Dr.signal}));if(wr.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let kr=wr.clientSecret,Hn=Dd({createdAt:Date.now(),sessionId:at,...kt?{nonce:kt}:{},clientSecret:kr,providerObjectId:wr.providerObjectId,paymentMethodType:V,accountPatch:pr});window.clearTimeout(br),Gr=!0,_t?.performance({stage:"callback",durationMs:Math.max(0,(_t?.now()??globalThis.performance?.now()??Date.now())-qr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Or=_t?.now()??globalThis.performance?.now()??Date.now(),Lr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...dr?{walletType:dr}:{},attempt:Yt},Fn=!1,an=null;_t?.log({name:"payment.provider_confirmation.started",...Lr}),Tt=window.setTimeout(()=>{Tt!==null&&et.current.delete(Tt),Fn=!0;let be=_t?.now()??globalThis.performance?.now()??Date.now();_t?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Lr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,be-Or),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),_t?.flush?.().catch(()=>{}),an?.()},Td),et.current.add(Tt);let rr=(be,Vt)=>{Tt!==null&&(window.clearTimeout(Tt),et.current.delete(Tt),Tt=null);let ae=_t?.now()??globalThis.performance?.now()??Date.now(),Nt=Math.max(0,ae-Or),hr=be;Fn&&(be==="resolved"?hr="resolved_late":be==="returned_error"?hr="returned_error_late":hr="rejected_late");let Nr=Vt??(be==="resolved"?"approved":"provider_error");return _t?.log({name:"payment.provider_confirmation.returned",...Lr,operationOutcome:hr,terminalReason:Nr}),_t?.performance({...Lr,durationMs:Nt,durationMode:"buyer",operationOutcome:hr,terminalReason:Nr}),{durationMs:Nt,operationOutcome:hr,terminalReason:Nr}},ve=!1,gr=!1,Xr=be=>{if(!be||typeof be!="object")return null;let Vt=be;if(Vt.error)return null;let ae=Vt.setupIntent??Vt.paymentIntent,Nt=ls(ae??null,void 0,!!Vt.setupIntent);return Nt.kind==="confirmed"?Nt:null},le=be=>{if(ve||k&&N.current!==k.generation)return;let Vt=Xr(be);if(!Vt)return;if(Hn&&!$l(at,kt,kr)){ve=!0;return}let{intentId:ae,paymentMethodId:Nt}=Vt;ve=!0,gr=!0,Fe.current=null,Ce.current=null,O.current&&(q("idle"),Ae(!1));let hr=`${ec}:${at}`;sr(hr,{createdAt:Date.now(),sessionId:at,nonce:kt,accountPatch:pr,paymentMethodId:Nt,providerIntentId:ae,paymentMethodType:V});try{l({id:Nt,type:"card",threeDSecureActionResultTokenId:ae},{accountPatch:pr,paymentMethodCategory:"wallet",sessionId:at,nonce:kt})}finally{sr(hr)}},At=!1;an=async()=>{if(!(At||ve||gr)){At=!0,O.current&&q("checking");try{let be=await Hl(v,kr,et.current);if(ve||gr)return;let Vt=(0,d.isSetupIntentClientSecret)(kr),ae=ls(be,wr.providerObjectId,Vt);if(ae.kind==="confirmed"){le(Vt?{setupIntent:be}:{paymentIntent:be});return}if(ae.kind==="terminal"){if(gr=!0,ss(at,kt,kr),Fe.current=null,Ce.current=null,!O.current)return;q("idle"),ue(),P(V,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",k?.generation,!0);return}O.current&&!gr&&(q("blocked"),Ae(!1))}catch{O.current&&!gr&&(q("blocked"),Ae(!1))}finally{At=!1}}},Ce.current=an;let te,$t;try{j=!0,Be.current+=1;let be;try{be=await((0,d.isSetupIntentClientSecret)(kr)?v.confirmSetup({elements:xe,clientSecret:kr,redirect:"if_required"}):v.confirmPayment({elements:xe,clientSecret:kr,redirect:"if_required"}))}finally{It()}if(!be||typeof be!="object")throw new Ma(Bd(be));if(te=be,!te.error&&!Xr(te))throw new Ma("confirmation_result_unconfirmed");$t=rr(te.error?"returned_error":"resolved",te.error&&(0,ke.isProviderDecline)(te.error)?"provider_declined":void 0)}catch(be){let Vt=be instanceof Ma?be.reason:void 0,ae=Vt!==void 0,Nt=rr(ae?"returned_error":"rejected");if(_t?.error({...ae?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Vt}:Zi(be),...Lr,operationOutcome:Nt.operationOutcome,durationMs:Nt.durationMs,statusClass:"unknown",terminalReason:Nt.terminalReason}),!O.current||ve)return;await an?.();return}let nr=te.error;if(nr){if(!O.current||ve)return;if((0,ke.isProviderDecline)(nr)){gr=!0,ss(at,kt,kr),Fe.current=null,Ce.current=null,q("idle"),xt.current.get(me)===k&&xt.current.delete(me);let be=nr.message??"Your payment was declined.";p?.(be),f?.(_r(Br,be,{code:(0,ke.getProviderErrorCode)(nr),declineCode:(0,ke.getProviderDeclineCode)(nr)})),vi({billingApiUrl:n,sessionId:at,nonce:kt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:V,providerDeclineReason:(0,ke.getProviderErrorCode)(nr)??"provider_declined",...wr.intentKind==="payment"&&wr.providerObjectId.startsWith("pi_")?{providerIntentId:wr.providerObjectId}:{}}})}else _t?.error({...Zi(nr),...Lr,operationOutcome:$t.operationOutcome,durationMs:$t.durationMs,statusClass:"unknown",terminalReason:$t.terminalReason}),await an?.();return}if(le(te),!ve)throw new Error("Invalid provider returned for APM intent")}catch(at){if(at===fi){let kt=_t?.now()??globalThis.performance?.now()??Date.now();_t?.error({errorCode:Ld(pn),stage:Xt,requestCategory:pn,paymentMethodCategory:"wallet",provider:"stripe",...dr?{walletType:dr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:An,durationMs:Math.max(0,kt-qr),statusClass:"timeout",failureCategory:jr,attempt:Yt,terminalReason:"provider_error"}),_t?.flush?.().catch(()=>{})}ue(),P(V,at,at===fi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",k?.generation,at===fi)}finally{if(window.clearTimeout(br),Tt!==null&&(window.clearTimeout(Tt),et.current.delete(Tt)),!Gr){let at=_t?.now()??globalThis.performance?.now()??Date.now();_t?.performance({stage:"callback",durationMs:Math.max(0,at-qr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...tr?{statusClass:"timeout"}:{}})}O.current&&Ae(!1)}},[v,xe,e,t,r,R,B,H,n,he,a,l,p,f,C,P,It,Re,pt,ht,N,I,me]),We=(0,o.useMemo)(()=>di(s),[s]),Ge=(0,o.useMemo)(()=>s.map(d.stripeExpressMethodToOptionKey),[s]),Dt=(0,o.useMemo)(()=>(0,u.jsx)(ir.ExpressCheckoutElement,{onReady:c=>{Pe(Ea(c,Ge))},onLoadError:c=>{Pe("load_error"),fs(I,"stripe","wallet","provider_error")},onClick:async c=>{let L=I?.now()??globalThis.performance?.now()??Date.now();ut.current=c.expressPaymentType,ze.current=Xl(c.expressPaymentType);let j=!0,ue=window.setTimeout(()=>{j=!1,c.reject(),T(c.expressPaymentType)},Ed),k=C?await C(ze.current,{abandoned:()=>!j}):{proceed:!0};if(window.clearTimeout(ue),!j)return;if(!k.proceed){xt.current.delete(me),c.reject();return}let V=bt(c.expressPaymentType);Lt.current=!1,nt.current={generation:V,startedAt:L},xt.current.set(me,{generation:V,method:c.expressPaymentType,accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}),G(!1),I?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:V,...c.expressPaymentType==="apple_pay"||c.expressPaymentType==="google_pay"?{walletType:c.expressPaymentType}:{}}),m?.(ze.current),c.resolve()},onConfirm:ot,onCancel:()=>{let c=xt.current.get(me);xt.current.delete(me);let L=nt.current,j=I?.now()??globalThis.performance?.now()??Date.now();if(c&&L?.generation===c.generation&&(0,d.isWalletSheetRefusedForWindowSize)({method:c.method,elapsedMs:j-L.startedAt,handoffObserved:cr.current===c.generation})){I?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:c.generation,walletType:"google_pay"}),Fe.current=null,P(c.method,new Error("The browser window is too small for the Google Pay sheet."),d.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,c.generation,!0);return}I?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...c?{attempt:c.generation}:{}}),_(c?.generation),Fe.current=null,G(!1),Se.current=!0,Ee()},options:{...ui,paymentMethods:We,emailRequired:st,billingAddressRequired:st}},me),[Ge,We,ot,_,m,st,P,T,Ee,C,bt,me,I]);return(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(Ia,{state:se,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Z,children:(0,u.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:[Q&&(0,u.jsxs)("button",{ref:Ne,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ie,style:us,children:["Try ",ps(Ve)," again"]}),$!=="idle"&&(0,u.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,u.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,u.jsx)("button",{type:"button",onClick:lt,disabled:$==="checking",style:us,children:$==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ke&&(0,u.jsx)($o,{identity:Ke.identity,methodLabel:Ke.methodLabel,onComplete:St,onCancel:()=>St(null)},Ke.id),(0,u.jsxs)("div",{style:{display:Ke||$!=="idle"?"none":void 0},children:[(0,u.jsx)(Zd,{active:K}),Dt]})]})}),fe&&(0,u.jsx)(nn,{status:"processing"})]})}function oc(e,t,r){let n=(0,d.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,paymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function ms({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:l,onTokenizedBody:p,onErrorChange:m,onDecline:f,onCancel:S,runBeforeButtonClick:C,onButtonClick:R,isProcessing:H,submitButtonColor:E,submitButtonBorderRadius:Z,submitButtonStyle:M,errorText:y}){let g=ro(),{emitInstrument:he}=(0,o.useContext)(gn),v=(0,ir.useStripe)(),xe=(0,ir.useElements)(),[I,se]=(0,o.useState)(!1),Pe=(0,o.useRef)(!1),[fe,Ae]=(0,o.useState)(!1),[st,Ke]=(0,o.useState)("loading"),[B,St]=(0,o.useState)(""),Xe=!(0,d.isValidEmail)(n?.trim()),Ne=!Xe||(0,d.isValidEmail)(B.trim()),me=(0,o.useCallback)(async()=>{if(!v||!xe||H||Pe.current||!fe)return;Pe.current=!0,se(!0);let ee=C?await C("card"):{proceed:!0};if(!ee.proceed){Pe.current=!1,se(!1);return}R?.("card");let K=ee.sessionId??t,Ue=ee.nonce??r,tt=(0,Vo.splitFullName)(a?.trim()),qe=(0,hn.compactBuyerIdentity)({email:ee.accountPatch?.email?.trim()||n?.trim()||B.trim(),firstName:ee.accountPatch?.firstName?.trim()||tt.firstName,lastName:ee.accountPatch?.lastName?.trim()||tt.lastName}),Q=qe.email,G=(0,hn.compactBuyerIdentity)({...ee.accountPatch,...qe});try{if(m?.(null),!(0,d.isValidEmail)(Q))throw new Error("A valid email address is required for payment.");await s?.(qe);let $=await xe.submit();if($.error){m?.($.error.message??"Payment failed.");return}let q=[qe.firstName,qe.lastName].filter(Boolean).join(" "),Ve=await v.createPaymentMethod({elements:xe,params:{billing_details:{email:Q,...q?{name:q}:{}}}});if(Ve.error||!Ve.paymentMethod){m?.(Ve.error?.message??"Failed to create payment method.");return}let Oe=Ve.paymentMethod;if(!K||!Q)throw new Error("Missing sessionId or email for payment.");let Ce=Oe.type||e,O=await Pi(l,he,K,Ue??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Ce,paymentMethodId:null,intentKind:"payment"});if(O.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Se=O.clientSecret;sr(Vn,{clientSecret:Se,sessionId:K,nonce:Ue,accountPatch:G,paymentMethodId:Oe.id,paymentMethodType:Oe.type??e,gateway:"stripe"});let{error:ut,paymentIntent:ze}=await v.confirmPayment({clientSecret:Se,confirmParams:{return_url:window.location.href,payment_method:Oe.id},redirect:"if_required"});if(ut){sr(Vn);let et=ut.message??"Payment failed.";m?.(et),f?.(_r("card",et,{code:ut.code})),await vi({billingApiUrl:l,sessionId:K,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ut.code??"provider_declined"}});return}let rt=ze?.status;if(!fa(rt)){sr(Vn);let et=rt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(et),f?.(_r("card",et,{code:rt??"missing_payment_intent"}));return}sr(Vn);let Fe=typeof ze?.payment_method=="string"?ze.payment_method:ze?.payment_method?.id;p({id:Fe??Oe.id,type:"card",threeDSecureActionResultTokenId:ze?.id,gateway:"stripe",paymentMethodType:Oe.type??e},{accountPatch:G,paymentMethodCategory:"apm",sessionId:K,nonce:Ue})}catch($){m?.($ instanceof Error?$.message:"Payment failed. Please try again.")}finally{Pe.current=!1,se(!1)}},[v,xe,H,fe,C,R,t,r,n,a,B,s,l,he,e,p,m,f]);return(0,u.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Xe&&(0,u.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Xe&&(0,u.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,u.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:B,onChange:ee=>St(ee.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,u.jsx)(ir.PaymentElement,{onReady:()=>Ke("ready"),onLoadError:()=>{Ke("load_error"),fs(vr(g),"stripe","apm")},onChange:ee=>{Ae(!!ee.complete)},options:{layout:pi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,d.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,u.jsx)(mi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{me()},disabled:!fe||!Ne||I||H||st!=="ready",color:E,borderRadius:Z,style:M,children:I?"Processing\u2026":`Pay with ${(0,d.getStripeMethodDisplayName)(e)}`}),y&&(0,u.jsx)(Go,{margin:"0.75rem 0 0",children:y})]})}function Ql({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:l,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:f,onTokenizedBody:S,onErrorChange:C,onButtonClick:R,onDecline:H,runBeforeButtonClick:E,onLoadStateChange:Z,isProcessing:M=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:g=8,submitButtonStyle:he,buttonAppearance:v,themeId:xe,onExpandApm:I,expandedApmMethod:se}){let{emitInstrument:Pe}=(0,o.useContext)(gn),[fe,Ae]=(0,o.useState)(null),[st,Ke]=(0,o.useState)(null),B=(0,o.useRef)(!1),{request:St,collect:Xe,finish:Ne}=Wo();(0,o.useEffect)(()=>{l.length>0&&p?Z?.("ready"):p||Z?.("loading")},[l.length,p,Z]);let me=(0,o.useCallback)(async Q=>{if(!p||B.current||M)return;B.current=!0,Ke(Q);let G=E?await E("card"):{proceed:!0};if(!G.proceed){B.current=!1,Ke(null);return}R?.("card");let $=G.sessionId??e,q=G.nonce??t,Ve=(0,Vo.splitFullName)([G.accountPatch?.firstName,G.accountPatch?.lastName].filter(Boolean).join(" ")||n),Oe=(0,hn.compactBuyerIdentity)({email:G.accountPatch?.email?.trim()||r?.trim(),firstName:G.accountPatch?.firstName?.trim()||Ve.firstName,lastName:G.accountPatch?.lastName?.trim()||Ve.lastName});if(!(0,d.isValidEmail)(Oe.email)){Ke(null);let Se=await Xe((0,d.getStripeMethodDisplayName)(Q),Oe);if(!Se){B.current=!1;return}Oe=Se,Ke(Q)}let Ce=Oe.email,O=(0,hn.compactBuyerIdentity)({...G.accountPatch,...Oe});try{if(C?.(null),!$||!(0,d.isValidEmail)(Ce))throw new Error("Missing sessionId or email for payment.");await a?.(Oe);let Se=await Pi(s,Pe,$,q??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if(Se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ut=Se.clientSecret;sr(Vn,{clientSecret:ut,sessionId:$,nonce:q,accountPatch:O,paymentMethodType:Q,gateway:"stripe"});let{error:ze,paymentIntent:rt}=await p.confirmPayment({clientSecret:ut,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:[Oe.firstName,Oe.lastName].filter(Boolean).join(" "),...Ce?{email:Ce}:{}}}},redirect:"if_required"});if(ze){sr(Vn);let nt=ze.message??"Payment failed.";C?.(nt),H?.(_r("card",nt,{code:ze.code})),await vi({billingApiUrl:s,sessionId:$,nonce:q,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:ze.code??"provider_declined"}});return}let Fe=rt?.status;if(!fa(Fe)){sr(Vn);let nt=Fe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";C?.(nt),H?.(_r("card",nt,{code:Fe??"missing_payment_intent"}));return}sr(Vn);let et=typeof rt?.payment_method=="string"?rt.payment_method:rt?.payment_method?.id;S({id:et??rt?.id,type:"card",threeDSecureActionResultTokenId:rt?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:O,paymentMethodCategory:"apm",sessionId:$,nonce:q})}catch(Se){C?.(Se instanceof Error?Se.message:"Payment failed. Please try again.")}finally{B.current=!1,Ke(null)}},[p,M,E,R,e,t,r,Xe,s,Pe,n,a,S,C,H]),[ee,K]=(0,o.useState)(null),Ue=I?se??null:ee,tt=(0,o.useCallback)(Q=>{B.current||M||Ue&&Ue!==Q||((0,d.needsStripeMethodExplicitConfirm)(Q)?I?I(Q):K(Q):me(Q))},[Ue,M,me,I]),qe=(0,o.useMemo)(()=>ee?oc(m,ee,f):null,[ee,m,f]);return(0,u.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:St?(0,u.jsx)($o,{identity:St.identity,methodLabel:St.methodLabel,onComplete:Ne,onCancel:()=>Ne(null)},St.id):l.map(Q=>{let G=se===Q,$=st===Q,q=st!==null&&st!==Q||se!=null&&se!==Q;return(0,u.jsxs)(o.default.Fragment,{children:[(0,u.jsx)(ci,{method:Q,themeId:xe,submitting:$,disabled:q,highlighted:G,hasNextStep:(0,d.needsStripeMethodExplicitConfirm)(Q),onClick:()=>tt(Q),backgroundColor:v?.backgroundColor,borderColor:v?.borderColor,textColor:v?.textColor,borderRadius:v?.borderRadius,fontFamily:v?.fontFamily}),!I&&ee===Q&&qe&&p&&(0,u.jsx)(ir.Elements,{stripe:p,options:qe,children:(0,u.jsx)(ms,{method:Q,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:S,onErrorChange:C,onDecline:H,onCancel:()=>K(null),runBeforeButtonClick:E,onButtonClick:R,isProcessing:M,submitButtonColor:y,submitButtonBorderRadius:g,submitButtonStyle:he})},Q)]},Q)})})}function Qd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:l,onError:p,onDecline:m,onCancel:f,onTokenizedBody:S,firstName:C,lastName:R,chv:H,className:E,submitLabel:Z,isProcessing:M,error:y,onErrorChange:g,showPayPal:he=!0,showStripe:v=!0,walletPresentation:xe="auto",enabledPaymentMethods:I,enabledPaymentMethodCountries:se,showApplePay:Pe=!0,showGooglePay:fe=!0,layout:Ae="default",theme:st,buttonsTheme:Ke,buttonsStyles:B,appearance:St,cardButtonContent:Xe,cardBackButtonContent:Ne,cardTitleContent:me,showSecurityFooter:ee,onButtonClick:K,onBeforeButtonClick:Ue,onBuyerIdentityReady:tt,enableAVS:qe,cardFieldOrder:Q,cardPreFormSlot:G,avsLayout:$="row",country:q,zip:Ve,addressLine1:Oe,addressLine2:Ce,city:O,state:Se,onCountryChange:ut,onZipChange:ze,avsCheck:rt,checkoutType:Fe,checkoutLayout:et,totalAmount:nt=0,currency:cr="usd",initialCardOpen:xt=!1,directPaypal:bt,isSubscription:Re=!1,session:_,dataAttachmentPending:ht=!1,dataAttachmentRequiresIdentity:pt=!1,debug:N=!1}){let Be=ro(),Lt=Ja(),Ee=(0,o.useContext)(In),{emitInstrument:It}=(0,o.useContext)(gn),P=(0,o.useRef)(null);P.current||(P.current=Qa());let T=P.current,[,Le]=(0,o.useState)(0),Ie=(0,o.useRef)(null);Ie.current||(Ie.current=(0,zn.detectPayPalEnvironment)());let lt=Ie.current,ot=(0,o.useMemo)(()=>({browser:lt,capability:T,presentationMode:"popup"}),[lt,T]),We=_??Ee.session,Ge=(0,o.useMemo)(()=>({futureUse:We?.futureUse,futureUseUnsupported:We?.futureUseUnsupported}),[We?.futureUse,We?.futureUseUnsupported]),Dt=We?.gateways?.paypal?.providerObjectType??bt?.providerObjectType,c=ht||Ee.claimPending===!0,L=pt||Ee.claimRequiresIdentity===!0,j=c&&!L,ue=Tl(),k=r||ue,[V,Ut]=(0,o.useState)(!1),[Br,dr]=(0,o.useState)(null),[Yt,_t]=(0,o.useState)(q??""),[qr,Dr]=(0,o.useState)(Ve??""),[tr,Gr]=(0,o.useState)(Oe??""),[Tt,An]=(0,o.useState)(Ce??""),[Xt,pn]=(0,o.useState)(O??""),[jr,Vr]=(0,o.useState)(Se??""),[ur,br]=(0,o.useState)(""),[Yr,at]=(0,o.useState)({}),kt=(0,o.useRef)(Ve??""),xr=(0,o.useRef)(q??""),Wt=(0,o.useRef)(Oe??""),pr=(0,o.useRef)(Ce??""),fr=(0,o.useRef)(O??""),Jt=(0,o.useRef)(Se??""),Zt=(0,o.useRef)(""),Sr=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(w,Y,Te,J,Me)=>{if(Sr.current[w])return;let qt=Y?.trim();!qt||qt===Te.current||(Te.current=qt,J(qt),Me?.(qt))};i("country",q,xr,_t,ut),i("zip",Ve,kt,Dr,ze),i("addressLine1",Oe,Wt,Gr),i("addressLine2",Ce,pr,An),i("city",O,fr,pn),i("state",Se,Jt,Vr)},[q,Ve,Oe,Ce,O,Se,ut,ze]);let Je=(0,o.useMemo)(()=>(0,d.resolveAVSConfig)(qe),[qe]),wr=Je!==null,kr=(0,o.useMemo)(()=>(0,d.isAuthorizationOnlySession)(_),[_]),Hn=(0,d.isMountableVaultBlock)(_?.vault),Or=!!_?.gateways?.pcivault,Lr=(0,En.hasServerSideCardGateway)(_),an=!!(_?.gateways?.stripe?.enabledPaymentMethods??I)?.includes("card")||(0,En.canRecoverHostedCardForm)(_),rr=Hn||an||Or,ve=!!(v&&rr&&e),[gr,Xr]=(0,o.useState)(()=>Ae!=="buttons"||xt?e??null:null),[le,At]=(0,o.useState)(0),te=Ae!=="buttons"||xt||!!e&&gr===e,$t=_?.captureMethod,nr=(0,o.useRef)(Be);(0,o.useEffect)(()=>{nr.current=Be},[Be]);let[be,Vt]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!ve||!e||!te){Vt(null);return}let i=nr.current?nr.current.cardCapture({sessionId:e,captureMethod:$t}):new xn.PciVaultCardCapture({sessionId:e,captureMethod:$t,billingApiUrl:k,telemetry:n});return Vt({sessionId:e,captureMethod:$t,billingApiUrl:k,telemetry:n,capture:i}),()=>{i.unmount()}},[ve,e,te,$t,k,n]);let ae=ve&&e&&te&&be?.sessionId===e&&be.captureMethod===$t&&be.billingApiUrl===k&&be.telemetry===n?be.capture:null,Nt=(0,o.useMemo)(()=>{let i=Yt,w=Je?(0,d.isAVSFieldVisible)(Je.postal_code,i):!1;return Gd(i,qr,w)},[Je,Yt,qr]),{avsInvalid:hr,invalidAvsFields:Nr}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!ve||!Je)return{avsInvalid:!1,invalidAvsFields:i};let w=Yt,Y=(Me,qt)=>(0,d.isAVSFieldVisible)(Me,w)&&!qt.trim(),Te={line1:Y(Je.address_line_1,tr),city:Y(Je.city,Xt),state:Y(Je.state,jr),zip:Nt.empty||Nt.malformed};return{avsInvalid:Te.line1||Te.city||Te.state||Te.zip,invalidAvsFields:Te}},[ve,Je,Yt,tr,Xt,jr,Nt]),[Qt,Bn]=(0,o.useState)(!1),[Kn,Dn]=(0,o.useState)(!1),[On,Gn]=(0,o.useState)(!1),[so,lo]=(0,o.useState)({line1:!1,city:!1,state:!1}),Ar=(0,o.useRef)(!1),Yn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),mn=(0,o.useRef)(!1),zt=(0,o.useCallback)(i=>{Yn.current[i]=!0,mn.current=!0},[]),Jr=(0,o.useCallback)(i=>!Ar.current&&Yn.current[i],[]),Zr=(0,o.useCallback)(i=>{Jr(i)&&lo(w=>w[i]?w:{...w,[i]:!0})},[Jr]),[sn,Qr]=(0,o.useState)(()=>(0,d.resolveVaultMountOptions)(_?.vault,{billingApiUrl:k,sessionId:e,nonce:t})),[ct,Pr]=(0,o.useState)(xt&&rr?"card":"buttons"),[or,en]=(0,o.useState)(null),fo=ct==="expanding"||ct==="card",Xn=_?.gateways?.stripe&&!Lr?"stripe":void 0,wn=(0,o.useCallback)(()=>{It?.({class:"card_surface",provider:Xn})},[Xn,It]),ln=(0,o.useRef)(null),Rr=(0,o.useCallback)(i=>{ln.current&&clearTimeout(ln.current),ln.current=setTimeout(()=>{ln.current=null,i()},xa)},[]);(0,o.useEffect)(()=>()=>{ln.current&&clearTimeout(ln.current)},[]);let Jn=(0,o.useRef)(!1),[Ur,U]=(0,o.useState)(0),z=(0,o.useRef)(null),ie=(0,o.useCallback)(()=>{wn(),Xr(e??null),Jn.current&&(Jn.current=!1,U(i=>i+1)),At(i=>i+1),Pr("expanding"),Rr(()=>Pr("card"))},[Rr,wn,e]),we=(0,o.useCallback)(()=>{Pr("collapsing"),Rr(()=>Pr("buttons"))},[Rr]),mt=(0,o.useCallback)(i=>{en(i),Pr("apm-expanding"),Rr(()=>Pr("apm-form"))},[Rr]),Ht=(0,o.useCallback)(()=>{Pr("apm-collapsing"),Rr(()=>{Pr("buttons"),en(null)})},[Rr]);(0,o.useEffect)(()=>{Ae==="buttons"&&xt&&rr&&(Xr(e??null),Pr("card"))},[Ae,xt,rr,e]);let[_e,pe]=(0,o.useState)(null),X=(0,o.useRef)(!1),W=(0,o.useRef)(null),ce=(0,o.useRef)("idle"),[$e,de]=(0,o.useState)(!1),yt=(0,o.useRef)($e);yt.current=$e;let[Ot,x]=(0,o.useState)(()=>bt?.existingOrderId?{orderId:bt.existingOrderId,attempts:1}:null),A=(0,o.useRef)(Ot);(0,o.useEffect)(()=>{A.current=Ot},[Ot]);let D=(0,o.useRef)(null),re=(0,o.useMemo)(()=>{if(tt||Ee.claimBuyerIdentity||_?.buyerIdentified!==!1||!e||!t)return;let i=`${k}|${e}|${t}`;D.current?.key!==i&&(D.current={key:i,claim:qo(new xn.PaymentAPI(k,{telemetry:!1}),e,t,{...s?{userId:s}:{},...C?{firstName:C}:{},...R?{lastName:R}:{}})});let w=D.current.claim;return async Y=>{await w(Y)}},[tt,Ee.claimBuyerIdentity,_?.buyerIdentified,e,t,k,s,C,R]),ge=tt??Ee.claimBuyerIdentity??re,De=y??Br,Pt=(0,o.useMemo)(()=>(0,d.resolveTheme)(st),[st]),ne=(0,o.useMemo)(()=>{let i=Pt?.buttonsLayout??(0,d.resolveButtonsLayoutTheme)(Ke);return B?{...i,...B,cardButton:{...i.cardButton,...B.cardButton},cardFormContainer:{...i.cardFormContainer,...B.cardFormContainer},backButton:{...i.backButton,...B.backButton},backButtonIcon:{...i.backButtonIcon,...B.backButtonIcon},submitButton:{...i.submitButton,...B.submitButton},title:{...i.title,...B.title}}:i},[Pt,Ke,B]),Mt=St??Pt?.appearance,Wr=(0,o.useMemo)(()=>(0,d.computeVaultCardThemeColors)({appearance:Mt,buttonsStyles:ne,layout:Ae}),[Mt,ne,Ae]),Er=Ee.inlineSessionPatchProcessing??!1,ye=(M??V)||Er,dt=k.replace(/\/+$/,""),oe=(0,o.useMemo)(()=>Ji({userId:s,email:a,firstName:C,lastName:R,country:q,zip:Ve},Yr),[s,a,C,R,q,Ve,Yr]),Rt=[oe.firstName,oe.lastName].filter(i=>!!i?.trim()).join(" "),wt=!(0,d.isValidEmail)(oe.email?.trim()),$r=(0,o.useRef)(null);ve&&$r.current===null&&($r.current=wt);let Ft=ve&&($r.current??wt),Io=(0,o.useMemo)(()=>Yd(ur,Ft),[ur,Ft]),_o=Io.empty||Io.malformed,cn=(0,o.useMemo)(()=>Be?Be.getRawProvider():null,[Be]),_s=(0,o.useMemo)(()=>Lt?Lt.getRawProvider():null,[Lt]),ra=nt||100,To=cr.toLowerCase(),Ti=(0,o.useMemo)(()=>Mt?(0,xn.toStripeAppearance)(Mt):null,[Mt]),Mo=Ti,Ts=(0,o.useMemo)(()=>{let i=Ti??{},w=i.rules??{};return{...i,rules:{...w,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...w[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...w[".AccordionItemContents"]??{}}}}},[Ti]),Ms=(0,o.useMemo)(()=>({...El(nt,We?.captureMethod,Ge),currency:To,...Mo?{appearance:Mo}:null}),[nt,To,We?.captureMethod,Ge,Mo]),Mi=(0,d.resolveSetupFutureUsage)(Ge,"paypal","paypal"),xs=(0,o.useMemo)(()=>({mode:"payment",amount:ra,currency:To,captureMethod:"manual",...Mi?{setupFutureUsage:Mi}:null,...Mo?{appearance:Mo}:null}),[ra,To,Mi,Mo]),je=(0,o.useCallback)(i=>{dr(i),g?.(i)},[g]),As=(0,o.useRef)(0);(0,o.useEffect)(()=>{Ur!==As.current&&(As.current=Ur,je(null))},[Ur,je]);let xi=(0,o.useRef)(""),[Fs,Ic]=(0,o.useState)(!1),Ai=(0,o.useCallback)(()=>{Ic(!0)},[]);(0,o.useEffect)(()=>{if(!ve||!Ft||!ge||!Fs||_o||xi.current)return;let i=(0,hn.compactBuyerIdentity)({email:(0,d.isValidEmail)(oe.email?.trim())?oe.email?.trim():Zt.current.trim(),firstName:oe.firstName?.trim(),lastName:oe.lastName?.trim()});xi.current=JSON.stringify(i),at(w=>({...w,...i})),Promise.resolve(ge(i)).catch(w=>{xi.current="",je(w instanceof Error?w.message:"Failed to attach buyer details.")})},[ve,Ft,ge,Fs,_o,oe.email,oe.firstName,oe.lastName,je]),(0,o.useEffect)(()=>{!ve||!ae||ae.setCardFieldOrder?.(Q??null,Je==null&&!Ft)},[ve,ae,Q,Je,Ft]),(0,o.useEffect)(()=>{(ct==="expanding"||ct==="collapsing"||ct==="apm-expanding"||ct==="apm-collapsing")&&je(null)},[ct,je]);let Ln=(0,o.useCallback)((i,w,Y)=>{m?.(_r(i,w,Y))},[m]),Bs=(0,o.useRef)(ct);Bs.current=ct;let[Ds]=(0,o.useState)(ti),Os=(0,o.useCallback)(()=>{let i=Bs.current;if(Ae==="buttons"&&(i==="card"||i==="expanding"))return!0;let w=ce.current;return w==="validation-window"||w==="processing"||yt.current},[Ae]),Ls=(0,o.useCallback)((i,w,Y)=>{Ds.take(e)&&vr(Be)?.log(ko({...ot,presentationMode:Y?.presentationMode??"popup"},{name:ei,stage:"recovery",reason:"other_method_active",provider:Y?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:Y?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[ot,Be,Ds,e]),Fi=(0,o.useCallback)((i,w,Y)=>{Y?.telemetryReported||vr(Be)?.error(ko({...ot,presentationMode:Y?.presentationMode??"popup"},{errorCode:w?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:Y?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:Y?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:Y?.terminalReason??(w?"popup_blocked":"provider_error")}))},[ot,Be]),xo=(0,o.useCallback)((i,w,Y)=>{let Te=Y?.popupBlocked??(0,ke.isPopupBlockedError)(w);if(Os()){Fi(i,Te,Y),Ls(i,w,Y);return}Te&&T.markBlocked()&&Le(Et=>Et+1);let J=ps(i),Me=Y?.code===d.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,d.buildWalletSheetWindowMessage)(J):(0,ke.buildExternalMethodRecoveryMessage)(J,Te,lt.inAppBrowser),qt=(0,ke.getProviderErrorCode)(w),fn=(qt?.toLowerCase()==="error"?void 0:qt)??(0,ke.sanitizeExternalFailureCode)(Y?.code)??"external_payment_method_failed",vt=new d.FloPayError(Me,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:fn,popupBlocked:Te,inAppBrowser:lt.inAppBrowser,appFamily:lt.appFamily,popupCapability:T.current(),presentationMode:Y?.presentationMode??"popup"}});Fi(i,Te,Y),pe(null),Ae==="buttons"&&(Pr("buttons"),en(null)),je(Me),p?.(vt),console.error("[FloPay] External payment method failed:",{method:i,code:fn,popupBlocked:Te})},[lt,Os,Ae,p,T,Ls,Fi,je]);(0,o.useEffect)(()=>{if(!ve||!e){Qr(null);return}let i={billingApiUrl:dt,sessionId:e,nonce:t},w=(0,d.resolveVaultMountOptions)(_?.vault,i);if(w){Qr(w);return}if(!te){Qr(null);return}let Y=`${dt}\0${e}\0${t??""}`,Te=z.current;if(Te&&Te.key===Y){Qr(Te.mount);return}Qr(null);let J=!0;return new xn.PaymentAPI(dt).getVaultCapture(e,t).then(Me=>{if(!J)return;let qt=(0,d.resolveVaultMountOptions)(Me,i);qt?.verificationRequired&&!Me.html&&(z.current={key:Y,mount:qt}),qt?Qr(qt):je("Failed to load the secure card form.")}).catch(Me=>{J&&je(Me instanceof Error?Me.message:"Failed to load the secure card form.")}),()=>{J=!1}},[ve,te,le,e,_?.vault,dt,t,je]);let kn=(0,o.useRef)({onComplete:l,onError:p,updateError:je,emitDecline:Ln,resolvedAccount:oe,avsConfig:Je,avsCheckProp:rt,sessionId:e,nonce:t,baseUrl:dt,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt,serverSideCardGateway:Lr});kn.current={onComplete:l,onError:p,updateError:je,emitDecline:Ln,resolvedAccount:oe,avsConfig:Je,avsCheckProp:rt,sessionId:e,nonce:t,baseUrl:dt,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt,serverSideCardGateway:Lr};let Bi=(0,o.useRef)(!1),Ns=(0,o.useCallback)(()=>{let i=kn.current,w=i.resolvedAccount.email?.trim(),Y=(0,d.isValidEmail)(w)?w:Zt.current.trim();if(!(0,d.isValidEmail)(Y))return null;let Te=i.resolvedAccount.firstName?.trim(),J=i.resolvedAccount.lastName?.trim(),Me=xr.current.trim()||i.resolvedAccount.country?.trim()||"",qt=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.state,Me):!1,fn=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.address_line_1,Me):!1,vt=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.postal_code,Me):!1,Et=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.city,Me):!1,Bt=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.address_line_2,Me):!1,Kt=fn&&!qt&&vt?(0,d.getStateFromPostalCode)(Me,(kt.current??"").trim()):null,Po=qt?Jt.current:Kt;return{accountData:{userId:i.resolvedAccount.userId??"",email:Y,...Te?{firstName:Te}:{},...J?{lastName:J}:{},...vt&&kt.current?{zip:kt.current}:{},...Et&&fr.current?{city:fr.current}:{},...Po?{state:Po}:{},...fn&&Wt.current?{addressLine1:Wt.current}:{},...Bt&&pr.current?{addressLine2:pr.current}:{},...Me?{country:Me}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,d.isAVSFieldVisible)(i.avsConfig.country,Me),postal_code:vt,address_line_1:fn,address_line_2:Bt,city:Et,state:qt}}:{}}},[]),Us=(0,o.useRef)(c);Us.current=c,(0,o.useEffect)(()=>{c||De!==Kl||kn.current.updateError(null)},[c,De]),(0,o.useEffect)(()=>{!ve||!ae||ae.setSubmitGate?.(hr||c||_o||$e)},[ve,ae,hr,c,_o,$e]),(0,o.useEffect)(()=>{if(!ve||!ae)return;Bi.current=!1;let i=null,w=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,ce.current="idle",pe(null)},400)},Y=ae.on("submitting",()=>{Bn(!0),W.current&&clearTimeout(W.current),ce.current="validation-window",W.current=setTimeout(()=>{W.current=null,ce.current==="validation-window"&&(ce.current="processing")},Nd),pe("processing");let vt=kn.current;if(!vt.sessionId||!vt.nonce)return;let Et=Ns();if(!Et){vt.updateError("Enter a valid email address."),ce.current="idle",pe(null);return}new xn.PaymentAPI(vt.baseUrl).patchAccountSnapshot(vt.sessionId,vt.nonce,Et,{telemetryMode:"best_effort"}).catch(Bt=>{if(!zd(Bt))return;let Kt=Bt instanceof Error?Bt.message:"Please check your billing address and try again.";vt.updateError(Kt),ce.current="idle",pe(null),vt.onError?.(Bt instanceof d.FloPayError?Bt:new d.FloPayError(Kt,"api_error"))})}),Te=ae.on("complete",vt=>{(0,Tn.markSessionRecentlyCompleted)(vt.sessionId??kn.current.sessionId),ce.current="terminal",de(!1),pe("success"),setTimeout(()=>{if(Bi.current)return;Bi.current=!0;let Et=kn.current,Bt=(0,d.isAuthorizationOnlySession)(Et)||vt.outcome==="authorized",Kt=Et.serverSideCardGateway?{}:{paymentIntentId:vt.intentId};kn.current.onComplete?.(Bt?{status:"authorized",...Kt,paymentId:vt.paymentId??Et.paymentId,sessionId:vt.sessionId??Et.sessionId,authorizationExpiresAt:vt.authorizationExpiresAt??Et.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Kt,checkoutMethod:"card"})},600)}),J=ae.on("decline",vt=>{let Et=kn.current,Bt=vt.message??"Your payment was declined. Please try another card or contact your bank.";ce.current="terminal",de(!1),Et.updateError(Bt),pe("error");let Kt=vt.failureOutcome??(0,d.normalizeCheckoutFailureOutcome)(vt.declineReason)??"authorization_declined";Et.emitDecline("card",Bt,{code:Kt,declineCode:Kt}),w()}),Me=ae.on("error",vt=>{let Et=kn.current,Bt=vt.message??"There was a problem processing your payment. Please try again.";ce.current="terminal",de(!1),Et.updateError(Bt),pe("error"),Et.onError?.(new d.FloPayError(Bt,"api_error",{code:vt.failureOutcome??"capture_failed"})),w()}),qt=ae.on("challenge_dismissed",()=>{W.current&&(clearTimeout(W.current),W.current=null),ce.current="processing",de(!0),pe(null)}),fn=ae.on("blocked",()=>{if(yt.current){kn.current.updateError(Ud);return}if(!Us.current){Bn(!0);return}Ai(),kn.current.updateError(Kl)});return()=>{i&&(clearTimeout(i),i=null),W.current&&(clearTimeout(W.current),W.current=null),ce.current="idle",de(!1),pe(null),Y(),Te(),J(),Me(),qt(),fn()}},[ve,ae,Ai,Ns]);let Nn=!!bt?.clientId,na=Array.isArray(I),Oa=na&&I.length>0,zs=na&&I.includes("paypal"),La=(0,o.useRef)(null);La.current===null&&(La.current=(0,d.hasMatchingStripePayPalReturn)());let Ao=La.current?"redirect":(0,qn.resolveStripePayPalPresentation)(lt,xe,T.current()),{expressMethods:Na,paymentElementMethods:Di}=(0,o.useMemo)(()=>(0,d.partitionStripeMethods)(I,{excludePaypal:Nn}),[I,Nn]),qs=Nn||!!Lt||zs&&Ao==="redirect",_c=(0,o.useMemo)(()=>qs?Na.filter(i=>i!=="paypal"):Na,[Na,qs]),Tc=(0,o.useMemo)(()=>{let i=[];return Pe&&i.push("apple_pay"),fe&&i.push("google_pay"),i},[Pe,fe]),Fo=na?_c:Tc,Mc=v&&Fo.length>0,js=wr?Yt:q,Ua=(0,o.useMemo)(()=>(0,d.filterStripeMethodsByCountryGate)(Di,js,se),[Di,js,se]),Oi=(0,o.useMemo)(()=>({mode:"payment",amount:ra,currency:To,paymentMethodCreation:"manual",appearance:Ts}),[ra,To,Ts]),[Vs,Ws]=(0,o.useState)("loading"),[$s,Hs]=(0,o.useState)("loading"),[Ks,Gs]=(0,o.useState)("loading"),[xc,Li]=(0,o.useState)(!1),[Ys,Ni]=(0,o.useState)("loading"),[Ui,Ac]=(0,o.useState)();(0,o.useEffect)(()=>{Ac((0,zn.detectPayPalEnvironment)())},[]);let za=Ui?.inAppBrowser,qa=Ui?(0,qn.resolvePayPalPresentationMode)(Ui,bt?.approvalPresentation,Dt??(Re?"subscription":"order")):"popup",Xs=he&&(Nn||(na?zs:za===!1)),Fc=lt.inAppBrowser&&T.current()==="blocked",Js=v&&Mc&&!Fc,oa=(!j||!!Ee.waitForDataAttachment)&&Xs&&Nn,Zs=Ys==="retrying"||Ys==="exhausted",aa=null;v&&(Lt?aa=_s:Ao==="redirect"&&(aa=cn));let Qs=(0,o.useMemo)(()=>({...ot,presentationMode:Ao}),[ot,Ao]),ia=!j&&Xs&&!!aa&&(!Nn||Zs),Bo=!j&&Js&&!!cn,sa=!j&&v&&Oa&&Ua.length>0&&!!cn,Bc=oa&&!Zs?xc:ia&&as(Vs),Dc=Bo&&as($s),Oc=sa&&Ks!=="load_error",el=i=>i==="loading"||i==="ready",tl=oa||ia&&el(Vs)||Bo&&el($s)||sa&&Ks!=="load_error",ja=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!ja.current){if(!v&&!he){ja.current=!0;let i=new d.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),je(i.message)}else if(!v&&he&&!Nn){ja.current=!0;let i=new d.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),je(i.message)}else if(za!==void 0&&!j&&!rr&&!tl){ja.current=!0;let i=new d.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(i),je(i.message)}}},[v,he,Nn,za,j,rr,tl,p,je]);let rl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(rl.current||!Oa)return;let i=[];Pe!==!0&&i.push("showApplePay"),fe!==!0&&i.push("showGooglePay"),i.length!==0&&(rl.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Oa,Pe,fe]);let nl=(0,o.useCallback)((i,w,Y)=>Ee.applyInlineSessionPatch?Ee.applyInlineSessionPatch(i).then(Te=>({error:null,sessionId:Te.sessionId||e,nonce:Te.session?.clientSecret||t})).catch(Te=>{let J=(0,d.normalizeBeforeButtonClickError)(w,Te);return Y?.abandoned?.()||(je(J.message),p?.(J)),{error:J,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ee.applyInlineSessionPatch,t,p,e,je]),Rn=(0,o.useCallback)(async(i,w)=>{if(i!=="card"&&j&&await Ee.waitForDataAttachment?.(),!Ue)return{proceed:!0};try{let Y=await Ue({method:i,sessionId:e||void 0,createSession:Ee.inlineSessionDraft});if(Y===!1)return{proceed:!1};if(Y&&typeof Y=="object"){Y.account&&at(J=>({...J??{},...Y.account}));let Te=await nl(Y,i,w);return Te.error?{proceed:!1,accountPatch:Y.account}:{proceed:!0,accountPatch:Y.account,sessionId:Te.sessionId,nonce:Te.nonce}}return{proceed:!0}}catch(Y){if(!w?.abandoned?.()){let Te=(0,d.normalizeBeforeButtonClickError)(i,Y);je(Te.message),p?.(Te)}return{proceed:!1}}},[nl,Ee.inlineSessionDraft,Ee.waitForDataAttachment,j,Ue,p,e,je]),ol=(0,o.useCallback)(async(i,w)=>{if(X.current)return;X.current=!0,Ut(!0),pe("processing"),je(null);let Y=w?.sessionId??e,Te=w?.nonce??t,J=Ji(oe,w?.accountPatch),Me=w?.completionPaymentMethodId??ga(i),qt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,fn=Wd(i),vt=w?.presentationMode?li(vr(Be),{...ot,presentationMode:w.presentationMode}):void 0,Et=()=>{It?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:fn}),vt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Mn,requestCategory:"process_payment"})};try{let Bt=new xn.PaymentAPI(dt),Kt=await Bt.processPayment(J.userId??"",{sessionId:Y,nonce:Te,paymentMethodCategory:w?.paymentMethodCategory??Hd(i),tokenizedData:qt,accountData:{...w?.accountPatch,userId:J.userId??"",email:J.email??"",firstName:J.firstName||void 0,lastName:J.lastName||void 0,...(0,d.buildProcessPaymentAvsAccount)({avsConfig:Je,country:xr.current,zip:kt.current,city:fr.current,state:Jt.current,addressLine1:Wt.current,addressLine2:pr.current})},...(0,d.buildCheckoutProcessMetadata)({chv:H,avsCheck:rt,checkoutType:Fe,checkoutLayout:et,avsConfig:Je,country:xr.current})}),Po=async Ir=>{let vo=(0,d.isAuthorizationOnlySession)(_)||Ir?.status==="authorized";(0,Tn.markSessionRecentlyCompleted)(Y),vt?.terminal({outcome:"payment_succeeded",...Mn}),pe("success"),x(null),await new Promise(ma=>setTimeout(ma,600));let Un;typeof Ir?.paymentId=="string"?Un=Ir.paymentId:_?.paymentId&&(Un=_.paymentId);let Co;typeof Ir?.authorizationExpiresAt=="string"?Co=Ir.authorizationExpiresAt:_?.authorizationExpiresAt&&(Co=_.authorizationExpiresAt),l?.(vo?{status:"authorized",...Un===void 0?{}:{paymentId:Un},sessionId:typeof Ir?.sessionId=="string"?Ir.sessionId:Y,...Co===void 0?{}:{authorizationExpiresAt:Co},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Me,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Me,checkoutMethod:i.isPaypal?"paypal":"card"})};if(Kt.ok){await Po(Kt.status===204?null:await Kt.json().catch(()=>null));return}let dn=await Kt.json().catch(()=>null);if(dn?.type==="paypal_redirect_required"){let Ir=dn.threeDSecureToken,vo=dn.paymentMethodId||i.id||"";if(!Be||!Ir){pe("error"),je("PayPal authorization required but no token provided.");return}try{let Un=Lt?.getRawProvider();if(!Un){je("PayPal is not available.");return}let Co={return_url:window.location.href};vo&&(Co.payment_method=vo);let{error:ma}=await Un.confirmPayment({clientSecret:Ir,confirmParams:Co,redirect:"if_required"});if(ma){pe("error");let gl=ma.message??"PayPal payment failed.";je(gl),Ln("paypal",gl,{code:ma.code})}}catch(Un){pe("error"),je(Un instanceof Error?Un.message:"PayPal authorization failed.")}return}if(dn?.type==="paypal_direct_required"){let Ir=dn.orderId;if(!Ir){pe("error"),je("PayPal retry required but no order id provided.");return}let vo=A.current?.attempts??0;if(vo>=2){pe("error"),je("PayPal payment could not be completed after multiple attempts."),Ln("paypal","paypal_direct_required retry limit exceeded");return}Li(!1),Ni("loading"),x({orderId:Ir,attempts:vo+1}),pe(null);return}if(Kt.headers.get(xd)===Ad){let Ir=await Fd(Bt,Y,Te);if(Ir!==void 0){await Po(Ir);return}}(0,d.classifyPaymentRejection)(Kt.status,dn)?vt?.terminal({outcome:"payment_declined",...Mn,terminalReason:"provider_declined"}):Et(),pe("error");let fl=dn?.message??"Payment failed. Please try again.";je(fl),Ln(i.isPaypal?"paypal":"card",fl,{code:dn?.code??dn?.gatewayErrorCode,declineCode:dn?.declineCode??dn?.gatewayDeclineReason}),await new Promise(Ir=>setTimeout(Ir,400))}catch(Bt){rc(Bt)||Et(),pe("error"),je(Bt instanceof Error?Bt.message:"An unexpected error occurred"),await new Promise(Kt=>setTimeout(Kt,400))}finally{Ut(!1),pe(null),X.current=!1}},[dt,e,t,oe,Je,rt,Fe,et,H,Be,Lt,_,l,je,Ln,It,ot]),tn=(0,o.useCallback)((i,w)=>{S?S(i):ol(i,w)},[S,ol]),la=`${ec}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(la);if(!i)return;let w;try{w=JSON.parse(i)}catch{sr(la);return}if(!w||typeof w.createdAt!="number"||Date.now()-w.createdAt<0||Date.now()-w.createdAt>tc||typeof w.paymentMethodId!="string"||typeof w.providerIntentId!="string"||typeof w.paymentMethodType!="string"||w.sessionId!==e||!t||w.nonce!==t||!Fo.includes(w.paymentMethodType)){sr(la);return}sr(la),tn({id:w.paymentMethodId,type:"card",threeDSecureActionResultTokenId:w.providerIntentId,gateway:"stripe",paymentMethodType:w.paymentMethodType},{...w.accountPatch?{accountPatch:w.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[tn,t,e,la,Fo]);let al=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||al.current)return;let[i,w,Y]=(0,d.readStripeRedirectParams)();if(!i||!w||La.current||!Be)return;let Te=Be.getRawProvider();if(!Te)return;let J=Et=>{let Bt=localStorage.getItem(Et);if(!Bt)return null;try{return JSON.parse(Bt)}catch{return sr(Et),null}},Me=J(Vn)??J(Wl),qt;if(Me?.clientSecret){if(Me.clientSecret!==w)return;qt={...Me.accountPatch?{accountPatch:Me.accountPatch}:{},...Me.sessionId?{sessionId:Me.sessionId}:{},...Me.nonce?{nonce:Me.nonce}:{}}}else if(Me?.sessionId&&Me.sessionId!==e)return;al.current=!0,sr(Vn),sr(Wl),window.history.replaceState({},"",(0,d.stripeRedirectReturnUrl)());let fn=Me?.paymentMethodType??Me?.tokenType??"card",vt="card";(async()=>{if(Y==="failed"){let Zn="Payment was declined. Please try again.";je(Zn),Ln(vt,Zn);return}let{paymentIntent:Et,error:Bt}=await Te.retrievePaymentIntent(w);if(Bt){let Zn=Bt.message??"Failed to retrieve payment status.";je(Zn),Ln(vt,Zn,{code:Bt.code});return}let Kt=Et?.status,Po=fa(Kt);if(!Et||!Po){let Zn=Kt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";je(Zn),Ln(vt,Zn,{code:Kt??"missing_payment_intent"});return}let dn=typeof Et.payment_method=="string"?Et.payment_method:Et.payment_method?.id;tn({id:dn??Me?.paymentMethodId??Me?.tokenId??Et.id,type:"card",threeDSecureActionResultTokenId:Et.id,gateway:Me?.gateway??"stripe",paymentMethodType:fn},qt)})()},[e,tn,Be,je,Ln]);let zi=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(ve||Be!==null))return(0,u.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ca=Ae==="buttons",rn=Mt?.variables,Lc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),qi=rn?.colorBackground,Nc=qi&&!Lc.has(qi)?qi:void 0,da=ne.cardInputBorder??(ca?"#e5e7eb":"#A4A4FF"),il=rn?.colorDanger??"#dc2626",er=i=>Nr[i]&&(so[i]||Qt),Va=_o&&(On||Qt),yn=i=>i?il:da,Wa=(Nt.malformed||Nt.empty)&&(Kn||Qt),Uc=yn(Wa),ji=ne.cardFormContainer?.backgroundColor??Nc??(ca?"white":"#EDEDFF"),Do=ne.cardInputBackground??rn?.colorBackground??"white",Vi=No(Ne),sl=No(me),Oo=ne.nameInput,ll=ne.cardInputFontSize??Xd(Oo?.fontSize)??rn?.fontSizeBase??"16px",cl=typeof Oo?.fontFamily=="string"?Oo.fontFamily:rn?.fontFamily??"Poppins, sans-serif",dl=(0,d.toCssWeight)(Oo?.fontWeight)??400,zc=ne.cardInputColor??(typeof Oo?.color=="string"?Oo.color:void 0)??rn?.colorText??"#262833",qc=ne.cardInputPlaceholderColor??"#9ca3af",ar=rn?.borderRadius??"8px",go=rn?.borderRadius??ne.cardButton?.borderRadius??ar,ho=rn?.colorPrimary??"#4A49FF",jc=rn?.colorPrimaryHover??(0,d.darkenHex)(ho,.12),Wi=rn?.colorText??"#262833",$i={fontSize:ll,fontFamily:cl,fontWeight:dl,color:zc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ua={marginTop:"0.375rem",...$i,fontSize:"0.75rem",lineHeight:1.4,color:il},Vc={"--flopay-input-placeholder-color":qc,"--flopay-input-font-size":ll,"--flopay-input-font-family":cl,"--flopay-input-font-weight":String(dl)},pa=ne.cardFormContainer??{},Hi=pa.padding??(ca?"0":"1rem"),Ki=pa.borderRadius??ar,Wc=ae&&sn?(0,u.jsx)(po,{capture:ae,html:sn.html,messageToken:sn.messageToken,expectedOrigin:sn.expectedOrigin,verificationRequired:sn.verificationRequired,theme:Wr,submitLabel:Z,onReady:()=>{if(!Ft&&!Je||typeof document>"u")return;let i=()=>{let Y=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(Y){Ar.current=!0;try{Y.focus()}finally{Ar.current=!1}}};mn.current||i()},onError:i=>{i&&sn.verificationRequired&&ce.current==="idle"&&(Jn.current=!0),je(i)},onValidation:i=>{let w=ce.current;(w==="idle"||w==="validation-window")&&(je(i),i&&ce.current==="validation-window"&&(W.current&&(clearTimeout(W.current),W.current=null),ce.current="idle",pe(null)))}},Ur):(0,u.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ul=(0,u.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&wn()},style:{backgroundColor:ji,borderRadius:Ki,...pa,padding:Hi,...Vc,display:"flex",flexDirection:"column"},children:[(0,u.jsx)("style",{children:`
|
|
30
|
+
`,Jo=44;function Zo(){return(0,xr.jsx)("style",{children:wd})}function Ra(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function Ea({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,xr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,xr.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,xr.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 as(e){return e!=="unavailable"&&e!=="load_error"}function di({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:l,backgroundColor:p,borderColor:m,textColor:h,borderRadius:R,fontFamily:w}){let I=(0,lo.resolveStripeMethodBrandVariant)(e,t),Y=Wl[e],[_,Z]=(0,$l.useState)(!1),A=!!Y&&!_,y=I?.backgroundColor??p??"#ffffff",P=I?.borderColor??m??"#d1d5db",me=I?.textColor??h??"#262833";return(0,xr.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:Jo,padding:"0 1rem",backgroundColor:y,color:me,border:`1px solid ${P}`,borderRadius:R??8,fontSize:"0.95rem",fontWeight:600,fontFamily:w,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,xr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,lo.getStripeMethodDisplayName)(e)}\u2026`}):(0,xr.jsxs)(xr.Fragment,{children:[(0,xr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,lo.hasVendoredStripeMethodLogo)(e)?8:0},children:[A?(0,xr.jsx)("img",{src:Y,alt:"","aria-hidden":"true",onError:()=>Z(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!A&&I?.logoSvg?(0,xr.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,xr.jsx)("span",{children:(0,lo.getStripeMethodDisplayName)(e)})]}),s&&(0,xr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:me,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,xr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function ui(e){let t=new Set(e.map(lo.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var pi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},mi={type:"accordion",defaultCollapsed:!1,radios:"never"};function yi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:l,children:p}){return(0,xr.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:s,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...l??{}},children:p})}var mn=require("react");var Ia=require("@flopay/shared"),kd=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 Rd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return kd.has(t.charAt(0).toLowerCase()+t.slice(1))}function Ed(e,t){return typeof t=="number"&&t!==0&&!Rd(e)?`${t}px`:String(t).trim()}function Hl(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]=Ed(r,n)}}}var Eo=require("react/jsx-runtime"),is=new WeakSet;function go({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:l,containerStyle:p,onReady:m,onError:h,onValidation:R}){let w=(0,mn.useRef)(null),I=(0,mn.useRef)(m),Y=(0,mn.useRef)(h),_=(0,mn.useRef)(R);I.current=m,Y.current=h,_.current=R;let Z=(0,mn.useRef)(s);Z.current=s;let A=(0,mn.useRef)(null),y=l??void 0,P=(0,mn.useRef)(y);P.current=y;let me=(0,mn.useRef)(void 0);return(0,mn.useEffect)(()=>{let S=w.current;if(!S)return;let xe=!0,T=!1,le=()=>{!xe||T||(T=!0,I.current?.())},ye=e.on("ready",()=>{le()}),pe=e.on("error",B=>{Y.current?.(B.message??"There was a problem loading the secure card form.")}),Re=e.on("validation",B=>{_.current?.(B.message??null)}),lt=P.current??(is.has(e)?null:void 0),$e={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...Z.current?{theme:Z.current}:{},...lt===void 0?{}:{submitLabel:lt}};return A.current=Z.current??null,me.current=P.current,P.current!==void 0&&is.add(e),e.mount(S,$e).then(()=>{le()}).catch(B=>{xe&&Y.current?.(B instanceof Error?B.message:"Failed to load the secure card form.")}),()=>{xe=!1,ye(),pe(),Re(),e.unmount()}},[e,t,r,n,a]),wo(()=>{let S=w.current;S&&Hl(S,p)},[p]),(0,mn.useEffect)(()=>{s!==void 0&&(s===null&&A.current===null||(A.current=s,e.applyTheme?.(s)))},[e,s]),(0,mn.useEffect)(()=>{y!==me.current&&(me.current=y,y!==void 0&&is.add(e),e.setSubmitLabel?.(y??null))},[e,y]),(0,Eo.jsx)("div",{ref:w,"data-testid":"flopay-vault-card-fields"})}function fi({label:e}){return(0,Eo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,Eo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,Eo.jsx)("span",{children:e}),(0,Eo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var hs=require("@flopay/shared"),u=require("react/jsx-runtime"),Gn="flopay_stripe_resume",Kl="flopay_wallet_resume",nc="fw1",Id="fw2",oc=300*1e3,_d=900,Td="express_checkout_click_timeout",Md=25e3,xd=25e3,Ad=1e4,Dn={provider:"paypal",paymentMethodCategory:"paypal"},Fd="x-flopay-process-result-source",Bd="status";async function Dd(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 gi={},Ta=class{constructor(t){this.reason=t}};function Od(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function dr(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 ys(e){return`${Id}:${e}`}function hi(e){return dr(ys(e))}function Pi(e,t){if(typeof window>"u")return null;let r=ys(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>oc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(hi(e),null):a}catch{return hi(e),null}}function Ld(e){return dr(ys(e.sessionId),e)}function Gl(e,t,r){let n=Pi(e,t);return!n||n.clientSecret!==r?!1:hi(e)}function ss(e,t,r){if(typeof window>"u")return;Pi(e,t)?.clientSecret===r&&hi(e)}function Nd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ls(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":ya(e.status),a=Nd(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Yl(e,t,r){let n=null;try{return await Promise.race([Il(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Ad),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Ud(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function ac(e){return e instanceof d.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function vi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new On.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw ac(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var cs=d.STRIPE_PAYPAL_RESUME_KEY,_a=new Map,zd=250,Xl="Just a moment \u2014 we are finalizing your order. Please press pay again.",qd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function fs(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 Ci({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new On.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function jd(e){return e instanceof d.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ic({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,jo.splitFullName)(r),l=s.firstName?s:(0,jo.splitFullName)(n?.name);return(0,vn.compactBuyerIdentity)({email:(0,d.isValidEmail)(a)?a:n?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Vd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let l=ic({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,d.isValidEmail)(l.email)?l:s(a,l)}var Ma=180,Jl=`flopay-card-enter ${Ma}ms cubic-bezier(0, 0, 0.2, 1) both`,Zl=`flopay-card-exit ${Ma}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Wd=`flopay-buttons-enter ${Ma}ms cubic-bezier(0, 0, 0.2, 1) both`,$d=`flopay-buttons-exit ${Ma}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Hd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function gs(e){return(0,d.derivePrimaryTileStyle)(e)}var Kd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Gd(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 us={width:"100%",minHeight:Jo,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 Ql(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ps(e){return e==="paypal"?"PayPal":(0,d.getStripeMethodDisplayName)(e)}function Yd(e){let t=(0,d.getPostalCodeExample)(e);return`Enter a valid ${(0,d.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Xd(e,t,r){let n=(0,d.isPostalCodeSupported)(e),a=t.trim(),s=r&&n,l=s&&!a,p=s&&!!a&&!(0,d.isValidPostalCode)(e,a);return{visible:r,supported:n,required:s,empty:l,malformed:p}}function Jd(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,d.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function Zd(e){return typeof e=="number"?`${e}px`:e}function bi(e){return(0,u.jsx)(tu,{...e})}function ec({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:l=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:h,runBeforeButtonClick:R,billingName:w,onBuyerIdentityReady:I,onLoadStateChange:Y,placeholderBorderRadius:_,popupCapabilityOwner:Z,externalTelemetryContext:A,presentationMode:y}){let P=io(),{emitInstrument:me}=(0,o.useContext)(Pn),S=(0,cr.useStripe)(),xe=(0,cr.useElements)(),T=(0,o.useMemo)(()=>ci(wr(P),A),[A,P]),[le,ye]=(0,o.useState)("loading");(0,o.useEffect)(()=>{Y?.(le)},[le,Y]);let[pe,Re]=(0,o.useState)(!1),lt=(0,o.useRef)(!1),$e=!(0,d.isValidEmail)(r?.trim())||!w?.trim(),{request:B,collect:wt,finish:Ye}=Vo(),Ne=(0,o.useRef)(!1),ue=(0,o.useRef)(null),ne=(0,o.useRef)(null),[K,Le]=(0,o.useState)(0),[nt,je]=(0,o.useState)(!1),X=(0,o.useRef)(!1),$=(0,o.useRef)(new Map),{startAttempt:H,finishAttempt:V,invalidateAttempt:Ve,isAttemptInvalidated:De,isAttemptCurrent:fe,generationRef:D}=Pa((be,M,gt)=>{h?.(be,M,{...gt,popupBlocked:gt?.popupBlocked??(0,ke.isPopupBlockedError)(M),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y,terminalReason:"overlay_timeout"}),je(!0),Le(ct=>ct+1)},{onHandoffObserved:()=>{Z.markAvailable(),T?.log({name:"provider.popup.opened",stage:"overlay_open",...Dn,attempt:D.current})}});(0,o.useEffect)(()=>{nt&&ne.current?.focus()},[nt,K]);let ge=(0,o.useCallback)(()=>{Le(be=>be+1)},[]),pt=(0,o.useCallback)((be,M,gt)=>{Ve(gt),h?.("paypal",be,{code:M,popupBlocked:(0,ke.isPopupBlockedError)(be),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y}),je(!0),ge()},[Ve,h,y,ge]),Ue=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ue.current?.querySelector("iframe")??ue.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{X.current&&(X.current=!1,Ue())},[Ue,K]);let ot=(0,o.useCallback)(()=>{je(!1),s?.(null),Ue()},[Ue,s]);(0,o.useEffect)(()=>{if(!S||Ne.current)return;let[be,M,gt]=(0,d.readStripeRedirectParams)();if(!be||!M)return;let ct=(0,d.readMatchingStripePayPalContinuation)(M);if(!ct)return;Ne.current=!0;let N=!0,Fe=_a.get(M);Fe||(Fe=gt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>S.retrievePaymentIntent(M)),_a.set(M,Fe));let Lt={accountPatch:ct.accountPatch,sessionId:ct.sessionId,nonce:ct.nonce},Se=()=>{T?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Dn,requestCategory:"provider_sdk"})};return T?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Dn}),(async()=>{try{Re(!0);let b=await Fe;if(!N)return;if(b?.error){_a.delete(M),Se(),s?.(b.error.message??"Failed to retrieve PayPal payment status.");return}if((0,d.clearStripePayPalReturn)(),_a.delete(M),gt==="failed"){let Be="PayPal payment was declined. Please try again.";T?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}),s?.(Be),m?.(Sr("paypal",Be));return}let x=b?.paymentIntent;if(x&&x.id!==be){Se(),s?.("Failed to match the returned PayPal payment.");return}if(x&&(x.status==="requires_capture"||x.status==="succeeded")){let Be=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id;a({id:Be??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0},{...Lt,presentationMode:"redirect"})}else{let Be="PayPal payment was not completed. Please try again.";T?.terminal({outcome:x?.status==="canceled"?"payment_cancelled":"payment_declined",...Dn,terminalReason:x?.status==="canceled"?"cancelled":"provider_declined"}),s?.(Be),m?.(Sr("paypal",Be))}}catch(b){if(!N)return;_a.delete(M),Se(),s?.(b instanceof Error?b.message:"Failed to complete PayPal payment.")}finally{N&&Re(!1)}})(),()=>{N=!1,Ne.current=!1}},[S,a,s,m,T]);let Ae=(0,o.useCallback)(async(be=!1)=>{let M=R?await R("paypal"):{proceed:!0};if(!M.proceed)return $.current.delete(K),!1;let gt=H("paypal");return $.current.set(K,{generation:gt,accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}),je(!1),T?.log({name:`provider.${be?"redirect.started":"handoff.requested"}`,stage:be?"redirect":"overlay_open",...Dn,attempt:gt}),p?.("paypal"),!0},[p,T,R,H,K]),Qe=(0,o.useCallback)(async be=>{if(l||pe||!await Ae()){be.reject();return}be.resolve()},[l,Ae,pe]),at=(0,o.useCallback)(async be=>{if(!S||!xe)return;let M=$.current.get(K);if(M&&!fe(M.generation)){$.current.delete(K);return}if(!M&&De()||M&&!V(M.generation))return;M||V();let gt=M??null;if($.current.delete(K),!gt&&R){let It=await R("paypal");if(!It.proceed){be.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}gt={accountPatch:It.accountPatch,sessionId:It.sessionId,nonce:It.nonce}}let ct=gt?.sessionId??e,N=gt?.nonce??t,Fe=await Vd({event:be,prepared:gt,email:r,billingName:w,methodLabel:"PayPal",collect:wt});if(!Fe){be.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Lt=Fe.email,Se={...gt?.accountPatch,...(0,vn.compactBuyerIdentity)(Fe,!0)};try{if(Re(!0),s?.(null),!ct||!(0,d.isValidEmail)(Lt))throw new Error("Missing sessionId or email for PayPal payment");await I?.(Fe);let It=S.createPaymentMethod,{error:b,paymentMethod:x}=await It({type:"paypal"});if(b){pt(b,"stripe_paypal_create_payment_method_failed",M?.generation),be.paymentFailed({reason:"fail"});return}let Be=await vi(n,me,ct,N??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:x?.id??null,intentKind:"payment"});if((0,d.isSettledSessionIntent)(Be)){be.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:Se,paymentMethodCategory:"paypal",presentationMode:y,sessionId:ct,nonce:N,settledProcessResponse:Be.response});return}if(Be.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ee=Be.clientSecret,dt={return_url:(0,d.stripeRedirectReturnUrl)()};if(x?.id&&(dt.payment_method=x.id),!dr(cs,{clientSecret:Ee,sessionId:ct,nonce:N,accountPatch:Se})&&y==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:We,paymentIntent:He}=await S.confirmPayment({clientSecret:Ee,confirmParams:dt,redirect:"if_required"});if(We){if(dr(cs),(0,ke.isProviderDecline)(We)){let c=We.message??"Your payment was declined.";T?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}),s?.(c),m?.(Sr("paypal",c,{code:(0,ke.getProviderErrorCode)(We),declineCode:(0,ke.getProviderDeclineCode)(We)})),await Ci({billingApiUrl:n,sessionId:ct,nonce:N,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,ke.getProviderErrorCode)(We)??"provider_declined"}})}else pt(We,"stripe_paypal_confirm_failed",M?.generation);return}dr(cs);let Dt=typeof He?.payment_method=="string"?He.payment_method:He?.payment_method?.id;a({id:Dt??He?.id,type:"card",threeDSecureActionResultTokenId:He?.id,isPaypal:!0},{accountPatch:Se,paymentMethodCategory:"paypal",presentationMode:y,sessionId:ct,nonce:N});return}catch(It){pt(It,"stripe_paypal_failed",M?.generation)}finally{Re(!1)}},[S,xe,e,t,r,w,wt,I,n,me,a,s,m,R,pt,V,fe,De,T,y,K]),pr=(0,o.useCallback)(async()=>{if(!(lt.current||l||pe||!S||!xe)){lt.current=!0,Re(!0);try{if(!await Ae(!0))return;await at({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{lt.current=!1,Re(!1)}}},[xe,at,l,Ae,S,pe]),Mt=y==="redirect"?(0,u.jsx)("button",{type:"button",disabled:l||pe,onClick:()=>{pr()},style:{width:"100%",minHeight:Jo,border:"1px solid #d1d5db",borderRadius:_??8,background:"#ffc439",color:"#111827",cursor:l||pe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,u.jsx)(cr.ExpressCheckoutElement,{onReady:be=>ye(Ra(be,["paypal"])),onLoadError:()=>{ye("load_error"),fs(T,"paypal","paypal","provider_error")},onClick:Qe,onConfirm:at,onCancel:()=>{let be=$.current.get(K);$.current.delete(K),T?.terminal({outcome:"payment_cancelled",...Dn,terminalReason:"cancelled",...be?{attempt:be.generation}:{}}),Ve(be?.generation),je(!1),X.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:$e,emailRequired:$e,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},K),vt=(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("div",{ref:ue,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[nt&&(0,u.jsx)("button",{ref:ne,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:us,children:"Try PayPal again"}),B&&(0,u.jsx)(Wo,{identity:B.identity,methodLabel:B.methodLabel,onComplete:Ye,onCancel:()=>Ye(null)},B.id),(0,u.jsx)("div",{style:{display:B?"none":void 0},children:Mt})]}),pe&&!B&&(0,u.jsx)(sn,{status:"processing"})]});return y==="redirect"?vt:(0,u.jsx)(Ea,{state:le,placeholderTestId:"flopay-paypal-placeholder",borderRadius:_,children:vt})}function ds(e){return e==="apple_pay"||e==="google_pay"}var Qd=200;function eu({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,d.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function tc({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:l,onErrorChange:p,onButtonClick:m,onDecline:h,onTechnicalFailure:R,runBeforeButtonClick:w,billingName:I,onBuyerIdentityReady:Y,onLoadStateChange:_,placeholderBorderRadius:Z,popupCapabilityOwner:A,externalTelemetryContext:y}){let P=io(),{emitInstrument:me}=(0,o.useContext)(Pn),S=(0,cr.useStripe)(),xe=(0,cr.useElements)(),T=(0,o.useMemo)(()=>ci(wr(P),y),[y,P]),[le,ye]=(0,o.useState)("loading");(0,o.useEffect)(()=>{_?.(le)},[le,_]);let[pe,Re]=(0,o.useState)(!1);(0,o.useEffect)(()=>{je.current=pe},[pe]);let lt=(0,o.useRef)(!(0,d.isValidEmail)(r?.trim())||!I?.trim()).current,{request:$e,collect:B,finish:wt}=Vo(),Ye=(0,o.useRef)(null),Ne=(0,o.useRef)(null),[ue,ne]=(0,o.useState)(0),[K,Le]=(0,o.useState)(()=>(0,d.shouldPreferWalletPopup)()),nt=(0,o.useRef)(K),je=(0,o.useRef)(!1),[X,$]=(0,o.useState)(!1),[H,V]=(0,o.useState)(()=>Pi(e,t)?"blocked":"idle"),[Ve,De]=(0,o.useState)("google_pay"),fe=(0,o.useRef)(null),D=(0,o.useRef)(!0),ge=(0,o.useRef)(!1),pt=(0,o.useRef)("google_pay"),Ue=(0,o.useRef)("google_pay"),ot=(0,o.useRef)(null),Ae=(0,o.useRef)(null),Qe=(0,o.useRef)(new Set),at=(0,o.useRef)(null),pr=(0,o.useRef)(null);(0,o.useEffect)(()=>(D.current=!0,()=>{D.current=!1;for(let c of Qe.current)window.clearTimeout(c);Qe.current.clear()}),[]);let Mt=(0,o.useRef)(new Map),{startAttempt:vt,finishAttempt:be,invalidateAttempt:M,isAttemptInvalidated:gt,isAttemptCurrent:ct,generationRef:N}=Pa((c,U,W)=>{R?.(c,U,{...W,popupBlocked:W?.popupBlocked??(0,ke.isPopupBlockedError)(U),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),De(c),$(!0),ne(ce=>ce+1)},{onHandoffObserved:c=>{pr.current=N.current,A.markAvailable(),T?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:N.current,...c==="apple_pay"||c==="google_pay"?{walletType:c}:{}})},defersMissingTerminal:ds,onMissingTerminalDeferred:(c,U)=>{let W=T?.now()??globalThis.performance?.now()??Date.now(),ce=at.current,E=ce?.generation===U?ce.startedAt:W;T?.performance({stage:"overlay_return",durationMs:Math.max(0,W-E),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:U,...ds(c)?{walletType:c}:{}}),T?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{X&&Ne.current?.focus()},[X,ue]);let Fe=(0,o.useRef)(0),Lt=(0,o.useRef)(!1),Se=(0,o.useCallback)(()=>{if(Fe.current>0){Lt.current=!0;return}ne(c=>c+1)},[]),It=(0,o.useCallback)(()=>{Fe.current-=1,!(Fe.current>0||!Lt.current)&&(Lt.current=!1,D.current&&ne(c=>c+1))},[]),b=(0,o.useCallback)((c,U,W,ce,E=!1)=>{M(ce),R?.(c,U,{code:W,popupBlocked:(0,ke.isPopupBlockedError)(U),telemetryReported:E,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),De(c),$(!0),Se()},[M,R,Se]),x=(0,o.useCallback)(c=>{T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...ds(c)?{walletType:c}:{}}),R?.(c,new Error("The wallet click was not ready within the time the wallet allows."),{code:Td,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),De(c),$(!0)},[R,T]),Be=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Ye.current?.querySelector("iframe")??Ye.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{ge.current&&(ge.current=!1,Be())},[Be,ue]);let Ee=(0,o.useCallback)(()=>{$(!1),p?.(null),Be()},[Be,p]),dt=(0,o.useCallback)(()=>{fe.current?.()},[]);(0,o.useEffect)(()=>{let c=null,U=()=>{c=null;let ce=(0,d.shouldPreferWalletPopup)();ce!==nt.current&&(nt.current=ce,Le(ce),!je.current&&!ct(N.current)&&Se())},W=()=>{c!==null&&window.clearTimeout(c),c=window.setTimeout(U,Qd)};return window.addEventListener("resize",W),()=>{window.removeEventListener("resize",W),c!==null&&window.clearTimeout(c)}},[N,ct,Se]),(0,o.useEffect)(()=>{let c=Pi(e,t);if(!c)return;let U=!1,W=!1,ce=async()=>{if(!W){W=!0,U||V("checking");try{let E=await Yl(S,c.clientSecret,Qe.current);if(U)return;let z=ls(E,c.providerObjectId,(0,d.isSetupIntentClientSecret)(c.clientSecret));if(z.kind==="confirmed"){if(!Gl(e,t,c.clientSecret))return;fe.current=null,V("idle"),l({id:z.paymentMethodId,type:"card",threeDSecureActionResultTokenId:z.intentId},{...c.accountPatch?{accountPatch:c.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(z.kind==="terminal"){ss(e,t,c.clientSecret),fe.current=null,V("idle"),De(c.paymentMethodType),$(!0),Se();return}V("blocked")}catch{U||V("blocked")}finally{W=!1}}};return fe.current=ce,V("blocked"),()=>{U=!0,fe.current===ce&&(fe.current=null)}},[t,l,Se,e,S]);let it=(0,o.useCallback)(async c=>{let U=!1,W=!1,ce=et=>{U||W||(U=!0,c.paymentFailed({reason:"fail",...et?{message:et}:{}}))};if(!S||!xe){ce();return}let E=Mt.current.get(ue);if(E&&!ct(E.generation)){Mt.current.delete(ue),ce();return}if(!E&>()){ce();return}if(E&&!be(E.generation)){ce();return}E||(be(),Lt.current=!1);let z=c.expressPaymentType??E?.method??pt.current,Ut=E??null,Fr=Ql(z),tr;z==="apple_pay"?tr="apple_pay":z==="google_pay"&&(tr="google_pay");let Wt=E?.generation??N.current,_t=T,$r=_t?.now()??globalThis.performance?.now()??Date.now(),Nr=new AbortController,rr=!1,Qr=!1,Tt=null,Ln=e,Xt="processing",yn="other",Hr="provider_runtime",Kr,Jt=new Promise((et,kt)=>{Kr=kt}),Pr=window.setTimeout(()=>{rr=!0,Nr.abort(),Kr(gi)},Md),en=async(et,kt,Br)=>{Xt=et,yn=kt,Hr=kt==="intent_create"||kt==="session_claim"?"transport_error":"provider_runtime";let $t=_t?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Br,Jt])}finally{let nr=_t?.now()??globalThis.performance?.now()??Date.now();_t?.performance({stage:et,durationMs:Math.max(0,nr-$t),durationMode:"machine",requestCategory:kt,paymentMethodCategory:"wallet",provider:"stripe",...rr?{statusClass:"timeout"}:{}})}};try{if(Re(!0),p?.(null),!Ut&&w){let Pe=await en("processing","other",w(Fr));if(!Pe.proceed){ce();return}Ut={accountPatch:Pe.accountPatch,sessionId:Pe.sessionId,nonce:Pe.nonce}}let et=Ut?.sessionId??e;Ln=et;let kt=Ut?.nonce??t,Br=ot.current??Ut?.accountPatch,$t=ic({event:c,fallbackEmail:Br?.email??r,fallbackName:[Br?.firstName,Br?.lastName].join(" ").trim()||I});if(!(0,d.isValidEmail)($t.email)){ce("Buyer details are required."),B(ps(z),$t).then(Pe=>{Pe&&(ot.current=Pe)});return}ot.current=null;let nr={...Ut?.accountPatch,...(0,vn.compactBuyerIdentity)($t,!0)};await en("processing","session_claim",Promise.resolve(Y?.($t)));let{error:vr}=await en("tokenization","provider_sdk",xe.submit());if(vr){ce(),b(z,vr,"stripe_wallet_submit_failed",E?.generation);return}if(!et)throw new Error("Missing sessionId or email for payment.");let Zt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:z,paymentMethodId:null,intentKind:a},Ht=JSON.stringify({sessionId:et,nonce:kt??"",request:Zt}),Rr=Ae.current,Xe=Rr?.retryIdentity===Ht?Rr.authorizationAttemptId:(0,d.randomUuidV4)();Ae.current={authorizationAttemptId:Xe,retryIdentity:Ht};let or=await en("processing","intent_create",vi(n,me,et,kt??"",{...Zt,authorizationAttemptId:Xe},{signal:Nr.signal}));if((0,d.isSettledSessionIntent)(or)){ce(),l({type:"card",paymentMethodType:z},{accountPatch:nr,paymentMethodCategory:"wallet",sessionId:et,nonce:kt,settledProcessResponse:or.response});return}if(or.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Er=or.clientSecret,Jn=Ld({createdAt:Date.now(),sessionId:et,...kt?{nonce:kt}:{},clientSecret:Er,providerObjectId:or.providerObjectId,paymentMethodType:z,accountPatch:nr});window.clearTimeout(Pr),Qr=!0,_t?.performance({stage:"callback",durationMs:Math.max(0,(_t?.now()??globalThis.performance?.now()??Date.now())-$r),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Ur=_t?.now()??globalThis.performance?.now()??Date.now(),zr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...tr?{walletType:tr}:{},attempt:Wt},Nn=!1,cn=null;_t?.log({name:"payment.provider_confirmation.started",...zr}),Tt=window.setTimeout(()=>{Tt!==null&&Qe.current.delete(Tt),Nn=!0;let Pe=_t?.now()??globalThis.performance?.now()??Date.now();_t?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...zr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Pe-Ur),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),_t?.flush?.().catch(()=>{}),cn?.()},xd),Qe.current.add(Tt);let ar=(Pe,Vt)=>{Tt!==null&&(window.clearTimeout(Tt),Qe.current.delete(Tt),Tt=null);let ae=_t?.now()??globalThis.performance?.now()??Date.now(),Nt=Math.max(0,ae-Ur),br=Pe;Nn&&(Pe==="resolved"?br="resolved_late":Pe==="returned_error"?br="returned_error_late":br="rejected_late");let qr=Vt??(Pe==="resolved"?"approved":"provider_error");return _t?.log({name:"payment.provider_confirmation.returned",...zr,operationOutcome:br,terminalReason:qr}),_t?.performance({...zr,durationMs:Nt,durationMode:"buyer",operationOutcome:br,terminalReason:qr}),{durationMs:Nt,operationOutcome:br,terminalReason:qr}},he=!1,Cr=!1,Gr=Pe=>{if(!Pe||typeof Pe!="object")return null;let Vt=Pe;if(Vt.error)return null;let ae=Vt.setupIntent??Vt.paymentIntent,Nt=ls(ae??null,void 0,!!Vt.setupIntent);return Nt.kind==="confirmed"?Nt:null},oe=Pe=>{if(he||E&&N.current!==E.generation)return;let Vt=Gr(Pe);if(!Vt)return;if(Jn&&!Gl(et,kt,Er)){he=!0;return}let{intentId:ae,paymentMethodId:Nt}=Vt;he=!0,Cr=!0,Ae.current=null,fe.current=null,D.current&&(V("idle"),Re(!1));let br=`${nc}:${et}`;dr(br,{createdAt:Date.now(),sessionId:et,nonce:kt,accountPatch:nr,paymentMethodId:Nt,providerIntentId:ae,paymentMethodType:z});try{l({id:Nt,type:"card",threeDSecureActionResultTokenId:ae},{accountPatch:nr,paymentMethodCategory:"wallet",sessionId:et,nonce:kt})}finally{dr(br)}},xt=!1;cn=async()=>{if(!(xt||he||Cr)){xt=!0,D.current&&V("checking");try{let Pe=await Yl(S,Er,Qe.current);if(he||Cr)return;let Vt=(0,d.isSetupIntentClientSecret)(Er),ae=ls(Pe,or.providerObjectId,Vt);if(ae.kind==="confirmed"){oe(Vt?{setupIntent:Pe}:{paymentIntent:Pe});return}if(ae.kind==="terminal"){if(Cr=!0,ss(et,kt,Er),Ae.current=null,fe.current=null,!D.current)return;V("idle"),ce(),b(z,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",E?.generation,!0);return}D.current&&!Cr&&(V("blocked"),Re(!1))}catch{D.current&&!Cr&&(V("blocked"),Re(!1))}finally{xt=!1}}},fe.current=cn;let Q,Kt;try{W=!0,Fe.current+=1;let Pe;try{Pe=await((0,d.isSetupIntentClientSecret)(Er)?S.confirmSetup({elements:xe,clientSecret:Er,redirect:"if_required"}):S.confirmPayment({elements:xe,clientSecret:Er,redirect:"if_required"}))}finally{It()}if(!Pe||typeof Pe!="object")throw new Ta(Od(Pe));if(Q=Pe,!Q.error&&!Gr(Q))throw new Ta("confirmation_result_unconfirmed");Kt=ar(Q.error?"returned_error":"resolved",Q.error&&(0,ke.isProviderDecline)(Q.error)?"provider_declined":void 0)}catch(Pe){let Vt=Pe instanceof Ta?Pe.reason:void 0,ae=Vt!==void 0,Nt=ar(ae?"returned_error":"rejected");if(_t?.error({...ae?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Vt}:Zi(Pe),...zr,operationOutcome:Nt.operationOutcome,durationMs:Nt.durationMs,statusClass:"unknown",terminalReason:Nt.terminalReason}),!D.current||he)return;await cn?.();return}let ir=Q.error;if(ir){if(!D.current||he)return;if((0,ke.isProviderDecline)(ir)){Cr=!0,ss(et,kt,Er),Ae.current=null,fe.current=null,V("idle"),Mt.current.get(ue)===E&&Mt.current.delete(ue);let Pe=ir.message??"Your payment was declined.";p?.(Pe),h?.(Sr(Fr,Pe,{code:(0,ke.getProviderErrorCode)(ir),declineCode:(0,ke.getProviderDeclineCode)(ir)})),Ci({billingApiUrl:n,sessionId:et,nonce:kt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:z,providerDeclineReason:(0,ke.getProviderErrorCode)(ir)??"provider_declined",...or.intentKind==="payment"&&or.providerObjectId.startsWith("pi_")?{providerIntentId:or.providerObjectId}:{}}})}else _t?.error({...Zi(ir),...zr,operationOutcome:Kt.operationOutcome,durationMs:Kt.durationMs,statusClass:"unknown",terminalReason:Kt.terminalReason}),await cn?.();return}if(oe(Q),!he)throw new Error("Invalid provider returned for APM intent")}catch(et){if(et===gi){let kt=_t?.now()??globalThis.performance?.now()??Date.now();_t?.error({errorCode:Ud(yn),stage:Xt,requestCategory:yn,paymentMethodCategory:"wallet",provider:"stripe",...tr?{walletType:tr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ln,durationMs:Math.max(0,kt-$r),statusClass:"timeout",failureCategory:Hr,attempt:Wt,terminalReason:"provider_error"}),_t?.flush?.().catch(()=>{})}ce(),b(z,et,et===gi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",E?.generation,et===gi)}finally{if(window.clearTimeout(Pr),Tt!==null&&(window.clearTimeout(Tt),Qe.current.delete(Tt)),!Qr){let et=_t?.now()??globalThis.performance?.now()??Date.now();_t?.performance({stage:"callback",durationMs:Math.max(0,et-$r),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...rr?{statusClass:"timeout"}:{}})}D.current&&Re(!1)}},[S,xe,e,t,r,I,B,Y,n,me,a,l,p,h,w,b,It,be,ct,gt,N,T,ue]),We=(0,o.useMemo)(()=>ui(s),[s]),He=(0,o.useMemo)(()=>s.map(d.stripeExpressMethodToOptionKey),[s]),Dt=(0,o.useMemo)(()=>(0,u.jsx)(cr.ExpressCheckoutElement,{onReady:c=>{ye(Ra(c,He))},onLoadError:c=>{ye("load_error"),fs(T,"stripe","wallet","provider_error")},onClick:async c=>{let U=T?.now()??globalThis.performance?.now()??Date.now();pt.current=c.expressPaymentType,Ue.current=Ql(c.expressPaymentType);let W=!0,ce=window.setTimeout(()=>{W=!1,c.reject(),x(c.expressPaymentType)},_d),E=w?await w(Ue.current,{abandoned:()=>!W}):{proceed:!0};if(window.clearTimeout(ce),!W)return;if(!E.proceed){Mt.current.delete(ue),c.reject();return}let z=vt(c.expressPaymentType);Lt.current=!1,at.current={generation:z,startedAt:U},Mt.current.set(ue,{generation:z,method:c.expressPaymentType,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),$(!1),T?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:z,...c.expressPaymentType==="apple_pay"||c.expressPaymentType==="google_pay"?{walletType:c.expressPaymentType}:{}}),m?.(Ue.current),c.resolve()},onConfirm:it,onCancel:()=>{let c=Mt.current.get(ue);Mt.current.delete(ue);let U=at.current,W=T?.now()??globalThis.performance?.now()??Date.now();if(c&&U?.generation===c.generation&&(0,d.isWalletSheetRefusedForWindowSize)({method:c.method,elapsedMs:W-U.startedAt,handoffObserved:pr.current===c.generation})){T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:c.generation,walletType:"google_pay"}),Ae.current=null,b(c.method,new Error("The browser window is too small for the Google Pay sheet."),d.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,c.generation,!0);return}T?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...c?{attempt:c.generation}:{}}),M(c?.generation),Ae.current=null,$(!1),ge.current=!0,Se()},options:{...pi,paymentMethods:We,emailRequired:lt,billingAddressRequired:lt}},ue),[He,We,it,M,m,lt,b,x,Se,w,vt,ue,T]);return(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(Ea,{state:le,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Z,children:(0,u.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:[X&&(0,u.jsxs)("button",{ref:Ne,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ee,style:us,children:["Try ",ps(Ve)," again"]}),H!=="idle"&&(0,u.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,u.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,u.jsx)("button",{type:"button",onClick:dt,disabled:H==="checking",style:us,children:H==="checking"?"Checking payment status\u2026":"Check payment status"})]}),$e&&(0,u.jsx)(Wo,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:wt,onCancel:()=>wt(null)},$e.id),(0,u.jsxs)("div",{style:{display:$e||H!=="idle"?"none":void 0},children:[(0,u.jsx)(eu,{active:K}),Dt]})]})}),pe&&(0,u.jsx)(sn,{status:"processing"})]})}function sc(e,t,r){let n=(0,d.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function ms({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:l,onTokenizedBody:p,onErrorChange:m,onDecline:h,onCancel:R,runBeforeButtonClick:w,onButtonClick:I,isProcessing:Y,submitButtonColor:_,submitButtonBorderRadius:Z,submitButtonStyle:A,errorText:y}){let P=io(),{emitInstrument:me}=(0,o.useContext)(Pn),S=(0,cr.useStripe)(),xe=(0,cr.useElements)(),[T,le]=(0,o.useState)(!1),ye=(0,o.useRef)(!1),[pe,Re]=(0,o.useState)(!1),[lt,$e]=(0,o.useState)("loading"),[B,wt]=(0,o.useState)(""),Ye=!(0,d.isValidEmail)(n?.trim()),Ne=!Ye||(0,d.isValidEmail)(B.trim()),ue=(0,o.useCallback)(async()=>{if(!S||!xe||Y||ye.current||!pe)return;ye.current=!0,le(!0);let ne=w?await w("card"):{proceed:!0};if(!ne.proceed){ye.current=!1,le(!1);return}I?.("card");let K=ne.sessionId??t,Le=ne.nonce??r,nt=(0,jo.splitFullName)(a?.trim()),je=(0,vn.compactBuyerIdentity)({email:ne.accountPatch?.email?.trim()||n?.trim()||B.trim(),firstName:ne.accountPatch?.firstName?.trim()||nt.firstName,lastName:ne.accountPatch?.lastName?.trim()||nt.lastName}),X=je.email,$=(0,vn.compactBuyerIdentity)({...ne.accountPatch,...je});try{if(m?.(null),!(0,d.isValidEmail)(X))throw new Error("A valid email address is required for payment.");await s?.(je);let H=await xe.submit();if(H.error){m?.(H.error.message??"Payment failed.");return}let V=[je.firstName,je.lastName].filter(Boolean).join(" "),Ve=await S.createPaymentMethod({elements:xe,params:{billing_details:{email:X,...V?{name:V}:{}}}});if(Ve.error||!Ve.paymentMethod){m?.(Ve.error?.message??"Failed to create payment method.");return}let De=Ve.paymentMethod;if(!K||!X)throw new Error("Missing sessionId or email for payment.");let fe=De.type||e,D=await vi(l,me,K,Le??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:fe,paymentMethodId:null,intentKind:"payment"});if((0,d.isSettledSessionIntent)(D)){p({type:"card",gateway:"stripe",paymentMethodType:fe},{accountPatch:$,paymentMethodCategory:"apm",sessionId:K,nonce:Le,settledProcessResponse:D.response});return}if(D.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ge=D.clientSecret;dr(Gn,{clientSecret:ge,sessionId:K,nonce:Le,accountPatch:$,paymentMethodId:De.id,paymentMethodType:De.type??e,gateway:"stripe"});let{error:pt,paymentIntent:Ue}=await S.confirmPayment({clientSecret:ge,confirmParams:{return_url:window.location.href,payment_method:De.id},redirect:"if_required"});if(pt){dr(Gn);let Qe=pt.message??"Payment failed.";m?.(Qe),h?.(Sr("card",Qe,{code:pt.code})),await Ci({billingApiUrl:l,sessionId:K,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:pt.code??"provider_declined"}});return}let ot=Ue?.status;if(!ya(ot)){dr(Gn);let Qe=ot==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(Qe),h?.(Sr("card",Qe,{code:ot??"missing_payment_intent"}));return}dr(Gn);let Ae=typeof Ue?.payment_method=="string"?Ue.payment_method:Ue?.payment_method?.id;p({id:Ae??De.id,type:"card",threeDSecureActionResultTokenId:Ue?.id,gateway:"stripe",paymentMethodType:De.type??e},{accountPatch:$,paymentMethodCategory:"apm",sessionId:K,nonce:Le})}catch(H){m?.(H instanceof Error?H.message:"Payment failed. Please try again.")}finally{ye.current=!1,le(!1)}},[S,xe,Y,pe,w,I,t,r,n,a,B,s,l,me,e,p,m,h]);return(0,u.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ye&&(0,u.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ye&&(0,u.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,u.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:B,onChange:ne=>wt(ne.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,u.jsx)(cr.PaymentElement,{onReady:()=>$e("ready"),onLoadError:()=>{$e("load_error"),fs(wr(P),"stripe","apm")},onChange:ne=>{Re(!!ne.complete)},options:{layout:mi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,d.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,u.jsx)(yi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ue()},disabled:!pe||!Ne||T||Y||lt!=="ready",color:_,borderRadius:Z,style:A,children:T?"Processing\u2026":`Pay with ${(0,d.getStripeMethodDisplayName)(e)}`}),y&&(0,u.jsx)(Ko,{margin:"0.75rem 0 0",children:y})]})}function rc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:l,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:h,onTokenizedBody:R,onErrorChange:w,onButtonClick:I,onDecline:Y,runBeforeButtonClick:_,onLoadStateChange:Z,isProcessing:A=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:me,buttonAppearance:S,themeId:xe,onExpandApm:T,expandedApmMethod:le}){let{emitInstrument:ye}=(0,o.useContext)(Pn),[pe,Re]=(0,o.useState)(null),[lt,$e]=(0,o.useState)(null),B=(0,o.useRef)(!1),{request:wt,collect:Ye,finish:Ne}=Vo();(0,o.useEffect)(()=>{l.length>0&&p?Z?.("ready"):p||Z?.("loading")},[l.length,p,Z]);let ue=(0,o.useCallback)(async X=>{if(!p||B.current||A)return;B.current=!0,$e(X);let $=_?await _("card"):{proceed:!0};if(!$.proceed){B.current=!1,$e(null);return}I?.("card");let H=$.sessionId??e,V=$.nonce??t,Ve=(0,jo.splitFullName)([$.accountPatch?.firstName,$.accountPatch?.lastName].filter(Boolean).join(" ")||n),De=(0,vn.compactBuyerIdentity)({email:$.accountPatch?.email?.trim()||r?.trim(),firstName:$.accountPatch?.firstName?.trim()||Ve.firstName,lastName:$.accountPatch?.lastName?.trim()||Ve.lastName});if(!(0,d.isValidEmail)(De.email)){$e(null);let ge=await Ye((0,d.getStripeMethodDisplayName)(X),De);if(!ge){B.current=!1;return}De=ge,$e(X)}let fe=De.email,D=(0,vn.compactBuyerIdentity)({...$.accountPatch,...De});try{if(w?.(null),!H||!(0,d.isValidEmail)(fe))throw new Error("Missing sessionId or email for payment.");await a?.(De);let ge=await vi(s,ye,H,V??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if((0,d.isSettledSessionIntent)(ge)){R({type:"card",gateway:"stripe",paymentMethodType:X},{accountPatch:D,paymentMethodCategory:"apm",sessionId:H,nonce:V,settledProcessResponse:ge.response});return}if(ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let pt=ge.clientSecret;dr(Gn,{clientSecret:pt,sessionId:H,nonce:V,accountPatch:D,paymentMethodType:X,gateway:"stripe"});let{error:Ue,paymentIntent:ot}=await p.confirmPayment({clientSecret:pt,confirmParams:{return_url:window.location.href,payment_method_data:{type:X,billing_details:{name:[De.firstName,De.lastName].filter(Boolean).join(" "),...fe?{email:fe}:{}}}},redirect:"if_required"});if(Ue){dr(Gn);let at=Ue.message??"Payment failed.";w?.(at),Y?.(Sr("card",at,{code:Ue.code})),await Ci({billingApiUrl:s,sessionId:H,nonce:V,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:Ue.code??"provider_declined"}});return}let Ae=ot?.status;if(!ya(Ae)){dr(Gn);let at=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";w?.(at),Y?.(Sr("card",at,{code:Ae??"missing_payment_intent"}));return}dr(Gn);let Qe=typeof ot?.payment_method=="string"?ot.payment_method:ot?.payment_method?.id;R({id:Qe??ot?.id,type:"card",threeDSecureActionResultTokenId:ot?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:D,paymentMethodCategory:"apm",sessionId:H,nonce:V})}catch(ge){w?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{B.current=!1,$e(null)}},[p,A,_,I,e,t,r,Ye,s,ye,n,a,R,w,Y]),[ne,K]=(0,o.useState)(null),Le=T?le??null:ne,nt=(0,o.useCallback)(X=>{B.current||A||Le&&Le!==X||((0,d.needsStripeMethodExplicitConfirm)(X)?T?T(X):K(X):ue(X))},[Le,A,ue,T]),je=(0,o.useMemo)(()=>ne?sc(m,ne,h):null,[ne,m,h]);return(0,u.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:wt?(0,u.jsx)(Wo,{identity:wt.identity,methodLabel:wt.methodLabel,onComplete:Ne,onCancel:()=>Ne(null)},wt.id):l.map(X=>{let $=le===X,H=lt===X,V=lt!==null&<!==X||le!=null&&le!==X;return(0,u.jsxs)(o.default.Fragment,{children:[(0,u.jsx)(di,{method:X,themeId:xe,submitting:H,disabled:V,highlighted:$,hasNextStep:(0,d.needsStripeMethodExplicitConfirm)(X),onClick:()=>nt(X),backgroundColor:S?.backgroundColor,borderColor:S?.borderColor,textColor:S?.textColor,borderRadius:S?.borderRadius,fontFamily:S?.fontFamily}),!T&&ne===X&&je&&p&&(0,u.jsx)(cr.Elements,{stripe:p,options:je,children:(0,u.jsx)(ms,{method:X,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:R,onErrorChange:w,onDecline:Y,onCancel:()=>K(null),runBeforeButtonClick:_,onButtonClick:I,isProcessing:A,submitButtonColor:y,submitButtonBorderRadius:P,submitButtonStyle:me})},X)]},X)})})}function tu({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:l,onError:p,onDecline:m,onCancel:h,onTokenizedBody:R,firstName:w,lastName:I,chv:Y,className:_,submitLabel:Z,isProcessing:A,error:y,onErrorChange:P,showPayPal:me=!0,showStripe:S=!0,walletPresentation:xe="auto",enabledPaymentMethods:T,enabledPaymentMethodCountries:le,showApplePay:ye=!0,showGooglePay:pe=!0,layout:Re="default",theme:lt,buttonsTheme:$e,buttonsStyles:B,appearance:wt,cardButtonContent:Ye,cardBackButtonContent:Ne,cardTitleContent:ue,showSecurityFooter:ne,onButtonClick:K,onBeforeButtonClick:Le,onBuyerIdentityReady:nt,enableAVS:je,cardFieldOrder:X,cardPreFormSlot:$,avsLayout:H="row",country:V,zip:Ve,addressLine1:De,addressLine2:fe,city:D,state:ge,onCountryChange:pt,onZipChange:Ue,avsCheck:ot,checkoutType:Ae,checkoutLayout:Qe,totalAmount:at=0,currency:pr="usd",initialCardOpen:Mt=!1,directPaypal:vt,isSubscription:be=!1,session:M,dataAttachmentPending:gt=!1,dataAttachmentRequiresIdentity:ct=!1,debug:N=!1}){let Fe=io(),Lt=Za(),Se=(0,o.useContext)(An),{emitInstrument:It}=(0,o.useContext)(Pn),b=(0,o.useRef)(null);b.current||(b.current=ei());let x=b.current,[,Be]=(0,o.useState)(0),Ee=(0,o.useRef)(null);Ee.current||(Ee.current=(0,$n.detectPayPalEnvironment)());let dt=Ee.current,it=(0,o.useMemo)(()=>({browser:dt,capability:x,presentationMode:"popup"}),[dt,x]),We=M??Se.session,He=(0,o.useMemo)(()=>({futureUse:We?.futureUse,futureUseUnsupported:We?.futureUseUnsupported}),[We?.futureUse,We?.futureUseUnsupported]),Dt=We?.gateways?.paypal?.providerObjectType??vt?.providerObjectType,c=gt||Se.claimPending===!0,U=ct||Se.claimRequiresIdentity===!0,W=c&&!U,ce=xl(),E=r||ce,[z,Ut]=(0,o.useState)(!1),[Fr,tr]=(0,o.useState)(null),[Wt,_t]=(0,o.useState)(V??""),[$r,Nr]=(0,o.useState)(Ve??""),[rr,Qr]=(0,o.useState)(De??""),[Tt,Ln]=(0,o.useState)(fe??""),[Xt,yn]=(0,o.useState)(D??""),[Hr,Kr]=(0,o.useState)(ge??""),[Jt,Pr]=(0,o.useState)(""),[en,et]=(0,o.useState)({}),kt=(0,o.useRef)(Ve??""),Br=(0,o.useRef)(V??""),$t=(0,o.useRef)(De??""),nr=(0,o.useRef)(fe??""),vr=(0,o.useRef)(D??""),Zt=(0,o.useRef)(ge??""),Ht=(0,o.useRef)(""),Rr=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(C,G,Te,J,Me)=>{if(Rr.current[C])return;let qt=G?.trim();!qt||qt===Te.current||(Te.current=qt,J(qt),Me?.(qt))};i("country",V,Br,_t,pt),i("zip",Ve,kt,Nr,Ue),i("addressLine1",De,$t,Qr),i("addressLine2",fe,nr,Ln),i("city",D,vr,yn),i("state",ge,Zt,Kr)},[V,Ve,De,fe,D,ge,pt,Ue]);let Xe=(0,o.useMemo)(()=>(0,d.resolveAVSConfig)(je),[je]),or=Xe!==null,Er=(0,o.useMemo)(()=>(0,d.isAuthorizationOnlySession)(M),[M]),Jn=(0,d.isMountableVaultBlock)(M?.vault),Ur=!!M?.gateways?.pcivault,zr=(0,xn.hasServerSideCardGateway)(M),cn=!!(M?.gateways?.stripe?.enabledPaymentMethods??T)?.includes("card")||(0,xn.canRecoverHostedCardForm)(M),ar=Jn||cn||Ur,he=!!(S&&ar&&e),[Cr,Gr]=(0,o.useState)(()=>Re!=="buttons"||Mt?e??null:null),[oe,xt]=(0,o.useState)(0),Q=Re!=="buttons"||Mt||!!e&&Cr===e,Kt=M?.captureMethod,ir=(0,o.useRef)(Fe);(0,o.useEffect)(()=>{ir.current=Fe},[Fe]);let[Pe,Vt]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!he||!e||!Q){Vt(null);return}let i=ir.current?ir.current.cardCapture({sessionId:e,captureMethod:Kt}):new On.PciVaultCardCapture({sessionId:e,captureMethod:Kt,billingApiUrl:E,telemetry:n});return Vt({sessionId:e,captureMethod:Kt,billingApiUrl:E,telemetry:n,capture:i}),()=>{i.unmount()}},[he,e,Q,Kt,E,n]);let ae=he&&e&&Q&&Pe?.sessionId===e&&Pe.captureMethod===Kt&&Pe.billingApiUrl===E&&Pe.telemetry===n?Pe.capture:null,Nt=(0,o.useMemo)(()=>{let i=Wt,C=Xe?(0,d.isAVSFieldVisible)(Xe.postal_code,i):!1;return Xd(i,$r,C)},[Xe,Wt,$r]),{avsInvalid:br,invalidAvsFields:qr}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!he||!Xe)return{avsInvalid:!1,invalidAvsFields:i};let C=Wt,G=(Me,qt)=>(0,d.isAVSFieldVisible)(Me,C)&&!qt.trim(),Te={line1:G(Xe.address_line_1,rr),city:G(Xe.city,Xt),state:G(Xe.state,Hr),zip:Nt.empty||Nt.malformed};return{avsInvalid:Te.line1||Te.city||Te.state||Te.zip,invalidAvsFields:Te}},[he,Xe,Wt,rr,Xt,Hr,Nt]),[Qt,Un]=(0,o.useState)(!1),[Zn,zn]=(0,o.useState)(!1),[qn,Qn]=(0,o.useState)(!1),[po,mo]=(0,o.useState)({line1:!1,city:!1,state:!1}),Dr=(0,o.useRef)(!1),eo=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),fn=(0,o.useRef)(!1),zt=(0,o.useCallback)(i=>{eo.current[i]=!0,fn.current=!0},[]),tn=(0,o.useCallback)(i=>!Dr.current&&eo.current[i],[]),rn=(0,o.useCallback)(i=>{tn(i)&&mo(C=>C[i]?C:{...C,[i]:!0})},[tn]),[dn,nn]=(0,o.useState)(()=>(0,d.resolveVaultMountOptions)(M?.vault,{billingApiUrl:E,sessionId:e,nonce:t})),[ut,mr]=(0,o.useState)(Mt&&ar?"card":"buttons"),[sr,Yr]=(0,o.useState)(null),ho=ut==="expanding"||ut==="card",to=M?.gateways?.stripe&&!zr?"stripe":void 0,In=(0,o.useCallback)(()=>{It?.({class:"card_surface",provider:to})},[to,It]),un=(0,o.useRef)(null),Ir=(0,o.useCallback)(i=>{un.current&&clearTimeout(un.current),un.current=setTimeout(()=>{un.current=null,i()},Ma)},[]);(0,o.useEffect)(()=>()=>{un.current&&clearTimeout(un.current)},[]);let ro=(0,o.useRef)(!1),[jr,q]=(0,o.useState)(0),j=(0,o.useRef)(null),ie=(0,o.useCallback)(()=>{In(),Gr(e??null),ro.current&&(ro.current=!1,q(i=>i+1)),xt(i=>i+1),mr("expanding"),Ir(()=>mr("card"))},[Ir,In,e]),we=(0,o.useCallback)(()=>{mr("collapsing"),Ir(()=>mr("buttons"))},[Ir]),mt=(0,o.useCallback)(i=>{Yr(i),mr("apm-expanding"),Ir(()=>mr("apm-form"))},[Ir]),Gt=(0,o.useCallback)(()=>{mr("apm-collapsing"),Ir(()=>{mr("buttons"),Yr(null)})},[Ir]);(0,o.useEffect)(()=>{Re==="buttons"&&Mt&&ar&&(Gr(e??null),mr("card"))},[Re,Mt,ar,e]);let[Ie,de]=(0,o.useState)(null),ee=(0,o.useRef)(!1),ve=(0,o.useRef)(null),te=(0,o.useRef)("idle"),[tt,re]=(0,o.useState)(!1),Je=(0,o.useRef)(tt);Je.current=tt;let[Ze,At]=(0,o.useState)(()=>vt?.existingOrderId?{orderId:vt.existingOrderId,attempts:1}:null),_r=(0,o.useRef)(Ze);(0,o.useEffect)(()=>{_r.current=Ze},[Ze]);let g=(0,o.useRef)(null),f=(0,o.useMemo)(()=>{if(nt||Se.claimBuyerIdentity||M?.buyerIdentified!==!1||!e||!t)return;let i=`${E}|${e}|${t}`;g.current?.key!==i&&(g.current={key:i,claim:zo(new On.PaymentAPI(E,{telemetry:!1}),e,t,{...s?{userId:s}:{},...w?{firstName:w}:{},...I?{lastName:I}:{}})});let C=g.current.claim;return async G=>{await C(G)}},[nt,Se.claimBuyerIdentity,M?.buyerIdentified,e,t,E,s,w,I]),O=nt??Se.claimBuyerIdentity??f,Ce=y??Fr,_e=(0,o.useMemo)(()=>(0,d.resolveTheme)(lt),[lt]),L=(0,o.useMemo)(()=>{let i=_e?.buttonsLayout??(0,d.resolveButtonsLayoutTheme)($e);return B?{...i,...B,cardButton:{...i.cardButton,...B.cardButton},cardFormContainer:{...i.cardFormContainer,...B.cardFormContainer},backButton:{...i.backButton,...B.backButton},backButtonIcon:{...i.backButtonIcon,...B.backButtonIcon},submitButton:{...i.submitButton,...B.submitButton},title:{...i.title,...B.title}}:i},[_e,$e,B]),Ct=wt??_e?.appearance,yr=(0,o.useMemo)(()=>(0,d.computeVaultCardThemeColors)({appearance:Ct,buttonsStyles:L,layout:Re}),[Ct,L,Re]),Tr=Se.inlineSessionPatchProcessing??!1,bt=(A??z)||Tr,pn=E.replace(/\/+$/,""),se=(0,o.useMemo)(()=>Ji({userId:s,email:a,firstName:w,lastName:I,country:V,zip:Ve},en),[s,a,w,I,V,Ve,en]),ht=[se.firstName,se.lastName].filter(i=>!!i?.trim()).join(" "),Rt=!(0,d.isValidEmail)(se.email?.trim()),Ft=(0,o.useRef)(null);he&&Ft.current===null&&(Ft.current=Rt);let rt=he&&(Ft.current??Rt),Xr=(0,o.useMemo)(()=>Jd(Jt,rt),[Jt,rt]),Ot=Xr.empty||Xr.malformed,Vr=(0,o.useMemo)(()=>Fe?Fe.getRawProvider():null,[Fe]),_s=(0,o.useMemo)(()=>Lt?Lt.getRawProvider():null,[Lt]),ta=at||100,_o=pr.toLowerCase(),Mi=(0,o.useMemo)(()=>Ct?(0,On.toStripeAppearance)(Ct):null,[Ct]),To=Mi,Ts=(0,o.useMemo)(()=>{let i=Mi??{},C=i.rules??{};return{...i,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[Mi]),Ms=(0,o.useMemo)(()=>({..._l(at,We?.captureMethod,He),currency:_o,...To?{appearance:To}:null}),[at,_o,We?.captureMethod,He,To]),xi=(0,d.resolveSetupFutureUsage)(He,"paypal","paypal"),xs=(0,o.useMemo)(()=>({mode:"payment",amount:ta,currency:_o,captureMethod:"manual",...xi?{setupFutureUsage:xi}:null,...To?{appearance:To}:null}),[ta,_o,xi,To]),ze=(0,o.useCallback)(i=>{tr(i),P?.(i)},[P]),As=(0,o.useRef)(0);(0,o.useEffect)(()=>{jr!==As.current&&(As.current=jr,ze(null))},[jr,ze]);let Ai=(0,o.useRef)(""),[Fs,Mc]=(0,o.useState)(!1),Fi=(0,o.useCallback)(()=>{Mc(!0)},[]);(0,o.useEffect)(()=>{if(!he||!rt||!O||!Fs||Ot||Ai.current)return;let i=(0,vn.compactBuyerIdentity)({email:(0,d.isValidEmail)(se.email?.trim())?se.email?.trim():Ht.current.trim(),firstName:se.firstName?.trim(),lastName:se.lastName?.trim()});Ai.current=JSON.stringify(i),et(C=>({...C,...i})),Promise.resolve(O(i)).catch(C=>{Ai.current="",ze(C instanceof Error?C.message:"Failed to attach buyer details.")})},[he,rt,O,Fs,Ot,se.email,se.firstName,se.lastName,ze]),(0,o.useEffect)(()=>{!he||!ae||ae.setCardFieldOrder?.(X??null,Xe==null&&!rt)},[he,ae,X,Xe,rt]),(0,o.useEffect)(()=>{(ut==="expanding"||ut==="collapsing"||ut==="apm-expanding"||ut==="apm-collapsing")&&ze(null)},[ut,ze]);let jn=(0,o.useCallback)((i,C,G)=>{m?.(Sr(i,C,G))},[m]),Bs=(0,o.useRef)(ut);Bs.current=ut;let[Ds]=(0,o.useState)(ri),Os=(0,o.useCallback)(()=>{let i=Bs.current;if(Re==="buttons"&&(i==="card"||i==="expanding"))return!0;let C=te.current;return C==="validation-window"||C==="processing"||Je.current},[Re]),Ls=(0,o.useCallback)((i,C,G)=>{Ds.take(e)&&wr(Fe)?.log(Ro({...it,presentationMode:G?.presentationMode??"popup"},{name:ti,stage:"recovery",reason:"other_method_active",provider:G?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:G?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[it,Fe,Ds,e]),Da=(0,o.useCallback)((i,C,G)=>{G?.telemetryReported||wr(Fe)?.error(Ro({...it,presentationMode:G?.presentationMode??"popup"},{errorCode:C?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:G?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:G?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:G?.terminalReason??(C?"popup_blocked":"provider_error")}))},[it,Fe]),Mo=(0,o.useCallback)((i,C,G)=>{let Te=G?.popupBlocked??(0,ke.isPopupBlockedError)(C);if(Os()){Da(i,Te,G),Ls(i,C,G);return}if(C instanceof d.FloPayError&&C.code==="checkout_processing_timeout"){Da(i,!1,G),de(null),Re==="buttons"&&(mr("buttons"),Yr(null)),ze(C.message),p?.(C);return}Te&&x.markBlocked()&&Be(Et=>Et+1);let J=ps(i),Me=G?.code===d.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,d.buildWalletSheetWindowMessage)(J):(0,ke.buildExternalMethodRecoveryMessage)(J,Te,dt.inAppBrowser),qt=(0,ke.getProviderErrorCode)(C),hn=(qt?.toLowerCase()==="error"?void 0:qt)??(0,ke.sanitizeExternalFailureCode)(G?.code)??"external_payment_method_failed",Pt=new d.FloPayError(Me,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:hn,popupBlocked:Te,inAppBrowser:dt.inAppBrowser,appFamily:dt.appFamily,popupCapability:x.current(),presentationMode:G?.presentationMode??"popup"}});Da(i,Te,G),de(null),Re==="buttons"&&(mr("buttons"),Yr(null)),ze(Me),p?.(Pt),console.error("[FloPay] External payment method failed:",{method:i,code:hn,popupBlocked:Te})},[dt,Os,Re,p,x,Ls,Da,ze]);(0,o.useEffect)(()=>{if(!he||!e){nn(null);return}let i={billingApiUrl:pn,sessionId:e,nonce:t},C=(0,d.resolveVaultMountOptions)(M?.vault,i);if(C){nn(C);return}if(!Q){nn(null);return}let G=`${pn}\0${e}\0${t??""}`,Te=j.current;if(Te&&Te.key===G){nn(Te.mount);return}nn(null);let J=!0;return new On.PaymentAPI(pn).getVaultCapture(e,t).then(Me=>{if(!J)return;let qt=(0,d.resolveVaultMountOptions)(Me,i);qt?.verificationRequired&&!Me.html&&(j.current={key:G,mount:qt}),qt?nn(qt):ze("Failed to load the secure card form.")}).catch(Me=>{J&&ze(Me instanceof Error?Me.message:"Failed to load the secure card form.")}),()=>{J=!1}},[he,Q,oe,e,M?.vault,pn,t,ze]);let _n=(0,o.useRef)({onComplete:l,onError:p,updateError:ze,emitDecline:jn,resolvedAccount:se,avsConfig:Xe,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:pn,captureMethod:M?.captureMethod,paymentId:M?.paymentId,authorizationExpiresAt:M?.authorizationExpiresAt,serverSideCardGateway:zr});_n.current={onComplete:l,onError:p,updateError:ze,emitDecline:jn,resolvedAccount:se,avsConfig:Xe,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:pn,captureMethod:M?.captureMethod,paymentId:M?.paymentId,authorizationExpiresAt:M?.authorizationExpiresAt,serverSideCardGateway:zr};let Bi=(0,o.useRef)(!1),Ns=(0,o.useCallback)(()=>{let i=_n.current,C=i.resolvedAccount.email?.trim(),G=(0,d.isValidEmail)(C)?C:Ht.current.trim();if(!(0,d.isValidEmail)(G))return null;let Te=i.resolvedAccount.firstName?.trim(),J=i.resolvedAccount.lastName?.trim(),Me=Br.current.trim()||i.resolvedAccount.country?.trim()||"",qt=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.state,Me):!1,hn=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.address_line_1,Me):!1,Pt=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.postal_code,Me):!1,Et=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.city,Me):!1,Bt=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.address_line_2,Me):!1,Or=hn&&!qt&&Pt?(0,d.getStateFromPostalCode)(Me,(kt.current??"").trim()):null,Mn=qt?Zt.current:Or;return{accountData:{userId:i.resolvedAccount.userId??"",email:G,...Te?{firstName:Te}:{},...J?{lastName:J}:{},...Pt&&kt.current?{zip:kt.current}:{},...Et&&vr.current?{city:vr.current}:{},...Mn?{state:Mn}:{},...hn&&$t.current?{addressLine1:$t.current}:{},...Bt&&nr.current?{addressLine2:nr.current}:{},...Me?{country:Me}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,d.isAVSFieldVisible)(i.avsConfig.country,Me),postal_code:Pt,address_line_1:hn,address_line_2:Bt,city:Et,state:qt}}:{}}},[]),Us=(0,o.useRef)(c);Us.current=c,(0,o.useEffect)(()=>{c||Ce!==Xl||_n.current.updateError(null)},[c,Ce]),(0,o.useEffect)(()=>{!he||!ae||ae.setSubmitGate?.(br||c||Ot||tt)},[he,ae,br,c,Ot,tt]),(0,o.useEffect)(()=>{if(!he||!ae)return;Bi.current=!1;let i=null,C=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,te.current="idle",de(null)},400)},G=ae.on("submitting",()=>{Un(!0),ve.current&&clearTimeout(ve.current),te.current="validation-window",ve.current=setTimeout(()=>{ve.current=null,te.current==="validation-window"&&(te.current="processing")},zd),de("processing");let Pt=_n.current;if(!Pt.sessionId||!Pt.nonce)return;let Et=Ns();if(!Et){Pt.updateError("Enter a valid email address."),te.current="idle",de(null);return}new On.PaymentAPI(Pt.baseUrl).patchAccountSnapshot(Pt.sessionId,Pt.nonce,Et,{telemetryMode:"best_effort"}).catch(Bt=>{if(!jd(Bt))return;let Or=Bt instanceof Error?Bt.message:"Please check your billing address and try again.";Pt.updateError(Or),te.current="idle",de(null),Pt.onError?.(Bt instanceof d.FloPayError?Bt:new d.FloPayError(Or,"api_error"))})}),Te=ae.on("complete",Pt=>{(0,Bn.markSessionRecentlyCompleted)(Pt.sessionId??_n.current.sessionId),te.current="terminal",re(!1),de("success"),setTimeout(()=>{if(Bi.current)return;Bi.current=!0;let Et=_n.current,Bt=(0,d.isAuthorizationOnlySession)(Et)||Pt.outcome==="authorized",Or=Et.serverSideCardGateway?{}:{paymentIntentId:Pt.intentId};_n.current.onComplete?.(Bt?{status:"authorized",...Or,paymentId:Pt.paymentId??Et.paymentId,sessionId:Pt.sessionId??Et.sessionId,authorizationExpiresAt:Pt.authorizationExpiresAt??Et.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Or,checkoutMethod:"card"})},600)}),J=ae.on("decline",Pt=>{let Et=_n.current,Bt=Pt.message??"Your payment was declined. Please try another card or contact your bank.";te.current="terminal",re(!1),Et.updateError(Bt),de("error");let Or=Pt.failureOutcome??(0,d.normalizeCheckoutFailureOutcome)(Pt.declineReason)??"authorization_declined";Et.emitDecline("card",Bt,{code:Or,declineCode:Or}),C()}),Me=ae.on("error",Pt=>{let Et=_n.current,Bt=Pt.message??"There was a problem processing your payment. Please try again.";te.current="terminal",re(!1),Et.updateError(Bt),de("error"),Et.onError?.(new d.FloPayError(Bt,"api_error",{code:Pt.failureOutcome??"capture_failed"})),C()}),qt=ae.on("challenge_dismissed",()=>{ve.current&&(clearTimeout(ve.current),ve.current=null),te.current="processing",re(!0),de(null)}),hn=ae.on("blocked",()=>{if(Je.current){_n.current.updateError(qd);return}if(!Us.current){Un(!0);return}Fi(),_n.current.updateError(Xl)});return()=>{i&&(clearTimeout(i),i=null),ve.current&&(clearTimeout(ve.current),ve.current=null),te.current="idle",re(!1),de(null),G(),Te(),J(),Me(),qt(),hn()}},[he,ae,Fi,Ns]);let Vn=!!vt?.clientId,ra=Array.isArray(T),Oa=ra&&T.length>0,zs=ra&&T.includes("paypal"),La=(0,o.useRef)(null);La.current===null&&(La.current=(0,d.hasMatchingStripePayPalReturn)());let xo=La.current?"redirect":(0,Hn.resolveStripePayPalPresentation)(dt,xe,x.current()),{expressMethods:Na,paymentElementMethods:Di}=(0,o.useMemo)(()=>(0,d.partitionStripeMethods)(T,{excludePaypal:Vn}),[T,Vn]),qs=Vn||!!Lt||zs&&xo==="redirect",xc=(0,o.useMemo)(()=>qs?Na.filter(i=>i!=="paypal"):Na,[Na,qs]),Ac=(0,o.useMemo)(()=>{let i=[];return ye&&i.push("apple_pay"),pe&&i.push("google_pay"),i},[ye,pe]),Ao=ra?xc:Ac,Fc=S&&Ao.length>0,js=or?Wt:V,Ua=(0,o.useMemo)(()=>(0,d.filterStripeMethodsByCountryGate)(Di,js,le),[Di,js,le]),Oi=(0,o.useMemo)(()=>({mode:"payment",amount:ta,currency:_o,paymentMethodCreation:"manual",appearance:Ts}),[ta,_o,Ts]),[Vs,Ws]=(0,o.useState)("loading"),[$s,Hs]=(0,o.useState)("loading"),[Ks,Gs]=(0,o.useState)("loading"),[Bc,Li]=(0,o.useState)(!1),[Ys,Ni]=(0,o.useState)("loading"),[Ui,Dc]=(0,o.useState)();(0,o.useEffect)(()=>{Dc((0,$n.detectPayPalEnvironment)())},[]);let za=Ui?.inAppBrowser,qa=Ui?(0,Hn.resolvePayPalPresentationMode)(Ui,vt?.approvalPresentation,Dt??(be?"subscription":"order")):"popup",Xs=me&&(Vn||(ra?zs:za===!1)),Oc=dt.inAppBrowser&&x.current()==="blocked",Js=S&&Fc&&!Oc,na=(!W||!!Se.waitForDataAttachment)&&Xs&&Vn,Zs=Ys==="retrying"||Ys==="exhausted",oa=null;S&&(Lt?oa=_s:xo==="redirect"&&(oa=Vr));let Qs=(0,o.useMemo)(()=>({...it,presentationMode:xo}),[it,xo]),aa=!W&&Xs&&!!oa&&(!Vn||Zs),Fo=!W&&Js&&!!Vr,ia=!W&&S&&Oa&&Ua.length>0&&!!Vr,Lc=na&&!Zs?Bc:aa&&as(Vs),Nc=Fo&&as($s),Uc=ia&&Ks!=="load_error",el=i=>i==="loading"||i==="ready",tl=na||aa&&el(Vs)||Fo&&el($s)||ia&&Ks!=="load_error",ja=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!ja.current){if(!S&&!me){ja.current=!0;let i=new d.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),ze(i.message)}else if(!S&&me&&!Vn){ja.current=!0;let i=new d.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),ze(i.message)}else if(za!==void 0&&!W&&!ar&&!tl){ja.current=!0;let i=new d.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(i),ze(i.message)}}},[S,me,Vn,za,W,ar,tl,p,ze]);let rl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(rl.current||!Oa)return;let i=[];ye!==!0&&i.push("showApplePay"),pe!==!0&&i.push("showGooglePay"),i.length!==0&&(rl.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Oa,ye,pe]);let nl=(0,o.useCallback)((i,C,G)=>Se.applyInlineSessionPatch?Se.applyInlineSessionPatch(i).then(Te=>({error:null,sessionId:Te.sessionId||e,nonce:Te.session?.clientSecret||t})).catch(Te=>{let J=(0,d.normalizeBeforeButtonClickError)(C,Te);return G?.abandoned?.()||(ze(J.message),p?.(J)),{error:J,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Se.applyInlineSessionPatch,t,p,e,ze]),Tn=(0,o.useCallback)(async(i,C)=>{if(i!=="card"&&W&&await Se.waitForDataAttachment?.(),!Le)return{proceed:!0};try{let G=await Le({method:i,sessionId:e||void 0,createSession:Se.inlineSessionDraft});if(G===!1)return{proceed:!1};if(G&&typeof G=="object"){G.account&&et(J=>({...J??{},...G.account}));let Te=await nl(G,i,C);return Te.error?{proceed:!1,accountPatch:G.account}:{proceed:!0,accountPatch:G.account,sessionId:Te.sessionId,nonce:Te.nonce}}return{proceed:!0}}catch(G){if(!C?.abandoned?.()){let Te=(0,d.normalizeBeforeButtonClickError)(i,G);ze(Te.message),p?.(Te)}return{proceed:!1}}},[nl,Se.inlineSessionDraft,Se.waitForDataAttachment,W,Le,p,e,ze]),ol=(0,o.useCallback)(async(i,C)=>{if(ee.current)return;ee.current=!0,Ut(!0),de("processing"),ze(null);let G=C?.sessionId??e,Te=C?.nonce??t,J=Ji(se,C?.accountPatch),Me=C?.completionPaymentMethodId??fa(i),qt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,hn=Hd(i),Pt=C?.presentationMode?ci(wr(Fe),{...it,presentationMode:C.presentationMode}):void 0,Et=()=>{It?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:hn}),Pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Dn,requestCategory:"process_payment"})};try{let Bt=new On.PaymentAPI(pn),Mn=C?.settledProcessResponse??await Bt.processPayment(J.userId??"",{sessionId:G,nonce:Te,paymentMethodCategory:C?.paymentMethodCategory??Gd(i),tokenizedData:qt,accountData:{...C?.accountPatch,userId:J.userId??"",email:J.email??"",firstName:J.firstName||void 0,lastName:J.lastName||void 0,...(0,d.buildProcessPaymentAvsAccount)({avsConfig:Xe,country:Br.current,zip:kt.current,city:vr.current,state:Zt.current,addressLine1:$t.current,addressLine2:nr.current})},...(0,d.buildCheckoutProcessMetadata)({chv:Y,avsCheck:ot,checkoutType:Ae,checkoutLayout:Qe,avsConfig:Xe,country:Br.current})}),Ka=async Mr=>{let Co=(0,d.isAuthorizationOnlySession)(M)||Mr?.status==="authorized";(0,Bn.markSessionRecentlyCompleted)(G),Pt?.terminal({outcome:"payment_succeeded",...Dn}),de("success"),At(null),await new Promise(pa=>setTimeout(pa,600));let Wn;typeof Mr?.paymentId=="string"?Wn=Mr.paymentId:M?.paymentId&&(Wn=M.paymentId);let bo;typeof Mr?.authorizationExpiresAt=="string"?bo=Mr.authorizationExpiresAt:M?.authorizationExpiresAt&&(bo=M.authorizationExpiresAt),l?.(Co?{status:"authorized",...Wn===void 0?{}:{paymentId:Wn},sessionId:typeof Mr?.sessionId=="string"?Mr.sessionId:G,...bo===void 0?{}:{authorizationExpiresAt:bo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Me,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Me,checkoutMethod:i.isPaypal?"paypal":"card"})};if(Mn.ok){await Ka(Mn.status===204?null:await Mn.json().catch(()=>null));return}let fr=await Mn.json().catch(()=>null);if(fr?.type==="paypal_redirect_required"){let Mr=fr.threeDSecureToken,Co=fr.paymentMethodId||i.id||"";if(!Fe||!Mr){de("error"),ze("PayPal authorization required but no token provided.");return}try{let Wn=Lt?.getRawProvider();if(!Wn){ze("PayPal is not available.");return}let bo={return_url:window.location.href};Co&&(bo.payment_method=Co);let{error:pa}=await Wn.confirmPayment({clientSecret:Mr,confirmParams:bo,redirect:"if_required"});if(pa){de("error");let gl=pa.message??"PayPal payment failed.";ze(gl),jn("paypal",gl,{code:pa.code})}}catch(Wn){de("error"),ze(Wn instanceof Error?Wn.message:"PayPal authorization failed.")}return}if(fr?.type==="paypal_direct_required"){let Mr=fr.orderId;if(!Mr){de("error"),ze("PayPal retry required but no order id provided.");return}let Co=_r.current?.attempts??0;if(Co>=2){de("error"),ze("PayPal payment could not be completed after multiple attempts."),jn("paypal","paypal_direct_required retry limit exceeded");return}Li(!1),Ni("loading"),At({orderId:Mr,attempts:Co+1}),de(null);return}if(Mn.headers.get(Fd)===Bd){let Mr=await Dd(Bt,G,Te);if(Mr!==void 0){await Ka(Mr);return}}(0,d.classifyPaymentRejection)(Mn.status,fr)?Pt?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}):Et(),de("error");let fl=fr?.message??"Payment failed. Please try again.";ze(fl),jn(i.isPaypal?"paypal":"card",fl,{code:fr?.code??fr?.gatewayErrorCode,declineCode:fr?.declineCode??fr?.gatewayDeclineReason}),await new Promise(Mr=>setTimeout(Mr,400))}catch(Bt){ac(Bt)||Et(),de("error"),ze(Bt instanceof Error?Bt.message:"An unexpected error occurred"),await new Promise(Or=>setTimeout(Or,400))}finally{Ut(!1),de(null),ee.current=!1}},[pn,e,t,se,Xe,ot,Ae,Qe,Y,Fe,Lt,M,l,ze,jn,It,it]),on=(0,o.useCallback)((i,C)=>{R&&!C?.settledProcessResponse?R(i):ol(i,C)},[R,ol]),sa=`${nc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(sa);if(!i)return;let C;try{C=JSON.parse(i)}catch{dr(sa);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>oc||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!Ao.includes(C.paymentMethodType)){dr(sa);return}dr(sa),on({id:C.paymentMethodId,type:"card",threeDSecureActionResultTokenId:C.providerIntentId,gateway:"stripe",paymentMethodType:C.paymentMethodType},{...C.accountPatch?{accountPatch:C.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[on,t,e,sa,Ao]);let al=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||al.current)return;let[i,C,G]=(0,d.readStripeRedirectParams)();if(!i||!C||La.current||!Fe)return;let Te=Fe.getRawProvider();if(!Te)return;let J=Et=>{let Bt=localStorage.getItem(Et);if(!Bt)return null;try{return JSON.parse(Bt)}catch{return dr(Et),null}},Me=J(Gn)??J(Kl),qt;if(Me?.clientSecret){if(Me.clientSecret!==C)return;qt={...Me.accountPatch?{accountPatch:Me.accountPatch}:{},...Me.sessionId?{sessionId:Me.sessionId}:{},...Me.nonce?{nonce:Me.nonce}:{}}}else if(Me?.sessionId&&Me.sessionId!==e)return;al.current=!0,dr(Gn),dr(Kl),window.history.replaceState({},"",(0,d.stripeRedirectReturnUrl)());let hn=Me?.paymentMethodType??Me?.tokenType??"card",Pt="card";(async()=>{if(G==="failed"){let fr="Payment was declined. Please try again.";ze(fr),jn(Pt,fr);return}let{paymentIntent:Et,error:Bt}=await Te.retrievePaymentIntent(C);if(Bt){let fr=Bt.message??"Failed to retrieve payment status.";ze(fr),jn(Pt,fr,{code:Bt.code});return}let Or=Et?.status,Mn=ya(Or);if(!Et||!Mn){let fr=Or==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ze(fr),jn(Pt,fr,{code:Or??"missing_payment_intent"});return}let Ka=typeof Et.payment_method=="string"?Et.payment_method:Et.payment_method?.id;on({id:Ka??Me?.paymentMethodId??Me?.tokenId??Et.id,type:"card",threeDSecureActionResultTokenId:Et.id,gateway:Me?.gateway??"stripe",paymentMethodType:hn},qt)})()},[e,on,Fe,ze,jn]);let zi=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(he||Fe!==null))return(0,u.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let la=Re==="buttons",an=Ct?.variables,zc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),qi=an?.colorBackground,qc=qi&&!zc.has(qi)?qi:void 0,ca=L.cardInputBorder??(la?"#e5e7eb":"#A4A4FF"),il=an?.colorDanger??"#dc2626",er=i=>qr[i]&&(po[i]||Qt),Va=Ot&&(qn||Qt),gn=i=>i?il:ca,Wa=(Nt.malformed||Nt.empty)&&(Zn||Qt),jc=gn(Wa),ji=L.cardFormContainer?.backgroundColor??qc??(la?"white":"#EDEDFF"),Bo=L.cardInputBackground??an?.colorBackground??"white",Vi=Lo(Ne),sl=Lo(ue),Do=L.nameInput,ll=L.cardInputFontSize??Zd(Do?.fontSize)??an?.fontSizeBase??"16px",cl=typeof Do?.fontFamily=="string"?Do.fontFamily:an?.fontFamily??"Poppins, sans-serif",dl=(0,d.toCssWeight)(Do?.fontWeight)??400,Vc=L.cardInputColor??(typeof Do?.color=="string"?Do.color:void 0)??an?.colorText??"#262833",Wc=L.cardInputPlaceholderColor??"#9ca3af",lr=an?.borderRadius??"8px",Po=an?.borderRadius??L.cardButton?.borderRadius??lr,vo=an?.colorPrimary??"#4A49FF",$c=an?.colorPrimaryHover??(0,d.darkenHex)(vo,.12),Wi=an?.colorText??"#262833",$i={fontSize:ll,fontFamily:cl,fontWeight:dl,color:Vc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},da={marginTop:"0.375rem",...$i,fontSize:"0.75rem",lineHeight:1.4,color:il},Hc={"--flopay-input-placeholder-color":Wc,"--flopay-input-font-size":ll,"--flopay-input-font-family":cl,"--flopay-input-font-weight":String(dl)},ua=L.cardFormContainer??{},Hi=ua.padding??(la?"0":"1rem"),Ki=ua.borderRadius??lr,Kc=ae&&dn?(0,u.jsx)(go,{capture:ae,html:dn.html,messageToken:dn.messageToken,expectedOrigin:dn.expectedOrigin,verificationRequired:dn.verificationRequired,theme:yr,submitLabel:Z,onReady:()=>{if(!rt&&!Xe||typeof document>"u")return;let i=()=>{let G=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(G){Dr.current=!0;try{G.focus()}finally{Dr.current=!1}}};fn.current||i()},onError:i=>{i&&dn.verificationRequired&&te.current==="idle"&&(ro.current=!0),ze(i)},onValidation:i=>{let C=te.current;(C==="idle"||C==="validation-window")&&(ze(i),i&&te.current==="validation-window"&&(ve.current&&(clearTimeout(ve.current),ve.current=null),te.current="idle",de(null)))}},jr):(0,u.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ul=(0,u.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&In()},style:{backgroundColor:ji,borderRadius:Ki,...ua,padding:Hi,...Hc,display:"flex",flexDirection:"column"},children:[(0,u.jsx)("style",{children:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
|
@@ -35,13 +35,13 @@ ${ue.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),ca&&fo&&(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ve?-2:0},children:[(0,u.jsxs)("button",{type:"button",onClick:we,style:{display:"inline-flex",alignItems:"center",gap:Vi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ne.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ne.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ne.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(zo,{content:Ne})]}),sl?(0,u.jsx)("div",{style:{flex:1}}):(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ne.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...ne.title},children:(0,u.jsx)(ya,{content:me})})]}),!ca&&!sl&&(0,u.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Wi,order:ve?-3:0,...ne.title},children:(0,u.jsx)(ya,{content:me})}),ve&&G&&(0,u.jsx)("div",{style:{order:-2,width:"100%"},children:G}),ve&&Ft&&(0,u.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,u.jsx)("div",{style:{backgroundColor:Do,border:`1px solid ${yn(Va)}`,borderRadius:ar,padding:"10px"},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:ur,onChange:i=>{zt("email"),Zt.current=i.target.value,br(i.target.value)},onPointerDown:()=>zt("email"),onKeyDown:()=>zt("email"),onBlur:()=>{Jr("email")&&Gn(!0),_o||Ai()},disabled:ye,required:!0,"aria-invalid":Va||void 0,"aria-describedby":Va?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...$i}})}),Va&&(0,u.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ua,children:Io.empty?"Email address is required":"Enter a valid email address"})]}),Je&&(0,u.jsx)("div",{style:{order:ve?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Yt,w=(J=!1)=>({backgroundColor:Do,border:`1px solid ${yn(J)}`,borderRadius:ar,marginTop:"0.5rem",padding:"10px"}),Y=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...$i}),Te=(0,d.getStateOptions)(i);return(0,u.jsxs)(u.Fragment,{children:[(0,d.isAVSFieldVisible)(Je.address_line_1,i)&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)("div",{style:w(er("line1")),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:tr,onChange:J=>{zt("line1"),Sr.current.addressLine1=!0,Wt.current=J.target.value,Gr(J.target.value)},onPointerDown:()=>zt("line1"),onKeyDown:()=>zt("line1"),onBlur:()=>Zr("line1"),disabled:ye,required:!0,"aria-invalid":er("line1")||void 0,"aria-describedby":er("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:Y()})}),er("line1")&&(0,u.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ua,children:"Street address is required"})]}),(0,d.isAVSFieldVisible)(Je.address_line_2,i)&&(0,u.jsx)("div",{style:w(),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Tt,onChange:J=>{Sr.current.addressLine2=!0,pr.current=J.target.value,An(J.target.value)},disabled:ye,"data-testid":"flopay-address-line2",style:Y()})}),((0,d.isAVSFieldVisible)(Je.city,i)||(0,d.isAVSFieldVisible)(Je.state,i))&&(0,u.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Je.city,i)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Do,borderTop:`1px solid ${yn(er("city"))}`,borderRight:`1px solid ${yn(er("city"))}`,borderBottom:`1px solid ${yn(er("city"))}`,borderLeft:`1px solid ${yn(er("city"))}`,padding:"10px",borderTopLeftRadius:ar,borderBottomLeftRadius:ar,...(0,d.isAVSFieldVisible)(Je.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ar}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Xt,onChange:J=>{zt("city"),Sr.current.city=!0,fr.current=J.target.value,pn(J.target.value)},onPointerDown:()=>zt("city"),onKeyDown:()=>zt("city"),onBlur:()=>Zr("city"),disabled:ye,required:!0,"aria-invalid":er("city")||void 0,"aria-describedby":er("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:Y()})}),(0,d.isAVSFieldVisible)(Je.state,i)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Do,borderTop:`1px solid ${yn(er("state"))}`,borderRight:`1px solid ${yn(er("state"))}`,borderBottom:`1px solid ${yn(er("state"))}`,borderLeft:`1px solid ${yn(er("state"))}`,padding:"10px",borderTopRightRadius:ar,borderBottomRightRadius:ar,...(0,d.isAVSFieldVisible)(Je.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${yn(er("state")||er("city"))}`}:{borderRadius:ar}},children:Te?(0,u.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:jr,onChange:J=>{zt("state"),Sr.current.state=!0,Jt.current=J.target.value,Vr(J.target.value)},onPointerDown:()=>zt("state"),onKeyDown:()=>zt("state"),onBlur:()=>Zr("state"),disabled:ye,autoComplete:"billing address-level1",required:!0,"aria-invalid":er("state")||void 0,"aria-describedby":er("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...Y(),cursor:"pointer"},children:[(0,u.jsx)("option",{value:"",children:(0,d.getStateLabel)(i)}),Te.map(J=>(0,u.jsx)("option",{value:J.code,children:J.name},J.code))]}):(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,d.getStateLabel)(i),autoComplete:"billing address-level1",value:jr,onChange:J=>{zt("state"),Sr.current.state=!0,Jt.current=J.target.value,Vr(J.target.value)},onPointerDown:()=>zt("state"),onKeyDown:()=>zt("state"),onBlur:()=>Zr("state"),disabled:ye,required:!0,"aria-invalid":er("state")||void 0,"aria-describedby":er("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:Y()})})]}),er("city")&&(0,u.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ua,children:"City is required"}),er("state")&&(0,u.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ua,children:[(0,d.getStateLabel)(i)," is required"]}),((0,d.isAVSFieldVisible)(Je.country,i)||(0,d.isAVSFieldVisible)(Je.postal_code,i))&&(0,u.jsxs)("div",{style:{display:"flex",flexDirection:$==="column"?"column":"row",gap:$==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Je.country,i)&&(0,u.jsx)("div",{style:{flex:$==="row"?1:void 0,backgroundColor:Do,borderTop:`1px solid ${da}`,borderRight:`1px solid ${da}`,borderBottom:`1px solid ${da}`,borderLeft:`1px solid ${da}`,padding:"10px",...$==="row"&&(0,d.isAVSFieldVisible)(Je.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:ar,borderBottomLeftRadius:ar,borderRight:"none"}:{borderRadius:ar}},children:(0,u.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Yt,onChange:J=>{Sr.current.country=!0,xr.current=J.target.value,_t(J.target.value),ut?.(J.target.value),Jt.current="",Vr("")},disabled:ye,autoComplete:"billing country","data-testid":"flopay-country",style:{...Y(),cursor:"pointer"},children:[Yt===""?(0,u.jsx)("option",{value:"",children:"Select country"}):null,d.COUNTRY_OPTIONS.map(J=>(0,u.jsxs)("option",{value:J.code,children:[J.flag," ",J.name]},J.code))]})}),(0,d.isAVSFieldVisible)(Je.postal_code,i)&&(0,u.jsx)("div",{style:{flex:$==="row"?1:void 0,backgroundColor:Do,border:`1px solid ${Uc}`,padding:"10px",...$==="row"&&(0,d.isAVSFieldVisible)(Je.country,i)?{borderRadius:"0",borderTopRightRadius:ar,borderBottomRightRadius:ar}:{borderRadius:ar}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,d.getPostalCodeLabel)(Yt),autoComplete:"billing postal-code",value:qr,onChange:J=>{zt("zip"),Sr.current.zip=!0,kt.current=J.target.value,Dr(J.target.value),ze?.(J.target.value)},onPointerDown:()=>zt("zip"),onKeyDown:()=>zt("zip"),onBlur:()=>{Jr("zip")&&Dn(!0)},disabled:ye,required:Nt.required,"aria-invalid":Wa||void 0,"aria-describedby":Wa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:Y()})})]}),Wa&&(0,u.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ua,children:Nt.empty?`${(0,d.getPostalCodeLabel)(i)} is required`:Kd(i)})]})})()}),ve&&Wc,De&&(0,u.jsx)(Go,{margin:"0.75rem 0",styleOverride:ne.errorBanner,children:De})]}),$a={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"},pl=i=>N?!he||!Nn?(0,u.jsx)("pre",{"data-testid":i,style:$a,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":i,style:$a,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${he}`,` directPaypalConfigured=${Nn}`,` inAppBrowserDetected=${String(za)}`,` shouldRenderDirectPayPal=${oa}`,` shouldRenderStripePayPal=${ia}`,` hasPaypalStripeInstance=${!!_s}`].join(`
|
|
39
|
-
`)}):null,ml=i=>N?!
|
|
40
|
-
`)}):null,yl=ct==="apm-expanding"||ct==="apm-form"||ct==="apm-collapsing",Lo;ct==="apm-expanding"?Lo=Gl:ct==="apm-collapsing"&&(Lo=Yl);let Ha=or?oc(Oi,or,Ge):null;if(Ae==="buttons"){let i=ct==="buttons"||ct==="expanding"||ct==="apm-expanding",w=ct==="expanding"||ct==="card"||ct==="collapsing",Y=Xe===void 0?{boxSizing:"border-box",height:Zo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Te;ct==="expanding"||ct==="apm-expanding"?Te=Vd:(ct==="collapsing"||ct==="apm-collapsing")&&(Te=jd);let J;return ct==="expanding"?J=Gl:ct==="collapsing"&&(J=Yl),(0,u.jsxs)("form",{onSubmit:zi,className:E,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Qo,{}),_e&&(0,u.jsx)(nn,{status:_e,errorMessage:De,authorized:kr}),(0,u.jsxs)("div",{style:{display:"grid"},children:[(0,u.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Te?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Te?$d:{},...Te?{animation:Te,pointerEvents:"none"}:{}},children:[pl("flopay-direct-paypal-gate-debug"),ml("flopay-stripe-gate-debug"),oa&&bt&&(0,u.jsxs)(u.Fragment,{children:[Ot&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(Pa.Provider,{value:T,children:(0,u.jsx)(Ca,{sessionId:e,nonce:t,billingApiUrl:k,email:oe.email,billingName:Rt||void 0,onBuyerIdentityReady:ge,clientId:bt.clientId,environment:bt.environment,currency:cr.toUpperCase(),isSubscription:Re,providerObjectType:Dt,approvalPresentation:qa==="popup"?void 0:qa,onTokenizedBody:tn,onComplete:l,onErrorChange:je,onDecline:m,onCancel:f,onTechnicalFailure:xo,onButtonClick:K,runBeforeButtonClick:Rn,isProcessing:ye,onLoadStateChange:Li,onInitializationStateChange:Ni,session:We,existingOrderId:Ot?.orderId,debug:N},Ot?.orderId??"fresh")})]}),ia&&(0,u.jsx)(ir.Elements,{stripe:aa,options:xs,children:(0,u.jsx)(Jl,{sessionId:e,nonce:t,email:oe.email,billingName:Rt||void 0,onBuyerIdentityReady:ge,billingApiUrl:k,onTokenizedBody:tn,onErrorChange:je,isProcessing:ye,onButtonClick:K,onDecline:m,onTechnicalFailure:xo,runBeforeButtonClick:Rn,onLoadStateChange:Ws,placeholderBorderRadius:go,popupCapabilityOwner:T,externalTelemetryContext:Qs,presentationMode:Ao})}),Bo?(0,u.jsx)(ir.Elements,{stripe:cn,options:Ms,children:(0,u.jsx)(Zl,{sessionId:e,nonce:t,email:oe.email,billingName:Rt||void 0,onBuyerIdentityReady:ge,billingApiUrl:k,intentKind:nt>0?"payment":"setup",expressMethods:Fo,onTokenizedBody:tn,onErrorChange:je,onButtonClick:K,onDecline:m,onTechnicalFailure:xo,runBeforeButtonClick:Rn,onLoadStateChange:Hs,placeholderBorderRadius:go,popupCapabilityOwner:T,externalTelemetryContext:ot})}):null,!Bo&&Js?(0,u.jsx)("div",{style:{height:Zo,borderRadius:go,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,sa&&(0,u.jsx)(Ql,{sessionId:e,nonce:t,email:oe.email,billingName:[oe.firstName,oe.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ge,billingApiUrl:k,paymentElementMethods:Ua,stripeInstance:cn,paymentElementBaseOptions:Oi,futureUseSession:Ge,onTokenizedBody:tn,onErrorChange:je,onButtonClick:K,onDecline:m,runBeforeButtonClick:Rn,onLoadStateChange:Gs,isProcessing:ye,submitButtonColor:ho,submitButtonBorderRadius:ar,submitButtonStyle:ne.submitButton,onExpandApm:mt,expandedApmMethod:or,themeId:st,buttonAppearance:{backgroundColor:ne.cardButton?.backgroundColor,borderColor:ne.cardInputBorder,textColor:ne.cardButton?.color,borderRadius:go}}),ve&&(0,u.jsx)("button",{type:"button",onClick:async()=>{ye||!(await Rn("card")).proceed||(K?.("card"),ie())},disabled:ye,style:{width:"100%",...Y,...ne.cardButton,...gs({themeBundle:Pt,resolvedPrimaryColor:ho,resolvedBorderRadius:ar,submitButtonStyle:ne.submitButton,explicitPrimaryColor:rn?.colorPrimary}),fontSize:ne.cardButtonFontSize??"0.95rem",fontWeight:600,cursor: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:ye?.6:1},onMouseEnter:Me=>{!ye&&(Pt||rn?.colorPrimary)&&(Me.currentTarget.style.backgroundColor=jc)},onMouseLeave:Me=>{(Pt||rn?.colorPrimary)&&(Me.currentTarget.style.backgroundColor=ho)},onMouseDown:Me=>{Me.currentTarget.style.transform="scale(0.985)"},onMouseUp:Me=>{Me.currentTarget.style.transform="scale(1)"},children:(0,u.jsx)(Uo,{content:Xe})}),De&&ct==="buttons"&&(0,u.jsx)(Go,{margin:"0.25rem 0",styleOverride:ne.errorBanner,children:De})]}),ve&&w&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...J?{animation:J}:{},...ct==="collapsing"?{pointerEvents:"none"}:{}},children:ul}),v&&yl&&or&&Ha&&cn&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...Lo?{animation:Lo}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:ji,borderRadius:Ki,...pa,padding:Hi},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Ht,style:{display:"inline-flex",alignItems:"center",gap:Vi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ne.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ne.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ne.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(zo,{content:Ne})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ne.titleFontSize??"1.05rem",color:Wi,paddingRight:80,...ne.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(or)}`})]}),(0,u.jsx)(ir.Elements,{stripe:cn,options:Ha,children:(0,u.jsx)(ms,{method:or,sessionId:e,nonce:t,email:oe.email,billingName:[oe.firstName,oe.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ge,billingApiUrl:k,onTokenizedBody:tn,onErrorChange:je,onDecline:m,onCancel:Ht,runBeforeButtonClick:Rn,onButtonClick:K,isProcessing:ye,submitButtonColor:ho,submitButtonBorderRadius:ar,submitButtonStyle:ne.submitButton,errorText:De})},or)]})})]})]})}return yl&&or&&Ha&&cn&&v?(0,u.jsxs)("form",{onSubmit:zi,className:E,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Qo,{}),_e&&(0,u.jsx)(nn,{status:_e,errorMessage:De,authorized:kr}),(0,u.jsx)("div",{style:{...Lo?{animation:Lo}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:ji,borderRadius:Ki,...pa,padding:Hi},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Ht,style:{display:"inline-flex",alignItems:"center",gap:Vi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ne.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ne.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ne.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(zo,{content:Ne})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ne.titleFontSize??"1.05rem",color:Wi,paddingRight:80,...ne.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(or)}`})]}),(0,u.jsx)(ir.Elements,{stripe:cn,options:Ha,children:(0,u.jsx)(ms,{method:or,sessionId:e,nonce:t,email:oe.email,billingName:[oe.firstName,oe.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ge,billingApiUrl:k,onTokenizedBody:tn,onErrorChange:je,onDecline:m,onCancel:Ht,runBeforeButtonClick:Rn,onButtonClick:K,isProcessing:ye,submitButtonColor:ho,submitButtonBorderRadius:ar,submitButtonStyle:ne.submitButton,errorText:De})},or)]})})]}):(0,u.jsxs)("form",{onSubmit:zi,className:E,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Qo,{}),_e&&(0,u.jsx)(nn,{status:_e,errorMessage:De,authorized:kr}),(0,u.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[pl("flopay-direct-paypal-gate-debug-default"),ml("flopay-stripe-gate-debug-default"),oa&&bt&&(0,u.jsxs)(u.Fragment,{children:[Ot&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(Pa.Provider,{value:T,children:(0,u.jsx)(Ca,{sessionId:e,nonce:t,billingApiUrl:k,email:oe.email,billingName:Rt||void 0,onBuyerIdentityReady:ge,clientId:bt.clientId,environment:bt.environment,currency:cr.toUpperCase(),isSubscription:Re,providerObjectType:Dt,approvalPresentation:qa==="popup"?void 0:qa,onTokenizedBody:tn,onComplete:l,onErrorChange:je,onDecline:m,onCancel:f,onTechnicalFailure:xo,onButtonClick:K,runBeforeButtonClick:Rn,isProcessing:ye,onLoadStateChange:Li,onInitializationStateChange:Ni,session:We,existingOrderId:Ot?.orderId,debug:N},Ot?.orderId??"fresh")})]}),ia&&(0,u.jsx)(ir.Elements,{stripe:aa,options:xs,children:(0,u.jsx)(Jl,{sessionId:e,nonce:t,email:oe.email,billingName:Rt||void 0,onBuyerIdentityReady:ge,billingApiUrl:k,onTokenizedBody:tn,onErrorChange:je,isProcessing:ye,onButtonClick:K,onDecline:m,onTechnicalFailure:xo,runBeforeButtonClick:Rn,onLoadStateChange:Ws,placeholderBorderRadius:go,popupCapabilityOwner:T,externalTelemetryContext:Qs,presentationMode:Ao})}),Bo&&(0,u.jsx)(ir.Elements,{stripe:cn,options:Ms,children:(0,u.jsx)(Zl,{sessionId:e,nonce:t,email:oe.email,billingName:Rt||void 0,onBuyerIdentityReady:ge,billingApiUrl:k,intentKind:nt>0?"payment":"setup",expressMethods:Fo,onTokenizedBody:tn,onErrorChange:je,onButtonClick:K,onDecline:m,onTechnicalFailure:xo,runBeforeButtonClick:Rn,onLoadStateChange:Hs,placeholderBorderRadius:go,popupCapabilityOwner:T,externalTelemetryContext:ot})}),sa&&(0,u.jsx)(Ql,{sessionId:e,nonce:t,email:oe.email,billingName:[oe.firstName,oe.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:k,paymentElementMethods:Ua,stripeInstance:cn,paymentElementBaseOptions:Oi,futureUseSession:Ge,onTokenizedBody:tn,onErrorChange:je,onButtonClick:K,onDecline:m,runBeforeButtonClick:Rn,onLoadStateChange:Gs,isProcessing:ye,submitButtonColor:ho,submitButtonBorderRadius:ar,submitButtonStyle:ne.submitButton,themeId:st,onExpandApm:mt,expandedApmMethod:or,buttonAppearance:{backgroundColor:ne.cardButton?.backgroundColor,borderColor:ne.cardInputBorder,textColor:ne.cardButton?.color,borderRadius:go}})]}),ve&&(Dc||Bc||Oc)&&(0,u.jsx)(yi,{label:"or pay with card"}),ve&&ul]})}var F=require("react/jsx-runtime"),ea=44,ws="flopay_checkout_saved_payment_resume",wi=new Map,bi=new Map;function ac(e,t){t.settled&&t.consumers===0&&wi.get(e)===t&&wi.delete(e)}function eu(e,t,r){let n=bi.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};bi.set(e,s);let l=()=>{bi.get(e)===s&&bi.delete(e)};return a.then(l,l),a}function Aa(e){return new Promise(t=>setTimeout(t,e))}function Si(e,t,r){let n=ri({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:He.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Fa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ps(e,t,r,n,a,s){let l=Si(e,t,r);l.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Fa(l)}function ic(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 sc(e,t,r,n,a){let s=(0,He.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:s.statusClass}),t instanceof He.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof He.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):s.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...s,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function vs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,He.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var tu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function ru(e){return new ao.FloPay(tu,{publishableKey:"provider_unavailable",...e})}async function Cs(e,t){let{publishableKey:r,paypalPublishableKey:n}=ns(e);return{...await os({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function ks(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function nu(){if(!ks())return null;try{let e=window.sessionStorage.getItem(ws);return e?JSON.parse(e):null}catch{return null}}function lc(e){if(ks())try{window.sessionStorage.setItem(ws,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function bs(){if(ks())try{window.sessionStorage.removeItem(ws)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ou(){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 cc(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 Ss(e,t){return(0,He.resolveCheckoutLogLayout)(!!e,t)}function au(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function dc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function iu(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 ki({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:l,loading:p,error:m,onComplete:f,onError:S,onInstrument:C,onDecline:R,onCancel:H,onCountryChange:E,onZipChange:Z,showPayPal:M=!0,showStripe:y=!0,walletPresentation:g="auto",enabledPaymentMethods:he,showApplePay:v=!0,showGooglePay:xe=!0,debug:I=!1,layout:se,theme:Pe,buttonsTheme:fe,buttonsStyles:Ae,cardButtonContent:st,cardBackButtonContent:Ke,cardTitleContent:B,showSecurityFooter:St,onButtonClick:Xe,onBeforeButtonClick:Ne,enableAVS:me,cardFieldOrder:ee,cardPreFormSlot:K,avsLayout:Ue,submitLabel:tt,className:qe,initialErrorMessage:Q=null,initialPayPalOrderId:G,children:$,checkoutMode:q,confirmLabel:Ve,renderConfirmButton:Oe,onSessionCompleted:Ce}){let O=(0,He.resolveBillingApiUrl)(n),Se=(0,h.useMemo)(()=>(0,He.resolveTheme)(Pe),[Pe]),ut=s??Se?.appearance,ze=r?"embedded_checkout":"standard_checkout",rt=Ss($,se),[Fe,et]=(0,h.useState)(null),[nt,cr]=(0,h.useState)(null),xt=(0,h.useRef)(null),bt=(0,h.useRef)(null),Re=(0,h.useRef)(0),[_,ht]=(0,h.useState)(null),pt=(0,h.useRef)(null),[N,Be]=(0,h.useState)(null),Lt=(0,h.useMemo)(()=>r?(0,ft.serializeCreateParams)(r):"",[r]),Ee=r?`create:${Lt}`:`session:${e??""}`,It=dc(N),P=(0,h.useRef)(new Set),T=(0,h.useRef)(Ee),Le=(0,h.useRef)(Ee);So(()=>{Le.current=Ee,T.current!==Ee&&(T.current=Ee,P.current.clear())},[Ee]);let Ie=(0,h.useCallback)(U=>{if(Le.current===Ee){if(es.FLO_INSTRUMENT_ONCE_NAMES.has(U.name)){if(P.current.has(U.name))return;P.current.add(U.name)}(0,Ze.invokeMerchantCallback)(()=>C?.(U))}},[Ee,C]),lt=Ko(Ie,Ee),ot=(0,h.useRef)(!1),We=(0,h.useCallback)(U=>{if(ot.current)return;let z=U.gateway||!It?U:{...U,gateway:It};Ie(z)},[Ie,It]);(0,h.useEffect)(()=>{lt({class:"lifecycle",name:"checkout.mount"})},[lt]);let[Ge,Dt]=(0,h.useState)(e??""),c=e??Ge,L=r?"":c,[j,ue]=(0,h.useState)(!0),[k,V]=(0,h.useState)(null),[Ut,Br]=(0,h.useState)(0),[dr,Yt]=(0,h.useState)("full"),[_t,qr]=(0,h.useState)(!1),[Dr,tr]=(0,h.useState)(Q),[Gr,Tt]=(0,h.useState)(null),[An,Xt]=(0,h.useState)(null),[pn,jr]=(0,h.useState)(!1),[Vr,ur]=(0,h.useState)(void 0),[br,Yr]=(0,h.useState)(""),[at,kt]=(0,h.useState)(!1),[xr,Wt]=(0,h.useState)(!1),[pr,fr]=(0,h.useState)(!1),Jt=(0,h.useRef)(null),Zt=(0,h.useRef)(0),Sr=(0,h.useRef)(void 0),[Je,wr]=(0,h.useState)("loading"),[kr,Hn]=(0,h.useState)(0),Or=(0,h.useRef)(!1),Lr=(0,h.useRef)(!1),Fn=(0,h.useRef)(!1),an=(0,h.useRef)(null),rr=(0,h.useRef)(null),ve=(0,h.useMemo)(()=>({checkoutMode:q??dr,layout:au($,se)}),[q,$,dr,se]),gr=(0,h.useRef)(f);gr.current=f;let Xr=(0,h.useRef)(S);Xr.current=S;let le=(0,h.useRef)(R);le.current=R;let At=(0,h.useCallback)(U=>ai(an,async z=>{try{return await U(z)}catch(ie){throw z.aborted?Yo(ie):ie}}),[]);(0,h.useEffect)(()=>()=>{an.current?.abort(),an.current=null},[]);let te=(0,h.useCallback)((U,z)=>{xt.current=U,cr(U),pt.current=z,ht(z)},[]),$t=(0,h.useCallback)(()=>{let U=bt.current;U&&(bt.current=null,U.destroy())},[]);(0,h.useEffect)(()=>{vr(nt)?.setCheckoutContext(ve),_&&_!==nt&&vr(_)?.setCheckoutContext(ve)},[nt,_,ve]);let nr=(0,h.useRef)(Ce);nr.current=Ce;let be=(0,h.useCallback)(U=>{wr(U),!(U!=="exhausted"||Fn.current)&&(Fn.current=!0,Xr.current?.(new He.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Vt=(0,h.useCallback)(()=>{wr("retrying"),Hn(U=>U+1)},[]);(0,h.useEffect)(()=>{wr("loading"),Hn(0),Fn.current=!1},[c]),(0,h.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:He.SDK_VERSION,checkout_type:ze,checkout_layout:rt,billing_api_url:O})},[rt,ze,O]);let ae=(0,h.useMemo)(()=>r?(0,ft.serializeCreateParams)(r,!0):"",[r]),Nt=(0,h.useMemo)(()=>br===ae?Vr:void 0,[Vr,br,ae]),hr=(0,h.useMemo)(()=>r?Xi(r,Nt):void 0,[r,Nt]),Nr=q??hr?.checkoutMode??"full",Qt=(0,h.useMemo)(()=>hr?{...hr,checkoutMode:Nr}:void 0,[hr,Nr]);(0,h.useEffect)(()=>{ur(void 0),Yr(ae),Sr.current=void 0,Jt.current=null,fr(!1)},[ae]),(0,h.useEffect)(()=>{tr(Q)},[Q]);let Bn=(0,h.useCallback)((U,z,ie)=>{(0,Ze.invokeMerchantCallback)(()=>{le.current?.(_r(U,z,ie))})},[]),Kn=(0,h.useCallback)(async(U,z)=>{tr(null),Xt(null),jr(!1),Tt("processing");let ie=z?.sessionId??U.id,we=U.clientSecret||t,mt=dc(U),Ht=xt.current??pt.current,_e=vr(Ht),pe=Ht?null:Si(O,a,ve),X={log:D=>{_e?_e.log(D):pe?.log(D)},error:D=>{_e?_e.error(D):pe?.error(D)},terminal:D=>{_e?_e.terminal(D):pe?.terminal(D)},performance:D=>{_e?_e.performance(D):pe?.performance(D)},now:()=>_e?.now()??pe?.now()??0,elapsed:D=>_e?.elapsed(D)??Math.max(0,(pe?.now()??D)-D)},W=X.now(),ce=!!(z?.initialAutoProcessingError||z?.initialAutoProcessingPending),$e=!1,de,yt=()=>{$e||($e=!0,ce=!0,de=X.now(),X.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),X.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ot=!1,x=()=>{Ot||(Ot=!0,X.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),X.performance({stage:"processing",durationMs:X.elapsed(W),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),de!==void 0&&X.performance({stage:"recovery",durationMs:X.elapsed(de),durationMode:"machine",paymentMethodCategory:"saved"}))};X.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ot.current=!0;try{X.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ot.current=!1}lt({class:"lifecycle",name:"payment.processing.started",provider:mt}),ce&&yt();let A;try{let D=Nl(z?.initialAutoProcessingError),re=z?.initialAutoProcessingError?.type==="3ds_required"&&!z.initialAutoProcessingError.threeDSecureToken&&z.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:z.initialAutoProcessingError.nextActionRedirectUrl}:null,ge,De=Pt=>(yt(),At(ne=>Xo(Pt,{billingApiUrl:O,sessionId:ie,nonce:we,session:U,signal:ne})));if(re)ge=await De(re);else if(D)yt(),D.type==="paypal_redirect_required"&&rr.current?.publishableKey&&lc({sessionId:ie,publishableKey:rr.current.publishableKey,paypalPublishableKey:rr.current.paypalPublishableKey}),ge=await At(Pt=>si(D,{flopay:xt.current,paypalFlopay:pt.current,attempt3DS:z?.attempt3DS,billingApiUrl:O,sessionId:ie,session:U,telemetry:!1,signal:Pt})),D.type==="paypal_redirect_required"&&bs();else if(z?.initialAutoProcessingPending){let Pt=z.initialAutoProcessingPending,ne=new ao.PaymentAPI(O,{telemetry:!1}),Mt=await At(ye=>ne.waitForCheckoutSessionCompletion(Pt.sessionId,{initialDelayMs:Pt.retryAfterMs,nonce:we,statusUrl:Pt.statusUrl,signal:ye})),Wr=uo(Mt,U),Er=Mt.autoProcessingError?.type==="3ds_required"&&Mt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Mt.autoProcessingError.nextActionRedirectUrl}:null;if(Er)ge=await De(Er);else{if(!eo(Wr))throw jo(Wr);ge=Qn(Wr,ie)}}else{if(z?.initialAutoProcessingError)throw jn(z.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:z.initialAutoProcessingError.checkoutMethod});if(z?.fromCreateSession)return z?.fallbackToFull&&(Yt("full"),cc("full")),!1;{let Pt=await Jo({billingApiUrl:O,sessionId:ie,session:U,nonce:we,telemetry:!1});Pt.type==="success"?ge=Pt.result:Pt.type==="next_action_required"?ge=await De(Pt):(yt(),Pt.type==="paypal_redirect_required"&&rr.current?.publishableKey&&lc({sessionId:ie,publishableKey:rr.current.publishableKey,paypalPublishableKey:rr.current.paypalPublishableKey}),ge=await At(ne=>si(Pt,{flopay:xt.current,paypalFlopay:pt.current,attempt3DS:z?.attempt3DS,billingApiUrl:O,sessionId:ie,session:U,telemetry:!1,signal:ne})),Pt.type==="paypal_redirect_required"&&bs())}}ie&&(0,Tn.markSessionRecentlyCompleted)(ie),x(),ce&&(X.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),X.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),X.terminal({outcome:ge.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),jr(ge.status==="authorized"),Tt("success"),await Aa(600),A=()=>gr.current?.(ge)}catch(D){let re=co(Ra(D),ie);if(re.code==="three_ds_aborted")return!1;let ge=re.checkoutMethod??ka;tr(re.message),Xt(re.message),jr(!1),z?.fallbackToFull&&(X.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Yt("full"),cc("full")),x();let De=re.statusCode===void 0?void 0:(0,He.telemetryStatusClass)(re.statusCode,"unknown"),Pt=De==="4xx"?{requestCategory:"process_payment",statusClass:De}:{},ne=De===void 0||De==="4xx";if(ne&&(re.telemetryOutcome==="payment_declined"||!!(re.declineCode||re.code?.toLowerCase().includes("declin"))))X.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Pt});else if(ne&&(re.telemetryOutcome==="validation_rejected"||re.type==="validation_error"))X.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Pt});else{let Er=(0,He.classifyTelemetryFailure)(D,ce?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),ye=re.telemetryRequestCategory??"process_payment";ot.current=!0;try{X.error({...Er,...re.telemetryFailureCategory?{failureCategory:re.telemetryFailureCategory}:{},stage:ce?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:ye})}finally{ot.current=!1}lt({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:ye,provider:mt})}return(0,Ze.invokeMerchantCallback)(()=>Xr.current?.(re)),Bn(ge,re,{code:re.code,declineCode:re.declineCode}),Tt("error"),await Promise.allSettled([Aa(400),z?.ensureProvidersReady?z.ensureProvidersReady():Promise.resolve()]),ce&&(X.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),X.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{x(),pe&&Fa(pe),Tt(null),Xt(null)}return(0,Ze.invokeMerchantCallback)(A),!0},[Bn,lt,t,O,At,a,ve]);(0,h.useEffect)(()=>{if(typeof window>"u"||Lr.current)return;let U=new URLSearchParams(window.location.search),z=U.get("payment_intent_client_secret");if(!z)return;let ie=nu();ie&&(Lr.current=!0,(async()=>{let we,mt=0;tr(null),Xt(null),Tt("processing"),qr(!0);try{if(U.get("redirect_status")==="failed")throw Object.assign(new He.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Ht,paypalFlopay:_e}=await os({publishableKey:ie.publishableKey,paypalPublishableKey:ie.paypalPublishableKey,billingApiUrl:O,locale:l,telemetry:a});we=vr(_e??Ht),we?.setCheckoutContext(ve),mt=we?.now()??0,we?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),we?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let pe=(_e??Ht)?.getRawProvider();if(!pe)throw Object.assign(new He.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:X,error:W}=await pe.retrievePaymentIntent(z);if(W)throw Object.assign(new He.FloPayError(W.message??"Failed to retrieve PayPal payment status.","api_error",{code:W.code}),{checkoutMethod:"paypal"});let ce=kl(X?.status);if(!X||ce==="failed")throw Object.assign(new He.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let $e=typeof X.payment_method=="string"?X.payment_method:X.payment_method?.id,de=ce;if(ie.sessionId){let x=(await new ao.PaymentAPI(O,{telemetry:!1}).getUnifiedCheckoutSession(ie.sessionId)).data.session;if(x&&x.status!=="complete"){let A=await Jo({billingApiUrl:O,sessionId:ie.sessionId,session:x,telemetry:!1,tokenizedData:{id:$e??X.id,type:"card",threeDSecureActionResultTokenId:X.id,isPaypal:!0}});if(A.type!=="success")throw Object.assign(new He.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});de=A.result.status}}ie.sessionId&&(0,Tn.markSessionRecentlyCompleted)(ie.sessionId),we?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),we?.performance({stage:"redirect_resume",durationMs:we.elapsed(mt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),we?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Tt("success"),await Aa(600),(0,Ze.invokeMerchantCallback)(()=>gr.current?.({status:de,paymentIntentId:X.id,paymentMethodId:$e,checkoutMethod:"paypal"}))}catch(Ht){let _e=co(Ra(Ht),ie.sessionId),pe=_e.checkoutMethod??"paypal",X=!!(_e.declineCode||_e.code?.toLowerCase().includes("declin"));if(we)we.performance({stage:"redirect_resume",durationMs:we.elapsed(mt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),X?we.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):we.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(X){let W=Si(O,a,ve);W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Fa(W)}else Ps(O,a,ve,"REDIRECT_RESUME_FAILED","redirect_resume");tr(_e.message),Xt(_e.message),(0,Ze.invokeMerchantCallback)(()=>Xr.current?.(_e)),Bn(pe,_e,{code:_e.code,declineCode:_e.declineCode}),Tt("error"),await Aa(400)}finally{bs(),ou(),Tt(null),Xt(null),qr(!1)}})())},[Bn,l,O,a,ve]);let Dn=(0,h.useRef)(null),On=(0,h.useMemo)(()=>Qt?(0,ft.serializeCreateParams)(Qt):"",[Qt]),Gn=(0,h.useRef)(Qt);Gn.current=Qt,(0,h.useEffect)(()=>{Dt(e??"")},[e]),(0,h.useEffect)(()=>{Or.current=!1,tr(Q),Xt(null),jr(!1),Tt(null)},[On,Q,e]);async function so(U,z,ie){let we=Si(O,a,ve),mt=new ao.PaymentAPI(O,{telemetry:!1}),Ht=!1;try{let _e=U.idempotencyKey===void 0?void 0:(0,He.resolveIdempotencyKey)(U.idempotencyKey),pe=(0,ft.readCachedInlineSession)(z,ie),X=(0,ft.readCachedInlineIdempotencyKey)(z,ie);pe?.canonicalIdentity===ie&&X&&X.canonicalIdentity===void 0&&((0,ft.persistCachedInlineIdempotencyKey)(z,ie,X.idempotencyKey),X={...X,canonicalIdentity:ie});let W=_e??(X?.canonicalIdentity===ie?X.idempotencyKey:void 0),ce,$e=!1;we.log({name:pe?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let de=pe?.sid??null,yt=null,Ot,x,A=!1;if(de)try{yt=await mt.getUnifiedCheckoutSession(de,pe?.nonce),pe&&pe.canonicalIdentity===void 0&&((0,ft.legacyCachedSessionMatchesDraft)(yt.data.session,U)?((0,ft.persistCachedInlineSession)(z,ie,de,pe.nonce??yt.data.session?.clientSecret),X&&X.canonicalIdentity===void 0&&((0,ft.persistCachedInlineIdempotencyKey)(z,ie,X.idempotencyKey),W??(W=X.idempotencyKey))):((0,ft.clearCachedInlineCheckout)(z,ie),X=null,W=_e,de=null,yt=null));let re=yt?.data.session?.status,ge=yt?.data.session,De=ge?.clientSecret||pe?.nonce;if(de&&ge?.buyerIdentified===!1&&De&&(x=qo(mt,de,De,U.account)),de&&yt&&re==="complete"){if((0,Tn.wasSessionRecentlyCompleted)(de))return{sid:de,result:yt};(0,ft.clearCachedInlineCheckout)(z,ie),de=null,yt=null,$e=!0}}catch{we.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),pe?.canonicalIdentity===void 0?((0,ft.clearCachedInlineCheckout)(z,ie),W=_e):(0,ft.clearCachedInlineSession)(z,ie),de=null}if(!de){!_e&&($e||!W)&&(W=(0,He.resolveIdempotencyKey)(),ce=W),W&&(0,ft.persistCachedInlineIdempotencyKey)(z,ie,W);let re=we.now(),ge=0;we.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let De={...U,idempotencyKey:W,avsCheck:!!me,avsConfig:typeof me=="object"?me:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ss($,se)};Object.defineProperty(De,ao.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Mt=>{ge=Math.max(ge,Mt)}}});let Pt=()=>{ic(we,"session_create",re,ge)},ne=Mt=>{sc(we,Mt,"session_create",re,ge)&<({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,He.isDetachedSessionEligible)(De)){let Mt=await mt.createDetachedSession(De);Mt.claimed.catch(()=>{}),yt=Mt.shell,de=Mt.sessionId,x=Mt.claim;let Wr=we.now();we.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Ot=Mt.claimed.then(Er=>{let ye=Er.data.session?.id??Mt.sessionId;return ye&&(0,ft.persistCachedInlineSession)(z,ie,ye,Er.data.session?.clientSecret??Mt.nonce),ic(we,"session_claim",Wr),Pt(),Er},Er=>{throw(0,ft.clearCachedInlineSession)(z,ie),sc(we,Er,"session_claim",Wr,0)&<({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Er}).finally(()=>Fa(we)),Ot.catch(()=>{}),Ht=!0,we.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),we.performance({stage:"session_shell",durationMs:we.now()-re,durationMode:"machine",requestCategory:"session_create",attempt:ge,statusClass:"2xx",paymentMethodCategory:"card"})}else yt=await mt.createAndFetchSession(De),Pt()}catch(Mt){throw ne(Mt),Mt}de=yt.data.session?.id??de??"",de&&!Ot&&(0,ft.persistCachedInlineSession)(z,ie,de,yt.data.session?.clientSecret)}let D=yt?.data.session;return!x&&de&&D?.buyerIdentified===!1&&D.clientSecret&&(x=qo(mt,de,D.clientSecret,U.account)),{sid:de??"",result:yt,sdkGeneratedIdempotencyKey:ce,...Ot?{claimed:Ot}:{},...x?{claim:x}:{},...A?{claimRequiresIdentity:!0}:{}}}finally{Ht||Fa(we)}}let lo=(0,h.useRef)(so);So(()=>{lo.current=so},[so]);let Ar=(0,h.useCallback)(async(U,z)=>{let ie=Gn.current;if(!ie)throw new He.FloPayError("createSession is required to bootstrap checkout.","validation_error");let we=Xi(ie,U),mt=(0,ft.serializeCreateParams)(we),Ht=(0,ft.hashCreateParams)(we),_e=wi.get(mt);if(!_e){let W={canonicalIdentity:mt,promise:lo.current(we,Ht,mt),consumers:0,settled:!1};_e=W,wi.set(mt,W);let ce=()=>{W.settled=!0,ac(mt,W)};W.promise.then(ce,ce)}_e.consumers+=1;let pe=!1,X=()=>{pe||(pe=!0,_e.consumers-=1,ac(mt,_e))};z?.(X);try{let W=await _e.promise;Dn.current=mt,U&&(Yr(ae),ur(D=>bl(D,U)));let{sid:ce,result:$e,claimed:de,claim:yt,claimRequiresIdentity:Ot}=W;if(Sr.current=yt,fr(Ot===!0),et($e),$e.data.session&&Be($e.data.session),ce&&Dt(ce),de){Zt.current+=1;let D=Zt.current;Jt.current=de,Wt(!0),de.then(re=>{Zt.current===D&&(Jt.current===de&&(Jt.current=null),et(re),re.data.session&&Be(re.data.session),Wt(!1),fr(!1))},re=>{Zt.current===D&&(Jt.current===de&&(Jt.current=null),Wt(!1),fr(!1),V(re instanceof He.FloPayError?re:new He.FloPayError(re instanceof Error?re.message:"Failed to create session","api_error")))})}else Zt.current+=1,Jt.current=null,Wt(!1),fr(!1);let{flopay:x,paypalFlopay:A}=await Cs($e,{billingApiUrl:O,locale:l,telemetry:a});return te(x,A),ue(!1),W}catch(W){throw Dn.current===mt&&(Dn.current=null),W}finally{z||X()}},[ae,te,l,O,a]),Yn=(0,h.useRef)(Kn);Yn.current=Kn;let mn=(0,h.useRef)(Ar);mn.current=Ar;let zt=(0,h.useCallback)(async U=>{if(!iu(U)||at)return{sessionId:Ge,session:N};kt(!0);try{let z=await Ar(U);return{sessionId:z.sid,session:z.result.data.session??null}}finally{kt(!1)}},[Ar,at,Ge,N]),Jr=(0,h.useCallback)(async U=>{let z=Sr.current;if(!z)return;let ie=Zt.current,we=await z(U);Zt.current===ie&&(et(we),we.data.session&&Be(we.data.session))},[]),Zr=(0,h.useCallback)(async()=>{await Jt.current},[]),sn=(0,h.useCallback)(async()=>(await Zr(),{proceed:!0}),[Zr]);(0,h.useEffect)(()=>{let U=!1,z,ie=++Re.current;$t(),V(null),Br(0);let we=()=>{U=!0,Re.current===ie&&(Re.current+=1,$t())},mt=Gn.current;if(On&&mt)return Yt(Nr),ue(!1),Dn.current===On?we:(Be(Sl(mt,q)),(async()=>{let pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),X=Nr==="auto"&&!Or.current&&!pe;X&&(tr(null),Xt(null),Tt("processing"));try{let W=await mn.current(void 0,yt=>{z=yt}),ce=W.result.data.session??null;rr.current=ns(W.result);let $e=vs(W.result),de=(0,Tn.wasSessionRecentlyCompleted)(W.sid||ce?.id);if(!U&&X&&ce&&!$e&&!de){Or.current=!0,await eu(On,W.sdkGeneratedIdempotencyKey,()=>Yn.current(ce,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:W.result.autoProcessingError,initialAutoProcessingPending:W.result.autoProcessingPending,autoProcessingAttempted:W.result.autoProcessingAttempted,sessionId:W.sid||ce.id}));return}!U&&X&&(($e||de)&&(Or.current=!0),Tt(null),Xt(null))}catch(W){if(U)return;let ce=Ya(W);if(X&&ce==="session_auto_completed"){Or.current=!0,Tt("success"),await Aa(600),U||((0,Ze.invokeMerchantCallback)(()=>{gr.current?.({status:"succeeded"})}),Tt(null),Xt(null));return}X&&(Tt(null),Xt(null));let $e=W instanceof He.FloPayError?W:new He.FloPayError(W instanceof Error?W.message:"Failed to create session","api_error");V($e)}finally{z?.(),z=void 0}})(),()=>{we(),z?.()});ue(!0);async function Ht(){let pe=!1,X=null;try{let W=new ao.PaymentAPI(O,{telemetry:!1}),ce=await W.getUnifiedCheckoutSession(c,t);if(X=ce,U)return;et(ce);let $e=ce.data.session??null;if(Be($e),!$e)throw new He.FloPayError("No session data returned","api_error");let de=$e.checkoutMode;if(de==="setup")throw new He.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if($e.status==="authorized"){ue(!1),(0,Ze.invokeMerchantCallback)(()=>{gr.current?.(Qn($e,c)),nr.current?.($e.successUrl??"")});return}if($e.status==="complete"){ue(!1),(0,Ze.invokeMerchantCallback)(()=>{nr.current?.($e.successUrl??"")});return}if($e.status==="expired")throw Ga($e);pe=!0;let yt=q??de??"full";Yt(yt),Zt.current+=1;let Ot=$e.clientSecret||t;Sr.current=$e.buyerIdentified===!1&&Ot?qo(W,c,Ot,{...$e.customer?.id?{userId:$e.customer.id}:{}}):void 0,Wt(!1),fr(!1);let x=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),A=vs(ce);if(yt==="auto"&&!Or.current&&!x&&!A){Or.current=!0;let D=_e(ce);try{if(await Yn.current($e,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>D,sessionId:c||$e.id}),U)return;await D,U||ue(!1);return}catch{if(U)return;await D,U||ue(!1);return}}await _e(ce),U||ue(!1)}catch(W){if(U)return;let ce=Cl(W,pe);if(pe&<({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ce){let{errorCode:de,stage:yt,...Ot}=ce;Ps(O,a,ve,de,yt,Ot)}if(ce?.stage==="provider_load"&&(q??X?.data.session?.checkoutMode??"full")==="full"&&vl(X,M,y)){let de=ru({billingApiUrl:O,locale:l,telemetry:a});bt.current=de,te(de,null),Br(1),ue(!1);return}let $e=W instanceof He.FloPayError&&ce?.stage!=="provider_load"?W:Pl();$e!==W&&(0,Ze.invokeMerchantCallback)(()=>Xr.current?.($e)),V($e),ue(!1)}}async function _e(pe){let{flopay:X,paypalFlopay:W,...ce}=await Cs(pe,{billingApiUrl:O,locale:l,telemetry:a});rr.current={publishableKey:ce.publishableKey,paypalPublishableKey:ce.paypalPublishableKey},te(X,W),Br(0)}return Ht(),we},[q,On,Nr,L,t,M,y]);let Qr=(0,h.useCallback)(async()=>{if(!Fe||Ut!==1)return;let U=Re.current;Br(2);try{let{flopay:z,paypalFlopay:ie}=await Cs(Fe,{billingApiUrl:O,locale:l,telemetry:a});if(Re.current!==U)return;$t(),te(z,ie),Br(0)}catch(z){if(Re.current!==U)return;let{errorCode:ie,stage:we,...mt}=Yi(z);Ps(O,a,ve,ie,we,mt)}},[$t,te,l,Ut,O,a,ve,Fe]),ct=!!(c&&(N?.clientSecret||t)),Pr=_t||!ct,or=(0,h.useCallback)(async()=>{if(!(_t||!ct||!N)){qr(!0),tr(null);try{await Kn(N,{attempt3DS:!0,fallbackToFull:!0,sessionId:c||N.id})}finally{qr(!1)}}},[c,_t,ct,Kn,N]),en=(0,He.resolveDirectPaypalConfig)(Fe?.data.paypal,G),fo=vs(Fe),Xn=(0,h.useMemo)(()=>{if(!(!Fe||!N||!Fe.data.stripe?.publishableKey))return{billingApiUrl:O}},[Fe,N,O]),wn=!!(r&&!$&&se==="buttons"&&Ne&&Nr==="full"),ln=!!(c&&((0,He.isMountableVaultBlock)(N?.vault)||(0,En.canRecoverHostedCardForm)(N))),Rr=(0,h.useMemo)(()=>({session:N,loading:j,error:k,checkoutMode:dr,inlineSessionDraft:Qt,applyInlineSessionPatch:wn?zt:void 0,inlineSessionPatchProcessing:at,claimPending:xr,claimRequiresIdentity:pr,claimBuyerIdentity:Jr,waitForDataAttachment:Zr}),[N,j,k,dr,Qt,wn,zt,at,xr,pr,Jr,Zr]),Jn=!!r&&se==="buttons"&&!fo&&!ln&&(!nt||!Xn),Ur=Gr?(0,F.jsx)(nn,{status:Gr,errorMessage:An,authorized:pn}):null;if(j&&!ln){if(p)return(0,F.jsxs)(F.Fragment,{children:[p,Ur]});if(se==="buttons"){let U=Se?.buttonsLayout?.cardButton?.borderRadius??Se?.appearance.variables?.borderRadius??8,z=ie=>(0,F.jsx)("div",{style:{height:ie,borderRadius:U,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:[M&&z(ea),y&&(v||xe)&&z(ea),y&&z(ea),(0,F.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ur]})}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); } }"})]}),Ur]})}return k?m?(0,F.jsx)(In.Provider,{value:Rr,children:m(k)}):(0,F.jsx)(In.Provider,{value:Rr,children:(0,F.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:k.message})}):Jn?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(In.Provider,{value:Rr,children:(0,F.jsx)(lu,{onButtonClick:Xe,showPayPal:M,showStripe:y,showApplePay:v,showGooglePay:xe,theme:Pe,buttonsTheme:fe,buttonsStyles:Ae,cardButtonContent:st,cardBackButtonContent:Ke,cardTitleContent:B})}),Ur]}):fo&&N&&en?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(In.Provider,{value:Rr,children:(0,F.jsxs)("div",{className:qe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Dr&&(0,F.jsx)(Go,{icon:!1,children:Dr}),Je==="retrying"&&(0,F.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Je==="exhausted"&&(0,F.jsxs)("div",{role:"alert",children:[(0,F.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,F.jsx)("button",{type:"button",onClick:Vt,children:"Retry PayPal"})]}),Je!=="exhausted"&&(0,F.jsx)("div",{"aria-hidden":Je==="retrying"?!0:void 0,style:Je==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,F.jsx)(Bl,{sessionId:c,nonce:N.clientSecret||void 0,billingApiUrl:O,email:N.customer?.email||Qt?.account?.email,billingName:[N.customer?.firstName,N.customer?.lastName].filter(Boolean).join(" ")||[Qt?.account?.firstName,Qt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Jr,clientId:en.clientId,environment:en.environment,currency:(N.currency??"usd").toUpperCase(),isSubscription:N.mode==="subscription",providerObjectType:en.providerObjectType,approvalPresentation:en.approvalPresentation,existingOrderId:en.existingOrderId,onComplete:f,onErrorChange:tr,onDecline:R,onCancel:H,onButtonClick:Xe,runBeforeButtonClick:sn,onInitializationStateChange:be,allowAutomaticRetry:kr===0,session:N,telemetry:a,telemetryContext:ve,onInstrument:We,debug:I},`${Ee}:paypal-init-${kr}`)})]})}),Ur]}):dr==="confirm"?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(In.Provider,{value:Rr,children:(0,F.jsx)(Sa,{flopay:nt,paypalFlopay:_,options:Xn??{billingApiUrl:O},onInstrument:We,children:(0,F.jsxs)("div",{className:qe,children:[Dr&&(0,F.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Dr}),Oe?Oe({onConfirm:or,isProcessing:Pr}):(0,F.jsx)("button",{type:"button",onClick:or,disabled:Pr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Pr?"not-allowed":"pointer",opacity:Pr?.6:1},children:_t?"Processing...":Ve??"Confirm Purchase"})]})},Ee)}),Ur]}):(!nt||!Xn)&&!(ln&&dr==="full")?(0,F.jsx)(F.Fragment,{children:Ur}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(In.Provider,{value:Rr,children:(0,F.jsxs)(Sa,{flopay:nt,paypalFlopay:_,options:Xn??{billingApiUrl:O},onInstrument:We,children:[Ut===1&&(0,F.jsx)("button",{type:"button",onClick:Qr,children:"Retry payment methods"}),$?(0,F.jsxs)(F.Fragment,{children:[Dr&&(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:Dr}),(0,F.jsx)(su,{sessionId:c,nonce:N?.clientSecret||void 0,billingApiUrl:O,session:N,submitLabel:tt,walletPresentation:g,children:$})]}):(0,F.jsx)(Ci,{sessionId:c,nonce:N?.clientSecret||void 0,telemetry:a,email:N?.customer?.email||Qt?.account?.email,userId:N?.customer?.id||Qt?.account?.userId,firstName:N?.customer?.firstName||Qt?.account?.firstName,lastName:N?.customer?.lastName||Qt?.account?.lastName,totalAmount:N?Math.round((0,He.buildCheckoutDisplayData)(N).total*100):0,currency:N?.currency?.toLowerCase()??"usd",onComplete:f,onError:S,onDecline:R,onCancel:H,error:Dr,onErrorChange:tr,showPayPal:M,showStripe:y,walletPresentation:g,enabledPaymentMethods:Ut?[]:he??Fe?.data.stripe?.enabledPaymentMethods??N?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Fe?.data.stripe?.enabledPaymentMethodCountries,showApplePay:v,showGooglePay:xe,layout:se,theme:Pe,buttonsTheme:fe,buttonsStyles:Ae,appearance:ut,cardButtonContent:st,cardBackButtonContent:Ke,cardTitleContent:B,onButtonClick:Xe,onBeforeButtonClick:Ne,onBuyerIdentityReady:Jr,enableAVS:me,...ee?{cardFieldOrder:ee}:{},...K?{cardPreFormSlot:K}:{},avsLayout:Ue,country:N?.customer?.country,city:N?.customer?.city,state:N?.customer?.state,onCountryChange:E,onZipChange:Z,avsCheck:!!me,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Ss($,se),className:qe,submitLabel:tt,directPaypal:en,isSubscription:N?.mode==="subscription",session:N,dataAttachmentPending:xr,dataAttachmentRequiresIdentity:pr,debug:I})]},Ee)}),Ur]})}function su({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,children:l}){return(0,F.jsx)(F.Fragment,{children:h.default.Children.map(l,p=>{if(!h.default.isValidElement(p))return p;let m=p.props,f={};return m.sessionId||(f.sessionId=e),!m.nonce&&t&&(f.nonce=t),m.billingApiUrl||(f.billingApiUrl=r),m.submitLabel===void 0&&a!==void 0&&(f.submitLabel=a),m.walletPresentation===void 0&&(f.walletPresentation=s),n?.customer&&(m.email||(f.email=n.customer.email),m.userId||(f.userId=n.customer.id),m.firstName||(f.firstName=n.customer.firstName),m.lastName||(f.lastName=n.customer.lastName)),Object.keys(f).length===0?p:h.default.cloneElement(p,f)})})}function lu({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:s,buttonsTheme:l,buttonsStyles:p,cardButtonContent:m,cardBackButtonContent:f,cardTitleContent:S}){let[C,R]=(0,h.useState)(!1),H=(0,h.useMemo)(()=>(0,He.resolveTheme)(s),[s]),E=(0,h.useMemo)(()=>{let g=H?.buttonsLayout??(0,He.resolveButtonsLayoutTheme)(l);return p?{...g,...p,cardButton:{...g.cardButton,...p.cardButton},cardFormContainer:{...g.cardFormContainer,...p.cardFormContainer},backButton:{...g.backButton,...p.backButton},backButtonIcon:{...g.backButtonIcon,...p.backButtonIcon},submitButton:{...g.submitButton,...p.submitButton},title:{...g.title,...p.title}}:g},[H,l,p]),Z=H?.buttonsLayout?.cardButton?.borderRadius??H?.appearance.variables?.borderRadius??8,M=g=>(0,F.jsx)("div",{style:{height:g,borderRadius:Z,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),y=m===void 0?{boxSizing:"border-box",height:ea,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(C){let g=E.cardInputBorder??"#e5e7eb",he=E.cardInputBackground??"white",v=No(f),xe=No(S);return(0,F.jsxs)("div",{style:{backgroundColor:E.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...E.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:()=>R(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:v?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...E.backButton},children:[(0,F.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...E.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)(zo,{content:f})]}),xe?(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,...E.title},children:(0,F.jsx)(ya,{content:S})})]}),(0,F.jsx)("div",{style:{backgroundColor:he,border:`1px solid ${g}`,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:he,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,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:he,borderTop:"none",borderRight:`1px solid ${g}`,borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,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:he,border:`1px solid ${g}`,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",...E.submitButton,opacity:.5}}),(0,F.jsx)("style",{children:`
|
|
38
|
+
`}),la&&ho&&(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:he?-2:0},children:[(0,u.jsxs)("button",{type:"button",onClick:we,style:{display:"inline-flex",alignItems:"center",gap:Vi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:L.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...L.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...L.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Uo,{content:Ne})]}),sl?(0,u.jsx)("div",{style:{flex:1}}):(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:L.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...L.title},children:(0,u.jsx)(ma,{content:ue})})]}),!la&&!sl&&(0,u.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Wi,order:he?-3:0,...L.title},children:(0,u.jsx)(ma,{content:ue})}),he&&$&&(0,u.jsx)("div",{style:{order:-2,width:"100%"},children:$}),he&&rt&&(0,u.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,u.jsx)("div",{style:{backgroundColor:Bo,border:`1px solid ${gn(Va)}`,borderRadius:lr,padding:"10px"},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Jt,onChange:i=>{zt("email"),Ht.current=i.target.value,Pr(i.target.value)},onPointerDown:()=>zt("email"),onKeyDown:()=>zt("email"),onBlur:()=>{tn("email")&&Qn(!0),Ot||Fi()},disabled:bt,required:!0,"aria-invalid":Va||void 0,"aria-describedby":Va?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...$i}})}),Va&&(0,u.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:da,children:Xr.empty?"Email address is required":"Enter a valid email address"})]}),Xe&&(0,u.jsx)("div",{style:{order:he?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Wt,C=(J=!1)=>({backgroundColor:Bo,border:`1px solid ${gn(J)}`,borderRadius:lr,marginTop:"0.5rem",padding:"10px"}),G=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...$i}),Te=(0,d.getStateOptions)(i);return(0,u.jsxs)(u.Fragment,{children:[(0,d.isAVSFieldVisible)(Xe.address_line_1,i)&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)("div",{style:C(er("line1")),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:rr,onChange:J=>{zt("line1"),Rr.current.addressLine1=!0,$t.current=J.target.value,Qr(J.target.value)},onPointerDown:()=>zt("line1"),onKeyDown:()=>zt("line1"),onBlur:()=>rn("line1"),disabled:bt,required:!0,"aria-invalid":er("line1")||void 0,"aria-describedby":er("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:G()})}),er("line1")&&(0,u.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:da,children:"Street address is required"})]}),(0,d.isAVSFieldVisible)(Xe.address_line_2,i)&&(0,u.jsx)("div",{style:C(),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Tt,onChange:J=>{Rr.current.addressLine2=!0,nr.current=J.target.value,Ln(J.target.value)},disabled:bt,"data-testid":"flopay-address-line2",style:G()})}),((0,d.isAVSFieldVisible)(Xe.city,i)||(0,d.isAVSFieldVisible)(Xe.state,i))&&(0,u.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Xe.city,i)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Bo,borderTop:`1px solid ${gn(er("city"))}`,borderRight:`1px solid ${gn(er("city"))}`,borderBottom:`1px solid ${gn(er("city"))}`,borderLeft:`1px solid ${gn(er("city"))}`,padding:"10px",borderTopLeftRadius:lr,borderBottomLeftRadius:lr,...(0,d.isAVSFieldVisible)(Xe.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:lr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Xt,onChange:J=>{zt("city"),Rr.current.city=!0,vr.current=J.target.value,yn(J.target.value)},onPointerDown:()=>zt("city"),onKeyDown:()=>zt("city"),onBlur:()=>rn("city"),disabled:bt,required:!0,"aria-invalid":er("city")||void 0,"aria-describedby":er("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:G()})}),(0,d.isAVSFieldVisible)(Xe.state,i)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Bo,borderTop:`1px solid ${gn(er("state"))}`,borderRight:`1px solid ${gn(er("state"))}`,borderBottom:`1px solid ${gn(er("state"))}`,borderLeft:`1px solid ${gn(er("state"))}`,padding:"10px",borderTopRightRadius:lr,borderBottomRightRadius:lr,...(0,d.isAVSFieldVisible)(Xe.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${gn(er("state")||er("city"))}`}:{borderRadius:lr}},children:Te?(0,u.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Hr,onChange:J=>{zt("state"),Rr.current.state=!0,Zt.current=J.target.value,Kr(J.target.value)},onPointerDown:()=>zt("state"),onKeyDown:()=>zt("state"),onBlur:()=>rn("state"),disabled:bt,autoComplete:"billing address-level1",required:!0,"aria-invalid":er("state")||void 0,"aria-describedby":er("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...G(),cursor:"pointer"},children:[(0,u.jsx)("option",{value:"",children:(0,d.getStateLabel)(i)}),Te.map(J=>(0,u.jsx)("option",{value:J.code,children:J.name},J.code))]}):(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,d.getStateLabel)(i),autoComplete:"billing address-level1",value:Hr,onChange:J=>{zt("state"),Rr.current.state=!0,Zt.current=J.target.value,Kr(J.target.value)},onPointerDown:()=>zt("state"),onKeyDown:()=>zt("state"),onBlur:()=>rn("state"),disabled:bt,required:!0,"aria-invalid":er("state")||void 0,"aria-describedby":er("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:G()})})]}),er("city")&&(0,u.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:da,children:"City is required"}),er("state")&&(0,u.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:da,children:[(0,d.getStateLabel)(i)," is required"]}),((0,d.isAVSFieldVisible)(Xe.country,i)||(0,d.isAVSFieldVisible)(Xe.postal_code,i))&&(0,u.jsxs)("div",{style:{display:"flex",flexDirection:H==="column"?"column":"row",gap:H==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Xe.country,i)&&(0,u.jsx)("div",{style:{flex:H==="row"?1:void 0,backgroundColor:Bo,borderTop:`1px solid ${ca}`,borderRight:`1px solid ${ca}`,borderBottom:`1px solid ${ca}`,borderLeft:`1px solid ${ca}`,padding:"10px",...H==="row"&&(0,d.isAVSFieldVisible)(Xe.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:lr,borderBottomLeftRadius:lr,borderRight:"none"}:{borderRadius:lr}},children:(0,u.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Wt,onChange:J=>{Rr.current.country=!0,Br.current=J.target.value,_t(J.target.value),pt?.(J.target.value),Zt.current="",Kr("")},disabled:bt,autoComplete:"billing country","data-testid":"flopay-country",style:{...G(),cursor:"pointer"},children:[Wt===""?(0,u.jsx)("option",{value:"",children:"Select country"}):null,d.COUNTRY_OPTIONS.map(J=>(0,u.jsxs)("option",{value:J.code,children:[J.flag," ",J.name]},J.code))]})}),(0,d.isAVSFieldVisible)(Xe.postal_code,i)&&(0,u.jsx)("div",{style:{flex:H==="row"?1:void 0,backgroundColor:Bo,border:`1px solid ${jc}`,padding:"10px",...H==="row"&&(0,d.isAVSFieldVisible)(Xe.country,i)?{borderRadius:"0",borderTopRightRadius:lr,borderBottomRightRadius:lr}:{borderRadius:lr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,d.getPostalCodeLabel)(Wt),autoComplete:"billing postal-code",value:$r,onChange:J=>{zt("zip"),Rr.current.zip=!0,kt.current=J.target.value,Nr(J.target.value),Ue?.(J.target.value)},onPointerDown:()=>zt("zip"),onKeyDown:()=>zt("zip"),onBlur:()=>{tn("zip")&&zn(!0)},disabled:bt,required:Nt.required,"aria-invalid":Wa||void 0,"aria-describedby":Wa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:G()})})]}),Wa&&(0,u.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:da,children:Nt.empty?`${(0,d.getPostalCodeLabel)(i)} is required`:Yd(i)})]})})()}),he&&Kc,Ce&&(0,u.jsx)(Ko,{margin:"0.75rem 0",styleOverride:L.errorBanner,children:Ce})]}),$a={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"},pl=i=>N?!me||!Vn?(0,u.jsx)("pre",{"data-testid":i,style:$a,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":i,style:$a,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${me}`,` directPaypalConfigured=${Vn}`,` inAppBrowserDetected=${String(za)}`,` shouldRenderDirectPayPal=${na}`,` shouldRenderStripePayPal=${aa}`,` hasPaypalStripeInstance=${!!_s}`].join(`
|
|
39
|
+
`)}):null,ml=i=>N?!S||!Vr?(0,u.jsx)("pre",{"data-testid":i,style:$a,children:"FloPay/Stripe-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":i,style:$a,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${S}`,` currency=${pr}`,` amountInCents=${ta}`,` enabledPaymentMethods: ${JSON.stringify(T??[])}`,` enabledPaymentMethodsProvided=${ra}`,` hasEnabledMethods=${Oa}`,` expressMethods: ${JSON.stringify(Na)}`,` walletExpressMethods: ${JSON.stringify(Ao)}`,` paymentElementMethods: ${JSON.stringify(Di)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ua)}`,` hasStripeInstance=${!!Vr}`,` shouldRenderWallets=${Fo}`,` shouldRenderPaymentElement=${ia}`].join(`
|
|
40
|
+
`)}):null,yl=ut==="apm-expanding"||ut==="apm-form"||ut==="apm-collapsing",Oo;ut==="apm-expanding"?Oo=Jl:ut==="apm-collapsing"&&(Oo=Zl);let Ha=sr?sc(Oi,sr,He):null;if(Re==="buttons"){let i=ut==="buttons"||ut==="expanding"||ut==="apm-expanding",C=ut==="expanding"||ut==="card"||ut==="collapsing",G=Ye===void 0?{boxSizing:"border-box",height:Jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Te;ut==="expanding"||ut==="apm-expanding"?Te=$d:(ut==="collapsing"||ut==="apm-collapsing")&&(Te=Wd);let J;return ut==="expanding"?J=Jl:ut==="collapsing"&&(J=Zl),(0,u.jsxs)("form",{onSubmit:zi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Zo,{}),Ie&&(0,u.jsx)(sn,{status:Ie,errorMessage:Ce,authorized:Er}),(0,u.jsxs)("div",{style:{display:"grid"},children:[(0,u.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Te?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Te?Kd:{},...Te?{animation:Te,pointerEvents:"none"}:{}},children:[pl("flopay-direct-paypal-gate-debug"),ml("flopay-stripe-gate-debug"),na&&vt&&(0,u.jsxs)(u.Fragment,{children:[Ze&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(ha.Provider,{value:x,children:(0,u.jsx)(va,{sessionId:e,nonce:t,billingApiUrl:E,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,clientId:vt.clientId,environment:vt.environment,currency:pr.toUpperCase(),isSubscription:be,providerObjectType:Dt,approvalPresentation:qa==="popup"?void 0:qa,onTokenizedBody:on,onComplete:l,onErrorChange:ze,onDecline:m,onCancel:h,onTechnicalFailure:Mo,onButtonClick:K,runBeforeButtonClick:Tn,isProcessing:bt,onLoadStateChange:Li,onInitializationStateChange:Ni,session:We,existingOrderId:Ze?.orderId,debug:N},Ze?.orderId??"fresh")})]}),aa&&(0,u.jsx)(cr.Elements,{stripe:oa,options:xs,children:(0,u.jsx)(ec,{sessionId:e,nonce:t,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,isProcessing:bt,onButtonClick:K,onDecline:m,onTechnicalFailure:Mo,runBeforeButtonClick:Tn,onLoadStateChange:Ws,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:Qs,presentationMode:xo})}),Fo?(0,u.jsx)(cr.Elements,{stripe:Vr,options:Ms,children:(0,u.jsx)(tc,{sessionId:e,nonce:t,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,billingApiUrl:E,intentKind:at>0?"payment":"setup",expressMethods:Ao,onTokenizedBody:on,onErrorChange:ze,onButtonClick:K,onDecline:m,onTechnicalFailure:Mo,runBeforeButtonClick:Tn,onLoadStateChange:Hs,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:it})}):null,!Fo&&Js?(0,u.jsx)("div",{style:{height:Jo,borderRadius:Po,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ia&&(0,u.jsx)(rc,{sessionId:e,nonce:t,email:se.email,billingName:[se.firstName,se.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:O,billingApiUrl:E,paymentElementMethods:Ua,stripeInstance:Vr,paymentElementBaseOptions:Oi,futureUseSession:He,onTokenizedBody:on,onErrorChange:ze,onButtonClick:K,onDecline:m,runBeforeButtonClick:Tn,onLoadStateChange:Gs,isProcessing:bt,submitButtonColor:vo,submitButtonBorderRadius:lr,submitButtonStyle:L.submitButton,onExpandApm:mt,expandedApmMethod:sr,themeId:lt,buttonAppearance:{backgroundColor:L.cardButton?.backgroundColor,borderColor:L.cardInputBorder,textColor:L.cardButton?.color,borderRadius:Po}}),he&&(0,u.jsx)("button",{type:"button",onClick:async()=>{bt||!(await Tn("card")).proceed||(K?.("card"),ie())},disabled:bt,style:{width:"100%",...G,...L.cardButton,...gs({themeBundle:_e,resolvedPrimaryColor:vo,resolvedBorderRadius:lr,submitButtonStyle:L.submitButton,explicitPrimaryColor:an?.colorPrimary}),fontSize:L.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:bt?"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:bt?.6:1},onMouseEnter:Me=>{!bt&&(_e||an?.colorPrimary)&&(Me.currentTarget.style.backgroundColor=$c)},onMouseLeave:Me=>{(_e||an?.colorPrimary)&&(Me.currentTarget.style.backgroundColor=vo)},onMouseDown:Me=>{Me.currentTarget.style.transform="scale(0.985)"},onMouseUp:Me=>{Me.currentTarget.style.transform="scale(1)"},children:(0,u.jsx)(No,{content:Ye})}),Ce&&ut==="buttons"&&(0,u.jsx)(Ko,{margin:"0.25rem 0",styleOverride:L.errorBanner,children:Ce})]}),he&&C&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...J?{animation:J}:{},...ut==="collapsing"?{pointerEvents:"none"}:{}},children:ul}),S&&yl&&sr&&Ha&&Vr&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...Oo?{animation:Oo}:{},...ut==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:ji,borderRadius:Ki,...ua,padding:Hi},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:Vi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:L.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...L.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...L.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Uo,{content:Ne})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:L.titleFontSize??"1.05rem",color:Wi,paddingRight:80,...L.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(sr)}`})]}),(0,u.jsx)(cr.Elements,{stripe:Vr,options:Ha,children:(0,u.jsx)(ms,{method:sr,sessionId:e,nonce:t,email:se.email,billingName:[se.firstName,se.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:O,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,onDecline:m,onCancel:Gt,runBeforeButtonClick:Tn,onButtonClick:K,isProcessing:bt,submitButtonColor:vo,submitButtonBorderRadius:lr,submitButtonStyle:L.submitButton,errorText:Ce})},sr)]})})]})]})}return yl&&sr&&Ha&&Vr&&S?(0,u.jsxs)("form",{onSubmit:zi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Zo,{}),Ie&&(0,u.jsx)(sn,{status:Ie,errorMessage:Ce,authorized:Er}),(0,u.jsx)("div",{style:{...Oo?{animation:Oo}:{},...ut==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:ji,borderRadius:Ki,...ua,padding:Hi},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:Vi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:L.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...L.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...L.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Uo,{content:Ne})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:L.titleFontSize??"1.05rem",color:Wi,paddingRight:80,...L.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(sr)}`})]}),(0,u.jsx)(cr.Elements,{stripe:Vr,options:Ha,children:(0,u.jsx)(ms,{method:sr,sessionId:e,nonce:t,email:se.email,billingName:[se.firstName,se.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:O,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,onDecline:m,onCancel:Gt,runBeforeButtonClick:Tn,onButtonClick:K,isProcessing:bt,submitButtonColor:vo,submitButtonBorderRadius:lr,submitButtonStyle:L.submitButton,errorText:Ce})},sr)]})})]}):(0,u.jsxs)("form",{onSubmit:zi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Zo,{}),Ie&&(0,u.jsx)(sn,{status:Ie,errorMessage:Ce,authorized:Er}),(0,u.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[pl("flopay-direct-paypal-gate-debug-default"),ml("flopay-stripe-gate-debug-default"),na&&vt&&(0,u.jsxs)(u.Fragment,{children:[Ze&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(ha.Provider,{value:x,children:(0,u.jsx)(va,{sessionId:e,nonce:t,billingApiUrl:E,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,clientId:vt.clientId,environment:vt.environment,currency:pr.toUpperCase(),isSubscription:be,providerObjectType:Dt,approvalPresentation:qa==="popup"?void 0:qa,onTokenizedBody:on,onComplete:l,onErrorChange:ze,onDecline:m,onCancel:h,onTechnicalFailure:Mo,onButtonClick:K,runBeforeButtonClick:Tn,isProcessing:bt,onLoadStateChange:Li,onInitializationStateChange:Ni,session:We,existingOrderId:Ze?.orderId,debug:N},Ze?.orderId??"fresh")})]}),aa&&(0,u.jsx)(cr.Elements,{stripe:oa,options:xs,children:(0,u.jsx)(ec,{sessionId:e,nonce:t,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,isProcessing:bt,onButtonClick:K,onDecline:m,onTechnicalFailure:Mo,runBeforeButtonClick:Tn,onLoadStateChange:Ws,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:Qs,presentationMode:xo})}),Fo&&(0,u.jsx)(cr.Elements,{stripe:Vr,options:Ms,children:(0,u.jsx)(tc,{sessionId:e,nonce:t,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,billingApiUrl:E,intentKind:at>0?"payment":"setup",expressMethods:Ao,onTokenizedBody:on,onErrorChange:ze,onButtonClick:K,onDecline:m,onTechnicalFailure:Mo,runBeforeButtonClick:Tn,onLoadStateChange:Hs,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:it})}),ia&&(0,u.jsx)(rc,{sessionId:e,nonce:t,email:se.email,billingName:[se.firstName,se.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:E,paymentElementMethods:Ua,stripeInstance:Vr,paymentElementBaseOptions:Oi,futureUseSession:He,onTokenizedBody:on,onErrorChange:ze,onButtonClick:K,onDecline:m,runBeforeButtonClick:Tn,onLoadStateChange:Gs,isProcessing:bt,submitButtonColor:vo,submitButtonBorderRadius:lr,submitButtonStyle:L.submitButton,themeId:lt,onExpandApm:mt,expandedApmMethod:sr,buttonAppearance:{backgroundColor:L.cardButton?.backgroundColor,borderColor:L.cardInputBorder,textColor:L.cardButton?.color,borderRadius:Po}})]}),he&&(Nc||Lc||Uc)&&(0,u.jsx)(fi,{label:"or pay with card"}),he&&ul]})}var F=require("react/jsx-runtime"),Qo=44,ws="flopay_checkout_saved_payment_resume",ki=new Map,Si=new Map;function lc(e,t){t.settled&&t.consumers===0&&ki.get(e)===t&&ki.delete(e)}function ru(e,t,r){let n=Si.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};Si.set(e,s);let l=()=>{Si.get(e)===s&&Si.delete(e)};return a.then(l,l),a}function xa(e){return new Promise(t=>setTimeout(t,e))}function wi(e,t,r){let n=ni({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Oe.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Aa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ps(e,t,r,n,a,s){let l=wi(e,t,r);l.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Aa(l)}function cc(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 dc(e,t,r,n,a){let s=(0,Oe.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:s.statusClass}),t instanceof Oe.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Oe.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):s.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...s,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function vs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,Oe.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var nu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function ou(e){return new co.FloPay(nu,{publishableKey:"provider_unavailable",...e})}async function Cs(e,t){let{publishableKey:r,paypalPublishableKey:n}=ns(e);return{...await os({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function ks(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function au(){if(!ks())return null;try{let e=window.sessionStorage.getItem(ws);return e?JSON.parse(e):null}catch{return null}}function uc(e){if(ks())try{window.sessionStorage.setItem(ws,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function bs(){if(ks())try{window.sessionStorage.removeItem(ws)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function iu(){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 pc(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 Ss(e,t){return(0,Oe.resolveCheckoutLogLayout)(!!e,t)}function su(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function mc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function lu(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 Ri({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:l,loading:p,error:m,onComplete:h,onError:R,onInstrument:w,onDecline:I,onCancel:Y,onCountryChange:_,onZipChange:Z,showPayPal:A=!0,showStripe:y=!0,walletPresentation:P="auto",enabledPaymentMethods:me,showApplePay:S=!0,showGooglePay:xe=!0,debug:T=!1,layout:le,theme:ye,buttonsTheme:pe,buttonsStyles:Re,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B,showSecurityFooter:wt,onButtonClick:Ye,onBeforeButtonClick:Ne,enableAVS:ue,cardFieldOrder:ne,cardPreFormSlot:K,avsLayout:Le,submitLabel:nt,className:je,initialErrorMessage:X=null,initialPayPalOrderId:$,children:H,checkoutMode:V,confirmLabel:Ve,renderConfirmButton:De,onSessionCompleted:fe}){let D=(0,Oe.resolveBillingApiUrl)(n),ge=(0,v.useMemo)(()=>(0,Oe.resolveTheme)(ye),[ye]),pt=s??ge?.appearance,Ue=r?"embedded_checkout":"standard_checkout",ot=Ss(H,le),[Ae,Qe]=(0,v.useState)(null),[at,pr]=(0,v.useState)(null),Mt=(0,v.useRef)(null),vt=(0,v.useRef)(null),be=(0,v.useRef)(0),[M,gt]=(0,v.useState)(null),ct=(0,v.useRef)(null),[N,Fe]=(0,v.useState)(null),Lt=(0,v.useMemo)(()=>r?(0,yt.serializeCreateParams)(r):"",[r]),Se=r?`create:${Lt}`:`session:${e??""}`,It=mc(N),b=(0,v.useRef)(new Set),x=(0,v.useRef)(Se),Be=(0,v.useRef)(Se);wo(()=>{Be.current=Se,x.current!==Se&&(x.current=Se,b.current.clear())},[Se]);let Ee=(0,v.useCallback)(q=>{if(Be.current===Se){if(es.FLO_INSTRUMENT_ONCE_NAMES.has(q.name)){if(b.current.has(q.name))return;b.current.add(q.name)}(0,Ke.invokeMerchantCallback)(()=>w?.(q))}},[Se,w]),dt=Ho(Ee,Se),it=(0,v.useRef)(!1),We=(0,v.useCallback)(q=>{if(it.current)return;let j=q.gateway||!It?q:{...q,gateway:It};Ee(j)},[Ee,It]);(0,v.useEffect)(()=>{dt({class:"lifecycle",name:"checkout.mount"})},[dt]);let[He,Dt]=(0,v.useState)(e??""),c=e??He,U=r?"":c,[W,ce]=(0,v.useState)(!0),[E,z]=(0,v.useState)(null),[Ut,Fr]=(0,v.useState)(0),[tr,Wt]=(0,v.useState)("full"),[_t,$r]=(0,v.useState)(!1),[Nr,rr]=(0,v.useState)(X),[Qr,Tt]=(0,v.useState)(null),[Ln,Xt]=(0,v.useState)(null),[yn,Hr]=(0,v.useState)(!1),[Kr,Jt]=(0,v.useState)(void 0),[Pr,en]=(0,v.useState)(""),[et,kt]=(0,v.useState)(!1),[Br,$t]=(0,v.useState)(!1),[nr,vr]=(0,v.useState)(!1),Zt=(0,v.useRef)(null),Ht=(0,v.useRef)(0),Rr=(0,v.useRef)(void 0),[Xe,or]=(0,v.useState)("loading"),[Er,Jn]=(0,v.useState)(0),Ur=(0,v.useRef)(!1),zr=(0,v.useRef)(!1),Nn=(0,v.useRef)(!1),cn=(0,v.useRef)(null),ar=(0,v.useRef)(null),he=(0,v.useMemo)(()=>({checkoutMode:V??tr,layout:su(H,le)}),[V,H,tr,le]),Cr=(0,v.useRef)(h);Cr.current=h;let Gr=(0,v.useRef)(R);Gr.current=R;let oe=(0,v.useRef)(I);oe.current=I;let xt=(0,v.useCallback)(q=>ii(cn,async j=>{try{return await q(j)}catch(ie){throw j.aborted?Go(ie):ie}}),[]);(0,v.useEffect)(()=>()=>{cn.current?.abort(),cn.current=null},[]);let Q=(0,v.useCallback)((q,j)=>{Mt.current=q,pr(q),ct.current=j,gt(j)},[]),Kt=(0,v.useCallback)(()=>{let q=vt.current;q&&(vt.current=null,q.destroy())},[]);(0,v.useEffect)(()=>{wr(at)?.setCheckoutContext(he),M&&M!==at&&wr(M)?.setCheckoutContext(he)},[at,M,he]);let ir=(0,v.useRef)(fe);ir.current=fe;let Pe=(0,v.useCallback)(q=>{or(q),!(q!=="exhausted"||Nn.current)&&(Nn.current=!0,Gr.current?.(new Oe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Vt=(0,v.useCallback)(()=>{or("retrying"),Jn(q=>q+1)},[]);(0,v.useEffect)(()=>{or("loading"),Jn(0),Nn.current=!1},[c]),(0,v.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Oe.SDK_VERSION,checkout_type:Ue,checkout_layout:ot,billing_api_url:D})},[ot,Ue,D]);let ae=(0,v.useMemo)(()=>r?(0,yt.serializeCreateParams)(r,!0):"",[r]),Nt=(0,v.useMemo)(()=>Pr===ae?Kr:void 0,[Kr,Pr,ae]),br=(0,v.useMemo)(()=>r?Xi(r,Nt):void 0,[r,Nt]),qr=V??br?.checkoutMode??"full",Qt=(0,v.useMemo)(()=>br?{...br,checkoutMode:qr}:void 0,[br,qr]);(0,v.useEffect)(()=>{Jt(void 0),en(ae),Rr.current=void 0,Zt.current=null,vr(!1)},[ae]),(0,v.useEffect)(()=>{rr(X)},[X]);let Un=(0,v.useCallback)((q,j,ie)=>{(0,Ke.invokeMerchantCallback)(()=>{oe.current?.(Sr(q,j,ie))})},[]),Zn=(0,v.useCallback)(async(q,j)=>{rr(null),Xt(null),Hr(!1),Tt("processing");let ie=j?.sessionId??q.id,we=q.clientSecret||t,mt=mc(q),Gt=Mt.current??ct.current,Ie=wr(Gt),de=Gt?null:wi(D,a,he),ee={log:g=>{Ie?Ie.log(g):de?.log(g)},error:g=>{Ie?Ie.error(g):de?.error(g)},terminal:g=>{Ie?Ie.terminal(g):de?.terminal(g)},performance:g=>{Ie?Ie.performance(g):de?.performance(g)},now:()=>Ie?.now()??de?.now()??0,elapsed:g=>Ie?.elapsed(g)??Math.max(0,(de?.now()??g)-g)},ve=ee.now(),te=!!(j?.initialAutoProcessingError||j?.initialAutoProcessingPending),tt=!1,re,Je=()=>{tt||(tt=!0,te=!0,re=ee.now(),ee.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ze=!1,At=()=>{Ze||(Ze=!0,ee.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),ee.performance({stage:"processing",durationMs:ee.elapsed(ve),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),re!==void 0&&ee.performance({stage:"recovery",durationMs:ee.elapsed(re),durationMode:"machine",paymentMethodCategory:"saved"}))};ee.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),it.current=!0;try{ee.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{it.current=!1}dt({class:"lifecycle",name:"payment.processing.started",provider:mt}),te&&Je();let _r;try{let g=ql(j?.initialAutoProcessingError),f=j?.initialAutoProcessingError?.type==="3ds_required"&&!j.initialAutoProcessingError.threeDSecureToken&&j.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:j.initialAutoProcessingError.nextActionRedirectUrl}:null,O,Ce=_e=>(Je(),xt(L=>Yo(_e,{billingApiUrl:D,sessionId:ie,nonce:we,session:q,signal:L})));if(f)O=await Ce(f);else if(g)Je(),g.type==="paypal_redirect_required"&&ar.current?.publishableKey&&uc({sessionId:ie,publishableKey:ar.current.publishableKey,paypalPublishableKey:ar.current.paypalPublishableKey}),O=await xt(_e=>li(g,{flopay:Mt.current,paypalFlopay:ct.current,attempt3DS:j?.attempt3DS,billingApiUrl:D,sessionId:ie,session:q,telemetry:!1,signal:_e})),g.type==="paypal_redirect_required"&&bs();else if(j?.initialAutoProcessingPending){let _e=j.initialAutoProcessingPending,L=new co.PaymentAPI(D,{telemetry:!1}),Ct=await xt(bt=>L.waitForCheckoutSessionCompletion(_e.sessionId,{initialDelayMs:_e.retryAfterMs,nonce:we,statusUrl:_e.statusUrl,signal:bt})),yr=fo(Ct,q),Tr=Ct.autoProcessingError?.type==="3ds_required"&&Ct.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ct.autoProcessingError.nextActionRedirectUrl}:null;if(Tr)O=await Ce(Tr);else{if(!oo(yr))throw qo(yr);O=no(yr,ie)}}else{if(j?.initialAutoProcessingError)throw Kn(j.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.initialAutoProcessingError.checkoutMethod});if(j?.fromCreateSession)return j?.fallbackToFull&&(Wt("full"),pc("full")),!1;{let _e=await Xo({billingApiUrl:D,sessionId:ie,session:q,nonce:we,telemetry:!1});_e.type==="success"?O=_e.result:_e.type==="next_action_required"?O=await Ce(_e):(Je(),_e.type==="paypal_redirect_required"&&ar.current?.publishableKey&&uc({sessionId:ie,publishableKey:ar.current.publishableKey,paypalPublishableKey:ar.current.paypalPublishableKey}),O=await xt(L=>li(_e,{flopay:Mt.current,paypalFlopay:ct.current,attempt3DS:j?.attempt3DS,billingApiUrl:D,sessionId:ie,session:q,telemetry:!1,signal:L})),_e.type==="paypal_redirect_required"&&bs())}}ie&&(0,Bn.markSessionRecentlyCompleted)(ie),At(),te&&(ee.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),ee.terminal({outcome:O.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Hr(O.status==="authorized"),Tt("success"),await xa(600),_r=()=>Cr.current?.(O)}catch(g){let f=yo(ka(g),ie);if(f.code==="three_ds_aborted")return!1;let O=f.checkoutMethod??wa;rr(f.message),Xt(f.message),Hr(!1),j?.fallbackToFull&&(ee.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Wt("full"),pc("full")),At();let Ce=f.statusCode===void 0?void 0:(0,Oe.telemetryStatusClass)(f.statusCode,"unknown"),_e=Ce==="4xx"?{requestCategory:"process_payment",statusClass:Ce}:{},L=Ce===void 0||Ce==="4xx";if(L&&(f.telemetryOutcome==="payment_declined"||!!(f.declineCode||f.code?.toLowerCase().includes("declin"))))ee.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",..._e});else if(L&&(f.telemetryOutcome==="validation_rejected"||f.type==="validation_error"))ee.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",..._e});else{let Tr=(0,Oe.classifyTelemetryFailure)(g,te?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),bt=f.telemetryRequestCategory??"process_payment";it.current=!0;try{ee.error({...Tr,...f.telemetryFailureCategory?{failureCategory:f.telemetryFailureCategory}:{},stage:te?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:bt})}finally{it.current=!1}dt({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:bt,provider:mt})}return(0,Ke.invokeMerchantCallback)(()=>Gr.current?.(f)),Un(O,f,{code:f.code,declineCode:f.declineCode}),Tt("error"),await Promise.allSettled([xa(400),j?.ensureProvidersReady?j.ensureProvidersReady():Promise.resolve()]),te&&(ee.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{At(),de&&Aa(de),Tt(null),Xt(null)}return(0,Ke.invokeMerchantCallback)(_r),!0},[Un,dt,t,D,xt,a,he]);(0,v.useEffect)(()=>{if(typeof window>"u"||zr.current)return;let q=new URLSearchParams(window.location.search),j=q.get("payment_intent_client_secret");if(!j)return;let ie=au();ie&&(zr.current=!0,(async()=>{let we,mt=0;rr(null),Xt(null),Tt("processing"),$r(!0);try{if(q.get("redirect_status")==="failed")throw Object.assign(new Oe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Gt,paypalFlopay:Ie}=await os({publishableKey:ie.publishableKey,paypalPublishableKey:ie.paypalPublishableKey,billingApiUrl:D,locale:l,telemetry:a});we=wr(Ie??Gt),we?.setCheckoutContext(he),mt=we?.now()??0,we?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),we?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let de=(Ie??Gt)?.getRawProvider();if(!de)throw Object.assign(new Oe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:ee,error:ve}=await de.retrievePaymentIntent(j);if(ve)throw Object.assign(new Oe.FloPayError(ve.message??"Failed to retrieve PayPal payment status.","api_error",{code:ve.code}),{checkoutMethod:"paypal"});let te=El(ee?.status);if(!ee||te==="failed")throw Object.assign(new Oe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let tt=typeof ee.payment_method=="string"?ee.payment_method:ee.payment_method?.id,re=te;if(ie.sessionId){let At=(await new co.PaymentAPI(D,{telemetry:!1}).getUnifiedCheckoutSession(ie.sessionId)).data.session;if(At&&At.status!=="complete"){let _r=await Xo({billingApiUrl:D,sessionId:ie.sessionId,session:At,telemetry:!1,tokenizedData:{id:tt??ee.id,type:"card",threeDSecureActionResultTokenId:ee.id,isPaypal:!0}});if(_r.type!=="success")throw Object.assign(new Oe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});re=_r.result.status}}ie.sessionId&&(0,Bn.markSessionRecentlyCompleted)(ie.sessionId),we?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),we?.performance({stage:"redirect_resume",durationMs:we.elapsed(mt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),we?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Tt("success"),await xa(600),(0,Ke.invokeMerchantCallback)(()=>Cr.current?.({status:re,paymentIntentId:ee.id,paymentMethodId:tt,checkoutMethod:"paypal"}))}catch(Gt){let Ie=yo(ka(Gt),ie.sessionId),de=Ie.checkoutMethod??"paypal",ee=!!(Ie.declineCode||Ie.code?.toLowerCase().includes("declin"));if(we)we.performance({stage:"redirect_resume",durationMs:we.elapsed(mt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ee?we.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):we.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(ee){let ve=wi(D,a,he);ve.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Aa(ve)}else Ps(D,a,he,"REDIRECT_RESUME_FAILED","redirect_resume");rr(Ie.message),Xt(Ie.message),(0,Ke.invokeMerchantCallback)(()=>Gr.current?.(Ie)),Un(de,Ie,{code:Ie.code,declineCode:Ie.declineCode}),Tt("error"),await xa(400)}finally{bs(),iu(),Tt(null),Xt(null),$r(!1)}})())},[Un,l,D,a,he]);let zn=(0,v.useRef)(null),qn=(0,v.useMemo)(()=>Qt?(0,yt.serializeCreateParams)(Qt):"",[Qt]),Qn=(0,v.useRef)(Qt);Qn.current=Qt,(0,v.useEffect)(()=>{Dt(e??"")},[e]),(0,v.useEffect)(()=>{Ur.current=!1,rr(X),Xt(null),Hr(!1),Tt(null)},[qn,X,e]);async function po(q,j,ie){let we=wi(D,a,he),mt=new co.PaymentAPI(D,{telemetry:!1}),Gt=!1;try{let Ie=q.idempotencyKey===void 0?void 0:(0,Oe.resolveIdempotencyKey)(q.idempotencyKey),de=(0,yt.readCachedInlineSession)(j,ie),ee=(0,yt.readCachedInlineIdempotencyKey)(j,ie);de?.canonicalIdentity===ie&&ee&&ee.canonicalIdentity===void 0&&((0,yt.persistCachedInlineIdempotencyKey)(j,ie,ee.idempotencyKey),ee={...ee,canonicalIdentity:ie});let ve=Ie??(ee?.canonicalIdentity===ie?ee.idempotencyKey:void 0),te,tt=!1;we.log({name:de?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let re=de?.sid??null,Je=null,Ze,At,_r=!1;if(re)try{Je=await mt.getUnifiedCheckoutSession(re,de?.nonce),de&&de.canonicalIdentity===void 0&&((0,yt.legacyCachedSessionMatchesDraft)(Je.data.session,q)?((0,yt.persistCachedInlineSession)(j,ie,re,de.nonce??Je.data.session?.clientSecret),ee&&ee.canonicalIdentity===void 0&&((0,yt.persistCachedInlineIdempotencyKey)(j,ie,ee.idempotencyKey),ve??(ve=ee.idempotencyKey))):((0,yt.clearCachedInlineCheckout)(j,ie),ee=null,ve=Ie,re=null,Je=null));let f=Je?.data.session?.status,O=Je?.data.session,Ce=O?.clientSecret||de?.nonce;if(re&&O?.buyerIdentified===!1&&Ce&&(At=zo(mt,re,Ce,q.account)),re&&Je&&f==="complete"){if((0,Bn.wasSessionRecentlyCompleted)(re))return{sid:re,result:Je};(0,yt.clearCachedInlineCheckout)(j,ie),re=null,Je=null,tt=!0}}catch{we.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),de?.canonicalIdentity===void 0?((0,yt.clearCachedInlineCheckout)(j,ie),ve=Ie):(0,yt.clearCachedInlineSession)(j,ie),re=null}if(!re){!Ie&&(tt||!ve)&&(ve=(0,Oe.resolveIdempotencyKey)(),te=ve),ve&&(0,yt.persistCachedInlineIdempotencyKey)(j,ie,ve);let f=we.now(),O=0;we.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ce={...q,idempotencyKey:ve,avsCheck:!!ue,avsConfig:typeof ue=="object"?ue:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ss(H,le)};Object.defineProperty(Ce,co.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Ct=>{O=Math.max(O,Ct)}}});let _e=()=>{cc(we,"session_create",f,O)},L=Ct=>{dc(we,Ct,"session_create",f,O)&&dt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Oe.isDetachedSessionEligible)(Ce)){let Ct=await mt.createDetachedSession(Ce);Ct.claimed.catch(()=>{}),Je=Ct.shell,re=Ct.sessionId,At=Ct.claim;let yr=we.now();we.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Ze=Ct.claimed.then(Tr=>{let bt=Tr.data.session?.id??Ct.sessionId;return bt&&(0,yt.persistCachedInlineSession)(j,ie,bt,Tr.data.session?.clientSecret??Ct.nonce),cc(we,"session_claim",yr),_e(),Tr},Tr=>{throw(0,yt.clearCachedInlineSession)(j,ie),dc(we,Tr,"session_claim",yr,0)&&dt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Tr}).finally(()=>Aa(we)),Ze.catch(()=>{}),Gt=!0,we.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),we.performance({stage:"session_shell",durationMs:we.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:O,statusClass:"2xx",paymentMethodCategory:"card"})}else Je=await mt.createAndFetchSession(Ce),_e()}catch(Ct){throw L(Ct),Ct}re=Je.data.session?.id??re??"",re&&!Ze&&(0,yt.persistCachedInlineSession)(j,ie,re,Je.data.session?.clientSecret)}let g=Je?.data.session;return!At&&re&&g?.buyerIdentified===!1&&g.clientSecret&&(At=zo(mt,re,g.clientSecret,q.account)),{sid:re??"",result:Je,sdkGeneratedIdempotencyKey:te,...Ze?{claimed:Ze}:{},...At?{claim:At}:{},..._r?{claimRequiresIdentity:!0}:{}}}finally{Gt||Aa(we)}}let mo=(0,v.useRef)(po);wo(()=>{mo.current=po},[po]);let Dr=(0,v.useCallback)(async(q,j)=>{let ie=Qn.current;if(!ie)throw new Oe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let we=Xi(ie,q),mt=(0,yt.serializeCreateParams)(we),Gt=(0,yt.hashCreateParams)(we),Ie=ki.get(mt);if(!Ie){let ve={canonicalIdentity:mt,promise:mo.current(we,Gt,mt),consumers:0,settled:!1};Ie=ve,ki.set(mt,ve);let te=()=>{ve.settled=!0,lc(mt,ve)};ve.promise.then(te,te)}Ie.consumers+=1;let de=!1,ee=()=>{de||(de=!0,Ie.consumers-=1,lc(mt,Ie))};j?.(ee);try{let ve=await Ie.promise;zn.current=mt,q&&(en(ae),Jt(g=>Cl(g,q)));let{sid:te,result:tt,claimed:re,claim:Je,claimRequiresIdentity:Ze}=ve;if(Rr.current=Je,vr(Ze===!0),Qe(tt),tt.data.session&&Fe(tt.data.session),te&&Dt(te),re){Ht.current+=1;let g=Ht.current;Zt.current=re,$t(!0),re.then(f=>{Ht.current===g&&(Zt.current===re&&(Zt.current=null),Qe(f),f.data.session&&Fe(f.data.session),$t(!1),vr(!1))},f=>{Ht.current===g&&(Zt.current===re&&(Zt.current=null),$t(!1),vr(!1),z(f instanceof Oe.FloPayError?f:new Oe.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error")))})}else Ht.current+=1,Zt.current=null,$t(!1),vr(!1);let{flopay:At,paypalFlopay:_r}=await Cs(tt,{billingApiUrl:D,locale:l,telemetry:a}).catch(g=>{throw wl(g,te||tt.data.session?.id)});return Q(At,_r),ce(!1),ve}catch(ve){throw zn.current===mt&&(zn.current=null),ve}finally{j||ee()}},[ae,Q,l,D,a]),eo=(0,v.useRef)(Zn);eo.current=Zn;let fn=(0,v.useRef)(Dr);fn.current=Dr;let zt=(0,v.useCallback)(async q=>{if(!lu(q)||et)return{sessionId:He,session:N};kt(!0);try{let j=await Dr(q);return{sessionId:j.sid,session:j.result.data.session??null}}finally{kt(!1)}},[Dr,et,He,N]),tn=(0,v.useCallback)(async q=>{let j=Rr.current;if(!j)return;let ie=Ht.current,we=await j(q);Ht.current===ie&&(Qe(we),we.data.session&&Fe(we.data.session))},[]),rn=(0,v.useCallback)(async()=>{await Zt.current},[]),dn=(0,v.useCallback)(async()=>(await rn(),{proceed:!0}),[rn]);(0,v.useEffect)(()=>{let q=!1,j,ie=++be.current;Kt(),z(null),Fr(0);let we=()=>{q=!0,be.current===ie&&(be.current+=1,Kt())},mt=Qn.current;if(qn&&mt)return Wt(qr),ce(!1),zn.current===qn?we:(Fe(bl(mt,V)),(async()=>{let de=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ee=qr==="auto"&&!Ur.current&&!de;ee&&(rr(null),Xt(null),Tt("processing"));let ve=!1;try{let te=await fn.current(void 0,Ze=>{j=Ze});ve=!0;let tt=te.result.data.session??null;ar.current=ns(te.result);let re=vs(te.result),Je=(0,Bn.wasSessionRecentlyCompleted)(te.sid||tt?.id);if(!q&&ee&&tt&&!re&&!Je){Ur.current=!0,await ru(qn,te.sdkGeneratedIdempotencyKey,()=>eo.current(tt,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:te.result.autoProcessingError,initialAutoProcessingPending:te.result.autoProcessingPending,autoProcessingAttempted:te.result.autoProcessingAttempted,sessionId:te.sid||tt.id}));return}!q&&ee&&((re||Je)&&(Ur.current=!0),Tt(null),Xt(null))}catch(te){if(q)return;let tt=Xa(te);if(ee&&tt==="session_auto_completed"){Ur.current=!0,Tt("success"),await xa(600),q||((0,Ke.invokeMerchantCallback)(()=>{Cr.current?.({status:"succeeded"})}),Tt(null),Xt(null));return}if(ee&&(Tt(null),Xt(null)),!ve){let Je=kl(te),Ze=(0,Oe.toPublicCheckoutInitError)(te,Je?{stage:"provider_load",provider:"stripe",...Je}:{stage:"session_request"});(Je||!(te instanceof Oe.FloPayError))&&(0,Ke.invokeMerchantCallback)(()=>Gr.current?.(Ze)),z(Ze);return}let re=te instanceof Oe.FloPayError?te:new Oe.FloPayError(te instanceof Error?te.message:"Failed to create session","api_error");z(re)}finally{j?.(),j=void 0}})(),()=>{we(),j?.()});ce(!0);async function Gt(){let de=!1,ee=!1,ve=null;try{let te=new co.PaymentAPI(D,{telemetry:!1}),tt=await te.getUnifiedCheckoutSession(c,t);if(ee=!0,ve=tt,q)return;Qe(tt);let re=tt.data.session??null;if(Fe(re),!re)throw new Oe.FloPayError("No session data returned","api_error");let Je=re.checkoutMode;if(Je==="setup")throw new Oe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(re.status==="authorized"){ce(!1),(0,Ke.invokeMerchantCallback)(()=>{Cr.current?.(no(re,c)),ir.current?.(re.successUrl??"")});return}if(re.status==="complete"){ce(!1),(0,Ke.invokeMerchantCallback)(()=>{ir.current?.(re.successUrl??"")});return}if(re.status==="expired")throw Ya(re);de=!0;let Ze=V??Je??"full";Wt(Ze),Ht.current+=1;let At=re.clientSecret||t;Rr.current=re.buyerIdentified===!1&&At?zo(te,c,At,{...re.customer?.id?{userId:re.customer.id}:{}}):void 0,$t(!1),vr(!1);let _r=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),g=vs(tt);if(Ze==="auto"&&!Ur.current&&!_r&&!g){Ur.current=!0;let f=Ie(tt);try{if(await eo.current(re,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>f,sessionId:c||re.id}),q)return;await f,q||ce(!1);return}catch{if(q)return;await f,q||ce(!1);return}}await Ie(tt),q||ce(!1)}catch(te){if(q)return;let tt=vl(te,de);if(de&&dt({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),tt){let{errorCode:At,stage:_r,...g}=tt;Ps(D,a,he,At,_r,g)}if(tt?.stage==="provider_load"&&(V??ve?.data.session?.checkoutMode??"full")==="full"&&Pl(ve,A,y)){let At=ou({billingApiUrl:D,locale:l,telemetry:a});vt.current=At,Q(At,null),Fr(1),ce(!1);return}let re=tt?.stage==="provider_load",Je="session_request";re?Je="provider_load":ee&&(Je="post_session");let Ze=(0,Oe.toPublicCheckoutInitError)(te,{stage:Je,provider:"stripe",sessionId:c||void 0});(re||!(te instanceof Oe.FloPayError))&&(0,Ke.invokeMerchantCallback)(()=>Gr.current?.(Ze)),z(Ze),ce(!1)}}async function Ie(de){let{flopay:ee,paypalFlopay:ve,...te}=await Cs(de,{billingApiUrl:D,locale:l,telemetry:a});ar.current={publishableKey:te.publishableKey,paypalPublishableKey:te.paypalPublishableKey},Q(ee,ve),Fr(0)}return Gt(),we},[V,qn,qr,U,t,A,y]);let nn=(0,v.useCallback)(async()=>{if(!Ae||Ut!==1)return;let q=be.current;Fr(2);try{let{flopay:j,paypalFlopay:ie}=await Cs(Ae,{billingApiUrl:D,locale:l,telemetry:a});if(be.current!==q)return;Kt(),Q(j,ie),Fr(0)}catch(j){if(be.current!==q)return;let{errorCode:ie,stage:we,...mt}=Yi(j);Ps(D,a,he,ie,we,mt)}},[Kt,Q,l,Ut,D,a,he,Ae]),ut=!!(c&&(N?.clientSecret||t)),mr=_t||!ut,sr=(0,v.useCallback)(async()=>{if(!(_t||!ut||!N)){$r(!0),rr(null);try{await Zn(N,{attempt3DS:!0,fallbackToFull:!0,sessionId:c||N.id})}finally{$r(!1)}}},[c,_t,ut,Zn,N]),Yr=(0,Oe.resolveDirectPaypalConfig)(Ae?.data.paypal,$),ho=vs(Ae),to=(0,v.useMemo)(()=>{if(!(!Ae||!N||!Ae.data.stripe?.publishableKey))return{billingApiUrl:D}},[Ae,N,D]),In=!!(r&&!H&&le==="buttons"&&Ne&&qr==="full"),un=!!(c&&((0,Oe.isMountableVaultBlock)(N?.vault)||(0,xn.canRecoverHostedCardForm)(N))),Ir=(0,v.useMemo)(()=>({session:N,loading:W,error:E,checkoutMode:tr,inlineSessionDraft:Qt,applyInlineSessionPatch:In?zt:void 0,inlineSessionPatchProcessing:et,claimPending:Br,claimRequiresIdentity:nr,claimBuyerIdentity:tn,waitForDataAttachment:rn}),[N,W,E,tr,Qt,In,zt,et,Br,nr,tn,rn]),ro=!!r&&le==="buttons"&&!ho&&!un&&(!at||!to),jr=Qr?(0,F.jsx)(sn,{status:Qr,errorMessage:Ln,authorized:yn}):null;if(W&&!un){if(p)return(0,F.jsxs)(F.Fragment,{children:[p,jr]});if(le==="buttons"){let q=ge?.buttonsLayout?.cardButton?.borderRadius??ge?.appearance.variables?.borderRadius??8,j=ie=>(0,F.jsx)("div",{style:{height:ie,borderRadius:q,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:[A&&j(Qo),y&&(S||xe)&&j(Qo),y&&j(Qo),(0,F.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),jr]})}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); } }"})]}),jr]})}return E?m?(0,F.jsx)(An.Provider,{value:Ir,children:m(E)}):(0,F.jsx)(An.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:E.message})}):ro?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Ir,children:(0,F.jsx)(du,{onButtonClick:Ye,showPayPal:A,showStripe:y,showApplePay:S,showGooglePay:xe,theme:ye,buttonsTheme:pe,buttonsStyles:Re,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B})}),jr]}):ho&&N&&Yr?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Ir,children:(0,F.jsxs)("div",{className:je,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Nr&&(0,F.jsx)(Ko,{icon:!1,children:Nr}),Xe==="retrying"&&(0,F.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Xe==="exhausted"&&(0,F.jsxs)("div",{role:"alert",children:[(0,F.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,F.jsx)("button",{type:"button",onClick:Vt,children:"Retry PayPal"})]}),Xe!=="exhausted"&&(0,F.jsx)("div",{"aria-hidden":Xe==="retrying"?!0:void 0,style:Xe==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,F.jsx)(Ll,{sessionId:c,nonce:N.clientSecret||void 0,billingApiUrl:D,email:N.customer?.email||Qt?.account?.email,billingName:[N.customer?.firstName,N.customer?.lastName].filter(Boolean).join(" ")||[Qt?.account?.firstName,Qt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:tn,clientId:Yr.clientId,environment:Yr.environment,currency:(N.currency??"usd").toUpperCase(),isSubscription:N.mode==="subscription",providerObjectType:Yr.providerObjectType,approvalPresentation:Yr.approvalPresentation,existingOrderId:Yr.existingOrderId,onComplete:h,onErrorChange:rr,onDecline:I,onCancel:Y,onButtonClick:Ye,runBeforeButtonClick:dn,onInitializationStateChange:Pe,allowAutomaticRetry:Er===0,session:N,telemetry:a,telemetryContext:he,onInstrument:We,debug:T},`${Se}:paypal-init-${Er}`)})]})}),jr]}):tr==="confirm"?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Ir,children:(0,F.jsx)(ba,{flopay:at,paypalFlopay:M,options:to??{billingApiUrl:D},onInstrument:We,children:(0,F.jsxs)("div",{className:je,children:[Nr&&(0,F.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Nr}),De?De({onConfirm:sr,isProcessing:mr}):(0,F.jsx)("button",{type:"button",onClick:sr,disabled:mr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:mr?"not-allowed":"pointer",opacity:mr?.6:1},children:_t?"Processing...":Ve??"Confirm Purchase"})]})},Se)}),jr]}):(!at||!to)&&!(un&&tr==="full")?(0,F.jsx)(F.Fragment,{children:jr}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Ir,children:(0,F.jsxs)(ba,{flopay:at,paypalFlopay:M,options:to??{billingApiUrl:D},onInstrument:We,children:[Ut===1&&(0,F.jsx)("button",{type:"button",onClick:nn,children:"Retry payment methods"}),H?(0,F.jsxs)(F.Fragment,{children:[Nr&&(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:Nr}),(0,F.jsx)(cu,{sessionId:c,nonce:N?.clientSecret||void 0,billingApiUrl:D,session:N,submitLabel:nt,walletPresentation:P,children:H})]}):(0,F.jsx)(bi,{sessionId:c,nonce:N?.clientSecret||void 0,telemetry:a,email:N?.customer?.email||Qt?.account?.email,userId:N?.customer?.id||Qt?.account?.userId,firstName:N?.customer?.firstName||Qt?.account?.firstName,lastName:N?.customer?.lastName||Qt?.account?.lastName,totalAmount:N?Math.round((0,Oe.buildCheckoutDisplayData)(N).total*100):0,currency:N?.currency?.toLowerCase()??"usd",onComplete:h,onError:R,onDecline:I,onCancel:Y,error:Nr,onErrorChange:rr,showPayPal:A,showStripe:y,walletPresentation:P,enabledPaymentMethods:Ut?[]:me??Ae?.data.stripe?.enabledPaymentMethods??N?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ae?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:xe,layout:le,theme:ye,buttonsTheme:pe,buttonsStyles:Re,appearance:pt,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B,onButtonClick:Ye,onBeforeButtonClick:Ne,onBuyerIdentityReady:tn,enableAVS:ue,...ne?{cardFieldOrder:ne}:{},...K?{cardPreFormSlot:K}:{},avsLayout:Le,country:N?.customer?.country,city:N?.customer?.city,state:N?.customer?.state,onCountryChange:_,onZipChange:Z,avsCheck:!!ue,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Ss(H,le),className:je,submitLabel:nt,directPaypal:Yr,isSubscription:N?.mode==="subscription",session:N,dataAttachmentPending:Br,dataAttachmentRequiresIdentity:nr,debug:T})]},Se)}),jr]})}function cu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,children:l}){return(0,F.jsx)(F.Fragment,{children:v.default.Children.map(l,p=>{if(!v.default.isValidElement(p))return p;let m=p.props,h={};return m.sessionId||(h.sessionId=e),!m.nonce&&t&&(h.nonce=t),m.billingApiUrl||(h.billingApiUrl=r),m.submitLabel===void 0&&a!==void 0&&(h.submitLabel=a),m.walletPresentation===void 0&&(h.walletPresentation=s),n?.customer&&(m.email||(h.email=n.customer.email),m.userId||(h.userId=n.customer.id),m.firstName||(h.firstName=n.customer.firstName),m.lastName||(h.lastName=n.customer.lastName)),Object.keys(h).length===0?p:v.default.cloneElement(p,h)})})}function du({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:s,buttonsTheme:l,buttonsStyles:p,cardButtonContent:m,cardBackButtonContent:h,cardTitleContent:R}){let[w,I]=(0,v.useState)(!1),Y=(0,v.useMemo)(()=>(0,Oe.resolveTheme)(s),[s]),_=(0,v.useMemo)(()=>{let P=Y?.buttonsLayout??(0,Oe.resolveButtonsLayoutTheme)(l);return p?{...P,...p,cardButton:{...P.cardButton,...p.cardButton},cardFormContainer:{...P.cardFormContainer,...p.cardFormContainer},backButton:{...P.backButton,...p.backButton},backButtonIcon:{...P.backButtonIcon,...p.backButtonIcon},submitButton:{...P.submitButton,...p.submitButton},title:{...P.title,...p.title}}:P},[Y,l,p]),Z=Y?.buttonsLayout?.cardButton?.borderRadius??Y?.appearance.variables?.borderRadius??8,A=P=>(0,F.jsx)("div",{style:{height:P,borderRadius:Z,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),y=m===void 0?{boxSizing:"border-box",height:Qo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(w){let P=_.cardInputBorder??"#e5e7eb",me=_.cardInputBackground??"white",S=Lo(h),xe=Lo(R);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:S?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)(Uo,{content:h})]}),xe?(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)(ma,{content:R})})]}),(0,F.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsxs)("div",{style:{display:"flex"},children:[(0,F.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,F.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",..._.submitButton,opacity:.5}}),(0,F.jsx)("style",{children:`
|
|
41
41
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
42
|
@keyframes flopay-interim-expand {
|
|
43
43
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
44
|
40% { opacity: 1; }
|
|
45
45
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
46
|
}
|
|
47
|
-
`})]})}return(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&M(ea),r&&(n||a)&&M(ea),r&&(0,F.jsx)("button",{type:"button",onClick:()=>{e?.("card"),R(!0)},style:{width:"100%",...y,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:E.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,...E.cardButton},onMouseDown:g=>{g.currentTarget.style.transform="scale(0.985)"},onMouseUp:g=>{g.currentTarget.style.transform="scale(1)"},children:(0,F.jsx)(Uo,{content:m})}),(0,F.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var bn=require("react/jsx-runtime"),cu=44;function uc(e){return new Promise(t=>setTimeout(t,e))}function du(e,t){return e instanceof Sn.FloPayError?e:new Sn.FloPayError(e instanceof Error?e.message:t,"api_error")}function uu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function pu(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 pc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:s,products:l,items:p,subscriptions:m,account:f,successUrl:S,cancelUrl:C,couponCodes:R,tagsData:H,utmMetadata:E,billingApiUrl:Z,locale:M,theme:y,appearance:g,buttonsTheme:he,buttonsStyles:v,onSuccess:xe,onError:I,onDecline:se,children:Pe,disabled:fe=!1,type:Ae="button",style:st,...Ke}){let B=(0,gt.useMemo)(()=>(0,Sn.resolveBillingApiUrl)(Z),[Z]),St=(0,gt.useMemo)(()=>pu({createSession:r,clientId:s,products:l,items:p,subscriptions:m,account:f,successUrl:S,cancelUrl:C,couponCodes:R,tagsData:H,utmMetadata:E}),[f,C,s,R,r,l,p,m,S,H,E]),[Xe,Ne]=(0,gt.useState)(!1),[me,ee]=(0,gt.useState)(null),[K,Ue]=(0,gt.useState)(null),[tt,qe]=(0,gt.useState)(!1),[Q,G]=(0,gt.useState)(null),[$,q]=(0,gt.useState)(null),Ve=(0,gt.useRef)(!0),Oe=(0,gt.useRef)(null),Ce=(0,gt.useRef)($),O=(0,gt.useRef)(xe),Se=(0,gt.useRef)(I),ut=(0,gt.useRef)(se),ze=(0,gt.useCallback)(P=>ai(Oe,async T=>{try{return await P(T)}catch(Le){throw T.aborted?Yo(Le):Le}}),[]);(0,gt.useEffect)(()=>{Ce.current=$},[$]),(0,gt.useEffect)(()=>{O.current=xe},[xe]),(0,gt.useEffect)(()=>{Se.current=I},[I]),(0,gt.useEffect)(()=>{ut.current=se},[se]),(0,gt.useEffect)(()=>(Ve.current=!0,()=>{Ve.current=!1,Oe.current?.abort()}),[]),(0,gt.useEffect)(()=>{if(typeof window>"u")return;let P=T=>{T.key==="Escape"&&q(null)};return window.addEventListener("keydown",P),()=>{window.removeEventListener("keydown",P)}},[]);let rt=(0,gt.useCallback)((P,T=ka)=>{ut.current?.(_r(T,P,{code:P.code,declineCode:P.declineCode}))},[]),Fe=(0,gt.useCallback)(async P=>{Ve.current&&(Ue(null),qe(P.result.status==="authorized"),ee("success"),await uc(600),Ve.current&&(0,Ze.invokeMerchantCallback)(()=>O.current?.(P)))},[]),et=(0,gt.useCallback)(async(P,T)=>{Ve.current&&(Se.current?.(P),T?.emitDecline&&rt(P,T.method),Ue(P.message),qe(!1),ee("error"),await uc(400))},[rt]),nt=(0,gt.useCallback)(async(P,T,Le)=>{let Ie=P.data.session??null;if(!Ie)throw co(new Sn.FloPayError("No session data returned","api_error"),T);let lt=Ie.clientSecret||t;if(eo(Ie)){await Fe({result:Qn(Ie,T),session:Ie,sessionId:Ie.id||T,autoCompleted:!1});return}if(Ie.status==="expired")throw co(Ga(Ie),Ie.id||T);try{if(P.autoProcessingPending){let We=P.autoProcessingPending,Ge=new Ri.PaymentAPI(B),Dt=await ze(j=>Ge.waitForCheckoutSessionCompletion(We.sessionId,{initialDelayMs:We.retryAfterMs,nonce:lt,statusUrl:We.statusUrl,signal:j})),c=uo(Dt,Ie),L=Dt.autoProcessingError?.type==="3ds_required"&&Dt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Dt.autoProcessingError.nextActionRedirectUrl}:null;if(L&&T&<){let j=await ze(ue=>Xo(L,{billingApiUrl:B,sessionId:T,nonce:lt,session:Ie,signal:ue,telemetry:!0}));await Fe({result:j,session:Ie,sessionId:Ie.id||T,autoCompleted:!1});return}if(Dt.autoProcessingError)throw jn(Dt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Dt.autoProcessingError.checkoutMethod});if(!eo(c))throw jo(c);await Fe({result:Qn(c,T),session:c,sessionId:c.id||T,autoCompleted:!1});return}if(P.autoProcessingError){let We=P.autoProcessingError.nextActionRedirectUrl;if(P.autoProcessingError.type==="3ds_required"&&We&&T&<){let Ge=await ze(j=>Ul({billingApiUrl:B,sessionId:T,nonce:lt,nextActionRedirectUrl:We,signal:j}));if(Ge.status==="declined")throw jn({type:Ge.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ge.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:P.autoProcessingError.checkoutMethod});let c=await new Ri.PaymentAPI(B).waitForCheckoutSessionCompletion(T,{initialDelayMs:0,nonce:lt}),L=uo(c,Ie);if(!eo(L))throw jn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:P.autoProcessingError.checkoutMethod});await Fe({result:Qn(L,T),session:L,sessionId:L.id||T,autoCompleted:!1});return}throw jn(P.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:P.autoProcessingError.checkoutMethod})}if(Le?.fromCreateSession&&P.autoProcessingAttempted===!0)throw jn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ot=await Jo({billingApiUrl:B,sessionId:T??Ie.id,session:Ie,nonce:lt});if(ot.type==="next_action_required"&<){let We=T??Ie.id,Ge=await ze(Dt=>Xo(ot,{billingApiUrl:B,sessionId:We,nonce:lt,session:Ie,signal:Dt,telemetry:!0}));await Fe({result:Ge,session:Ie,sessionId:Ie.id||We,autoCompleted:!1});return}if(ot.type!=="success")throw jn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Fe({result:ot.result,session:Ie,sessionId:Ie.id||T,autoCompleted:!1})}catch(ot){let We=Ie.id||T,Ge=co(Ra(ot),We);if(Ge.code==="three_ds_aborted")return;if(Ge.code==="checkout_processing_timeout"){if(!Ve.current)return;G(Ge.message),(0,Ze.invokeMerchantCallback)(()=>Se.current?.(Ge));return}await et(Ge,{emitDecline:!0,method:Ge.checkoutMethod??ka}),uu(Ge,We)&&We&&Ve.current&&q({sessionId:We,errorMessage:Ge.message,nonce:lt||void 0,payPalOrderId:Ge.orderId})}},[t,B,ze,et,Fe]),cr=(0,gt.useCallback)(async P=>{if(Ke.onClick?.(P),!(P.defaultPrevented||fe||Xe)){if(q(null),G(null),e&&St){let T=new Sn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await et(T),Ve.current&&(ee(null),Ue(null));return}if(!e&&!St){let T=new Sn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await et(T),Ve.current&&(ee(null),Ue(null));return}Ne(!0),Ue(null),qe(!1),ee("processing");try{let T=new Ri.PaymentAPI(B);if(e){let Le=await T.getUnifiedCheckoutSession(e,t);await nt(Le,e);return}try{let Le=await T.createAndFetchSession({...St});await nt(Le,Le.data.session?.id??null,{fromCreateSession:!0})}catch(Le){if(Ya(Le)==="session_auto_completed"){await Fe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Le}}catch(T){await et(co(du(T,"Automatic payment failed. Please try again."),e))}finally{Ve.current&&(ee(null),Ue(null),Ne(!1))}}},[Ke.onClick,St,fe,Xe,t,nt,B,e,et,Fe]),xt=(0,gt.useCallback)(P=>{let T=Ce.current;q(null),O.current?.({result:P,session:null,sessionId:T?.sessionId??null,autoCompleted:!1})},[]),bt=(0,gt.useCallback)(P=>{Se.current?.(P)},[]),Re=(0,gt.useCallback)(P=>{ut.current?.(P)},[]),_=(0,gt.useMemo)(()=>(0,Sn.resolveTheme)(y),[y]),ht=(0,gt.useMemo)(()=>{let P=_?.buttonsLayout??(0,Sn.resolveButtonsLayoutTheme)(he);return v?{...P,...v,cardButton:{...P.cardButton,...v.cardButton}}:P},[_,he,v]),pt=(0,gt.useMemo)(()=>{let P=_?.appearance;return g?P?{...P,...g,variables:{...P.variables,...g.variables}}:g:P},[g,_]),N=pt?.variables,Be=N?.colorPrimary??"#4A49FF",Lt=N?.colorPrimaryHover??(0,hs.darkenHex)(Be,.12),Ee=N?.borderRadius??"8px";return(0,bn.jsxs)(bn.Fragment,{children:[(0,bn.jsx)("button",{...Ke,type:Ae,onClick:cr,disabled:fe||Xe,"aria-busy":Xe,style:{width:"100%",...Pe===void 0?{boxSizing:"border-box",height:cu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...ht.cardButton,...gs({themeBundle:_,resolvedPrimaryColor:Be,resolvedBorderRadius:Ee,submitButtonStyle:ht.submitButton,explicitPrimaryColor:N?.colorPrimary}),fontSize:ht.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:fe||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:fe||Xe?.6:1,...st},onMouseEnter:P=>{Ke.onMouseEnter?.(P),!P.defaultPrevented&&!fe&&!Xe&&(_||N?.colorPrimary)&&(P.currentTarget.style.backgroundColor=Lt)},onMouseLeave:P=>{Ke.onMouseLeave?.(P),!P.defaultPrevented&&(_||N?.colorPrimary)&&(P.currentTarget.style.backgroundColor=Be)},onMouseDown:P=>{Ke.onMouseDown?.(P),P.defaultPrevented||(P.currentTarget.style.transform="scale(0.985)")},onMouseUp:P=>{Ke.onMouseUp?.(P),P.defaultPrevented||(P.currentTarget.style.transform="scale(1)")},children:(0,bn.jsx)(Uo,{content:Pe})}),Q&&(0,bn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Q}),me&&(0,bn.jsx)(nn,{status:me,errorMessage:K,authorized:tt}),$&&(0,bn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:P=>{P.target===P.currentTarget&&q(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,bn.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,bn.jsx)(ki,{sessionId:$.sessionId,nonce:$.nonce,checkoutMode:"full",billingApiUrl:B,locale:M,theme:y,...pt?{appearance:pt}:{},buttonsTheme:he,buttonsStyles:v,initialErrorMessage:$.errorMessage,initialPayPalOrderId:$.payPalOrderId,cardTitleContent:null,onComplete:xt,onError:bt,onDecline:Re})})})]})}var Ii=require("@flopay/js/card-setup"),Hr=require("@flopay/shared"),jt=require("react");var Rs=require("@flopay/shared"),mu=require("@flopay/shared");function Ei(e){let t=(0,Rs.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Wn=require("react/jsx-runtime"),Ba=class extends Hr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function io(e,t={}){let r=e instanceof Hr.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 Ba(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 mc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:l,buttonsStyles:p,loading:m=null,onReady:f,onComplete:S,onDecline:C,onCancel:R,onValidation:H,onError:E}){let[Z,M]=(0,jt.useState)(null),[y,g]=(0,jt.useState)(null),[he,v]=(0,jt.useState)(null),[xe,I]=(0,jt.useState)(null),[se,Pe]=(0,jt.useState)(null),fe=(0,jt.useRef)(!1),Ae=(0,jt.useRef)(!1),{vaultTheme:st,surface:Ke,overlayTheme:B}=(0,jt.useMemo)(()=>Ei({theme:a,appearance:l,buttonsStyles:p}),[a,l,p]),St=(0,jt.useMemo)(()=>(0,_a.mergeCardSetupSurface)(Ke,s),[Ke,s]),Xe=(0,jt.useRef)(f),Ne=(0,jt.useRef)(E),me=(0,jt.useRef)(S),ee=(0,jt.useRef)(C),K=(0,jt.useRef)(R),Ue=(0,jt.useRef)(H),tt=(0,jt.useRef)(!1),qe=(0,jt.useRef)(!1),Q=(0,jt.useRef)(0);return Xe.current=f,Ne.current=E,me.current=S,ee.current=C,K.current=R,Ue.current=H,(0,jt.useEffect)(()=>{let G=Q.current+1;return Q.current=G,()=>{queueMicrotask(()=>{Q.current===G&&(tt.current||qe.current||(qe.current=!0,(0,Ze.invokeMerchantCallback)(()=>{K.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,jt.useEffect)(()=>{let G=!0,$=(0,Hr.resolveBillingApiUrl)(r),q=new Ii.PaymentAPI($,{telemetry:n});return M(null),g(null),v(null),tt.current=!1,qe.current=!1,(async()=>{try{if(!e.trim())throw new Hr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Hr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Ve=await q.getUnifiedCheckoutSession(e,t);if(!G)return;let Oe=Ve.data.session;if(!Oe||!(0,Hr.isCardSetupCheckoutSession)(Oe))throw new Hr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Ce=Oe.vault;(0,Hr.isMountableVaultBlock)(Ce)||(Ce=await q.getVaultCapture(e,t));let O=(0,Hr.resolveVaultMountOptions)(Ce,{billingApiUrl:$,sessionId:e,nonce:t});if(!O)throw new Hr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!G)return;g(O),M(new Ii.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(Ve){if(!G)return;let Oe=io(Ve);tt.current=!0,v(Oe),(0,Ze.invokeMerchantCallback)(()=>Ne.current?.(Oe))}})(),()=>{G=!1,q.destroy()}},[r,t,e,n]),(0,jt.useEffect)(()=>{if(!Z)return;let G=!1;Ae.current=!1,fe.current=!1;let $=Z.on("submitting",()=>{fe.current=!0,Pe(null),I("processing")}),q=Z.on("complete",Ce=>{tt.current=!0,fe.current=!1,I("success"),(async()=>(await new Promise(O=>setTimeout(O,600)),!Ae.current&&(Ae.current=!0,(0,Ze.invokeMerchantCallback)(()=>{me.current?.({status:"succeeded",sessionId:e,...Ce.paymentMethod?{paymentMethod:Ce.paymentMethod}:{}})}),G||I(null))))()}),Ve=Z.on("decline",Ce=>{tt.current=!0,fe.current=!1,Pe(Ce.message??null),I("error"),(0,Ze.invokeMerchantCallback)(()=>{ee.current?.({status:"declined",sessionId:e,...Ce.declineReason?{reason:Ce.declineReason}:{},...Ce.message?{message:Ce.message}:{}})}),(async()=>(await new Promise(O=>setTimeout(O,400)),G||I(null)))()}),Oe=Z.on("challenge_dismissed",()=>{I(null)});return()=>{G=!0,$(),q(),Ve(),Oe()}},[Z,e]),he?(0,Wn.jsx)("div",{role:"alert",children:he.message}):!Z||!y?.html?(0,Wn.jsx)(Wn.Fragment,{children:m}):(0,Wn.jsxs)(Wn.Fragment,{children:[xe&&(0,Wn.jsx)(nn,{status:xe,errorMessage:se,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...B?{theme:B}:{}}),(0,Wn.jsx)(po,{capture:Z,html:y.html,messageToken:y.messageToken,expectedOrigin:y.expectedOrigin,verificationRequired:y.verificationRequired,theme:st,containerStyle:St,onReady:()=>{(0,Ze.invokeMerchantCallback)(()=>Xe.current?.())},onValidation:G=>{(0,Ze.invokeMerchantCallback)(()=>Ue.current?.(G))},onError:G=>{if(!G)return;fe.current&&(fe.current=!1,Pe(G),I("error"),setTimeout(()=>I(null),400));let $=io(new Error(G),{code:"card_setup_widget_failed",retryable:!0});(0,Ze.invokeMerchantCallback)(()=>Ne.current?.($))}})]})}var yc=require("@flopay/js/card-setup"),mo=require("@flopay/shared"),fc=require("@paypal/paypal-js"),Eo=require("react");var hc=require("react/jsx-runtime");function gc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:l,customer:{userId:p,email:m},onSubmitting:f,onConfirmed:S,onFailed:C,onAbandoned:R}){let H=(0,Eo.useRef)(null),E=(0,Eo.useRef)({onSubmitting:f,onConfirmed:S,onFailed:C,onAbandoned:R});E.current={onSubmitting:f,onConfirmed:S,onFailed:C,onAbandoned:R};let[Z]=(0,Eo.useState)(()=>(0,zn.detectPayPalEnvironment)().inAppBrowser);return(0,Eo.useEffect)(()=>{let M=!0,y,g=new yc.PaymentAPI(s,{telemetry:l}),he={userId:p,email:m};return(async()=>{try{let v=await(0,fc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),xe=H.current;if(!M||!xe)return;if(!v?.Buttons)throw new mo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let I=v.Buttons({createVaultSetupToken:async()=>{E.current.onSubmitting();let se=await g.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:mo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(se.provider!=="paypal"||se.providerObjectType!=="setup_token")throw new mo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return se.providerObjectId},onApprove:async se=>{let Pe=se.vaultSetupToken;if(!Pe)throw new mo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let fe=await g.processPayment(he.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:Pe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:mo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:he});if(!fe.ok)throw new mo.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:fe.status});M&&E.current.onConfirmed()},onCancel:()=>{M&&E.current.onAbandoned()},onError:se=>{if(!M)return;let{popupBlocked:Pe}=(0,ke.classifyExternalMethodFailure)(se,{inAppBrowser:Z,handoffObserved:!1});E.current.onFailed(Pe?new Error((0,ke.buildExternalMethodRecoveryMessage)("PayPal",!0,Z)):se,{code:Pe?"popup_blocked":"paypal_setup_failed",retryable:!0})}});y=()=>I.close(),await I.render(xe)}catch(v){if(!M)return;E.current.onFailed(v,{code:"paypal_unavailable",retryable:!0})}})(),()=>{M=!1,y?.().catch(()=>{}),g.destroy()}},[s,e,r,m,t,Z,a,n,l,p]),(0,hc.jsx)("div",{ref:H,"data-flopay-paypal-setup":""})}var vc=require("@flopay/js/card-setup"),yo=require("@flopay/shared"),$n=require("@stripe/react-stripe-js"),Cc=require("@stripe/stripe-js"),Kr=require("react");var zr=require("react/jsx-runtime"),bc={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"}},Es=new Map;function yu(e){let t=Es.get(e);if(t)return t;let r=(0,Cc.loadStripe)(e).catch(n=>{throw Es.delete(e),n});return Es.set(e,r),r}function fu(e){return e?(0,yo.toStripeAppearance)(e):void 0}function gu(e){return(0,ke.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Pc(e){return e==="paypal"?"PayPal":(0,yo.getStripeMethodDisplayName)(e)}function hu(){return typeof window>"u"?"":window.location.href}var Pu={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function Sc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:l}=e,[p]=(0,Kr.useState)(()=>yu(t)),m=(0,Kr.useMemo)(()=>{let f=fu(l),S=(0,yo.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:bc[r]?.types??[r],...S?{setupFutureUsage:S}:{},...f?{appearance:f}:{}}},[l,n,a,s,r]);return(0,zr.jsx)($n.Elements,{stripe:p,options:m,children:(0,zr.jsx)(vu,{...e})})}function vu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:l,themeId:p,buttonsLayout:m,onSubmitting:f,onConfirmed:S,onDeclined:C,onFailed:R,onValidation:H,onUnavailable:E}){let Z=(0,$n.useStripe)(),M=(0,$n.useElements)(),[y,g]=(0,Kr.useState)(!1),[he,v]=(0,Kr.useState)("loading"),[xe,I]=(0,Kr.useState)(!1),[se,Pe]=(0,Kr.useState)(!1),fe=(0,Kr.useRef)(!1),[Ae]=(0,Kr.useState)(()=>(0,zn.detectPayPalEnvironment)()),[st,Ke]=(0,Kr.useState)(!1),B=(0,Kr.useCallback)((K,Ue)=>{if((0,ke.classifyExternalMethodFailure)(K,{inAppBrowser:Ae.inAppBrowser,handoffObserved:!1}).popupBlocked){Ke(!0),R(new Error((0,ke.buildExternalMethodRecoveryMessage)(Pc(e),!0,Ae.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}R(Ue.message===void 0?K:new Error(Ue.message),{code:Ue.code,retryable:!0})},[Ae.inAppBrowser,e,R]),St=(0,Kr.useCallback)(async K=>{let Ue=!1,tt=!1,qe=()=>{!K||Ue||tt||(tt=!0,K.paymentFailed({reason:"fail"}))};if(!Z||!M||fe.current){qe();return}fe.current=!0,g(!0);try{let Q=await M.submit();if(Q.error){qe(),H(Q.error.message??null);return}f();let G=await new vc.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(G.provider!=="stripe"||G.intentKind!=="setup")throw new yo.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Ue=!0;let $=await Z.confirmSetup({elements:M,clientSecret:G.clientSecret,confirmParams:{return_url:hu()},redirect:"if_required"});if($.error){gu($.error)?C({...$.error.decline_code||$.error.code?{reason:$.error.decline_code??$.error.code}:{},...$.error.message?{message:$.error.message}:{}}):B($.error,{code:"payment_method_setup_provider_failed",message:$.error.message??"The payment method could not be saved."});return}S()}catch(Q){qe(),B(Q,{code:"payment_method_setup_failed"})}finally{fe.current=!1,g(!1)}},[a,t,M,e,n,S,C,f,H,B,r,Z,s]),Xe=bc[e]?.wallet,Ne=Xe==="paypal"&&(0,qn.resolveStripePayPalPresentation)(Ae,"auto",st?"blocked":Ae.popupCapability)==="redirect",me=l?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&Xe&&!Ne)return(0,zr.jsxs)(zr.Fragment,{children:[(0,zr.jsx)(Qo,{}),(0,zr.jsx)(Ia,{state:he,borderRadius:me,children:(0,zr.jsx)($n.ExpressCheckoutElement,{options:{...ui,paymentMethods:di([e])},onReady:K=>{let Ue=Ea(K,[Xe]);v(Ue),Ue==="unavailable"&&E()},onLoadError:()=>{v("load_error"),E()},onConfirm:K=>{St(K)}})})]});let ee=Pc(e);return(0,zr.jsxs)(zr.Fragment,{children:[xe?(0,zr.jsx)(ci,{method:e,themeId:p,hasNextStep:!0,highlighted:se,disabled:y,onClick:()=>Pe(K=>!K),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:me}):null,(0,zr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!se,style:se?{display:"flex",flexDirection:"column"}:Pu,children:[(0,zr.jsx)($n.PaymentElement,{options:{layout:pi},onReady:()=>I(!0),onLoadError:()=>E(),onChange:K=>{K.complete&&H(null)}}),(0,zr.jsx)(mi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!Z||!M||y||!se,onClick:()=>{St()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:m?.submitButton,children:y?"Saving\u2026":`Save ${ee}`})]})]})}var Da=require("@flopay/js/card-setup"),Cr=require("@flopay/shared"),Ye=Gi(require("react"),1);var ta=require("@flopay/js/card-setup"),Mr=require("@flopay/shared");var lr=require("react/jsx-runtime"),Cu=15,bu=2e3;function Su(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Is(e){return new Promise(t=>setTimeout(t,e))}async function wu(e,t,r){if(!t.trim())throw new Cr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Cr.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,Cr.isCardSetupCheckoutSession)(a))throw new Cr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Mr.readSetupAdvertisement)(n);if(!(0,Mr.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:l}=s,p=l.length>0?`FloPay: this setup session advertises only Stripe methods (${l.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new Cr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function ku(e,t,r,n,a){let s=t.vault??null;(0,Cr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let l=(0,Cr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!l)throw new Cr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return l}var _i=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 wc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:l="modern-light",containerStyle:p,appearance:m,buttonsStyles:f,loading:S=null,onReady:C,onComplete:R,onDecline:H,onCancel:E,onValidation:Z,onError:M}){let[y]=(0,Ye.useState)(ta.readSetupRedirectReturn),[g,he]=(0,Ye.useState)(null),[v,xe]=(0,Ye.useState)(!1),[I,se]=(0,Ye.useState)(null),[Pe,fe]=(0,Ye.useState)(null),[Ae,st]=(0,Ye.useState)(null),[Ke,B]=(0,Ye.useState)(null),[St,Xe]=(0,Ye.useState)(()=>new Set),Ne=(0,Ye.useRef)(St),me=(0,Ye.useRef)(null);me.current=g;let ee=(0,Ye.useRef)(!1),K=(0,Ye.useRef)(!1),Ue=(0,Ye.useRef)(!1),tt=(0,Ye.useRef)(!1),qe=(0,Ye.useRef)(0),Q=(0,Ye.useRef)(0),G=(0,Ye.useRef)(!1),{vaultTheme:$,surface:q,overlayTheme:Ve,appearance:Oe,buttonsLayout:Ce}=(0,Ye.useMemo)(()=>Ei({theme:l,appearance:m,buttonsStyles:f}),[l,m,f]),O=(0,Ye.useMemo)(()=>(0,_a.mergeCardSetupSurface)(q,p),[q,p]),Se=(0,Ye.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:C,onComplete:R,onDecline:H,onCancel:E,onValidation:Z,onError:M});Se.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:C,onComplete:R,onDecline:H,onCancel:E,onValidation:Z,onError:M},(0,Ye.useEffect)(()=>{G.current=!0;let c=qe.current+1;return qe.current=c,()=>{G.current=!1,Q.current+=1,queueMicrotask(()=>{qe.current===c&&(Ue.current||tt.current||(tt.current=!0,(0,Ze.invokeMerchantCallback)(()=>{Se.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let ut=(0,Ye.useCallback)((c,L)=>{Ue.current=!0,ee.current=!1,B({status:"success",wording:c,message:null}),(async()=>(await Is(600),!K.current&&(K.current=!0,(0,Ze.invokeMerchantCallback)(()=>{Se.current.onComplete?.({status:"succeeded",sessionId:Se.current.sessionId,...L?{paymentMethod:L}:{}})}),G.current&&B(null))))()},[]),ze=(0,Ye.useCallback)((c,L)=>{Ue.current=!0,ee.current=!1,B({status:"error",wording:c,message:L.message??null}),(0,Ze.invokeMerchantCallback)(()=>{Se.current.onDecline?.({status:"declined",sessionId:Se.current.sessionId,...L.reason?{reason:L.reason}:{},...L.message?{message:L.message}:{}})}),(async()=>(await Is(400),G.current&&B(null)))()},[]),rt=(0,Ye.useCallback)((c,L)=>{ee.current?(ee.current=!1,B({status:"error",wording:c,message:L.message}),setTimeout(()=>{G.current&&B(null)},400)):B(null),(0,Ze.invokeMerchantCallback)(()=>Se.current.onError?.(L))},[]),Fe=(0,Ye.useCallback)(async c=>{let L=Q.current+1;Q.current=L;let j=()=>!G.current||L!==Q.current;ee.current=!0,B({status:"processing",wording:"payment_method",message:null});let ue=new Da.PaymentAPI((0,Cr.resolveBillingApiUrl)(Se.current.billingApiUrl),{telemetry:Se.current.telemetry});try{for(let k=0;k<Cu;k+=1){if((k>0||c.waitFirst)&&await Is(bu),j())return;let V=await ue.getUnifiedCheckoutSession(Se.current.sessionId,Se.current.nonce);if(j())return;let Ut=V.data.session?.status;if(Ut==="complete"){xe(!0),ut("payment_method");return}if(Ut==="expired")throw new Cr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Cr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(k){if(j())return;let V=k instanceof Cr.FloPayError&&k.code==="payment_method_setup_unverified";rt("payment_method",io(k,V?{retryable:!0}:{}))}finally{ue.destroy()}},[rt,ut]);(0,Ye.useEffect)(()=>{let c=!0,L=(0,Cr.resolveBillingApiUrl)(a),j=new Da.PaymentAPI(L,{telemetry:s});he(null),xe(!1),se(null),fe(null),st(null);let ue=new Set;return Ne.current=ue,Xe(ue),Ue.current=!1,tt.current=!1,K.current=!1,(async()=>{try{let{session:k,advertisement:V}=await wu(j,r,n);if(!c)return;let Ut={advertisement:V,customer:Su(k),...k.futureUse?{futureUse:k.futureUse}:{},...k.futureUseUnsupported?{futureUseUnsupported:k.futureUseUnsupported}:{}};if(y){if((0,ta.clearSetupRedirectParams)(),k.status==="complete"){xe(!0),he(Ut),ut("payment_method");return}y.failed?ze("payment_method",{reason:"redirect_failed"}):Fe({waitFirst:!0})}let Br=V.card?await ku(j,k,r,n,L):null;if(!c)return;he(Ut),Br&&(fe(Br),se(new Da.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(k){if(!c)return;let V=io(k);Ue.current=!0,st(V),(0,Ze.invokeMerchantCallback)(()=>Se.current.onError?.(V))}})(),()=>{c=!1,j.destroy()}},[a,n,y,ze,ut,r,s,Fe]),(0,Ye.useEffect)(()=>{if(!I)return;ee.current=!1;let c=I.on("submitting",()=>{ee.current=!0,B({status:"processing",wording:"card",message:null})}),L=I.on("complete",k=>{ut("card",k.paymentMethod)}),j=I.on("decline",k=>{ze("card",{...k.declineReason?{reason:k.declineReason}:{},...k.message?{message:k.message}:{}})}),ue=I.on("challenge_dismissed",()=>{B(null)});return()=>{c(),L(),j(),ue()}},[I,ze,ut]);let et=(0,Ye.useCallback)((c,L,j)=>{if(j.retryable){rt("payment_method",io(L,j));return}if(Ne.current.has(c))return;let ue=new Set(Ne.current);ue.add(c),Ne.current=ue,Xe(ue);let k=me.current?.advertisement,V=k?(0,Mr.advertisedMethodKeys)(k).some(Ut=>!ue.has(Ut)):!1;rt("payment_method",io(L,{code:j.code,retryable:V}))},[rt]),nt=(0,Ye.useMemo)(()=>({onSubmitting:()=>{ee.current=!0,B({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Fe({waitFirst:!1})},onDeclined:c=>ze("payment_method",c),onValidation:c=>{(0,Ze.invokeMerchantCallback)(()=>Se.current.onValidation?.(c))},onAbandoned:()=>{ee.current=!1,B(null)}}),[ze,Fe]),cr=(0,Ye.useRef)(et);cr.current=et;let xt=(0,Ye.useRef)(new Map),bt=c=>{let L=xt.current.get(c);if(L)return L;let j=(ue,k)=>cr.current(c,ue,k);return xt.current.set(c,j),j},Re=(0,Ye.useCallback)(c=>{if(Ne.current.has(c))return;let L=new Set(Ne.current);L.add(c),Ne.current=L,Xe(L);let j=me.current?.advertisement;j&&(0,Mr.advertisedMethodKeys)(j).some(k=>!L.has(k))||rt("payment_method",io(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[rt]),_=(0,Ye.useRef)(Re);_.current=Re;let ht=(0,Ye.useRef)(new Map),pt=c=>{let L=ht.current.get(c);if(L)return L;let j=()=>_.current(c);return ht.current.set(c,j),j},N=Ke?(0,lr.jsx)(nn,{status:Ke.status,errorMessage:Ke.message,...(0,Mr.setupOverlayLabels)(Ke.wording),successNote:null,...Ve?{theme:Ve}:{}}):null;if(Ae)return(0,lr.jsx)("div",{role:"alert",children:Ae.message});if(!g||v)return(0,lr.jsxs)(lr.Fragment,{children:[N,g?null:S]});let{advertisement:Be,customer:Lt,futureUse:Ee,futureUseUnsupported:It}=g,P=(0,Cr.resolveBillingApiUrl)(a),T=s===void 0?{}:{telemetry:s},Le=Be.stripe.filter(({method:c})=>!St.has(c)),Ie=St.has("paypal")?null:Be.paypal,lt=!!(Be.card&&I&&Pe?.html),ot=({method:c,publishableKey:L,currency:j})=>(0,lr.jsx)("div",{"data-flopay-payment-method":c,style:{display:"contents"},children:(0,lr.jsx)(_i,{onFailed:bt(c),children:(0,lr.jsx)(Ye.Suspense,{fallback:null,children:(0,lr.jsx)(e,{method:c,category:(0,Mr.stripeMethodCategory)(c),publishableKey:L,currency:j,...Ee?{futureUse:Ee}:{},...It?{futureUseUnsupported:It}:{},sessionId:r,nonce:n,billingApiUrl:P,...T,...Oe?{appearance:Oe}:{},...Ce?{buttonsLayout:Ce}:{},...typeof l=="string"?{themeId:l}:{},...nt,onFailed:bt(c),onUnavailable:pt(c)})})})},c),We=Le.filter(({method:c})=>(0,Mr.stripeMethodCategory)(c)==="wallet"),Ge=Le.filter(({method:c})=>(0,Mr.stripeMethodCategory)(c)!=="wallet"),Dt=Le.length>0||Ie!==null;return(0,lr.jsxs)(lr.Fragment,{children:[N,Dt?(0,lr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[We.map(ot),Ie?(0,lr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,lr.jsx)(_i,{onFailed:bt("paypal"),children:(0,lr.jsx)(Ye.Suspense,{fallback:null,children:(0,lr.jsx)(t,{clientId:Ie.clientId,...Ie.environment?{environment:Ie.environment}:{},...Be.currency?{currency:Be.currency}:{},sessionId:r,nonce:n,billingApiUrl:P,customer:Lt,...T,...nt,onFailed:bt("paypal"),onUnavailable:pt("paypal")})})})}):null,Ge.map(ot)]}):null,lt&&Dt?(0,lr.jsx)(yi,{label:"or add a card"}):null,lt&&I&&Pe?.html?(0,lr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,lr.jsx)(po,{capture:I,html:Pe.html,messageToken:Pe.messageToken,expectedOrigin:Pe.expectedOrigin,verificationRequired:Pe.verificationRequired,theme:$,containerStyle:O,onReady:()=>{(0,Ze.invokeMerchantCallback)(()=>Se.current.onReady?.())},onValidation:c=>{(0,Ze.invokeMerchantCallback)(()=>Se.current.onValidation?.(c))},onError:c=>{c&&rt("card",io(new Error(c),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Rc=require("react/jsx-runtime"),Ru={StripeSetupMethod:Sc,PayPalSetupMethod:gc};function kc(e){return(0,Rc.jsx)(wc,{...e,branches:Ru})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&A(Qo),r&&(n||a)&&A(Qo),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:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,F.jsx)(No,{content:m})}),(0,F.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var wn=require("react/jsx-runtime"),uu=44;function yc(e){return new Promise(t=>setTimeout(t,e))}function pu(e,t){return e instanceof kn.FloPayError?e:new kn.FloPayError(e instanceof Error?e.message:t,"api_error")}function mu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function yu(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 fc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:s,products:l,items:p,subscriptions:m,account:h,successUrl:R,cancelUrl:w,couponCodes:I,tagsData:Y,utmMetadata:_,billingApiUrl:Z,locale:A,theme:y,appearance:P,buttonsTheme:me,buttonsStyles:S,onSuccess:xe,onError:T,onDecline:le,children:ye,disabled:pe=!1,type:Re="button",style:lt,...$e}){let B=(0,ft.useMemo)(()=>(0,kn.resolveBillingApiUrl)(Z),[Z]),wt=(0,ft.useMemo)(()=>yu({createSession:r,clientId:s,products:l,items:p,subscriptions:m,account:h,successUrl:R,cancelUrl:w,couponCodes:I,tagsData:Y,utmMetadata:_}),[h,w,s,I,r,l,p,m,R,Y,_]),[Ye,Ne]=(0,ft.useState)(!1),[ue,ne]=(0,ft.useState)(null),[K,Le]=(0,ft.useState)(null),[nt,je]=(0,ft.useState)(!1),[X,$]=(0,ft.useState)(null),[H,V]=(0,ft.useState)(null),Ve=(0,ft.useRef)(!0),De=(0,ft.useRef)(null),fe=(0,ft.useRef)(H),D=(0,ft.useRef)(xe),ge=(0,ft.useRef)(T),pt=(0,ft.useRef)(le),Ue=(0,ft.useCallback)(b=>ii(De,async x=>{try{return await b(x)}catch(Be){throw x.aborted?Go(Be):Be}}),[]);(0,ft.useEffect)(()=>{fe.current=H},[H]),(0,ft.useEffect)(()=>{D.current=xe},[xe]),(0,ft.useEffect)(()=>{ge.current=T},[T]),(0,ft.useEffect)(()=>{pt.current=le},[le]),(0,ft.useEffect)(()=>(Ve.current=!0,()=>{Ve.current=!1,De.current?.abort()}),[]),(0,ft.useEffect)(()=>{if(typeof window>"u")return;let b=x=>{x.key==="Escape"&&V(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let ot=(0,ft.useCallback)((b,x=wa)=>{pt.current?.(Sr(x,b,{code:b.code,declineCode:b.declineCode}))},[]),Ae=(0,ft.useCallback)(async b=>{Ve.current&&(Le(null),je(b.result.status==="authorized"),ne("success"),await yc(600),Ve.current&&(0,Ke.invokeMerchantCallback)(()=>D.current?.(b)))},[]),Qe=(0,ft.useCallback)(async(b,x)=>{Ve.current&&(ge.current?.(b),x?.emitDecline&&ot(b,x.method),Le(b.message),je(!1),ne("error"),await yc(400))},[ot]),at=(0,ft.useCallback)(async(b,x,Be)=>{let Ee=b.data.session??null;if(!Ee)throw yo(new kn.FloPayError("No session data returned","api_error"),x);let dt=Ee.clientSecret||t;if(oo(Ee)){await Ae({result:no(Ee,x),session:Ee,sessionId:Ee.id||x,autoCompleted:!1});return}if(Ee.status==="expired")throw yo(Ya(Ee),Ee.id||x);try{if(b.autoProcessingPending){let We=b.autoProcessingPending,He=new Ei.PaymentAPI(B),Dt=await Ue(W=>He.waitForCheckoutSessionCompletion(We.sessionId,{initialDelayMs:We.retryAfterMs,nonce:dt,statusUrl:We.statusUrl,signal:W})),c=fo(Dt,Ee),U=Dt.autoProcessingError?.type==="3ds_required"&&Dt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Dt.autoProcessingError.nextActionRedirectUrl}:null;if(U&&x&&dt){let W=await Ue(ce=>Yo(U,{billingApiUrl:B,sessionId:x,nonce:dt,session:Ee,signal:ce,telemetry:!0}));await Ae({result:W,session:Ee,sessionId:Ee.id||x,autoCompleted:!1});return}if(Dt.autoProcessingError)throw Kn(Dt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Dt.autoProcessingError.checkoutMethod});if(!oo(c))throw qo(c);await Ae({result:no(c,x),session:c,sessionId:c.id||x,autoCompleted:!1});return}if(b.autoProcessingError){let We=b.autoProcessingError.nextActionRedirectUrl;if(b.autoProcessingError.type==="3ds_required"&&We&&x&&dt){let He=await Ue(W=>jl({billingApiUrl:B,sessionId:x,nonce:dt,nextActionRedirectUrl:We,signal:W}));if(He.status==="declined")throw Kn({type:He.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:He.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let c=await new Ei.PaymentAPI(B).waitForCheckoutSessionCompletion(x,{initialDelayMs:0,nonce:dt}),U=fo(c,Ee);if(!oo(U))throw Kn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await Ae({result:no(U,x),session:U,sessionId:U.id||x,autoCompleted:!1});return}throw Kn(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(Be?.fromCreateSession&&b.autoProcessingAttempted===!0)throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let it=await Xo({billingApiUrl:B,sessionId:x??Ee.id,session:Ee,nonce:dt});if(it.type==="next_action_required"&&dt){let We=x??Ee.id,He=await Ue(Dt=>Yo(it,{billingApiUrl:B,sessionId:We,nonce:dt,session:Ee,signal:Dt,telemetry:!0}));await Ae({result:He,session:Ee,sessionId:Ee.id||We,autoCompleted:!1});return}if(it.type!=="success")throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ae({result:it.result,session:Ee,sessionId:Ee.id||x,autoCompleted:!1})}catch(it){let We=Ee.id||x,He=yo(ka(it),We);if(He.code==="three_ds_aborted")return;if(He.code==="checkout_processing_timeout"){if(!Ve.current)return;$(He.message),(0,Ke.invokeMerchantCallback)(()=>ge.current?.(He));return}await Qe(He,{emitDecline:!0,method:He.checkoutMethod??wa}),mu(He,We)&&We&&Ve.current&&V({sessionId:We,errorMessage:He.message,nonce:dt||void 0,payPalOrderId:He.orderId})}},[t,B,Ue,Qe,Ae]),pr=(0,ft.useCallback)(async b=>{if($e.onClick?.(b),!(b.defaultPrevented||pe||Ye)){if(V(null),$(null),e&&wt){let x=new kn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Qe(x),Ve.current&&(ne(null),Le(null));return}if(!e&&!wt){let x=new kn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Qe(x),Ve.current&&(ne(null),Le(null));return}Ne(!0),Le(null),je(!1),ne("processing");try{let x=new Ei.PaymentAPI(B);if(e){let Be=await x.getUnifiedCheckoutSession(e,t);await at(Be,e);return}try{let Be=await x.createAndFetchSession({...wt});await at(Be,Be.data.session?.id??null,{fromCreateSession:!0})}catch(Be){if(Xa(Be)==="session_auto_completed"){await Ae({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Be}}catch(x){await Qe(yo(pu(x,"Automatic payment failed. Please try again."),e))}finally{Ve.current&&(ne(null),Le(null),Ne(!1))}}},[$e.onClick,wt,pe,Ye,t,at,B,e,Qe,Ae]),Mt=(0,ft.useCallback)(b=>{let x=fe.current;V(null),D.current?.({result:b,session:null,sessionId:x?.sessionId??null,autoCompleted:!1})},[]),vt=(0,ft.useCallback)(b=>{ge.current?.(b)},[]),be=(0,ft.useCallback)(b=>{pt.current?.(b)},[]),M=(0,ft.useMemo)(()=>(0,kn.resolveTheme)(y),[y]),gt=(0,ft.useMemo)(()=>{let b=M?.buttonsLayout??(0,kn.resolveButtonsLayoutTheme)(me);return S?{...b,...S,cardButton:{...b.cardButton,...S.cardButton}}:b},[M,me,S]),ct=(0,ft.useMemo)(()=>{let b=M?.appearance;return P?b?{...b,...P,variables:{...b.variables,...P.variables}}:P:b},[P,M]),N=ct?.variables,Fe=N?.colorPrimary??"#4A49FF",Lt=N?.colorPrimaryHover??(0,hs.darkenHex)(Fe,.12),Se=N?.borderRadius??"8px";return(0,wn.jsxs)(wn.Fragment,{children:[(0,wn.jsx)("button",{...$e,type:Re,onClick:pr,disabled:pe||Ye,"aria-busy":Ye,style:{width:"100%",...ye===void 0?{boxSizing:"border-box",height:uu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...gt.cardButton,...gs({themeBundle:M,resolvedPrimaryColor:Fe,resolvedBorderRadius:Se,submitButtonStyle:gt.submitButton,explicitPrimaryColor:N?.colorPrimary}),fontSize:gt.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,...lt},onMouseEnter:b=>{$e.onMouseEnter?.(b),!b.defaultPrevented&&!pe&&!Ye&&(M||N?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Lt)},onMouseLeave:b=>{$e.onMouseLeave?.(b),!b.defaultPrevented&&(M||N?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Fe)},onMouseDown:b=>{$e.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{$e.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:(0,wn.jsx)(No,{content:ye})}),X&&(0,wn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:X}),ue&&(0,wn.jsx)(sn,{status:ue,errorMessage:K,authorized:nt}),H&&(0,wn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:b=>{b.target===b.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,wn.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,wn.jsx)(Ri,{sessionId:H.sessionId,nonce:H.nonce,checkoutMode:"full",billingApiUrl:B,locale:A,theme:y,...ct?{appearance:ct}:{},buttonsTheme:me,buttonsStyles:S,initialErrorMessage:H.errorMessage,initialPayPalOrderId:H.payPalOrderId,cardTitleContent:null,onComplete:Mt,onError:vt,onDecline:be})})})]})}var _i=require("@flopay/js/card-setup"),Jr=require("@flopay/shared"),jt=require("react");var Rs=require("@flopay/shared"),fu=require("@flopay/shared");function Ii(e){let t=(0,Rs.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Yn=require("react/jsx-runtime"),Fa=class extends Jr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function uo(e,t={}){let r=e instanceof Jr.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 Fa(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 gc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:l,buttonsStyles:p,loading:m=null,onReady:h,onComplete:R,onDecline:w,onCancel:I,onValidation:Y,onError:_}){let[Z,A]=(0,jt.useState)(null),[y,P]=(0,jt.useState)(null),[me,S]=(0,jt.useState)(null),[xe,T]=(0,jt.useState)(null),[le,ye]=(0,jt.useState)(null),pe=(0,jt.useRef)(!1),Re=(0,jt.useRef)(!1),{vaultTheme:lt,surface:$e,overlayTheme:B}=(0,jt.useMemo)(()=>Ii({theme:a,appearance:l,buttonsStyles:p}),[a,l,p]),wt=(0,jt.useMemo)(()=>(0,Ia.mergeCardSetupSurface)($e,s),[$e,s]),Ye=(0,jt.useRef)(h),Ne=(0,jt.useRef)(_),ue=(0,jt.useRef)(R),ne=(0,jt.useRef)(w),K=(0,jt.useRef)(I),Le=(0,jt.useRef)(Y),nt=(0,jt.useRef)(!1),je=(0,jt.useRef)(!1),X=(0,jt.useRef)(0);return Ye.current=h,Ne.current=_,ue.current=R,ne.current=w,K.current=I,Le.current=Y,(0,jt.useEffect)(()=>{let $=X.current+1;return X.current=$,()=>{queueMicrotask(()=>{X.current===$&&(nt.current||je.current||(je.current=!0,(0,Ke.invokeMerchantCallback)(()=>{K.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,jt.useEffect)(()=>{let $=!0,H=(0,Jr.resolveBillingApiUrl)(r),V=new _i.PaymentAPI(H,{telemetry:n});return A(null),P(null),S(null),nt.current=!1,je.current=!1,(async()=>{try{if(!e.trim())throw new Jr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Jr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Ve=await V.getUnifiedCheckoutSession(e,t);if(!$)return;let De=Ve.data.session;if(!De||!(0,Jr.isCardSetupCheckoutSession)(De))throw new Jr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let fe=De.vault;(0,Jr.isMountableVaultBlock)(fe)||(fe=await V.getVaultCapture(e,t));let D=(0,Jr.resolveVaultMountOptions)(fe,{billingApiUrl:H,sessionId:e,nonce:t});if(!D)throw new Jr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!$)return;P(D),A(new _i.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(Ve){if(!$)return;let De=uo(Ve);nt.current=!0,S(De),(0,Ke.invokeMerchantCallback)(()=>Ne.current?.(De))}})(),()=>{$=!1,V.destroy()}},[r,t,e,n]),(0,jt.useEffect)(()=>{if(!Z)return;let $=!1;Re.current=!1,pe.current=!1;let H=Z.on("submitting",()=>{pe.current=!0,ye(null),T("processing")}),V=Z.on("complete",fe=>{nt.current=!0,pe.current=!1,T("success"),(async()=>(await new Promise(D=>setTimeout(D,600)),!Re.current&&(Re.current=!0,(0,Ke.invokeMerchantCallback)(()=>{ue.current?.({status:"succeeded",sessionId:e,...fe.paymentMethod?{paymentMethod:fe.paymentMethod}:{}})}),$||T(null))))()}),Ve=Z.on("decline",fe=>{nt.current=!0,pe.current=!1,ye(fe.message??null),T("error"),(0,Ke.invokeMerchantCallback)(()=>{ne.current?.({status:"declined",sessionId:e,...fe.declineReason?{reason:fe.declineReason}:{},...fe.message?{message:fe.message}:{}})}),(async()=>(await new Promise(D=>setTimeout(D,400)),$||T(null)))()}),De=Z.on("challenge_dismissed",()=>{T(null)});return()=>{$=!0,H(),V(),Ve(),De()}},[Z,e]),me?(0,Yn.jsx)("div",{role:"alert",children:me.message}):!Z||!y?.html?(0,Yn.jsx)(Yn.Fragment,{children:m}):(0,Yn.jsxs)(Yn.Fragment,{children:[xe&&(0,Yn.jsx)(sn,{status:xe,errorMessage:le,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...B?{theme:B}:{}}),(0,Yn.jsx)(go,{capture:Z,html:y.html,messageToken:y.messageToken,expectedOrigin:y.expectedOrigin,verificationRequired:y.verificationRequired,theme:lt,containerStyle:wt,onReady:()=>{(0,Ke.invokeMerchantCallback)(()=>Ye.current?.())},onValidation:$=>{(0,Ke.invokeMerchantCallback)(()=>Le.current?.($))},onError:$=>{if(!$)return;pe.current&&(pe.current=!1,ye($),T("error"),setTimeout(()=>T(null),400));let H=uo(new Error($),{code:"card_setup_widget_failed",retryable:!0});(0,Ke.invokeMerchantCallback)(()=>Ne.current?.(H))}})]})}var hc=require("@flopay/js/card-setup"),Rn=require("@flopay/shared"),Pc=require("@paypal/paypal-js"),Io=require("react");var Cc=require("react/jsx-runtime");function vc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:l,customer:{userId:p,email:m},onSubmitting:h,onConfirmed:R,onFailed:w,onAbandoned:I}){let Y=(0,Io.useRef)(null),_=(0,Io.useRef)({onSubmitting:h,onConfirmed:R,onFailed:w,onAbandoned:I});_.current={onSubmitting:h,onConfirmed:R,onFailed:w,onAbandoned:I};let[Z]=(0,Io.useState)(()=>(0,$n.detectPayPalEnvironment)().inAppBrowser);return(0,Io.useEffect)(()=>{let A=!0,y,P=new hc.PaymentAPI(s,{telemetry:l}),me={userId:p,email:m};return(async()=>{try{let S=await(0,Pc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),xe=Y.current;if(!A||!xe)return;if(!S?.Buttons)throw new Rn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let T=S.Buttons({createVaultSetupToken:async()=>{_.current.onSubmitting();let le=await P.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Rn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,Rn.isSettledSessionIntent)(le))throw(0,Rn.settledSessionIntentError)(n);if(le.provider!=="paypal"||le.providerObjectType!=="setup_token")throw new Rn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return le.providerObjectId},onApprove:async le=>{let ye=le.vaultSetupToken;if(!ye)throw new Rn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let pe=await P.processPayment(me.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:ye,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Rn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:me});if(!pe.ok)throw new Rn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:pe.status});A&&_.current.onConfirmed()},onCancel:()=>{A&&_.current.onAbandoned()},onError:le=>{if(!A)return;let{popupBlocked:ye}=(0,ke.classifyExternalMethodFailure)(le,{inAppBrowser:Z,handoffObserved:!1});_.current.onFailed(ye?new Error((0,ke.buildExternalMethodRecoveryMessage)("PayPal",!0,Z)):le,{code:ye?"popup_blocked":"paypal_setup_failed",retryable:!0})}});y=()=>T.close(),await T.render(xe)}catch(S){if(!A)return;_.current.onFailed(S,{code:"paypal_unavailable",retryable:!0})}})(),()=>{A=!1,y?.().catch(()=>{}),P.destroy()}},[s,e,r,m,t,Z,a,n,l,p]),(0,Cc.jsx)("div",{ref:Y,"data-flopay-paypal-setup":""})}var Sc=require("@flopay/js/card-setup"),En=require("@flopay/shared"),Xn=require("@stripe/react-stripe-js"),wc=require("@stripe/stripe-js"),Zr=require("react");var Wr=require("react/jsx-runtime"),kc={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"}},Es=new Map;function gu(e){let t=Es.get(e);if(t)return t;let r=(0,wc.loadStripe)(e).catch(n=>{throw Es.delete(e),n});return Es.set(e,r),r}function hu(e){return e?(0,En.toStripeAppearance)(e):void 0}function Pu(e){return(0,ke.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function bc(e){return e==="paypal"?"PayPal":(0,En.getStripeMethodDisplayName)(e)}function vu(){return typeof window>"u"?"":window.location.href}var Cu={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function Rc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:l}=e,[p]=(0,Zr.useState)(()=>gu(t)),m=(0,Zr.useMemo)(()=>{let h=hu(l),R=(0,En.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:kc[r]?.types??[r],...R?{setupFutureUsage:R}:{},...h?{appearance:h}:{}}},[l,n,a,s,r]);return(0,Wr.jsx)(Xn.Elements,{stripe:p,options:m,children:(0,Wr.jsx)(bu,{...e})})}function bu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:l,themeId:p,buttonsLayout:m,onSubmitting:h,onConfirmed:R,onDeclined:w,onFailed:I,onValidation:Y,onUnavailable:_}){let Z=(0,Xn.useStripe)(),A=(0,Xn.useElements)(),[y,P]=(0,Zr.useState)(!1),[me,S]=(0,Zr.useState)("loading"),[xe,T]=(0,Zr.useState)(!1),[le,ye]=(0,Zr.useState)(!1),pe=(0,Zr.useRef)(!1),[Re]=(0,Zr.useState)(()=>(0,$n.detectPayPalEnvironment)()),[lt,$e]=(0,Zr.useState)(!1),B=(0,Zr.useCallback)((K,Le)=>{if((0,ke.classifyExternalMethodFailure)(K,{inAppBrowser:Re.inAppBrowser,handoffObserved:!1}).popupBlocked){$e(!0),I(new Error((0,ke.buildExternalMethodRecoveryMessage)(bc(e),!0,Re.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}I(Le.message===void 0?K:new Error(Le.message),{code:Le.code,retryable:!0})},[Re.inAppBrowser,e,I]),wt=(0,Zr.useCallback)(async K=>{let Le=!1,nt=!1,je=()=>{!K||Le||nt||(nt=!0,K.paymentFailed({reason:"fail"}))};if(!Z||!A||pe.current){je();return}pe.current=!0,P(!0);try{let X=await A.submit();if(X.error){je(),Y(X.error.message??null);return}h();let $=await new Sc.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,En.isSettledSessionIntent)($))throw(0,En.settledSessionIntentError)(r);if($.provider!=="stripe"||$.intentKind!=="setup")throw new En.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Le=!0;let H=await Z.confirmSetup({elements:A,clientSecret:$.clientSecret,confirmParams:{return_url:vu()},redirect:"if_required"});if(H.error){Pu(H.error)?w({...H.error.decline_code||H.error.code?{reason:H.error.decline_code??H.error.code}:{},...H.error.message?{message:H.error.message}:{}}):B(H.error,{code:"payment_method_setup_provider_failed",message:H.error.message??"The payment method could not be saved."});return}R()}catch(X){je(),B(X,{code:"payment_method_setup_failed"})}finally{pe.current=!1,P(!1)}},[a,t,A,e,n,R,w,h,Y,B,r,Z,s]),Ye=kc[e]?.wallet,Ne=Ye==="paypal"&&(0,Hn.resolveStripePayPalPresentation)(Re,"auto",lt?"blocked":Re.popupCapability)==="redirect",ue=l?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&Ye&&!Ne)return(0,Wr.jsxs)(Wr.Fragment,{children:[(0,Wr.jsx)(Zo,{}),(0,Wr.jsx)(Ea,{state:me,borderRadius:ue,children:(0,Wr.jsx)(Xn.ExpressCheckoutElement,{options:{...pi,paymentMethods:ui([e])},onReady:K=>{let Le=Ra(K,[Ye]);S(Le),Le==="unavailable"&&_()},onLoadError:()=>{S("load_error"),_()},onConfirm:K=>{wt(K)}})})]});let ne=bc(e);return(0,Wr.jsxs)(Wr.Fragment,{children:[xe?(0,Wr.jsx)(di,{method:e,themeId:p,hasNextStep:!0,highlighted:le,disabled:y,onClick:()=>ye(K=>!K),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:ue}):null,(0,Wr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!le,style:le?{display:"flex",flexDirection:"column"}:Cu,children:[(0,Wr.jsx)(Xn.PaymentElement,{options:{layout:mi},onReady:()=>T(!0),onLoadError:()=>_(),onChange:K=>{K.complete&&Y(null)}}),(0,Wr.jsx)(yi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!Z||!A||y||!le,onClick:()=>{wt()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:m?.submitButton,children:y?"Saving\u2026":`Save ${ne}`})]})]})}var Ba=require("@flopay/js/card-setup"),kr=require("@flopay/shared"),Ge=Gi(require("react"),1);var ea=require("@flopay/js/card-setup"),Ar=require("@flopay/shared");var ur=require("react/jsx-runtime"),Su=15,wu=2e3;function ku(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Is(e){return new Promise(t=>setTimeout(t,e))}async function Ru(e,t,r){if(!t.trim())throw new kr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new kr.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,kr.isCardSetupCheckoutSession)(a))throw new kr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Ar.readSetupAdvertisement)(n);if(!(0,Ar.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:l}=s,p=l.length>0?`FloPay: this setup session advertises only Stripe methods (${l.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new kr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function Eu(e,t,r,n,a){let s=t.vault??null;(0,kr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let l=(0,kr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!l)throw new kr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return l}var Ti=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 Ec({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:l="modern-light",containerStyle:p,appearance:m,buttonsStyles:h,loading:R=null,onReady:w,onComplete:I,onDecline:Y,onCancel:_,onValidation:Z,onError:A}){let[y]=(0,Ge.useState)(ea.readSetupRedirectReturn),[P,me]=(0,Ge.useState)(null),[S,xe]=(0,Ge.useState)(!1),[T,le]=(0,Ge.useState)(null),[ye,pe]=(0,Ge.useState)(null),[Re,lt]=(0,Ge.useState)(null),[$e,B]=(0,Ge.useState)(null),[wt,Ye]=(0,Ge.useState)(()=>new Set),Ne=(0,Ge.useRef)(wt),ue=(0,Ge.useRef)(null);ue.current=P;let ne=(0,Ge.useRef)(!1),K=(0,Ge.useRef)(!1),Le=(0,Ge.useRef)(!1),nt=(0,Ge.useRef)(!1),je=(0,Ge.useRef)(0),X=(0,Ge.useRef)(0),$=(0,Ge.useRef)(!1),{vaultTheme:H,surface:V,overlayTheme:Ve,appearance:De,buttonsLayout:fe}=(0,Ge.useMemo)(()=>Ii({theme:l,appearance:m,buttonsStyles:h}),[l,m,h]),D=(0,Ge.useMemo)(()=>(0,Ia.mergeCardSetupSurface)(V,p),[V,p]),ge=(0,Ge.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:w,onComplete:I,onDecline:Y,onCancel:_,onValidation:Z,onError:A});ge.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:w,onComplete:I,onDecline:Y,onCancel:_,onValidation:Z,onError:A},(0,Ge.useEffect)(()=>{$.current=!0;let c=je.current+1;return je.current=c,()=>{$.current=!1,X.current+=1,queueMicrotask(()=>{je.current===c&&(Le.current||nt.current||(nt.current=!0,(0,Ke.invokeMerchantCallback)(()=>{ge.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let pt=(0,Ge.useCallback)((c,U)=>{Le.current=!0,ne.current=!1,B({status:"success",wording:c,message:null}),(async()=>(await Is(600),!K.current&&(K.current=!0,(0,Ke.invokeMerchantCallback)(()=>{ge.current.onComplete?.({status:"succeeded",sessionId:ge.current.sessionId,...U?{paymentMethod:U}:{}})}),$.current&&B(null))))()},[]),Ue=(0,Ge.useCallback)((c,U)=>{Le.current=!0,ne.current=!1,B({status:"error",wording:c,message:U.message??null}),(0,Ke.invokeMerchantCallback)(()=>{ge.current.onDecline?.({status:"declined",sessionId:ge.current.sessionId,...U.reason?{reason:U.reason}:{},...U.message?{message:U.message}:{}})}),(async()=>(await Is(400),$.current&&B(null)))()},[]),ot=(0,Ge.useCallback)((c,U)=>{ne.current?(ne.current=!1,B({status:"error",wording:c,message:U.message}),setTimeout(()=>{$.current&&B(null)},400)):B(null),(0,Ke.invokeMerchantCallback)(()=>ge.current.onError?.(U))},[]),Ae=(0,Ge.useCallback)(async c=>{let U=X.current+1;X.current=U;let W=()=>!$.current||U!==X.current;ne.current=!0,B({status:"processing",wording:"payment_method",message:null});let ce=new Ba.PaymentAPI((0,kr.resolveBillingApiUrl)(ge.current.billingApiUrl),{telemetry:ge.current.telemetry});try{for(let E=0;E<Su;E+=1){if((E>0||c.waitFirst)&&await Is(wu),W())return;let z=await ce.getUnifiedCheckoutSession(ge.current.sessionId,ge.current.nonce);if(W())return;let Ut=z.data.session?.status;if(Ut==="complete"){xe(!0),pt("payment_method");return}if(Ut==="expired")throw new kr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new kr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(E){if(W())return;let z=E instanceof kr.FloPayError&&E.code==="payment_method_setup_unverified";ot("payment_method",uo(E,z?{retryable:!0}:{}))}finally{ce.destroy()}},[ot,pt]);(0,Ge.useEffect)(()=>{let c=!0,U=(0,kr.resolveBillingApiUrl)(a),W=new Ba.PaymentAPI(U,{telemetry:s});me(null),xe(!1),le(null),pe(null),lt(null);let ce=new Set;return Ne.current=ce,Ye(ce),Le.current=!1,nt.current=!1,K.current=!1,(async()=>{try{let{session:E,advertisement:z}=await Ru(W,r,n);if(!c)return;let Ut={advertisement:z,customer:ku(E),...E.futureUse?{futureUse:E.futureUse}:{},...E.futureUseUnsupported?{futureUseUnsupported:E.futureUseUnsupported}:{}};if(y){if((0,ea.clearSetupRedirectParams)(),E.status==="complete"){xe(!0),me(Ut),pt("payment_method");return}y.failed?Ue("payment_method",{reason:"redirect_failed"}):Ae({waitFirst:!0})}let Fr=z.card?await Eu(W,E,r,n,U):null;if(!c)return;me(Ut),Fr&&(pe(Fr),le(new Ba.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(E){if(!c)return;let z=uo(E);Le.current=!0,lt(z),(0,Ke.invokeMerchantCallback)(()=>ge.current.onError?.(z))}})(),()=>{c=!1,W.destroy()}},[a,n,y,Ue,pt,r,s,Ae]),(0,Ge.useEffect)(()=>{if(!T)return;ne.current=!1;let c=T.on("submitting",()=>{ne.current=!0,B({status:"processing",wording:"card",message:null})}),U=T.on("complete",E=>{pt("card",E.paymentMethod)}),W=T.on("decline",E=>{Ue("card",{...E.declineReason?{reason:E.declineReason}:{},...E.message?{message:E.message}:{}})}),ce=T.on("challenge_dismissed",()=>{B(null)});return()=>{c(),U(),W(),ce()}},[T,Ue,pt]);let Qe=(0,Ge.useCallback)((c,U,W)=>{if(W.retryable){ot("payment_method",uo(U,W));return}if(Ne.current.has(c))return;let ce=new Set(Ne.current);ce.add(c),Ne.current=ce,Ye(ce);let E=ue.current?.advertisement,z=E?(0,Ar.advertisedMethodKeys)(E).some(Ut=>!ce.has(Ut)):!1;ot("payment_method",uo(U,{code:W.code,retryable:z}))},[ot]),at=(0,Ge.useMemo)(()=>({onSubmitting:()=>{ne.current=!0,B({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Ae({waitFirst:!1})},onDeclined:c=>Ue("payment_method",c),onValidation:c=>{(0,Ke.invokeMerchantCallback)(()=>ge.current.onValidation?.(c))},onAbandoned:()=>{ne.current=!1,B(null)}}),[Ue,Ae]),pr=(0,Ge.useRef)(Qe);pr.current=Qe;let Mt=(0,Ge.useRef)(new Map),vt=c=>{let U=Mt.current.get(c);if(U)return U;let W=(ce,E)=>pr.current(c,ce,E);return Mt.current.set(c,W),W},be=(0,Ge.useCallback)(c=>{if(Ne.current.has(c))return;let U=new Set(Ne.current);U.add(c),Ne.current=U,Ye(U);let W=ue.current?.advertisement;W&&(0,Ar.advertisedMethodKeys)(W).some(E=>!U.has(E))||ot("payment_method",uo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ot]),M=(0,Ge.useRef)(be);M.current=be;let gt=(0,Ge.useRef)(new Map),ct=c=>{let U=gt.current.get(c);if(U)return U;let W=()=>M.current(c);return gt.current.set(c,W),W},N=$e?(0,ur.jsx)(sn,{status:$e.status,errorMessage:$e.message,...(0,Ar.setupOverlayLabels)($e.wording),successNote:null,...Ve?{theme:Ve}:{}}):null;if(Re)return(0,ur.jsx)("div",{role:"alert",children:Re.message});if(!P||S)return(0,ur.jsxs)(ur.Fragment,{children:[N,P?null:R]});let{advertisement:Fe,customer:Lt,futureUse:Se,futureUseUnsupported:It}=P,b=(0,kr.resolveBillingApiUrl)(a),x=s===void 0?{}:{telemetry:s},Be=Fe.stripe.filter(({method:c})=>!wt.has(c)),Ee=wt.has("paypal")?null:Fe.paypal,dt=!!(Fe.card&&T&&ye?.html),it=({method:c,publishableKey:U,currency:W})=>(0,ur.jsx)("div",{"data-flopay-payment-method":c,style:{display:"contents"},children:(0,ur.jsx)(Ti,{onFailed:vt(c),children:(0,ur.jsx)(Ge.Suspense,{fallback:null,children:(0,ur.jsx)(e,{method:c,category:(0,Ar.stripeMethodCategory)(c),publishableKey:U,currency:W,...Se?{futureUse:Se}:{},...It?{futureUseUnsupported:It}:{},sessionId:r,nonce:n,billingApiUrl:b,...x,...De?{appearance:De}:{},...fe?{buttonsLayout:fe}:{},...typeof l=="string"?{themeId:l}:{},...at,onFailed:vt(c),onUnavailable:ct(c)})})})},c),We=Be.filter(({method:c})=>(0,Ar.stripeMethodCategory)(c)==="wallet"),He=Be.filter(({method:c})=>(0,Ar.stripeMethodCategory)(c)!=="wallet"),Dt=Be.length>0||Ee!==null;return(0,ur.jsxs)(ur.Fragment,{children:[N,Dt?(0,ur.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[We.map(it),Ee?(0,ur.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,ur.jsx)(Ti,{onFailed:vt("paypal"),children:(0,ur.jsx)(Ge.Suspense,{fallback:null,children:(0,ur.jsx)(t,{clientId:Ee.clientId,...Ee.environment?{environment:Ee.environment}:{},...Fe.currency?{currency:Fe.currency}:{},sessionId:r,nonce:n,billingApiUrl:b,customer:Lt,...x,...at,onFailed:vt("paypal"),onUnavailable:ct("paypal")})})})}):null,He.map(it)]}):null,dt&&Dt?(0,ur.jsx)(fi,{label:"or add a card"}):null,dt&&T&&ye?.html?(0,ur.jsx)("div",{"data-flopay-payment-method":"card",children:(0,ur.jsx)(go,{capture:T,html:ye.html,messageToken:ye.messageToken,expectedOrigin:ye.expectedOrigin,verificationRequired:ye.verificationRequired,theme:H,containerStyle:D,onReady:()=>{(0,Ke.invokeMerchantCallback)(()=>ge.current.onReady?.())},onValidation:c=>{(0,Ke.invokeMerchantCallback)(()=>ge.current.onValidation?.(c))},onError:c=>{c&&ot("card",uo(new Error(c),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var _c=require("react/jsx-runtime"),Iu={StripeSetupMethod:Rc,PayPalSetupMethod:vc};function Ic(e){return(0,_c.jsx)(Ec,{...e,branches:Iu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|