@flopay/react 1.14.14 → 1.14.15

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 Qc=Object.create;var Za=Object.defineProperty;var ed=Object.getOwnPropertyDescriptor;var td=Object.getOwnPropertyNames;var rd=Object.getPrototypeOf,nd=Object.prototype.hasOwnProperty;var od=(e,t)=>{for(var r in t)Za(e,r,{get:t[r],enumerable:!0})},Sl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of td(t))!nd.call(e,a)&&a!==r&&Za(e,a,{get:()=>t[a],enumerable:!(n=ed(t,a))||n.enumerable});return e};var Qi=(e,t,r)=>(r=e!=null?Qc(rd(e)):{},Sl(t||!e||!e.__esModule?Za(r,"default",{value:e,enumerable:!0}):r,e)),ad=e=>Sl(Za({},"__esModule",{value:!0}),e);var Fu={};od(Fu,{DirectPayPalButton:()=>Sa,FloPayAutomaticPaymentButton:()=>Cc,FloPayCardSetup:()=>bc,FloPayCardSetupError:()=>La,FloPayCheckout:()=>Ti,FloPayPaymentMethodSetup:()=>Ac,FloPayProvider:()=>Ra,SplitCardForm:()=>ki,VaultCardFields:()=>ho,dropThirdPartyOnlyError:()=>Bc.dropThirdPartyOnlyError,useCheckout:()=>Dl,useFloPay:()=>io,usePayPalFloPay:()=>ri});module.exports=ad(Fu);var Bc=require("@flopay/shared");var Mi=require("@flopay/js"),Rn=require("@flopay/shared"),ht=require("react");var er=require("react/jsx-runtime");function id(){return(0,er.jsxs)(er.Fragment,{children:[(0,er.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,er.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,er.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,er.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,er.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function sd(){return(0,er.jsx)(er.Fragment,{children:"Go back"})}function ld(){return(0,er.jsx)(er.Fragment,{children:"Secure card checkout"})}function zo(e){return e!==void 0&&(e===""||e===null||e===!1)}function qo({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(id,{}):e})}function jo({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(sd,{}):e})}function ga({content:e}){return(0,er.jsx)(er.Fragment,{children:e===void 0?(0,er.jsx)(ld,{}):e})}var bt=require("@flopay/shared"),Dn=require("@flopay/shared"),$o=require("@flopay/shared"),So=require("@flopay/shared");function es(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof bt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function cd(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 wl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,bt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,bt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function Rl(e,t){if(t&&(!(e instanceof bt.FloPayError)||e.type==="authentication_error"))return es(e);if(!(e instanceof bt.FloPayError&&cd(e))){if(!t&&!(e instanceof bt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,bt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof bt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof bt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Vo(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let c={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,bt.isCardHolderNamePlaceholder)(c.firstName,c.lastName);if(!(0,bt.isValidEmail)(c.email))return Promise.reject(new bt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[g,E]of Object.entries(c)){if(p&&g.endsWith("Name")||typeof E!="string")continue;let R=E.trim();R&&(y[g]=R)}return a=e.claimCheckoutSession(t,r,{accountData:y}),a.catch(()=>{}),a}}function kl(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 ts(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 El(e,t){let r=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],n=r.reduce((s,c)=>s+(c.overrideAmount??c.totalAmount??0),0),a=e.currency??r.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:r.map((s,c)=>({uuid:`synthetic-${s.type??"item"}-${c}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??a,metadata:s.metadata??null}))}}function rs(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,s=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,c=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...s?{declineCode:s}:{},...c?{sessionId:c}:{}}}var Il=new WeakMap;function _l(e,t){return typeof e=="object"&&e!==null&&Il.set(e,t?{sessionId:t}:{}),e}function Tl(e){return typeof e=="object"&&e!==null?Il.get(e):void 0}function fo(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 go(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 Ml(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Qa(e){let t=Ml(e);return new bt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ei(e){return e instanceof bt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Wo(e){return Ml(e)?new bt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new bt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new bt.FloPayError(bt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ha(e,t){return e==="processing"||(0,bt.isMoneySettledOutcome)(e,t)}function xl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Al(e,t){let r=e;if((0,bt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:c}=await r.retrieveSetupIntent(t);if(c)throw new bt.FloPayError(c.message??"Failed to retrieve setup intent.","api_error",{...c.code?{code:c.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new bt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var dd=["apple_pay","google_pay"];function Fl(e,t="automatic",r){let n=(0,bt.resolveSetupFutureUsage)(r,dd,"wallet");return{...(0,bt.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var ud=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ns(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:ud.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Pa(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"),Ne=require("@flopay/shared"),P=Qi(require("react"),1);var os=require("react"),vn=(0,os.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),On=(0,os.createContext)({session:null,loading:!1,error:null});var li=require("@flopay/js"),qe=require("@flopay/shared"),zl=require("@paypal/paypal-js"),k=require("react");var ti=require("@flopay/shared"),Ln=require("react"),Cn=require("@flopay/shared"),ao=require("react/jsx-runtime");function Ho(){let[e,t]=(0,Ln.useState)(null),r=(0,Ln.useRef)(null),n=(0,Ln.useRef)(0),a=(0,Ln.useCallback)((c,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:c,identity:p}),new Promise(y=>{r.current=y})),[]),s=(0,Ln.useCallback)(c=>{let p=r.current;r.current=null,t(null),p?.(c)},[]);return(0,Ln.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function Ko({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[c,p]=(0,Ln.useState)(e.email?.trim()??""),y=(0,ti.isValidEmail)(c.trim());return(0,ao.jsxs)("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,ao.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,ao.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,ao.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:c,onChange:g=>p(g.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:!y||a,onClick:()=>{r((0,ti.compactBuyerIdentity)({...e,email:c.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var we=require("@flopay/shared");var Bl=require("@flopay/shared"),va=require("react");function io(){return(0,va.useContext)(vn).flopay}function ri(){return(0,va.useContext)(vn).paypalFlopay??null}function Dl(){return(0,va.useContext)(On)}function Ol(){return(0,va.useContext)(vn).billingApiUrl||(0,Bl.resolveBillingApiUrl)()}var pd=require("@flopay/shared"),Gn=require("@flopay/shared"),Yn=require("@flopay/shared");var Go=require("@flopay/shared"),Ro=require("react");var ni=require("react"),wo=typeof window>"u"?ni.useEffect:ni.useLayoutEffect;var as=require("@flopay/shared");function Yo(e,t){let r=(0,Ro.useRef)(e);r.current=e;let n=(0,Ro.useRef)(new Set),a=(0,Ro.useRef)(t),s=(0,Ro.useRef)(t);return wo(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Ro.useCallback)(c=>{if(s.current!==t)return;let p=(0,Go.projectFloInstrument)(c);if(p){if(Go.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,Go.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Xe=require("@flopay/shared");var Ll=require("react"),Ca=(0,Ll.createContext)(null);function oi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ai="provider.callback.ignored";function ii(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var md=Symbol.for("@flopay/js.telemetry.bridge.v1"),yd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function fd(){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 gd(e){let t=fd(),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 si(e){let t=globalThis[yd];return gd(t?.(e)??{})}function Rr(e){if(e)return e[md]}var gr=require("react");function ba(e,t){let r=(0,gr.useRef)(0),n=(0,gr.useRef)(null),a=(0,gr.useRef)(null),s=(0,gr.useRef)(e),c=(0,gr.useRef)(t?.onHandoffObserved),p=(0,gr.useRef)(t?.defersMissingTerminal),y=(0,gr.useRef)(t?.onMissingTerminalDeferred);(0,gr.useEffect)(()=>{s.current=e,c.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let g=(0,gr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),E=(0,gr.useCallback)(f=>{g();let h=r.current+1;return r.current=h,n.current=null,a.current={generation:h,method:f,timer:null,yieldedControl:!1},h},[g]),R=(0,gr.useCallback)(f=>{let h=a.current;return f!==void 0&&h?.generation!==f?!1:(g(h),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[g]),_=(0,gr.useCallback)(f=>{let h=a.current,ge=f??h?.generation??r.current;(f===void 0||h?.generation===f)&&(g(h),a.current=null),n.current=ge},[g]),H=(0,gr.useCallback)(f=>n.current===(f??r.current),[]),T=(0,gr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),Y=(0,gr.useCallback)(()=>{let f=a.current;f&&(g(f),!f.yieldedControl&&(f.yieldedControl=!0,c.current?.(f.method)))},[g]),B=(0,gr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(g(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(p.current?.(f.method)){y.current?.(f.method,f.generation);return}a.current=null,n.current=f.generation,s.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},we.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[g]);return(0,gr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?B():Y()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",Y),window.addEventListener("focus",B),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",Y),window.removeEventListener("focus",B),g()}},[g,Y,B]),{startAttempt:E,finishAttempt:R,invalidateAttempt:_,isAttemptInvalidated:H,isAttemptCurrent:T,generationRef:r}}var bn=require("react/jsx-runtime"),ci=45,hd=1e3,Pd=11e3,Nl="paypal_intent_settled",vd={width:"100%",minHeight:ci,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"},Cd={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 bd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Cd[e.kind]??null}}function Ul(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,we.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function Sd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function ql({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:c,environment:p,currency:y,isSubscription:g,providerObjectType:E,approvalPresentation:R,onTokenizedBody:_,onComplete:H,onErrorChange:T,onDecline:Y,onCancel:B,onTechnicalFailure:f,isProcessing:h=!1,onLoadStateChange:ge,onInitializationStateChange:S,allowAutomaticRetry:Me=!0,onButtonClick:A,runBeforeButtonClick:ie,session:he,existingOrderId:fe,telemetry:Re,telemetryContext:ct,onInstrument:Ke,debug:F=!1}){let St=io(),et=Yo(Ke,e),Ue=(0,k.useMemo)(()=>{if(St)return null;let K=si({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:qe.SDK_VERSION,enabled:Re!==!1});return K.setCheckoutContext(ct??{}),K.beginCheckout(ct??{}),K},[r,St,Re,ct?.checkoutMode,ct?.layout]),ye=(0,k.useMemo)(()=>Rr(St),[St]);(0,k.useEffect)(()=>()=>{Ue&&Ue.flush().catch(()=>{}).finally(()=>Ue.destroy())},[Ue]);let J=(0,k.useMemo)(()=>({error:K=>{ye?ye.error(K):Ue?.error(K),et({class:"technical_error",errorCode:K.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":K.errorCode,requestCategory:K.requestCategory,provider:K.provider})},log:K=>{ye?ye.log(K):Ue?.log(K),et({class:"lifecycle",name:K.name,provider:K.provider})},performance:K=>{ye?ye.performance(K):Ue?.performance(K)},terminal:K=>{ye?ye.terminal(K):Ue?.terminal(K)},startTiming:()=>ye?.now()??Ue?.now()??0,elapsed:K=>ye?.elapsed(K)??Math.max(0,(Ue?.now()??K)-K)}),[et,ye,Ue]),W=(0,k.useRef)(null),Fe=(0,k.useRef)(0),dt=(0,k.useRef)(null),We=(0,k.useRef)(null),Z=(0,k.useRef)(null),L=(0,k.useContext)(Ca),le=(0,k.useRef)(null);le.current||(le.current=oi());let j=L??le.current,Se=(0,k.useRef)(null),xe=(0,k.useRef)(!1),[Pe,Be]=(0,k.useState)(!1),[M,nt]=(0,k.useState)(!1),[je,ut]=(0,k.useState)(0),Ge=(0,k.useRef)(0),[$e,Rt]=(0,k.useState)(!1),Ot=(0,k.useRef)(!1),zt=(0,k.useRef)(!1),[Ft,ue]=(0,k.useState)(!1),[pe,X]=(0,k.useState)(!1),{request:Pt,collect:pt,finish:V}=Ho(),rt=(0,k.useRef)({sessionId:e,required:(0,qe.paypalProviderIdentityRequired)(n,he)});rt.current.sessionId!==e&&(rt.current={sessionId:e,required:(0,qe.paypalProviderIdentityRequired)(n,he)});let wt=rt.current.required,ke=(0,k.useMemo)(()=>r.replace(/\/+$/,""),[r]),U=he?.gateways?.paypal?.providerObjectType??E,ne=U??(g?"subscription":"order"),[Ae]=(0,k.useState)(Gn.detectPayPalEnvironment),Dt=he?.gateways?.paypal?.approvalPresentation??R,ot=(0,Yn.resolvePayPalPresentationMode)(Ae,Dt==="app_switch"?"app_switch":void 0,ne),De=(0,qe.usesPayPalVaultedChannel)(U),Oe=(0,k.useMemo)(()=>JSON.stringify([ke,c,y,p??"",ne,De,ot,e,fe??""]),[ke,c,y,p,fe,ne,De,ot,e]),_t=(0,k.useRef)(Oe),u=_t.current!==Oe,C=(0,k.useRef)(F),Q=(0,k.useRef)(null),[ce,N]=(0,k.useState)([]),w=(0,k.useCallback)(K=>{C.current&&N(Nt=>[...Nt,`${new Date().toISOString().slice(11,23)} ${K}`])},[]);(0,k.useEffect)(()=>{C.current=F,F&&w("debug:enabled"),Q.current?.setEnabled(F)},[w,F]);let qt=(0,k.useRef)(_),Ar=(0,k.useRef)(H),mr=(0,k.useRef)(T),Fr=(0,k.useRef)(Y),st=(0,k.useRef)(B),Gr=(0,k.useRef)(f),Yr=(0,k.useRef)(A),Br=(0,k.useRef)(ge),Xt=(0,k.useRef)(S),ar=(0,k.useRef)(s),tr=(0,k.useRef)(ie),In=(0,k.useRef)(he),Jt=(0,k.useRef)(n),qn=(0,k.useRef)(a),Dr=(0,k.useRef)(t),Zt=(0,k.useRef)(null),ir=(0,k.useRef)(new Map),nn=(0,k.useRef)(new Map),mt=(0,k.useRef)(!1),Tt=(0,k.useRef)(e);Tt.current=e;let[Or]=(0,k.useState)(ii);(0,k.useEffect)(()=>(mt.current=!0,()=>{mt.current=!1}),[]),(0,k.useEffect)(()=>{qt.current=_},[_]),(0,k.useEffect)(()=>{ar.current=s},[s]),(0,k.useEffect)(()=>{Ar.current=H},[H]),(0,k.useEffect)(()=>{mr.current=T},[T]),(0,k.useEffect)(()=>{Fr.current=Y},[Y]),(0,k.useEffect)(()=>{st.current=B},[B]),(0,k.useEffect)(()=>{Gr.current=f},[f]),(0,k.useEffect)(()=>{Yr.current=A},[A]),(0,k.useEffect)(()=>{Br.current=ge},[ge]),(0,k.useEffect)(()=>{Xt.current=S},[S]),(0,k.useEffect)(()=>{tr.current=ie},[ie]),(0,k.useEffect)(()=>{In.current=he},[he]),(0,k.useEffect)(()=>{Jt.current=n},[n]),(0,k.useEffect)(()=>{qn.current=a},[a]),(0,k.useEffect)(()=>{Dr.current=t},[t]),(0,k.useEffect)(()=>{Ge.current=je},[je]),(0,k.useEffect)(()=>{$e&&Se.current?.focus()},[$e,je]);let sr=(0,k.useCallback)(()=>{window.setTimeout(()=>{Se.current?.focus()},0)},[]),Qt=(0,k.useCallback)(()=>{Be(!1),ut(K=>K+1)},[]),zr=(0,k.useCallback)(()=>{Rt(!1),(W.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??W.current)?.focus?.()},[]);(0,k.useEffect)(()=>{!Pe||!xe.current||(xe.current=!1,zr())},[zr,Pe,je]);let Pr=(0,k.useCallback)((K,Nt)=>{let ae=Nt?.popupBlocked??(0,we.isPopupBlockedError)(K);ae&&j.markBlocked();let Ht=(0,we.buildExternalMethodRecoveryMessage)("PayPal",ae,Ae.inAppBrowser),Gt=Gr.current;if(Gt){let be=ae&&Ae.inAppBrowser?new qe.FloPayError(Ht,"api_error",{code:Nt?.code??"paypal_popup_blocked"}):K;Gt("paypal",be,Nt);return}if(K instanceof qe.FloPayError&&K.code==="checkout_processing_timeout"){mr.current?.(K.message);return}mr.current?.(Ht)},[j,Ae.inAppBrowser]),jt=(0,k.useCallback)(K=>{let Nt=dt.current,ae=We.current;Nt===null||!ae||(J.log({...ae,popupCapability:j.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:K}),J.performance({...ae,popupCapability:j.current(),stage:"overlay_return",durationMs:J.elapsed(Nt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:K}),dt.current=null)},[j,J]),Lr=(0,k.useCallback)((K,Nt,ae)=>{let Ht=We.current;jt("overlay_timeout"),Ht&&J.error({...Ht,popupCapability:j.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Pr(Nt,{...ae,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ot,terminalReason:"overlay_timeout"}),Rt(!0),Qt(),sr()},[jt,sr,Pr,j,ot,Qt,J]),Er=(0,k.useCallback)(()=>{j.markAvailable();let K=We.current;K&&(Z.current=K.attempt,J.log({...K,popupCapability:j.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[j,J]),{finishAttempt:Ce,generationRef:Nr,invalidateAttempt:_n,isAttemptCurrent:Tn,isAttemptInvalidated:vr,startAttempt:pn}=ba(Lr,{onHandoffObserved:Er}),mn=(0,k.useCallback)(()=>(Rt(!1),pn("paypal")),[pn]),Mn=(0,k.useCallback)(K=>{_n(K?.generation),K?.showRetry&&Rt(!0),K?.remount&&Qt(),K?.focus!==!1&&sr()},[sr,_n,Qt]),Lt=K=>{let Nt=Zt.current;return Nt&&nn.current.set(K,Nt),K};(0,k.useEffect)(()=>{_t.current!==Oe&&(_t.current=Oe,Ot.current=!1,zt.current=!1,Be(!1),nt(!1),ue(!1),Xt.current?.("loading"))},[Oe]),(0,k.useEffect)(()=>{(0,Xe.invokeMerchantCallback)(()=>Br.current?.(Pe&&!Ft))},[Pe,Ft]);let ve=(0,qe.normalizeGatewayEnvironment)(p);(0,k.useEffect)(()=>{let K={attempt:Nr.current+1,inAppBrowser:Ae.inAppBrowser,appFamily:Ae.appFamily,popupCapability:j.current(),presentationMode:ot},Nt=()=>({...We.current??K,popupCapability:j.current()}),ae={error:x=>J.error({...x,...Nt()}),log:x=>J.log({...x,...Nt()}),performance:x=>J.performance({...x,...Nt()}),terminal:x=>J.terminal({...x,...Nt()}),startTiming:J.startTiming,elapsed:J.elapsed},Ht=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",Gt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(w(`mount clientId=${Ht} env=${p??"(unset)"}\u2192${ve??"live"} ccy=${y} sub=${g}`),w(`ua=${Gt.slice(0,80)}${Gt.length>80?"\u2026":""}`),!c){w("FAIL: clientId empty \u2014 gateway misconfigured"),ue(!0),ae.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(!W.current){w("FAIL: containerRef not attached");return}Fe.current=ae.startTiming(),ae.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let be=!1,Ut=!1,tt=()=>be||Ut,at=x=>{let m=mt.current,I=m?x:"torn_down";m&&w(`onError ignored reason=${I}`),Or.take(Tt.current)&&ae.log({name:ai,stage:"provider_ready",reason:I,provider:"paypal",paymentMethodCategory:"paypal"})},rr=()=>Tt.current===e?"stale_attempt":"session_changed",Vr=De?ne:void 0,yn,lr=!1,jn=()=>{yn=(0,qe.generateIdempotencyKey)(),yn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),lr=!0},Vn=null,eo=!1,xn=null,po=!1,to=()=>{!xn||po||(po=!0,xn.close().catch(()=>{}))},an=!1,An=!1,sn=W.current,Wn=null,Vt=null,Xr=[],Jr=null,Zr=!1,fn=!1,yt=null,nr=x=>{if(!x||typeof x.getBoundingClientRect!="function")return"(no rect)";let m=x.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},Ir=x=>{if(!x)return"(empty)";try{let m=new URL(x,typeof window>"u"?"https://localhost":window.location.href),I=m.pathname.toLowerCase();return I.includes("checkcaptcha")||I.includes("captcha")?`CAPTCHA(${m.host}${I})`:I.includes("risk")||I.includes("challenge")?`RISK(${m.host}${I})`:I.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${I}`.slice(0,100)}catch{return x.slice(0,80)}},Wr=x=>{let m=x.getAttribute("src"),I=x.getAttribute("srcdoc"),Le=x.getAttribute("name"),Ze=x.getAttribute("sandbox"),He=[];return m&&He.push(`src=${Ir(m)}`),I&&He.push(`srcdoc[${I.length}ch]`),!m&&!I&&He.push("src=(empty) srcdoc=(empty)"),Le&&He.push(`name=${Le.slice(0,40)}`),Ze!==null&&He.push(`sandbox="${Ze.slice(0,40)}"`),He.join(" ")},_o=x=>{if(!(x instanceof HTMLIFrameElement))return"";try{let m=x.contentDocument;if(!m)return"cd=null";let I=m.body?.children.length??0,Le=m.body?.innerHTML.length??0,Ze=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${I}children,${Le}ch] head[${Ze}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},gn=[],ro=x=>{if(tt())return;let m=x.message??String(x.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(w(`window:error ${m.slice(0,140)}`),gn.push(m))},ln=x=>{if(tt())return;let m=x.reason instanceof Error?x.reason.message:String(x.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(w(`window:rejection ${m.slice(0,140)}`),gn.push(m))},Cr={value:0},mo=()=>{Wn?.disconnect(),Wn=null,Vt?.disconnect(),Vt=null;for(let x of Xr.splice(0))clearTimeout(x);fn=!1,Zr&&typeof window<"u"&&(window.removeEventListener("error",ro),window.removeEventListener("unhandledrejection",ln)),Zr=!1},qr=()=>{if(!(Zr||tt()||an)){if(Zr=!0,gn.length=0,Cr.value=0,typeof window<"u"&&(window.addEventListener("error",ro),window.addEventListener("unhandledrejection",ln)),typeof PerformanceObserver<"u")try{Vt=new PerformanceObserver(x=>{if(!tt())for(let m of x.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;Cr.value+=1;let I=Math.round(m.duration);w(`net ${I}ms ${m.name.slice(0,90)}`)}}),Vt.observe({type:"resource",buffered:!0})}catch{}yt?.()}},z=()=>{Jr&&(clearTimeout(Jr),Jr=null)},O=()=>{mo(),z()},se={setEnabled:x=>{x?qr():mo()}};Q.current=se,C.current&&qr();let me=qe.isPayPalTeardownMessage,kt=x=>{if(tt()||me(x))return;let m=(0,So.applyFriendlyMessageOverride)(x)??x;(0,Xe.invokeMerchantCallback)(()=>mr.current?.(m))},Wt=(x,m)=>{if(be||eo)return;eo=!0,Ut=!0,O(),to();let I=bd({kind:x,generationActive:!0,automaticRetryAllowed:Me,automaticRetryUsed:Ot.current});if(I.action==="retry"){Ot.current=!0,Be(!1),X(!1),nt(!0),Xt.current?.("retrying"),Vn=setTimeout(()=>{be||ut(Le=>Le+1)},hd);return}if(Be(!1),X(!1),nt(!1),ue(!0),I.action!=="ignore"){if(Xt.current?.("exhausted"),I.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",m);return}if(I.report){let Le=(0,we.classifyExternalMethodFailure)({code:Ul(x,m),message:m},{inAppBrowser:Ae.inAppBrowser,handoffObserved:!1});Le.popupBlocked&&j.markBlocked(),ae.error({errorCode:Le.popupBlocked?Le.errorCode:I.report.errorCode,stage:I.report.stage,operationOutcome:I.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:Le.terminalReason})}zt.current||(zt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ul(x,m)))}};ue(!1);let Ve=async(x,m=Zt.current)=>{if(tt())return;let I=m?.sessionId??e;if(qt.current){await qt.current(x,{sessionId:I,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let Le=ae.startTiming();ae.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Ze=()=>{ae.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ae.performance({stage:"processing",durationMs:ae.elapsed(Le),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let He=(0,qe.buildPayPalProcessPaymentRequest)({body:x,sessionId:I,nonce:m?.nonce??Dr.current,accountPatch:m?.accountPatch,session:In.current,email:Jt.current}),Ye=await new li.PaymentAPI(ke,{telemetry:!1}).processPayment(He.userId,He.params);if(Ye.ok){if(Ut||be&&mt.current)return;Ze(),ae.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Xe.invokeMerchantCallback)(()=>Ar.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(tt())return;let br=await Ye.json().catch(()=>null),de=(0,qe.describePayPalProcessFailure)(br),Sr=de.message;Ze(),Ye.status===400&&(typeof br?.declineCode=="string"||!Array.isArray(br?.fields))?ae.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Ye.status===400||Ye.status===422?ae.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):ae.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Sd(Ye.status),failureCategory:Ye.status>=500?"server_error":void 0}),kt(Sr),(0,Xe.invokeMerchantCallback)(()=>Fr.current?.(wr("paypal",Sr,{code:de.code,declineCode:de.declineCode})));return}catch(He){if(tt())return;Ze(),ae.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let It=(0,qe.friendlyPayPalFailureMessage)(He instanceof Error?He.message:void 0);kt(It),(0,Xe.invokeMerchantCallback)(()=>Fr.current?.(wr("paypal",It)));return}},oe=()=>new qe.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),te=x=>tt()?Promise.reject(oe()):Promise.resolve(x),Je=async x=>{if(x.ok){ae.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Xe.invokeMerchantCallback)(()=>Ar.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let m=await x.json().catch(()=>null),I=(0,qe.describePayPalProcessFailure)(m);ae.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Xe.invokeMerchantCallback)(()=>Fr.current?.(wr("paypal",I.message,{code:I.code,declineCode:I.declineCode})))},Ee=()=>{let x=Zt.current;jt("approved"),x&&(ir.current.delete(x.surfaceKey),Ce(x.generation)),Zt.current=null},it=async x=>{if(tt())throw oe();lr||jn();let m=Zt.current,I=m?.sessionId??e,Le=m?.nonce??Dr.current;ae.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Ze;try{Ze=await new li.PaymentAPI(ke,{telemetry:!1}).createSessionIntent(I,Le??"",(0,qe.buildPayPalSessionIntentRequest)(Vr),{idempotencyKey:yn})}catch(He){throw ae.error({...(0,qe.classifyTelemetryFailure)(He,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),He}if(tt())throw oe();if((0,qe.isSettledSessionIntent)(Ze))throw await Je(Ze.response),Ee(),new qe.FloPayError("PayPal checkout already settled.","api_error",{code:Nl});if(Ze.provider!=="paypal"||Ze.providerObjectType!==ne)throw new Error(x);return ae.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Ze.providerObjectId},q=(x,m)=>{let I=m?.nonce??Dr.current;if(!I)return;let Le=m?.sessionId??e,Ze=(0,qe.resolvePayPalDeclineReason)(x);new li.PaymentAPI(ke,{telemetry:!1}).reportSessionIntentDecline(Le,I,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ze}).catch(()=>{})},ee=je;w("loadScript:scheduled (deferred 1 tick)");let Bt=null,Et=setTimeout(()=>{if(be){w("loadScript:skipped (cancelled before defer ran)");return}w("loadScript:start");let x=ve==="live"?"production":ve,m={};ne==="subscription"?m={intent:"subscription",vault:!0}:ne==="order"&&(m={intent:"capture"}),Bt=(0,zl.loadScript)({clientId:c,currency:y,...m,...x?{environment:x}:{},...x==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let I=!1;Bt.then(Le=>{if(I=!0,w(`loadScript:resolved inactive=${tt()} ns=${!!Le} buttons=${!!Le?.Buttons}`),tt())return;if(!Le?.Buttons){w("FAIL: namespace missing Buttons factory"),Wt("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}ae.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),ae.performance({stage:"provider_ready",durationMs:ae.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ae.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Ze=async(Mt,xt)=>{if(tt()||Ge.current!==ee)return;let Ie=Mt.vaultSetupToken??Mt.subscriptionID??Mt.orderID??"",vt=Ie?nn.current.get(Ie):ir.current.get(ee);if(!(!vt||!Tn(vt.generation))&&Ce(vt.generation)){nn.current.delete(Ie),ir.current.delete(vt.surfaceKey),jt("approved");try{if(X(!0),(0,Xe.invokeMerchantCallback)(()=>mr.current?.(null)),!Ie)throw new qe.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let re=(0,qe.resolvePayPalApprovalIdentity)({accountPatch:vt.accountPatch,email:Jt.current,billingName:qn.current,session:In.current});if((0,qe.needsPayPalPayerDetails)(re))try{re=(0,qe.mergePayPalPayerIdentity)(re,await xt?.order?.get?.())}catch{}if((ar.current||wt)&&!(0,qe.isValidEmail)(re.email)){let Yt=await pt("PayPal",re);if(!Yt)return;re=Yt}(0,qe.isValidEmail)(re.email)&&(vt.accountPatch=(0,Cn.compactBuyerIdentity)({...vt.accountPatch,...re}),await ar.current?.(re));let _r=(0,qe.buildPayPalTokenizedBody)(Ie,Vr);await Ve(_r,vt)}catch(re){kt(re instanceof Error?re.message:"PayPal capture failed.")}finally{tt()||X(!1)}}},He=Mt=>{let xt=fe?()=>te(fe):()=>it(Mt);return async()=>Lt(await xt())},It=Le.Buttons({style:{layout:"horizontal",height:ci,tagline:!1},...ot==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Mt,xt)=>{if(tt()){await xt.reject();return}jn();let Ie=tr.current,vt={};if(Ie)try{let Yt=await Ie("paypal");if(tt()){await xt.reject();return}if(!Yt.proceed){Zt.current=null,ir.current.delete(ee),await xt.reject();return}vt={sessionId:Yt.sessionId,accountPatch:Yt.accountPatch,nonce:Yt.nonce}}catch(Yt){w(`onClick:runBeforeButtonClick rejected msg=${(Yt instanceof Error?Yt.message:String(Yt)).slice(0,120)}`),Zt.current=null,ir.current.delete(ee),await xt.reject();return}(0,Xe.invokeMerchantCallback)(()=>Yr.current?.("paypal"));let re=mn(),_r={generation:re,surfaceKey:ee,...vt};Zt.current=_r,ir.current.set(ee,_r),We.current={...K,attempt:re},await xt.resolve(),ae.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ae.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),dt.current=ae.startTiming()},createOrder:ne==="order"?He("Failed to create PayPal order."):void 0,createSubscription:ne==="subscription"?He("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ne==="setup_token"?async()=>Lt(await it("Failed to create PayPal setup token.")):void 0,onApprove:Ze,onCancel:()=>{if(tt())return;let Mt=ir.current.get(ee)??Zt.current,xt=Mt&&Tn(Mt.generation)?(0,qe.buildPayPalCancelEvent)(Mt.sessionId??e,Vr):null;Mt&&ir.current.delete(Mt.surfaceKey),Zt.current=null,jt("cancelled"),ae.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),xe.current=!0,Mn({generation:Mt?.generation,remount:!0,focus:!1}),xt&&(0,Xe.invokeMerchantCallback)(()=>st.current?.(xt))},onError:Mt=>{if(Mt instanceof qe.FloPayError&&Mt.code===Nl)return;let xt=Mt instanceof Error?Mt.message:"PayPal failed to render.";if(tt()||Ge.current!==ee){me(xt)||at(rr());return}if(an){let Ie=ir.current.get(ee)??Zt.current;if(!Ie||!Tn(Ie.generation)){if(me(xt)){!Ie&&!vr()&&Ce();return}at(Ie||vr()?"stale_attempt":"no_current_attempt");return}if(w(`onError rendered=${an} msg=${xt.slice(0,120)}`),me(xt)){Ce(Ie.generation);return}let{errorCode:vt,popupBlocked:re,providerDeclined:_r,terminalReason:Yt}=(0,we.classifyExternalMethodFailure)(Mt,{inAppBrowser:Ae.inAppBrowser,handoffObserved:Z.current===Ie.generation});if(re&&j.markBlocked(),jt(Yt),_r){ae.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Yt}),q(Mt,Ie),(0,Xe.invokeMerchantCallback)(()=>Fr.current?.(wr("paypal",xt))),ir.current.delete(Ie.surfaceKey),Zt.current=null,Ce(Ie.generation);return}ae.error({errorCode:vt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Yt}),ir.current.delete(Ie.surfaceKey),Zt.current=null,Mn({generation:Ie.generation,remount:!0,showRetry:!0,focus:!0}),Pr(Mt,{code:"paypal_runtime_failed",popupBlocked:re,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ot,terminalReason:Yt});return}w(`onError rendered=${an} msg=${xt.slice(0,120)}`),Wt(me(xt)?"teardown":"pre_ready_callback",xt)}}),Ye=It.isEligible();if(w(`isEligible=${Ye}`),ae.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Ye){Be(!1),Wt("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}An=!0,xn=It,yt=()=>{if(!Zr||fn||tt()||an)return;fn=!0,w(`container:dims ${nr(sn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Wn=new MutationObserver(xt=>{if(!tt()){for(let Ie of xt)if(Ie.type==="childList")Ie.addedNodes.forEach(vt=>{if(!(vt instanceof Element))return;let re=vt.tagName.toLowerCase(),_r=(vt.getAttribute("title")??"").slice(0,40),Yt=re==="iframe"?` ${Wr(vt)}`:"";w(`child+ ${re}${_r?` title="${_r}"`:""}${Yt} dims=${nr(vt)}`)});else if(Ie.type==="attributes"&&Ie.target instanceof Element){let vt=Ie.target;if(vt.tagName.toLowerCase()!=="iframe")continue;let re=Ie.attributeName;(re==="src"||re==="srcdoc")&&w(`attr~ iframe ${re}=${re==="srcdoc"?`[${(vt.getAttribute("srcdoc")??"").length}ch]`:Ir(vt.getAttribute("src"))} dims=${nr(vt)}`)}}}),Wn.observe(sn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Mt=xt=>{if(tt()||an)return;let Ie=sn.querySelectorAll("iframe"),vt=typeof document<"u"&&"hasStorageAccess"in document;w(`watchdog:${xt} container=${nr(sn)} children=${sn.childElementCount} iframes=${Ie.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${vt} paypalNetRequests=${Cr.value}`),Ie.forEach((re,_r)=>{let Yt=(re.getAttribute("title")??"").slice(0,40);w(` iframe[${_r}] ${nr(re)}${Yt?` title="${Yt}"`:""} ${Wr(re)}`);let To=_o(re);To&&w(` ${To}`)}),gn.length===0&&w(" (no PayPal/zoid window errors captured)")};Xr.push(setTimeout(()=>Mt("3s"),3e3)),Xr.push(setTimeout(()=>Mt("8s"),8e3)),Xr.push(setTimeout(()=>Mt("15s"),15e3))},yt(),w("render:start");let de=ae.startTiming();Jr=setTimeout(()=>{tt()||an||(w("watchdog:11s retryable render timeout"),Wt("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Pd);let Sr=It.render(sn);(async()=>{try{if(await Sr,w(`render:resolved inactive=${tt()}`),O(),tt()){to();return}an=!0,Be(!0),nt(!1),Xt.current?.("ready"),ae.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),ae.performance({stage:"checkout_render",durationMs:ae.elapsed(de),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Mt){let xt=Mt instanceof Error?Mt.message:"PayPal failed to render.";w(`render:rejected msg=${xt.slice(0,120)}`),O(),Wt(me(xt)?"teardown":"render_rejected",xt)}})()}).catch(Le=>{let Ze=Le instanceof Error?Le.message:"PayPal operation failed.";w(`provider:failed msg=${Ze.slice(0,120)}`);let He="script_rejected";I&&me(Ze)?He="teardown":I&&An&&(He="render_rejected"),Wt(He,Ze)})},0);return()=>{be=!0,clearTimeout(Et),Vn&&clearTimeout(Vn),O(),Q.current===se&&(Q.current=null),to(),dt.current=null,We.current=null}},[Me,ke,c,y,p,ne,ot,De,e,fe,je,J,pt,wt,w,jt]);let on=F?(0,bn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ft?"#fef2f2":"#f3f4f6",border:`1px solid ${Ft?"#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=${Pe} failed=${Ft})`,ce.length===0?`
1
+ "use strict";var Qc=Object.create;var Qa=Object.defineProperty;var ed=Object.getOwnPropertyDescriptor;var td=Object.getOwnPropertyNames;var rd=Object.getPrototypeOf,nd=Object.prototype.hasOwnProperty;var od=(e,t)=>{for(var r in t)Qa(e,r,{get:t[r],enumerable:!0})},Sl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of td(t))!nd.call(e,a)&&a!==r&&Qa(e,a,{get:()=>t[a],enumerable:!(n=ed(t,a))||n.enumerable});return e};var Qi=(e,t,r)=>(r=e!=null?Qc(rd(e)):{},Sl(t||!e||!e.__esModule?Qa(r,"default",{value:e,enumerable:!0}):r,e)),ad=e=>Sl(Qa({},"__esModule",{value:!0}),e);var Fu={};od(Fu,{DirectPayPalButton:()=>wa,FloPayAutomaticPaymentButton:()=>Cc,FloPayCardSetup:()=>bc,FloPayCardSetupError:()=>Na,FloPayCheckout:()=>Mi,FloPayPaymentMethodSetup:()=>Ac,FloPayProvider:()=>Ra,SplitCardForm:()=>Ei,VaultCardFields:()=>fo,dropThirdPartyOnlyError:()=>Bc.dropThirdPartyOnlyError,useCheckout:()=>Dl,useFloPay:()=>no,usePayPalFloPay:()=>ni});module.exports=ad(Fu);var Bc=require("@flopay/shared");var xi=require("@flopay/js"),Sn=require("@flopay/shared"),Ct=require("react");var Zt=require("react/jsx-runtime");function id(){return(0,Zt.jsxs)(Zt.Fragment,{children:[(0,Zt.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,Zt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Zt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Zt.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,Zt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function sd(){return(0,Zt.jsx)(Zt.Fragment,{children:"Go back"})}function ld(){return(0,Zt.jsx)(Zt.Fragment,{children:"Secure card checkout"})}function qo(e){return e!==void 0&&(e===""||e===null||e===!1)}function jo({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(id,{}):e})}function Vo({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(sd,{}):e})}function ha({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(ld,{}):e})}var wt=require("@flopay/shared"),An=require("@flopay/shared"),Ho=require("@flopay/shared"),wo=require("@flopay/shared");function es(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof wt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function cd(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 wl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,wt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,wt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function kl(e,t){if(t&&(!(e instanceof wt.FloPayError)||e.type==="authentication_error"))return es(e);if(!(e instanceof wt.FloPayError&&cd(e))){if(!t&&!(e instanceof wt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,wt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof wt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof wt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Wo(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let c={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,wt.isCardHolderNamePlaceholder)(c.firstName,c.lastName);if(!(0,wt.isValidEmail)(c.email))return Promise.reject(new wt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[g,_]of Object.entries(c)){if(p&&g.endsWith("Name")||typeof _!="string")continue;let E=_.trim();E&&(m[g]=E)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function Rl(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 ts(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 El(e,t){let r=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],n=r.reduce((s,c)=>s+(c.overrideAmount??c.totalAmount??0),0),a=e.currency??r.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:r.map((s,c)=>({uuid:`synthetic-${s.type??"item"}-${c}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??a,metadata:s.metadata??null}))}}function rs(e,t){return t?{...e,...t}:e}function br(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,s=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,c=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...s?{declineCode:s}:{},...c?{sessionId:c}:{}}}var _l=new WeakMap;function Il(e,t){return typeof e=="object"&&e!==null&&_l.set(e,t?{sessionId:t}:{}),e}function Tl(e){return typeof e=="object"&&e!==null?_l.get(e):void 0}function mo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function eo(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function to(e){return e?.status==="authorized"||e?.status==="complete"}function yo(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 Ml(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ei(e){let t=Ml(e);return new wt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ti(e){return e instanceof wt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function $o(e){return Ml(e)?new wt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new wt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new wt.FloPayError(wt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function Pa(e,t){return e==="processing"||(0,wt.isMoneySettledOutcome)(e,t)}function xl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Al(e,t){let r=e;if((0,wt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:c}=await r.retrieveSetupIntent(t);if(c)throw new wt.FloPayError(c.message??"Failed to retrieve setup intent.","api_error",{...c.code?{code:c.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new wt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var dd=["apple_pay","google_pay"];function Fl(e,t="automatic",r){let n=(0,wt.resolveSetupFutureUsage)(r,dd,"wallet");return{...(0,wt.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var ud=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ns(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:ud.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function va(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var io=require("@flopay/js"),Ue=require("@flopay/shared"),P=Qi(require("react"),1);var os=require("react"),hn=(0,os.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Fn=(0,os.createContext)({session:null,loading:!1,error:null});var ci=require("@flopay/js"),$e=require("@flopay/shared"),zl=require("@paypal/paypal-js"),R=require("react");var ri=require("@flopay/shared"),Bn=require("react"),Pn=require("@flopay/shared"),ro=require("react/jsx-runtime");function Ko(){let[e,t]=(0,Bn.useState)(null),r=(0,Bn.useRef)(null),n=(0,Bn.useRef)(0),a=(0,Bn.useCallback)((c,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:c,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,Bn.useCallback)(c=>{let p=r.current;r.current=null,t(null),p?.(c)},[]);return(0,Bn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function Go({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[c,p]=(0,Bn.useState)(e.email?.trim()??""),m=(0,ri.isValidEmail)(c.trim());return(0,ro.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,ro.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,ro.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,ro.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:c,onChange:g=>p(g.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,ro.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,ro.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,ro.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,ri.compactBuyerIdentity)({...e,email:c.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var we=require("@flopay/shared");var Bl=require("@flopay/shared"),Ca=require("react");function no(){return(0,Ca.useContext)(hn).flopay}function ni(){return(0,Ca.useContext)(hn).paypalFlopay??null}function Dl(){return(0,Ca.useContext)(Fn)}function Ol(){return(0,Ca.useContext)(hn).billingApiUrl||(0,Bl.resolveBillingApiUrl)()}var pd=require("@flopay/shared"),Wn=require("@flopay/shared"),$n=require("@flopay/shared");var Yo=require("@flopay/shared"),Ro=require("react");var oi=require("react"),ko=typeof window>"u"?oi.useEffect:oi.useLayoutEffect;var as=require("@flopay/shared");function Xo(e,t){let r=(0,Ro.useRef)(e);r.current=e;let n=(0,Ro.useRef)(new Set),a=(0,Ro.useRef)(t),s=(0,Ro.useRef)(t);return ko(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Ro.useCallback)(c=>{if(s.current!==t)return;let p=(0,Yo.projectFloInstrument)(c);if(p){if(Yo.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,Yo.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Qe=require("@flopay/shared");var Ll=require("react"),ba=(0,Ll.createContext)(null);function ai(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ii="provider.callback.ignored";function si(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var md=Symbol.for("@flopay/js.telemetry.bridge.v1"),yd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function fd(){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 gd(e){let t=fd(),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 li(e){let t=globalThis[yd];return gd(t?.(e)??{})}function Sr(e){if(e)return e[md]}var fr=require("react");function Sa(e,t){let r=(0,fr.useRef)(0),n=(0,fr.useRef)(null),a=(0,fr.useRef)(null),s=(0,fr.useRef)(e),c=(0,fr.useRef)(t?.onHandoffObserved),p=(0,fr.useRef)(t?.defersMissingTerminal),m=(0,fr.useRef)(t?.onMissingTerminalDeferred);(0,fr.useEffect)(()=>{s.current=e,c.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let g=(0,fr.useCallback)((y=a.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),_=(0,fr.useCallback)(y=>{g();let h=r.current+1;return r.current=h,n.current=null,a.current={generation:h,method:y,timer:null,yieldedControl:!1},h},[g]),E=(0,fr.useCallback)(y=>{let h=a.current;return y!==void 0&&h?.generation!==y?!1:(g(h),a.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[g]),I=(0,fr.useCallback)(y=>{let h=a.current,ge=y??h?.generation??r.current;(y===void 0||h?.generation===y)&&(g(h),a.current=null),n.current=ge},[g]),H=(0,fr.useCallback)(y=>n.current===(y??r.current),[]),T=(0,fr.useCallback)(y=>a.current?.generation===y&&n.current!==y,[]),Y=(0,fr.useCallback)(()=>{let y=a.current;y&&(g(y),!y.yieldedControl&&(y.yieldedControl=!0,c.current?.(y.method)))},[g]),F=(0,fr.useCallback)(()=>{let y=a.current;!y?.yieldedControl||document.visibilityState!=="visible"||(g(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"})}},we.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[g]);return(0,fr.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?F():Y()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",Y),window.addEventListener("focus",F),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",Y),window.removeEventListener("focus",F),g()}},[g,Y,F]),{startAttempt:_,finishAttempt:E,invalidateAttempt:I,isAttemptInvalidated:H,isAttemptCurrent:T,generationRef:r}}var vn=require("react/jsx-runtime"),di=45,hd=1e3,Pd=11e3,Nl="paypal_intent_settled",vd={width:"100%",minHeight:di,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"},Cd={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 bd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Cd[e.kind]??null}}function Ul(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,we.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function Sd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function ql({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:c,environment:p,currency:m,isSubscription:g,providerObjectType:_,approvalPresentation:E,onTokenizedBody:I,onComplete:H,onErrorChange:T,onDecline:Y,onCancel:F,onTechnicalFailure:y,isProcessing:h=!1,onLoadStateChange:ge,onInitializationStateChange:w,allowAutomaticRetry:Te=!0,onButtonClick:x,runBeforeButtonClick:ie,session:he,existingOrderId:fe,telemetry:ke,telemetryContext:mt,onInstrument:Je,debug:A=!1}){let kt=no(),tt=Xo(Je,e),Ve=(0,R.useMemo)(()=>{if(kt)return null;let N=li({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:$e.SDK_VERSION,enabled:ke!==!1});return N.setCheckoutContext(mt??{}),N.beginCheckout(mt??{}),N},[r,kt,ke,mt?.checkoutMode,mt?.layout]),me=(0,R.useMemo)(()=>Sr(kt),[kt]);(0,R.useEffect)(()=>()=>{Ve&&Ve.flush().catch(()=>{}).finally(()=>Ve.destroy())},[Ve]);let K=(0,R.useMemo)(()=>({error:N=>{me?me.error(N):Ve?.error(N),tt({class:"technical_error",errorCode:N.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":N.errorCode,requestCategory:N.requestCategory,provider:N.provider})},log:N=>{me?me.log(N):Ve?.log(N),tt({class:"lifecycle",name:N.name,provider:N.provider})},performance:N=>{me?me.performance(N):Ve?.performance(N)},terminal:N=>{me?me.terminal(N):Ve?.terminal(N)},startTiming:()=>me?.now()??Ve?.now()??0,elapsed:N=>me?.elapsed(N)??Math.max(0,(Ve?.now()??N)-N)}),[tt,me,Ve]),W=(0,R.useRef)(null),Fe=(0,R.useRef)(0),lt=(0,R.useRef)(null),He=(0,R.useRef)(null),J=(0,R.useRef)(null),D=(0,R.useContext)(ba),se=(0,R.useRef)(null);se.current||(se.current=ai());let O=D??se.current,be=(0,R.useRef)(null),Me=(0,R.useRef)(!1),[Pe,Be]=(0,R.useState)(!1),[M,at]=(0,R.useState)(!1),[Ke,yt]=(0,R.useState)(0),Ze=(0,R.useRef)(0),[Ge,_t]=(0,R.useState)(!1),Ut=(0,R.useRef)(!1),qt=(0,R.useRef)(!1),[Ft,de]=(0,R.useState)(!1),[ue,X]=(0,R.useState)(!1),{request:bt,collect:ft,finish:V}=Ko(),rt=(0,R.useRef)({sessionId:e,required:(0,$e.paypalProviderIdentityRequired)(n,he)});rt.current.sessionId!==e&&(rt.current={sessionId:e,required:(0,$e.paypalProviderIdentityRequired)(n,he)});let Rt=rt.current.required,Re=(0,R.useMemo)(()=>r.replace(/\/+$/,""),[r]),q=he?.gateways?.paypal?.providerObjectType??_,oe=q??(g?"subscription":"order"),[xe]=(0,R.useState)(Wn.detectPayPalEnvironment),Lt=he?.gateways?.paypal?.approvalPresentation??E,it=(0,$n.resolvePayPalPresentationMode)(xe,Lt==="app_switch"?"app_switch":void 0,oe),De=(0,$e.usesPayPalVaultedChannel)(q),Oe=(0,R.useMemo)(()=>JSON.stringify([Re,c,m,p??"",oe,De,it,e,fe??""]),[Re,c,m,p,fe,oe,De,it,e]),Tt=(0,R.useRef)(Oe),u=Tt.current!==Oe,C=(0,R.useRef)(A),Q=(0,R.useRef)(null),[le,L]=(0,R.useState)([]),k=(0,R.useCallback)(N=>{C.current&&L(dt=>[...dt,`${new Date().toISOString().slice(11,23)} ${N}`])},[]);(0,R.useEffect)(()=>{C.current=A,A&&k("debug:enabled"),Q.current?.setEnabled(A)},[k,A]);let jt=(0,R.useRef)(I),Mr=(0,R.useRef)(H),dr=(0,R.useRef)(T),xr=(0,R.useRef)(Y),ct=(0,R.useRef)(F),Gr=(0,R.useRef)(y),Yr=(0,R.useRef)(x),Ar=(0,R.useRef)(ge),Gt=(0,R.useRef)(w),nr=(0,R.useRef)(s),Qt=(0,R.useRef)(ie),Rn=(0,R.useRef)(he),Yt=(0,R.useRef)(n),Nn=(0,R.useRef)(a),Fr=(0,R.useRef)(t),Xt=(0,R.useRef)(null),or=(0,R.useRef)(new Map),on=(0,R.useRef)(new Map),gt=(0,R.useRef)(!1),Mt=(0,R.useRef)(e);Mt.current=e;let[Br]=(0,R.useState)(si);(0,R.useEffect)(()=>(gt.current=!0,()=>{gt.current=!1}),[]),(0,R.useEffect)(()=>{jt.current=I},[I]),(0,R.useEffect)(()=>{nr.current=s},[s]),(0,R.useEffect)(()=>{Mr.current=H},[H]),(0,R.useEffect)(()=>{dr.current=T},[T]),(0,R.useEffect)(()=>{xr.current=Y},[Y]),(0,R.useEffect)(()=>{ct.current=F},[F]),(0,R.useEffect)(()=>{Gr.current=y},[y]),(0,R.useEffect)(()=>{Yr.current=x},[x]),(0,R.useEffect)(()=>{Ar.current=ge},[ge]),(0,R.useEffect)(()=>{Gt.current=w},[w]),(0,R.useEffect)(()=>{Qt.current=ie},[ie]),(0,R.useEffect)(()=>{Rn.current=he},[he]),(0,R.useEffect)(()=>{Yt.current=n},[n]),(0,R.useEffect)(()=>{Nn.current=a},[a]),(0,R.useEffect)(()=>{Fr.current=t},[t]),(0,R.useEffect)(()=>{Ze.current=Ke},[Ke]),(0,R.useEffect)(()=>{Ge&&be.current?.focus()},[Ge,Ke]);let ar=(0,R.useCallback)(()=>{window.setTimeout(()=>{be.current?.focus()},0)},[]),Jt=(0,R.useCallback)(()=>{Be(!1),yt(N=>N+1)},[]),Ur=(0,R.useCallback)(()=>{_t(!1),(W.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??W.current)?.focus?.()},[]);(0,R.useEffect)(()=>{!Pe||!Me.current||(Me.current=!1,Ur())},[Ur,Pe,Ke]);let hr=(0,R.useCallback)((N,dt)=>{let te=dt?.popupBlocked??(0,we.isPopupBlockedError)(N);te&&O.markBlocked();let Se=(0,we.buildExternalMethodRecoveryMessage)("PayPal",te,xe.inAppBrowser),Dt=Gr.current;if(Dt){let $t=te&&xe.inAppBrowser?new $e.FloPayError(Se,"api_error",{code:dt?.code??"paypal_popup_blocked"}):N;Dt("paypal",$t,dt);return}if(N instanceof $e.FloPayError&&N.code==="checkout_processing_timeout"){dr.current?.(N.message);return}dr.current?.(Se)},[O,xe.inAppBrowser]),Vt=(0,R.useCallback)(N=>{let dt=lt.current,te=He.current;dt===null||!te||(K.log({...te,popupCapability:O.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:N}),K.performance({...te,popupCapability:O.current(),stage:"overlay_return",durationMs:K.elapsed(dt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:N}),lt.current=null)},[O,K]),Dr=(0,R.useCallback)((N,dt,te)=>{let Se=He.current;Vt("overlay_timeout"),Se&&K.error({...Se,popupCapability:O.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),hr(dt,{...te,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:"overlay_timeout"}),_t(!0),Jt(),ar()},[Vt,ar,hr,O,it,Jt,K]),kr=(0,R.useCallback)(()=>{O.markAvailable();let N=He.current;N&&(J.current=N.attempt,K.log({...N,popupCapability:O.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[O,K]),Le=(0,R.useCallback)(()=>!0,[]),Or=(0,R.useCallback)(()=>{let N=He.current;if(!N)return;let dt=lt.current;K.performance({...N,popupCapability:O.current(),stage:"overlay_return",durationMs:dt===null?0:K.elapsed(dt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[O,K]),{finishAttempt:Xr,generationRef:Xn,invalidateAttempt:Pr,isAttemptCurrent:an,isAttemptInvalidated:sn,startAttempt:En}=Sa(Dr,{onHandoffObserved:kr,defersMissingTerminal:Le,onMissingTerminalDeferred:Or}),Wt=(0,R.useCallback)(()=>(_t(!1),En("paypal")),[En]),Ce=(0,R.useCallback)(N=>{Pr(N?.generation),N?.showRetry&&_t(!0),N?.remount&&Jt(),N?.focus!==!1&&ar()},[ar,Pr,Jt]),ln=N=>{let dt=Xt.current;return dt&&on.current.set(N,dt),N};(0,R.useEffect)(()=>{Tt.current!==Oe&&(Tt.current=Oe,Ut.current=!1,qt.current=!1,Be(!1),at(!1),de(!1),Gt.current?.("loading"))},[Oe]),(0,R.useEffect)(()=>{(0,Qe.invokeMerchantCallback)(()=>Ar.current?.(Pe&&!Ft))},[Pe,Ft]);let zr=(0,$e.normalizeGatewayEnvironment)(p);(0,R.useEffect)(()=>{let N={attempt:Xn.current+1,inAppBrowser:xe.inAppBrowser,appFamily:xe.appFamily,popupCapability:O.current(),presentationMode:it},dt=()=>({...He.current??N,popupCapability:O.current()}),te={error:f=>K.error({...f,...dt()}),log:f=>K.log({...f,...dt()}),performance:f=>K.performance({...f,...dt()}),terminal:f=>K.terminal({...f,...dt()}),startTiming:K.startTiming,elapsed:K.elapsed},Se=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",Dt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(k(`mount clientId=${Se} env=${p??"(unset)"}\u2192${zr??"live"} ccy=${m} sub=${g}`),k(`ua=${Dt.slice(0,80)}${Dt.length>80?"\u2026":""}`),!c){k("FAIL: clientId empty \u2014 gateway misconfigured"),de(!0),te.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!W.current){k("FAIL: containerRef not attached");return}Fe.current=te.startTiming(),te.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let $t=!1,nt=!1,Ye=()=>$t||nt,Jr=f=>{let S=gt.current,ne=S?f:"torn_down";S&&k(`onError ignored reason=${ne}`),Br.take(Mt.current)&&te.log({name:ii,stage:"provider_ready",reason:ne,provider:"paypal",paymentMethodCategory:"paypal"})},Un=()=>Mt.current===e?"stale_attempt":"session_changed",er=De?oe:void 0,In,Jn=!1,Zn=()=>{In=(0,$e.generateIdempotencyKey)(),In||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Jn=!0},Tn=null,lo=!1,Qn=null,go=!1,yn=()=>{!Qn||go||(go=!0,Qn.close().catch(()=>{}))},jr=!1,co=!1,Nt=W.current,Zr=null,Qr=null,cn=[],dn=null,st=!1,ur=!1,vr=null,Rr=f=>{if(!f||typeof f.getBoundingClientRect!="function")return"(no rect)";let S=f.getBoundingClientRect();return`${Math.round(S.width)}\xD7${Math.round(S.height)}`},ho=f=>{if(!f)return"(empty)";try{let S=new URL(f,typeof window>"u"?"https://localhost":window.location.href),ne=S.pathname.toLowerCase();return ne.includes("checkcaptcha")||ne.includes("captcha")?`CAPTCHA(${S.host}${ne})`:ne.includes("risk")||ne.includes("challenge")?`RISK(${S.host}${ne})`:ne.includes("smart/buttons")?`smart-buttons(${S.host})`:`${S.host}${ne}`.slice(0,100)}catch{return f.slice(0,80)}},zn=f=>{let S=f.getAttribute("src"),ne=f.getAttribute("srcdoc"),qe=f.getAttribute("name"),je=f.getAttribute("sandbox"),ye=[];return S&&ye.push(`src=${ho(S)}`),ne&&ye.push(`srcdoc[${ne.length}ch]`),!S&&!ne&&ye.push("src=(empty) srcdoc=(empty)"),qe&&ye.push(`name=${qe.slice(0,40)}`),je!==null&&ye.push(`sandbox="${je.slice(0,40)}"`),ye.join(" ")},uo=f=>{if(!(f instanceof HTMLIFrameElement))return"";try{let S=f.contentDocument;if(!S)return"cd=null";let ne=S.body?.children.length??0,qe=S.body?.innerHTML.length??0,je=S.head?.innerHTML.length??0;return`cd=same-origin readyState=${S.readyState} body[${ne}children,${qe}ch] head[${je}ch]`}catch(S){return`cd=cross-origin(${S.message.slice(0,30)})`}},Vr=[],Er=f=>{if(Ye())return;let S=f.message??String(f.error??"(no message)");S&&(S.toLowerCase().includes("paypal")||S.toLowerCase().includes("zoid")||S.toLowerCase().includes("postrobot")||S.toLowerCase().includes("storage"))&&(k(`window:error ${S.slice(0,140)}`),Vr.push(S))},po=f=>{if(Ye())return;let S=f.reason instanceof Error?f.reason.message:String(f.reason??"(no reason)");S&&(S.toLowerCase().includes("paypal")||S.toLowerCase().includes("zoid")||S.toLowerCase().includes("postrobot")||S.toLowerCase().includes("storage"))&&(k(`window:rejection ${S.slice(0,140)}`),Vr.push(S))},Lr={value:0},U=()=>{Zr?.disconnect(),Zr=null,Qr?.disconnect(),Qr=null;for(let f of cn.splice(0))clearTimeout(f);ur=!1,st&&typeof window<"u"&&(window.removeEventListener("error",Er),window.removeEventListener("unhandledrejection",po)),st=!1},z=()=>{if(!(st||Ye()||jr)){if(st=!0,Vr.length=0,Lr.value=0,typeof window<"u"&&(window.addEventListener("error",Er),window.addEventListener("unhandledrejection",po)),typeof PerformanceObserver<"u")try{Qr=new PerformanceObserver(f=>{if(!Ye())for(let S of f.getEntries()){if(!S.name.toLowerCase().includes("paypal"))continue;Lr.value+=1;let ne=Math.round(S.duration);k(`net ${ne}ms ${S.name.slice(0,90)}`)}}),Qr.observe({type:"resource",buffered:!0})}catch{}vr?.()}},ce=()=>{dn&&(clearTimeout(dn),dn=null)},ve=()=>{U(),ce()},xt={setEnabled:f=>{f?z():U()}};Q.current=xt,C.current&&z();let zt=$e.isPayPalTeardownMessage,ze=f=>{if(Ye()||zt(f))return;let S=(0,wo.applyFriendlyMessageOverride)(f)??f;(0,Qe.invokeMerchantCallback)(()=>dr.current?.(S))},Z=(f,S)=>{if($t||lo)return;lo=!0,nt=!0,ve(),yn();let ne=bd({kind:f,generationActive:!0,automaticRetryAllowed:Te,automaticRetryUsed:Ut.current});if(ne.action==="retry"){Ut.current=!0,Be(!1),X(!1),at(!0),Gt.current?.("retrying"),Tn=setTimeout(()=>{$t||yt(qe=>qe+1)},hd);return}if(Be(!1),X(!1),at(!1),de(!0),ne.action!=="ignore"){if(Gt.current?.("exhausted"),ne.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",S);return}if(ne.report){let qe=(0,we.classifyExternalMethodFailure)({code:Ul(f,S),message:S},{inAppBrowser:xe.inAppBrowser,handoffObserved:!1});qe.popupBlocked&&O.markBlocked(),te.error({errorCode:qe.popupBlocked?qe.errorCode:ne.report.errorCode,stage:ne.report.stage,operationOutcome:ne.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:qe.terminalReason})}qt.current||(qt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ul(f,S)))}};de(!1);let re=async(f,S=Xt.current)=>{if(Ye())return;let ne=S?.sessionId??e;if(jt.current){await jt.current(f,{sessionId:ne,accountPatch:S?.accountPatch,nonce:S?.nonce});return}let qe=te.startTiming();te.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let je=()=>{te.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"processing",durationMs:te.elapsed(qe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ye=(0,$e.buildPayPalProcessPaymentRequest)({body:f,sessionId:ne,nonce:S?.nonce??Fr.current,accountPatch:S?.accountPatch,session:Rn.current,email:Yt.current}),ee=await new ci.PaymentAPI(Re,{telemetry:!1}).processPayment(ye.userId,ye.params);if(ee.ok){if(nt||$t&&gt.current)return;je(),te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Qe.invokeMerchantCallback)(()=>Mr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ye())return;let Cr=await ee.json().catch(()=>null),Po=(0,$e.describePayPalProcessFailure)(Cr),To=Po.message;je(),ee.status===400&&(typeof Cr?.declineCode=="string"||!Array.isArray(Cr?.fields))?te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ee.status===400||ee.status===422?te.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):te.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Sd(ee.status),failureCategory:ee.status>=500?"server_error":void 0}),ze(To),(0,Qe.invokeMerchantCallback)(()=>xr.current?.(br("paypal",To,{code:Po.code,declineCode:Po.declineCode})));return}catch(ye){if(Ye())return;je(),te.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let tr=(0,$e.friendlyPayPalFailureMessage)(ye instanceof Error?ye.message:void 0);ze(tr),(0,Qe.invokeMerchantCallback)(()=>xr.current?.(br("paypal",tr)));return}},Xe=()=>new $e.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ee=f=>Ye()?Promise.reject(Xe()):Promise.resolve(f),ut=async f=>{if(f.ok){te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Qe.invokeMerchantCallback)(()=>Mr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let S=await f.json().catch(()=>null),ne=(0,$e.describePayPalProcessFailure)(S);te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Qe.invokeMerchantCallback)(()=>xr.current?.(br("paypal",ne.message,{code:ne.code,declineCode:ne.declineCode})))},j=()=>{let f=Xt.current;Vt("approved"),f&&(or.current.delete(f.surfaceKey),Xr(f.generation)),Xt.current=null},pe=async f=>{if(Ye())throw Xe();Jn||Zn();let S=Xt.current,ne=S?.sessionId??e,qe=S?.nonce??Fr.current;te.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let je;try{je=await new ci.PaymentAPI(Re,{telemetry:!1}).createSessionIntent(ne,qe??"",(0,$e.buildPayPalSessionIntentRequest)(er),{idempotencyKey:In})}catch(ye){throw te.error({...(0,$e.classifyTelemetryFailure)(ye,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ye}if(Ye())throw Xe();if((0,$e.isSettledSessionIntent)(je))throw await ut(je.response),j(),new $e.FloPayError("PayPal checkout already settled.","api_error",{code:Nl});if(je.provider!=="paypal"||je.providerObjectType!==oe)throw new Error(f);return te.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),je.providerObjectId},Ot=(f,S)=>{let ne=S?.nonce??Fr.current;if(!ne)return;let qe=S?.sessionId??e,je=(0,$e.resolvePayPalDeclineReason)(f);new ci.PaymentAPI(Re,{telemetry:!1}).reportSessionIntentDecline(qe,ne,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:je}).catch(()=>{})},ot=Ke;k("loadScript:scheduled (deferred 1 tick)");let pr=null,Ne=setTimeout(()=>{if($t){k("loadScript:skipped (cancelled before defer ran)");return}k("loadScript:start");let f=zr==="live"?"production":zr,S={};oe==="subscription"?S={intent:"subscription",vault:!0}:oe==="order"&&(S={intent:"capture"}),pr=(0,zl.loadScript)({clientId:c,currency:m,...S,...f?{environment:f}:{},...f==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let ne=!1;pr.then(qe=>{if(ne=!0,k(`loadScript:resolved inactive=${Ye()} ns=${!!qe} buttons=${!!qe?.Buttons}`),Ye())return;if(!qe?.Buttons){k("FAIL: namespace missing Buttons factory"),Z("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}te.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"provider_ready",durationMs:te.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),te.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let je=async(Ae,ht)=>{if(Ye()||Ze.current!==ot)return;let ae=Ae.vaultSetupToken??Ae.subscriptionID??Ae.orderID??"",It=ae?on.current.get(ae):or.current.get(ot);if(!(!It||!an(It.generation))&&Xr(It.generation)){on.current.delete(ae),or.current.delete(It.surfaceKey),Vt("approved");try{if(X(!0),(0,Qe.invokeMerchantCallback)(()=>dr.current?.(null)),!ae)throw new $e.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Et=(0,$e.resolvePayPalApprovalIdentity)({accountPatch:It.accountPatch,email:Yt.current,billingName:Nn.current,session:Rn.current});if((0,$e.needsPayPalPayerDetails)(Et))try{Et=(0,$e.mergePayPalPayerIdentity)(Et,await ht?.order?.get?.())}catch{}if((nr.current||Rt)&&!(0,$e.isValidEmail)(Et.email)){let Bt=await ft("PayPal",Et);if(!Bt)return;Et=Bt}(0,$e.isValidEmail)(Et.email)&&(It.accountPatch=(0,Pn.compactBuyerIdentity)({...It.accountPatch,...Et}),await nr.current?.(Et));let Wr=(0,$e.buildPayPalTokenizedBody)(ae,er);await re(Wr,It)}catch(Et){ze(Et instanceof Error?Et.message:"PayPal capture failed.")}finally{Ye()||X(!1)}}},ye=Ae=>{let ht=fe?()=>Ee(fe):()=>pe(Ae);return async()=>ln(await ht())},tr=qe.Buttons({style:{layout:"horizontal",height:di,tagline:!1},...it==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Ae,ht)=>{if(Ye()){await ht.reject();return}Zn();let ae=Qt.current,It={};if(ae)try{let Bt=await ae("paypal");if(Ye()){await ht.reject();return}if(!Bt.proceed){Xt.current=null,or.current.delete(ot),await ht.reject();return}It={sessionId:Bt.sessionId,accountPatch:Bt.accountPatch,nonce:Bt.nonce}}catch(Bt){k(`onClick:runBeforeButtonClick rejected msg=${(Bt instanceof Error?Bt.message:String(Bt)).slice(0,120)}`),Xt.current=null,or.current.delete(ot),await ht.reject();return}(0,Qe.invokeMerchantCallback)(()=>Yr.current?.("paypal"));let Et=Wt(),Wr={generation:Et,surfaceKey:ot,...It};Xt.current=Wr,or.current.set(ot,Wr),He.current={...N,attempt:Et},await ht.resolve(),te.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),lt.current=te.startTiming()},createOrder:oe==="order"?ye("Failed to create PayPal order."):void 0,createSubscription:oe==="subscription"?ye("Failed to create PayPal subscription."):void 0,createVaultSetupToken:oe==="setup_token"?async()=>ln(await pe("Failed to create PayPal setup token.")):void 0,onApprove:je,onCancel:()=>{if(Ye())return;let Ae=or.current.get(ot)??Xt.current,ht=Ae&&an(Ae.generation)?(0,$e.buildPayPalCancelEvent)(Ae.sessionId??e,er):null;Ae&&or.current.delete(Ae.surfaceKey),Xt.current=null,Vt("cancelled"),te.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Me.current=!0,Ce({generation:Ae?.generation,remount:!0,focus:!1}),ht&&(0,Qe.invokeMerchantCallback)(()=>ct.current?.(ht))},onError:Ae=>{if(Ae instanceof $e.FloPayError&&Ae.code===Nl)return;let ht=Ae instanceof Error?Ae.message:"PayPal failed to render.";if(Ye()||Ze.current!==ot){zt(ht)||Jr(Un());return}if(jr){let ae=or.current.get(ot)??Xt.current;if(!ae||!an(ae.generation)){if(zt(ht)){!ae&&!sn()&&Xr();return}Jr(ae||sn()?"stale_attempt":"no_current_attempt");return}if(k(`onError rendered=${jr} msg=${ht.slice(0,120)}`),zt(ht)){Xr(ae.generation);return}let{errorCode:It,popupBlocked:Et,providerDeclined:Wr,terminalReason:Bt}=(0,we.classifyExternalMethodFailure)(Ae,{inAppBrowser:xe.inAppBrowser,handoffObserved:J.current===ae.generation});if(Et&&O.markBlocked(),Vt(Bt),Wr){te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Bt}),Ot(Ae,ae),(0,Qe.invokeMerchantCallback)(()=>xr.current?.(br("paypal",ht))),or.current.delete(ae.surfaceKey),Xt.current=null,Xr(ae.generation);return}te.error({errorCode:It,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Bt}),or.current.delete(ae.surfaceKey),Xt.current=null,Ce({generation:ae.generation,remount:!0,showRetry:!0,focus:!0}),hr(Ae,{code:"paypal_runtime_failed",popupBlocked:Et,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:Bt});return}k(`onError rendered=${jr} msg=${ht.slice(0,120)}`),Z(zt(ht)?"teardown":"pre_ready_callback",ht)}}),ee=tr.isEligible();if(k(`isEligible=${ee}`),te.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ee){Be(!1),Z("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}co=!0,Qn=tr,vr=()=>{if(!st||ur||Ye()||jr)return;ur=!0,k(`container:dims ${Rr(Nt)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Zr=new MutationObserver(ht=>{if(!Ye()){for(let ae of ht)if(ae.type==="childList")ae.addedNodes.forEach(It=>{if(!(It instanceof Element))return;let Et=It.tagName.toLowerCase(),Wr=(It.getAttribute("title")??"").slice(0,40),Bt=Et==="iframe"?` ${zn(It)}`:"";k(`child+ ${Et}${Wr?` title="${Wr}"`:""}${Bt} dims=${Rr(It)}`)});else if(ae.type==="attributes"&&ae.target instanceof Element){let It=ae.target;if(It.tagName.toLowerCase()!=="iframe")continue;let Et=ae.attributeName;(Et==="src"||Et==="srcdoc")&&k(`attr~ iframe ${Et}=${Et==="srcdoc"?`[${(It.getAttribute("srcdoc")??"").length}ch]`:ho(It.getAttribute("src"))} dims=${Rr(It)}`)}}}),Zr.observe(Nt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ae=ht=>{if(Ye()||jr)return;let ae=Nt.querySelectorAll("iframe"),It=typeof document<"u"&&"hasStorageAccess"in document;k(`watchdog:${ht} container=${Rr(Nt)} children=${Nt.childElementCount} iframes=${ae.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${It} paypalNetRequests=${Lr.value}`),ae.forEach((Et,Wr)=>{let Bt=(Et.getAttribute("title")??"").slice(0,40);k(` iframe[${Wr}] ${Rr(Et)}${Bt?` title="${Bt}"`:""} ${zn(Et)}`);let Mo=uo(Et);Mo&&k(` ${Mo}`)}),Vr.length===0&&k(" (no PayPal/zoid window errors captured)")};cn.push(setTimeout(()=>Ae("3s"),3e3)),cn.push(setTimeout(()=>Ae("8s"),8e3)),cn.push(setTimeout(()=>Ae("15s"),15e3))},vr(),k("render:start");let Po=te.startTiming();dn=setTimeout(()=>{Ye()||jr||(k("watchdog:11s retryable render timeout"),Z("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Pd);let To=tr.render(Nt);(async()=>{try{if(await To,k(`render:resolved inactive=${Ye()}`),ve(),Ye()){yn();return}jr=!0,Be(!0),at(!1),Gt.current?.("ready"),te.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"checkout_render",durationMs:te.elapsed(Po),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Ae){let ht=Ae instanceof Error?Ae.message:"PayPal failed to render.";k(`render:rejected msg=${ht.slice(0,120)}`),ve(),Z(zt(ht)?"teardown":"render_rejected",ht)}})()}).catch(qe=>{let je=qe instanceof Error?qe.message:"PayPal operation failed.";k(`provider:failed msg=${je.slice(0,120)}`);let ye="script_rejected";ne&&zt(je)?ye="teardown":ne&&co&&(ye="render_rejected"),Z(ye,je)})},0);return()=>{$t=!0,clearTimeout(Ne),Tn&&clearTimeout(Tn),ve(),Q.current===xt&&(Q.current=null),yn(),lt.current=null,He.current=null}},[Te,Re,c,m,p,oe,it,De,e,fe,Ke,K,ft,Rt,k,Vt]);let _n=A?(0,vn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ft?"#fef2f2":"#f3f4f6",border:`1px solid ${Ft?"#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=${Pe} failed=${Ft})`,le.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${ce.join(`
4
- `)}`]}):null;return Ft&&!u?F?(0,bn.jsx)("div",{children:on}):null:(0,bn.jsxs)("div",{children:[on,Pt&&(0,bn.jsx)(Ko,{identity:Pt.identity,methodLabel:Pt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:V,onCancel:()=>V(null)}),(0,bn.jsxs)("div",{"aria-hidden":M||Pt?!0:void 0,style:M||Pt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ci},children:[!Pe&&!M&&(0,bn.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,bn.jsx)("div",{ref:W,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ci,display:"flex",opacity:Pe?1:0},"aria-busy":pe||h},je)]},je),$e&&(0,bn.jsx)("button",{ref:Se,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:zr,style:vd,children:"Try PayPal again"})]})}function Sa(e){return(0,bn.jsx)(ql,{...e})}function jl(e){return(0,bn.jsx)(ql,{...e})}var wa=require("react/jsx-runtime");function Xo({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,wa.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,wa.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,wa.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 gt=require("@flopay/shared");var hr=require("react/jsx-runtime");var wd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function tn({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:s="PAYMENT FAILED",successNote:c="You will be automatically redirected, do not close or navigate away from this window.",theme:p=wd}){let y={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"&&c!==null&&(0,hr.jsx)("p",{style:y,children:c}),e==="error"&&t&&(0,hr.jsx)("p",{style:y,children:t}),(0,hr.jsx)("style",{children:`
3
+ ${le.join(`
4
+ `)}`]}):null;return Ft&&!u?A?(0,vn.jsx)("div",{children:_n}):null:(0,vn.jsxs)("div",{children:[_n,bt&&(0,vn.jsx)(Go,{identity:bt.identity,methodLabel:bt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:V,onCancel:()=>V(null)}),(0,vn.jsxs)("div",{"aria-hidden":M||bt?!0:void 0,style:M||bt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:di},children:[!Pe&&!M&&(0,vn.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,vn.jsx)("div",{ref:W,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:di,display:"flex",opacity:Pe?1:0},"aria-busy":ue||h},Ke)]},Ke),Ge&&(0,vn.jsx)("button",{ref:be,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Ur,style:vd,children:"Try PayPal again"})]})}function wa(e){return(0,vn.jsx)(ql,{...e})}function jl(e){return(0,vn.jsx)(ql,{...e})}var ka=require("react/jsx-runtime");function Jo({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,ka.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,ka.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ka.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var vt=require("@flopay/shared");var gr=require("react/jsx-runtime");var wd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function rn({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:s="PAYMENT FAILED",successNote:c="You will be automatically redirected, do not close or navigate away from this window.",theme:p=wd}){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"&&s]}),e==="success"&&c!==null&&(0,gr.jsx)("p",{style:m,children:c}),e==="error"&&t&&(0,gr.jsx)("p",{style:m,children:t}),(0,gr.jsx)("style",{children:`
5
5
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
6
6
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
7
7
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
8
8
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
9
- `})]})})}var Vl=require("@flopay/shared"),Ur=require("react");var Wl=require("react/jsx-runtime");function Ra({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,c]=(0,Ur.useState)(e instanceof Promise?null:e),[p,y]=(0,Ur.useState)(t instanceof Promise||!t?null:t),g=(0,Ur.useRef)(null),E=(0,Ur.useRef)(null),R=Yo(n);(0,Ur.useEffect)(()=>{R({class:"lifecycle",name:"checkout.mount"})},[R]),(0,Ur.useEffect)(()=>{s&&R({class:"lifecycle",name:"sdk.initialize.ready"})},[R,s]),(0,Ur.useEffect)(()=>{if(s)return Rr(s)?.subscribe?.(R)},[R,s]),(0,Ur.useEffect)(()=>{if(!(!p||p===s))return Rr(p)?.subscribe?.(R)},[R,s,p]),(0,Ur.useEffect)(()=>{if(!s)return;let T=Rr(s);return g.current=T?.beginCheckout()??T?.now()??0,T?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{T?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Ur.useEffect)(()=>{let T=!1;return e instanceof Promise?e.then(Y=>{T||c(Y)},()=>{T||R({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{T=!0}},[R,e]),(0,Ur.useEffect)(()=>{let T=!1;if(!t){y(null);return}return t instanceof Promise?t.then(Y=>{T||y(Y)},()=>{T||R({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{T=!0}},[R,t]),(0,Ur.useEffect)(()=>{if(!s||E.current===s)return;E.current=s;let T=Rr(s);T?.log({name:"checkout.rendered",stage:"checkout_render"}),R({class:"lifecycle",name:"checkout.rendered"}),T?.performance({stage:"checkout_render",durationMs:T.elapsed(g.current??0),durationMode:"machine"})},[R,s]);let _=(0,Vl.resolveBillingApiUrl)(r?.billingApiUrl),H=(0,Ur.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:_,emitInstrument:R}),[s,p,_,R]);return(0,Wl.jsx)(vn.Provider,{value:H,children:a})}var Nn=require("@flopay/shared");async function di(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 $r=require("@flopay/js"),lt=require("@flopay/shared");var Ea="card";async function Rd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function kd(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:s}=await e.confirmCardPayment(t,r);return{error:s,intent:a??null}}function Jo(e){return new lt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ed(){return new lt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function ss(e,t){return Object.assign(e,{checkoutMethod:t})}function so(e,t){let r=e instanceof lt.FloPayError?e:new lt.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function ka(e,t){try{return await e()}catch(r){throw so(r,t)}}function Hl(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 Kl(e){return(0,$r.runSavedCardChallenge)(e)}function Ia(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new $r.PaymentAPI(e),c=(0,$r.beginSavedCardChallengeTelemetry)(s,t,r);return c?{telemetry:c,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function Zo(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,c=new $r.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,y;try{y=await(0,$r.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:E=>Xn({type:E.declineReason??"authorization_declined",gatewayErrorCode:E.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},c)}catch(E){if(a.aborted||E instanceof Error&&E.name==="AbortError")throw E instanceof lt.FloPayError&&E.code==="three_ds_aborted"?E:Jo(E);if(!(E instanceof lt.FloPayError)||E.code!=="three_ds_timeout"&&E.code!=="checkout_processing_timeout")throw E;try{y=await c.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(_){if(a.aborted)throw Jo(_);if(!(_ instanceof lt.FloPayError)||_.code!=="checkout_processing_timeout")throw _}let R=y&&go(y,t.session);if(!oo(R)&&R?.status!=="expired"){if(t.telemetry){let _=new $r.PaymentAPI(r);try{_.reportThreeDsAbandoned(n)}finally{_.destroy()}}throw Ed()}}let g=y&&go(y,t.session);if(!oo(g))throw Wo(g);return{...no(g,n),checkoutMethod:"card"}}function Xn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,s=(0,So.applyFriendlyMessageOverride)(a)??a,c=ss(new lt.FloPayError(s,"api_error",{code:e?.code??(0,lt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,lt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(c.orderId=e.orderId),c}function is(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ui(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Gl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ui(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||ui(p)))return p;let c=a.gateways;if(c&&typeof c=="object"){let p=c.stripe;if(p&&typeof p=="object"){let y=p,g=[y.stripeClientSecret,y.clientSecret];for(let E of g)if(typeof E=="string"&&E.length>0&&(!t?.requirePaymentIntentClientSecret||ui(E)))return E}}}}async function Id({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Gl(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 $r.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(ui(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function Qo({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:c}){let p=e.replace(/\/+$/,""),y=t??r.id,g=n??r.clientSecret,E=r.customer?.id??r.accountData?.userId??"",R=r.customer?.email??r.accountData?.email??"",_=r.customer?.firstName??r.accountData?.firstName??"",H=r.customer?.lastName??r.accountData?.lastName??"",T=r.customer?.country??r.accountData?.country??void 0,Y=r.customer?.zip??r.accountData?.zip??void 0,f=await new $r.PaymentAPI(p,c===!1?{telemetry:!1}:void 0).processPayment(E,{sessionId:y,nonce:g,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:E,email:R,firstName:_,lastName:H,country:T,zip:Y},returnUrl:s??is(r)});if(f.ok){let S=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,lt.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:y,authorizationExpiresAt:typeof S?.authorizationExpiresAt=="string"?S.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:Pa(a),checkoutMethod:$l(a,r)}};let Me=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Me?{paymentIntentId:Me}:{},paymentMethodId:Pa(a),checkoutMethod:$l(a,r)}}}let h;try{h=await f.json()}catch(S){throw new lt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:S})}if(h?.type==="3ds_required"&&typeof h.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:h.nextActionRedirectUrl};if(h?.type==="paypal_redirect_required"||h?.type==="3ds_required"){let S=Gl(h);if(!S)throw new lt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:h.type,threeDSecureToken:S,paymentMethodId:h.paymentMethodId}}if(h?.gatewayErrorCode==="authentication_required"){let S=await Id({billingApiUrl:p,sessionId:y,nonce:g,responseJson:h});if(S)return S;throw ss(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ge=new lt.FloPayError(h?.message??"Payment failed. Please try again.","api_error",{code:h?.code??h?.gatewayErrorCode,declineCode:h?.declineCode??h?.gatewayDeclineReason,statusCode:f.status});throw Object.assign(ge,{telemetryOutcome:(0,lt.classifyPaymentRejection)(f.status,h)})}async function pi(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:y,signal:g}){let E=t?.getRawProvider();if(!E)throw so(new lt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw ss(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let R=(0,lt.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,H=e.paymentMethodId,T=await ka(()=>Rd(E,e.threeDSecureToken,R),"card");if(T){if(T.error)throw so(new lt.FloPayError(T.error.message??`Failed to retrieve 3DS ${R?"setup":"payment"} status.`,"api_error",{code:T.error.code}),"card");let B=T.intent;!H&&B?.payment_method&&(typeof B.payment_method=="string"?H=B.payment_method:"id"in B.payment_method&&(H=B.payment_method.id??void 0))}let Y=H?await ka(()=>kd(E,e.threeDSecureToken,{payment_method:H,return_url:p??is(c)??window.location.href},R),"card"):null;if(Y){if(Y.error)throw so(new lt.FloPayError(Y.error.message??"3DS authentication failed.","api_error",{code:Y.error.code}),"card");_=Y.intent}else{let B=await ka(()=>E.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(B.error)throw so(new lt.FloPayError(B.error.message??"3DS authentication failed.","api_error",{code:B.error.code}),"card");_=(R?B.setupIntent:B.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let B=await Qo({billingApiUrl:a,sessionId:s,session:c,telemetry:y,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:p});return B.type==="success"?{...B.result,paymentIntentId:B.result.paymentIntentId??_.id,paymentMethodId:B.result.paymentMethodId??H}:B.type==="next_action_required"?Zo(B,{billingApiUrl:a,sessionId:s??c.id,session:c,signal:g}):pi(B,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:y,signal:g})}throw so(new lt.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let R=(r??t)?.getRawProvider();if(!R)throw so(new lt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:H}=await ka(()=>R.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(H)throw so(new lt.FloPayError(H.message??"PayPal authorization failed.","api_error",{code:H.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await ka(()=>R.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??is(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw so(new lt.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new lt.FloPayError("Unsupported payment redirect state.","api_error")}function _a(e){if(e instanceof lt.FloPayError){let n=(0,So.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new lt.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,So.applyFriendlyMessageOverride)(t)??t;return new lt.FloPayError(r,"api_error")}function ls(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,lt.isMountableVaultBlock)(e.data.session?.vault)||(0,Dn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new lt.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function $l(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Dn.canRecoverHostedCardForm)(t)?"card":void 0}async function cs({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let s=t&&t!==e?t:void 0,[c,p]=await Promise.all([(0,$r.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,$r.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(g=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",g),null)):Promise.resolve(null)]);if(!c)throw new lt.FloPayError("The payment provider did not initialize.","authentication_error");let y=null;return s?y=p:t&&(y=c),{flopay:c,paypalFlopay:y}}var zn=require("@flopay/js"),l=require("@flopay/shared"),dr=require("@stripe/react-stripe-js"),o=Qi(require("react"),1);function ko(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function mi(e,t){if(e)return{error:r=>e.error(ko(t,r)),log:r=>e.log(ko(t,r)),performance:r=>e.performance(ko(t,r)),terminal:r=>e.terminal(ko(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var lo=require("@flopay/shared"),Xl=require("react");var Yl={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 Mr=require("react/jsx-runtime"),_d=`
9
+ `})]})})}var Vl=require("@flopay/shared"),Nr=require("react");var Wl=require("react/jsx-runtime");function Ra({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,c]=(0,Nr.useState)(e instanceof Promise?null:e),[p,m]=(0,Nr.useState)(t instanceof Promise||!t?null:t),g=(0,Nr.useRef)(null),_=(0,Nr.useRef)(null),E=Xo(n);(0,Nr.useEffect)(()=>{E({class:"lifecycle",name:"checkout.mount"})},[E]),(0,Nr.useEffect)(()=>{s&&E({class:"lifecycle",name:"sdk.initialize.ready"})},[E,s]),(0,Nr.useEffect)(()=>{if(s)return Sr(s)?.subscribe?.(E)},[E,s]),(0,Nr.useEffect)(()=>{if(!(!p||p===s))return Sr(p)?.subscribe?.(E)},[E,s,p]),(0,Nr.useEffect)(()=>{if(!s)return;let T=Sr(s);return g.current=T?.beginCheckout()??T?.now()??0,T?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{T?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Nr.useEffect)(()=>{let T=!1;return e instanceof Promise?e.then(Y=>{T||c(Y)},()=>{T||E({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{T=!0}},[E,e]),(0,Nr.useEffect)(()=>{let T=!1;if(!t){m(null);return}return t instanceof Promise?t.then(Y=>{T||m(Y)},()=>{T||E({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{T=!0}},[E,t]),(0,Nr.useEffect)(()=>{if(!s||_.current===s)return;_.current=s;let T=Sr(s);T?.log({name:"checkout.rendered",stage:"checkout_render"}),E({class:"lifecycle",name:"checkout.rendered"}),T?.performance({stage:"checkout_render",durationMs:T.elapsed(g.current??0),durationMode:"machine"})},[E,s]);let I=(0,Vl.resolveBillingApiUrl)(r?.billingApiUrl),H=(0,Nr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:I,emitInstrument:E}),[s,p,I,E]);return(0,Wl.jsx)(hn.Provider,{value:H,children:a})}var Dn=require("@flopay/shared");async function ui(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 $r=require("@flopay/js"),pt=require("@flopay/shared");var _a="card";async function kd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function Rd(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:s}=await e.confirmCardPayment(t,r);return{error:s,intent:a??null}}function Zo(e){return new pt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ed(){return new pt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function ss(e,t){return Object.assign(e,{checkoutMethod:t})}function oo(e,t){let r=e instanceof pt.FloPayError?e:new pt.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 Ea(e,t){try{return await e()}catch(r){throw oo(r,t)}}function Hl(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 Kl(e){return(0,$r.runSavedCardChallenge)(e)}function Ia(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new $r.PaymentAPI(e),c=(0,$r.beginSavedCardChallengeTelemetry)(s,t,r);return c?{telemetry:c,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function Qo(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,c=new $r.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,$r.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:_=>Hn({type:_.declineReason??"authorization_declined",gatewayErrorCode:_.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},c)}catch(_){if(a.aborted||_ instanceof Error&&_.name==="AbortError")throw _ instanceof pt.FloPayError&&_.code==="three_ds_aborted"?_:Zo(_);if(!(_ instanceof pt.FloPayError)||_.code!=="three_ds_timeout"&&_.code!=="checkout_processing_timeout")throw _;try{m=await c.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(I){if(a.aborted)throw Zo(I);if(!(I instanceof pt.FloPayError)||I.code!=="checkout_processing_timeout")throw I}let E=m&&yo(m,t.session);if(!to(E)&&E?.status!=="expired"){if(t.telemetry){let I=new $r.PaymentAPI(r);try{I.reportThreeDsAbandoned(n)}finally{I.destroy()}}throw Ed()}}let g=m&&yo(m,t.session);if(!to(g))throw $o(g);return{...eo(g,n),checkoutMethod:"card"}}function Hn(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,wo.applyFriendlyMessageOverride)(a)??a,c=ss(new pt.FloPayError(s,"api_error",{code:e?.code??(0,pt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,pt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(c.orderId=e.orderId),c}function is(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function pi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Gl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||pi(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||pi(p)))return p;let c=a.gateways;if(c&&typeof c=="object"){let p=c.stripe;if(p&&typeof p=="object"){let m=p,g=[m.stripeClientSecret,m.clientSecret];for(let _ of g)if(typeof _=="string"&&_.length>0&&(!t?.requirePaymentIntentClientSecret||pi(_)))return _}}}}async function _d({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Gl(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 $r.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(pi(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function ea({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:c}){let p=e.replace(/\/+$/,""),m=t??r.id,g=n??r.clientSecret,_=r.customer?.id??r.accountData?.userId??"",E=r.customer?.email??r.accountData?.email??"",I=r.customer?.firstName??r.accountData?.firstName??"",H=r.customer?.lastName??r.accountData?.lastName??"",T=r.customer?.country??r.accountData?.country??void 0,Y=r.customer?.zip??r.accountData?.zip??void 0,y=await new $r.PaymentAPI(p,c===!1?{telemetry:!1}:void 0).processPayment(_,{sessionId:m,nonce:g,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:_,email:E,firstName:I,lastName:H,country:T,zip:Y},returnUrl:s??is(r)});if(y.ok){let w=typeof y.json=="function"?await y.json().catch(()=>null):null;if((0,pt.isAuthorizationOnlySession)(r)||w?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof w?.paymentId=="string"?w.paymentId:r.paymentId,sessionId:typeof w?.sessionId=="string"?w.sessionId:m,authorizationExpiresAt:typeof w?.authorizationExpiresAt=="string"?w.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:va(a),checkoutMethod:$l(a,r)}};let Te=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Te?{paymentIntentId:Te}:{},paymentMethodId:va(a),checkoutMethod:$l(a,r)}}}let h;try{h=await y.json()}catch(w){throw new pt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status,cause:w})}if(h?.type==="3ds_required"&&typeof h.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:h.nextActionRedirectUrl};if(h?.type==="paypal_redirect_required"||h?.type==="3ds_required"){let w=Gl(h);if(!w)throw new pt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status});return{type:h.type,threeDSecureToken:w,paymentMethodId:h.paymentMethodId}}if(h?.gatewayErrorCode==="authentication_required"){let w=await _d({billingApiUrl:p,sessionId:m,nonce:g,responseJson:h});if(w)return w;throw ss(new pt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ge=new pt.FloPayError(h?.message??"Payment failed. Please try again.","api_error",{code:h?.code??h?.gatewayErrorCode,declineCode:h?.declineCode??h?.gatewayDeclineReason,statusCode:y.status});throw Object.assign(ge,{telemetryOutcome:(0,pt.classifyPaymentRejection)(y.status,h)})}async function mi(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:m,signal:g}){let _=t?.getRawProvider();if(!_)throw oo(new pt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw ss(new pt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let E=(0,pt.isSetupIntentClientSecret)(e.threeDSecureToken),I=null,H=e.paymentMethodId,T=await Ea(()=>kd(_,e.threeDSecureToken,E),"card");if(T){if(T.error)throw oo(new pt.FloPayError(T.error.message??`Failed to retrieve 3DS ${E?"setup":"payment"} status.`,"api_error",{code:T.error.code}),"card");let F=T.intent;!H&&F?.payment_method&&(typeof F.payment_method=="string"?H=F.payment_method:"id"in F.payment_method&&(H=F.payment_method.id??void 0))}let Y=H?await Ea(()=>Rd(_,e.threeDSecureToken,{payment_method:H,return_url:p??is(c)??window.location.href},E),"card"):null;if(Y){if(Y.error)throw oo(new pt.FloPayError(Y.error.message??"3DS authentication failed.","api_error",{code:Y.error.code}),"card");I=Y.intent}else{let F=await Ea(()=>_.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(F.error)throw oo(new pt.FloPayError(F.error.message??"3DS authentication failed.","api_error",{code:F.error.code}),"card");I=(E?F.setupIntent:F.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let F=await ea({billingApiUrl:a,sessionId:s,session:c,telemetry:m,tokenizedData:{id:I.id,type:"card",threeDSecureActionResultTokenId:I.id},returnUrl:p});return F.type==="success"?{...F.result,paymentIntentId:F.result.paymentIntentId??I.id,paymentMethodId:F.result.paymentMethodId??H}:F.type==="next_action_required"?Qo(F,{billingApiUrl:a,sessionId:s??c.id,session:c,signal:g}):mi(F,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:m,signal:g})}throw oo(new pt.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let E=(r??t)?.getRawProvider();if(!E)throw oo(new pt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:H}=await Ea(()=>E.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(H)throw oo(new pt.FloPayError(H.message??"PayPal authorization failed.","api_error",{code:H.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:I}=await Ea(()=>E.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??is(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(I)throw oo(new pt.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new pt.FloPayError("Unsupported payment redirect state.","api_error")}function Ta(e){if(e instanceof pt.FloPayError){let n=(0,wo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new pt.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,wo.applyFriendlyMessageOverride)(t)??t;return new pt.FloPayError(r,"api_error")}function ls(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,pt.isMountableVaultBlock)(e.data.session?.vault)||(0,An.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new pt.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 $l(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,An.canRecoverHostedCardForm)(t)?"card":void 0}async function cs({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let s=t&&t!==e?t:void 0,[c,p]=await Promise.all([(0,$r.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,$r.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(g=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",g),null)):Promise.resolve(null)]);if(!c)throw new pt.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=c),{flopay:c,paypalFlopay:m}}var Ln=require("@flopay/js"),l=require("@flopay/shared"),sr=require("@stripe/react-stripe-js"),o=Qi(require("react"),1);function Eo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function yi(e,t){if(e)return{error:r=>e.error(Eo(t,r)),log:r=>e.log(Eo(t,r)),performance:r=>e.performance(Eo(t,r)),terminal:r=>e.terminal(Eo(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 ao=require("@flopay/shared"),Xl=require("react");var Yl={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 Ir=require("react/jsx-runtime"),Id=`
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 @@ ${ce.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
- `,ea=44;function ta(){return(0,Mr.jsx)("style",{children:_d})}function Ta(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function Ma({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Mr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Mr.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,Mr.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 ds(e){return e!=="unavailable"&&e!=="load_error"}function yi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:c,backgroundColor:p,borderColor:y,textColor:g,borderRadius:E,fontFamily:R}){let _=(0,lo.resolveStripeMethodBrandVariant)(e,t),H=Yl[e],[T,Y]=(0,Xl.useState)(!1),B=!!H&&!T,f=_?.backgroundColor??p??"#ffffff",h=_?.borderColor??y??"#d1d5db",ge=_?.textColor??g??"#262833";return(0,Mr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&c()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ea,padding:"0 1rem",backgroundColor:f,color:ge,border:`1px solid ${h}`,borderRadius:E??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,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,Mr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,lo.getStripeMethodDisplayName)(e)}\u2026`}):(0,Mr.jsxs)(Mr.Fragment,{children:[(0,Mr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,lo.hasVendoredStripeMethodLogo)(e)?8:0},children:[B?(0,Mr.jsx)("img",{src:H,alt:"","aria-hidden":"true",onError:()=>Y(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!B&&_?.logoSvg?(0,Mr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:_.logoSvg}}):null,(0,Mr.jsx)("span",{children:(0,lo.getStripeMethodDisplayName)(e)})]}),s&&(0,Mr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ge,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,Mr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function fi(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 gi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},hi={type:"accordion",defaultCollapsed:!1,radios:"never"};function Pi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:c,children:p}){return(0,Mr.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:s,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...c??{}},children:p})}var un=require("react");var xa=require("@flopay/shared"),Td=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 Md(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Td.has(t.charAt(0).toLowerCase()+t.slice(1))}function xd(e,t){return typeof t=="number"&&t!==0&&!Md(e)?`${t}px`:String(t).trim()}function Jl(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]=xd(r,n)}}}var Eo=require("react/jsx-runtime"),us=new WeakSet;function ho({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:c,containerStyle:p,onReady:y,onError:g,onValidation:E}){let R=(0,un.useRef)(null),_=(0,un.useRef)(y),H=(0,un.useRef)(g),T=(0,un.useRef)(E);_.current=y,H.current=g,T.current=E;let Y=(0,un.useRef)(s);Y.current=s;let B=(0,un.useRef)(null),f=c??void 0,h=(0,un.useRef)(f);h.current=f;let ge=(0,un.useRef)(void 0);return(0,un.useEffect)(()=>{let S=R.current;if(!S)return;let Me=!0,A=!1,ie=()=>{!Me||A||(A=!0,_.current?.())},he=e.on("ready",()=>{ie()}),fe=e.on("error",F=>{H.current?.(F.message??"There was a problem loading the secure card form.")}),Re=e.on("validation",F=>{T.current?.(F.message??null)}),ct=h.current??(us.has(e)?null:void 0),Ke={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...Y.current?{theme:Y.current}:{},...ct===void 0?{}:{submitLabel:ct}};return B.current=Y.current??null,ge.current=h.current,h.current!==void 0&&us.add(e),e.mount(S,Ke).then(()=>{ie()}).catch(F=>{Me&&H.current?.(F instanceof Error?F.message:"Failed to load the secure card form.")}),()=>{Me=!1,he(),fe(),Re(),e.unmount()}},[e,t,r,n,a]),wo(()=>{let S=R.current;S&&Jl(S,p)},[p]),(0,un.useEffect)(()=>{s!==void 0&&(s===null&&B.current===null||(B.current=s,e.applyTheme?.(s)))},[e,s]),(0,un.useEffect)(()=>{f!==ge.current&&(ge.current=f,f!==void 0&&us.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,Eo.jsx)("div",{ref:R,"data-testid":"flopay-vault-card-fields"})}function vi({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 Ss=require("@flopay/shared"),d=require("react/jsx-runtime"),Jn="flopay_stripe_resume",Zl="flopay_wallet_resume",lc="fw1",Ad="fw2",cc=300*1e3,Fd=900,Bd="express_checkout_click_timeout",Dd=25e3,Od=25e3,Ld=1e4,Un={provider:"paypal",paymentMethodCategory:"paypal"},Nd="x-flopay-process-result-source",Ud="status";async function zd(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 Ci={},Fa=class{constructor(t){this.reason=t}};function qd(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function ur(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function vs(e){return`${Ad}:${e}`}function bi(e){return ur(vs(e))}function Si(e,t){if(typeof window>"u")return null;let r=vs(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>cc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(bi(e),null):a}catch{return bi(e),null}}function jd(e){return ur(vs(e.sessionId),e)}function Ql(e,t,r){let n=Si(e,t);return!n||n.clientSecret!==r?!1:bi(e)}function ps(e,t,r){if(typeof window>"u")return;Si(e,t)?.clientSecret===r&&bi(e)}function Vd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ms(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":ha(e.status),a=Vd(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function ec(e,t,r){let n=null;try{return await Promise.race([Al(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Ld),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Wd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function dc(e){return e instanceof l.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function wi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new zn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw dc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var ys=l.STRIPE_PAYPAL_RESUME_KEY,Aa=new Map,$d=250,tc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Hd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Cs(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 Ri({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new zn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Kd(e){return e instanceof l.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function uc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,$o.splitFullName)(r),c=s.firstName?s:(0,$o.splitFullName)(n?.name);return(0,Cn.compactBuyerIdentity)({email:(0,l.isValidEmail)(a)?a:n?.email?.trim(),firstName:c.firstName,lastName:c.lastName})}async function Gd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let c=uc({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,l.isValidEmail)(c.email)?c:s(a,c)}var Ba=180,rc=`flopay-card-enter ${Ba}ms cubic-bezier(0, 0, 0.2, 1) both`,nc=`flopay-card-exit ${Ba}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Yd=`flopay-buttons-enter ${Ba}ms cubic-bezier(0, 0, 0.2, 1) both`,Xd=`flopay-buttons-exit ${Ba}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Jd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function bs(e){return(0,l.derivePrimaryTileStyle)(e)}var Zd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Qd(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 gs={width:"100%",minHeight:ea,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 oc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function hs(e){return e==="paypal"?"PayPal":(0,l.getStripeMethodDisplayName)(e)}function eu(e){let t=(0,l.getPostalCodeExample)(e);return`Enter a valid ${(0,l.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function tu(e,t,r){let n=(0,l.isPostalCodeSupported)(e),a=t.trim(),s=r&&n,c=s&&!a,p=s&&!!a&&!(0,l.isValidPostalCode)(e,a);return{visible:r,supported:n,required:s,empty:c,malformed:p}}function ru(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,l.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function nu(e){return typeof e=="number"?`${e}px`:e}function ki(e){return(0,d.jsx)(iu,{...e})}function ac({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:c=!1,onButtonClick:p,onDecline:y,onTechnicalFailure:g,runBeforeButtonClick:E,billingName:R,onBuyerIdentityReady:_,onLoadStateChange:H,placeholderBorderRadius:T,popupCapabilityOwner:Y,externalTelemetryContext:B,presentationMode:f}){let h=io(),{emitInstrument:ge}=(0,o.useContext)(vn),S=(0,dr.useStripe)(),Me=(0,dr.useElements)(),A=(0,o.useMemo)(()=>mi(Rr(h),B),[B,h]),[ie,he]=(0,o.useState)("loading");(0,o.useEffect)(()=>{H?.(ie)},[ie,H]);let[fe,Re]=(0,o.useState)(!1),ct=(0,o.useRef)(!1),Ke=!(0,l.isValidEmail)(r?.trim())||!R?.trim(),{request:F,collect:St,finish:et}=Ho(),Ue=(0,o.useRef)(!1),ye=(0,o.useRef)(null),J=(0,o.useRef)(null),[W,Fe]=(0,o.useState)(0),[dt,We]=(0,o.useState)(!1),Z=(0,o.useRef)(!1),L=(0,o.useRef)(new Map),{startAttempt:le,finishAttempt:j,invalidateAttempt:Se,isAttemptInvalidated:xe,isAttemptCurrent:Pe,generationRef:Be}=ba((ue,pe,X)=>{g?.(ue,pe,{...X,popupBlocked:X?.popupBlocked??(0,we.isPopupBlockedError)(pe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),We(!0),Fe(Pt=>Pt+1)},{onHandoffObserved:()=>{Y.markAvailable(),A?.log({name:"provider.popup.opened",stage:"overlay_open",...Un,attempt:Be.current})}});(0,o.useEffect)(()=>{dt&&J.current?.focus()},[dt,W]);let M=(0,o.useCallback)(()=>{Fe(ue=>ue+1)},[]),nt=(0,o.useCallback)((ue,pe,X)=>{Se(X),g?.("paypal",ue,{code:pe,popupBlocked:(0,we.isPopupBlockedError)(ue),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),We(!0),M()},[Se,g,f,M]),je=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ye.current?.querySelector("iframe")??ye.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Z.current&&(Z.current=!1,je())},[je,W]);let ut=(0,o.useCallback)(()=>{We(!1),s?.(null),je()},[je,s]);(0,o.useEffect)(()=>{if(!S||Ue.current)return;let[ue,pe,X]=(0,l.readStripeRedirectParams)();if(!ue||!pe)return;let Pt=(0,l.readMatchingStripePayPalContinuation)(pe);if(!Pt)return;Ue.current=!0;let pt=!0,V=Aa.get(pe);V||(V=X==="failed"?Promise.resolve(null):Promise.resolve().then(()=>S.retrievePaymentIntent(pe)),Aa.set(pe,V));let rt={accountPatch:Pt.accountPatch,sessionId:Pt.sessionId,nonce:Pt.nonce},wt=()=>{A?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Un,requestCategory:"provider_sdk"})};return A?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Un}),(async()=>{try{Re(!0);let v=await V;if(!pt)return;if(v?.error){Aa.delete(pe),wt(),s?.(v.error.message??"Failed to retrieve PayPal payment status.");return}if((0,l.clearStripePayPalReturn)(),Aa.delete(pe),X==="failed"){let ne="PayPal payment was declined. Please try again.";A?.terminal({outcome:"payment_declined",...Un,terminalReason:"provider_declined"}),s?.(ne),y?.(wr("paypal",ne));return}let U=v?.paymentIntent;if(U&&U.id!==ue){wt(),s?.("Failed to match the returned PayPal payment.");return}if(U&&(U.status==="requires_capture"||U.status==="succeeded")){let ne=typeof U.payment_method=="string"?U.payment_method:U.payment_method?.id;a({id:ne??U.id,type:"card",threeDSecureActionResultTokenId:U.id,isPaypal:!0},{...rt,presentationMode:"redirect"})}else{let ne="PayPal payment was not completed. Please try again.";A?.terminal({outcome:U?.status==="canceled"?"payment_cancelled":"payment_declined",...Un,terminalReason:U?.status==="canceled"?"cancelled":"provider_declined"}),s?.(ne),y?.(wr("paypal",ne))}}catch(v){if(!pt)return;Aa.delete(pe),wt(),s?.(v instanceof Error?v.message:"Failed to complete PayPal payment.")}finally{pt&&Re(!1)}})(),()=>{pt=!1,Ue.current=!1}},[S,a,s,y,A]);let Ge=(0,o.useCallback)(async(ue=!1)=>{let pe=E?await E("paypal"):{proceed:!0};if(!pe.proceed)return L.current.delete(W),!1;let X=le("paypal");return L.current.set(W,{generation:X,accountPatch:pe.accountPatch,sessionId:pe.sessionId,nonce:pe.nonce}),We(!1),A?.log({name:`provider.${ue?"redirect.started":"handoff.requested"}`,stage:ue?"redirect":"overlay_open",...Un,attempt:X}),p?.("paypal"),!0},[p,A,E,le,W]),$e=(0,o.useCallback)(async ue=>{if(c||fe||!await Ge()){ue.reject();return}ue.resolve()},[c,Ge,fe]),Rt=(0,o.useCallback)(async ue=>{if(!S||!Me)return;let pe=L.current.get(W);if(pe&&!Pe(pe.generation)){L.current.delete(W);return}if(!pe&&xe()||pe&&!j(pe.generation))return;pe||j();let X=pe??null;if(L.current.delete(W),!X&&E){let ke=await E("paypal");if(!ke.proceed){ue.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}X={accountPatch:ke.accountPatch,sessionId:ke.sessionId,nonce:ke.nonce}}let Pt=X?.sessionId??e,pt=X?.nonce??t,V=await Gd({event:ue,prepared:X,email:r,billingName:R,methodLabel:"PayPal",collect:St});if(!V){ue.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let rt=V.email,wt={...X?.accountPatch,...(0,Cn.compactBuyerIdentity)(V,!0)};try{if(Re(!0),s?.(null),!Pt||!(0,l.isValidEmail)(rt))throw new Error("Missing sessionId or email for PayPal payment");await _?.(V);let ke=S.createPaymentMethod,{error:v,paymentMethod:U}=await ke({type:"paypal"});if(v){nt(v,"stripe_paypal_create_payment_method_failed",pe?.generation),ue.paymentFailed({reason:"fail"});return}let ne=await wi(n,ge,Pt,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:U?.id??null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(ne)){ue.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:wt,paymentMethodCategory:"paypal",presentationMode:f,sessionId:Pt,nonce:pt,settledProcessResponse:ne.response});return}if(ne.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ae=ne.clientSecret,Dt={return_url:(0,l.stripeRedirectReturnUrl)()};if(U?.id&&(Dt.payment_method=U.id),!ur(ys,{clientSecret:Ae,sessionId:Pt,nonce:pt,accountPatch:wt})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:De,paymentIntent:Oe}=await S.confirmPayment({clientSecret:Ae,confirmParams:Dt,redirect:"if_required"});if(De){if(ur(ys),(0,we.isProviderDecline)(De)){let u=De.message??"Your payment was declined.";A?.terminal({outcome:"payment_declined",...Un,terminalReason:"provider_declined"}),s?.(u),y?.(wr("paypal",u,{code:(0,we.getProviderErrorCode)(De),declineCode:(0,we.getProviderDeclineCode)(De)})),await Ri({billingApiUrl:n,sessionId:Pt,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,we.getProviderErrorCode)(De)??"provider_declined"}})}else nt(De,"stripe_paypal_confirm_failed",pe?.generation);return}ur(ys);let _t=typeof Oe?.payment_method=="string"?Oe.payment_method:Oe?.payment_method?.id;a({id:_t??Oe?.id,type:"card",threeDSecureActionResultTokenId:Oe?.id,isPaypal:!0},{accountPatch:wt,paymentMethodCategory:"paypal",presentationMode:f,sessionId:Pt,nonce:pt});return}catch(ke){nt(ke,"stripe_paypal_failed",pe?.generation)}finally{Re(!1)}},[S,Me,e,t,r,R,St,_,n,ge,a,s,y,E,nt,j,Pe,xe,A,f,W]),Ot=(0,o.useCallback)(async()=>{if(!(ct.current||c||fe||!S||!Me)){ct.current=!0,Re(!0);try{if(!await Ge(!0))return;await Rt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{ct.current=!1,Re(!1)}}},[Me,Rt,c,Ge,S,fe]),zt=f==="redirect"?(0,d.jsx)("button",{type:"button",disabled:c||fe,onClick:()=>{Ot()},style:{width:"100%",minHeight:ea,border:"1px solid #d1d5db",borderRadius:T??8,background:"#ffc439",color:"#111827",cursor:c||fe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(dr.ExpressCheckoutElement,{onReady:ue=>he(Ta(ue,["paypal"])),onLoadError:()=>{he("load_error"),Cs(A,"paypal","paypal","provider_error")},onClick:$e,onConfirm:Rt,onCancel:()=>{let ue=L.current.get(W);L.current.delete(W),A?.terminal({outcome:"payment_cancelled",...Un,terminalReason:"cancelled",...ue?{attempt:ue.generation}:{}}),Se(ue?.generation),We(!1),Z.current=!0,M()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Ke,emailRequired:Ke,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},W),Ft=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:ye,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[dt&&(0,d.jsx)("button",{ref:J,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ut,style:gs,children:"Try PayPal again"}),F&&(0,d.jsx)(Ko,{identity:F.identity,methodLabel:F.methodLabel,onComplete:et,onCancel:()=>et(null)},F.id),(0,d.jsx)("div",{style:{display:F?"none":void 0},children:zt})]}),fe&&!F&&(0,d.jsx)(tn,{status:"processing"})]});return f==="redirect"?Ft:(0,d.jsx)(Ma,{state:ie,placeholderTestId:"flopay-paypal-placeholder",borderRadius:T,children:Ft})}function fs(e){return e==="apple_pay"||e==="google_pay"}var ou=200;function au({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,l.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function ic({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:c,onErrorChange:p,onButtonClick:y,onDecline:g,onTechnicalFailure:E,runBeforeButtonClick:R,billingName:_,onBuyerIdentityReady:H,onLoadStateChange:T,placeholderBorderRadius:Y,popupCapabilityOwner:B,externalTelemetryContext:f}){let h=io(),{emitInstrument:ge}=(0,o.useContext)(vn),S=(0,dr.useStripe)(),Me=(0,dr.useElements)(),A=(0,o.useMemo)(()=>mi(Rr(h),f),[f,h]),[ie,he]=(0,o.useState)("loading");(0,o.useEffect)(()=>{T?.(ie)},[ie,T]);let[fe,Re]=(0,o.useState)(!1);(0,o.useEffect)(()=>{We.current=fe},[fe]);let ct=(0,o.useRef)(!(0,l.isValidEmail)(r?.trim())||!_?.trim()).current,{request:Ke,collect:F,finish:St}=Ho(),et=(0,o.useRef)(null),Ue=(0,o.useRef)(null),[ye,J]=(0,o.useState)(0),[W,Fe]=(0,o.useState)(()=>(0,l.shouldPreferWalletPopup)()),dt=(0,o.useRef)(W),We=(0,o.useRef)(!1),[Z,L]=(0,o.useState)(!1),[le,j]=(0,o.useState)(()=>Si(e,t)?"blocked":"idle"),[Se,xe]=(0,o.useState)("google_pay"),Pe=(0,o.useRef)(null),Be=(0,o.useRef)(!0),M=(0,o.useRef)(!1),nt=(0,o.useRef)("google_pay"),je=(0,o.useRef)("google_pay"),ut=(0,o.useRef)(null),Ge=(0,o.useRef)(null),$e=(0,o.useRef)(new Set),Rt=(0,o.useRef)(null),Ot=(0,o.useRef)(null);(0,o.useEffect)(()=>(Be.current=!0,()=>{Be.current=!1;for(let u of $e.current)window.clearTimeout(u);$e.current.clear()}),[]);let zt=(0,o.useRef)(new Map),{startAttempt:Ft,finishAttempt:ue,invalidateAttempt:pe,isAttemptInvalidated:X,isAttemptCurrent:Pt,generationRef:pt}=ba((u,C,Q)=>{E?.(u,C,{...Q,popupBlocked:Q?.popupBlocked??(0,we.isPopupBlockedError)(C),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),xe(u),L(!0),J(ce=>ce+1)},{onHandoffObserved:u=>{Ot.current=pt.current,B.markAvailable(),A?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:pt.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:fs,onMissingTerminalDeferred:(u,C)=>{let Q=A?.now()??globalThis.performance?.now()??Date.now(),ce=Rt.current,N=ce?.generation===C?ce.startedAt:Q;A?.performance({stage:"overlay_return",durationMs:Math.max(0,Q-N),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:C,...fs(u)?{walletType:u}:{}}),A?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{Z&&Ue.current?.focus()},[Z,ye]);let V=(0,o.useRef)(0),rt=(0,o.useRef)(!1),wt=(0,o.useCallback)(()=>{if(V.current>0){rt.current=!0;return}J(u=>u+1)},[]),ke=(0,o.useCallback)(()=>{V.current-=1,!(V.current>0||!rt.current)&&(rt.current=!1,Be.current&&J(u=>u+1))},[]),v=(0,o.useCallback)((u,C,Q,ce,N=!1)=>{pe(ce),E?.(u,C,{code:Q,popupBlocked:(0,we.isPopupBlockedError)(C),telemetryReported:N,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),xe(u),L(!0),wt()},[pe,E,wt]),U=(0,o.useCallback)(u=>{A?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...fs(u)?{walletType:u}:{}}),E?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:Bd,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),xe(u),L(!0)},[E,A]),ne=(0,o.useCallback)(()=>{window.setTimeout(()=>{(et.current?.querySelector("iframe")??et.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{M.current&&(M.current=!1,ne())},[ne,ye]);let Ae=(0,o.useCallback)(()=>{L(!1),p?.(null),ne()},[ne,p]),Dt=(0,o.useCallback)(()=>{Pe.current?.()},[]);(0,o.useEffect)(()=>{let u=null,C=()=>{u=null;let ce=(0,l.shouldPreferWalletPopup)();ce!==dt.current&&(dt.current=ce,Fe(ce),!We.current&&!Pt(pt.current)&&wt())},Q=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(C,ou)};return window.addEventListener("resize",Q),()=>{window.removeEventListener("resize",Q),u!==null&&window.clearTimeout(u)}},[pt,Pt,wt]),(0,o.useEffect)(()=>{let u=Si(e,t);if(!u)return;let C=!1,Q=!1,ce=async()=>{if(!Q){Q=!0,C||j("checking");try{let N=await ec(S,u.clientSecret,$e.current);if(C)return;let w=ms(N,u.providerObjectId,(0,l.isSetupIntentClientSecret)(u.clientSecret));if(w.kind==="confirmed"){if(!Ql(e,t,u.clientSecret))return;Pe.current=null,j("idle"),c({id:w.paymentMethodId,type:"card",threeDSecureActionResultTokenId:w.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(w.kind==="terminal"){ps(e,t,u.clientSecret),Pe.current=null,j("idle"),xe(u.paymentMethodType),L(!0),wt();return}j("blocked")}catch{C||j("blocked")}finally{Q=!1}}};return Pe.current=ce,j("blocked"),()=>{C=!0,Pe.current===ce&&(Pe.current=null)}},[t,c,wt,e,S]);let ot=(0,o.useCallback)(async u=>{let C=!1,Q=!1,ce=mt=>{C||Q||(C=!0,u.paymentFailed({reason:"fail",...mt?{message:mt}:{}}))};if(!S||!Me){ce();return}let N=zt.current.get(ye);if(N&&!Pt(N.generation)){zt.current.delete(ye),ce();return}if(!N&&X()){ce();return}if(N&&!ue(N.generation)){ce();return}N||(ue(),rt.current=!1);let w=u.expressPaymentType??N?.method??nt.current,qt=N??null,Ar=oc(w),mr;w==="apple_pay"?mr="apple_pay":w==="google_pay"&&(mr="google_pay");let Fr=N?.generation??pt.current,st=A,Gr=st?.now()??globalThis.performance?.now()??Date.now(),Yr=new AbortController,Br=!1,Xt=!1,ar=null,tr=e,In="processing",Jt="other",qn="provider_runtime",Dr,Zt=new Promise((mt,Tt)=>{Dr=Tt}),ir=window.setTimeout(()=>{Br=!0,Yr.abort(),Dr(Ci)},Dd),nn=async(mt,Tt,Or)=>{In=mt,Jt=Tt,qn=Tt==="intent_create"||Tt==="session_claim"?"transport_error":"provider_runtime";let sr=st?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Or,Zt])}finally{let Qt=st?.now()??globalThis.performance?.now()??Date.now();st?.performance({stage:mt,durationMs:Math.max(0,Qt-sr),durationMode:"machine",requestCategory:Tt,paymentMethodCategory:"wallet",provider:"stripe",...Br?{statusClass:"timeout"}:{}})}};try{if(Re(!0),p?.(null),!qt&&R){let be=await nn("processing","other",R(Ar));if(!be.proceed){ce();return}qt={accountPatch:be.accountPatch,sessionId:be.sessionId,nonce:be.nonce}}let mt=qt?.sessionId??e;tr=mt;let Tt=qt?.nonce??t,Or=ut.current??qt?.accountPatch,sr=uc({event:u,fallbackEmail:Or?.email??r,fallbackName:[Or?.firstName,Or?.lastName].join(" ").trim()||_});if(!(0,l.isValidEmail)(sr.email)){ce("Buyer details are required."),F(hs(w),sr).then(be=>{be&&(ut.current=be)});return}ut.current=null;let Qt={...qt?.accountPatch,...(0,Cn.compactBuyerIdentity)(sr,!0)};await nn("processing","session_claim",Promise.resolve(H?.(sr)));let{error:zr}=await nn("tokenization","provider_sdk",Me.submit());if(zr){ce(),v(w,zr,"stripe_wallet_submit_failed",N?.generation);return}if(!mt)throw new Error("Missing sessionId or email for payment.");let Pr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:w,paymentMethodId:null,intentKind:a},jt=JSON.stringify({sessionId:mt,nonce:Tt??"",request:Pr}),Lr=Ge.current,Er=Lr?.retryIdentity===jt?Lr.authorizationAttemptId:(0,l.randomUuidV4)();Ge.current={authorizationAttemptId:Er,retryIdentity:jt};let Ce=await nn("processing","intent_create",wi(n,ge,mt,Tt??"",{...Pr,authorizationAttemptId:Er},{signal:Yr.signal}));if((0,l.isSettledSessionIntent)(Ce)){ce(),c({type:"card",paymentMethodType:w},{accountPatch:Qt,paymentMethodCategory:"wallet",sessionId:mt,nonce:Tt,settledProcessResponse:Ce.response});return}if(Ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Nr=Ce.clientSecret,_n=jd({createdAt:Date.now(),sessionId:mt,...Tt?{nonce:Tt}:{},clientSecret:Nr,providerObjectId:Ce.providerObjectId,paymentMethodType:w,accountPatch:Qt});window.clearTimeout(ir),Xt=!0,st?.performance({stage:"callback",durationMs:Math.max(0,(st?.now()??globalThis.performance?.now()??Date.now())-Gr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Tn=st?.now()??globalThis.performance?.now()??Date.now(),vr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...mr?{walletType:mr}:{},attempt:Fr},pn=!1,mn=null;st?.log({name:"payment.provider_confirmation.started",...vr}),ar=window.setTimeout(()=>{ar!==null&&$e.current.delete(ar),pn=!0;let be=st?.now()??globalThis.performance?.now()??Date.now();st?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...vr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,be-Tn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),st?.flush?.().catch(()=>{}),mn?.()},Od),$e.current.add(ar);let Mn=(be,Ut)=>{ar!==null&&(window.clearTimeout(ar),$e.current.delete(ar),ar=null);let tt=st?.now()??globalThis.performance?.now()??Date.now(),at=Math.max(0,tt-Tn),rr=be;pn&&(be==="resolved"?rr="resolved_late":be==="returned_error"?rr="returned_error_late":rr="rejected_late");let Vr=Ut??(be==="resolved"?"approved":"provider_error");return st?.log({name:"payment.provider_confirmation.returned",...vr,operationOutcome:rr,terminalReason:Vr}),st?.performance({...vr,durationMs:at,durationMode:"buyer",operationOutcome:rr,terminalReason:Vr}),{durationMs:at,operationOutcome:rr,terminalReason:Vr}},Lt=!1,ve=!1,on=be=>{if(!be||typeof be!="object")return null;let Ut=be;if(Ut.error)return null;let tt=Ut.setupIntent??Ut.paymentIntent,at=ms(tt??null,void 0,!!Ut.setupIntent);return at.kind==="confirmed"?at:null},K=be=>{if(Lt||N&&pt.current!==N.generation)return;let Ut=on(be);if(!Ut)return;if(_n&&!Ql(mt,Tt,Nr)){Lt=!0;return}let{intentId:tt,paymentMethodId:at}=Ut;Lt=!0,ve=!0,Ge.current=null,Pe.current=null,Be.current&&(j("idle"),Re(!1));let rr=`${lc}:${mt}`;ur(rr,{createdAt:Date.now(),sessionId:mt,nonce:Tt,accountPatch:Qt,paymentMethodId:at,providerIntentId:tt,paymentMethodType:w});try{c({id:at,type:"card",threeDSecureActionResultTokenId:tt},{accountPatch:Qt,paymentMethodCategory:"wallet",sessionId:mt,nonce:Tt})}finally{ur(rr)}},Nt=!1;mn=async()=>{if(!(Nt||Lt||ve)){Nt=!0,Be.current&&j("checking");try{let be=await ec(S,Nr,$e.current);if(Lt||ve)return;let Ut=(0,l.isSetupIntentClientSecret)(Nr),tt=ms(be,Ce.providerObjectId,Ut);if(tt.kind==="confirmed"){K(Ut?{setupIntent:be}:{paymentIntent:be});return}if(tt.kind==="terminal"){if(ve=!0,ps(mt,Tt,Nr),Ge.current=null,Pe.current=null,!Be.current)return;j("idle"),ce(),v(w,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",N?.generation,!0);return}Be.current&&!ve&&(j("blocked"),Re(!1))}catch{Be.current&&!ve&&(j("blocked"),Re(!1))}finally{Nt=!1}}},Pe.current=mn;let ae,Ht;try{Q=!0,V.current+=1;let be;try{be=await((0,l.isSetupIntentClientSecret)(Nr)?S.confirmSetup({elements:Me,clientSecret:Nr,redirect:"if_required"}):S.confirmPayment({elements:Me,clientSecret:Nr,redirect:"if_required"}))}finally{ke()}if(!be||typeof be!="object")throw new Fa(qd(be));if(ae=be,!ae.error&&!on(ae))throw new Fa("confirmation_result_unconfirmed");Ht=Mn(ae.error?"returned_error":"resolved",ae.error&&(0,we.isProviderDecline)(ae.error)?"provider_declined":void 0)}catch(be){let Ut=be instanceof Fa?be.reason:void 0,tt=Ut!==void 0,at=Mn(tt?"returned_error":"rejected");if(st?.error({...tt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Ut}:ns(be),...vr,operationOutcome:at.operationOutcome,durationMs:at.durationMs,statusClass:"unknown",terminalReason:at.terminalReason}),!Be.current||Lt)return;await mn?.();return}let Gt=ae.error;if(Gt){if(!Be.current||Lt)return;if((0,we.isProviderDecline)(Gt)){ve=!0,ps(mt,Tt,Nr),Ge.current=null,Pe.current=null,j("idle"),zt.current.get(ye)===N&&zt.current.delete(ye);let be=Gt.message??"Your payment was declined.";p?.(be),g?.(wr(Ar,be,{code:(0,we.getProviderErrorCode)(Gt),declineCode:(0,we.getProviderDeclineCode)(Gt)})),Ri({billingApiUrl:n,sessionId:mt,nonce:Tt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:w,providerDeclineReason:(0,we.getProviderErrorCode)(Gt)??"provider_declined",...Ce.intentKind==="payment"&&Ce.providerObjectId.startsWith("pi_")?{providerIntentId:Ce.providerObjectId}:{}}})}else st?.error({...ns(Gt),...vr,operationOutcome:Ht.operationOutcome,durationMs:Ht.durationMs,statusClass:"unknown",terminalReason:Ht.terminalReason}),await mn?.();return}if(K(ae),!Lt)throw new Error("Invalid provider returned for APM intent")}catch(mt){if(mt===Ci){let Tt=st?.now()??globalThis.performance?.now()??Date.now();st?.error({errorCode:Wd(Jt),stage:In,requestCategory:Jt,paymentMethodCategory:"wallet",provider:"stripe",...mr?{walletType:mr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:tr,durationMs:Math.max(0,Tt-Gr),statusClass:"timeout",failureCategory:qn,attempt:Fr,terminalReason:"provider_error"}),st?.flush?.().catch(()=>{})}ce(),v(w,mt,mt===Ci?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",N?.generation,mt===Ci)}finally{if(window.clearTimeout(ir),ar!==null&&(window.clearTimeout(ar),$e.current.delete(ar)),!Xt){let mt=st?.now()??globalThis.performance?.now()??Date.now();st?.performance({stage:"callback",durationMs:Math.max(0,mt-Gr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Br?{statusClass:"timeout"}:{}})}Be.current&&Re(!1)}},[S,Me,e,t,r,_,F,H,n,ge,a,c,p,g,R,v,ke,ue,Pt,X,pt,A,ye]),De=(0,o.useMemo)(()=>fi(s),[s]),Oe=(0,o.useMemo)(()=>s.map(l.stripeExpressMethodToOptionKey),[s]),_t=(0,o.useMemo)(()=>(0,d.jsx)(dr.ExpressCheckoutElement,{onReady:u=>{he(Ta(u,Oe))},onLoadError:u=>{he("load_error"),Cs(A,"stripe","wallet","provider_error")},onClick:async u=>{let C=A?.now()??globalThis.performance?.now()??Date.now();nt.current=u.expressPaymentType,je.current=oc(u.expressPaymentType);let Q=!0,ce=window.setTimeout(()=>{Q=!1,u.reject(),U(u.expressPaymentType)},Fd),N=R?await R(je.current,{abandoned:()=>!Q}):{proceed:!0};if(window.clearTimeout(ce),!Q)return;if(!N.proceed){zt.current.delete(ye),u.reject();return}let w=Ft(u.expressPaymentType);rt.current=!1,Rt.current={generation:w,startedAt:C},zt.current.set(ye,{generation:w,method:u.expressPaymentType,accountPatch:N.accountPatch,sessionId:N.sessionId,nonce:N.nonce}),L(!1),A?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:w,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),y?.(je.current),u.resolve()},onConfirm:ot,onCancel:()=>{let u=zt.current.get(ye);zt.current.delete(ye);let C=Rt.current,Q=A?.now()??globalThis.performance?.now()??Date.now();if(u&&C?.generation===u.generation&&(0,l.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:Q-C.startedAt,handoffObserved:Ot.current===u.generation})){A?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:u.generation,walletType:"google_pay"}),Ge.current=null,v(u.method,new Error("The browser window is too small for the Google Pay sheet."),l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,u.generation,!0);return}A?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),pe(u?.generation),Ge.current=null,L(!1),M.current=!0,wt()},options:{...gi,paymentMethods:De,emailRequired:ct,billingAddressRequired:ct}},ye),[Oe,De,ot,pe,y,ct,v,U,wt,R,Ft,ye,A]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Ma,{state:ie,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Y,children:(0,d.jsxs)("div",{ref:et,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Z&&(0,d.jsxs)("button",{ref:Ue,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ae,style:gs,children:["Try ",hs(Se)," again"]}),le!=="idle"&&(0,d.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,d.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,d.jsx)("button",{type:"button",onClick:Dt,disabled:le==="checking",style:gs,children:le==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ke&&(0,d.jsx)(Ko,{identity:Ke.identity,methodLabel:Ke.methodLabel,onComplete:St,onCancel:()=>St(null)},Ke.id),(0,d.jsxs)("div",{style:{display:Ke||le!=="idle"?"none":void 0},children:[(0,d.jsx)(au,{active:W}),_t]})]})}),fe&&(0,d.jsx)(tn,{status:"processing"})]})}function pc(e,t,r){let n=(0,l.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function Ps({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:c,onTokenizedBody:p,onErrorChange:y,onDecline:g,onCancel:E,runBeforeButtonClick:R,onButtonClick:_,isProcessing:H,submitButtonColor:T,submitButtonBorderRadius:Y,submitButtonStyle:B,errorText:f}){let h=io(),{emitInstrument:ge}=(0,o.useContext)(vn),S=(0,dr.useStripe)(),Me=(0,dr.useElements)(),[A,ie]=(0,o.useState)(!1),he=(0,o.useRef)(!1),[fe,Re]=(0,o.useState)(!1),[ct,Ke]=(0,o.useState)("loading"),[F,St]=(0,o.useState)(""),et=!(0,l.isValidEmail)(n?.trim()),Ue=!et||(0,l.isValidEmail)(F.trim()),ye=(0,o.useCallback)(async()=>{if(!S||!Me||H||he.current||!fe)return;he.current=!0,ie(!0);let J=R?await R("card"):{proceed:!0};if(!J.proceed){he.current=!1,ie(!1);return}_?.("card");let W=J.sessionId??t,Fe=J.nonce??r,dt=(0,$o.splitFullName)(a?.trim()),We=(0,Cn.compactBuyerIdentity)({email:J.accountPatch?.email?.trim()||n?.trim()||F.trim(),firstName:J.accountPatch?.firstName?.trim()||dt.firstName,lastName:J.accountPatch?.lastName?.trim()||dt.lastName}),Z=We.email,L=(0,Cn.compactBuyerIdentity)({...J.accountPatch,...We});try{if(y?.(null),!(0,l.isValidEmail)(Z))throw new Error("A valid email address is required for payment.");await s?.(We);let le=await Me.submit();if(le.error){y?.(le.error.message??"Payment failed.");return}let j=[We.firstName,We.lastName].filter(Boolean).join(" "),Se=await S.createPaymentMethod({elements:Me,params:{billing_details:{email:Z,...j?{name:j}:{}}}});if(Se.error||!Se.paymentMethod){y?.(Se.error?.message??"Failed to create payment method.");return}let xe=Se.paymentMethod;if(!W||!Z)throw new Error("Missing sessionId or email for payment.");let Pe=xe.type||e,Be=await wi(c,ge,W,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Pe,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(Be)){p({type:"card",gateway:"stripe",paymentMethodType:Pe},{accountPatch:L,paymentMethodCategory:"apm",sessionId:W,nonce:Fe,settledProcessResponse:Be.response});return}if(Be.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let M=Be.clientSecret;ur(Jn,{clientSecret:M,sessionId:W,nonce:Fe,accountPatch:L,paymentMethodId:xe.id,paymentMethodType:xe.type??e,gateway:"stripe"});let{error:nt,paymentIntent:je}=await S.confirmPayment({clientSecret:M,confirmParams:{return_url:window.location.href,payment_method:xe.id},redirect:"if_required"});if(nt){ur(Jn);let $e=nt.message??"Payment failed.";y?.($e),g?.(wr("card",$e,{code:nt.code})),await Ri({billingApiUrl:c,sessionId:W,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:nt.code??"provider_declined"}});return}let ut=je?.status;if(!ha(ut)){ur(Jn);let $e=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.($e),g?.(wr("card",$e,{code:ut??"missing_payment_intent"}));return}ur(Jn);let Ge=typeof je?.payment_method=="string"?je.payment_method:je?.payment_method?.id;p({id:Ge??xe.id,type:"card",threeDSecureActionResultTokenId:je?.id,gateway:"stripe",paymentMethodType:xe.type??e},{accountPatch:L,paymentMethodCategory:"apm",sessionId:W,nonce:Fe})}catch(le){y?.(le instanceof Error?le.message:"Payment failed. Please try again.")}finally{he.current=!1,ie(!1)}},[S,Me,H,fe,R,_,t,r,n,a,F,s,c,ge,e,p,y,g]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[et&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:et&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:F,onChange:J=>St(J.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(dr.PaymentElement,{onReady:()=>Ke("ready"),onLoadError:()=>{Ke("load_error"),Cs(Rr(h),"stripe","apm")},onChange:J=>{Re(!!J.complete)},options:{layout:hi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,l.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,d.jsx)(Pi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ye()},disabled:!fe||!Ue||A||H||ct!=="ready",color:T,borderRadius:Y,style:B,children:A?"Processing\u2026":`Pay with ${(0,l.getStripeMethodDisplayName)(e)}`}),f&&(0,d.jsx)(Xo,{margin:"0.75rem 0 0",children:f})]})}function sc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:c,stripeInstance:p,paymentElementBaseOptions:y,futureUseSession:g,onTokenizedBody:E,onErrorChange:R,onButtonClick:_,onDecline:H,runBeforeButtonClick:T,onLoadStateChange:Y,isProcessing:B=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:h=8,submitButtonStyle:ge,buttonAppearance:S,themeId:Me,onExpandApm:A,expandedApmMethod:ie}){let{emitInstrument:he}=(0,o.useContext)(vn),[fe,Re]=(0,o.useState)(null),[ct,Ke]=(0,o.useState)(null),F=(0,o.useRef)(!1),{request:St,collect:et,finish:Ue}=Ho();(0,o.useEffect)(()=>{c.length>0&&p?Y?.("ready"):p||Y?.("loading")},[c.length,p,Y]);let ye=(0,o.useCallback)(async Z=>{if(!p||F.current||B)return;F.current=!0,Ke(Z);let L=T?await T("card"):{proceed:!0};if(!L.proceed){F.current=!1,Ke(null);return}_?.("card");let le=L.sessionId??e,j=L.nonce??t,Se=(0,$o.splitFullName)([L.accountPatch?.firstName,L.accountPatch?.lastName].filter(Boolean).join(" ")||n),xe=(0,Cn.compactBuyerIdentity)({email:L.accountPatch?.email?.trim()||r?.trim(),firstName:L.accountPatch?.firstName?.trim()||Se.firstName,lastName:L.accountPatch?.lastName?.trim()||Se.lastName});if(!(0,l.isValidEmail)(xe.email)){Ke(null);let M=await et((0,l.getStripeMethodDisplayName)(Z),xe);if(!M){F.current=!1;return}xe=M,Ke(Z)}let Pe=xe.email,Be=(0,Cn.compactBuyerIdentity)({...L.accountPatch,...xe});try{if(R?.(null),!le||!(0,l.isValidEmail)(Pe))throw new Error("Missing sessionId or email for payment.");await a?.(xe);let M=await wi(s,he,le,j??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(M)){E({type:"card",gateway:"stripe",paymentMethodType:Z},{accountPatch:Be,paymentMethodCategory:"apm",sessionId:le,nonce:j,settledProcessResponse:M.response});return}if(M.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let nt=M.clientSecret;ur(Jn,{clientSecret:nt,sessionId:le,nonce:j,accountPatch:Be,paymentMethodType:Z,gateway:"stripe"});let{error:je,paymentIntent:ut}=await p.confirmPayment({clientSecret:nt,confirmParams:{return_url:window.location.href,payment_method_data:{type:Z,billing_details:{name:[xe.firstName,xe.lastName].filter(Boolean).join(" "),...Pe?{email:Pe}:{}}}},redirect:"if_required"});if(je){ur(Jn);let Rt=je.message??"Payment failed.";R?.(Rt),H?.(wr("card",Rt,{code:je.code})),await Ri({billingApiUrl:s,sessionId:le,nonce:j,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,providerDeclineReason:je.code??"provider_declined"}});return}let Ge=ut?.status;if(!ha(Ge)){ur(Jn);let Rt=Ge==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";R?.(Rt),H?.(wr("card",Rt,{code:Ge??"missing_payment_intent"}));return}ur(Jn);let $e=typeof ut?.payment_method=="string"?ut.payment_method:ut?.payment_method?.id;E({id:$e??ut?.id,type:"card",threeDSecureActionResultTokenId:ut?.id,gateway:"stripe",paymentMethodType:Z},{accountPatch:Be,paymentMethodCategory:"apm",sessionId:le,nonce:j})}catch(M){R?.(M instanceof Error?M.message:"Payment failed. Please try again.")}finally{F.current=!1,Ke(null)}},[p,B,T,_,e,t,r,et,s,he,n,a,E,R,H]),[J,W]=(0,o.useState)(null),Fe=A?ie??null:J,dt=(0,o.useCallback)(Z=>{F.current||B||Fe&&Fe!==Z||((0,l.needsStripeMethodExplicitConfirm)(Z)?A?A(Z):W(Z):ye(Z))},[Fe,B,ye,A]),We=(0,o.useMemo)(()=>J?pc(y,J,g):null,[J,y,g]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:St?(0,d.jsx)(Ko,{identity:St.identity,methodLabel:St.methodLabel,onComplete:Ue,onCancel:()=>Ue(null)},St.id):c.map(Z=>{let L=ie===Z,le=ct===Z,j=ct!==null&&ct!==Z||ie!=null&&ie!==Z;return(0,d.jsxs)(o.default.Fragment,{children:[(0,d.jsx)(yi,{method:Z,themeId:Me,submitting:le,disabled:j,highlighted:L,hasNextStep:(0,l.needsStripeMethodExplicitConfirm)(Z),onClick:()=>dt(Z),backgroundColor:S?.backgroundColor,borderColor:S?.borderColor,textColor:S?.textColor,borderRadius:S?.borderRadius,fontFamily:S?.fontFamily}),!A&&J===Z&&We&&p&&(0,d.jsx)(dr.Elements,{stripe:p,options:We,children:(0,d.jsx)(Ps,{method:Z,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:E,onErrorChange:R,onDecline:H,onCancel:()=>W(null),runBeforeButtonClick:T,onButtonClick:_,isProcessing:B,submitButtonColor:f,submitButtonBorderRadius:h,submitButtonStyle:ge})},Z)]},Z)})})}function iu({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:c,onError:p,onDecline:y,onCancel:g,onTokenizedBody:E,firstName:R,lastName:_,chv:H,className:T,submitLabel:Y,isProcessing:B,error:f,onErrorChange:h,showPayPal:ge=!0,showStripe:S=!0,walletPresentation:Me="auto",enabledPaymentMethods:A,enabledPaymentMethodCountries:ie,showApplePay:he=!0,showGooglePay:fe=!0,layout:Re="default",theme:ct,buttonsTheme:Ke,buttonsStyles:F,appearance:St,cardButtonContent:et,cardBackButtonContent:Ue,cardTitleContent:ye,showSecurityFooter:J,onButtonClick:W,onBeforeButtonClick:Fe,onBuyerIdentityReady:dt,enableAVS:We,cardFieldOrder:Z,cardAutoFocus:L,cardPreFormSlot:le,avsLayout:j="row",country:Se,zip:xe,addressLine1:Pe,addressLine2:Be,city:M,state:nt,onCountryChange:je,onZipChange:ut,avsCheck:Ge,checkoutType:$e,checkoutLayout:Rt,totalAmount:Ot=0,currency:zt="usd",initialCardOpen:Ft=!1,directPaypal:ue,isSubscription:pe=!1,session:X,dataAttachmentPending:Pt=!1,dataAttachmentRequiresIdentity:pt=!1,debug:V=!1}){let rt=io(),wt=ri(),ke=(0,o.useContext)(On),{emitInstrument:v}=(0,o.useContext)(vn),U=(0,o.useRef)(null);U.current||(U.current=oi());let ne=U.current,[,Ae]=(0,o.useState)(0),Dt=(0,o.useRef)(null);Dt.current||(Dt.current=(0,Gn.detectPayPalEnvironment)());let ot=Dt.current,De=(0,o.useMemo)(()=>({browser:ot,capability:ne,presentationMode:"popup"}),[ot,ne]),Oe=X??ke.session,_t=(0,o.useMemo)(()=>({futureUse:Oe?.futureUse,futureUseUnsupported:Oe?.futureUseUnsupported}),[Oe?.futureUse,Oe?.futureUseUnsupported]),u=Oe?.gateways?.paypal?.providerObjectType??ue?.providerObjectType,C=Pt||ke.claimPending===!0,Q=pt||ke.claimRequiresIdentity===!0,ce=C&&!Q,N=Ol(),w=r||N,[qt,Ar]=(0,o.useState)(!1),[mr,Fr]=(0,o.useState)(null),[st,Gr]=(0,o.useState)(Se??""),[Yr,Br]=(0,o.useState)(xe??""),[Xt,ar]=(0,o.useState)(Pe??""),[tr,In]=(0,o.useState)(Be??""),[Jt,qn]=(0,o.useState)(M??""),[Dr,Zt]=(0,o.useState)(nt??""),[ir,nn]=(0,o.useState)(""),[mt,Tt]=(0,o.useState)({}),Or=(0,o.useRef)(xe??""),sr=(0,o.useRef)(Se??""),Qt=(0,o.useRef)(Pe??""),zr=(0,o.useRef)(Be??""),Pr=(0,o.useRef)(M??""),jt=(0,o.useRef)(nt??""),Lr=(0,o.useRef)(""),Er=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(b,$,_e,G,Te)=>{if(Er.current[b])return;let $t=$?.trim();!$t||$t===_e.current||(_e.current=$t,G($t),Te?.($t))};i("country",Se,sr,Gr,je),i("zip",xe,Or,Br,ut),i("addressLine1",Pe,Qt,ar),i("addressLine2",Be,zr,In),i("city",M,Pr,qn),i("state",nt,jt,Zt)},[Se,xe,Pe,Be,M,nt,je,ut]);let Ce=(0,o.useMemo)(()=>(0,l.resolveAVSConfig)(We),[We]),Nr=Ce!==null,_n=(0,o.useMemo)(()=>(0,l.isAuthorizationOnlySession)(X),[X]),Tn=(0,l.isMountableVaultBlock)(X?.vault),vr=!!X?.gateways?.pcivault,pn=(0,Dn.hasServerSideCardGateway)(X),Mn=!!(X?.gateways?.stripe?.enabledPaymentMethods??A)?.includes("card")||(0,Dn.canRecoverHostedCardForm)(X),Lt=Tn||Mn||vr,ve=!!(S&&Lt&&e),[on,K]=(0,o.useState)(()=>Re!=="buttons"||Ft?e??null:null),[Nt,ae]=(0,o.useState)(0),Ht=Re!=="buttons"||Ft||!!e&&on===e,Gt=X?.captureMethod,be=(0,o.useRef)(rt);(0,o.useEffect)(()=>{be.current=rt},[rt]);let[Ut,tt]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!ve||!e||!Ht){tt(null);return}let i=be.current?be.current.cardCapture({sessionId:e,captureMethod:Gt}):new zn.PciVaultCardCapture({sessionId:e,captureMethod:Gt,billingApiUrl:w,telemetry:n});return tt({sessionId:e,captureMethod:Gt,billingApiUrl:w,telemetry:n,capture:i}),()=>{i.unmount()}},[ve,e,Ht,Gt,w,n]);let at=ve&&e&&Ht&&Ut?.sessionId===e&&Ut.captureMethod===Gt&&Ut.billingApiUrl===w&&Ut.telemetry===n?Ut.capture:null,rr=(0,o.useMemo)(()=>{let i=st,b=Ce?(0,l.isAVSFieldVisible)(Ce.postal_code,i):!1;return tu(i,Yr,b)},[Ce,st,Yr]),{avsInvalid:Vr,invalidAvsFields:yn}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!ve||!Ce)return{avsInvalid:!1,invalidAvsFields:i};let b=st,$=(Te,$t)=>(0,l.isAVSFieldVisible)(Te,b)&&!$t.trim(),_e={line1:$(Ce.address_line_1,Xt),city:$(Ce.city,Jt),state:$(Ce.state,Dr),zip:rr.empty||rr.malformed};return{avsInvalid:_e.line1||_e.city||_e.state||_e.zip,invalidAvsFields:_e}},[ve,Ce,st,Xt,Jt,Dr,rr]),[lr,jn]=(0,o.useState)(!1),[Vn,eo]=(0,o.useState)(!1),[xn,po]=(0,o.useState)(!1),[to,an]=(0,o.useState)({line1:!1,city:!1,state:!1}),An=(0,o.useRef)(!1),sn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Wn=(0,o.useRef)(!1),Vt=(0,o.useCallback)(i=>{sn.current[i]=!0,Wn.current=!0},[]),Xr=(0,o.useCallback)(i=>!An.current&&sn.current[i],[]),Jr=(0,o.useCallback)(i=>{Xr(i)&&an(b=>b[i]?b:{...b,[i]:!0})},[Xr]),[Zr,fn]=(0,o.useState)(()=>(0,l.resolveVaultMountOptions)(X?.vault,{billingApiUrl:w,sessionId:e,nonce:t})),[yt,nr]=(0,o.useState)(Ft&&Lt?"card":"buttons"),[Ir,Wr]=(0,o.useState)(null),_o=yt==="expanding"||yt==="card",gn=X?.gateways?.stripe&&!pn?"stripe":void 0,ro=(0,o.useCallback)(()=>{v?.({class:"card_surface",provider:gn})},[gn,v]),ln=(0,o.useRef)(null),Cr=(0,o.useCallback)(i=>{ln.current&&clearTimeout(ln.current),ln.current=setTimeout(()=>{ln.current=null,i()},Ba)},[]);(0,o.useEffect)(()=>()=>{ln.current&&clearTimeout(ln.current)},[]);let mo=(0,o.useRef)(!1),[qr,z]=(0,o.useState)(0),O=(0,o.useRef)(null),se=(0,o.useCallback)(()=>{ro(),K(e??null),mo.current&&(mo.current=!1,z(i=>i+1)),ae(i=>i+1),nr("expanding"),Cr(()=>nr("card"))},[Cr,ro,e]),me=(0,o.useCallback)(()=>{nr("collapsing"),Cr(()=>nr("buttons"))},[Cr]),kt=(0,o.useCallback)(i=>{Wr(i),nr("apm-expanding"),Cr(()=>nr("apm-form"))},[Cr]),Wt=(0,o.useCallback)(()=>{nr("apm-collapsing"),Cr(()=>{nr("buttons"),Wr(null)})},[Cr]);(0,o.useEffect)(()=>{Re==="buttons"&&Ft&&Lt&&(K(e??null),nr("card"))},[Re,Ft,Lt,e]);let[Ve,oe]=(0,o.useState)(null),te=(0,o.useRef)(null),[Je,Ee]=(0,o.useState)(0);(0,o.useEffect)(()=>{Je!==0&&te.current?.focus()},[Je]);let it=(0,o.useRef)(!1),q=(0,o.useRef)(null),ee=(0,o.useRef)("idle"),[Bt,Et]=(0,o.useState)(!1),x=(0,o.useRef)(Bt);x.current=Bt;let[m,I]=(0,o.useState)(()=>ue?.existingOrderId?{orderId:ue.existingOrderId,attempts:1}:null),Le=(0,o.useRef)(m);(0,o.useEffect)(()=>{Le.current=m},[m]);let Ze=(0,o.useRef)(null),He=(0,o.useMemo)(()=>{if(dt||ke.claimBuyerIdentity||X?.buyerIdentified!==!1||!e||!t)return;let i=`${w}|${e}|${t}`;Ze.current?.key!==i&&(Ze.current={key:i,claim:Vo(new zn.PaymentAPI(w,{telemetry:!1}),e,t,{...s?{userId:s}:{},...R?{firstName:R}:{},..._?{lastName:_}:{}})});let b=Ze.current.claim;return async $=>{await b($)}},[dt,ke.claimBuyerIdentity,X?.buyerIdentified,e,t,w,s,R,_]),It=dt??ke.claimBuyerIdentity??He,Ye=f??mr,br=(0,o.useMemo)(()=>(0,l.resolveTheme)(ct),[ct]),de=(0,o.useMemo)(()=>{let i=br?.buttonsLayout??(0,l.resolveButtonsLayoutTheme)(Ke);return F?{...i,...F,cardButton:{...i.cardButton,...F.cardButton},cardFormContainer:{...i.cardFormContainer,...F.cardFormContainer},backButton:{...i.backButton,...F.backButton},backButtonIcon:{...i.backButtonIcon,...F.backButtonIcon},submitButton:{...i.submitButton,...F.submitButton},title:{...i.title,...F.title}}:i},[br,Ke,F]),Sr=St??br?.appearance,Mt=(0,o.useMemo)(()=>(0,l.computeVaultCardThemeColors)({appearance:Sr,buttonsStyles:de,layout:Re}),[Sr,de,Re]),xt=ke.inlineSessionPatchProcessing??!1,Ie=(B??qt)||xt,vt=w.replace(/\/+$/,""),re=(0,o.useMemo)(()=>rs({userId:s,email:a,firstName:R,lastName:_,country:Se,zip:xe},mt),[s,a,R,_,Se,xe,mt]),_r=[re.firstName,re.lastName].filter(i=>!!i?.trim()).join(" "),Yt=!(0,l.isValidEmail)(re.email?.trim()),To=(0,o.useRef)(null);ve&&To.current===null&&(To.current=Yt);let yo=ve&&(To.current??Yt),Bi=(0,o.useMemo)(()=>ru(ir,yo),[ir,yo]),Mo=Bi.empty||Bi.malformed,cn=(0,o.useMemo)(()=>rt?rt.getRawProvider():null,[rt]),Fs=(0,o.useMemo)(()=>wt?wt.getRawProvider():null,[wt]),oa=Ot||100,xo=zt.toLowerCase(),Di=(0,o.useMemo)(()=>Sr?(0,zn.toStripeAppearance)(Sr):null,[Sr]),Ao=Di,Bs=(0,o.useMemo)(()=>{let i=Di??{},b=i.rules??{};return{...i,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[Di]),Ds=(0,o.useMemo)(()=>({...Fl(Ot,Oe?.captureMethod,_t),currency:xo,...Ao?{appearance:Ao}:null}),[Ot,xo,Oe?.captureMethod,_t,Ao]),Oi=(0,l.resolveSetupFutureUsage)(_t,"paypal","paypal"),Os=(0,o.useMemo)(()=>({mode:"payment",amount:oa,currency:xo,captureMethod:"manual",...Oi?{setupFutureUsage:Oi}:null,...Ao?{appearance:Ao}:null}),[oa,xo,Oi,Ao]),ze=(0,o.useCallback)(i=>{Fr(i),h?.(i)},[h]),Ls=(0,o.useRef)(0);(0,o.useEffect)(()=>{qr!==Ls.current&&(Ls.current=qr,ze(null))},[qr,ze]);let Li=(0,o.useRef)(""),[Ns,Dc]=(0,o.useState)(!1),Ni=(0,o.useCallback)(()=>{Dc(!0)},[]);(0,o.useEffect)(()=>{if(!ve||!yo||!It||!Ns||Mo||Li.current)return;let i=(0,Cn.compactBuyerIdentity)({email:(0,l.isValidEmail)(re.email?.trim())?re.email?.trim():Lr.current.trim(),firstName:re.firstName?.trim(),lastName:re.lastName?.trim()});Li.current=JSON.stringify(i),Tt(b=>({...b,...i})),Promise.resolve(It(i)).catch(b=>{Li.current="",ze(b instanceof Error?b.message:"Failed to attach buyer details.")})},[ve,yo,It,Ns,Mo,re.email,re.firstName,re.lastName,ze]),(0,o.useEffect)(()=>{if(!ve||!at)return;let i=L!==!1&&Ce==null&&!yo;at.setCardFieldOrder?.(Z??null,i)},[ve,at,Z,L,Ce,yo]),(0,o.useEffect)(()=>{(yt==="expanding"||yt==="collapsing"||yt==="apm-expanding"||yt==="apm-collapsing")&&ze(null)},[yt,ze]);let $n=(0,o.useCallback)((i,b,$)=>{y?.(wr(i,b,$))},[y]),Us=(0,o.useRef)(yt);Us.current=yt;let[zs]=(0,o.useState)(ii),qs=(0,o.useCallback)(()=>{let i=Us.current;if(Re==="buttons"&&(i==="card"||i==="expanding"))return!0;let b=ee.current;return b==="validation-window"||b==="processing"||x.current},[Re]),js=(0,o.useCallback)((i,b,$)=>{zs.take(e)&&Rr(rt)?.log(ko({...De,presentationMode:$?.presentationMode??"popup"},{name:ai,stage:"recovery",reason:"other_method_active",provider:$?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:$?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[De,rt,zs,e]),Ua=(0,o.useCallback)((i,b,$)=>{$?.telemetryReported||Rr(rt)?.error(ko({...De,presentationMode:$?.presentationMode??"popup"},{errorCode:b?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:$?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:$?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:$?.terminalReason??(b?"popup_blocked":"provider_error")}))},[De,rt]),Fo=(0,o.useCallback)((i,b,$)=>{let _e=$?.popupBlocked??(0,we.isPopupBlockedError)(b);if(qs()){Ua(i,_e,$),js(i,b,$);return}if(b instanceof l.FloPayError&&b.code==="checkout_processing_timeout"){Ua(i,!1,$),oe(null),Re==="buttons"&&(nr("buttons"),Wr(null)),ze(b.message),p?.(b);return}_e&&ne.markBlocked()&&Ae(Ct=>Ct+1);let G=hs(i),Te=$?.code===l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,l.buildWalletSheetWindowMessage)(G):(0,we.buildExternalMethodRecoveryMessage)(G,_e,ot.inAppBrowser),$t=(0,we.getProviderErrorCode)(b),Pn=($t?.toLowerCase()==="error"?void 0:$t)??(0,we.sanitizeExternalFailureCode)($?.code)??"external_payment_method_failed",ft=new l.FloPayError(Te,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:Pn,popupBlocked:_e,inAppBrowser:ot.inAppBrowser,appFamily:ot.appFamily,popupCapability:ne.current(),presentationMode:$?.presentationMode??"popup"}});Ua(i,_e,$),oe(null),Re==="buttons"&&(nr("buttons"),Wr(null)),ze(Te),p?.(ft),console.error("[FloPay] External payment method failed:",{method:i,code:Pn,popupBlocked:_e})},[ot,qs,Re,p,ne,js,Ua,ze]);(0,o.useEffect)(()=>{if(!ve||!e){fn(null);return}let i={billingApiUrl:vt,sessionId:e,nonce:t},b=(0,l.resolveVaultMountOptions)(X?.vault,i);if(b){fn(b);return}if(!Ht){fn(null);return}let $=`${vt}\0${e}\0${t??""}`,_e=O.current;if(_e&&_e.key===$){fn(_e.mount);return}fn(null);let G=!0;return new zn.PaymentAPI(vt).getVaultCapture(e,t).then(Te=>{if(!G)return;let $t=(0,l.resolveVaultMountOptions)(Te,i);$t?.verificationRequired&&!Te.html&&(O.current={key:$,mount:$t}),$t?fn($t):ze("Failed to load the secure card form.")}).catch(Te=>{G&&ze(Te instanceof Error?Te.message:"Failed to load the secure card form.")}),()=>{G=!1}},[ve,Ht,Nt,e,X?.vault,vt,t,ze]);let Fn=(0,o.useRef)({onComplete:c,onError:p,updateError:ze,emitDecline:$n,resolvedAccount:re,avsConfig:Ce,avsCheckProp:Ge,sessionId:e,nonce:t,baseUrl:vt,captureMethod:X?.captureMethod,paymentId:X?.paymentId,authorizationExpiresAt:X?.authorizationExpiresAt,serverSideCardGateway:pn});Fn.current={onComplete:c,onError:p,updateError:ze,emitDecline:$n,resolvedAccount:re,avsConfig:Ce,avsCheckProp:Ge,sessionId:e,nonce:t,baseUrl:vt,captureMethod:X?.captureMethod,paymentId:X?.paymentId,authorizationExpiresAt:X?.authorizationExpiresAt,serverSideCardGateway:pn};let Ui=(0,o.useRef)(!1),Vs=(0,o.useCallback)(()=>{let i=Fn.current,b=i.resolvedAccount.email?.trim(),$=(0,l.isValidEmail)(b)?b:Lr.current.trim();if(!(0,l.isValidEmail)($))return null;let _e=i.resolvedAccount.firstName?.trim(),G=i.resolvedAccount.lastName?.trim(),Te=sr.current.trim()||i.resolvedAccount.country?.trim()||"",$t=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.state,Te):!1,Pn=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_1,Te):!1,ft=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.postal_code,Te):!1,Ct=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.city,Te):!1,At=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_2,Te):!1,yr=Pn&&!$t&&ft?(0,l.getStateFromPostalCode)(Te,(Or.current??"").trim()):null,dn=$t?jt.current:yr;return{accountData:{userId:i.resolvedAccount.userId??"",email:$,..._e?{firstName:_e}:{},...G?{lastName:G}:{},...ft&&Or.current?{zip:Or.current}:{},...Ct&&Pr.current?{city:Pr.current}:{},...dn?{state:dn}:{},...Pn&&Qt.current?{addressLine1:Qt.current}:{},...At&&zr.current?{addressLine2:zr.current}:{},...Te?{country:Te}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,l.isAVSFieldVisible)(i.avsConfig.country,Te),postal_code:ft,address_line_1:Pn,address_line_2:At,city:Ct,state:$t}}:{}}},[]),Ws=(0,o.useRef)(C);Ws.current=C,(0,o.useEffect)(()=>{C||Ye!==tc||Fn.current.updateError(null)},[C,Ye]),(0,o.useEffect)(()=>{!ve||!at||at.setSubmitGate?.(Vr||C||Mo||Bt)},[ve,at,Vr,C,Mo,Bt]),(0,o.useEffect)(()=>{if(!ve||!at)return;Ui.current=!1;let i=null,b=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,ee.current="idle",oe(null)},400)},$=at.on("submitting",()=>{jn(!0),q.current&&clearTimeout(q.current),ee.current="validation-window",q.current=setTimeout(()=>{q.current=null,ee.current==="validation-window"&&(ee.current="processing")},$d),oe("processing");let ft=Fn.current;if(!ft.sessionId||!ft.nonce)return;let Ct=Vs();if(!Ct){ft.updateError("Enter a valid email address."),ee.current="idle",oe(null);return}new zn.PaymentAPI(ft.baseUrl).patchAccountSnapshot(ft.sessionId,ft.nonce,Ct,{telemetryMode:"best_effort"}).catch(At=>{if(!Kd(At))return;let yr=At instanceof Error?At.message:"Please check your billing address and try again.";ft.updateError(yr),ee.current="idle",oe(null),ft.onError?.(At instanceof l.FloPayError?At:new l.FloPayError(yr,"api_error"))})}),_e=at.on("complete",ft=>{(0,Nn.markSessionRecentlyCompleted)(ft.sessionId??Fn.current.sessionId),ee.current="terminal",Et(!1),oe("success"),setTimeout(()=>{if(Ui.current)return;Ui.current=!0;let Ct=Fn.current,At=(0,l.isAuthorizationOnlySession)(Ct)||ft.outcome==="authorized",yr=Ct.serverSideCardGateway?{}:{paymentIntentId:ft.intentId};Fn.current.onComplete?.(At?{status:"authorized",...yr,paymentId:ft.paymentId??Ct.paymentId,sessionId:ft.sessionId??Ct.sessionId,authorizationExpiresAt:ft.authorizationExpiresAt??Ct.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...yr,checkoutMethod:"card"})},600)}),G=at.on("decline",ft=>{let Ct=Fn.current,At=ft.message??"Your payment was declined. Please try another card or contact your bank.";ee.current="terminal",Et(!1),Ct.updateError(At),oe("error");let yr=ft.failureOutcome??(0,l.normalizeCheckoutFailureOutcome)(ft.declineReason)??"authorization_declined";Ct.emitDecline("card",At,{code:yr,declineCode:yr}),b()}),Te=at.on("error",ft=>{let Ct=Fn.current,At=(0,l.buyerEmailRequiredPrompt)(ft.vaultOutcome);if(At!==null){i&&(clearTimeout(i),i=null),ee.current="idle",Et(!1),Ct.updateError(At),oe(null),Ee(dn=>dn+1),Ct.onError?.(new l.FloPayError(At,"api_error",{code:l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let yr=ft.message??"There was a problem processing your payment. Please try again.";ee.current="terminal",Et(!1),Ct.updateError(yr),oe("error"),Ct.onError?.(new l.FloPayError(yr,"api_error",{code:ft.failureOutcome??"capture_failed"})),b()}),$t=at.on("challenge_dismissed",()=>{q.current&&(clearTimeout(q.current),q.current=null),ee.current="processing",Et(!0),oe(null)}),Pn=at.on("blocked",()=>{if(x.current){Fn.current.updateError(Hd);return}if(!Ws.current){jn(!0);return}Ni(),Fn.current.updateError(tc)});return()=>{i&&(clearTimeout(i),i=null),q.current&&(clearTimeout(q.current),q.current=null),ee.current="idle",Et(!1),oe(null),$(),_e(),G(),Te(),$t(),Pn()}},[ve,at,Ni,Vs]);let Hn=!!ue?.clientId,aa=Array.isArray(A),za=aa&&A.length>0,$s=aa&&A.includes("paypal"),qa=(0,o.useRef)(null);qa.current===null&&(qa.current=(0,l.hasMatchingStripePayPalReturn)());let Bo=qa.current?"redirect":(0,Yn.resolveStripePayPalPresentation)(ot,Me,ne.current()),{expressMethods:ja,paymentElementMethods:zi}=(0,o.useMemo)(()=>(0,l.partitionStripeMethods)(A,{excludePaypal:Hn}),[A,Hn]),Hs=Hn||!!wt||$s&&Bo==="redirect",Oc=(0,o.useMemo)(()=>Hs?ja.filter(i=>i!=="paypal"):ja,[ja,Hs]),Lc=(0,o.useMemo)(()=>{let i=[];return he&&i.push("apple_pay"),fe&&i.push("google_pay"),i},[he,fe]),Do=aa?Oc:Lc,Nc=S&&Do.length>0,Ks=Nr?st:Se,Va=(0,o.useMemo)(()=>(0,l.filterStripeMethodsByCountryGate)(zi,Ks,ie),[zi,Ks,ie]),qi=(0,o.useMemo)(()=>({mode:"payment",amount:oa,currency:xo,paymentMethodCreation:"manual",appearance:Bs}),[oa,xo,Bs]),[Gs,Ys]=(0,o.useState)("loading"),[Xs,Js]=(0,o.useState)("loading"),[Zs,Qs]=(0,o.useState)("loading"),[Uc,ji]=(0,o.useState)(!1),[el,Vi]=(0,o.useState)("loading"),[Wi,zc]=(0,o.useState)();(0,o.useEffect)(()=>{zc((0,Gn.detectPayPalEnvironment)())},[]);let Wa=Wi?.inAppBrowser,$a=Wi?(0,Yn.resolvePayPalPresentationMode)(Wi,ue?.approvalPresentation,u??(pe?"subscription":"order")):"popup",tl=ge&&(Hn||(aa?$s:Wa===!1)),qc=ot.inAppBrowser&&ne.current()==="blocked",rl=S&&Nc&&!qc,ia=(!ce||!!ke.waitForDataAttachment)&&tl&&Hn,nl=el==="retrying"||el==="exhausted",sa=null;S&&(wt?sa=Fs:Bo==="redirect"&&(sa=cn));let ol=(0,o.useMemo)(()=>({...De,presentationMode:Bo}),[De,Bo]),la=!ce&&tl&&!!sa&&(!Hn||nl),Oo=!ce&&rl&&!!cn,ca=!ce&&S&&za&&Va.length>0&&!!cn,jc=ia&&!nl?Uc:la&&ds(Gs),Vc=Oo&&ds(Xs),Wc=ca&&Zs!=="load_error",al=i=>i==="loading"||i==="ready",il=ia||la&&al(Gs)||Oo&&al(Xs)||ca&&Zs!=="load_error",Ha=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Ha.current){if(!S&&!ge){Ha.current=!0;let i=new l.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),ze(i.message)}else if(!S&&ge&&!Hn){Ha.current=!0;let i=new l.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),ze(i.message)}else if(Wa!==void 0&&!ce&&!Lt&&!il){Ha.current=!0;let i=new l.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(i),ze(i.message)}}},[S,ge,Hn,Wa,ce,Lt,il,p,ze]);let sl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(sl.current||!za)return;let i=[];he!==!0&&i.push("showApplePay"),fe!==!0&&i.push("showGooglePay"),i.length!==0&&(sl.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.`))},[za,he,fe]);let ll=(0,o.useCallback)((i,b,$)=>ke.applyInlineSessionPatch?ke.applyInlineSessionPatch(i).then(_e=>({error:null,sessionId:_e.sessionId||e,nonce:_e.session?.clientSecret||t})).catch(_e=>{let G=(0,l.normalizeBeforeButtonClickError)(b,_e);return $?.abandoned?.()||(ze(G.message),p?.(G)),{error:G,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ke.applyInlineSessionPatch,t,p,e,ze]),Bn=(0,o.useCallback)(async(i,b)=>{if(i!=="card"&&ce&&await ke.waitForDataAttachment?.(),!Fe)return{proceed:!0};try{let $=await Fe({method:i,sessionId:e||void 0,createSession:ke.inlineSessionDraft});if($===!1)return{proceed:!1};if($&&typeof $=="object"){$.account&&Tt(G=>({...G??{},...$.account}));let _e=await ll($,i,b);return _e.error?{proceed:!1,accountPatch:$.account}:{proceed:!0,accountPatch:$.account,sessionId:_e.sessionId,nonce:_e.nonce}}return{proceed:!0}}catch($){if(!b?.abandoned?.()){let _e=(0,l.normalizeBeforeButtonClickError)(i,$);ze(_e.message),p?.(_e)}return{proceed:!1}}},[ll,ke.inlineSessionDraft,ke.waitForDataAttachment,ce,Fe,p,e,ze]),cl=(0,o.useCallback)(async(i,b)=>{if(it.current)return;it.current=!0,Ar(!0),oe("processing"),ze(null);let $=b?.sessionId??e,_e=b?.nonce??t,G=rs(re,b?.accountPatch),Te=b?.completionPaymentMethodId??Pa(i),$t=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,Pn=Jd(i),ft=b?.presentationMode?mi(Rr(rt),{...De,presentationMode:b.presentationMode}):void 0,Ct=()=>{v?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Pn}),ft?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Un,requestCategory:"process_payment"})};try{let At=new zn.PaymentAPI(vt),dn=b?.settledProcessResponse??await At.processPayment(G.userId??"",{sessionId:$,nonce:_e,paymentMethodCategory:b?.paymentMethodCategory??Qd(i),tokenizedData:$t,accountData:{...b?.accountPatch,userId:G.userId??"",email:G.email??"",firstName:G.firstName||void 0,lastName:G.lastName||void 0,...(0,l.buildProcessPaymentAvsAccount)({avsConfig:Ce,country:sr.current,zip:Or.current,city:Pr.current,state:jt.current,addressLine1:Qt.current,addressLine2:zr.current})},...(0,l.buildCheckoutProcessMetadata)({chv:H,avsCheck:Ge,checkoutType:$e,checkoutLayout:Rt,avsConfig:Ce,country:sr.current})}),Ja=async Tr=>{let Co=(0,l.isAuthorizationOnlySession)(X)||Tr?.status==="authorized";(0,Nn.markSessionRecentlyCompleted)($),ft?.terminal({outcome:"payment_succeeded",...Un}),oe("success"),I(null),await new Promise(fa=>setTimeout(fa,600));let Kn;typeof Tr?.paymentId=="string"?Kn=Tr.paymentId:X?.paymentId&&(Kn=X.paymentId);let bo;typeof Tr?.authorizationExpiresAt=="string"?bo=Tr.authorizationExpiresAt:X?.authorizationExpiresAt&&(bo=X.authorizationExpiresAt),c?.(Co?{status:"authorized",...Kn===void 0?{}:{paymentId:Kn},sessionId:typeof Tr?.sessionId=="string"?Tr.sessionId:$,...bo===void 0?{}:{authorizationExpiresAt:bo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Te,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Te,checkoutMethod:i.isPaypal?"paypal":"card"})};if(dn.ok){await Ja(dn.status===204?null:await dn.json().catch(()=>null));return}let fr=await dn.json().catch(()=>null);if(fr?.type==="paypal_redirect_required"){let Tr=fr.threeDSecureToken,Co=fr.paymentMethodId||i.id||"";if(!rt||!Tr){oe("error"),ze("PayPal authorization required but no token provided.");return}try{let Kn=wt?.getRawProvider();if(!Kn){ze("PayPal is not available.");return}let bo={return_url:window.location.href};Co&&(bo.payment_method=Co);let{error:fa}=await Kn.confirmPayment({clientSecret:Tr,confirmParams:bo,redirect:"if_required"});if(fa){oe("error");let bl=fa.message??"PayPal payment failed.";ze(bl),$n("paypal",bl,{code:fa.code})}}catch(Kn){oe("error"),ze(Kn instanceof Error?Kn.message:"PayPal authorization failed.")}return}if(fr?.type==="paypal_direct_required"){let Tr=fr.orderId;if(!Tr){oe("error"),ze("PayPal retry required but no order id provided.");return}let Co=Le.current?.attempts??0;if(Co>=2){oe("error"),ze("PayPal payment could not be completed after multiple attempts."),$n("paypal","paypal_direct_required retry limit exceeded");return}ji(!1),Vi("loading"),I({orderId:Tr,attempts:Co+1}),oe(null);return}if(dn.headers.get(Nd)===Ud){let Tr=await zd(At,$,_e);if(Tr!==void 0){await Ja(Tr);return}}(0,l.classifyPaymentRejection)(dn.status,fr)?ft?.terminal({outcome:"payment_declined",...Un,terminalReason:"provider_declined"}):Ct(),oe("error");let Cl=fr?.message??"Payment failed. Please try again.";ze(Cl),$n(i.isPaypal?"paypal":"card",Cl,{code:fr?.code??fr?.gatewayErrorCode,declineCode:fr?.declineCode??fr?.gatewayDeclineReason}),await new Promise(Tr=>setTimeout(Tr,400))}catch(At){dc(At)||Ct(),oe("error"),ze(At instanceof Error?At.message:"An unexpected error occurred"),await new Promise(yr=>setTimeout(yr,400))}finally{Ar(!1),oe(null),it.current=!1}},[vt,e,t,re,Ce,Ge,$e,Rt,H,rt,wt,X,c,ze,$n,v,De]),Qr=(0,o.useCallback)((i,b)=>{E&&!b?.settledProcessResponse?E(i):cl(i,b)},[E,cl]),da=`${lc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(da);if(!i)return;let b;try{b=JSON.parse(i)}catch{ur(da);return}if(!b||typeof b.createdAt!="number"||Date.now()-b.createdAt<0||Date.now()-b.createdAt>cc||typeof b.paymentMethodId!="string"||typeof b.providerIntentId!="string"||typeof b.paymentMethodType!="string"||b.sessionId!==e||!t||b.nonce!==t||!Do.includes(b.paymentMethodType)){ur(da);return}ur(da),Qr({id:b.paymentMethodId,type:"card",threeDSecureActionResultTokenId:b.providerIntentId,gateway:"stripe",paymentMethodType:b.paymentMethodType},{...b.accountPatch?{accountPatch:b.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Qr,t,e,da,Do]);let dl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||dl.current)return;let[i,b,$]=(0,l.readStripeRedirectParams)();if(!i||!b||qa.current||!rt)return;let _e=rt.getRawProvider();if(!_e)return;let G=Ct=>{let At=localStorage.getItem(Ct);if(!At)return null;try{return JSON.parse(At)}catch{return ur(Ct),null}},Te=G(Jn)??G(Zl),$t;if(Te?.clientSecret){if(Te.clientSecret!==b)return;$t={...Te.accountPatch?{accountPatch:Te.accountPatch}:{},...Te.sessionId?{sessionId:Te.sessionId}:{},...Te.nonce?{nonce:Te.nonce}:{}}}else if(Te?.sessionId&&Te.sessionId!==e)return;dl.current=!0,ur(Jn),ur(Zl),window.history.replaceState({},"",(0,l.stripeRedirectReturnUrl)());let Pn=Te?.paymentMethodType??Te?.tokenType??"card",ft="card";(async()=>{if($==="failed"){let fr="Payment was declined. Please try again.";ze(fr),$n(ft,fr);return}let{paymentIntent:Ct,error:At}=await _e.retrievePaymentIntent(b);if(At){let fr=At.message??"Failed to retrieve payment status.";ze(fr),$n(ft,fr,{code:At.code});return}let yr=Ct?.status,dn=ha(yr);if(!Ct||!dn){let fr=yr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ze(fr),$n(ft,fr,{code:yr??"missing_payment_intent"});return}let Ja=typeof Ct.payment_method=="string"?Ct.payment_method:Ct.payment_method?.id;Qr({id:Ja??Te?.paymentMethodId??Te?.tokenId??Ct.id,type:"card",threeDSecureActionResultTokenId:Ct.id,gateway:Te?.gateway??"stripe",paymentMethodType:Pn},$t)})()},[e,Qr,rt,ze,$n]);let $i=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(ve||rt!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ua=Re==="buttons",en=Sr?.variables,$c=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Hi=en?.colorBackground,Hc=Hi&&!$c.has(Hi)?Hi:void 0,pa=de.cardInputBorder??(ua?"#e5e7eb":"#A4A4FF"),ul=en?.colorDanger??"#dc2626",or=i=>yn[i]&&(to[i]||lr),Ka=Mo&&(xn||lr),hn=i=>i?ul:pa,Ga=(rr.malformed||rr.empty)&&(Vn||lr),Kc=hn(Ga),Ki=de.cardFormContainer?.backgroundColor??Hc??(ua?"white":"#EDEDFF"),Lo=de.cardInputBackground??en?.colorBackground??"white",Gi=zo(Ue),pl=zo(ye),No=de.nameInput,ml=de.cardInputFontSize??nu(No?.fontSize)??en?.fontSizeBase??"16px",yl=typeof No?.fontFamily=="string"?No.fontFamily:en?.fontFamily??"Poppins, sans-serif",fl=(0,l.toCssWeight)(No?.fontWeight)??400,Gc=de.cardInputColor??(typeof No?.color=="string"?No.color:void 0)??en?.colorText??"#262833",Yc=de.cardInputPlaceholderColor??"#9ca3af",cr=en?.borderRadius??"8px",Po=en?.borderRadius??de.cardButton?.borderRadius??cr,vo=en?.colorPrimary??"#4A49FF",Xc=en?.colorPrimaryHover??(0,l.darkenHex)(vo,.12),Yi=en?.colorText??"#262833",Xi={fontSize:ml,fontFamily:yl,fontWeight:fl,color:Gc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ma={marginTop:"0.375rem",...Xi,fontSize:"0.75rem",lineHeight:1.4,color:ul},Jc={"--flopay-input-placeholder-color":Yc,"--flopay-input-font-size":ml,"--flopay-input-font-family":yl,"--flopay-input-font-weight":String(fl)},ya=de.cardFormContainer??{},Ji=ya.padding??(ua?"0":"1rem"),Zi=ya.borderRadius??cr,Zc=at&&Zr?(0,d.jsx)(ho,{capture:at,html:Zr.html,messageToken:Zr.messageToken,expectedOrigin:Zr.expectedOrigin,verificationRequired:Zr.verificationRequired,theme:Mt,submitLabel:Y,onReady:()=>{if(!yo&&!Ce||typeof document>"u"||L===!1)return;let i=()=>{let $=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if($){An.current=!0;try{$.focus()}finally{An.current=!1}}};Wn.current||i()},onError:i=>{i&&Zr.verificationRequired&&ee.current==="idle"&&(mo.current=!0),ze(i)},onValidation:i=>{let b=ee.current;(b==="idle"||b==="validation-window")&&(ze(i),i&&ee.current==="validation-window"&&(q.current&&(clearTimeout(q.current),q.current=null),ee.current="idle",oe(null)))}},qr):(0,d.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),gl=(0,d.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&ro()},style:{backgroundColor:Ki,borderRadius:Zi,...ya,padding:Ji,...Jc,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
30
+ `,ta=44;function ra(){return(0,Ir.jsx)("style",{children:Id})}function Ma(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function xa({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Ir.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Ir.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,Ir.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 ds(e){return e!=="unavailable"&&e!=="load_error"}function fi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:c,backgroundColor:p,borderColor:m,textColor:g,borderRadius:_,fontFamily:E}){let I=(0,ao.resolveStripeMethodBrandVariant)(e,t),H=Yl[e],[T,Y]=(0,Xl.useState)(!1),F=!!H&&!T,y=I?.backgroundColor??p??"#ffffff",h=I?.borderColor??m??"#d1d5db",ge=I?.textColor??g??"#262833";return(0,Ir.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&c()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ta,padding:"0 1rem",backgroundColor:y,color:ge,border:`1px solid ${h}`,borderRadius:_??8,fontSize:"0.95rem",fontWeight:600,fontFamily:E,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,Ir.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,ao.getStripeMethodDisplayName)(e)}\u2026`}):(0,Ir.jsxs)(Ir.Fragment,{children:[(0,Ir.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,ao.hasVendoredStripeMethodLogo)(e)?8:0},children:[F?(0,Ir.jsx)("img",{src:H,alt:"","aria-hidden":"true",onError:()=>Y(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!F&&I?.logoSvg?(0,Ir.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,Ir.jsx)("span",{children:(0,ao.getStripeMethodDisplayName)(e)})]}),s&&(0,Ir.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ge,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,Ir.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function gi(e){let t=new Set(e.map(ao.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var hi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Pi={type:"accordion",defaultCollapsed:!1,radios:"never"};function vi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:c,children:p}){return(0,Ir.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:s,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...c??{}},children:p})}var mn=require("react");var Aa=require("@flopay/shared"),Td=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 Md(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Td.has(t.charAt(0).toLowerCase()+t.slice(1))}function xd(e,t){return typeof t=="number"&&t!==0&&!Md(e)?`${t}px`:String(t).trim()}function Jl(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]=xd(r,n)}}}var _o=require("react/jsx-runtime"),us=new WeakSet;function fo({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:c,containerStyle:p,onReady:m,onError:g,onValidation:_}){let E=(0,mn.useRef)(null),I=(0,mn.useRef)(m),H=(0,mn.useRef)(g),T=(0,mn.useRef)(_);I.current=m,H.current=g,T.current=_;let Y=(0,mn.useRef)(s);Y.current=s;let F=(0,mn.useRef)(null),y=c??void 0,h=(0,mn.useRef)(y);h.current=y;let ge=(0,mn.useRef)(void 0);return(0,mn.useEffect)(()=>{let w=E.current;if(!w)return;let Te=!0,x=!1,ie=()=>{!Te||x||(x=!0,I.current?.())},he=e.on("ready",()=>{ie()}),fe=e.on("error",A=>{H.current?.(A.message??"There was a problem loading the secure card form.")}),ke=e.on("validation",A=>{T.current?.(A.message??null)}),mt=h.current??(us.has(e)?null:void 0),Je={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...Y.current?{theme:Y.current}:{},...mt===void 0?{}:{submitLabel:mt}};return F.current=Y.current??null,ge.current=h.current,h.current!==void 0&&us.add(e),e.mount(w,Je).then(()=>{ie()}).catch(A=>{Te&&H.current?.(A instanceof Error?A.message:"Failed to load the secure card form.")}),()=>{Te=!1,he(),fe(),ke(),e.unmount()}},[e,t,r,n,a]),ko(()=>{let w=E.current;w&&Jl(w,p)},[p]),(0,mn.useEffect)(()=>{s!==void 0&&(s===null&&F.current===null||(F.current=s,e.applyTheme?.(s)))},[e,s]),(0,mn.useEffect)(()=>{y!==ge.current&&(ge.current=y,y!==void 0&&us.add(e),e.setSubmitLabel?.(y??null))},[e,y]),(0,_o.jsx)("div",{ref:E,"data-testid":"flopay-vault-card-fields"})}function Ci({label:e}){return(0,_o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,_o.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,_o.jsx)("span",{children:e}),(0,_o.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var Ss=require("@flopay/shared"),d=require("react/jsx-runtime"),Kn="flopay_stripe_resume",Zl="flopay_wallet_resume",lc="fw1",Ad="fw2",cc=300*1e3,Fd=900,Bd="express_checkout_click_timeout",Dd=25e3,Od=25e3,Ld=1e4,On={provider:"paypal",paymentMethodCategory:"paypal"},Nd="x-flopay-process-result-source",Ud="status";async function zd(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 bi={},Ba=class{constructor(t){this.reason=t}};function qd(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function lr(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 vs(e){return`${Ad}:${e}`}function Si(e){return lr(vs(e))}function wi(e,t){if(typeof window>"u")return null;let r=vs(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>cc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Si(e),null):a}catch{return Si(e),null}}function jd(e){return lr(vs(e.sessionId),e)}function Ql(e,t,r){let n=wi(e,t);return!n||n.clientSecret!==r?!1:Si(e)}function ps(e,t,r){if(typeof window>"u")return;wi(e,t)?.clientSecret===r&&Si(e)}function Vd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ms(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=Vd(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function ec(e,t,r){let n=null;try{return await Promise.race([Al(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Ld),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Wd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function dc(e){return e instanceof l.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ki(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Ln.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw dc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var ys=l.STRIPE_PAYPAL_RESUME_KEY,Fa=new Map,$d=250,tc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Hd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Cs(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 Ri({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Ln.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Kd(e){return e instanceof l.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function uc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,Ho.splitFullName)(r),c=s.firstName?s:(0,Ho.splitFullName)(n?.name);return(0,Pn.compactBuyerIdentity)({email:(0,l.isValidEmail)(a)?a:n?.email?.trim(),firstName:c.firstName,lastName:c.lastName})}async function Gd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let c=uc({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,l.isValidEmail)(c.email)?c:s(a,c)}var Da=180,rc=`flopay-card-enter ${Da}ms cubic-bezier(0, 0, 0.2, 1) both`,nc=`flopay-card-exit ${Da}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Yd=`flopay-buttons-enter ${Da}ms cubic-bezier(0, 0, 0.2, 1) both`,Xd=`flopay-buttons-exit ${Da}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Jd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function bs(e){return(0,l.derivePrimaryTileStyle)(e)}var Zd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Qd(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 gs={width:"100%",minHeight:ta,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 oc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function hs(e){return e==="paypal"?"PayPal":(0,l.getStripeMethodDisplayName)(e)}function eu(e){let t=(0,l.getPostalCodeExample)(e);return`Enter a valid ${(0,l.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function tu(e,t,r){let n=(0,l.isPostalCodeSupported)(e),a=t.trim(),s=r&&n,c=s&&!a,p=s&&!!a&&!(0,l.isValidPostalCode)(e,a);return{visible:r,supported:n,required:s,empty:c,malformed:p}}function ru(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,l.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function nu(e){return typeof e=="number"?`${e}px`:e}function Ei(e){return(0,d.jsx)(iu,{...e})}function ac({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:c=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:g,runBeforeButtonClick:_,billingName:E,onBuyerIdentityReady:I,onLoadStateChange:H,placeholderBorderRadius:T,popupCapabilityOwner:Y,externalTelemetryContext:F,presentationMode:y}){let h=no(),{emitInstrument:ge}=(0,o.useContext)(hn),w=(0,sr.useStripe)(),Te=(0,sr.useElements)(),x=(0,o.useMemo)(()=>yi(Sr(h),F),[F,h]),[ie,he]=(0,o.useState)("loading");(0,o.useEffect)(()=>{H?.(ie)},[ie,H]);let[fe,ke]=(0,o.useState)(!1),mt=(0,o.useRef)(!1),Je=!(0,l.isValidEmail)(r?.trim())||!E?.trim(),{request:A,collect:kt,finish:tt}=Ko(),Ve=(0,o.useRef)(!1),me=(0,o.useRef)(null),K=(0,o.useRef)(null),[W,Fe]=(0,o.useState)(0),[lt,He]=(0,o.useState)(!1),J=(0,o.useRef)(!1),D=(0,o.useRef)(new Map),{startAttempt:se,finishAttempt:O,invalidateAttempt:be,isAttemptInvalidated:Me,isAttemptCurrent:Pe,generationRef:Be}=Sa((de,ue,X)=>{g?.(de,ue,{...X,popupBlocked:X?.popupBlocked??(0,we.isPopupBlockedError)(ue),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y,terminalReason:"overlay_timeout"}),He(!0),Fe(bt=>bt+1)},{onHandoffObserved:()=>{Y.markAvailable(),x?.log({name:"provider.popup.opened",stage:"overlay_open",...On,attempt:Be.current})}});(0,o.useEffect)(()=>{lt&&K.current?.focus()},[lt,W]);let M=(0,o.useCallback)(()=>{Fe(de=>de+1)},[]),at=(0,o.useCallback)((de,ue,X)=>{be(X),g?.("paypal",de,{code:ue,popupBlocked:(0,we.isPopupBlockedError)(de),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y}),He(!0),M()},[be,g,y,M]),Ke=(0,o.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{J.current&&(J.current=!1,Ke())},[Ke,W]);let yt=(0,o.useCallback)(()=>{He(!1),s?.(null),Ke()},[Ke,s]);(0,o.useEffect)(()=>{if(!w||Ve.current)return;let[de,ue,X]=(0,l.readStripeRedirectParams)();if(!de||!ue)return;let bt=(0,l.readMatchingStripePayPalContinuation)(ue);if(!bt)return;Ve.current=!0;let ft=!0,V=Fa.get(ue);V||(V=X==="failed"?Promise.resolve(null):Promise.resolve().then(()=>w.retrievePaymentIntent(ue)),Fa.set(ue,V));let rt={accountPatch:bt.accountPatch,sessionId:bt.sessionId,nonce:bt.nonce},Rt=()=>{x?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...On,requestCategory:"provider_sdk"})};return x?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...On}),(async()=>{try{ke(!0);let v=await V;if(!ft)return;if(v?.error){Fa.delete(ue),Rt(),s?.(v.error.message??"Failed to retrieve PayPal payment status.");return}if((0,l.clearStripePayPalReturn)(),Fa.delete(ue),X==="failed"){let oe="PayPal payment was declined. Please try again.";x?.terminal({outcome:"payment_declined",...On,terminalReason:"provider_declined"}),s?.(oe),m?.(br("paypal",oe));return}let q=v?.paymentIntent;if(q&&q.id!==de){Rt(),s?.("Failed to match the returned PayPal payment.");return}if(q&&(q.status==="requires_capture"||q.status==="succeeded")){let oe=typeof q.payment_method=="string"?q.payment_method:q.payment_method?.id;a({id:oe??q.id,type:"card",threeDSecureActionResultTokenId:q.id,isPaypal:!0},{...rt,presentationMode:"redirect"})}else{let oe="PayPal payment was not completed. Please try again.";x?.terminal({outcome:q?.status==="canceled"?"payment_cancelled":"payment_declined",...On,terminalReason:q?.status==="canceled"?"cancelled":"provider_declined"}),s?.(oe),m?.(br("paypal",oe))}}catch(v){if(!ft)return;Fa.delete(ue),Rt(),s?.(v instanceof Error?v.message:"Failed to complete PayPal payment.")}finally{ft&&ke(!1)}})(),()=>{ft=!1,Ve.current=!1}},[w,a,s,m,x]);let Ze=(0,o.useCallback)(async(de=!1)=>{let ue=_?await _("paypal"):{proceed:!0};if(!ue.proceed)return D.current.delete(W),!1;let X=se("paypal");return D.current.set(W,{generation:X,accountPatch:ue.accountPatch,sessionId:ue.sessionId,nonce:ue.nonce}),He(!1),x?.log({name:`provider.${de?"redirect.started":"handoff.requested"}`,stage:de?"redirect":"overlay_open",...On,attempt:X}),p?.("paypal"),!0},[p,x,_,se,W]),Ge=(0,o.useCallback)(async de=>{if(c||fe||!await Ze()){de.reject();return}de.resolve()},[c,Ze,fe]),_t=(0,o.useCallback)(async de=>{if(!w||!Te)return;let ue=D.current.get(W);if(ue&&!Pe(ue.generation)){D.current.delete(W);return}if(!ue&&Me()||ue&&!O(ue.generation))return;ue||O();let X=ue??null;if(D.current.delete(W),!X&&_){let Re=await _("paypal");if(!Re.proceed){de.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}X={accountPatch:Re.accountPatch,sessionId:Re.sessionId,nonce:Re.nonce}}let bt=X?.sessionId??e,ft=X?.nonce??t,V=await Gd({event:de,prepared:X,email:r,billingName:E,methodLabel:"PayPal",collect:kt});if(!V){de.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let rt=V.email,Rt={...X?.accountPatch,...(0,Pn.compactBuyerIdentity)(V,!0)};try{if(ke(!0),s?.(null),!bt||!(0,l.isValidEmail)(rt))throw new Error("Missing sessionId or email for PayPal payment");await I?.(V);let Re=w.createPaymentMethod,{error:v,paymentMethod:q}=await Re({type:"paypal"});if(v){at(v,"stripe_paypal_create_payment_method_failed",ue?.generation),de.paymentFailed({reason:"fail"});return}let oe=await ki(n,ge,bt,ft??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:q?.id??null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(oe)){de.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:Rt,paymentMethodCategory:"paypal",presentationMode:y,sessionId:bt,nonce:ft,settledProcessResponse:oe.response});return}if(oe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let xe=oe.clientSecret,Lt={return_url:(0,l.stripeRedirectReturnUrl)()};if(q?.id&&(Lt.payment_method=q.id),!lr(ys,{clientSecret:xe,sessionId:bt,nonce:ft,accountPatch:Rt})&&y==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:De,paymentIntent:Oe}=await w.confirmPayment({clientSecret:xe,confirmParams:Lt,redirect:"if_required"});if(De){if(lr(ys),(0,we.isProviderDecline)(De)){let u=De.message??"Your payment was declined.";x?.terminal({outcome:"payment_declined",...On,terminalReason:"provider_declined"}),s?.(u),m?.(br("paypal",u,{code:(0,we.getProviderErrorCode)(De),declineCode:(0,we.getProviderDeclineCode)(De)})),await Ri({billingApiUrl:n,sessionId:bt,nonce:ft,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,we.getProviderErrorCode)(De)??"provider_declined"}})}else at(De,"stripe_paypal_confirm_failed",ue?.generation);return}lr(ys);let Tt=typeof Oe?.payment_method=="string"?Oe.payment_method:Oe?.payment_method?.id;a({id:Tt??Oe?.id,type:"card",threeDSecureActionResultTokenId:Oe?.id,isPaypal:!0},{accountPatch:Rt,paymentMethodCategory:"paypal",presentationMode:y,sessionId:bt,nonce:ft});return}catch(Re){at(Re,"stripe_paypal_failed",ue?.generation)}finally{ke(!1)}},[w,Te,e,t,r,E,kt,I,n,ge,a,s,m,_,at,O,Pe,Me,x,y,W]),Ut=(0,o.useCallback)(async()=>{if(!(mt.current||c||fe||!w||!Te)){mt.current=!0,ke(!0);try{if(!await Ze(!0))return;await _t({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{mt.current=!1,ke(!1)}}},[Te,_t,c,Ze,w,fe]),qt=y==="redirect"?(0,d.jsx)("button",{type:"button",disabled:c||fe,onClick:()=>{Ut()},style:{width:"100%",minHeight:ta,border:"1px solid #d1d5db",borderRadius:T??8,background:"#ffc439",color:"#111827",cursor:c||fe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(sr.ExpressCheckoutElement,{onReady:de=>he(Ma(de,["paypal"])),onLoadError:()=>{he("load_error"),Cs(x,"paypal","paypal","provider_error")},onClick:Ge,onConfirm:_t,onCancel:()=>{let de=D.current.get(W);D.current.delete(W),x?.terminal({outcome:"payment_cancelled",...On,terminalReason:"cancelled",...de?{attempt:de.generation}:{}}),be(de?.generation),He(!1),J.current=!0,M()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Je,emailRequired:Je,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},W),Ft=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[lt&&(0,d.jsx)("button",{ref:K,type:"button","data-testid":"flopay-paypal-retry-button",onClick:yt,style:gs,children:"Try PayPal again"}),A&&(0,d.jsx)(Go,{identity:A.identity,methodLabel:A.methodLabel,onComplete:tt,onCancel:()=>tt(null)},A.id),(0,d.jsx)("div",{style:{display:A?"none":void 0},children:qt})]}),fe&&!A&&(0,d.jsx)(rn,{status:"processing"})]});return y==="redirect"?Ft:(0,d.jsx)(xa,{state:ie,placeholderTestId:"flopay-paypal-placeholder",borderRadius:T,children:Ft})}function fs(e){return e==="apple_pay"||e==="google_pay"}var ou=200;function au({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,l.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function ic({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:c,onErrorChange:p,onButtonClick:m,onDecline:g,onTechnicalFailure:_,runBeforeButtonClick:E,billingName:I,onBuyerIdentityReady:H,onLoadStateChange:T,placeholderBorderRadius:Y,popupCapabilityOwner:F,externalTelemetryContext:y}){let h=no(),{emitInstrument:ge}=(0,o.useContext)(hn),w=(0,sr.useStripe)(),Te=(0,sr.useElements)(),x=(0,o.useMemo)(()=>yi(Sr(h),y),[y,h]),[ie,he]=(0,o.useState)("loading");(0,o.useEffect)(()=>{T?.(ie)},[ie,T]);let[fe,ke]=(0,o.useState)(!1);(0,o.useEffect)(()=>{He.current=fe},[fe]);let mt=(0,o.useRef)(!(0,l.isValidEmail)(r?.trim())||!I?.trim()).current,{request:Je,collect:A,finish:kt}=Ko(),tt=(0,o.useRef)(null),Ve=(0,o.useRef)(null),[me,K]=(0,o.useState)(0),[W,Fe]=(0,o.useState)(()=>(0,l.shouldPreferWalletPopup)()),lt=(0,o.useRef)(W),He=(0,o.useRef)(!1),[J,D]=(0,o.useState)(!1),[se,O]=(0,o.useState)(()=>wi(e,t)?"blocked":"idle"),[be,Me]=(0,o.useState)("google_pay"),Pe=(0,o.useRef)(null),Be=(0,o.useRef)(!0),M=(0,o.useRef)(!1),at=(0,o.useRef)("google_pay"),Ke=(0,o.useRef)("google_pay"),yt=(0,o.useRef)(null),Ze=(0,o.useRef)(null),Ge=(0,o.useRef)(new Set),_t=(0,o.useRef)(null),Ut=(0,o.useRef)(null);(0,o.useEffect)(()=>(Be.current=!0,()=>{Be.current=!1;for(let u of Ge.current)window.clearTimeout(u);Ge.current.clear()}),[]);let qt=(0,o.useRef)(new Map),{startAttempt:Ft,finishAttempt:de,invalidateAttempt:ue,isAttemptInvalidated:X,isAttemptCurrent:bt,generationRef:ft}=Sa((u,C,Q)=>{_?.(u,C,{...Q,popupBlocked:Q?.popupBlocked??(0,we.isPopupBlockedError)(C),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Me(u),D(!0),K(le=>le+1)},{onHandoffObserved:u=>{Ut.current=ft.current,F.markAvailable(),x?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ft.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:fs,onMissingTerminalDeferred:(u,C)=>{let Q=x?.now()??globalThis.performance?.now()??Date.now(),le=_t.current,L=le?.generation===C?le.startedAt:Q;x?.performance({stage:"overlay_return",durationMs:Math.max(0,Q-L),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:C,...fs(u)?{walletType:u}:{}}),x?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{J&&Ve.current?.focus()},[J,me]);let V=(0,o.useRef)(0),rt=(0,o.useRef)(!1),Rt=(0,o.useCallback)(()=>{if(V.current>0){rt.current=!0;return}K(u=>u+1)},[]),Re=(0,o.useCallback)(()=>{V.current-=1,!(V.current>0||!rt.current)&&(rt.current=!1,Be.current&&K(u=>u+1))},[]),v=(0,o.useCallback)((u,C,Q,le,L=!1)=>{ue(le),_?.(u,C,{code:Q,popupBlocked:(0,we.isPopupBlockedError)(C),telemetryReported:L,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Me(u),D(!0),Rt()},[ue,_,Rt]),q=(0,o.useCallback)(u=>{x?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...fs(u)?{walletType:u}:{}}),_?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:Bd,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Me(u),D(!0)},[_,x]),oe=(0,o.useCallback)(()=>{window.setTimeout(()=>{(tt.current?.querySelector("iframe")??tt.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{M.current&&(M.current=!1,oe())},[oe,me]);let xe=(0,o.useCallback)(()=>{D(!1),p?.(null),oe()},[oe,p]),Lt=(0,o.useCallback)(()=>{Pe.current?.()},[]);(0,o.useEffect)(()=>{let u=null,C=()=>{u=null;let le=(0,l.shouldPreferWalletPopup)();le!==lt.current&&(lt.current=le,Fe(le),!He.current&&!bt(ft.current)&&Rt())},Q=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(C,ou)};return window.addEventListener("resize",Q),()=>{window.removeEventListener("resize",Q),u!==null&&window.clearTimeout(u)}},[ft,bt,Rt]),(0,o.useEffect)(()=>{let u=wi(e,t);if(!u)return;let C=!1,Q=!1,le=async()=>{if(!Q){Q=!0,C||O("checking");try{let L=await ec(w,u.clientSecret,Ge.current);if(C)return;let k=ms(L,u.providerObjectId,(0,l.isSetupIntentClientSecret)(u.clientSecret));if(k.kind==="confirmed"){if(!Ql(e,t,u.clientSecret))return;Pe.current=null,O("idle"),c({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(k.kind==="terminal"){ps(e,t,u.clientSecret),Pe.current=null,O("idle"),Me(u.paymentMethodType),D(!0),Rt();return}O("blocked")}catch{C||O("blocked")}finally{Q=!1}}};return Pe.current=le,O("blocked"),()=>{C=!0,Pe.current===le&&(Pe.current=null)}},[t,c,Rt,e,w]);let it=(0,o.useCallback)(async u=>{let C=!1,Q=!1,le=gt=>{C||Q||(C=!0,u.paymentFailed({reason:"fail",...gt?{message:gt}:{}}))};if(!w||!Te){le();return}let L=qt.current.get(me);if(L&&!bt(L.generation)){qt.current.delete(me),le();return}if(!L&&X()){le();return}if(L&&!de(L.generation)){le();return}L||(de(),rt.current=!1);let k=u.expressPaymentType??L?.method??at.current,jt=L??null,Mr=oc(k),dr;k==="apple_pay"?dr="apple_pay":k==="google_pay"&&(dr="google_pay");let xr=L?.generation??ft.current,ct=x,Gr=ct?.now()??globalThis.performance?.now()??Date.now(),Yr=new AbortController,Ar=!1,Gt=!1,nr=null,Qt=e,Rn="processing",Yt="other",Nn="provider_runtime",Fr,Xt=new Promise((gt,Mt)=>{Fr=Mt}),or=window.setTimeout(()=>{Ar=!0,Yr.abort(),Fr(bi)},Dd),on=async(gt,Mt,Br)=>{Rn=gt,Yt=Mt,Nn=Mt==="intent_create"||Mt==="session_claim"?"transport_error":"provider_runtime";let ar=ct?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Br,Xt])}finally{let Jt=ct?.now()??globalThis.performance?.now()??Date.now();ct?.performance({stage:gt,durationMs:Math.max(0,Jt-ar),durationMode:"machine",requestCategory:Mt,paymentMethodCategory:"wallet",provider:"stripe",...Ar?{statusClass:"timeout"}:{}})}};try{if(ke(!0),p?.(null),!jt&&E){let Se=await on("processing","other",E(Mr));if(!Se.proceed){le();return}jt={accountPatch:Se.accountPatch,sessionId:Se.sessionId,nonce:Se.nonce}}let gt=jt?.sessionId??e;Qt=gt;let Mt=jt?.nonce??t,Br=yt.current??jt?.accountPatch,ar=uc({event:u,fallbackEmail:Br?.email??r,fallbackName:[Br?.firstName,Br?.lastName].join(" ").trim()||I});if(!(0,l.isValidEmail)(ar.email)){le("Buyer details are required."),A(hs(k),ar).then(Se=>{Se&&(yt.current=Se)});return}yt.current=null;let Jt={...jt?.accountPatch,...(0,Pn.compactBuyerIdentity)(ar,!0)};await on("processing","session_claim",Promise.resolve(H?.(ar)));let{error:Ur}=await on("tokenization","provider_sdk",Te.submit());if(Ur){le(),v(k,Ur,"stripe_wallet_submit_failed",L?.generation);return}if(!gt)throw new Error("Missing sessionId or email for payment.");let hr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,paymentMethodId:null,intentKind:a},Vt=JSON.stringify({sessionId:gt,nonce:Mt??"",request:hr}),Dr=Ze.current,kr=Dr?.retryIdentity===Vt?Dr.authorizationAttemptId:(0,l.randomUuidV4)();Ze.current={authorizationAttemptId:kr,retryIdentity:Vt};let Le=await on("processing","intent_create",ki(n,ge,gt,Mt??"",{...hr,authorizationAttemptId:kr},{signal:Yr.signal}));if((0,l.isSettledSessionIntent)(Le)){le(),c({type:"card",paymentMethodType:k},{accountPatch:Jt,paymentMethodCategory:"wallet",sessionId:gt,nonce:Mt,settledProcessResponse:Le.response});return}if(Le.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Or=Le.clientSecret,Xr=jd({createdAt:Date.now(),sessionId:gt,...Mt?{nonce:Mt}:{},clientSecret:Or,providerObjectId:Le.providerObjectId,paymentMethodType:k,accountPatch:Jt});window.clearTimeout(or),Gt=!0,ct?.performance({stage:"callback",durationMs:Math.max(0,(ct?.now()??globalThis.performance?.now()??Date.now())-Gr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Xn=ct?.now()??globalThis.performance?.now()??Date.now(),Pr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...dr?{walletType:dr}:{},attempt:xr},an=!1,sn=null;ct?.log({name:"payment.provider_confirmation.started",...Pr}),nr=window.setTimeout(()=>{nr!==null&&Ge.current.delete(nr),an=!0;let Se=ct?.now()??globalThis.performance?.now()??Date.now();ct?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Pr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Se-Xn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),ct?.flush?.().catch(()=>{}),sn?.()},Od),Ge.current.add(nr);let En=(Se,Dt)=>{nr!==null&&(window.clearTimeout(nr),Ge.current.delete(nr),nr=null);let $t=ct?.now()??globalThis.performance?.now()??Date.now(),nt=Math.max(0,$t-Xn),Ye=Se;an&&(Se==="resolved"?Ye="resolved_late":Se==="returned_error"?Ye="returned_error_late":Ye="rejected_late");let Jr=Dt??(Se==="resolved"?"approved":"provider_error");return ct?.log({name:"payment.provider_confirmation.returned",...Pr,operationOutcome:Ye,terminalReason:Jr}),ct?.performance({...Pr,durationMs:nt,durationMode:"buyer",operationOutcome:Ye,terminalReason:Jr}),{durationMs:nt,operationOutcome:Ye,terminalReason:Jr}},Wt=!1,Ce=!1,ln=Se=>{if(!Se||typeof Se!="object")return null;let Dt=Se;if(Dt.error)return null;let $t=Dt.setupIntent??Dt.paymentIntent,nt=ms($t??null,void 0,!!Dt.setupIntent);return nt.kind==="confirmed"?nt:null},zr=Se=>{if(Wt||L&&ft.current!==L.generation)return;let Dt=ln(Se);if(!Dt)return;if(Xr&&!Ql(gt,Mt,Or)){Wt=!0;return}let{intentId:$t,paymentMethodId:nt}=Dt;Wt=!0,Ce=!0,Ze.current=null,Pe.current=null,Be.current&&(O("idle"),ke(!1));let Ye=`${lc}:${gt}`;lr(Ye,{createdAt:Date.now(),sessionId:gt,nonce:Mt,accountPatch:Jt,paymentMethodId:nt,providerIntentId:$t,paymentMethodType:k});try{c({id:nt,type:"card",threeDSecureActionResultTokenId:$t},{accountPatch:Jt,paymentMethodCategory:"wallet",sessionId:gt,nonce:Mt})}finally{lr(Ye)}},_n=!1;sn=async()=>{if(!(_n||Wt||Ce)){_n=!0,Be.current&&O("checking");try{let Se=await ec(w,Or,Ge.current);if(Wt||Ce)return;let Dt=(0,l.isSetupIntentClientSecret)(Or),$t=ms(Se,Le.providerObjectId,Dt);if($t.kind==="confirmed"){zr(Dt?{setupIntent:Se}:{paymentIntent:Se});return}if($t.kind==="terminal"){if(Ce=!0,ps(gt,Mt,Or),Ze.current=null,Pe.current=null,!Be.current)return;O("idle"),le(),v(k,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",L?.generation,!0);return}Be.current&&!Ce&&(O("blocked"),ke(!1))}catch{Be.current&&!Ce&&(O("blocked"),ke(!1))}finally{_n=!1}}},Pe.current=sn;let N,dt;try{Q=!0,V.current+=1;let Se;try{Se=await((0,l.isSetupIntentClientSecret)(Or)?w.confirmSetup({elements:Te,clientSecret:Or,redirect:"if_required"}):w.confirmPayment({elements:Te,clientSecret:Or,redirect:"if_required"}))}finally{Re()}if(!Se||typeof Se!="object")throw new Ba(qd(Se));if(N=Se,!N.error&&!ln(N))throw new Ba("confirmation_result_unconfirmed");dt=En(N.error?"returned_error":"resolved",N.error&&(0,we.isProviderDecline)(N.error)?"provider_declined":void 0)}catch(Se){let Dt=Se instanceof Ba?Se.reason:void 0,$t=Dt!==void 0,nt=En($t?"returned_error":"rejected");if(ct?.error({...$t?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Dt}:ns(Se),...Pr,operationOutcome:nt.operationOutcome,durationMs:nt.durationMs,statusClass:"unknown",terminalReason:nt.terminalReason}),!Be.current||Wt)return;await sn?.();return}let te=N.error;if(te){if(!Be.current||Wt)return;if((0,we.isProviderDecline)(te)){Ce=!0,ps(gt,Mt,Or),Ze.current=null,Pe.current=null,O("idle"),qt.current.get(me)===L&&qt.current.delete(me);let Se=te.message??"Your payment was declined.";p?.(Se),g?.(br(Mr,Se,{code:(0,we.getProviderErrorCode)(te),declineCode:(0,we.getProviderDeclineCode)(te)})),Ri({billingApiUrl:n,sessionId:gt,nonce:Mt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,providerDeclineReason:(0,we.getProviderErrorCode)(te)??"provider_declined",...Le.intentKind==="payment"&&Le.providerObjectId.startsWith("pi_")?{providerIntentId:Le.providerObjectId}:{}}})}else ct?.error({...ns(te),...Pr,operationOutcome:dt.operationOutcome,durationMs:dt.durationMs,statusClass:"unknown",terminalReason:dt.terminalReason}),await sn?.();return}if(zr(N),!Wt)throw new Error("Invalid provider returned for APM intent")}catch(gt){if(gt===bi){let Mt=ct?.now()??globalThis.performance?.now()??Date.now();ct?.error({errorCode:Wd(Yt),stage:Rn,requestCategory:Yt,paymentMethodCategory:"wallet",provider:"stripe",...dr?{walletType:dr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Qt,durationMs:Math.max(0,Mt-Gr),statusClass:"timeout",failureCategory:Nn,attempt:xr,terminalReason:"provider_error"}),ct?.flush?.().catch(()=>{})}le(),v(k,gt,gt===bi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",L?.generation,gt===bi)}finally{if(window.clearTimeout(or),nr!==null&&(window.clearTimeout(nr),Ge.current.delete(nr)),!Gt){let gt=ct?.now()??globalThis.performance?.now()??Date.now();ct?.performance({stage:"callback",durationMs:Math.max(0,gt-Gr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Ar?{statusClass:"timeout"}:{}})}Be.current&&ke(!1)}},[w,Te,e,t,r,I,A,H,n,ge,a,c,p,g,E,v,Re,de,bt,X,ft,x,me]),De=(0,o.useMemo)(()=>gi(s),[s]),Oe=(0,o.useMemo)(()=>s.map(l.stripeExpressMethodToOptionKey),[s]),Tt=(0,o.useMemo)(()=>(0,d.jsx)(sr.ExpressCheckoutElement,{onReady:u=>{he(Ma(u,Oe))},onLoadError:u=>{he("load_error"),Cs(x,"stripe","wallet","provider_error")},onClick:async u=>{let C=x?.now()??globalThis.performance?.now()??Date.now();at.current=u.expressPaymentType,Ke.current=oc(u.expressPaymentType);let Q=!0,le=window.setTimeout(()=>{Q=!1,u.reject(),q(u.expressPaymentType)},Fd),L=E?await E(Ke.current,{abandoned:()=>!Q}):{proceed:!0};if(window.clearTimeout(le),!Q)return;if(!L.proceed){qt.current.delete(me),u.reject();return}let k=Ft(u.expressPaymentType);rt.current=!1,_t.current={generation:k,startedAt:C},qt.current.set(me,{generation:k,method:u.expressPaymentType,accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce}),D(!1),x?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:k,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),m?.(Ke.current),u.resolve()},onConfirm:it,onCancel:()=>{let u=qt.current.get(me);qt.current.delete(me);let C=_t.current,Q=x?.now()??globalThis.performance?.now()??Date.now();if(u&&C?.generation===u.generation&&(0,l.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:Q-C.startedAt,handoffObserved:Ut.current===u.generation})){x?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:u.generation,walletType:"google_pay"}),Ze.current=null,v(u.method,new Error("The browser window is too small for the Google Pay sheet."),l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,u.generation,!0);return}x?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),ue(u?.generation),Ze.current=null,D(!1),M.current=!0,Rt()},options:{...hi,paymentMethods:De,emailRequired:mt,billingAddressRequired:mt}},me),[Oe,De,it,ue,m,mt,v,q,Rt,E,Ft,me,x]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(xa,{state:ie,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Y,children:(0,d.jsxs)("div",{ref:tt,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[J&&(0,d.jsxs)("button",{ref:Ve,type:"button","data-testid":"flopay-wallet-retry-button",onClick:xe,style:gs,children:["Try ",hs(be)," again"]}),se!=="idle"&&(0,d.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,d.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,d.jsx)("button",{type:"button",onClick:Lt,disabled:se==="checking",style:gs,children:se==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Je&&(0,d.jsx)(Go,{identity:Je.identity,methodLabel:Je.methodLabel,onComplete:kt,onCancel:()=>kt(null)},Je.id),(0,d.jsxs)("div",{style:{display:Je||se!=="idle"?"none":void 0},children:[(0,d.jsx)(au,{active:W}),Tt]})]})}),fe&&(0,d.jsx)(rn,{status:"processing"})]})}function pc(e,t,r){let n=(0,l.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function Ps({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:c,onTokenizedBody:p,onErrorChange:m,onDecline:g,onCancel:_,runBeforeButtonClick:E,onButtonClick:I,isProcessing:H,submitButtonColor:T,submitButtonBorderRadius:Y,submitButtonStyle:F,errorText:y}){let h=no(),{emitInstrument:ge}=(0,o.useContext)(hn),w=(0,sr.useStripe)(),Te=(0,sr.useElements)(),[x,ie]=(0,o.useState)(!1),he=(0,o.useRef)(!1),[fe,ke]=(0,o.useState)(!1),[mt,Je]=(0,o.useState)("loading"),[A,kt]=(0,o.useState)(""),tt=!(0,l.isValidEmail)(n?.trim()),Ve=!tt||(0,l.isValidEmail)(A.trim()),me=(0,o.useCallback)(async()=>{if(!w||!Te||H||he.current||!fe)return;he.current=!0,ie(!0);let K=E?await E("card"):{proceed:!0};if(!K.proceed){he.current=!1,ie(!1);return}I?.("card");let W=K.sessionId??t,Fe=K.nonce??r,lt=(0,Ho.splitFullName)(a?.trim()),He=(0,Pn.compactBuyerIdentity)({email:K.accountPatch?.email?.trim()||n?.trim()||A.trim(),firstName:K.accountPatch?.firstName?.trim()||lt.firstName,lastName:K.accountPatch?.lastName?.trim()||lt.lastName}),J=He.email,D=(0,Pn.compactBuyerIdentity)({...K.accountPatch,...He});try{if(m?.(null),!(0,l.isValidEmail)(J))throw new Error("A valid email address is required for payment.");await s?.(He);let se=await Te.submit();if(se.error){m?.(se.error.message??"Payment failed.");return}let O=[He.firstName,He.lastName].filter(Boolean).join(" "),be=await w.createPaymentMethod({elements:Te,params:{billing_details:{email:J,...O?{name:O}:{}}}});if(be.error||!be.paymentMethod){m?.(be.error?.message??"Failed to create payment method.");return}let Me=be.paymentMethod;if(!W||!J)throw new Error("Missing sessionId or email for payment.");let Pe=Me.type||e,Be=await ki(c,ge,W,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Pe,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(Be)){p({type:"card",gateway:"stripe",paymentMethodType:Pe},{accountPatch:D,paymentMethodCategory:"apm",sessionId:W,nonce:Fe,settledProcessResponse:Be.response});return}if(Be.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let M=Be.clientSecret;lr(Kn,{clientSecret:M,sessionId:W,nonce:Fe,accountPatch:D,paymentMethodId:Me.id,paymentMethodType:Me.type??e,gateway:"stripe"});let{error:at,paymentIntent:Ke}=await w.confirmPayment({clientSecret:M,confirmParams:{return_url:window.location.href,payment_method:Me.id},redirect:"if_required"});if(at){lr(Kn);let Ge=at.message??"Payment failed.";m?.(Ge),g?.(br("card",Ge,{code:at.code})),await Ri({billingApiUrl:c,sessionId:W,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:at.code??"provider_declined"}});return}let yt=Ke?.status;if(!Pa(yt)){lr(Kn);let Ge=yt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(Ge),g?.(br("card",Ge,{code:yt??"missing_payment_intent"}));return}lr(Kn);let Ze=typeof Ke?.payment_method=="string"?Ke.payment_method:Ke?.payment_method?.id;p({id:Ze??Me.id,type:"card",threeDSecureActionResultTokenId:Ke?.id,gateway:"stripe",paymentMethodType:Me.type??e},{accountPatch:D,paymentMethodCategory:"apm",sessionId:W,nonce:Fe})}catch(se){m?.(se instanceof Error?se.message:"Payment failed. Please try again.")}finally{he.current=!1,ie(!1)}},[w,Te,H,fe,E,I,t,r,n,a,A,s,c,ge,e,p,m,g]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[tt&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:tt&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:A,onChange:K=>kt(K.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(sr.PaymentElement,{onReady:()=>Je("ready"),onLoadError:()=>{Je("load_error"),Cs(Sr(h),"stripe","apm")},onChange:K=>{ke(!!K.complete)},options:{layout:Pi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,l.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,d.jsx)(vi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{me()},disabled:!fe||!Ve||x||H||mt!=="ready",color:T,borderRadius:Y,style:F,children:x?"Processing\u2026":`Pay with ${(0,l.getStripeMethodDisplayName)(e)}`}),y&&(0,d.jsx)(Jo,{margin:"0.75rem 0 0",children:y})]})}function sc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:c,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:g,onTokenizedBody:_,onErrorChange:E,onButtonClick:I,onDecline:H,runBeforeButtonClick:T,onLoadStateChange:Y,isProcessing:F=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:h=8,submitButtonStyle:ge,buttonAppearance:w,themeId:Te,onExpandApm:x,expandedApmMethod:ie}){let{emitInstrument:he}=(0,o.useContext)(hn),[fe,ke]=(0,o.useState)(null),[mt,Je]=(0,o.useState)(null),A=(0,o.useRef)(!1),{request:kt,collect:tt,finish:Ve}=Ko();(0,o.useEffect)(()=>{c.length>0&&p?Y?.("ready"):p||Y?.("loading")},[c.length,p,Y]);let me=(0,o.useCallback)(async J=>{if(!p||A.current||F)return;A.current=!0,Je(J);let D=T?await T("card"):{proceed:!0};if(!D.proceed){A.current=!1,Je(null);return}I?.("card");let se=D.sessionId??e,O=D.nonce??t,be=(0,Ho.splitFullName)([D.accountPatch?.firstName,D.accountPatch?.lastName].filter(Boolean).join(" ")||n),Me=(0,Pn.compactBuyerIdentity)({email:D.accountPatch?.email?.trim()||r?.trim(),firstName:D.accountPatch?.firstName?.trim()||be.firstName,lastName:D.accountPatch?.lastName?.trim()||be.lastName});if(!(0,l.isValidEmail)(Me.email)){Je(null);let M=await tt((0,l.getStripeMethodDisplayName)(J),Me);if(!M){A.current=!1;return}Me=M,Je(J)}let Pe=Me.email,Be=(0,Pn.compactBuyerIdentity)({...D.accountPatch,...Me});try{if(E?.(null),!se||!(0,l.isValidEmail)(Pe))throw new Error("Missing sessionId or email for payment.");await a?.(Me);let M=await ki(s,he,se,O??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(M)){_({type:"card",gateway:"stripe",paymentMethodType:J},{accountPatch:Be,paymentMethodCategory:"apm",sessionId:se,nonce:O,settledProcessResponse:M.response});return}if(M.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let at=M.clientSecret;lr(Kn,{clientSecret:at,sessionId:se,nonce:O,accountPatch:Be,paymentMethodType:J,gateway:"stripe"});let{error:Ke,paymentIntent:yt}=await p.confirmPayment({clientSecret:at,confirmParams:{return_url:window.location.href,payment_method_data:{type:J,billing_details:{name:[Me.firstName,Me.lastName].filter(Boolean).join(" "),...Pe?{email:Pe}:{}}}},redirect:"if_required"});if(Ke){lr(Kn);let _t=Ke.message??"Payment failed.";E?.(_t),H?.(br("card",_t,{code:Ke.code})),await Ri({billingApiUrl:s,sessionId:se,nonce:O,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,providerDeclineReason:Ke.code??"provider_declined"}});return}let Ze=yt?.status;if(!Pa(Ze)){lr(Kn);let _t=Ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";E?.(_t),H?.(br("card",_t,{code:Ze??"missing_payment_intent"}));return}lr(Kn);let Ge=typeof yt?.payment_method=="string"?yt.payment_method:yt?.payment_method?.id;_({id:Ge??yt?.id,type:"card",threeDSecureActionResultTokenId:yt?.id,gateway:"stripe",paymentMethodType:J},{accountPatch:Be,paymentMethodCategory:"apm",sessionId:se,nonce:O})}catch(M){E?.(M instanceof Error?M.message:"Payment failed. Please try again.")}finally{A.current=!1,Je(null)}},[p,F,T,I,e,t,r,tt,s,he,n,a,_,E,H]),[K,W]=(0,o.useState)(null),Fe=x?ie??null:K,lt=(0,o.useCallback)(J=>{A.current||F||Fe&&Fe!==J||((0,l.needsStripeMethodExplicitConfirm)(J)?x?x(J):W(J):me(J))},[Fe,F,me,x]),He=(0,o.useMemo)(()=>K?pc(m,K,g):null,[K,m,g]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:kt?(0,d.jsx)(Go,{identity:kt.identity,methodLabel:kt.methodLabel,onComplete:Ve,onCancel:()=>Ve(null)},kt.id):c.map(J=>{let D=ie===J,se=mt===J,O=mt!==null&&mt!==J||ie!=null&&ie!==J;return(0,d.jsxs)(o.default.Fragment,{children:[(0,d.jsx)(fi,{method:J,themeId:Te,submitting:se,disabled:O,highlighted:D,hasNextStep:(0,l.needsStripeMethodExplicitConfirm)(J),onClick:()=>lt(J),backgroundColor:w?.backgroundColor,borderColor:w?.borderColor,textColor:w?.textColor,borderRadius:w?.borderRadius,fontFamily:w?.fontFamily}),!x&&K===J&&He&&p&&(0,d.jsx)(sr.Elements,{stripe:p,options:He,children:(0,d.jsx)(Ps,{method:J,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:_,onErrorChange:E,onDecline:H,onCancel:()=>W(null),runBeforeButtonClick:T,onButtonClick:I,isProcessing:F,submitButtonColor:y,submitButtonBorderRadius:h,submitButtonStyle:ge})},J)]},J)})})}function iu({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:c,onError:p,onDecline:m,onCancel:g,onTokenizedBody:_,firstName:E,lastName:I,chv:H,className:T,submitLabel:Y,isProcessing:F,error:y,onErrorChange:h,showPayPal:ge=!0,showStripe:w=!0,walletPresentation:Te="auto",enabledPaymentMethods:x,enabledPaymentMethodCountries:ie,showApplePay:he=!0,showGooglePay:fe=!0,layout:ke="default",theme:mt,buttonsTheme:Je,buttonsStyles:A,appearance:kt,cardButtonContent:tt,cardBackButtonContent:Ve,cardTitleContent:me,showSecurityFooter:K,onButtonClick:W,onBeforeButtonClick:Fe,onBuyerIdentityReady:lt,enableAVS:He,cardFieldOrder:J,cardAutoFocus:D,cardPreFormSlot:se,avsLayout:O="row",country:be,zip:Me,addressLine1:Pe,addressLine2:Be,city:M,state:at,onCountryChange:Ke,onZipChange:yt,avsCheck:Ze,checkoutType:Ge,checkoutLayout:_t,totalAmount:Ut=0,currency:qt="usd",initialCardOpen:Ft=!1,directPaypal:de,isSubscription:ue=!1,session:X,dataAttachmentPending:bt=!1,dataAttachmentRequiresIdentity:ft=!1,debug:V=!1}){let rt=no(),Rt=ni(),Re=(0,o.useContext)(Fn),{emitInstrument:v}=(0,o.useContext)(hn),q=(0,o.useRef)(null);q.current||(q.current=ai());let oe=q.current,[,xe]=(0,o.useState)(0),Lt=(0,o.useRef)(null);Lt.current||(Lt.current=(0,Wn.detectPayPalEnvironment)());let it=Lt.current,De=(0,o.useMemo)(()=>({browser:it,capability:oe,presentationMode:"popup"}),[it,oe]),Oe=X??Re.session,Tt=(0,o.useMemo)(()=>({futureUse:Oe?.futureUse,futureUseUnsupported:Oe?.futureUseUnsupported}),[Oe?.futureUse,Oe?.futureUseUnsupported]),u=Oe?.gateways?.paypal?.providerObjectType??de?.providerObjectType,C=bt||Re.claimPending===!0,Q=ft||Re.claimRequiresIdentity===!0,le=C&&!Q,L=Ol(),k=r||L,[jt,Mr]=(0,o.useState)(!1),[dr,xr]=(0,o.useState)(null),[ct,Gr]=(0,o.useState)(be??""),[Yr,Ar]=(0,o.useState)(Me??""),[Gt,nr]=(0,o.useState)(Pe??""),[Qt,Rn]=(0,o.useState)(Be??""),[Yt,Nn]=(0,o.useState)(M??""),[Fr,Xt]=(0,o.useState)(at??""),[or,on]=(0,o.useState)(""),[gt,Mt]=(0,o.useState)({}),Br=(0,o.useRef)(Me??""),ar=(0,o.useRef)(be??""),Jt=(0,o.useRef)(Pe??""),Ur=(0,o.useRef)(Be??""),hr=(0,o.useRef)(M??""),Vt=(0,o.useRef)(at??""),Dr=(0,o.useRef)(""),kr=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(b,$,_e,G,Ie)=>{if(kr.current[b])return;let Ht=$?.trim();!Ht||Ht===_e.current||(_e.current=Ht,G(Ht),Ie?.(Ht))};i("country",be,ar,Gr,Ke),i("zip",Me,Br,Ar,yt),i("addressLine1",Pe,Jt,nr),i("addressLine2",Be,Ur,Rn),i("city",M,hr,Nn),i("state",at,Vt,Xt)},[be,Me,Pe,Be,M,at,Ke,yt]);let Le=(0,o.useMemo)(()=>(0,l.resolveAVSConfig)(He),[He]),Or=Le!==null,Xr=(0,o.useMemo)(()=>(0,l.isAuthorizationOnlySession)(X),[X]),Xn=(0,l.isMountableVaultBlock)(X?.vault),Pr=!!X?.gateways?.pcivault,an=(0,An.hasServerSideCardGateway)(X),En=!!(X?.gateways?.stripe?.enabledPaymentMethods??x)?.includes("card")||(0,An.canRecoverHostedCardForm)(X),Wt=Xn||En||Pr,Ce=!!(w&&Wt&&e),[ln,zr]=(0,o.useState)(()=>ke!=="buttons"||Ft?e??null:null),[_n,N]=(0,o.useState)(0),dt=ke!=="buttons"||Ft||!!e&&ln===e,te=X?.captureMethod,Se=(0,o.useRef)(rt);(0,o.useEffect)(()=>{Se.current=rt},[rt]);let[Dt,$t]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!Ce||!e||!dt){$t(null);return}let i=Se.current?Se.current.cardCapture({sessionId:e,captureMethod:te}):new Ln.PciVaultCardCapture({sessionId:e,captureMethod:te,billingApiUrl:k,telemetry:n});return $t({sessionId:e,captureMethod:te,billingApiUrl:k,telemetry:n,capture:i}),()=>{i.unmount()}},[Ce,e,dt,te,k,n]);let nt=Ce&&e&&dt&&Dt?.sessionId===e&&Dt.captureMethod===te&&Dt.billingApiUrl===k&&Dt.telemetry===n?Dt.capture:null,Ye=(0,o.useMemo)(()=>{let i=ct,b=Le?(0,l.isAVSFieldVisible)(Le.postal_code,i):!1;return tu(i,Yr,b)},[Le,ct,Yr]),{avsInvalid:Jr,invalidAvsFields:Un}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Ce||!Le)return{avsInvalid:!1,invalidAvsFields:i};let b=ct,$=(Ie,Ht)=>(0,l.isAVSFieldVisible)(Ie,b)&&!Ht.trim(),_e={line1:$(Le.address_line_1,Gt),city:$(Le.city,Yt),state:$(Le.state,Fr),zip:Ye.empty||Ye.malformed};return{avsInvalid:_e.line1||_e.city||_e.state||_e.zip,invalidAvsFields:_e}},[Ce,Le,ct,Gt,Yt,Fr,Ye]),[er,In]=(0,o.useState)(!1),[Jn,Zn]=(0,o.useState)(!1),[Tn,lo]=(0,o.useState)(!1),[Qn,go]=(0,o.useState)({line1:!1,city:!1,state:!1}),yn=(0,o.useRef)(!1),jr=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),co=(0,o.useRef)(!1),Nt=(0,o.useCallback)(i=>{jr.current[i]=!0,co.current=!0},[]),Zr=(0,o.useCallback)(i=>!yn.current&&jr.current[i],[]),Qr=(0,o.useCallback)(i=>{Zr(i)&&go(b=>b[i]?b:{...b,[i]:!0})},[Zr]),[cn,dn]=(0,o.useState)(()=>(0,l.resolveVaultMountOptions)(X?.vault,{billingApiUrl:k,sessionId:e,nonce:t})),[st,ur]=(0,o.useState)(Ft&&Wt?"card":"buttons"),[vr,Rr]=(0,o.useState)(null),ho=st==="expanding"||st==="card",zn=X?.gateways?.stripe&&!an?"stripe":void 0,uo=(0,o.useCallback)(()=>{v?.({class:"card_surface",provider:zn})},[zn,v]),Vr=(0,o.useRef)(null),Er=(0,o.useCallback)(i=>{Vr.current&&clearTimeout(Vr.current),Vr.current=setTimeout(()=>{Vr.current=null,i()},Da)},[]);(0,o.useEffect)(()=>()=>{Vr.current&&clearTimeout(Vr.current)},[]);let po=(0,o.useRef)(!1),[Lr,U]=(0,o.useState)(0),z=(0,o.useRef)(null),ce=(0,o.useCallback)(()=>{uo(),zr(e??null),po.current&&(po.current=!1,U(i=>i+1)),N(i=>i+1),ur("expanding"),Er(()=>ur("card"))},[Er,uo,e]),ve=(0,o.useCallback)(()=>{ur("collapsing"),Er(()=>ur("buttons"))},[Er]),xt=(0,o.useCallback)(i=>{Rr(i),ur("apm-expanding"),Er(()=>ur("apm-form"))},[Er]),zt=(0,o.useCallback)(()=>{ur("apm-collapsing"),Er(()=>{ur("buttons"),Rr(null)})},[Er]);(0,o.useEffect)(()=>{ke==="buttons"&&Ft&&Wt&&(zr(e??null),ur("card"))},[ke,Ft,Wt,e]);let[ze,Z]=(0,o.useState)(null),re=(0,o.useRef)(null),[Xe,Ee]=(0,o.useState)(0);(0,o.useEffect)(()=>{Xe!==0&&re.current?.focus()},[Xe]);let ut=(0,o.useRef)(!1),j=(0,o.useRef)(null),pe=(0,o.useRef)("idle"),[Ot,ot]=(0,o.useState)(!1),pr=(0,o.useRef)(Ot);pr.current=Ot;let[Ne,f]=(0,o.useState)(()=>de?.existingOrderId?{orderId:de.existingOrderId,attempts:1}:null),S=(0,o.useRef)(Ne);(0,o.useEffect)(()=>{S.current=Ne},[Ne]);let ne=(0,o.useRef)(null),qe=(0,o.useMemo)(()=>{if(lt||Re.claimBuyerIdentity||X?.buyerIdentified!==!1||!e||!t)return;let i=`${k}|${e}|${t}`;ne.current?.key!==i&&(ne.current={key:i,claim:Wo(new Ln.PaymentAPI(k,{telemetry:!1}),e,t,{...s?{userId:s}:{},...E?{firstName:E}:{},...I?{lastName:I}:{}})});let b=ne.current.claim;return async $=>{await b($)}},[lt,Re.claimBuyerIdentity,X?.buyerIdentified,e,t,k,s,E,I]),je=lt??Re.claimBuyerIdentity??qe,ye=y??dr,tr=(0,o.useMemo)(()=>(0,l.resolveTheme)(mt),[mt]),ee=(0,o.useMemo)(()=>{let i=tr?.buttonsLayout??(0,l.resolveButtonsLayoutTheme)(Je);return A?{...i,...A,cardButton:{...i.cardButton,...A.cardButton},cardFormContainer:{...i.cardFormContainer,...A.cardFormContainer},backButton:{...i.backButton,...A.backButton},backButtonIcon:{...i.backButtonIcon,...A.backButtonIcon},submitButton:{...i.submitButton,...A.submitButton},title:{...i.title,...A.title}}:i},[tr,Je,A]),Cr=kt??tr?.appearance,Po=(0,o.useMemo)(()=>(0,l.computeVaultCardThemeColors)({appearance:Cr,buttonsStyles:ee,layout:ke}),[Cr,ee,ke]),To=Re.inlineSessionPatchProcessing??!1,Ae=(F??jt)||To,ht=k.replace(/\/+$/,""),ae=(0,o.useMemo)(()=>rs({userId:s,email:a,firstName:E,lastName:I,country:be,zip:Me},gt),[s,a,E,I,be,Me,gt]),It=[ae.firstName,ae.lastName].filter(i=>!!i?.trim()).join(" "),Et=!(0,l.isValidEmail)(ae.email?.trim()),Wr=(0,o.useRef)(null);Ce&&Wr.current===null&&(Wr.current=Et);let Bt=Ce&&(Wr.current??Et),Mo=(0,o.useMemo)(()=>ru(or,Bt),[or,Bt]),xo=Mo.empty||Mo.malformed,un=(0,o.useMemo)(()=>rt?rt.getRawProvider():null,[rt]),Fs=(0,o.useMemo)(()=>Rt?Rt.getRawProvider():null,[Rt]),aa=Ut||100,Ao=qt.toLowerCase(),Di=(0,o.useMemo)(()=>Cr?(0,Ln.toStripeAppearance)(Cr):null,[Cr]),Fo=Di,Bs=(0,o.useMemo)(()=>{let i=Di??{},b=i.rules??{};return{...i,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[Di]),Ds=(0,o.useMemo)(()=>({...Fl(Ut,Oe?.captureMethod,Tt),currency:Ao,...Fo?{appearance:Fo}:null}),[Ut,Ao,Oe?.captureMethod,Tt,Fo]),Oi=(0,l.resolveSetupFutureUsage)(Tt,"paypal","paypal"),Os=(0,o.useMemo)(()=>({mode:"payment",amount:aa,currency:Ao,captureMethod:"manual",...Oi?{setupFutureUsage:Oi}:null,...Fo?{appearance:Fo}:null}),[aa,Ao,Oi,Fo]),We=(0,o.useCallback)(i=>{xr(i),h?.(i)},[h]),Ls=(0,o.useRef)(0);(0,o.useEffect)(()=>{Lr!==Ls.current&&(Ls.current=Lr,We(null))},[Lr,We]);let Li=(0,o.useRef)(""),[Ns,Dc]=(0,o.useState)(!1),Ni=(0,o.useCallback)(()=>{Dc(!0)},[]);(0,o.useEffect)(()=>{if(!Ce||!Bt||!je||!Ns||xo||Li.current)return;let i=(0,Pn.compactBuyerIdentity)({email:(0,l.isValidEmail)(ae.email?.trim())?ae.email?.trim():Dr.current.trim(),firstName:ae.firstName?.trim(),lastName:ae.lastName?.trim()});Li.current=JSON.stringify(i),Mt(b=>({...b,...i})),Promise.resolve(je(i)).catch(b=>{Li.current="",We(b instanceof Error?b.message:"Failed to attach buyer details.")})},[Ce,Bt,je,Ns,xo,ae.email,ae.firstName,ae.lastName,We]),(0,o.useEffect)(()=>{if(!Ce||!nt)return;let i=D!==!1&&Le==null&&!Bt;nt.setCardFieldOrder?.(J??null,i)},[Ce,nt,J,D,Le,Bt]),(0,o.useEffect)(()=>{(st==="expanding"||st==="collapsing"||st==="apm-expanding"||st==="apm-collapsing")&&We(null)},[st,We]);let qn=(0,o.useCallback)((i,b,$)=>{m?.(br(i,b,$))},[m]),Us=(0,o.useRef)(st);Us.current=st;let[zs]=(0,o.useState)(si),qs=(0,o.useCallback)(()=>{let i=Us.current;if(ke==="buttons"&&(i==="card"||i==="expanding"))return!0;let b=pe.current;return b==="validation-window"||b==="processing"||pr.current},[ke]),js=(0,o.useCallback)((i,b,$)=>{zs.take(e)&&Sr(rt)?.log(Eo({...De,presentationMode:$?.presentationMode??"popup"},{name:ii,stage:"recovery",reason:"other_method_active",provider:$?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:$?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[De,rt,zs,e]),za=(0,o.useCallback)((i,b,$)=>{$?.telemetryReported||Sr(rt)?.error(Eo({...De,presentationMode:$?.presentationMode??"popup"},{errorCode:b?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:$?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:$?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:$?.terminalReason??(b?"popup_blocked":"provider_error")}))},[De,rt]),Bo=(0,o.useCallback)((i,b,$)=>{let _e=$?.popupBlocked??(0,we.isPopupBlockedError)(b);if(qs()){za(i,_e,$),js(i,b,$);return}if(b instanceof l.FloPayError&&b.code==="checkout_processing_timeout"){za(i,!1,$),Z(null),ke==="buttons"&&(ur("buttons"),Rr(null)),We(b.message),p?.(b);return}_e&&oe.markBlocked()&&xe(St=>St+1);let G=hs(i),Ie=$?.code===l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,l.buildWalletSheetWindowMessage)(G):(0,we.buildExternalMethodRecoveryMessage)(G,_e,it.inAppBrowser),Ht=(0,we.getProviderErrorCode)(b),gn=(Ht?.toLowerCase()==="error"?void 0:Ht)??(0,we.sanitizeExternalFailureCode)($?.code)??"external_payment_method_failed",Pt=new l.FloPayError(Ie,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:gn,popupBlocked:_e,inAppBrowser:it.inAppBrowser,appFamily:it.appFamily,popupCapability:oe.current(),presentationMode:$?.presentationMode??"popup"}});za(i,_e,$),Z(null),ke==="buttons"&&(ur("buttons"),Rr(null)),We(Ie),p?.(Pt),console.error("[FloPay] External payment method failed:",{method:i,code:gn,popupBlocked:_e})},[it,qs,ke,p,oe,js,za,We]);(0,o.useEffect)(()=>{if(!Ce||!e){dn(null);return}let i={billingApiUrl:ht,sessionId:e,nonce:t},b=(0,l.resolveVaultMountOptions)(X?.vault,i);if(b){dn(b);return}if(!dt){dn(null);return}let $=`${ht}\0${e}\0${t??""}`,_e=z.current;if(_e&&_e.key===$){dn(_e.mount);return}dn(null);let G=!0;return new Ln.PaymentAPI(ht).getVaultCapture(e,t).then(Ie=>{if(!G)return;let Ht=(0,l.resolveVaultMountOptions)(Ie,i);Ht?.verificationRequired&&!Ie.html&&(z.current={key:$,mount:Ht}),Ht?dn(Ht):We("Failed to load the secure card form.")}).catch(Ie=>{G&&We(Ie instanceof Error?Ie.message:"Failed to load the secure card form.")}),()=>{G=!1}},[Ce,dt,_n,e,X?.vault,ht,t,We]);let Mn=(0,o.useRef)({onComplete:c,onError:p,updateError:We,emitDecline:qn,resolvedAccount:ae,avsConfig:Le,avsCheckProp:Ze,sessionId:e,nonce:t,baseUrl:ht,captureMethod:X?.captureMethod,paymentId:X?.paymentId,authorizationExpiresAt:X?.authorizationExpiresAt,serverSideCardGateway:an});Mn.current={onComplete:c,onError:p,updateError:We,emitDecline:qn,resolvedAccount:ae,avsConfig:Le,avsCheckProp:Ze,sessionId:e,nonce:t,baseUrl:ht,captureMethod:X?.captureMethod,paymentId:X?.paymentId,authorizationExpiresAt:X?.authorizationExpiresAt,serverSideCardGateway:an};let Ui=(0,o.useRef)(!1),Vs=(0,o.useCallback)(()=>{let i=Mn.current,b=i.resolvedAccount.email?.trim(),$=(0,l.isValidEmail)(b)?b:Dr.current.trim();if(!(0,l.isValidEmail)($))return null;let _e=i.resolvedAccount.firstName?.trim(),G=i.resolvedAccount.lastName?.trim(),Ie=ar.current.trim()||i.resolvedAccount.country?.trim()||"",Ht=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.state,Ie):!1,gn=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_1,Ie):!1,Pt=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.postal_code,Ie):!1,St=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.city,Ie):!1,At=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_2,Ie):!1,mr=gn&&!Ht&&Pt?(0,l.getStateFromPostalCode)(Ie,(Br.current??"").trim()):null,pn=Ht?Vt.current:mr;return{accountData:{userId:i.resolvedAccount.userId??"",email:$,..._e?{firstName:_e}:{},...G?{lastName:G}:{},...Pt&&Br.current?{zip:Br.current}:{},...St&&hr.current?{city:hr.current}:{},...pn?{state:pn}:{},...gn&&Jt.current?{addressLine1:Jt.current}:{},...At&&Ur.current?{addressLine2:Ur.current}:{},...Ie?{country:Ie}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,l.isAVSFieldVisible)(i.avsConfig.country,Ie),postal_code:Pt,address_line_1:gn,address_line_2:At,city:St,state:Ht}}:{}}},[]),Ws=(0,o.useRef)(C);Ws.current=C,(0,o.useEffect)(()=>{C||ye!==tc||Mn.current.updateError(null)},[C,ye]),(0,o.useEffect)(()=>{!Ce||!nt||nt.setSubmitGate?.(Jr||C||xo||Ot)},[Ce,nt,Jr,C,xo,Ot]),(0,o.useEffect)(()=>{if(!Ce||!nt)return;Ui.current=!1;let i=null,b=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,pe.current="idle",Z(null)},400)},$=nt.on("submitting",()=>{In(!0),j.current&&clearTimeout(j.current),pe.current="validation-window",j.current=setTimeout(()=>{j.current=null,pe.current==="validation-window"&&(pe.current="processing")},$d),Z("processing");let Pt=Mn.current;if(!Pt.sessionId||!Pt.nonce)return;let St=Vs();if(!St){Pt.updateError("Enter a valid email address."),pe.current="idle",Z(null);return}new Ln.PaymentAPI(Pt.baseUrl).patchAccountSnapshot(Pt.sessionId,Pt.nonce,St,{telemetryMode:"best_effort"}).catch(At=>{if(!Kd(At))return;let mr=At instanceof Error?At.message:"Please check your billing address and try again.";Pt.updateError(mr),pe.current="idle",Z(null),Pt.onError?.(At instanceof l.FloPayError?At:new l.FloPayError(mr,"api_error"))})}),_e=nt.on("complete",Pt=>{(0,Dn.markSessionRecentlyCompleted)(Pt.sessionId??Mn.current.sessionId),pe.current="terminal",ot(!1),Z("success"),setTimeout(()=>{if(Ui.current)return;Ui.current=!0;let St=Mn.current,At=(0,l.isAuthorizationOnlySession)(St)||Pt.outcome==="authorized",mr=St.serverSideCardGateway?{}:{paymentIntentId:Pt.intentId};Mn.current.onComplete?.(At?{status:"authorized",...mr,paymentId:Pt.paymentId??St.paymentId,sessionId:Pt.sessionId??St.sessionId,authorizationExpiresAt:Pt.authorizationExpiresAt??St.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...mr,checkoutMethod:"card"})},600)}),G=nt.on("decline",Pt=>{let St=Mn.current,At=Pt.message??"Your payment was declined. Please try another card or contact your bank.";pe.current="terminal",ot(!1),St.updateError(At),Z("error");let mr=Pt.failureOutcome??(0,l.normalizeCheckoutFailureOutcome)(Pt.declineReason)??"authorization_declined";St.emitDecline("card",At,{code:mr,declineCode:mr}),b()}),Ie=nt.on("error",Pt=>{let St=Mn.current,At=(0,l.buyerEmailRequiredPrompt)(Pt.vaultOutcome);if(At!==null){i&&(clearTimeout(i),i=null),pe.current="idle",ot(!1),St.updateError(At),Z(null),Ee(pn=>pn+1),St.onError?.(new l.FloPayError(At,"api_error",{code:l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let mr=Pt.message??"There was a problem processing your payment. Please try again.";pe.current="terminal",ot(!1),St.updateError(mr),Z("error"),St.onError?.(new l.FloPayError(mr,"api_error",{code:Pt.failureOutcome??"capture_failed"})),b()}),Ht=nt.on("challenge_dismissed",()=>{j.current&&(clearTimeout(j.current),j.current=null),pe.current="processing",ot(!0),Z(null)}),gn=nt.on("blocked",()=>{if(pr.current){Mn.current.updateError(Hd);return}if(!Ws.current){In(!0);return}Ni(),Mn.current.updateError(tc)});return()=>{i&&(clearTimeout(i),i=null),j.current&&(clearTimeout(j.current),j.current=null),pe.current="idle",ot(!1),Z(null),$(),_e(),G(),Ie(),Ht(),gn()}},[Ce,nt,Ni,Vs]);let jn=!!de?.clientId,ia=Array.isArray(x),qa=ia&&x.length>0,$s=ia&&x.includes("paypal"),ja=(0,o.useRef)(null);ja.current===null&&(ja.current=(0,l.hasMatchingStripePayPalReturn)());let Do=ja.current?"redirect":(0,$n.resolveStripePayPalPresentation)(it,Te,oe.current()),{expressMethods:Va,paymentElementMethods:zi}=(0,o.useMemo)(()=>(0,l.partitionStripeMethods)(x,{excludePaypal:jn}),[x,jn]),Hs=jn||!!Rt||$s&&Do==="redirect",Oc=(0,o.useMemo)(()=>Hs?Va.filter(i=>i!=="paypal"):Va,[Va,Hs]),Lc=(0,o.useMemo)(()=>{let i=[];return he&&i.push("apple_pay"),fe&&i.push("google_pay"),i},[he,fe]),Oo=ia?Oc:Lc,Nc=w&&Oo.length>0,Ks=Or?ct:be,Wa=(0,o.useMemo)(()=>(0,l.filterStripeMethodsByCountryGate)(zi,Ks,ie),[zi,Ks,ie]),qi=(0,o.useMemo)(()=>({mode:"payment",amount:aa,currency:Ao,paymentMethodCreation:"manual",appearance:Bs}),[aa,Ao,Bs]),[Gs,Ys]=(0,o.useState)("loading"),[Xs,Js]=(0,o.useState)("loading"),[Zs,Qs]=(0,o.useState)("loading"),[Uc,ji]=(0,o.useState)(!1),[el,Vi]=(0,o.useState)("loading"),[Wi,zc]=(0,o.useState)();(0,o.useEffect)(()=>{zc((0,Wn.detectPayPalEnvironment)())},[]);let $a=Wi?.inAppBrowser,Ha=Wi?(0,$n.resolvePayPalPresentationMode)(Wi,de?.approvalPresentation,u??(ue?"subscription":"order")):"popup",tl=ge&&(jn||(ia?$s:$a===!1)),qc=it.inAppBrowser&&oe.current()==="blocked",rl=w&&Nc&&!qc,sa=(!le||!!Re.waitForDataAttachment)&&tl&&jn,nl=el==="retrying"||el==="exhausted",la=null;w&&(Rt?la=Fs:Do==="redirect"&&(la=un));let ol=(0,o.useMemo)(()=>({...De,presentationMode:Do}),[De,Do]),ca=!le&&tl&&!!la&&(!jn||nl),Lo=!le&&rl&&!!un,da=!le&&w&&qa&&Wa.length>0&&!!un,jc=sa&&!nl?Uc:ca&&ds(Gs),Vc=Lo&&ds(Xs),Wc=da&&Zs!=="load_error",al=i=>i==="loading"||i==="ready",il=sa||ca&&al(Gs)||Lo&&al(Xs)||da&&Zs!=="load_error",Ka=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Ka.current){if(!w&&!ge){Ka.current=!0;let i=new l.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),We(i.message)}else if(!w&&ge&&!jn){Ka.current=!0;let i=new l.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),We(i.message)}else if($a!==void 0&&!le&&!Wt&&!il){Ka.current=!0;let i=new l.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(i),We(i.message)}}},[w,ge,jn,$a,le,Wt,il,p,We]);let sl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(sl.current||!qa)return;let i=[];he!==!0&&i.push("showApplePay"),fe!==!0&&i.push("showGooglePay"),i.length!==0&&(sl.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.`))},[qa,he,fe]);let ll=(0,o.useCallback)((i,b,$)=>Re.applyInlineSessionPatch?Re.applyInlineSessionPatch(i).then(_e=>({error:null,sessionId:_e.sessionId||e,nonce:_e.session?.clientSecret||t})).catch(_e=>{let G=(0,l.normalizeBeforeButtonClickError)(b,_e);return $?.abandoned?.()||(We(G.message),p?.(G)),{error:G,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Re.applyInlineSessionPatch,t,p,e,We]),xn=(0,o.useCallback)(async(i,b)=>{if(i!=="card"&&le&&await Re.waitForDataAttachment?.(),!Fe)return{proceed:!0};try{let $=await Fe({method:i,sessionId:e||void 0,createSession:Re.inlineSessionDraft});if($===!1)return{proceed:!1};if($&&typeof $=="object"){$.account&&Mt(G=>({...G??{},...$.account}));let _e=await ll($,i,b);return _e.error?{proceed:!1,accountPatch:$.account}:{proceed:!0,accountPatch:$.account,sessionId:_e.sessionId,nonce:_e.nonce}}return{proceed:!0}}catch($){if(!b?.abandoned?.()){let _e=(0,l.normalizeBeforeButtonClickError)(i,$);We(_e.message),p?.(_e)}return{proceed:!1}}},[ll,Re.inlineSessionDraft,Re.waitForDataAttachment,le,Fe,p,e,We]),cl=(0,o.useCallback)(async(i,b)=>{if(ut.current)return;ut.current=!0,Mr(!0),Z("processing"),We(null);let $=b?.sessionId??e,_e=b?.nonce??t,G=rs(ae,b?.accountPatch),Ie=b?.completionPaymentMethodId??va(i),Ht=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,gn=Jd(i),Pt=b?.presentationMode?yi(Sr(rt),{...De,presentationMode:b.presentationMode}):void 0,St=()=>{v?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:gn}),Pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...On,requestCategory:"process_payment"})};try{let At=new Ln.PaymentAPI(ht),pn=b?.settledProcessResponse??await At.processPayment(G.userId??"",{sessionId:$,nonce:_e,paymentMethodCategory:b?.paymentMethodCategory??Qd(i),tokenizedData:Ht,accountData:{...b?.accountPatch,userId:G.userId??"",email:G.email??"",firstName:G.firstName||void 0,lastName:G.lastName||void 0,...(0,l.buildProcessPaymentAvsAccount)({avsConfig:Le,country:ar.current,zip:Br.current,city:hr.current,state:Vt.current,addressLine1:Jt.current,addressLine2:Ur.current})},...(0,l.buildCheckoutProcessMetadata)({chv:H,avsCheck:Ze,checkoutType:Ge,checkoutLayout:_t,avsConfig:Le,country:ar.current})}),Za=async _r=>{let bo=(0,l.isAuthorizationOnlySession)(X)||_r?.status==="authorized";(0,Dn.markSessionRecentlyCompleted)($),Pt?.terminal({outcome:"payment_succeeded",...On}),Z("success"),f(null),await new Promise(ga=>setTimeout(ga,600));let Vn;typeof _r?.paymentId=="string"?Vn=_r.paymentId:X?.paymentId&&(Vn=X.paymentId);let So;typeof _r?.authorizationExpiresAt=="string"?So=_r.authorizationExpiresAt:X?.authorizationExpiresAt&&(So=X.authorizationExpiresAt),c?.(bo?{status:"authorized",...Vn===void 0?{}:{paymentId:Vn},sessionId:typeof _r?.sessionId=="string"?_r.sessionId:$,...So===void 0?{}:{authorizationExpiresAt:So},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Ie,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Ie,checkoutMethod:i.isPaypal?"paypal":"card"})};if(pn.ok){await Za(pn.status===204?null:await pn.json().catch(()=>null));return}let yr=await pn.json().catch(()=>null);if(yr?.type==="paypal_redirect_required"){let _r=yr.threeDSecureToken,bo=yr.paymentMethodId||i.id||"";if(!rt||!_r){Z("error"),We("PayPal authorization required but no token provided.");return}try{let Vn=Rt?.getRawProvider();if(!Vn){We("PayPal is not available.");return}let So={return_url:window.location.href};bo&&(So.payment_method=bo);let{error:ga}=await Vn.confirmPayment({clientSecret:_r,confirmParams:So,redirect:"if_required"});if(ga){Z("error");let bl=ga.message??"PayPal payment failed.";We(bl),qn("paypal",bl,{code:ga.code})}}catch(Vn){Z("error"),We(Vn instanceof Error?Vn.message:"PayPal authorization failed.")}return}if(yr?.type==="paypal_direct_required"){let _r=yr.orderId;if(!_r){Z("error"),We("PayPal retry required but no order id provided.");return}let bo=S.current?.attempts??0;if(bo>=2){Z("error"),We("PayPal payment could not be completed after multiple attempts."),qn("paypal","paypal_direct_required retry limit exceeded");return}ji(!1),Vi("loading"),f({orderId:_r,attempts:bo+1}),Z(null);return}if(pn.headers.get(Nd)===Ud){let _r=await zd(At,$,_e);if(_r!==void 0){await Za(_r);return}}(0,l.classifyPaymentRejection)(pn.status,yr)?Pt?.terminal({outcome:"payment_declined",...On,terminalReason:"provider_declined"}):St(),Z("error");let Cl=yr?.message??"Payment failed. Please try again.";We(Cl),qn(i.isPaypal?"paypal":"card",Cl,{code:yr?.code??yr?.gatewayErrorCode,declineCode:yr?.declineCode??yr?.gatewayDeclineReason}),await new Promise(_r=>setTimeout(_r,400))}catch(At){dc(At)||St(),Z("error"),We(At instanceof Error?At.message:"An unexpected error occurred"),await new Promise(mr=>setTimeout(mr,400))}finally{Mr(!1),Z(null),ut.current=!1}},[ht,e,t,ae,Le,Ze,Ge,_t,H,rt,Rt,X,c,We,qn,v,De]),en=(0,o.useCallback)((i,b)=>{_&&!b?.settledProcessResponse?_(i):cl(i,b)},[_,cl]),ua=`${lc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(ua);if(!i)return;let b;try{b=JSON.parse(i)}catch{lr(ua);return}if(!b||typeof b.createdAt!="number"||Date.now()-b.createdAt<0||Date.now()-b.createdAt>cc||typeof b.paymentMethodId!="string"||typeof b.providerIntentId!="string"||typeof b.paymentMethodType!="string"||b.sessionId!==e||!t||b.nonce!==t||!Oo.includes(b.paymentMethodType)){lr(ua);return}lr(ua),en({id:b.paymentMethodId,type:"card",threeDSecureActionResultTokenId:b.providerIntentId,gateway:"stripe",paymentMethodType:b.paymentMethodType},{...b.accountPatch?{accountPatch:b.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[en,t,e,ua,Oo]);let dl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||dl.current)return;let[i,b,$]=(0,l.readStripeRedirectParams)();if(!i||!b||ja.current||!rt)return;let _e=rt.getRawProvider();if(!_e)return;let G=St=>{let At=localStorage.getItem(St);if(!At)return null;try{return JSON.parse(At)}catch{return lr(St),null}},Ie=G(Kn)??G(Zl),Ht;if(Ie?.clientSecret){if(Ie.clientSecret!==b)return;Ht={...Ie.accountPatch?{accountPatch:Ie.accountPatch}:{},...Ie.sessionId?{sessionId:Ie.sessionId}:{},...Ie.nonce?{nonce:Ie.nonce}:{}}}else if(Ie?.sessionId&&Ie.sessionId!==e)return;dl.current=!0,lr(Kn),lr(Zl),window.history.replaceState({},"",(0,l.stripeRedirectReturnUrl)());let gn=Ie?.paymentMethodType??Ie?.tokenType??"card",Pt="card";(async()=>{if($==="failed"){let yr="Payment was declined. Please try again.";We(yr),qn(Pt,yr);return}let{paymentIntent:St,error:At}=await _e.retrievePaymentIntent(b);if(At){let yr=At.message??"Failed to retrieve payment status.";We(yr),qn(Pt,yr,{code:At.code});return}let mr=St?.status,pn=Pa(mr);if(!St||!pn){let yr=mr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";We(yr),qn(Pt,yr,{code:mr??"missing_payment_intent"});return}let Za=typeof St.payment_method=="string"?St.payment_method:St.payment_method?.id;en({id:Za??Ie?.paymentMethodId??Ie?.tokenId??St.id,type:"card",threeDSecureActionResultTokenId:St.id,gateway:Ie?.gateway??"stripe",paymentMethodType:gn},Ht)})()},[e,en,rt,We,qn]);let $i=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(Ce||rt!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let pa=ke==="buttons",tn=Cr?.variables,$c=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Hi=tn?.colorBackground,Hc=Hi&&!$c.has(Hi)?Hi:void 0,ma=ee.cardInputBorder??(pa?"#e5e7eb":"#A4A4FF"),ul=tn?.colorDanger??"#dc2626",rr=i=>Un[i]&&(Qn[i]||er),Ga=xo&&(Tn||er),fn=i=>i?ul:ma,Ya=(Ye.malformed||Ye.empty)&&(Jn||er),Kc=fn(Ya),Ki=ee.cardFormContainer?.backgroundColor??Hc??(pa?"white":"#EDEDFF"),No=ee.cardInputBackground??tn?.colorBackground??"white",Gi=qo(Ve),pl=qo(me),Uo=ee.nameInput,ml=ee.cardInputFontSize??nu(Uo?.fontSize)??tn?.fontSizeBase??"16px",yl=typeof Uo?.fontFamily=="string"?Uo.fontFamily:tn?.fontFamily??"Poppins, sans-serif",fl=(0,l.toCssWeight)(Uo?.fontWeight)??400,Gc=ee.cardInputColor??(typeof Uo?.color=="string"?Uo.color:void 0)??tn?.colorText??"#262833",Yc=ee.cardInputPlaceholderColor??"#9ca3af",ir=tn?.borderRadius??"8px",vo=tn?.borderRadius??ee.cardButton?.borderRadius??ir,Co=tn?.colorPrimary??"#4A49FF",Xc=tn?.colorPrimaryHover??(0,l.darkenHex)(Co,.12),Yi=tn?.colorText??"#262833",Xi={fontSize:ml,fontFamily:yl,fontWeight:fl,color:Gc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ya={marginTop:"0.375rem",...Xi,fontSize:"0.75rem",lineHeight:1.4,color:ul},Jc={"--flopay-input-placeholder-color":Yc,"--flopay-input-font-size":ml,"--flopay-input-font-family":yl,"--flopay-input-font-weight":String(fl)},fa=ee.cardFormContainer??{},Ji=fa.padding??(pa?"0":"1rem"),Zi=fa.borderRadius??ir,Zc=nt&&cn?(0,d.jsx)(fo,{capture:nt,html:cn.html,messageToken:cn.messageToken,expectedOrigin:cn.expectedOrigin,verificationRequired:cn.verificationRequired,theme:Po,submitLabel:Y,onReady:()=>{if(!Bt&&!Le||typeof document>"u"||D===!1)return;let i=()=>{let $=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if($){yn.current=!0;try{$.focus()}finally{yn.current=!1}}};co.current||i()},onError:i=>{i&&cn.verificationRequired&&pe.current==="idle"&&(po.current=!0),We(i)},onValidation:i=>{let b=pe.current;(b==="idle"||b==="validation-window")&&(We(i),i&&pe.current==="validation-window"&&(j.current&&(clearTimeout(j.current),j.current=null),pe.current="idle",Z(null)))}},Lr):(0,d.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),gl=(0,d.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&uo()},style:{backgroundColor:Ki,borderRadius:Zi,...fa,padding:Ji,...Jc,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${ce.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),ua&&_o&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ve?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:me,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:de.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...de.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...de.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(jo,{content:Ue})]}),pl?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:de.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...de.title},children:(0,d.jsx)(ga,{content:ye})})]}),!ua&&!pl&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Yi,order:ve?-3:0,...de.title},children:(0,d.jsx)(ga,{content:ye})}),ve&&le&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:le}),ve&&yo&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:Lo,border:`1px solid ${hn(Ka)}`,borderRadius:cr,padding:"10px"},children:(0,d.jsx)("input",{ref:te,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:ir,onChange:i=>{Vt("email"),Lr.current=i.target.value,nn(i.target.value)},onPointerDown:()=>Vt("email"),onKeyDown:()=>Vt("email"),onBlur:()=>{Xr("email")&&po(!0),Mo||Ni()},disabled:Ie,required:!0,"aria-invalid":Ka||void 0,"aria-describedby":Ka?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Xi}})}),Ka&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ma,children:Bi.empty?"Email address is required":"Enter a valid email address"})]}),Ce&&(0,d.jsx)("div",{style:{order:ve?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=st,b=(G=!1)=>({backgroundColor:Lo,border:`1px solid ${hn(G)}`,borderRadius:cr,marginTop:"0.5rem",padding:"10px"}),$=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Xi}),_e=(0,l.getStateOptions)(i);return(0,d.jsxs)(d.Fragment,{children:[(0,l.isAVSFieldVisible)(Ce.address_line_1,i)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:b(or("line1")),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Xt,onChange:G=>{Vt("line1"),Er.current.addressLine1=!0,Qt.current=G.target.value,ar(G.target.value)},onPointerDown:()=>Vt("line1"),onKeyDown:()=>Vt("line1"),onBlur:()=>Jr("line1"),disabled:Ie,required:!0,"aria-invalid":or("line1")||void 0,"aria-describedby":or("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:$()})}),or("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ma,children:"Street address is required"})]}),(0,l.isAVSFieldVisible)(Ce.address_line_2,i)&&(0,d.jsx)("div",{style:b(),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:tr,onChange:G=>{Er.current.addressLine2=!0,zr.current=G.target.value,In(G.target.value)},disabled:Ie,"data-testid":"flopay-address-line2",style:$()})}),((0,l.isAVSFieldVisible)(Ce.city,i)||(0,l.isAVSFieldVisible)(Ce.state,i))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Ce.city,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Lo,borderTop:`1px solid ${hn(or("city"))}`,borderRight:`1px solid ${hn(or("city"))}`,borderBottom:`1px solid ${hn(or("city"))}`,borderLeft:`1px solid ${hn(or("city"))}`,padding:"10px",borderTopLeftRadius:cr,borderBottomLeftRadius:cr,...(0,l.isAVSFieldVisible)(Ce.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:cr}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Jt,onChange:G=>{Vt("city"),Er.current.city=!0,Pr.current=G.target.value,qn(G.target.value)},onPointerDown:()=>Vt("city"),onKeyDown:()=>Vt("city"),onBlur:()=>Jr("city"),disabled:Ie,required:!0,"aria-invalid":or("city")||void 0,"aria-describedby":or("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:$()})}),(0,l.isAVSFieldVisible)(Ce.state,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Lo,borderTop:`1px solid ${hn(or("state"))}`,borderRight:`1px solid ${hn(or("state"))}`,borderBottom:`1px solid ${hn(or("state"))}`,borderLeft:`1px solid ${hn(or("state"))}`,padding:"10px",borderTopRightRadius:cr,borderBottomRightRadius:cr,...(0,l.isAVSFieldVisible)(Ce.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${hn(or("state")||or("city"))}`}:{borderRadius:cr}},children:_e?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Dr,onChange:G=>{Vt("state"),Er.current.state=!0,jt.current=G.target.value,Zt(G.target.value)},onPointerDown:()=>Vt("state"),onKeyDown:()=>Vt("state"),onBlur:()=>Jr("state"),disabled:Ie,autoComplete:"billing address-level1",required:!0,"aria-invalid":or("state")||void 0,"aria-describedby":or("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...$(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,l.getStateLabel)(i)}),_e.map(G=>(0,d.jsx)("option",{value:G.code,children:G.name},G.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,l.getStateLabel)(i),autoComplete:"billing address-level1",value:Dr,onChange:G=>{Vt("state"),Er.current.state=!0,jt.current=G.target.value,Zt(G.target.value)},onPointerDown:()=>Vt("state"),onKeyDown:()=>Vt("state"),onBlur:()=>Jr("state"),disabled:Ie,required:!0,"aria-invalid":or("state")||void 0,"aria-describedby":or("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:$()})})]}),or("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ma,children:"City is required"}),or("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ma,children:[(0,l.getStateLabel)(i)," is required"]}),((0,l.isAVSFieldVisible)(Ce.country,i)||(0,l.isAVSFieldVisible)(Ce.postal_code,i))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:j==="column"?"column":"row",gap:j==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Ce.country,i)&&(0,d.jsx)("div",{style:{flex:j==="row"?1:void 0,backgroundColor:Lo,borderTop:`1px solid ${pa}`,borderRight:`1px solid ${pa}`,borderBottom:`1px solid ${pa}`,borderLeft:`1px solid ${pa}`,padding:"10px",...j==="row"&&(0,l.isAVSFieldVisible)(Ce.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:cr,borderBottomLeftRadius:cr,borderRight:"none"}:{borderRadius:cr}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:st,onChange:G=>{Er.current.country=!0,sr.current=G.target.value,Gr(G.target.value),je?.(G.target.value),jt.current="",Zt("")},disabled:Ie,autoComplete:"billing country","data-testid":"flopay-country",style:{...$(),cursor:"pointer"},children:[st===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,l.COUNTRY_OPTIONS.map(G=>(0,d.jsxs)("option",{value:G.code,children:[G.flag," ",G.name]},G.code))]})}),(0,l.isAVSFieldVisible)(Ce.postal_code,i)&&(0,d.jsx)("div",{style:{flex:j==="row"?1:void 0,backgroundColor:Lo,border:`1px solid ${Kc}`,padding:"10px",...j==="row"&&(0,l.isAVSFieldVisible)(Ce.country,i)?{borderRadius:"0",borderTopRightRadius:cr,borderBottomRightRadius:cr}:{borderRadius:cr}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,l.getPostalCodeLabel)(st),autoComplete:"billing postal-code",value:Yr,onChange:G=>{Vt("zip"),Er.current.zip=!0,Or.current=G.target.value,Br(G.target.value),ut?.(G.target.value)},onPointerDown:()=>Vt("zip"),onKeyDown:()=>Vt("zip"),onBlur:()=>{Xr("zip")&&eo(!0)},disabled:Ie,required:rr.required,"aria-invalid":Ga||void 0,"aria-describedby":Ga?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:$()})})]}),Ga&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ma,children:rr.empty?`${(0,l.getPostalCodeLabel)(i)} is required`:eu(i)})]})})()}),ve&&Zc,Ye&&(0,d.jsx)(Xo,{margin:"0.75rem 0",styleOverride:de.errorBanner,children:Ye})]}),Ya={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"},hl=i=>V?!ge||!Hn?(0,d.jsx)("pre",{"data-testid":i,style:Ya,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Ya,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ge}`,` directPaypalConfigured=${Hn}`,` inAppBrowserDetected=${String(Wa)}`,` shouldRenderDirectPayPal=${ia}`,` shouldRenderStripePayPal=${la}`,` hasPaypalStripeInstance=${!!Fs}`].join(`
39
- `)}):null,Pl=i=>V?!S||!cn?(0,d.jsx)("pre",{"data-testid":i,style:Ya,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Ya,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${S}`,` currency=${zt}`,` amountInCents=${oa}`,` enabledPaymentMethods: ${JSON.stringify(A??[])}`,` enabledPaymentMethodsProvided=${aa}`,` hasEnabledMethods=${za}`,` expressMethods: ${JSON.stringify(ja)}`,` walletExpressMethods: ${JSON.stringify(Do)}`,` paymentElementMethods: ${JSON.stringify(zi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Va)}`,` hasStripeInstance=${!!cn}`,` shouldRenderWallets=${Oo}`,` shouldRenderPaymentElement=${ca}`].join(`
40
- `)}):null,vl=yt==="apm-expanding"||yt==="apm-form"||yt==="apm-collapsing",Uo;yt==="apm-expanding"?Uo=rc:yt==="apm-collapsing"&&(Uo=nc);let Xa=Ir?pc(qi,Ir,_t):null;if(Re==="buttons"){let i=yt==="buttons"||yt==="expanding"||yt==="apm-expanding",b=yt==="expanding"||yt==="card"||yt==="collapsing",$=et===void 0?{boxSizing:"border-box",height:ea,padding:"0 1rem"}:{padding:"0.9rem 1rem"},_e;yt==="expanding"||yt==="apm-expanding"?_e=Xd:(yt==="collapsing"||yt==="apm-collapsing")&&(_e=Yd);let G;return yt==="expanding"?G=rc:yt==="collapsing"&&(G=nc),(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ta,{}),Ve&&(0,d.jsx)(tn,{status:Ve,errorMessage:Ye,authorized:_n}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!_e?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!_e?Zd:{},..._e?{animation:_e,pointerEvents:"none"}:{}},children:[hl("flopay-direct-paypal-gate-debug"),Pl("flopay-stripe-gate-debug"),ia&&ue&&(0,d.jsxs)(d.Fragment,{children:[m&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(Ca.Provider,{value:ne,children:(0,d.jsx)(Sa,{sessionId:e,nonce:t,billingApiUrl:w,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,clientId:ue.clientId,environment:ue.environment,currency:zt.toUpperCase(),isSubscription:pe,providerObjectType:u,approvalPresentation:$a==="popup"?void 0:$a,onTokenizedBody:Qr,onComplete:c,onErrorChange:ze,onDecline:y,onCancel:g,onTechnicalFailure:Fo,onButtonClick:W,runBeforeButtonClick:Bn,isProcessing:Ie,onLoadStateChange:ji,onInitializationStateChange:Vi,session:Oe,existingOrderId:m?.orderId,debug:V},m?.orderId??"fresh")})]}),la&&(0,d.jsx)(dr.Elements,{stripe:sa,options:Os,children:(0,d.jsx)(ac,{sessionId:e,nonce:t,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,billingApiUrl:w,onTokenizedBody:Qr,onErrorChange:ze,isProcessing:Ie,onButtonClick:W,onDecline:y,onTechnicalFailure:Fo,runBeforeButtonClick:Bn,onLoadStateChange:Ys,placeholderBorderRadius:Po,popupCapabilityOwner:ne,externalTelemetryContext:ol,presentationMode:Bo})}),Oo?(0,d.jsx)(dr.Elements,{stripe:cn,options:Ds,children:(0,d.jsx)(ic,{sessionId:e,nonce:t,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,billingApiUrl:w,intentKind:Ot>0?"payment":"setup",expressMethods:Do,onTokenizedBody:Qr,onErrorChange:ze,onButtonClick:W,onDecline:y,onTechnicalFailure:Fo,runBeforeButtonClick:Bn,onLoadStateChange:Js,placeholderBorderRadius:Po,popupCapabilityOwner:ne,externalTelemetryContext:De})}):null,!Oo&&rl?(0,d.jsx)("div",{style:{height:ea,borderRadius:Po,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ca&&(0,d.jsx)(sc,{sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:It,billingApiUrl:w,paymentElementMethods:Va,stripeInstance:cn,paymentElementBaseOptions:qi,futureUseSession:_t,onTokenizedBody:Qr,onErrorChange:ze,onButtonClick:W,onDecline:y,runBeforeButtonClick:Bn,onLoadStateChange:Qs,isProcessing:Ie,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:de.submitButton,onExpandApm:kt,expandedApmMethod:Ir,themeId:ct,buttonAppearance:{backgroundColor:de.cardButton?.backgroundColor,borderColor:de.cardInputBorder,textColor:de.cardButton?.color,borderRadius:Po}}),ve&&(0,d.jsx)("button",{type:"button",onClick:async()=>{Ie||!(await Bn("card")).proceed||(W?.("card"),se())},disabled:Ie,style:{width:"100%",...$,...de.cardButton,...bs({themeBundle:br,resolvedPrimaryColor:vo,resolvedBorderRadius:cr,submitButtonStyle:de.submitButton,explicitPrimaryColor:en?.colorPrimary}),fontSize:de.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ie?"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:Ie?.6:1},onMouseEnter:Te=>{!Ie&&(br||en?.colorPrimary)&&(Te.currentTarget.style.backgroundColor=Xc)},onMouseLeave:Te=>{(br||en?.colorPrimary)&&(Te.currentTarget.style.backgroundColor=vo)},onMouseDown:Te=>{Te.currentTarget.style.transform="scale(0.985)"},onMouseUp:Te=>{Te.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(qo,{content:et})}),Ye&&yt==="buttons"&&(0,d.jsx)(Xo,{margin:"0.25rem 0",styleOverride:de.errorBanner,children:Ye})]}),ve&&b&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...G?{animation:G}:{},...yt==="collapsing"?{pointerEvents:"none"}:{}},children:gl}),S&&vl&&Ir&&Xa&&cn&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Uo?{animation:Uo}:{},...yt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ki,borderRadius:Zi,...ya,padding:Ji},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:de.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...de.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...de.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(jo,{content:Ue})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:de.titleFontSize??"1.05rem",color:Yi,paddingRight:80,...de.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(Ir)}`})]}),(0,d.jsx)(dr.Elements,{stripe:cn,options:Xa,children:(0,d.jsx)(Ps,{method:Ir,sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:It,billingApiUrl:w,onTokenizedBody:Qr,onErrorChange:ze,onDecline:y,onCancel:Wt,runBeforeButtonClick:Bn,onButtonClick:W,isProcessing:Ie,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:de.submitButton,errorText:Ye})},Ir)]})})]})]})}return vl&&Ir&&Xa&&cn&&S?(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ta,{}),Ve&&(0,d.jsx)(tn,{status:Ve,errorMessage:Ye,authorized:_n}),(0,d.jsx)("div",{style:{...Uo?{animation:Uo}:{},...yt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ki,borderRadius:Zi,...ya,padding:Ji},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:de.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...de.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...de.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(jo,{content:Ue})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:de.titleFontSize??"1.05rem",color:Yi,paddingRight:80,...de.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(Ir)}`})]}),(0,d.jsx)(dr.Elements,{stripe:cn,options:Xa,children:(0,d.jsx)(Ps,{method:Ir,sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:It,billingApiUrl:w,onTokenizedBody:Qr,onErrorChange:ze,onDecline:y,onCancel:Wt,runBeforeButtonClick:Bn,onButtonClick:W,isProcessing:Ie,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:de.submitButton,errorText:Ye})},Ir)]})})]}):(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ta,{}),Ve&&(0,d.jsx)(tn,{status:Ve,errorMessage:Ye,authorized:_n}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[hl("flopay-direct-paypal-gate-debug-default"),Pl("flopay-stripe-gate-debug-default"),ia&&ue&&(0,d.jsxs)(d.Fragment,{children:[m&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(Ca.Provider,{value:ne,children:(0,d.jsx)(Sa,{sessionId:e,nonce:t,billingApiUrl:w,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,clientId:ue.clientId,environment:ue.environment,currency:zt.toUpperCase(),isSubscription:pe,providerObjectType:u,approvalPresentation:$a==="popup"?void 0:$a,onTokenizedBody:Qr,onComplete:c,onErrorChange:ze,onDecline:y,onCancel:g,onTechnicalFailure:Fo,onButtonClick:W,runBeforeButtonClick:Bn,isProcessing:Ie,onLoadStateChange:ji,onInitializationStateChange:Vi,session:Oe,existingOrderId:m?.orderId,debug:V},m?.orderId??"fresh")})]}),la&&(0,d.jsx)(dr.Elements,{stripe:sa,options:Os,children:(0,d.jsx)(ac,{sessionId:e,nonce:t,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,billingApiUrl:w,onTokenizedBody:Qr,onErrorChange:ze,isProcessing:Ie,onButtonClick:W,onDecline:y,onTechnicalFailure:Fo,runBeforeButtonClick:Bn,onLoadStateChange:Ys,placeholderBorderRadius:Po,popupCapabilityOwner:ne,externalTelemetryContext:ol,presentationMode:Bo})}),Oo&&(0,d.jsx)(dr.Elements,{stripe:cn,options:Ds,children:(0,d.jsx)(ic,{sessionId:e,nonce:t,email:re.email,billingName:_r||void 0,onBuyerIdentityReady:It,billingApiUrl:w,intentKind:Ot>0?"payment":"setup",expressMethods:Do,onTokenizedBody:Qr,onErrorChange:ze,onButtonClick:W,onDecline:y,onTechnicalFailure:Fo,runBeforeButtonClick:Bn,onLoadStateChange:Js,placeholderBorderRadius:Po,popupCapabilityOwner:ne,externalTelemetryContext:De})}),ca&&(0,d.jsx)(sc,{sessionId:e,nonce:t,email:re.email,billingName:[re.firstName,re.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:w,paymentElementMethods:Va,stripeInstance:cn,paymentElementBaseOptions:qi,futureUseSession:_t,onTokenizedBody:Qr,onErrorChange:ze,onButtonClick:W,onDecline:y,runBeforeButtonClick:Bn,onLoadStateChange:Qs,isProcessing:Ie,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:de.submitButton,themeId:ct,onExpandApm:kt,expandedApmMethod:Ir,buttonAppearance:{backgroundColor:de.cardButton?.backgroundColor,borderColor:de.cardInputBorder,textColor:de.cardButton?.color,borderRadius:Po}})]}),ve&&(Vc||jc||Wc)&&(0,d.jsx)(vi,{label:"or pay with card"}),ve&&gl]})}var D=require("react/jsx-runtime"),ra=44,_s="flopay_checkout_saved_payment_resume",_i=new Map,Ei=new Map;function mc(e,t){t.settled&&t.consumers===0&&_i.get(e)===t&&_i.delete(e)}function su(e,t,r){let n=Ei.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};Ei.set(e,s);let c=()=>{Ei.get(e)===s&&Ei.delete(e)};return a.then(c,c),a}function Da(e){return new Promise(t=>setTimeout(t,e))}function Ii(e,t,r){let n=si({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ne.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Oa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ws(e,t,r,n,a,s){let c=Ii(e,t,r);c.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Oa(c)}function yc(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 fc(e,t,r,n,a){let s=(0,Ne.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 Ne.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Ne.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 Rs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,Ne.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var lu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function cu(e){return new co.FloPay(lu,{publishableKey:"provider_unavailable",...e})}async function ks(e,t){let{publishableKey:r,paypalPublishableKey:n}=ls(e);return{...await cs({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Ts(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function du(){if(!Ts())return null;try{let e=window.sessionStorage.getItem(_s);return e?JSON.parse(e):null}catch{return null}}function gc(e){if(Ts())try{window.sessionStorage.setItem(_s,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Es(){if(Ts())try{window.sessionStorage.removeItem(_s)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function uu(){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 hc(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 Is(e,t){return(0,Ne.resolveCheckoutLogLayout)(!!e,t)}function pu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Pc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function mu(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 Ti({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:c,loading:p,error:y,onComplete:g,onError:E,onInstrument:R,onDecline:_,onCancel:H,onCountryChange:T,onZipChange:Y,showPayPal:B=!0,showStripe:f=!0,walletPresentation:h="auto",enabledPaymentMethods:ge,showApplePay:S=!0,showGooglePay:Me=!0,debug:A=!1,layout:ie,theme:he,buttonsTheme:fe,buttonsStyles:Re,cardButtonContent:ct,cardBackButtonContent:Ke,cardTitleContent:F,showSecurityFooter:St,onButtonClick:et,onBeforeButtonClick:Ue,enableAVS:ye,cardFieldOrder:J,cardAutoFocus:W,cardPreFormSlot:Fe,avsLayout:dt,submitLabel:We,className:Z,initialErrorMessage:L=null,initialPayPalOrderId:le,children:j,checkoutMode:Se,confirmLabel:xe,renderConfirmButton:Pe,onSessionCompleted:Be}){let M=(0,Ne.resolveBillingApiUrl)(n),nt=(0,P.useMemo)(()=>(0,Ne.resolveTheme)(he),[he]),je=s??nt?.appearance,ut=r?"embedded_checkout":"standard_checkout",Ge=Is(j,ie),[$e,Rt]=(0,P.useState)(null),[Ot,zt]=(0,P.useState)(null),Ft=(0,P.useRef)(null),ue=(0,P.useRef)(null),pe=(0,P.useRef)(0),[X,Pt]=(0,P.useState)(null),pt=(0,P.useRef)(null),[V,rt]=(0,P.useState)(null),wt=(0,P.useMemo)(()=>r?(0,gt.serializeCreateParams)(r):"",[r]),ke=r?`create:${wt}`:`session:${e??""}`,v=Pc(V),U=(0,P.useRef)(new Set),ne=(0,P.useRef)(ke),Ae=(0,P.useRef)(ke);wo(()=>{Ae.current=ke,ne.current!==ke&&(ne.current=ke,U.current.clear())},[ke]);let Dt=(0,P.useCallback)(z=>{if(Ae.current===ke){if(as.FLO_INSTRUMENT_ONCE_NAMES.has(z.name)){if(U.current.has(z.name))return;U.current.add(z.name)}(0,Xe.invokeMerchantCallback)(()=>R?.(z))}},[ke,R]),ot=Yo(Dt,ke),De=(0,P.useRef)(!1),Oe=(0,P.useCallback)(z=>{if(De.current)return;let O=z.gateway||!v?z:{...z,gateway:v};Dt(O)},[Dt,v]);(0,P.useEffect)(()=>{ot({class:"lifecycle",name:"checkout.mount"})},[ot]);let[_t,u]=(0,P.useState)(e??""),C=e??_t,Q=r?"":C,[ce,N]=(0,P.useState)(!0),[w,qt]=(0,P.useState)(null),[Ar,mr]=(0,P.useState)(0),[Fr,st]=(0,P.useState)("full"),[Gr,Yr]=(0,P.useState)(!1),[Br,Xt]=(0,P.useState)(L),[ar,tr]=(0,P.useState)(null),[In,Jt]=(0,P.useState)(null),[qn,Dr]=(0,P.useState)(!1),[Zt,ir]=(0,P.useState)(void 0),[nn,mt]=(0,P.useState)(""),[Tt,Or]=(0,P.useState)(!1),[sr,Qt]=(0,P.useState)(!1),[zr,Pr]=(0,P.useState)(!1),jt=(0,P.useRef)(null),Lr=(0,P.useRef)(0),Er=(0,P.useRef)(void 0),[Ce,Nr]=(0,P.useState)("loading"),[_n,Tn]=(0,P.useState)(0),vr=(0,P.useRef)(!1),pn=(0,P.useRef)(!1),mn=(0,P.useRef)(!1),Mn=(0,P.useRef)(null),Lt=(0,P.useRef)(null),ve=(0,P.useMemo)(()=>({checkoutMode:Se??Fr,layout:pu(j,ie)}),[Se,j,Fr,ie]),on=(0,P.useRef)(g);on.current=g;let K=(0,P.useRef)(E);K.current=E;let Nt=(0,P.useRef)(_);Nt.current=_;let ae=(0,P.useCallback)(z=>di(Mn,async O=>{try{return await z(O)}catch(se){throw O.aborted?Jo(se):se}}),[]);(0,P.useEffect)(()=>()=>{Mn.current?.abort(),Mn.current=null},[]);let Ht=(0,P.useCallback)((z,O)=>{Ft.current=z,zt(z),pt.current=O,Pt(O)},[]),Gt=(0,P.useCallback)(()=>{let z=ue.current;z&&(ue.current=null,z.destroy())},[]);(0,P.useEffect)(()=>{Rr(Ot)?.setCheckoutContext(ve),X&&X!==Ot&&Rr(X)?.setCheckoutContext(ve)},[Ot,X,ve]);let be=(0,P.useRef)(Be);be.current=Be;let Ut=(0,P.useCallback)(z=>{Nr(z),!(z!=="exhausted"||mn.current)&&(mn.current=!0,K.current?.(new Ne.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),tt=(0,P.useCallback)(()=>{Nr("retrying"),Tn(z=>z+1)},[]);(0,P.useEffect)(()=>{Nr("loading"),Tn(0),mn.current=!1},[C]),(0,P.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ne.SDK_VERSION,checkout_type:ut,checkout_layout:Ge,billing_api_url:M})},[Ge,ut,M]);let at=(0,P.useMemo)(()=>r?(0,gt.serializeCreateParams)(r,!0):"",[r]),rr=(0,P.useMemo)(()=>nn===at?Zt:void 0,[Zt,nn,at]),Vr=(0,P.useMemo)(()=>r?ts(r,rr):void 0,[r,rr]),yn=Se??Vr?.checkoutMode??"full",lr=(0,P.useMemo)(()=>Vr?{...Vr,checkoutMode:yn}:void 0,[Vr,yn]);(0,P.useEffect)(()=>{ir(void 0),mt(at),Er.current=void 0,jt.current=null,Pr(!1)},[at]),(0,P.useEffect)(()=>{Xt(L)},[L]);let jn=(0,P.useCallback)((z,O,se)=>{(0,Xe.invokeMerchantCallback)(()=>{Nt.current?.(wr(z,O,se))})},[]),Vn=(0,P.useCallback)(async(z,O)=>{Xt(null),Jt(null),Dr(!1),tr("processing");let se=O?.sessionId??z.id,me=z.clientSecret||t,kt=Pc(z),Wt=Ft.current??pt.current,Ve=Rr(Wt),oe=Wt?null:Ii(M,a,ve),te={log:m=>{Ve?Ve.log(m):oe?.log(m)},error:m=>{Ve?Ve.error(m):oe?.error(m)},terminal:m=>{Ve?Ve.terminal(m):oe?.terminal(m)},performance:m=>{Ve?Ve.performance(m):oe?.performance(m)},now:()=>Ve?.now()??oe?.now()??0,elapsed:m=>Ve?.elapsed(m)??Math.max(0,(oe?.now()??m)-m)},Je=te.now(),Ee=!!(O?.initialAutoProcessingError||O?.initialAutoProcessingPending),it=!1,q,ee=()=>{it||(it=!0,Ee=!0,q=te.now(),te.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Bt=!1,Et=()=>{Bt||(Bt=!0,te.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),te.performance({stage:"processing",durationMs:te.elapsed(Je),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),q!==void 0&&te.performance({stage:"recovery",durationMs:te.elapsed(q),durationMode:"machine",paymentMethodCategory:"saved"}))};te.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),De.current=!0;try{te.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{De.current=!1}ot({class:"lifecycle",name:"payment.processing.started",provider:kt}),Ee&&ee();let x;try{let m=Hl(O?.initialAutoProcessingError),I=O?.initialAutoProcessingError?.type==="3ds_required"&&!O.initialAutoProcessingError.threeDSecureToken&&O.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:O.initialAutoProcessingError.nextActionRedirectUrl}:null,Le,Ze=He=>{ee();let It=Ia(M,se,z,a!==!1);return ae(Ye=>Zo(He,{billingApiUrl:M,sessionId:se,nonce:me,session:z,signal:Ye,...It.telemetry?{challengeTelemetry:It.telemetry}:{}})).finally(It.release)};if(I)Le=await Ze(I);else if(m)ee(),m.type==="paypal_redirect_required"&&Lt.current?.publishableKey&&gc({sessionId:se,publishableKey:Lt.current.publishableKey,paypalPublishableKey:Lt.current.paypalPublishableKey}),Le=await ae(He=>pi(m,{flopay:Ft.current,paypalFlopay:pt.current,attempt3DS:O?.attempt3DS,billingApiUrl:M,sessionId:se,session:z,telemetry:!1,signal:He})),m.type==="paypal_redirect_required"&&Es();else if(O?.initialAutoProcessingPending){let He=O.initialAutoProcessingPending,It=new co.PaymentAPI(M,{telemetry:!1}),Ye=await ae(Sr=>It.waitForCheckoutSessionCompletion(He.sessionId,{initialDelayMs:He.retryAfterMs,nonce:me,statusUrl:He.statusUrl,signal:Sr})),br=go(Ye,z),de=Ye.autoProcessingError?.type==="3ds_required"&&Ye.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ye.autoProcessingError.nextActionRedirectUrl}:null;if(de)Le=await Ze(de);else{if(!oo(br))throw Wo(br);Le=no(br,se)}}else{if(O?.initialAutoProcessingError)throw Xn(O.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:O.initialAutoProcessingError.checkoutMethod});if(O?.fromCreateSession)return O?.fallbackToFull&&(st("full"),hc("full")),!1;{let He=await Qo({billingApiUrl:M,sessionId:se,session:z,nonce:me,telemetry:!1});He.type==="success"?Le=He.result:He.type==="next_action_required"?Le=await Ze(He):(ee(),He.type==="paypal_redirect_required"&&Lt.current?.publishableKey&&gc({sessionId:se,publishableKey:Lt.current.publishableKey,paypalPublishableKey:Lt.current.paypalPublishableKey}),Le=await ae(It=>pi(He,{flopay:Ft.current,paypalFlopay:pt.current,attempt3DS:O?.attempt3DS,billingApiUrl:M,sessionId:se,session:z,telemetry:!1,signal:It})),He.type==="paypal_redirect_required"&&Es())}}se&&(0,Nn.markSessionRecentlyCompleted)(se),Et(),Ee&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),te.terminal({outcome:Le.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Dr(Le.status==="authorized"),tr("success"),await Da(600),x=()=>on.current?.(Le)}catch(m){let I=fo(_a(m),se);if(I.code==="three_ds_aborted")return!1;let Le=I.checkoutMethod??Ea;Xt(I.message),Jt(I.message),Dr(!1),O?.fallbackToFull&&(te.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),st("full"),hc("full")),Et();let Ze=I.statusCode===void 0?void 0:(0,Ne.telemetryStatusClass)(I.statusCode,"unknown"),He=Ze==="4xx"?{requestCategory:"process_payment",statusClass:Ze}:{},It=Ze===void 0||Ze==="4xx";if(It&&(I.telemetryOutcome==="payment_declined"||!!(I.declineCode||I.code?.toLowerCase().includes("declin"))))te.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...He});else if(It&&(I.telemetryOutcome==="validation_rejected"||I.type==="validation_error"))te.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...He});else{let de=(0,Ne.classifyTelemetryFailure)(m,Ee?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Sr=I.telemetryRequestCategory??"process_payment";De.current=!0;try{te.error({...de,...I.telemetryFailureCategory?{failureCategory:I.telemetryFailureCategory}:{},stage:Ee?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Sr})}finally{De.current=!1}ot({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Sr,provider:kt})}return(0,Xe.invokeMerchantCallback)(()=>K.current?.(I)),jn(Le,I,{code:I.code,declineCode:I.declineCode}),tr("error"),await Promise.allSettled([Da(400),O?.ensureProvidersReady?O.ensureProvidersReady():Promise.resolve()]),Ee&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Et(),oe&&Oa(oe),tr(null),Jt(null)}return(0,Xe.invokeMerchantCallback)(x),!0},[jn,ot,t,M,ae,a,ve]);(0,P.useEffect)(()=>{if(typeof window>"u"||pn.current)return;let z=new URLSearchParams(window.location.search),O=z.get("payment_intent_client_secret");if(!O)return;let se=du();se&&(pn.current=!0,(async()=>{let me,kt=0;Xt(null),Jt(null),tr("processing"),Yr(!0);try{if(z.get("redirect_status")==="failed")throw Object.assign(new Ne.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Wt,paypalFlopay:Ve}=await cs({publishableKey:se.publishableKey,paypalPublishableKey:se.paypalPublishableKey,billingApiUrl:M,locale:c,telemetry:a});me=Rr(Ve??Wt),me?.setCheckoutContext(ve),kt=me?.now()??0,me?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),me?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let oe=(Ve??Wt)?.getRawProvider();if(!oe)throw Object.assign(new Ne.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:te,error:Je}=await oe.retrievePaymentIntent(O);if(Je)throw Object.assign(new Ne.FloPayError(Je.message??"Failed to retrieve PayPal payment status.","api_error",{code:Je.code}),{checkoutMethod:"paypal"});let Ee=xl(te?.status);if(!te||Ee==="failed")throw Object.assign(new Ne.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let it=typeof te.payment_method=="string"?te.payment_method:te.payment_method?.id,q=Ee;if(se.sessionId){let Et=(await new co.PaymentAPI(M,{telemetry:!1}).getUnifiedCheckoutSession(se.sessionId)).data.session;if(Et&&Et.status!=="complete"){let x=await Qo({billingApiUrl:M,sessionId:se.sessionId,session:Et,telemetry:!1,tokenizedData:{id:it??te.id,type:"card",threeDSecureActionResultTokenId:te.id,isPaypal:!0}});if(x.type!=="success")throw Object.assign(new Ne.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});q=x.result.status}}se.sessionId&&(0,Nn.markSessionRecentlyCompleted)(se.sessionId),me?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),me?.performance({stage:"redirect_resume",durationMs:me.elapsed(kt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),me?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),tr("success"),await Da(600),(0,Xe.invokeMerchantCallback)(()=>on.current?.({status:q,paymentIntentId:te.id,paymentMethodId:it,checkoutMethod:"paypal"}))}catch(Wt){let Ve=fo(_a(Wt),se.sessionId),oe=Ve.checkoutMethod??"paypal",te=!!(Ve.declineCode||Ve.code?.toLowerCase().includes("declin"));if(me)me.performance({stage:"redirect_resume",durationMs:me.elapsed(kt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),te?me.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):me.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(te){let Je=Ii(M,a,ve);Je.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Oa(Je)}else ws(M,a,ve,"REDIRECT_RESUME_FAILED","redirect_resume");Xt(Ve.message),Jt(Ve.message),(0,Xe.invokeMerchantCallback)(()=>K.current?.(Ve)),jn(oe,Ve,{code:Ve.code,declineCode:Ve.declineCode}),tr("error"),await Da(400)}finally{Es(),uu(),tr(null),Jt(null),Yr(!1)}})())},[jn,c,M,a,ve]);let eo=(0,P.useRef)(null),xn=(0,P.useMemo)(()=>lr?(0,gt.serializeCreateParams)(lr):"",[lr]),po=(0,P.useRef)(lr);po.current=lr,(0,P.useEffect)(()=>{u(e??"")},[e]),(0,P.useEffect)(()=>{vr.current=!1,Xt(L),Jt(null),Dr(!1),tr(null)},[xn,L,e]);async function to(z,O,se){let me=Ii(M,a,ve),kt=new co.PaymentAPI(M,{telemetry:!1}),Wt=!1;try{let Ve=z.idempotencyKey===void 0?void 0:(0,Ne.resolveIdempotencyKey)(z.idempotencyKey),oe=(0,gt.readCachedInlineSession)(O,se),te=(0,gt.readCachedInlineIdempotencyKey)(O,se);oe?.canonicalIdentity===se&&te&&te.canonicalIdentity===void 0&&((0,gt.persistCachedInlineIdempotencyKey)(O,se,te.idempotencyKey),te={...te,canonicalIdentity:se});let Je=Ve??(te?.canonicalIdentity===se?te.idempotencyKey:void 0),Ee,it=!1;me.log({name:oe?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let q=oe?.sid??null,ee=null,Bt,Et,x=!1;if(q)try{ee=await kt.getUnifiedCheckoutSession(q,oe?.nonce),oe&&oe.canonicalIdentity===void 0&&((0,gt.legacyCachedSessionMatchesDraft)(ee.data.session,z)?((0,gt.persistCachedInlineSession)(O,se,q,oe.nonce??ee.data.session?.clientSecret),te&&te.canonicalIdentity===void 0&&((0,gt.persistCachedInlineIdempotencyKey)(O,se,te.idempotencyKey),Je??(Je=te.idempotencyKey))):((0,gt.clearCachedInlineCheckout)(O,se),te=null,Je=Ve,q=null,ee=null));let I=ee?.data.session?.status,Le=ee?.data.session,Ze=Le?.clientSecret||oe?.nonce;if(q&&Le?.buyerIdentified===!1&&Ze&&(Et=Vo(kt,q,Ze,z.account)),q&&ee&&I==="complete"){if((0,Nn.wasSessionRecentlyCompleted)(q))return{sid:q,result:ee};(0,gt.clearCachedInlineCheckout)(O,se),q=null,ee=null,it=!0}}catch{me.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),oe?.canonicalIdentity===void 0?((0,gt.clearCachedInlineCheckout)(O,se),Je=Ve):(0,gt.clearCachedInlineSession)(O,se),q=null}if(!q){!Ve&&(it||!Je)&&(Je=(0,Ne.resolveIdempotencyKey)(),Ee=Je),Je&&(0,gt.persistCachedInlineIdempotencyKey)(O,se,Je);let I=me.now(),Le=0;me.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ze={...z,idempotencyKey:Je,avsCheck:!!ye,avsConfig:typeof ye=="object"?ye:void 0,checkoutType:"embedded_checkout",checkoutLayout:Is(j,ie)};Object.defineProperty(Ze,co.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Ye=>{Le=Math.max(Le,Ye)}}});let He=()=>{yc(me,"session_create",I,Le)},It=Ye=>{fc(me,Ye,"session_create",I,Le)&&ot({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Ne.isDetachedSessionEligible)(Ze)){let Ye=await kt.createDetachedSession(Ze);Ye.claimed.catch(()=>{}),ee=Ye.shell,q=Ye.sessionId,Et=Ye.claim;let br=me.now();me.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Bt=Ye.claimed.then(de=>{let Sr=de.data.session?.id??Ye.sessionId;return Sr&&(0,gt.persistCachedInlineSession)(O,se,Sr,de.data.session?.clientSecret??Ye.nonce),yc(me,"session_claim",br),He(),de},de=>{throw(0,gt.clearCachedInlineSession)(O,se),fc(me,de,"session_claim",br,0)&&ot({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),de}).finally(()=>Oa(me)),Bt.catch(()=>{}),Wt=!0,me.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),me.performance({stage:"session_shell",durationMs:me.now()-I,durationMode:"machine",requestCategory:"session_create",attempt:Le,statusClass:"2xx",paymentMethodCategory:"card"})}else ee=await kt.createAndFetchSession(Ze),He()}catch(Ye){throw It(Ye),Ye}q=ee.data.session?.id??q??"",q&&!Bt&&(0,gt.persistCachedInlineSession)(O,se,q,ee.data.session?.clientSecret)}let m=ee?.data.session;return!Et&&q&&m?.buyerIdentified===!1&&m.clientSecret&&(Et=Vo(kt,q,m.clientSecret,z.account)),{sid:q??"",result:ee,sdkGeneratedIdempotencyKey:Ee,...Bt?{claimed:Bt}:{},...Et?{claim:Et}:{},...x?{claimRequiresIdentity:!0}:{}}}finally{Wt||Oa(me)}}let an=(0,P.useRef)(to);wo(()=>{an.current=to},[to]);let An=(0,P.useCallback)(async(z,O)=>{let se=po.current;if(!se)throw new Ne.FloPayError("createSession is required to bootstrap checkout.","validation_error");let me=ts(se,z),kt=(0,gt.serializeCreateParams)(me),Wt=(0,gt.hashCreateParams)(me),Ve=_i.get(kt);if(!Ve){let Je={canonicalIdentity:kt,promise:an.current(me,Wt,kt),consumers:0,settled:!1};Ve=Je,_i.set(kt,Je);let Ee=()=>{Je.settled=!0,mc(kt,Je)};Je.promise.then(Ee,Ee)}Ve.consumers+=1;let oe=!1,te=()=>{oe||(oe=!0,Ve.consumers-=1,mc(kt,Ve))};O?.(te);try{let Je=await Ve.promise;eo.current=kt,z&&(mt(at),ir(m=>kl(m,z)));let{sid:Ee,result:it,claimed:q,claim:ee,claimRequiresIdentity:Bt}=Je;if(Er.current=ee,Pr(Bt===!0),Rt(it),it.data.session&&rt(it.data.session),Ee&&u(Ee),q){Lr.current+=1;let m=Lr.current;jt.current=q,Qt(!0),q.then(I=>{Lr.current===m&&(jt.current===q&&(jt.current=null),Rt(I),I.data.session&&rt(I.data.session),Qt(!1),Pr(!1))},I=>{Lr.current===m&&(jt.current===q&&(jt.current=null),Qt(!1),Pr(!1),qt(I instanceof Ne.FloPayError?I:new Ne.FloPayError(I instanceof Error?I.message:"Failed to create session","api_error")))})}else Lr.current+=1,jt.current=null,Qt(!1),Pr(!1);let{flopay:Et,paypalFlopay:x}=await ks(it,{billingApiUrl:M,locale:c,telemetry:a}).catch(m=>{throw _l(m,Ee||it.data.session?.id)});return Ht(Et,x),N(!1),Je}catch(Je){throw eo.current===kt&&(eo.current=null),Je}finally{O||te()}},[at,Ht,c,M,a]),sn=(0,P.useRef)(Vn);sn.current=Vn;let Wn=(0,P.useRef)(An);Wn.current=An;let Vt=(0,P.useCallback)(async z=>{if(!mu(z)||Tt)return{sessionId:_t,session:V};Or(!0);try{let O=await An(z);return{sessionId:O.sid,session:O.result.data.session??null}}finally{Or(!1)}},[An,Tt,_t,V]),Xr=(0,P.useCallback)(async z=>{let O=Er.current;if(!O)return;let se=Lr.current,me=await O(z);Lr.current===se&&(Rt(me),me.data.session&&rt(me.data.session))},[]),Jr=(0,P.useCallback)(async()=>{await jt.current},[]),Zr=(0,P.useCallback)(async()=>(await Jr(),{proceed:!0}),[Jr]);(0,P.useEffect)(()=>{let z=!1,O,se=++pe.current;Gt(),qt(null),mr(0);let me=()=>{z=!0,pe.current===se&&(pe.current+=1,Gt())},kt=po.current;if(xn&&kt)return st(yn),N(!1),eo.current===xn?me:(rt(El(kt,Se)),(async()=>{let oe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),te=yn==="auto"&&!vr.current&&!oe;te&&(Xt(null),Jt(null),tr("processing"));let Je=!1;try{let Ee=await Wn.current(void 0,Bt=>{O=Bt});Je=!0;let it=Ee.result.data.session??null;Lt.current=ls(Ee.result);let q=Rs(Ee.result),ee=(0,Nn.wasSessionRecentlyCompleted)(Ee.sid||it?.id);if(!z&&te&&it&&!q&&!ee){vr.current=!0,await su(xn,Ee.sdkGeneratedIdempotencyKey,()=>sn.current(it,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Ee.result.autoProcessingError,initialAutoProcessingPending:Ee.result.autoProcessingPending,autoProcessingAttempted:Ee.result.autoProcessingAttempted,sessionId:Ee.sid||it.id}));return}!z&&te&&((q||ee)&&(vr.current=!0),tr(null),Jt(null))}catch(Ee){if(z)return;let it=ei(Ee);if(te&&it==="session_auto_completed"){vr.current=!0,tr("success"),await Da(600),z||((0,Xe.invokeMerchantCallback)(()=>{on.current?.({status:"succeeded"})}),tr(null),Jt(null));return}if(te&&(tr(null),Jt(null)),!Je){let ee=Tl(Ee),Bt=(0,Ne.toPublicCheckoutInitError)(Ee,ee?{stage:"provider_load",provider:"stripe",...ee}:{stage:"session_request"});(ee||!(Ee instanceof Ne.FloPayError))&&(0,Xe.invokeMerchantCallback)(()=>K.current?.(Bt)),qt(Bt);return}let q=Ee instanceof Ne.FloPayError?Ee:new Ne.FloPayError(Ee instanceof Error?Ee.message:"Failed to create session","api_error");qt(q)}finally{O?.(),O=void 0}})(),()=>{me(),O?.()});N(!0);async function Wt(){let oe=!1,te=!1,Je=null;try{let Ee=new co.PaymentAPI(M,{telemetry:!1}),it=await Ee.getUnifiedCheckoutSession(C,t);if(te=!0,Je=it,z)return;Rt(it);let q=it.data.session??null;if(rt(q),!q)throw new Ne.FloPayError("No session data returned","api_error");let ee=q.checkoutMode;if(ee==="setup")throw new Ne.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(q.status==="authorized"){N(!1),(0,Xe.invokeMerchantCallback)(()=>{on.current?.(no(q,C)),be.current?.(q.successUrl??"")});return}if(q.status==="complete"){N(!1),(0,Xe.invokeMerchantCallback)(()=>{be.current?.(q.successUrl??"")});return}if(q.status==="expired")throw Qa(q);oe=!0;let Bt=Se??ee??"full";st(Bt),Lr.current+=1;let Et=q.clientSecret||t;Er.current=q.buyerIdentified===!1&&Et?Vo(Ee,C,Et,{...q.customer?.id?{userId:q.customer.id}:{}}):void 0,Qt(!1),Pr(!1);let x=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),m=Rs(it);if(Bt==="auto"&&!vr.current&&!x&&!m){vr.current=!0;let I=Ve(it);try{if(await sn.current(q,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>I,sessionId:C||q.id}),z)return;await I,z||N(!1);return}catch{if(z)return;await I,z||N(!1);return}}await Ve(it),z||N(!1)}catch(Ee){if(z)return;let it=Rl(Ee,oe);if(oe&&ot({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),it){let{errorCode:Et,stage:x,...m}=it;ws(M,a,ve,Et,x,m)}if(it?.stage==="provider_load"&&(Se??Je?.data.session?.checkoutMode??"full")==="full"&&wl(Je,B,f)){let Et=cu({billingApiUrl:M,locale:c,telemetry:a});ue.current=Et,Ht(Et,null),mr(1),N(!1);return}let q=it?.stage==="provider_load",ee="session_request";q?ee="provider_load":te&&(ee="post_session");let Bt=(0,Ne.toPublicCheckoutInitError)(Ee,{stage:ee,provider:"stripe",sessionId:C||void 0});(q||!(Ee instanceof Ne.FloPayError))&&(0,Xe.invokeMerchantCallback)(()=>K.current?.(Bt)),qt(Bt),N(!1)}}async function Ve(oe){let{flopay:te,paypalFlopay:Je,...Ee}=await ks(oe,{billingApiUrl:M,locale:c,telemetry:a});Lt.current={publishableKey:Ee.publishableKey,paypalPublishableKey:Ee.paypalPublishableKey},Ht(te,Je),mr(0)}return Wt(),me},[Se,xn,yn,Q,t,B,f]);let fn=(0,P.useCallback)(async()=>{if(!$e||Ar!==1)return;let z=pe.current;mr(2);try{let{flopay:O,paypalFlopay:se}=await ks($e,{billingApiUrl:M,locale:c,telemetry:a});if(pe.current!==z)return;Gt(),Ht(O,se),mr(0)}catch(O){if(pe.current!==z)return;let{errorCode:se,stage:me,...kt}=es(O);ws(M,a,ve,se,me,kt)}},[Gt,Ht,c,Ar,M,a,ve,$e]),yt=!!(C&&(V?.clientSecret||t)),nr=Gr||!yt,Ir=(0,P.useCallback)(async()=>{if(!(Gr||!yt||!V)){Yr(!0),Xt(null);try{await Vn(V,{attempt3DS:!0,fallbackToFull:!0,sessionId:C||V.id})}finally{Yr(!1)}}},[C,Gr,yt,Vn,V]),Wr=(0,Ne.resolveDirectPaypalConfig)($e?.data.paypal,le),_o=Rs($e),gn=(0,P.useMemo)(()=>{if(!(!$e||!V||!$e.data.stripe?.publishableKey))return{billingApiUrl:M}},[$e,V,M]),ro=!!(r&&!j&&ie==="buttons"&&Ue&&yn==="full"),ln=!!(C&&((0,Ne.isMountableVaultBlock)(V?.vault)||(0,Dn.canRecoverHostedCardForm)(V))),Cr=(0,P.useMemo)(()=>({session:V,loading:ce,error:w,checkoutMode:Fr,inlineSessionDraft:lr,applyInlineSessionPatch:ro?Vt:void 0,inlineSessionPatchProcessing:Tt,claimPending:sr,claimRequiresIdentity:zr,claimBuyerIdentity:Xr,waitForDataAttachment:Jr}),[V,ce,w,Fr,lr,ro,Vt,Tt,sr,zr,Xr,Jr]),mo=!!r&&ie==="buttons"&&!_o&&!ln&&(!Ot||!gn),qr=ar?(0,D.jsx)(tn,{status:ar,errorMessage:In,authorized:qn}):null;if(ce&&!ln){if(p)return(0,D.jsxs)(D.Fragment,{children:[p,qr]});if(ie==="buttons"){let z=nt?.buttonsLayout?.cardButton?.borderRadius??nt?.appearance.variables?.borderRadius??8,O=se=>(0,D.jsx)("div",{style:{height:se,borderRadius:z,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[B&&O(ra),f&&(S||Me)&&O(ra),f&&O(ra),(0,D.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),qr]})}return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,D.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,D.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),qr]})}return w?y?(0,D.jsx)(On.Provider,{value:Cr,children:y(w)}):(0,D.jsx)(On.Provider,{value:Cr,children:(0,D.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:w.message})}):mo?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(On.Provider,{value:Cr,children:(0,D.jsx)(fu,{onButtonClick:et,showPayPal:B,showStripe:f,showApplePay:S,showGooglePay:Me,theme:he,buttonsTheme:fe,buttonsStyles:Re,cardButtonContent:ct,cardBackButtonContent:Ke,cardTitleContent:F})}),qr]}):_o&&V&&Wr?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(On.Provider,{value:Cr,children:(0,D.jsxs)("div",{className:Z,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Br&&(0,D.jsx)(Xo,{icon:!1,children:Br}),Ce==="retrying"&&(0,D.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ce==="exhausted"&&(0,D.jsxs)("div",{role:"alert",children:[(0,D.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,D.jsx)("button",{type:"button",onClick:tt,children:"Retry PayPal"})]}),Ce!=="exhausted"&&(0,D.jsx)("div",{"aria-hidden":Ce==="retrying"?!0:void 0,style:Ce==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,D.jsx)(jl,{sessionId:C,nonce:V.clientSecret||void 0,billingApiUrl:M,email:V.customer?.email||lr?.account?.email,billingName:[V.customer?.firstName,V.customer?.lastName].filter(Boolean).join(" ")||[lr?.account?.firstName,lr?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Xr,clientId:Wr.clientId,environment:Wr.environment,currency:(V.currency??"usd").toUpperCase(),isSubscription:V.mode==="subscription",providerObjectType:Wr.providerObjectType,approvalPresentation:Wr.approvalPresentation,existingOrderId:Wr.existingOrderId,onComplete:g,onErrorChange:Xt,onDecline:_,onCancel:H,onButtonClick:et,runBeforeButtonClick:Zr,onInitializationStateChange:Ut,allowAutomaticRetry:_n===0,session:V,telemetry:a,telemetryContext:ve,onInstrument:Oe,debug:A},`${ke}:paypal-init-${_n}`)})]})}),qr]}):Fr==="confirm"?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(On.Provider,{value:Cr,children:(0,D.jsx)(Ra,{flopay:Ot,paypalFlopay:X,options:gn??{billingApiUrl:M},onInstrument:Oe,children:(0,D.jsxs)("div",{className:Z,children:[Br&&(0,D.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Br}),Pe?Pe({onConfirm:Ir,isProcessing:nr}):(0,D.jsx)("button",{type:"button",onClick:Ir,disabled:nr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:nr?"not-allowed":"pointer",opacity:nr?.6:1},children:Gr?"Processing...":xe??"Confirm Purchase"})]})},ke)}),qr]}):(!Ot||!gn)&&!(ln&&Fr==="full")?(0,D.jsx)(D.Fragment,{children:qr}):(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(On.Provider,{value:Cr,children:(0,D.jsxs)(Ra,{flopay:Ot,paypalFlopay:X,options:gn??{billingApiUrl:M},onInstrument:Oe,children:[Ar===1&&(0,D.jsx)("button",{type:"button",onClick:fn,children:"Retry payment methods"}),j?(0,D.jsxs)(D.Fragment,{children:[Br&&(0,D.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Br}),(0,D.jsx)(yu,{sessionId:C,nonce:V?.clientSecret||void 0,billingApiUrl:M,session:V,submitLabel:We,walletPresentation:h,children:j})]}):(0,D.jsx)(ki,{sessionId:C,nonce:V?.clientSecret||void 0,telemetry:a,email:V?.customer?.email||lr?.account?.email,userId:V?.customer?.id||lr?.account?.userId,firstName:V?.customer?.firstName||lr?.account?.firstName,lastName:V?.customer?.lastName||lr?.account?.lastName,totalAmount:V?Math.round((0,Ne.buildCheckoutDisplayData)(V).total*100):0,currency:V?.currency?.toLowerCase()??"usd",onComplete:g,onError:E,onDecline:_,onCancel:H,error:Br,onErrorChange:Xt,showPayPal:B,showStripe:f,walletPresentation:h,enabledPaymentMethods:Ar?[]:ge??$e?.data.stripe?.enabledPaymentMethods??V?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:$e?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:Me,layout:ie,theme:he,buttonsTheme:fe,buttonsStyles:Re,appearance:je,cardButtonContent:ct,cardBackButtonContent:Ke,cardTitleContent:F,onButtonClick:et,onBeforeButtonClick:Ue,onBuyerIdentityReady:Xr,enableAVS:ye,...J?{cardFieldOrder:J}:{},...W===void 0?{}:{cardAutoFocus:W},...Fe?{cardPreFormSlot:Fe}:{},avsLayout:dt,country:V?.customer?.country,city:V?.customer?.city,state:V?.customer?.state,onCountryChange:T,onZipChange:Y,avsCheck:!!ye,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Is(j,ie),className:Z,submitLabel:We,directPaypal:Wr,isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:sr,dataAttachmentRequiresIdentity:zr,debug:A})]},ke)}),qr]})}function yu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,children:c}){return(0,D.jsx)(D.Fragment,{children:P.default.Children.map(c,p=>{if(!P.default.isValidElement(p))return p;let y=p.props,g={};return y.sessionId||(g.sessionId=e),!y.nonce&&t&&(g.nonce=t),y.billingApiUrl||(g.billingApiUrl=r),y.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),y.walletPresentation===void 0&&(g.walletPresentation=s),n?.customer&&(y.email||(g.email=n.customer.email),y.userId||(g.userId=n.customer.id),y.firstName||(g.firstName=n.customer.firstName),y.lastName||(g.lastName=n.customer.lastName)),Object.keys(g).length===0?p:P.default.cloneElement(p,g)})})}function fu({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:s,buttonsTheme:c,buttonsStyles:p,cardButtonContent:y,cardBackButtonContent:g,cardTitleContent:E}){let[R,_]=(0,P.useState)(!1),H=(0,P.useMemo)(()=>(0,Ne.resolveTheme)(s),[s]),T=(0,P.useMemo)(()=>{let h=H?.buttonsLayout??(0,Ne.resolveButtonsLayoutTheme)(c);return p?{...h,...p,cardButton:{...h.cardButton,...p.cardButton},cardFormContainer:{...h.cardFormContainer,...p.cardFormContainer},backButton:{...h.backButton,...p.backButton},backButtonIcon:{...h.backButtonIcon,...p.backButtonIcon},submitButton:{...h.submitButton,...p.submitButton},title:{...h.title,...p.title}}:h},[H,c,p]),Y=H?.buttonsLayout?.cardButton?.borderRadius??H?.appearance.variables?.borderRadius??8,B=h=>(0,D.jsx)("div",{style:{height:h,borderRadius:Y,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),f=y===void 0?{boxSizing:"border-box",height:ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let h=T.cardInputBorder??"#e5e7eb",ge=T.cardInputBackground??"white",S=zo(g),Me=zo(E);return(0,D.jsxs)("div",{style:{backgroundColor:T.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...T.cardFormContainer},children:[(0,D.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,D.jsxs)("button",{type:"button",onClick:()=>_(!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",...T.backButton},children:[(0,D.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...T.backButtonIcon},children:(0,D.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,D.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,D.jsx)(jo,{content:g})]}),Me?(0,D.jsx)("div",{style:{flex:1}}):(0,D.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...T.title},children:(0,D.jsx)(ga,{content:E})})]}),(0,D.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${h}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,D.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,D.jsxs)("div",{style:{display:"flex"},children:[(0,D.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,D.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,D.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:`1px solid ${h}`,borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,D.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,D.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${h}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,D.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,D.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...T.submitButton,opacity:.5}}),(0,D.jsx)("style",{children:`
38
+ `}),pa&&ho&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ce?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:ve,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ee.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ee.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ee.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Vo,{content:Ve})]}),pl?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ee.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...ee.title},children:(0,d.jsx)(ha,{content:me})})]}),!pa&&!pl&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Yi,order:Ce?-3:0,...ee.title},children:(0,d.jsx)(ha,{content:me})}),Ce&&se&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:se}),Ce&&Bt&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:No,border:`1px solid ${fn(Ga)}`,borderRadius:ir,padding:"10px"},children:(0,d.jsx)("input",{ref:re,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:or,onChange:i=>{Nt("email"),Dr.current=i.target.value,on(i.target.value)},onPointerDown:()=>Nt("email"),onKeyDown:()=>Nt("email"),onBlur:()=>{Zr("email")&&lo(!0),xo||Ni()},disabled:Ae,required:!0,"aria-invalid":Ga||void 0,"aria-describedby":Ga?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Xi}})}),Ga&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ya,children:Mo.empty?"Email address is required":"Enter a valid email address"})]}),Le&&(0,d.jsx)("div",{style:{order:Ce?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=ct,b=(G=!1)=>({backgroundColor:No,border:`1px solid ${fn(G)}`,borderRadius:ir,marginTop:"0.5rem",padding:"10px"}),$=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Xi}),_e=(0,l.getStateOptions)(i);return(0,d.jsxs)(d.Fragment,{children:[(0,l.isAVSFieldVisible)(Le.address_line_1,i)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:b(rr("line1")),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Gt,onChange:G=>{Nt("line1"),kr.current.addressLine1=!0,Jt.current=G.target.value,nr(G.target.value)},onPointerDown:()=>Nt("line1"),onKeyDown:()=>Nt("line1"),onBlur:()=>Qr("line1"),disabled:Ae,required:!0,"aria-invalid":rr("line1")||void 0,"aria-describedby":rr("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:$()})}),rr("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ya,children:"Street address is required"})]}),(0,l.isAVSFieldVisible)(Le.address_line_2,i)&&(0,d.jsx)("div",{style:b(),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Qt,onChange:G=>{kr.current.addressLine2=!0,Ur.current=G.target.value,Rn(G.target.value)},disabled:Ae,"data-testid":"flopay-address-line2",style:$()})}),((0,l.isAVSFieldVisible)(Le.city,i)||(0,l.isAVSFieldVisible)(Le.state,i))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Le.city,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:No,borderTop:`1px solid ${fn(rr("city"))}`,borderRight:`1px solid ${fn(rr("city"))}`,borderBottom:`1px solid ${fn(rr("city"))}`,borderLeft:`1px solid ${fn(rr("city"))}`,padding:"10px",borderTopLeftRadius:ir,borderBottomLeftRadius:ir,...(0,l.isAVSFieldVisible)(Le.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ir}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Yt,onChange:G=>{Nt("city"),kr.current.city=!0,hr.current=G.target.value,Nn(G.target.value)},onPointerDown:()=>Nt("city"),onKeyDown:()=>Nt("city"),onBlur:()=>Qr("city"),disabled:Ae,required:!0,"aria-invalid":rr("city")||void 0,"aria-describedby":rr("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:$()})}),(0,l.isAVSFieldVisible)(Le.state,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:No,borderTop:`1px solid ${fn(rr("state"))}`,borderRight:`1px solid ${fn(rr("state"))}`,borderBottom:`1px solid ${fn(rr("state"))}`,borderLeft:`1px solid ${fn(rr("state"))}`,padding:"10px",borderTopRightRadius:ir,borderBottomRightRadius:ir,...(0,l.isAVSFieldVisible)(Le.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${fn(rr("state")||rr("city"))}`}:{borderRadius:ir}},children:_e?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Fr,onChange:G=>{Nt("state"),kr.current.state=!0,Vt.current=G.target.value,Xt(G.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>Qr("state"),disabled:Ae,autoComplete:"billing address-level1",required:!0,"aria-invalid":rr("state")||void 0,"aria-describedby":rr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...$(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,l.getStateLabel)(i)}),_e.map(G=>(0,d.jsx)("option",{value:G.code,children:G.name},G.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,l.getStateLabel)(i),autoComplete:"billing address-level1",value:Fr,onChange:G=>{Nt("state"),kr.current.state=!0,Vt.current=G.target.value,Xt(G.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>Qr("state"),disabled:Ae,required:!0,"aria-invalid":rr("state")||void 0,"aria-describedby":rr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:$()})})]}),rr("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ya,children:"City is required"}),rr("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ya,children:[(0,l.getStateLabel)(i)," is required"]}),((0,l.isAVSFieldVisible)(Le.country,i)||(0,l.isAVSFieldVisible)(Le.postal_code,i))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:O==="column"?"column":"row",gap:O==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Le.country,i)&&(0,d.jsx)("div",{style:{flex:O==="row"?1:void 0,backgroundColor:No,borderTop:`1px solid ${ma}`,borderRight:`1px solid ${ma}`,borderBottom:`1px solid ${ma}`,borderLeft:`1px solid ${ma}`,padding:"10px",...O==="row"&&(0,l.isAVSFieldVisible)(Le.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:ir,borderBottomLeftRadius:ir,borderRight:"none"}:{borderRadius:ir}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:ct,onChange:G=>{kr.current.country=!0,ar.current=G.target.value,Gr(G.target.value),Ke?.(G.target.value),Vt.current="",Xt("")},disabled:Ae,autoComplete:"billing country","data-testid":"flopay-country",style:{...$(),cursor:"pointer"},children:[ct===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,l.COUNTRY_OPTIONS.map(G=>(0,d.jsxs)("option",{value:G.code,children:[G.flag," ",G.name]},G.code))]})}),(0,l.isAVSFieldVisible)(Le.postal_code,i)&&(0,d.jsx)("div",{style:{flex:O==="row"?1:void 0,backgroundColor:No,border:`1px solid ${Kc}`,padding:"10px",...O==="row"&&(0,l.isAVSFieldVisible)(Le.country,i)?{borderRadius:"0",borderTopRightRadius:ir,borderBottomRightRadius:ir}:{borderRadius:ir}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,l.getPostalCodeLabel)(ct),autoComplete:"billing postal-code",value:Yr,onChange:G=>{Nt("zip"),kr.current.zip=!0,Br.current=G.target.value,Ar(G.target.value),yt?.(G.target.value)},onPointerDown:()=>Nt("zip"),onKeyDown:()=>Nt("zip"),onBlur:()=>{Zr("zip")&&Zn(!0)},disabled:Ae,required:Ye.required,"aria-invalid":Ya||void 0,"aria-describedby":Ya?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:$()})})]}),Ya&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ya,children:Ye.empty?`${(0,l.getPostalCodeLabel)(i)} is required`:eu(i)})]})})()}),Ce&&Zc,ye&&(0,d.jsx)(Jo,{margin:"0.75rem 0",styleOverride:ee.errorBanner,children:ye})]}),Xa={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"},hl=i=>V?!ge||!jn?(0,d.jsx)("pre",{"data-testid":i,style:Xa,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Xa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ge}`,` directPaypalConfigured=${jn}`,` inAppBrowserDetected=${String($a)}`,` shouldRenderDirectPayPal=${sa}`,` shouldRenderStripePayPal=${ca}`,` hasPaypalStripeInstance=${!!Fs}`].join(`
39
+ `)}):null,Pl=i=>V?!w||!un?(0,d.jsx)("pre",{"data-testid":i,style:Xa,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Xa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${w}`,` currency=${qt}`,` amountInCents=${aa}`,` enabledPaymentMethods: ${JSON.stringify(x??[])}`,` enabledPaymentMethodsProvided=${ia}`,` hasEnabledMethods=${qa}`,` expressMethods: ${JSON.stringify(Va)}`,` walletExpressMethods: ${JSON.stringify(Oo)}`,` paymentElementMethods: ${JSON.stringify(zi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Wa)}`,` hasStripeInstance=${!!un}`,` shouldRenderWallets=${Lo}`,` shouldRenderPaymentElement=${da}`].join(`
40
+ `)}):null,vl=st==="apm-expanding"||st==="apm-form"||st==="apm-collapsing",zo;st==="apm-expanding"?zo=rc:st==="apm-collapsing"&&(zo=nc);let Ja=vr?pc(qi,vr,Tt):null;if(ke==="buttons"){let i=st==="buttons"||st==="expanding"||st==="apm-expanding",b=st==="expanding"||st==="card"||st==="collapsing",$=tt===void 0?{boxSizing:"border-box",height:ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"},_e;st==="expanding"||st==="apm-expanding"?_e=Xd:(st==="collapsing"||st==="apm-collapsing")&&(_e=Yd);let G;return st==="expanding"?G=rc:st==="collapsing"&&(G=nc),(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ra,{}),ze&&(0,d.jsx)(rn,{status:ze,errorMessage:ye,authorized:Xr}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!_e?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!_e?Zd:{},..._e?{animation:_e,pointerEvents:"none"}:{}},children:[hl("flopay-direct-paypal-gate-debug"),Pl("flopay-stripe-gate-debug"),sa&&de&&(0,d.jsxs)(d.Fragment,{children:[Ne&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(ba.Provider,{value:oe,children:(0,d.jsx)(wa,{sessionId:e,nonce:t,billingApiUrl:k,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,clientId:de.clientId,environment:de.environment,currency:qt.toUpperCase(),isSubscription:ue,providerObjectType:u,approvalPresentation:Ha==="popup"?void 0:Ha,onTokenizedBody:en,onComplete:c,onErrorChange:We,onDecline:m,onCancel:g,onTechnicalFailure:Bo,onButtonClick:W,runBeforeButtonClick:xn,isProcessing:Ae,onLoadStateChange:ji,onInitializationStateChange:Vi,session:Oe,existingOrderId:Ne?.orderId,debug:V},Ne?.orderId??"fresh")})]}),ca&&(0,d.jsx)(sr.Elements,{stripe:la,options:Os,children:(0,d.jsx)(ac,{sessionId:e,nonce:t,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,billingApiUrl:k,onTokenizedBody:en,onErrorChange:We,isProcessing:Ae,onButtonClick:W,onDecline:m,onTechnicalFailure:Bo,runBeforeButtonClick:xn,onLoadStateChange:Ys,placeholderBorderRadius:vo,popupCapabilityOwner:oe,externalTelemetryContext:ol,presentationMode:Do})}),Lo?(0,d.jsx)(sr.Elements,{stripe:un,options:Ds,children:(0,d.jsx)(ic,{sessionId:e,nonce:t,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,billingApiUrl:k,intentKind:Ut>0?"payment":"setup",expressMethods:Oo,onTokenizedBody:en,onErrorChange:We,onButtonClick:W,onDecline:m,onTechnicalFailure:Bo,runBeforeButtonClick:xn,onLoadStateChange:Js,placeholderBorderRadius:vo,popupCapabilityOwner:oe,externalTelemetryContext:De})}):null,!Lo&&rl?(0,d.jsx)("div",{style:{height:ta,borderRadius:vo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,da&&(0,d.jsx)(sc,{sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:je,billingApiUrl:k,paymentElementMethods:Wa,stripeInstance:un,paymentElementBaseOptions:qi,futureUseSession:Tt,onTokenizedBody:en,onErrorChange:We,onButtonClick:W,onDecline:m,runBeforeButtonClick:xn,onLoadStateChange:Qs,isProcessing:Ae,submitButtonColor:Co,submitButtonBorderRadius:ir,submitButtonStyle:ee.submitButton,onExpandApm:xt,expandedApmMethod:vr,themeId:mt,buttonAppearance:{backgroundColor:ee.cardButton?.backgroundColor,borderColor:ee.cardInputBorder,textColor:ee.cardButton?.color,borderRadius:vo}}),Ce&&(0,d.jsx)("button",{type:"button",onClick:async()=>{Ae||!(await xn("card")).proceed||(W?.("card"),ce())},disabled:Ae,style:{width:"100%",...$,...ee.cardButton,...bs({themeBundle:tr,resolvedPrimaryColor:Co,resolvedBorderRadius:ir,submitButtonStyle:ee.submitButton,explicitPrimaryColor:tn?.colorPrimary}),fontSize:ee.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ae?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Ae?.6:1},onMouseEnter:Ie=>{!Ae&&(tr||tn?.colorPrimary)&&(Ie.currentTarget.style.backgroundColor=Xc)},onMouseLeave:Ie=>{(tr||tn?.colorPrimary)&&(Ie.currentTarget.style.backgroundColor=Co)},onMouseDown:Ie=>{Ie.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ie=>{Ie.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(jo,{content:tt})}),ye&&st==="buttons"&&(0,d.jsx)(Jo,{margin:"0.25rem 0",styleOverride:ee.errorBanner,children:ye})]}),Ce&&b&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...G?{animation:G}:{},...st==="collapsing"?{pointerEvents:"none"}:{}},children:gl}),w&&vl&&vr&&Ja&&un&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...zo?{animation:zo}:{},...st==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ki,borderRadius:Zi,...fa,padding:Ji},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:zt,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ee.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ee.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ee.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Vo,{content:Ve})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ee.titleFontSize??"1.05rem",color:Yi,paddingRight:80,...ee.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(vr)}`})]}),(0,d.jsx)(sr.Elements,{stripe:un,options:Ja,children:(0,d.jsx)(Ps,{method:vr,sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:je,billingApiUrl:k,onTokenizedBody:en,onErrorChange:We,onDecline:m,onCancel:zt,runBeforeButtonClick:xn,onButtonClick:W,isProcessing:Ae,submitButtonColor:Co,submitButtonBorderRadius:ir,submitButtonStyle:ee.submitButton,errorText:ye})},vr)]})})]})]})}return vl&&vr&&Ja&&un&&w?(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ra,{}),ze&&(0,d.jsx)(rn,{status:ze,errorMessage:ye,authorized:Xr}),(0,d.jsx)("div",{style:{...zo?{animation:zo}:{},...st==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ki,borderRadius:Zi,...fa,padding:Ji},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:zt,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ee.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ee.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ee.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Vo,{content:Ve})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ee.titleFontSize??"1.05rem",color:Yi,paddingRight:80,...ee.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(vr)}`})]}),(0,d.jsx)(sr.Elements,{stripe:un,options:Ja,children:(0,d.jsx)(Ps,{method:vr,sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:je,billingApiUrl:k,onTokenizedBody:en,onErrorChange:We,onDecline:m,onCancel:zt,runBeforeButtonClick:xn,onButtonClick:W,isProcessing:Ae,submitButtonColor:Co,submitButtonBorderRadius:ir,submitButtonStyle:ee.submitButton,errorText:ye})},vr)]})})]}):(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ra,{}),ze&&(0,d.jsx)(rn,{status:ze,errorMessage:ye,authorized:Xr}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[hl("flopay-direct-paypal-gate-debug-default"),Pl("flopay-stripe-gate-debug-default"),sa&&de&&(0,d.jsxs)(d.Fragment,{children:[Ne&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(ba.Provider,{value:oe,children:(0,d.jsx)(wa,{sessionId:e,nonce:t,billingApiUrl:k,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,clientId:de.clientId,environment:de.environment,currency:qt.toUpperCase(),isSubscription:ue,providerObjectType:u,approvalPresentation:Ha==="popup"?void 0:Ha,onTokenizedBody:en,onComplete:c,onErrorChange:We,onDecline:m,onCancel:g,onTechnicalFailure:Bo,onButtonClick:W,runBeforeButtonClick:xn,isProcessing:Ae,onLoadStateChange:ji,onInitializationStateChange:Vi,session:Oe,existingOrderId:Ne?.orderId,debug:V},Ne?.orderId??"fresh")})]}),ca&&(0,d.jsx)(sr.Elements,{stripe:la,options:Os,children:(0,d.jsx)(ac,{sessionId:e,nonce:t,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,billingApiUrl:k,onTokenizedBody:en,onErrorChange:We,isProcessing:Ae,onButtonClick:W,onDecline:m,onTechnicalFailure:Bo,runBeforeButtonClick:xn,onLoadStateChange:Ys,placeholderBorderRadius:vo,popupCapabilityOwner:oe,externalTelemetryContext:ol,presentationMode:Do})}),Lo&&(0,d.jsx)(sr.Elements,{stripe:un,options:Ds,children:(0,d.jsx)(ic,{sessionId:e,nonce:t,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,billingApiUrl:k,intentKind:Ut>0?"payment":"setup",expressMethods:Oo,onTokenizedBody:en,onErrorChange:We,onButtonClick:W,onDecline:m,onTechnicalFailure:Bo,runBeforeButtonClick:xn,onLoadStateChange:Js,placeholderBorderRadius:vo,popupCapabilityOwner:oe,externalTelemetryContext:De})}),da&&(0,d.jsx)(sc,{sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:k,paymentElementMethods:Wa,stripeInstance:un,paymentElementBaseOptions:qi,futureUseSession:Tt,onTokenizedBody:en,onErrorChange:We,onButtonClick:W,onDecline:m,runBeforeButtonClick:xn,onLoadStateChange:Qs,isProcessing:Ae,submitButtonColor:Co,submitButtonBorderRadius:ir,submitButtonStyle:ee.submitButton,themeId:mt,onExpandApm:xt,expandedApmMethod:vr,buttonAppearance:{backgroundColor:ee.cardButton?.backgroundColor,borderColor:ee.cardInputBorder,textColor:ee.cardButton?.color,borderRadius:vo}})]}),Ce&&(Vc||jc||Wc)&&(0,d.jsx)(Ci,{label:"or pay with card"}),Ce&&gl]})}var B=require("react/jsx-runtime"),na=44,Is="flopay_checkout_saved_payment_resume",Ti=new Map,_i=new Map;function mc(e,t){t.settled&&t.consumers===0&&Ti.get(e)===t&&Ti.delete(e)}function su(e,t,r){let n=_i.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};_i.set(e,s);let c=()=>{_i.get(e)===s&&_i.delete(e)};return a.then(c,c),a}function Oa(e){return new Promise(t=>setTimeout(t,e))}function Ii(e,t,r){let n=li({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ue.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function La(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ws(e,t,r,n,a,s){let c=Ii(e,t,r);c.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),La(c)}function yc(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 fc(e,t,r,n,a){let s=(0,Ue.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 Ue.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Ue.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 ks(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,Ue.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var lu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function cu(e){return new io.FloPay(lu,{publishableKey:"provider_unavailable",...e})}async function Rs(e,t){let{publishableKey:r,paypalPublishableKey:n}=ls(e);return{...await cs({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Ts(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function du(){if(!Ts())return null;try{let e=window.sessionStorage.getItem(Is);return e?JSON.parse(e):null}catch{return null}}function gc(e){if(Ts())try{window.sessionStorage.setItem(Is,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Es(){if(Ts())try{window.sessionStorage.removeItem(Is)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function uu(){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 hc(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 _s(e,t){return(0,Ue.resolveCheckoutLogLayout)(!!e,t)}function pu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Pc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function mu(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 Mi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:c,loading:p,error:m,onComplete:g,onError:_,onInstrument:E,onDecline:I,onCancel:H,onCountryChange:T,onZipChange:Y,showPayPal:F=!0,showStripe:y=!0,walletPresentation:h="auto",enabledPaymentMethods:ge,showApplePay:w=!0,showGooglePay:Te=!0,debug:x=!1,layout:ie,theme:he,buttonsTheme:fe,buttonsStyles:ke,cardButtonContent:mt,cardBackButtonContent:Je,cardTitleContent:A,showSecurityFooter:kt,onButtonClick:tt,onBeforeButtonClick:Ve,enableAVS:me,cardFieldOrder:K,cardAutoFocus:W,cardPreFormSlot:Fe,avsLayout:lt,submitLabel:He,className:J,initialErrorMessage:D=null,initialPayPalOrderId:se,children:O,checkoutMode:be,confirmLabel:Me,renderConfirmButton:Pe,onSessionCompleted:Be}){let M=(0,Ue.resolveBillingApiUrl)(n),at=(0,P.useMemo)(()=>(0,Ue.resolveTheme)(he),[he]),Ke=s??at?.appearance,yt=r?"embedded_checkout":"standard_checkout",Ze=_s(O,ie),[Ge,_t]=(0,P.useState)(null),[Ut,qt]=(0,P.useState)(null),Ft=(0,P.useRef)(null),de=(0,P.useRef)(null),ue=(0,P.useRef)(0),[X,bt]=(0,P.useState)(null),ft=(0,P.useRef)(null),[V,rt]=(0,P.useState)(null),Rt=(0,P.useMemo)(()=>r?(0,vt.serializeCreateParams)(r):"",[r]),Re=r?`create:${Rt}`:`session:${e??""}`,v=Pc(V),q=(0,P.useRef)(new Set),oe=(0,P.useRef)(Re),xe=(0,P.useRef)(Re);ko(()=>{xe.current=Re,oe.current!==Re&&(oe.current=Re,q.current.clear())},[Re]);let Lt=(0,P.useCallback)(U=>{if(xe.current===Re){if(as.FLO_INSTRUMENT_ONCE_NAMES.has(U.name)){if(q.current.has(U.name))return;q.current.add(U.name)}(0,Qe.invokeMerchantCallback)(()=>E?.(U))}},[Re,E]),it=Xo(Lt,Re),De=(0,P.useRef)(!1),Oe=(0,P.useCallback)(U=>{if(De.current)return;let z=U.gateway||!v?U:{...U,gateway:v};Lt(z)},[Lt,v]);(0,P.useEffect)(()=>{it({class:"lifecycle",name:"checkout.mount"})},[it]);let[Tt,u]=(0,P.useState)(e??""),C=e??Tt,Q=r?"":C,[le,L]=(0,P.useState)(!0),[k,jt]=(0,P.useState)(null),[Mr,dr]=(0,P.useState)(0),[xr,ct]=(0,P.useState)("full"),[Gr,Yr]=(0,P.useState)(!1),[Ar,Gt]=(0,P.useState)(D),[nr,Qt]=(0,P.useState)(null),[Rn,Yt]=(0,P.useState)(null),[Nn,Fr]=(0,P.useState)(!1),[Xt,or]=(0,P.useState)(void 0),[on,gt]=(0,P.useState)(""),[Mt,Br]=(0,P.useState)(!1),[ar,Jt]=(0,P.useState)(!1),[Ur,hr]=(0,P.useState)(!1),Vt=(0,P.useRef)(null),Dr=(0,P.useRef)(0),kr=(0,P.useRef)(void 0),[Le,Or]=(0,P.useState)("loading"),[Xr,Xn]=(0,P.useState)(0),Pr=(0,P.useRef)(!1),an=(0,P.useRef)(!1),sn=(0,P.useRef)(!1),En=(0,P.useRef)(null),Wt=(0,P.useRef)(null),Ce=(0,P.useMemo)(()=>({checkoutMode:be??xr,layout:pu(O,ie)}),[be,O,xr,ie]),ln=(0,P.useRef)(g);ln.current=g;let zr=(0,P.useRef)(_);zr.current=_;let _n=(0,P.useRef)(I);_n.current=I;let N=(0,P.useCallback)(U=>ui(En,async z=>{try{return await U(z)}catch(ce){throw z.aborted?Zo(ce):ce}}),[]);(0,P.useEffect)(()=>()=>{En.current?.abort(),En.current=null},[]);let dt=(0,P.useCallback)((U,z)=>{Ft.current=U,qt(U),ft.current=z,bt(z)},[]),te=(0,P.useCallback)(()=>{let U=de.current;U&&(de.current=null,U.destroy())},[]);(0,P.useEffect)(()=>{Sr(Ut)?.setCheckoutContext(Ce),X&&X!==Ut&&Sr(X)?.setCheckoutContext(Ce)},[Ut,X,Ce]);let Se=(0,P.useRef)(Be);Se.current=Be;let Dt=(0,P.useCallback)(U=>{Or(U),!(U!=="exhausted"||sn.current)&&(sn.current=!0,zr.current?.(new Ue.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),$t=(0,P.useCallback)(()=>{Or("retrying"),Xn(U=>U+1)},[]);(0,P.useEffect)(()=>{Or("loading"),Xn(0),sn.current=!1},[C]),(0,P.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ue.SDK_VERSION,checkout_type:yt,checkout_layout:Ze,billing_api_url:M})},[Ze,yt,M]);let nt=(0,P.useMemo)(()=>r?(0,vt.serializeCreateParams)(r,!0):"",[r]),Ye=(0,P.useMemo)(()=>on===nt?Xt:void 0,[Xt,on,nt]),Jr=(0,P.useMemo)(()=>r?ts(r,Ye):void 0,[r,Ye]),Un=be??Jr?.checkoutMode??"full",er=(0,P.useMemo)(()=>Jr?{...Jr,checkoutMode:Un}:void 0,[Jr,Un]);(0,P.useEffect)(()=>{or(void 0),gt(nt),kr.current=void 0,Vt.current=null,hr(!1)},[nt]),(0,P.useEffect)(()=>{Gt(D)},[D]);let In=(0,P.useCallback)((U,z,ce)=>{(0,Qe.invokeMerchantCallback)(()=>{_n.current?.(br(U,z,ce))})},[]),Jn=(0,P.useCallback)(async(U,z)=>{Gt(null),Yt(null),Fr(!1),Qt("processing");let ce=z?.sessionId??U.id,ve=U.clientSecret||t,xt=Pc(U),zt=Ft.current??ft.current,ze=Sr(zt),Z=zt?null:Ii(M,a,Ce),re={log:Ne=>{ze?ze.log(Ne):Z?.log(Ne)},error:Ne=>{ze?ze.error(Ne):Z?.error(Ne)},terminal:Ne=>{ze?ze.terminal(Ne):Z?.terminal(Ne)},performance:Ne=>{ze?ze.performance(Ne):Z?.performance(Ne)},now:()=>ze?.now()??Z?.now()??0,elapsed:Ne=>ze?.elapsed(Ne)??Math.max(0,(Z?.now()??Ne)-Ne)},Xe=re.now(),Ee=!!(z?.initialAutoProcessingError||z?.initialAutoProcessingPending),ut=!1,j,pe=()=>{ut||(ut=!0,Ee=!0,j=re.now(),re.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ot=!1,ot=()=>{Ot||(Ot=!0,re.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),re.performance({stage:"processing",durationMs:re.elapsed(Xe),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),j!==void 0&&re.performance({stage:"recovery",durationMs:re.elapsed(j),durationMode:"machine",paymentMethodCategory:"saved"}))};re.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),De.current=!0;try{re.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{De.current=!1}it({class:"lifecycle",name:"payment.processing.started",provider:xt}),Ee&&pe();let pr;try{let Ne=Hl(z?.initialAutoProcessingError),f=z?.initialAutoProcessingError?.type==="3ds_required"&&!z.initialAutoProcessingError.threeDSecureToken&&z.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:z.initialAutoProcessingError.nextActionRedirectUrl}:null,S,ne=qe=>{pe();let je=Ia(M,ce,U,a!==!1);return N(ye=>Qo(qe,{billingApiUrl:M,sessionId:ce,nonce:ve,session:U,signal:ye,...je.telemetry?{challengeTelemetry:je.telemetry}:{}})).finally(je.release)};if(f)S=await ne(f);else if(Ne)pe(),Ne.type==="paypal_redirect_required"&&Wt.current?.publishableKey&&gc({sessionId:ce,publishableKey:Wt.current.publishableKey,paypalPublishableKey:Wt.current.paypalPublishableKey}),S=await N(qe=>mi(Ne,{flopay:Ft.current,paypalFlopay:ft.current,attempt3DS:z?.attempt3DS,billingApiUrl:M,sessionId:ce,session:U,telemetry:!1,signal:qe})),Ne.type==="paypal_redirect_required"&&Es();else if(z?.initialAutoProcessingPending){let qe=z.initialAutoProcessingPending,je=new io.PaymentAPI(M,{telemetry:!1}),ye=await N(Cr=>je.waitForCheckoutSessionCompletion(qe.sessionId,{initialDelayMs:qe.retryAfterMs,nonce:ve,statusUrl:qe.statusUrl,signal:Cr})),tr=yo(ye,U),ee=ye.autoProcessingError?.type==="3ds_required"&&ye.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ye.autoProcessingError.nextActionRedirectUrl}:null;if(ee)S=await ne(ee);else{if(!to(tr))throw $o(tr);S=eo(tr,ce)}}else{if(z?.initialAutoProcessingError)throw Hn(z.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:z.initialAutoProcessingError.checkoutMethod});if(z?.fromCreateSession)return z?.fallbackToFull&&(ct("full"),hc("full")),!1;{let qe=await ea({billingApiUrl:M,sessionId:ce,session:U,nonce:ve,telemetry:!1});qe.type==="success"?S=qe.result:qe.type==="next_action_required"?S=await ne(qe):(pe(),qe.type==="paypal_redirect_required"&&Wt.current?.publishableKey&&gc({sessionId:ce,publishableKey:Wt.current.publishableKey,paypalPublishableKey:Wt.current.paypalPublishableKey}),S=await N(je=>mi(qe,{flopay:Ft.current,paypalFlopay:ft.current,attempt3DS:z?.attempt3DS,billingApiUrl:M,sessionId:ce,session:U,telemetry:!1,signal:je})),qe.type==="paypal_redirect_required"&&Es())}}ce&&(0,Dn.markSessionRecentlyCompleted)(ce),ot(),Ee&&(re.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),re.terminal({outcome:S.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Fr(S.status==="authorized"),Qt("success"),await Oa(600),pr=()=>ln.current?.(S)}catch(Ne){let f=mo(Ta(Ne),ce);if(f.code==="three_ds_aborted")return!1;let S=f.checkoutMethod??_a;Gt(f.message),Yt(f.message),Fr(!1),z?.fallbackToFull&&(re.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),ct("full"),hc("full")),ot();let ne=f.statusCode===void 0?void 0:(0,Ue.telemetryStatusClass)(f.statusCode,"unknown"),qe=ne==="4xx"?{requestCategory:"process_payment",statusClass:ne}:{},je=ne===void 0||ne==="4xx";if(je&&(f.telemetryOutcome==="payment_declined"||!!(f.declineCode||f.code?.toLowerCase().includes("declin"))))re.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...qe});else if(je&&(f.telemetryOutcome==="validation_rejected"||f.type==="validation_error"))re.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...qe});else{let ee=(0,Ue.classifyTelemetryFailure)(Ne,Ee?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Cr=f.telemetryRequestCategory??"process_payment";De.current=!0;try{re.error({...ee,...f.telemetryFailureCategory?{failureCategory:f.telemetryFailureCategory}:{},stage:Ee?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Cr})}finally{De.current=!1}it({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Cr,provider:xt})}return(0,Qe.invokeMerchantCallback)(()=>zr.current?.(f)),In(S,f,{code:f.code,declineCode:f.declineCode}),Qt("error"),await Promise.allSettled([Oa(400),z?.ensureProvidersReady?z.ensureProvidersReady():Promise.resolve()]),Ee&&(re.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{ot(),Z&&La(Z),Qt(null),Yt(null)}return(0,Qe.invokeMerchantCallback)(pr),!0},[In,it,t,M,N,a,Ce]);(0,P.useEffect)(()=>{if(typeof window>"u"||an.current)return;let U=new URLSearchParams(window.location.search),z=U.get("payment_intent_client_secret");if(!z)return;let ce=du();ce&&(an.current=!0,(async()=>{let ve,xt=0;Gt(null),Yt(null),Qt("processing"),Yr(!0);try{if(U.get("redirect_status")==="failed")throw Object.assign(new Ue.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:zt,paypalFlopay:ze}=await cs({publishableKey:ce.publishableKey,paypalPublishableKey:ce.paypalPublishableKey,billingApiUrl:M,locale:c,telemetry:a});ve=Sr(ze??zt),ve?.setCheckoutContext(Ce),xt=ve?.now()??0,ve?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Z=(ze??zt)?.getRawProvider();if(!Z)throw Object.assign(new Ue.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:re,error:Xe}=await Z.retrievePaymentIntent(z);if(Xe)throw Object.assign(new Ue.FloPayError(Xe.message??"Failed to retrieve PayPal payment status.","api_error",{code:Xe.code}),{checkoutMethod:"paypal"});let Ee=xl(re?.status);if(!re||Ee==="failed")throw Object.assign(new Ue.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let ut=typeof re.payment_method=="string"?re.payment_method:re.payment_method?.id,j=Ee;if(ce.sessionId){let ot=(await new io.PaymentAPI(M,{telemetry:!1}).getUnifiedCheckoutSession(ce.sessionId)).data.session;if(ot&&ot.status!=="complete"){let pr=await ea({billingApiUrl:M,sessionId:ce.sessionId,session:ot,telemetry:!1,tokenizedData:{id:ut??re.id,type:"card",threeDSecureActionResultTokenId:re.id,isPaypal:!0}});if(pr.type!=="success")throw Object.assign(new Ue.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});j=pr.result.status}}ce.sessionId&&(0,Dn.markSessionRecentlyCompleted)(ce.sessionId),ve?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.performance({stage:"redirect_resume",durationMs:ve.elapsed(xt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Qt("success"),await Oa(600),(0,Qe.invokeMerchantCallback)(()=>ln.current?.({status:j,paymentIntentId:re.id,paymentMethodId:ut,checkoutMethod:"paypal"}))}catch(zt){let ze=mo(Ta(zt),ce.sessionId),Z=ze.checkoutMethod??"paypal",re=!!(ze.declineCode||ze.code?.toLowerCase().includes("declin"));if(ve)ve.performance({stage:"redirect_resume",durationMs:ve.elapsed(xt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),re?ve.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ve.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(re){let Xe=Ii(M,a,Ce);Xe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),La(Xe)}else ws(M,a,Ce,"REDIRECT_RESUME_FAILED","redirect_resume");Gt(ze.message),Yt(ze.message),(0,Qe.invokeMerchantCallback)(()=>zr.current?.(ze)),In(Z,ze,{code:ze.code,declineCode:ze.declineCode}),Qt("error"),await Oa(400)}finally{Es(),uu(),Qt(null),Yt(null),Yr(!1)}})())},[In,c,M,a,Ce]);let Zn=(0,P.useRef)(null),Tn=(0,P.useMemo)(()=>er?(0,vt.serializeCreateParams)(er):"",[er]),lo=(0,P.useRef)(er);lo.current=er,(0,P.useEffect)(()=>{u(e??"")},[e]),(0,P.useEffect)(()=>{Pr.current=!1,Gt(D),Yt(null),Fr(!1),Qt(null)},[Tn,D,e]);async function Qn(U,z,ce){let ve=Ii(M,a,Ce),xt=new io.PaymentAPI(M,{telemetry:!1}),zt=!1;try{let ze=U.idempotencyKey===void 0?void 0:(0,Ue.resolveIdempotencyKey)(U.idempotencyKey),Z=(0,vt.readCachedInlineSession)(z,ce),re=(0,vt.readCachedInlineIdempotencyKey)(z,ce);Z?.canonicalIdentity===ce&&re&&re.canonicalIdentity===void 0&&((0,vt.persistCachedInlineIdempotencyKey)(z,ce,re.idempotencyKey),re={...re,canonicalIdentity:ce});let Xe=ze??(re?.canonicalIdentity===ce?re.idempotencyKey:void 0),Ee,ut=!1;ve.log({name:Z?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let j=Z?.sid??null,pe=null,Ot,ot,pr=!1;if(j)try{pe=await xt.getUnifiedCheckoutSession(j,Z?.nonce),Z&&Z.canonicalIdentity===void 0&&((0,vt.legacyCachedSessionMatchesDraft)(pe.data.session,U)?((0,vt.persistCachedInlineSession)(z,ce,j,Z.nonce??pe.data.session?.clientSecret),re&&re.canonicalIdentity===void 0&&((0,vt.persistCachedInlineIdempotencyKey)(z,ce,re.idempotencyKey),Xe??(Xe=re.idempotencyKey))):((0,vt.clearCachedInlineCheckout)(z,ce),re=null,Xe=ze,j=null,pe=null));let f=pe?.data.session?.status,S=pe?.data.session,ne=S?.clientSecret||Z?.nonce;if(j&&S?.buyerIdentified===!1&&ne&&(ot=Wo(xt,j,ne,U.account)),j&&pe&&f==="complete"){if((0,Dn.wasSessionRecentlyCompleted)(j))return{sid:j,result:pe};(0,vt.clearCachedInlineCheckout)(z,ce),j=null,pe=null,ut=!0}}catch{ve.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Z?.canonicalIdentity===void 0?((0,vt.clearCachedInlineCheckout)(z,ce),Xe=ze):(0,vt.clearCachedInlineSession)(z,ce),j=null}if(!j){!ze&&(ut||!Xe)&&(Xe=(0,Ue.resolveIdempotencyKey)(),Ee=Xe),Xe&&(0,vt.persistCachedInlineIdempotencyKey)(z,ce,Xe);let f=ve.now(),S=0;ve.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ne={...U,idempotencyKey:Xe,avsCheck:!!me,avsConfig:typeof me=="object"?me:void 0,checkoutType:"embedded_checkout",checkoutLayout:_s(O,ie)};Object.defineProperty(ne,io.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ye=>{S=Math.max(S,ye)}}});let qe=()=>{yc(ve,"session_create",f,S)},je=ye=>{fc(ve,ye,"session_create",f,S)&&it({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Ue.isDetachedSessionEligible)(ne)){let ye=await xt.createDetachedSession(ne);ye.claimed.catch(()=>{}),pe=ye.shell,j=ye.sessionId,ot=ye.claim;let tr=ve.now();ve.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Ot=ye.claimed.then(ee=>{let Cr=ee.data.session?.id??ye.sessionId;return Cr&&(0,vt.persistCachedInlineSession)(z,ce,Cr,ee.data.session?.clientSecret??ye.nonce),yc(ve,"session_claim",tr),qe(),ee},ee=>{throw(0,vt.clearCachedInlineSession)(z,ce),fc(ve,ee,"session_claim",tr,0)&&it({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),ee}).finally(()=>La(ve)),Ot.catch(()=>{}),zt=!0,ve.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ve.performance({stage:"session_shell",durationMs:ve.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:S,statusClass:"2xx",paymentMethodCategory:"card"})}else pe=await xt.createAndFetchSession(ne),qe()}catch(ye){throw je(ye),ye}j=pe.data.session?.id??j??"",j&&!Ot&&(0,vt.persistCachedInlineSession)(z,ce,j,pe.data.session?.clientSecret)}let Ne=pe?.data.session;return!ot&&j&&Ne?.buyerIdentified===!1&&Ne.clientSecret&&(ot=Wo(xt,j,Ne.clientSecret,U.account)),{sid:j??"",result:pe,sdkGeneratedIdempotencyKey:Ee,...Ot?{claimed:Ot}:{},...ot?{claim:ot}:{},...pr?{claimRequiresIdentity:!0}:{}}}finally{zt||La(ve)}}let go=(0,P.useRef)(Qn);ko(()=>{go.current=Qn},[Qn]);let yn=(0,P.useCallback)(async(U,z)=>{let ce=lo.current;if(!ce)throw new Ue.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ve=ts(ce,U),xt=(0,vt.serializeCreateParams)(ve),zt=(0,vt.hashCreateParams)(ve),ze=Ti.get(xt);if(!ze){let Xe={canonicalIdentity:xt,promise:go.current(ve,zt,xt),consumers:0,settled:!1};ze=Xe,Ti.set(xt,Xe);let Ee=()=>{Xe.settled=!0,mc(xt,Xe)};Xe.promise.then(Ee,Ee)}ze.consumers+=1;let Z=!1,re=()=>{Z||(Z=!0,ze.consumers-=1,mc(xt,ze))};z?.(re);try{let Xe=await ze.promise;Zn.current=xt,U&&(gt(nt),or(Ne=>Rl(Ne,U)));let{sid:Ee,result:ut,claimed:j,claim:pe,claimRequiresIdentity:Ot}=Xe;if(kr.current=pe,hr(Ot===!0),_t(ut),ut.data.session&&rt(ut.data.session),Ee&&u(Ee),j){Dr.current+=1;let Ne=Dr.current;Vt.current=j,Jt(!0),j.then(f=>{Dr.current===Ne&&(Vt.current===j&&(Vt.current=null),_t(f),f.data.session&&rt(f.data.session),Jt(!1),hr(!1))},f=>{Dr.current===Ne&&(Vt.current===j&&(Vt.current=null),Jt(!1),hr(!1),jt(f instanceof Ue.FloPayError?f:new Ue.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error")))})}else Dr.current+=1,Vt.current=null,Jt(!1),hr(!1);let{flopay:ot,paypalFlopay:pr}=await Rs(ut,{billingApiUrl:M,locale:c,telemetry:a}).catch(Ne=>{throw Il(Ne,Ee||ut.data.session?.id)});return dt(ot,pr),L(!1),Xe}catch(Xe){throw Zn.current===xt&&(Zn.current=null),Xe}finally{z||re()}},[nt,dt,c,M,a]),jr=(0,P.useRef)(Jn);jr.current=Jn;let co=(0,P.useRef)(yn);co.current=yn;let Nt=(0,P.useCallback)(async U=>{if(!mu(U)||Mt)return{sessionId:Tt,session:V};Br(!0);try{let z=await yn(U);return{sessionId:z.sid,session:z.result.data.session??null}}finally{Br(!1)}},[yn,Mt,Tt,V]),Zr=(0,P.useCallback)(async U=>{let z=kr.current;if(!z)return;let ce=Dr.current,ve=await z(U);Dr.current===ce&&(_t(ve),ve.data.session&&rt(ve.data.session))},[]),Qr=(0,P.useCallback)(async()=>{await Vt.current},[]),cn=(0,P.useCallback)(async()=>(await Qr(),{proceed:!0}),[Qr]);(0,P.useEffect)(()=>{let U=!1,z,ce=++ue.current;te(),jt(null),dr(0);let ve=()=>{U=!0,ue.current===ce&&(ue.current+=1,te())},xt=lo.current;if(Tn&&xt)return ct(Un),L(!1),Zn.current===Tn?ve:(rt(El(xt,be)),(async()=>{let Z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),re=Un==="auto"&&!Pr.current&&!Z;re&&(Gt(null),Yt(null),Qt("processing"));let Xe=!1;try{let Ee=await co.current(void 0,Ot=>{z=Ot});Xe=!0;let ut=Ee.result.data.session??null;Wt.current=ls(Ee.result);let j=ks(Ee.result),pe=(0,Dn.wasSessionRecentlyCompleted)(Ee.sid||ut?.id);if(!U&&re&&ut&&!j&&!pe){Pr.current=!0,await su(Tn,Ee.sdkGeneratedIdempotencyKey,()=>jr.current(ut,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Ee.result.autoProcessingError,initialAutoProcessingPending:Ee.result.autoProcessingPending,autoProcessingAttempted:Ee.result.autoProcessingAttempted,sessionId:Ee.sid||ut.id}));return}!U&&re&&((j||pe)&&(Pr.current=!0),Qt(null),Yt(null))}catch(Ee){if(U)return;let ut=ti(Ee);if(re&&ut==="session_auto_completed"){Pr.current=!0,Qt("success"),await Oa(600),U||((0,Qe.invokeMerchantCallback)(()=>{ln.current?.({status:"succeeded"})}),Qt(null),Yt(null));return}if(re&&(Qt(null),Yt(null)),!Xe){let pe=Tl(Ee),Ot=(0,Ue.toPublicCheckoutInitError)(Ee,pe?{stage:"provider_load",provider:"stripe",...pe}:{stage:"session_request"});(pe||!(Ee instanceof Ue.FloPayError))&&(0,Qe.invokeMerchantCallback)(()=>zr.current?.(Ot)),jt(Ot);return}let j=Ee instanceof Ue.FloPayError?Ee:new Ue.FloPayError(Ee instanceof Error?Ee.message:"Failed to create session","api_error");jt(j)}finally{z?.(),z=void 0}})(),()=>{ve(),z?.()});L(!0);async function zt(){let Z=!1,re=!1,Xe=null;try{let Ee=new io.PaymentAPI(M,{telemetry:!1}),ut=await Ee.getUnifiedCheckoutSession(C,t);if(re=!0,Xe=ut,U)return;_t(ut);let j=ut.data.session??null;if(rt(j),!j)throw new Ue.FloPayError("No session data returned","api_error");let pe=j.checkoutMode;if(pe==="setup")throw new Ue.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(j.status==="authorized"){L(!1),(0,Qe.invokeMerchantCallback)(()=>{ln.current?.(eo(j,C)),Se.current?.(j.successUrl??"")});return}if(j.status==="complete"){L(!1),(0,Qe.invokeMerchantCallback)(()=>{Se.current?.(j.successUrl??"")});return}if(j.status==="expired")throw ei(j);Z=!0;let Ot=be??pe??"full";ct(Ot),Dr.current+=1;let ot=j.clientSecret||t;kr.current=j.buyerIdentified===!1&&ot?Wo(Ee,C,ot,{...j.customer?.id?{userId:j.customer.id}:{}}):void 0,Jt(!1),hr(!1);let pr=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ne=ks(ut);if(Ot==="auto"&&!Pr.current&&!pr&&!Ne){Pr.current=!0;let f=ze(ut);try{if(await jr.current(j,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>f,sessionId:C||j.id}),U)return;await f,U||L(!1);return}catch{if(U)return;await f,U||L(!1);return}}await ze(ut),U||L(!1)}catch(Ee){if(U)return;let ut=kl(Ee,Z);if(Z&&it({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ut){let{errorCode:ot,stage:pr,...Ne}=ut;ws(M,a,Ce,ot,pr,Ne)}if(ut?.stage==="provider_load"&&(be??Xe?.data.session?.checkoutMode??"full")==="full"&&wl(Xe,F,y)){let ot=cu({billingApiUrl:M,locale:c,telemetry:a});de.current=ot,dt(ot,null),dr(1),L(!1);return}let j=ut?.stage==="provider_load",pe="session_request";j?pe="provider_load":re&&(pe="post_session");let Ot=(0,Ue.toPublicCheckoutInitError)(Ee,{stage:pe,provider:"stripe",sessionId:C||void 0});(j||!(Ee instanceof Ue.FloPayError))&&(0,Qe.invokeMerchantCallback)(()=>zr.current?.(Ot)),jt(Ot),L(!1)}}async function ze(Z){let{flopay:re,paypalFlopay:Xe,...Ee}=await Rs(Z,{billingApiUrl:M,locale:c,telemetry:a});Wt.current={publishableKey:Ee.publishableKey,paypalPublishableKey:Ee.paypalPublishableKey},dt(re,Xe),dr(0)}return zt(),ve},[be,Tn,Un,Q,t,F,y]);let dn=(0,P.useCallback)(async()=>{if(!Ge||Mr!==1)return;let U=ue.current;dr(2);try{let{flopay:z,paypalFlopay:ce}=await Rs(Ge,{billingApiUrl:M,locale:c,telemetry:a});if(ue.current!==U)return;te(),dt(z,ce),dr(0)}catch(z){if(ue.current!==U)return;let{errorCode:ce,stage:ve,...xt}=es(z);ws(M,a,Ce,ce,ve,xt)}},[te,dt,c,Mr,M,a,Ce,Ge]),st=!!(C&&(V?.clientSecret||t)),ur=Gr||!st,vr=(0,P.useCallback)(async()=>{if(!(Gr||!st||!V)){Yr(!0),Gt(null);try{await Jn(V,{attempt3DS:!0,fallbackToFull:!0,sessionId:C||V.id})}finally{Yr(!1)}}},[C,Gr,st,Jn,V]),Rr=(0,Ue.resolveDirectPaypalConfig)(Ge?.data.paypal,se),ho=ks(Ge),zn=(0,P.useMemo)(()=>{if(!(!Ge||!V||!Ge.data.stripe?.publishableKey))return{billingApiUrl:M}},[Ge,V,M]),uo=!!(r&&!O&&ie==="buttons"&&Ve&&Un==="full"),Vr=!!(C&&((0,Ue.isMountableVaultBlock)(V?.vault)||(0,An.canRecoverHostedCardForm)(V))),Er=(0,P.useMemo)(()=>({session:V,loading:le,error:k,checkoutMode:xr,inlineSessionDraft:er,applyInlineSessionPatch:uo?Nt:void 0,inlineSessionPatchProcessing:Mt,claimPending:ar,claimRequiresIdentity:Ur,claimBuyerIdentity:Zr,waitForDataAttachment:Qr}),[V,le,k,xr,er,uo,Nt,Mt,ar,Ur,Zr,Qr]),po=!!r&&ie==="buttons"&&!ho&&!Vr&&(!Ut||!zn),Lr=nr?(0,B.jsx)(rn,{status:nr,errorMessage:Rn,authorized:Nn}):null;if(le&&!Vr){if(p)return(0,B.jsxs)(B.Fragment,{children:[p,Lr]});if(ie==="buttons"){let U=at?.buttonsLayout?.cardButton?.borderRadius??at?.appearance.variables?.borderRadius??8,z=ce=>(0,B.jsx)("div",{style:{height:ce,borderRadius:U,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[F&&z(na),y&&(w||Te)&&z(na),y&&z(na),(0,B.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Lr]})}return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,B.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,B.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Lr]})}return k?m?(0,B.jsx)(Fn.Provider,{value:Er,children:m(k)}):(0,B.jsx)(Fn.Provider,{value:Er,children:(0,B.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:k.message})}):po?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fn.Provider,{value:Er,children:(0,B.jsx)(fu,{onButtonClick:tt,showPayPal:F,showStripe:y,showApplePay:w,showGooglePay:Te,theme:he,buttonsTheme:fe,buttonsStyles:ke,cardButtonContent:mt,cardBackButtonContent:Je,cardTitleContent:A})}),Lr]}):ho&&V&&Rr?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fn.Provider,{value:Er,children:(0,B.jsxs)("div",{className:J,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ar&&(0,B.jsx)(Jo,{icon:!1,children:Ar}),Le==="retrying"&&(0,B.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Le==="exhausted"&&(0,B.jsxs)("div",{role:"alert",children:[(0,B.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,B.jsx)("button",{type:"button",onClick:$t,children:"Retry PayPal"})]}),Le!=="exhausted"&&(0,B.jsx)("div",{"aria-hidden":Le==="retrying"?!0:void 0,style:Le==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,B.jsx)(jl,{sessionId:C,nonce:V.clientSecret||void 0,billingApiUrl:M,email:V.customer?.email||er?.account?.email,billingName:[V.customer?.firstName,V.customer?.lastName].filter(Boolean).join(" ")||[er?.account?.firstName,er?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Zr,clientId:Rr.clientId,environment:Rr.environment,currency:(V.currency??"usd").toUpperCase(),isSubscription:V.mode==="subscription",providerObjectType:Rr.providerObjectType,approvalPresentation:Rr.approvalPresentation,existingOrderId:Rr.existingOrderId,onComplete:g,onErrorChange:Gt,onDecline:I,onCancel:H,onButtonClick:tt,runBeforeButtonClick:cn,onInitializationStateChange:Dt,allowAutomaticRetry:Xr===0,session:V,telemetry:a,telemetryContext:Ce,onInstrument:Oe,debug:x},`${Re}:paypal-init-${Xr}`)})]})}),Lr]}):xr==="confirm"?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fn.Provider,{value:Er,children:(0,B.jsx)(Ra,{flopay:Ut,paypalFlopay:X,options:zn??{billingApiUrl:M},onInstrument:Oe,children:(0,B.jsxs)("div",{className:J,children:[Ar&&(0,B.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ar}),Pe?Pe({onConfirm:vr,isProcessing:ur}):(0,B.jsx)("button",{type:"button",onClick:vr,disabled:ur,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:ur?"not-allowed":"pointer",opacity:ur?.6:1},children:Gr?"Processing...":Me??"Confirm Purchase"})]})},Re)}),Lr]}):(!Ut||!zn)&&!(Vr&&xr==="full")?(0,B.jsx)(B.Fragment,{children:Lr}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fn.Provider,{value:Er,children:(0,B.jsxs)(Ra,{flopay:Ut,paypalFlopay:X,options:zn??{billingApiUrl:M},onInstrument:Oe,children:[Mr===1&&(0,B.jsx)("button",{type:"button",onClick:dn,children:"Retry payment methods"}),O?(0,B.jsxs)(B.Fragment,{children:[Ar&&(0,B.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ar}),(0,B.jsx)(yu,{sessionId:C,nonce:V?.clientSecret||void 0,billingApiUrl:M,session:V,submitLabel:He,walletPresentation:h,children:O})]}):(0,B.jsx)(Ei,{sessionId:C,nonce:V?.clientSecret||void 0,telemetry:a,email:V?.customer?.email||er?.account?.email,userId:V?.customer?.id||er?.account?.userId,firstName:V?.customer?.firstName||er?.account?.firstName,lastName:V?.customer?.lastName||er?.account?.lastName,totalAmount:V?Math.round((0,Ue.buildCheckoutDisplayData)(V).total*100):0,currency:V?.currency?.toLowerCase()??"usd",onComplete:g,onError:_,onDecline:I,onCancel:H,error:Ar,onErrorChange:Gt,showPayPal:F,showStripe:y,walletPresentation:h,enabledPaymentMethods:Mr?[]:ge??Ge?.data.stripe?.enabledPaymentMethods??V?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ge?.data.stripe?.enabledPaymentMethodCountries,showApplePay:w,showGooglePay:Te,layout:ie,theme:he,buttonsTheme:fe,buttonsStyles:ke,appearance:Ke,cardButtonContent:mt,cardBackButtonContent:Je,cardTitleContent:A,onButtonClick:tt,onBeforeButtonClick:Ve,onBuyerIdentityReady:Zr,enableAVS:me,...K?{cardFieldOrder:K}:{},...W===void 0?{}:{cardAutoFocus:W},...Fe?{cardPreFormSlot:Fe}:{},avsLayout:lt,country:V?.customer?.country,city:V?.customer?.city,state:V?.customer?.state,onCountryChange:T,onZipChange:Y,avsCheck:!!me,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:_s(O,ie),className:J,submitLabel:He,directPaypal:Rr,isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:ar,dataAttachmentRequiresIdentity:Ur,debug:x})]},Re)}),Lr]})}function yu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,children:c}){return(0,B.jsx)(B.Fragment,{children:P.default.Children.map(c,p=>{if(!P.default.isValidElement(p))return p;let m=p.props,g={};return m.sessionId||(g.sessionId=e),!m.nonce&&t&&(g.nonce=t),m.billingApiUrl||(g.billingApiUrl=r),m.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),m.walletPresentation===void 0&&(g.walletPresentation=s),n?.customer&&(m.email||(g.email=n.customer.email),m.userId||(g.userId=n.customer.id),m.firstName||(g.firstName=n.customer.firstName),m.lastName||(g.lastName=n.customer.lastName)),Object.keys(g).length===0?p:P.default.cloneElement(p,g)})})}function fu({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:s,buttonsTheme:c,buttonsStyles:p,cardButtonContent:m,cardBackButtonContent:g,cardTitleContent:_}){let[E,I]=(0,P.useState)(!1),H=(0,P.useMemo)(()=>(0,Ue.resolveTheme)(s),[s]),T=(0,P.useMemo)(()=>{let h=H?.buttonsLayout??(0,Ue.resolveButtonsLayoutTheme)(c);return p?{...h,...p,cardButton:{...h.cardButton,...p.cardButton},cardFormContainer:{...h.cardFormContainer,...p.cardFormContainer},backButton:{...h.backButton,...p.backButton},backButtonIcon:{...h.backButtonIcon,...p.backButtonIcon},submitButton:{...h.submitButton,...p.submitButton},title:{...h.title,...p.title}}:h},[H,c,p]),Y=H?.buttonsLayout?.cardButton?.borderRadius??H?.appearance.variables?.borderRadius??8,F=h=>(0,B.jsx)("div",{style:{height:h,borderRadius:Y,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),y=m===void 0?{boxSizing:"border-box",height:na,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let h=T.cardInputBorder??"#e5e7eb",ge=T.cardInputBackground??"white",w=qo(g),Te=qo(_);return(0,B.jsxs)("div",{style:{backgroundColor:T.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...T.cardFormContainer},children:[(0,B.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,B.jsxs)("button",{type:"button",onClick:()=>I(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:w?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...T.backButton},children:[(0,B.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...T.backButtonIcon},children:(0,B.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,B.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,B.jsx)(Vo,{content:g})]}),Te?(0,B.jsx)("div",{style:{flex:1}}):(0,B.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...T.title},children:(0,B.jsx)(ha,{content:_})})]}),(0,B.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${h}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsxs)("div",{style:{display:"flex"},children:[(0,B.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:`1px solid ${h}`,borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,B.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${h}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...T.submitButton,opacity:.5}}),(0,B.jsx)("style",{children:`
41
41
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
42
42
  @keyframes flopay-interim-expand {
43
43
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
44
44
  40% { opacity: 1; }
45
45
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
46
46
  }
47
- `})]})}return(0,D.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&B(ra),r&&(n||a)&&B(ra),r&&(0,D.jsx)("button",{type:"button",onClick:()=>{e?.("card"),_(!0)},style:{width:"100%",...f,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:T.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,...T.cardButton},onMouseDown:h=>{h.currentTarget.style.transform="scale(0.985)"},onMouseUp:h=>{h.currentTarget.style.transform="scale(1)"},children:(0,D.jsx)(qo,{content:y})}),(0,D.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var wn=require("react/jsx-runtime"),gu=44;function vc(e){return new Promise(t=>setTimeout(t,e))}function hu(e,t){return e instanceof Rn.FloPayError?e:new Rn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Pu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function vu(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 Cc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:s,products:c,items:p,subscriptions:y,account:g,successUrl:E,cancelUrl:R,couponCodes:_,tagsData:H,utmMetadata:T,billingApiUrl:Y,locale:B,theme:f,appearance:h,buttonsTheme:ge,buttonsStyles:S,onSuccess:Me,onError:A,onDecline:ie,children:he,disabled:fe=!1,type:Re="button",style:ct,...Ke}){let F=(0,ht.useMemo)(()=>(0,Rn.resolveBillingApiUrl)(Y),[Y]),St=(0,ht.useMemo)(()=>vu({createSession:r,clientId:s,products:c,items:p,subscriptions:y,account:g,successUrl:E,cancelUrl:R,couponCodes:_,tagsData:H,utmMetadata:T}),[g,R,s,_,r,c,p,y,E,H,T]),[et,Ue]=(0,ht.useState)(!1),[ye,J]=(0,ht.useState)(null),[W,Fe]=(0,ht.useState)(null),[dt,We]=(0,ht.useState)(!1),[Z,L]=(0,ht.useState)(null),[le,j]=(0,ht.useState)(null),Se=(0,ht.useRef)(!0),xe=(0,ht.useRef)(null),Pe=(0,ht.useRef)(le),Be=(0,ht.useRef)(Me),M=(0,ht.useRef)(A),nt=(0,ht.useRef)(ie),je=(0,ht.useCallback)(v=>di(xe,async U=>{try{return await v(U)}catch(ne){throw U.aborted?Jo(ne):ne}}),[]);(0,ht.useEffect)(()=>{Pe.current=le},[le]),(0,ht.useEffect)(()=>{Be.current=Me},[Me]),(0,ht.useEffect)(()=>{M.current=A},[A]),(0,ht.useEffect)(()=>{nt.current=ie},[ie]),(0,ht.useEffect)(()=>(Se.current=!0,()=>{Se.current=!1,xe.current?.abort()}),[]),(0,ht.useEffect)(()=>{if(typeof window>"u")return;let v=U=>{U.key==="Escape"&&j(null)};return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[]);let ut=(0,ht.useCallback)((v,U=Ea)=>{nt.current?.(wr(U,v,{code:v.code,declineCode:v.declineCode}))},[]),Ge=(0,ht.useCallback)(async v=>{Se.current&&(Fe(null),We(v.result.status==="authorized"),J("success"),await vc(600),Se.current&&(0,Xe.invokeMerchantCallback)(()=>Be.current?.(v)))},[]),$e=(0,ht.useCallback)(async(v,U)=>{Se.current&&(M.current?.(v),U?.emitDecline&&ut(v,U.method),Fe(v.message),We(!1),J("error"),await vc(400))},[ut]),Rt=(0,ht.useCallback)(async(v,U,ne)=>{let Ae=v.data.session??null;if(!Ae)throw fo(new Rn.FloPayError("No session data returned","api_error"),U);let Dt=Ae.clientSecret||t;if(oo(Ae)){await Ge({result:no(Ae,U),session:Ae,sessionId:Ae.id||U,autoCompleted:!1});return}if(Ae.status==="expired")throw fo(Qa(Ae),Ae.id||U);try{if(v.autoProcessingPending){let De=v.autoProcessingPending,Oe=new Mi.PaymentAPI(F),_t=await je(Q=>Oe.waitForCheckoutSessionCompletion(De.sessionId,{initialDelayMs:De.retryAfterMs,nonce:Dt,statusUrl:De.statusUrl,signal:Q})),u=go(_t,Ae),C=_t.autoProcessingError?.type==="3ds_required"&&_t.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:_t.autoProcessingError.nextActionRedirectUrl}:null;if(C&&U&&Dt){let Q=Ia(F,U,Ae),ce=await je(N=>Zo(C,{billingApiUrl:F,sessionId:U,nonce:Dt,session:Ae,signal:N,telemetry:!0,...Q.telemetry?{challengeTelemetry:Q.telemetry}:{}})).finally(Q.release);await Ge({result:ce,session:Ae,sessionId:Ae.id||U,autoCompleted:!1});return}if(_t.autoProcessingError)throw Xn(_t.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:_t.autoProcessingError.checkoutMethod});if(!oo(u))throw Wo(u);await Ge({result:no(u,U),session:u,sessionId:u.id||U,autoCompleted:!1});return}if(v.autoProcessingError){let De=v.autoProcessingError.nextActionRedirectUrl;if(v.autoProcessingError.type==="3ds_required"&&De&&U&&Dt){let Oe=await je(Q=>Kl({billingApiUrl:F,sessionId:U,nonce:Dt,nextActionRedirectUrl:De,signal:Q}));if(Oe.status==="declined")throw Xn({type:Oe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Oe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:v.autoProcessingError.checkoutMethod});let u=await new Mi.PaymentAPI(F).waitForCheckoutSessionCompletion(U,{initialDelayMs:0,nonce:Dt}),C=go(u,Ae);if(!oo(C))throw Xn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:v.autoProcessingError.checkoutMethod});await Ge({result:no(C,U),session:C,sessionId:C.id||U,autoCompleted:!1});return}throw Xn(v.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:v.autoProcessingError.checkoutMethod})}if(ne?.fromCreateSession&&v.autoProcessingAttempted===!0)throw Xn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ot=await Qo({billingApiUrl:F,sessionId:U??Ae.id,session:Ae,nonce:Dt});if(ot.type==="next_action_required"&&Dt){let De=U??Ae.id,Oe=Ia(F,De,Ae),_t=await je(u=>Zo(ot,{billingApiUrl:F,sessionId:De,nonce:Dt,session:Ae,signal:u,telemetry:!0,...Oe.telemetry?{challengeTelemetry:Oe.telemetry}:{}})).finally(Oe.release);await Ge({result:_t,session:Ae,sessionId:Ae.id||De,autoCompleted:!1});return}if(ot.type!=="success")throw Xn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ge({result:ot.result,session:Ae,sessionId:Ae.id||U,autoCompleted:!1})}catch(ot){let De=Ae.id||U,Oe=fo(_a(ot),De);if(Oe.code==="three_ds_aborted")return;if(Oe.code==="checkout_processing_timeout"){if(!Se.current)return;L(Oe.message),(0,Xe.invokeMerchantCallback)(()=>M.current?.(Oe));return}await $e(Oe,{emitDecline:!0,method:Oe.checkoutMethod??Ea}),Pu(Oe,De)&&De&&Se.current&&j({sessionId:De,errorMessage:Oe.message,nonce:Dt||void 0,payPalOrderId:Oe.orderId})}},[t,F,je,$e,Ge]),Ot=(0,ht.useCallback)(async v=>{if(Ke.onClick?.(v),!(v.defaultPrevented||fe||et)){if(j(null),L(null),e&&St){let U=new Rn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await $e(U),Se.current&&(J(null),Fe(null));return}if(!e&&!St){let U=new Rn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $e(U),Se.current&&(J(null),Fe(null));return}Ue(!0),Fe(null),We(!1),J("processing");try{let U=new Mi.PaymentAPI(F);if(e){let ne=await U.getUnifiedCheckoutSession(e,t);await Rt(ne,e);return}try{let ne=await U.createAndFetchSession({...St});await Rt(ne,ne.data.session?.id??null,{fromCreateSession:!0})}catch(ne){if(ei(ne)==="session_auto_completed"){await Ge({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ne}}catch(U){await $e(fo(hu(U,"Automatic payment failed. Please try again."),e))}finally{Se.current&&(J(null),Fe(null),Ue(!1))}}},[Ke.onClick,St,fe,et,t,Rt,F,e,$e,Ge]),zt=(0,ht.useCallback)(v=>{let U=Pe.current;j(null),Be.current?.({result:v,session:null,sessionId:U?.sessionId??null,autoCompleted:!1})},[]),Ft=(0,ht.useCallback)(v=>{M.current?.(v)},[]),ue=(0,ht.useCallback)(v=>{nt.current?.(v)},[]),pe=(0,ht.useMemo)(()=>(0,Rn.resolveTheme)(f),[f]),X=(0,ht.useMemo)(()=>{let v=pe?.buttonsLayout??(0,Rn.resolveButtonsLayoutTheme)(ge);return S?{...v,...S,cardButton:{...v.cardButton,...S.cardButton}}:v},[pe,ge,S]),Pt=(0,ht.useMemo)(()=>{let v=pe?.appearance;return h?v?{...v,...h,variables:{...v.variables,...h.variables}}:h:v},[h,pe]),pt=Pt?.variables,V=pt?.colorPrimary??"#4A49FF",rt=pt?.colorPrimaryHover??(0,Ss.darkenHex)(V,.12),wt=pt?.borderRadius??"8px";return(0,wn.jsxs)(wn.Fragment,{children:[(0,wn.jsx)("button",{...Ke,type:Re,onClick:Ot,disabled:fe||et,"aria-busy":et,style:{width:"100%",...he===void 0?{boxSizing:"border-box",height:gu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...X.cardButton,...bs({themeBundle:pe,resolvedPrimaryColor:V,resolvedBorderRadius:wt,submitButtonStyle:X.submitButton,explicitPrimaryColor:pt?.colorPrimary}),fontSize:X.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:fe||et?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:fe||et?.6:1,...ct},onMouseEnter:v=>{Ke.onMouseEnter?.(v),!v.defaultPrevented&&!fe&&!et&&(pe||pt?.colorPrimary)&&(v.currentTarget.style.backgroundColor=rt)},onMouseLeave:v=>{Ke.onMouseLeave?.(v),!v.defaultPrevented&&(pe||pt?.colorPrimary)&&(v.currentTarget.style.backgroundColor=V)},onMouseDown:v=>{Ke.onMouseDown?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(0.985)")},onMouseUp:v=>{Ke.onMouseUp?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(1)")},children:(0,wn.jsx)(qo,{content:he})}),Z&&(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:Z}),ye&&(0,wn.jsx)(tn,{status:ye,errorMessage:W,authorized:dt}),le&&(0,wn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:v=>{v.target===v.currentTarget&&j(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,wn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,wn.jsx)(Ti,{sessionId:le.sessionId,nonce:le.nonce,checkoutMode:"full",billingApiUrl:F,locale:B,theme:f,...Pt?{appearance:Pt}:{},buttonsTheme:ge,buttonsStyles:S,initialErrorMessage:le.errorMessage,initialPayPalOrderId:le.payPalOrderId,cardTitleContent:null,onComplete:zt,onError:Ft,onDecline:ue})})})]})}var Ai=require("@flopay/js/card-setup"),Hr=require("@flopay/shared"),Kt=require("react");var Ms=require("@flopay/shared"),Cu=require("@flopay/shared");function xi(e){let t=(0,Ms.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Zn=require("react/jsx-runtime"),La=class extends Hr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function uo(e,t={}){let r=e instanceof Hr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new La(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 bc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:c,buttonsStyles:p,loading:y=null,onReady:g,onComplete:E,onDecline:R,onCancel:_,onValidation:H,onError:T}){let[Y,B]=(0,Kt.useState)(null),[f,h]=(0,Kt.useState)(null),[ge,S]=(0,Kt.useState)(null),[Me,A]=(0,Kt.useState)(null),[ie,he]=(0,Kt.useState)(null),fe=(0,Kt.useRef)(!1),Re=(0,Kt.useRef)(!1),{vaultTheme:ct,surface:Ke,overlayTheme:F}=(0,Kt.useMemo)(()=>xi({theme:a,appearance:c,buttonsStyles:p}),[a,c,p]),St=(0,Kt.useMemo)(()=>(0,xa.mergeCardSetupSurface)(Ke,s),[Ke,s]),et=(0,Kt.useRef)(g),Ue=(0,Kt.useRef)(T),ye=(0,Kt.useRef)(E),J=(0,Kt.useRef)(R),W=(0,Kt.useRef)(_),Fe=(0,Kt.useRef)(H),dt=(0,Kt.useRef)(!1),We=(0,Kt.useRef)(!1),Z=(0,Kt.useRef)(0);return et.current=g,Ue.current=T,ye.current=E,J.current=R,W.current=_,Fe.current=H,(0,Kt.useEffect)(()=>{let L=Z.current+1;return Z.current=L,()=>{queueMicrotask(()=>{Z.current===L&&(dt.current||We.current||(We.current=!0,(0,Xe.invokeMerchantCallback)(()=>{W.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Kt.useEffect)(()=>{let L=!0,le=(0,Hr.resolveBillingApiUrl)(r),j=new Ai.PaymentAPI(le,{telemetry:n});return B(null),h(null),S(null),dt.current=!1,We.current=!1,(async()=>{try{if(!e.trim())throw new Hr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Hr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Se=await j.getUnifiedCheckoutSession(e,t);if(!L)return;let xe=Se.data.session;if(!xe||!(0,Hr.isCardSetupCheckoutSession)(xe))throw new Hr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Pe=xe.vault;(0,Hr.isMountableVaultBlock)(Pe)||(Pe=await j.getVaultCapture(e,t));let Be=(0,Hr.resolveVaultMountOptions)(Pe,{billingApiUrl:le,sessionId:e,nonce:t});if(!Be)throw new Hr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!L)return;h(Be),B(new Ai.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(Se){if(!L)return;let xe=uo(Se);dt.current=!0,S(xe),(0,Xe.invokeMerchantCallback)(()=>Ue.current?.(xe))}})(),()=>{L=!1,j.destroy()}},[r,t,e,n]),(0,Kt.useEffect)(()=>{if(!Y)return;let L=!1;Re.current=!1,fe.current=!1;let le=Y.on("submitting",()=>{fe.current=!0,he(null),A("processing")}),j=Y.on("complete",Pe=>{dt.current=!0,fe.current=!1,A("success"),(async()=>(await new Promise(Be=>setTimeout(Be,600)),!Re.current&&(Re.current=!0,(0,Xe.invokeMerchantCallback)(()=>{ye.current?.({status:"succeeded",sessionId:e,...Pe.paymentMethod?{paymentMethod:Pe.paymentMethod}:{}})}),L||A(null))))()}),Se=Y.on("decline",Pe=>{dt.current=!0,fe.current=!1,he(Pe.message??null),A("error"),(0,Xe.invokeMerchantCallback)(()=>{J.current?.({status:"declined",sessionId:e,...Pe.declineReason?{reason:Pe.declineReason}:{},...Pe.message?{message:Pe.message}:{}})}),(async()=>(await new Promise(Be=>setTimeout(Be,400)),L||A(null)))()}),xe=Y.on("challenge_dismissed",()=>{A(null)});return()=>{L=!0,le(),j(),Se(),xe()}},[Y,e]),ge?(0,Zn.jsx)("div",{role:"alert",children:ge.message}):!Y||!f?.html?(0,Zn.jsx)(Zn.Fragment,{children:y}):(0,Zn.jsxs)(Zn.Fragment,{children:[Me&&(0,Zn.jsx)(tn,{status:Me,errorMessage:ie,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...F?{theme:F}:{}}),(0,Zn.jsx)(ho,{capture:Y,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:ct,containerStyle:St,onReady:()=>{(0,Xe.invokeMerchantCallback)(()=>et.current?.())},onValidation:L=>{(0,Xe.invokeMerchantCallback)(()=>Fe.current?.(L))},onError:L=>{if(!L)return;fe.current&&(fe.current=!1,he(L),A("error"),setTimeout(()=>A(null),400));let le=uo(new Error(L),{code:"card_setup_widget_failed",retryable:!0});(0,Xe.invokeMerchantCallback)(()=>Ue.current?.(le))}})]})}var Sc=require("@flopay/js/card-setup"),kn=require("@flopay/shared"),wc=require("@paypal/paypal-js"),Io=require("react");var kc=require("react/jsx-runtime");function Rc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:c,customer:{userId:p,email:y},onSubmitting:g,onConfirmed:E,onFailed:R,onAbandoned:_}){let H=(0,Io.useRef)(null),T=(0,Io.useRef)({onSubmitting:g,onConfirmed:E,onFailed:R,onAbandoned:_});T.current={onSubmitting:g,onConfirmed:E,onFailed:R,onAbandoned:_};let[Y]=(0,Io.useState)(()=>(0,Gn.detectPayPalEnvironment)().inAppBrowser);return(0,Io.useEffect)(()=>{let B=!0,f,h=new Sc.PaymentAPI(s,{telemetry:c}),ge={userId:p,email:y};return(async()=>{try{let S=await(0,wc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Me=H.current;if(!B||!Me)return;if(!S?.Buttons)throw new kn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let A=S.Buttons({createVaultSetupToken:async()=>{T.current.onSubmitting();let ie=await h.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:kn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,kn.isSettledSessionIntent)(ie))throw(0,kn.settledSessionIntentError)(n);if(ie.provider!=="paypal"||ie.providerObjectType!=="setup_token")throw new kn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ie.providerObjectId},onApprove:async ie=>{let he=ie.vaultSetupToken;if(!he)throw new kn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let fe=await h.processPayment(ge.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:he,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:kn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:ge});if(!fe.ok)throw new kn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:fe.status});B&&T.current.onConfirmed()},onCancel:()=>{B&&T.current.onAbandoned()},onError:ie=>{if(!B)return;let{popupBlocked:he}=(0,we.classifyExternalMethodFailure)(ie,{inAppBrowser:Y,handoffObserved:!1});T.current.onFailed(he?new Error((0,we.buildExternalMethodRecoveryMessage)("PayPal",!0,Y)):ie,{code:he?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>A.close(),await A.render(Me)}catch(S){if(!B)return;T.current.onFailed(S,{code:"paypal_unavailable",retryable:!0})}})(),()=>{B=!1,f?.().catch(()=>{}),h.destroy()}},[s,e,r,y,t,Y,a,n,c,p]),(0,kc.jsx)("div",{ref:H,"data-flopay-paypal-setup":""})}var Ic=require("@flopay/js/card-setup"),En=require("@flopay/shared"),Qn=require("@stripe/react-stripe-js"),_c=require("@stripe/stripe-js"),Kr=require("react");var jr=require("react/jsx-runtime"),Tc={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"}},xs=new Map;function bu(e){let t=xs.get(e);if(t)return t;let r=(0,_c.loadStripe)(e).catch(n=>{throw xs.delete(e),n});return xs.set(e,r),r}function Su(e){return e?(0,En.toStripeAppearance)(e):void 0}function wu(e){return(0,we.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Ec(e){return e==="paypal"?"PayPal":(0,En.getStripeMethodDisplayName)(e)}function Ru(){return typeof window>"u"?"":window.location.href}var ku={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function Mc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:c}=e,[p]=(0,Kr.useState)(()=>bu(t)),y=(0,Kr.useMemo)(()=>{let g=Su(c),E=(0,En.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:Tc[r]?.types??[r],...E?{setupFutureUsage:E}:{},...g?{appearance:g}:{}}},[c,n,a,s,r]);return(0,jr.jsx)(Qn.Elements,{stripe:p,options:y,children:(0,jr.jsx)(Eu,{...e})})}function Eu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:c,themeId:p,buttonsLayout:y,onSubmitting:g,onConfirmed:E,onDeclined:R,onFailed:_,onValidation:H,onUnavailable:T}){let Y=(0,Qn.useStripe)(),B=(0,Qn.useElements)(),[f,h]=(0,Kr.useState)(!1),[ge,S]=(0,Kr.useState)("loading"),[Me,A]=(0,Kr.useState)(!1),[ie,he]=(0,Kr.useState)(!1),fe=(0,Kr.useRef)(!1),[Re]=(0,Kr.useState)(()=>(0,Gn.detectPayPalEnvironment)()),[ct,Ke]=(0,Kr.useState)(!1),F=(0,Kr.useCallback)((W,Fe)=>{if((0,we.classifyExternalMethodFailure)(W,{inAppBrowser:Re.inAppBrowser,handoffObserved:!1}).popupBlocked){Ke(!0),_(new Error((0,we.buildExternalMethodRecoveryMessage)(Ec(e),!0,Re.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}_(Fe.message===void 0?W:new Error(Fe.message),{code:Fe.code,retryable:!0})},[Re.inAppBrowser,e,_]),St=(0,Kr.useCallback)(async W=>{let Fe=!1,dt=!1,We=()=>{!W||Fe||dt||(dt=!0,W.paymentFailed({reason:"fail"}))};if(!Y||!B||fe.current){We();return}fe.current=!0,h(!0);try{let Z=await B.submit();if(Z.error){We(),H(Z.error.message??null);return}g();let L=await new Ic.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,En.isSettledSessionIntent)(L))throw(0,En.settledSessionIntentError)(r);if(L.provider!=="stripe"||L.intentKind!=="setup")throw new En.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Fe=!0;let le=await Y.confirmSetup({elements:B,clientSecret:L.clientSecret,confirmParams:{return_url:Ru()},redirect:"if_required"});if(le.error){wu(le.error)?R({...le.error.decline_code||le.error.code?{reason:le.error.decline_code??le.error.code}:{},...le.error.message?{message:le.error.message}:{}}):F(le.error,{code:"payment_method_setup_provider_failed",message:le.error.message??"The payment method could not be saved."});return}E()}catch(Z){We(),F(Z,{code:"payment_method_setup_failed"})}finally{fe.current=!1,h(!1)}},[a,t,B,e,n,E,R,g,H,F,r,Y,s]),et=Tc[e]?.wallet,Ue=et==="paypal"&&(0,Yn.resolveStripePayPalPresentation)(Re,"auto",ct?"blocked":Re.popupCapability)==="redirect",ye=c?.variables?.borderRadius??y?.cardButton?.borderRadius??8;if(t==="wallet"&&et&&!Ue)return(0,jr.jsxs)(jr.Fragment,{children:[(0,jr.jsx)(ta,{}),(0,jr.jsx)(Ma,{state:ge,borderRadius:ye,children:(0,jr.jsx)(Qn.ExpressCheckoutElement,{options:{...gi,paymentMethods:fi([e])},onReady:W=>{let Fe=Ta(W,[et]);S(Fe),Fe==="unavailable"&&T()},onLoadError:()=>{S("load_error"),T()},onConfirm:W=>{St(W)}})})]});let J=Ec(e);return(0,jr.jsxs)(jr.Fragment,{children:[Me?(0,jr.jsx)(yi,{method:e,themeId:p,hasNextStep:!0,highlighted:ie,disabled:f,onClick:()=>he(W=>!W),backgroundColor:y?.cardButton?.backgroundColor,borderColor:y?.cardInputBorder,textColor:y?.cardButton?.color,borderRadius:ye}):null,(0,jr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ie,style:ie?{display:"flex",flexDirection:"column"}:ku,children:[(0,jr.jsx)(Qn.PaymentElement,{options:{layout:hi},onReady:()=>A(!0),onLoadError:()=>T(),onChange:W=>{W.complete&&H(null)}}),(0,jr.jsx)(Pi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!Y||!B||f||!ie,onClick:()=>{St()},color:c?.variables?.colorPrimary??"#4A49FF",borderRadius:c?.variables?.borderRadius??"8px",style:y?.submitButton,children:f?"Saving\u2026":`Save ${J}`})]})]})}var Na=require("@flopay/js/card-setup"),kr=require("@flopay/shared"),Qe=Qi(require("react"),1);var na=require("@flopay/js/card-setup"),xr=require("@flopay/shared");var pr=require("react/jsx-runtime"),Iu=15,_u=2e3;function Tu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function As(e){return new Promise(t=>setTimeout(t,e))}async function Mu(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,xr.readSetupAdvertisement)(n);if(!(0,xr.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:c}=s,p=c.length>0?`FloPay: this setup session advertises only Stripe methods (${c.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new kr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function xu(e,t,r,n,a){let s=t.vault??null;(0,kr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let c=(0,kr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!c)throw new kr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return c}var Fi=class extends Qe.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 xc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:c="modern-light",containerStyle:p,appearance:y,buttonsStyles:g,loading:E=null,onReady:R,onComplete:_,onDecline:H,onCancel:T,onValidation:Y,onError:B}){let[f]=(0,Qe.useState)(na.readSetupRedirectReturn),[h,ge]=(0,Qe.useState)(null),[S,Me]=(0,Qe.useState)(!1),[A,ie]=(0,Qe.useState)(null),[he,fe]=(0,Qe.useState)(null),[Re,ct]=(0,Qe.useState)(null),[Ke,F]=(0,Qe.useState)(null),[St,et]=(0,Qe.useState)(()=>new Set),Ue=(0,Qe.useRef)(St),ye=(0,Qe.useRef)(null);ye.current=h;let J=(0,Qe.useRef)(!1),W=(0,Qe.useRef)(!1),Fe=(0,Qe.useRef)(!1),dt=(0,Qe.useRef)(!1),We=(0,Qe.useRef)(0),Z=(0,Qe.useRef)(0),L=(0,Qe.useRef)(!1),{vaultTheme:le,surface:j,overlayTheme:Se,appearance:xe,buttonsLayout:Pe}=(0,Qe.useMemo)(()=>xi({theme:c,appearance:y,buttonsStyles:g}),[c,y,g]),Be=(0,Qe.useMemo)(()=>(0,xa.mergeCardSetupSurface)(j,p),[j,p]),M=(0,Qe.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:R,onComplete:_,onDecline:H,onCancel:T,onValidation:Y,onError:B});M.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:R,onComplete:_,onDecline:H,onCancel:T,onValidation:Y,onError:B},(0,Qe.useEffect)(()=>{L.current=!0;let u=We.current+1;return We.current=u,()=>{L.current=!1,Z.current+=1,queueMicrotask(()=>{We.current===u&&(Fe.current||dt.current||(dt.current=!0,(0,Xe.invokeMerchantCallback)(()=>{M.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let nt=(0,Qe.useCallback)((u,C)=>{Fe.current=!0,J.current=!1,F({status:"success",wording:u,message:null}),(async()=>(await As(600),!W.current&&(W.current=!0,(0,Xe.invokeMerchantCallback)(()=>{M.current.onComplete?.({status:"succeeded",sessionId:M.current.sessionId,...C?{paymentMethod:C}:{}})}),L.current&&F(null))))()},[]),je=(0,Qe.useCallback)((u,C)=>{Fe.current=!0,J.current=!1,F({status:"error",wording:u,message:C.message??null}),(0,Xe.invokeMerchantCallback)(()=>{M.current.onDecline?.({status:"declined",sessionId:M.current.sessionId,...C.reason?{reason:C.reason}:{},...C.message?{message:C.message}:{}})}),(async()=>(await As(400),L.current&&F(null)))()},[]),ut=(0,Qe.useCallback)((u,C)=>{J.current?(J.current=!1,F({status:"error",wording:u,message:C.message}),setTimeout(()=>{L.current&&F(null)},400)):F(null),(0,Xe.invokeMerchantCallback)(()=>M.current.onError?.(C))},[]),Ge=(0,Qe.useCallback)(async u=>{let C=Z.current+1;Z.current=C;let Q=()=>!L.current||C!==Z.current;J.current=!0,F({status:"processing",wording:"payment_method",message:null});let ce=new Na.PaymentAPI((0,kr.resolveBillingApiUrl)(M.current.billingApiUrl),{telemetry:M.current.telemetry});try{for(let N=0;N<Iu;N+=1){if((N>0||u.waitFirst)&&await As(_u),Q())return;let w=await ce.getUnifiedCheckoutSession(M.current.sessionId,M.current.nonce);if(Q())return;let qt=w.data.session?.status;if(qt==="complete"){Me(!0),nt("payment_method");return}if(qt==="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(N){if(Q())return;let w=N instanceof kr.FloPayError&&N.code==="payment_method_setup_unverified";ut("payment_method",uo(N,w?{retryable:!0}:{}))}finally{ce.destroy()}},[ut,nt]);(0,Qe.useEffect)(()=>{let u=!0,C=(0,kr.resolveBillingApiUrl)(a),Q=new Na.PaymentAPI(C,{telemetry:s});ge(null),Me(!1),ie(null),fe(null),ct(null);let ce=new Set;return Ue.current=ce,et(ce),Fe.current=!1,dt.current=!1,W.current=!1,(async()=>{try{let{session:N,advertisement:w}=await Mu(Q,r,n);if(!u)return;let qt={advertisement:w,customer:Tu(N),...N.futureUse?{futureUse:N.futureUse}:{},...N.futureUseUnsupported?{futureUseUnsupported:N.futureUseUnsupported}:{}};if(f){if((0,na.clearSetupRedirectParams)(),N.status==="complete"){Me(!0),ge(qt),nt("payment_method");return}f.failed?je("payment_method",{reason:"redirect_failed"}):Ge({waitFirst:!0})}let Ar=w.card?await xu(Q,N,r,n,C):null;if(!u)return;ge(qt),Ar&&(fe(Ar),ie(new Na.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(N){if(!u)return;let w=uo(N);Fe.current=!0,ct(w),(0,Xe.invokeMerchantCallback)(()=>M.current.onError?.(w))}})(),()=>{u=!1,Q.destroy()}},[a,n,f,je,nt,r,s,Ge]),(0,Qe.useEffect)(()=>{if(!A)return;J.current=!1;let u=A.on("submitting",()=>{J.current=!0,F({status:"processing",wording:"card",message:null})}),C=A.on("complete",N=>{nt("card",N.paymentMethod)}),Q=A.on("decline",N=>{je("card",{...N.declineReason?{reason:N.declineReason}:{},...N.message?{message:N.message}:{}})}),ce=A.on("challenge_dismissed",()=>{F(null)});return()=>{u(),C(),Q(),ce()}},[A,je,nt]);let $e=(0,Qe.useCallback)((u,C,Q)=>{if(Q.retryable){ut("payment_method",uo(C,Q));return}if(Ue.current.has(u))return;let ce=new Set(Ue.current);ce.add(u),Ue.current=ce,et(ce);let N=ye.current?.advertisement,w=N?(0,xr.advertisedMethodKeys)(N).some(qt=>!ce.has(qt)):!1;ut("payment_method",uo(C,{code:Q.code,retryable:w}))},[ut]),Rt=(0,Qe.useMemo)(()=>({onSubmitting:()=>{J.current=!0,F({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Ge({waitFirst:!1})},onDeclined:u=>je("payment_method",u),onValidation:u=>{(0,Xe.invokeMerchantCallback)(()=>M.current.onValidation?.(u))},onAbandoned:()=>{J.current=!1,F(null)}}),[je,Ge]),Ot=(0,Qe.useRef)($e);Ot.current=$e;let zt=(0,Qe.useRef)(new Map),Ft=u=>{let C=zt.current.get(u);if(C)return C;let Q=(ce,N)=>Ot.current(u,ce,N);return zt.current.set(u,Q),Q},ue=(0,Qe.useCallback)(u=>{if(Ue.current.has(u))return;let C=new Set(Ue.current);C.add(u),Ue.current=C,et(C);let Q=ye.current?.advertisement;Q&&(0,xr.advertisedMethodKeys)(Q).some(N=>!C.has(N))||ut("payment_method",uo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ut]),pe=(0,Qe.useRef)(ue);pe.current=ue;let X=(0,Qe.useRef)(new Map),Pt=u=>{let C=X.current.get(u);if(C)return C;let Q=()=>pe.current(u);return X.current.set(u,Q),Q},pt=Ke?(0,pr.jsx)(tn,{status:Ke.status,errorMessage:Ke.message,...(0,xr.setupOverlayLabels)(Ke.wording),successNote:null,...Se?{theme:Se}:{}}):null;if(Re)return(0,pr.jsx)("div",{role:"alert",children:Re.message});if(!h||S)return(0,pr.jsxs)(pr.Fragment,{children:[pt,h?null:E]});let{advertisement:V,customer:rt,futureUse:wt,futureUseUnsupported:ke}=h,v=(0,kr.resolveBillingApiUrl)(a),U=s===void 0?{}:{telemetry:s},ne=V.stripe.filter(({method:u})=>!St.has(u)),Ae=St.has("paypal")?null:V.paypal,Dt=!!(V.card&&A&&he?.html),ot=({method:u,publishableKey:C,currency:Q})=>(0,pr.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,pr.jsx)(Fi,{onFailed:Ft(u),children:(0,pr.jsx)(Qe.Suspense,{fallback:null,children:(0,pr.jsx)(e,{method:u,category:(0,xr.stripeMethodCategory)(u),publishableKey:C,currency:Q,...wt?{futureUse:wt}:{},...ke?{futureUseUnsupported:ke}:{},sessionId:r,nonce:n,billingApiUrl:v,...U,...xe?{appearance:xe}:{},...Pe?{buttonsLayout:Pe}:{},...typeof c=="string"?{themeId:c}:{},...Rt,onFailed:Ft(u),onUnavailable:Pt(u)})})})},u),De=ne.filter(({method:u})=>(0,xr.stripeMethodCategory)(u)==="wallet"),Oe=ne.filter(({method:u})=>(0,xr.stripeMethodCategory)(u)!=="wallet"),_t=ne.length>0||Ae!==null;return(0,pr.jsxs)(pr.Fragment,{children:[pt,_t?(0,pr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[De.map(ot),Ae?(0,pr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,pr.jsx)(Fi,{onFailed:Ft("paypal"),children:(0,pr.jsx)(Qe.Suspense,{fallback:null,children:(0,pr.jsx)(t,{clientId:Ae.clientId,...Ae.environment?{environment:Ae.environment}:{},...V.currency?{currency:V.currency}:{},sessionId:r,nonce:n,billingApiUrl:v,customer:rt,...U,...Rt,onFailed:Ft("paypal"),onUnavailable:Pt("paypal")})})})}):null,Oe.map(ot)]}):null,Dt&&_t?(0,pr.jsx)(vi,{label:"or add a card"}):null,Dt&&A&&he?.html?(0,pr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,pr.jsx)(ho,{capture:A,html:he.html,messageToken:he.messageToken,expectedOrigin:he.expectedOrigin,verificationRequired:he.verificationRequired,theme:le,containerStyle:Be,onReady:()=>{(0,Xe.invokeMerchantCallback)(()=>M.current.onReady?.())},onValidation:u=>{(0,Xe.invokeMerchantCallback)(()=>M.current.onValidation?.(u))},onError:u=>{u&&ut("card",uo(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Fc=require("react/jsx-runtime"),Au={StripeSetupMethod:Mc,PayPalSetupMethod:Rc};function Ac(e){return(0,Fc.jsx)(xc,{...e,branches:Au})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,B.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&F(na),r&&(n||a)&&F(na),r&&(0,B.jsx)("button",{type:"button",onClick:()=>{e?.("card"),I(!0)},style:{width:"100%",...y,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:T.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,...T.cardButton},onMouseDown:h=>{h.currentTarget.style.transform="scale(0.985)"},onMouseUp:h=>{h.currentTarget.style.transform="scale(1)"},children:(0,B.jsx)(jo,{content:m})}),(0,B.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var bn=require("react/jsx-runtime"),gu=44;function vc(e){return new Promise(t=>setTimeout(t,e))}function hu(e,t){return e instanceof Sn.FloPayError?e:new Sn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Pu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function vu(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 Cc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:s,products:c,items:p,subscriptions:m,account:g,successUrl:_,cancelUrl:E,couponCodes:I,tagsData:H,utmMetadata:T,billingApiUrl:Y,locale:F,theme:y,appearance:h,buttonsTheme:ge,buttonsStyles:w,onSuccess:Te,onError:x,onDecline:ie,children:he,disabled:fe=!1,type:ke="button",style:mt,...Je}){let A=(0,Ct.useMemo)(()=>(0,Sn.resolveBillingApiUrl)(Y),[Y]),kt=(0,Ct.useMemo)(()=>vu({createSession:r,clientId:s,products:c,items:p,subscriptions:m,account:g,successUrl:_,cancelUrl:E,couponCodes:I,tagsData:H,utmMetadata:T}),[g,E,s,I,r,c,p,m,_,H,T]),[tt,Ve]=(0,Ct.useState)(!1),[me,K]=(0,Ct.useState)(null),[W,Fe]=(0,Ct.useState)(null),[lt,He]=(0,Ct.useState)(!1),[J,D]=(0,Ct.useState)(null),[se,O]=(0,Ct.useState)(null),be=(0,Ct.useRef)(!0),Me=(0,Ct.useRef)(null),Pe=(0,Ct.useRef)(se),Be=(0,Ct.useRef)(Te),M=(0,Ct.useRef)(x),at=(0,Ct.useRef)(ie),Ke=(0,Ct.useCallback)(v=>ui(Me,async q=>{try{return await v(q)}catch(oe){throw q.aborted?Zo(oe):oe}}),[]);(0,Ct.useEffect)(()=>{Pe.current=se},[se]),(0,Ct.useEffect)(()=>{Be.current=Te},[Te]),(0,Ct.useEffect)(()=>{M.current=x},[x]),(0,Ct.useEffect)(()=>{at.current=ie},[ie]),(0,Ct.useEffect)(()=>(be.current=!0,()=>{be.current=!1,Me.current?.abort()}),[]),(0,Ct.useEffect)(()=>{if(typeof window>"u")return;let v=q=>{q.key==="Escape"&&O(null)};return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[]);let yt=(0,Ct.useCallback)((v,q=_a)=>{at.current?.(br(q,v,{code:v.code,declineCode:v.declineCode}))},[]),Ze=(0,Ct.useCallback)(async v=>{be.current&&(Fe(null),He(v.result.status==="authorized"),K("success"),await vc(600),be.current&&(0,Qe.invokeMerchantCallback)(()=>Be.current?.(v)))},[]),Ge=(0,Ct.useCallback)(async(v,q)=>{be.current&&(M.current?.(v),q?.emitDecline&&yt(v,q.method),Fe(v.message),He(!1),K("error"),await vc(400))},[yt]),_t=(0,Ct.useCallback)(async(v,q,oe)=>{let xe=v.data.session??null;if(!xe)throw mo(new Sn.FloPayError("No session data returned","api_error"),q);let Lt=xe.clientSecret||t;if(to(xe)){await Ze({result:eo(xe,q),session:xe,sessionId:xe.id||q,autoCompleted:!1});return}if(xe.status==="expired")throw mo(ei(xe),xe.id||q);try{if(v.autoProcessingPending){let De=v.autoProcessingPending,Oe=new xi.PaymentAPI(A),Tt=await Ke(Q=>Oe.waitForCheckoutSessionCompletion(De.sessionId,{initialDelayMs:De.retryAfterMs,nonce:Lt,statusUrl:De.statusUrl,signal:Q})),u=yo(Tt,xe),C=Tt.autoProcessingError?.type==="3ds_required"&&Tt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Tt.autoProcessingError.nextActionRedirectUrl}:null;if(C&&q&&Lt){let Q=Ia(A,q,xe),le=await Ke(L=>Qo(C,{billingApiUrl:A,sessionId:q,nonce:Lt,session:xe,signal:L,telemetry:!0,...Q.telemetry?{challengeTelemetry:Q.telemetry}:{}})).finally(Q.release);await Ze({result:le,session:xe,sessionId:xe.id||q,autoCompleted:!1});return}if(Tt.autoProcessingError)throw Hn(Tt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Tt.autoProcessingError.checkoutMethod});if(!to(u))throw $o(u);await Ze({result:eo(u,q),session:u,sessionId:u.id||q,autoCompleted:!1});return}if(v.autoProcessingError){let De=v.autoProcessingError.nextActionRedirectUrl;if(v.autoProcessingError.type==="3ds_required"&&De&&q&&Lt){let Oe=await Ke(Q=>Kl({billingApiUrl:A,sessionId:q,nonce:Lt,nextActionRedirectUrl:De,signal:Q}));if(Oe.status==="declined")throw Hn({type:Oe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Oe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:v.autoProcessingError.checkoutMethod});let u=await new xi.PaymentAPI(A).waitForCheckoutSessionCompletion(q,{initialDelayMs:0,nonce:Lt}),C=yo(u,xe);if(!to(C))throw Hn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:v.autoProcessingError.checkoutMethod});await Ze({result:eo(C,q),session:C,sessionId:C.id||q,autoCompleted:!1});return}throw Hn(v.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:v.autoProcessingError.checkoutMethod})}if(oe?.fromCreateSession&&v.autoProcessingAttempted===!0)throw Hn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let it=await ea({billingApiUrl:A,sessionId:q??xe.id,session:xe,nonce:Lt});if(it.type==="next_action_required"&&Lt){let De=q??xe.id,Oe=Ia(A,De,xe),Tt=await Ke(u=>Qo(it,{billingApiUrl:A,sessionId:De,nonce:Lt,session:xe,signal:u,telemetry:!0,...Oe.telemetry?{challengeTelemetry:Oe.telemetry}:{}})).finally(Oe.release);await Ze({result:Tt,session:xe,sessionId:xe.id||De,autoCompleted:!1});return}if(it.type!=="success")throw Hn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ze({result:it.result,session:xe,sessionId:xe.id||q,autoCompleted:!1})}catch(it){let De=xe.id||q,Oe=mo(Ta(it),De);if(Oe.code==="three_ds_aborted")return;if(Oe.code==="checkout_processing_timeout"){if(!be.current)return;D(Oe.message),(0,Qe.invokeMerchantCallback)(()=>M.current?.(Oe));return}await Ge(Oe,{emitDecline:!0,method:Oe.checkoutMethod??_a}),Pu(Oe,De)&&De&&be.current&&O({sessionId:De,errorMessage:Oe.message,nonce:Lt||void 0,payPalOrderId:Oe.orderId})}},[t,A,Ke,Ge,Ze]),Ut=(0,Ct.useCallback)(async v=>{if(Je.onClick?.(v),!(v.defaultPrevented||fe||tt)){if(O(null),D(null),e&&kt){let q=new Sn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Ge(q),be.current&&(K(null),Fe(null));return}if(!e&&!kt){let q=new Sn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Ge(q),be.current&&(K(null),Fe(null));return}Ve(!0),Fe(null),He(!1),K("processing");try{let q=new xi.PaymentAPI(A);if(e){let oe=await q.getUnifiedCheckoutSession(e,t);await _t(oe,e);return}try{let oe=await q.createAndFetchSession({...kt});await _t(oe,oe.data.session?.id??null,{fromCreateSession:!0})}catch(oe){if(ti(oe)==="session_auto_completed"){await Ze({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw oe}}catch(q){await Ge(mo(hu(q,"Automatic payment failed. Please try again."),e))}finally{be.current&&(K(null),Fe(null),Ve(!1))}}},[Je.onClick,kt,fe,tt,t,_t,A,e,Ge,Ze]),qt=(0,Ct.useCallback)(v=>{let q=Pe.current;O(null),Be.current?.({result:v,session:null,sessionId:q?.sessionId??null,autoCompleted:!1})},[]),Ft=(0,Ct.useCallback)(v=>{M.current?.(v)},[]),de=(0,Ct.useCallback)(v=>{at.current?.(v)},[]),ue=(0,Ct.useMemo)(()=>(0,Sn.resolveTheme)(y),[y]),X=(0,Ct.useMemo)(()=>{let v=ue?.buttonsLayout??(0,Sn.resolveButtonsLayoutTheme)(ge);return w?{...v,...w,cardButton:{...v.cardButton,...w.cardButton}}:v},[ue,ge,w]),bt=(0,Ct.useMemo)(()=>{let v=ue?.appearance;return h?v?{...v,...h,variables:{...v.variables,...h.variables}}:h:v},[h,ue]),ft=bt?.variables,V=ft?.colorPrimary??"#4A49FF",rt=ft?.colorPrimaryHover??(0,Ss.darkenHex)(V,.12),Rt=ft?.borderRadius??"8px";return(0,bn.jsxs)(bn.Fragment,{children:[(0,bn.jsx)("button",{...Je,type:ke,onClick:Ut,disabled:fe||tt,"aria-busy":tt,style:{width:"100%",...he===void 0?{boxSizing:"border-box",height:gu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...X.cardButton,...bs({themeBundle:ue,resolvedPrimaryColor:V,resolvedBorderRadius:Rt,submitButtonStyle:X.submitButton,explicitPrimaryColor:ft?.colorPrimary}),fontSize:X.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:fe||tt?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:fe||tt?.6:1,...mt},onMouseEnter:v=>{Je.onMouseEnter?.(v),!v.defaultPrevented&&!fe&&!tt&&(ue||ft?.colorPrimary)&&(v.currentTarget.style.backgroundColor=rt)},onMouseLeave:v=>{Je.onMouseLeave?.(v),!v.defaultPrevented&&(ue||ft?.colorPrimary)&&(v.currentTarget.style.backgroundColor=V)},onMouseDown:v=>{Je.onMouseDown?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(0.985)")},onMouseUp:v=>{Je.onMouseUp?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(1)")},children:(0,bn.jsx)(jo,{content:he})}),J&&(0,bn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:J}),me&&(0,bn.jsx)(rn,{status:me,errorMessage:W,authorized:lt}),se&&(0,bn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:v=>{v.target===v.currentTarget&&O(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,bn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,bn.jsx)(Mi,{sessionId:se.sessionId,nonce:se.nonce,checkoutMode:"full",billingApiUrl:A,locale:F,theme:y,...bt?{appearance:bt}:{},buttonsTheme:ge,buttonsStyles:w,initialErrorMessage:se.errorMessage,initialPayPalOrderId:se.payPalOrderId,cardTitleContent:null,onComplete:qt,onError:Ft,onDecline:de})})})]})}var Fi=require("@flopay/js/card-setup"),Hr=require("@flopay/shared"),Kt=require("react");var Ms=require("@flopay/shared"),Cu=require("@flopay/shared");function Ai(e){let t=(0,Ms.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Gn=require("react/jsx-runtime"),Na=class extends Hr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function so(e,t={}){let r=e instanceof Hr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new Na(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 bc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:c,buttonsStyles:p,loading:m=null,onReady:g,onComplete:_,onDecline:E,onCancel:I,onValidation:H,onError:T}){let[Y,F]=(0,Kt.useState)(null),[y,h]=(0,Kt.useState)(null),[ge,w]=(0,Kt.useState)(null),[Te,x]=(0,Kt.useState)(null),[ie,he]=(0,Kt.useState)(null),fe=(0,Kt.useRef)(!1),ke=(0,Kt.useRef)(!1),{vaultTheme:mt,surface:Je,overlayTheme:A}=(0,Kt.useMemo)(()=>Ai({theme:a,appearance:c,buttonsStyles:p}),[a,c,p]),kt=(0,Kt.useMemo)(()=>(0,Aa.mergeCardSetupSurface)(Je,s),[Je,s]),tt=(0,Kt.useRef)(g),Ve=(0,Kt.useRef)(T),me=(0,Kt.useRef)(_),K=(0,Kt.useRef)(E),W=(0,Kt.useRef)(I),Fe=(0,Kt.useRef)(H),lt=(0,Kt.useRef)(!1),He=(0,Kt.useRef)(!1),J=(0,Kt.useRef)(0);return tt.current=g,Ve.current=T,me.current=_,K.current=E,W.current=I,Fe.current=H,(0,Kt.useEffect)(()=>{let D=J.current+1;return J.current=D,()=>{queueMicrotask(()=>{J.current===D&&(lt.current||He.current||(He.current=!0,(0,Qe.invokeMerchantCallback)(()=>{W.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Kt.useEffect)(()=>{let D=!0,se=(0,Hr.resolveBillingApiUrl)(r),O=new Fi.PaymentAPI(se,{telemetry:n});return F(null),h(null),w(null),lt.current=!1,He.current=!1,(async()=>{try{if(!e.trim())throw new Hr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Hr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let be=await O.getUnifiedCheckoutSession(e,t);if(!D)return;let Me=be.data.session;if(!Me||!(0,Hr.isCardSetupCheckoutSession)(Me))throw new Hr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Pe=Me.vault;(0,Hr.isMountableVaultBlock)(Pe)||(Pe=await O.getVaultCapture(e,t));let Be=(0,Hr.resolveVaultMountOptions)(Pe,{billingApiUrl:se,sessionId:e,nonce:t});if(!Be)throw new Hr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!D)return;h(Be),F(new Fi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(be){if(!D)return;let Me=so(be);lt.current=!0,w(Me),(0,Qe.invokeMerchantCallback)(()=>Ve.current?.(Me))}})(),()=>{D=!1,O.destroy()}},[r,t,e,n]),(0,Kt.useEffect)(()=>{if(!Y)return;let D=!1;ke.current=!1,fe.current=!1;let se=Y.on("submitting",()=>{fe.current=!0,he(null),x("processing")}),O=Y.on("complete",Pe=>{lt.current=!0,fe.current=!1,x("success"),(async()=>(await new Promise(Be=>setTimeout(Be,600)),!ke.current&&(ke.current=!0,(0,Qe.invokeMerchantCallback)(()=>{me.current?.({status:"succeeded",sessionId:e,...Pe.paymentMethod?{paymentMethod:Pe.paymentMethod}:{}})}),D||x(null))))()}),be=Y.on("decline",Pe=>{lt.current=!0,fe.current=!1,he(Pe.message??null),x("error"),(0,Qe.invokeMerchantCallback)(()=>{K.current?.({status:"declined",sessionId:e,...Pe.declineReason?{reason:Pe.declineReason}:{},...Pe.message?{message:Pe.message}:{}})}),(async()=>(await new Promise(Be=>setTimeout(Be,400)),D||x(null)))()}),Me=Y.on("challenge_dismissed",()=>{x(null)});return()=>{D=!0,se(),O(),be(),Me()}},[Y,e]),ge?(0,Gn.jsx)("div",{role:"alert",children:ge.message}):!Y||!y?.html?(0,Gn.jsx)(Gn.Fragment,{children:m}):(0,Gn.jsxs)(Gn.Fragment,{children:[Te&&(0,Gn.jsx)(rn,{status:Te,errorMessage:ie,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...A?{theme:A}:{}}),(0,Gn.jsx)(fo,{capture:Y,html:y.html,messageToken:y.messageToken,expectedOrigin:y.expectedOrigin,verificationRequired:y.verificationRequired,theme:mt,containerStyle:kt,onReady:()=>{(0,Qe.invokeMerchantCallback)(()=>tt.current?.())},onValidation:D=>{(0,Qe.invokeMerchantCallback)(()=>Fe.current?.(D))},onError:D=>{if(!D)return;fe.current&&(fe.current=!1,he(D),x("error"),setTimeout(()=>x(null),400));let se=so(new Error(D),{code:"card_setup_widget_failed",retryable:!0});(0,Qe.invokeMerchantCallback)(()=>Ve.current?.(se))}})]})}var Sc=require("@flopay/js/card-setup"),wn=require("@flopay/shared"),wc=require("@paypal/paypal-js"),Io=require("react");var Rc=require("react/jsx-runtime");function kc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:c,customer:{userId:p,email:m},onSubmitting:g,onConfirmed:_,onFailed:E,onAbandoned:I}){let H=(0,Io.useRef)(null),T=(0,Io.useRef)({onSubmitting:g,onConfirmed:_,onFailed:E,onAbandoned:I});T.current={onSubmitting:g,onConfirmed:_,onFailed:E,onAbandoned:I};let[Y]=(0,Io.useState)(()=>(0,Wn.detectPayPalEnvironment)().inAppBrowser);return(0,Io.useEffect)(()=>{let F=!0,y,h=new Sc.PaymentAPI(s,{telemetry:c}),ge={userId:p,email:m};return(async()=>{try{let w=await(0,wc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Te=H.current;if(!F||!Te)return;if(!w?.Buttons)throw new wn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let x=w.Buttons({createVaultSetupToken:async()=>{T.current.onSubmitting();let ie=await h.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:wn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,wn.isSettledSessionIntent)(ie))throw(0,wn.settledSessionIntentError)(n);if(ie.provider!=="paypal"||ie.providerObjectType!=="setup_token")throw new wn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ie.providerObjectId},onApprove:async ie=>{let he=ie.vaultSetupToken;if(!he)throw new wn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let fe=await h.processPayment(ge.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:he,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:wn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:ge});if(!fe.ok)throw new wn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:fe.status});F&&T.current.onConfirmed()},onCancel:()=>{F&&T.current.onAbandoned()},onError:ie=>{if(!F)return;let{popupBlocked:he}=(0,we.classifyExternalMethodFailure)(ie,{inAppBrowser:Y,handoffObserved:!1});T.current.onFailed(he?new Error((0,we.buildExternalMethodRecoveryMessage)("PayPal",!0,Y)):ie,{code:he?"popup_blocked":"paypal_setup_failed",retryable:!0})}});y=()=>x.close(),await x.render(Te)}catch(w){if(!F)return;T.current.onFailed(w,{code:"paypal_unavailable",retryable:!0})}})(),()=>{F=!1,y?.().catch(()=>{}),h.destroy()}},[s,e,r,m,t,Y,a,n,c,p]),(0,Rc.jsx)("div",{ref:H,"data-flopay-paypal-setup":""})}var _c=require("@flopay/js/card-setup"),kn=require("@flopay/shared"),Yn=require("@stripe/react-stripe-js"),Ic=require("@stripe/stripe-js"),Kr=require("react");var qr=require("react/jsx-runtime"),Tc={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"}},xs=new Map;function bu(e){let t=xs.get(e);if(t)return t;let r=(0,Ic.loadStripe)(e).catch(n=>{throw xs.delete(e),n});return xs.set(e,r),r}function Su(e){return e?(0,kn.toStripeAppearance)(e):void 0}function wu(e){return(0,we.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Ec(e){return e==="paypal"?"PayPal":(0,kn.getStripeMethodDisplayName)(e)}function ku(){return typeof window>"u"?"":window.location.href}var Ru={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function Mc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:c}=e,[p]=(0,Kr.useState)(()=>bu(t)),m=(0,Kr.useMemo)(()=>{let g=Su(c),_=(0,kn.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:Tc[r]?.types??[r],..._?{setupFutureUsage:_}:{},...g?{appearance:g}:{}}},[c,n,a,s,r]);return(0,qr.jsx)(Yn.Elements,{stripe:p,options:m,children:(0,qr.jsx)(Eu,{...e})})}function Eu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:c,themeId:p,buttonsLayout:m,onSubmitting:g,onConfirmed:_,onDeclined:E,onFailed:I,onValidation:H,onUnavailable:T}){let Y=(0,Yn.useStripe)(),F=(0,Yn.useElements)(),[y,h]=(0,Kr.useState)(!1),[ge,w]=(0,Kr.useState)("loading"),[Te,x]=(0,Kr.useState)(!1),[ie,he]=(0,Kr.useState)(!1),fe=(0,Kr.useRef)(!1),[ke]=(0,Kr.useState)(()=>(0,Wn.detectPayPalEnvironment)()),[mt,Je]=(0,Kr.useState)(!1),A=(0,Kr.useCallback)((W,Fe)=>{if((0,we.classifyExternalMethodFailure)(W,{inAppBrowser:ke.inAppBrowser,handoffObserved:!1}).popupBlocked){Je(!0),I(new Error((0,we.buildExternalMethodRecoveryMessage)(Ec(e),!0,ke.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}I(Fe.message===void 0?W:new Error(Fe.message),{code:Fe.code,retryable:!0})},[ke.inAppBrowser,e,I]),kt=(0,Kr.useCallback)(async W=>{let Fe=!1,lt=!1,He=()=>{!W||Fe||lt||(lt=!0,W.paymentFailed({reason:"fail"}))};if(!Y||!F||fe.current){He();return}fe.current=!0,h(!0);try{let J=await F.submit();if(J.error){He(),H(J.error.message??null);return}g();let D=await new _c.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,kn.isSettledSessionIntent)(D))throw(0,kn.settledSessionIntentError)(r);if(D.provider!=="stripe"||D.intentKind!=="setup")throw new kn.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Fe=!0;let se=await Y.confirmSetup({elements:F,clientSecret:D.clientSecret,confirmParams:{return_url:ku()},redirect:"if_required"});if(se.error){wu(se.error)?E({...se.error.decline_code||se.error.code?{reason:se.error.decline_code??se.error.code}:{},...se.error.message?{message:se.error.message}:{}}):A(se.error,{code:"payment_method_setup_provider_failed",message:se.error.message??"The payment method could not be saved."});return}_()}catch(J){He(),A(J,{code:"payment_method_setup_failed"})}finally{fe.current=!1,h(!1)}},[a,t,F,e,n,_,E,g,H,A,r,Y,s]),tt=Tc[e]?.wallet,Ve=tt==="paypal"&&(0,$n.resolveStripePayPalPresentation)(ke,"auto",mt?"blocked":ke.popupCapability)==="redirect",me=c?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&tt&&!Ve)return(0,qr.jsxs)(qr.Fragment,{children:[(0,qr.jsx)(ra,{}),(0,qr.jsx)(xa,{state:ge,borderRadius:me,children:(0,qr.jsx)(Yn.ExpressCheckoutElement,{options:{...hi,paymentMethods:gi([e])},onReady:W=>{let Fe=Ma(W,[tt]);w(Fe),Fe==="unavailable"&&T()},onLoadError:()=>{w("load_error"),T()},onConfirm:W=>{kt(W)}})})]});let K=Ec(e);return(0,qr.jsxs)(qr.Fragment,{children:[Te?(0,qr.jsx)(fi,{method:e,themeId:p,hasNextStep:!0,highlighted:ie,disabled:y,onClick:()=>he(W=>!W),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:me}):null,(0,qr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ie,style:ie?{display:"flex",flexDirection:"column"}:Ru,children:[(0,qr.jsx)(Yn.PaymentElement,{options:{layout:Pi},onReady:()=>x(!0),onLoadError:()=>T(),onChange:W=>{W.complete&&H(null)}}),(0,qr.jsx)(vi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!Y||!F||y||!ie,onClick:()=>{kt()},color:c?.variables?.colorPrimary??"#4A49FF",borderRadius:c?.variables?.borderRadius??"8px",style:m?.submitButton,children:y?"Saving\u2026":`Save ${K}`})]})]})}var Ua=require("@flopay/js/card-setup"),wr=require("@flopay/shared"),et=Qi(require("react"),1);var oa=require("@flopay/js/card-setup"),Tr=require("@flopay/shared");var cr=require("react/jsx-runtime"),_u=15,Iu=2e3;function Tu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function As(e){return new Promise(t=>setTimeout(t,e))}async function Mu(e,t,r){if(!t.trim())throw new wr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new wr.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,wr.isCardSetupCheckoutSession)(a))throw new wr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Tr.readSetupAdvertisement)(n);if(!(0,Tr.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:c}=s,p=c.length>0?`FloPay: this setup session advertises only Stripe methods (${c.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new wr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function xu(e,t,r,n,a){let s=t.vault??null;(0,wr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let c=(0,wr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!c)throw new wr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return c}var Bi=class extends et.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 xc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:c="modern-light",containerStyle:p,appearance:m,buttonsStyles:g,loading:_=null,onReady:E,onComplete:I,onDecline:H,onCancel:T,onValidation:Y,onError:F}){let[y]=(0,et.useState)(oa.readSetupRedirectReturn),[h,ge]=(0,et.useState)(null),[w,Te]=(0,et.useState)(!1),[x,ie]=(0,et.useState)(null),[he,fe]=(0,et.useState)(null),[ke,mt]=(0,et.useState)(null),[Je,A]=(0,et.useState)(null),[kt,tt]=(0,et.useState)(()=>new Set),Ve=(0,et.useRef)(kt),me=(0,et.useRef)(null);me.current=h;let K=(0,et.useRef)(!1),W=(0,et.useRef)(!1),Fe=(0,et.useRef)(!1),lt=(0,et.useRef)(!1),He=(0,et.useRef)(0),J=(0,et.useRef)(0),D=(0,et.useRef)(!1),{vaultTheme:se,surface:O,overlayTheme:be,appearance:Me,buttonsLayout:Pe}=(0,et.useMemo)(()=>Ai({theme:c,appearance:m,buttonsStyles:g}),[c,m,g]),Be=(0,et.useMemo)(()=>(0,Aa.mergeCardSetupSurface)(O,p),[O,p]),M=(0,et.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:E,onComplete:I,onDecline:H,onCancel:T,onValidation:Y,onError:F});M.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:E,onComplete:I,onDecline:H,onCancel:T,onValidation:Y,onError:F},(0,et.useEffect)(()=>{D.current=!0;let u=He.current+1;return He.current=u,()=>{D.current=!1,J.current+=1,queueMicrotask(()=>{He.current===u&&(Fe.current||lt.current||(lt.current=!0,(0,Qe.invokeMerchantCallback)(()=>{M.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let at=(0,et.useCallback)((u,C)=>{Fe.current=!0,K.current=!1,A({status:"success",wording:u,message:null}),(async()=>(await As(600),!W.current&&(W.current=!0,(0,Qe.invokeMerchantCallback)(()=>{M.current.onComplete?.({status:"succeeded",sessionId:M.current.sessionId,...C?{paymentMethod:C}:{}})}),D.current&&A(null))))()},[]),Ke=(0,et.useCallback)((u,C)=>{Fe.current=!0,K.current=!1,A({status:"error",wording:u,message:C.message??null}),(0,Qe.invokeMerchantCallback)(()=>{M.current.onDecline?.({status:"declined",sessionId:M.current.sessionId,...C.reason?{reason:C.reason}:{},...C.message?{message:C.message}:{}})}),(async()=>(await As(400),D.current&&A(null)))()},[]),yt=(0,et.useCallback)((u,C)=>{K.current?(K.current=!1,A({status:"error",wording:u,message:C.message}),setTimeout(()=>{D.current&&A(null)},400)):A(null),(0,Qe.invokeMerchantCallback)(()=>M.current.onError?.(C))},[]),Ze=(0,et.useCallback)(async u=>{let C=J.current+1;J.current=C;let Q=()=>!D.current||C!==J.current;K.current=!0,A({status:"processing",wording:"payment_method",message:null});let le=new Ua.PaymentAPI((0,wr.resolveBillingApiUrl)(M.current.billingApiUrl),{telemetry:M.current.telemetry});try{for(let L=0;L<_u;L+=1){if((L>0||u.waitFirst)&&await As(Iu),Q())return;let k=await le.getUnifiedCheckoutSession(M.current.sessionId,M.current.nonce);if(Q())return;let jt=k.data.session?.status;if(jt==="complete"){Te(!0),at("payment_method");return}if(jt==="expired")throw new wr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new wr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(L){if(Q())return;let k=L instanceof wr.FloPayError&&L.code==="payment_method_setup_unverified";yt("payment_method",so(L,k?{retryable:!0}:{}))}finally{le.destroy()}},[yt,at]);(0,et.useEffect)(()=>{let u=!0,C=(0,wr.resolveBillingApiUrl)(a),Q=new Ua.PaymentAPI(C,{telemetry:s});ge(null),Te(!1),ie(null),fe(null),mt(null);let le=new Set;return Ve.current=le,tt(le),Fe.current=!1,lt.current=!1,W.current=!1,(async()=>{try{let{session:L,advertisement:k}=await Mu(Q,r,n);if(!u)return;let jt={advertisement:k,customer:Tu(L),...L.futureUse?{futureUse:L.futureUse}:{},...L.futureUseUnsupported?{futureUseUnsupported:L.futureUseUnsupported}:{}};if(y){if((0,oa.clearSetupRedirectParams)(),L.status==="complete"){Te(!0),ge(jt),at("payment_method");return}y.failed?Ke("payment_method",{reason:"redirect_failed"}):Ze({waitFirst:!0})}let Mr=k.card?await xu(Q,L,r,n,C):null;if(!u)return;ge(jt),Mr&&(fe(Mr),ie(new Ua.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(L){if(!u)return;let k=so(L);Fe.current=!0,mt(k),(0,Qe.invokeMerchantCallback)(()=>M.current.onError?.(k))}})(),()=>{u=!1,Q.destroy()}},[a,n,y,Ke,at,r,s,Ze]),(0,et.useEffect)(()=>{if(!x)return;K.current=!1;let u=x.on("submitting",()=>{K.current=!0,A({status:"processing",wording:"card",message:null})}),C=x.on("complete",L=>{at("card",L.paymentMethod)}),Q=x.on("decline",L=>{Ke("card",{...L.declineReason?{reason:L.declineReason}:{},...L.message?{message:L.message}:{}})}),le=x.on("challenge_dismissed",()=>{A(null)});return()=>{u(),C(),Q(),le()}},[x,Ke,at]);let Ge=(0,et.useCallback)((u,C,Q)=>{if(Q.retryable){yt("payment_method",so(C,Q));return}if(Ve.current.has(u))return;let le=new Set(Ve.current);le.add(u),Ve.current=le,tt(le);let L=me.current?.advertisement,k=L?(0,Tr.advertisedMethodKeys)(L).some(jt=>!le.has(jt)):!1;yt("payment_method",so(C,{code:Q.code,retryable:k}))},[yt]),_t=(0,et.useMemo)(()=>({onSubmitting:()=>{K.current=!0,A({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Ze({waitFirst:!1})},onDeclined:u=>Ke("payment_method",u),onValidation:u=>{(0,Qe.invokeMerchantCallback)(()=>M.current.onValidation?.(u))},onAbandoned:()=>{K.current=!1,A(null)}}),[Ke,Ze]),Ut=(0,et.useRef)(Ge);Ut.current=Ge;let qt=(0,et.useRef)(new Map),Ft=u=>{let C=qt.current.get(u);if(C)return C;let Q=(le,L)=>Ut.current(u,le,L);return qt.current.set(u,Q),Q},de=(0,et.useCallback)(u=>{if(Ve.current.has(u))return;let C=new Set(Ve.current);C.add(u),Ve.current=C,tt(C);let Q=me.current?.advertisement;Q&&(0,Tr.advertisedMethodKeys)(Q).some(L=>!C.has(L))||yt("payment_method",so(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[yt]),ue=(0,et.useRef)(de);ue.current=de;let X=(0,et.useRef)(new Map),bt=u=>{let C=X.current.get(u);if(C)return C;let Q=()=>ue.current(u);return X.current.set(u,Q),Q},ft=Je?(0,cr.jsx)(rn,{status:Je.status,errorMessage:Je.message,...(0,Tr.setupOverlayLabels)(Je.wording),successNote:null,...be?{theme:be}:{}}):null;if(ke)return(0,cr.jsx)("div",{role:"alert",children:ke.message});if(!h||w)return(0,cr.jsxs)(cr.Fragment,{children:[ft,h?null:_]});let{advertisement:V,customer:rt,futureUse:Rt,futureUseUnsupported:Re}=h,v=(0,wr.resolveBillingApiUrl)(a),q=s===void 0?{}:{telemetry:s},oe=V.stripe.filter(({method:u})=>!kt.has(u)),xe=kt.has("paypal")?null:V.paypal,Lt=!!(V.card&&x&&he?.html),it=({method:u,publishableKey:C,currency:Q})=>(0,cr.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,cr.jsx)(Bi,{onFailed:Ft(u),children:(0,cr.jsx)(et.Suspense,{fallback:null,children:(0,cr.jsx)(e,{method:u,category:(0,Tr.stripeMethodCategory)(u),publishableKey:C,currency:Q,...Rt?{futureUse:Rt}:{},...Re?{futureUseUnsupported:Re}:{},sessionId:r,nonce:n,billingApiUrl:v,...q,...Me?{appearance:Me}:{},...Pe?{buttonsLayout:Pe}:{},...typeof c=="string"?{themeId:c}:{},..._t,onFailed:Ft(u),onUnavailable:bt(u)})})})},u),De=oe.filter(({method:u})=>(0,Tr.stripeMethodCategory)(u)==="wallet"),Oe=oe.filter(({method:u})=>(0,Tr.stripeMethodCategory)(u)!=="wallet"),Tt=oe.length>0||xe!==null;return(0,cr.jsxs)(cr.Fragment,{children:[ft,Tt?(0,cr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[De.map(it),xe?(0,cr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,cr.jsx)(Bi,{onFailed:Ft("paypal"),children:(0,cr.jsx)(et.Suspense,{fallback:null,children:(0,cr.jsx)(t,{clientId:xe.clientId,...xe.environment?{environment:xe.environment}:{},...V.currency?{currency:V.currency}:{},sessionId:r,nonce:n,billingApiUrl:v,customer:rt,...q,..._t,onFailed:Ft("paypal"),onUnavailable:bt("paypal")})})})}):null,Oe.map(it)]}):null,Lt&&Tt?(0,cr.jsx)(Ci,{label:"or add a card"}):null,Lt&&x&&he?.html?(0,cr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,cr.jsx)(fo,{capture:x,html:he.html,messageToken:he.messageToken,expectedOrigin:he.expectedOrigin,verificationRequired:he.verificationRequired,theme:se,containerStyle:Be,onReady:()=>{(0,Qe.invokeMerchantCallback)(()=>M.current.onReady?.())},onValidation:u=>{(0,Qe.invokeMerchantCallback)(()=>M.current.onValidation?.(u))},onError:u=>{u&&yt("card",so(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Fc=require("react/jsx-runtime"),Au={StripeSetupMethod:Mc,PayPalSetupMethod:kc};function Ac(e){return(0,Fc.jsx)(xc,{...e,branches:Au})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});