@flopay/react 1.14.8 → 1.14.10

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