@flopay/react 1.14.7 → 1.14.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var Nc=Object.create;var Wa=Object.defineProperty;var Uc=Object.getOwnPropertyDescriptor;var zc=Object.getOwnPropertyNames;var qc=Object.getPrototypeOf,jc=Object.prototype.hasOwnProperty;var Vc=(e,t)=>{for(var r in t)Wa(e,r,{get:t[r],enumerable:!0})},dl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of zc(t))!jc.call(e,a)&&a!==r&&Wa(e,a,{get:()=>t[a],enumerable:!(n=Uc(t,a))||n.enumerable});return e};var Wi=(e,t,r)=>(r=e!=null?Nc(qc(e)):{},dl(t||!e||!e.__esModule?Wa(r,"default",{value:e,enumerable:!0}):r,e)),Wc=e=>dl(Wa({},"__esModule",{value:!0}),e);var vu={};Vc(vu,{DirectPayPalButton:()=>ha,FloPayAutomaticPaymentButton:()=>ac,FloPayCardSetup:()=>ic,FloPayCardSetupError:()=>xa,FloPayCheckout:()=>vi,FloPayPaymentMethodSetup:()=>hc,FloPayProvider:()=>va,SplitCardForm:()=>fi,VaultCardFields:()=>co,dropThirdPartyOnlyError:()=>vc.dropThirdPartyOnlyError,useCheckout:()=>bl,useFloPay:()=>Qn,usePayPalFloPay:()=>Ga});module.exports=Wc(vu);var vc=require("@flopay/shared");var Ci=require("@flopay/js"),Pn=require("@flopay/shared"),gt=require("react");var $t=require("react/jsx-runtime");function $c(){return(0,$t.jsxs)($t.Fragment,{children:[(0,$t.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,$t.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,$t.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,$t.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,$t.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Hc(){return(0,$t.jsx)($t.Fragment,{children:"Go back"})}function Kc(){return(0,$t.jsx)($t.Fragment,{children:"Secure card checkout"})}function Bo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Do({content:e}){return(0,$t.jsx)($t.Fragment,{children:e===void 0?(0,$t.jsx)($c,{}):e})}function Oo({content:e}){return(0,$t.jsx)($t.Fragment,{children:e===void 0?(0,$t.jsx)(Hc,{}):e})}function ua({content:e}){return(0,$t.jsx)($t.Fragment,{children:e===void 0?(0,$t.jsx)(Kc,{}):e})}var vt=require("@flopay/shared"),Rn=require("@flopay/shared"),Uo=require("@flopay/shared"),vo=require("@flopay/shared"),Gc="Checkout is temporarily unavailable. Please try again later.";function $i(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof vt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Yc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function ul(){return new vt.FloPayError(Gc,"api_error",{code:"CheckoutInitializationFailed"})}function pl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,vt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,vt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function ml(e,t){if(t&&(!(e instanceof vt.FloPayError)||e.type==="authentication_error"))return $i(e);if(!(e instanceof vt.FloPayError&&Yc(e))){if(!t&&!(e instanceof vt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,vt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof vt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof vt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Lo(e,t,r,n={}){let a;return(i={})=>{if(a!==void 0)return a;let l={...n,...i,email:i.email?.trim()||n.email?.trim()},p=(0,vt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,vt.isValidEmail)(l.email))return Promise.reject(new vt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[h,w]of Object.entries(l)){if(p&&h.endsWith("Name")||typeof w!="string")continue;let S=w.trim();S&&(m[h]=S)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function yl(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Hi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function fl(e,t){let r=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],n=r.reduce((i,l)=>i+(l.overrideAmount??l.totalAmount??0),0),a=e.currency??r.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:r.map((i,l)=>({uuid:`synthetic-${i.type??"item"}-${l}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Ki(e,t){return t?{...e,...t}:e}function wr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,i=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,l=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...i?{declineCode:i}:{},...l?{sessionId:l}:{}}}function so(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Xn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Jn(e){return e?.status==="authorized"||e?.status==="complete"}function lo(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function gl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function $a(e){let t=gl(e);return new vt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Ha(e){return e instanceof vt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function No(e){return gl(e)?new vt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new vt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new vt.FloPayError(vt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function pa(e,t){return e==="processing"||(0,vt.isMoneySettledOutcome)(e,t)}function hl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Pl(e,t){let r=e;if((0,vt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:i,error:l}=await r.retrieveSetupIntent(t);if(l)throw new vt.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return i??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new vt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var Xc=["apple_pay","google_pay"];function vl(e,t="automatic",r){let n=(0,vt.resolveSetupFutureUsage)(r,Xc,"wallet");return{...(0,vt.resolveWalletModeOptions)(e,t),paymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Jc=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Gi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Jc.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function ma(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var ro=require("@flopay/js"),We=require("@flopay/shared"),v=Wi(require("react"),1);var Yi=require("react"),pn=(0,Yi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),En=(0,Yi.createContext)({session:null,loading:!1,error:null});var Za=require("@flopay/js"),Qe=require("@flopay/shared"),Rl=require("@paypal/paypal-js"),k=require("react");var Ka=require("@flopay/shared"),In=require("react"),mn=require("@flopay/shared"),Zn=require("react/jsx-runtime");function zo(){let[e,t]=(0,In.useState)(null),r=(0,In.useRef)(null),n=(0,In.useRef)(0),a=(0,In.useCallback)((l,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:l,identity:p}),new Promise(m=>{r.current=m})),[]),i=(0,In.useCallback)(l=>{let p=r.current;r.current=null,t(null),p?.(l)},[]);return(0,In.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:i}}function qo({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[l,p]=(0,In.useState)(e.email?.trim()??""),m=(0,Ka.isValidEmail)(l.trim());return(0,Zn.jsxs)("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Zn.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Zn.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Zn.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:h=>p(h.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Zn.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,Zn.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Zn.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,Ka.compactBuyerIdentity)({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var ve=require("@flopay/shared");var Cl=require("@flopay/shared"),ya=require("react");function Qn(){return(0,ya.useContext)(pn).flopay}function Ga(){return(0,ya.useContext)(pn).paypalFlopay??null}function bl(){return(0,ya.useContext)(En)}function Sl(){return(0,ya.useContext)(pn).billingApiUrl||(0,Cl.resolveBillingApiUrl)()}var Zc=require("@flopay/shared"),Un=require("@flopay/shared"),zn=require("@flopay/shared");var jo=require("@flopay/shared"),bo=require("react");var Ya=require("react"),Co=typeof window>"u"?Ya.useEffect:Ya.useLayoutEffect;var Xi=require("@flopay/shared");function Vo(e,t){let r=(0,bo.useRef)(e);r.current=e;let n=(0,bo.useRef)(new Set),a=(0,bo.useRef)(t),i=(0,bo.useRef)(t);return Co(()=>{i.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,bo.useCallback)(l=>{if(i.current!==t)return;let p=(0,jo.projectFloInstrument)(l);if(p){if(jo.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,jo.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ze=require("@flopay/shared");var wl=require("react"),fa=(0,wl.createContext)(null);function Xa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Qc=Symbol.for("@flopay/js.telemetry.bridge.v1"),ed=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function td(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function rd(e){let t=td(),r=(a,i)=>a?a.bind(e):i,n=r(e.now,t.now);return{error:r(e.error,t.error),log:r(e.log,t.log),performance:r(e.performance,t.performance),terminal:r(e.terminal,t.terminal),now:n,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,n()-a),setCheckoutContext:r(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:r(e.beginCheckout,t.beginCheckout),disable:r(e.disable,t.disable),subscribe:r(e.subscribe,t.subscribe),flush:r(e.flush,t.flush),destroy:r(e.destroy,t.destroy)}}function Ja(e){let t=globalThis[ed];return rd(t?.(e)??{})}function kr(e){if(e)return e[Qc]}var fr=require("react");function ga(e,t){let r=(0,fr.useRef)(0),n=(0,fr.useRef)(null),a=(0,fr.useRef)(null),i=(0,fr.useRef)(e),l=(0,fr.useRef)(t?.onHandoffObserved),p=(0,fr.useRef)(t?.defersMissingTerminal),m=(0,fr.useRef)(t?.onMissingTerminalDeferred);(0,fr.useEffect)(()=>{i.current=e,l.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let h=(0,fr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),w=(0,fr.useCallback)(f=>{h();let P=r.current+1;return r.current=P,n.current=null,a.current={generation:P,method:f,timer:null,yieldedControl:!1},P},[h]),S=(0,fr.useCallback)(f=>{let P=a.current;return f!==void 0&&P?.generation!==f?!1:(h(P),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[h]),E=(0,fr.useCallback)(f=>{let P=a.current,pe=f??P?.generation??r.current;(f===void 0||P?.generation===f)&&(h(P),a.current=null),n.current=pe},[h]),Y=(0,fr.useCallback)(f=>n.current===(f??r.current),[]),I=(0,fr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),ee=(0,fr.useCallback)(()=>{let f=a.current;f&&(h(f),!f.yieldedControl&&(f.yieldedControl=!0,l.current?.(f.method)))},[h]),x=(0,fr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(h(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(p.current?.(f.method)){m.current?.(f.method,f.generation);return}a.current=null,n.current=f.generation,i.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},ve.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[h]);return(0,fr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?x():ee()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",ee),window.addEventListener("focus",x),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",ee),window.removeEventListener("focus",x),h()}},[h,ee,x]),{startAttempt:w,finishAttempt:S,invalidateAttempt:E,isAttemptInvalidated:Y,isAttemptCurrent:I,generationRef:r}}var yn=require("react/jsx-runtime"),Qa=45,nd=1e3,od=11e3,ad={width:"100%",minHeight:Qa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},id={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function sd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:id[e.kind]??null}}function kl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,ve.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function ld(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function El({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:i,clientId:l,environment:p,currency:m,isSubscription:h,providerObjectType:w,approvalPresentation:S,onTokenizedBody:E,onComplete:Y,onErrorChange:I,onDecline:ee,onCancel:x,onTechnicalFailure:f,isProcessing:P=!1,onLoadStateChange:pe,onInitializationStateChange:b,allowAutomaticRetry:Ie=!0,onButtonClick:_,runBeforeButtonClick:ie,session:me,existingOrderId:ue,telemetry:xe,telemetryContext:lt,onInstrument:$e,debug:B=!1}){let St=Qn(),Ge=Vo($e,e),De=(0,k.useMemo)(()=>{if(St)return null;let Z=Ja({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:Qe.SDK_VERSION,enabled:xe!==!1});return Z.setCheckoutContext(lt??{}),Z.beginCheckout(lt??{}),Z},[r,St,xe,lt?.checkoutMode,lt?.layout]),de=(0,k.useMemo)(()=>kr(St),[St]);(0,k.useEffect)(()=>()=>{De&&De.flush().catch(()=>{}).finally(()=>De.destroy())},[De]);let re=(0,k.useMemo)(()=>({error:Z=>{de?de.error(Z):De?.error(Z),Ge({class:"technical_error",errorCode:Z.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":Z.errorCode,requestCategory:Z.requestCategory,provider:Z.provider})},log:Z=>{de?de.log(Z):De?.log(Z),Ge({class:"lifecycle",name:Z.name,provider:Z.provider})},performance:Z=>{de?de.performance(Z):De?.performance(Z)},terminal:Z=>{de?de.terminal(Z):De?.terminal(Z)},startTiming:()=>de?.now()??De?.now()??0,elapsed:Z=>de?.elapsed(Z)??Math.max(0,(De?.now()??Z)-Z)}),[Ge,de,De]),X=(0,k.useRef)(null),Oe=(0,k.useRef)(0),nt=(0,k.useRef)(null),ze=(0,k.useRef)(null),te=(0,k.useRef)(null),J=(0,k.useContext)(fa),H=(0,k.useRef)(null);H.current||(H.current=Xa());let j=J??H.current,je=(0,k.useRef)(null),Te=(0,k.useRef)(!1),[fe,O]=(0,k.useState)(!1),[Pe,ut]=(0,k.useState)(!1),[Le,ot]=(0,k.useState)(0),_e=(0,k.useRef)(0),[et,at]=(0,k.useState)(!1),ar=(0,k.useRef)(!1),xt=(0,k.useRef)(!1),[Ct,Ce]=(0,k.useState)(!1),[T,ht]=(0,k.useState)(!1),{request:pt,collect:z,finish:Ae}=zo(),Dt=(0,k.useRef)({sessionId:e,required:(0,Qe.paypalProviderIdentityRequired)(n,me)});Dt.current.sessionId!==e&&(Dt.current={sessionId:e,required:(0,Qe.paypalProviderIdentityRequired)(n,me)});let be=Dt.current.required,_t=(0,k.useMemo)(()=>r.replace(/\/+$/,""),[r]),M=me?.gateways?.paypal?.providerObjectType??w,Fe=M??(h?"subscription":"order"),[Se]=(0,k.useState)(Un.detectPayPalEnvironment),ct=me?.gateways?.paypal?.approvalPresentation??S,mt=(0,zn.resolvePayPalPresentationMode)(Se,ct==="app_switch"?"app_switch":void 0,Fe),Ve=(0,Qe.usesPayPalVaultedChannel)(M),He=(0,k.useMemo)(()=>JSON.stringify([_t,l,m,p??"",Fe,Ve,mt,e,ue??""]),[_t,l,m,p,ue,Fe,Ve,mt,e]),Bt=(0,k.useRef)(He),c=Bt.current!==He,U=(0,k.useRef)(B),V=(0,k.useRef)(null),[se,R]=(0,k.useState)([]),K=(0,k.useCallback)(Z=>{U.current&&R(At=>[...At,`${new Date().toISOString().slice(11,23)} ${Z}`])},[]);(0,k.useEffect)(()=>{U.current=B,B&&K("debug:enabled"),V.current?.setEnabled(B)},[K,B]);let Ut=(0,k.useRef)(E),xr=(0,k.useRef)(Y),ir=(0,k.useRef)(I),Ht=(0,k.useRef)(ee),Tt=(0,k.useRef)(x),Lr=(0,k.useRef)(f),Ar=(0,k.useRef)(_),Zt=(0,k.useRef)(pe),$r=(0,k.useRef)(b),Mt=(0,k.useRef)(i),xn=(0,k.useRef)(ie),Kt=(0,k.useRef)(me),ln=(0,k.useRef)(n),Nr=(0,k.useRef)(a),Ur=(0,k.useRef)(t),sr=(0,k.useRef)(null),br=(0,k.useRef)(new Map),Hr=(0,k.useRef)(new Map),dt=(0,k.useRef)(!1);(0,k.useEffect)(()=>(dt.current=!0,()=>{dt.current=!1}),[]),(0,k.useEffect)(()=>{Ut.current=E},[E]),(0,k.useEffect)(()=>{Mt.current=i},[i]),(0,k.useEffect)(()=>{xr.current=Y},[Y]),(0,k.useEffect)(()=>{ir.current=I},[I]),(0,k.useEffect)(()=>{Ht.current=ee},[ee]),(0,k.useEffect)(()=>{Tt.current=x},[x]),(0,k.useEffect)(()=>{Lr.current=f},[f]),(0,k.useEffect)(()=>{Ar.current=_},[_]),(0,k.useEffect)(()=>{Zt.current=pe},[pe]),(0,k.useEffect)(()=>{$r.current=b},[b]),(0,k.useEffect)(()=>{xn.current=ie},[ie]),(0,k.useEffect)(()=>{Kt.current=me},[me]),(0,k.useEffect)(()=>{ln.current=n},[n]),(0,k.useEffect)(()=>{Nr.current=a},[a]),(0,k.useEffect)(()=>{Ur.current=t},[t]),(0,k.useEffect)(()=>{_e.current=Le},[Le]),(0,k.useEffect)(()=>{et&&je.current?.focus()},[et,Le]);let wt=(0,k.useCallback)(()=>{window.setTimeout(()=>{je.current?.focus()},0)},[]),lr=(0,k.useCallback)(()=>{O(!1),ot(Z=>Z+1)},[]),Gt=(0,k.useCallback)(()=>{at(!1),(X.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??X.current)?.focus?.()},[]);(0,k.useEffect)(()=>{!fe||!Te.current||(Te.current=!1,Gt())},[Gt,fe,Le]);let hr=(0,k.useCallback)((Z,At)=>{let Me=At?.popupBlocked??(0,ve.isPopupBlockedError)(Z);Me&&j.markBlocked();let Pr=(0,ve.buildExternalMethodRecoveryMessage)("PayPal",Me,Se.inAppBrowser),Ot=Lr.current;if(Ot){let jt=Me&&Se.inAppBrowser?new Qe.FloPayError(Pr,"api_error",{code:At?.code??"paypal_popup_blocked"}):Z;Ot("paypal",jt,At);return}ir.current?.(Pr)},[j,Se.inAppBrowser]),Yt=(0,k.useCallback)(Z=>{let At=nt.current,Me=ze.current;At===null||!Me||(re.log({...Me,popupCapability:j.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Z}),re.performance({...Me,popupCapability:j.current(),stage:"overlay_return",durationMs:re.elapsed(At),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Z}),nt.current=null)},[j,re]),cr=(0,k.useCallback)((Z,At,Me)=>{let Pr=ze.current;Yt("overlay_timeout"),Pr&&re.error({...Pr,popupCapability:j.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),hr(At,{...Me,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:mt,terminalReason:"overlay_timeout"}),at(!0),lr(),wt()},[Yt,wt,hr,j,mt,lr,re]),Ir=(0,k.useCallback)(()=>{j.markAvailable();let Z=ze.current;Z&&(te.current=Z.attempt,re.log({...Z,popupCapability:j.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[j,re]),{finishAttempt:dr,generationRef:Ye,invalidateAttempt:Fr,isAttemptCurrent:ur,isAttemptInvalidated:oo,startAttempt:zr}=ga(cr,{onHandoffObserved:Ir}),qr=(0,k.useCallback)(()=>(at(!1),zr("paypal")),[zr]),An=(0,k.useCallback)(Z=>{Fr(Z?.generation),Z?.showRetry&&at(!0),Z?.remount&&lr(),Z?.focus!==!1&&wt()},[wt,Fr,lr]),Kr=Z=>{let At=sr.current;return At&&Hr.current.set(Z,At),Z};(0,k.useEffect)(()=>{Bt.current!==He&&(Bt.current=He,ar.current=!1,xt.current=!1,O(!1),ut(!1),Ce(!1),$r.current?.("loading"))},[He]),(0,k.useEffect)(()=>{(0,Ze.invokeMerchantCallback)(()=>Zt.current?.(fe&&!Ct))},[fe,Ct]);let Xt=(0,Qe.normalizeGatewayEnvironment)(p);(0,k.useEffect)(()=>{let Z={attempt:Ye.current+1,inAppBrowser:Se.inAppBrowser,appFamily:Se.appFamily,popupCapability:j.current(),presentationMode:mt},At=()=>({...ze.current??Z,popupCapability:j.current()}),Me={error:g=>re.error({...g,...At()}),log:g=>re.log({...g,...At()}),performance:g=>re.performance({...g,...At()}),terminal:g=>re.terminal({...g,...At()}),startTiming:re.startTiming,elapsed:re.elapsed},Pr=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Ot=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(K(`mount clientId=${Pr} env=${p??"(unset)"}\u2192${Xt??"live"} ccy=${m} sub=${h}`),K(`ua=${Ot.slice(0,80)}${Ot.length>80?"\u2026":""}`),!l){K("FAIL: clientId empty \u2014 gateway misconfigured"),Ce(!0),Me.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!X.current){K("FAIL: containerRef not attached");return}Oe.current=Me.startTiming(),Me.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let jt=!1,vr=!1,$=()=>jt||vr,Vt=Ve?Fe:void 0,tt,Lt=!1,pr=()=>{tt=(0,Qe.generateIdempotencyKey)(),tt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Lt=!0},Br=null,Qt=!1,vn=null,$n=!1,Fn=()=>{!vn||$n||($n=!0,vn.close().catch(()=>{}))},jr=!1,ao=!1,cn=X.current,Hn=null,en=null,Cn=[],Bn=null,Nt=!1,tn=!1,rn=null,Gr=g=>{if(!g||typeof g.getBoundingClientRect!="function")return"(no rect)";let y=g.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},bn=g=>{if(!g)return"(empty)";try{let y=new URL(g,typeof window>"u"?"https://localhost":window.location.href),G=y.pathname.toLowerCase();return G.includes("checkcaptcha")||G.includes("captcha")?`CAPTCHA(${y.host}${G})`:G.includes("risk")||G.includes("challenge")?`RISK(${y.host}${G})`:G.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${G}`.slice(0,100)}catch{return g.slice(0,80)}},bt=g=>{let y=g.getAttribute("src"),G=g.getAttribute("srcdoc"),ke=g.getAttribute("name"),Xe=g.getAttribute("sandbox"),yt=[];return y&&yt.push(`src=${bn(y)}`),G&&yt.push(`srcdoc[${G.length}ch]`),!y&&!G&&yt.push("src=(empty) srcdoc=(empty)"),ke&&yt.push(`name=${ke.slice(0,40)}`),Xe!==null&&yt.push(`sandbox="${Xe.slice(0,40)}"`),yt.join(" ")},_r=g=>{if(!(g instanceof HTMLIFrameElement))return"";try{let y=g.contentDocument;if(!y)return"cd=null";let G=y.body?.children.length??0,ke=y.body?.innerHTML.length??0,Xe=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${G}children,${ke}ch] head[${Xe}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},mr=[],Yr=g=>{if($())return;let y=g.message??String(g.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(K(`window:error ${y.slice(0,140)}`),mr.push(y))},mo=g=>{if($())return;let y=g.reason instanceof Error?g.reason.message:String(g.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(K(`window:rejection ${y.slice(0,140)}`),mr.push(y))},Sn={value:0},Kn=()=>{Hn?.disconnect(),Hn=null,en?.disconnect(),en=null;for(let g of Cn.splice(0))clearTimeout(g);tn=!1,Nt&&typeof window<"u"&&(window.removeEventListener("error",Yr),window.removeEventListener("unhandledrejection",mo)),Nt=!1},nn=()=>{if(!(Nt||$()||jr)){if(Nt=!0,mr.length=0,Sn.value=0,typeof window<"u"&&(window.addEventListener("error",Yr),window.addEventListener("unhandledrejection",mo)),typeof PerformanceObserver<"u")try{en=new PerformanceObserver(g=>{if(!$())for(let y of g.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Sn.value+=1;let G=Math.round(y.duration);K(`net ${G}ms ${y.name.slice(0,90)}`)}}),en.observe({type:"resource",buffered:!0})}catch{}rn?.()}},Tr=()=>{Bn&&(clearTimeout(Bn),Bn=null)},Dn=()=>{Kn(),Tr()},Dr={setEnabled:g=>{g?nn():Kn()}};V.current=Dr,U.current&&nn();let L=Qe.isPayPalTeardownMessage,N=g=>{if($()||L(g))return;let y=(0,vo.applyFriendlyMessageOverride)(g)??g;(0,Ze.invokeMerchantCallback)(()=>ir.current?.(y))},ne=(g,y)=>{if(jt||Qt)return;Qt=!0,vr=!0,Dn(),Fn();let G=sd({kind:g,generationActive:!0,automaticRetryAllowed:Ie,automaticRetryUsed:ar.current});if(G.action==="retry"){ar.current=!0,O(!1),ht(!1),ut(!0),$r.current?.("retrying"),Br=setTimeout(()=>{jt||ot(ke=>ke+1)},nd);return}if(O(!1),ht(!1),ut(!1),Ce(!0),G.action!=="ignore"){if($r.current?.("exhausted"),G.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}if(G.report){let ke=(0,ve.classifyExternalMethodFailure)({code:kl(g,y),message:y},{inAppBrowser:Se.inAppBrowser,handoffObserved:!1});ke.popupBlocked&&j.markBlocked(),Me.error({errorCode:ke.popupBlocked?ke.errorCode:G.report.errorCode,stage:G.report.stage,operationOutcome:G.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:ke.terminalReason})}xt.current||(xt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",kl(g,y)))}};Ce(!1);let we=async(g,y=sr.current)=>{if($())return;let G=y?.sessionId??e;if(Ut.current){await Ut.current(g,{sessionId:G,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let ke=Me.startTiming();Me.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Xe=()=>{Me.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Me.performance({stage:"processing",durationMs:Me.elapsed(ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let yt=(0,Qe.buildPayPalProcessPaymentRequest)({body:g,sessionId:G,nonce:y?.nonce??Ur.current,accountPatch:y?.accountPatch,session:Kt.current,email:ln.current}),Be=await new Za.PaymentAPI(_t,{telemetry:!1}).processPayment(yt.userId,yt.params);if(Be.ok){if(vr||jt&&dt.current)return;Xe(),Me.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ze.invokeMerchantCallback)(()=>xr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if($())return;let it=await Be.json().catch(()=>null),kt=(0,Qe.describePayPalProcessFailure)(it),Et=kt.message;Xe(),Be.status===400&&(typeof it?.declineCode=="string"||!Array.isArray(it?.fields))?Me.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Be.status===400||Be.status===422?Me.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):Me.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ld(Be.status),failureCategory:Be.status>=500?"server_error":void 0}),N(Et),(0,Ze.invokeMerchantCallback)(()=>Ht.current?.(wr("paypal",Et,{code:kt.code,declineCode:kt.declineCode})));return}catch(yt){if($())return;Xe(),Me.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ue=(0,Qe.friendlyPayPalFailureMessage)(yt instanceof Error?yt.message:void 0);N(Ue),(0,Ze.invokeMerchantCallback)(()=>Ht.current?.(wr("paypal",Ue)));return}},Rt=()=>new Qe.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),er=g=>$()?Promise.reject(Rt()):Promise.resolve(g),Ne=async g=>{if($())throw Rt();Lt||pr();let y=sr.current,G=y?.sessionId??e,ke=y?.nonce??Ur.current;Me.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Xe;try{Xe=await new Za.PaymentAPI(_t,{telemetry:!1}).createSessionIntent(G,ke??"",(0,Qe.buildPayPalSessionIntentRequest)(Vt),{idempotencyKey:tt})}catch(yt){throw Me.error({...(0,Qe.classifyTelemetryFailure)(yt,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),yt}if($())throw Rt();if(Xe.provider!=="paypal"||Xe.providerObjectType!==Fe)throw new Error(g);return Me.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Xe.providerObjectId},le=(g,y)=>{let G=y?.nonce??Ur.current;if(!G)return;let ke=y?.sessionId??e,Xe=(0,Qe.resolvePayPalDeclineReason)(g);new Za.PaymentAPI(_t,{telemetry:!1}).reportSessionIntentDecline(ke,G,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Xe}).catch(()=>{})},q=Le;K("loadScript:scheduled (deferred 1 tick)");let W=null,ce=setTimeout(()=>{if(jt){K("loadScript:skipped (cancelled before defer ran)");return}K("loadScript:start");let g=Xt==="live"?"production":Xt,y={};Fe==="subscription"?y={intent:"subscription",vault:!0}:Fe==="order"&&(y={intent:"capture"}),W=(0,Rl.loadScript)({clientId:l,currency:m,...y,...g?{environment:g}:{},...g==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let G=!1;W.then(ke=>{if(G=!0,K(`loadScript:resolved inactive=${$()} ns=${!!ke} buttons=${!!ke?.Buttons}`),$())return;if(!ke?.Buttons){K("FAIL: namespace missing Buttons factory"),ne("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}Me.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),Me.performance({stage:"provider_ready",durationMs:Me.elapsed(Oe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Me.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Xe=async(A,ge)=>{if($()||_e.current!==q)return;let Je=A.vaultSetupToken??A.subscriptionID??A.orderID??"",rt=Je?Hr.current.get(Je):br.current.get(q);if(!(!rt||!ur(rt.generation))&&dr(rt.generation)){Hr.current.delete(Je),br.current.delete(rt.surfaceKey),Yt("approved");try{if(ht(!0),(0,Ze.invokeMerchantCallback)(()=>ir.current?.(null)),!Je)throw new Qe.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let oe=(0,Qe.resolvePayPalApprovalIdentity)({accountPatch:rt.accountPatch,email:ln.current,billingName:Nr.current,session:Kt.current});if((0,Qe.needsPayPalPayerDetails)(oe))try{oe=(0,Qe.mergePayPalPayerIdentity)(oe,await ge?.order?.get?.())}catch{}if((Mt.current||be)&&!(0,Qe.isValidEmail)(oe.email)){let he=await z("PayPal",oe);if(!he)return;oe=he}(0,Qe.isValidEmail)(oe.email)&&(rt.accountPatch=(0,mn.compactBuyerIdentity)({...rt.accountPatch,...oe}),await Mt.current?.(oe));let yr=(0,Qe.buildPayPalTokenizedBody)(Je,Vt);await we(yr,rt)}catch(oe){N(oe instanceof Error?oe.message:"PayPal capture failed.")}finally{$()||ht(!1)}}},yt=A=>{let ge=ue?()=>er(ue):()=>Ne(A);return async()=>Kr(await ge())},Ue=ke.Buttons({style:{layout:"horizontal",height:Qa,tagline:!1},...mt==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(A,ge)=>{if($()){await ge.reject();return}pr();let Je=xn.current,rt={};if(Je)try{let he=await Je("paypal");if($()){await ge.reject();return}if(!he.proceed){sr.current=null,br.current.delete(q),await ge.reject();return}rt={sessionId:he.sessionId,accountPatch:he.accountPatch,nonce:he.nonce}}catch(he){K(`onClick:runBeforeButtonClick rejected msg=${(he instanceof Error?he.message:String(he)).slice(0,120)}`),sr.current=null,br.current.delete(q),await ge.reject();return}(0,Ze.invokeMerchantCallback)(()=>Ar.current?.("paypal"));let oe=qr(),yr={generation:oe,surfaceKey:q,...rt};sr.current=yr,br.current.set(q,yr),ze.current={...Z,attempt:oe},await ge.resolve(),Me.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Me.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nt.current=Me.startTiming()},createOrder:Fe==="order"?yt("Failed to create PayPal order."):void 0,createSubscription:Fe==="subscription"?yt("Failed to create PayPal subscription."):void 0,createVaultSetupToken:Fe==="setup_token"?async()=>Kr(await Ne("Failed to create PayPal setup token.")):void 0,onApprove:Xe,onCancel:()=>{if($())return;let A=br.current.get(q)??sr.current,ge=A&&ur(A.generation)?(0,Qe.buildPayPalCancelEvent)(A.sessionId??e,Vt):null;A&&br.current.delete(A.surfaceKey),sr.current=null,Yt("cancelled"),Me.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Te.current=!0,An({generation:A?.generation,remount:!0,focus:!1}),ge&&(0,Ze.invokeMerchantCallback)(()=>Tt.current?.(ge))},onError:A=>{if($()||_e.current!==q)return;let ge=A instanceof Error?A.message:"PayPal failed to render.";if(K(`onError rendered=${jr} msg=${ge.slice(0,120)}`),jr){let Je=br.current.get(q)??sr.current;if(Je&&!ur(Je.generation)||!Je&&oo())return;if(L(ge)){dr(Je?.generation);return}let{errorCode:rt,popupBlocked:oe,providerDeclined:yr,terminalReason:he}=(0,ve.classifyExternalMethodFailure)(A,{inAppBrowser:Se.inAppBrowser,handoffObserved:Je!=null&&te.current===Je.generation});if(oe&&j.markBlocked(),Yt(he),yr){Me.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:he}),le(A,Je),(0,Ze.invokeMerchantCallback)(()=>Ht.current?.(wr("paypal",ge))),Je&&br.current.delete(Je.surfaceKey),sr.current=null,dr(Je?.generation);return}Me.error({errorCode:rt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:he}),Je&&br.current.delete(Je.surfaceKey),sr.current=null,An({generation:Je?.generation,remount:!0,showRetry:!0,focus:!0}),hr(A,{code:"paypal_runtime_failed",popupBlocked:oe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:mt,terminalReason:he});return}ne(L(ge)?"teardown":"pre_ready_callback",ge)}}),Be=Ue.isEligible();if(K(`isEligible=${Be}`),Me.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Be){O(!1),ne("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}ao=!0,vn=Ue,rn=()=>{if(!Nt||tn||$()||jr)return;tn=!0,K(`container:dims ${Gr(cn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Hn=new MutationObserver(ge=>{if(!$()){for(let Je of ge)if(Je.type==="childList")Je.addedNodes.forEach(rt=>{if(!(rt instanceof Element))return;let oe=rt.tagName.toLowerCase(),yr=(rt.getAttribute("title")??"").slice(0,40),he=oe==="iframe"?` ${bt(rt)}`:"";K(`child+ ${oe}${yr?` title="${yr}"`:""}${he} dims=${Gr(rt)}`)});else if(Je.type==="attributes"&&Je.target instanceof Element){let rt=Je.target;if(rt.tagName.toLowerCase()!=="iframe")continue;let oe=Je.attributeName;(oe==="src"||oe==="srcdoc")&&K(`attr~ iframe ${oe}=${oe==="srcdoc"?`[${(rt.getAttribute("srcdoc")??"").length}ch]`:bn(rt.getAttribute("src"))} dims=${Gr(rt)}`)}}}),Hn.observe(cn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let A=ge=>{if($()||jr)return;let Je=cn.querySelectorAll("iframe"),rt=typeof document<"u"&&"hasStorageAccess"in document;K(`watchdog:${ge} container=${Gr(cn)} children=${cn.childElementCount} iframes=${Je.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${rt} paypalNetRequests=${Sn.value}`),Je.forEach((oe,yr)=>{let he=(oe.getAttribute("title")??"").slice(0,40);K(` iframe[${yr}] ${Gr(oe)}${he?` title="${he}"`:""} ${bt(oe)}`);let Gn=_r(oe);Gn&&K(` ${Gn}`)}),mr.length===0&&K(" (no PayPal/zoid window errors captured)")};Cn.push(setTimeout(()=>A("3s"),3e3)),Cn.push(setTimeout(()=>A("8s"),8e3)),Cn.push(setTimeout(()=>A("15s"),15e3))},rn(),K("render:start");let kt=Me.startTiming();Bn=setTimeout(()=>{$()||jr||(K("watchdog:11s retryable render timeout"),ne("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},od);let Et=Ue.render(cn);(async()=>{try{if(await Et,K(`render:resolved inactive=${$()}`),Dn(),$()){Fn();return}jr=!0,O(!0),ut(!1),$r.current?.("ready"),Me.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),Me.performance({stage:"checkout_render",durationMs:Me.elapsed(kt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(A){let ge=A instanceof Error?A.message:"PayPal failed to render.";K(`render:rejected msg=${ge.slice(0,120)}`),Dn(),ne(L(ge)?"teardown":"render_rejected",ge)}})()}).catch(ke=>{let Xe=ke instanceof Error?ke.message:"PayPal operation failed.";K(`provider:failed msg=${Xe.slice(0,120)}`);let yt="script_rejected";G&&L(Xe)?yt="teardown":G&&ao&&(yt="render_rejected"),ne(yt,Xe)})},0);return()=>{jt=!0,clearTimeout(ce),Br&&clearTimeout(Br),Dn(),V.current===Dr&&(V.current=null),Fn(),nt.current=null,ze.current=null}},[Ie,_t,l,m,p,Fe,mt,Ve,e,ue,Le,re,z,be,K,Yt]);let ye=B?(0,yn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ct?"#fef2f2":"#f3f4f6",border:`1px solid ${Ct?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${fe} failed=${Ct})`,se.length===0?`
1
+ "use strict";var Gc=Object.create;var Ga=Object.defineProperty;var Yc=Object.getOwnPropertyDescriptor;var Xc=Object.getOwnPropertyNames;var Jc=Object.getPrototypeOf,Zc=Object.prototype.hasOwnProperty;var Qc=(e,t)=>{for(var r in t)Ga(e,r,{get:t[r],enumerable:!0})},hl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Xc(t))!Zc.call(e,a)&&a!==r&&Ga(e,a,{get:()=>t[a],enumerable:!(n=Yc(t,a))||n.enumerable});return e};var Gi=(e,t,r)=>(r=e!=null?Gc(Jc(e)):{},hl(t||!e||!e.__esModule?Ga(r,"default",{value:e,enumerable:!0}):r,e)),ed=e=>hl(Ga({},"__esModule",{value:!0}),e);var _u={};Qc(_u,{DirectPayPalButton:()=>va,FloPayAutomaticPaymentButton:()=>fc,FloPayCardSetup:()=>gc,FloPayCardSetupError:()=>Fa,FloPayCheckout:()=>Ri,FloPayPaymentMethodSetup:()=>Ic,FloPayProvider:()=>ba,SplitCardForm:()=>bi,VaultCardFields:()=>go,dropThirdPartyOnlyError:()=>Tc.dropThirdPartyOnlyError,useCheckout:()=>Ml,useFloPay:()=>io,usePayPalFloPay:()=>Za});module.exports=ed(_u);var Tc=require("@flopay/shared");var Ei=require("@flopay/js"),kn=require("@flopay/shared"),ft=require("react");var Yt=require("react/jsx-runtime");function td(){return(0,Yt.jsxs)(Yt.Fragment,{children:[(0,Yt.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,Yt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Yt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Yt.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,Yt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function rd(){return(0,Yt.jsx)(Yt.Fragment,{children:"Go back"})}function nd(){return(0,Yt.jsx)(Yt.Fragment,{children:"Secure card checkout"})}function Lo(e){return e!==void 0&&(e===""||e===null||e===!1)}function No({content:e}){return(0,Yt.jsx)(Yt.Fragment,{children:e===void 0?(0,Yt.jsx)(td,{}):e})}function Uo({content:e}){return(0,Yt.jsx)(Yt.Fragment,{children:e===void 0?(0,Yt.jsx)(rd,{}):e})}function ma({content:e}){return(0,Yt.jsx)(Yt.Fragment,{children:e===void 0?(0,Yt.jsx)(nd,{}):e})}var St=require("@flopay/shared"),xn=require("@flopay/shared"),jo=require("@flopay/shared"),So=require("@flopay/shared");function Yi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof St.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function od(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Pl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,St.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,St.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function vl(e,t){if(t&&(!(e instanceof St.FloPayError)||e.type==="authentication_error"))return Yi(e);if(!(e instanceof St.FloPayError&&od(e))){if(!t&&!(e instanceof St.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,St.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof St.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof St.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function zo(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let l={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,St.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,St.isValidEmail)(l.email))return Promise.reject(new St.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[h,R]of Object.entries(l)){if(p&&h.endsWith("Name")||typeof R!="string")continue;let w=R.trim();w&&(m[h]=w)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function Cl(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Xi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function bl(e,t){let r=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],n=r.reduce((s,l)=>s+(l.overrideAmount??l.totalAmount??0),0),a=e.currency??r.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:r.map((s,l)=>({uuid:`synthetic-${s.type??"item"}-${l}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??a,metadata:s.metadata??null}))}}function Ji(e,t){return t?{...e,...t}:e}function Sr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,s=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,l=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...s?{declineCode:s}:{},...l?{sessionId:l}:{}}}var Sl=new WeakMap;function wl(e,t){return typeof e=="object"&&e!==null&&Sl.set(e,t?{sessionId:t}:{}),e}function kl(e){return typeof e=="object"&&e!==null?Sl.get(e):void 0}function yo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function no(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function oo(e){return e?.status==="authorized"||e?.status==="complete"}function fo(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function Rl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ya(e){let t=Rl(e);return new St.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Xa(e){return e instanceof St.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function qo(e){return Rl(e)?new St.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new St.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new St.FloPayError(St.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ya(e,t){return e==="processing"||(0,St.isMoneySettledOutcome)(e,t)}function El(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Il(e,t){let r=e;if((0,St.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:l}=await r.retrieveSetupIntent(t);if(l)throw new St.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new St.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var ad=["apple_pay","google_pay"];function _l(e,t="automatic",r){let n=(0,St.resolveSetupFutureUsage)(r,ad,"wallet");return{...(0,St.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var id=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Zi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:id.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function fa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var co=require("@flopay/js"),Oe=require("@flopay/shared"),v=Gi(require("react"),1);var Qi=require("react"),Pn=(0,Qi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),An=(0,Qi.createContext)({session:null,loading:!1,error:null});var oi=require("@flopay/js"),qe=require("@flopay/shared"),Dl=require("@paypal/paypal-js"),k=require("react");var Ja=require("@flopay/shared"),Fn=require("react"),vn=require("@flopay/shared"),ao=require("react/jsx-runtime");function Vo(){let[e,t]=(0,Fn.useState)(null),r=(0,Fn.useRef)(null),n=(0,Fn.useRef)(0),a=(0,Fn.useCallback)((l,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:l,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,Fn.useCallback)(l=>{let p=r.current;r.current=null,t(null),p?.(l)},[]);return(0,Fn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function Wo({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[l,p]=(0,Fn.useState)(e.email?.trim()??""),m=(0,Ja.isValidEmail)(l.trim());return(0,ao.jsxs)("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,ao.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,ao.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,ao.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:h=>p(h.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,ao.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,ao.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,ao.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,Ja.compactBuyerIdentity)({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var ke=require("@flopay/shared");var Tl=require("@flopay/shared"),ga=require("react");function io(){return(0,ga.useContext)(Pn).flopay}function Za(){return(0,ga.useContext)(Pn).paypalFlopay??null}function Ml(){return(0,ga.useContext)(An)}function xl(){return(0,ga.useContext)(Pn).billingApiUrl||(0,Tl.resolveBillingApiUrl)()}var sd=require("@flopay/shared"),$n=require("@flopay/shared"),Hn=require("@flopay/shared");var $o=require("@flopay/shared"),ko=require("react");var Qa=require("react"),wo=typeof window>"u"?Qa.useEffect:Qa.useLayoutEffect;var es=require("@flopay/shared");function Ho(e,t){let r=(0,ko.useRef)(e);r.current=e;let n=(0,ko.useRef)(new Set),a=(0,ko.useRef)(t),s=(0,ko.useRef)(t);return wo(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,ko.useCallback)(l=>{if(s.current!==t)return;let p=(0,$o.projectFloInstrument)(l);if(p){if($o.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,$o.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ke=require("@flopay/shared");var Al=require("react"),ha=(0,Al.createContext)(null);function ei(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ti="provider.callback.ignored";function ri(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var ld=Symbol.for("@flopay/js.telemetry.bridge.v1"),cd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function dd(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function ud(e){let t=dd(),r=(a,s)=>a?a.bind(e):s,n=r(e.now,t.now);return{error:r(e.error,t.error),log:r(e.log,t.log),performance:r(e.performance,t.performance),terminal:r(e.terminal,t.terminal),now:n,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,n()-a),setCheckoutContext:r(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:r(e.beginCheckout,t.beginCheckout),disable:r(e.disable,t.disable),subscribe:r(e.subscribe,t.subscribe),flush:r(e.flush,t.flush),destroy:r(e.destroy,t.destroy)}}function ni(e){let t=globalThis[cd];return ud(t?.(e)??{})}function wr(e){if(e)return e[ld]}var gr=require("react");function Pa(e,t){let r=(0,gr.useRef)(0),n=(0,gr.useRef)(null),a=(0,gr.useRef)(null),s=(0,gr.useRef)(e),l=(0,gr.useRef)(t?.onHandoffObserved),p=(0,gr.useRef)(t?.defersMissingTerminal),m=(0,gr.useRef)(t?.onMissingTerminalDeferred);(0,gr.useEffect)(()=>{s.current=e,l.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let h=(0,gr.useCallback)((y=a.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),R=(0,gr.useCallback)(y=>{h();let P=r.current+1;return r.current=P,n.current=null,a.current={generation:P,method:y,timer:null,yieldedControl:!1},P},[h]),w=(0,gr.useCallback)(y=>{let P=a.current;return y!==void 0&&P?.generation!==y?!1:(h(P),a.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[h]),I=(0,gr.useCallback)(y=>{let P=a.current,me=y??P?.generation??r.current;(y===void 0||P?.generation===y)&&(h(P),a.current=null),n.current=me},[h]),Y=(0,gr.useCallback)(y=>n.current===(y??r.current),[]),_=(0,gr.useCallback)(y=>a.current?.generation===y&&n.current!==y,[]),Z=(0,gr.useCallback)(()=>{let y=a.current;y&&(h(y),!y.yieldedControl&&(y.yieldedControl=!0,l.current?.(y.method)))},[h]),A=(0,gr.useCallback)(()=>{let y=a.current;!y?.yieldedControl||document.visibilityState!=="visible"||(h(y),y.timer=setTimeout(()=>{if(y.timer=null,a.current?.generation===y.generation){if(p.current?.(y.method)){m.current?.(y.method,y.generation);return}a.current=null,n.current=y.generation,s.current(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},ke.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[h]);return(0,gr.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?A():Z()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",Z),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",Z),window.removeEventListener("focus",A),h()}},[h,Z,A]),{startAttempt:R,finishAttempt:w,invalidateAttempt:I,isAttemptInvalidated:Y,isAttemptCurrent:_,generationRef:r}}var Cn=require("react/jsx-runtime"),ai=45,pd=1e3,md=11e3,Fl="paypal_intent_settled",yd={width:"100%",minHeight:ai,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},fd={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function gd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:fd[e.kind]??null}}function Bl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,ke.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function hd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Ol({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:l,environment:p,currency:m,isSubscription:h,providerObjectType:R,approvalPresentation:w,onTokenizedBody:I,onComplete:Y,onErrorChange:_,onDecline:Z,onCancel:A,onTechnicalFailure:y,isProcessing:P=!1,onLoadStateChange:me,onInitializationStateChange:S,allowAutomaticRetry:xe=!0,onButtonClick:T,runBeforeButtonClick:le,session:ye,existingOrderId:pe,telemetry:Re,telemetryContext:lt,onInstrument:$e,debug:B=!1}){let wt=io(),Ye=Ho($e,e),Ne=(0,k.useMemo)(()=>{if(wt)return null;let oe=ni({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:qe.SDK_VERSION,enabled:Re!==!1});return oe.setCheckoutContext(lt??{}),oe.beginCheckout(lt??{}),oe},[r,wt,Re,lt?.checkoutMode,lt?.layout]),ue=(0,k.useMemo)(()=>wr(wt),[wt]);(0,k.useEffect)(()=>()=>{Ne&&Ne.flush().catch(()=>{}).finally(()=>Ne.destroy())},[Ne]);let ne=(0,k.useMemo)(()=>({error:oe=>{ue?ue.error(oe):Ne?.error(oe),Ye({class:"technical_error",errorCode:oe.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":oe.errorCode,requestCategory:oe.requestCategory,provider:oe.provider})},log:oe=>{ue?ue.log(oe):Ne?.log(oe),Ye({class:"lifecycle",name:oe.name,provider:oe.provider})},performance:oe=>{ue?ue.performance(oe):Ne?.performance(oe)},terminal:oe=>{ue?ue.terminal(oe):Ne?.terminal(oe)},startTiming:()=>ue?.now()??Ne?.now()??0,elapsed:oe=>ue?.elapsed(oe)??Math.max(0,(Ne?.now()??oe)-oe)}),[Ye,ue,Ne]),K=(0,k.useRef)(null),Le=(0,k.useRef)(0),nt=(0,k.useRef)(null),je=(0,k.useRef)(null),X=(0,k.useRef)(null),$=(0,k.useContext)(ha),H=(0,k.useRef)(null);H.current||(H.current=ei());let V=$??H.current,Ve=(0,k.useRef)(null),De=(0,k.useRef)(!1),[fe,D]=(0,k.useState)(!1),[ge,pt]=(0,k.useState)(!1),[Ue,ot]=(0,k.useState)(0),Ae=(0,k.useRef)(0),[Qe,at]=(0,k.useState)(!1),pr=(0,k.useRef)(!1),Mt=(0,k.useRef)(!1),[vt,be]=(0,k.useState)(!1),[M,gt]=(0,k.useState)(!1),{request:ct,collect:N,finish:Fe}=Vo(),Lt=(0,k.useRef)({sessionId:e,required:(0,qe.paypalProviderIdentityRequired)(n,ye)});Lt.current.sessionId!==e&&(Lt.current={sessionId:e,required:(0,qe.paypalProviderIdentityRequired)(n,ye)});let Se=Lt.current.required,It=(0,k.useMemo)(()=>r.replace(/\/+$/,""),[r]),x=ye?.gateways?.paypal?.providerObjectType??R,Be=x??(h?"subscription":"order"),[Ee]=(0,k.useState)($n.detectPayPalEnvironment),dt=ye?.gateways?.paypal?.approvalPresentation??w,it=(0,Hn.resolvePayPalPresentationMode)(Ee,dt==="app_switch"?"app_switch":void 0,Be),We=(0,qe.usesPayPalVaultedChannel)(x),He=(0,k.useMemo)(()=>JSON.stringify([It,l,m,p??"",Be,We,it,e,pe??""]),[It,l,m,p,pe,Be,We,it,e]),Dt=(0,k.useRef)(He),c=Dt.current!==He,U=(0,k.useRef)(B),W=(0,k.useRef)(null),[ce,E]=(0,k.useState)([]),z=(0,k.useCallback)(oe=>{U.current&&E(xt=>[...xt,`${new Date().toISOString().slice(11,23)} ${oe}`])},[]);(0,k.useEffect)(()=>{U.current=B,B&&z("debug:enabled"),W.current?.setEnabled(B)},[z,B]);let Ut=(0,k.useRef)(I),Fr=(0,k.useRef)(Y),tr=(0,k.useRef)(_),Wt=(0,k.useRef)(Z),_t=(0,k.useRef)(A),$r=(0,k.useRef)(y),Nr=(0,k.useRef)(T),rr=(0,k.useRef)(me),Qr=(0,k.useRef)(S),Tt=(0,k.useRef)(s),Ln=(0,k.useRef)(le),Xt=(0,k.useRef)(ye),yn=(0,k.useRef)(n),Hr=(0,k.useRef)(a),Kr=(0,k.useRef)(t),Jt=(0,k.useRef)(null),Pr=(0,k.useRef)(new Map),en=(0,k.useRef)(new Map),et=(0,k.useRef)(!1),kt=(0,k.useRef)(e);kt.current=e;let[Br]=(0,k.useState)(ri);(0,k.useEffect)(()=>(et.current=!0,()=>{et.current=!1}),[]),(0,k.useEffect)(()=>{Ut.current=I},[I]),(0,k.useEffect)(()=>{Tt.current=s},[s]),(0,k.useEffect)(()=>{Fr.current=Y},[Y]),(0,k.useEffect)(()=>{tr.current=_},[_]),(0,k.useEffect)(()=>{Wt.current=Z},[Z]),(0,k.useEffect)(()=>{_t.current=A},[A]),(0,k.useEffect)(()=>{$r.current=y},[y]),(0,k.useEffect)(()=>{Nr.current=T},[T]),(0,k.useEffect)(()=>{rr.current=me},[me]),(0,k.useEffect)(()=>{Qr.current=S},[S]),(0,k.useEffect)(()=>{Ln.current=le},[le]),(0,k.useEffect)(()=>{Xt.current=ye},[ye]),(0,k.useEffect)(()=>{yn.current=n},[n]),(0,k.useEffect)(()=>{Hr.current=a},[a]),(0,k.useEffect)(()=>{Kr.current=t},[t]),(0,k.useEffect)(()=>{Ae.current=Ue},[Ue]),(0,k.useEffect)(()=>{Qe&&Ve.current?.focus()},[Qe,Ue]);let $t=(0,k.useCallback)(()=>{window.setTimeout(()=>{Ve.current?.focus()},0)},[]),nr=(0,k.useCallback)(()=>{D(!1),ot(oe=>oe+1)},[]),vr=(0,k.useCallback)(()=>{at(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);(0,k.useEffect)(()=>{!fe||!De.current||(De.current=!1,vr())},[vr,fe,Ue]);let Zt=(0,k.useCallback)((oe,xt)=>{let Q=xt?.popupBlocked??(0,ke.isPopupBlockedError)(oe);Q&&V.markBlocked();let Kt=(0,ke.buildExternalMethodRecoveryMessage)("PayPal",Q,Ee.inAppBrowser),ir=$r.current;if(ir){let Pe=Q&&Ee.inAppBrowser?new qe.FloPayError(Kt,"api_error",{code:xt?.code??"paypal_popup_blocked"}):oe;ir("paypal",Pe,xt);return}if(oe instanceof qe.FloPayError&&oe.code==="checkout_processing_timeout"){tr.current?.(oe.message);return}tr.current?.(Kt)},[V,Ee.inAppBrowser]),Ht=(0,k.useCallback)(oe=>{let xt=nt.current,Q=je.current;xt===null||!Q||(ne.log({...Q,popupCapability:V.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:oe}),ne.performance({...Q,popupCapability:V.current(),stage:"overlay_return",durationMs:ne.elapsed(xt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:oe}),nt.current=null)},[V,ne]),Rr=(0,k.useCallback)((oe,xt,Q)=>{let Kt=je.current;Ht("overlay_timeout"),Kt&&ne.error({...Kt,popupCapability:V.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Zt(xt,{...Q,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:"overlay_timeout"}),at(!0),nr(),$t()},[Ht,$t,Zt,V,it,nr,ne]),Xe=(0,k.useCallback)(()=>{V.markAvailable();let oe=je.current;oe&&(X.current=oe.attempt,ne.log({...oe,popupCapability:V.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[V,ne]),{finishAttempt:or,generationRef:Er,invalidateAttempt:Jn,isAttemptCurrent:Ur,isAttemptInvalidated:zr,startAttempt:Nn}=Pa(Rr,{onHandoffObserved:Xe}),cn=(0,k.useCallback)(()=>(at(!1),Nn("paypal")),[Nn]),ar=(0,k.useCallback)(oe=>{Jn(oe?.generation),oe?.showRetry&&at(!0),oe?.remount&&nr(),oe?.focus!==!1&&$t()},[$t,Jn,nr]),he=oe=>{let xt=Jt.current;return xt&&en.current.set(oe,xt),oe};(0,k.useEffect)(()=>{Dt.current!==He&&(Dt.current=He,pr.current=!1,Mt.current=!1,D(!1),pt(!1),be(!1),Qr.current?.("loading"))},[He]),(0,k.useEffect)(()=>{(0,Ke.invokeMerchantCallback)(()=>rr.current?.(fe&&!vt))},[fe,vt]);let Cr=(0,qe.normalizeGatewayEnvironment)(p);(0,k.useEffect)(()=>{let oe={attempt:Er.current+1,inAppBrowser:Ee.inAppBrowser,appFamily:Ee.appFamily,popupCapability:V.current(),presentationMode:it},xt=()=>({...je.current??oe,popupCapability:V.current()}),Q={error:g=>ne.error({...g,...xt()}),log:g=>ne.log({...g,...xt()}),performance:g=>ne.performance({...g,...xt()}),terminal:g=>ne.terminal({...g,...xt()}),startTiming:ne.startTiming,elapsed:ne.elapsed},Kt=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",ir=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(z(`mount clientId=${Kt} env=${p??"(unset)"}\u2192${Cr??"live"} ccy=${m} sub=${h}`),z(`ua=${ir.slice(0,80)}${ir.length>80?"\u2026":""}`),!l){z("FAIL: clientId empty \u2014 gateway misconfigured"),be(!0),Q.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!K.current){z("FAIL: containerRef not attached");return}Le.current=Q.startTiming(),Q.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=!1,Vt=!1,ae=()=>Pe||Vt,Nt=g=>{let f=et.current,O=f?g:"torn_down";f&&z(`onError ignored reason=${O}`),Br.take(kt.current)&&Q.log({name:ti,stage:"provider_ready",reason:O,provider:"paypal",paymentMethodCategory:"paypal"})},br=()=>kt.current===e?"stale_attempt":"session_changed",qr=We?Be:void 0,Qt,Un=!1,Zn=()=>{Qt=(0,qe.generateIdempotencyKey)(),Qt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Un=!0},zn=null,qn=!1,Qn=null,po=!1,mo=()=>{!Qn||po||(po=!0,Qn.close().catch(()=>{}))},Dr=!1,eo=!1,fn=K.current,zt=null,tn=null,rn=[],dn=null,nn=!1,ut=!1,mr=null,sr=g=>{if(!g||typeof g.getBoundingClientRect!="function")return"(no rect)";let f=g.getBoundingClientRect();return`${Math.round(f.width)}\xD7${Math.round(f.height)}`},Yr=g=>{if(!g)return"(empty)";try{let f=new URL(g,typeof window>"u"?"https://localhost":window.location.href),O=f.pathname.toLowerCase();return O.includes("checkcaptcha")||O.includes("captcha")?`CAPTCHA(${f.host}${O})`:O.includes("risk")||O.includes("challenge")?`RISK(${f.host}${O})`:O.includes("smart/buttons")?`smart-buttons(${f.host})`:`${f.host}${O}`.slice(0,100)}catch{return g.slice(0,80)}},ho=g=>{let f=g.getAttribute("src"),O=g.getAttribute("srcdoc"),Ce=g.getAttribute("name"),_e=g.getAttribute("sandbox"),L=[];return f&&L.push(`src=${Yr(f)}`),O&&L.push(`srcdoc[${O.length}ch]`),!f&&!O&&L.push("src=(empty) srcdoc=(empty)"),Ce&&L.push(`name=${Ce.slice(0,40)}`),_e!==null&&L.push(`sandbox="${_e.slice(0,40)}"`),L.join(" ")},to=g=>{if(!(g instanceof HTMLIFrameElement))return"";try{let f=g.contentDocument;if(!f)return"cd=null";let O=f.body?.children.length??0,Ce=f.body?.innerHTML.length??0,_e=f.head?.innerHTML.length??0;return`cd=same-origin readyState=${f.readyState} body[${O}children,${Ce}ch] head[${_e}ch]`}catch(f){return`cd=cross-origin(${f.message.slice(0,30)})`}},In=[],un=g=>{if(ae())return;let f=g.message??String(g.error??"(no message)");f&&(f.toLowerCase().includes("paypal")||f.toLowerCase().includes("zoid")||f.toLowerCase().includes("postrobot")||f.toLowerCase().includes("storage"))&&(z(`window:error ${f.slice(0,140)}`),In.push(f))},Ir=g=>{if(ae())return;let f=g.reason instanceof Error?g.reason.message:String(g.reason??"(no reason)");f&&(f.toLowerCase().includes("paypal")||f.toLowerCase().includes("zoid")||f.toLowerCase().includes("postrobot")||f.toLowerCase().includes("storage"))&&(z(`window:rejection ${f.slice(0,140)}`),In.push(f))},ro={value:0},jr=()=>{zt?.disconnect(),zt=null,tn?.disconnect(),tn=null;for(let g of rn.splice(0))clearTimeout(g);ut=!1,nn&&typeof window<"u"&&(window.removeEventListener("error",un),window.removeEventListener("unhandledrejection",Ir)),nn=!1},q=()=>{if(!(nn||ae()||Dr)){if(nn=!0,In.length=0,ro.value=0,typeof window<"u"&&(window.addEventListener("error",un),window.addEventListener("unhandledrejection",Ir)),typeof PerformanceObserver<"u")try{tn=new PerformanceObserver(g=>{if(!ae())for(let f of g.getEntries()){if(!f.name.toLowerCase().includes("paypal"))continue;ro.value+=1;let O=Math.round(f.duration);z(`net ${O}ms ${f.name.slice(0,90)}`)}}),tn.observe({type:"resource",buffered:!0})}catch{}mr?.()}},j=()=>{dn&&(clearTimeout(dn),dn=null)},ie=()=>{jr(),j()},we={setEnabled:g=>{g?q():jr()}};W.current=we,U.current&&q();let mt=qe.isPayPalTeardownMessage,Gt=g=>{if(ae()||mt(g))return;let f=(0,So.applyFriendlyMessageOverride)(g)??g;(0,Ke.invokeMerchantCallback)(()=>tr.current?.(f))},Ie=(g,f)=>{if(Pe||qn)return;qn=!0,Vt=!0,ie(),mo();let O=gd({kind:g,generationActive:!0,automaticRetryAllowed:xe,automaticRetryUsed:pr.current});if(O.action==="retry"){pr.current=!0,D(!1),gt(!1),pt(!0),Qr.current?.("retrying"),zn=setTimeout(()=>{Pe||ot(Ce=>Ce+1)},pd);return}if(D(!1),gt(!1),pt(!1),be(!0),O.action!=="ignore"){if(Qr.current?.("exhausted"),O.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",f);return}if(O.report){let Ce=(0,ke.classifyExternalMethodFailure)({code:Bl(g,f),message:f},{inAppBrowser:Ee.inAppBrowser,handoffObserved:!1});Ce.popupBlocked&&V.markBlocked(),Q.error({errorCode:Ce.popupBlocked?Ce.errorCode:O.report.errorCode,stage:O.report.stage,operationOutcome:O.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:Ce.terminalReason})}Mt.current||(Mt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Bl(g,f)))}};be(!1);let de=async(g,f=Jt.current)=>{if(ae())return;let O=f?.sessionId??e;if(Ut.current){await Ut.current(g,{sessionId:O,accountPatch:f?.accountPatch,nonce:f?.nonce});return}let Ce=Q.startTiming();Q.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let _e=()=>{Q.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"processing",durationMs:Q.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let L=(0,qe.buildPayPalProcessPaymentRequest)({body:g,sessionId:O,nonce:f?.nonce??Kr.current,accountPatch:f?.accountPatch,session:Xt.current,email:yn.current}),yr=await new oi.PaymentAPI(It,{telemetry:!1}).processPayment(L.userId,L.params);if(yr.ok){if(Vt||Pe&&et.current)return;_e(),Q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ke.invokeMerchantCallback)(()=>Fr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ae())return;let Tr=await yr.json().catch(()=>null),bt=(0,qe.describePayPalProcessFailure)(Tr),pn=bt.message;_e(),yr.status===400&&(typeof Tr?.declineCode=="string"||!Array.isArray(Tr?.fields))?Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):yr.status===400||yr.status===422?Q.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):Q.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:hd(yr.status),failureCategory:yr.status>=500?"server_error":void 0}),Gt(pn),(0,Ke.invokeMerchantCallback)(()=>Wt.current?.(Sr("paypal",pn,{code:bt.code,declineCode:bt.declineCode})));return}catch(L){if(ae())return;_e(),Q.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ct=(0,qe.friendlyPayPalFailureMessage)(L instanceof Error?L.message:void 0);Gt(Ct),(0,Ke.invokeMerchantCallback)(()=>Wt.current?.(Sr("paypal",Ct)));return}},ee=()=>new qe.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ve=g=>ae()?Promise.reject(ee()):Promise.resolve(g),te=async g=>{if(g.ok){Q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ke.invokeMerchantCallback)(()=>Fr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let f=await g.json().catch(()=>null),O=(0,qe.describePayPalProcessFailure)(f);Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ke.invokeMerchantCallback)(()=>Wt.current?.(Sr("paypal",O.message,{code:O.code,declineCode:O.declineCode})))},tt=()=>{let g=Jt.current;Ht("approved"),g&&(Pr.current.delete(g.surfaceKey),or(g.generation)),Jt.current=null},re=async g=>{if(ae())throw ee();Un||Zn();let f=Jt.current,O=f?.sessionId??e,Ce=f?.nonce??Kr.current;Q.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let _e;try{_e=await new oi.PaymentAPI(It,{telemetry:!1}).createSessionIntent(O,Ce??"",(0,qe.buildPayPalSessionIntentRequest)(qr),{idempotencyKey:Qt})}catch(L){throw Q.error({...(0,qe.classifyTelemetryFailure)(L,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),L}if(ae())throw ee();if((0,qe.isSettledSessionIntent)(_e))throw await te(_e.response),tt(),new qe.FloPayError("PayPal checkout already settled.","api_error",{code:Fl});if(_e.provider!=="paypal"||_e.providerObjectType!==Be)throw new Error(g);return Q.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),_e.providerObjectId},Je=(g,f)=>{let O=f?.nonce??Kr.current;if(!O)return;let Ce=f?.sessionId??e,_e=(0,qe.resolvePayPalDeclineReason)(g);new oi.PaymentAPI(It,{telemetry:!1}).reportSessionIntentDecline(Ce,O,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:_e}).catch(()=>{})},Ze=Ue;z("loadScript:scheduled (deferred 1 tick)");let At=null,_r=setTimeout(()=>{if(Pe){z("loadScript:skipped (cancelled before defer ran)");return}z("loadScript:start");let g=Cr==="live"?"production":Cr,f={};Be==="subscription"?f={intent:"subscription",vault:!0}:Be==="order"&&(f={intent:"capture"}),At=(0,Dl.loadScript)({clientId:l,currency:m,...f,...g?{environment:g}:{},...g==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let O=!1;At.then(Ce=>{if(O=!0,z(`loadScript:resolved inactive=${ae()} ns=${!!Ce} buttons=${!!Ce?.Buttons}`),ae())return;if(!Ce?.Buttons){z("FAIL: namespace missing Buttons factory"),Ie("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}Q.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"provider_ready",durationMs:Q.elapsed(Le.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Q.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let _e=async(se,ht)=>{if(ae()||Ae.current!==Ze)return;let Rt=se.vaultSetupToken??se.subscriptionID??se.orderID??"",Ft=Rt?en.current.get(Rt):Pr.current.get(Ze);if(!(!Ft||!Ur(Ft.generation))&&or(Ft.generation)){en.current.delete(Rt),Pr.current.delete(Ft.surfaceKey),Ht("approved");try{if(gt(!0),(0,Ke.invokeMerchantCallback)(()=>tr.current?.(null)),!Rt)throw new qe.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let rt=(0,qe.resolvePayPalApprovalIdentity)({accountPatch:Ft.accountPatch,email:yn.current,billingName:Hr.current,session:Xt.current});if((0,qe.needsPayPalPayerDetails)(rt))try{rt=(0,qe.mergePayPalPayerIdentity)(rt,await ht?.order?.get?.())}catch{}if((Tt.current||Se)&&!(0,qe.isValidEmail)(rt.email)){let Ot=await N("PayPal",rt);if(!Ot)return;rt=Ot}(0,qe.isValidEmail)(rt.email)&&(Ft.accountPatch=(0,vn.compactBuyerIdentity)({...Ft.accountPatch,...rt}),await Tt.current?.(rt));let Xr=(0,qe.buildPayPalTokenizedBody)(Rt,qr);await de(Xr,Ft)}catch(rt){Gt(rt instanceof Error?rt.message:"PayPal capture failed.")}finally{ae()||gt(!1)}}},L=se=>{let ht=pe?()=>ve(pe):()=>re(se);return async()=>he(await ht())},Ct=Ce.Buttons({style:{layout:"horizontal",height:ai,tagline:!1},...it==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(se,ht)=>{if(ae()){await ht.reject();return}Zn();let Rt=Ln.current,Ft={};if(Rt)try{let Ot=await Rt("paypal");if(ae()){await ht.reject();return}if(!Ot.proceed){Jt.current=null,Pr.current.delete(Ze),await ht.reject();return}Ft={sessionId:Ot.sessionId,accountPatch:Ot.accountPatch,nonce:Ot.nonce}}catch(Ot){z(`onClick:runBeforeButtonClick rejected msg=${(Ot instanceof Error?Ot.message:String(Ot)).slice(0,120)}`),Jt.current=null,Pr.current.delete(Ze),await ht.reject();return}(0,Ke.invokeMerchantCallback)(()=>Nr.current?.("paypal"));let rt=cn(),Xr={generation:rt,surfaceKey:Ze,...Ft};Jt.current=Xr,Pr.current.set(Ze,Xr),je.current={...oe,attempt:rt},await ht.resolve(),Q.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Q.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nt.current=Q.startTiming()},createOrder:Be==="order"?L("Failed to create PayPal order."):void 0,createSubscription:Be==="subscription"?L("Failed to create PayPal subscription."):void 0,createVaultSetupToken:Be==="setup_token"?async()=>he(await re("Failed to create PayPal setup token.")):void 0,onApprove:_e,onCancel:()=>{if(ae())return;let se=Pr.current.get(Ze)??Jt.current,ht=se&&Ur(se.generation)?(0,qe.buildPayPalCancelEvent)(se.sessionId??e,qr):null;se&&Pr.current.delete(se.surfaceKey),Jt.current=null,Ht("cancelled"),Q.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),De.current=!0,ar({generation:se?.generation,remount:!0,focus:!1}),ht&&(0,Ke.invokeMerchantCallback)(()=>_t.current?.(ht))},onError:se=>{if(se instanceof qe.FloPayError&&se.code===Fl)return;let ht=se instanceof Error?se.message:"PayPal failed to render.";if(ae()||Ae.current!==Ze){mt(ht)||Nt(br());return}if(Dr){let Rt=Pr.current.get(Ze)??Jt.current;if(!Rt||!Ur(Rt.generation)){if(mt(ht)){!Rt&&!zr()&&or();return}Nt(Rt||zr()?"stale_attempt":"no_current_attempt");return}if(z(`onError rendered=${Dr} msg=${ht.slice(0,120)}`),mt(ht)){or(Rt.generation);return}let{errorCode:Ft,popupBlocked:rt,providerDeclined:Xr,terminalReason:Ot}=(0,ke.classifyExternalMethodFailure)(se,{inAppBrowser:Ee.inAppBrowser,handoffObserved:X.current===Rt.generation});if(rt&&V.markBlocked(),Ht(Ot),Xr){Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ot}),Je(se,Rt),(0,Ke.invokeMerchantCallback)(()=>Wt.current?.(Sr("paypal",ht))),Pr.current.delete(Rt.surfaceKey),Jt.current=null,or(Rt.generation);return}Q.error({errorCode:Ft,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ot}),Pr.current.delete(Rt.surfaceKey),Jt.current=null,ar({generation:Rt.generation,remount:!0,showRetry:!0,focus:!0}),Zt(se,{code:"paypal_runtime_failed",popupBlocked:rt,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:Ot});return}z(`onError rendered=${Dr} msg=${ht.slice(0,120)}`),Ie(mt(ht)?"teardown":"pre_ready_callback",ht)}}),yr=Ct.isEligible();if(z(`isEligible=${yr}`),Q.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!yr){D(!1),Ie("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}eo=!0,Qn=Ct,mr=()=>{if(!nn||ut||ae()||Dr)return;ut=!0,z(`container:dims ${sr(fn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(zt=new MutationObserver(ht=>{if(!ae()){for(let Rt of ht)if(Rt.type==="childList")Rt.addedNodes.forEach(Ft=>{if(!(Ft instanceof Element))return;let rt=Ft.tagName.toLowerCase(),Xr=(Ft.getAttribute("title")??"").slice(0,40),Ot=rt==="iframe"?` ${ho(Ft)}`:"";z(`child+ ${rt}${Xr?` title="${Xr}"`:""}${Ot} dims=${sr(Ft)}`)});else if(Rt.type==="attributes"&&Rt.target instanceof Element){let Ft=Rt.target;if(Ft.tagName.toLowerCase()!=="iframe")continue;let rt=Rt.attributeName;(rt==="src"||rt==="srcdoc")&&z(`attr~ iframe ${rt}=${rt==="srcdoc"?`[${(Ft.getAttribute("srcdoc")??"").length}ch]`:Yr(Ft.getAttribute("src"))} dims=${sr(Ft)}`)}}}),zt.observe(fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let se=ht=>{if(ae()||Dr)return;let Rt=fn.querySelectorAll("iframe"),Ft=typeof document<"u"&&"hasStorageAccess"in document;z(`watchdog:${ht} container=${sr(fn)} children=${fn.childElementCount} iframes=${Rt.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Ft} paypalNetRequests=${ro.value}`),Rt.forEach((rt,Xr)=>{let Ot=(rt.getAttribute("title")??"").slice(0,40);z(` iframe[${Xr}] ${sr(rt)}${Ot?` title="${Ot}"`:""} ${ho(rt)}`);let Vr=to(rt);Vr&&z(` ${Vr}`)}),In.length===0&&z(" (no PayPal/zoid window errors captured)")};rn.push(setTimeout(()=>se("3s"),3e3)),rn.push(setTimeout(()=>se("8s"),8e3)),rn.push(setTimeout(()=>se("15s"),15e3))},mr(),z("render:start");let bt=Q.startTiming();dn=setTimeout(()=>{ae()||Dr||(z("watchdog:11s retryable render timeout"),Ie("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},md);let pn=Ct.render(fn);(async()=>{try{if(await pn,z(`render:resolved inactive=${ae()}`),ie(),ae()){mo();return}Dr=!0,D(!0),pt(!1),Qr.current?.("ready"),Q.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"checkout_render",durationMs:Q.elapsed(bt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(se){let ht=se instanceof Error?se.message:"PayPal failed to render.";z(`render:rejected msg=${ht.slice(0,120)}`),ie(),Ie(mt(ht)?"teardown":"render_rejected",ht)}})()}).catch(Ce=>{let _e=Ce instanceof Error?Ce.message:"PayPal operation failed.";z(`provider:failed msg=${_e.slice(0,120)}`);let L="script_rejected";O&&mt(_e)?L="teardown":O&&eo&&(L="render_rejected"),Ie(L,_e)})},0);return()=>{Pe=!0,clearTimeout(_r),zn&&clearTimeout(zn),ie(),W.current===we&&(W.current=null),mo(),nt.current=null,je.current=null}},[xe,It,l,m,p,Be,it,We,e,pe,Ue,ne,N,Se,z,Ht]);let Gr=B?(0,Cn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:vt?"#fef2f2":"#f3f4f6",border:`1px solid ${vt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${fe} failed=${vt})`,ce.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${se.join(`
4
- `)}`]}):null;return Ct&&!c?B?(0,yn.jsx)("div",{children:ye}):null:(0,yn.jsxs)("div",{children:[ye,pt&&(0,yn.jsx)(qo,{identity:pt.identity,methodLabel:pt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ae,onCancel:()=>Ae(null)}),(0,yn.jsxs)("div",{"aria-hidden":Pe||pt?!0:void 0,style:Pe||pt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Qa},children:[!fe&&!Pe&&(0,yn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,yn.jsx)("div",{ref:X,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Qa,display:"flex",opacity:fe?1:0},"aria-busy":T||P},Le)]},Le),et&&(0,yn.jsx)("button",{ref:je,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Gt,style:ad,children:"Try PayPal again"})]})}function ha(e){return(0,yn.jsx)(El,{...e})}function Il(e){return(0,yn.jsx)(El,{...e})}var Pa=require("react/jsx-runtime");function Wo({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,Pa.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...r?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...n??{}},children:[r&&(0,Pa.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Pa.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var ft=require("@flopay/shared");var gr=require("react/jsx-runtime");var cd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function Zr({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:i="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:p=cd}){let m={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,gr.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,gr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...p.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,gr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,gr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,gr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,gr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,gr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,gr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,gr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,gr.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,gr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,gr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,gr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,gr.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,gr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:p.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&l!==null&&(0,gr.jsx)("p",{style:m,children:l}),e==="error"&&t&&(0,gr.jsx)("p",{style:m,children:t}),(0,gr.jsx)("style",{children:`
3
+ ${ce.join(`
4
+ `)}`]}):null;return vt&&!c?B?(0,Cn.jsx)("div",{children:Gr}):null:(0,Cn.jsxs)("div",{children:[Gr,ct&&(0,Cn.jsx)(Wo,{identity:ct.identity,methodLabel:ct.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Fe,onCancel:()=>Fe(null)}),(0,Cn.jsxs)("div",{"aria-hidden":ge||ct?!0:void 0,style:ge||ct?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ai},children:[!fe&&!ge&&(0,Cn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,Cn.jsx)("div",{ref:K,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ai,display:"flex",opacity:fe?1:0},"aria-busy":M||P},Ue)]},Ue),Qe&&(0,Cn.jsx)("button",{ref:Ve,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:vr,style:yd,children:"Try PayPal again"})]})}function va(e){return(0,Cn.jsx)(Ol,{...e})}function Ll(e){return(0,Cn.jsx)(Ol,{...e})}var Ca=require("react/jsx-runtime");function Ko({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,Ca.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...r?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...n??{}},children:[r&&(0,Ca.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Ca.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var yt=require("@flopay/shared");var hr=require("react/jsx-runtime");var Pd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function sn({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:s="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:p=Pd}){let m={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,hr.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,hr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...p.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,hr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,hr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,hr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,hr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,hr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,hr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,hr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,hr.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,hr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,hr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,hr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,hr.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,hr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:p.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&s]}),e==="success"&&l!==null&&(0,hr.jsx)("p",{style:m,children:l}),e==="error"&&t&&(0,hr.jsx)("p",{style:m,children:t}),(0,hr.jsx)("style",{children:`
5
5
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
6
6
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
7
7
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
8
8
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
9
- `})]})})}var _l=require("@flopay/shared"),Mr=require("react");var Tl=require("react/jsx-runtime");function va({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[i,l]=(0,Mr.useState)(e instanceof Promise?null:e),[p,m]=(0,Mr.useState)(t instanceof Promise||!t?null:t),h=(0,Mr.useRef)(null),w=(0,Mr.useRef)(null),S=Vo(n);(0,Mr.useEffect)(()=>{S({class:"lifecycle",name:"checkout.mount"})},[S]),(0,Mr.useEffect)(()=>{i&&S({class:"lifecycle",name:"sdk.initialize.ready"})},[S,i]),(0,Mr.useEffect)(()=>{if(i)return kr(i)?.subscribe?.(S)},[S,i]),(0,Mr.useEffect)(()=>{if(!(!p||p===i))return kr(p)?.subscribe?.(S)},[S,i,p]),(0,Mr.useEffect)(()=>{if(!i)return;let I=kr(i);return h.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Mr.useEffect)(()=>{let I=!1;return e instanceof Promise?e.then(ee=>{I||l(ee)},()=>{I||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{I=!0}},[S,e]),(0,Mr.useEffect)(()=>{let I=!1;if(!t){m(null);return}return t instanceof Promise?t.then(ee=>{I||m(ee)},()=>{I||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{I=!0}},[S,t]),(0,Mr.useEffect)(()=>{if(!i||w.current===i)return;w.current=i;let I=kr(i);I?.log({name:"checkout.rendered",stage:"checkout_render"}),S({class:"lifecycle",name:"checkout.rendered"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(h.current??0),durationMode:"machine"})},[S,i]);let E=(0,_l.resolveBillingApiUrl)(r?.billingApiUrl),Y=(0,Mr.useMemo)(()=>({flopay:i,paypalFlopay:p,billingApiUrl:E,emitInstrument:S}),[i,p,E,S]);return(0,Tl.jsx)(pn.Provider,{value:Y,children:a})}var _n=require("@flopay/shared");async function ei(e,t){e.current?.abort();let r=new AbortController;e.current=r;try{return await t(r.signal)}finally{e.current===r&&(e.current=null)}}var fn=require("@flopay/js"),st=require("@flopay/shared");var ba="card";async function dd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function ud(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,r);return{error:i,intent:a??null}}function $o(e){return new st.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function pd(){return new st.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Zi(e,t){return Object.assign(e,{checkoutMethod:t})}function eo(e,t){let r=e instanceof st.FloPayError?e:new st.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ca(e,t){try{return await e()}catch(r){throw eo(r,t)}}function xl(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Al(e){return(0,fn.runSavedCardChallenge)(e)}async function Ho(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,i=t.nonce??t.session.clientSecret,l=new fn.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,fn.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:w=>qn({type:w.declineReason??"authorization_declined",gatewayErrorCode:w.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(w){if(a.aborted||w instanceof Error&&w.name==="AbortError")throw w instanceof st.FloPayError&&w.code==="three_ds_aborted"?w:$o(w);if(!(w instanceof st.FloPayError)||w.code!=="three_ds_timeout"&&w.code!=="checkout_processing_timeout")throw w;try{m=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:i,statusUrl:p,timeoutMs:5e3,signal:a})}catch(E){if(a.aborted)throw $o(E);if(!(E instanceof st.FloPayError)||E.code!=="checkout_processing_timeout")throw E}let S=m&&lo(m,t.session);if(!Jn(S)&&S?.status!=="expired"){if(t.telemetry){let E=new fn.PaymentAPI(r);try{E.reportThreeDsAbandoned(n)}finally{E.destroy()}}throw pd()}}let h=m&&lo(m,t.session);if(!Jn(h))throw No(h);return{...Xn(h,n),checkoutMethod:"card"}}function qn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=(0,vo.applyFriendlyMessageOverride)(a)??a,l=Zi(new st.FloPayError(i,"api_error",{code:e?.code??(0,st.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,st.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(l.orderId=e.orderId),l}function Ji(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Fl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ti(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let p of i)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||ti(p)))return p;let l=a.gateways;if(l&&typeof l=="object"){let p=l.stripe;if(p&&typeof p=="object"){let m=p,h=[m.stripeClientSecret,m.clientSecret];for(let w of h)if(typeof w=="string"&&w.length>0&&(!t?.requirePaymentIntentClientSecret||ti(w)))return w}}}}async function md({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Fl(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let p=(await new fn.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(ti(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function Ko({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:i,telemetry:l}){let p=e.replace(/\/+$/,""),m=t??r.id,h=n??r.clientSecret,w=r.customer?.id??r.accountData?.userId??"",S=r.customer?.email??r.accountData?.email??"",E=r.customer?.firstName??r.accountData?.firstName??"",Y=r.customer?.lastName??r.accountData?.lastName??"",I=r.customer?.country??r.accountData?.country??void 0,ee=r.customer?.zip??r.accountData?.zip??void 0,f=await new fn.PaymentAPI(p,l===!1?{telemetry:!1}:void 0).processPayment(w,{sessionId:m,nonce:h,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:w,email:S,firstName:E,lastName:Y,country:I,zip:ee},returnUrl:i??Ji(r)});if(f.ok){let b=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,st.isAuthorizationOnlySession)(r)||b?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof b?.paymentId=="string"?b.paymentId:r.paymentId,sessionId:typeof b?.sessionId=="string"?b.sessionId:m,authorizationExpiresAt:typeof b?.authorizationExpiresAt=="string"?b.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:ma(a),checkoutMethod:Ml(a,r)}};let Ie=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Ie?{paymentIntentId:Ie}:{},paymentMethodId:ma(a),checkoutMethod:Ml(a,r)}}}let P;try{P=await f.json()}catch(b){throw new st.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:b})}if(P?.type==="3ds_required"&&typeof P.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:P.nextActionRedirectUrl};if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let b=Fl(P);if(!b)throw new st.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:P.type,threeDSecureToken:b,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let b=await md({billingApiUrl:p,sessionId:m,nonce:h,responseJson:P});if(b)return b;throw Zi(new st.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let pe=new st.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:f.status});throw Object.assign(pe,{telemetryOutcome:(0,st.classifyPaymentRejection)(f.status,P)})}async function ri(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:i,session:l,returnUrl:p,telemetry:m,signal:h}){let w=t?.getRawProvider();if(!w)throw eo(new st.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw Zi(new st.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let S=(0,st.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,Y=e.paymentMethodId,I=await Ca(()=>dd(w,e.threeDSecureToken,S),"card");if(I){if(I.error)throw eo(new st.FloPayError(I.error.message??`Failed to retrieve 3DS ${S?"setup":"payment"} status.`,"api_error",{code:I.error.code}),"card");let x=I.intent;!Y&&x?.payment_method&&(typeof x.payment_method=="string"?Y=x.payment_method:"id"in x.payment_method&&(Y=x.payment_method.id??void 0))}let ee=Y?await Ca(()=>ud(w,e.threeDSecureToken,{payment_method:Y,return_url:p??Ji(l)??window.location.href},S),"card"):null;if(ee){if(ee.error)throw eo(new st.FloPayError(ee.error.message??"3DS authentication failed.","api_error",{code:ee.error.code}),"card");E=ee.intent}else{let x=await Ca(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(x.error)throw eo(new st.FloPayError(x.error.message??"3DS authentication failed.","api_error",{code:x.error.code}),"card");E=(S?x.setupIntent:x.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let x=await Ko({billingApiUrl:a,sessionId:i,session:l,telemetry:m,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:p});return x.type==="success"?{...x.result,paymentIntentId:x.result.paymentIntentId??E.id,paymentMethodId:x.result.paymentMethodId??Y}:x.type==="next_action_required"?Ho(x,{billingApiUrl:a,sessionId:i??l.id,session:l,signal:h}):ri(x,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:i,session:l,returnUrl:p,telemetry:m,signal:h})}throw eo(new st.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let S=(r??t)?.getRawProvider();if(!S)throw eo(new st.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:Y}=await Ca(()=>S.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(Y)throw eo(new st.FloPayError(Y.message??"PayPal authorization failed.","api_error",{code:Y.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await Ca(()=>S.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??Ji(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(E)throw eo(new st.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new st.FloPayError("Unsupported payment redirect state.","api_error")}function Sa(e){if(e instanceof st.FloPayError){let n=(0,vo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new st.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,vo.applyFriendlyMessageOverride)(t)??t;return new st.FloPayError(r,"api_error")}function Qi(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,st.isMountableVaultBlock)(e.data.session?.vault)||(0,Rn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new st.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Ml(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Rn.canRecoverHostedCardForm)(t)?"card":void 0}async function es({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[l,p]=await Promise.all([(0,fn.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),i?(0,fn.loadFloPay)(i,{billingApiUrl:r,locale:n,telemetry:a}).catch(h=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",h),null)):Promise.resolve(null)]);if(!l)throw new st.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return i?m=p:t&&(m=l),{flopay:l,paypalFlopay:m}}var Mn=require("@flopay/js"),d=require("@flopay/shared"),rr=require("@stripe/react-stripe-js"),o=Wi(require("react"),1);function Go(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ni(e,t){if(e)return{error:r=>e.error(Go(t,r)),log:r=>e.log(Go(t,r)),performance:r=>e.performance(Go(t,r)),terminal:r=>e.terminal(Go(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var to=require("@flopay/shared"),Dl=require("react");var Bl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var Rr=require("react/jsx-runtime"),yd=`
9
+ `})]})})}var Nl=require("@flopay/shared"),Lr=require("react");var Ul=require("react/jsx-runtime");function ba({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,l]=(0,Lr.useState)(e instanceof Promise?null:e),[p,m]=(0,Lr.useState)(t instanceof Promise||!t?null:t),h=(0,Lr.useRef)(null),R=(0,Lr.useRef)(null),w=Ho(n);(0,Lr.useEffect)(()=>{w({class:"lifecycle",name:"checkout.mount"})},[w]),(0,Lr.useEffect)(()=>{s&&w({class:"lifecycle",name:"sdk.initialize.ready"})},[w,s]),(0,Lr.useEffect)(()=>{if(s)return wr(s)?.subscribe?.(w)},[w,s]),(0,Lr.useEffect)(()=>{if(!(!p||p===s))return wr(p)?.subscribe?.(w)},[w,s,p]),(0,Lr.useEffect)(()=>{if(!s)return;let _=wr(s);return h.current=_?.beginCheckout()??_?.now()??0,_?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{_?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Lr.useEffect)(()=>{let _=!1;return e instanceof Promise?e.then(Z=>{_||l(Z)},()=>{_||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{_=!0}},[w,e]),(0,Lr.useEffect)(()=>{let _=!1;if(!t){m(null);return}return t instanceof Promise?t.then(Z=>{_||m(Z)},()=>{_||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{_=!0}},[w,t]),(0,Lr.useEffect)(()=>{if(!s||R.current===s)return;R.current=s;let _=wr(s);_?.log({name:"checkout.rendered",stage:"checkout_render"}),w({class:"lifecycle",name:"checkout.rendered"}),_?.performance({stage:"checkout_render",durationMs:_.elapsed(h.current??0),durationMode:"machine"})},[w,s]);let I=(0,Nl.resolveBillingApiUrl)(r?.billingApiUrl),Y=(0,Lr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:I,emitInstrument:w}),[s,p,I,w]);return(0,Ul.jsx)(Pn.Provider,{value:Y,children:a})}var Bn=require("@flopay/shared");async function ii(e,t){e.current?.abort();let r=new AbortController;e.current=r;try{return await t(r.signal)}finally{e.current===r&&(e.current=null)}}var bn=require("@flopay/js"),st=require("@flopay/shared");var wa="card";async function vd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function Cd(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:s}=await e.confirmCardPayment(t,r);return{error:s,intent:a??null}}function Go(e){return new st.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function bd(){return new st.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function rs(e,t){return Object.assign(e,{checkoutMethod:t})}function so(e,t){let r=e instanceof st.FloPayError?e:new st.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Sa(e,t){try{return await e()}catch(r){throw so(r,t)}}function ql(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function jl(e){return(0,bn.runSavedCardChallenge)(e)}async function Yo(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,l=new bn.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,bn.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:R=>Kn({type:R.declineReason??"authorization_declined",gatewayErrorCode:R.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(R){if(a.aborted||R instanceof Error&&R.name==="AbortError")throw R instanceof st.FloPayError&&R.code==="three_ds_aborted"?R:Go(R);if(!(R instanceof st.FloPayError)||R.code!=="three_ds_timeout"&&R.code!=="checkout_processing_timeout")throw R;try{m=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(I){if(a.aborted)throw Go(I);if(!(I instanceof st.FloPayError)||I.code!=="checkout_processing_timeout")throw I}let w=m&&fo(m,t.session);if(!oo(w)&&w?.status!=="expired"){if(t.telemetry){let I=new bn.PaymentAPI(r);try{I.reportThreeDsAbandoned(n)}finally{I.destroy()}}throw bd()}}let h=m&&fo(m,t.session);if(!oo(h))throw qo(h);return{...no(h,n),checkoutMethod:"card"}}function Kn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,s=(0,So.applyFriendlyMessageOverride)(a)??a,l=rs(new st.FloPayError(s,"api_error",{code:e?.code??(0,st.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,st.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(l.orderId=e.orderId),l}function ts(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function si(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Vl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||si(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,s=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let p of s)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||si(p)))return p;let l=a.gateways;if(l&&typeof l=="object"){let p=l.stripe;if(p&&typeof p=="object"){let m=p,h=[m.stripeClientSecret,m.clientSecret];for(let R of h)if(typeof R=="string"&&R.length>0&&(!t?.requirePaymentIntentClientSecret||si(R)))return R}}}}async function Sd({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Vl(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let p=(await new bn.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(si(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function Xo({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:l}){let p=e.replace(/\/+$/,""),m=t??r.id,h=n??r.clientSecret,R=r.customer?.id??r.accountData?.userId??"",w=r.customer?.email??r.accountData?.email??"",I=r.customer?.firstName??r.accountData?.firstName??"",Y=r.customer?.lastName??r.accountData?.lastName??"",_=r.customer?.country??r.accountData?.country??void 0,Z=r.customer?.zip??r.accountData?.zip??void 0,y=await new bn.PaymentAPI(p,l===!1?{telemetry:!1}:void 0).processPayment(R,{sessionId:m,nonce:h,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:R,email:w,firstName:I,lastName:Y,country:_,zip:Z},returnUrl:s??ts(r)});if(y.ok){let S=typeof y.json=="function"?await y.json().catch(()=>null):null;if((0,st.isAuthorizationOnlySession)(r)||S?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof S?.paymentId=="string"?S.paymentId:r.paymentId,sessionId:typeof S?.sessionId=="string"?S.sessionId:m,authorizationExpiresAt:typeof S?.authorizationExpiresAt=="string"?S.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:fa(a),checkoutMethod:zl(a,r)}};let xe=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...xe?{paymentIntentId:xe}:{},paymentMethodId:fa(a),checkoutMethod:zl(a,r)}}}let P;try{P=await y.json()}catch(S){throw new st.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status,cause:S})}if(P?.type==="3ds_required"&&typeof P.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:P.nextActionRedirectUrl};if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let S=Vl(P);if(!S)throw new st.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status});return{type:P.type,threeDSecureToken:S,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let S=await Sd({billingApiUrl:p,sessionId:m,nonce:h,responseJson:P});if(S)return S;throw rs(new st.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new st.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:y.status});throw Object.assign(me,{telemetryOutcome:(0,st.classifyPaymentRejection)(y.status,P)})}async function li(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:l,returnUrl:p,telemetry:m,signal:h}){let R=t?.getRawProvider();if(!R)throw so(new st.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw rs(new st.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let w=(0,st.isSetupIntentClientSecret)(e.threeDSecureToken),I=null,Y=e.paymentMethodId,_=await Sa(()=>vd(R,e.threeDSecureToken,w),"card");if(_){if(_.error)throw so(new st.FloPayError(_.error.message??`Failed to retrieve 3DS ${w?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let A=_.intent;!Y&&A?.payment_method&&(typeof A.payment_method=="string"?Y=A.payment_method:"id"in A.payment_method&&(Y=A.payment_method.id??void 0))}let Z=Y?await Sa(()=>Cd(R,e.threeDSecureToken,{payment_method:Y,return_url:p??ts(l)??window.location.href},w),"card"):null;if(Z){if(Z.error)throw so(new st.FloPayError(Z.error.message??"3DS authentication failed.","api_error",{code:Z.error.code}),"card");I=Z.intent}else{let A=await Sa(()=>R.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(A.error)throw so(new st.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");I=(w?A.setupIntent:A.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let A=await Xo({billingApiUrl:a,sessionId:s,session:l,telemetry:m,tokenizedData:{id:I.id,type:"card",threeDSecureActionResultTokenId:I.id},returnUrl:p});return A.type==="success"?{...A.result,paymentIntentId:A.result.paymentIntentId??I.id,paymentMethodId:A.result.paymentMethodId??Y}:A.type==="next_action_required"?Yo(A,{billingApiUrl:a,sessionId:s??l.id,session:l,signal:h}):li(A,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:l,returnUrl:p,telemetry:m,signal:h})}throw so(new st.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let w=(r??t)?.getRawProvider();if(!w)throw so(new st.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:Y}=await Sa(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(Y)throw so(new st.FloPayError(Y.message??"PayPal authorization failed.","api_error",{code:Y.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:I}=await Sa(()=>w.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??ts(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(I)throw so(new st.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new st.FloPayError("Unsupported payment redirect state.","api_error")}function ka(e){if(e instanceof st.FloPayError){let n=(0,So.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new st.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,So.applyFriendlyMessageOverride)(t)??t;return new st.FloPayError(r,"api_error")}function ns(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,st.isMountableVaultBlock)(e.data.session?.vault)||(0,xn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new st.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function zl(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,xn.canRecoverHostedCardForm)(t)?"card":void 0}async function os({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let s=t&&t!==e?t:void 0,[l,p]=await Promise.all([(0,bn.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,bn.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(h=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",h),null)):Promise.resolve(null)]);if(!l)throw new st.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=l),{flopay:l,paypalFlopay:m}}var On=require("@flopay/js"),d=require("@flopay/shared"),cr=require("@stripe/react-stripe-js"),o=Gi(require("react"),1);function Ro(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ci(e,t){if(e)return{error:r=>e.error(Ro(t,r)),log:r=>e.log(Ro(t,r)),performance:r=>e.performance(Ro(t,r)),terminal:r=>e.terminal(Ro(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var lo=require("@flopay/shared"),$l=require("react");var Wl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var xr=require("react/jsx-runtime"),wd=`
10
10
  .paypal-buttons { margin: 0 !important; vertical-align: top !important; }
11
11
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
12
12
  @keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
@@ -27,7 +27,7 @@ ${se.join(`
27
27
  0% { opacity: 1; transform: translateX(0) scale(1); }
28
28
  100% { opacity: 0; transform: translateX(16px) scale(0.97); }
29
29
  }
30
- `,Yo=44;function Xo(){return(0,Rr.jsx)("style",{children:yd})}function wa(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function ka({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Rr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Rr.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,Rr.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:n})]})}function ts(e){return e!=="unavailable"&&e!=="load_error"}function oi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:l,backgroundColor:p,borderColor:m,textColor:h,borderRadius:w,fontFamily:S}){let E=(0,to.resolveStripeMethodBrandVariant)(e,t),Y=Bl[e],[I,ee]=(0,Dl.useState)(!1),x=!!Y&&!I,f=E?.backgroundColor??p??"#ffffff",P=E?.borderColor??m??"#d1d5db",pe=E?.textColor??h??"#262833";return(0,Rr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&l()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Yo,padding:"0 1rem",backgroundColor:f,color:pe,border:`1px solid ${P}`,borderRadius:w??8,fontSize:"0.95rem",fontWeight:600,fontFamily:S,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,Rr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,to.getStripeMethodDisplayName)(e)}\u2026`}):(0,Rr.jsxs)(Rr.Fragment,{children:[(0,Rr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,to.hasVendoredStripeMethodLogo)(e)?8:0},children:[x?(0,Rr.jsx)("img",{src:Y,alt:"","aria-hidden":"true",onError:()=>ee(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!x&&E?.logoSvg?(0,Rr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:E.logoSvg}}):null,(0,Rr.jsx)("span",{children:(0,to.getStripeMethodDisplayName)(e)})]}),i&&(0,Rr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:pe,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,Rr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function ai(e){let t=new Set(e.map(to.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var ii={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},si={type:"accordion",defaultCollapsed:!1,radios:"never"};function li({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:i,style:l,children:p}){return(0,Rr.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:i,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...l??{}},children:p})}var sn=require("react");var Ra=require("@flopay/shared"),fd=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function gd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return fd.has(t.charAt(0).toLowerCase()+t.slice(1))}function hd(e,t){return typeof t=="number"&&t!==0&&!gd(e)?`${t}px`:String(t).trim()}function Ol(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=hd(r,n)}}}var So=require("react/jsx-runtime"),rs=new WeakSet;function co({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:i,submitLabel:l,containerStyle:p,onReady:m,onError:h,onValidation:w}){let S=(0,sn.useRef)(null),E=(0,sn.useRef)(m),Y=(0,sn.useRef)(h),I=(0,sn.useRef)(w);E.current=m,Y.current=h,I.current=w;let ee=(0,sn.useRef)(i);ee.current=i;let x=(0,sn.useRef)(null),f=l??void 0,P=(0,sn.useRef)(f);P.current=f;let pe=(0,sn.useRef)(void 0);return(0,sn.useEffect)(()=>{let b=S.current;if(!b)return;let Ie=!0,_=!1,ie=()=>{!Ie||_||(_=!0,E.current?.())},me=e.on("ready",()=>{ie()}),ue=e.on("error",B=>{Y.current?.(B.message??"There was a problem loading the secure card form.")}),xe=e.on("validation",B=>{I.current?.(B.message??null)}),lt=P.current??(rs.has(e)?null:void 0),$e={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...ee.current?{theme:ee.current}:{},...lt===void 0?{}:{submitLabel:lt}};return x.current=ee.current??null,pe.current=P.current,P.current!==void 0&&rs.add(e),e.mount(b,$e).then(()=>{ie()}).catch(B=>{Ie&&Y.current?.(B instanceof Error?B.message:"Failed to load the secure card form.")}),()=>{Ie=!1,me(),ue(),xe(),e.unmount()}},[e,t,r,n,a]),Co(()=>{let b=S.current;b&&Ol(b,p)},[p]),(0,sn.useEffect)(()=>{i!==void 0&&(i===null&&x.current===null||(x.current=i,e.applyTheme?.(i)))},[e,i]),(0,sn.useEffect)(()=>{f!==pe.current&&(pe.current=f,f!==void 0&&rs.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,So.jsx)("div",{ref:S,"data-testid":"flopay-vault-card-fields"})}function ci({label:e}){return(0,So.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,So.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,So.jsx)("span",{children:e}),(0,So.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var ms=require("@flopay/shared"),u=require("react/jsx-runtime"),jn="flopay_stripe_resume",Ll="flopay_wallet_resume",Kl="fw1",Pd="fw2",Gl=300*1e3,vd=900,Cd="express_checkout_click_timeout",bd=25e3,Sd=25e3,wd=1e4,Tn={provider:"paypal",paymentMethodCategory:"paypal"},kd="x-flopay-process-result-source",Rd="status";async function Ed(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var di={},Ia=class{constructor(t){this.reason=t}};function Id(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function nr(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ds(e){return`${Pd}:${e}`}function ui(e){return nr(ds(e))}function pi(e,t){if(typeof window>"u")return null;let r=ds(e);try{let n=localStorage.getItem(r);if(!n)return null;let a=JSON.parse(n);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>Gl||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ui(e),null):a}catch{return ui(e),null}}function _d(e){return nr(ds(e.sessionId),e)}function Nl(e,t,r){let n=pi(e,t);return!n||n.clientSecret!==r?!1:ui(e)}function ns(e,t,r){if(typeof window>"u")return;pi(e,t)?.clientSecret===r&&ui(e)}function Td(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function os(e,t,r){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let n=r?e.status==="succeeded":pa(e.status),a=Td(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Ul(e,t,r){let n=null;try{return await Promise.race([Pl(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},wd),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Md(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Yl(e){return e instanceof d.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function mi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Mn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw Yl(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var as=d.STRIPE_PAYPAL_RESUME_KEY,Ea=new Map,xd=250,zl="Just a moment \u2014 we are finalizing your order. Please press pay again.",Ad="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function us(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function yi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Mn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Fd(e){return e instanceof d.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Xl({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),i=(0,Uo.splitFullName)(r),l=i.firstName?i:(0,Uo.splitFullName)(n?.name);return(0,mn.compactBuyerIdentity)({email:(0,d.isValidEmail)(a)?a:n?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Bd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:i}){let l=Xl({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,d.isValidEmail)(l.email)?l:i(a,l)}var _a=180,ql=`flopay-card-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,jl=`flopay-card-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Dd=`flopay-buttons-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,Od=`flopay-buttons-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Ld(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ps(e){return(0,d.derivePrimaryTileStyle)(e)}var Nd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ud(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var ss={width:"100%",minHeight:Yo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Vl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ls(e){return e==="paypal"?"PayPal":(0,d.getStripeMethodDisplayName)(e)}function zd(e){let t=(0,d.getPostalCodeExample)(e);return`Enter a valid ${(0,d.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function qd(e,t,r){let n=(0,d.isPostalCodeSupported)(e),a=t.trim(),i=r&&n,l=i&&!a,p=i&&!!a&&!(0,d.isValidPostalCode)(e,a);return{visible:r,supported:n,required:i,empty:l,malformed:p}}function jd(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,d.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function Vd(e){return typeof e=="number"?`${e}px`:e}function fi(e){return(0,u.jsx)(Hd,{...e})}function Wl({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:i,isProcessing:l=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:h,runBeforeButtonClick:w,billingName:S,onBuyerIdentityReady:E,onLoadStateChange:Y,placeholderBorderRadius:I,popupCapabilityOwner:ee,externalTelemetryContext:x,presentationMode:f}){let P=Qn(),{emitInstrument:pe}=(0,o.useContext)(pn),b=(0,rr.useStripe)(),Ie=(0,rr.useElements)(),_=(0,o.useMemo)(()=>ni(kr(P),x),[x,P]),[ie,me]=(0,o.useState)("loading");(0,o.useEffect)(()=>{Y?.(ie)},[ie,Y]);let[ue,xe]=(0,o.useState)(!1),lt=(0,o.useRef)(!1),$e=!(0,d.isValidEmail)(r?.trim())||!S?.trim(),{request:B,collect:St,finish:Ge}=zo(),De=(0,o.useRef)(!1),de=(0,o.useRef)(null),re=(0,o.useRef)(null),[X,Oe]=(0,o.useState)(0),[nt,ze]=(0,o.useState)(!1),te=(0,o.useRef)(!1),J=(0,o.useRef)(new Map),{startAttempt:H,finishAttempt:j,invalidateAttempt:je,isAttemptInvalidated:Te,isAttemptCurrent:fe,generationRef:O}=ga((Ce,T,ht)=>{h?.(Ce,T,{...ht,popupBlocked:ht?.popupBlocked??(0,ve.isPopupBlockedError)(T),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),ze(!0),Oe(pt=>pt+1)},{onHandoffObserved:()=>{ee.markAvailable(),_?.log({name:"provider.popup.opened",stage:"overlay_open",...Tn,attempt:O.current})}});(0,o.useEffect)(()=>{nt&&re.current?.focus()},[nt,X]);let Pe=(0,o.useCallback)(()=>{Oe(Ce=>Ce+1)},[]),ut=(0,o.useCallback)((Ce,T,ht)=>{je(ht),h?.("paypal",Ce,{code:T,popupBlocked:(0,ve.isPopupBlockedError)(Ce),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),ze(!0),Pe()},[je,h,f,Pe]),Le=(0,o.useCallback)(()=>{window.setTimeout(()=>{(de.current?.querySelector("iframe")??de.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{te.current&&(te.current=!1,Le())},[Le,X]);let ot=(0,o.useCallback)(()=>{ze(!1),i?.(null),Le()},[Le,i]);(0,o.useEffect)(()=>{if(!b||De.current)return;let[Ce,T,ht]=(0,d.readStripeRedirectParams)();if(!Ce||!T)return;let pt=(0,d.readMatchingStripePayPalContinuation)(T);if(!pt)return;De.current=!0;let z=!0,Ae=Ea.get(T);Ae||(Ae=ht==="failed"?Promise.resolve(null):Promise.resolve().then(()=>b.retrievePaymentIntent(T)),Ea.set(T,Ae));let Dt={accountPatch:pt.accountPatch,sessionId:pt.sessionId,nonce:pt.nonce},be=()=>{_?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Tn,requestCategory:"provider_sdk"})};return _?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Tn}),(async()=>{try{xe(!0);let C=await Ae;if(!z)return;if(C?.error){Ea.delete(T),be(),i?.(C.error.message??"Failed to retrieve PayPal payment status.");return}if((0,d.clearStripePayPalReturn)(),Ea.delete(T),ht==="failed"){let Fe="PayPal payment was declined. Please try again.";_?.terminal({outcome:"payment_declined",...Tn,terminalReason:"provider_declined"}),i?.(Fe),m?.(wr("paypal",Fe));return}let M=C?.paymentIntent;if(M&&M.id!==Ce){be(),i?.("Failed to match the returned PayPal payment.");return}if(M&&(M.status==="requires_capture"||M.status==="succeeded")){let Fe=typeof M.payment_method=="string"?M.payment_method:M.payment_method?.id;a({id:Fe??M.id,type:"card",threeDSecureActionResultTokenId:M.id,isPaypal:!0},{...Dt,presentationMode:"redirect"})}else{let Fe="PayPal payment was not completed. Please try again.";_?.terminal({outcome:M?.status==="canceled"?"payment_cancelled":"payment_declined",...Tn,terminalReason:M?.status==="canceled"?"cancelled":"provider_declined"}),i?.(Fe),m?.(wr("paypal",Fe))}}catch(C){if(!z)return;Ea.delete(T),be(),i?.(C instanceof Error?C.message:"Failed to complete PayPal payment.")}finally{z&&xe(!1)}})(),()=>{z=!1,De.current=!1}},[b,a,i,m,_]);let _e=(0,o.useCallback)(async(Ce=!1)=>{let T=w?await w("paypal"):{proceed:!0};if(!T.proceed)return J.current.delete(X),!1;let ht=H("paypal");return J.current.set(X,{generation:ht,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),ze(!1),_?.log({name:`provider.${Ce?"redirect.started":"handoff.requested"}`,stage:Ce?"redirect":"overlay_open",...Tn,attempt:ht}),p?.("paypal"),!0},[p,_,w,H,X]),et=(0,o.useCallback)(async Ce=>{if(l||ue||!await _e()){Ce.reject();return}Ce.resolve()},[l,_e,ue]),at=(0,o.useCallback)(async Ce=>{if(!b||!Ie)return;let T=J.current.get(X);if(T&&!fe(T.generation)){J.current.delete(X);return}if(!T&&Te()||T&&!j(T.generation))return;T||j();let ht=T??null;if(J.current.delete(X),!ht&&w){let _t=await w("paypal");if(!_t.proceed){Ce.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ht={accountPatch:_t.accountPatch,sessionId:_t.sessionId,nonce:_t.nonce}}let pt=ht?.sessionId??e,z=ht?.nonce??t,Ae=await Bd({event:Ce,prepared:ht,email:r,billingName:S,methodLabel:"PayPal",collect:St});if(!Ae){Ce.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Dt=Ae.email,be={...ht?.accountPatch,...(0,mn.compactBuyerIdentity)(Ae,!0)};try{if(xe(!0),i?.(null),!pt||!(0,d.isValidEmail)(Dt))throw new Error("Missing sessionId or email for PayPal payment");await E?.(Ae);let _t=b.createPaymentMethod,{error:C,paymentMethod:M}=await _t({type:"paypal"});if(C){ut(C,"stripe_paypal_create_payment_method_failed",T?.generation),Ce.paymentFailed({reason:"fail"});return}let Fe=await mi(n,pe,pt,z??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:M?.id??null,intentKind:"payment"});if(Fe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Se=Fe.clientSecret,ct={return_url:(0,d.stripeRedirectReturnUrl)()};if(M?.id&&(ct.payment_method=M.id),!nr(as,{clientSecret:Se,sessionId:pt,nonce:z,accountPatch:be})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Ve,paymentIntent:He}=await b.confirmPayment({clientSecret:Se,confirmParams:ct,redirect:"if_required"});if(Ve){if(nr(as),(0,ve.isProviderDecline)(Ve)){let c=Ve.message??"Your payment was declined.";_?.terminal({outcome:"payment_declined",...Tn,terminalReason:"provider_declined"}),i?.(c),m?.(wr("paypal",c,{code:(0,ve.getProviderErrorCode)(Ve),declineCode:(0,ve.getProviderDeclineCode)(Ve)})),await yi({billingApiUrl:n,sessionId:pt,nonce:z,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,ve.getProviderErrorCode)(Ve)??"provider_declined"}})}else ut(Ve,"stripe_paypal_confirm_failed",T?.generation);return}nr(as);let Bt=typeof He?.payment_method=="string"?He.payment_method:He?.payment_method?.id;a({id:Bt??He?.id,type:"card",threeDSecureActionResultTokenId:He?.id,isPaypal:!0},{accountPatch:be,paymentMethodCategory:"paypal",presentationMode:f,sessionId:pt,nonce:z});return}catch(_t){ut(_t,"stripe_paypal_failed",T?.generation)}finally{xe(!1)}},[b,Ie,e,t,r,S,St,E,n,pe,a,i,m,w,ut,j,fe,Te,_,f,X]),ar=(0,o.useCallback)(async()=>{if(!(lt.current||l||ue||!b||!Ie)){lt.current=!0,xe(!0);try{if(!await _e(!0))return;await at({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{lt.current=!1,xe(!1)}}},[Ie,at,l,_e,b,ue]),xt=f==="redirect"?(0,u.jsx)("button",{type:"button",disabled:l||ue,onClick:()=>{ar()},style:{width:"100%",minHeight:Yo,border:"1px solid #d1d5db",borderRadius:I??8,background:"#ffc439",color:"#111827",cursor:l||ue?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,u.jsx)(rr.ExpressCheckoutElement,{onReady:Ce=>me(wa(Ce,["paypal"])),onLoadError:()=>{me("load_error"),us(_,"paypal","paypal","provider_error")},onClick:et,onConfirm:at,onCancel:()=>{let Ce=J.current.get(X);J.current.delete(X),_?.terminal({outcome:"payment_cancelled",...Tn,terminalReason:"cancelled",...Ce?{attempt:Ce.generation}:{}}),je(Ce?.generation),ze(!1),te.current=!0,Pe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:$e,emailRequired:$e,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},X),Ct=(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("div",{ref:de,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[nt&&(0,u.jsx)("button",{ref:re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:ss,children:"Try PayPal again"}),B&&(0,u.jsx)(qo,{identity:B.identity,methodLabel:B.methodLabel,onComplete:Ge,onCancel:()=>Ge(null)},B.id),(0,u.jsx)("div",{style:{display:B?"none":void 0},children:xt})]}),ue&&!B&&(0,u.jsx)(Zr,{status:"processing"})]});return f==="redirect"?Ct:(0,u.jsx)(ka,{state:ie,placeholderTestId:"flopay-paypal-placeholder",borderRadius:I,children:Ct})}function is(e){return e==="apple_pay"||e==="google_pay"}var Wd=200;function $d({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,d.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function $l({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:i,onTokenizedBody:l,onErrorChange:p,onButtonClick:m,onDecline:h,onTechnicalFailure:w,runBeforeButtonClick:S,billingName:E,onBuyerIdentityReady:Y,onLoadStateChange:I,placeholderBorderRadius:ee,popupCapabilityOwner:x,externalTelemetryContext:f}){let P=Qn(),{emitInstrument:pe}=(0,o.useContext)(pn),b=(0,rr.useStripe)(),Ie=(0,rr.useElements)(),_=(0,o.useMemo)(()=>ni(kr(P),f),[f,P]),[ie,me]=(0,o.useState)("loading");(0,o.useEffect)(()=>{I?.(ie)},[ie,I]);let[ue,xe]=(0,o.useState)(!1);(0,o.useEffect)(()=>{ze.current=ue},[ue]);let lt=(0,o.useRef)(!(0,d.isValidEmail)(r?.trim())||!E?.trim()).current,{request:$e,collect:B,finish:St}=zo(),Ge=(0,o.useRef)(null),De=(0,o.useRef)(null),[de,re]=(0,o.useState)(0),[X,Oe]=(0,o.useState)(()=>(0,d.shouldPreferWalletPopup)()),nt=(0,o.useRef)(X),ze=(0,o.useRef)(!1),[te,J]=(0,o.useState)(!1),[H,j]=(0,o.useState)(()=>pi(e,t)?"blocked":"idle"),[je,Te]=(0,o.useState)("google_pay"),fe=(0,o.useRef)(null),O=(0,o.useRef)(!0),Pe=(0,o.useRef)(!1),ut=(0,o.useRef)("google_pay"),Le=(0,o.useRef)("google_pay"),ot=(0,o.useRef)(null),_e=(0,o.useRef)(null),et=(0,o.useRef)(new Set),at=(0,o.useRef)(null),ar=(0,o.useRef)(null);(0,o.useEffect)(()=>(O.current=!0,()=>{O.current=!1;for(let c of et.current)window.clearTimeout(c);et.current.clear()}),[]);let xt=(0,o.useRef)(new Map),{startAttempt:Ct,finishAttempt:Ce,invalidateAttempt:T,isAttemptInvalidated:ht,isAttemptCurrent:pt,generationRef:z}=ga((c,U,V)=>{w?.(c,U,{...V,popupBlocked:V?.popupBlocked??(0,ve.isPopupBlockedError)(U),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Te(c),J(!0),re(se=>se+1)},{onHandoffObserved:c=>{ar.current=z.current,x.markAvailable(),_?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:z.current,...c==="apple_pay"||c==="google_pay"?{walletType:c}:{}})},defersMissingTerminal:is,onMissingTerminalDeferred:(c,U)=>{let V=_?.now()??globalThis.performance?.now()??Date.now(),se=at.current,R=se?.generation===U?se.startedAt:V;_?.performance({stage:"overlay_return",durationMs:Math.max(0,V-R),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:U,...is(c)?{walletType:c}:{}}),_?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{te&&De.current?.focus()},[te,de]);let Ae=(0,o.useRef)(0),Dt=(0,o.useRef)(!1),be=(0,o.useCallback)(()=>{if(Ae.current>0){Dt.current=!0;return}re(c=>c+1)},[]),_t=(0,o.useCallback)(()=>{Ae.current-=1,!(Ae.current>0||!Dt.current)&&(Dt.current=!1,O.current&&re(c=>c+1))},[]),C=(0,o.useCallback)((c,U,V,se,R=!1)=>{T(se),w?.(c,U,{code:V,popupBlocked:(0,ve.isPopupBlockedError)(U),telemetryReported:R,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Te(c),J(!0),be()},[T,w,be]),M=(0,o.useCallback)(c=>{_?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...is(c)?{walletType:c}:{}}),w?.(c,new Error("The wallet click was not ready within the time the wallet allows."),{code:Cd,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Te(c),J(!0)},[w,_]),Fe=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Ge.current?.querySelector("iframe")??Ge.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Pe.current&&(Pe.current=!1,Fe())},[Fe,de]);let Se=(0,o.useCallback)(()=>{J(!1),p?.(null),Fe()},[Fe,p]),ct=(0,o.useCallback)(()=>{fe.current?.()},[]);(0,o.useEffect)(()=>{let c=null,U=()=>{c=null;let se=(0,d.shouldPreferWalletPopup)();se!==nt.current&&(nt.current=se,Oe(se),!ze.current&&!pt(z.current)&&be())},V=()=>{c!==null&&window.clearTimeout(c),c=window.setTimeout(U,Wd)};return window.addEventListener("resize",V),()=>{window.removeEventListener("resize",V),c!==null&&window.clearTimeout(c)}},[z,pt,be]),(0,o.useEffect)(()=>{let c=pi(e,t);if(!c)return;let U=!1,V=!1,se=async()=>{if(!V){V=!0,U||j("checking");try{let R=await Ul(b,c.clientSecret,et.current);if(U)return;let K=os(R,c.providerObjectId,(0,d.isSetupIntentClientSecret)(c.clientSecret));if(K.kind==="confirmed"){if(!Nl(e,t,c.clientSecret))return;fe.current=null,j("idle"),l({id:K.paymentMethodId,type:"card",threeDSecureActionResultTokenId:K.intentId},{...c.accountPatch?{accountPatch:c.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(K.kind==="terminal"){ns(e,t,c.clientSecret),fe.current=null,j("idle"),Te(c.paymentMethodType),J(!0),be();return}j("blocked")}catch{U||j("blocked")}finally{V=!1}}};return fe.current=se,j("blocked"),()=>{U=!0,fe.current===se&&(fe.current=null)}},[t,l,be,e,b]);let mt=(0,o.useCallback)(async c=>{let U=!1,V=!1,se=dt=>{U||V||(U=!0,c.paymentFailed({reason:"fail",...dt?{message:dt}:{}}))};if(!b||!Ie){se();return}let R=xt.current.get(de);if(R&&!pt(R.generation)){xt.current.delete(de),se();return}if(!R&&ht()){se();return}if(R&&!Ce(R.generation)){se();return}R||(Ce(),Dt.current=!1);let K=c.expressPaymentType??R?.method??ut.current,Ut=R??null,xr=Vl(K),ir;K==="apple_pay"?ir="apple_pay":K==="google_pay"&&(ir="google_pay");let Ht=R?.generation??z.current,Tt=_,Lr=Tt?.now()??globalThis.performance?.now()??Date.now(),Ar=new AbortController,Zt=!1,$r=!1,Mt=null,xn=e,Kt="processing",ln="other",Nr="provider_runtime",Ur,sr=new Promise((dt,wt)=>{Ur=wt}),br=window.setTimeout(()=>{Zt=!0,Ar.abort(),Ur(di)},bd),Hr=async(dt,wt,lr)=>{Kt=dt,ln=wt,Nr=wt==="intent_create"||wt==="session_claim"?"transport_error":"provider_runtime";let Gt=Tt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([lr,sr])}finally{let hr=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.performance({stage:dt,durationMs:Math.max(0,hr-Gt),durationMode:"machine",requestCategory:wt,paymentMethodCategory:"wallet",provider:"stripe",...Zt?{statusClass:"timeout"}:{}})}};try{if(xe(!0),p?.(null),!Ut&&S){let $=await Hr("processing","other",S(xr));if(!$.proceed){se();return}Ut={accountPatch:$.accountPatch,sessionId:$.sessionId,nonce:$.nonce}}let dt=Ut?.sessionId??e;xn=dt;let wt=Ut?.nonce??t,lr=ot.current??Ut?.accountPatch,Gt=Xl({event:c,fallbackEmail:lr?.email??r,fallbackName:[lr?.firstName,lr?.lastName].join(" ").trim()||E});if(!(0,d.isValidEmail)(Gt.email)){se("Buyer details are required."),B(ls(K),Gt).then($=>{$&&(ot.current=$)});return}ot.current=null;let hr={...Ut?.accountPatch,...(0,mn.compactBuyerIdentity)(Gt,!0)};await Hr("processing","session_claim",Promise.resolve(Y?.(Gt)));let{error:Yt}=await Hr("tokenization","provider_sdk",Ie.submit());if(Yt){se(),C(K,Yt,"stripe_wallet_submit_failed",R?.generation);return}if(!dt)throw new Error("Missing sessionId or email for payment.");let cr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:K,paymentMethodId:null,intentKind:a},Ir=JSON.stringify({sessionId:dt,nonce:wt??"",request:cr}),dr=_e.current,Ye=dr?.retryIdentity===Ir?dr.authorizationAttemptId:(0,d.randomUuidV4)();_e.current={authorizationAttemptId:Ye,retryIdentity:Ir};let Fr=await Hr("processing","intent_create",mi(n,pe,dt,wt??"",{...cr,authorizationAttemptId:Ye},{signal:Ar.signal}));if(Fr.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ur=Fr.clientSecret,oo=_d({createdAt:Date.now(),sessionId:dt,...wt?{nonce:wt}:{},clientSecret:ur,providerObjectId:Fr.providerObjectId,paymentMethodType:K,accountPatch:hr});window.clearTimeout(br),$r=!0,Tt?.performance({stage:"callback",durationMs:Math.max(0,(Tt?.now()??globalThis.performance?.now()??Date.now())-Lr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let zr=Tt?.now()??globalThis.performance?.now()??Date.now(),qr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...ir?{walletType:ir}:{},attempt:Ht},An=!1,Kr=null;Tt?.log({name:"payment.provider_confirmation.started",...qr}),Mt=window.setTimeout(()=>{Mt!==null&&et.current.delete(Mt),An=!0;let $=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...qr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,$-zr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Tt?.flush?.().catch(()=>{}),Kr?.()},Sd),et.current.add(Mt);let Xt=($,Vt)=>{Mt!==null&&(window.clearTimeout(Mt),et.current.delete(Mt),Mt=null);let tt=Tt?.now()??globalThis.performance?.now()??Date.now(),Lt=Math.max(0,tt-zr),pr=$;An&&($==="resolved"?pr="resolved_late":$==="returned_error"?pr="returned_error_late":pr="rejected_late");let Br=Vt??($==="resolved"?"approved":"provider_error");return Tt?.log({name:"payment.provider_confirmation.returned",...qr,operationOutcome:pr,terminalReason:Br}),Tt?.performance({...qr,durationMs:Lt,durationMode:"buyer",operationOutcome:pr,terminalReason:Br}),{durationMs:Lt,operationOutcome:pr,terminalReason:Br}},ye=!1,Z=!1,At=$=>{if(!$||typeof $!="object")return null;let Vt=$;if(Vt.error)return null;let tt=Vt.setupIntent??Vt.paymentIntent,Lt=os(tt??null,void 0,!!Vt.setupIntent);return Lt.kind==="confirmed"?Lt:null},Me=$=>{if(ye||R&&z.current!==R.generation)return;let Vt=At($);if(!Vt)return;if(oo&&!Nl(dt,wt,ur)){ye=!0;return}let{intentId:tt,paymentMethodId:Lt}=Vt;ye=!0,Z=!0,_e.current=null,fe.current=null,O.current&&(j("idle"),xe(!1));let pr=`${Kl}:${dt}`;nr(pr,{createdAt:Date.now(),sessionId:dt,nonce:wt,accountPatch:hr,paymentMethodId:Lt,providerIntentId:tt,paymentMethodType:K});try{l({id:Lt,type:"card",threeDSecureActionResultTokenId:tt},{accountPatch:hr,paymentMethodCategory:"wallet",sessionId:dt,nonce:wt})}finally{nr(pr)}},Pr=!1;Kr=async()=>{if(!(Pr||ye||Z)){Pr=!0,O.current&&j("checking");try{let $=await Ul(b,ur,et.current);if(ye||Z)return;let Vt=(0,d.isSetupIntentClientSecret)(ur),tt=os($,Fr.providerObjectId,Vt);if(tt.kind==="confirmed"){Me(Vt?{setupIntent:$}:{paymentIntent:$});return}if(tt.kind==="terminal"){if(Z=!0,ns(dt,wt,ur),_e.current=null,fe.current=null,!O.current)return;j("idle"),se(),C(K,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",R?.generation,!0);return}O.current&&!Z&&(j("blocked"),xe(!1))}catch{O.current&&!Z&&(j("blocked"),xe(!1))}finally{Pr=!1}}},fe.current=Kr;let Ot,jt;try{V=!0,Ae.current+=1;let $;try{$=await((0,d.isSetupIntentClientSecret)(ur)?b.confirmSetup({elements:Ie,clientSecret:ur,redirect:"if_required"}):b.confirmPayment({elements:Ie,clientSecret:ur,redirect:"if_required"}))}finally{_t()}if(!$||typeof $!="object")throw new Ia(Id($));if(Ot=$,!Ot.error&&!At(Ot))throw new Ia("confirmation_result_unconfirmed");jt=Xt(Ot.error?"returned_error":"resolved",Ot.error&&(0,ve.isProviderDecline)(Ot.error)?"provider_declined":void 0)}catch($){let Vt=$ instanceof Ia?$.reason:void 0,tt=Vt!==void 0,Lt=Xt(tt?"returned_error":"rejected");if(Tt?.error({...tt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Vt}:Gi($),...qr,operationOutcome:Lt.operationOutcome,durationMs:Lt.durationMs,statusClass:"unknown",terminalReason:Lt.terminalReason}),!O.current||ye)return;await Kr?.();return}let vr=Ot.error;if(vr){if(!O.current||ye)return;if((0,ve.isProviderDecline)(vr)){Z=!0,ns(dt,wt,ur),_e.current=null,fe.current=null,j("idle"),xt.current.get(de)===R&&xt.current.delete(de);let $=vr.message??"Your payment was declined.";p?.($),h?.(wr(xr,$,{code:(0,ve.getProviderErrorCode)(vr),declineCode:(0,ve.getProviderDeclineCode)(vr)})),yi({billingApiUrl:n,sessionId:dt,nonce:wt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:K,providerDeclineReason:(0,ve.getProviderErrorCode)(vr)??"provider_declined",...Fr.intentKind==="payment"&&Fr.providerObjectId.startsWith("pi_")?{providerIntentId:Fr.providerObjectId}:{}}})}else Tt?.error({...Gi(vr),...qr,operationOutcome:jt.operationOutcome,durationMs:jt.durationMs,statusClass:"unknown",terminalReason:jt.terminalReason}),await Kr?.();return}if(Me(Ot),!ye)throw new Error("Invalid provider returned for APM intent")}catch(dt){if(dt===di){let wt=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.error({errorCode:Md(ln),stage:Kt,requestCategory:ln,paymentMethodCategory:"wallet",provider:"stripe",...ir?{walletType:ir}:{},operationOutcome:"watchdog_expired",checkoutSessionId:xn,durationMs:Math.max(0,wt-Lr),statusClass:"timeout",failureCategory:Nr,attempt:Ht,terminalReason:"provider_error"}),Tt?.flush?.().catch(()=>{})}se(),C(K,dt,dt===di?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",R?.generation,dt===di)}finally{if(window.clearTimeout(br),Mt!==null&&(window.clearTimeout(Mt),et.current.delete(Mt)),!$r){let dt=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.performance({stage:"callback",durationMs:Math.max(0,dt-Lr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Zt?{statusClass:"timeout"}:{}})}O.current&&xe(!1)}},[b,Ie,e,t,r,E,B,Y,n,pe,a,l,p,h,S,C,_t,Ce,pt,ht,z,_,de]),Ve=(0,o.useMemo)(()=>ai(i),[i]),He=(0,o.useMemo)(()=>i.map(d.stripeExpressMethodToOptionKey),[i]),Bt=(0,o.useMemo)(()=>(0,u.jsx)(rr.ExpressCheckoutElement,{onReady:c=>{me(wa(c,He))},onLoadError:c=>{me("load_error"),us(_,"stripe","wallet","provider_error")},onClick:async c=>{let U=_?.now()??globalThis.performance?.now()??Date.now();ut.current=c.expressPaymentType,Le.current=Vl(c.expressPaymentType);let V=!0,se=window.setTimeout(()=>{V=!1,c.reject(),M(c.expressPaymentType)},vd),R=S?await S(Le.current,{abandoned:()=>!V}):{proceed:!0};if(window.clearTimeout(se),!V)return;if(!R.proceed){xt.current.delete(de),c.reject();return}let K=Ct(c.expressPaymentType);Dt.current=!1,at.current={generation:K,startedAt:U},xt.current.set(de,{generation:K,method:c.expressPaymentType,accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}),J(!1),_?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:K,...c.expressPaymentType==="apple_pay"||c.expressPaymentType==="google_pay"?{walletType:c.expressPaymentType}:{}}),m?.(Le.current),c.resolve()},onConfirm:mt,onCancel:()=>{let c=xt.current.get(de);xt.current.delete(de);let U=at.current,V=_?.now()??globalThis.performance?.now()??Date.now();if(c&&U?.generation===c.generation&&(0,d.isWalletSheetRefusedForWindowSize)({method:c.method,elapsedMs:V-U.startedAt,handoffObserved:ar.current===c.generation})){_?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:c.generation,walletType:"google_pay"}),_e.current=null,C(c.method,new Error("The browser window is too small for the Google Pay sheet."),d.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,c.generation,!0);return}_?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...c?{attempt:c.generation}:{}}),T(c?.generation),_e.current=null,J(!1),Pe.current=!0,be()},options:{...ii,paymentMethods:Ve,emailRequired:lt,billingAddressRequired:lt}},de),[He,Ve,mt,T,m,lt,C,M,be,S,Ct,de,_]);return(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(ka,{state:ie,placeholderTestId:"flopay-wallet-placeholder",borderRadius:ee,children:(0,u.jsxs)("div",{ref:Ge,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[te&&(0,u.jsxs)("button",{ref:De,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Se,style:ss,children:["Try ",ls(je)," again"]}),H!=="idle"&&(0,u.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,u.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,u.jsx)("button",{type:"button",onClick:ct,disabled:H==="checking",style:ss,children:H==="checking"?"Checking payment status\u2026":"Check payment status"})]}),$e&&(0,u.jsx)(qo,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:St,onCancel:()=>St(null)},$e.id),(0,u.jsxs)("div",{style:{display:$e||H!=="idle"?"none":void 0},children:[(0,u.jsx)($d,{active:X}),Bt]})]})}),ue&&(0,u.jsx)(Zr,{status:"processing"})]})}function Jl(e,t,r){let n=(0,d.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,paymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function cs({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:p,onErrorChange:m,onDecline:h,onCancel:w,runBeforeButtonClick:S,onButtonClick:E,isProcessing:Y,submitButtonColor:I,submitButtonBorderRadius:ee,submitButtonStyle:x,errorText:f}){let P=Qn(),{emitInstrument:pe}=(0,o.useContext)(pn),b=(0,rr.useStripe)(),Ie=(0,rr.useElements)(),[_,ie]=(0,o.useState)(!1),me=(0,o.useRef)(!1),[ue,xe]=(0,o.useState)(!1),[lt,$e]=(0,o.useState)("loading"),[B,St]=(0,o.useState)(""),Ge=!(0,d.isValidEmail)(n?.trim()),De=!Ge||(0,d.isValidEmail)(B.trim()),de=(0,o.useCallback)(async()=>{if(!b||!Ie||Y||me.current||!ue)return;me.current=!0,ie(!0);let re=S?await S("card"):{proceed:!0};if(!re.proceed){me.current=!1,ie(!1);return}E?.("card");let X=re.sessionId??t,Oe=re.nonce??r,nt=(0,Uo.splitFullName)(a?.trim()),ze=(0,mn.compactBuyerIdentity)({email:re.accountPatch?.email?.trim()||n?.trim()||B.trim(),firstName:re.accountPatch?.firstName?.trim()||nt.firstName,lastName:re.accountPatch?.lastName?.trim()||nt.lastName}),te=ze.email,J=(0,mn.compactBuyerIdentity)({...re.accountPatch,...ze});try{if(m?.(null),!(0,d.isValidEmail)(te))throw new Error("A valid email address is required for payment.");await i?.(ze);let H=await Ie.submit();if(H.error){m?.(H.error.message??"Payment failed.");return}let j=[ze.firstName,ze.lastName].filter(Boolean).join(" "),je=await b.createPaymentMethod({elements:Ie,params:{billing_details:{email:te,...j?{name:j}:{}}}});if(je.error||!je.paymentMethod){m?.(je.error?.message??"Failed to create payment method.");return}let Te=je.paymentMethod;if(!X||!te)throw new Error("Missing sessionId or email for payment.");let fe=Te.type||e,O=await mi(l,pe,X,Oe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:fe,paymentMethodId:null,intentKind:"payment"});if(O.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Pe=O.clientSecret;nr(jn,{clientSecret:Pe,sessionId:X,nonce:Oe,accountPatch:J,paymentMethodId:Te.id,paymentMethodType:Te.type??e,gateway:"stripe"});let{error:ut,paymentIntent:Le}=await b.confirmPayment({clientSecret:Pe,confirmParams:{return_url:window.location.href,payment_method:Te.id},redirect:"if_required"});if(ut){nr(jn);let et=ut.message??"Payment failed.";m?.(et),h?.(wr("card",et,{code:ut.code})),await yi({billingApiUrl:l,sessionId:X,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ut.code??"provider_declined"}});return}let ot=Le?.status;if(!pa(ot)){nr(jn);let et=ot==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(et),h?.(wr("card",et,{code:ot??"missing_payment_intent"}));return}nr(jn);let _e=typeof Le?.payment_method=="string"?Le.payment_method:Le?.payment_method?.id;p({id:_e??Te.id,type:"card",threeDSecureActionResultTokenId:Le?.id,gateway:"stripe",paymentMethodType:Te.type??e},{accountPatch:J,paymentMethodCategory:"apm",sessionId:X,nonce:Oe})}catch(H){m?.(H instanceof Error?H.message:"Payment failed. Please try again.")}finally{me.current=!1,ie(!1)}},[b,Ie,Y,ue,S,E,t,r,n,a,B,i,l,pe,e,p,m,h]);return(0,u.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ge&&(0,u.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ge&&(0,u.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,u.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:B,onChange:re=>St(re.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,u.jsx)(rr.PaymentElement,{onReady:()=>$e("ready"),onLoadError:()=>{$e("load_error"),us(kr(P),"stripe","apm")},onChange:re=>{xe(!!re.complete)},options:{layout:si,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,d.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,u.jsx)(li,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{de()},disabled:!ue||!De||_||Y||lt!=="ready",color:I,borderRadius:ee,style:x,children:_?"Processing\u2026":`Pay with ${(0,d.getStripeMethodDisplayName)(e)}`}),f&&(0,u.jsx)(Wo,{margin:"0.75rem 0 0",children:f})]})}function Hl({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:l,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:h,onTokenizedBody:w,onErrorChange:S,onButtonClick:E,onDecline:Y,runBeforeButtonClick:I,onLoadStateChange:ee,isProcessing:x=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:pe,buttonAppearance:b,themeId:Ie,onExpandApm:_,expandedApmMethod:ie}){let{emitInstrument:me}=(0,o.useContext)(pn),[ue,xe]=(0,o.useState)(null),[lt,$e]=(0,o.useState)(null),B=(0,o.useRef)(!1),{request:St,collect:Ge,finish:De}=zo();(0,o.useEffect)(()=>{l.length>0&&p?ee?.("ready"):p||ee?.("loading")},[l.length,p,ee]);let de=(0,o.useCallback)(async te=>{if(!p||B.current||x)return;B.current=!0,$e(te);let J=I?await I("card"):{proceed:!0};if(!J.proceed){B.current=!1,$e(null);return}E?.("card");let H=J.sessionId??e,j=J.nonce??t,je=(0,Uo.splitFullName)([J.accountPatch?.firstName,J.accountPatch?.lastName].filter(Boolean).join(" ")||n),Te=(0,mn.compactBuyerIdentity)({email:J.accountPatch?.email?.trim()||r?.trim(),firstName:J.accountPatch?.firstName?.trim()||je.firstName,lastName:J.accountPatch?.lastName?.trim()||je.lastName});if(!(0,d.isValidEmail)(Te.email)){$e(null);let Pe=await Ge((0,d.getStripeMethodDisplayName)(te),Te);if(!Pe){B.current=!1;return}Te=Pe,$e(te)}let fe=Te.email,O=(0,mn.compactBuyerIdentity)({...J.accountPatch,...Te});try{if(S?.(null),!H||!(0,d.isValidEmail)(fe))throw new Error("Missing sessionId or email for payment.");await a?.(Te);let Pe=await mi(i,me,H,j??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(Pe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ut=Pe.clientSecret;nr(jn,{clientSecret:ut,sessionId:H,nonce:j,accountPatch:O,paymentMethodType:te,gateway:"stripe"});let{error:Le,paymentIntent:ot}=await p.confirmPayment({clientSecret:ut,confirmParams:{return_url:window.location.href,payment_method_data:{type:te,billing_details:{name:[Te.firstName,Te.lastName].filter(Boolean).join(" "),...fe?{email:fe}:{}}}},redirect:"if_required"});if(Le){nr(jn);let at=Le.message??"Payment failed.";S?.(at),Y?.(wr("card",at,{code:Le.code})),await yi({billingApiUrl:i,sessionId:H,nonce:j,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,providerDeclineReason:Le.code??"provider_declined"}});return}let _e=ot?.status;if(!pa(_e)){nr(jn);let at=_e==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(at),Y?.(wr("card",at,{code:_e??"missing_payment_intent"}));return}nr(jn);let et=typeof ot?.payment_method=="string"?ot.payment_method:ot?.payment_method?.id;w({id:et??ot?.id,type:"card",threeDSecureActionResultTokenId:ot?.id,gateway:"stripe",paymentMethodType:te},{accountPatch:O,paymentMethodCategory:"apm",sessionId:H,nonce:j})}catch(Pe){S?.(Pe instanceof Error?Pe.message:"Payment failed. Please try again.")}finally{B.current=!1,$e(null)}},[p,x,I,E,e,t,r,Ge,i,me,n,a,w,S,Y]),[re,X]=(0,o.useState)(null),Oe=_?ie??null:re,nt=(0,o.useCallback)(te=>{B.current||x||Oe&&Oe!==te||((0,d.needsStripeMethodExplicitConfirm)(te)?_?_(te):X(te):de(te))},[Oe,x,de,_]),ze=(0,o.useMemo)(()=>re?Jl(m,re,h):null,[re,m,h]);return(0,u.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:St?(0,u.jsx)(qo,{identity:St.identity,methodLabel:St.methodLabel,onComplete:De,onCancel:()=>De(null)},St.id):l.map(te=>{let J=ie===te,H=lt===te,j=lt!==null&&lt!==te||ie!=null&&ie!==te;return(0,u.jsxs)(o.default.Fragment,{children:[(0,u.jsx)(oi,{method:te,themeId:Ie,submitting:H,disabled:j,highlighted:J,hasNextStep:(0,d.needsStripeMethodExplicitConfirm)(te),onClick:()=>nt(te),backgroundColor:b?.backgroundColor,borderColor:b?.borderColor,textColor:b?.textColor,borderRadius:b?.borderRadius,fontFamily:b?.fontFamily}),!_&&re===te&&ze&&p&&(0,u.jsx)(rr.Elements,{stripe:p,options:ze,children:(0,u.jsx)(cs,{method:te,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:w,onErrorChange:S,onDecline:Y,onCancel:()=>X(null),runBeforeButtonClick:I,onButtonClick:E,isProcessing:x,submitButtonColor:f,submitButtonBorderRadius:P,submitButtonStyle:pe})},te)]},te)})})}function Hd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:i,onComplete:l,onError:p,onDecline:m,onCancel:h,onTokenizedBody:w,firstName:S,lastName:E,chv:Y,className:I,submitLabel:ee,isProcessing:x,error:f,onErrorChange:P,showPayPal:pe=!0,showStripe:b=!0,walletPresentation:Ie="auto",enabledPaymentMethods:_,enabledPaymentMethodCountries:ie,showApplePay:me=!0,showGooglePay:ue=!0,layout:xe="default",theme:lt,buttonsTheme:$e,buttonsStyles:B,appearance:St,cardButtonContent:Ge,cardBackButtonContent:De,cardTitleContent:de,showSecurityFooter:re,onButtonClick:X,onBeforeButtonClick:Oe,onBuyerIdentityReady:nt,enableAVS:ze,cardFieldOrder:te,cardPreFormSlot:J,avsLayout:H="row",country:j,zip:je,addressLine1:Te,addressLine2:fe,city:O,state:Pe,onCountryChange:ut,onZipChange:Le,avsCheck:ot,checkoutType:_e,checkoutLayout:et,totalAmount:at=0,currency:ar="usd",initialCardOpen:xt=!1,directPaypal:Ct,isSubscription:Ce=!1,session:T,dataAttachmentPending:ht=!1,dataAttachmentRequiresIdentity:pt=!1,debug:z=!1}){let Ae=Qn(),Dt=Ga(),be=(0,o.useContext)(En),{emitInstrument:_t}=(0,o.useContext)(pn),C=(0,o.useRef)(null);C.current||(C.current=Xa());let M=C.current,[,Fe]=(0,o.useState)(0),Se=(0,o.useRef)(null);Se.current||(Se.current=(0,Un.detectPayPalEnvironment)());let ct=Se.current,mt=(0,o.useMemo)(()=>({browser:ct,capability:M,presentationMode:"popup"}),[ct,M]),Ve=T??be.session,He=(0,o.useMemo)(()=>({futureUse:Ve?.futureUse,futureUseUnsupported:Ve?.futureUseUnsupported}),[Ve?.futureUse,Ve?.futureUseUnsupported]),Bt=Ve?.gateways?.paypal?.providerObjectType??Ct?.providerObjectType,c=ht||be.claimPending===!0,U=pt||be.claimRequiresIdentity===!0,V=c&&!U,se=Sl(),R=r||se,[K,Ut]=(0,o.useState)(!1),[xr,ir]=(0,o.useState)(null),[Ht,Tt]=(0,o.useState)(j??""),[Lr,Ar]=(0,o.useState)(je??""),[Zt,$r]=(0,o.useState)(Te??""),[Mt,xn]=(0,o.useState)(fe??""),[Kt,ln]=(0,o.useState)(O??""),[Nr,Ur]=(0,o.useState)(Pe??""),[sr,br]=(0,o.useState)(""),[Hr,dt]=(0,o.useState)({}),wt=(0,o.useRef)(je??""),lr=(0,o.useRef)(j??""),Gt=(0,o.useRef)(Te??""),hr=(0,o.useRef)(fe??""),Yt=(0,o.useRef)(O??""),cr=(0,o.useRef)(Pe??""),Ir=(0,o.useRef)(""),dr=(0,o.useRef)({});(0,o.useEffect)(()=>{let s=(D,ae,Re,Q,Ee)=>{if(dr.current[D])return;let zt=ae?.trim();!zt||zt===Re.current||(Re.current=zt,Q(zt),Ee?.(zt))};s("country",j,lr,Tt,ut),s("zip",je,wt,Ar,Le),s("addressLine1",Te,Gt,$r),s("addressLine2",fe,hr,xn),s("city",O,Yt,ln),s("state",Pe,cr,Ur)},[j,je,Te,fe,O,Pe,ut,Le]);let Ye=(0,o.useMemo)(()=>(0,d.resolveAVSConfig)(ze),[ze]),Fr=Ye!==null,ur=(0,o.useMemo)(()=>(0,d.isAuthorizationOnlySession)(T),[T]),oo=(0,d.isMountableVaultBlock)(T?.vault),zr=!!T?.gateways?.pcivault,qr=(0,Rn.hasServerSideCardGateway)(T),Kr=!!(T?.gateways?.stripe?.enabledPaymentMethods??_)?.includes("card")||(0,Rn.canRecoverHostedCardForm)(T),Xt=oo||Kr||zr,ye=!!(b&&Xt&&e),[Z,At]=(0,o.useState)(()=>xe!=="buttons"||xt?e??null:null),[Me,Pr]=(0,o.useState)(0),Ot=xe!=="buttons"||xt||!!e&&Z===e,jt=T?.captureMethod,vr=(0,o.useRef)(Ae);(0,o.useEffect)(()=>{vr.current=Ae},[Ae]);let[$,Vt]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!ye||!e||!Ot){Vt(null);return}let s=vr.current?vr.current.cardCapture({sessionId:e,captureMethod:jt}):new Mn.PciVaultCardCapture({sessionId:e,captureMethod:jt,billingApiUrl:R,telemetry:n});return Vt({sessionId:e,captureMethod:jt,billingApiUrl:R,telemetry:n,capture:s}),()=>{s.unmount()}},[ye,e,Ot,jt,R,n]);let tt=ye&&e&&Ot&&$?.sessionId===e&&$.captureMethod===jt&&$.billingApiUrl===R&&$.telemetry===n?$.capture:null,Lt=(0,o.useMemo)(()=>{let s=Ht,D=Ye?(0,d.isAVSFieldVisible)(Ye.postal_code,s):!1;return qd(s,Lr,D)},[Ye,Ht,Lr]),{avsInvalid:pr,invalidAvsFields:Br}=(0,o.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!ye||!Ye)return{avsInvalid:!1,invalidAvsFields:s};let D=Ht,ae=(Ee,zt)=>(0,d.isAVSFieldVisible)(Ee,D)&&!zt.trim(),Re={line1:ae(Ye.address_line_1,Zt),city:ae(Ye.city,Kt),state:ae(Ye.state,Nr),zip:Lt.empty||Lt.malformed};return{avsInvalid:Re.line1||Re.city||Re.state||Re.zip,invalidAvsFields:Re}},[ye,Ye,Ht,Zt,Kt,Nr,Lt]),[Qt,vn]=(0,o.useState)(!1),[$n,Fn]=(0,o.useState)(!1),[jr,ao]=(0,o.useState)(!1),[cn,Hn]=(0,o.useState)({line1:!1,city:!1,state:!1}),en=(0,o.useRef)(!1),Cn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Bn=(0,o.useRef)(!1),Nt=(0,o.useCallback)(s=>{Cn.current[s]=!0,Bn.current=!0},[]),tn=(0,o.useCallback)(s=>!en.current&&Cn.current[s],[]),rn=(0,o.useCallback)(s=>{tn(s)&&Hn(D=>D[s]?D:{...D,[s]:!0})},[tn]),[Gr,bn]=(0,o.useState)(()=>(0,d.resolveVaultMountOptions)(T?.vault,{billingApiUrl:R,sessionId:e,nonce:t})),[bt,_r]=(0,o.useState)(xt&&Xt?"card":"buttons"),[mr,Yr]=(0,o.useState)(null),mo=bt==="expanding"||bt==="card",Sn=T?.gateways?.stripe&&!qr?"stripe":void 0,Kn=(0,o.useCallback)(()=>{_t?.({class:"card_surface",provider:Sn})},[Sn,_t]),nn=(0,o.useRef)(null),Tr=(0,o.useCallback)(s=>{nn.current&&clearTimeout(nn.current),nn.current=setTimeout(()=>{nn.current=null,s()},_a)},[]);(0,o.useEffect)(()=>()=>{nn.current&&clearTimeout(nn.current)},[]);let Dn=(0,o.useRef)(!1),[Dr,L]=(0,o.useState)(0),N=(0,o.useRef)(null),ne=(0,o.useCallback)(()=>{Kn(),At(e??null),Dn.current&&(Dn.current=!1,L(s=>s+1)),Pr(s=>s+1),_r("expanding"),Tr(()=>_r("card"))},[Tr,Kn,e]),we=(0,o.useCallback)(()=>{_r("collapsing"),Tr(()=>_r("buttons"))},[Tr]),Rt=(0,o.useCallback)(s=>{Yr(s),_r("apm-expanding"),Tr(()=>_r("apm-form"))},[Tr]),er=(0,o.useCallback)(()=>{_r("apm-collapsing"),Tr(()=>{_r("buttons"),Yr(null)})},[Tr]);(0,o.useEffect)(()=>{xe==="buttons"&&xt&&Xt&&(At(e??null),_r("card"))},[xe,xt,Xt,e]);let[Ne,le]=(0,o.useState)(null),q=(0,o.useRef)(!1),W=(0,o.useRef)(null),ce=(0,o.useRef)("idle"),[g,y]=(0,o.useState)(!1),G=(0,o.useRef)(g);G.current=g;let[ke,Xe]=(0,o.useState)(()=>Ct?.existingOrderId?{orderId:Ct.existingOrderId,attempts:1}:null),yt=(0,o.useRef)(ke);(0,o.useEffect)(()=>{yt.current=ke},[ke]);let Ue=(0,o.useRef)(null),Be=(0,o.useMemo)(()=>{if(nt||be.claimBuyerIdentity||T?.buyerIdentified!==!1||!e||!t)return;let s=`${R}|${e}|${t}`;Ue.current?.key!==s&&(Ue.current={key:s,claim:Lo(new Mn.PaymentAPI(R,{telemetry:!1}),e,t,{...i?{userId:i}:{},...S?{firstName:S}:{},...E?{lastName:E}:{}})});let D=Ue.current.claim;return async ae=>{await D(ae)}},[nt,be.claimBuyerIdentity,T?.buyerIdentified,e,t,R,i,S,E]),it=nt??be.claimBuyerIdentity??Be,kt=f??xr,Et=(0,o.useMemo)(()=>(0,d.resolveTheme)(lt),[lt]),A=(0,o.useMemo)(()=>{let s=Et?.buttonsLayout??(0,d.resolveButtonsLayoutTheme)($e);return B?{...s,...B,cardButton:{...s.cardButton,...B.cardButton},cardFormContainer:{...s.cardFormContainer,...B.cardFormContainer},backButton:{...s.backButton,...B.backButton},backButtonIcon:{...s.backButtonIcon,...B.backButtonIcon},submitButton:{...s.submitButton,...B.submitButton},title:{...s.title,...B.title}}:s},[Et,$e,B]),ge=St??Et?.appearance,Je=(0,o.useMemo)(()=>(0,d.computeVaultCardThemeColors)({appearance:ge,buttonsStyles:A,layout:xe}),[ge,A,xe]),rt=be.inlineSessionPatchProcessing??!1,oe=(x??K)||rt,yr=R.replace(/\/+$/,""),he=(0,o.useMemo)(()=>Ki({userId:i,email:a,firstName:S,lastName:E,country:j,zip:je},Hr),[i,a,S,E,j,je,Hr]),Gn=[he.firstName,he.lastName].filter(s=>!!s?.trim()).join(" "),ks=!(0,d.isValidEmail)(he.email?.trim()),ki=(0,o.useRef)(null);ye&&ki.current===null&&(ki.current=ks);let io=ye&&(ki.current??ks),Ri=(0,o.useMemo)(()=>jd(sr,io),[sr,io]),ko=Ri.empty||Ri.malformed,on=(0,o.useMemo)(()=>Ae?Ae.getRawProvider():null,[Ae]),Rs=(0,o.useMemo)(()=>Dt?Dt.getRawProvider():null,[Dt]),Qo=at||100,Ro=ar.toLowerCase(),Ei=(0,o.useMemo)(()=>ge?(0,Mn.toStripeAppearance)(ge):null,[ge]),Eo=Ei,Es=(0,o.useMemo)(()=>{let s=Ei??{},D=s.rules??{};return{...s,rules:{...D,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...D[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...D[".AccordionItemContents"]??{}}}}},[Ei]),Is=(0,o.useMemo)(()=>({...vl(at,Ve?.captureMethod,He),currency:Ro,...Eo?{appearance:Eo}:null}),[at,Ro,Ve?.captureMethod,He,Eo]),Ii=(0,d.resolveSetupFutureUsage)(He,"paypal","paypal"),_s=(0,o.useMemo)(()=>({mode:"payment",amount:Qo,currency:Ro,captureMethod:"manual",...Ii?{setupFutureUsage:Ii}:null,...Eo?{appearance:Eo}:null}),[Qo,Ro,Ii,Eo]),qe=(0,o.useCallback)(s=>{ir(s),P?.(s)},[P]),Ts=(0,o.useRef)(0);(0,o.useEffect)(()=>{Dr!==Ts.current&&(Ts.current=Dr,qe(null))},[Dr,qe]);let _i=(0,o.useRef)(""),[Ms,Cc]=(0,o.useState)(!1),Ti=(0,o.useCallback)(()=>{Cc(!0)},[]);(0,o.useEffect)(()=>{if(!ye||!io||!it||!Ms||ko||_i.current)return;let s=(0,mn.compactBuyerIdentity)({email:(0,d.isValidEmail)(he.email?.trim())?he.email?.trim():Ir.current.trim(),firstName:he.firstName?.trim(),lastName:he.lastName?.trim()});_i.current=JSON.stringify(s),dt(D=>({...D,...s})),Promise.resolve(it(s)).catch(D=>{_i.current="",qe(D instanceof Error?D.message:"Failed to attach buyer details.")})},[ye,io,it,Ms,ko,he.email,he.firstName,he.lastName,qe]),(0,o.useEffect)(()=>{!ye||!tt||tt.setCardFieldOrder?.(te??null,Ye==null&&!io)},[ye,tt,te,Ye,io]),(0,o.useEffect)(()=>{(bt==="expanding"||bt==="collapsing"||bt==="apm-expanding"||bt==="apm-collapsing")&&qe(null)},[bt,qe]);let On=(0,o.useCallback)((s,D,ae)=>{m?.(wr(s,D,ae))},[m]),Io=(0,o.useCallback)((s,D,ae)=>{let Re=ae?.popupBlocked??(0,ve.isPopupBlockedError)(D);Re&&M.markBlocked()&&Fe(It=>It+1);let Q=ls(s),Ee=ae?.code===d.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,d.buildWalletSheetWindowMessage)(Q):(0,ve.buildExternalMethodRecoveryMessage)(Q,Re,ct.inAppBrowser),zt=(0,ve.getProviderErrorCode)(D),un=(zt?.toLowerCase()==="error"?void 0:zt)??(0,ve.sanitizeExternalFailureCode)(ae?.code)??"external_payment_method_failed",Pt=new d.FloPayError(Ee,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:un,popupBlocked:Re,inAppBrowser:ct.inAppBrowser,appFamily:ct.appFamily,popupCapability:M.current(),presentationMode:ae?.presentationMode??"popup"}});ae?.telemetryReported||kr(Ae)?.error(Go({...mt,presentationMode:ae?.presentationMode??"popup"},{errorCode:Re?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:ae?.provider??(s==="paypal"?"paypal":"stripe"),paymentMethodCategory:ae?.paymentMethodCategory??(s==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:ae?.terminalReason??(Re?"popup_blocked":"provider_error")})),le(null),xe==="buttons"&&(_r("buttons"),Yr(null)),qe(Ee),p?.(Pt),console.error("[FloPay] External payment method failed:",{method:s,code:un,popupBlocked:Re})},[ct,mt,Ae,xe,p,M,qe]);(0,o.useEffect)(()=>{if(!ye||!e){bn(null);return}let s={billingApiUrl:yr,sessionId:e,nonce:t},D=(0,d.resolveVaultMountOptions)(T?.vault,s);if(D){bn(D);return}if(!Ot){bn(null);return}let ae=`${yr}\0${e}\0${t??""}`,Re=N.current;if(Re&&Re.key===ae){bn(Re.mount);return}bn(null);let Q=!0;return new Mn.PaymentAPI(yr).getVaultCapture(e,t).then(Ee=>{if(!Q)return;let zt=(0,d.resolveVaultMountOptions)(Ee,s);zt?.verificationRequired&&!Ee.html&&(N.current={key:ae,mount:zt}),zt?bn(zt):qe("Failed to load the secure card form.")}).catch(Ee=>{Q&&qe(Ee instanceof Error?Ee.message:"Failed to load the secure card form.")}),()=>{Q=!1}},[ye,Ot,Me,e,T?.vault,yr,t,qe]);let wn=(0,o.useRef)({onComplete:l,onError:p,updateError:qe,emitDecline:On,resolvedAccount:he,avsConfig:Ye,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:yr,captureMethod:T?.captureMethod,paymentId:T?.paymentId,authorizationExpiresAt:T?.authorizationExpiresAt,serverSideCardGateway:qr});wn.current={onComplete:l,onError:p,updateError:qe,emitDecline:On,resolvedAccount:he,avsConfig:Ye,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:yr,captureMethod:T?.captureMethod,paymentId:T?.paymentId,authorizationExpiresAt:T?.authorizationExpiresAt,serverSideCardGateway:qr};let Mi=(0,o.useRef)(!1),xs=(0,o.useCallback)(()=>{let s=wn.current,D=s.resolvedAccount.email?.trim(),ae=(0,d.isValidEmail)(D)?D:Ir.current.trim();if(!(0,d.isValidEmail)(ae))return null;let Re=s.resolvedAccount.firstName?.trim(),Q=s.resolvedAccount.lastName?.trim(),Ee=lr.current.trim()||s.resolvedAccount.country?.trim()||"",zt=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.state,Ee):!1,un=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.address_line_1,Ee):!1,Pt=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.postal_code,Ee):!1,It=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.city,Ee):!1,Ft=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.address_line_2,Ee):!1,Wt=un&&!zt&&Pt?(0,d.getStateFromPostalCode)(Ee,(wt.current??"").trim()):null,go=zt?cr.current:Wt;return{accountData:{userId:s.resolvedAccount.userId??"",email:ae,...Re?{firstName:Re}:{},...Q?{lastName:Q}:{},...Pt&&wt.current?{zip:wt.current}:{},...It&&Yt.current?{city:Yt.current}:{},...go?{state:go}:{},...un&&Gt.current?{addressLine1:Gt.current}:{},...Ft&&hr.current?{addressLine2:hr.current}:{},...Ee?{country:Ee}:{}},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,d.isAVSFieldVisible)(s.avsConfig.country,Ee),postal_code:Pt,address_line_1:un,address_line_2:Ft,city:It,state:zt}}:{}}},[]),As=(0,o.useRef)(c);As.current=c,(0,o.useEffect)(()=>{c||kt!==zl||wn.current.updateError(null)},[c,kt]),(0,o.useEffect)(()=>{!ye||!tt||tt.setSubmitGate?.(pr||c||ko||g)},[ye,tt,pr,c,ko,g]),(0,o.useEffect)(()=>{if(!ye||!tt)return;Mi.current=!1;let s=null,D=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,ce.current="idle",le(null)},400)},ae=tt.on("submitting",()=>{vn(!0),W.current&&clearTimeout(W.current),ce.current="validation-window",W.current=setTimeout(()=>{W.current=null,ce.current==="validation-window"&&(ce.current="processing")},xd),le("processing");let Pt=wn.current;if(!Pt.sessionId||!Pt.nonce)return;let It=xs();if(!It){Pt.updateError("Enter a valid email address."),ce.current="idle",le(null);return}new Mn.PaymentAPI(Pt.baseUrl).patchAccountSnapshot(Pt.sessionId,Pt.nonce,It,{telemetryMode:"best_effort"}).catch(Ft=>{if(!Fd(Ft))return;let Wt=Ft instanceof Error?Ft.message:"Please check your billing address and try again.";Pt.updateError(Wt),ce.current="idle",le(null),Pt.onError?.(Ft instanceof d.FloPayError?Ft:new d.FloPayError(Wt,"api_error"))})}),Re=tt.on("complete",Pt=>{(0,_n.markSessionRecentlyCompleted)(Pt.sessionId??wn.current.sessionId),ce.current="terminal",y(!1),le("success"),setTimeout(()=>{if(Mi.current)return;Mi.current=!0;let It=wn.current,Ft=(0,d.isAuthorizationOnlySession)(It)||Pt.outcome==="authorized",Wt=It.serverSideCardGateway?{}:{paymentIntentId:Pt.intentId};wn.current.onComplete?.(Ft?{status:"authorized",...Wt,paymentId:Pt.paymentId??It.paymentId,sessionId:Pt.sessionId??It.sessionId,authorizationExpiresAt:Pt.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Wt,checkoutMethod:"card"})},600)}),Q=tt.on("decline",Pt=>{let It=wn.current,Ft=Pt.message??"Your payment was declined. Please try another card or contact your bank.";ce.current="terminal",y(!1),It.updateError(Ft),le("error");let Wt=Pt.failureOutcome??(0,d.normalizeCheckoutFailureOutcome)(Pt.declineReason)??"authorization_declined";It.emitDecline("card",Ft,{code:Wt,declineCode:Wt}),D()}),Ee=tt.on("error",Pt=>{let It=wn.current,Ft=Pt.message??"There was a problem processing your payment. Please try again.";ce.current="terminal",y(!1),It.updateError(Ft),le("error"),It.onError?.(new d.FloPayError(Ft,"api_error",{code:Pt.failureOutcome??"capture_failed"})),D()}),zt=tt.on("challenge_dismissed",()=>{W.current&&(clearTimeout(W.current),W.current=null),ce.current="processing",y(!0),le(null)}),un=tt.on("blocked",()=>{if(G.current){wn.current.updateError(Ad);return}if(!As.current){vn(!0);return}Ti(),wn.current.updateError(zl)});return()=>{s&&(clearTimeout(s),s=null),W.current&&(clearTimeout(W.current),W.current=null),ce.current="idle",y(!1),le(null),ae(),Re(),Q(),Ee(),zt(),un()}},[ye,tt,Ti,xs]);let Ln=!!Ct?.clientId,ea=Array.isArray(_),Fa=ea&&_.length>0,Fs=ea&&_.includes("paypal"),Ba=(0,o.useRef)(null);Ba.current===null&&(Ba.current=(0,d.hasMatchingStripePayPalReturn)());let _o=Ba.current?"redirect":(0,zn.resolveStripePayPalPresentation)(ct,Ie,M.current()),{expressMethods:Da,paymentElementMethods:xi}=(0,o.useMemo)(()=>(0,d.partitionStripeMethods)(_,{excludePaypal:Ln}),[_,Ln]),Bs=Ln||!!Dt||Fs&&_o==="redirect",bc=(0,o.useMemo)(()=>Bs?Da.filter(s=>s!=="paypal"):Da,[Da,Bs]),Sc=(0,o.useMemo)(()=>{let s=[];return me&&s.push("apple_pay"),ue&&s.push("google_pay"),s},[me,ue]),To=ea?bc:Sc,wc=b&&To.length>0,Ds=Fr?Ht:j,Oa=(0,o.useMemo)(()=>(0,d.filterStripeMethodsByCountryGate)(xi,Ds,ie),[xi,Ds,ie]),Ai=(0,o.useMemo)(()=>({mode:"payment",amount:Qo,currency:Ro,paymentMethodCreation:"manual",appearance:Es}),[Qo,Ro,Es]),[Os,Ls]=(0,o.useState)("loading"),[Ns,Us]=(0,o.useState)("loading"),[zs,qs]=(0,o.useState)("loading"),[kc,Fi]=(0,o.useState)(!1),[js,Bi]=(0,o.useState)("loading"),[Di,Rc]=(0,o.useState)();(0,o.useEffect)(()=>{Rc((0,Un.detectPayPalEnvironment)())},[]);let La=Di?.inAppBrowser,Na=Di?(0,zn.resolvePayPalPresentationMode)(Di,Ct?.approvalPresentation,Bt??(Ce?"subscription":"order")):"popup",Vs=pe&&(Ln||(ea?Fs:La===!1)),Ec=ct.inAppBrowser&&M.current()==="blocked",Ws=b&&wc&&!Ec,ta=(!V||!!be.waitForDataAttachment)&&Vs&&Ln,$s=js==="retrying"||js==="exhausted",ra=null;b&&(Dt?ra=Rs:_o==="redirect"&&(ra=on));let Hs=(0,o.useMemo)(()=>({...mt,presentationMode:_o}),[mt,_o]),na=!V&&Vs&&!!ra&&(!Ln||$s),Mo=!V&&Ws&&!!on,oa=!V&&b&&Fa&&Oa.length>0&&!!on,Ic=ta&&!$s?kc:na&&ts(Os),_c=Mo&&ts(Ns),Tc=oa&&zs!=="load_error",Ks=s=>s==="loading"||s==="ready",Gs=ta||na&&Ks(Os)||Mo&&Ks(Ns)||oa&&zs!=="load_error",Ua=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Ua.current){if(!b&&!pe){Ua.current=!0;let s=new d.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(s),qe(s.message)}else if(!b&&pe&&!Ln){Ua.current=!0;let s=new d.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(s),qe(s.message)}else if(La!==void 0&&!V&&!Xt&&!Gs){Ua.current=!0;let s=new d.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(s),qe(s.message)}}},[b,pe,Ln,La,V,Xt,Gs,p,qe]);let Ys=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(Ys.current||!Fa)return;let s=[];me!==!0&&s.push("showApplePay"),ue!==!0&&s.push("showGooglePay"),s.length!==0&&(Ys.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Fa,me,ue]);let Xs=(0,o.useCallback)((s,D,ae)=>be.applyInlineSessionPatch?be.applyInlineSessionPatch(s).then(Re=>({error:null,sessionId:Re.sessionId||e,nonce:Re.session?.clientSecret||t})).catch(Re=>{let Q=(0,d.normalizeBeforeButtonClickError)(D,Re);return ae?.abandoned?.()||(qe(Q.message),p?.(Q)),{error:Q,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[be.applyInlineSessionPatch,t,p,e,qe]),kn=(0,o.useCallback)(async(s,D)=>{if(s!=="card"&&V&&await be.waitForDataAttachment?.(),!Oe)return{proceed:!0};try{let ae=await Oe({method:s,sessionId:e||void 0,createSession:be.inlineSessionDraft});if(ae===!1)return{proceed:!1};if(ae&&typeof ae=="object"){ae.account&&dt(Q=>({...Q??{},...ae.account}));let Re=await Xs(ae,s,D);return Re.error?{proceed:!1,accountPatch:ae.account}:{proceed:!0,accountPatch:ae.account,sessionId:Re.sessionId,nonce:Re.nonce}}return{proceed:!0}}catch(ae){if(!D?.abandoned?.()){let Re=(0,d.normalizeBeforeButtonClickError)(s,ae);qe(Re.message),p?.(Re)}return{proceed:!1}}},[Xs,be.inlineSessionDraft,be.waitForDataAttachment,V,Oe,p,e,qe]),Js=(0,o.useCallback)(async(s,D)=>{if(q.current)return;q.current=!0,Ut(!0),le("processing"),qe(null);let ae=D?.sessionId??e,Re=D?.nonce??t,Q=Ki(he,D?.accountPatch),Ee=D?.completionPaymentMethodId??ma(s),zt=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,un=Ld(s),Pt=D?.presentationMode?ni(kr(Ae),{...mt,presentationMode:D.presentationMode}):void 0,It=()=>{_t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:un}),Pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Tn,requestCategory:"process_payment"})};try{let Ft=new Mn.PaymentAPI(yr),Wt=await Ft.processPayment(Q.userId??"",{sessionId:ae,nonce:Re,paymentMethodCategory:D?.paymentMethodCategory??Ud(s),tokenizedData:zt,accountData:{...D?.accountPatch,userId:Q.userId??"",email:Q.email??"",firstName:Q.firstName||void 0,lastName:Q.lastName||void 0,...(0,d.buildProcessPaymentAvsAccount)({avsConfig:Ye,country:lr.current,zip:wt.current,city:Yt.current,state:cr.current,addressLine1:Gt.current,addressLine2:hr.current})},...(0,d.buildCheckoutProcessMetadata)({chv:Y,avsCheck:ot,checkoutType:_e,checkoutLayout:et,avsConfig:Ye,country:lr.current})}),go=async Sr=>{let ho=(0,d.isAuthorizationOnlySession)(T)||Sr?.status==="authorized";(0,_n.markSessionRecentlyCompleted)(ae),Pt?.terminal({outcome:"payment_succeeded",...Tn}),le("success"),Xe(null),await new Promise(da=>setTimeout(da,600));let Nn;typeof Sr?.paymentId=="string"?Nn=Sr.paymentId:T?.paymentId&&(Nn=T.paymentId);let Po;typeof Sr?.authorizationExpiresAt=="string"?Po=Sr.authorizationExpiresAt:T?.authorizationExpiresAt&&(Po=T.authorizationExpiresAt),l?.(ho?{status:"authorized",...Nn===void 0?{}:{paymentId:Nn},sessionId:typeof Sr?.sessionId=="string"?Sr.sessionId:ae,...Po===void 0?{}:{authorizationExpiresAt:Po},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Ee,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Ee,checkoutMethod:s.isPaypal?"paypal":"card"})};if(Wt.ok){await go(Wt.status===204?null:await Wt.json().catch(()=>null));return}let an=await Wt.json().catch(()=>null);if(an?.type==="paypal_redirect_required"){let Sr=an.threeDSecureToken,ho=an.paymentMethodId||s.id||"";if(!Ae||!Sr){le("error"),qe("PayPal authorization required but no token provided.");return}try{let Nn=Dt?.getRawProvider();if(!Nn){qe("PayPal is not available.");return}let Po={return_url:window.location.href};ho&&(Po.payment_method=ho);let{error:da}=await Nn.confirmPayment({clientSecret:Sr,confirmParams:Po,redirect:"if_required"});if(da){le("error");let cl=da.message??"PayPal payment failed.";qe(cl),On("paypal",cl,{code:da.code})}}catch(Nn){le("error"),qe(Nn instanceof Error?Nn.message:"PayPal authorization failed.")}return}if(an?.type==="paypal_direct_required"){let Sr=an.orderId;if(!Sr){le("error"),qe("PayPal retry required but no order id provided.");return}let ho=yt.current?.attempts??0;if(ho>=2){le("error"),qe("PayPal payment could not be completed after multiple attempts."),On("paypal","paypal_direct_required retry limit exceeded");return}Fi(!1),Bi("loading"),Xe({orderId:Sr,attempts:ho+1}),le(null);return}if(Wt.headers.get(kd)===Rd){let Sr=await Ed(Ft,ae,Re);if(Sr!==void 0){await go(Sr);return}}(0,d.classifyPaymentRejection)(Wt.status,an)?Pt?.terminal({outcome:"payment_declined",...Tn,terminalReason:"provider_declined"}):It(),le("error");let ll=an?.message??"Payment failed. Please try again.";qe(ll),On(s.isPaypal?"paypal":"card",ll,{code:an?.code??an?.gatewayErrorCode,declineCode:an?.declineCode??an?.gatewayDeclineReason}),await new Promise(Sr=>setTimeout(Sr,400))}catch(Ft){Yl(Ft)||It(),le("error"),qe(Ft instanceof Error?Ft.message:"An unexpected error occurred"),await new Promise(Wt=>setTimeout(Wt,400))}finally{Ut(!1),le(null),q.current=!1}},[yr,e,t,he,Ye,ot,_e,et,Y,Ae,Dt,T,l,qe,On,_t,mt]),Xr=(0,o.useCallback)((s,D)=>{w?w(s):Js(s,D)},[w,Js]),aa=`${Kl}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(aa);if(!s)return;let D;try{D=JSON.parse(s)}catch{nr(aa);return}if(!D||typeof D.createdAt!="number"||Date.now()-D.createdAt<0||Date.now()-D.createdAt>Gl||typeof D.paymentMethodId!="string"||typeof D.providerIntentId!="string"||typeof D.paymentMethodType!="string"||D.sessionId!==e||!t||D.nonce!==t||!To.includes(D.paymentMethodType)){nr(aa);return}nr(aa),Xr({id:D.paymentMethodId,type:"card",threeDSecureActionResultTokenId:D.providerIntentId,gateway:"stripe",paymentMethodType:D.paymentMethodType},{...D.accountPatch?{accountPatch:D.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Xr,t,e,aa,To]);let Zs=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Zs.current)return;let[s,D,ae]=(0,d.readStripeRedirectParams)();if(!s||!D||Ba.current||!Ae)return;let Re=Ae.getRawProvider();if(!Re)return;let Q=It=>{let Ft=localStorage.getItem(It);if(!Ft)return null;try{return JSON.parse(Ft)}catch{return nr(It),null}},Ee=Q(jn)??Q(Ll),zt;if(Ee?.clientSecret){if(Ee.clientSecret!==D)return;zt={...Ee.accountPatch?{accountPatch:Ee.accountPatch}:{},...Ee.sessionId?{sessionId:Ee.sessionId}:{},...Ee.nonce?{nonce:Ee.nonce}:{}}}else if(Ee?.sessionId&&Ee.sessionId!==e)return;Zs.current=!0,nr(jn),nr(Ll),window.history.replaceState({},"",(0,d.stripeRedirectReturnUrl)());let un=Ee?.paymentMethodType??Ee?.tokenType??"card",Pt="card";(async()=>{if(ae==="failed"){let Yn="Payment was declined. Please try again.";qe(Yn),On(Pt,Yn);return}let{paymentIntent:It,error:Ft}=await Re.retrievePaymentIntent(D);if(Ft){let Yn=Ft.message??"Failed to retrieve payment status.";qe(Yn),On(Pt,Yn,{code:Ft.code});return}let Wt=It?.status,go=pa(Wt);if(!It||!go){let Yn=Wt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";qe(Yn),On(Pt,Yn,{code:Wt??"missing_payment_intent"});return}let an=typeof It.payment_method=="string"?It.payment_method:It.payment_method?.id;Xr({id:an??Ee?.paymentMethodId??Ee?.tokenId??It.id,type:"card",threeDSecureActionResultTokenId:It.id,gateway:Ee?.gateway??"stripe",paymentMethodType:un},zt)})()},[e,Xr,Ae,qe,On]);let Oi=(0,o.useCallback)(s=>{s.preventDefault()},[]);if(!(ye||Ae!==null))return(0,u.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ia=xe==="buttons",Jr=ge?.variables,Mc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Li=Jr?.colorBackground,xc=Li&&!Mc.has(Li)?Li:void 0,sa=A.cardInputBorder??(ia?"#e5e7eb":"#A4A4FF"),Qs=Jr?.colorDanger??"#dc2626",Jt=s=>Br[s]&&(cn[s]||Qt),za=ko&&(jr||Qt),dn=s=>s?Qs:sa,qa=(Lt.malformed||Lt.empty)&&($n||Qt),Ac=dn(qa),Ni=A.cardFormContainer?.backgroundColor??xc??(ia?"white":"#EDEDFF"),xo=A.cardInputBackground??Jr?.colorBackground??"white",Ui=Bo(De),el=Bo(de),Ao=A.nameInput,tl=A.cardInputFontSize??Vd(Ao?.fontSize)??Jr?.fontSizeBase??"16px",rl=typeof Ao?.fontFamily=="string"?Ao.fontFamily:Jr?.fontFamily??"Poppins, sans-serif",nl=(0,d.toCssWeight)(Ao?.fontWeight)??400,Fc=A.cardInputColor??(typeof Ao?.color=="string"?Ao.color:void 0)??Jr?.colorText??"#262833",Bc=A.cardInputPlaceholderColor??"#9ca3af",tr=Jr?.borderRadius??"8px",yo=Jr?.borderRadius??A.cardButton?.borderRadius??tr,fo=Jr?.colorPrimary??"#4A49FF",Dc=Jr?.colorPrimaryHover??(0,d.darkenHex)(fo,.12),zi=Jr?.colorText??"#262833",qi={fontSize:tl,fontFamily:rl,fontWeight:nl,color:Fc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},la={marginTop:"0.375rem",...qi,fontSize:"0.75rem",lineHeight:1.4,color:Qs},Oc={"--flopay-input-placeholder-color":Bc,"--flopay-input-font-size":tl,"--flopay-input-font-family":rl,"--flopay-input-font-weight":String(nl)},ca=A.cardFormContainer??{},ji=ca.padding??(ia?"0":"1rem"),Vi=ca.borderRadius??tr,Lc=tt&&Gr?(0,u.jsx)(co,{capture:tt,html:Gr.html,messageToken:Gr.messageToken,expectedOrigin:Gr.expectedOrigin,verificationRequired:Gr.verificationRequired,theme:Je,submitLabel:ee,onReady:()=>{if(!io&&!Ye||typeof document>"u")return;let s=()=>{let ae=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(ae){en.current=!0;try{ae.focus()}finally{en.current=!1}}};Bn.current||s()},onError:s=>{s&&Gr.verificationRequired&&ce.current==="idle"&&(Dn.current=!0),qe(s)},onValidation:s=>{let D=ce.current;(D==="idle"||D==="validation-window")&&(qe(s),s&&ce.current==="validation-window"&&(W.current&&(clearTimeout(W.current),W.current=null),ce.current="idle",le(null)))}},Dr):(0,u.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ol=(0,u.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&Kn()},style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji,...Oc,display:"flex",flexDirection:"column"},children:[(0,u.jsx)("style",{children:`
30
+ `,Jo=44;function Zo(){return(0,xr.jsx)("style",{children:wd})}function Ra(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function Ea({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,xr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,xr.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,xr.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:n})]})}function as(e){return e!=="unavailable"&&e!=="load_error"}function di({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:l,backgroundColor:p,borderColor:m,textColor:h,borderRadius:R,fontFamily:w}){let I=(0,lo.resolveStripeMethodBrandVariant)(e,t),Y=Wl[e],[_,Z]=(0,$l.useState)(!1),A=!!Y&&!_,y=I?.backgroundColor??p??"#ffffff",P=I?.borderColor??m??"#d1d5db",me=I?.textColor??h??"#262833";return(0,xr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&l()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Jo,padding:"0 1rem",backgroundColor:y,color:me,border:`1px solid ${P}`,borderRadius:R??8,fontSize:"0.95rem",fontWeight:600,fontFamily:w,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,xr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,lo.getStripeMethodDisplayName)(e)}\u2026`}):(0,xr.jsxs)(xr.Fragment,{children:[(0,xr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,lo.hasVendoredStripeMethodLogo)(e)?8:0},children:[A?(0,xr.jsx)("img",{src:Y,alt:"","aria-hidden":"true",onError:()=>Z(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!A&&I?.logoSvg?(0,xr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:I.logoSvg}}):null,(0,xr.jsx)("span",{children:(0,lo.getStripeMethodDisplayName)(e)})]}),s&&(0,xr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:me,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,xr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function ui(e){let t=new Set(e.map(lo.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var pi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},mi={type:"accordion",defaultCollapsed:!1,radios:"never"};function yi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:l,children:p}){return(0,xr.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:s,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...l??{}},children:p})}var mn=require("react");var Ia=require("@flopay/shared"),kd=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function Rd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return kd.has(t.charAt(0).toLowerCase()+t.slice(1))}function Ed(e,t){return typeof t=="number"&&t!==0&&!Rd(e)?`${t}px`:String(t).trim()}function Hl(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=Ed(r,n)}}}var Eo=require("react/jsx-runtime"),is=new WeakSet;function go({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:l,containerStyle:p,onReady:m,onError:h,onValidation:R}){let w=(0,mn.useRef)(null),I=(0,mn.useRef)(m),Y=(0,mn.useRef)(h),_=(0,mn.useRef)(R);I.current=m,Y.current=h,_.current=R;let Z=(0,mn.useRef)(s);Z.current=s;let A=(0,mn.useRef)(null),y=l??void 0,P=(0,mn.useRef)(y);P.current=y;let me=(0,mn.useRef)(void 0);return(0,mn.useEffect)(()=>{let S=w.current;if(!S)return;let xe=!0,T=!1,le=()=>{!xe||T||(T=!0,I.current?.())},ye=e.on("ready",()=>{le()}),pe=e.on("error",B=>{Y.current?.(B.message??"There was a problem loading the secure card form.")}),Re=e.on("validation",B=>{_.current?.(B.message??null)}),lt=P.current??(is.has(e)?null:void 0),$e={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...Z.current?{theme:Z.current}:{},...lt===void 0?{}:{submitLabel:lt}};return A.current=Z.current??null,me.current=P.current,P.current!==void 0&&is.add(e),e.mount(S,$e).then(()=>{le()}).catch(B=>{xe&&Y.current?.(B instanceof Error?B.message:"Failed to load the secure card form.")}),()=>{xe=!1,ye(),pe(),Re(),e.unmount()}},[e,t,r,n,a]),wo(()=>{let S=w.current;S&&Hl(S,p)},[p]),(0,mn.useEffect)(()=>{s!==void 0&&(s===null&&A.current===null||(A.current=s,e.applyTheme?.(s)))},[e,s]),(0,mn.useEffect)(()=>{y!==me.current&&(me.current=y,y!==void 0&&is.add(e),e.setSubmitLabel?.(y??null))},[e,y]),(0,Eo.jsx)("div",{ref:w,"data-testid":"flopay-vault-card-fields"})}function fi({label:e}){return(0,Eo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,Eo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,Eo.jsx)("span",{children:e}),(0,Eo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var hs=require("@flopay/shared"),u=require("react/jsx-runtime"),Gn="flopay_stripe_resume",Kl="flopay_wallet_resume",nc="fw1",Id="fw2",oc=300*1e3,_d=900,Td="express_checkout_click_timeout",Md=25e3,xd=25e3,Ad=1e4,Dn={provider:"paypal",paymentMethodCategory:"paypal"},Fd="x-flopay-process-result-source",Bd="status";async function Dd(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var gi={},Ta=class{constructor(t){this.reason=t}};function Od(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function dr(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ys(e){return`${Id}:${e}`}function hi(e){return dr(ys(e))}function Pi(e,t){if(typeof window>"u")return null;let r=ys(e);try{let n=localStorage.getItem(r);if(!n)return null;let a=JSON.parse(n);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>oc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(hi(e),null):a}catch{return hi(e),null}}function Ld(e){return dr(ys(e.sessionId),e)}function Gl(e,t,r){let n=Pi(e,t);return!n||n.clientSecret!==r?!1:hi(e)}function ss(e,t,r){if(typeof window>"u")return;Pi(e,t)?.clientSecret===r&&hi(e)}function Nd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ls(e,t,r){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let n=r?e.status==="succeeded":ya(e.status),a=Nd(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Yl(e,t,r){let n=null;try{return await Promise.race([Il(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Ad),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Ud(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function ac(e){return e instanceof d.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function vi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new On.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw ac(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var cs=d.STRIPE_PAYPAL_RESUME_KEY,_a=new Map,zd=250,Xl="Just a moment \u2014 we are finalizing your order. Please press pay again.",qd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function fs(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function Ci({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new On.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function jd(e){return e instanceof d.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ic({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,jo.splitFullName)(r),l=s.firstName?s:(0,jo.splitFullName)(n?.name);return(0,vn.compactBuyerIdentity)({email:(0,d.isValidEmail)(a)?a:n?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Vd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let l=ic({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,d.isValidEmail)(l.email)?l:s(a,l)}var Ma=180,Jl=`flopay-card-enter ${Ma}ms cubic-bezier(0, 0, 0.2, 1) both`,Zl=`flopay-card-exit ${Ma}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Wd=`flopay-buttons-enter ${Ma}ms cubic-bezier(0, 0, 0.2, 1) both`,$d=`flopay-buttons-exit ${Ma}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Hd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function gs(e){return(0,d.derivePrimaryTileStyle)(e)}var Kd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Gd(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var us={width:"100%",minHeight:Jo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Ql(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ps(e){return e==="paypal"?"PayPal":(0,d.getStripeMethodDisplayName)(e)}function Yd(e){let t=(0,d.getPostalCodeExample)(e);return`Enter a valid ${(0,d.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Xd(e,t,r){let n=(0,d.isPostalCodeSupported)(e),a=t.trim(),s=r&&n,l=s&&!a,p=s&&!!a&&!(0,d.isValidPostalCode)(e,a);return{visible:r,supported:n,required:s,empty:l,malformed:p}}function Jd(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,d.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function Zd(e){return typeof e=="number"?`${e}px`:e}function bi(e){return(0,u.jsx)(tu,{...e})}function ec({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:l=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:h,runBeforeButtonClick:R,billingName:w,onBuyerIdentityReady:I,onLoadStateChange:Y,placeholderBorderRadius:_,popupCapabilityOwner:Z,externalTelemetryContext:A,presentationMode:y}){let P=io(),{emitInstrument:me}=(0,o.useContext)(Pn),S=(0,cr.useStripe)(),xe=(0,cr.useElements)(),T=(0,o.useMemo)(()=>ci(wr(P),A),[A,P]),[le,ye]=(0,o.useState)("loading");(0,o.useEffect)(()=>{Y?.(le)},[le,Y]);let[pe,Re]=(0,o.useState)(!1),lt=(0,o.useRef)(!1),$e=!(0,d.isValidEmail)(r?.trim())||!w?.trim(),{request:B,collect:wt,finish:Ye}=Vo(),Ne=(0,o.useRef)(!1),ue=(0,o.useRef)(null),ne=(0,o.useRef)(null),[K,Le]=(0,o.useState)(0),[nt,je]=(0,o.useState)(!1),X=(0,o.useRef)(!1),$=(0,o.useRef)(new Map),{startAttempt:H,finishAttempt:V,invalidateAttempt:Ve,isAttemptInvalidated:De,isAttemptCurrent:fe,generationRef:D}=Pa((be,M,gt)=>{h?.(be,M,{...gt,popupBlocked:gt?.popupBlocked??(0,ke.isPopupBlockedError)(M),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y,terminalReason:"overlay_timeout"}),je(!0),Le(ct=>ct+1)},{onHandoffObserved:()=>{Z.markAvailable(),T?.log({name:"provider.popup.opened",stage:"overlay_open",...Dn,attempt:D.current})}});(0,o.useEffect)(()=>{nt&&ne.current?.focus()},[nt,K]);let ge=(0,o.useCallback)(()=>{Le(be=>be+1)},[]),pt=(0,o.useCallback)((be,M,gt)=>{Ve(gt),h?.("paypal",be,{code:M,popupBlocked:(0,ke.isPopupBlockedError)(be),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y}),je(!0),ge()},[Ve,h,y,ge]),Ue=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ue.current?.querySelector("iframe")??ue.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{X.current&&(X.current=!1,Ue())},[Ue,K]);let ot=(0,o.useCallback)(()=>{je(!1),s?.(null),Ue()},[Ue,s]);(0,o.useEffect)(()=>{if(!S||Ne.current)return;let[be,M,gt]=(0,d.readStripeRedirectParams)();if(!be||!M)return;let ct=(0,d.readMatchingStripePayPalContinuation)(M);if(!ct)return;Ne.current=!0;let N=!0,Fe=_a.get(M);Fe||(Fe=gt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>S.retrievePaymentIntent(M)),_a.set(M,Fe));let Lt={accountPatch:ct.accountPatch,sessionId:ct.sessionId,nonce:ct.nonce},Se=()=>{T?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Dn,requestCategory:"provider_sdk"})};return T?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Dn}),(async()=>{try{Re(!0);let b=await Fe;if(!N)return;if(b?.error){_a.delete(M),Se(),s?.(b.error.message??"Failed to retrieve PayPal payment status.");return}if((0,d.clearStripePayPalReturn)(),_a.delete(M),gt==="failed"){let Be="PayPal payment was declined. Please try again.";T?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}),s?.(Be),m?.(Sr("paypal",Be));return}let x=b?.paymentIntent;if(x&&x.id!==be){Se(),s?.("Failed to match the returned PayPal payment.");return}if(x&&(x.status==="requires_capture"||x.status==="succeeded")){let Be=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id;a({id:Be??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0},{...Lt,presentationMode:"redirect"})}else{let Be="PayPal payment was not completed. Please try again.";T?.terminal({outcome:x?.status==="canceled"?"payment_cancelled":"payment_declined",...Dn,terminalReason:x?.status==="canceled"?"cancelled":"provider_declined"}),s?.(Be),m?.(Sr("paypal",Be))}}catch(b){if(!N)return;_a.delete(M),Se(),s?.(b instanceof Error?b.message:"Failed to complete PayPal payment.")}finally{N&&Re(!1)}})(),()=>{N=!1,Ne.current=!1}},[S,a,s,m,T]);let Ae=(0,o.useCallback)(async(be=!1)=>{let M=R?await R("paypal"):{proceed:!0};if(!M.proceed)return $.current.delete(K),!1;let gt=H("paypal");return $.current.set(K,{generation:gt,accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}),je(!1),T?.log({name:`provider.${be?"redirect.started":"handoff.requested"}`,stage:be?"redirect":"overlay_open",...Dn,attempt:gt}),p?.("paypal"),!0},[p,T,R,H,K]),Qe=(0,o.useCallback)(async be=>{if(l||pe||!await Ae()){be.reject();return}be.resolve()},[l,Ae,pe]),at=(0,o.useCallback)(async be=>{if(!S||!xe)return;let M=$.current.get(K);if(M&&!fe(M.generation)){$.current.delete(K);return}if(!M&&De()||M&&!V(M.generation))return;M||V();let gt=M??null;if($.current.delete(K),!gt&&R){let It=await R("paypal");if(!It.proceed){be.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}gt={accountPatch:It.accountPatch,sessionId:It.sessionId,nonce:It.nonce}}let ct=gt?.sessionId??e,N=gt?.nonce??t,Fe=await Vd({event:be,prepared:gt,email:r,billingName:w,methodLabel:"PayPal",collect:wt});if(!Fe){be.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Lt=Fe.email,Se={...gt?.accountPatch,...(0,vn.compactBuyerIdentity)(Fe,!0)};try{if(Re(!0),s?.(null),!ct||!(0,d.isValidEmail)(Lt))throw new Error("Missing sessionId or email for PayPal payment");await I?.(Fe);let It=S.createPaymentMethod,{error:b,paymentMethod:x}=await It({type:"paypal"});if(b){pt(b,"stripe_paypal_create_payment_method_failed",M?.generation),be.paymentFailed({reason:"fail"});return}let Be=await vi(n,me,ct,N??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:x?.id??null,intentKind:"payment"});if((0,d.isSettledSessionIntent)(Be)){be.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:Se,paymentMethodCategory:"paypal",presentationMode:y,sessionId:ct,nonce:N,settledProcessResponse:Be.response});return}if(Be.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ee=Be.clientSecret,dt={return_url:(0,d.stripeRedirectReturnUrl)()};if(x?.id&&(dt.payment_method=x.id),!dr(cs,{clientSecret:Ee,sessionId:ct,nonce:N,accountPatch:Se})&&y==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:We,paymentIntent:He}=await S.confirmPayment({clientSecret:Ee,confirmParams:dt,redirect:"if_required"});if(We){if(dr(cs),(0,ke.isProviderDecline)(We)){let c=We.message??"Your payment was declined.";T?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}),s?.(c),m?.(Sr("paypal",c,{code:(0,ke.getProviderErrorCode)(We),declineCode:(0,ke.getProviderDeclineCode)(We)})),await Ci({billingApiUrl:n,sessionId:ct,nonce:N,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,ke.getProviderErrorCode)(We)??"provider_declined"}})}else pt(We,"stripe_paypal_confirm_failed",M?.generation);return}dr(cs);let Dt=typeof He?.payment_method=="string"?He.payment_method:He?.payment_method?.id;a({id:Dt??He?.id,type:"card",threeDSecureActionResultTokenId:He?.id,isPaypal:!0},{accountPatch:Se,paymentMethodCategory:"paypal",presentationMode:y,sessionId:ct,nonce:N});return}catch(It){pt(It,"stripe_paypal_failed",M?.generation)}finally{Re(!1)}},[S,xe,e,t,r,w,wt,I,n,me,a,s,m,R,pt,V,fe,De,T,y,K]),pr=(0,o.useCallback)(async()=>{if(!(lt.current||l||pe||!S||!xe)){lt.current=!0,Re(!0);try{if(!await Ae(!0))return;await at({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{lt.current=!1,Re(!1)}}},[xe,at,l,Ae,S,pe]),Mt=y==="redirect"?(0,u.jsx)("button",{type:"button",disabled:l||pe,onClick:()=>{pr()},style:{width:"100%",minHeight:Jo,border:"1px solid #d1d5db",borderRadius:_??8,background:"#ffc439",color:"#111827",cursor:l||pe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,u.jsx)(cr.ExpressCheckoutElement,{onReady:be=>ye(Ra(be,["paypal"])),onLoadError:()=>{ye("load_error"),fs(T,"paypal","paypal","provider_error")},onClick:Qe,onConfirm:at,onCancel:()=>{let be=$.current.get(K);$.current.delete(K),T?.terminal({outcome:"payment_cancelled",...Dn,terminalReason:"cancelled",...be?{attempt:be.generation}:{}}),Ve(be?.generation),je(!1),X.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:$e,emailRequired:$e,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},K),vt=(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("div",{ref:ue,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[nt&&(0,u.jsx)("button",{ref:ne,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:us,children:"Try PayPal again"}),B&&(0,u.jsx)(Wo,{identity:B.identity,methodLabel:B.methodLabel,onComplete:Ye,onCancel:()=>Ye(null)},B.id),(0,u.jsx)("div",{style:{display:B?"none":void 0},children:Mt})]}),pe&&!B&&(0,u.jsx)(sn,{status:"processing"})]});return y==="redirect"?vt:(0,u.jsx)(Ea,{state:le,placeholderTestId:"flopay-paypal-placeholder",borderRadius:_,children:vt})}function ds(e){return e==="apple_pay"||e==="google_pay"}var Qd=200;function eu({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,d.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function tc({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:l,onErrorChange:p,onButtonClick:m,onDecline:h,onTechnicalFailure:R,runBeforeButtonClick:w,billingName:I,onBuyerIdentityReady:Y,onLoadStateChange:_,placeholderBorderRadius:Z,popupCapabilityOwner:A,externalTelemetryContext:y}){let P=io(),{emitInstrument:me}=(0,o.useContext)(Pn),S=(0,cr.useStripe)(),xe=(0,cr.useElements)(),T=(0,o.useMemo)(()=>ci(wr(P),y),[y,P]),[le,ye]=(0,o.useState)("loading");(0,o.useEffect)(()=>{_?.(le)},[le,_]);let[pe,Re]=(0,o.useState)(!1);(0,o.useEffect)(()=>{je.current=pe},[pe]);let lt=(0,o.useRef)(!(0,d.isValidEmail)(r?.trim())||!I?.trim()).current,{request:$e,collect:B,finish:wt}=Vo(),Ye=(0,o.useRef)(null),Ne=(0,o.useRef)(null),[ue,ne]=(0,o.useState)(0),[K,Le]=(0,o.useState)(()=>(0,d.shouldPreferWalletPopup)()),nt=(0,o.useRef)(K),je=(0,o.useRef)(!1),[X,$]=(0,o.useState)(!1),[H,V]=(0,o.useState)(()=>Pi(e,t)?"blocked":"idle"),[Ve,De]=(0,o.useState)("google_pay"),fe=(0,o.useRef)(null),D=(0,o.useRef)(!0),ge=(0,o.useRef)(!1),pt=(0,o.useRef)("google_pay"),Ue=(0,o.useRef)("google_pay"),ot=(0,o.useRef)(null),Ae=(0,o.useRef)(null),Qe=(0,o.useRef)(new Set),at=(0,o.useRef)(null),pr=(0,o.useRef)(null);(0,o.useEffect)(()=>(D.current=!0,()=>{D.current=!1;for(let c of Qe.current)window.clearTimeout(c);Qe.current.clear()}),[]);let Mt=(0,o.useRef)(new Map),{startAttempt:vt,finishAttempt:be,invalidateAttempt:M,isAttemptInvalidated:gt,isAttemptCurrent:ct,generationRef:N}=Pa((c,U,W)=>{R?.(c,U,{...W,popupBlocked:W?.popupBlocked??(0,ke.isPopupBlockedError)(U),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),De(c),$(!0),ne(ce=>ce+1)},{onHandoffObserved:c=>{pr.current=N.current,A.markAvailable(),T?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:N.current,...c==="apple_pay"||c==="google_pay"?{walletType:c}:{}})},defersMissingTerminal:ds,onMissingTerminalDeferred:(c,U)=>{let W=T?.now()??globalThis.performance?.now()??Date.now(),ce=at.current,E=ce?.generation===U?ce.startedAt:W;T?.performance({stage:"overlay_return",durationMs:Math.max(0,W-E),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:U,...ds(c)?{walletType:c}:{}}),T?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{X&&Ne.current?.focus()},[X,ue]);let Fe=(0,o.useRef)(0),Lt=(0,o.useRef)(!1),Se=(0,o.useCallback)(()=>{if(Fe.current>0){Lt.current=!0;return}ne(c=>c+1)},[]),It=(0,o.useCallback)(()=>{Fe.current-=1,!(Fe.current>0||!Lt.current)&&(Lt.current=!1,D.current&&ne(c=>c+1))},[]),b=(0,o.useCallback)((c,U,W,ce,E=!1)=>{M(ce),R?.(c,U,{code:W,popupBlocked:(0,ke.isPopupBlockedError)(U),telemetryReported:E,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),De(c),$(!0),Se()},[M,R,Se]),x=(0,o.useCallback)(c=>{T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...ds(c)?{walletType:c}:{}}),R?.(c,new Error("The wallet click was not ready within the time the wallet allows."),{code:Td,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),De(c),$(!0)},[R,T]),Be=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Ye.current?.querySelector("iframe")??Ye.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{ge.current&&(ge.current=!1,Be())},[Be,ue]);let Ee=(0,o.useCallback)(()=>{$(!1),p?.(null),Be()},[Be,p]),dt=(0,o.useCallback)(()=>{fe.current?.()},[]);(0,o.useEffect)(()=>{let c=null,U=()=>{c=null;let ce=(0,d.shouldPreferWalletPopup)();ce!==nt.current&&(nt.current=ce,Le(ce),!je.current&&!ct(N.current)&&Se())},W=()=>{c!==null&&window.clearTimeout(c),c=window.setTimeout(U,Qd)};return window.addEventListener("resize",W),()=>{window.removeEventListener("resize",W),c!==null&&window.clearTimeout(c)}},[N,ct,Se]),(0,o.useEffect)(()=>{let c=Pi(e,t);if(!c)return;let U=!1,W=!1,ce=async()=>{if(!W){W=!0,U||V("checking");try{let E=await Yl(S,c.clientSecret,Qe.current);if(U)return;let z=ls(E,c.providerObjectId,(0,d.isSetupIntentClientSecret)(c.clientSecret));if(z.kind==="confirmed"){if(!Gl(e,t,c.clientSecret))return;fe.current=null,V("idle"),l({id:z.paymentMethodId,type:"card",threeDSecureActionResultTokenId:z.intentId},{...c.accountPatch?{accountPatch:c.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(z.kind==="terminal"){ss(e,t,c.clientSecret),fe.current=null,V("idle"),De(c.paymentMethodType),$(!0),Se();return}V("blocked")}catch{U||V("blocked")}finally{W=!1}}};return fe.current=ce,V("blocked"),()=>{U=!0,fe.current===ce&&(fe.current=null)}},[t,l,Se,e,S]);let it=(0,o.useCallback)(async c=>{let U=!1,W=!1,ce=et=>{U||W||(U=!0,c.paymentFailed({reason:"fail",...et?{message:et}:{}}))};if(!S||!xe){ce();return}let E=Mt.current.get(ue);if(E&&!ct(E.generation)){Mt.current.delete(ue),ce();return}if(!E&&gt()){ce();return}if(E&&!be(E.generation)){ce();return}E||(be(),Lt.current=!1);let z=c.expressPaymentType??E?.method??pt.current,Ut=E??null,Fr=Ql(z),tr;z==="apple_pay"?tr="apple_pay":z==="google_pay"&&(tr="google_pay");let Wt=E?.generation??N.current,_t=T,$r=_t?.now()??globalThis.performance?.now()??Date.now(),Nr=new AbortController,rr=!1,Qr=!1,Tt=null,Ln=e,Xt="processing",yn="other",Hr="provider_runtime",Kr,Jt=new Promise((et,kt)=>{Kr=kt}),Pr=window.setTimeout(()=>{rr=!0,Nr.abort(),Kr(gi)},Md),en=async(et,kt,Br)=>{Xt=et,yn=kt,Hr=kt==="intent_create"||kt==="session_claim"?"transport_error":"provider_runtime";let $t=_t?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Br,Jt])}finally{let nr=_t?.now()??globalThis.performance?.now()??Date.now();_t?.performance({stage:et,durationMs:Math.max(0,nr-$t),durationMode:"machine",requestCategory:kt,paymentMethodCategory:"wallet",provider:"stripe",...rr?{statusClass:"timeout"}:{}})}};try{if(Re(!0),p?.(null),!Ut&&w){let Pe=await en("processing","other",w(Fr));if(!Pe.proceed){ce();return}Ut={accountPatch:Pe.accountPatch,sessionId:Pe.sessionId,nonce:Pe.nonce}}let et=Ut?.sessionId??e;Ln=et;let kt=Ut?.nonce??t,Br=ot.current??Ut?.accountPatch,$t=ic({event:c,fallbackEmail:Br?.email??r,fallbackName:[Br?.firstName,Br?.lastName].join(" ").trim()||I});if(!(0,d.isValidEmail)($t.email)){ce("Buyer details are required."),B(ps(z),$t).then(Pe=>{Pe&&(ot.current=Pe)});return}ot.current=null;let nr={...Ut?.accountPatch,...(0,vn.compactBuyerIdentity)($t,!0)};await en("processing","session_claim",Promise.resolve(Y?.($t)));let{error:vr}=await en("tokenization","provider_sdk",xe.submit());if(vr){ce(),b(z,vr,"stripe_wallet_submit_failed",E?.generation);return}if(!et)throw new Error("Missing sessionId or email for payment.");let Zt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:z,paymentMethodId:null,intentKind:a},Ht=JSON.stringify({sessionId:et,nonce:kt??"",request:Zt}),Rr=Ae.current,Xe=Rr?.retryIdentity===Ht?Rr.authorizationAttemptId:(0,d.randomUuidV4)();Ae.current={authorizationAttemptId:Xe,retryIdentity:Ht};let or=await en("processing","intent_create",vi(n,me,et,kt??"",{...Zt,authorizationAttemptId:Xe},{signal:Nr.signal}));if((0,d.isSettledSessionIntent)(or)){ce(),l({type:"card",paymentMethodType:z},{accountPatch:nr,paymentMethodCategory:"wallet",sessionId:et,nonce:kt,settledProcessResponse:or.response});return}if(or.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Er=or.clientSecret,Jn=Ld({createdAt:Date.now(),sessionId:et,...kt?{nonce:kt}:{},clientSecret:Er,providerObjectId:or.providerObjectId,paymentMethodType:z,accountPatch:nr});window.clearTimeout(Pr),Qr=!0,_t?.performance({stage:"callback",durationMs:Math.max(0,(_t?.now()??globalThis.performance?.now()??Date.now())-$r),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Ur=_t?.now()??globalThis.performance?.now()??Date.now(),zr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...tr?{walletType:tr}:{},attempt:Wt},Nn=!1,cn=null;_t?.log({name:"payment.provider_confirmation.started",...zr}),Tt=window.setTimeout(()=>{Tt!==null&&Qe.current.delete(Tt),Nn=!0;let Pe=_t?.now()??globalThis.performance?.now()??Date.now();_t?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...zr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Pe-Ur),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),_t?.flush?.().catch(()=>{}),cn?.()},xd),Qe.current.add(Tt);let ar=(Pe,Vt)=>{Tt!==null&&(window.clearTimeout(Tt),Qe.current.delete(Tt),Tt=null);let ae=_t?.now()??globalThis.performance?.now()??Date.now(),Nt=Math.max(0,ae-Ur),br=Pe;Nn&&(Pe==="resolved"?br="resolved_late":Pe==="returned_error"?br="returned_error_late":br="rejected_late");let qr=Vt??(Pe==="resolved"?"approved":"provider_error");return _t?.log({name:"payment.provider_confirmation.returned",...zr,operationOutcome:br,terminalReason:qr}),_t?.performance({...zr,durationMs:Nt,durationMode:"buyer",operationOutcome:br,terminalReason:qr}),{durationMs:Nt,operationOutcome:br,terminalReason:qr}},he=!1,Cr=!1,Gr=Pe=>{if(!Pe||typeof Pe!="object")return null;let Vt=Pe;if(Vt.error)return null;let ae=Vt.setupIntent??Vt.paymentIntent,Nt=ls(ae??null,void 0,!!Vt.setupIntent);return Nt.kind==="confirmed"?Nt:null},oe=Pe=>{if(he||E&&N.current!==E.generation)return;let Vt=Gr(Pe);if(!Vt)return;if(Jn&&!Gl(et,kt,Er)){he=!0;return}let{intentId:ae,paymentMethodId:Nt}=Vt;he=!0,Cr=!0,Ae.current=null,fe.current=null,D.current&&(V("idle"),Re(!1));let br=`${nc}:${et}`;dr(br,{createdAt:Date.now(),sessionId:et,nonce:kt,accountPatch:nr,paymentMethodId:Nt,providerIntentId:ae,paymentMethodType:z});try{l({id:Nt,type:"card",threeDSecureActionResultTokenId:ae},{accountPatch:nr,paymentMethodCategory:"wallet",sessionId:et,nonce:kt})}finally{dr(br)}},xt=!1;cn=async()=>{if(!(xt||he||Cr)){xt=!0,D.current&&V("checking");try{let Pe=await Yl(S,Er,Qe.current);if(he||Cr)return;let Vt=(0,d.isSetupIntentClientSecret)(Er),ae=ls(Pe,or.providerObjectId,Vt);if(ae.kind==="confirmed"){oe(Vt?{setupIntent:Pe}:{paymentIntent:Pe});return}if(ae.kind==="terminal"){if(Cr=!0,ss(et,kt,Er),Ae.current=null,fe.current=null,!D.current)return;V("idle"),ce(),b(z,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",E?.generation,!0);return}D.current&&!Cr&&(V("blocked"),Re(!1))}catch{D.current&&!Cr&&(V("blocked"),Re(!1))}finally{xt=!1}}},fe.current=cn;let Q,Kt;try{W=!0,Fe.current+=1;let Pe;try{Pe=await((0,d.isSetupIntentClientSecret)(Er)?S.confirmSetup({elements:xe,clientSecret:Er,redirect:"if_required"}):S.confirmPayment({elements:xe,clientSecret:Er,redirect:"if_required"}))}finally{It()}if(!Pe||typeof Pe!="object")throw new Ta(Od(Pe));if(Q=Pe,!Q.error&&!Gr(Q))throw new Ta("confirmation_result_unconfirmed");Kt=ar(Q.error?"returned_error":"resolved",Q.error&&(0,ke.isProviderDecline)(Q.error)?"provider_declined":void 0)}catch(Pe){let Vt=Pe instanceof Ta?Pe.reason:void 0,ae=Vt!==void 0,Nt=ar(ae?"returned_error":"rejected");if(_t?.error({...ae?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Vt}:Zi(Pe),...zr,operationOutcome:Nt.operationOutcome,durationMs:Nt.durationMs,statusClass:"unknown",terminalReason:Nt.terminalReason}),!D.current||he)return;await cn?.();return}let ir=Q.error;if(ir){if(!D.current||he)return;if((0,ke.isProviderDecline)(ir)){Cr=!0,ss(et,kt,Er),Ae.current=null,fe.current=null,V("idle"),Mt.current.get(ue)===E&&Mt.current.delete(ue);let Pe=ir.message??"Your payment was declined.";p?.(Pe),h?.(Sr(Fr,Pe,{code:(0,ke.getProviderErrorCode)(ir),declineCode:(0,ke.getProviderDeclineCode)(ir)})),Ci({billingApiUrl:n,sessionId:et,nonce:kt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:z,providerDeclineReason:(0,ke.getProviderErrorCode)(ir)??"provider_declined",...or.intentKind==="payment"&&or.providerObjectId.startsWith("pi_")?{providerIntentId:or.providerObjectId}:{}}})}else _t?.error({...Zi(ir),...zr,operationOutcome:Kt.operationOutcome,durationMs:Kt.durationMs,statusClass:"unknown",terminalReason:Kt.terminalReason}),await cn?.();return}if(oe(Q),!he)throw new Error("Invalid provider returned for APM intent")}catch(et){if(et===gi){let kt=_t?.now()??globalThis.performance?.now()??Date.now();_t?.error({errorCode:Ud(yn),stage:Xt,requestCategory:yn,paymentMethodCategory:"wallet",provider:"stripe",...tr?{walletType:tr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ln,durationMs:Math.max(0,kt-$r),statusClass:"timeout",failureCategory:Hr,attempt:Wt,terminalReason:"provider_error"}),_t?.flush?.().catch(()=>{})}ce(),b(z,et,et===gi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",E?.generation,et===gi)}finally{if(window.clearTimeout(Pr),Tt!==null&&(window.clearTimeout(Tt),Qe.current.delete(Tt)),!Qr){let et=_t?.now()??globalThis.performance?.now()??Date.now();_t?.performance({stage:"callback",durationMs:Math.max(0,et-$r),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...rr?{statusClass:"timeout"}:{}})}D.current&&Re(!1)}},[S,xe,e,t,r,I,B,Y,n,me,a,l,p,h,w,b,It,be,ct,gt,N,T,ue]),We=(0,o.useMemo)(()=>ui(s),[s]),He=(0,o.useMemo)(()=>s.map(d.stripeExpressMethodToOptionKey),[s]),Dt=(0,o.useMemo)(()=>(0,u.jsx)(cr.ExpressCheckoutElement,{onReady:c=>{ye(Ra(c,He))},onLoadError:c=>{ye("load_error"),fs(T,"stripe","wallet","provider_error")},onClick:async c=>{let U=T?.now()??globalThis.performance?.now()??Date.now();pt.current=c.expressPaymentType,Ue.current=Ql(c.expressPaymentType);let W=!0,ce=window.setTimeout(()=>{W=!1,c.reject(),x(c.expressPaymentType)},_d),E=w?await w(Ue.current,{abandoned:()=>!W}):{proceed:!0};if(window.clearTimeout(ce),!W)return;if(!E.proceed){Mt.current.delete(ue),c.reject();return}let z=vt(c.expressPaymentType);Lt.current=!1,at.current={generation:z,startedAt:U},Mt.current.set(ue,{generation:z,method:c.expressPaymentType,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),$(!1),T?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:z,...c.expressPaymentType==="apple_pay"||c.expressPaymentType==="google_pay"?{walletType:c.expressPaymentType}:{}}),m?.(Ue.current),c.resolve()},onConfirm:it,onCancel:()=>{let c=Mt.current.get(ue);Mt.current.delete(ue);let U=at.current,W=T?.now()??globalThis.performance?.now()??Date.now();if(c&&U?.generation===c.generation&&(0,d.isWalletSheetRefusedForWindowSize)({method:c.method,elapsedMs:W-U.startedAt,handoffObserved:pr.current===c.generation})){T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:c.generation,walletType:"google_pay"}),Ae.current=null,b(c.method,new Error("The browser window is too small for the Google Pay sheet."),d.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,c.generation,!0);return}T?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...c?{attempt:c.generation}:{}}),M(c?.generation),Ae.current=null,$(!1),ge.current=!0,Se()},options:{...pi,paymentMethods:We,emailRequired:lt,billingAddressRequired:lt}},ue),[He,We,it,M,m,lt,b,x,Se,w,vt,ue,T]);return(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(Ea,{state:le,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Z,children:(0,u.jsxs)("div",{ref:Ye,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[X&&(0,u.jsxs)("button",{ref:Ne,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ee,style:us,children:["Try ",ps(Ve)," again"]}),H!=="idle"&&(0,u.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,u.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,u.jsx)("button",{type:"button",onClick:dt,disabled:H==="checking",style:us,children:H==="checking"?"Checking payment status\u2026":"Check payment status"})]}),$e&&(0,u.jsx)(Wo,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:wt,onCancel:()=>wt(null)},$e.id),(0,u.jsxs)("div",{style:{display:$e||H!=="idle"?"none":void 0},children:[(0,u.jsx)(eu,{active:K}),Dt]})]})}),pe&&(0,u.jsx)(sn,{status:"processing"})]})}function sc(e,t,r){let n=(0,d.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function ms({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:l,onTokenizedBody:p,onErrorChange:m,onDecline:h,onCancel:R,runBeforeButtonClick:w,onButtonClick:I,isProcessing:Y,submitButtonColor:_,submitButtonBorderRadius:Z,submitButtonStyle:A,errorText:y}){let P=io(),{emitInstrument:me}=(0,o.useContext)(Pn),S=(0,cr.useStripe)(),xe=(0,cr.useElements)(),[T,le]=(0,o.useState)(!1),ye=(0,o.useRef)(!1),[pe,Re]=(0,o.useState)(!1),[lt,$e]=(0,o.useState)("loading"),[B,wt]=(0,o.useState)(""),Ye=!(0,d.isValidEmail)(n?.trim()),Ne=!Ye||(0,d.isValidEmail)(B.trim()),ue=(0,o.useCallback)(async()=>{if(!S||!xe||Y||ye.current||!pe)return;ye.current=!0,le(!0);let ne=w?await w("card"):{proceed:!0};if(!ne.proceed){ye.current=!1,le(!1);return}I?.("card");let K=ne.sessionId??t,Le=ne.nonce??r,nt=(0,jo.splitFullName)(a?.trim()),je=(0,vn.compactBuyerIdentity)({email:ne.accountPatch?.email?.trim()||n?.trim()||B.trim(),firstName:ne.accountPatch?.firstName?.trim()||nt.firstName,lastName:ne.accountPatch?.lastName?.trim()||nt.lastName}),X=je.email,$=(0,vn.compactBuyerIdentity)({...ne.accountPatch,...je});try{if(m?.(null),!(0,d.isValidEmail)(X))throw new Error("A valid email address is required for payment.");await s?.(je);let H=await xe.submit();if(H.error){m?.(H.error.message??"Payment failed.");return}let V=[je.firstName,je.lastName].filter(Boolean).join(" "),Ve=await S.createPaymentMethod({elements:xe,params:{billing_details:{email:X,...V?{name:V}:{}}}});if(Ve.error||!Ve.paymentMethod){m?.(Ve.error?.message??"Failed to create payment method.");return}let De=Ve.paymentMethod;if(!K||!X)throw new Error("Missing sessionId or email for payment.");let fe=De.type||e,D=await vi(l,me,K,Le??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:fe,paymentMethodId:null,intentKind:"payment"});if((0,d.isSettledSessionIntent)(D)){p({type:"card",gateway:"stripe",paymentMethodType:fe},{accountPatch:$,paymentMethodCategory:"apm",sessionId:K,nonce:Le,settledProcessResponse:D.response});return}if(D.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ge=D.clientSecret;dr(Gn,{clientSecret:ge,sessionId:K,nonce:Le,accountPatch:$,paymentMethodId:De.id,paymentMethodType:De.type??e,gateway:"stripe"});let{error:pt,paymentIntent:Ue}=await S.confirmPayment({clientSecret:ge,confirmParams:{return_url:window.location.href,payment_method:De.id},redirect:"if_required"});if(pt){dr(Gn);let Qe=pt.message??"Payment failed.";m?.(Qe),h?.(Sr("card",Qe,{code:pt.code})),await Ci({billingApiUrl:l,sessionId:K,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:pt.code??"provider_declined"}});return}let ot=Ue?.status;if(!ya(ot)){dr(Gn);let Qe=ot==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(Qe),h?.(Sr("card",Qe,{code:ot??"missing_payment_intent"}));return}dr(Gn);let Ae=typeof Ue?.payment_method=="string"?Ue.payment_method:Ue?.payment_method?.id;p({id:Ae??De.id,type:"card",threeDSecureActionResultTokenId:Ue?.id,gateway:"stripe",paymentMethodType:De.type??e},{accountPatch:$,paymentMethodCategory:"apm",sessionId:K,nonce:Le})}catch(H){m?.(H instanceof Error?H.message:"Payment failed. Please try again.")}finally{ye.current=!1,le(!1)}},[S,xe,Y,pe,w,I,t,r,n,a,B,s,l,me,e,p,m,h]);return(0,u.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ye&&(0,u.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ye&&(0,u.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,u.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:B,onChange:ne=>wt(ne.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,u.jsx)(cr.PaymentElement,{onReady:()=>$e("ready"),onLoadError:()=>{$e("load_error"),fs(wr(P),"stripe","apm")},onChange:ne=>{Re(!!ne.complete)},options:{layout:mi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,d.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,u.jsx)(yi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ue()},disabled:!pe||!Ne||T||Y||lt!=="ready",color:_,borderRadius:Z,style:A,children:T?"Processing\u2026":`Pay with ${(0,d.getStripeMethodDisplayName)(e)}`}),y&&(0,u.jsx)(Ko,{margin:"0.75rem 0 0",children:y})]})}function rc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:l,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:h,onTokenizedBody:R,onErrorChange:w,onButtonClick:I,onDecline:Y,runBeforeButtonClick:_,onLoadStateChange:Z,isProcessing:A=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:me,buttonAppearance:S,themeId:xe,onExpandApm:T,expandedApmMethod:le}){let{emitInstrument:ye}=(0,o.useContext)(Pn),[pe,Re]=(0,o.useState)(null),[lt,$e]=(0,o.useState)(null),B=(0,o.useRef)(!1),{request:wt,collect:Ye,finish:Ne}=Vo();(0,o.useEffect)(()=>{l.length>0&&p?Z?.("ready"):p||Z?.("loading")},[l.length,p,Z]);let ue=(0,o.useCallback)(async X=>{if(!p||B.current||A)return;B.current=!0,$e(X);let $=_?await _("card"):{proceed:!0};if(!$.proceed){B.current=!1,$e(null);return}I?.("card");let H=$.sessionId??e,V=$.nonce??t,Ve=(0,jo.splitFullName)([$.accountPatch?.firstName,$.accountPatch?.lastName].filter(Boolean).join(" ")||n),De=(0,vn.compactBuyerIdentity)({email:$.accountPatch?.email?.trim()||r?.trim(),firstName:$.accountPatch?.firstName?.trim()||Ve.firstName,lastName:$.accountPatch?.lastName?.trim()||Ve.lastName});if(!(0,d.isValidEmail)(De.email)){$e(null);let ge=await Ye((0,d.getStripeMethodDisplayName)(X),De);if(!ge){B.current=!1;return}De=ge,$e(X)}let fe=De.email,D=(0,vn.compactBuyerIdentity)({...$.accountPatch,...De});try{if(w?.(null),!H||!(0,d.isValidEmail)(fe))throw new Error("Missing sessionId or email for payment.");await a?.(De);let ge=await vi(s,ye,H,V??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if((0,d.isSettledSessionIntent)(ge)){R({type:"card",gateway:"stripe",paymentMethodType:X},{accountPatch:D,paymentMethodCategory:"apm",sessionId:H,nonce:V,settledProcessResponse:ge.response});return}if(ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let pt=ge.clientSecret;dr(Gn,{clientSecret:pt,sessionId:H,nonce:V,accountPatch:D,paymentMethodType:X,gateway:"stripe"});let{error:Ue,paymentIntent:ot}=await p.confirmPayment({clientSecret:pt,confirmParams:{return_url:window.location.href,payment_method_data:{type:X,billing_details:{name:[De.firstName,De.lastName].filter(Boolean).join(" "),...fe?{email:fe}:{}}}},redirect:"if_required"});if(Ue){dr(Gn);let at=Ue.message??"Payment failed.";w?.(at),Y?.(Sr("card",at,{code:Ue.code})),await Ci({billingApiUrl:s,sessionId:H,nonce:V,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:Ue.code??"provider_declined"}});return}let Ae=ot?.status;if(!ya(Ae)){dr(Gn);let at=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";w?.(at),Y?.(Sr("card",at,{code:Ae??"missing_payment_intent"}));return}dr(Gn);let Qe=typeof ot?.payment_method=="string"?ot.payment_method:ot?.payment_method?.id;R({id:Qe??ot?.id,type:"card",threeDSecureActionResultTokenId:ot?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:D,paymentMethodCategory:"apm",sessionId:H,nonce:V})}catch(ge){w?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{B.current=!1,$e(null)}},[p,A,_,I,e,t,r,Ye,s,ye,n,a,R,w,Y]),[ne,K]=(0,o.useState)(null),Le=T?le??null:ne,nt=(0,o.useCallback)(X=>{B.current||A||Le&&Le!==X||((0,d.needsStripeMethodExplicitConfirm)(X)?T?T(X):K(X):ue(X))},[Le,A,ue,T]),je=(0,o.useMemo)(()=>ne?sc(m,ne,h):null,[ne,m,h]);return(0,u.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:wt?(0,u.jsx)(Wo,{identity:wt.identity,methodLabel:wt.methodLabel,onComplete:Ne,onCancel:()=>Ne(null)},wt.id):l.map(X=>{let $=le===X,H=lt===X,V=lt!==null&&lt!==X||le!=null&&le!==X;return(0,u.jsxs)(o.default.Fragment,{children:[(0,u.jsx)(di,{method:X,themeId:xe,submitting:H,disabled:V,highlighted:$,hasNextStep:(0,d.needsStripeMethodExplicitConfirm)(X),onClick:()=>nt(X),backgroundColor:S?.backgroundColor,borderColor:S?.borderColor,textColor:S?.textColor,borderRadius:S?.borderRadius,fontFamily:S?.fontFamily}),!T&&ne===X&&je&&p&&(0,u.jsx)(cr.Elements,{stripe:p,options:je,children:(0,u.jsx)(ms,{method:X,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:R,onErrorChange:w,onDecline:Y,onCancel:()=>K(null),runBeforeButtonClick:_,onButtonClick:I,isProcessing:A,submitButtonColor:y,submitButtonBorderRadius:P,submitButtonStyle:me})},X)]},X)})})}function tu({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:l,onError:p,onDecline:m,onCancel:h,onTokenizedBody:R,firstName:w,lastName:I,chv:Y,className:_,submitLabel:Z,isProcessing:A,error:y,onErrorChange:P,showPayPal:me=!0,showStripe:S=!0,walletPresentation:xe="auto",enabledPaymentMethods:T,enabledPaymentMethodCountries:le,showApplePay:ye=!0,showGooglePay:pe=!0,layout:Re="default",theme:lt,buttonsTheme:$e,buttonsStyles:B,appearance:wt,cardButtonContent:Ye,cardBackButtonContent:Ne,cardTitleContent:ue,showSecurityFooter:ne,onButtonClick:K,onBeforeButtonClick:Le,onBuyerIdentityReady:nt,enableAVS:je,cardFieldOrder:X,cardPreFormSlot:$,avsLayout:H="row",country:V,zip:Ve,addressLine1:De,addressLine2:fe,city:D,state:ge,onCountryChange:pt,onZipChange:Ue,avsCheck:ot,checkoutType:Ae,checkoutLayout:Qe,totalAmount:at=0,currency:pr="usd",initialCardOpen:Mt=!1,directPaypal:vt,isSubscription:be=!1,session:M,dataAttachmentPending:gt=!1,dataAttachmentRequiresIdentity:ct=!1,debug:N=!1}){let Fe=io(),Lt=Za(),Se=(0,o.useContext)(An),{emitInstrument:It}=(0,o.useContext)(Pn),b=(0,o.useRef)(null);b.current||(b.current=ei());let x=b.current,[,Be]=(0,o.useState)(0),Ee=(0,o.useRef)(null);Ee.current||(Ee.current=(0,$n.detectPayPalEnvironment)());let dt=Ee.current,it=(0,o.useMemo)(()=>({browser:dt,capability:x,presentationMode:"popup"}),[dt,x]),We=M??Se.session,He=(0,o.useMemo)(()=>({futureUse:We?.futureUse,futureUseUnsupported:We?.futureUseUnsupported}),[We?.futureUse,We?.futureUseUnsupported]),Dt=We?.gateways?.paypal?.providerObjectType??vt?.providerObjectType,c=gt||Se.claimPending===!0,U=ct||Se.claimRequiresIdentity===!0,W=c&&!U,ce=xl(),E=r||ce,[z,Ut]=(0,o.useState)(!1),[Fr,tr]=(0,o.useState)(null),[Wt,_t]=(0,o.useState)(V??""),[$r,Nr]=(0,o.useState)(Ve??""),[rr,Qr]=(0,o.useState)(De??""),[Tt,Ln]=(0,o.useState)(fe??""),[Xt,yn]=(0,o.useState)(D??""),[Hr,Kr]=(0,o.useState)(ge??""),[Jt,Pr]=(0,o.useState)(""),[en,et]=(0,o.useState)({}),kt=(0,o.useRef)(Ve??""),Br=(0,o.useRef)(V??""),$t=(0,o.useRef)(De??""),nr=(0,o.useRef)(fe??""),vr=(0,o.useRef)(D??""),Zt=(0,o.useRef)(ge??""),Ht=(0,o.useRef)(""),Rr=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(C,G,Te,J,Me)=>{if(Rr.current[C])return;let qt=G?.trim();!qt||qt===Te.current||(Te.current=qt,J(qt),Me?.(qt))};i("country",V,Br,_t,pt),i("zip",Ve,kt,Nr,Ue),i("addressLine1",De,$t,Qr),i("addressLine2",fe,nr,Ln),i("city",D,vr,yn),i("state",ge,Zt,Kr)},[V,Ve,De,fe,D,ge,pt,Ue]);let Xe=(0,o.useMemo)(()=>(0,d.resolveAVSConfig)(je),[je]),or=Xe!==null,Er=(0,o.useMemo)(()=>(0,d.isAuthorizationOnlySession)(M),[M]),Jn=(0,d.isMountableVaultBlock)(M?.vault),Ur=!!M?.gateways?.pcivault,zr=(0,xn.hasServerSideCardGateway)(M),cn=!!(M?.gateways?.stripe?.enabledPaymentMethods??T)?.includes("card")||(0,xn.canRecoverHostedCardForm)(M),ar=Jn||cn||Ur,he=!!(S&&ar&&e),[Cr,Gr]=(0,o.useState)(()=>Re!=="buttons"||Mt?e??null:null),[oe,xt]=(0,o.useState)(0),Q=Re!=="buttons"||Mt||!!e&&Cr===e,Kt=M?.captureMethod,ir=(0,o.useRef)(Fe);(0,o.useEffect)(()=>{ir.current=Fe},[Fe]);let[Pe,Vt]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!he||!e||!Q){Vt(null);return}let i=ir.current?ir.current.cardCapture({sessionId:e,captureMethod:Kt}):new On.PciVaultCardCapture({sessionId:e,captureMethod:Kt,billingApiUrl:E,telemetry:n});return Vt({sessionId:e,captureMethod:Kt,billingApiUrl:E,telemetry:n,capture:i}),()=>{i.unmount()}},[he,e,Q,Kt,E,n]);let ae=he&&e&&Q&&Pe?.sessionId===e&&Pe.captureMethod===Kt&&Pe.billingApiUrl===E&&Pe.telemetry===n?Pe.capture:null,Nt=(0,o.useMemo)(()=>{let i=Wt,C=Xe?(0,d.isAVSFieldVisible)(Xe.postal_code,i):!1;return Xd(i,$r,C)},[Xe,Wt,$r]),{avsInvalid:br,invalidAvsFields:qr}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!he||!Xe)return{avsInvalid:!1,invalidAvsFields:i};let C=Wt,G=(Me,qt)=>(0,d.isAVSFieldVisible)(Me,C)&&!qt.trim(),Te={line1:G(Xe.address_line_1,rr),city:G(Xe.city,Xt),state:G(Xe.state,Hr),zip:Nt.empty||Nt.malformed};return{avsInvalid:Te.line1||Te.city||Te.state||Te.zip,invalidAvsFields:Te}},[he,Xe,Wt,rr,Xt,Hr,Nt]),[Qt,Un]=(0,o.useState)(!1),[Zn,zn]=(0,o.useState)(!1),[qn,Qn]=(0,o.useState)(!1),[po,mo]=(0,o.useState)({line1:!1,city:!1,state:!1}),Dr=(0,o.useRef)(!1),eo=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),fn=(0,o.useRef)(!1),zt=(0,o.useCallback)(i=>{eo.current[i]=!0,fn.current=!0},[]),tn=(0,o.useCallback)(i=>!Dr.current&&eo.current[i],[]),rn=(0,o.useCallback)(i=>{tn(i)&&mo(C=>C[i]?C:{...C,[i]:!0})},[tn]),[dn,nn]=(0,o.useState)(()=>(0,d.resolveVaultMountOptions)(M?.vault,{billingApiUrl:E,sessionId:e,nonce:t})),[ut,mr]=(0,o.useState)(Mt&&ar?"card":"buttons"),[sr,Yr]=(0,o.useState)(null),ho=ut==="expanding"||ut==="card",to=M?.gateways?.stripe&&!zr?"stripe":void 0,In=(0,o.useCallback)(()=>{It?.({class:"card_surface",provider:to})},[to,It]),un=(0,o.useRef)(null),Ir=(0,o.useCallback)(i=>{un.current&&clearTimeout(un.current),un.current=setTimeout(()=>{un.current=null,i()},Ma)},[]);(0,o.useEffect)(()=>()=>{un.current&&clearTimeout(un.current)},[]);let ro=(0,o.useRef)(!1),[jr,q]=(0,o.useState)(0),j=(0,o.useRef)(null),ie=(0,o.useCallback)(()=>{In(),Gr(e??null),ro.current&&(ro.current=!1,q(i=>i+1)),xt(i=>i+1),mr("expanding"),Ir(()=>mr("card"))},[Ir,In,e]),we=(0,o.useCallback)(()=>{mr("collapsing"),Ir(()=>mr("buttons"))},[Ir]),mt=(0,o.useCallback)(i=>{Yr(i),mr("apm-expanding"),Ir(()=>mr("apm-form"))},[Ir]),Gt=(0,o.useCallback)(()=>{mr("apm-collapsing"),Ir(()=>{mr("buttons"),Yr(null)})},[Ir]);(0,o.useEffect)(()=>{Re==="buttons"&&Mt&&ar&&(Gr(e??null),mr("card"))},[Re,Mt,ar,e]);let[Ie,de]=(0,o.useState)(null),ee=(0,o.useRef)(!1),ve=(0,o.useRef)(null),te=(0,o.useRef)("idle"),[tt,re]=(0,o.useState)(!1),Je=(0,o.useRef)(tt);Je.current=tt;let[Ze,At]=(0,o.useState)(()=>vt?.existingOrderId?{orderId:vt.existingOrderId,attempts:1}:null),_r=(0,o.useRef)(Ze);(0,o.useEffect)(()=>{_r.current=Ze},[Ze]);let g=(0,o.useRef)(null),f=(0,o.useMemo)(()=>{if(nt||Se.claimBuyerIdentity||M?.buyerIdentified!==!1||!e||!t)return;let i=`${E}|${e}|${t}`;g.current?.key!==i&&(g.current={key:i,claim:zo(new On.PaymentAPI(E,{telemetry:!1}),e,t,{...s?{userId:s}:{},...w?{firstName:w}:{},...I?{lastName:I}:{}})});let C=g.current.claim;return async G=>{await C(G)}},[nt,Se.claimBuyerIdentity,M?.buyerIdentified,e,t,E,s,w,I]),O=nt??Se.claimBuyerIdentity??f,Ce=y??Fr,_e=(0,o.useMemo)(()=>(0,d.resolveTheme)(lt),[lt]),L=(0,o.useMemo)(()=>{let i=_e?.buttonsLayout??(0,d.resolveButtonsLayoutTheme)($e);return B?{...i,...B,cardButton:{...i.cardButton,...B.cardButton},cardFormContainer:{...i.cardFormContainer,...B.cardFormContainer},backButton:{...i.backButton,...B.backButton},backButtonIcon:{...i.backButtonIcon,...B.backButtonIcon},submitButton:{...i.submitButton,...B.submitButton},title:{...i.title,...B.title}}:i},[_e,$e,B]),Ct=wt??_e?.appearance,yr=(0,o.useMemo)(()=>(0,d.computeVaultCardThemeColors)({appearance:Ct,buttonsStyles:L,layout:Re}),[Ct,L,Re]),Tr=Se.inlineSessionPatchProcessing??!1,bt=(A??z)||Tr,pn=E.replace(/\/+$/,""),se=(0,o.useMemo)(()=>Ji({userId:s,email:a,firstName:w,lastName:I,country:V,zip:Ve},en),[s,a,w,I,V,Ve,en]),ht=[se.firstName,se.lastName].filter(i=>!!i?.trim()).join(" "),Rt=!(0,d.isValidEmail)(se.email?.trim()),Ft=(0,o.useRef)(null);he&&Ft.current===null&&(Ft.current=Rt);let rt=he&&(Ft.current??Rt),Xr=(0,o.useMemo)(()=>Jd(Jt,rt),[Jt,rt]),Ot=Xr.empty||Xr.malformed,Vr=(0,o.useMemo)(()=>Fe?Fe.getRawProvider():null,[Fe]),_s=(0,o.useMemo)(()=>Lt?Lt.getRawProvider():null,[Lt]),ta=at||100,_o=pr.toLowerCase(),Mi=(0,o.useMemo)(()=>Ct?(0,On.toStripeAppearance)(Ct):null,[Ct]),To=Mi,Ts=(0,o.useMemo)(()=>{let i=Mi??{},C=i.rules??{};return{...i,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[Mi]),Ms=(0,o.useMemo)(()=>({..._l(at,We?.captureMethod,He),currency:_o,...To?{appearance:To}:null}),[at,_o,We?.captureMethod,He,To]),xi=(0,d.resolveSetupFutureUsage)(He,"paypal","paypal"),xs=(0,o.useMemo)(()=>({mode:"payment",amount:ta,currency:_o,captureMethod:"manual",...xi?{setupFutureUsage:xi}:null,...To?{appearance:To}:null}),[ta,_o,xi,To]),ze=(0,o.useCallback)(i=>{tr(i),P?.(i)},[P]),As=(0,o.useRef)(0);(0,o.useEffect)(()=>{jr!==As.current&&(As.current=jr,ze(null))},[jr,ze]);let Ai=(0,o.useRef)(""),[Fs,Mc]=(0,o.useState)(!1),Fi=(0,o.useCallback)(()=>{Mc(!0)},[]);(0,o.useEffect)(()=>{if(!he||!rt||!O||!Fs||Ot||Ai.current)return;let i=(0,vn.compactBuyerIdentity)({email:(0,d.isValidEmail)(se.email?.trim())?se.email?.trim():Ht.current.trim(),firstName:se.firstName?.trim(),lastName:se.lastName?.trim()});Ai.current=JSON.stringify(i),et(C=>({...C,...i})),Promise.resolve(O(i)).catch(C=>{Ai.current="",ze(C instanceof Error?C.message:"Failed to attach buyer details.")})},[he,rt,O,Fs,Ot,se.email,se.firstName,se.lastName,ze]),(0,o.useEffect)(()=>{!he||!ae||ae.setCardFieldOrder?.(X??null,Xe==null&&!rt)},[he,ae,X,Xe,rt]),(0,o.useEffect)(()=>{(ut==="expanding"||ut==="collapsing"||ut==="apm-expanding"||ut==="apm-collapsing")&&ze(null)},[ut,ze]);let jn=(0,o.useCallback)((i,C,G)=>{m?.(Sr(i,C,G))},[m]),Bs=(0,o.useRef)(ut);Bs.current=ut;let[Ds]=(0,o.useState)(ri),Os=(0,o.useCallback)(()=>{let i=Bs.current;if(Re==="buttons"&&(i==="card"||i==="expanding"))return!0;let C=te.current;return C==="validation-window"||C==="processing"||Je.current},[Re]),Ls=(0,o.useCallback)((i,C,G)=>{Ds.take(e)&&wr(Fe)?.log(Ro({...it,presentationMode:G?.presentationMode??"popup"},{name:ti,stage:"recovery",reason:"other_method_active",provider:G?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:G?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[it,Fe,Ds,e]),Da=(0,o.useCallback)((i,C,G)=>{G?.telemetryReported||wr(Fe)?.error(Ro({...it,presentationMode:G?.presentationMode??"popup"},{errorCode:C?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:G?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:G?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:G?.terminalReason??(C?"popup_blocked":"provider_error")}))},[it,Fe]),Mo=(0,o.useCallback)((i,C,G)=>{let Te=G?.popupBlocked??(0,ke.isPopupBlockedError)(C);if(Os()){Da(i,Te,G),Ls(i,C,G);return}if(C instanceof d.FloPayError&&C.code==="checkout_processing_timeout"){Da(i,!1,G),de(null),Re==="buttons"&&(mr("buttons"),Yr(null)),ze(C.message),p?.(C);return}Te&&x.markBlocked()&&Be(Et=>Et+1);let J=ps(i),Me=G?.code===d.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,d.buildWalletSheetWindowMessage)(J):(0,ke.buildExternalMethodRecoveryMessage)(J,Te,dt.inAppBrowser),qt=(0,ke.getProviderErrorCode)(C),hn=(qt?.toLowerCase()==="error"?void 0:qt)??(0,ke.sanitizeExternalFailureCode)(G?.code)??"external_payment_method_failed",Pt=new d.FloPayError(Me,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:hn,popupBlocked:Te,inAppBrowser:dt.inAppBrowser,appFamily:dt.appFamily,popupCapability:x.current(),presentationMode:G?.presentationMode??"popup"}});Da(i,Te,G),de(null),Re==="buttons"&&(mr("buttons"),Yr(null)),ze(Me),p?.(Pt),console.error("[FloPay] External payment method failed:",{method:i,code:hn,popupBlocked:Te})},[dt,Os,Re,p,x,Ls,Da,ze]);(0,o.useEffect)(()=>{if(!he||!e){nn(null);return}let i={billingApiUrl:pn,sessionId:e,nonce:t},C=(0,d.resolveVaultMountOptions)(M?.vault,i);if(C){nn(C);return}if(!Q){nn(null);return}let G=`${pn}\0${e}\0${t??""}`,Te=j.current;if(Te&&Te.key===G){nn(Te.mount);return}nn(null);let J=!0;return new On.PaymentAPI(pn).getVaultCapture(e,t).then(Me=>{if(!J)return;let qt=(0,d.resolveVaultMountOptions)(Me,i);qt?.verificationRequired&&!Me.html&&(j.current={key:G,mount:qt}),qt?nn(qt):ze("Failed to load the secure card form.")}).catch(Me=>{J&&ze(Me instanceof Error?Me.message:"Failed to load the secure card form.")}),()=>{J=!1}},[he,Q,oe,e,M?.vault,pn,t,ze]);let _n=(0,o.useRef)({onComplete:l,onError:p,updateError:ze,emitDecline:jn,resolvedAccount:se,avsConfig:Xe,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:pn,captureMethod:M?.captureMethod,paymentId:M?.paymentId,authorizationExpiresAt:M?.authorizationExpiresAt,serverSideCardGateway:zr});_n.current={onComplete:l,onError:p,updateError:ze,emitDecline:jn,resolvedAccount:se,avsConfig:Xe,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:pn,captureMethod:M?.captureMethod,paymentId:M?.paymentId,authorizationExpiresAt:M?.authorizationExpiresAt,serverSideCardGateway:zr};let Bi=(0,o.useRef)(!1),Ns=(0,o.useCallback)(()=>{let i=_n.current,C=i.resolvedAccount.email?.trim(),G=(0,d.isValidEmail)(C)?C:Ht.current.trim();if(!(0,d.isValidEmail)(G))return null;let Te=i.resolvedAccount.firstName?.trim(),J=i.resolvedAccount.lastName?.trim(),Me=Br.current.trim()||i.resolvedAccount.country?.trim()||"",qt=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.state,Me):!1,hn=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.address_line_1,Me):!1,Pt=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.postal_code,Me):!1,Et=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.city,Me):!1,Bt=i.avsConfig?(0,d.isAVSFieldVisible)(i.avsConfig.address_line_2,Me):!1,Or=hn&&!qt&&Pt?(0,d.getStateFromPostalCode)(Me,(kt.current??"").trim()):null,Mn=qt?Zt.current:Or;return{accountData:{userId:i.resolvedAccount.userId??"",email:G,...Te?{firstName:Te}:{},...J?{lastName:J}:{},...Pt&&kt.current?{zip:kt.current}:{},...Et&&vr.current?{city:vr.current}:{},...Mn?{state:Mn}:{},...hn&&$t.current?{addressLine1:$t.current}:{},...Bt&&nr.current?{addressLine2:nr.current}:{},...Me?{country:Me}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,d.isAVSFieldVisible)(i.avsConfig.country,Me),postal_code:Pt,address_line_1:hn,address_line_2:Bt,city:Et,state:qt}}:{}}},[]),Us=(0,o.useRef)(c);Us.current=c,(0,o.useEffect)(()=>{c||Ce!==Xl||_n.current.updateError(null)},[c,Ce]),(0,o.useEffect)(()=>{!he||!ae||ae.setSubmitGate?.(br||c||Ot||tt)},[he,ae,br,c,Ot,tt]),(0,o.useEffect)(()=>{if(!he||!ae)return;Bi.current=!1;let i=null,C=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,te.current="idle",de(null)},400)},G=ae.on("submitting",()=>{Un(!0),ve.current&&clearTimeout(ve.current),te.current="validation-window",ve.current=setTimeout(()=>{ve.current=null,te.current==="validation-window"&&(te.current="processing")},zd),de("processing");let Pt=_n.current;if(!Pt.sessionId||!Pt.nonce)return;let Et=Ns();if(!Et){Pt.updateError("Enter a valid email address."),te.current="idle",de(null);return}new On.PaymentAPI(Pt.baseUrl).patchAccountSnapshot(Pt.sessionId,Pt.nonce,Et,{telemetryMode:"best_effort"}).catch(Bt=>{if(!jd(Bt))return;let Or=Bt instanceof Error?Bt.message:"Please check your billing address and try again.";Pt.updateError(Or),te.current="idle",de(null),Pt.onError?.(Bt instanceof d.FloPayError?Bt:new d.FloPayError(Or,"api_error"))})}),Te=ae.on("complete",Pt=>{(0,Bn.markSessionRecentlyCompleted)(Pt.sessionId??_n.current.sessionId),te.current="terminal",re(!1),de("success"),setTimeout(()=>{if(Bi.current)return;Bi.current=!0;let Et=_n.current,Bt=(0,d.isAuthorizationOnlySession)(Et)||Pt.outcome==="authorized",Or=Et.serverSideCardGateway?{}:{paymentIntentId:Pt.intentId};_n.current.onComplete?.(Bt?{status:"authorized",...Or,paymentId:Pt.paymentId??Et.paymentId,sessionId:Pt.sessionId??Et.sessionId,authorizationExpiresAt:Pt.authorizationExpiresAt??Et.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Or,checkoutMethod:"card"})},600)}),J=ae.on("decline",Pt=>{let Et=_n.current,Bt=Pt.message??"Your payment was declined. Please try another card or contact your bank.";te.current="terminal",re(!1),Et.updateError(Bt),de("error");let Or=Pt.failureOutcome??(0,d.normalizeCheckoutFailureOutcome)(Pt.declineReason)??"authorization_declined";Et.emitDecline("card",Bt,{code:Or,declineCode:Or}),C()}),Me=ae.on("error",Pt=>{let Et=_n.current,Bt=Pt.message??"There was a problem processing your payment. Please try again.";te.current="terminal",re(!1),Et.updateError(Bt),de("error"),Et.onError?.(new d.FloPayError(Bt,"api_error",{code:Pt.failureOutcome??"capture_failed"})),C()}),qt=ae.on("challenge_dismissed",()=>{ve.current&&(clearTimeout(ve.current),ve.current=null),te.current="processing",re(!0),de(null)}),hn=ae.on("blocked",()=>{if(Je.current){_n.current.updateError(qd);return}if(!Us.current){Un(!0);return}Fi(),_n.current.updateError(Xl)});return()=>{i&&(clearTimeout(i),i=null),ve.current&&(clearTimeout(ve.current),ve.current=null),te.current="idle",re(!1),de(null),G(),Te(),J(),Me(),qt(),hn()}},[he,ae,Fi,Ns]);let Vn=!!vt?.clientId,ra=Array.isArray(T),Oa=ra&&T.length>0,zs=ra&&T.includes("paypal"),La=(0,o.useRef)(null);La.current===null&&(La.current=(0,d.hasMatchingStripePayPalReturn)());let xo=La.current?"redirect":(0,Hn.resolveStripePayPalPresentation)(dt,xe,x.current()),{expressMethods:Na,paymentElementMethods:Di}=(0,o.useMemo)(()=>(0,d.partitionStripeMethods)(T,{excludePaypal:Vn}),[T,Vn]),qs=Vn||!!Lt||zs&&xo==="redirect",xc=(0,o.useMemo)(()=>qs?Na.filter(i=>i!=="paypal"):Na,[Na,qs]),Ac=(0,o.useMemo)(()=>{let i=[];return ye&&i.push("apple_pay"),pe&&i.push("google_pay"),i},[ye,pe]),Ao=ra?xc:Ac,Fc=S&&Ao.length>0,js=or?Wt:V,Ua=(0,o.useMemo)(()=>(0,d.filterStripeMethodsByCountryGate)(Di,js,le),[Di,js,le]),Oi=(0,o.useMemo)(()=>({mode:"payment",amount:ta,currency:_o,paymentMethodCreation:"manual",appearance:Ts}),[ta,_o,Ts]),[Vs,Ws]=(0,o.useState)("loading"),[$s,Hs]=(0,o.useState)("loading"),[Ks,Gs]=(0,o.useState)("loading"),[Bc,Li]=(0,o.useState)(!1),[Ys,Ni]=(0,o.useState)("loading"),[Ui,Dc]=(0,o.useState)();(0,o.useEffect)(()=>{Dc((0,$n.detectPayPalEnvironment)())},[]);let za=Ui?.inAppBrowser,qa=Ui?(0,Hn.resolvePayPalPresentationMode)(Ui,vt?.approvalPresentation,Dt??(be?"subscription":"order")):"popup",Xs=me&&(Vn||(ra?zs:za===!1)),Oc=dt.inAppBrowser&&x.current()==="blocked",Js=S&&Fc&&!Oc,na=(!W||!!Se.waitForDataAttachment)&&Xs&&Vn,Zs=Ys==="retrying"||Ys==="exhausted",oa=null;S&&(Lt?oa=_s:xo==="redirect"&&(oa=Vr));let Qs=(0,o.useMemo)(()=>({...it,presentationMode:xo}),[it,xo]),aa=!W&&Xs&&!!oa&&(!Vn||Zs),Fo=!W&&Js&&!!Vr,ia=!W&&S&&Oa&&Ua.length>0&&!!Vr,Lc=na&&!Zs?Bc:aa&&as(Vs),Nc=Fo&&as($s),Uc=ia&&Ks!=="load_error",el=i=>i==="loading"||i==="ready",tl=na||aa&&el(Vs)||Fo&&el($s)||ia&&Ks!=="load_error",ja=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!ja.current){if(!S&&!me){ja.current=!0;let i=new d.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),ze(i.message)}else if(!S&&me&&!Vn){ja.current=!0;let i=new d.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),ze(i.message)}else if(za!==void 0&&!W&&!ar&&!tl){ja.current=!0;let i=new d.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(i),ze(i.message)}}},[S,me,Vn,za,W,ar,tl,p,ze]);let rl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(rl.current||!Oa)return;let i=[];ye!==!0&&i.push("showApplePay"),pe!==!0&&i.push("showGooglePay"),i.length!==0&&(rl.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Oa,ye,pe]);let nl=(0,o.useCallback)((i,C,G)=>Se.applyInlineSessionPatch?Se.applyInlineSessionPatch(i).then(Te=>({error:null,sessionId:Te.sessionId||e,nonce:Te.session?.clientSecret||t})).catch(Te=>{let J=(0,d.normalizeBeforeButtonClickError)(C,Te);return G?.abandoned?.()||(ze(J.message),p?.(J)),{error:J,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Se.applyInlineSessionPatch,t,p,e,ze]),Tn=(0,o.useCallback)(async(i,C)=>{if(i!=="card"&&W&&await Se.waitForDataAttachment?.(),!Le)return{proceed:!0};try{let G=await Le({method:i,sessionId:e||void 0,createSession:Se.inlineSessionDraft});if(G===!1)return{proceed:!1};if(G&&typeof G=="object"){G.account&&et(J=>({...J??{},...G.account}));let Te=await nl(G,i,C);return Te.error?{proceed:!1,accountPatch:G.account}:{proceed:!0,accountPatch:G.account,sessionId:Te.sessionId,nonce:Te.nonce}}return{proceed:!0}}catch(G){if(!C?.abandoned?.()){let Te=(0,d.normalizeBeforeButtonClickError)(i,G);ze(Te.message),p?.(Te)}return{proceed:!1}}},[nl,Se.inlineSessionDraft,Se.waitForDataAttachment,W,Le,p,e,ze]),ol=(0,o.useCallback)(async(i,C)=>{if(ee.current)return;ee.current=!0,Ut(!0),de("processing"),ze(null);let G=C?.sessionId??e,Te=C?.nonce??t,J=Ji(se,C?.accountPatch),Me=C?.completionPaymentMethodId??fa(i),qt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,hn=Hd(i),Pt=C?.presentationMode?ci(wr(Fe),{...it,presentationMode:C.presentationMode}):void 0,Et=()=>{It?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:hn}),Pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Dn,requestCategory:"process_payment"})};try{let Bt=new On.PaymentAPI(pn),Mn=C?.settledProcessResponse??await Bt.processPayment(J.userId??"",{sessionId:G,nonce:Te,paymentMethodCategory:C?.paymentMethodCategory??Gd(i),tokenizedData:qt,accountData:{...C?.accountPatch,userId:J.userId??"",email:J.email??"",firstName:J.firstName||void 0,lastName:J.lastName||void 0,...(0,d.buildProcessPaymentAvsAccount)({avsConfig:Xe,country:Br.current,zip:kt.current,city:vr.current,state:Zt.current,addressLine1:$t.current,addressLine2:nr.current})},...(0,d.buildCheckoutProcessMetadata)({chv:Y,avsCheck:ot,checkoutType:Ae,checkoutLayout:Qe,avsConfig:Xe,country:Br.current})}),Ka=async Mr=>{let Co=(0,d.isAuthorizationOnlySession)(M)||Mr?.status==="authorized";(0,Bn.markSessionRecentlyCompleted)(G),Pt?.terminal({outcome:"payment_succeeded",...Dn}),de("success"),At(null),await new Promise(pa=>setTimeout(pa,600));let Wn;typeof Mr?.paymentId=="string"?Wn=Mr.paymentId:M?.paymentId&&(Wn=M.paymentId);let bo;typeof Mr?.authorizationExpiresAt=="string"?bo=Mr.authorizationExpiresAt:M?.authorizationExpiresAt&&(bo=M.authorizationExpiresAt),l?.(Co?{status:"authorized",...Wn===void 0?{}:{paymentId:Wn},sessionId:typeof Mr?.sessionId=="string"?Mr.sessionId:G,...bo===void 0?{}:{authorizationExpiresAt:bo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Me,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Me,checkoutMethod:i.isPaypal?"paypal":"card"})};if(Mn.ok){await Ka(Mn.status===204?null:await Mn.json().catch(()=>null));return}let fr=await Mn.json().catch(()=>null);if(fr?.type==="paypal_redirect_required"){let Mr=fr.threeDSecureToken,Co=fr.paymentMethodId||i.id||"";if(!Fe||!Mr){de("error"),ze("PayPal authorization required but no token provided.");return}try{let Wn=Lt?.getRawProvider();if(!Wn){ze("PayPal is not available.");return}let bo={return_url:window.location.href};Co&&(bo.payment_method=Co);let{error:pa}=await Wn.confirmPayment({clientSecret:Mr,confirmParams:bo,redirect:"if_required"});if(pa){de("error");let gl=pa.message??"PayPal payment failed.";ze(gl),jn("paypal",gl,{code:pa.code})}}catch(Wn){de("error"),ze(Wn instanceof Error?Wn.message:"PayPal authorization failed.")}return}if(fr?.type==="paypal_direct_required"){let Mr=fr.orderId;if(!Mr){de("error"),ze("PayPal retry required but no order id provided.");return}let Co=_r.current?.attempts??0;if(Co>=2){de("error"),ze("PayPal payment could not be completed after multiple attempts."),jn("paypal","paypal_direct_required retry limit exceeded");return}Li(!1),Ni("loading"),At({orderId:Mr,attempts:Co+1}),de(null);return}if(Mn.headers.get(Fd)===Bd){let Mr=await Dd(Bt,G,Te);if(Mr!==void 0){await Ka(Mr);return}}(0,d.classifyPaymentRejection)(Mn.status,fr)?Pt?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}):Et(),de("error");let fl=fr?.message??"Payment failed. Please try again.";ze(fl),jn(i.isPaypal?"paypal":"card",fl,{code:fr?.code??fr?.gatewayErrorCode,declineCode:fr?.declineCode??fr?.gatewayDeclineReason}),await new Promise(Mr=>setTimeout(Mr,400))}catch(Bt){ac(Bt)||Et(),de("error"),ze(Bt instanceof Error?Bt.message:"An unexpected error occurred"),await new Promise(Or=>setTimeout(Or,400))}finally{Ut(!1),de(null),ee.current=!1}},[pn,e,t,se,Xe,ot,Ae,Qe,Y,Fe,Lt,M,l,ze,jn,It,it]),on=(0,o.useCallback)((i,C)=>{R&&!C?.settledProcessResponse?R(i):ol(i,C)},[R,ol]),sa=`${nc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(sa);if(!i)return;let C;try{C=JSON.parse(i)}catch{dr(sa);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>oc||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!Ao.includes(C.paymentMethodType)){dr(sa);return}dr(sa),on({id:C.paymentMethodId,type:"card",threeDSecureActionResultTokenId:C.providerIntentId,gateway:"stripe",paymentMethodType:C.paymentMethodType},{...C.accountPatch?{accountPatch:C.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[on,t,e,sa,Ao]);let al=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||al.current)return;let[i,C,G]=(0,d.readStripeRedirectParams)();if(!i||!C||La.current||!Fe)return;let Te=Fe.getRawProvider();if(!Te)return;let J=Et=>{let Bt=localStorage.getItem(Et);if(!Bt)return null;try{return JSON.parse(Bt)}catch{return dr(Et),null}},Me=J(Gn)??J(Kl),qt;if(Me?.clientSecret){if(Me.clientSecret!==C)return;qt={...Me.accountPatch?{accountPatch:Me.accountPatch}:{},...Me.sessionId?{sessionId:Me.sessionId}:{},...Me.nonce?{nonce:Me.nonce}:{}}}else if(Me?.sessionId&&Me.sessionId!==e)return;al.current=!0,dr(Gn),dr(Kl),window.history.replaceState({},"",(0,d.stripeRedirectReturnUrl)());let hn=Me?.paymentMethodType??Me?.tokenType??"card",Pt="card";(async()=>{if(G==="failed"){let fr="Payment was declined. Please try again.";ze(fr),jn(Pt,fr);return}let{paymentIntent:Et,error:Bt}=await Te.retrievePaymentIntent(C);if(Bt){let fr=Bt.message??"Failed to retrieve payment status.";ze(fr),jn(Pt,fr,{code:Bt.code});return}let Or=Et?.status,Mn=ya(Or);if(!Et||!Mn){let fr=Or==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ze(fr),jn(Pt,fr,{code:Or??"missing_payment_intent"});return}let Ka=typeof Et.payment_method=="string"?Et.payment_method:Et.payment_method?.id;on({id:Ka??Me?.paymentMethodId??Me?.tokenId??Et.id,type:"card",threeDSecureActionResultTokenId:Et.id,gateway:Me?.gateway??"stripe",paymentMethodType:hn},qt)})()},[e,on,Fe,ze,jn]);let zi=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(he||Fe!==null))return(0,u.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let la=Re==="buttons",an=Ct?.variables,zc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),qi=an?.colorBackground,qc=qi&&!zc.has(qi)?qi:void 0,ca=L.cardInputBorder??(la?"#e5e7eb":"#A4A4FF"),il=an?.colorDanger??"#dc2626",er=i=>qr[i]&&(po[i]||Qt),Va=Ot&&(qn||Qt),gn=i=>i?il:ca,Wa=(Nt.malformed||Nt.empty)&&(Zn||Qt),jc=gn(Wa),ji=L.cardFormContainer?.backgroundColor??qc??(la?"white":"#EDEDFF"),Bo=L.cardInputBackground??an?.colorBackground??"white",Vi=Lo(Ne),sl=Lo(ue),Do=L.nameInput,ll=L.cardInputFontSize??Zd(Do?.fontSize)??an?.fontSizeBase??"16px",cl=typeof Do?.fontFamily=="string"?Do.fontFamily:an?.fontFamily??"Poppins, sans-serif",dl=(0,d.toCssWeight)(Do?.fontWeight)??400,Vc=L.cardInputColor??(typeof Do?.color=="string"?Do.color:void 0)??an?.colorText??"#262833",Wc=L.cardInputPlaceholderColor??"#9ca3af",lr=an?.borderRadius??"8px",Po=an?.borderRadius??L.cardButton?.borderRadius??lr,vo=an?.colorPrimary??"#4A49FF",$c=an?.colorPrimaryHover??(0,d.darkenHex)(vo,.12),Wi=an?.colorText??"#262833",$i={fontSize:ll,fontFamily:cl,fontWeight:dl,color:Vc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},da={marginTop:"0.375rem",...$i,fontSize:"0.75rem",lineHeight:1.4,color:il},Hc={"--flopay-input-placeholder-color":Wc,"--flopay-input-font-size":ll,"--flopay-input-font-family":cl,"--flopay-input-font-weight":String(dl)},ua=L.cardFormContainer??{},Hi=ua.padding??(la?"0":"1rem"),Ki=ua.borderRadius??lr,Kc=ae&&dn?(0,u.jsx)(go,{capture:ae,html:dn.html,messageToken:dn.messageToken,expectedOrigin:dn.expectedOrigin,verificationRequired:dn.verificationRequired,theme:yr,submitLabel:Z,onReady:()=>{if(!rt&&!Xe||typeof document>"u")return;let i=()=>{let G=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(G){Dr.current=!0;try{G.focus()}finally{Dr.current=!1}}};fn.current||i()},onError:i=>{i&&dn.verificationRequired&&te.current==="idle"&&(ro.current=!0),ze(i)},onValidation:i=>{let C=te.current;(C==="idle"||C==="validation-window")&&(ze(i),i&&te.current==="validation-window"&&(ve.current&&(clearTimeout(ve.current),ve.current=null),te.current="idle",de(null)))}},jr):(0,u.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ul=(0,u.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&In()},style:{backgroundColor:ji,borderRadius:Ki,...ua,padding:Hi,...Hc,display:"flex",flexDirection:"column"},children:[(0,u.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${se.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),ia&&mo&&(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ye?-2:0},children:[(0,u.jsxs)("button",{type:"button",onClick:we,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:A.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...A.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...A.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Oo,{content:De})]}),el?(0,u.jsx)("div",{style:{flex:1}}):(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...A.title},children:(0,u.jsx)(ua,{content:de})})]}),!ia&&!el&&(0,u.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:zi,order:ye?-3:0,...A.title},children:(0,u.jsx)(ua,{content:de})}),ye&&J&&(0,u.jsx)("div",{style:{order:-2,width:"100%"},children:J}),ye&&io&&(0,u.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,u.jsx)("div",{style:{backgroundColor:xo,border:`1px solid ${dn(za)}`,borderRadius:tr,padding:"10px"},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:sr,onChange:s=>{Nt("email"),Ir.current=s.target.value,br(s.target.value)},onPointerDown:()=>Nt("email"),onKeyDown:()=>Nt("email"),onBlur:()=>{tn("email")&&ao(!0),ko||Ti()},disabled:oe,required:!0,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...qi}})}),za&&(0,u.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:la,children:Ri.empty?"Email address is required":"Enter a valid email address"})]}),Ye&&(0,u.jsx)("div",{style:{order:ye?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Ht,D=(Q=!1)=>({backgroundColor:xo,border:`1px solid ${dn(Q)}`,borderRadius:tr,marginTop:"0.5rem",padding:"10px"}),ae=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...qi}),Re=(0,d.getStateOptions)(s);return(0,u.jsxs)(u.Fragment,{children:[(0,d.isAVSFieldVisible)(Ye.address_line_1,s)&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)("div",{style:D(Jt("line1")),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Zt,onChange:Q=>{Nt("line1"),dr.current.addressLine1=!0,Gt.current=Q.target.value,$r(Q.target.value)},onPointerDown:()=>Nt("line1"),onKeyDown:()=>Nt("line1"),onBlur:()=>rn("line1"),disabled:oe,required:!0,"aria-invalid":Jt("line1")||void 0,"aria-describedby":Jt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:ae()})}),Jt("line1")&&(0,u.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:la,children:"Street address is required"})]}),(0,d.isAVSFieldVisible)(Ye.address_line_2,s)&&(0,u.jsx)("div",{style:D(),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Mt,onChange:Q=>{dr.current.addressLine2=!0,hr.current=Q.target.value,xn(Q.target.value)},disabled:oe,"data-testid":"flopay-address-line2",style:ae()})}),((0,d.isAVSFieldVisible)(Ye.city,s)||(0,d.isAVSFieldVisible)(Ye.state,s))&&(0,u.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Ye.city,s)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${dn(Jt("city"))}`,borderRight:`1px solid ${dn(Jt("city"))}`,borderBottom:`1px solid ${dn(Jt("city"))}`,borderLeft:`1px solid ${dn(Jt("city"))}`,padding:"10px",borderTopLeftRadius:tr,borderBottomLeftRadius:tr,...(0,d.isAVSFieldVisible)(Ye.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:tr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Kt,onChange:Q=>{Nt("city"),dr.current.city=!0,Yt.current=Q.target.value,ln(Q.target.value)},onPointerDown:()=>Nt("city"),onKeyDown:()=>Nt("city"),onBlur:()=>rn("city"),disabled:oe,required:!0,"aria-invalid":Jt("city")||void 0,"aria-describedby":Jt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:ae()})}),(0,d.isAVSFieldVisible)(Ye.state,s)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${dn(Jt("state"))}`,borderRight:`1px solid ${dn(Jt("state"))}`,borderBottom:`1px solid ${dn(Jt("state"))}`,borderLeft:`1px solid ${dn(Jt("state"))}`,padding:"10px",borderTopRightRadius:tr,borderBottomRightRadius:tr,...(0,d.isAVSFieldVisible)(Ye.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${dn(Jt("state")||Jt("city"))}`}:{borderRadius:tr}},children:Re?(0,u.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Nr,onChange:Q=>{Nt("state"),dr.current.state=!0,cr.current=Q.target.value,Ur(Q.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>rn("state"),disabled:oe,autoComplete:"billing address-level1",required:!0,"aria-invalid":Jt("state")||void 0,"aria-describedby":Jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...ae(),cursor:"pointer"},children:[(0,u.jsx)("option",{value:"",children:(0,d.getStateLabel)(s)}),Re.map(Q=>(0,u.jsx)("option",{value:Q.code,children:Q.name},Q.code))]}):(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,d.getStateLabel)(s),autoComplete:"billing address-level1",value:Nr,onChange:Q=>{Nt("state"),dr.current.state=!0,cr.current=Q.target.value,Ur(Q.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>rn("state"),disabled:oe,required:!0,"aria-invalid":Jt("state")||void 0,"aria-describedby":Jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:ae()})})]}),Jt("city")&&(0,u.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:la,children:"City is required"}),Jt("state")&&(0,u.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:la,children:[(0,d.getStateLabel)(s)," is required"]}),((0,d.isAVSFieldVisible)(Ye.country,s)||(0,d.isAVSFieldVisible)(Ye.postal_code,s))&&(0,u.jsxs)("div",{style:{display:"flex",flexDirection:H==="column"?"column":"row",gap:H==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Ye.country,s)&&(0,u.jsx)("div",{style:{flex:H==="row"?1:void 0,backgroundColor:xo,borderTop:`1px solid ${sa}`,borderRight:`1px solid ${sa}`,borderBottom:`1px solid ${sa}`,borderLeft:`1px solid ${sa}`,padding:"10px",...H==="row"&&(0,d.isAVSFieldVisible)(Ye.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:tr,borderBottomLeftRadius:tr,borderRight:"none"}:{borderRadius:tr}},children:(0,u.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Ht,onChange:Q=>{dr.current.country=!0,lr.current=Q.target.value,Tt(Q.target.value),ut?.(Q.target.value),cr.current="",Ur("")},disabled:oe,autoComplete:"billing country","data-testid":"flopay-country",style:{...ae(),cursor:"pointer"},children:[Ht===""?(0,u.jsx)("option",{value:"",children:"Select country"}):null,d.COUNTRY_OPTIONS.map(Q=>(0,u.jsxs)("option",{value:Q.code,children:[Q.flag," ",Q.name]},Q.code))]})}),(0,d.isAVSFieldVisible)(Ye.postal_code,s)&&(0,u.jsx)("div",{style:{flex:H==="row"?1:void 0,backgroundColor:xo,border:`1px solid ${Ac}`,padding:"10px",...H==="row"&&(0,d.isAVSFieldVisible)(Ye.country,s)?{borderRadius:"0",borderTopRightRadius:tr,borderBottomRightRadius:tr}:{borderRadius:tr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,d.getPostalCodeLabel)(Ht),autoComplete:"billing postal-code",value:Lr,onChange:Q=>{Nt("zip"),dr.current.zip=!0,wt.current=Q.target.value,Ar(Q.target.value),Le?.(Q.target.value)},onPointerDown:()=>Nt("zip"),onKeyDown:()=>Nt("zip"),onBlur:()=>{tn("zip")&&Fn(!0)},disabled:oe,required:Lt.required,"aria-invalid":qa||void 0,"aria-describedby":qa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:ae()})})]}),qa&&(0,u.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:la,children:Lt.empty?`${(0,d.getPostalCodeLabel)(s)} is required`:zd(s)})]})})()}),ye&&Lc,kt&&(0,u.jsx)(Wo,{margin:"0.75rem 0",styleOverride:A.errorBanner,children:kt})]}),ja={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},al=s=>z?!pe||!Ln?(0,u.jsx)("pre",{"data-testid":s,style:ja,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":s,style:ja,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${pe}`,` directPaypalConfigured=${Ln}`,` inAppBrowserDetected=${String(La)}`,` shouldRenderDirectPayPal=${ta}`,` shouldRenderStripePayPal=${na}`,` hasPaypalStripeInstance=${!!Rs}`].join(`
39
- `)}):null,il=s=>z?!b||!on?(0,u.jsx)("pre",{"data-testid":s,style:ja,children:"FloPay/Stripe-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":s,style:ja,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${b}`,` currency=${ar}`,` amountInCents=${Qo}`,` enabledPaymentMethods: ${JSON.stringify(_??[])}`,` enabledPaymentMethodsProvided=${ea}`,` hasEnabledMethods=${Fa}`,` expressMethods: ${JSON.stringify(Da)}`,` walletExpressMethods: ${JSON.stringify(To)}`,` paymentElementMethods: ${JSON.stringify(xi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Oa)}`,` hasStripeInstance=${!!on}`,` shouldRenderWallets=${Mo}`,` shouldRenderPaymentElement=${oa}`].join(`
40
- `)}):null,sl=bt==="apm-expanding"||bt==="apm-form"||bt==="apm-collapsing",Fo;bt==="apm-expanding"?Fo=ql:bt==="apm-collapsing"&&(Fo=jl);let Va=mr?Jl(Ai,mr,He):null;if(xe==="buttons"){let s=bt==="buttons"||bt==="expanding"||bt==="apm-expanding",D=bt==="expanding"||bt==="card"||bt==="collapsing",ae=Ge===void 0?{boxSizing:"border-box",height:Yo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Re;bt==="expanding"||bt==="apm-expanding"?Re=Od:(bt==="collapsing"||bt==="apm-collapsing")&&(Re=Dd);let Q;return bt==="expanding"?Q=ql:bt==="collapsing"&&(Q=jl),(0,u.jsxs)("form",{onSubmit:Oi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Xo,{}),Ne&&(0,u.jsx)(Zr,{status:Ne,errorMessage:kt,authorized:ur}),(0,u.jsxs)("div",{style:{display:"grid"},children:[(0,u.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Re?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Re?Nd:{},...Re?{animation:Re,pointerEvents:"none"}:{}},children:[al("flopay-direct-paypal-gate-debug"),il("flopay-stripe-gate-debug"),ta&&Ct&&(0,u.jsxs)(u.Fragment,{children:[ke&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(fa.Provider,{value:M,children:(0,u.jsx)(ha,{sessionId:e,nonce:t,billingApiUrl:R,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,clientId:Ct.clientId,environment:Ct.environment,currency:ar.toUpperCase(),isSubscription:Ce,providerObjectType:Bt,approvalPresentation:Na==="popup"?void 0:Na,onTokenizedBody:Xr,onComplete:l,onErrorChange:qe,onDecline:m,onCancel:h,onTechnicalFailure:Io,onButtonClick:X,runBeforeButtonClick:kn,isProcessing:oe,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:Ve,existingOrderId:ke?.orderId,debug:z},ke?.orderId??"fresh")})]}),na&&(0,u.jsx)(rr.Elements,{stripe:ra,options:_s,children:(0,u.jsx)(Wl,{sessionId:e,nonce:t,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,billingApiUrl:R,onTokenizedBody:Xr,onErrorChange:qe,isProcessing:oe,onButtonClick:X,onDecline:m,onTechnicalFailure:Io,runBeforeButtonClick:kn,onLoadStateChange:Ls,placeholderBorderRadius:yo,popupCapabilityOwner:M,externalTelemetryContext:Hs,presentationMode:_o})}),Mo?(0,u.jsx)(rr.Elements,{stripe:on,options:Is,children:(0,u.jsx)($l,{sessionId:e,nonce:t,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,billingApiUrl:R,intentKind:at>0?"payment":"setup",expressMethods:To,onTokenizedBody:Xr,onErrorChange:qe,onButtonClick:X,onDecline:m,onTechnicalFailure:Io,runBeforeButtonClick:kn,onLoadStateChange:Us,placeholderBorderRadius:yo,popupCapabilityOwner:M,externalTelemetryContext:mt})}):null,!Mo&&Ws?(0,u.jsx)("div",{style:{height:Yo,borderRadius:yo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,oa&&(0,u.jsx)(Hl,{sessionId:e,nonce:t,email:he.email,billingName:[he.firstName,he.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:it,billingApiUrl:R,paymentElementMethods:Oa,stripeInstance:on,paymentElementBaseOptions:Ai,futureUseSession:He,onTokenizedBody:Xr,onErrorChange:qe,onButtonClick:X,onDecline:m,runBeforeButtonClick:kn,onLoadStateChange:qs,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,onExpandApm:Rt,expandedApmMethod:mr,themeId:lt,buttonAppearance:{backgroundColor:A.cardButton?.backgroundColor,borderColor:A.cardInputBorder,textColor:A.cardButton?.color,borderRadius:yo}}),ye&&(0,u.jsx)("button",{type:"button",onClick:async()=>{oe||!(await kn("card")).proceed||(X?.("card"),ne())},disabled:oe,style:{width:"100%",...ae,...A.cardButton,...ps({themeBundle:Et,resolvedPrimaryColor:fo,resolvedBorderRadius:tr,submitButtonStyle:A.submitButton,explicitPrimaryColor:Jr?.colorPrimary}),fontSize:A.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:oe?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:oe?.6:1},onMouseEnter:Ee=>{!oe&&(Et||Jr?.colorPrimary)&&(Ee.currentTarget.style.backgroundColor=Dc)},onMouseLeave:Ee=>{(Et||Jr?.colorPrimary)&&(Ee.currentTarget.style.backgroundColor=fo)},onMouseDown:Ee=>{Ee.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ee=>{Ee.currentTarget.style.transform="scale(1)"},children:(0,u.jsx)(Do,{content:Ge})}),kt&&bt==="buttons"&&(0,u.jsx)(Wo,{margin:"0.25rem 0",styleOverride:A.errorBanner,children:kt})]}),ye&&D&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...Q?{animation:Q}:{},...bt==="collapsing"?{pointerEvents:"none"}:{}},children:ol}),b&&sl&&mr&&Va&&on&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...Fo?{animation:Fo}:{},...bt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:er,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:A.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...A.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...A.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Oo,{content:De})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:zi,paddingRight:80,...A.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(mr)}`})]}),(0,u.jsx)(rr.Elements,{stripe:on,options:Va,children:(0,u.jsx)(cs,{method:mr,sessionId:e,nonce:t,email:he.email,billingName:[he.firstName,he.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:it,billingApiUrl:R,onTokenizedBody:Xr,onErrorChange:qe,onDecline:m,onCancel:er,runBeforeButtonClick:kn,onButtonClick:X,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,errorText:kt})},mr)]})})]})]})}return sl&&mr&&Va&&on&&b?(0,u.jsxs)("form",{onSubmit:Oi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Xo,{}),Ne&&(0,u.jsx)(Zr,{status:Ne,errorMessage:kt,authorized:ur}),(0,u.jsx)("div",{style:{...Fo?{animation:Fo}:{},...bt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:er,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:A.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...A.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...A.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Oo,{content:De})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:zi,paddingRight:80,...A.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(mr)}`})]}),(0,u.jsx)(rr.Elements,{stripe:on,options:Va,children:(0,u.jsx)(cs,{method:mr,sessionId:e,nonce:t,email:he.email,billingName:[he.firstName,he.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:it,billingApiUrl:R,onTokenizedBody:Xr,onErrorChange:qe,onDecline:m,onCancel:er,runBeforeButtonClick:kn,onButtonClick:X,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,errorText:kt})},mr)]})})]}):(0,u.jsxs)("form",{onSubmit:Oi,className:I,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Xo,{}),Ne&&(0,u.jsx)(Zr,{status:Ne,errorMessage:kt,authorized:ur}),(0,u.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[al("flopay-direct-paypal-gate-debug-default"),il("flopay-stripe-gate-debug-default"),ta&&Ct&&(0,u.jsxs)(u.Fragment,{children:[ke&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(fa.Provider,{value:M,children:(0,u.jsx)(ha,{sessionId:e,nonce:t,billingApiUrl:R,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,clientId:Ct.clientId,environment:Ct.environment,currency:ar.toUpperCase(),isSubscription:Ce,providerObjectType:Bt,approvalPresentation:Na==="popup"?void 0:Na,onTokenizedBody:Xr,onComplete:l,onErrorChange:qe,onDecline:m,onCancel:h,onTechnicalFailure:Io,onButtonClick:X,runBeforeButtonClick:kn,isProcessing:oe,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:Ve,existingOrderId:ke?.orderId,debug:z},ke?.orderId??"fresh")})]}),na&&(0,u.jsx)(rr.Elements,{stripe:ra,options:_s,children:(0,u.jsx)(Wl,{sessionId:e,nonce:t,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,billingApiUrl:R,onTokenizedBody:Xr,onErrorChange:qe,isProcessing:oe,onButtonClick:X,onDecline:m,onTechnicalFailure:Io,runBeforeButtonClick:kn,onLoadStateChange:Ls,placeholderBorderRadius:yo,popupCapabilityOwner:M,externalTelemetryContext:Hs,presentationMode:_o})}),Mo&&(0,u.jsx)(rr.Elements,{stripe:on,options:Is,children:(0,u.jsx)($l,{sessionId:e,nonce:t,email:he.email,billingName:Gn||void 0,onBuyerIdentityReady:it,billingApiUrl:R,intentKind:at>0?"payment":"setup",expressMethods:To,onTokenizedBody:Xr,onErrorChange:qe,onButtonClick:X,onDecline:m,onTechnicalFailure:Io,runBeforeButtonClick:kn,onLoadStateChange:Us,placeholderBorderRadius:yo,popupCapabilityOwner:M,externalTelemetryContext:mt})}),oa&&(0,u.jsx)(Hl,{sessionId:e,nonce:t,email:he.email,billingName:[he.firstName,he.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:R,paymentElementMethods:Oa,stripeInstance:on,paymentElementBaseOptions:Ai,futureUseSession:He,onTokenizedBody:Xr,onErrorChange:qe,onButtonClick:X,onDecline:m,runBeforeButtonClick:kn,onLoadStateChange:qs,isProcessing:oe,submitButtonColor:fo,submitButtonBorderRadius:tr,submitButtonStyle:A.submitButton,themeId:lt,onExpandApm:Rt,expandedApmMethod:mr,buttonAppearance:{backgroundColor:A.cardButton?.backgroundColor,borderColor:A.cardInputBorder,textColor:A.cardButton?.color,borderRadius:yo}})]}),ye&&(_c||Ic||Tc)&&(0,u.jsx)(ci,{label:"or pay with card"}),ye&&ol]})}var F=require("react/jsx-runtime"),Jo=44,vs="flopay_checkout_saved_payment_resume",Pi=new Map,gi=new Map;function Zl(e,t){t.settled&&t.consumers===0&&Pi.get(e)===t&&Pi.delete(e)}function Kd(e,t,r){let n=gi.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),i={attempt:a,sdkGeneratedIdempotencyKey:t};gi.set(e,i);let l=()=>{gi.get(e)===i&&gi.delete(e)};return a.then(l,l),a}function Ta(e){return new Promise(t=>setTimeout(t,e))}function hi(e,t,r){let n=Ja({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:We.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Ma(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ys(e,t,r,n,a,i){let l=hi(e,t,r);l.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Ma(l)}function Ql(e,t,r,n){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:t,...n===void 0?{}:{attempt:n},statusClass:"2xx"})}function ec(e,t,r,n,a){let i=(0,We.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:a,statusClass:i.statusClass}),t instanceof We.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof We.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...i,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function fs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,We.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var Gd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Yd(e){return new ro.FloPay(Gd,{publishableKey:"provider_unavailable",...e})}async function gs(e,t){let{publishableKey:r,paypalPublishableKey:n}=Qi(e);return{...await es({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Cs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Xd(){if(!Cs())return null;try{let e=window.sessionStorage.getItem(vs);return e?JSON.parse(e):null}catch{return null}}function tc(e){if(Cs())try{window.sessionStorage.setItem(vs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function hs(){if(Cs())try{window.sessionStorage.removeItem(vs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Jd(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],r=!1;for(let n of t)e.searchParams.has(n)&&(e.searchParams.delete(n),r=!0);r&&window.history.replaceState(window.history.state,"",e.toString())}function rc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Ps(e,t){return(0,We.resolveCheckoutLogLayout)(!!e,t)}function Zd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function nc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Qd(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function vi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:i,locale:l,loading:p,error:m,onComplete:h,onError:w,onInstrument:S,onDecline:E,onCancel:Y,onCountryChange:I,onZipChange:ee,showPayPal:x=!0,showStripe:f=!0,walletPresentation:P="auto",enabledPaymentMethods:pe,showApplePay:b=!0,showGooglePay:Ie=!0,debug:_=!1,layout:ie,theme:me,buttonsTheme:ue,buttonsStyles:xe,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B,showSecurityFooter:St,onButtonClick:Ge,onBeforeButtonClick:De,enableAVS:de,cardFieldOrder:re,cardPreFormSlot:X,avsLayout:Oe,submitLabel:nt,className:ze,initialErrorMessage:te=null,initialPayPalOrderId:J,children:H,checkoutMode:j,confirmLabel:je,renderConfirmButton:Te,onSessionCompleted:fe}){let O=(0,We.resolveBillingApiUrl)(n),Pe=(0,v.useMemo)(()=>(0,We.resolveTheme)(me),[me]),ut=i??Pe?.appearance,Le=r?"embedded_checkout":"standard_checkout",ot=Ps(H,ie),[_e,et]=(0,v.useState)(null),[at,ar]=(0,v.useState)(null),xt=(0,v.useRef)(null),Ct=(0,v.useRef)(null),Ce=(0,v.useRef)(0),[T,ht]=(0,v.useState)(null),pt=(0,v.useRef)(null),[z,Ae]=(0,v.useState)(null),Dt=(0,v.useMemo)(()=>r?(0,ft.serializeCreateParams)(r):"",[r]),be=r?`create:${Dt}`:`session:${e??""}`,_t=nc(z),C=(0,v.useRef)(new Set),M=(0,v.useRef)(be),Fe=(0,v.useRef)(be);Co(()=>{Fe.current=be,M.current!==be&&(M.current=be,C.current.clear())},[be]);let Se=(0,v.useCallback)(L=>{if(Fe.current===be){if(Xi.FLO_INSTRUMENT_ONCE_NAMES.has(L.name)){if(C.current.has(L.name))return;C.current.add(L.name)}(0,Ze.invokeMerchantCallback)(()=>S?.(L))}},[be,S]),ct=Vo(Se,be),mt=(0,v.useRef)(!1),Ve=(0,v.useCallback)(L=>{if(mt.current)return;let N=L.gateway||!_t?L:{...L,gateway:_t};Se(N)},[Se,_t]);(0,v.useEffect)(()=>{ct({class:"lifecycle",name:"checkout.mount"})},[ct]);let[He,Bt]=(0,v.useState)(e??""),c=e??He,U=r?"":c,[V,se]=(0,v.useState)(!0),[R,K]=(0,v.useState)(null),[Ut,xr]=(0,v.useState)(0),[ir,Ht]=(0,v.useState)("full"),[Tt,Lr]=(0,v.useState)(!1),[Ar,Zt]=(0,v.useState)(te),[$r,Mt]=(0,v.useState)(null),[xn,Kt]=(0,v.useState)(null),[ln,Nr]=(0,v.useState)(!1),[Ur,sr]=(0,v.useState)(void 0),[br,Hr]=(0,v.useState)(""),[dt,wt]=(0,v.useState)(!1),[lr,Gt]=(0,v.useState)(!1),[hr,Yt]=(0,v.useState)(!1),cr=(0,v.useRef)(null),Ir=(0,v.useRef)(0),dr=(0,v.useRef)(void 0),[Ye,Fr]=(0,v.useState)("loading"),[ur,oo]=(0,v.useState)(0),zr=(0,v.useRef)(!1),qr=(0,v.useRef)(!1),An=(0,v.useRef)(!1),Kr=(0,v.useRef)(null),Xt=(0,v.useRef)(null),ye=(0,v.useMemo)(()=>({checkoutMode:j??ir,layout:Zd(H,ie)}),[j,H,ir,ie]),Z=(0,v.useRef)(h);Z.current=h;let At=(0,v.useRef)(w);At.current=w;let Me=(0,v.useRef)(E);Me.current=E;let Pr=(0,v.useCallback)(L=>ei(Kr,async N=>{try{return await L(N)}catch(ne){throw N.aborted?$o(ne):ne}}),[]);(0,v.useEffect)(()=>()=>{Kr.current?.abort(),Kr.current=null},[]);let Ot=(0,v.useCallback)((L,N)=>{xt.current=L,ar(L),pt.current=N,ht(N)},[]),jt=(0,v.useCallback)(()=>{let L=Ct.current;L&&(Ct.current=null,L.destroy())},[]);(0,v.useEffect)(()=>{kr(at)?.setCheckoutContext(ye),T&&T!==at&&kr(T)?.setCheckoutContext(ye)},[at,T,ye]);let vr=(0,v.useRef)(fe);vr.current=fe;let $=(0,v.useCallback)(L=>{Fr(L),!(L!=="exhausted"||An.current)&&(An.current=!0,At.current?.(new We.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Vt=(0,v.useCallback)(()=>{Fr("retrying"),oo(L=>L+1)},[]);(0,v.useEffect)(()=>{Fr("loading"),oo(0),An.current=!1},[c]),(0,v.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:We.SDK_VERSION,checkout_type:Le,checkout_layout:ot,billing_api_url:O})},[ot,Le,O]);let tt=(0,v.useMemo)(()=>r?(0,ft.serializeCreateParams)(r,!0):"",[r]),Lt=(0,v.useMemo)(()=>br===tt?Ur:void 0,[Ur,br,tt]),pr=(0,v.useMemo)(()=>r?Hi(r,Lt):void 0,[r,Lt]),Br=j??pr?.checkoutMode??"full",Qt=(0,v.useMemo)(()=>pr?{...pr,checkoutMode:Br}:void 0,[pr,Br]);(0,v.useEffect)(()=>{sr(void 0),Hr(tt),dr.current=void 0,cr.current=null,Yt(!1)},[tt]),(0,v.useEffect)(()=>{Zt(te)},[te]);let vn=(0,v.useCallback)((L,N,ne)=>{(0,Ze.invokeMerchantCallback)(()=>{Me.current?.(wr(L,N,ne))})},[]),$n=(0,v.useCallback)(async(L,N)=>{Zt(null),Kt(null),Nr(!1),Mt("processing");let ne=N?.sessionId??L.id,we=L.clientSecret||t,Rt=nc(L),er=xt.current??pt.current,Ne=kr(er),le=er?null:hi(O,a,ye),q={log:Ue=>{Ne?Ne.log(Ue):le?.log(Ue)},error:Ue=>{Ne?Ne.error(Ue):le?.error(Ue)},terminal:Ue=>{Ne?Ne.terminal(Ue):le?.terminal(Ue)},performance:Ue=>{Ne?Ne.performance(Ue):le?.performance(Ue)},now:()=>Ne?.now()??le?.now()??0,elapsed:Ue=>Ne?.elapsed(Ue)??Math.max(0,(le?.now()??Ue)-Ue)},W=q.now(),ce=!!(N?.initialAutoProcessingError||N?.initialAutoProcessingPending),g=!1,y,G=()=>{g||(g=!0,ce=!0,y=q.now(),q.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),q.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ke=!1,Xe=()=>{ke||(ke=!0,q.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),q.performance({stage:"processing",durationMs:q.elapsed(W),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),y!==void 0&&q.performance({stage:"recovery",durationMs:q.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}))};q.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),mt.current=!0;try{q.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{mt.current=!1}ct({class:"lifecycle",name:"payment.processing.started",provider:Rt}),ce&&G();let yt;try{let Ue=xl(N?.initialAutoProcessingError),Be=N?.initialAutoProcessingError?.type==="3ds_required"&&!N.initialAutoProcessingError.threeDSecureToken&&N.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:N.initialAutoProcessingError.nextActionRedirectUrl}:null,it,kt=Et=>(G(),Pr(A=>Ho(Et,{billingApiUrl:O,sessionId:ne,nonce:we,session:L,signal:A})));if(Be)it=await kt(Be);else if(Ue)G(),Ue.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&tc({sessionId:ne,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),it=await Pr(Et=>ri(Ue,{flopay:xt.current,paypalFlopay:pt.current,attempt3DS:N?.attempt3DS,billingApiUrl:O,sessionId:ne,session:L,telemetry:!1,signal:Et})),Ue.type==="paypal_redirect_required"&&hs();else if(N?.initialAutoProcessingPending){let Et=N.initialAutoProcessingPending,A=new ro.PaymentAPI(O,{telemetry:!1}),ge=await Pr(oe=>A.waitForCheckoutSessionCompletion(Et.sessionId,{initialDelayMs:Et.retryAfterMs,nonce:we,statusUrl:Et.statusUrl,signal:oe})),Je=lo(ge,L),rt=ge.autoProcessingError?.type==="3ds_required"&&ge.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ge.autoProcessingError.nextActionRedirectUrl}:null;if(rt)it=await kt(rt);else{if(!Jn(Je))throw No(Je);it=Xn(Je,ne)}}else{if(N?.initialAutoProcessingError)throw qn(N.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:N.initialAutoProcessingError.checkoutMethod});if(N?.fromCreateSession)return N?.fallbackToFull&&(Ht("full"),rc("full")),!1;{let Et=await Ko({billingApiUrl:O,sessionId:ne,session:L,nonce:we,telemetry:!1});Et.type==="success"?it=Et.result:Et.type==="next_action_required"?it=await kt(Et):(G(),Et.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&tc({sessionId:ne,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),it=await Pr(A=>ri(Et,{flopay:xt.current,paypalFlopay:pt.current,attempt3DS:N?.attempt3DS,billingApiUrl:O,sessionId:ne,session:L,telemetry:!1,signal:A})),Et.type==="paypal_redirect_required"&&hs())}}ne&&(0,_n.markSessionRecentlyCompleted)(ne),Xe(),ce&&(q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),q.terminal({outcome:it.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Nr(it.status==="authorized"),Mt("success"),await Ta(600),yt=()=>Z.current?.(it)}catch(Ue){let Be=so(Sa(Ue),ne);if(Be.code==="three_ds_aborted")return!1;let it=Be.checkoutMethod??ba;Zt(Be.message),Kt(Be.message),Nr(!1),N?.fallbackToFull&&(q.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Ht("full"),rc("full")),Xe();let kt=Be.statusCode===void 0?void 0:(0,We.telemetryStatusClass)(Be.statusCode,"unknown"),Et=kt==="4xx"?{requestCategory:"process_payment",statusClass:kt}:{},A=kt===void 0||kt==="4xx";if(A&&(Be.telemetryOutcome==="payment_declined"||!!(Be.declineCode||Be.code?.toLowerCase().includes("declin"))))q.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Et});else if(A&&(Be.telemetryOutcome==="validation_rejected"||Be.type==="validation_error"))q.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Et});else{let rt=(0,We.classifyTelemetryFailure)(Ue,ce?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),oe=Be.telemetryRequestCategory??"process_payment";mt.current=!0;try{q.error({...rt,...Be.telemetryFailureCategory?{failureCategory:Be.telemetryFailureCategory}:{},stage:ce?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:oe})}finally{mt.current=!1}ct({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:oe,provider:Rt})}return(0,Ze.invokeMerchantCallback)(()=>At.current?.(Be)),vn(it,Be,{code:Be.code,declineCode:Be.declineCode}),Mt("error"),await Promise.allSettled([Ta(400),N?.ensureProvidersReady?N.ensureProvidersReady():Promise.resolve()]),ce&&(q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Xe(),le&&Ma(le),Mt(null),Kt(null)}return(0,Ze.invokeMerchantCallback)(yt),!0},[vn,ct,t,O,Pr,a,ye]);(0,v.useEffect)(()=>{if(typeof window>"u"||qr.current)return;let L=new URLSearchParams(window.location.search),N=L.get("payment_intent_client_secret");if(!N)return;let ne=Xd();ne&&(qr.current=!0,(async()=>{let we,Rt=0;Zt(null),Kt(null),Mt("processing"),Lr(!0);try{if(L.get("redirect_status")==="failed")throw Object.assign(new We.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:er,paypalFlopay:Ne}=await es({publishableKey:ne.publishableKey,paypalPublishableKey:ne.paypalPublishableKey,billingApiUrl:O,locale:l,telemetry:a});we=kr(Ne??er),we?.setCheckoutContext(ye),Rt=we?.now()??0,we?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),we?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let le=(Ne??er)?.getRawProvider();if(!le)throw Object.assign(new We.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:q,error:W}=await le.retrievePaymentIntent(N);if(W)throw Object.assign(new We.FloPayError(W.message??"Failed to retrieve PayPal payment status.","api_error",{code:W.code}),{checkoutMethod:"paypal"});let ce=hl(q?.status);if(!q||ce==="failed")throw Object.assign(new We.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let g=typeof q.payment_method=="string"?q.payment_method:q.payment_method?.id,y=ce;if(ne.sessionId){let Xe=(await new ro.PaymentAPI(O,{telemetry:!1}).getUnifiedCheckoutSession(ne.sessionId)).data.session;if(Xe&&Xe.status!=="complete"){let yt=await Ko({billingApiUrl:O,sessionId:ne.sessionId,session:Xe,telemetry:!1,tokenizedData:{id:g??q.id,type:"card",threeDSecureActionResultTokenId:q.id,isPaypal:!0}});if(yt.type!=="success")throw Object.assign(new We.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});y=yt.result.status}}ne.sessionId&&(0,_n.markSessionRecentlyCompleted)(ne.sessionId),we?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),we?.performance({stage:"redirect_resume",durationMs:we.elapsed(Rt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),we?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Mt("success"),await Ta(600),(0,Ze.invokeMerchantCallback)(()=>Z.current?.({status:y,paymentIntentId:q.id,paymentMethodId:g,checkoutMethod:"paypal"}))}catch(er){let Ne=so(Sa(er),ne.sessionId),le=Ne.checkoutMethod??"paypal",q=!!(Ne.declineCode||Ne.code?.toLowerCase().includes("declin"));if(we)we.performance({stage:"redirect_resume",durationMs:we.elapsed(Rt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),q?we.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):we.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(q){let W=hi(O,a,ye);W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ma(W)}else ys(O,a,ye,"REDIRECT_RESUME_FAILED","redirect_resume");Zt(Ne.message),Kt(Ne.message),(0,Ze.invokeMerchantCallback)(()=>At.current?.(Ne)),vn(le,Ne,{code:Ne.code,declineCode:Ne.declineCode}),Mt("error"),await Ta(400)}finally{hs(),Jd(),Mt(null),Kt(null),Lr(!1)}})())},[vn,l,O,a,ye]);let Fn=(0,v.useRef)(null),jr=(0,v.useMemo)(()=>Qt?(0,ft.serializeCreateParams)(Qt):"",[Qt]),ao=(0,v.useRef)(Qt);ao.current=Qt,(0,v.useEffect)(()=>{Bt(e??"")},[e]),(0,v.useEffect)(()=>{zr.current=!1,Zt(te),Kt(null),Nr(!1),Mt(null)},[jr,te,e]);async function cn(L,N,ne){let we=hi(O,a,ye),Rt=new ro.PaymentAPI(O,{telemetry:!1}),er=!1;try{let Ne=L.idempotencyKey===void 0?void 0:(0,We.resolveIdempotencyKey)(L.idempotencyKey),le=(0,ft.readCachedInlineSession)(N,ne),q=(0,ft.readCachedInlineIdempotencyKey)(N,ne);le?.canonicalIdentity===ne&&q&&q.canonicalIdentity===void 0&&((0,ft.persistCachedInlineIdempotencyKey)(N,ne,q.idempotencyKey),q={...q,canonicalIdentity:ne});let W=Ne??(q?.canonicalIdentity===ne?q.idempotencyKey:void 0),ce,g=!1;we.log({name:le?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let y=le?.sid??null,G=null,ke,Xe,yt=!1;if(y)try{G=await Rt.getUnifiedCheckoutSession(y,le?.nonce),le&&le.canonicalIdentity===void 0&&((0,ft.legacyCachedSessionMatchesDraft)(G.data.session,L)?((0,ft.persistCachedInlineSession)(N,ne,y,le.nonce??G.data.session?.clientSecret),q&&q.canonicalIdentity===void 0&&((0,ft.persistCachedInlineIdempotencyKey)(N,ne,q.idempotencyKey),W??(W=q.idempotencyKey))):((0,ft.clearCachedInlineCheckout)(N,ne),q=null,W=Ne,y=null,G=null));let Be=G?.data.session?.status,it=G?.data.session,kt=it?.clientSecret||le?.nonce;if(y&&it?.buyerIdentified===!1&&kt&&(Xe=Lo(Rt,y,kt,L.account)),y&&G&&Be==="complete"){if((0,_n.wasSessionRecentlyCompleted)(y))return{sid:y,result:G};(0,ft.clearCachedInlineCheckout)(N,ne),y=null,G=null,g=!0}}catch{we.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),le?.canonicalIdentity===void 0?((0,ft.clearCachedInlineCheckout)(N,ne),W=Ne):(0,ft.clearCachedInlineSession)(N,ne),y=null}if(!y){!Ne&&(g||!W)&&(W=(0,We.resolveIdempotencyKey)(),ce=W),W&&(0,ft.persistCachedInlineIdempotencyKey)(N,ne,W);let Be=we.now(),it=0;we.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let kt={...L,idempotencyKey:W,avsCheck:!!de,avsConfig:typeof de=="object"?de:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ps(H,ie)};Object.defineProperty(kt,ro.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ge=>{it=Math.max(it,ge)}}});let Et=()=>{Ql(we,"session_create",Be,it)},A=ge=>{ec(we,ge,"session_create",Be,it)&&ct({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,We.isDetachedSessionEligible)(kt)){let ge=await Rt.createDetachedSession(kt);ge.claimed.catch(()=>{}),G=ge.shell,y=ge.sessionId,Xe=ge.claim;let Je=we.now();we.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ke=ge.claimed.then(rt=>{let oe=rt.data.session?.id??ge.sessionId;return oe&&(0,ft.persistCachedInlineSession)(N,ne,oe,rt.data.session?.clientSecret??ge.nonce),Ql(we,"session_claim",Je),Et(),rt},rt=>{throw(0,ft.clearCachedInlineSession)(N,ne),ec(we,rt,"session_claim",Je,0)&&ct({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),rt}).finally(()=>Ma(we)),ke.catch(()=>{}),er=!0,we.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),we.performance({stage:"session_shell",durationMs:we.now()-Be,durationMode:"machine",requestCategory:"session_create",attempt:it,statusClass:"2xx",paymentMethodCategory:"card"})}else G=await Rt.createAndFetchSession(kt),Et()}catch(ge){throw A(ge),ge}y=G.data.session?.id??y??"",y&&!ke&&(0,ft.persistCachedInlineSession)(N,ne,y,G.data.session?.clientSecret)}let Ue=G?.data.session;return!Xe&&y&&Ue?.buyerIdentified===!1&&Ue.clientSecret&&(Xe=Lo(Rt,y,Ue.clientSecret,L.account)),{sid:y??"",result:G,sdkGeneratedIdempotencyKey:ce,...ke?{claimed:ke}:{},...Xe?{claim:Xe}:{},...yt?{claimRequiresIdentity:!0}:{}}}finally{er||Ma(we)}}let Hn=(0,v.useRef)(cn);Co(()=>{Hn.current=cn},[cn]);let en=(0,v.useCallback)(async(L,N)=>{let ne=ao.current;if(!ne)throw new We.FloPayError("createSession is required to bootstrap checkout.","validation_error");let we=Hi(ne,L),Rt=(0,ft.serializeCreateParams)(we),er=(0,ft.hashCreateParams)(we),Ne=Pi.get(Rt);if(!Ne){let W={canonicalIdentity:Rt,promise:Hn.current(we,er,Rt),consumers:0,settled:!1};Ne=W,Pi.set(Rt,W);let ce=()=>{W.settled=!0,Zl(Rt,W)};W.promise.then(ce,ce)}Ne.consumers+=1;let le=!1,q=()=>{le||(le=!0,Ne.consumers-=1,Zl(Rt,Ne))};N?.(q);try{let W=await Ne.promise;Fn.current=Rt,L&&(Hr(tt),sr(Ue=>yl(Ue,L)));let{sid:ce,result:g,claimed:y,claim:G,claimRequiresIdentity:ke}=W;if(dr.current=G,Yt(ke===!0),et(g),g.data.session&&Ae(g.data.session),ce&&Bt(ce),y){Ir.current+=1;let Ue=Ir.current;cr.current=y,Gt(!0),y.then(Be=>{Ir.current===Ue&&(cr.current===y&&(cr.current=null),et(Be),Be.data.session&&Ae(Be.data.session),Gt(!1),Yt(!1))},Be=>{Ir.current===Ue&&(cr.current===y&&(cr.current=null),Gt(!1),Yt(!1),K(Be instanceof We.FloPayError?Be:new We.FloPayError(Be instanceof Error?Be.message:"Failed to create session","api_error")))})}else Ir.current+=1,cr.current=null,Gt(!1),Yt(!1);let{flopay:Xe,paypalFlopay:yt}=await gs(g,{billingApiUrl:O,locale:l,telemetry:a});return Ot(Xe,yt),se(!1),W}catch(W){throw Fn.current===Rt&&(Fn.current=null),W}finally{N||q()}},[tt,Ot,l,O,a]),Cn=(0,v.useRef)($n);Cn.current=$n;let Bn=(0,v.useRef)(en);Bn.current=en;let Nt=(0,v.useCallback)(async L=>{if(!Qd(L)||dt)return{sessionId:He,session:z};wt(!0);try{let N=await en(L);return{sessionId:N.sid,session:N.result.data.session??null}}finally{wt(!1)}},[en,dt,He,z]),tn=(0,v.useCallback)(async L=>{let N=dr.current;if(!N)return;let ne=Ir.current,we=await N(L);Ir.current===ne&&(et(we),we.data.session&&Ae(we.data.session))},[]),rn=(0,v.useCallback)(async()=>{await cr.current},[]),Gr=(0,v.useCallback)(async()=>(await rn(),{proceed:!0}),[rn]);(0,v.useEffect)(()=>{let L=!1,N,ne=++Ce.current;jt(),K(null),xr(0);let we=()=>{L=!0,Ce.current===ne&&(Ce.current+=1,jt())},Rt=ao.current;if(jr&&Rt)return Ht(Br),se(!1),Fn.current===jr?we:(Ae(fl(Rt,j)),(async()=>{let le=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),q=Br==="auto"&&!zr.current&&!le;q&&(Zt(null),Kt(null),Mt("processing"));try{let W=await Bn.current(void 0,G=>{N=G}),ce=W.result.data.session??null;Xt.current=Qi(W.result);let g=fs(W.result),y=(0,_n.wasSessionRecentlyCompleted)(W.sid||ce?.id);if(!L&&q&&ce&&!g&&!y){zr.current=!0,await Kd(jr,W.sdkGeneratedIdempotencyKey,()=>Cn.current(ce,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:W.result.autoProcessingError,initialAutoProcessingPending:W.result.autoProcessingPending,autoProcessingAttempted:W.result.autoProcessingAttempted,sessionId:W.sid||ce.id}));return}!L&&q&&((g||y)&&(zr.current=!0),Mt(null),Kt(null))}catch(W){if(L)return;let ce=Ha(W);if(q&&ce==="session_auto_completed"){zr.current=!0,Mt("success"),await Ta(600),L||((0,Ze.invokeMerchantCallback)(()=>{Z.current?.({status:"succeeded"})}),Mt(null),Kt(null));return}q&&(Mt(null),Kt(null));let g=W instanceof We.FloPayError?W:new We.FloPayError(W instanceof Error?W.message:"Failed to create session","api_error");K(g)}finally{N?.(),N=void 0}})(),()=>{we(),N?.()});se(!0);async function er(){let le=!1,q=null;try{let W=new ro.PaymentAPI(O,{telemetry:!1}),ce=await W.getUnifiedCheckoutSession(c,t);if(q=ce,L)return;et(ce);let g=ce.data.session??null;if(Ae(g),!g)throw new We.FloPayError("No session data returned","api_error");let y=g.checkoutMode;if(y==="setup")throw new We.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(g.status==="authorized"){se(!1),(0,Ze.invokeMerchantCallback)(()=>{Z.current?.(Xn(g,c)),vr.current?.(g.successUrl??"")});return}if(g.status==="complete"){se(!1),(0,Ze.invokeMerchantCallback)(()=>{vr.current?.(g.successUrl??"")});return}if(g.status==="expired")throw $a(g);le=!0;let G=j??y??"full";Ht(G),Ir.current+=1;let ke=g.clientSecret||t;dr.current=g.buyerIdentified===!1&&ke?Lo(W,c,ke,{...g.customer?.id?{userId:g.customer.id}:{}}):void 0,Gt(!1),Yt(!1);let Xe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),yt=fs(ce);if(G==="auto"&&!zr.current&&!Xe&&!yt){zr.current=!0;let Ue=Ne(ce);try{if(await Cn.current(g,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Ue,sessionId:c||g.id}),L)return;await Ue,L||se(!1);return}catch{if(L)return;await Ue,L||se(!1);return}}await Ne(ce),L||se(!1)}catch(W){if(L)return;let ce=ml(W,le);if(le&&ct({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ce){let{errorCode:y,stage:G,...ke}=ce;ys(O,a,ye,y,G,ke)}if(ce?.stage==="provider_load"&&(j??q?.data.session?.checkoutMode??"full")==="full"&&pl(q,x,f)){let y=Yd({billingApiUrl:O,locale:l,telemetry:a});Ct.current=y,Ot(y,null),xr(1),se(!1);return}let g=W instanceof We.FloPayError&&ce?.stage!=="provider_load"?W:ul();g!==W&&(0,Ze.invokeMerchantCallback)(()=>At.current?.(g)),K(g),se(!1)}}async function Ne(le){let{flopay:q,paypalFlopay:W,...ce}=await gs(le,{billingApiUrl:O,locale:l,telemetry:a});Xt.current={publishableKey:ce.publishableKey,paypalPublishableKey:ce.paypalPublishableKey},Ot(q,W),xr(0)}return er(),we},[j,jr,Br,U,t,x,f]);let bn=(0,v.useCallback)(async()=>{if(!_e||Ut!==1)return;let L=Ce.current;xr(2);try{let{flopay:N,paypalFlopay:ne}=await gs(_e,{billingApiUrl:O,locale:l,telemetry:a});if(Ce.current!==L)return;jt(),Ot(N,ne),xr(0)}catch(N){if(Ce.current!==L)return;let{errorCode:ne,stage:we,...Rt}=$i(N);ys(O,a,ye,ne,we,Rt)}},[jt,Ot,l,Ut,O,a,ye,_e]),bt=!!(c&&(z?.clientSecret||t)),_r=Tt||!bt,mr=(0,v.useCallback)(async()=>{if(!(Tt||!bt||!z)){Lr(!0),Zt(null);try{await $n(z,{attempt3DS:!0,fallbackToFull:!0,sessionId:c||z.id})}finally{Lr(!1)}}},[c,Tt,bt,$n,z]),Yr=(0,We.resolveDirectPaypalConfig)(_e?.data.paypal,J),mo=fs(_e),Sn=(0,v.useMemo)(()=>{if(!(!_e||!z||!_e.data.stripe?.publishableKey))return{billingApiUrl:O}},[_e,z,O]),Kn=!!(r&&!H&&ie==="buttons"&&De&&Br==="full"),nn=!!(c&&((0,We.isMountableVaultBlock)(z?.vault)||(0,Rn.canRecoverHostedCardForm)(z))),Tr=(0,v.useMemo)(()=>({session:z,loading:V,error:R,checkoutMode:ir,inlineSessionDraft:Qt,applyInlineSessionPatch:Kn?Nt:void 0,inlineSessionPatchProcessing:dt,claimPending:lr,claimRequiresIdentity:hr,claimBuyerIdentity:tn,waitForDataAttachment:rn}),[z,V,R,ir,Qt,Kn,Nt,dt,lr,hr,tn,rn]),Dn=!!r&&ie==="buttons"&&!mo&&!nn&&(!at||!Sn),Dr=$r?(0,F.jsx)(Zr,{status:$r,errorMessage:xn,authorized:ln}):null;if(V&&!nn){if(p)return(0,F.jsxs)(F.Fragment,{children:[p,Dr]});if(ie==="buttons"){let L=Pe?.buttonsLayout?.cardButton?.borderRadius??Pe?.appearance.variables?.borderRadius??8,N=ne=>(0,F.jsx)("div",{style:{height:ne,borderRadius:L,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[x&&N(Jo),f&&(b||Ie)&&N(Jo),f&&N(Jo),(0,F.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Dr]})}return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,F.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,F.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Dr]})}return R?m?(0,F.jsx)(En.Provider,{value:Tr,children:m(R)}):(0,F.jsx)(En.Provider,{value:Tr,children:(0,F.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:R.message})}):Dn?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:Tr,children:(0,F.jsx)(tu,{onButtonClick:Ge,showPayPal:x,showStripe:f,showApplePay:b,showGooglePay:Ie,theme:me,buttonsTheme:ue,buttonsStyles:xe,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B})}),Dr]}):mo&&z&&Yr?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:Tr,children:(0,F.jsxs)("div",{className:ze,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ar&&(0,F.jsx)(Wo,{icon:!1,children:Ar}),Ye==="retrying"&&(0,F.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ye==="exhausted"&&(0,F.jsxs)("div",{role:"alert",children:[(0,F.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,F.jsx)("button",{type:"button",onClick:Vt,children:"Retry PayPal"})]}),Ye!=="exhausted"&&(0,F.jsx)("div",{"aria-hidden":Ye==="retrying"?!0:void 0,style:Ye==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,F.jsx)(Il,{sessionId:c,nonce:z.clientSecret||void 0,billingApiUrl:O,email:z.customer?.email||Qt?.account?.email,billingName:[z.customer?.firstName,z.customer?.lastName].filter(Boolean).join(" ")||[Qt?.account?.firstName,Qt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:tn,clientId:Yr.clientId,environment:Yr.environment,currency:(z.currency??"usd").toUpperCase(),isSubscription:z.mode==="subscription",providerObjectType:Yr.providerObjectType,approvalPresentation:Yr.approvalPresentation,existingOrderId:Yr.existingOrderId,onComplete:h,onErrorChange:Zt,onDecline:E,onCancel:Y,onButtonClick:Ge,runBeforeButtonClick:Gr,onInitializationStateChange:$,allowAutomaticRetry:ur===0,session:z,telemetry:a,telemetryContext:ye,onInstrument:Ve,debug:_},`${be}:paypal-init-${ur}`)})]})}),Dr]}):ir==="confirm"?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:Tr,children:(0,F.jsx)(va,{flopay:at,paypalFlopay:T,options:Sn??{billingApiUrl:O},onInstrument:Ve,children:(0,F.jsxs)("div",{className:ze,children:[Ar&&(0,F.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ar}),Te?Te({onConfirm:mr,isProcessing:_r}):(0,F.jsx)("button",{type:"button",onClick:mr,disabled:_r,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:_r?"not-allowed":"pointer",opacity:_r?.6:1},children:Tt?"Processing...":je??"Confirm Purchase"})]})},be)}),Dr]}):(!at||!Sn)&&!(nn&&ir==="full")?(0,F.jsx)(F.Fragment,{children:Dr}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:Tr,children:(0,F.jsxs)(va,{flopay:at,paypalFlopay:T,options:Sn??{billingApiUrl:O},onInstrument:Ve,children:[Ut===1&&(0,F.jsx)("button",{type:"button",onClick:bn,children:"Retry payment methods"}),H?(0,F.jsxs)(F.Fragment,{children:[Ar&&(0,F.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ar}),(0,F.jsx)(eu,{sessionId:c,nonce:z?.clientSecret||void 0,billingApiUrl:O,session:z,submitLabel:nt,walletPresentation:P,children:H})]}):(0,F.jsx)(fi,{sessionId:c,nonce:z?.clientSecret||void 0,telemetry:a,email:z?.customer?.email||Qt?.account?.email,userId:z?.customer?.id||Qt?.account?.userId,firstName:z?.customer?.firstName||Qt?.account?.firstName,lastName:z?.customer?.lastName||Qt?.account?.lastName,totalAmount:z?Math.round((0,We.buildCheckoutDisplayData)(z).total*100):0,currency:z?.currency?.toLowerCase()??"usd",onComplete:h,onError:w,onDecline:E,onCancel:Y,error:Ar,onErrorChange:Zt,showPayPal:x,showStripe:f,walletPresentation:P,enabledPaymentMethods:Ut?[]:pe??_e?.data.stripe?.enabledPaymentMethods??z?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:_e?.data.stripe?.enabledPaymentMethodCountries,showApplePay:b,showGooglePay:Ie,layout:ie,theme:me,buttonsTheme:ue,buttonsStyles:xe,appearance:ut,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B,onButtonClick:Ge,onBeforeButtonClick:De,onBuyerIdentityReady:tn,enableAVS:de,...re?{cardFieldOrder:re}:{},...X?{cardPreFormSlot:X}:{},avsLayout:Oe,country:z?.customer?.country,city:z?.customer?.city,state:z?.customer?.state,onCountryChange:I,onZipChange:ee,avsCheck:!!de,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Ps(H,ie),className:ze,submitLabel:nt,directPaypal:Yr,isSubscription:z?.mode==="subscription",session:z,dataAttachmentPending:lr,dataAttachmentRequiresIdentity:hr,debug:_})]},be)}),Dr]})}function eu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:i,children:l}){return(0,F.jsx)(F.Fragment,{children:v.default.Children.map(l,p=>{if(!v.default.isValidElement(p))return p;let m=p.props,h={};return m.sessionId||(h.sessionId=e),!m.nonce&&t&&(h.nonce=t),m.billingApiUrl||(h.billingApiUrl=r),m.submitLabel===void 0&&a!==void 0&&(h.submitLabel=a),m.walletPresentation===void 0&&(h.walletPresentation=i),n?.customer&&(m.email||(h.email=n.customer.email),m.userId||(h.userId=n.customer.id),m.firstName||(h.firstName=n.customer.firstName),m.lastName||(h.lastName=n.customer.lastName)),Object.keys(h).length===0?p:v.default.cloneElement(p,h)})})}function tu({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:i,buttonsTheme:l,buttonsStyles:p,cardButtonContent:m,cardBackButtonContent:h,cardTitleContent:w}){let[S,E]=(0,v.useState)(!1),Y=(0,v.useMemo)(()=>(0,We.resolveTheme)(i),[i]),I=(0,v.useMemo)(()=>{let P=Y?.buttonsLayout??(0,We.resolveButtonsLayoutTheme)(l);return p?{...P,...p,cardButton:{...P.cardButton,...p.cardButton},cardFormContainer:{...P.cardFormContainer,...p.cardFormContainer},backButton:{...P.backButton,...p.backButton},backButtonIcon:{...P.backButtonIcon,...p.backButtonIcon},submitButton:{...P.submitButton,...p.submitButton},title:{...P.title,...p.title}}:P},[Y,l,p]),ee=Y?.buttonsLayout?.cardButton?.borderRadius??Y?.appearance.variables?.borderRadius??8,x=P=>(0,F.jsx)("div",{style:{height:P,borderRadius:ee,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),f=m===void 0?{boxSizing:"border-box",height:Jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(S){let P=I.cardInputBorder??"#e5e7eb",pe=I.cardInputBackground??"white",b=Bo(h),Ie=Bo(w);return(0,F.jsxs)("div",{style:{backgroundColor:I.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...I.cardFormContainer},children:[(0,F.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,F.jsxs)("button",{type:"button",onClick:()=>E(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:b?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...I.backButton},children:[(0,F.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...I.backButtonIcon},children:(0,F.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,F.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,F.jsx)(Oo,{content:h})]}),Ie?(0,F.jsx)("div",{style:{flex:1}}):(0,F.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...I.title},children:(0,F.jsx)(ua,{content:w})})]}),(0,F.jsx)("div",{style:{backgroundColor:pe,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsxs)("div",{style:{display:"flex"},children:[(0,F.jsx)("div",{style:{flex:1,backgroundColor:pe,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{flex:1,backgroundColor:pe,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,F.jsx)("div",{style:{backgroundColor:pe,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...I.submitButton,opacity:.5}}),(0,F.jsx)("style",{children:`
38
+ `}),la&&ho&&(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:he?-2:0},children:[(0,u.jsxs)("button",{type:"button",onClick:we,style:{display:"inline-flex",alignItems:"center",gap:Vi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:L.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...L.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...L.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Uo,{content:Ne})]}),sl?(0,u.jsx)("div",{style:{flex:1}}):(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:L.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...L.title},children:(0,u.jsx)(ma,{content:ue})})]}),!la&&!sl&&(0,u.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Wi,order:he?-3:0,...L.title},children:(0,u.jsx)(ma,{content:ue})}),he&&$&&(0,u.jsx)("div",{style:{order:-2,width:"100%"},children:$}),he&&rt&&(0,u.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,u.jsx)("div",{style:{backgroundColor:Bo,border:`1px solid ${gn(Va)}`,borderRadius:lr,padding:"10px"},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Jt,onChange:i=>{zt("email"),Ht.current=i.target.value,Pr(i.target.value)},onPointerDown:()=>zt("email"),onKeyDown:()=>zt("email"),onBlur:()=>{tn("email")&&Qn(!0),Ot||Fi()},disabled:bt,required:!0,"aria-invalid":Va||void 0,"aria-describedby":Va?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...$i}})}),Va&&(0,u.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:da,children:Xr.empty?"Email address is required":"Enter a valid email address"})]}),Xe&&(0,u.jsx)("div",{style:{order:he?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Wt,C=(J=!1)=>({backgroundColor:Bo,border:`1px solid ${gn(J)}`,borderRadius:lr,marginTop:"0.5rem",padding:"10px"}),G=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...$i}),Te=(0,d.getStateOptions)(i);return(0,u.jsxs)(u.Fragment,{children:[(0,d.isAVSFieldVisible)(Xe.address_line_1,i)&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)("div",{style:C(er("line1")),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:rr,onChange:J=>{zt("line1"),Rr.current.addressLine1=!0,$t.current=J.target.value,Qr(J.target.value)},onPointerDown:()=>zt("line1"),onKeyDown:()=>zt("line1"),onBlur:()=>rn("line1"),disabled:bt,required:!0,"aria-invalid":er("line1")||void 0,"aria-describedby":er("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:G()})}),er("line1")&&(0,u.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:da,children:"Street address is required"})]}),(0,d.isAVSFieldVisible)(Xe.address_line_2,i)&&(0,u.jsx)("div",{style:C(),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Tt,onChange:J=>{Rr.current.addressLine2=!0,nr.current=J.target.value,Ln(J.target.value)},disabled:bt,"data-testid":"flopay-address-line2",style:G()})}),((0,d.isAVSFieldVisible)(Xe.city,i)||(0,d.isAVSFieldVisible)(Xe.state,i))&&(0,u.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Xe.city,i)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Bo,borderTop:`1px solid ${gn(er("city"))}`,borderRight:`1px solid ${gn(er("city"))}`,borderBottom:`1px solid ${gn(er("city"))}`,borderLeft:`1px solid ${gn(er("city"))}`,padding:"10px",borderTopLeftRadius:lr,borderBottomLeftRadius:lr,...(0,d.isAVSFieldVisible)(Xe.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:lr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Xt,onChange:J=>{zt("city"),Rr.current.city=!0,vr.current=J.target.value,yn(J.target.value)},onPointerDown:()=>zt("city"),onKeyDown:()=>zt("city"),onBlur:()=>rn("city"),disabled:bt,required:!0,"aria-invalid":er("city")||void 0,"aria-describedby":er("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:G()})}),(0,d.isAVSFieldVisible)(Xe.state,i)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Bo,borderTop:`1px solid ${gn(er("state"))}`,borderRight:`1px solid ${gn(er("state"))}`,borderBottom:`1px solid ${gn(er("state"))}`,borderLeft:`1px solid ${gn(er("state"))}`,padding:"10px",borderTopRightRadius:lr,borderBottomRightRadius:lr,...(0,d.isAVSFieldVisible)(Xe.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${gn(er("state")||er("city"))}`}:{borderRadius:lr}},children:Te?(0,u.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Hr,onChange:J=>{zt("state"),Rr.current.state=!0,Zt.current=J.target.value,Kr(J.target.value)},onPointerDown:()=>zt("state"),onKeyDown:()=>zt("state"),onBlur:()=>rn("state"),disabled:bt,autoComplete:"billing address-level1",required:!0,"aria-invalid":er("state")||void 0,"aria-describedby":er("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...G(),cursor:"pointer"},children:[(0,u.jsx)("option",{value:"",children:(0,d.getStateLabel)(i)}),Te.map(J=>(0,u.jsx)("option",{value:J.code,children:J.name},J.code))]}):(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,d.getStateLabel)(i),autoComplete:"billing address-level1",value:Hr,onChange:J=>{zt("state"),Rr.current.state=!0,Zt.current=J.target.value,Kr(J.target.value)},onPointerDown:()=>zt("state"),onKeyDown:()=>zt("state"),onBlur:()=>rn("state"),disabled:bt,required:!0,"aria-invalid":er("state")||void 0,"aria-describedby":er("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:G()})})]}),er("city")&&(0,u.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:da,children:"City is required"}),er("state")&&(0,u.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:da,children:[(0,d.getStateLabel)(i)," is required"]}),((0,d.isAVSFieldVisible)(Xe.country,i)||(0,d.isAVSFieldVisible)(Xe.postal_code,i))&&(0,u.jsxs)("div",{style:{display:"flex",flexDirection:H==="column"?"column":"row",gap:H==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Xe.country,i)&&(0,u.jsx)("div",{style:{flex:H==="row"?1:void 0,backgroundColor:Bo,borderTop:`1px solid ${ca}`,borderRight:`1px solid ${ca}`,borderBottom:`1px solid ${ca}`,borderLeft:`1px solid ${ca}`,padding:"10px",...H==="row"&&(0,d.isAVSFieldVisible)(Xe.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:lr,borderBottomLeftRadius:lr,borderRight:"none"}:{borderRadius:lr}},children:(0,u.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Wt,onChange:J=>{Rr.current.country=!0,Br.current=J.target.value,_t(J.target.value),pt?.(J.target.value),Zt.current="",Kr("")},disabled:bt,autoComplete:"billing country","data-testid":"flopay-country",style:{...G(),cursor:"pointer"},children:[Wt===""?(0,u.jsx)("option",{value:"",children:"Select country"}):null,d.COUNTRY_OPTIONS.map(J=>(0,u.jsxs)("option",{value:J.code,children:[J.flag," ",J.name]},J.code))]})}),(0,d.isAVSFieldVisible)(Xe.postal_code,i)&&(0,u.jsx)("div",{style:{flex:H==="row"?1:void 0,backgroundColor:Bo,border:`1px solid ${jc}`,padding:"10px",...H==="row"&&(0,d.isAVSFieldVisible)(Xe.country,i)?{borderRadius:"0",borderTopRightRadius:lr,borderBottomRightRadius:lr}:{borderRadius:lr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,d.getPostalCodeLabel)(Wt),autoComplete:"billing postal-code",value:$r,onChange:J=>{zt("zip"),Rr.current.zip=!0,kt.current=J.target.value,Nr(J.target.value),Ue?.(J.target.value)},onPointerDown:()=>zt("zip"),onKeyDown:()=>zt("zip"),onBlur:()=>{tn("zip")&&zn(!0)},disabled:bt,required:Nt.required,"aria-invalid":Wa||void 0,"aria-describedby":Wa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:G()})})]}),Wa&&(0,u.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:da,children:Nt.empty?`${(0,d.getPostalCodeLabel)(i)} is required`:Yd(i)})]})})()}),he&&Kc,Ce&&(0,u.jsx)(Ko,{margin:"0.75rem 0",styleOverride:L.errorBanner,children:Ce})]}),$a={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},pl=i=>N?!me||!Vn?(0,u.jsx)("pre",{"data-testid":i,style:$a,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":i,style:$a,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${me}`,` directPaypalConfigured=${Vn}`,` inAppBrowserDetected=${String(za)}`,` shouldRenderDirectPayPal=${na}`,` shouldRenderStripePayPal=${aa}`,` hasPaypalStripeInstance=${!!_s}`].join(`
39
+ `)}):null,ml=i=>N?!S||!Vr?(0,u.jsx)("pre",{"data-testid":i,style:$a,children:"FloPay/Stripe-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":i,style:$a,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${S}`,` currency=${pr}`,` amountInCents=${ta}`,` enabledPaymentMethods: ${JSON.stringify(T??[])}`,` enabledPaymentMethodsProvided=${ra}`,` hasEnabledMethods=${Oa}`,` expressMethods: ${JSON.stringify(Na)}`,` walletExpressMethods: ${JSON.stringify(Ao)}`,` paymentElementMethods: ${JSON.stringify(Di)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ua)}`,` hasStripeInstance=${!!Vr}`,` shouldRenderWallets=${Fo}`,` shouldRenderPaymentElement=${ia}`].join(`
40
+ `)}):null,yl=ut==="apm-expanding"||ut==="apm-form"||ut==="apm-collapsing",Oo;ut==="apm-expanding"?Oo=Jl:ut==="apm-collapsing"&&(Oo=Zl);let Ha=sr?sc(Oi,sr,He):null;if(Re==="buttons"){let i=ut==="buttons"||ut==="expanding"||ut==="apm-expanding",C=ut==="expanding"||ut==="card"||ut==="collapsing",G=Ye===void 0?{boxSizing:"border-box",height:Jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Te;ut==="expanding"||ut==="apm-expanding"?Te=$d:(ut==="collapsing"||ut==="apm-collapsing")&&(Te=Wd);let J;return ut==="expanding"?J=Jl:ut==="collapsing"&&(J=Zl),(0,u.jsxs)("form",{onSubmit:zi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Zo,{}),Ie&&(0,u.jsx)(sn,{status:Ie,errorMessage:Ce,authorized:Er}),(0,u.jsxs)("div",{style:{display:"grid"},children:[(0,u.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Te?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Te?Kd:{},...Te?{animation:Te,pointerEvents:"none"}:{}},children:[pl("flopay-direct-paypal-gate-debug"),ml("flopay-stripe-gate-debug"),na&&vt&&(0,u.jsxs)(u.Fragment,{children:[Ze&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(ha.Provider,{value:x,children:(0,u.jsx)(va,{sessionId:e,nonce:t,billingApiUrl:E,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,clientId:vt.clientId,environment:vt.environment,currency:pr.toUpperCase(),isSubscription:be,providerObjectType:Dt,approvalPresentation:qa==="popup"?void 0:qa,onTokenizedBody:on,onComplete:l,onErrorChange:ze,onDecline:m,onCancel:h,onTechnicalFailure:Mo,onButtonClick:K,runBeforeButtonClick:Tn,isProcessing:bt,onLoadStateChange:Li,onInitializationStateChange:Ni,session:We,existingOrderId:Ze?.orderId,debug:N},Ze?.orderId??"fresh")})]}),aa&&(0,u.jsx)(cr.Elements,{stripe:oa,options:xs,children:(0,u.jsx)(ec,{sessionId:e,nonce:t,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,isProcessing:bt,onButtonClick:K,onDecline:m,onTechnicalFailure:Mo,runBeforeButtonClick:Tn,onLoadStateChange:Ws,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:Qs,presentationMode:xo})}),Fo?(0,u.jsx)(cr.Elements,{stripe:Vr,options:Ms,children:(0,u.jsx)(tc,{sessionId:e,nonce:t,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,billingApiUrl:E,intentKind:at>0?"payment":"setup",expressMethods:Ao,onTokenizedBody:on,onErrorChange:ze,onButtonClick:K,onDecline:m,onTechnicalFailure:Mo,runBeforeButtonClick:Tn,onLoadStateChange:Hs,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:it})}):null,!Fo&&Js?(0,u.jsx)("div",{style:{height:Jo,borderRadius:Po,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ia&&(0,u.jsx)(rc,{sessionId:e,nonce:t,email:se.email,billingName:[se.firstName,se.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:O,billingApiUrl:E,paymentElementMethods:Ua,stripeInstance:Vr,paymentElementBaseOptions:Oi,futureUseSession:He,onTokenizedBody:on,onErrorChange:ze,onButtonClick:K,onDecline:m,runBeforeButtonClick:Tn,onLoadStateChange:Gs,isProcessing:bt,submitButtonColor:vo,submitButtonBorderRadius:lr,submitButtonStyle:L.submitButton,onExpandApm:mt,expandedApmMethod:sr,themeId:lt,buttonAppearance:{backgroundColor:L.cardButton?.backgroundColor,borderColor:L.cardInputBorder,textColor:L.cardButton?.color,borderRadius:Po}}),he&&(0,u.jsx)("button",{type:"button",onClick:async()=>{bt||!(await Tn("card")).proceed||(K?.("card"),ie())},disabled:bt,style:{width:"100%",...G,...L.cardButton,...gs({themeBundle:_e,resolvedPrimaryColor:vo,resolvedBorderRadius:lr,submitButtonStyle:L.submitButton,explicitPrimaryColor:an?.colorPrimary}),fontSize:L.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:bt?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:bt?.6:1},onMouseEnter:Me=>{!bt&&(_e||an?.colorPrimary)&&(Me.currentTarget.style.backgroundColor=$c)},onMouseLeave:Me=>{(_e||an?.colorPrimary)&&(Me.currentTarget.style.backgroundColor=vo)},onMouseDown:Me=>{Me.currentTarget.style.transform="scale(0.985)"},onMouseUp:Me=>{Me.currentTarget.style.transform="scale(1)"},children:(0,u.jsx)(No,{content:Ye})}),Ce&&ut==="buttons"&&(0,u.jsx)(Ko,{margin:"0.25rem 0",styleOverride:L.errorBanner,children:Ce})]}),he&&C&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...J?{animation:J}:{},...ut==="collapsing"?{pointerEvents:"none"}:{}},children:ul}),S&&yl&&sr&&Ha&&Vr&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...Oo?{animation:Oo}:{},...ut==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:ji,borderRadius:Ki,...ua,padding:Hi},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:Vi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:L.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...L.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...L.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Uo,{content:Ne})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:L.titleFontSize??"1.05rem",color:Wi,paddingRight:80,...L.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(sr)}`})]}),(0,u.jsx)(cr.Elements,{stripe:Vr,options:Ha,children:(0,u.jsx)(ms,{method:sr,sessionId:e,nonce:t,email:se.email,billingName:[se.firstName,se.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:O,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,onDecline:m,onCancel:Gt,runBeforeButtonClick:Tn,onButtonClick:K,isProcessing:bt,submitButtonColor:vo,submitButtonBorderRadius:lr,submitButtonStyle:L.submitButton,errorText:Ce})},sr)]})})]})]})}return yl&&sr&&Ha&&Vr&&S?(0,u.jsxs)("form",{onSubmit:zi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Zo,{}),Ie&&(0,u.jsx)(sn,{status:Ie,errorMessage:Ce,authorized:Er}),(0,u.jsx)("div",{style:{...Oo?{animation:Oo}:{},...ut==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:ji,borderRadius:Ki,...ua,padding:Hi},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:Vi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:L.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...L.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...L.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Uo,{content:Ne})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:L.titleFontSize??"1.05rem",color:Wi,paddingRight:80,...L.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(sr)}`})]}),(0,u.jsx)(cr.Elements,{stripe:Vr,options:Ha,children:(0,u.jsx)(ms,{method:sr,sessionId:e,nonce:t,email:se.email,billingName:[se.firstName,se.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:O,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,onDecline:m,onCancel:Gt,runBeforeButtonClick:Tn,onButtonClick:K,isProcessing:bt,submitButtonColor:vo,submitButtonBorderRadius:lr,submitButtonStyle:L.submitButton,errorText:Ce})},sr)]})})]}):(0,u.jsxs)("form",{onSubmit:zi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Zo,{}),Ie&&(0,u.jsx)(sn,{status:Ie,errorMessage:Ce,authorized:Er}),(0,u.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[pl("flopay-direct-paypal-gate-debug-default"),ml("flopay-stripe-gate-debug-default"),na&&vt&&(0,u.jsxs)(u.Fragment,{children:[Ze&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(ha.Provider,{value:x,children:(0,u.jsx)(va,{sessionId:e,nonce:t,billingApiUrl:E,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,clientId:vt.clientId,environment:vt.environment,currency:pr.toUpperCase(),isSubscription:be,providerObjectType:Dt,approvalPresentation:qa==="popup"?void 0:qa,onTokenizedBody:on,onComplete:l,onErrorChange:ze,onDecline:m,onCancel:h,onTechnicalFailure:Mo,onButtonClick:K,runBeforeButtonClick:Tn,isProcessing:bt,onLoadStateChange:Li,onInitializationStateChange:Ni,session:We,existingOrderId:Ze?.orderId,debug:N},Ze?.orderId??"fresh")})]}),aa&&(0,u.jsx)(cr.Elements,{stripe:oa,options:xs,children:(0,u.jsx)(ec,{sessionId:e,nonce:t,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,isProcessing:bt,onButtonClick:K,onDecline:m,onTechnicalFailure:Mo,runBeforeButtonClick:Tn,onLoadStateChange:Ws,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:Qs,presentationMode:xo})}),Fo&&(0,u.jsx)(cr.Elements,{stripe:Vr,options:Ms,children:(0,u.jsx)(tc,{sessionId:e,nonce:t,email:se.email,billingName:ht||void 0,onBuyerIdentityReady:O,billingApiUrl:E,intentKind:at>0?"payment":"setup",expressMethods:Ao,onTokenizedBody:on,onErrorChange:ze,onButtonClick:K,onDecline:m,onTechnicalFailure:Mo,runBeforeButtonClick:Tn,onLoadStateChange:Hs,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:it})}),ia&&(0,u.jsx)(rc,{sessionId:e,nonce:t,email:se.email,billingName:[se.firstName,se.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:E,paymentElementMethods:Ua,stripeInstance:Vr,paymentElementBaseOptions:Oi,futureUseSession:He,onTokenizedBody:on,onErrorChange:ze,onButtonClick:K,onDecline:m,runBeforeButtonClick:Tn,onLoadStateChange:Gs,isProcessing:bt,submitButtonColor:vo,submitButtonBorderRadius:lr,submitButtonStyle:L.submitButton,themeId:lt,onExpandApm:mt,expandedApmMethod:sr,buttonAppearance:{backgroundColor:L.cardButton?.backgroundColor,borderColor:L.cardInputBorder,textColor:L.cardButton?.color,borderRadius:Po}})]}),he&&(Nc||Lc||Uc)&&(0,u.jsx)(fi,{label:"or pay with card"}),he&&ul]})}var F=require("react/jsx-runtime"),Qo=44,ws="flopay_checkout_saved_payment_resume",ki=new Map,Si=new Map;function lc(e,t){t.settled&&t.consumers===0&&ki.get(e)===t&&ki.delete(e)}function ru(e,t,r){let n=Si.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};Si.set(e,s);let l=()=>{Si.get(e)===s&&Si.delete(e)};return a.then(l,l),a}function xa(e){return new Promise(t=>setTimeout(t,e))}function wi(e,t,r){let n=ni({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Oe.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Aa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ps(e,t,r,n,a,s){let l=wi(e,t,r);l.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Aa(l)}function cc(e,t,r,n){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:t,...n===void 0?{}:{attempt:n},statusClass:"2xx"})}function dc(e,t,r,n,a){let s=(0,Oe.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:a,statusClass:s.statusClass}),t instanceof Oe.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Oe.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):s.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...s,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function vs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,Oe.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var nu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function ou(e){return new co.FloPay(nu,{publishableKey:"provider_unavailable",...e})}async function Cs(e,t){let{publishableKey:r,paypalPublishableKey:n}=ns(e);return{...await os({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function ks(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function au(){if(!ks())return null;try{let e=window.sessionStorage.getItem(ws);return e?JSON.parse(e):null}catch{return null}}function uc(e){if(ks())try{window.sessionStorage.setItem(ws,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function bs(){if(ks())try{window.sessionStorage.removeItem(ws)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function iu(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],r=!1;for(let n of t)e.searchParams.has(n)&&(e.searchParams.delete(n),r=!0);r&&window.history.replaceState(window.history.state,"",e.toString())}function pc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Ss(e,t){return(0,Oe.resolveCheckoutLogLayout)(!!e,t)}function su(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function mc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function lu(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function Ri({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:l,loading:p,error:m,onComplete:h,onError:R,onInstrument:w,onDecline:I,onCancel:Y,onCountryChange:_,onZipChange:Z,showPayPal:A=!0,showStripe:y=!0,walletPresentation:P="auto",enabledPaymentMethods:me,showApplePay:S=!0,showGooglePay:xe=!0,debug:T=!1,layout:le,theme:ye,buttonsTheme:pe,buttonsStyles:Re,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B,showSecurityFooter:wt,onButtonClick:Ye,onBeforeButtonClick:Ne,enableAVS:ue,cardFieldOrder:ne,cardPreFormSlot:K,avsLayout:Le,submitLabel:nt,className:je,initialErrorMessage:X=null,initialPayPalOrderId:$,children:H,checkoutMode:V,confirmLabel:Ve,renderConfirmButton:De,onSessionCompleted:fe}){let D=(0,Oe.resolveBillingApiUrl)(n),ge=(0,v.useMemo)(()=>(0,Oe.resolveTheme)(ye),[ye]),pt=s??ge?.appearance,Ue=r?"embedded_checkout":"standard_checkout",ot=Ss(H,le),[Ae,Qe]=(0,v.useState)(null),[at,pr]=(0,v.useState)(null),Mt=(0,v.useRef)(null),vt=(0,v.useRef)(null),be=(0,v.useRef)(0),[M,gt]=(0,v.useState)(null),ct=(0,v.useRef)(null),[N,Fe]=(0,v.useState)(null),Lt=(0,v.useMemo)(()=>r?(0,yt.serializeCreateParams)(r):"",[r]),Se=r?`create:${Lt}`:`session:${e??""}`,It=mc(N),b=(0,v.useRef)(new Set),x=(0,v.useRef)(Se),Be=(0,v.useRef)(Se);wo(()=>{Be.current=Se,x.current!==Se&&(x.current=Se,b.current.clear())},[Se]);let Ee=(0,v.useCallback)(q=>{if(Be.current===Se){if(es.FLO_INSTRUMENT_ONCE_NAMES.has(q.name)){if(b.current.has(q.name))return;b.current.add(q.name)}(0,Ke.invokeMerchantCallback)(()=>w?.(q))}},[Se,w]),dt=Ho(Ee,Se),it=(0,v.useRef)(!1),We=(0,v.useCallback)(q=>{if(it.current)return;let j=q.gateway||!It?q:{...q,gateway:It};Ee(j)},[Ee,It]);(0,v.useEffect)(()=>{dt({class:"lifecycle",name:"checkout.mount"})},[dt]);let[He,Dt]=(0,v.useState)(e??""),c=e??He,U=r?"":c,[W,ce]=(0,v.useState)(!0),[E,z]=(0,v.useState)(null),[Ut,Fr]=(0,v.useState)(0),[tr,Wt]=(0,v.useState)("full"),[_t,$r]=(0,v.useState)(!1),[Nr,rr]=(0,v.useState)(X),[Qr,Tt]=(0,v.useState)(null),[Ln,Xt]=(0,v.useState)(null),[yn,Hr]=(0,v.useState)(!1),[Kr,Jt]=(0,v.useState)(void 0),[Pr,en]=(0,v.useState)(""),[et,kt]=(0,v.useState)(!1),[Br,$t]=(0,v.useState)(!1),[nr,vr]=(0,v.useState)(!1),Zt=(0,v.useRef)(null),Ht=(0,v.useRef)(0),Rr=(0,v.useRef)(void 0),[Xe,or]=(0,v.useState)("loading"),[Er,Jn]=(0,v.useState)(0),Ur=(0,v.useRef)(!1),zr=(0,v.useRef)(!1),Nn=(0,v.useRef)(!1),cn=(0,v.useRef)(null),ar=(0,v.useRef)(null),he=(0,v.useMemo)(()=>({checkoutMode:V??tr,layout:su(H,le)}),[V,H,tr,le]),Cr=(0,v.useRef)(h);Cr.current=h;let Gr=(0,v.useRef)(R);Gr.current=R;let oe=(0,v.useRef)(I);oe.current=I;let xt=(0,v.useCallback)(q=>ii(cn,async j=>{try{return await q(j)}catch(ie){throw j.aborted?Go(ie):ie}}),[]);(0,v.useEffect)(()=>()=>{cn.current?.abort(),cn.current=null},[]);let Q=(0,v.useCallback)((q,j)=>{Mt.current=q,pr(q),ct.current=j,gt(j)},[]),Kt=(0,v.useCallback)(()=>{let q=vt.current;q&&(vt.current=null,q.destroy())},[]);(0,v.useEffect)(()=>{wr(at)?.setCheckoutContext(he),M&&M!==at&&wr(M)?.setCheckoutContext(he)},[at,M,he]);let ir=(0,v.useRef)(fe);ir.current=fe;let Pe=(0,v.useCallback)(q=>{or(q),!(q!=="exhausted"||Nn.current)&&(Nn.current=!0,Gr.current?.(new Oe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Vt=(0,v.useCallback)(()=>{or("retrying"),Jn(q=>q+1)},[]);(0,v.useEffect)(()=>{or("loading"),Jn(0),Nn.current=!1},[c]),(0,v.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Oe.SDK_VERSION,checkout_type:Ue,checkout_layout:ot,billing_api_url:D})},[ot,Ue,D]);let ae=(0,v.useMemo)(()=>r?(0,yt.serializeCreateParams)(r,!0):"",[r]),Nt=(0,v.useMemo)(()=>Pr===ae?Kr:void 0,[Kr,Pr,ae]),br=(0,v.useMemo)(()=>r?Xi(r,Nt):void 0,[r,Nt]),qr=V??br?.checkoutMode??"full",Qt=(0,v.useMemo)(()=>br?{...br,checkoutMode:qr}:void 0,[br,qr]);(0,v.useEffect)(()=>{Jt(void 0),en(ae),Rr.current=void 0,Zt.current=null,vr(!1)},[ae]),(0,v.useEffect)(()=>{rr(X)},[X]);let Un=(0,v.useCallback)((q,j,ie)=>{(0,Ke.invokeMerchantCallback)(()=>{oe.current?.(Sr(q,j,ie))})},[]),Zn=(0,v.useCallback)(async(q,j)=>{rr(null),Xt(null),Hr(!1),Tt("processing");let ie=j?.sessionId??q.id,we=q.clientSecret||t,mt=mc(q),Gt=Mt.current??ct.current,Ie=wr(Gt),de=Gt?null:wi(D,a,he),ee={log:g=>{Ie?Ie.log(g):de?.log(g)},error:g=>{Ie?Ie.error(g):de?.error(g)},terminal:g=>{Ie?Ie.terminal(g):de?.terminal(g)},performance:g=>{Ie?Ie.performance(g):de?.performance(g)},now:()=>Ie?.now()??de?.now()??0,elapsed:g=>Ie?.elapsed(g)??Math.max(0,(de?.now()??g)-g)},ve=ee.now(),te=!!(j?.initialAutoProcessingError||j?.initialAutoProcessingPending),tt=!1,re,Je=()=>{tt||(tt=!0,te=!0,re=ee.now(),ee.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ze=!1,At=()=>{Ze||(Ze=!0,ee.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),ee.performance({stage:"processing",durationMs:ee.elapsed(ve),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),re!==void 0&&ee.performance({stage:"recovery",durationMs:ee.elapsed(re),durationMode:"machine",paymentMethodCategory:"saved"}))};ee.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),it.current=!0;try{ee.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{it.current=!1}dt({class:"lifecycle",name:"payment.processing.started",provider:mt}),te&&Je();let _r;try{let g=ql(j?.initialAutoProcessingError),f=j?.initialAutoProcessingError?.type==="3ds_required"&&!j.initialAutoProcessingError.threeDSecureToken&&j.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:j.initialAutoProcessingError.nextActionRedirectUrl}:null,O,Ce=_e=>(Je(),xt(L=>Yo(_e,{billingApiUrl:D,sessionId:ie,nonce:we,session:q,signal:L})));if(f)O=await Ce(f);else if(g)Je(),g.type==="paypal_redirect_required"&&ar.current?.publishableKey&&uc({sessionId:ie,publishableKey:ar.current.publishableKey,paypalPublishableKey:ar.current.paypalPublishableKey}),O=await xt(_e=>li(g,{flopay:Mt.current,paypalFlopay:ct.current,attempt3DS:j?.attempt3DS,billingApiUrl:D,sessionId:ie,session:q,telemetry:!1,signal:_e})),g.type==="paypal_redirect_required"&&bs();else if(j?.initialAutoProcessingPending){let _e=j.initialAutoProcessingPending,L=new co.PaymentAPI(D,{telemetry:!1}),Ct=await xt(bt=>L.waitForCheckoutSessionCompletion(_e.sessionId,{initialDelayMs:_e.retryAfterMs,nonce:we,statusUrl:_e.statusUrl,signal:bt})),yr=fo(Ct,q),Tr=Ct.autoProcessingError?.type==="3ds_required"&&Ct.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ct.autoProcessingError.nextActionRedirectUrl}:null;if(Tr)O=await Ce(Tr);else{if(!oo(yr))throw qo(yr);O=no(yr,ie)}}else{if(j?.initialAutoProcessingError)throw Kn(j.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.initialAutoProcessingError.checkoutMethod});if(j?.fromCreateSession)return j?.fallbackToFull&&(Wt("full"),pc("full")),!1;{let _e=await Xo({billingApiUrl:D,sessionId:ie,session:q,nonce:we,telemetry:!1});_e.type==="success"?O=_e.result:_e.type==="next_action_required"?O=await Ce(_e):(Je(),_e.type==="paypal_redirect_required"&&ar.current?.publishableKey&&uc({sessionId:ie,publishableKey:ar.current.publishableKey,paypalPublishableKey:ar.current.paypalPublishableKey}),O=await xt(L=>li(_e,{flopay:Mt.current,paypalFlopay:ct.current,attempt3DS:j?.attempt3DS,billingApiUrl:D,sessionId:ie,session:q,telemetry:!1,signal:L})),_e.type==="paypal_redirect_required"&&bs())}}ie&&(0,Bn.markSessionRecentlyCompleted)(ie),At(),te&&(ee.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),ee.terminal({outcome:O.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Hr(O.status==="authorized"),Tt("success"),await xa(600),_r=()=>Cr.current?.(O)}catch(g){let f=yo(ka(g),ie);if(f.code==="three_ds_aborted")return!1;let O=f.checkoutMethod??wa;rr(f.message),Xt(f.message),Hr(!1),j?.fallbackToFull&&(ee.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Wt("full"),pc("full")),At();let Ce=f.statusCode===void 0?void 0:(0,Oe.telemetryStatusClass)(f.statusCode,"unknown"),_e=Ce==="4xx"?{requestCategory:"process_payment",statusClass:Ce}:{},L=Ce===void 0||Ce==="4xx";if(L&&(f.telemetryOutcome==="payment_declined"||!!(f.declineCode||f.code?.toLowerCase().includes("declin"))))ee.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",..._e});else if(L&&(f.telemetryOutcome==="validation_rejected"||f.type==="validation_error"))ee.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",..._e});else{let Tr=(0,Oe.classifyTelemetryFailure)(g,te?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),bt=f.telemetryRequestCategory??"process_payment";it.current=!0;try{ee.error({...Tr,...f.telemetryFailureCategory?{failureCategory:f.telemetryFailureCategory}:{},stage:te?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:bt})}finally{it.current=!1}dt({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:bt,provider:mt})}return(0,Ke.invokeMerchantCallback)(()=>Gr.current?.(f)),Un(O,f,{code:f.code,declineCode:f.declineCode}),Tt("error"),await Promise.allSettled([xa(400),j?.ensureProvidersReady?j.ensureProvidersReady():Promise.resolve()]),te&&(ee.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{At(),de&&Aa(de),Tt(null),Xt(null)}return(0,Ke.invokeMerchantCallback)(_r),!0},[Un,dt,t,D,xt,a,he]);(0,v.useEffect)(()=>{if(typeof window>"u"||zr.current)return;let q=new URLSearchParams(window.location.search),j=q.get("payment_intent_client_secret");if(!j)return;let ie=au();ie&&(zr.current=!0,(async()=>{let we,mt=0;rr(null),Xt(null),Tt("processing"),$r(!0);try{if(q.get("redirect_status")==="failed")throw Object.assign(new Oe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Gt,paypalFlopay:Ie}=await os({publishableKey:ie.publishableKey,paypalPublishableKey:ie.paypalPublishableKey,billingApiUrl:D,locale:l,telemetry:a});we=wr(Ie??Gt),we?.setCheckoutContext(he),mt=we?.now()??0,we?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),we?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let de=(Ie??Gt)?.getRawProvider();if(!de)throw Object.assign(new Oe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:ee,error:ve}=await de.retrievePaymentIntent(j);if(ve)throw Object.assign(new Oe.FloPayError(ve.message??"Failed to retrieve PayPal payment status.","api_error",{code:ve.code}),{checkoutMethod:"paypal"});let te=El(ee?.status);if(!ee||te==="failed")throw Object.assign(new Oe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let tt=typeof ee.payment_method=="string"?ee.payment_method:ee.payment_method?.id,re=te;if(ie.sessionId){let At=(await new co.PaymentAPI(D,{telemetry:!1}).getUnifiedCheckoutSession(ie.sessionId)).data.session;if(At&&At.status!=="complete"){let _r=await Xo({billingApiUrl:D,sessionId:ie.sessionId,session:At,telemetry:!1,tokenizedData:{id:tt??ee.id,type:"card",threeDSecureActionResultTokenId:ee.id,isPaypal:!0}});if(_r.type!=="success")throw Object.assign(new Oe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});re=_r.result.status}}ie.sessionId&&(0,Bn.markSessionRecentlyCompleted)(ie.sessionId),we?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),we?.performance({stage:"redirect_resume",durationMs:we.elapsed(mt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),we?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Tt("success"),await xa(600),(0,Ke.invokeMerchantCallback)(()=>Cr.current?.({status:re,paymentIntentId:ee.id,paymentMethodId:tt,checkoutMethod:"paypal"}))}catch(Gt){let Ie=yo(ka(Gt),ie.sessionId),de=Ie.checkoutMethod??"paypal",ee=!!(Ie.declineCode||Ie.code?.toLowerCase().includes("declin"));if(we)we.performance({stage:"redirect_resume",durationMs:we.elapsed(mt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ee?we.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):we.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(ee){let ve=wi(D,a,he);ve.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Aa(ve)}else Ps(D,a,he,"REDIRECT_RESUME_FAILED","redirect_resume");rr(Ie.message),Xt(Ie.message),(0,Ke.invokeMerchantCallback)(()=>Gr.current?.(Ie)),Un(de,Ie,{code:Ie.code,declineCode:Ie.declineCode}),Tt("error"),await xa(400)}finally{bs(),iu(),Tt(null),Xt(null),$r(!1)}})())},[Un,l,D,a,he]);let zn=(0,v.useRef)(null),qn=(0,v.useMemo)(()=>Qt?(0,yt.serializeCreateParams)(Qt):"",[Qt]),Qn=(0,v.useRef)(Qt);Qn.current=Qt,(0,v.useEffect)(()=>{Dt(e??"")},[e]),(0,v.useEffect)(()=>{Ur.current=!1,rr(X),Xt(null),Hr(!1),Tt(null)},[qn,X,e]);async function po(q,j,ie){let we=wi(D,a,he),mt=new co.PaymentAPI(D,{telemetry:!1}),Gt=!1;try{let Ie=q.idempotencyKey===void 0?void 0:(0,Oe.resolveIdempotencyKey)(q.idempotencyKey),de=(0,yt.readCachedInlineSession)(j,ie),ee=(0,yt.readCachedInlineIdempotencyKey)(j,ie);de?.canonicalIdentity===ie&&ee&&ee.canonicalIdentity===void 0&&((0,yt.persistCachedInlineIdempotencyKey)(j,ie,ee.idempotencyKey),ee={...ee,canonicalIdentity:ie});let ve=Ie??(ee?.canonicalIdentity===ie?ee.idempotencyKey:void 0),te,tt=!1;we.log({name:de?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let re=de?.sid??null,Je=null,Ze,At,_r=!1;if(re)try{Je=await mt.getUnifiedCheckoutSession(re,de?.nonce),de&&de.canonicalIdentity===void 0&&((0,yt.legacyCachedSessionMatchesDraft)(Je.data.session,q)?((0,yt.persistCachedInlineSession)(j,ie,re,de.nonce??Je.data.session?.clientSecret),ee&&ee.canonicalIdentity===void 0&&((0,yt.persistCachedInlineIdempotencyKey)(j,ie,ee.idempotencyKey),ve??(ve=ee.idempotencyKey))):((0,yt.clearCachedInlineCheckout)(j,ie),ee=null,ve=Ie,re=null,Je=null));let f=Je?.data.session?.status,O=Je?.data.session,Ce=O?.clientSecret||de?.nonce;if(re&&O?.buyerIdentified===!1&&Ce&&(At=zo(mt,re,Ce,q.account)),re&&Je&&f==="complete"){if((0,Bn.wasSessionRecentlyCompleted)(re))return{sid:re,result:Je};(0,yt.clearCachedInlineCheckout)(j,ie),re=null,Je=null,tt=!0}}catch{we.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),de?.canonicalIdentity===void 0?((0,yt.clearCachedInlineCheckout)(j,ie),ve=Ie):(0,yt.clearCachedInlineSession)(j,ie),re=null}if(!re){!Ie&&(tt||!ve)&&(ve=(0,Oe.resolveIdempotencyKey)(),te=ve),ve&&(0,yt.persistCachedInlineIdempotencyKey)(j,ie,ve);let f=we.now(),O=0;we.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ce={...q,idempotencyKey:ve,avsCheck:!!ue,avsConfig:typeof ue=="object"?ue:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ss(H,le)};Object.defineProperty(Ce,co.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Ct=>{O=Math.max(O,Ct)}}});let _e=()=>{cc(we,"session_create",f,O)},L=Ct=>{dc(we,Ct,"session_create",f,O)&&dt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Oe.isDetachedSessionEligible)(Ce)){let Ct=await mt.createDetachedSession(Ce);Ct.claimed.catch(()=>{}),Je=Ct.shell,re=Ct.sessionId,At=Ct.claim;let yr=we.now();we.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Ze=Ct.claimed.then(Tr=>{let bt=Tr.data.session?.id??Ct.sessionId;return bt&&(0,yt.persistCachedInlineSession)(j,ie,bt,Tr.data.session?.clientSecret??Ct.nonce),cc(we,"session_claim",yr),_e(),Tr},Tr=>{throw(0,yt.clearCachedInlineSession)(j,ie),dc(we,Tr,"session_claim",yr,0)&&dt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Tr}).finally(()=>Aa(we)),Ze.catch(()=>{}),Gt=!0,we.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),we.performance({stage:"session_shell",durationMs:we.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:O,statusClass:"2xx",paymentMethodCategory:"card"})}else Je=await mt.createAndFetchSession(Ce),_e()}catch(Ct){throw L(Ct),Ct}re=Je.data.session?.id??re??"",re&&!Ze&&(0,yt.persistCachedInlineSession)(j,ie,re,Je.data.session?.clientSecret)}let g=Je?.data.session;return!At&&re&&g?.buyerIdentified===!1&&g.clientSecret&&(At=zo(mt,re,g.clientSecret,q.account)),{sid:re??"",result:Je,sdkGeneratedIdempotencyKey:te,...Ze?{claimed:Ze}:{},...At?{claim:At}:{},..._r?{claimRequiresIdentity:!0}:{}}}finally{Gt||Aa(we)}}let mo=(0,v.useRef)(po);wo(()=>{mo.current=po},[po]);let Dr=(0,v.useCallback)(async(q,j)=>{let ie=Qn.current;if(!ie)throw new Oe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let we=Xi(ie,q),mt=(0,yt.serializeCreateParams)(we),Gt=(0,yt.hashCreateParams)(we),Ie=ki.get(mt);if(!Ie){let ve={canonicalIdentity:mt,promise:mo.current(we,Gt,mt),consumers:0,settled:!1};Ie=ve,ki.set(mt,ve);let te=()=>{ve.settled=!0,lc(mt,ve)};ve.promise.then(te,te)}Ie.consumers+=1;let de=!1,ee=()=>{de||(de=!0,Ie.consumers-=1,lc(mt,Ie))};j?.(ee);try{let ve=await Ie.promise;zn.current=mt,q&&(en(ae),Jt(g=>Cl(g,q)));let{sid:te,result:tt,claimed:re,claim:Je,claimRequiresIdentity:Ze}=ve;if(Rr.current=Je,vr(Ze===!0),Qe(tt),tt.data.session&&Fe(tt.data.session),te&&Dt(te),re){Ht.current+=1;let g=Ht.current;Zt.current=re,$t(!0),re.then(f=>{Ht.current===g&&(Zt.current===re&&(Zt.current=null),Qe(f),f.data.session&&Fe(f.data.session),$t(!1),vr(!1))},f=>{Ht.current===g&&(Zt.current===re&&(Zt.current=null),$t(!1),vr(!1),z(f instanceof Oe.FloPayError?f:new Oe.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error")))})}else Ht.current+=1,Zt.current=null,$t(!1),vr(!1);let{flopay:At,paypalFlopay:_r}=await Cs(tt,{billingApiUrl:D,locale:l,telemetry:a}).catch(g=>{throw wl(g,te||tt.data.session?.id)});return Q(At,_r),ce(!1),ve}catch(ve){throw zn.current===mt&&(zn.current=null),ve}finally{j||ee()}},[ae,Q,l,D,a]),eo=(0,v.useRef)(Zn);eo.current=Zn;let fn=(0,v.useRef)(Dr);fn.current=Dr;let zt=(0,v.useCallback)(async q=>{if(!lu(q)||et)return{sessionId:He,session:N};kt(!0);try{let j=await Dr(q);return{sessionId:j.sid,session:j.result.data.session??null}}finally{kt(!1)}},[Dr,et,He,N]),tn=(0,v.useCallback)(async q=>{let j=Rr.current;if(!j)return;let ie=Ht.current,we=await j(q);Ht.current===ie&&(Qe(we),we.data.session&&Fe(we.data.session))},[]),rn=(0,v.useCallback)(async()=>{await Zt.current},[]),dn=(0,v.useCallback)(async()=>(await rn(),{proceed:!0}),[rn]);(0,v.useEffect)(()=>{let q=!1,j,ie=++be.current;Kt(),z(null),Fr(0);let we=()=>{q=!0,be.current===ie&&(be.current+=1,Kt())},mt=Qn.current;if(qn&&mt)return Wt(qr),ce(!1),zn.current===qn?we:(Fe(bl(mt,V)),(async()=>{let de=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ee=qr==="auto"&&!Ur.current&&!de;ee&&(rr(null),Xt(null),Tt("processing"));let ve=!1;try{let te=await fn.current(void 0,Ze=>{j=Ze});ve=!0;let tt=te.result.data.session??null;ar.current=ns(te.result);let re=vs(te.result),Je=(0,Bn.wasSessionRecentlyCompleted)(te.sid||tt?.id);if(!q&&ee&&tt&&!re&&!Je){Ur.current=!0,await ru(qn,te.sdkGeneratedIdempotencyKey,()=>eo.current(tt,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:te.result.autoProcessingError,initialAutoProcessingPending:te.result.autoProcessingPending,autoProcessingAttempted:te.result.autoProcessingAttempted,sessionId:te.sid||tt.id}));return}!q&&ee&&((re||Je)&&(Ur.current=!0),Tt(null),Xt(null))}catch(te){if(q)return;let tt=Xa(te);if(ee&&tt==="session_auto_completed"){Ur.current=!0,Tt("success"),await xa(600),q||((0,Ke.invokeMerchantCallback)(()=>{Cr.current?.({status:"succeeded"})}),Tt(null),Xt(null));return}if(ee&&(Tt(null),Xt(null)),!ve){let Je=kl(te),Ze=(0,Oe.toPublicCheckoutInitError)(te,Je?{stage:"provider_load",provider:"stripe",...Je}:{stage:"session_request"});(Je||!(te instanceof Oe.FloPayError))&&(0,Ke.invokeMerchantCallback)(()=>Gr.current?.(Ze)),z(Ze);return}let re=te instanceof Oe.FloPayError?te:new Oe.FloPayError(te instanceof Error?te.message:"Failed to create session","api_error");z(re)}finally{j?.(),j=void 0}})(),()=>{we(),j?.()});ce(!0);async function Gt(){let de=!1,ee=!1,ve=null;try{let te=new co.PaymentAPI(D,{telemetry:!1}),tt=await te.getUnifiedCheckoutSession(c,t);if(ee=!0,ve=tt,q)return;Qe(tt);let re=tt.data.session??null;if(Fe(re),!re)throw new Oe.FloPayError("No session data returned","api_error");let Je=re.checkoutMode;if(Je==="setup")throw new Oe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(re.status==="authorized"){ce(!1),(0,Ke.invokeMerchantCallback)(()=>{Cr.current?.(no(re,c)),ir.current?.(re.successUrl??"")});return}if(re.status==="complete"){ce(!1),(0,Ke.invokeMerchantCallback)(()=>{ir.current?.(re.successUrl??"")});return}if(re.status==="expired")throw Ya(re);de=!0;let Ze=V??Je??"full";Wt(Ze),Ht.current+=1;let At=re.clientSecret||t;Rr.current=re.buyerIdentified===!1&&At?zo(te,c,At,{...re.customer?.id?{userId:re.customer.id}:{}}):void 0,$t(!1),vr(!1);let _r=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),g=vs(tt);if(Ze==="auto"&&!Ur.current&&!_r&&!g){Ur.current=!0;let f=Ie(tt);try{if(await eo.current(re,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>f,sessionId:c||re.id}),q)return;await f,q||ce(!1);return}catch{if(q)return;await f,q||ce(!1);return}}await Ie(tt),q||ce(!1)}catch(te){if(q)return;let tt=vl(te,de);if(de&&dt({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),tt){let{errorCode:At,stage:_r,...g}=tt;Ps(D,a,he,At,_r,g)}if(tt?.stage==="provider_load"&&(V??ve?.data.session?.checkoutMode??"full")==="full"&&Pl(ve,A,y)){let At=ou({billingApiUrl:D,locale:l,telemetry:a});vt.current=At,Q(At,null),Fr(1),ce(!1);return}let re=tt?.stage==="provider_load",Je="session_request";re?Je="provider_load":ee&&(Je="post_session");let Ze=(0,Oe.toPublicCheckoutInitError)(te,{stage:Je,provider:"stripe",sessionId:c||void 0});(re||!(te instanceof Oe.FloPayError))&&(0,Ke.invokeMerchantCallback)(()=>Gr.current?.(Ze)),z(Ze),ce(!1)}}async function Ie(de){let{flopay:ee,paypalFlopay:ve,...te}=await Cs(de,{billingApiUrl:D,locale:l,telemetry:a});ar.current={publishableKey:te.publishableKey,paypalPublishableKey:te.paypalPublishableKey},Q(ee,ve),Fr(0)}return Gt(),we},[V,qn,qr,U,t,A,y]);let nn=(0,v.useCallback)(async()=>{if(!Ae||Ut!==1)return;let q=be.current;Fr(2);try{let{flopay:j,paypalFlopay:ie}=await Cs(Ae,{billingApiUrl:D,locale:l,telemetry:a});if(be.current!==q)return;Kt(),Q(j,ie),Fr(0)}catch(j){if(be.current!==q)return;let{errorCode:ie,stage:we,...mt}=Yi(j);Ps(D,a,he,ie,we,mt)}},[Kt,Q,l,Ut,D,a,he,Ae]),ut=!!(c&&(N?.clientSecret||t)),mr=_t||!ut,sr=(0,v.useCallback)(async()=>{if(!(_t||!ut||!N)){$r(!0),rr(null);try{await Zn(N,{attempt3DS:!0,fallbackToFull:!0,sessionId:c||N.id})}finally{$r(!1)}}},[c,_t,ut,Zn,N]),Yr=(0,Oe.resolveDirectPaypalConfig)(Ae?.data.paypal,$),ho=vs(Ae),to=(0,v.useMemo)(()=>{if(!(!Ae||!N||!Ae.data.stripe?.publishableKey))return{billingApiUrl:D}},[Ae,N,D]),In=!!(r&&!H&&le==="buttons"&&Ne&&qr==="full"),un=!!(c&&((0,Oe.isMountableVaultBlock)(N?.vault)||(0,xn.canRecoverHostedCardForm)(N))),Ir=(0,v.useMemo)(()=>({session:N,loading:W,error:E,checkoutMode:tr,inlineSessionDraft:Qt,applyInlineSessionPatch:In?zt:void 0,inlineSessionPatchProcessing:et,claimPending:Br,claimRequiresIdentity:nr,claimBuyerIdentity:tn,waitForDataAttachment:rn}),[N,W,E,tr,Qt,In,zt,et,Br,nr,tn,rn]),ro=!!r&&le==="buttons"&&!ho&&!un&&(!at||!to),jr=Qr?(0,F.jsx)(sn,{status:Qr,errorMessage:Ln,authorized:yn}):null;if(W&&!un){if(p)return(0,F.jsxs)(F.Fragment,{children:[p,jr]});if(le==="buttons"){let q=ge?.buttonsLayout?.cardButton?.borderRadius??ge?.appearance.variables?.borderRadius??8,j=ie=>(0,F.jsx)("div",{style:{height:ie,borderRadius:q,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[A&&j(Qo),y&&(S||xe)&&j(Qo),y&&j(Qo),(0,F.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),jr]})}return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,F.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,F.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),jr]})}return E?m?(0,F.jsx)(An.Provider,{value:Ir,children:m(E)}):(0,F.jsx)(An.Provider,{value:Ir,children:(0,F.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:E.message})}):ro?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Ir,children:(0,F.jsx)(du,{onButtonClick:Ye,showPayPal:A,showStripe:y,showApplePay:S,showGooglePay:xe,theme:ye,buttonsTheme:pe,buttonsStyles:Re,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B})}),jr]}):ho&&N&&Yr?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Ir,children:(0,F.jsxs)("div",{className:je,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Nr&&(0,F.jsx)(Ko,{icon:!1,children:Nr}),Xe==="retrying"&&(0,F.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Xe==="exhausted"&&(0,F.jsxs)("div",{role:"alert",children:[(0,F.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,F.jsx)("button",{type:"button",onClick:Vt,children:"Retry PayPal"})]}),Xe!=="exhausted"&&(0,F.jsx)("div",{"aria-hidden":Xe==="retrying"?!0:void 0,style:Xe==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,F.jsx)(Ll,{sessionId:c,nonce:N.clientSecret||void 0,billingApiUrl:D,email:N.customer?.email||Qt?.account?.email,billingName:[N.customer?.firstName,N.customer?.lastName].filter(Boolean).join(" ")||[Qt?.account?.firstName,Qt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:tn,clientId:Yr.clientId,environment:Yr.environment,currency:(N.currency??"usd").toUpperCase(),isSubscription:N.mode==="subscription",providerObjectType:Yr.providerObjectType,approvalPresentation:Yr.approvalPresentation,existingOrderId:Yr.existingOrderId,onComplete:h,onErrorChange:rr,onDecline:I,onCancel:Y,onButtonClick:Ye,runBeforeButtonClick:dn,onInitializationStateChange:Pe,allowAutomaticRetry:Er===0,session:N,telemetry:a,telemetryContext:he,onInstrument:We,debug:T},`${Se}:paypal-init-${Er}`)})]})}),jr]}):tr==="confirm"?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Ir,children:(0,F.jsx)(ba,{flopay:at,paypalFlopay:M,options:to??{billingApiUrl:D},onInstrument:We,children:(0,F.jsxs)("div",{className:je,children:[Nr&&(0,F.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Nr}),De?De({onConfirm:sr,isProcessing:mr}):(0,F.jsx)("button",{type:"button",onClick:sr,disabled:mr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:mr?"not-allowed":"pointer",opacity:mr?.6:1},children:_t?"Processing...":Ve??"Confirm Purchase"})]})},Se)}),jr]}):(!at||!to)&&!(un&&tr==="full")?(0,F.jsx)(F.Fragment,{children:jr}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Ir,children:(0,F.jsxs)(ba,{flopay:at,paypalFlopay:M,options:to??{billingApiUrl:D},onInstrument:We,children:[Ut===1&&(0,F.jsx)("button",{type:"button",onClick:nn,children:"Retry payment methods"}),H?(0,F.jsxs)(F.Fragment,{children:[Nr&&(0,F.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Nr}),(0,F.jsx)(cu,{sessionId:c,nonce:N?.clientSecret||void 0,billingApiUrl:D,session:N,submitLabel:nt,walletPresentation:P,children:H})]}):(0,F.jsx)(bi,{sessionId:c,nonce:N?.clientSecret||void 0,telemetry:a,email:N?.customer?.email||Qt?.account?.email,userId:N?.customer?.id||Qt?.account?.userId,firstName:N?.customer?.firstName||Qt?.account?.firstName,lastName:N?.customer?.lastName||Qt?.account?.lastName,totalAmount:N?Math.round((0,Oe.buildCheckoutDisplayData)(N).total*100):0,currency:N?.currency?.toLowerCase()??"usd",onComplete:h,onError:R,onDecline:I,onCancel:Y,error:Nr,onErrorChange:rr,showPayPal:A,showStripe:y,walletPresentation:P,enabledPaymentMethods:Ut?[]:me??Ae?.data.stripe?.enabledPaymentMethods??N?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ae?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:xe,layout:le,theme:ye,buttonsTheme:pe,buttonsStyles:Re,appearance:pt,cardButtonContent:lt,cardBackButtonContent:$e,cardTitleContent:B,onButtonClick:Ye,onBeforeButtonClick:Ne,onBuyerIdentityReady:tn,enableAVS:ue,...ne?{cardFieldOrder:ne}:{},...K?{cardPreFormSlot:K}:{},avsLayout:Le,country:N?.customer?.country,city:N?.customer?.city,state:N?.customer?.state,onCountryChange:_,onZipChange:Z,avsCheck:!!ue,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Ss(H,le),className:je,submitLabel:nt,directPaypal:Yr,isSubscription:N?.mode==="subscription",session:N,dataAttachmentPending:Br,dataAttachmentRequiresIdentity:nr,debug:T})]},Se)}),jr]})}function cu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,children:l}){return(0,F.jsx)(F.Fragment,{children:v.default.Children.map(l,p=>{if(!v.default.isValidElement(p))return p;let m=p.props,h={};return m.sessionId||(h.sessionId=e),!m.nonce&&t&&(h.nonce=t),m.billingApiUrl||(h.billingApiUrl=r),m.submitLabel===void 0&&a!==void 0&&(h.submitLabel=a),m.walletPresentation===void 0&&(h.walletPresentation=s),n?.customer&&(m.email||(h.email=n.customer.email),m.userId||(h.userId=n.customer.id),m.firstName||(h.firstName=n.customer.firstName),m.lastName||(h.lastName=n.customer.lastName)),Object.keys(h).length===0?p:v.default.cloneElement(p,h)})})}function du({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:s,buttonsTheme:l,buttonsStyles:p,cardButtonContent:m,cardBackButtonContent:h,cardTitleContent:R}){let[w,I]=(0,v.useState)(!1),Y=(0,v.useMemo)(()=>(0,Oe.resolveTheme)(s),[s]),_=(0,v.useMemo)(()=>{let P=Y?.buttonsLayout??(0,Oe.resolveButtonsLayoutTheme)(l);return p?{...P,...p,cardButton:{...P.cardButton,...p.cardButton},cardFormContainer:{...P.cardFormContainer,...p.cardFormContainer},backButton:{...P.backButton,...p.backButton},backButtonIcon:{...P.backButtonIcon,...p.backButtonIcon},submitButton:{...P.submitButton,...p.submitButton},title:{...P.title,...p.title}}:P},[Y,l,p]),Z=Y?.buttonsLayout?.cardButton?.borderRadius??Y?.appearance.variables?.borderRadius??8,A=P=>(0,F.jsx)("div",{style:{height:P,borderRadius:Z,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),y=m===void 0?{boxSizing:"border-box",height:Qo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(w){let P=_.cardInputBorder??"#e5e7eb",me=_.cardInputBackground??"white",S=Lo(h),xe=Lo(R);return(0,F.jsxs)("div",{style:{backgroundColor:_.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",..._.cardFormContainer},children:[(0,F.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,F.jsxs)("button",{type:"button",onClick:()=>I(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:S?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",..._.backButton},children:[(0,F.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",..._.backButtonIcon},children:(0,F.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,F.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,F.jsx)(Uo,{content:h})]}),xe?(0,F.jsx)("div",{style:{flex:1}}):(0,F.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,..._.title},children:(0,F.jsx)(ma,{content:R})})]}),(0,F.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsxs)("div",{style:{display:"flex"},children:[(0,F.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,F.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",..._.submitButton,opacity:.5}}),(0,F.jsx)("style",{children:`
41
41
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
42
42
  @keyframes flopay-interim-expand {
43
43
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
44
44
  40% { opacity: 1; }
45
45
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
46
46
  }
47
- `})]})}return(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&x(Jo),r&&(n||a)&&x(Jo),r&&(0,F.jsx)("button",{type:"button",onClick:()=>{e?.("card"),E(!0)},style:{width:"100%",...f,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:I.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...I.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,F.jsx)(Do,{content:m})}),(0,F.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var hn=require("react/jsx-runtime"),ru=44;function oc(e){return new Promise(t=>setTimeout(t,e))}function nu(e,t){return e instanceof Pn.FloPayError?e:new Pn.FloPayError(e instanceof Error?e.message:t,"api_error")}function ou(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function au(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function ac({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:i,products:l,items:p,subscriptions:m,account:h,successUrl:w,cancelUrl:S,couponCodes:E,tagsData:Y,utmMetadata:I,billingApiUrl:ee,locale:x,theme:f,appearance:P,buttonsTheme:pe,buttonsStyles:b,onSuccess:Ie,onError:_,onDecline:ie,children:me,disabled:ue=!1,type:xe="button",style:lt,...$e}){let B=(0,gt.useMemo)(()=>(0,Pn.resolveBillingApiUrl)(ee),[ee]),St=(0,gt.useMemo)(()=>au({createSession:r,clientId:i,products:l,items:p,subscriptions:m,account:h,successUrl:w,cancelUrl:S,couponCodes:E,tagsData:Y,utmMetadata:I}),[h,S,i,E,r,l,p,m,w,Y,I]),[Ge,De]=(0,gt.useState)(!1),[de,re]=(0,gt.useState)(null),[X,Oe]=(0,gt.useState)(null),[nt,ze]=(0,gt.useState)(!1),[te,J]=(0,gt.useState)(null),[H,j]=(0,gt.useState)(null),je=(0,gt.useRef)(!0),Te=(0,gt.useRef)(null),fe=(0,gt.useRef)(H),O=(0,gt.useRef)(Ie),Pe=(0,gt.useRef)(_),ut=(0,gt.useRef)(ie),Le=(0,gt.useCallback)(C=>ei(Te,async M=>{try{return await C(M)}catch(Fe){throw M.aborted?$o(Fe):Fe}}),[]);(0,gt.useEffect)(()=>{fe.current=H},[H]),(0,gt.useEffect)(()=>{O.current=Ie},[Ie]),(0,gt.useEffect)(()=>{Pe.current=_},[_]),(0,gt.useEffect)(()=>{ut.current=ie},[ie]),(0,gt.useEffect)(()=>(je.current=!0,()=>{je.current=!1,Te.current?.abort()}),[]),(0,gt.useEffect)(()=>{if(typeof window>"u")return;let C=M=>{M.key==="Escape"&&j(null)};return window.addEventListener("keydown",C),()=>{window.removeEventListener("keydown",C)}},[]);let ot=(0,gt.useCallback)((C,M=ba)=>{ut.current?.(wr(M,C,{code:C.code,declineCode:C.declineCode}))},[]),_e=(0,gt.useCallback)(async C=>{je.current&&(Oe(null),ze(C.result.status==="authorized"),re("success"),await oc(600),je.current&&(0,Ze.invokeMerchantCallback)(()=>O.current?.(C)))},[]),et=(0,gt.useCallback)(async(C,M)=>{je.current&&(Pe.current?.(C),M?.emitDecline&&ot(C,M.method),Oe(C.message),ze(!1),re("error"),await oc(400))},[ot]),at=(0,gt.useCallback)(async(C,M,Fe)=>{let Se=C.data.session??null;if(!Se)throw so(new Pn.FloPayError("No session data returned","api_error"),M);let ct=Se.clientSecret||t;if(Jn(Se)){await _e({result:Xn(Se,M),session:Se,sessionId:Se.id||M,autoCompleted:!1});return}if(Se.status==="expired")throw so($a(Se),Se.id||M);try{if(C.autoProcessingPending){let Ve=C.autoProcessingPending,He=new Ci.PaymentAPI(B),Bt=await Le(V=>He.waitForCheckoutSessionCompletion(Ve.sessionId,{initialDelayMs:Ve.retryAfterMs,nonce:ct,statusUrl:Ve.statusUrl,signal:V})),c=lo(Bt,Se),U=Bt.autoProcessingError?.type==="3ds_required"&&Bt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Bt.autoProcessingError.nextActionRedirectUrl}:null;if(U&&M&&ct){let V=await Le(se=>Ho(U,{billingApiUrl:B,sessionId:M,nonce:ct,session:Se,signal:se,telemetry:!0}));await _e({result:V,session:Se,sessionId:Se.id||M,autoCompleted:!1});return}if(Bt.autoProcessingError)throw qn(Bt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Bt.autoProcessingError.checkoutMethod});if(!Jn(c))throw No(c);await _e({result:Xn(c,M),session:c,sessionId:c.id||M,autoCompleted:!1});return}if(C.autoProcessingError){let Ve=C.autoProcessingError.nextActionRedirectUrl;if(C.autoProcessingError.type==="3ds_required"&&Ve&&M&&ct){let He=await Le(V=>Al({billingApiUrl:B,sessionId:M,nonce:ct,nextActionRedirectUrl:Ve,signal:V}));if(He.status==="declined")throw qn({type:He.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:He.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:C.autoProcessingError.checkoutMethod});let c=await new Ci.PaymentAPI(B).waitForCheckoutSessionCompletion(M,{initialDelayMs:0,nonce:ct}),U=lo(c,Se);if(!Jn(U))throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:C.autoProcessingError.checkoutMethod});await _e({result:Xn(U,M),session:U,sessionId:U.id||M,autoCompleted:!1});return}throw qn(C.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:C.autoProcessingError.checkoutMethod})}if(Fe?.fromCreateSession&&C.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let mt=await Ko({billingApiUrl:B,sessionId:M??Se.id,session:Se,nonce:ct});if(mt.type==="next_action_required"&&ct){let Ve=M??Se.id,He=await Le(Bt=>Ho(mt,{billingApiUrl:B,sessionId:Ve,nonce:ct,session:Se,signal:Bt,telemetry:!0}));await _e({result:He,session:Se,sessionId:Se.id||Ve,autoCompleted:!1});return}if(mt.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await _e({result:mt.result,session:Se,sessionId:Se.id||M,autoCompleted:!1})}catch(mt){let Ve=Se.id||M,He=so(Sa(mt),Ve);if(He.code==="three_ds_aborted")return;if(He.code==="checkout_processing_timeout"){if(!je.current)return;J(He.message),(0,Ze.invokeMerchantCallback)(()=>Pe.current?.(He));return}await et(He,{emitDecline:!0,method:He.checkoutMethod??ba}),ou(He,Ve)&&Ve&&je.current&&j({sessionId:Ve,errorMessage:He.message,nonce:ct||void 0,payPalOrderId:He.orderId})}},[t,B,Le,et,_e]),ar=(0,gt.useCallback)(async C=>{if($e.onClick?.(C),!(C.defaultPrevented||ue||Ge)){if(j(null),J(null),e&&St){let M=new Pn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await et(M),je.current&&(re(null),Oe(null));return}if(!e&&!St){let M=new Pn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await et(M),je.current&&(re(null),Oe(null));return}De(!0),Oe(null),ze(!1),re("processing");try{let M=new Ci.PaymentAPI(B);if(e){let Fe=await M.getUnifiedCheckoutSession(e,t);await at(Fe,e);return}try{let Fe=await M.createAndFetchSession({...St});await at(Fe,Fe.data.session?.id??null,{fromCreateSession:!0})}catch(Fe){if(Ha(Fe)==="session_auto_completed"){await _e({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Fe}}catch(M){await et(so(nu(M,"Automatic payment failed. Please try again."),e))}finally{je.current&&(re(null),Oe(null),De(!1))}}},[$e.onClick,St,ue,Ge,t,at,B,e,et,_e]),xt=(0,gt.useCallback)(C=>{let M=fe.current;j(null),O.current?.({result:C,session:null,sessionId:M?.sessionId??null,autoCompleted:!1})},[]),Ct=(0,gt.useCallback)(C=>{Pe.current?.(C)},[]),Ce=(0,gt.useCallback)(C=>{ut.current?.(C)},[]),T=(0,gt.useMemo)(()=>(0,Pn.resolveTheme)(f),[f]),ht=(0,gt.useMemo)(()=>{let C=T?.buttonsLayout??(0,Pn.resolveButtonsLayoutTheme)(pe);return b?{...C,...b,cardButton:{...C.cardButton,...b.cardButton}}:C},[T,pe,b]),pt=(0,gt.useMemo)(()=>{let C=T?.appearance;return P?C?{...C,...P,variables:{...C.variables,...P.variables}}:P:C},[P,T]),z=pt?.variables,Ae=z?.colorPrimary??"#4A49FF",Dt=z?.colorPrimaryHover??(0,ms.darkenHex)(Ae,.12),be=z?.borderRadius??"8px";return(0,hn.jsxs)(hn.Fragment,{children:[(0,hn.jsx)("button",{...$e,type:xe,onClick:ar,disabled:ue||Ge,"aria-busy":Ge,style:{width:"100%",...me===void 0?{boxSizing:"border-box",height:ru,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...ht.cardButton,...ps({themeBundle:T,resolvedPrimaryColor:Ae,resolvedBorderRadius:be,submitButtonStyle:ht.submitButton,explicitPrimaryColor:z?.colorPrimary}),fontSize:ht.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ue||Ge?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ue||Ge?.6:1,...lt},onMouseEnter:C=>{$e.onMouseEnter?.(C),!C.defaultPrevented&&!ue&&!Ge&&(T||z?.colorPrimary)&&(C.currentTarget.style.backgroundColor=Dt)},onMouseLeave:C=>{$e.onMouseLeave?.(C),!C.defaultPrevented&&(T||z?.colorPrimary)&&(C.currentTarget.style.backgroundColor=Ae)},onMouseDown:C=>{$e.onMouseDown?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(0.985)")},onMouseUp:C=>{$e.onMouseUp?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(1)")},children:(0,hn.jsx)(Do,{content:me})}),te&&(0,hn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:te}),de&&(0,hn.jsx)(Zr,{status:de,errorMessage:X,authorized:nt}),H&&(0,hn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:C=>{C.target===C.currentTarget&&j(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,hn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,hn.jsx)(vi,{sessionId:H.sessionId,nonce:H.nonce,checkoutMode:"full",billingApiUrl:B,locale:x,theme:f,...pt?{appearance:pt}:{},buttonsTheme:pe,buttonsStyles:b,initialErrorMessage:H.errorMessage,initialPayPalOrderId:H.payPalOrderId,cardTitleContent:null,onComplete:xt,onError:Ct,onDecline:Ce})})})]})}var Si=require("@flopay/js/card-setup"),Vr=require("@flopay/shared"),qt=require("react");var bs=require("@flopay/shared"),iu=require("@flopay/shared");function bi(e){let t=(0,bs.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Vn=require("react/jsx-runtime"),xa=class extends Vr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function no(e,t={}){let r=e instanceof Vr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new xa(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:a,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}function ic({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:i,appearance:l,buttonsStyles:p,loading:m=null,onReady:h,onComplete:w,onDecline:S,onCancel:E,onValidation:Y,onError:I}){let[ee,x]=(0,qt.useState)(null),[f,P]=(0,qt.useState)(null),[pe,b]=(0,qt.useState)(null),[Ie,_]=(0,qt.useState)(null),[ie,me]=(0,qt.useState)(null),ue=(0,qt.useRef)(!1),xe=(0,qt.useRef)(!1),{vaultTheme:lt,surface:$e,overlayTheme:B}=(0,qt.useMemo)(()=>bi({theme:a,appearance:l,buttonsStyles:p}),[a,l,p]),St=(0,qt.useMemo)(()=>(0,Ra.mergeCardSetupSurface)($e,i),[$e,i]),Ge=(0,qt.useRef)(h),De=(0,qt.useRef)(I),de=(0,qt.useRef)(w),re=(0,qt.useRef)(S),X=(0,qt.useRef)(E),Oe=(0,qt.useRef)(Y),nt=(0,qt.useRef)(!1),ze=(0,qt.useRef)(!1),te=(0,qt.useRef)(0);return Ge.current=h,De.current=I,de.current=w,re.current=S,X.current=E,Oe.current=Y,(0,qt.useEffect)(()=>{let J=te.current+1;return te.current=J,()=>{queueMicrotask(()=>{te.current===J&&(nt.current||ze.current||(ze.current=!0,(0,Ze.invokeMerchantCallback)(()=>{X.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,qt.useEffect)(()=>{let J=!0,H=(0,Vr.resolveBillingApiUrl)(r),j=new Si.PaymentAPI(H,{telemetry:n});return x(null),P(null),b(null),nt.current=!1,ze.current=!1,(async()=>{try{if(!e.trim())throw new Vr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Vr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let je=await j.getUnifiedCheckoutSession(e,t);if(!J)return;let Te=je.data.session;if(!Te||!(0,Vr.isCardSetupCheckoutSession)(Te))throw new Vr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let fe=Te.vault;(0,Vr.isMountableVaultBlock)(fe)||(fe=await j.getVaultCapture(e,t));let O=(0,Vr.resolveVaultMountOptions)(fe,{billingApiUrl:H,sessionId:e,nonce:t});if(!O)throw new Vr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!J)return;P(O),x(new Si.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(je){if(!J)return;let Te=no(je);nt.current=!0,b(Te),(0,Ze.invokeMerchantCallback)(()=>De.current?.(Te))}})(),()=>{J=!1,j.destroy()}},[r,t,e,n]),(0,qt.useEffect)(()=>{if(!ee)return;let J=!1;xe.current=!1,ue.current=!1;let H=ee.on("submitting",()=>{ue.current=!0,me(null),_("processing")}),j=ee.on("complete",fe=>{nt.current=!0,ue.current=!1,_("success"),(async()=>(await new Promise(O=>setTimeout(O,600)),!xe.current&&(xe.current=!0,(0,Ze.invokeMerchantCallback)(()=>{de.current?.({status:"succeeded",sessionId:e,...fe.paymentMethod?{paymentMethod:fe.paymentMethod}:{}})}),J||_(null))))()}),je=ee.on("decline",fe=>{nt.current=!0,ue.current=!1,me(fe.message??null),_("error"),(0,Ze.invokeMerchantCallback)(()=>{re.current?.({status:"declined",sessionId:e,...fe.declineReason?{reason:fe.declineReason}:{},...fe.message?{message:fe.message}:{}})}),(async()=>(await new Promise(O=>setTimeout(O,400)),J||_(null)))()}),Te=ee.on("challenge_dismissed",()=>{_(null)});return()=>{J=!0,H(),j(),je(),Te()}},[ee,e]),pe?(0,Vn.jsx)("div",{role:"alert",children:pe.message}):!ee||!f?.html?(0,Vn.jsx)(Vn.Fragment,{children:m}):(0,Vn.jsxs)(Vn.Fragment,{children:[Ie&&(0,Vn.jsx)(Zr,{status:Ie,errorMessage:ie,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...B?{theme:B}:{}}),(0,Vn.jsx)(co,{capture:ee,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:lt,containerStyle:St,onReady:()=>{(0,Ze.invokeMerchantCallback)(()=>Ge.current?.())},onValidation:J=>{(0,Ze.invokeMerchantCallback)(()=>Oe.current?.(J))},onError:J=>{if(!J)return;ue.current&&(ue.current=!1,me(J),_("error"),setTimeout(()=>_(null),400));let H=no(new Error(J),{code:"card_setup_widget_failed",retryable:!0});(0,Ze.invokeMerchantCallback)(()=>De.current?.(H))}})]})}var sc=require("@flopay/js/card-setup"),uo=require("@flopay/shared"),lc=require("@paypal/paypal-js"),wo=require("react");var dc=require("react/jsx-runtime");function cc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:i,telemetry:l,customer:{userId:p,email:m},onSubmitting:h,onConfirmed:w,onFailed:S,onAbandoned:E}){let Y=(0,wo.useRef)(null),I=(0,wo.useRef)({onSubmitting:h,onConfirmed:w,onFailed:S,onAbandoned:E});I.current={onSubmitting:h,onConfirmed:w,onFailed:S,onAbandoned:E};let[ee]=(0,wo.useState)(()=>(0,Un.detectPayPalEnvironment)().inAppBrowser);return(0,wo.useEffect)(()=>{let x=!0,f,P=new sc.PaymentAPI(i,{telemetry:l}),pe={userId:p,email:m};return(async()=>{try{let b=await(0,lc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Ie=Y.current;if(!x||!Ie)return;if(!b?.Buttons)throw new uo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let _=b.Buttons({createVaultSetupToken:async()=>{I.current.onSubmitting();let ie=await P.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(ie.provider!=="paypal"||ie.providerObjectType!=="setup_token")throw new uo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ie.providerObjectId},onApprove:async ie=>{let me=ie.vaultSetupToken;if(!me)throw new uo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let ue=await P.processPayment(pe.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:me,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:pe});if(!ue.ok)throw new uo.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:ue.status});x&&I.current.onConfirmed()},onCancel:()=>{x&&I.current.onAbandoned()},onError:ie=>{if(!x)return;let{popupBlocked:me}=(0,ve.classifyExternalMethodFailure)(ie,{inAppBrowser:ee,handoffObserved:!1});I.current.onFailed(me?new Error((0,ve.buildExternalMethodRecoveryMessage)("PayPal",!0,ee)):ie,{code:me?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>_.close(),await _.render(Ie)}catch(b){if(!x)return;I.current.onFailed(b,{code:"paypal_unavailable",retryable:!0})}})(),()=>{x=!1,f?.().catch(()=>{}),P.destroy()}},[i,e,r,m,t,ee,a,n,l,p]),(0,dc.jsx)("div",{ref:Y,"data-flopay-paypal-setup":""})}var pc=require("@flopay/js/card-setup"),po=require("@flopay/shared"),Wn=require("@stripe/react-stripe-js"),mc=require("@stripe/stripe-js"),Wr=require("react");var Or=require("react/jsx-runtime"),yc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Ss=new Map;function su(e){let t=Ss.get(e);if(t)return t;let r=(0,mc.loadStripe)(e).catch(n=>{throw Ss.delete(e),n});return Ss.set(e,r),r}function lu(e){return e?(0,po.toStripeAppearance)(e):void 0}function cu(e){return(0,ve.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function uc(e){return e==="paypal"?"PayPal":(0,po.getStripeMethodDisplayName)(e)}function du(){return typeof window>"u"?"":window.location.href}var uu={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function fc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:i,appearance:l}=e,[p]=(0,Wr.useState)(()=>su(t)),m=(0,Wr.useMemo)(()=>{let h=lu(l),w=(0,po.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:i},r,"setup");return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:yc[r]?.types??[r],...w?{setupFutureUsage:w}:{},...h?{appearance:h}:{}}},[l,n,a,i,r]);return(0,Or.jsx)(Wn.Elements,{stripe:p,options:m,children:(0,Or.jsx)(pu,{...e})})}function pu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,appearance:l,themeId:p,buttonsLayout:m,onSubmitting:h,onConfirmed:w,onDeclined:S,onFailed:E,onValidation:Y,onUnavailable:I}){let ee=(0,Wn.useStripe)(),x=(0,Wn.useElements)(),[f,P]=(0,Wr.useState)(!1),[pe,b]=(0,Wr.useState)("loading"),[Ie,_]=(0,Wr.useState)(!1),[ie,me]=(0,Wr.useState)(!1),ue=(0,Wr.useRef)(!1),[xe]=(0,Wr.useState)(()=>(0,Un.detectPayPalEnvironment)()),[lt,$e]=(0,Wr.useState)(!1),B=(0,Wr.useCallback)((X,Oe)=>{if((0,ve.classifyExternalMethodFailure)(X,{inAppBrowser:xe.inAppBrowser,handoffObserved:!1}).popupBlocked){$e(!0),E(new Error((0,ve.buildExternalMethodRecoveryMessage)(uc(e),!0,xe.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}E(Oe.message===void 0?X:new Error(Oe.message),{code:Oe.code,retryable:!0})},[xe.inAppBrowser,e,E]),St=(0,Wr.useCallback)(async X=>{let Oe=!1,nt=!1,ze=()=>{!X||Oe||nt||(nt=!0,X.paymentFailed({reason:"fail"}))};if(!ee||!x||ue.current){ze();return}ue.current=!0,P(!0);try{let te=await x.submit();if(te.error){ze(),Y(te.error.message??null);return}h();let J=await new pc.PaymentAPI(a,{telemetry:i}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(J.provider!=="stripe"||J.intentKind!=="setup")throw new po.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Oe=!0;let H=await ee.confirmSetup({elements:x,clientSecret:J.clientSecret,confirmParams:{return_url:du()},redirect:"if_required"});if(H.error){cu(H.error)?S({...H.error.decline_code||H.error.code?{reason:H.error.decline_code??H.error.code}:{},...H.error.message?{message:H.error.message}:{}}):B(H.error,{code:"payment_method_setup_provider_failed",message:H.error.message??"The payment method could not be saved."});return}w()}catch(te){ze(),B(te,{code:"payment_method_setup_failed"})}finally{ue.current=!1,P(!1)}},[a,t,x,e,n,w,S,h,Y,B,r,ee,i]),Ge=yc[e]?.wallet,De=Ge==="paypal"&&(0,zn.resolveStripePayPalPresentation)(xe,"auto",lt?"blocked":xe.popupCapability)==="redirect",de=l?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&Ge&&!De)return(0,Or.jsxs)(Or.Fragment,{children:[(0,Or.jsx)(Xo,{}),(0,Or.jsx)(ka,{state:pe,borderRadius:de,children:(0,Or.jsx)(Wn.ExpressCheckoutElement,{options:{...ii,paymentMethods:ai([e])},onReady:X=>{let Oe=wa(X,[Ge]);b(Oe),Oe==="unavailable"&&I()},onLoadError:()=>{b("load_error"),I()},onConfirm:X=>{St(X)}})})]});let re=uc(e);return(0,Or.jsxs)(Or.Fragment,{children:[Ie?(0,Or.jsx)(oi,{method:e,themeId:p,hasNextStep:!0,highlighted:ie,disabled:f,onClick:()=>me(X=>!X),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:de}):null,(0,Or.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ie,style:ie?{display:"flex",flexDirection:"column"}:uu,children:[(0,Or.jsx)(Wn.PaymentElement,{options:{layout:si},onReady:()=>_(!0),onLoadError:()=>I(),onChange:X=>{X.complete&&Y(null)}}),(0,Or.jsx)(li,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!ee||!x||f||!ie,onClick:()=>{St()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:m?.submitButton,children:f?"Saving\u2026":`Save ${re}`})]})]})}var Aa=require("@flopay/js/card-setup"),Cr=require("@flopay/shared"),Ke=Wi(require("react"),1);var Zo=require("@flopay/js/card-setup"),Er=require("@flopay/shared");var or=require("react/jsx-runtime"),mu=15,yu=2e3;function fu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function ws(e){return new Promise(t=>setTimeout(t,e))}async function gu(e,t,r){if(!t.trim())throw new Cr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Cr.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,Cr.isCardSetupCheckoutSession)(a))throw new Cr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let i=(0,Er.readSetupAdvertisement)(n);if(!(0,Er.advertisesAnyMethod)(i)){let{skippedForMissingCurrency:l}=i,p=l.length>0?`FloPay: this setup session advertises only Stripe methods (${l.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new Cr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:i}}async function hu(e,t,r,n,a){let i=t.vault??null;(0,Cr.isMountableVaultBlock)(i)||(i=await e.getVaultCapture(r,n));let l=(0,Cr.resolveVaultMountOptions)(i,{billingApiUrl:a,sessionId:r,nonce:n});if(!l)throw new Cr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return l}var wi=class extends Ke.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function gc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,theme:l="modern-light",containerStyle:p,appearance:m,buttonsStyles:h,loading:w=null,onReady:S,onComplete:E,onDecline:Y,onCancel:I,onValidation:ee,onError:x}){let[f]=(0,Ke.useState)(Zo.readSetupRedirectReturn),[P,pe]=(0,Ke.useState)(null),[b,Ie]=(0,Ke.useState)(!1),[_,ie]=(0,Ke.useState)(null),[me,ue]=(0,Ke.useState)(null),[xe,lt]=(0,Ke.useState)(null),[$e,B]=(0,Ke.useState)(null),[St,Ge]=(0,Ke.useState)(()=>new Set),De=(0,Ke.useRef)(St),de=(0,Ke.useRef)(null);de.current=P;let re=(0,Ke.useRef)(!1),X=(0,Ke.useRef)(!1),Oe=(0,Ke.useRef)(!1),nt=(0,Ke.useRef)(!1),ze=(0,Ke.useRef)(0),te=(0,Ke.useRef)(0),J=(0,Ke.useRef)(!1),{vaultTheme:H,surface:j,overlayTheme:je,appearance:Te,buttonsLayout:fe}=(0,Ke.useMemo)(()=>bi({theme:l,appearance:m,buttonsStyles:h}),[l,m,h]),O=(0,Ke.useMemo)(()=>(0,Ra.mergeCardSetupSurface)(j,p),[j,p]),Pe=(0,Ke.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,onReady:S,onComplete:E,onDecline:Y,onCancel:I,onValidation:ee,onError:x});Pe.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,onReady:S,onComplete:E,onDecline:Y,onCancel:I,onValidation:ee,onError:x},(0,Ke.useEffect)(()=>{J.current=!0;let c=ze.current+1;return ze.current=c,()=>{J.current=!1,te.current+=1,queueMicrotask(()=>{ze.current===c&&(Oe.current||nt.current||(nt.current=!0,(0,Ze.invokeMerchantCallback)(()=>{Pe.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let ut=(0,Ke.useCallback)((c,U)=>{Oe.current=!0,re.current=!1,B({status:"success",wording:c,message:null}),(async()=>(await ws(600),!X.current&&(X.current=!0,(0,Ze.invokeMerchantCallback)(()=>{Pe.current.onComplete?.({status:"succeeded",sessionId:Pe.current.sessionId,...U?{paymentMethod:U}:{}})}),J.current&&B(null))))()},[]),Le=(0,Ke.useCallback)((c,U)=>{Oe.current=!0,re.current=!1,B({status:"error",wording:c,message:U.message??null}),(0,Ze.invokeMerchantCallback)(()=>{Pe.current.onDecline?.({status:"declined",sessionId:Pe.current.sessionId,...U.reason?{reason:U.reason}:{},...U.message?{message:U.message}:{}})}),(async()=>(await ws(400),J.current&&B(null)))()},[]),ot=(0,Ke.useCallback)((c,U)=>{re.current?(re.current=!1,B({status:"error",wording:c,message:U.message}),setTimeout(()=>{J.current&&B(null)},400)):B(null),(0,Ze.invokeMerchantCallback)(()=>Pe.current.onError?.(U))},[]),_e=(0,Ke.useCallback)(async c=>{let U=te.current+1;te.current=U;let V=()=>!J.current||U!==te.current;re.current=!0,B({status:"processing",wording:"payment_method",message:null});let se=new Aa.PaymentAPI((0,Cr.resolveBillingApiUrl)(Pe.current.billingApiUrl),{telemetry:Pe.current.telemetry});try{for(let R=0;R<mu;R+=1){if((R>0||c.waitFirst)&&await ws(yu),V())return;let K=await se.getUnifiedCheckoutSession(Pe.current.sessionId,Pe.current.nonce);if(V())return;let Ut=K.data.session?.status;if(Ut==="complete"){Ie(!0),ut("payment_method");return}if(Ut==="expired")throw new Cr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Cr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(R){if(V())return;let K=R instanceof Cr.FloPayError&&R.code==="payment_method_setup_unverified";ot("payment_method",no(R,K?{retryable:!0}:{}))}finally{se.destroy()}},[ot,ut]);(0,Ke.useEffect)(()=>{let c=!0,U=(0,Cr.resolveBillingApiUrl)(a),V=new Aa.PaymentAPI(U,{telemetry:i});pe(null),Ie(!1),ie(null),ue(null),lt(null);let se=new Set;return De.current=se,Ge(se),Oe.current=!1,nt.current=!1,X.current=!1,(async()=>{try{let{session:R,advertisement:K}=await gu(V,r,n);if(!c)return;let Ut={advertisement:K,customer:fu(R),...R.futureUse?{futureUse:R.futureUse}:{},...R.futureUseUnsupported?{futureUseUnsupported:R.futureUseUnsupported}:{}};if(f){if((0,Zo.clearSetupRedirectParams)(),R.status==="complete"){Ie(!0),pe(Ut),ut("payment_method");return}f.failed?Le("payment_method",{reason:"redirect_failed"}):_e({waitFirst:!0})}let xr=K.card?await hu(V,R,r,n,U):null;if(!c)return;pe(Ut),xr&&(ue(xr),ie(new Aa.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:i})))}catch(R){if(!c)return;let K=no(R);Oe.current=!0,lt(K),(0,Ze.invokeMerchantCallback)(()=>Pe.current.onError?.(K))}})(),()=>{c=!1,V.destroy()}},[a,n,f,Le,ut,r,i,_e]),(0,Ke.useEffect)(()=>{if(!_)return;re.current=!1;let c=_.on("submitting",()=>{re.current=!0,B({status:"processing",wording:"card",message:null})}),U=_.on("complete",R=>{ut("card",R.paymentMethod)}),V=_.on("decline",R=>{Le("card",{...R.declineReason?{reason:R.declineReason}:{},...R.message?{message:R.message}:{}})}),se=_.on("challenge_dismissed",()=>{B(null)});return()=>{c(),U(),V(),se()}},[_,Le,ut]);let et=(0,Ke.useCallback)((c,U,V)=>{if(V.retryable){ot("payment_method",no(U,V));return}if(De.current.has(c))return;let se=new Set(De.current);se.add(c),De.current=se,Ge(se);let R=de.current?.advertisement,K=R?(0,Er.advertisedMethodKeys)(R).some(Ut=>!se.has(Ut)):!1;ot("payment_method",no(U,{code:V.code,retryable:K}))},[ot]),at=(0,Ke.useMemo)(()=>({onSubmitting:()=>{re.current=!0,B({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{_e({waitFirst:!1})},onDeclined:c=>Le("payment_method",c),onValidation:c=>{(0,Ze.invokeMerchantCallback)(()=>Pe.current.onValidation?.(c))},onAbandoned:()=>{re.current=!1,B(null)}}),[Le,_e]),ar=(0,Ke.useRef)(et);ar.current=et;let xt=(0,Ke.useRef)(new Map),Ct=c=>{let U=xt.current.get(c);if(U)return U;let V=(se,R)=>ar.current(c,se,R);return xt.current.set(c,V),V},Ce=(0,Ke.useCallback)(c=>{if(De.current.has(c))return;let U=new Set(De.current);U.add(c),De.current=U,Ge(U);let V=de.current?.advertisement;V&&(0,Er.advertisedMethodKeys)(V).some(R=>!U.has(R))||ot("payment_method",no(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ot]),T=(0,Ke.useRef)(Ce);T.current=Ce;let ht=(0,Ke.useRef)(new Map),pt=c=>{let U=ht.current.get(c);if(U)return U;let V=()=>T.current(c);return ht.current.set(c,V),V},z=$e?(0,or.jsx)(Zr,{status:$e.status,errorMessage:$e.message,...(0,Er.setupOverlayLabels)($e.wording),successNote:null,...je?{theme:je}:{}}):null;if(xe)return(0,or.jsx)("div",{role:"alert",children:xe.message});if(!P||b)return(0,or.jsxs)(or.Fragment,{children:[z,P?null:w]});let{advertisement:Ae,customer:Dt,futureUse:be,futureUseUnsupported:_t}=P,C=(0,Cr.resolveBillingApiUrl)(a),M=i===void 0?{}:{telemetry:i},Fe=Ae.stripe.filter(({method:c})=>!St.has(c)),Se=St.has("paypal")?null:Ae.paypal,ct=!!(Ae.card&&_&&me?.html),mt=({method:c,publishableKey:U,currency:V})=>(0,or.jsx)("div",{"data-flopay-payment-method":c,style:{display:"contents"},children:(0,or.jsx)(wi,{onFailed:Ct(c),children:(0,or.jsx)(Ke.Suspense,{fallback:null,children:(0,or.jsx)(e,{method:c,category:(0,Er.stripeMethodCategory)(c),publishableKey:U,currency:V,...be?{futureUse:be}:{},..._t?{futureUseUnsupported:_t}:{},sessionId:r,nonce:n,billingApiUrl:C,...M,...Te?{appearance:Te}:{},...fe?{buttonsLayout:fe}:{},...typeof l=="string"?{themeId:l}:{},...at,onFailed:Ct(c),onUnavailable:pt(c)})})})},c),Ve=Fe.filter(({method:c})=>(0,Er.stripeMethodCategory)(c)==="wallet"),He=Fe.filter(({method:c})=>(0,Er.stripeMethodCategory)(c)!=="wallet"),Bt=Fe.length>0||Se!==null;return(0,or.jsxs)(or.Fragment,{children:[z,Bt?(0,or.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ve.map(mt),Se?(0,or.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,or.jsx)(wi,{onFailed:Ct("paypal"),children:(0,or.jsx)(Ke.Suspense,{fallback:null,children:(0,or.jsx)(t,{clientId:Se.clientId,...Se.environment?{environment:Se.environment}:{},...Ae.currency?{currency:Ae.currency}:{},sessionId:r,nonce:n,billingApiUrl:C,customer:Dt,...M,...at,onFailed:Ct("paypal"),onUnavailable:pt("paypal")})})})}):null,He.map(mt)]}):null,ct&&Bt?(0,or.jsx)(ci,{label:"or add a card"}):null,ct&&_&&me?.html?(0,or.jsx)("div",{"data-flopay-payment-method":"card",children:(0,or.jsx)(co,{capture:_,html:me.html,messageToken:me.messageToken,expectedOrigin:me.expectedOrigin,verificationRequired:me.verificationRequired,theme:H,containerStyle:O,onReady:()=>{(0,Ze.invokeMerchantCallback)(()=>Pe.current.onReady?.())},onValidation:c=>{(0,Ze.invokeMerchantCallback)(()=>Pe.current.onValidation?.(c))},onError:c=>{c&&ot("card",no(new Error(c),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Pc=require("react/jsx-runtime"),Pu={StripeSetupMethod:fc,PayPalSetupMethod:cc};function hc(e){return(0,Pc.jsx)(gc,{...e,branches:Pu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&A(Qo),r&&(n||a)&&A(Qo),r&&(0,F.jsx)("button",{type:"button",onClick:()=>{e?.("card"),I(!0)},style:{width:"100%",...y,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:_.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,..._.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,F.jsx)(No,{content:m})}),(0,F.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var wn=require("react/jsx-runtime"),uu=44;function yc(e){return new Promise(t=>setTimeout(t,e))}function pu(e,t){return e instanceof kn.FloPayError?e:new kn.FloPayError(e instanceof Error?e.message:t,"api_error")}function mu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function yu(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function fc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:s,products:l,items:p,subscriptions:m,account:h,successUrl:R,cancelUrl:w,couponCodes:I,tagsData:Y,utmMetadata:_,billingApiUrl:Z,locale:A,theme:y,appearance:P,buttonsTheme:me,buttonsStyles:S,onSuccess:xe,onError:T,onDecline:le,children:ye,disabled:pe=!1,type:Re="button",style:lt,...$e}){let B=(0,ft.useMemo)(()=>(0,kn.resolveBillingApiUrl)(Z),[Z]),wt=(0,ft.useMemo)(()=>yu({createSession:r,clientId:s,products:l,items:p,subscriptions:m,account:h,successUrl:R,cancelUrl:w,couponCodes:I,tagsData:Y,utmMetadata:_}),[h,w,s,I,r,l,p,m,R,Y,_]),[Ye,Ne]=(0,ft.useState)(!1),[ue,ne]=(0,ft.useState)(null),[K,Le]=(0,ft.useState)(null),[nt,je]=(0,ft.useState)(!1),[X,$]=(0,ft.useState)(null),[H,V]=(0,ft.useState)(null),Ve=(0,ft.useRef)(!0),De=(0,ft.useRef)(null),fe=(0,ft.useRef)(H),D=(0,ft.useRef)(xe),ge=(0,ft.useRef)(T),pt=(0,ft.useRef)(le),Ue=(0,ft.useCallback)(b=>ii(De,async x=>{try{return await b(x)}catch(Be){throw x.aborted?Go(Be):Be}}),[]);(0,ft.useEffect)(()=>{fe.current=H},[H]),(0,ft.useEffect)(()=>{D.current=xe},[xe]),(0,ft.useEffect)(()=>{ge.current=T},[T]),(0,ft.useEffect)(()=>{pt.current=le},[le]),(0,ft.useEffect)(()=>(Ve.current=!0,()=>{Ve.current=!1,De.current?.abort()}),[]),(0,ft.useEffect)(()=>{if(typeof window>"u")return;let b=x=>{x.key==="Escape"&&V(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let ot=(0,ft.useCallback)((b,x=wa)=>{pt.current?.(Sr(x,b,{code:b.code,declineCode:b.declineCode}))},[]),Ae=(0,ft.useCallback)(async b=>{Ve.current&&(Le(null),je(b.result.status==="authorized"),ne("success"),await yc(600),Ve.current&&(0,Ke.invokeMerchantCallback)(()=>D.current?.(b)))},[]),Qe=(0,ft.useCallback)(async(b,x)=>{Ve.current&&(ge.current?.(b),x?.emitDecline&&ot(b,x.method),Le(b.message),je(!1),ne("error"),await yc(400))},[ot]),at=(0,ft.useCallback)(async(b,x,Be)=>{let Ee=b.data.session??null;if(!Ee)throw yo(new kn.FloPayError("No session data returned","api_error"),x);let dt=Ee.clientSecret||t;if(oo(Ee)){await Ae({result:no(Ee,x),session:Ee,sessionId:Ee.id||x,autoCompleted:!1});return}if(Ee.status==="expired")throw yo(Ya(Ee),Ee.id||x);try{if(b.autoProcessingPending){let We=b.autoProcessingPending,He=new Ei.PaymentAPI(B),Dt=await Ue(W=>He.waitForCheckoutSessionCompletion(We.sessionId,{initialDelayMs:We.retryAfterMs,nonce:dt,statusUrl:We.statusUrl,signal:W})),c=fo(Dt,Ee),U=Dt.autoProcessingError?.type==="3ds_required"&&Dt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Dt.autoProcessingError.nextActionRedirectUrl}:null;if(U&&x&&dt){let W=await Ue(ce=>Yo(U,{billingApiUrl:B,sessionId:x,nonce:dt,session:Ee,signal:ce,telemetry:!0}));await Ae({result:W,session:Ee,sessionId:Ee.id||x,autoCompleted:!1});return}if(Dt.autoProcessingError)throw Kn(Dt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Dt.autoProcessingError.checkoutMethod});if(!oo(c))throw qo(c);await Ae({result:no(c,x),session:c,sessionId:c.id||x,autoCompleted:!1});return}if(b.autoProcessingError){let We=b.autoProcessingError.nextActionRedirectUrl;if(b.autoProcessingError.type==="3ds_required"&&We&&x&&dt){let He=await Ue(W=>jl({billingApiUrl:B,sessionId:x,nonce:dt,nextActionRedirectUrl:We,signal:W}));if(He.status==="declined")throw Kn({type:He.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:He.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let c=await new Ei.PaymentAPI(B).waitForCheckoutSessionCompletion(x,{initialDelayMs:0,nonce:dt}),U=fo(c,Ee);if(!oo(U))throw Kn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await Ae({result:no(U,x),session:U,sessionId:U.id||x,autoCompleted:!1});return}throw Kn(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(Be?.fromCreateSession&&b.autoProcessingAttempted===!0)throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let it=await Xo({billingApiUrl:B,sessionId:x??Ee.id,session:Ee,nonce:dt});if(it.type==="next_action_required"&&dt){let We=x??Ee.id,He=await Ue(Dt=>Yo(it,{billingApiUrl:B,sessionId:We,nonce:dt,session:Ee,signal:Dt,telemetry:!0}));await Ae({result:He,session:Ee,sessionId:Ee.id||We,autoCompleted:!1});return}if(it.type!=="success")throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ae({result:it.result,session:Ee,sessionId:Ee.id||x,autoCompleted:!1})}catch(it){let We=Ee.id||x,He=yo(ka(it),We);if(He.code==="three_ds_aborted")return;if(He.code==="checkout_processing_timeout"){if(!Ve.current)return;$(He.message),(0,Ke.invokeMerchantCallback)(()=>ge.current?.(He));return}await Qe(He,{emitDecline:!0,method:He.checkoutMethod??wa}),mu(He,We)&&We&&Ve.current&&V({sessionId:We,errorMessage:He.message,nonce:dt||void 0,payPalOrderId:He.orderId})}},[t,B,Ue,Qe,Ae]),pr=(0,ft.useCallback)(async b=>{if($e.onClick?.(b),!(b.defaultPrevented||pe||Ye)){if(V(null),$(null),e&&wt){let x=new kn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Qe(x),Ve.current&&(ne(null),Le(null));return}if(!e&&!wt){let x=new kn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Qe(x),Ve.current&&(ne(null),Le(null));return}Ne(!0),Le(null),je(!1),ne("processing");try{let x=new Ei.PaymentAPI(B);if(e){let Be=await x.getUnifiedCheckoutSession(e,t);await at(Be,e);return}try{let Be=await x.createAndFetchSession({...wt});await at(Be,Be.data.session?.id??null,{fromCreateSession:!0})}catch(Be){if(Xa(Be)==="session_auto_completed"){await Ae({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Be}}catch(x){await Qe(yo(pu(x,"Automatic payment failed. Please try again."),e))}finally{Ve.current&&(ne(null),Le(null),Ne(!1))}}},[$e.onClick,wt,pe,Ye,t,at,B,e,Qe,Ae]),Mt=(0,ft.useCallback)(b=>{let x=fe.current;V(null),D.current?.({result:b,session:null,sessionId:x?.sessionId??null,autoCompleted:!1})},[]),vt=(0,ft.useCallback)(b=>{ge.current?.(b)},[]),be=(0,ft.useCallback)(b=>{pt.current?.(b)},[]),M=(0,ft.useMemo)(()=>(0,kn.resolveTheme)(y),[y]),gt=(0,ft.useMemo)(()=>{let b=M?.buttonsLayout??(0,kn.resolveButtonsLayoutTheme)(me);return S?{...b,...S,cardButton:{...b.cardButton,...S.cardButton}}:b},[M,me,S]),ct=(0,ft.useMemo)(()=>{let b=M?.appearance;return P?b?{...b,...P,variables:{...b.variables,...P.variables}}:P:b},[P,M]),N=ct?.variables,Fe=N?.colorPrimary??"#4A49FF",Lt=N?.colorPrimaryHover??(0,hs.darkenHex)(Fe,.12),Se=N?.borderRadius??"8px";return(0,wn.jsxs)(wn.Fragment,{children:[(0,wn.jsx)("button",{...$e,type:Re,onClick:pr,disabled:pe||Ye,"aria-busy":Ye,style:{width:"100%",...ye===void 0?{boxSizing:"border-box",height:uu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...gt.cardButton,...gs({themeBundle:M,resolvedPrimaryColor:Fe,resolvedBorderRadius:Se,submitButtonStyle:gt.submitButton,explicitPrimaryColor:N?.colorPrimary}),fontSize:gt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:pe||Ye?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:pe||Ye?.6:1,...lt},onMouseEnter:b=>{$e.onMouseEnter?.(b),!b.defaultPrevented&&!pe&&!Ye&&(M||N?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Lt)},onMouseLeave:b=>{$e.onMouseLeave?.(b),!b.defaultPrevented&&(M||N?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Fe)},onMouseDown:b=>{$e.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{$e.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:(0,wn.jsx)(No,{content:ye})}),X&&(0,wn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:X}),ue&&(0,wn.jsx)(sn,{status:ue,errorMessage:K,authorized:nt}),H&&(0,wn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:b=>{b.target===b.currentTarget&&V(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,wn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,wn.jsx)(Ri,{sessionId:H.sessionId,nonce:H.nonce,checkoutMode:"full",billingApiUrl:B,locale:A,theme:y,...ct?{appearance:ct}:{},buttonsTheme:me,buttonsStyles:S,initialErrorMessage:H.errorMessage,initialPayPalOrderId:H.payPalOrderId,cardTitleContent:null,onComplete:Mt,onError:vt,onDecline:be})})})]})}var _i=require("@flopay/js/card-setup"),Jr=require("@flopay/shared"),jt=require("react");var Rs=require("@flopay/shared"),fu=require("@flopay/shared");function Ii(e){let t=(0,Rs.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Yn=require("react/jsx-runtime"),Fa=class extends Jr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function uo(e,t={}){let r=e instanceof Jr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new Fa(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:a,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}function gc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:l,buttonsStyles:p,loading:m=null,onReady:h,onComplete:R,onDecline:w,onCancel:I,onValidation:Y,onError:_}){let[Z,A]=(0,jt.useState)(null),[y,P]=(0,jt.useState)(null),[me,S]=(0,jt.useState)(null),[xe,T]=(0,jt.useState)(null),[le,ye]=(0,jt.useState)(null),pe=(0,jt.useRef)(!1),Re=(0,jt.useRef)(!1),{vaultTheme:lt,surface:$e,overlayTheme:B}=(0,jt.useMemo)(()=>Ii({theme:a,appearance:l,buttonsStyles:p}),[a,l,p]),wt=(0,jt.useMemo)(()=>(0,Ia.mergeCardSetupSurface)($e,s),[$e,s]),Ye=(0,jt.useRef)(h),Ne=(0,jt.useRef)(_),ue=(0,jt.useRef)(R),ne=(0,jt.useRef)(w),K=(0,jt.useRef)(I),Le=(0,jt.useRef)(Y),nt=(0,jt.useRef)(!1),je=(0,jt.useRef)(!1),X=(0,jt.useRef)(0);return Ye.current=h,Ne.current=_,ue.current=R,ne.current=w,K.current=I,Le.current=Y,(0,jt.useEffect)(()=>{let $=X.current+1;return X.current=$,()=>{queueMicrotask(()=>{X.current===$&&(nt.current||je.current||(je.current=!0,(0,Ke.invokeMerchantCallback)(()=>{K.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,jt.useEffect)(()=>{let $=!0,H=(0,Jr.resolveBillingApiUrl)(r),V=new _i.PaymentAPI(H,{telemetry:n});return A(null),P(null),S(null),nt.current=!1,je.current=!1,(async()=>{try{if(!e.trim())throw new Jr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Jr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Ve=await V.getUnifiedCheckoutSession(e,t);if(!$)return;let De=Ve.data.session;if(!De||!(0,Jr.isCardSetupCheckoutSession)(De))throw new Jr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let fe=De.vault;(0,Jr.isMountableVaultBlock)(fe)||(fe=await V.getVaultCapture(e,t));let D=(0,Jr.resolveVaultMountOptions)(fe,{billingApiUrl:H,sessionId:e,nonce:t});if(!D)throw new Jr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!$)return;P(D),A(new _i.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(Ve){if(!$)return;let De=uo(Ve);nt.current=!0,S(De),(0,Ke.invokeMerchantCallback)(()=>Ne.current?.(De))}})(),()=>{$=!1,V.destroy()}},[r,t,e,n]),(0,jt.useEffect)(()=>{if(!Z)return;let $=!1;Re.current=!1,pe.current=!1;let H=Z.on("submitting",()=>{pe.current=!0,ye(null),T("processing")}),V=Z.on("complete",fe=>{nt.current=!0,pe.current=!1,T("success"),(async()=>(await new Promise(D=>setTimeout(D,600)),!Re.current&&(Re.current=!0,(0,Ke.invokeMerchantCallback)(()=>{ue.current?.({status:"succeeded",sessionId:e,...fe.paymentMethod?{paymentMethod:fe.paymentMethod}:{}})}),$||T(null))))()}),Ve=Z.on("decline",fe=>{nt.current=!0,pe.current=!1,ye(fe.message??null),T("error"),(0,Ke.invokeMerchantCallback)(()=>{ne.current?.({status:"declined",sessionId:e,...fe.declineReason?{reason:fe.declineReason}:{},...fe.message?{message:fe.message}:{}})}),(async()=>(await new Promise(D=>setTimeout(D,400)),$||T(null)))()}),De=Z.on("challenge_dismissed",()=>{T(null)});return()=>{$=!0,H(),V(),Ve(),De()}},[Z,e]),me?(0,Yn.jsx)("div",{role:"alert",children:me.message}):!Z||!y?.html?(0,Yn.jsx)(Yn.Fragment,{children:m}):(0,Yn.jsxs)(Yn.Fragment,{children:[xe&&(0,Yn.jsx)(sn,{status:xe,errorMessage:le,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...B?{theme:B}:{}}),(0,Yn.jsx)(go,{capture:Z,html:y.html,messageToken:y.messageToken,expectedOrigin:y.expectedOrigin,verificationRequired:y.verificationRequired,theme:lt,containerStyle:wt,onReady:()=>{(0,Ke.invokeMerchantCallback)(()=>Ye.current?.())},onValidation:$=>{(0,Ke.invokeMerchantCallback)(()=>Le.current?.($))},onError:$=>{if(!$)return;pe.current&&(pe.current=!1,ye($),T("error"),setTimeout(()=>T(null),400));let H=uo(new Error($),{code:"card_setup_widget_failed",retryable:!0});(0,Ke.invokeMerchantCallback)(()=>Ne.current?.(H))}})]})}var hc=require("@flopay/js/card-setup"),Rn=require("@flopay/shared"),Pc=require("@paypal/paypal-js"),Io=require("react");var Cc=require("react/jsx-runtime");function vc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:l,customer:{userId:p,email:m},onSubmitting:h,onConfirmed:R,onFailed:w,onAbandoned:I}){let Y=(0,Io.useRef)(null),_=(0,Io.useRef)({onSubmitting:h,onConfirmed:R,onFailed:w,onAbandoned:I});_.current={onSubmitting:h,onConfirmed:R,onFailed:w,onAbandoned:I};let[Z]=(0,Io.useState)(()=>(0,$n.detectPayPalEnvironment)().inAppBrowser);return(0,Io.useEffect)(()=>{let A=!0,y,P=new hc.PaymentAPI(s,{telemetry:l}),me={userId:p,email:m};return(async()=>{try{let S=await(0,Pc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),xe=Y.current;if(!A||!xe)return;if(!S?.Buttons)throw new Rn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let T=S.Buttons({createVaultSetupToken:async()=>{_.current.onSubmitting();let le=await P.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Rn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,Rn.isSettledSessionIntent)(le))throw(0,Rn.settledSessionIntentError)(n);if(le.provider!=="paypal"||le.providerObjectType!=="setup_token")throw new Rn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return le.providerObjectId},onApprove:async le=>{let ye=le.vaultSetupToken;if(!ye)throw new Rn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let pe=await P.processPayment(me.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:ye,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Rn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:me});if(!pe.ok)throw new Rn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:pe.status});A&&_.current.onConfirmed()},onCancel:()=>{A&&_.current.onAbandoned()},onError:le=>{if(!A)return;let{popupBlocked:ye}=(0,ke.classifyExternalMethodFailure)(le,{inAppBrowser:Z,handoffObserved:!1});_.current.onFailed(ye?new Error((0,ke.buildExternalMethodRecoveryMessage)("PayPal",!0,Z)):le,{code:ye?"popup_blocked":"paypal_setup_failed",retryable:!0})}});y=()=>T.close(),await T.render(xe)}catch(S){if(!A)return;_.current.onFailed(S,{code:"paypal_unavailable",retryable:!0})}})(),()=>{A=!1,y?.().catch(()=>{}),P.destroy()}},[s,e,r,m,t,Z,a,n,l,p]),(0,Cc.jsx)("div",{ref:Y,"data-flopay-paypal-setup":""})}var Sc=require("@flopay/js/card-setup"),En=require("@flopay/shared"),Xn=require("@stripe/react-stripe-js"),wc=require("@stripe/stripe-js"),Zr=require("react");var Wr=require("react/jsx-runtime"),kc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Es=new Map;function gu(e){let t=Es.get(e);if(t)return t;let r=(0,wc.loadStripe)(e).catch(n=>{throw Es.delete(e),n});return Es.set(e,r),r}function hu(e){return e?(0,En.toStripeAppearance)(e):void 0}function Pu(e){return(0,ke.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function bc(e){return e==="paypal"?"PayPal":(0,En.getStripeMethodDisplayName)(e)}function vu(){return typeof window>"u"?"":window.location.href}var Cu={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function Rc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:l}=e,[p]=(0,Zr.useState)(()=>gu(t)),m=(0,Zr.useMemo)(()=>{let h=hu(l),R=(0,En.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:kc[r]?.types??[r],...R?{setupFutureUsage:R}:{},...h?{appearance:h}:{}}},[l,n,a,s,r]);return(0,Wr.jsx)(Xn.Elements,{stripe:p,options:m,children:(0,Wr.jsx)(bu,{...e})})}function bu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:l,themeId:p,buttonsLayout:m,onSubmitting:h,onConfirmed:R,onDeclined:w,onFailed:I,onValidation:Y,onUnavailable:_}){let Z=(0,Xn.useStripe)(),A=(0,Xn.useElements)(),[y,P]=(0,Zr.useState)(!1),[me,S]=(0,Zr.useState)("loading"),[xe,T]=(0,Zr.useState)(!1),[le,ye]=(0,Zr.useState)(!1),pe=(0,Zr.useRef)(!1),[Re]=(0,Zr.useState)(()=>(0,$n.detectPayPalEnvironment)()),[lt,$e]=(0,Zr.useState)(!1),B=(0,Zr.useCallback)((K,Le)=>{if((0,ke.classifyExternalMethodFailure)(K,{inAppBrowser:Re.inAppBrowser,handoffObserved:!1}).popupBlocked){$e(!0),I(new Error((0,ke.buildExternalMethodRecoveryMessage)(bc(e),!0,Re.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}I(Le.message===void 0?K:new Error(Le.message),{code:Le.code,retryable:!0})},[Re.inAppBrowser,e,I]),wt=(0,Zr.useCallback)(async K=>{let Le=!1,nt=!1,je=()=>{!K||Le||nt||(nt=!0,K.paymentFailed({reason:"fail"}))};if(!Z||!A||pe.current){je();return}pe.current=!0,P(!0);try{let X=await A.submit();if(X.error){je(),Y(X.error.message??null);return}h();let $=await new Sc.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,En.isSettledSessionIntent)($))throw(0,En.settledSessionIntentError)(r);if($.provider!=="stripe"||$.intentKind!=="setup")throw new En.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Le=!0;let H=await Z.confirmSetup({elements:A,clientSecret:$.clientSecret,confirmParams:{return_url:vu()},redirect:"if_required"});if(H.error){Pu(H.error)?w({...H.error.decline_code||H.error.code?{reason:H.error.decline_code??H.error.code}:{},...H.error.message?{message:H.error.message}:{}}):B(H.error,{code:"payment_method_setup_provider_failed",message:H.error.message??"The payment method could not be saved."});return}R()}catch(X){je(),B(X,{code:"payment_method_setup_failed"})}finally{pe.current=!1,P(!1)}},[a,t,A,e,n,R,w,h,Y,B,r,Z,s]),Ye=kc[e]?.wallet,Ne=Ye==="paypal"&&(0,Hn.resolveStripePayPalPresentation)(Re,"auto",lt?"blocked":Re.popupCapability)==="redirect",ue=l?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&Ye&&!Ne)return(0,Wr.jsxs)(Wr.Fragment,{children:[(0,Wr.jsx)(Zo,{}),(0,Wr.jsx)(Ea,{state:me,borderRadius:ue,children:(0,Wr.jsx)(Xn.ExpressCheckoutElement,{options:{...pi,paymentMethods:ui([e])},onReady:K=>{let Le=Ra(K,[Ye]);S(Le),Le==="unavailable"&&_()},onLoadError:()=>{S("load_error"),_()},onConfirm:K=>{wt(K)}})})]});let ne=bc(e);return(0,Wr.jsxs)(Wr.Fragment,{children:[xe?(0,Wr.jsx)(di,{method:e,themeId:p,hasNextStep:!0,highlighted:le,disabled:y,onClick:()=>ye(K=>!K),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:ue}):null,(0,Wr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!le,style:le?{display:"flex",flexDirection:"column"}:Cu,children:[(0,Wr.jsx)(Xn.PaymentElement,{options:{layout:mi},onReady:()=>T(!0),onLoadError:()=>_(),onChange:K=>{K.complete&&Y(null)}}),(0,Wr.jsx)(yi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!Z||!A||y||!le,onClick:()=>{wt()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:m?.submitButton,children:y?"Saving\u2026":`Save ${ne}`})]})]})}var Ba=require("@flopay/js/card-setup"),kr=require("@flopay/shared"),Ge=Gi(require("react"),1);var ea=require("@flopay/js/card-setup"),Ar=require("@flopay/shared");var ur=require("react/jsx-runtime"),Su=15,wu=2e3;function ku(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Is(e){return new Promise(t=>setTimeout(t,e))}async function Ru(e,t,r){if(!t.trim())throw new kr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new kr.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,kr.isCardSetupCheckoutSession)(a))throw new kr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Ar.readSetupAdvertisement)(n);if(!(0,Ar.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:l}=s,p=l.length>0?`FloPay: this setup session advertises only Stripe methods (${l.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new kr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function Eu(e,t,r,n,a){let s=t.vault??null;(0,kr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let l=(0,kr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!l)throw new kr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return l}var Ti=class extends Ge.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function Ec({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:l="modern-light",containerStyle:p,appearance:m,buttonsStyles:h,loading:R=null,onReady:w,onComplete:I,onDecline:Y,onCancel:_,onValidation:Z,onError:A}){let[y]=(0,Ge.useState)(ea.readSetupRedirectReturn),[P,me]=(0,Ge.useState)(null),[S,xe]=(0,Ge.useState)(!1),[T,le]=(0,Ge.useState)(null),[ye,pe]=(0,Ge.useState)(null),[Re,lt]=(0,Ge.useState)(null),[$e,B]=(0,Ge.useState)(null),[wt,Ye]=(0,Ge.useState)(()=>new Set),Ne=(0,Ge.useRef)(wt),ue=(0,Ge.useRef)(null);ue.current=P;let ne=(0,Ge.useRef)(!1),K=(0,Ge.useRef)(!1),Le=(0,Ge.useRef)(!1),nt=(0,Ge.useRef)(!1),je=(0,Ge.useRef)(0),X=(0,Ge.useRef)(0),$=(0,Ge.useRef)(!1),{vaultTheme:H,surface:V,overlayTheme:Ve,appearance:De,buttonsLayout:fe}=(0,Ge.useMemo)(()=>Ii({theme:l,appearance:m,buttonsStyles:h}),[l,m,h]),D=(0,Ge.useMemo)(()=>(0,Ia.mergeCardSetupSurface)(V,p),[V,p]),ge=(0,Ge.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:w,onComplete:I,onDecline:Y,onCancel:_,onValidation:Z,onError:A});ge.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:w,onComplete:I,onDecline:Y,onCancel:_,onValidation:Z,onError:A},(0,Ge.useEffect)(()=>{$.current=!0;let c=je.current+1;return je.current=c,()=>{$.current=!1,X.current+=1,queueMicrotask(()=>{je.current===c&&(Le.current||nt.current||(nt.current=!0,(0,Ke.invokeMerchantCallback)(()=>{ge.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let pt=(0,Ge.useCallback)((c,U)=>{Le.current=!0,ne.current=!1,B({status:"success",wording:c,message:null}),(async()=>(await Is(600),!K.current&&(K.current=!0,(0,Ke.invokeMerchantCallback)(()=>{ge.current.onComplete?.({status:"succeeded",sessionId:ge.current.sessionId,...U?{paymentMethod:U}:{}})}),$.current&&B(null))))()},[]),Ue=(0,Ge.useCallback)((c,U)=>{Le.current=!0,ne.current=!1,B({status:"error",wording:c,message:U.message??null}),(0,Ke.invokeMerchantCallback)(()=>{ge.current.onDecline?.({status:"declined",sessionId:ge.current.sessionId,...U.reason?{reason:U.reason}:{},...U.message?{message:U.message}:{}})}),(async()=>(await Is(400),$.current&&B(null)))()},[]),ot=(0,Ge.useCallback)((c,U)=>{ne.current?(ne.current=!1,B({status:"error",wording:c,message:U.message}),setTimeout(()=>{$.current&&B(null)},400)):B(null),(0,Ke.invokeMerchantCallback)(()=>ge.current.onError?.(U))},[]),Ae=(0,Ge.useCallback)(async c=>{let U=X.current+1;X.current=U;let W=()=>!$.current||U!==X.current;ne.current=!0,B({status:"processing",wording:"payment_method",message:null});let ce=new Ba.PaymentAPI((0,kr.resolveBillingApiUrl)(ge.current.billingApiUrl),{telemetry:ge.current.telemetry});try{for(let E=0;E<Su;E+=1){if((E>0||c.waitFirst)&&await Is(wu),W())return;let z=await ce.getUnifiedCheckoutSession(ge.current.sessionId,ge.current.nonce);if(W())return;let Ut=z.data.session?.status;if(Ut==="complete"){xe(!0),pt("payment_method");return}if(Ut==="expired")throw new kr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new kr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(E){if(W())return;let z=E instanceof kr.FloPayError&&E.code==="payment_method_setup_unverified";ot("payment_method",uo(E,z?{retryable:!0}:{}))}finally{ce.destroy()}},[ot,pt]);(0,Ge.useEffect)(()=>{let c=!0,U=(0,kr.resolveBillingApiUrl)(a),W=new Ba.PaymentAPI(U,{telemetry:s});me(null),xe(!1),le(null),pe(null),lt(null);let ce=new Set;return Ne.current=ce,Ye(ce),Le.current=!1,nt.current=!1,K.current=!1,(async()=>{try{let{session:E,advertisement:z}=await Ru(W,r,n);if(!c)return;let Ut={advertisement:z,customer:ku(E),...E.futureUse?{futureUse:E.futureUse}:{},...E.futureUseUnsupported?{futureUseUnsupported:E.futureUseUnsupported}:{}};if(y){if((0,ea.clearSetupRedirectParams)(),E.status==="complete"){xe(!0),me(Ut),pt("payment_method");return}y.failed?Ue("payment_method",{reason:"redirect_failed"}):Ae({waitFirst:!0})}let Fr=z.card?await Eu(W,E,r,n,U):null;if(!c)return;me(Ut),Fr&&(pe(Fr),le(new Ba.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(E){if(!c)return;let z=uo(E);Le.current=!0,lt(z),(0,Ke.invokeMerchantCallback)(()=>ge.current.onError?.(z))}})(),()=>{c=!1,W.destroy()}},[a,n,y,Ue,pt,r,s,Ae]),(0,Ge.useEffect)(()=>{if(!T)return;ne.current=!1;let c=T.on("submitting",()=>{ne.current=!0,B({status:"processing",wording:"card",message:null})}),U=T.on("complete",E=>{pt("card",E.paymentMethod)}),W=T.on("decline",E=>{Ue("card",{...E.declineReason?{reason:E.declineReason}:{},...E.message?{message:E.message}:{}})}),ce=T.on("challenge_dismissed",()=>{B(null)});return()=>{c(),U(),W(),ce()}},[T,Ue,pt]);let Qe=(0,Ge.useCallback)((c,U,W)=>{if(W.retryable){ot("payment_method",uo(U,W));return}if(Ne.current.has(c))return;let ce=new Set(Ne.current);ce.add(c),Ne.current=ce,Ye(ce);let E=ue.current?.advertisement,z=E?(0,Ar.advertisedMethodKeys)(E).some(Ut=>!ce.has(Ut)):!1;ot("payment_method",uo(U,{code:W.code,retryable:z}))},[ot]),at=(0,Ge.useMemo)(()=>({onSubmitting:()=>{ne.current=!0,B({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Ae({waitFirst:!1})},onDeclined:c=>Ue("payment_method",c),onValidation:c=>{(0,Ke.invokeMerchantCallback)(()=>ge.current.onValidation?.(c))},onAbandoned:()=>{ne.current=!1,B(null)}}),[Ue,Ae]),pr=(0,Ge.useRef)(Qe);pr.current=Qe;let Mt=(0,Ge.useRef)(new Map),vt=c=>{let U=Mt.current.get(c);if(U)return U;let W=(ce,E)=>pr.current(c,ce,E);return Mt.current.set(c,W),W},be=(0,Ge.useCallback)(c=>{if(Ne.current.has(c))return;let U=new Set(Ne.current);U.add(c),Ne.current=U,Ye(U);let W=ue.current?.advertisement;W&&(0,Ar.advertisedMethodKeys)(W).some(E=>!U.has(E))||ot("payment_method",uo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ot]),M=(0,Ge.useRef)(be);M.current=be;let gt=(0,Ge.useRef)(new Map),ct=c=>{let U=gt.current.get(c);if(U)return U;let W=()=>M.current(c);return gt.current.set(c,W),W},N=$e?(0,ur.jsx)(sn,{status:$e.status,errorMessage:$e.message,...(0,Ar.setupOverlayLabels)($e.wording),successNote:null,...Ve?{theme:Ve}:{}}):null;if(Re)return(0,ur.jsx)("div",{role:"alert",children:Re.message});if(!P||S)return(0,ur.jsxs)(ur.Fragment,{children:[N,P?null:R]});let{advertisement:Fe,customer:Lt,futureUse:Se,futureUseUnsupported:It}=P,b=(0,kr.resolveBillingApiUrl)(a),x=s===void 0?{}:{telemetry:s},Be=Fe.stripe.filter(({method:c})=>!wt.has(c)),Ee=wt.has("paypal")?null:Fe.paypal,dt=!!(Fe.card&&T&&ye?.html),it=({method:c,publishableKey:U,currency:W})=>(0,ur.jsx)("div",{"data-flopay-payment-method":c,style:{display:"contents"},children:(0,ur.jsx)(Ti,{onFailed:vt(c),children:(0,ur.jsx)(Ge.Suspense,{fallback:null,children:(0,ur.jsx)(e,{method:c,category:(0,Ar.stripeMethodCategory)(c),publishableKey:U,currency:W,...Se?{futureUse:Se}:{},...It?{futureUseUnsupported:It}:{},sessionId:r,nonce:n,billingApiUrl:b,...x,...De?{appearance:De}:{},...fe?{buttonsLayout:fe}:{},...typeof l=="string"?{themeId:l}:{},...at,onFailed:vt(c),onUnavailable:ct(c)})})})},c),We=Be.filter(({method:c})=>(0,Ar.stripeMethodCategory)(c)==="wallet"),He=Be.filter(({method:c})=>(0,Ar.stripeMethodCategory)(c)!=="wallet"),Dt=Be.length>0||Ee!==null;return(0,ur.jsxs)(ur.Fragment,{children:[N,Dt?(0,ur.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[We.map(it),Ee?(0,ur.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,ur.jsx)(Ti,{onFailed:vt("paypal"),children:(0,ur.jsx)(Ge.Suspense,{fallback:null,children:(0,ur.jsx)(t,{clientId:Ee.clientId,...Ee.environment?{environment:Ee.environment}:{},...Fe.currency?{currency:Fe.currency}:{},sessionId:r,nonce:n,billingApiUrl:b,customer:Lt,...x,...at,onFailed:vt("paypal"),onUnavailable:ct("paypal")})})})}):null,He.map(it)]}):null,dt&&Dt?(0,ur.jsx)(fi,{label:"or add a card"}):null,dt&&T&&ye?.html?(0,ur.jsx)("div",{"data-flopay-payment-method":"card",children:(0,ur.jsx)(go,{capture:T,html:ye.html,messageToken:ye.messageToken,expectedOrigin:ye.expectedOrigin,verificationRequired:ye.verificationRequired,theme:H,containerStyle:D,onReady:()=>{(0,Ke.invokeMerchantCallback)(()=>ge.current.onReady?.())},onValidation:c=>{(0,Ke.invokeMerchantCallback)(()=>ge.current.onValidation?.(c))},onError:c=>{c&&ot("card",uo(new Error(c),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var _c=require("react/jsx-runtime"),Iu={StripeSetupMethod:Rc,PayPalSetupMethod:vc};function Ic(e){return(0,_c.jsx)(Ec,{...e,branches:Iu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});