@flopay/react 1.14.10 → 1.14.12

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 Jc=Object.create;var Xa=Object.defineProperty;var Zc=Object.getOwnPropertyDescriptor;var Qc=Object.getOwnPropertyNames;var ed=Object.getPrototypeOf,td=Object.prototype.hasOwnProperty;var rd=(e,t)=>{for(var r in t)Xa(e,r,{get:t[r],enumerable:!0})},Cl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Qc(t))!td.call(e,a)&&a!==r&&Xa(e,a,{get:()=>t[a],enumerable:!(n=Zc(t,a))||n.enumerable});return e};var Ji=(e,t,r)=>(r=e!=null?Jc(ed(e)):{},Cl(t||!e||!e.__esModule?Xa(r,"default",{value:e,enumerable:!0}):r,e)),nd=e=>Cl(Xa({},"__esModule",{value:!0}),e);var xu={};rd(xu,{DirectPayPalButton:()=>ba,FloPayAutomaticPaymentButton:()=>Pc,FloPayCardSetup:()=>vc,FloPayCardSetupError:()=>Da,FloPayCheckout:()=>Ii,FloPayPaymentMethodSetup:()=>Mc,FloPayProvider:()=>wa,SplitCardForm:()=>wi,VaultCardFields:()=>go,dropThirdPartyOnlyError:()=>Ac.dropThirdPartyOnlyError,useCheckout:()=>Fl,useFloPay:()=>io,usePayPalFloPay:()=>ei});module.exports=nd(xu);var Ac=require("@flopay/shared");var _i=require("@flopay/js"),Rn=require("@flopay/shared"),Ct=require("react");var Xt=require("react/jsx-runtime");function od(){return(0,Xt.jsxs)(Xt.Fragment,{children:[(0,Xt.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,Xt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Xt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Xt.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,Xt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ad(){return(0,Xt.jsx)(Xt.Fragment,{children:"Go back"})}function id(){return(0,Xt.jsx)(Xt.Fragment,{children:"Secure card checkout"})}function Uo(e){return e!==void 0&&(e===""||e===null||e===!1)}function zo({content:e}){return(0,Xt.jsx)(Xt.Fragment,{children:e===void 0?(0,Xt.jsx)(od,{}):e})}function qo({content:e}){return(0,Xt.jsx)(Xt.Fragment,{children:e===void 0?(0,Xt.jsx)(ad,{}):e})}function fa({content:e}){return(0,Xt.jsx)(Xt.Fragment,{children:e===void 0?(0,Xt.jsx)(id,{}):e})}var Rt=require("@flopay/shared"),xn=require("@flopay/shared"),Wo=require("@flopay/shared"),So=require("@flopay/shared");function Zi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Rt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function sd(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function bl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,Rt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,Rt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function Sl(e,t){if(t&&(!(e instanceof Rt.FloPayError)||e.type==="authentication_error"))return Zi(e);if(!(e instanceof Rt.FloPayError&&sd(e))){if(!t&&!(e instanceof Rt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Rt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Rt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Rt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function jo(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let c={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,Rt.isCardHolderNamePlaceholder)(c.firstName,c.lastName);if(!(0,Rt.isValidEmail)(c.email))return Promise.reject(new Rt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[h,k]of Object.entries(c)){if(p&&h.endsWith("Name")||typeof k!="string")continue;let w=k.trim();w&&(m[h]=w)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function wl(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Qi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Rl(e,t){let r=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],n=r.reduce((s,c)=>s+(c.overrideAmount??c.totalAmount??0),0),a=e.currency??r.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:r.map((s,c)=>({uuid:`synthetic-${s.type??"item"}-${c}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??a,metadata:s.metadata??null}))}}function es(e,t){return t?{...e,...t}:e}function kr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,s=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,c=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...s?{declineCode:s}:{},...c?{sessionId:c}:{}}}var kl=new WeakMap;function El(e,t){return typeof e=="object"&&e!==null&&kl.set(e,t?{sessionId:t}:{}),e}function Il(e){return typeof e=="object"&&e!==null?kl.get(e):void 0}function yo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function no(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function oo(e){return e?.status==="authorized"||e?.status==="complete"}function fo(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function _l(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ja(e){let t=_l(e);return new Rt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Za(e){return e instanceof Rt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Vo(e){return _l(e)?new Rt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Rt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Rt.FloPayError(Rt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ga(e,t){return e==="processing"||(0,Rt.isMoneySettledOutcome)(e,t)}function Tl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Ml(e,t){let r=e;if((0,Rt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:c}=await r.retrieveSetupIntent(t);if(c)throw new Rt.FloPayError(c.message??"Failed to retrieve setup intent.","api_error",{...c.code?{code:c.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new Rt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var ld=["apple_pay","google_pay"];function xl(e,t="automatic",r){let n=(0,Rt.resolveSetupFutureUsage)(r,ld,"wallet");return{...(0,Rt.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var cd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ts(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:cd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function ha(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var co=require("@flopay/js"),De=require("@flopay/shared"),v=Ji(require("react"),1);var rs=require("react"),Pn=(0,rs.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),An=(0,rs.createContext)({session:null,loading:!1,error:null});var ii=require("@flopay/js"),ze=require("@flopay/shared"),Nl=require("@paypal/paypal-js"),R=require("react");var Qa=require("@flopay/shared"),Fn=require("react"),vn=require("@flopay/shared"),ao=require("react/jsx-runtime");function $o(){let[e,t]=(0,Fn.useState)(null),r=(0,Fn.useRef)(null),n=(0,Fn.useRef)(0),a=(0,Fn.useCallback)((c,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:c,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,Fn.useCallback)(c=>{let p=r.current;r.current=null,t(null),p?.(c)},[]);return(0,Fn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function Ho({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[c,p]=(0,Fn.useState)(e.email?.trim()??""),m=(0,Qa.isValidEmail)(c.trim());return(0,ao.jsxs)("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,ao.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,ao.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,ao.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:c,onChange:h=>p(h.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,ao.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,ao.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,ao.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,Qa.compactBuyerIdentity)({...e,email:c.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Se=require("@flopay/shared");var Al=require("@flopay/shared"),Pa=require("react");function io(){return(0,Pa.useContext)(Pn).flopay}function ei(){return(0,Pa.useContext)(Pn).paypalFlopay??null}function Fl(){return(0,Pa.useContext)(An)}function Bl(){return(0,Pa.useContext)(Pn).billingApiUrl||(0,Al.resolveBillingApiUrl)()}var dd=require("@flopay/shared"),$n=require("@flopay/shared"),Hn=require("@flopay/shared");var Ko=require("@flopay/shared"),Ro=require("react");var ti=require("react"),wo=typeof window>"u"?ti.useEffect:ti.useLayoutEffect;var ns=require("@flopay/shared");function Go(e,t){let r=(0,Ro.useRef)(e);r.current=e;let n=(0,Ro.useRef)(new Set),a=(0,Ro.useRef)(t),s=(0,Ro.useRef)(t);return wo(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Ro.useCallback)(c=>{if(s.current!==t)return;let p=(0,Ko.projectFloInstrument)(c);if(p){if(Ko.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,Ko.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ye=require("@flopay/shared");var Dl=require("react"),va=(0,Dl.createContext)(null);function ri(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ni="provider.callback.ignored";function oi(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var ud=Symbol.for("@flopay/js.telemetry.bridge.v1"),pd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function md(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function yd(e){let t=md(),r=(a,s)=>a?a.bind(e):s,n=r(e.now,t.now);return{error:r(e.error,t.error),log:r(e.log,t.log),performance:r(e.performance,t.performance),terminal:r(e.terminal,t.terminal),now:n,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,n()-a),setCheckoutContext:r(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:r(e.beginCheckout,t.beginCheckout),disable:r(e.disable,t.disable),subscribe:r(e.subscribe,t.subscribe),flush:r(e.flush,t.flush),destroy:r(e.destroy,t.destroy)}}function ai(e){let t=globalThis[pd];return yd(t?.(e)??{})}function Er(e){if(e)return e[ud]}var Pr=require("react");function Ca(e,t){let r=(0,Pr.useRef)(0),n=(0,Pr.useRef)(null),a=(0,Pr.useRef)(null),s=(0,Pr.useRef)(e),c=(0,Pr.useRef)(t?.onHandoffObserved),p=(0,Pr.useRef)(t?.defersMissingTerminal),m=(0,Pr.useRef)(t?.onMissingTerminalDeferred);(0,Pr.useEffect)(()=>{s.current=e,c.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let h=(0,Pr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),k=(0,Pr.useCallback)(f=>{h();let P=r.current+1;return r.current=P,n.current=null,a.current={generation:P,method:f,timer:null,yieldedControl:!1},P},[h]),w=(0,Pr.useCallback)(f=>{let P=a.current;return f!==void 0&&P?.generation!==f?!1:(h(P),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[h]),I=(0,Pr.useCallback)(f=>{let P=a.current,me=f??P?.generation??r.current;(f===void 0||P?.generation===f)&&(h(P),a.current=null),n.current=me},[h]),G=(0,Pr.useCallback)(f=>n.current===(f??r.current),[]),_=(0,Pr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),Z=(0,Pr.useCallback)(()=>{let f=a.current;f&&(h(f),!f.yieldedControl&&(f.yieldedControl=!0,c.current?.(f.method)))},[h]),A=(0,Pr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(h(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(p.current?.(f.method)){m.current?.(f.method,f.generation);return}a.current=null,n.current=f.generation,s.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},Se.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[h]);return(0,Pr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?A():Z()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",Z),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",Z),window.removeEventListener("focus",A),h()}},[h,Z,A]),{startAttempt:k,finishAttempt:w,invalidateAttempt:I,isAttemptInvalidated:G,isAttemptCurrent:_,generationRef:r}}var Cn=require("react/jsx-runtime"),si=45,fd=1e3,gd=11e3,Ol="paypal_intent_settled",hd={width:"100%",minHeight:si,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},Pd={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function vd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Pd[e.kind]??null}}function Ll(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,Se.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function Cd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Ul({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:c,environment:p,currency:m,isSubscription:h,providerObjectType:k,approvalPresentation:w,onTokenizedBody:I,onComplete:G,onErrorChange:_,onDecline:Z,onCancel:A,onTechnicalFailure:f,isProcessing:P=!1,onLoadStateChange:me,onInitializationStateChange:S,allowAutomaticRetry:Te=!0,onButtonClick:T,runBeforeButtonClick:ae,session:ye,existingOrderId:pe,telemetry:we,telemetryContext:dt,onInstrument:Ke,debug:B=!1}){let kt=io(),Je=Go(Ke,e),Le=(0,R.useMemo)(()=>{if(kt)return null;let re=ai({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:ze.SDK_VERSION,enabled:we!==!1});return re.setCheckoutContext(dt??{}),re.beginCheckout(dt??{}),re},[r,kt,we,dt?.checkoutMode,dt?.layout]),de=(0,R.useMemo)(()=>Er(kt),[kt]);(0,R.useEffect)(()=>()=>{Le&&Le.flush().catch(()=>{}).finally(()=>Le.destroy())},[Le]);let ee=(0,R.useMemo)(()=>({error:re=>{de?de.error(re):Le?.error(re),Je({class:"technical_error",errorCode:re.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":re.errorCode,requestCategory:re.requestCategory,provider:re.provider})},log:re=>{de?de.log(re):Le?.log(re),Je({class:"lifecycle",name:re.name,provider:re.provider})},performance:re=>{de?de.performance(re):Le?.performance(re)},terminal:re=>{de?de.terminal(re):Le?.terminal(re)},startTiming:()=>de?.now()??Le?.now()??0,elapsed:re=>de?.elapsed(re)??Math.max(0,(Le?.now()??re)-re)}),[Je,de,Le]),H=(0,R.useRef)(null),Oe=(0,R.useRef)(0),nt=(0,R.useRef)(null),qe=(0,R.useRef)(null),Y=(0,R.useRef)(null),W=(0,R.useContext)(va),$=(0,R.useRef)(null);$.current||($.current=ri());let j=W??$.current,Ve=(0,R.useRef)(null),Be=(0,R.useRef)(!1),[fe,D]=(0,R.useState)(!1),[ge,ft]=(0,R.useState)(!1),[Ne,ot]=(0,R.useState)(0),Me=(0,R.useRef)(0),[et,at]=(0,R.useState)(!1),mr=(0,R.useRef)(!1),Ft=(0,R.useRef)(!1),[St,ve]=(0,R.useState)(!1),[M,bt]=(0,R.useState)(!1),{request:ut,collect:O,finish:xe}=$o(),Ot=(0,R.useRef)({sessionId:e,required:(0,ze.paypalProviderIdentityRequired)(n,ye)});Ot.current.sessionId!==e&&(Ot.current={sessionId:e,required:(0,ze.paypalProviderIdentityRequired)(n,ye)});let Ce=Ot.current.required,_t=(0,R.useMemo)(()=>r.replace(/\/+$/,""),[r]),x=ye?.gateways?.paypal?.providerObjectType??k,Ae=x??(h?"subscription":"order"),[Re]=(0,R.useState)($n.detectPayPalEnvironment),pt=ye?.gateways?.paypal?.approvalPresentation??w,it=(0,Hn.resolvePayPalPresentationMode)(Re,pt==="app_switch"?"app_switch":void 0,Ae),We=(0,ze.usesPayPalVaultedChannel)(x),Ge=(0,R.useMemo)(()=>JSON.stringify([_t,c,m,p??"",Ae,We,it,e,pe??""]),[_t,c,m,p,pe,Ae,We,it,e]),Dt=(0,R.useRef)(Ge),d=Dt.current!==Ge,L=(0,R.useRef)(B),V=(0,R.useRef)(null),[se,E]=(0,R.useState)([]),U=(0,R.useCallback)(re=>{L.current&&E(Bt=>[...Bt,`${new Date().toISOString().slice(11,23)} ${re}`])},[]);(0,R.useEffect)(()=>{L.current=B,B&&U("debug:enabled"),V.current?.setEnabled(B)},[U,B]);let Nt=(0,R.useRef)(I),Br=(0,R.useRef)(G),rr=(0,R.useRef)(_),$t=(0,R.useRef)(Z),Tt=(0,R.useRef)(A),Wr=(0,R.useRef)(f),Nr=(0,R.useRef)(T),nr=(0,R.useRef)(me),Jr=(0,R.useRef)(S),Mt=(0,R.useRef)(s),Ln=(0,R.useRef)(ae),Jt=(0,R.useRef)(ye),yn=(0,R.useRef)(n),$r=(0,R.useRef)(a),Hr=(0,R.useRef)(t),Zt=(0,R.useRef)(null),Cr=(0,R.useRef)(new Map),Zr=(0,R.useRef)(new Map),tt=(0,R.useRef)(!1),Et=(0,R.useRef)(e);Et.current=e;let[Dr]=(0,R.useState)(oi);(0,R.useEffect)(()=>(tt.current=!0,()=>{tt.current=!1}),[]),(0,R.useEffect)(()=>{Nt.current=I},[I]),(0,R.useEffect)(()=>{Mt.current=s},[s]),(0,R.useEffect)(()=>{Br.current=G},[G]),(0,R.useEffect)(()=>{rr.current=_},[_]),(0,R.useEffect)(()=>{$t.current=Z},[Z]),(0,R.useEffect)(()=>{Tt.current=A},[A]),(0,R.useEffect)(()=>{Wr.current=f},[f]),(0,R.useEffect)(()=>{Nr.current=T},[T]),(0,R.useEffect)(()=>{nr.current=me},[me]),(0,R.useEffect)(()=>{Jr.current=S},[S]),(0,R.useEffect)(()=>{Ln.current=ae},[ae]),(0,R.useEffect)(()=>{Jt.current=ye},[ye]),(0,R.useEffect)(()=>{yn.current=n},[n]),(0,R.useEffect)(()=>{$r.current=a},[a]),(0,R.useEffect)(()=>{Hr.current=t},[t]),(0,R.useEffect)(()=>{Me.current=Ne},[Ne]),(0,R.useEffect)(()=>{et&&Ve.current?.focus()},[et,Ne]);let Ht=(0,R.useCallback)(()=>{window.setTimeout(()=>{Ve.current?.focus()},0)},[]),or=(0,R.useCallback)(()=>{D(!1),ot(re=>re+1)},[]),br=(0,R.useCallback)(()=>{at(!1),(H.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??H.current)?.focus?.()},[]);(0,R.useEffect)(()=>{!fe||!Be.current||(Be.current=!1,br())},[br,fe,Ne]);let Qt=(0,R.useCallback)((re,Bt)=>{let Q=Bt?.popupBlocked??(0,Se.isPopupBlockedError)(re);Q&&j.markBlocked();let Gt=(0,Se.buildExternalMethodRecoveryMessage)("PayPal",Q,Re.inAppBrowser),sr=Wr.current;if(sr){let Pe=Q&&Re.inAppBrowser?new ze.FloPayError(Gt,"api_error",{code:Bt?.code??"paypal_popup_blocked"}):re;sr("paypal",Pe,Bt);return}if(re instanceof ze.FloPayError&&re.code==="checkout_processing_timeout"){rr.current?.(re.message);return}rr.current?.(Gt)},[j,Re.inAppBrowser]),Kt=(0,R.useCallback)(re=>{let Bt=nt.current,Q=qe.current;Bt===null||!Q||(ee.log({...Q,popupCapability:j.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:re}),ee.performance({...Q,popupCapability:j.current(),stage:"overlay_return",durationMs:ee.elapsed(Bt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:re}),nt.current=null)},[j,ee]),_r=(0,R.useCallback)((re,Bt,Q)=>{let Gt=qe.current;Kt("overlay_timeout"),Gt&&ee.error({...Gt,popupCapability:j.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Qt(Bt,{...Q,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:"overlay_timeout"}),at(!0),or(),Ht()},[Kt,Ht,Qt,j,it,or,ee]),Ze=(0,R.useCallback)(()=>{j.markAvailable();let re=qe.current;re&&(Y.current=re.attempt,ee.log({...re,popupCapability:j.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[j,ee]),{finishAttempt:ar,generationRef:Tr,invalidateAttempt:Jn,isAttemptCurrent:Ur,isAttemptInvalidated:zr,startAttempt:Nn}=Ca(_r,{onHandoffObserved:Ze}),ln=(0,R.useCallback)(()=>(at(!1),Nn("paypal")),[Nn]),ir=(0,R.useCallback)(re=>{Jn(re?.generation),re?.showRetry&&at(!0),re?.remount&&or(),re?.focus!==!1&&Ht()},[Ht,Jn,or]),he=re=>{let Bt=Zt.current;return Bt&&Zr.current.set(re,Bt),re};(0,R.useEffect)(()=>{Dt.current!==Ge&&(Dt.current=Ge,mr.current=!1,Ft.current=!1,D(!1),ft(!1),ve(!1),Jr.current?.("loading"))},[Ge]),(0,R.useEffect)(()=>{(0,Ye.invokeMerchantCallback)(()=>nr.current?.(fe&&!St))},[fe,St]);let Sr=(0,ze.normalizeGatewayEnvironment)(p);(0,R.useEffect)(()=>{let re={attempt:Tr.current+1,inAppBrowser:Re.inAppBrowser,appFamily:Re.appFamily,popupCapability:j.current(),presentationMode:it},Bt=()=>({...qe.current??re,popupCapability:j.current()}),Q={error:y=>ee.error({...y,...Bt()}),log:y=>ee.log({...y,...Bt()}),performance:y=>ee.performance({...y,...Bt()}),terminal:y=>ee.terminal({...y,...Bt()}),startTiming:ee.startTiming,elapsed:ee.elapsed},Gt=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",sr=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(U(`mount clientId=${Gt} env=${p??"(unset)"}\u2192${Sr??"live"} ccy=${m} sub=${h}`),U(`ua=${sr.slice(0,80)}${sr.length>80?"\u2026":""}`),!c){U("FAIL: clientId empty \u2014 gateway misconfigured"),ve(!0),Q.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!H.current){U("FAIL: containerRef not attached");return}Oe.current=Q.startTiming(),Q.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=!1,Wt=!1,ne=()=>Pe||Wt,Lt=y=>{let g=tt.current,X=g?y:"torn_down";g&&U(`onError ignored reason=${X}`),Dr.take(Et.current)&&Q.log({name:ni,stage:"provider_ready",reason:X,provider:"paypal",paymentMethodCategory:"paypal"})},wr=()=>Et.current===e?"stale_attempt":"session_changed",qr=We?Ae:void 0,er,Un=!1,Zn=()=>{er=(0,ze.generateIdempotencyKey)(),er||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Un=!0},zn=null,qn=!1,Qn=null,po=!1,mo=()=>{!Qn||po||(po=!0,Qn.close().catch(()=>{}))},Or=!1,eo=!1,fn=H.current,Ut=null,Qr=null,en=[],cn=null,tn=!1,mt=!1,yr=null,lr=y=>{if(!y||typeof y.getBoundingClientRect!="function")return"(no rect)";let g=y.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},Gr=y=>{if(!y)return"(empty)";try{let g=new URL(y,typeof window>"u"?"https://localhost":window.location.href),X=g.pathname.toLowerCase();return X.includes("checkcaptcha")||X.includes("captcha")?`CAPTCHA(${g.host}${X})`:X.includes("risk")||X.includes("challenge")?`RISK(${g.host}${X})`:X.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${X}`.slice(0,100)}catch{return y.slice(0,80)}},ho=y=>{let g=y.getAttribute("src"),X=y.getAttribute("srcdoc"),$e=y.getAttribute("name"),je=y.getAttribute("sandbox"),He=[];return g&&He.push(`src=${Gr(g)}`),X&&He.push(`srcdoc[${X.length}ch]`),!g&&!X&&He.push("src=(empty) srcdoc=(empty)"),$e&&He.push(`name=${$e.slice(0,40)}`),je!==null&&He.push(`sandbox="${je.slice(0,40)}"`),He.join(" ")},to=y=>{if(!(y instanceof HTMLIFrameElement))return"";try{let g=y.contentDocument;if(!g)return"cd=null";let X=g.body?.children.length??0,$e=g.body?.innerHTML.length??0,je=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${X}children,${$e}ch] head[${je}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},In=[],dn=y=>{if(ne())return;let g=y.message??String(y.error??"(no message)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(U(`window:error ${g.slice(0,140)}`),In.push(g))},Mr=y=>{if(ne())return;let g=y.reason instanceof Error?y.reason.message:String(y.reason??"(no reason)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(U(`window:rejection ${g.slice(0,140)}`),In.push(g))},ro={value:0},jr=()=>{Ut?.disconnect(),Ut=null,Qr?.disconnect(),Qr=null;for(let y of en.splice(0))clearTimeout(y);mt=!1,tn&&typeof window<"u"&&(window.removeEventListener("error",dn),window.removeEventListener("unhandledrejection",Mr)),tn=!1},z=()=>{if(!(tn||ne()||Or)){if(tn=!0,In.length=0,ro.value=0,typeof window<"u"&&(window.addEventListener("error",dn),window.addEventListener("unhandledrejection",Mr)),typeof PerformanceObserver<"u")try{Qr=new PerformanceObserver(y=>{if(!ne())for(let g of y.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;ro.value+=1;let X=Math.round(g.duration);U(`net ${X}ms ${g.name.slice(0,90)}`)}}),Qr.observe({type:"resource",buffered:!0})}catch{}yr?.()}},q=()=>{cn&&(clearTimeout(cn),cn=null)},oe=()=>{jr(),q()},be={setEnabled:y=>{y?z():jr()}};V.current=be,L.current&&z();let gt=ze.isPayPalTeardownMessage,Yt=y=>{if(ne()||gt(y))return;let g=(0,So.applyFriendlyMessageOverride)(y)??y;(0,Ye.invokeMerchantCallback)(()=>rr.current?.(g))},ke=(y,g)=>{if(Pe||qn)return;qn=!0,Wt=!0,oe(),mo();let X=vd({kind:y,generationActive:!0,automaticRetryAllowed:Te,automaticRetryUsed:mr.current});if(X.action==="retry"){mr.current=!0,D(!1),bt(!1),ft(!0),Jr.current?.("retrying"),zn=setTimeout(()=>{Pe||ot($e=>$e+1)},fd);return}if(D(!1),bt(!1),ft(!1),ve(!0),X.action!=="ignore"){if(Jr.current?.("exhausted"),X.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(X.report){let $e=(0,Se.classifyExternalMethodFailure)({code:Ll(y,g),message:g},{inAppBrowser:Re.inAppBrowser,handoffObserved:!1});$e.popupBlocked&&j.markBlocked(),Q.error({errorCode:$e.popupBlocked?$e.errorCode:X.report.errorCode,stage:X.report.stage,operationOutcome:X.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:$e.terminalReason})}Ft.current||(Ft.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ll(y,g)))}};ve(!1);let ie=async(y,g=Zt.current)=>{if(ne())return;let X=g?.sessionId??e;if(Nt.current){await Nt.current(y,{sessionId:X,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let $e=Q.startTiming();Q.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let je=()=>{Q.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"processing",durationMs:Q.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let He=(0,ze.buildPayPalProcessPaymentRequest)({body:y,sessionId:X,nonce:g?.nonce??Hr.current,accountPatch:g?.accountPatch,session:Jt.current,email:yn.current}),qt=await new ii.PaymentAPI(_t,{telemetry:!1}).processPayment(He.userId,He.params);if(qt.ok){if(Wt||Pe&&tt.current)return;je(),Q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ye.invokeMerchantCallback)(()=>Br.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ne())return;let le=await qt.json().catch(()=>null),fr=(0,ze.describePayPalProcessFailure)(le),_o=fr.message;je(),qt.status===400&&(typeof le?.declineCode=="string"||!Array.isArray(le?.fields))?Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):qt.status===400||qt.status===422?Q.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):Q.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Cd(qt.status),failureCategory:qt.status>=500?"server_error":void 0}),Yt(_o),(0,Ye.invokeMerchantCallback)(()=>$t.current?.(kr("paypal",_o,{code:fr.code,declineCode:fr.declineCode})));return}catch(He){if(ne())return;je(),Q.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let rt=(0,ze.friendlyPayPalFailureMessage)(He instanceof Error?He.message:void 0);Yt(rt),(0,Ye.invokeMerchantCallback)(()=>$t.current?.(kr("paypal",rt)));return}},te=()=>new ze.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Qe=y=>ne()?Promise.reject(te()):Promise.resolve(y),Ee=async y=>{if(y.ok){Q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ye.invokeMerchantCallback)(()=>Br.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let g=await y.json().catch(()=>null),X=(0,ze.describePayPalProcessFailure)(g);Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ye.invokeMerchantCallback)(()=>$t.current?.(kr("paypal",X.message,{code:X.code,declineCode:X.declineCode})))},st=()=>{let y=Zt.current;Kt("approved"),y&&(Cr.current.delete(y.surfaceKey),ar(y.generation)),Zt.current=null},N=async y=>{if(ne())throw te();Un||Zn();let g=Zt.current,X=g?.sessionId??e,$e=g?.nonce??Hr.current;Q.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let je;try{je=await new ii.PaymentAPI(_t,{telemetry:!1}).createSessionIntent(X,$e??"",(0,ze.buildPayPalSessionIntentRequest)(qr),{idempotencyKey:er})}catch(He){throw Q.error({...(0,ze.classifyTelemetryFailure)(He,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),He}if(ne())throw te();if((0,ze.isSettledSessionIntent)(je))throw await Ee(je.response),st(),new ze.FloPayError("PayPal checkout already settled.","api_error",{code:Ol});if(je.provider!=="paypal"||je.providerObjectType!==Ae)throw new Error(y);return Q.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),je.providerObjectId},ue=(y,g)=>{let X=g?.nonce??Hr.current;if(!X)return;let $e=g?.sessionId??e,je=(0,ze.resolvePayPalDeclineReason)(y);new ii.PaymentAPI(_t,{telemetry:!1}).reportSessionIntentDecline($e,X,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:je}).catch(()=>{})},ht=Ne;U("loadScript:scheduled (deferred 1 tick)");let It=null,Rr=setTimeout(()=>{if(Pe){U("loadScript:skipped (cancelled before defer ran)");return}U("loadScript:start");let y=Sr==="live"?"production":Sr,g={};Ae==="subscription"?g={intent:"subscription",vault:!0}:Ae==="order"&&(g={intent:"capture"}),It=(0,Nl.loadScript)({clientId:c,currency:m,...g,...y?{environment:y}:{},...y==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let X=!1;It.then($e=>{if(X=!0,U(`loadScript:resolved inactive=${ne()} ns=${!!$e} buttons=${!!$e?.Buttons}`),ne())return;if(!$e?.Buttons){U("FAIL: namespace missing Buttons factory"),ke("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}Q.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"provider_ready",durationMs:Q.elapsed(Oe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Q.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let je=async(xt,Fe)=>{if(ne()||Me.current!==ht)return;let lt=xt.vaultSetupToken??xt.subscriptionID??xt.orderID??"",ce=lt?Zr.current.get(lt):Cr.current.get(ht);if(!(!ce||!Ur(ce.generation))&&ar(ce.generation)){Zr.current.delete(lt),Cr.current.delete(ce.surfaceKey),Kt("approved");try{if(bt(!0),(0,Ye.invokeMerchantCallback)(()=>rr.current?.(null)),!lt)throw new ze.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let yt=(0,ze.resolvePayPalApprovalIdentity)({accountPatch:ce.accountPatch,email:yn.current,billingName:$r.current,session:Jt.current});if((0,ze.needsPayPalPayerDetails)(yt))try{yt=(0,ze.mergePayPalPayerIdentity)(yt,await Fe?.order?.get?.())}catch{}if((Mt.current||Ce)&&!(0,ze.isValidEmail)(yt.email)){let jt=await O("PayPal",yt);if(!jt)return;yt=jt}(0,ze.isValidEmail)(yt.email)&&(ce.accountPatch=(0,vn.compactBuyerIdentity)({...ce.accountPatch,...yt}),await Mt.current?.(yt));let rn=(0,ze.buildPayPalTokenizedBody)(lt,qr);await ie(rn,ce)}catch(yt){Yt(yt instanceof Error?yt.message:"PayPal capture failed.")}finally{ne()||bt(!1)}}},He=xt=>{let Fe=pe?()=>Qe(pe):()=>N(xt);return async()=>he(await Fe())},rt=$e.Buttons({style:{layout:"horizontal",height:si,tagline:!1},...it==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(xt,Fe)=>{if(ne()){await Fe.reject();return}Zn();let lt=Ln.current,ce={};if(lt)try{let jt=await lt("paypal");if(ne()){await Fe.reject();return}if(!jt.proceed){Zt.current=null,Cr.current.delete(ht),await Fe.reject();return}ce={sessionId:jt.sessionId,accountPatch:jt.accountPatch,nonce:jt.nonce}}catch(jt){U(`onClick:runBeforeButtonClick rejected msg=${(jt instanceof Error?jt.message:String(jt)).slice(0,120)}`),Zt.current=null,Cr.current.delete(ht),await Fe.reject();return}(0,Ye.invokeMerchantCallback)(()=>Nr.current?.("paypal"));let yt=ln(),rn={generation:yt,surfaceKey:ht,...ce};Zt.current=rn,Cr.current.set(ht,rn),qe.current={...re,attempt:yt},await Fe.resolve(),Q.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Q.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nt.current=Q.startTiming()},createOrder:Ae==="order"?He("Failed to create PayPal order."):void 0,createSubscription:Ae==="subscription"?He("Failed to create PayPal subscription."):void 0,createVaultSetupToken:Ae==="setup_token"?async()=>he(await N("Failed to create PayPal setup token.")):void 0,onApprove:je,onCancel:()=>{if(ne())return;let xt=Cr.current.get(ht)??Zt.current,Fe=xt&&Ur(xt.generation)?(0,ze.buildPayPalCancelEvent)(xt.sessionId??e,qr):null;xt&&Cr.current.delete(xt.surfaceKey),Zt.current=null,Kt("cancelled"),Q.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Be.current=!0,ir({generation:xt?.generation,remount:!0,focus:!1}),Fe&&(0,Ye.invokeMerchantCallback)(()=>Tt.current?.(Fe))},onError:xt=>{if(xt instanceof ze.FloPayError&&xt.code===Ol)return;let Fe=xt instanceof Error?xt.message:"PayPal failed to render.";if(ne()||Me.current!==ht){gt(Fe)||Lt(wr());return}if(Or){let lt=Cr.current.get(ht)??Zt.current;if(!lt||!Ur(lt.generation)){if(gt(Fe)){!lt&&!zr()&&ar();return}Lt(lt||zr()?"stale_attempt":"no_current_attempt");return}if(U(`onError rendered=${Or} msg=${Fe.slice(0,120)}`),gt(Fe)){ar(lt.generation);return}let{errorCode:ce,popupBlocked:yt,providerDeclined:rn,terminalReason:jt}=(0,Se.classifyExternalMethodFailure)(xt,{inAppBrowser:Re.inAppBrowser,handoffObserved:Y.current===lt.generation});if(yt&&j.markBlocked(),Kt(jt),rn){Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:jt}),ue(xt,lt),(0,Ye.invokeMerchantCallback)(()=>$t.current?.(kr("paypal",Fe))),Cr.current.delete(lt.surfaceKey),Zt.current=null,ar(lt.generation);return}Q.error({errorCode:ce,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:jt}),Cr.current.delete(lt.surfaceKey),Zt.current=null,ir({generation:lt.generation,remount:!0,showRetry:!0,focus:!0}),Qt(xt,{code:"paypal_runtime_failed",popupBlocked:yt,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:jt});return}U(`onError rendered=${Or} msg=${Fe.slice(0,120)}`),ke(gt(Fe)?"teardown":"pre_ready_callback",Fe)}}),qt=rt.isEligible();if(U(`isEligible=${qt}`),Q.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!qt){D(!1),ke("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}eo=!0,Qn=rt,yr=()=>{if(!tn||mt||ne()||Or)return;mt=!0,U(`container:dims ${lr(fn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Ut=new MutationObserver(Fe=>{if(!ne()){for(let lt of Fe)if(lt.type==="childList")lt.addedNodes.forEach(ce=>{if(!(ce instanceof Element))return;let yt=ce.tagName.toLowerCase(),rn=(ce.getAttribute("title")??"").slice(0,40),jt=yt==="iframe"?` ${ho(ce)}`:"";U(`child+ ${yt}${rn?` title="${rn}"`:""}${jt} dims=${lr(ce)}`)});else if(lt.type==="attributes"&&lt.target instanceof Element){let ce=lt.target;if(ce.tagName.toLowerCase()!=="iframe")continue;let yt=lt.attributeName;(yt==="src"||yt==="srcdoc")&&U(`attr~ iframe ${yt}=${yt==="srcdoc"?`[${(ce.getAttribute("srcdoc")??"").length}ch]`:Gr(ce.getAttribute("src"))} dims=${lr(ce)}`)}}}),Ut.observe(fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let xt=Fe=>{if(ne()||Or)return;let lt=fn.querySelectorAll("iframe"),ce=typeof document<"u"&&"hasStorageAccess"in document;U(`watchdog:${Fe} container=${lr(fn)} children=${fn.childElementCount} iframes=${lt.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ce} paypalNetRequests=${ro.value}`),lt.forEach((yt,rn)=>{let jt=(yt.getAttribute("title")??"").slice(0,40);U(` iframe[${rn}] ${lr(yt)}${jt?` title="${jt}"`:""} ${ho(yt)}`);let _n=to(yt);_n&&U(` ${_n}`)}),In.length===0&&U(" (no PayPal/zoid window errors captured)")};en.push(setTimeout(()=>xt("3s"),3e3)),en.push(setTimeout(()=>xt("8s"),8e3)),en.push(setTimeout(()=>xt("15s"),15e3))},yr(),U("render:start");let fr=Q.startTiming();cn=setTimeout(()=>{ne()||Or||(U("watchdog:11s retryable render timeout"),ke("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},gd);let _o=rt.render(fn);(async()=>{try{if(await _o,U(`render:resolved inactive=${ne()}`),oe(),ne()){mo();return}Or=!0,D(!0),ft(!1),Jr.current?.("ready"),Q.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"checkout_render",durationMs:Q.elapsed(fr),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(xt){let Fe=xt instanceof Error?xt.message:"PayPal failed to render.";U(`render:rejected msg=${Fe.slice(0,120)}`),oe(),ke(gt(Fe)?"teardown":"render_rejected",Fe)}})()}).catch($e=>{let je=$e instanceof Error?$e.message:"PayPal operation failed.";U(`provider:failed msg=${je.slice(0,120)}`);let He="script_rejected";X&&gt(je)?He="teardown":X&&eo&&(He="render_rejected"),ke(He,je)})},0);return()=>{Pe=!0,clearTimeout(Rr),zn&&clearTimeout(zn),oe(),V.current===be&&(V.current=null),mo(),nt.current=null,qe.current=null}},[Te,_t,c,m,p,Ae,it,We,e,pe,Ne,ee,O,Ce,U,Kt]);let Kr=B?(0,Cn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:St?"#fef2f2":"#f3f4f6",border:`1px solid ${St?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${fe} failed=${St})`,se.length===0?`
1
+ "use strict";var Zc=Object.create;var Ja=Object.defineProperty;var Qc=Object.getOwnPropertyDescriptor;var ed=Object.getOwnPropertyNames;var td=Object.getPrototypeOf,rd=Object.prototype.hasOwnProperty;var nd=(e,t)=>{for(var r in t)Ja(e,r,{get:t[r],enumerable:!0})},bl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of ed(t))!rd.call(e,a)&&a!==r&&Ja(e,a,{get:()=>t[a],enumerable:!(n=Qc(t,a))||n.enumerable});return e};var Zi=(e,t,r)=>(r=e!=null?Zc(td(e)):{},bl(t||!e||!e.__esModule?Ja(r,"default",{value:e,enumerable:!0}):r,e)),od=e=>bl(Ja({},"__esModule",{value:!0}),e);var Au={};nd(Au,{DirectPayPalButton:()=>ba,FloPayAutomaticPaymentButton:()=>vc,FloPayCardSetup:()=>Cc,FloPayCardSetupError:()=>Oa,FloPayCheckout:()=>_i,FloPayPaymentMethodSetup:()=>xc,FloPayProvider:()=>wa,SplitCardForm:()=>Ri,VaultCardFields:()=>go,dropThirdPartyOnlyError:()=>Fc.dropThirdPartyOnlyError,useCheckout:()=>Bl,useFloPay:()=>io,usePayPalFloPay:()=>ti});module.exports=od(Au);var Fc=require("@flopay/shared");var Ti=require("@flopay/js"),Rn=require("@flopay/shared"),Ct=require("react");var Xt=require("react/jsx-runtime");function ad(){return(0,Xt.jsxs)(Xt.Fragment,{children:[(0,Xt.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,Xt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Xt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Xt.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,Xt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function id(){return(0,Xt.jsx)(Xt.Fragment,{children:"Go back"})}function sd(){return(0,Xt.jsx)(Xt.Fragment,{children:"Secure card checkout"})}function Uo(e){return e!==void 0&&(e===""||e===null||e===!1)}function zo({content:e}){return(0,Xt.jsx)(Xt.Fragment,{children:e===void 0?(0,Xt.jsx)(ad,{}):e})}function qo({content:e}){return(0,Xt.jsx)(Xt.Fragment,{children:e===void 0?(0,Xt.jsx)(id,{}):e})}function fa({content:e}){return(0,Xt.jsx)(Xt.Fragment,{children:e===void 0?(0,Xt.jsx)(sd,{}):e})}var Rt=require("@flopay/shared"),xn=require("@flopay/shared"),Wo=require("@flopay/shared"),So=require("@flopay/shared");function Qi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Rt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function ld(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 Sl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,Rt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,Rt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function wl(e,t){if(t&&(!(e instanceof Rt.FloPayError)||e.type==="authentication_error"))return Qi(e);if(!(e instanceof Rt.FloPayError&&ld(e))){if(!t&&!(e instanceof Rt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Rt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Rt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Rt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function jo(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let c={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,Rt.isCardHolderNamePlaceholder)(c.firstName,c.lastName);if(!(0,Rt.isValidEmail)(c.email))return Promise.reject(new Rt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[h,k]of Object.entries(c)){if(p&&h.endsWith("Name")||typeof k!="string")continue;let w=k.trim();w&&(m[h]=w)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function 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 es(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 kl(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 ts(e,t){return t?{...e,...t}:e}function kr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,s=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,c=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...s?{declineCode:s}:{},...c?{sessionId:c}:{}}}var El=new WeakMap;function Il(e,t){return typeof e=="object"&&e!==null&&El.set(e,t?{sessionId:t}:{}),e}function _l(e){return typeof e=="object"&&e!==null?El.get(e):void 0}function yo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function no(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function oo(e){return e?.status==="authorized"||e?.status==="complete"}function fo(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function Tl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Za(e){let t=Tl(e);return new Rt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Qa(e){return e instanceof Rt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Vo(e){return Tl(e)?new Rt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Rt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Rt.FloPayError(Rt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ga(e,t){return e==="processing"||(0,Rt.isMoneySettledOutcome)(e,t)}function Ml(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function xl(e,t){let r=e;if((0,Rt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:c}=await r.retrieveSetupIntent(t);if(c)throw new Rt.FloPayError(c.message??"Failed to retrieve setup intent.","api_error",{...c.code?{code:c.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new Rt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var cd=["apple_pay","google_pay"];function Al(e,t="automatic",r){let n=(0,Rt.resolveSetupFutureUsage)(r,cd,"wallet");return{...(0,Rt.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var dd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function rs(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:dd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function ha(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var co=require("@flopay/js"),De=require("@flopay/shared"),v=Zi(require("react"),1);var ns=require("react"),vn=(0,ns.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),An=(0,ns.createContext)({session:null,loading:!1,error:null});var si=require("@flopay/js"),qe=require("@flopay/shared"),Ul=require("@paypal/paypal-js"),R=require("react");var ei=require("@flopay/shared"),Fn=require("react"),Cn=require("@flopay/shared"),ao=require("react/jsx-runtime");function $o(){let[e,t]=(0,Fn.useState)(null),r=(0,Fn.useRef)(null),n=(0,Fn.useRef)(0),a=(0,Fn.useCallback)((c,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:c,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,Fn.useCallback)(c=>{let p=r.current;r.current=null,t(null),p?.(c)},[]);return(0,Fn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function Ho({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[c,p]=(0,Fn.useState)(e.email?.trim()??""),m=(0,ei.isValidEmail)(c.trim());return(0,ao.jsxs)("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,ao.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,ao.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,ao.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:c,onChange:h=>p(h.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,ao.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,ao.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,ao.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,ei.compactBuyerIdentity)({...e,email:c.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var we=require("@flopay/shared");var Fl=require("@flopay/shared"),Pa=require("react");function io(){return(0,Pa.useContext)(vn).flopay}function ti(){return(0,Pa.useContext)(vn).paypalFlopay??null}function Bl(){return(0,Pa.useContext)(An)}function Dl(){return(0,Pa.useContext)(vn).billingApiUrl||(0,Fl.resolveBillingApiUrl)()}var ud=require("@flopay/shared"),$n=require("@flopay/shared"),Hn=require("@flopay/shared");var Ko=require("@flopay/shared"),Ro=require("react");var ri=require("react"),wo=typeof window>"u"?ri.useEffect:ri.useLayoutEffect;var os=require("@flopay/shared");function Go(e,t){let r=(0,Ro.useRef)(e);r.current=e;let n=(0,Ro.useRef)(new Set),a=(0,Ro.useRef)(t),s=(0,Ro.useRef)(t);return wo(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Ro.useCallback)(c=>{if(s.current!==t)return;let p=(0,Ko.projectFloInstrument)(c);if(p){if(Ko.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,Ko.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ye=require("@flopay/shared");var Ol=require("react"),va=(0,Ol.createContext)(null);function ni(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var oi="provider.callback.ignored";function ai(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var pd=Symbol.for("@flopay/js.telemetry.bridge.v1"),md=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function yd(){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 fd(e){let t=yd(),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 ii(e){let t=globalThis[md];return fd(t?.(e)??{})}function Er(e){if(e)return e[pd]}var Pr=require("react");function Ca(e,t){let r=(0,Pr.useRef)(0),n=(0,Pr.useRef)(null),a=(0,Pr.useRef)(null),s=(0,Pr.useRef)(e),c=(0,Pr.useRef)(t?.onHandoffObserved),p=(0,Pr.useRef)(t?.defersMissingTerminal),m=(0,Pr.useRef)(t?.onMissingTerminalDeferred);(0,Pr.useEffect)(()=>{s.current=e,c.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let h=(0,Pr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),k=(0,Pr.useCallback)(f=>{h();let P=r.current+1;return r.current=P,n.current=null,a.current={generation:P,method:f,timer:null,yieldedControl:!1},P},[h]),w=(0,Pr.useCallback)(f=>{let P=a.current;return f!==void 0&&P?.generation!==f?!1:(h(P),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[h]),I=(0,Pr.useCallback)(f=>{let P=a.current,me=f??P?.generation??r.current;(f===void 0||P?.generation===f)&&(h(P),a.current=null),n.current=me},[h]),G=(0,Pr.useCallback)(f=>n.current===(f??r.current),[]),_=(0,Pr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),Z=(0,Pr.useCallback)(()=>{let f=a.current;f&&(h(f),!f.yieldedControl&&(f.yieldedControl=!0,c.current?.(f.method)))},[h]),F=(0,Pr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(h(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(p.current?.(f.method)){m.current?.(f.method,f.generation);return}a.current=null,n.current=f.generation,s.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},we.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[h]);return(0,Pr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?F():Z()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",Z),window.addEventListener("focus",F),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",Z),window.removeEventListener("focus",F),h()}},[h,Z,F]),{startAttempt:k,finishAttempt:w,invalidateAttempt:I,isAttemptInvalidated:G,isAttemptCurrent:_,generationRef:r}}var bn=require("react/jsx-runtime"),li=45,gd=1e3,hd=11e3,Ll="paypal_intent_settled",Pd={width:"100%",minHeight:li,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"},vd={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 Cd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:vd[e.kind]??null}}function Nl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,we.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function bd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function zl({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:c,environment:p,currency:m,isSubscription:h,providerObjectType:k,approvalPresentation:w,onTokenizedBody:I,onComplete:G,onErrorChange:_,onDecline:Z,onCancel:F,onTechnicalFailure:f,isProcessing:P=!1,onLoadStateChange:me,onInitializationStateChange:S,allowAutomaticRetry:Te=!0,onButtonClick:T,runBeforeButtonClick:ae,session:ye,existingOrderId:pe,telemetry:Re,telemetryContext:dt,onInstrument:Ge,debug:x=!1}){let kt=io(),Je=Go(Ge,e),Le=(0,R.useMemo)(()=>{if(kt)return null;let re=ii({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:qe.SDK_VERSION,enabled:Re!==!1});return re.setCheckoutContext(dt??{}),re.beginCheckout(dt??{}),re},[r,kt,Re,dt?.checkoutMode,dt?.layout]),de=(0,R.useMemo)(()=>Er(kt),[kt]);(0,R.useEffect)(()=>()=>{Le&&Le.flush().catch(()=>{}).finally(()=>Le.destroy())},[Le]);let ee=(0,R.useMemo)(()=>({error:re=>{de?de.error(re):Le?.error(re),Je({class:"technical_error",errorCode:re.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":re.errorCode,requestCategory:re.requestCategory,provider:re.provider})},log:re=>{de?de.log(re):Le?.log(re),Je({class:"lifecycle",name:re.name,provider:re.provider})},performance:re=>{de?de.performance(re):Le?.performance(re)},terminal:re=>{de?de.terminal(re):Le?.terminal(re)},startTiming:()=>de?.now()??Le?.now()??0,elapsed:re=>de?.elapsed(re)??Math.max(0,(Le?.now()??re)-re)}),[Je,de,Le]),H=(0,R.useRef)(null),Oe=(0,R.useRef)(0),nt=(0,R.useRef)(null),je=(0,R.useRef)(null),Y=(0,R.useRef)(null),W=(0,R.useContext)(va),$=(0,R.useRef)(null);$.current||($.current=ni());let V=W??$.current,He=(0,R.useRef)(null),Be=(0,R.useRef)(!1),[fe,B]=(0,R.useState)(!1),[ge,ft]=(0,R.useState)(!1),[Ne,ot]=(0,R.useState)(0),Me=(0,R.useRef)(0),[tt,at]=(0,R.useState)(!1),mr=(0,R.useRef)(!1),Ft=(0,R.useRef)(!1),[St,Ce]=(0,R.useState)(!1),[A,bt]=(0,R.useState)(!1),{request:ut,collect:O,finish:xe}=$o(),Ot=(0,R.useRef)({sessionId:e,required:(0,qe.paypalProviderIdentityRequired)(n,ye)});Ot.current.sessionId!==e&&(Ot.current={sessionId:e,required:(0,qe.paypalProviderIdentityRequired)(n,ye)});let be=Ot.current.required,_t=(0,R.useMemo)(()=>r.replace(/\/+$/,""),[r]),M=ye?.gateways?.paypal?.providerObjectType??k,Ae=M??(h?"subscription":"order"),[Pe]=(0,R.useState)($n.detectPayPalEnvironment),pt=ye?.gateways?.paypal?.approvalPresentation??w,it=(0,Hn.resolvePayPalPresentationMode)(Pe,pt==="app_switch"?"app_switch":void 0,Ae),Ve=(0,qe.usesPayPalVaultedChannel)(M),We=(0,R.useMemo)(()=>JSON.stringify([_t,c,m,p??"",Ae,Ve,it,e,pe??""]),[_t,c,m,p,pe,Ae,Ve,it,e]),Dt=(0,R.useRef)(We),d=Dt.current!==We,L=(0,R.useRef)(x),z=(0,R.useRef)(null),[se,E]=(0,R.useState)([]),q=(0,R.useCallback)(re=>{L.current&&E(Bt=>[...Bt,`${new Date().toISOString().slice(11,23)} ${re}`])},[]);(0,R.useEffect)(()=>{L.current=x,x&&q("debug:enabled"),z.current?.setEnabled(x)},[q,x]);let Nt=(0,R.useRef)(I),Br=(0,R.useRef)(G),rr=(0,R.useRef)(_),$t=(0,R.useRef)(Z),Tt=(0,R.useRef)(F),Wr=(0,R.useRef)(f),Nr=(0,R.useRef)(T),nr=(0,R.useRef)(me),Zr=(0,R.useRef)(S),Mt=(0,R.useRef)(s),Ln=(0,R.useRef)(ae),Jt=(0,R.useRef)(ye),fn=(0,R.useRef)(n),$r=(0,R.useRef)(a),Hr=(0,R.useRef)(t),Zt=(0,R.useRef)(null),Cr=(0,R.useRef)(new Map),Qr=(0,R.useRef)(new Map),rt=(0,R.useRef)(!1),Et=(0,R.useRef)(e);Et.current=e;let[Dr]=(0,R.useState)(ai);(0,R.useEffect)(()=>(rt.current=!0,()=>{rt.current=!1}),[]),(0,R.useEffect)(()=>{Nt.current=I},[I]),(0,R.useEffect)(()=>{Mt.current=s},[s]),(0,R.useEffect)(()=>{Br.current=G},[G]),(0,R.useEffect)(()=>{rr.current=_},[_]),(0,R.useEffect)(()=>{$t.current=Z},[Z]),(0,R.useEffect)(()=>{Tt.current=F},[F]),(0,R.useEffect)(()=>{Wr.current=f},[f]),(0,R.useEffect)(()=>{Nr.current=T},[T]),(0,R.useEffect)(()=>{nr.current=me},[me]),(0,R.useEffect)(()=>{Zr.current=S},[S]),(0,R.useEffect)(()=>{Ln.current=ae},[ae]),(0,R.useEffect)(()=>{Jt.current=ye},[ye]),(0,R.useEffect)(()=>{fn.current=n},[n]),(0,R.useEffect)(()=>{$r.current=a},[a]),(0,R.useEffect)(()=>{Hr.current=t},[t]),(0,R.useEffect)(()=>{Me.current=Ne},[Ne]),(0,R.useEffect)(()=>{tt&&He.current?.focus()},[tt,Ne]);let Ht=(0,R.useCallback)(()=>{window.setTimeout(()=>{He.current?.focus()},0)},[]),or=(0,R.useCallback)(()=>{B(!1),ot(re=>re+1)},[]),br=(0,R.useCallback)(()=>{at(!1),(H.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??H.current)?.focus?.()},[]);(0,R.useEffect)(()=>{!fe||!Be.current||(Be.current=!1,br())},[br,fe,Ne]);let Qt=(0,R.useCallback)((re,Bt)=>{let Q=Bt?.popupBlocked??(0,we.isPopupBlockedError)(re);Q&&V.markBlocked();let Gt=(0,we.buildExternalMethodRecoveryMessage)("PayPal",Q,Pe.inAppBrowser),sr=Wr.current;if(sr){let ve=Q&&Pe.inAppBrowser?new qe.FloPayError(Gt,"api_error",{code:Bt?.code??"paypal_popup_blocked"}):re;sr("paypal",ve,Bt);return}if(re instanceof qe.FloPayError&&re.code==="checkout_processing_timeout"){rr.current?.(re.message);return}rr.current?.(Gt)},[V,Pe.inAppBrowser]),Kt=(0,R.useCallback)(re=>{let Bt=nt.current,Q=je.current;Bt===null||!Q||(ee.log({...Q,popupCapability:V.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:re}),ee.performance({...Q,popupCapability:V.current(),stage:"overlay_return",durationMs:ee.elapsed(Bt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:re}),nt.current=null)},[V,ee]),_r=(0,R.useCallback)((re,Bt,Q)=>{let Gt=je.current;Kt("overlay_timeout"),Gt&&ee.error({...Gt,popupCapability:V.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Qt(Bt,{...Q,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:"overlay_timeout"}),at(!0),or(),Ht()},[Kt,Ht,Qt,V,it,or,ee]),Ze=(0,R.useCallback)(()=>{V.markAvailable();let re=je.current;re&&(Y.current=re.attempt,ee.log({...re,popupCapability:V.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[V,ee]),{finishAttempt:ar,generationRef:Tr,invalidateAttempt:Jn,isAttemptCurrent:Ur,isAttemptInvalidated:zr,startAttempt:Nn}=Ca(_r,{onHandoffObserved:Ze}),cn=(0,R.useCallback)(()=>(at(!1),Nn("paypal")),[Nn]),ir=(0,R.useCallback)(re=>{Jn(re?.generation),re?.showRetry&&at(!0),re?.remount&&or(),re?.focus!==!1&&Ht()},[Ht,Jn,or]),he=re=>{let Bt=Zt.current;return Bt&&Qr.current.set(re,Bt),re};(0,R.useEffect)(()=>{Dt.current!==We&&(Dt.current=We,mr.current=!1,Ft.current=!1,B(!1),ft(!1),Ce(!1),Zr.current?.("loading"))},[We]),(0,R.useEffect)(()=>{(0,Ye.invokeMerchantCallback)(()=>nr.current?.(fe&&!St))},[fe,St]);let Sr=(0,qe.normalizeGatewayEnvironment)(p);(0,R.useEffect)(()=>{let re={attempt:Tr.current+1,inAppBrowser:Pe.inAppBrowser,appFamily:Pe.appFamily,popupCapability:V.current(),presentationMode:it},Bt=()=>({...je.current??re,popupCapability:V.current()}),Q={error:y=>ee.error({...y,...Bt()}),log:y=>ee.log({...y,...Bt()}),performance:y=>ee.performance({...y,...Bt()}),terminal:y=>ee.terminal({...y,...Bt()}),startTiming:ee.startTiming,elapsed:ee.elapsed},Gt=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",sr=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(q(`mount clientId=${Gt} env=${p??"(unset)"}\u2192${Sr??"live"} ccy=${m} sub=${h}`),q(`ua=${sr.slice(0,80)}${sr.length>80?"\u2026":""}`),!c){q("FAIL: clientId empty \u2014 gateway misconfigured"),Ce(!0),Q.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!H.current){q("FAIL: containerRef not attached");return}Oe.current=Q.startTiming(),Q.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ve=!1,Wt=!1,oe=()=>ve||Wt,Lt=y=>{let g=rt.current,X=g?y:"torn_down";g&&q(`onError ignored reason=${X}`),Dr.take(Et.current)&&Q.log({name:oi,stage:"provider_ready",reason:X,provider:"paypal",paymentMethodCategory:"paypal"})},wr=()=>Et.current===e?"stale_attempt":"session_changed",qr=Ve?Ae:void 0,er,Un=!1,Zn=()=>{er=(0,qe.generateIdempotencyKey)(),er||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Un=!0},zn=null,qn=!1,Qn=null,po=!1,mo=()=>{!Qn||po||(po=!0,Qn.close().catch(()=>{}))},Or=!1,eo=!1,gn=H.current,Ut=null,en=null,tn=[],dn=null,rn=!1,mt=!1,yr=null,lr=y=>{if(!y||typeof y.getBoundingClientRect!="function")return"(no rect)";let g=y.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},Gr=y=>{if(!y)return"(empty)";try{let g=new URL(y,typeof window>"u"?"https://localhost":window.location.href),X=g.pathname.toLowerCase();return X.includes("checkcaptcha")||X.includes("captcha")?`CAPTCHA(${g.host}${X})`:X.includes("risk")||X.includes("challenge")?`RISK(${g.host}${X})`:X.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${X}`.slice(0,100)}catch{return y.slice(0,80)}},ho=y=>{let g=y.getAttribute("src"),X=y.getAttribute("srcdoc"),Ke=y.getAttribute("name"),$e=y.getAttribute("sandbox"),Ue=[];return g&&Ue.push(`src=${Gr(g)}`),X&&Ue.push(`srcdoc[${X.length}ch]`),!g&&!X&&Ue.push("src=(empty) srcdoc=(empty)"),Ke&&Ue.push(`name=${Ke.slice(0,40)}`),$e!==null&&Ue.push(`sandbox="${$e.slice(0,40)}"`),Ue.join(" ")},to=y=>{if(!(y instanceof HTMLIFrameElement))return"";try{let g=y.contentDocument;if(!g)return"cd=null";let X=g.body?.children.length??0,Ke=g.body?.innerHTML.length??0,$e=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${X}children,${Ke}ch] head[${$e}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},In=[],un=y=>{if(oe())return;let g=y.message??String(y.error??"(no message)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(q(`window:error ${g.slice(0,140)}`),In.push(g))},Mr=y=>{if(oe())return;let g=y.reason instanceof Error?y.reason.message:String(y.reason??"(no reason)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(q(`window:rejection ${g.slice(0,140)}`),In.push(g))},ro={value:0},jr=()=>{Ut?.disconnect(),Ut=null,en?.disconnect(),en=null;for(let y of tn.splice(0))clearTimeout(y);mt=!1,rn&&typeof window<"u"&&(window.removeEventListener("error",un),window.removeEventListener("unhandledrejection",Mr)),rn=!1},N=()=>{if(!(rn||oe()||Or)){if(rn=!0,In.length=0,ro.value=0,typeof window<"u"&&(window.addEventListener("error",un),window.addEventListener("unhandledrejection",Mr)),typeof PerformanceObserver<"u")try{en=new PerformanceObserver(y=>{if(!oe())for(let g of y.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;ro.value+=1;let X=Math.round(g.duration);q(`net ${X}ms ${g.name.slice(0,90)}`)}}),en.observe({type:"resource",buffered:!0})}catch{}yr?.()}},j=()=>{dn&&(clearTimeout(dn),dn=null)},ne=()=>{jr(),j()},Se={setEnabled:y=>{y?N():jr()}};z.current=Se,L.current&&N();let gt=qe.isPayPalTeardownMessage,Yt=y=>{if(oe()||gt(y))return;let g=(0,So.applyFriendlyMessageOverride)(y)??y;(0,Ye.invokeMerchantCallback)(()=>rr.current?.(g))},ke=(y,g)=>{if(ve||qn)return;qn=!0,Wt=!0,ne(),mo();let X=Cd({kind:y,generationActive:!0,automaticRetryAllowed:Te,automaticRetryUsed:mr.current});if(X.action==="retry"){mr.current=!0,B(!1),bt(!1),ft(!0),Zr.current?.("retrying"),zn=setTimeout(()=>{ve||ot(Ke=>Ke+1)},gd);return}if(B(!1),bt(!1),ft(!1),Ce(!0),X.action!=="ignore"){if(Zr.current?.("exhausted"),X.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(X.report){let Ke=(0,we.classifyExternalMethodFailure)({code:Nl(y,g),message:g},{inAppBrowser:Pe.inAppBrowser,handoffObserved:!1});Ke.popupBlocked&&V.markBlocked(),Q.error({errorCode:Ke.popupBlocked?Ke.errorCode:X.report.errorCode,stage:X.report.stage,operationOutcome:X.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:Ke.terminalReason})}Ft.current||(Ft.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Nl(y,g)))}};Ce(!1);let ie=async(y,g=Zt.current)=>{if(oe())return;let X=g?.sessionId??e;if(Nt.current){await Nt.current(y,{sessionId:X,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let Ke=Q.startTiming();Q.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let $e=()=>{Q.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"processing",durationMs:Q.elapsed(Ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Ue=(0,qe.buildPayPalProcessPaymentRequest)({body:y,sessionId:X,nonce:g?.nonce??Hr.current,accountPatch:g?.accountPatch,session:Jt.current,email:fn.current}),qt=await new si.PaymentAPI(_t,{telemetry:!1}).processPayment(Ue.userId,Ue.params);if(qt.ok){if(Wt||ve&&rt.current)return;$e(),Q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ye.invokeMerchantCallback)(()=>Br.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(oe())return;let le=await qt.json().catch(()=>null),fr=(0,qe.describePayPalProcessFailure)(le),_o=fr.message;$e(),qt.status===400&&(typeof le?.declineCode=="string"||!Array.isArray(le?.fields))?Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):qt.status===400||qt.status===422?Q.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):Q.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:bd(qt.status),failureCategory:qt.status>=500?"server_error":void 0}),Yt(_o),(0,Ye.invokeMerchantCallback)(()=>$t.current?.(kr("paypal",_o,{code:fr.code,declineCode:fr.declineCode})));return}catch(Ue){if(oe())return;$e(),Q.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let et=(0,qe.friendlyPayPalFailureMessage)(Ue instanceof Error?Ue.message:void 0);Yt(et),(0,Ye.invokeMerchantCallback)(()=>$t.current?.(kr("paypal",et)));return}},te=()=>new qe.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Qe=y=>oe()?Promise.reject(te()):Promise.resolve(y),Ee=async y=>{if(y.ok){Q.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ye.invokeMerchantCallback)(()=>Br.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let g=await y.json().catch(()=>null),X=(0,qe.describePayPalProcessFailure)(g);Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ye.invokeMerchantCallback)(()=>$t.current?.(kr("paypal",X.message,{code:X.code,declineCode:X.declineCode})))},st=()=>{let y=Zt.current;Kt("approved"),y&&(Cr.current.delete(y.surfaceKey),ar(y.generation)),Zt.current=null},U=async y=>{if(oe())throw te();Un||Zn();let g=Zt.current,X=g?.sessionId??e,Ke=g?.nonce??Hr.current;Q.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let $e;try{$e=await new si.PaymentAPI(_t,{telemetry:!1}).createSessionIntent(X,Ke??"",(0,qe.buildPayPalSessionIntentRequest)(qr),{idempotencyKey:er})}catch(Ue){throw Q.error({...(0,qe.classifyTelemetryFailure)(Ue,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Ue}if(oe())throw te();if((0,qe.isSettledSessionIntent)($e))throw await Ee($e.response),st(),new qe.FloPayError("PayPal checkout already settled.","api_error",{code:Ll});if($e.provider!=="paypal"||$e.providerObjectType!==Ae)throw new Error(y);return Q.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),$e.providerObjectId},ue=(y,g)=>{let X=g?.nonce??Hr.current;if(!X)return;let Ke=g?.sessionId??e,$e=(0,qe.resolvePayPalDeclineReason)(y);new si.PaymentAPI(_t,{telemetry:!1}).reportSessionIntentDecline(Ke,X,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:$e}).catch(()=>{})},ht=Ne;q("loadScript:scheduled (deferred 1 tick)");let It=null,Rr=setTimeout(()=>{if(ve){q("loadScript:skipped (cancelled before defer ran)");return}q("loadScript:start");let y=Sr==="live"?"production":Sr,g={};Ae==="subscription"?g={intent:"subscription",vault:!0}:Ae==="order"&&(g={intent:"capture"}),It=(0,Ul.loadScript)({clientId:c,currency:m,...g,...y?{environment:y}:{},...y==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let X=!1;It.then(Ke=>{if(X=!0,q(`loadScript:resolved inactive=${oe()} ns=${!!Ke} buttons=${!!Ke?.Buttons}`),oe())return;if(!Ke?.Buttons){q("FAIL: namespace missing Buttons factory"),ke("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}Q.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"provider_ready",durationMs:Q.elapsed(Oe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Q.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let $e=async(xt,Fe)=>{if(oe()||Me.current!==ht)return;let lt=xt.vaultSetupToken??xt.subscriptionID??xt.orderID??"",ce=lt?Qr.current.get(lt):Cr.current.get(ht);if(!(!ce||!Ur(ce.generation))&&ar(ce.generation)){Qr.current.delete(lt),Cr.current.delete(ce.surfaceKey),Kt("approved");try{if(bt(!0),(0,Ye.invokeMerchantCallback)(()=>rr.current?.(null)),!lt)throw new qe.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let yt=(0,qe.resolvePayPalApprovalIdentity)({accountPatch:ce.accountPatch,email:fn.current,billingName:$r.current,session:Jt.current});if((0,qe.needsPayPalPayerDetails)(yt))try{yt=(0,qe.mergePayPalPayerIdentity)(yt,await Fe?.order?.get?.())}catch{}if((Mt.current||be)&&!(0,qe.isValidEmail)(yt.email)){let jt=await O("PayPal",yt);if(!jt)return;yt=jt}(0,qe.isValidEmail)(yt.email)&&(ce.accountPatch=(0,Cn.compactBuyerIdentity)({...ce.accountPatch,...yt}),await Mt.current?.(yt));let nn=(0,qe.buildPayPalTokenizedBody)(lt,qr);await ie(nn,ce)}catch(yt){Yt(yt instanceof Error?yt.message:"PayPal capture failed.")}finally{oe()||bt(!1)}}},Ue=xt=>{let Fe=pe?()=>Qe(pe):()=>U(xt);return async()=>he(await Fe())},et=Ke.Buttons({style:{layout:"horizontal",height:li,tagline:!1},...it==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(xt,Fe)=>{if(oe()){await Fe.reject();return}Zn();let lt=Ln.current,ce={};if(lt)try{let jt=await lt("paypal");if(oe()){await Fe.reject();return}if(!jt.proceed){Zt.current=null,Cr.current.delete(ht),await Fe.reject();return}ce={sessionId:jt.sessionId,accountPatch:jt.accountPatch,nonce:jt.nonce}}catch(jt){q(`onClick:runBeforeButtonClick rejected msg=${(jt instanceof Error?jt.message:String(jt)).slice(0,120)}`),Zt.current=null,Cr.current.delete(ht),await Fe.reject();return}(0,Ye.invokeMerchantCallback)(()=>Nr.current?.("paypal"));let yt=cn(),nn={generation:yt,surfaceKey:ht,...ce};Zt.current=nn,Cr.current.set(ht,nn),je.current={...re,attempt:yt},await Fe.resolve(),Q.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),Q.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nt.current=Q.startTiming()},createOrder:Ae==="order"?Ue("Failed to create PayPal order."):void 0,createSubscription:Ae==="subscription"?Ue("Failed to create PayPal subscription."):void 0,createVaultSetupToken:Ae==="setup_token"?async()=>he(await U("Failed to create PayPal setup token.")):void 0,onApprove:$e,onCancel:()=>{if(oe())return;let xt=Cr.current.get(ht)??Zt.current,Fe=xt&&Ur(xt.generation)?(0,qe.buildPayPalCancelEvent)(xt.sessionId??e,qr):null;xt&&Cr.current.delete(xt.surfaceKey),Zt.current=null,Kt("cancelled"),Q.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Be.current=!0,ir({generation:xt?.generation,remount:!0,focus:!1}),Fe&&(0,Ye.invokeMerchantCallback)(()=>Tt.current?.(Fe))},onError:xt=>{if(xt instanceof qe.FloPayError&&xt.code===Ll)return;let Fe=xt instanceof Error?xt.message:"PayPal failed to render.";if(oe()||Me.current!==ht){gt(Fe)||Lt(wr());return}if(Or){let lt=Cr.current.get(ht)??Zt.current;if(!lt||!Ur(lt.generation)){if(gt(Fe)){!lt&&!zr()&&ar();return}Lt(lt||zr()?"stale_attempt":"no_current_attempt");return}if(q(`onError rendered=${Or} msg=${Fe.slice(0,120)}`),gt(Fe)){ar(lt.generation);return}let{errorCode:ce,popupBlocked:yt,providerDeclined:nn,terminalReason:jt}=(0,we.classifyExternalMethodFailure)(xt,{inAppBrowser:Pe.inAppBrowser,handoffObserved:Y.current===lt.generation});if(yt&&V.markBlocked(),Kt(jt),nn){Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:jt}),ue(xt,lt),(0,Ye.invokeMerchantCallback)(()=>$t.current?.(kr("paypal",Fe))),Cr.current.delete(lt.surfaceKey),Zt.current=null,ar(lt.generation);return}Q.error({errorCode:ce,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:jt}),Cr.current.delete(lt.surfaceKey),Zt.current=null,ir({generation:lt.generation,remount:!0,showRetry:!0,focus:!0}),Qt(xt,{code:"paypal_runtime_failed",popupBlocked:yt,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:jt});return}q(`onError rendered=${Or} msg=${Fe.slice(0,120)}`),ke(gt(Fe)?"teardown":"pre_ready_callback",Fe)}}),qt=et.isEligible();if(q(`isEligible=${qt}`),Q.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!qt){B(!1),ke("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}eo=!0,Qn=et,yr=()=>{if(!rn||mt||oe()||Or)return;mt=!0,q(`container:dims ${lr(gn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Ut=new MutationObserver(Fe=>{if(!oe()){for(let lt of Fe)if(lt.type==="childList")lt.addedNodes.forEach(ce=>{if(!(ce instanceof Element))return;let yt=ce.tagName.toLowerCase(),nn=(ce.getAttribute("title")??"").slice(0,40),jt=yt==="iframe"?` ${ho(ce)}`:"";q(`child+ ${yt}${nn?` title="${nn}"`:""}${jt} dims=${lr(ce)}`)});else if(lt.type==="attributes"&&lt.target instanceof Element){let ce=lt.target;if(ce.tagName.toLowerCase()!=="iframe")continue;let yt=lt.attributeName;(yt==="src"||yt==="srcdoc")&&q(`attr~ iframe ${yt}=${yt==="srcdoc"?`[${(ce.getAttribute("srcdoc")??"").length}ch]`:Gr(ce.getAttribute("src"))} dims=${lr(ce)}`)}}}),Ut.observe(gn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let xt=Fe=>{if(oe()||Or)return;let lt=gn.querySelectorAll("iframe"),ce=typeof document<"u"&&"hasStorageAccess"in document;q(`watchdog:${Fe} container=${lr(gn)} children=${gn.childElementCount} iframes=${lt.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ce} paypalNetRequests=${ro.value}`),lt.forEach((yt,nn)=>{let jt=(yt.getAttribute("title")??"").slice(0,40);q(` iframe[${nn}] ${lr(yt)}${jt?` title="${jt}"`:""} ${ho(yt)}`);let _n=to(yt);_n&&q(` ${_n}`)}),In.length===0&&q(" (no PayPal/zoid window errors captured)")};tn.push(setTimeout(()=>xt("3s"),3e3)),tn.push(setTimeout(()=>xt("8s"),8e3)),tn.push(setTimeout(()=>xt("15s"),15e3))},yr(),q("render:start");let fr=Q.startTiming();dn=setTimeout(()=>{oe()||Or||(q("watchdog:11s retryable render timeout"),ke("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},hd);let _o=et.render(gn);(async()=>{try{if(await _o,q(`render:resolved inactive=${oe()}`),ne(),oe()){mo();return}Or=!0,B(!0),ft(!1),Zr.current?.("ready"),Q.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),Q.performance({stage:"checkout_render",durationMs:Q.elapsed(fr),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(xt){let Fe=xt instanceof Error?xt.message:"PayPal failed to render.";q(`render:rejected msg=${Fe.slice(0,120)}`),ne(),ke(gt(Fe)?"teardown":"render_rejected",Fe)}})()}).catch(Ke=>{let $e=Ke instanceof Error?Ke.message:"PayPal operation failed.";q(`provider:failed msg=${$e.slice(0,120)}`);let Ue="script_rejected";X&&gt($e)?Ue="teardown":X&&eo&&(Ue="render_rejected"),ke(Ue,$e)})},0);return()=>{ve=!0,clearTimeout(Rr),zn&&clearTimeout(zn),ne(),z.current===Se&&(z.current=null),mo(),nt.current=null,je.current=null}},[Te,_t,c,m,p,Ae,it,Ve,e,pe,Ne,ee,O,be,q,Kt]);let Kr=x?(0,bn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:St?"#fef2f2":"#f3f4f6",border:`1px solid ${St?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${fe} failed=${St})`,se.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
3
  ${se.join(`
4
- `)}`]}):null;return St&&!d?B?(0,Cn.jsx)("div",{children:Kr}):null:(0,Cn.jsxs)("div",{children:[Kr,ut&&(0,Cn.jsx)(Ho,{identity:ut.identity,methodLabel:ut.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:xe,onCancel:()=>xe(null)}),(0,Cn.jsxs)("div",{"aria-hidden":ge||ut?!0:void 0,style:ge||ut?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:si},children:[!fe&&!ge&&(0,Cn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,Cn.jsx)("div",{ref:H,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:si,display:"flex",opacity:fe?1:0},"aria-busy":M||P},Ne)]},Ne),et&&(0,Cn.jsx)("button",{ref:Ve,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:br,style:hd,children:"Try PayPal again"})]})}function ba(e){return(0,Cn.jsx)(Ul,{...e})}function zl(e){return(0,Cn.jsx)(Ul,{...e})}var Sa=require("react/jsx-runtime");function Yo({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,Sa.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...r?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...n??{}},children:[r&&(0,Sa.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Sa.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var vt=require("@flopay/shared");var vr=require("react/jsx-runtime");var bd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function an({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:s="PAYMENT FAILED",successNote:c="You will be automatically redirected, do not close or navigate away from this window.",theme:p=bd}){let m={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,vr.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,vr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...p.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,vr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,vr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,vr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,vr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,vr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,vr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,vr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,vr.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,vr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,vr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,vr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,vr.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,vr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:p.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&s]}),e==="success"&&c!==null&&(0,vr.jsx)("p",{style:m,children:c}),e==="error"&&t&&(0,vr.jsx)("p",{style:m,children:t}),(0,vr.jsx)("style",{children:`
4
+ `)}`]}):null;return St&&!d?x?(0,bn.jsx)("div",{children:Kr}):null:(0,bn.jsxs)("div",{children:[Kr,ut&&(0,bn.jsx)(Ho,{identity:ut.identity,methodLabel:ut.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:xe,onCancel:()=>xe(null)}),(0,bn.jsxs)("div",{"aria-hidden":ge||ut?!0:void 0,style:ge||ut?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:li},children:[!fe&&!ge&&(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:H,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:li,display:"flex",opacity:fe?1:0},"aria-busy":A||P},Ne)]},Ne),tt&&(0,bn.jsx)("button",{ref:He,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:br,style:Pd,children:"Try PayPal again"})]})}function ba(e){return(0,bn.jsx)(zl,{...e})}function ql(e){return(0,bn.jsx)(zl,{...e})}var Sa=require("react/jsx-runtime");function Yo({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,Sa.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...r?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...n??{}},children:[r&&(0,Sa.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Sa.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var vt=require("@flopay/shared");var vr=require("react/jsx-runtime");var Sd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function sn({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:s="PAYMENT FAILED",successNote:c="You will be automatically redirected, do not close or navigate away from this window.",theme:p=Sd}){let m={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,vr.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,vr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...p.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,vr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,vr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,vr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,vr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,vr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,vr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,vr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,vr.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,vr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,vr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,vr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,vr.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,vr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:p.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&s]}),e==="success"&&c!==null&&(0,vr.jsx)("p",{style:m,children:c}),e==="error"&&t&&(0,vr.jsx)("p",{style:m,children:t}),(0,vr.jsx)("style",{children:`
5
5
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
6
6
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
7
7
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
8
8
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
9
- `})]})})}var ql=require("@flopay/shared"),Lr=require("react");var jl=require("react/jsx-runtime");function wa({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,c]=(0,Lr.useState)(e instanceof Promise?null:e),[p,m]=(0,Lr.useState)(t instanceof Promise||!t?null:t),h=(0,Lr.useRef)(null),k=(0,Lr.useRef)(null),w=Go(n);(0,Lr.useEffect)(()=>{w({class:"lifecycle",name:"checkout.mount"})},[w]),(0,Lr.useEffect)(()=>{s&&w({class:"lifecycle",name:"sdk.initialize.ready"})},[w,s]),(0,Lr.useEffect)(()=>{if(s)return Er(s)?.subscribe?.(w)},[w,s]),(0,Lr.useEffect)(()=>{if(!(!p||p===s))return Er(p)?.subscribe?.(w)},[w,s,p]),(0,Lr.useEffect)(()=>{if(!s)return;let _=Er(s);return h.current=_?.beginCheckout()??_?.now()??0,_?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{_?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Lr.useEffect)(()=>{let _=!1;return e instanceof Promise?e.then(Z=>{_||c(Z)},()=>{_||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{_=!0}},[w,e]),(0,Lr.useEffect)(()=>{let _=!1;if(!t){m(null);return}return t instanceof Promise?t.then(Z=>{_||m(Z)},()=>{_||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{_=!0}},[w,t]),(0,Lr.useEffect)(()=>{if(!s||k.current===s)return;k.current=s;let _=Er(s);_?.log({name:"checkout.rendered",stage:"checkout_render"}),w({class:"lifecycle",name:"checkout.rendered"}),_?.performance({stage:"checkout_render",durationMs:_.elapsed(h.current??0),durationMode:"machine"})},[w,s]);let I=(0,ql.resolveBillingApiUrl)(r?.billingApiUrl),G=(0,Lr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:I,emitInstrument:w}),[s,p,I,w]);return(0,jl.jsx)(Pn.Provider,{value:G,children:a})}var Bn=require("@flopay/shared");async function li(e,t){e.current?.abort();let r=new AbortController;e.current=r;try{return await t(r.signal)}finally{e.current===r&&(e.current=null)}}var bn=require("@flopay/js"),ct=require("@flopay/shared");var ka="card";async function Sd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function wd(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:s}=await e.confirmCardPayment(t,r);return{error:s,intent:a??null}}function Xo(e){return new ct.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Rd(){return new ct.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function as(e,t){return Object.assign(e,{checkoutMethod:t})}function so(e,t){let r=e instanceof ct.FloPayError?e:new ct.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ra(e,t){try{return await e()}catch(r){throw so(r,t)}}function Wl(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function $l(e){return(0,bn.runSavedCardChallenge)(e)}async function Jo(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,c=new bn.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,bn.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:k=>Kn({type:k.declineReason??"authorization_declined",gatewayErrorCode:k.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},c)}catch(k){if(a.aborted||k instanceof Error&&k.name==="AbortError")throw k instanceof ct.FloPayError&&k.code==="three_ds_aborted"?k:Xo(k);if(!(k instanceof ct.FloPayError)||k.code!=="three_ds_timeout"&&k.code!=="checkout_processing_timeout")throw k;try{m=await c.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(I){if(a.aborted)throw Xo(I);if(!(I instanceof ct.FloPayError)||I.code!=="checkout_processing_timeout")throw I}let w=m&&fo(m,t.session);if(!oo(w)&&w?.status!=="expired"){if(t.telemetry){let I=new bn.PaymentAPI(r);try{I.reportThreeDsAbandoned(n)}finally{I.destroy()}}throw Rd()}}let h=m&&fo(m,t.session);if(!oo(h))throw Vo(h);return{...no(h,n),checkoutMethod:"card"}}function Kn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,s=(0,So.applyFriendlyMessageOverride)(a)??a,c=as(new ct.FloPayError(s,"api_error",{code:e?.code??(0,ct.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,ct.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(c.orderId=e.orderId),c}function os(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ci(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Hl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ci(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,s=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let p of s)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||ci(p)))return p;let c=a.gateways;if(c&&typeof c=="object"){let p=c.stripe;if(p&&typeof p=="object"){let m=p,h=[m.stripeClientSecret,m.clientSecret];for(let k of h)if(typeof k=="string"&&k.length>0&&(!t?.requirePaymentIntentClientSecret||ci(k)))return k}}}}async function kd({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Hl(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let p=(await new bn.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(ci(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function Zo({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:c}){let p=e.replace(/\/+$/,""),m=t??r.id,h=n??r.clientSecret,k=r.customer?.id??r.accountData?.userId??"",w=r.customer?.email??r.accountData?.email??"",I=r.customer?.firstName??r.accountData?.firstName??"",G=r.customer?.lastName??r.accountData?.lastName??"",_=r.customer?.country??r.accountData?.country??void 0,Z=r.customer?.zip??r.accountData?.zip??void 0,f=await new bn.PaymentAPI(p,c===!1?{telemetry:!1}:void 0).processPayment(k,{sessionId:m,nonce:h,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:k,email:w,firstName:I,lastName:G,country:_,zip:Z},returnUrl:s??os(r)});if(f.ok){let S=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,ct.isAuthorizationOnlySession)(r)||S?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof S?.paymentId=="string"?S.paymentId:r.paymentId,sessionId:typeof S?.sessionId=="string"?S.sessionId:m,authorizationExpiresAt:typeof S?.authorizationExpiresAt=="string"?S.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:ha(a),checkoutMethod:Vl(a,r)}};let Te=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Te?{paymentIntentId:Te}:{},paymentMethodId:ha(a),checkoutMethod:Vl(a,r)}}}let P;try{P=await f.json()}catch(S){throw new ct.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:S})}if(P?.type==="3ds_required"&&typeof P.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:P.nextActionRedirectUrl};if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let S=Hl(P);if(!S)throw new ct.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:P.type,threeDSecureToken:S,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let S=await kd({billingApiUrl:p,sessionId:m,nonce:h,responseJson:P});if(S)return S;throw as(new ct.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new ct.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:f.status});throw Object.assign(me,{telemetryOutcome:(0,ct.classifyPaymentRejection)(f.status,P)})}async function di(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:m,signal:h}){let k=t?.getRawProvider();if(!k)throw so(new ct.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw as(new ct.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let w=(0,ct.isSetupIntentClientSecret)(e.threeDSecureToken),I=null,G=e.paymentMethodId,_=await Ra(()=>Sd(k,e.threeDSecureToken,w),"card");if(_){if(_.error)throw so(new ct.FloPayError(_.error.message??`Failed to retrieve 3DS ${w?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let A=_.intent;!G&&A?.payment_method&&(typeof A.payment_method=="string"?G=A.payment_method:"id"in A.payment_method&&(G=A.payment_method.id??void 0))}let Z=G?await Ra(()=>wd(k,e.threeDSecureToken,{payment_method:G,return_url:p??os(c)??window.location.href},w),"card"):null;if(Z){if(Z.error)throw so(new ct.FloPayError(Z.error.message??"3DS authentication failed.","api_error",{code:Z.error.code}),"card");I=Z.intent}else{let A=await Ra(()=>k.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(A.error)throw so(new ct.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");I=(w?A.setupIntent:A.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let A=await Zo({billingApiUrl:a,sessionId:s,session:c,telemetry:m,tokenizedData:{id:I.id,type:"card",threeDSecureActionResultTokenId:I.id},returnUrl:p});return A.type==="success"?{...A.result,paymentIntentId:A.result.paymentIntentId??I.id,paymentMethodId:A.result.paymentMethodId??G}:A.type==="next_action_required"?Jo(A,{billingApiUrl:a,sessionId:s??c.id,session:c,signal:h}):di(A,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:m,signal:h})}throw so(new ct.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let w=(r??t)?.getRawProvider();if(!w)throw so(new ct.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:G}=await Ra(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(G)throw so(new ct.FloPayError(G.message??"PayPal authorization failed.","api_error",{code:G.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:I}=await Ra(()=>w.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??os(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(I)throw so(new ct.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new ct.FloPayError("Unsupported payment redirect state.","api_error")}function Ea(e){if(e instanceof ct.FloPayError){let n=(0,So.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new ct.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,So.applyFriendlyMessageOverride)(t)??t;return new ct.FloPayError(r,"api_error")}function is(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,ct.isMountableVaultBlock)(e.data.session?.vault)||(0,xn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new ct.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Vl(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,xn.canRecoverHostedCardForm)(t)?"card":void 0}async function ss({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let s=t&&t!==e?t:void 0,[c,p]=await Promise.all([(0,bn.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,bn.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(h=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",h),null)):Promise.resolve(null)]);if(!c)throw new ct.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=c),{flopay:c,paypalFlopay:m}}var On=require("@flopay/js"),l=require("@flopay/shared"),dr=require("@stripe/react-stripe-js"),o=Ji(require("react"),1);function ko(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ui(e,t){if(e)return{error:r=>e.error(ko(t,r)),log:r=>e.log(ko(t,r)),performance:r=>e.performance(ko(t,r)),terminal:r=>e.terminal(ko(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var lo=require("@flopay/shared"),Gl=require("react");var Kl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var Ar=require("react/jsx-runtime"),Ed=`
9
+ `})]})})}var jl=require("@flopay/shared"),Lr=require("react");var Vl=require("react/jsx-runtime");function wa({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,c]=(0,Lr.useState)(e instanceof Promise?null:e),[p,m]=(0,Lr.useState)(t instanceof Promise||!t?null:t),h=(0,Lr.useRef)(null),k=(0,Lr.useRef)(null),w=Go(n);(0,Lr.useEffect)(()=>{w({class:"lifecycle",name:"checkout.mount"})},[w]),(0,Lr.useEffect)(()=>{s&&w({class:"lifecycle",name:"sdk.initialize.ready"})},[w,s]),(0,Lr.useEffect)(()=>{if(s)return Er(s)?.subscribe?.(w)},[w,s]),(0,Lr.useEffect)(()=>{if(!(!p||p===s))return Er(p)?.subscribe?.(w)},[w,s,p]),(0,Lr.useEffect)(()=>{if(!s)return;let _=Er(s);return h.current=_?.beginCheckout()??_?.now()??0,_?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{_?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Lr.useEffect)(()=>{let _=!1;return e instanceof Promise?e.then(Z=>{_||c(Z)},()=>{_||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{_=!0}},[w,e]),(0,Lr.useEffect)(()=>{let _=!1;if(!t){m(null);return}return t instanceof Promise?t.then(Z=>{_||m(Z)},()=>{_||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{_=!0}},[w,t]),(0,Lr.useEffect)(()=>{if(!s||k.current===s)return;k.current=s;let _=Er(s);_?.log({name:"checkout.rendered",stage:"checkout_render"}),w({class:"lifecycle",name:"checkout.rendered"}),_?.performance({stage:"checkout_render",durationMs:_.elapsed(h.current??0),durationMode:"machine"})},[w,s]);let I=(0,jl.resolveBillingApiUrl)(r?.billingApiUrl),G=(0,Lr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:I,emitInstrument:w}),[s,p,I,w]);return(0,Vl.jsx)(vn.Provider,{value:G,children:a})}var Bn=require("@flopay/shared");async function ci(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 Yr=require("@flopay/js"),ct=require("@flopay/shared");var ka="card";async function wd(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 Xo(e){return new ct.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function kd(){return new ct.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function is(e,t){return Object.assign(e,{checkoutMethod:t})}function so(e,t){let r=e instanceof ct.FloPayError?e:new ct.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ra(e,t){try{return await e()}catch(r){throw so(r,t)}}function $l(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 Hl(e){return(0,Yr.runSavedCardChallenge)(e)}function Ea(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new Yr.PaymentAPI(e),c=(0,Yr.beginSavedCardChallengeTelemetry)(s,t,r);return c?{telemetry:c,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function Jo(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,c=new Yr.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,Yr.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:k=>Kn({type:k.declineReason??"authorization_declined",gatewayErrorCode:k.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},c)}catch(k){if(a.aborted||k instanceof Error&&k.name==="AbortError")throw k instanceof ct.FloPayError&&k.code==="three_ds_aborted"?k:Xo(k);if(!(k instanceof ct.FloPayError)||k.code!=="three_ds_timeout"&&k.code!=="checkout_processing_timeout")throw k;try{m=await c.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(I){if(a.aborted)throw Xo(I);if(!(I instanceof ct.FloPayError)||I.code!=="checkout_processing_timeout")throw I}let w=m&&fo(m,t.session);if(!oo(w)&&w?.status!=="expired"){if(t.telemetry){let I=new Yr.PaymentAPI(r);try{I.reportThreeDsAbandoned(n)}finally{I.destroy()}}throw kd()}}let h=m&&fo(m,t.session);if(!oo(h))throw Vo(h);return{...no(h,n),checkoutMethod:"card"}}function Kn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,s=(0,So.applyFriendlyMessageOverride)(a)??a,c=is(new ct.FloPayError(s,"api_error",{code:e?.code??(0,ct.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,ct.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(c.orderId=e.orderId),c}function as(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function di(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Kl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||di(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||di(p)))return p;let c=a.gateways;if(c&&typeof c=="object"){let p=c.stripe;if(p&&typeof p=="object"){let m=p,h=[m.stripeClientSecret,m.clientSecret];for(let k of h)if(typeof k=="string"&&k.length>0&&(!t?.requirePaymentIntentClientSecret||di(k)))return k}}}}async function Ed({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Kl(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 Yr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(di(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function Zo({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:c}){let p=e.replace(/\/+$/,""),m=t??r.id,h=n??r.clientSecret,k=r.customer?.id??r.accountData?.userId??"",w=r.customer?.email??r.accountData?.email??"",I=r.customer?.firstName??r.accountData?.firstName??"",G=r.customer?.lastName??r.accountData?.lastName??"",_=r.customer?.country??r.accountData?.country??void 0,Z=r.customer?.zip??r.accountData?.zip??void 0,f=await new Yr.PaymentAPI(p,c===!1?{telemetry:!1}:void 0).processPayment(k,{sessionId:m,nonce:h,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:k,email:w,firstName:I,lastName:G,country:_,zip:Z},returnUrl:s??as(r)});if(f.ok){let S=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,ct.isAuthorizationOnlySession)(r)||S?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof S?.paymentId=="string"?S.paymentId:r.paymentId,sessionId:typeof S?.sessionId=="string"?S.sessionId:m,authorizationExpiresAt:typeof S?.authorizationExpiresAt=="string"?S.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:ha(a),checkoutMethod:Wl(a,r)}};let Te=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Te?{paymentIntentId:Te}:{},paymentMethodId:ha(a),checkoutMethod:Wl(a,r)}}}let P;try{P=await f.json()}catch(S){throw new ct.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:S})}if(P?.type==="3ds_required"&&typeof P.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:P.nextActionRedirectUrl};if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let S=Kl(P);if(!S)throw new ct.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:P.type,threeDSecureToken:S,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let S=await Ed({billingApiUrl:p,sessionId:m,nonce:h,responseJson:P});if(S)return S;throw is(new ct.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new ct.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:f.status});throw Object.assign(me,{telemetryOutcome:(0,ct.classifyPaymentRejection)(f.status,P)})}async function ui(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:m,signal:h}){let k=t?.getRawProvider();if(!k)throw so(new ct.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw is(new ct.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let w=(0,ct.isSetupIntentClientSecret)(e.threeDSecureToken),I=null,G=e.paymentMethodId,_=await Ra(()=>wd(k,e.threeDSecureToken,w),"card");if(_){if(_.error)throw so(new ct.FloPayError(_.error.message??`Failed to retrieve 3DS ${w?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let F=_.intent;!G&&F?.payment_method&&(typeof F.payment_method=="string"?G=F.payment_method:"id"in F.payment_method&&(G=F.payment_method.id??void 0))}let Z=G?await Ra(()=>Rd(k,e.threeDSecureToken,{payment_method:G,return_url:p??as(c)??window.location.href},w),"card"):null;if(Z){if(Z.error)throw so(new ct.FloPayError(Z.error.message??"3DS authentication failed.","api_error",{code:Z.error.code}),"card");I=Z.intent}else{let F=await Ra(()=>k.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(F.error)throw so(new ct.FloPayError(F.error.message??"3DS authentication failed.","api_error",{code:F.error.code}),"card");I=(w?F.setupIntent:F.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let F=await Zo({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??G}:F.type==="next_action_required"?Jo(F,{billingApiUrl:a,sessionId:s??c.id,session:c,signal:h}):ui(F,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:m,signal:h})}throw so(new ct.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let w=(r??t)?.getRawProvider();if(!w)throw so(new ct.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:G}=await Ra(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(G)throw so(new ct.FloPayError(G.message??"PayPal authorization failed.","api_error",{code:G.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:I}=await Ra(()=>w.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??as(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(I)throw so(new ct.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new ct.FloPayError("Unsupported payment redirect state.","api_error")}function Ia(e){if(e instanceof ct.FloPayError){let n=(0,So.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new ct.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,So.applyFriendlyMessageOverride)(t)??t;return new ct.FloPayError(r,"api_error")}function ss(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,ct.isMountableVaultBlock)(e.data.session?.vault)||(0,xn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new ct.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Wl(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,xn.canRecoverHostedCardForm)(t)?"card":void 0}async function ls({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,Yr.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,Yr.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(h=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",h),null)):Promise.resolve(null)]);if(!c)throw new ct.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=c),{flopay:c,paypalFlopay:m}}var On=require("@flopay/js"),l=require("@flopay/shared"),dr=require("@stripe/react-stripe-js"),o=Zi(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 pi(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"),Yl=require("react");var Gl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var Ar=require("react/jsx-runtime"),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 @@ ${se.join(`
27
27
  0% { opacity: 1; transform: translateX(0) scale(1); }
28
28
  100% { opacity: 0; transform: translateX(16px) scale(0.97); }
29
29
  }
30
- `,Qo=44;function ea(){return(0,Ar.jsx)("style",{children:Ed})}function Ia(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function _a({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Ar.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Ar.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,Ar.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:n})]})}function ls(e){return e!=="unavailable"&&e!=="load_error"}function pi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:c,backgroundColor:p,borderColor:m,textColor:h,borderRadius:k,fontFamily:w}){let I=(0,lo.resolveStripeMethodBrandVariant)(e,t),G=Kl[e],[_,Z]=(0,Gl.useState)(!1),A=!!G&&!_,f=I?.backgroundColor??p??"#ffffff",P=I?.borderColor??m??"#d1d5db",me=I?.textColor??h??"#262833";return(0,Ar.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&c()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Qo,padding:"0 1rem",backgroundColor:f,color:me,border:`1px solid ${P}`,borderRadius:k??8,fontSize:"0.95rem",fontWeight:600,fontFamily:w,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,Ar.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,lo.getStripeMethodDisplayName)(e)}\u2026`}):(0,Ar.jsxs)(Ar.Fragment,{children:[(0,Ar.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,lo.hasVendoredStripeMethodLogo)(e)?8:0},children:[A?(0,Ar.jsx)("img",{src:G,alt:"","aria-hidden":"true",onError:()=>Z(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!A&&I?.logoSvg?(0,Ar.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:I.logoSvg}}):null,(0,Ar.jsx)("span",{children:(0,lo.getStripeMethodDisplayName)(e)})]}),s&&(0,Ar.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:me,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,Ar.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function mi(e){let t=new Set(e.map(lo.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var yi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},fi={type:"accordion",defaultCollapsed:!1,radios:"never"};function gi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:c,children:p}){return(0,Ar.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:s,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...c??{}},children:p})}var mn=require("react");var Ta=require("@flopay/shared"),Id=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function _d(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Id.has(t.charAt(0).toLowerCase()+t.slice(1))}function Td(e,t){return typeof t=="number"&&t!==0&&!_d(e)?`${t}px`:String(t).trim()}function Yl(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=Td(r,n)}}}var Eo=require("react/jsx-runtime"),cs=new WeakSet;function go({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:c,containerStyle:p,onReady:m,onError:h,onValidation:k}){let w=(0,mn.useRef)(null),I=(0,mn.useRef)(m),G=(0,mn.useRef)(h),_=(0,mn.useRef)(k);I.current=m,G.current=h,_.current=k;let Z=(0,mn.useRef)(s);Z.current=s;let A=(0,mn.useRef)(null),f=c??void 0,P=(0,mn.useRef)(f);P.current=f;let me=(0,mn.useRef)(void 0);return(0,mn.useEffect)(()=>{let S=w.current;if(!S)return;let Te=!0,T=!1,ae=()=>{!Te||T||(T=!0,I.current?.())},ye=e.on("ready",()=>{ae()}),pe=e.on("error",B=>{G.current?.(B.message??"There was a problem loading the secure card form.")}),we=e.on("validation",B=>{_.current?.(B.message??null)}),dt=P.current??(cs.has(e)?null:void 0),Ke={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...Z.current?{theme:Z.current}:{},...dt===void 0?{}:{submitLabel:dt}};return A.current=Z.current??null,me.current=P.current,P.current!==void 0&&cs.add(e),e.mount(S,Ke).then(()=>{ae()}).catch(B=>{Te&&G.current?.(B instanceof Error?B.message:"Failed to load the secure card form.")}),()=>{Te=!1,ye(),pe(),we(),e.unmount()}},[e,t,r,n,a]),wo(()=>{let S=w.current;S&&Yl(S,p)},[p]),(0,mn.useEffect)(()=>{s!==void 0&&(s===null&&A.current===null||(A.current=s,e.applyTheme?.(s)))},[e,s]),(0,mn.useEffect)(()=>{f!==me.current&&(me.current=f,f!==void 0&&cs.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,Eo.jsx)("div",{ref:w,"data-testid":"flopay-vault-card-fields"})}function hi({label:e}){return(0,Eo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,Eo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,Eo.jsx)("span",{children:e}),(0,Eo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var Cs=require("@flopay/shared"),u=require("react/jsx-runtime"),Gn="flopay_stripe_resume",Xl="flopay_wallet_resume",ic="fw1",Md="fw2",sc=300*1e3,xd=900,Ad="express_checkout_click_timeout",Fd=25e3,Bd=25e3,Dd=1e4,Dn={provider:"paypal",paymentMethodCategory:"paypal"},Od="x-flopay-process-result-source",Ld="status";async function Nd(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var Pi={},xa=class{constructor(t){this.reason=t}};function Ud(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function ur(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function hs(e){return`${Md}:${e}`}function vi(e){return ur(hs(e))}function Ci(e,t){if(typeof window>"u")return null;let r=hs(e);try{let n=localStorage.getItem(r);if(!n)return null;let a=JSON.parse(n);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>sc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(vi(e),null):a}catch{return vi(e),null}}function zd(e){return ur(hs(e.sessionId),e)}function Jl(e,t,r){let n=Ci(e,t);return!n||n.clientSecret!==r?!1:vi(e)}function ds(e,t,r){if(typeof window>"u")return;Ci(e,t)?.clientSecret===r&&vi(e)}function qd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function us(e,t,r){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let n=r?e.status==="succeeded":ga(e.status),a=qd(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Zl(e,t,r){let n=null;try{return await Promise.race([Ml(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Dd),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function jd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function lc(e){return e instanceof l.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function bi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new On.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw lc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var ps=l.STRIPE_PAYPAL_RESUME_KEY,Ma=new Map,Vd=250,Ql="Just a moment \u2014 we are finalizing your order. Please press pay again.",Wd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Ps(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function Si({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new On.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function $d(e){return e instanceof l.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function cc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,Wo.splitFullName)(r),c=s.firstName?s:(0,Wo.splitFullName)(n?.name);return(0,vn.compactBuyerIdentity)({email:(0,l.isValidEmail)(a)?a:n?.email?.trim(),firstName:c.firstName,lastName:c.lastName})}async function Hd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let c=cc({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,l.isValidEmail)(c.email)?c:s(a,c)}var Aa=180,ec=`flopay-card-enter ${Aa}ms cubic-bezier(0, 0, 0.2, 1) both`,tc=`flopay-card-exit ${Aa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Kd=`flopay-buttons-enter ${Aa}ms cubic-bezier(0, 0, 0.2, 1) both`,Gd=`flopay-buttons-exit ${Aa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Yd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function vs(e){return(0,l.derivePrimaryTileStyle)(e)}var Xd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Jd(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var ys={width:"100%",minHeight:Qo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function rc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function fs(e){return e==="paypal"?"PayPal":(0,l.getStripeMethodDisplayName)(e)}function Zd(e){let t=(0,l.getPostalCodeExample)(e);return`Enter a valid ${(0,l.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Qd(e,t,r){let n=(0,l.isPostalCodeSupported)(e),a=t.trim(),s=r&&n,c=s&&!a,p=s&&!!a&&!(0,l.isValidPostalCode)(e,a);return{visible:r,supported:n,required:s,empty:c,malformed:p}}function eu(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,l.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function tu(e){return typeof e=="number"?`${e}px`:e}function wi(e){return(0,u.jsx)(ou,{...e})}function nc({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:c=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:h,runBeforeButtonClick:k,billingName:w,onBuyerIdentityReady:I,onLoadStateChange:G,placeholderBorderRadius:_,popupCapabilityOwner:Z,externalTelemetryContext:A,presentationMode:f}){let P=io(),{emitInstrument:me}=(0,o.useContext)(Pn),S=(0,dr.useStripe)(),Te=(0,dr.useElements)(),T=(0,o.useMemo)(()=>ui(Er(P),A),[A,P]),[ae,ye]=(0,o.useState)("loading");(0,o.useEffect)(()=>{G?.(ae)},[ae,G]);let[pe,we]=(0,o.useState)(!1),dt=(0,o.useRef)(!1),Ke=!(0,l.isValidEmail)(r?.trim())||!w?.trim(),{request:B,collect:kt,finish:Je}=$o(),Le=(0,o.useRef)(!1),de=(0,o.useRef)(null),ee=(0,o.useRef)(null),[H,Oe]=(0,o.useState)(0),[nt,qe]=(0,o.useState)(!1),Y=(0,o.useRef)(!1),W=(0,o.useRef)(new Map),{startAttempt:$,finishAttempt:j,invalidateAttempt:Ve,isAttemptInvalidated:Be,isAttemptCurrent:fe,generationRef:D}=Ca((ve,M,bt)=>{h?.(ve,M,{...bt,popupBlocked:bt?.popupBlocked??(0,Se.isPopupBlockedError)(M),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),qe(!0),Oe(ut=>ut+1)},{onHandoffObserved:()=>{Z.markAvailable(),T?.log({name:"provider.popup.opened",stage:"overlay_open",...Dn,attempt:D.current})}});(0,o.useEffect)(()=>{nt&&ee.current?.focus()},[nt,H]);let ge=(0,o.useCallback)(()=>{Oe(ve=>ve+1)},[]),ft=(0,o.useCallback)((ve,M,bt)=>{Ve(bt),h?.("paypal",ve,{code:M,popupBlocked:(0,Se.isPopupBlockedError)(ve),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),qe(!0),ge()},[Ve,h,f,ge]),Ne=(0,o.useCallback)(()=>{window.setTimeout(()=>{(de.current?.querySelector("iframe")??de.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Y.current&&(Y.current=!1,Ne())},[Ne,H]);let ot=(0,o.useCallback)(()=>{qe(!1),s?.(null),Ne()},[Ne,s]);(0,o.useEffect)(()=>{if(!S||Le.current)return;let[ve,M,bt]=(0,l.readStripeRedirectParams)();if(!ve||!M)return;let ut=(0,l.readMatchingStripePayPalContinuation)(M);if(!ut)return;Le.current=!0;let O=!0,xe=Ma.get(M);xe||(xe=bt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>S.retrievePaymentIntent(M)),Ma.set(M,xe));let Ot={accountPatch:ut.accountPatch,sessionId:ut.sessionId,nonce:ut.nonce},Ce=()=>{T?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Dn,requestCategory:"provider_sdk"})};return T?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Dn}),(async()=>{try{we(!0);let b=await xe;if(!O)return;if(b?.error){Ma.delete(M),Ce(),s?.(b.error.message??"Failed to retrieve PayPal payment status.");return}if((0,l.clearStripePayPalReturn)(),Ma.delete(M),bt==="failed"){let Ae="PayPal payment was declined. Please try again.";T?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}),s?.(Ae),m?.(kr("paypal",Ae));return}let x=b?.paymentIntent;if(x&&x.id!==ve){Ce(),s?.("Failed to match the returned PayPal payment.");return}if(x&&(x.status==="requires_capture"||x.status==="succeeded")){let Ae=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id;a({id:Ae??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0},{...Ot,presentationMode:"redirect"})}else{let Ae="PayPal payment was not completed. Please try again.";T?.terminal({outcome:x?.status==="canceled"?"payment_cancelled":"payment_declined",...Dn,terminalReason:x?.status==="canceled"?"cancelled":"provider_declined"}),s?.(Ae),m?.(kr("paypal",Ae))}}catch(b){if(!O)return;Ma.delete(M),Ce(),s?.(b instanceof Error?b.message:"Failed to complete PayPal payment.")}finally{O&&we(!1)}})(),()=>{O=!1,Le.current=!1}},[S,a,s,m,T]);let Me=(0,o.useCallback)(async(ve=!1)=>{let M=k?await k("paypal"):{proceed:!0};if(!M.proceed)return W.current.delete(H),!1;let bt=$("paypal");return W.current.set(H,{generation:bt,accountPatch:M.accountPatch,sessionId:M.sessionId,nonce:M.nonce}),qe(!1),T?.log({name:`provider.${ve?"redirect.started":"handoff.requested"}`,stage:ve?"redirect":"overlay_open",...Dn,attempt:bt}),p?.("paypal"),!0},[p,T,k,$,H]),et=(0,o.useCallback)(async ve=>{if(c||pe||!await Me()){ve.reject();return}ve.resolve()},[c,Me,pe]),at=(0,o.useCallback)(async ve=>{if(!S||!Te)return;let M=W.current.get(H);if(M&&!fe(M.generation)){W.current.delete(H);return}if(!M&&Be()||M&&!j(M.generation))return;M||j();let bt=M??null;if(W.current.delete(H),!bt&&k){let _t=await k("paypal");if(!_t.proceed){ve.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}bt={accountPatch:_t.accountPatch,sessionId:_t.sessionId,nonce:_t.nonce}}let ut=bt?.sessionId??e,O=bt?.nonce??t,xe=await Hd({event:ve,prepared:bt,email:r,billingName:w,methodLabel:"PayPal",collect:kt});if(!xe){ve.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ot=xe.email,Ce={...bt?.accountPatch,...(0,vn.compactBuyerIdentity)(xe,!0)};try{if(we(!0),s?.(null),!ut||!(0,l.isValidEmail)(Ot))throw new Error("Missing sessionId or email for PayPal payment");await I?.(xe);let _t=S.createPaymentMethod,{error:b,paymentMethod:x}=await _t({type:"paypal"});if(b){ft(b,"stripe_paypal_create_payment_method_failed",M?.generation),ve.paymentFailed({reason:"fail"});return}let Ae=await bi(n,me,ut,O??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:x?.id??null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(Ae)){ve.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:Ce,paymentMethodCategory:"paypal",presentationMode:f,sessionId:ut,nonce:O,settledProcessResponse:Ae.response});return}if(Ae.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Re=Ae.clientSecret,pt={return_url:(0,l.stripeRedirectReturnUrl)()};if(x?.id&&(pt.payment_method=x.id),!ur(ps,{clientSecret:Re,sessionId:ut,nonce:O,accountPatch:Ce})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:We,paymentIntent:Ge}=await S.confirmPayment({clientSecret:Re,confirmParams:pt,redirect:"if_required"});if(We){if(ur(ps),(0,Se.isProviderDecline)(We)){let d=We.message??"Your payment was declined.";T?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}),s?.(d),m?.(kr("paypal",d,{code:(0,Se.getProviderErrorCode)(We),declineCode:(0,Se.getProviderDeclineCode)(We)})),await Si({billingApiUrl:n,sessionId:ut,nonce:O,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,Se.getProviderErrorCode)(We)??"provider_declined"}})}else ft(We,"stripe_paypal_confirm_failed",M?.generation);return}ur(ps);let Dt=typeof Ge?.payment_method=="string"?Ge.payment_method:Ge?.payment_method?.id;a({id:Dt??Ge?.id,type:"card",threeDSecureActionResultTokenId:Ge?.id,isPaypal:!0},{accountPatch:Ce,paymentMethodCategory:"paypal",presentationMode:f,sessionId:ut,nonce:O});return}catch(_t){ft(_t,"stripe_paypal_failed",M?.generation)}finally{we(!1)}},[S,Te,e,t,r,w,kt,I,n,me,a,s,m,k,ft,j,fe,Be,T,f,H]),mr=(0,o.useCallback)(async()=>{if(!(dt.current||c||pe||!S||!Te)){dt.current=!0,we(!0);try{if(!await Me(!0))return;await at({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{dt.current=!1,we(!1)}}},[Te,at,c,Me,S,pe]),Ft=f==="redirect"?(0,u.jsx)("button",{type:"button",disabled:c||pe,onClick:()=>{mr()},style:{width:"100%",minHeight:Qo,border:"1px solid #d1d5db",borderRadius:_??8,background:"#ffc439",color:"#111827",cursor:c||pe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,u.jsx)(dr.ExpressCheckoutElement,{onReady:ve=>ye(Ia(ve,["paypal"])),onLoadError:()=>{ye("load_error"),Ps(T,"paypal","paypal","provider_error")},onClick:et,onConfirm:at,onCancel:()=>{let ve=W.current.get(H);W.current.delete(H),T?.terminal({outcome:"payment_cancelled",...Dn,terminalReason:"cancelled",...ve?{attempt:ve.generation}:{}}),Ve(ve?.generation),qe(!1),Y.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Ke,emailRequired:Ke,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},H),St=(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("div",{ref:de,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[nt&&(0,u.jsx)("button",{ref:ee,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:ys,children:"Try PayPal again"}),B&&(0,u.jsx)(Ho,{identity:B.identity,methodLabel:B.methodLabel,onComplete:Je,onCancel:()=>Je(null)},B.id),(0,u.jsx)("div",{style:{display:B?"none":void 0},children:Ft})]}),pe&&!B&&(0,u.jsx)(an,{status:"processing"})]});return f==="redirect"?St:(0,u.jsx)(_a,{state:ae,placeholderTestId:"flopay-paypal-placeholder",borderRadius:_,children:St})}function ms(e){return e==="apple_pay"||e==="google_pay"}var ru=200;function nu({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,l.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function oc({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:c,onErrorChange:p,onButtonClick:m,onDecline:h,onTechnicalFailure:k,runBeforeButtonClick:w,billingName:I,onBuyerIdentityReady:G,onLoadStateChange:_,placeholderBorderRadius:Z,popupCapabilityOwner:A,externalTelemetryContext:f}){let P=io(),{emitInstrument:me}=(0,o.useContext)(Pn),S=(0,dr.useStripe)(),Te=(0,dr.useElements)(),T=(0,o.useMemo)(()=>ui(Er(P),f),[f,P]),[ae,ye]=(0,o.useState)("loading");(0,o.useEffect)(()=>{_?.(ae)},[ae,_]);let[pe,we]=(0,o.useState)(!1);(0,o.useEffect)(()=>{qe.current=pe},[pe]);let dt=(0,o.useRef)(!(0,l.isValidEmail)(r?.trim())||!I?.trim()).current,{request:Ke,collect:B,finish:kt}=$o(),Je=(0,o.useRef)(null),Le=(0,o.useRef)(null),[de,ee]=(0,o.useState)(0),[H,Oe]=(0,o.useState)(()=>(0,l.shouldPreferWalletPopup)()),nt=(0,o.useRef)(H),qe=(0,o.useRef)(!1),[Y,W]=(0,o.useState)(!1),[$,j]=(0,o.useState)(()=>Ci(e,t)?"blocked":"idle"),[Ve,Be]=(0,o.useState)("google_pay"),fe=(0,o.useRef)(null),D=(0,o.useRef)(!0),ge=(0,o.useRef)(!1),ft=(0,o.useRef)("google_pay"),Ne=(0,o.useRef)("google_pay"),ot=(0,o.useRef)(null),Me=(0,o.useRef)(null),et=(0,o.useRef)(new Set),at=(0,o.useRef)(null),mr=(0,o.useRef)(null);(0,o.useEffect)(()=>(D.current=!0,()=>{D.current=!1;for(let d of et.current)window.clearTimeout(d);et.current.clear()}),[]);let Ft=(0,o.useRef)(new Map),{startAttempt:St,finishAttempt:ve,invalidateAttempt:M,isAttemptInvalidated:bt,isAttemptCurrent:ut,generationRef:O}=Ca((d,L,V)=>{k?.(d,L,{...V,popupBlocked:V?.popupBlocked??(0,Se.isPopupBlockedError)(L),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Be(d),W(!0),ee(se=>se+1)},{onHandoffObserved:d=>{mr.current=O.current,A.markAvailable(),T?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:O.current,...d==="apple_pay"||d==="google_pay"?{walletType:d}:{}})},defersMissingTerminal:ms,onMissingTerminalDeferred:(d,L)=>{let V=T?.now()??globalThis.performance?.now()??Date.now(),se=at.current,E=se?.generation===L?se.startedAt:V;T?.performance({stage:"overlay_return",durationMs:Math.max(0,V-E),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:L,...ms(d)?{walletType:d}:{}}),T?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{Y&&Le.current?.focus()},[Y,de]);let xe=(0,o.useRef)(0),Ot=(0,o.useRef)(!1),Ce=(0,o.useCallback)(()=>{if(xe.current>0){Ot.current=!0;return}ee(d=>d+1)},[]),_t=(0,o.useCallback)(()=>{xe.current-=1,!(xe.current>0||!Ot.current)&&(Ot.current=!1,D.current&&ee(d=>d+1))},[]),b=(0,o.useCallback)((d,L,V,se,E=!1)=>{M(se),k?.(d,L,{code:V,popupBlocked:(0,Se.isPopupBlockedError)(L),telemetryReported:E,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Be(d),W(!0),Ce()},[M,k,Ce]),x=(0,o.useCallback)(d=>{T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...ms(d)?{walletType:d}:{}}),k?.(d,new Error("The wallet click was not ready within the time the wallet allows."),{code:Ad,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Be(d),W(!0)},[k,T]),Ae=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Je.current?.querySelector("iframe")??Je.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{ge.current&&(ge.current=!1,Ae())},[Ae,de]);let Re=(0,o.useCallback)(()=>{W(!1),p?.(null),Ae()},[Ae,p]),pt=(0,o.useCallback)(()=>{fe.current?.()},[]);(0,o.useEffect)(()=>{let d=null,L=()=>{d=null;let se=(0,l.shouldPreferWalletPopup)();se!==nt.current&&(nt.current=se,Oe(se),!qe.current&&!ut(O.current)&&Ce())},V=()=>{d!==null&&window.clearTimeout(d),d=window.setTimeout(L,ru)};return window.addEventListener("resize",V),()=>{window.removeEventListener("resize",V),d!==null&&window.clearTimeout(d)}},[O,ut,Ce]),(0,o.useEffect)(()=>{let d=Ci(e,t);if(!d)return;let L=!1,V=!1,se=async()=>{if(!V){V=!0,L||j("checking");try{let E=await Zl(S,d.clientSecret,et.current);if(L)return;let U=us(E,d.providerObjectId,(0,l.isSetupIntentClientSecret)(d.clientSecret));if(U.kind==="confirmed"){if(!Jl(e,t,d.clientSecret))return;fe.current=null,j("idle"),c({id:U.paymentMethodId,type:"card",threeDSecureActionResultTokenId:U.intentId},{...d.accountPatch?{accountPatch:d.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(U.kind==="terminal"){ds(e,t,d.clientSecret),fe.current=null,j("idle"),Be(d.paymentMethodType),W(!0),Ce();return}j("blocked")}catch{L||j("blocked")}finally{V=!1}}};return fe.current=se,j("blocked"),()=>{L=!0,fe.current===se&&(fe.current=null)}},[t,c,Ce,e,S]);let it=(0,o.useCallback)(async d=>{let L=!1,V=!1,se=tt=>{L||V||(L=!0,d.paymentFailed({reason:"fail",...tt?{message:tt}:{}}))};if(!S||!Te){se();return}let E=Ft.current.get(de);if(E&&!ut(E.generation)){Ft.current.delete(de),se();return}if(!E&&bt()){se();return}if(E&&!ve(E.generation)){se();return}E||(ve(),Ot.current=!1);let U=d.expressPaymentType??E?.method??ft.current,Nt=E??null,Br=rc(U),rr;U==="apple_pay"?rr="apple_pay":U==="google_pay"&&(rr="google_pay");let $t=E?.generation??O.current,Tt=T,Wr=Tt?.now()??globalThis.performance?.now()??Date.now(),Nr=new AbortController,nr=!1,Jr=!1,Mt=null,Ln=e,Jt="processing",yn="other",$r="provider_runtime",Hr,Zt=new Promise((tt,Et)=>{Hr=Et}),Cr=window.setTimeout(()=>{nr=!0,Nr.abort(),Hr(Pi)},Fd),Zr=async(tt,Et,Dr)=>{Jt=tt,yn=Et,$r=Et==="intent_create"||Et==="session_claim"?"transport_error":"provider_runtime";let Ht=Tt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Dr,Zt])}finally{let or=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.performance({stage:tt,durationMs:Math.max(0,or-Ht),durationMode:"machine",requestCategory:Et,paymentMethodCategory:"wallet",provider:"stripe",...nr?{statusClass:"timeout"}:{}})}};try{if(we(!0),p?.(null),!Nt&&w){let Pe=await Zr("processing","other",w(Br));if(!Pe.proceed){se();return}Nt={accountPatch:Pe.accountPatch,sessionId:Pe.sessionId,nonce:Pe.nonce}}let tt=Nt?.sessionId??e;Ln=tt;let Et=Nt?.nonce??t,Dr=ot.current??Nt?.accountPatch,Ht=cc({event:d,fallbackEmail:Dr?.email??r,fallbackName:[Dr?.firstName,Dr?.lastName].join(" ").trim()||I});if(!(0,l.isValidEmail)(Ht.email)){se("Buyer details are required."),B(fs(U),Ht).then(Pe=>{Pe&&(ot.current=Pe)});return}ot.current=null;let or={...Nt?.accountPatch,...(0,vn.compactBuyerIdentity)(Ht,!0)};await Zr("processing","session_claim",Promise.resolve(G?.(Ht)));let{error:br}=await Zr("tokenization","provider_sdk",Te.submit());if(br){se(),b(U,br,"stripe_wallet_submit_failed",E?.generation);return}if(!tt)throw new Error("Missing sessionId or email for payment.");let Qt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:U,paymentMethodId:null,intentKind:a},Kt=JSON.stringify({sessionId:tt,nonce:Et??"",request:Qt}),_r=Me.current,Ze=_r?.retryIdentity===Kt?_r.authorizationAttemptId:(0,l.randomUuidV4)();Me.current={authorizationAttemptId:Ze,retryIdentity:Kt};let ar=await Zr("processing","intent_create",bi(n,me,tt,Et??"",{...Qt,authorizationAttemptId:Ze},{signal:Nr.signal}));if((0,l.isSettledSessionIntent)(ar)){se(),c({type:"card",paymentMethodType:U},{accountPatch:or,paymentMethodCategory:"wallet",sessionId:tt,nonce:Et,settledProcessResponse:ar.response});return}if(ar.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Tr=ar.clientSecret,Jn=zd({createdAt:Date.now(),sessionId:tt,...Et?{nonce:Et}:{},clientSecret:Tr,providerObjectId:ar.providerObjectId,paymentMethodType:U,accountPatch:or});window.clearTimeout(Cr),Jr=!0,Tt?.performance({stage:"callback",durationMs:Math.max(0,(Tt?.now()??globalThis.performance?.now()??Date.now())-Wr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Ur=Tt?.now()??globalThis.performance?.now()??Date.now(),zr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...rr?{walletType:rr}:{},attempt:$t},Nn=!1,ln=null;Tt?.log({name:"payment.provider_confirmation.started",...zr}),Mt=window.setTimeout(()=>{Mt!==null&&et.current.delete(Mt),Nn=!0;let Pe=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...zr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Pe-Ur),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Tt?.flush?.().catch(()=>{}),ln?.()},Bd),et.current.add(Mt);let ir=(Pe,Wt)=>{Mt!==null&&(window.clearTimeout(Mt),et.current.delete(Mt),Mt=null);let ne=Tt?.now()??globalThis.performance?.now()??Date.now(),Lt=Math.max(0,ne-Ur),wr=Pe;Nn&&(Pe==="resolved"?wr="resolved_late":Pe==="returned_error"?wr="returned_error_late":wr="rejected_late");let qr=Wt??(Pe==="resolved"?"approved":"provider_error");return Tt?.log({name:"payment.provider_confirmation.returned",...zr,operationOutcome:wr,terminalReason:qr}),Tt?.performance({...zr,durationMs:Lt,durationMode:"buyer",operationOutcome:wr,terminalReason:qr}),{durationMs:Lt,operationOutcome:wr,terminalReason:qr}},he=!1,Sr=!1,Kr=Pe=>{if(!Pe||typeof Pe!="object")return null;let Wt=Pe;if(Wt.error)return null;let ne=Wt.setupIntent??Wt.paymentIntent,Lt=us(ne??null,void 0,!!Wt.setupIntent);return Lt.kind==="confirmed"?Lt:null},re=Pe=>{if(he||E&&O.current!==E.generation)return;let Wt=Kr(Pe);if(!Wt)return;if(Jn&&!Jl(tt,Et,Tr)){he=!0;return}let{intentId:ne,paymentMethodId:Lt}=Wt;he=!0,Sr=!0,Me.current=null,fe.current=null,D.current&&(j("idle"),we(!1));let wr=`${ic}:${tt}`;ur(wr,{createdAt:Date.now(),sessionId:tt,nonce:Et,accountPatch:or,paymentMethodId:Lt,providerIntentId:ne,paymentMethodType:U});try{c({id:Lt,type:"card",threeDSecureActionResultTokenId:ne},{accountPatch:or,paymentMethodCategory:"wallet",sessionId:tt,nonce:Et})}finally{ur(wr)}},Bt=!1;ln=async()=>{if(!(Bt||he||Sr)){Bt=!0,D.current&&j("checking");try{let Pe=await Zl(S,Tr,et.current);if(he||Sr)return;let Wt=(0,l.isSetupIntentClientSecret)(Tr),ne=us(Pe,ar.providerObjectId,Wt);if(ne.kind==="confirmed"){re(Wt?{setupIntent:Pe}:{paymentIntent:Pe});return}if(ne.kind==="terminal"){if(Sr=!0,ds(tt,Et,Tr),Me.current=null,fe.current=null,!D.current)return;j("idle"),se(),b(U,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",E?.generation,!0);return}D.current&&!Sr&&(j("blocked"),we(!1))}catch{D.current&&!Sr&&(j("blocked"),we(!1))}finally{Bt=!1}}},fe.current=ln;let Q,Gt;try{V=!0,xe.current+=1;let Pe;try{Pe=await((0,l.isSetupIntentClientSecret)(Tr)?S.confirmSetup({elements:Te,clientSecret:Tr,redirect:"if_required"}):S.confirmPayment({elements:Te,clientSecret:Tr,redirect:"if_required"}))}finally{_t()}if(!Pe||typeof Pe!="object")throw new xa(Ud(Pe));if(Q=Pe,!Q.error&&!Kr(Q))throw new xa("confirmation_result_unconfirmed");Gt=ir(Q.error?"returned_error":"resolved",Q.error&&(0,Se.isProviderDecline)(Q.error)?"provider_declined":void 0)}catch(Pe){let Wt=Pe instanceof xa?Pe.reason:void 0,ne=Wt!==void 0,Lt=ir(ne?"returned_error":"rejected");if(Tt?.error({...ne?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Wt}:ts(Pe),...zr,operationOutcome:Lt.operationOutcome,durationMs:Lt.durationMs,statusClass:"unknown",terminalReason:Lt.terminalReason}),!D.current||he)return;await ln?.();return}let sr=Q.error;if(sr){if(!D.current||he)return;if((0,Se.isProviderDecline)(sr)){Sr=!0,ds(tt,Et,Tr),Me.current=null,fe.current=null,j("idle"),Ft.current.get(de)===E&&Ft.current.delete(de);let Pe=sr.message??"Your payment was declined.";p?.(Pe),h?.(kr(Br,Pe,{code:(0,Se.getProviderErrorCode)(sr),declineCode:(0,Se.getProviderDeclineCode)(sr)})),Si({billingApiUrl:n,sessionId:tt,nonce:Et,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:U,providerDeclineReason:(0,Se.getProviderErrorCode)(sr)??"provider_declined",...ar.intentKind==="payment"&&ar.providerObjectId.startsWith("pi_")?{providerIntentId:ar.providerObjectId}:{}}})}else Tt?.error({...ts(sr),...zr,operationOutcome:Gt.operationOutcome,durationMs:Gt.durationMs,statusClass:"unknown",terminalReason:Gt.terminalReason}),await ln?.();return}if(re(Q),!he)throw new Error("Invalid provider returned for APM intent")}catch(tt){if(tt===Pi){let Et=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.error({errorCode:jd(yn),stage:Jt,requestCategory:yn,paymentMethodCategory:"wallet",provider:"stripe",...rr?{walletType:rr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ln,durationMs:Math.max(0,Et-Wr),statusClass:"timeout",failureCategory:$r,attempt:$t,terminalReason:"provider_error"}),Tt?.flush?.().catch(()=>{})}se(),b(U,tt,tt===Pi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",E?.generation,tt===Pi)}finally{if(window.clearTimeout(Cr),Mt!==null&&(window.clearTimeout(Mt),et.current.delete(Mt)),!Jr){let tt=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.performance({stage:"callback",durationMs:Math.max(0,tt-Wr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...nr?{statusClass:"timeout"}:{}})}D.current&&we(!1)}},[S,Te,e,t,r,I,B,G,n,me,a,c,p,h,w,b,_t,ve,ut,bt,O,T,de]),We=(0,o.useMemo)(()=>mi(s),[s]),Ge=(0,o.useMemo)(()=>s.map(l.stripeExpressMethodToOptionKey),[s]),Dt=(0,o.useMemo)(()=>(0,u.jsx)(dr.ExpressCheckoutElement,{onReady:d=>{ye(Ia(d,Ge))},onLoadError:d=>{ye("load_error"),Ps(T,"stripe","wallet","provider_error")},onClick:async d=>{let L=T?.now()??globalThis.performance?.now()??Date.now();ft.current=d.expressPaymentType,Ne.current=rc(d.expressPaymentType);let V=!0,se=window.setTimeout(()=>{V=!1,d.reject(),x(d.expressPaymentType)},xd),E=w?await w(Ne.current,{abandoned:()=>!V}):{proceed:!0};if(window.clearTimeout(se),!V)return;if(!E.proceed){Ft.current.delete(de),d.reject();return}let U=St(d.expressPaymentType);Ot.current=!1,at.current={generation:U,startedAt:L},Ft.current.set(de,{generation:U,method:d.expressPaymentType,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),W(!1),T?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:U,...d.expressPaymentType==="apple_pay"||d.expressPaymentType==="google_pay"?{walletType:d.expressPaymentType}:{}}),m?.(Ne.current),d.resolve()},onConfirm:it,onCancel:()=>{let d=Ft.current.get(de);Ft.current.delete(de);let L=at.current,V=T?.now()??globalThis.performance?.now()??Date.now();if(d&&L?.generation===d.generation&&(0,l.isWalletSheetRefusedForWindowSize)({method:d.method,elapsedMs:V-L.startedAt,handoffObserved:mr.current===d.generation})){T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:d.generation,walletType:"google_pay"}),Me.current=null,b(d.method,new Error("The browser window is too small for the Google Pay sheet."),l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,d.generation,!0);return}T?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...d?{attempt:d.generation}:{}}),M(d?.generation),Me.current=null,W(!1),ge.current=!0,Ce()},options:{...yi,paymentMethods:We,emailRequired:dt,billingAddressRequired:dt}},de),[Ge,We,it,M,m,dt,b,x,Ce,w,St,de,T]);return(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(_a,{state:ae,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Z,children:(0,u.jsxs)("div",{ref:Je,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Y&&(0,u.jsxs)("button",{ref:Le,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Re,style:ys,children:["Try ",fs(Ve)," again"]}),$!=="idle"&&(0,u.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,u.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,u.jsx)("button",{type:"button",onClick:pt,disabled:$==="checking",style:ys,children:$==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ke&&(0,u.jsx)(Ho,{identity:Ke.identity,methodLabel:Ke.methodLabel,onComplete:kt,onCancel:()=>kt(null)},Ke.id),(0,u.jsxs)("div",{style:{display:Ke||$!=="idle"?"none":void 0},children:[(0,u.jsx)(nu,{active:H}),Dt]})]})}),pe&&(0,u.jsx)(an,{status:"processing"})]})}function dc(e,t,r){let n=(0,l.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function gs({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:c,onTokenizedBody:p,onErrorChange:m,onDecline:h,onCancel:k,runBeforeButtonClick:w,onButtonClick:I,isProcessing:G,submitButtonColor:_,submitButtonBorderRadius:Z,submitButtonStyle:A,errorText:f}){let P=io(),{emitInstrument:me}=(0,o.useContext)(Pn),S=(0,dr.useStripe)(),Te=(0,dr.useElements)(),[T,ae]=(0,o.useState)(!1),ye=(0,o.useRef)(!1),[pe,we]=(0,o.useState)(!1),[dt,Ke]=(0,o.useState)("loading"),[B,kt]=(0,o.useState)(""),Je=!(0,l.isValidEmail)(n?.trim()),Le=!Je||(0,l.isValidEmail)(B.trim()),de=(0,o.useCallback)(async()=>{if(!S||!Te||G||ye.current||!pe)return;ye.current=!0,ae(!0);let ee=w?await w("card"):{proceed:!0};if(!ee.proceed){ye.current=!1,ae(!1);return}I?.("card");let H=ee.sessionId??t,Oe=ee.nonce??r,nt=(0,Wo.splitFullName)(a?.trim()),qe=(0,vn.compactBuyerIdentity)({email:ee.accountPatch?.email?.trim()||n?.trim()||B.trim(),firstName:ee.accountPatch?.firstName?.trim()||nt.firstName,lastName:ee.accountPatch?.lastName?.trim()||nt.lastName}),Y=qe.email,W=(0,vn.compactBuyerIdentity)({...ee.accountPatch,...qe});try{if(m?.(null),!(0,l.isValidEmail)(Y))throw new Error("A valid email address is required for payment.");await s?.(qe);let $=await Te.submit();if($.error){m?.($.error.message??"Payment failed.");return}let j=[qe.firstName,qe.lastName].filter(Boolean).join(" "),Ve=await S.createPaymentMethod({elements:Te,params:{billing_details:{email:Y,...j?{name:j}:{}}}});if(Ve.error||!Ve.paymentMethod){m?.(Ve.error?.message??"Failed to create payment method.");return}let Be=Ve.paymentMethod;if(!H||!Y)throw new Error("Missing sessionId or email for payment.");let fe=Be.type||e,D=await bi(c,me,H,Oe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:fe,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(D)){p({type:"card",gateway:"stripe",paymentMethodType:fe},{accountPatch:W,paymentMethodCategory:"apm",sessionId:H,nonce:Oe,settledProcessResponse:D.response});return}if(D.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ge=D.clientSecret;ur(Gn,{clientSecret:ge,sessionId:H,nonce:Oe,accountPatch:W,paymentMethodId:Be.id,paymentMethodType:Be.type??e,gateway:"stripe"});let{error:ft,paymentIntent:Ne}=await S.confirmPayment({clientSecret:ge,confirmParams:{return_url:window.location.href,payment_method:Be.id},redirect:"if_required"});if(ft){ur(Gn);let et=ft.message??"Payment failed.";m?.(et),h?.(kr("card",et,{code:ft.code})),await Si({billingApiUrl:c,sessionId:H,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ft.code??"provider_declined"}});return}let ot=Ne?.status;if(!ga(ot)){ur(Gn);let et=ot==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(et),h?.(kr("card",et,{code:ot??"missing_payment_intent"}));return}ur(Gn);let Me=typeof Ne?.payment_method=="string"?Ne.payment_method:Ne?.payment_method?.id;p({id:Me??Be.id,type:"card",threeDSecureActionResultTokenId:Ne?.id,gateway:"stripe",paymentMethodType:Be.type??e},{accountPatch:W,paymentMethodCategory:"apm",sessionId:H,nonce:Oe})}catch($){m?.($ instanceof Error?$.message:"Payment failed. Please try again.")}finally{ye.current=!1,ae(!1)}},[S,Te,G,pe,w,I,t,r,n,a,B,s,c,me,e,p,m,h]);return(0,u.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Je&&(0,u.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Je&&(0,u.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,u.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:B,onChange:ee=>kt(ee.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,u.jsx)(dr.PaymentElement,{onReady:()=>Ke("ready"),onLoadError:()=>{Ke("load_error"),Ps(Er(P),"stripe","apm")},onChange:ee=>{we(!!ee.complete)},options:{layout:fi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,l.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,u.jsx)(gi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{de()},disabled:!pe||!Le||T||G||dt!=="ready",color:_,borderRadius:Z,style:A,children:T?"Processing\u2026":`Pay with ${(0,l.getStripeMethodDisplayName)(e)}`}),f&&(0,u.jsx)(Yo,{margin:"0.75rem 0 0",children:f})]})}function ac({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:c,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:h,onTokenizedBody:k,onErrorChange:w,onButtonClick:I,onDecline:G,runBeforeButtonClick:_,onLoadStateChange:Z,isProcessing:A=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:me,buttonAppearance:S,themeId:Te,onExpandApm:T,expandedApmMethod:ae}){let{emitInstrument:ye}=(0,o.useContext)(Pn),[pe,we]=(0,o.useState)(null),[dt,Ke]=(0,o.useState)(null),B=(0,o.useRef)(!1),{request:kt,collect:Je,finish:Le}=$o();(0,o.useEffect)(()=>{c.length>0&&p?Z?.("ready"):p||Z?.("loading")},[c.length,p,Z]);let de=(0,o.useCallback)(async Y=>{if(!p||B.current||A)return;B.current=!0,Ke(Y);let W=_?await _("card"):{proceed:!0};if(!W.proceed){B.current=!1,Ke(null);return}I?.("card");let $=W.sessionId??e,j=W.nonce??t,Ve=(0,Wo.splitFullName)([W.accountPatch?.firstName,W.accountPatch?.lastName].filter(Boolean).join(" ")||n),Be=(0,vn.compactBuyerIdentity)({email:W.accountPatch?.email?.trim()||r?.trim(),firstName:W.accountPatch?.firstName?.trim()||Ve.firstName,lastName:W.accountPatch?.lastName?.trim()||Ve.lastName});if(!(0,l.isValidEmail)(Be.email)){Ke(null);let ge=await Je((0,l.getStripeMethodDisplayName)(Y),Be);if(!ge){B.current=!1;return}Be=ge,Ke(Y)}let fe=Be.email,D=(0,vn.compactBuyerIdentity)({...W.accountPatch,...Be});try{if(w?.(null),!$||!(0,l.isValidEmail)(fe))throw new Error("Missing sessionId or email for payment.");await a?.(Be);let ge=await bi(s,ye,$,j??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Y,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(ge)){k({type:"card",gateway:"stripe",paymentMethodType:Y},{accountPatch:D,paymentMethodCategory:"apm",sessionId:$,nonce:j,settledProcessResponse:ge.response});return}if(ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ft=ge.clientSecret;ur(Gn,{clientSecret:ft,sessionId:$,nonce:j,accountPatch:D,paymentMethodType:Y,gateway:"stripe"});let{error:Ne,paymentIntent:ot}=await p.confirmPayment({clientSecret:ft,confirmParams:{return_url:window.location.href,payment_method_data:{type:Y,billing_details:{name:[Be.firstName,Be.lastName].filter(Boolean).join(" "),...fe?{email:fe}:{}}}},redirect:"if_required"});if(Ne){ur(Gn);let at=Ne.message??"Payment failed.";w?.(at),G?.(kr("card",at,{code:Ne.code})),await Si({billingApiUrl:s,sessionId:$,nonce:j,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Y,providerDeclineReason:Ne.code??"provider_declined"}});return}let Me=ot?.status;if(!ga(Me)){ur(Gn);let at=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";w?.(at),G?.(kr("card",at,{code:Me??"missing_payment_intent"}));return}ur(Gn);let et=typeof ot?.payment_method=="string"?ot.payment_method:ot?.payment_method?.id;k({id:et??ot?.id,type:"card",threeDSecureActionResultTokenId:ot?.id,gateway:"stripe",paymentMethodType:Y},{accountPatch:D,paymentMethodCategory:"apm",sessionId:$,nonce:j})}catch(ge){w?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{B.current=!1,Ke(null)}},[p,A,_,I,e,t,r,Je,s,ye,n,a,k,w,G]),[ee,H]=(0,o.useState)(null),Oe=T?ae??null:ee,nt=(0,o.useCallback)(Y=>{B.current||A||Oe&&Oe!==Y||((0,l.needsStripeMethodExplicitConfirm)(Y)?T?T(Y):H(Y):de(Y))},[Oe,A,de,T]),qe=(0,o.useMemo)(()=>ee?dc(m,ee,h):null,[ee,m,h]);return(0,u.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:kt?(0,u.jsx)(Ho,{identity:kt.identity,methodLabel:kt.methodLabel,onComplete:Le,onCancel:()=>Le(null)},kt.id):c.map(Y=>{let W=ae===Y,$=dt===Y,j=dt!==null&&dt!==Y||ae!=null&&ae!==Y;return(0,u.jsxs)(o.default.Fragment,{children:[(0,u.jsx)(pi,{method:Y,themeId:Te,submitting:$,disabled:j,highlighted:W,hasNextStep:(0,l.needsStripeMethodExplicitConfirm)(Y),onClick:()=>nt(Y),backgroundColor:S?.backgroundColor,borderColor:S?.borderColor,textColor:S?.textColor,borderRadius:S?.borderRadius,fontFamily:S?.fontFamily}),!T&&ee===Y&&qe&&p&&(0,u.jsx)(dr.Elements,{stripe:p,options:qe,children:(0,u.jsx)(gs,{method:Y,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:k,onErrorChange:w,onDecline:G,onCancel:()=>H(null),runBeforeButtonClick:_,onButtonClick:I,isProcessing:A,submitButtonColor:f,submitButtonBorderRadius:P,submitButtonStyle:me})},Y)]},Y)})})}function ou({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:c,onError:p,onDecline:m,onCancel:h,onTokenizedBody:k,firstName:w,lastName:I,chv:G,className:_,submitLabel:Z,isProcessing:A,error:f,onErrorChange:P,showPayPal:me=!0,showStripe:S=!0,walletPresentation:Te="auto",enabledPaymentMethods:T,enabledPaymentMethodCountries:ae,showApplePay:ye=!0,showGooglePay:pe=!0,layout:we="default",theme:dt,buttonsTheme:Ke,buttonsStyles:B,appearance:kt,cardButtonContent:Je,cardBackButtonContent:Le,cardTitleContent:de,showSecurityFooter:ee,onButtonClick:H,onBeforeButtonClick:Oe,onBuyerIdentityReady:nt,enableAVS:qe,cardFieldOrder:Y,cardPreFormSlot:W,avsLayout:$="row",country:j,zip:Ve,addressLine1:Be,addressLine2:fe,city:D,state:ge,onCountryChange:ft,onZipChange:Ne,avsCheck:ot,checkoutType:Me,checkoutLayout:et,totalAmount:at=0,currency:mr="usd",initialCardOpen:Ft=!1,directPaypal:St,isSubscription:ve=!1,session:M,dataAttachmentPending:bt=!1,dataAttachmentRequiresIdentity:ut=!1,debug:O=!1}){let xe=io(),Ot=ei(),Ce=(0,o.useContext)(An),{emitInstrument:_t}=(0,o.useContext)(Pn),b=(0,o.useRef)(null);b.current||(b.current=ri());let x=b.current,[,Ae]=(0,o.useState)(0),Re=(0,o.useRef)(null);Re.current||(Re.current=(0,$n.detectPayPalEnvironment)());let pt=Re.current,it=(0,o.useMemo)(()=>({browser:pt,capability:x,presentationMode:"popup"}),[pt,x]),We=M??Ce.session,Ge=(0,o.useMemo)(()=>({futureUse:We?.futureUse,futureUseUnsupported:We?.futureUseUnsupported}),[We?.futureUse,We?.futureUseUnsupported]),Dt=We?.gateways?.paypal?.providerObjectType??St?.providerObjectType,d=bt||Ce.claimPending===!0,L=ut||Ce.claimRequiresIdentity===!0,V=d&&!L,se=Bl(),E=r||se,[U,Nt]=(0,o.useState)(!1),[Br,rr]=(0,o.useState)(null),[$t,Tt]=(0,o.useState)(j??""),[Wr,Nr]=(0,o.useState)(Ve??""),[nr,Jr]=(0,o.useState)(Be??""),[Mt,Ln]=(0,o.useState)(fe??""),[Jt,yn]=(0,o.useState)(D??""),[$r,Hr]=(0,o.useState)(ge??""),[Zt,Cr]=(0,o.useState)(""),[Zr,tt]=(0,o.useState)({}),Et=(0,o.useRef)(Ve??""),Dr=(0,o.useRef)(j??""),Ht=(0,o.useRef)(Be??""),or=(0,o.useRef)(fe??""),br=(0,o.useRef)(D??""),Qt=(0,o.useRef)(ge??""),Kt=(0,o.useRef)(""),_r=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(C,K,Ie,J,_e)=>{if(_r.current[C])return;let zt=K?.trim();!zt||zt===Ie.current||(Ie.current=zt,J(zt),_e?.(zt))};i("country",j,Dr,Tt,ft),i("zip",Ve,Et,Nr,Ne),i("addressLine1",Be,Ht,Jr),i("addressLine2",fe,or,Ln),i("city",D,br,yn),i("state",ge,Qt,Hr)},[j,Ve,Be,fe,D,ge,ft,Ne]);let Ze=(0,o.useMemo)(()=>(0,l.resolveAVSConfig)(qe),[qe]),ar=Ze!==null,Tr=(0,o.useMemo)(()=>(0,l.isAuthorizationOnlySession)(M),[M]),Jn=(0,l.isMountableVaultBlock)(M?.vault),Ur=!!M?.gateways?.pcivault,zr=(0,xn.hasServerSideCardGateway)(M),ln=!!(M?.gateways?.stripe?.enabledPaymentMethods??T)?.includes("card")||(0,xn.canRecoverHostedCardForm)(M),ir=Jn||ln||Ur,he=!!(S&&ir&&e),[Sr,Kr]=(0,o.useState)(()=>we!=="buttons"||Ft?e??null:null),[re,Bt]=(0,o.useState)(0),Q=we!=="buttons"||Ft||!!e&&Sr===e,Gt=M?.captureMethod,sr=(0,o.useRef)(xe);(0,o.useEffect)(()=>{sr.current=xe},[xe]);let[Pe,Wt]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!he||!e||!Q){Wt(null);return}let i=sr.current?sr.current.cardCapture({sessionId:e,captureMethod:Gt}):new On.PciVaultCardCapture({sessionId:e,captureMethod:Gt,billingApiUrl:E,telemetry:n});return Wt({sessionId:e,captureMethod:Gt,billingApiUrl:E,telemetry:n,capture:i}),()=>{i.unmount()}},[he,e,Q,Gt,E,n]);let ne=he&&e&&Q&&Pe?.sessionId===e&&Pe.captureMethod===Gt&&Pe.billingApiUrl===E&&Pe.telemetry===n?Pe.capture:null,Lt=(0,o.useMemo)(()=>{let i=$t,C=Ze?(0,l.isAVSFieldVisible)(Ze.postal_code,i):!1;return Qd(i,Wr,C)},[Ze,$t,Wr]),{avsInvalid:wr,invalidAvsFields:qr}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!he||!Ze)return{avsInvalid:!1,invalidAvsFields:i};let C=$t,K=(_e,zt)=>(0,l.isAVSFieldVisible)(_e,C)&&!zt.trim(),Ie={line1:K(Ze.address_line_1,nr),city:K(Ze.city,Jt),state:K(Ze.state,$r),zip:Lt.empty||Lt.malformed};return{avsInvalid:Ie.line1||Ie.city||Ie.state||Ie.zip,invalidAvsFields:Ie}},[he,Ze,$t,nr,Jt,$r,Lt]),[er,Un]=(0,o.useState)(!1),[Zn,zn]=(0,o.useState)(!1),[qn,Qn]=(0,o.useState)(!1),[po,mo]=(0,o.useState)({line1:!1,city:!1,state:!1}),Or=(0,o.useRef)(!1),eo=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),fn=(0,o.useRef)(!1),Ut=(0,o.useCallback)(i=>{eo.current[i]=!0,fn.current=!0},[]),Qr=(0,o.useCallback)(i=>!Or.current&&eo.current[i],[]),en=(0,o.useCallback)(i=>{Qr(i)&&mo(C=>C[i]?C:{...C,[i]:!0})},[Qr]),[cn,tn]=(0,o.useState)(()=>(0,l.resolveVaultMountOptions)(M?.vault,{billingApiUrl:E,sessionId:e,nonce:t})),[mt,yr]=(0,o.useState)(Ft&&ir?"card":"buttons"),[lr,Gr]=(0,o.useState)(null),ho=mt==="expanding"||mt==="card",to=M?.gateways?.stripe&&!zr?"stripe":void 0,In=(0,o.useCallback)(()=>{_t?.({class:"card_surface",provider:to})},[to,_t]),dn=(0,o.useRef)(null),Mr=(0,o.useCallback)(i=>{dn.current&&clearTimeout(dn.current),dn.current=setTimeout(()=>{dn.current=null,i()},Aa)},[]);(0,o.useEffect)(()=>()=>{dn.current&&clearTimeout(dn.current)},[]);let ro=(0,o.useRef)(!1),[jr,z]=(0,o.useState)(0),q=(0,o.useRef)(null),oe=(0,o.useCallback)(()=>{In(),Kr(e??null),ro.current&&(ro.current=!1,z(i=>i+1)),Bt(i=>i+1),yr("expanding"),Mr(()=>yr("card"))},[Mr,In,e]),be=(0,o.useCallback)(()=>{yr("collapsing"),Mr(()=>yr("buttons"))},[Mr]),gt=(0,o.useCallback)(i=>{Gr(i),yr("apm-expanding"),Mr(()=>yr("apm-form"))},[Mr]),Yt=(0,o.useCallback)(()=>{yr("apm-collapsing"),Mr(()=>{yr("buttons"),Gr(null)})},[Mr]);(0,o.useEffect)(()=>{we==="buttons"&&Ft&&ir&&(Kr(e??null),yr("card"))},[we,Ft,ir,e]);let[ke,ie]=(0,o.useState)(null),te=(0,o.useRef)(null),[Qe,Ee]=(0,o.useState)(0);(0,o.useEffect)(()=>{Qe!==0&&te.current?.focus()},[Qe]);let st=(0,o.useRef)(!1),N=(0,o.useRef)(null),ue=(0,o.useRef)("idle"),[ht,It]=(0,o.useState)(!1),Rr=(0,o.useRef)(ht);Rr.current=ht;let[y,g]=(0,o.useState)(()=>St?.existingOrderId?{orderId:St.existingOrderId,attempts:1}:null),X=(0,o.useRef)(y);(0,o.useEffect)(()=>{X.current=y},[y]);let $e=(0,o.useRef)(null),je=(0,o.useMemo)(()=>{if(nt||Ce.claimBuyerIdentity||M?.buyerIdentified!==!1||!e||!t)return;let i=`${E}|${e}|${t}`;$e.current?.key!==i&&($e.current={key:i,claim:jo(new On.PaymentAPI(E,{telemetry:!1}),e,t,{...s?{userId:s}:{},...w?{firstName:w}:{},...I?{lastName:I}:{}})});let C=$e.current.claim;return async K=>{await C(K)}},[nt,Ce.claimBuyerIdentity,M?.buyerIdentified,e,t,E,s,w,I]),He=nt??Ce.claimBuyerIdentity??je,rt=f??Br,qt=(0,o.useMemo)(()=>(0,l.resolveTheme)(dt),[dt]),le=(0,o.useMemo)(()=>{let i=qt?.buttonsLayout??(0,l.resolveButtonsLayoutTheme)(Ke);return B?{...i,...B,cardButton:{...i.cardButton,...B.cardButton},cardFormContainer:{...i.cardFormContainer,...B.cardFormContainer},backButton:{...i.backButton,...B.backButton},backButtonIcon:{...i.backButtonIcon,...B.backButtonIcon},submitButton:{...i.submitButton,...B.submitButton},title:{...i.title,...B.title}}:i},[qt,Ke,B]),fr=kt??qt?.appearance,_o=(0,o.useMemo)(()=>(0,l.computeVaultCardThemeColors)({appearance:fr,buttonsStyles:le,layout:we}),[fr,le,we]),xt=Ce.inlineSessionPatchProcessing??!1,Fe=(A??U)||xt,lt=E.replace(/\/+$/,""),ce=(0,o.useMemo)(()=>es({userId:s,email:a,firstName:w,lastName:I,country:j,zip:Ve},Zr),[s,a,w,I,j,Ve,Zr]),yt=[ce.firstName,ce.lastName].filter(i=>!!i?.trim()).join(" "),rn=!(0,l.isValidEmail)(ce.email?.trim()),jt=(0,o.useRef)(null);he&&jt.current===null&&(jt.current=rn);let _n=he&&(jt.current??rn),Ai=(0,o.useMemo)(()=>eu(Zt,_n),[Zt,_n]),To=Ai.empty||Ai.malformed,un=(0,o.useMemo)(()=>xe?xe.getRawProvider():null,[xe]),xs=(0,o.useMemo)(()=>Ot?Ot.getRawProvider():null,[Ot]),na=at||100,Mo=mr.toLowerCase(),Fi=(0,o.useMemo)(()=>fr?(0,On.toStripeAppearance)(fr):null,[fr]),xo=Fi,As=(0,o.useMemo)(()=>{let i=Fi??{},C=i.rules??{};return{...i,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[Fi]),Fs=(0,o.useMemo)(()=>({...xl(at,We?.captureMethod,Ge),currency:Mo,...xo?{appearance:xo}:null}),[at,Mo,We?.captureMethod,Ge,xo]),Bi=(0,l.resolveSetupFutureUsage)(Ge,"paypal","paypal"),Bs=(0,o.useMemo)(()=>({mode:"payment",amount:na,currency:Mo,captureMethod:"manual",...Bi?{setupFutureUsage:Bi}:null,...xo?{appearance:xo}:null}),[na,Mo,Bi,xo]),Ue=(0,o.useCallback)(i=>{rr(i),P?.(i)},[P]),Ds=(0,o.useRef)(0);(0,o.useEffect)(()=>{jr!==Ds.current&&(Ds.current=jr,Ue(null))},[jr,Ue]);let Di=(0,o.useRef)(""),[Os,Fc]=(0,o.useState)(!1),Oi=(0,o.useCallback)(()=>{Fc(!0)},[]);(0,o.useEffect)(()=>{if(!he||!_n||!He||!Os||To||Di.current)return;let i=(0,vn.compactBuyerIdentity)({email:(0,l.isValidEmail)(ce.email?.trim())?ce.email?.trim():Kt.current.trim(),firstName:ce.firstName?.trim(),lastName:ce.lastName?.trim()});Di.current=JSON.stringify(i),tt(C=>({...C,...i})),Promise.resolve(He(i)).catch(C=>{Di.current="",Ue(C instanceof Error?C.message:"Failed to attach buyer details.")})},[he,_n,He,Os,To,ce.email,ce.firstName,ce.lastName,Ue]),(0,o.useEffect)(()=>{!he||!ne||ne.setCardFieldOrder?.(Y??null,Ze==null&&!_n)},[he,ne,Y,Ze,_n]),(0,o.useEffect)(()=>{(mt==="expanding"||mt==="collapsing"||mt==="apm-expanding"||mt==="apm-collapsing")&&Ue(null)},[mt,Ue]);let jn=(0,o.useCallback)((i,C,K)=>{m?.(kr(i,C,K))},[m]),Ls=(0,o.useRef)(mt);Ls.current=mt;let[Ns]=(0,o.useState)(oi),Us=(0,o.useCallback)(()=>{let i=Ls.current;if(we==="buttons"&&(i==="card"||i==="expanding"))return!0;let C=ue.current;return C==="validation-window"||C==="processing"||Rr.current},[we]),zs=(0,o.useCallback)((i,C,K)=>{Ns.take(e)&&Er(xe)?.log(ko({...it,presentationMode:K?.presentationMode??"popup"},{name:ni,stage:"recovery",reason:"other_method_active",provider:K?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:K?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[it,xe,Ns,e]),La=(0,o.useCallback)((i,C,K)=>{K?.telemetryReported||Er(xe)?.error(ko({...it,presentationMode:K?.presentationMode??"popup"},{errorCode:C?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:K?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:K?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:K?.terminalReason??(C?"popup_blocked":"provider_error")}))},[it,xe]),Ao=(0,o.useCallback)((i,C,K)=>{let Ie=K?.popupBlocked??(0,Se.isPopupBlockedError)(C);if(Us()){La(i,Ie,K),zs(i,C,K);return}if(C instanceof l.FloPayError&&C.code==="checkout_processing_timeout"){La(i,!1,K),ie(null),we==="buttons"&&(yr("buttons"),Gr(null)),Ue(C.message),p?.(C);return}Ie&&x.markBlocked()&&Ae(wt=>wt+1);let J=fs(i),_e=K?.code===l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,l.buildWalletSheetWindowMessage)(J):(0,Se.buildExternalMethodRecoveryMessage)(J,Ie,pt.inAppBrowser),zt=(0,Se.getProviderErrorCode)(C),hn=(zt?.toLowerCase()==="error"?void 0:zt)??(0,Se.sanitizeExternalFailureCode)(K?.code)??"external_payment_method_failed",Pt=new l.FloPayError(_e,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:hn,popupBlocked:Ie,inAppBrowser:pt.inAppBrowser,appFamily:pt.appFamily,popupCapability:x.current(),presentationMode:K?.presentationMode??"popup"}});La(i,Ie,K),ie(null),we==="buttons"&&(yr("buttons"),Gr(null)),Ue(_e),p?.(Pt),console.error("[FloPay] External payment method failed:",{method:i,code:hn,popupBlocked:Ie})},[pt,Us,we,p,x,zs,La,Ue]);(0,o.useEffect)(()=>{if(!he||!e){tn(null);return}let i={billingApiUrl:lt,sessionId:e,nonce:t},C=(0,l.resolveVaultMountOptions)(M?.vault,i);if(C){tn(C);return}if(!Q){tn(null);return}let K=`${lt}\0${e}\0${t??""}`,Ie=q.current;if(Ie&&Ie.key===K){tn(Ie.mount);return}tn(null);let J=!0;return new On.PaymentAPI(lt).getVaultCapture(e,t).then(_e=>{if(!J)return;let zt=(0,l.resolveVaultMountOptions)(_e,i);zt?.verificationRequired&&!_e.html&&(q.current={key:K,mount:zt}),zt?tn(zt):Ue("Failed to load the secure card form.")}).catch(_e=>{J&&Ue(_e instanceof Error?_e.message:"Failed to load the secure card form.")}),()=>{J=!1}},[he,Q,re,e,M?.vault,lt,t,Ue]);let Tn=(0,o.useRef)({onComplete:c,onError:p,updateError:Ue,emitDecline:jn,resolvedAccount:ce,avsConfig:Ze,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:lt,captureMethod:M?.captureMethod,paymentId:M?.paymentId,authorizationExpiresAt:M?.authorizationExpiresAt,serverSideCardGateway:zr});Tn.current={onComplete:c,onError:p,updateError:Ue,emitDecline:jn,resolvedAccount:ce,avsConfig:Ze,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:lt,captureMethod:M?.captureMethod,paymentId:M?.paymentId,authorizationExpiresAt:M?.authorizationExpiresAt,serverSideCardGateway:zr};let Li=(0,o.useRef)(!1),qs=(0,o.useCallback)(()=>{let i=Tn.current,C=i.resolvedAccount.email?.trim(),K=(0,l.isValidEmail)(C)?C:Kt.current.trim();if(!(0,l.isValidEmail)(K))return null;let Ie=i.resolvedAccount.firstName?.trim(),J=i.resolvedAccount.lastName?.trim(),_e=Dr.current.trim()||i.resolvedAccount.country?.trim()||"",zt=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.state,_e):!1,hn=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_1,_e):!1,Pt=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.postal_code,_e):!1,wt=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.city,_e):!1,At=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_2,_e):!1,gr=hn&&!zt&&Pt?(0,l.getStateFromPostalCode)(_e,(Et.current??"").trim()):null,pn=zt?Qt.current:gr;return{accountData:{userId:i.resolvedAccount.userId??"",email:K,...Ie?{firstName:Ie}:{},...J?{lastName:J}:{},...Pt&&Et.current?{zip:Et.current}:{},...wt&&br.current?{city:br.current}:{},...pn?{state:pn}:{},...hn&&Ht.current?{addressLine1:Ht.current}:{},...At&&or.current?{addressLine2:or.current}:{},..._e?{country:_e}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,l.isAVSFieldVisible)(i.avsConfig.country,_e),postal_code:Pt,address_line_1:hn,address_line_2:At,city:wt,state:zt}}:{}}},[]),js=(0,o.useRef)(d);js.current=d,(0,o.useEffect)(()=>{d||rt!==Ql||Tn.current.updateError(null)},[d,rt]),(0,o.useEffect)(()=>{!he||!ne||ne.setSubmitGate?.(wr||d||To||ht)},[he,ne,wr,d,To,ht]),(0,o.useEffect)(()=>{if(!he||!ne)return;Li.current=!1;let i=null,C=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,ue.current="idle",ie(null)},400)},K=ne.on("submitting",()=>{Un(!0),N.current&&clearTimeout(N.current),ue.current="validation-window",N.current=setTimeout(()=>{N.current=null,ue.current==="validation-window"&&(ue.current="processing")},Vd),ie("processing");let Pt=Tn.current;if(!Pt.sessionId||!Pt.nonce)return;let wt=qs();if(!wt){Pt.updateError("Enter a valid email address."),ue.current="idle",ie(null);return}new On.PaymentAPI(Pt.baseUrl).patchAccountSnapshot(Pt.sessionId,Pt.nonce,wt,{telemetryMode:"best_effort"}).catch(At=>{if(!$d(At))return;let gr=At instanceof Error?At.message:"Please check your billing address and try again.";Pt.updateError(gr),ue.current="idle",ie(null),Pt.onError?.(At instanceof l.FloPayError?At:new l.FloPayError(gr,"api_error"))})}),Ie=ne.on("complete",Pt=>{(0,Bn.markSessionRecentlyCompleted)(Pt.sessionId??Tn.current.sessionId),ue.current="terminal",It(!1),ie("success"),setTimeout(()=>{if(Li.current)return;Li.current=!0;let wt=Tn.current,At=(0,l.isAuthorizationOnlySession)(wt)||Pt.outcome==="authorized",gr=wt.serverSideCardGateway?{}:{paymentIntentId:Pt.intentId};Tn.current.onComplete?.(At?{status:"authorized",...gr,paymentId:Pt.paymentId??wt.paymentId,sessionId:Pt.sessionId??wt.sessionId,authorizationExpiresAt:Pt.authorizationExpiresAt??wt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...gr,checkoutMethod:"card"})},600)}),J=ne.on("decline",Pt=>{let wt=Tn.current,At=Pt.message??"Your payment was declined. Please try another card or contact your bank.";ue.current="terminal",It(!1),wt.updateError(At),ie("error");let gr=Pt.failureOutcome??(0,l.normalizeCheckoutFailureOutcome)(Pt.declineReason)??"authorization_declined";wt.emitDecline("card",At,{code:gr,declineCode:gr}),C()}),_e=ne.on("error",Pt=>{let wt=Tn.current,At=(0,l.buyerEmailRequiredPrompt)(Pt.vaultOutcome);if(At!==null){i&&(clearTimeout(i),i=null),ue.current="idle",It(!1),wt.updateError(At),ie(null),Ee(pn=>pn+1),wt.onError?.(new l.FloPayError(At,"api_error",{code:l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let gr=Pt.message??"There was a problem processing your payment. Please try again.";ue.current="terminal",It(!1),wt.updateError(gr),ie("error"),wt.onError?.(new l.FloPayError(gr,"api_error",{code:Pt.failureOutcome??"capture_failed"})),C()}),zt=ne.on("challenge_dismissed",()=>{N.current&&(clearTimeout(N.current),N.current=null),ue.current="processing",It(!0),ie(null)}),hn=ne.on("blocked",()=>{if(Rr.current){Tn.current.updateError(Wd);return}if(!js.current){Un(!0);return}Oi(),Tn.current.updateError(Ql)});return()=>{i&&(clearTimeout(i),i=null),N.current&&(clearTimeout(N.current),N.current=null),ue.current="idle",It(!1),ie(null),K(),Ie(),J(),_e(),zt(),hn()}},[he,ne,Oi,qs]);let Vn=!!St?.clientId,oa=Array.isArray(T),Na=oa&&T.length>0,Vs=oa&&T.includes("paypal"),Ua=(0,o.useRef)(null);Ua.current===null&&(Ua.current=(0,l.hasMatchingStripePayPalReturn)());let Fo=Ua.current?"redirect":(0,Hn.resolveStripePayPalPresentation)(pt,Te,x.current()),{expressMethods:za,paymentElementMethods:Ni}=(0,o.useMemo)(()=>(0,l.partitionStripeMethods)(T,{excludePaypal:Vn}),[T,Vn]),Ws=Vn||!!Ot||Vs&&Fo==="redirect",Bc=(0,o.useMemo)(()=>Ws?za.filter(i=>i!=="paypal"):za,[za,Ws]),Dc=(0,o.useMemo)(()=>{let i=[];return ye&&i.push("apple_pay"),pe&&i.push("google_pay"),i},[ye,pe]),Bo=oa?Bc:Dc,Oc=S&&Bo.length>0,$s=ar?$t:j,qa=(0,o.useMemo)(()=>(0,l.filterStripeMethodsByCountryGate)(Ni,$s,ae),[Ni,$s,ae]),Ui=(0,o.useMemo)(()=>({mode:"payment",amount:na,currency:Mo,paymentMethodCreation:"manual",appearance:As}),[na,Mo,As]),[Hs,Ks]=(0,o.useState)("loading"),[Gs,Ys]=(0,o.useState)("loading"),[Xs,Js]=(0,o.useState)("loading"),[Lc,zi]=(0,o.useState)(!1),[Zs,qi]=(0,o.useState)("loading"),[ji,Nc]=(0,o.useState)();(0,o.useEffect)(()=>{Nc((0,$n.detectPayPalEnvironment)())},[]);let ja=ji?.inAppBrowser,Va=ji?(0,Hn.resolvePayPalPresentationMode)(ji,St?.approvalPresentation,Dt??(ve?"subscription":"order")):"popup",Qs=me&&(Vn||(oa?Vs:ja===!1)),Uc=pt.inAppBrowser&&x.current()==="blocked",el=S&&Oc&&!Uc,aa=(!V||!!Ce.waitForDataAttachment)&&Qs&&Vn,tl=Zs==="retrying"||Zs==="exhausted",ia=null;S&&(Ot?ia=xs:Fo==="redirect"&&(ia=un));let rl=(0,o.useMemo)(()=>({...it,presentationMode:Fo}),[it,Fo]),sa=!V&&Qs&&!!ia&&(!Vn||tl),Do=!V&&el&&!!un,la=!V&&S&&Na&&qa.length>0&&!!un,zc=aa&&!tl?Lc:sa&&ls(Hs),qc=Do&&ls(Gs),jc=la&&Xs!=="load_error",nl=i=>i==="loading"||i==="ready",ol=aa||sa&&nl(Hs)||Do&&nl(Gs)||la&&Xs!=="load_error",Wa=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Wa.current){if(!S&&!me){Wa.current=!0;let i=new l.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),Ue(i.message)}else if(!S&&me&&!Vn){Wa.current=!0;let i=new l.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),Ue(i.message)}else if(ja!==void 0&&!V&&!ir&&!ol){Wa.current=!0;let i=new l.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(i),Ue(i.message)}}},[S,me,Vn,ja,V,ir,ol,p,Ue]);let al=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(al.current||!Na)return;let i=[];ye!==!0&&i.push("showApplePay"),pe!==!0&&i.push("showGooglePay"),i.length!==0&&(al.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Na,ye,pe]);let il=(0,o.useCallback)((i,C,K)=>Ce.applyInlineSessionPatch?Ce.applyInlineSessionPatch(i).then(Ie=>({error:null,sessionId:Ie.sessionId||e,nonce:Ie.session?.clientSecret||t})).catch(Ie=>{let J=(0,l.normalizeBeforeButtonClickError)(C,Ie);return K?.abandoned?.()||(Ue(J.message),p?.(J)),{error:J,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ce.applyInlineSessionPatch,t,p,e,Ue]),Mn=(0,o.useCallback)(async(i,C)=>{if(i!=="card"&&V&&await Ce.waitForDataAttachment?.(),!Oe)return{proceed:!0};try{let K=await Oe({method:i,sessionId:e||void 0,createSession:Ce.inlineSessionDraft});if(K===!1)return{proceed:!1};if(K&&typeof K=="object"){K.account&&tt(J=>({...J??{},...K.account}));let Ie=await il(K,i,C);return Ie.error?{proceed:!1,accountPatch:K.account}:{proceed:!0,accountPatch:K.account,sessionId:Ie.sessionId,nonce:Ie.nonce}}return{proceed:!0}}catch(K){if(!C?.abandoned?.()){let Ie=(0,l.normalizeBeforeButtonClickError)(i,K);Ue(Ie.message),p?.(Ie)}return{proceed:!1}}},[il,Ce.inlineSessionDraft,Ce.waitForDataAttachment,V,Oe,p,e,Ue]),sl=(0,o.useCallback)(async(i,C)=>{if(st.current)return;st.current=!0,Nt(!0),ie("processing"),Ue(null);let K=C?.sessionId??e,Ie=C?.nonce??t,J=es(ce,C?.accountPatch),_e=C?.completionPaymentMethodId??ha(i),zt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,hn=Yd(i),Pt=C?.presentationMode?ui(Er(xe),{...it,presentationMode:C.presentationMode}):void 0,wt=()=>{_t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:hn}),Pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Dn,requestCategory:"process_payment"})};try{let At=new On.PaymentAPI(lt),pn=C?.settledProcessResponse??await At.processPayment(J.userId??"",{sessionId:K,nonce:Ie,paymentMethodCategory:C?.paymentMethodCategory??Jd(i),tokenizedData:zt,accountData:{...C?.accountPatch,userId:J.userId??"",email:J.email??"",firstName:J.firstName||void 0,lastName:J.lastName||void 0,...(0,l.buildProcessPaymentAvsAccount)({avsConfig:Ze,country:Dr.current,zip:Et.current,city:br.current,state:Qt.current,addressLine1:Ht.current,addressLine2:or.current})},...(0,l.buildCheckoutProcessMetadata)({chv:G,avsCheck:ot,checkoutType:Me,checkoutLayout:et,avsConfig:Ze,country:Dr.current})}),Ya=async xr=>{let Co=(0,l.isAuthorizationOnlySession)(M)||xr?.status==="authorized";(0,Bn.markSessionRecentlyCompleted)(K),Pt?.terminal({outcome:"payment_succeeded",...Dn}),ie("success"),g(null),await new Promise(ya=>setTimeout(ya,600));let Wn;typeof xr?.paymentId=="string"?Wn=xr.paymentId:M?.paymentId&&(Wn=M.paymentId);let bo;typeof xr?.authorizationExpiresAt=="string"?bo=xr.authorizationExpiresAt:M?.authorizationExpiresAt&&(bo=M.authorizationExpiresAt),c?.(Co?{status:"authorized",...Wn===void 0?{}:{paymentId:Wn},sessionId:typeof xr?.sessionId=="string"?xr.sessionId:K,...bo===void 0?{}:{authorizationExpiresAt:bo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:_e,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:_e,checkoutMethod:i.isPaypal?"paypal":"card"})};if(pn.ok){await Ya(pn.status===204?null:await pn.json().catch(()=>null));return}let hr=await pn.json().catch(()=>null);if(hr?.type==="paypal_redirect_required"){let xr=hr.threeDSecureToken,Co=hr.paymentMethodId||i.id||"";if(!xe||!xr){ie("error"),Ue("PayPal authorization required but no token provided.");return}try{let Wn=Ot?.getRawProvider();if(!Wn){Ue("PayPal is not available.");return}let bo={return_url:window.location.href};Co&&(bo.payment_method=Co);let{error:ya}=await Wn.confirmPayment({clientSecret:xr,confirmParams:bo,redirect:"if_required"});if(ya){ie("error");let vl=ya.message??"PayPal payment failed.";Ue(vl),jn("paypal",vl,{code:ya.code})}}catch(Wn){ie("error"),Ue(Wn instanceof Error?Wn.message:"PayPal authorization failed.")}return}if(hr?.type==="paypal_direct_required"){let xr=hr.orderId;if(!xr){ie("error"),Ue("PayPal retry required but no order id provided.");return}let Co=X.current?.attempts??0;if(Co>=2){ie("error"),Ue("PayPal payment could not be completed after multiple attempts."),jn("paypal","paypal_direct_required retry limit exceeded");return}zi(!1),qi("loading"),g({orderId:xr,attempts:Co+1}),ie(null);return}if(pn.headers.get(Od)===Ld){let xr=await Nd(At,K,Ie);if(xr!==void 0){await Ya(xr);return}}(0,l.classifyPaymentRejection)(pn.status,hr)?Pt?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}):wt(),ie("error");let Pl=hr?.message??"Payment failed. Please try again.";Ue(Pl),jn(i.isPaypal?"paypal":"card",Pl,{code:hr?.code??hr?.gatewayErrorCode,declineCode:hr?.declineCode??hr?.gatewayDeclineReason}),await new Promise(xr=>setTimeout(xr,400))}catch(At){lc(At)||wt(),ie("error"),Ue(At instanceof Error?At.message:"An unexpected error occurred"),await new Promise(gr=>setTimeout(gr,400))}finally{Nt(!1),ie(null),st.current=!1}},[lt,e,t,ce,Ze,ot,Me,et,G,xe,Ot,M,c,Ue,jn,_t,it]),nn=(0,o.useCallback)((i,C)=>{k&&!C?.settledProcessResponse?k(i):sl(i,C)},[k,sl]),ca=`${ic}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(ca);if(!i)return;let C;try{C=JSON.parse(i)}catch{ur(ca);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>sc||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!Bo.includes(C.paymentMethodType)){ur(ca);return}ur(ca),nn({id:C.paymentMethodId,type:"card",threeDSecureActionResultTokenId:C.providerIntentId,gateway:"stripe",paymentMethodType:C.paymentMethodType},{...C.accountPatch?{accountPatch:C.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[nn,t,e,ca,Bo]);let ll=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||ll.current)return;let[i,C,K]=(0,l.readStripeRedirectParams)();if(!i||!C||Ua.current||!xe)return;let Ie=xe.getRawProvider();if(!Ie)return;let J=wt=>{let At=localStorage.getItem(wt);if(!At)return null;try{return JSON.parse(At)}catch{return ur(wt),null}},_e=J(Gn)??J(Xl),zt;if(_e?.clientSecret){if(_e.clientSecret!==C)return;zt={..._e.accountPatch?{accountPatch:_e.accountPatch}:{},..._e.sessionId?{sessionId:_e.sessionId}:{},..._e.nonce?{nonce:_e.nonce}:{}}}else if(_e?.sessionId&&_e.sessionId!==e)return;ll.current=!0,ur(Gn),ur(Xl),window.history.replaceState({},"",(0,l.stripeRedirectReturnUrl)());let hn=_e?.paymentMethodType??_e?.tokenType??"card",Pt="card";(async()=>{if(K==="failed"){let hr="Payment was declined. Please try again.";Ue(hr),jn(Pt,hr);return}let{paymentIntent:wt,error:At}=await Ie.retrievePaymentIntent(C);if(At){let hr=At.message??"Failed to retrieve payment status.";Ue(hr),jn(Pt,hr,{code:At.code});return}let gr=wt?.status,pn=ga(gr);if(!wt||!pn){let hr=gr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ue(hr),jn(Pt,hr,{code:gr??"missing_payment_intent"});return}let Ya=typeof wt.payment_method=="string"?wt.payment_method:wt.payment_method?.id;nn({id:Ya??_e?.paymentMethodId??_e?.tokenId??wt.id,type:"card",threeDSecureActionResultTokenId:wt.id,gateway:_e?.gateway??"stripe",paymentMethodType:hn},zt)})()},[e,nn,xe,Ue,jn]);let Vi=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(he||xe!==null))return(0,u.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let da=we==="buttons",on=fr?.variables,Vc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Wi=on?.colorBackground,Wc=Wi&&!Vc.has(Wi)?Wi:void 0,ua=le.cardInputBorder??(da?"#e5e7eb":"#A4A4FF"),cl=on?.colorDanger??"#dc2626",tr=i=>qr[i]&&(po[i]||er),$a=To&&(qn||er),gn=i=>i?cl:ua,Ha=(Lt.malformed||Lt.empty)&&(Zn||er),$c=gn(Ha),$i=le.cardFormContainer?.backgroundColor??Wc??(da?"white":"#EDEDFF"),Oo=le.cardInputBackground??on?.colorBackground??"white",Hi=Uo(Le),dl=Uo(de),Lo=le.nameInput,ul=le.cardInputFontSize??tu(Lo?.fontSize)??on?.fontSizeBase??"16px",pl=typeof Lo?.fontFamily=="string"?Lo.fontFamily:on?.fontFamily??"Poppins, sans-serif",ml=(0,l.toCssWeight)(Lo?.fontWeight)??400,Hc=le.cardInputColor??(typeof Lo?.color=="string"?Lo.color:void 0)??on?.colorText??"#262833",Kc=le.cardInputPlaceholderColor??"#9ca3af",cr=on?.borderRadius??"8px",Po=on?.borderRadius??le.cardButton?.borderRadius??cr,vo=on?.colorPrimary??"#4A49FF",Gc=on?.colorPrimaryHover??(0,l.darkenHex)(vo,.12),Ki=on?.colorText??"#262833",Gi={fontSize:ul,fontFamily:pl,fontWeight:ml,color:Hc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},pa={marginTop:"0.375rem",...Gi,fontSize:"0.75rem",lineHeight:1.4,color:cl},Yc={"--flopay-input-placeholder-color":Kc,"--flopay-input-font-size":ul,"--flopay-input-font-family":pl,"--flopay-input-font-weight":String(ml)},ma=le.cardFormContainer??{},Yi=ma.padding??(da?"0":"1rem"),Xi=ma.borderRadius??cr,Xc=ne&&cn?(0,u.jsx)(go,{capture:ne,html:cn.html,messageToken:cn.messageToken,expectedOrigin:cn.expectedOrigin,verificationRequired:cn.verificationRequired,theme:_o,submitLabel:Z,onReady:()=>{if(!_n&&!Ze||typeof document>"u")return;let i=()=>{let K=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(K){Or.current=!0;try{K.focus()}finally{Or.current=!1}}};fn.current||i()},onError:i=>{i&&cn.verificationRequired&&ue.current==="idle"&&(ro.current=!0),Ue(i)},onValidation:i=>{let C=ue.current;(C==="idle"||C==="validation-window")&&(Ue(i),i&&ue.current==="validation-window"&&(N.current&&(clearTimeout(N.current),N.current=null),ue.current="idle",ie(null)))}},jr):(0,u.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),yl=(0,u.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&In()},style:{backgroundColor:$i,borderRadius:Xi,...ma,padding:Yi,...Yc,display:"flex",flexDirection:"column"},children:[(0,u.jsx)("style",{children:`
30
+ `,Qo=44;function ea(){return(0,Ar.jsx)("style",{children:Id})}function _a(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function Ta({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Ar.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Ar.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,Ar.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:n})]})}function cs(e){return e!=="unavailable"&&e!=="load_error"}function mi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:c,backgroundColor:p,borderColor:m,textColor:h,borderRadius:k,fontFamily:w}){let I=(0,lo.resolveStripeMethodBrandVariant)(e,t),G=Gl[e],[_,Z]=(0,Yl.useState)(!1),F=!!G&&!_,f=I?.backgroundColor??p??"#ffffff",P=I?.borderColor??m??"#d1d5db",me=I?.textColor??h??"#262833";return(0,Ar.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&c()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Qo,padding:"0 1rem",backgroundColor:f,color:me,border:`1px solid ${P}`,borderRadius:k??8,fontSize:"0.95rem",fontWeight:600,fontFamily:w,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,Ar.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,lo.getStripeMethodDisplayName)(e)}\u2026`}):(0,Ar.jsxs)(Ar.Fragment,{children:[(0,Ar.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,lo.hasVendoredStripeMethodLogo)(e)?8:0},children:[F?(0,Ar.jsx)("img",{src:G,alt:"","aria-hidden":"true",onError:()=>Z(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!F&&I?.logoSvg?(0,Ar.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:I.logoSvg}}):null,(0,Ar.jsx)("span",{children:(0,lo.getStripeMethodDisplayName)(e)})]}),s&&(0,Ar.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:me,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,Ar.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function yi(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 fi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},gi={type:"accordion",defaultCollapsed:!1,radios:"never"};function hi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:c,children:p}){return(0,Ar.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:s,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...c??{}},children:p})}var yn=require("react");var Ma=require("@flopay/shared"),_d=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 Td(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return _d.has(t.charAt(0).toLowerCase()+t.slice(1))}function Md(e,t){return typeof t=="number"&&t!==0&&!Td(e)?`${t}px`:String(t).trim()}function Xl(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]=Md(r,n)}}}var Eo=require("react/jsx-runtime"),ds=new WeakSet;function go({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:c,containerStyle:p,onReady:m,onError:h,onValidation:k}){let w=(0,yn.useRef)(null),I=(0,yn.useRef)(m),G=(0,yn.useRef)(h),_=(0,yn.useRef)(k);I.current=m,G.current=h,_.current=k;let Z=(0,yn.useRef)(s);Z.current=s;let F=(0,yn.useRef)(null),f=c??void 0,P=(0,yn.useRef)(f);P.current=f;let me=(0,yn.useRef)(void 0);return(0,yn.useEffect)(()=>{let S=w.current;if(!S)return;let Te=!0,T=!1,ae=()=>{!Te||T||(T=!0,I.current?.())},ye=e.on("ready",()=>{ae()}),pe=e.on("error",x=>{G.current?.(x.message??"There was a problem loading the secure card form.")}),Re=e.on("validation",x=>{_.current?.(x.message??null)}),dt=P.current??(ds.has(e)?null:void 0),Ge={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...Z.current?{theme:Z.current}:{},...dt===void 0?{}:{submitLabel:dt}};return F.current=Z.current??null,me.current=P.current,P.current!==void 0&&ds.add(e),e.mount(S,Ge).then(()=>{ae()}).catch(x=>{Te&&G.current?.(x instanceof Error?x.message:"Failed to load the secure card form.")}),()=>{Te=!1,ye(),pe(),Re(),e.unmount()}},[e,t,r,n,a]),wo(()=>{let S=w.current;S&&Xl(S,p)},[p]),(0,yn.useEffect)(()=>{s!==void 0&&(s===null&&F.current===null||(F.current=s,e.applyTheme?.(s)))},[e,s]),(0,yn.useEffect)(()=>{f!==me.current&&(me.current=f,f!==void 0&&ds.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,Eo.jsx)("div",{ref:w,"data-testid":"flopay-vault-card-fields"})}function Pi({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 bs=require("@flopay/shared"),u=require("react/jsx-runtime"),Gn="flopay_stripe_resume",Jl="flopay_wallet_resume",sc="fw1",xd="fw2",lc=300*1e3,Ad=900,Fd="express_checkout_click_timeout",Bd=25e3,Dd=25e3,Od=1e4,Dn={provider:"paypal",paymentMethodCategory:"paypal"},Ld="x-flopay-process-result-source",Nd="status";async function Ud(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 vi={},Aa=class{constructor(t){this.reason=t}};function zd(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 Ps(e){return`${xd}:${e}`}function Ci(e){return ur(Ps(e))}function bi(e,t){if(typeof window>"u")return null;let r=Ps(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>lc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Ci(e),null):a}catch{return Ci(e),null}}function qd(e){return ur(Ps(e.sessionId),e)}function Zl(e,t,r){let n=bi(e,t);return!n||n.clientSecret!==r?!1:Ci(e)}function us(e,t,r){if(typeof window>"u")return;bi(e,t)?.clientSecret===r&&Ci(e)}function jd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ps(e,t,r){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let n=r?e.status==="succeeded":ga(e.status),a=jd(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Ql(e,t,r){let n=null;try{return await Promise.race([xl(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Od),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Vd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function cc(e){return e instanceof l.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Si(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new On.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw cc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var ms=l.STRIPE_PAYPAL_RESUME_KEY,xa=new Map,Wd=250,ec="Just a moment \u2014 we are finalizing your order. Please press pay again.",$d="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function vs(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 wi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new On.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Hd(e){return e instanceof l.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function dc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,Wo.splitFullName)(r),c=s.firstName?s:(0,Wo.splitFullName)(n?.name);return(0,Cn.compactBuyerIdentity)({email:(0,l.isValidEmail)(a)?a:n?.email?.trim(),firstName:c.firstName,lastName:c.lastName})}async function Kd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let c=dc({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 Fa=180,tc=`flopay-card-enter ${Fa}ms cubic-bezier(0, 0, 0.2, 1) both`,rc=`flopay-card-exit ${Fa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Gd=`flopay-buttons-enter ${Fa}ms cubic-bezier(0, 0, 0.2, 1) both`,Yd=`flopay-buttons-exit ${Fa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Xd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Cs(e){return(0,l.derivePrimaryTileStyle)(e)}var Jd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Zd(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 fs={width:"100%",minHeight:Qo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function nc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function gs(e){return e==="paypal"?"PayPal":(0,l.getStripeMethodDisplayName)(e)}function Qd(e){let t=(0,l.getPostalCodeExample)(e);return`Enter a valid ${(0,l.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function eu(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 tu(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 ru(e){return typeof e=="number"?`${e}px`:e}function Ri(e){return(0,u.jsx)(au,{...e})}function oc({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:c=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:h,runBeforeButtonClick:k,billingName:w,onBuyerIdentityReady:I,onLoadStateChange:G,placeholderBorderRadius:_,popupCapabilityOwner:Z,externalTelemetryContext:F,presentationMode:f}){let P=io(),{emitInstrument:me}=(0,o.useContext)(vn),S=(0,dr.useStripe)(),Te=(0,dr.useElements)(),T=(0,o.useMemo)(()=>pi(Er(P),F),[F,P]),[ae,ye]=(0,o.useState)("loading");(0,o.useEffect)(()=>{G?.(ae)},[ae,G]);let[pe,Re]=(0,o.useState)(!1),dt=(0,o.useRef)(!1),Ge=!(0,l.isValidEmail)(r?.trim())||!w?.trim(),{request:x,collect:kt,finish:Je}=$o(),Le=(0,o.useRef)(!1),de=(0,o.useRef)(null),ee=(0,o.useRef)(null),[H,Oe]=(0,o.useState)(0),[nt,je]=(0,o.useState)(!1),Y=(0,o.useRef)(!1),W=(0,o.useRef)(new Map),{startAttempt:$,finishAttempt:V,invalidateAttempt:He,isAttemptInvalidated:Be,isAttemptCurrent:fe,generationRef:B}=Ca((Ce,A,bt)=>{h?.(Ce,A,{...bt,popupBlocked:bt?.popupBlocked??(0,we.isPopupBlockedError)(A),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),je(!0),Oe(ut=>ut+1)},{onHandoffObserved:()=>{Z.markAvailable(),T?.log({name:"provider.popup.opened",stage:"overlay_open",...Dn,attempt:B.current})}});(0,o.useEffect)(()=>{nt&&ee.current?.focus()},[nt,H]);let ge=(0,o.useCallback)(()=>{Oe(Ce=>Ce+1)},[]),ft=(0,o.useCallback)((Ce,A,bt)=>{He(bt),h?.("paypal",Ce,{code:A,popupBlocked:(0,we.isPopupBlockedError)(Ce),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),je(!0),ge()},[He,h,f,ge]),Ne=(0,o.useCallback)(()=>{window.setTimeout(()=>{(de.current?.querySelector("iframe")??de.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Y.current&&(Y.current=!1,Ne())},[Ne,H]);let ot=(0,o.useCallback)(()=>{je(!1),s?.(null),Ne()},[Ne,s]);(0,o.useEffect)(()=>{if(!S||Le.current)return;let[Ce,A,bt]=(0,l.readStripeRedirectParams)();if(!Ce||!A)return;let ut=(0,l.readMatchingStripePayPalContinuation)(A);if(!ut)return;Le.current=!0;let O=!0,xe=xa.get(A);xe||(xe=bt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>S.retrievePaymentIntent(A)),xa.set(A,xe));let Ot={accountPatch:ut.accountPatch,sessionId:ut.sessionId,nonce:ut.nonce},be=()=>{T?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Dn,requestCategory:"provider_sdk"})};return T?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Dn}),(async()=>{try{Re(!0);let b=await xe;if(!O)return;if(b?.error){xa.delete(A),be(),s?.(b.error.message??"Failed to retrieve PayPal payment status.");return}if((0,l.clearStripePayPalReturn)(),xa.delete(A),bt==="failed"){let Ae="PayPal payment was declined. Please try again.";T?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}),s?.(Ae),m?.(kr("paypal",Ae));return}let M=b?.paymentIntent;if(M&&M.id!==Ce){be(),s?.("Failed to match the returned PayPal payment.");return}if(M&&(M.status==="requires_capture"||M.status==="succeeded")){let Ae=typeof M.payment_method=="string"?M.payment_method:M.payment_method?.id;a({id:Ae??M.id,type:"card",threeDSecureActionResultTokenId:M.id,isPaypal:!0},{...Ot,presentationMode:"redirect"})}else{let Ae="PayPal payment was not completed. Please try again.";T?.terminal({outcome:M?.status==="canceled"?"payment_cancelled":"payment_declined",...Dn,terminalReason:M?.status==="canceled"?"cancelled":"provider_declined"}),s?.(Ae),m?.(kr("paypal",Ae))}}catch(b){if(!O)return;xa.delete(A),be(),s?.(b instanceof Error?b.message:"Failed to complete PayPal payment.")}finally{O&&Re(!1)}})(),()=>{O=!1,Le.current=!1}},[S,a,s,m,T]);let Me=(0,o.useCallback)(async(Ce=!1)=>{let A=k?await k("paypal"):{proceed:!0};if(!A.proceed)return W.current.delete(H),!1;let bt=$("paypal");return W.current.set(H,{generation:bt,accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}),je(!1),T?.log({name:`provider.${Ce?"redirect.started":"handoff.requested"}`,stage:Ce?"redirect":"overlay_open",...Dn,attempt:bt}),p?.("paypal"),!0},[p,T,k,$,H]),tt=(0,o.useCallback)(async Ce=>{if(c||pe||!await Me()){Ce.reject();return}Ce.resolve()},[c,Me,pe]),at=(0,o.useCallback)(async Ce=>{if(!S||!Te)return;let A=W.current.get(H);if(A&&!fe(A.generation)){W.current.delete(H);return}if(!A&&Be()||A&&!V(A.generation))return;A||V();let bt=A??null;if(W.current.delete(H),!bt&&k){let _t=await k("paypal");if(!_t.proceed){Ce.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}bt={accountPatch:_t.accountPatch,sessionId:_t.sessionId,nonce:_t.nonce}}let ut=bt?.sessionId??e,O=bt?.nonce??t,xe=await Kd({event:Ce,prepared:bt,email:r,billingName:w,methodLabel:"PayPal",collect:kt});if(!xe){Ce.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ot=xe.email,be={...bt?.accountPatch,...(0,Cn.compactBuyerIdentity)(xe,!0)};try{if(Re(!0),s?.(null),!ut||!(0,l.isValidEmail)(Ot))throw new Error("Missing sessionId or email for PayPal payment");await I?.(xe);let _t=S.createPaymentMethod,{error:b,paymentMethod:M}=await _t({type:"paypal"});if(b){ft(b,"stripe_paypal_create_payment_method_failed",A?.generation),Ce.paymentFailed({reason:"fail"});return}let Ae=await Si(n,me,ut,O??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:M?.id??null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(Ae)){Ce.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:be,paymentMethodCategory:"paypal",presentationMode:f,sessionId:ut,nonce:O,settledProcessResponse:Ae.response});return}if(Ae.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Pe=Ae.clientSecret,pt={return_url:(0,l.stripeRedirectReturnUrl)()};if(M?.id&&(pt.payment_method=M.id),!ur(ms,{clientSecret:Pe,sessionId:ut,nonce:O,accountPatch:be})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Ve,paymentIntent:We}=await S.confirmPayment({clientSecret:Pe,confirmParams:pt,redirect:"if_required"});if(Ve){if(ur(ms),(0,we.isProviderDecline)(Ve)){let d=Ve.message??"Your payment was declined.";T?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}),s?.(d),m?.(kr("paypal",d,{code:(0,we.getProviderErrorCode)(Ve),declineCode:(0,we.getProviderDeclineCode)(Ve)})),await wi({billingApiUrl:n,sessionId:ut,nonce:O,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,we.getProviderErrorCode)(Ve)??"provider_declined"}})}else ft(Ve,"stripe_paypal_confirm_failed",A?.generation);return}ur(ms);let Dt=typeof We?.payment_method=="string"?We.payment_method:We?.payment_method?.id;a({id:Dt??We?.id,type:"card",threeDSecureActionResultTokenId:We?.id,isPaypal:!0},{accountPatch:be,paymentMethodCategory:"paypal",presentationMode:f,sessionId:ut,nonce:O});return}catch(_t){ft(_t,"stripe_paypal_failed",A?.generation)}finally{Re(!1)}},[S,Te,e,t,r,w,kt,I,n,me,a,s,m,k,ft,V,fe,Be,T,f,H]),mr=(0,o.useCallback)(async()=>{if(!(dt.current||c||pe||!S||!Te)){dt.current=!0,Re(!0);try{if(!await Me(!0))return;await at({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{dt.current=!1,Re(!1)}}},[Te,at,c,Me,S,pe]),Ft=f==="redirect"?(0,u.jsx)("button",{type:"button",disabled:c||pe,onClick:()=>{mr()},style:{width:"100%",minHeight:Qo,border:"1px solid #d1d5db",borderRadius:_??8,background:"#ffc439",color:"#111827",cursor:c||pe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,u.jsx)(dr.ExpressCheckoutElement,{onReady:Ce=>ye(_a(Ce,["paypal"])),onLoadError:()=>{ye("load_error"),vs(T,"paypal","paypal","provider_error")},onClick:tt,onConfirm:at,onCancel:()=>{let Ce=W.current.get(H);W.current.delete(H),T?.terminal({outcome:"payment_cancelled",...Dn,terminalReason:"cancelled",...Ce?{attempt:Ce.generation}:{}}),He(Ce?.generation),je(!1),Y.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Ge,emailRequired:Ge,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},H),St=(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("div",{ref:de,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[nt&&(0,u.jsx)("button",{ref:ee,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:fs,children:"Try PayPal again"}),x&&(0,u.jsx)(Ho,{identity:x.identity,methodLabel:x.methodLabel,onComplete:Je,onCancel:()=>Je(null)},x.id),(0,u.jsx)("div",{style:{display:x?"none":void 0},children:Ft})]}),pe&&!x&&(0,u.jsx)(sn,{status:"processing"})]});return f==="redirect"?St:(0,u.jsx)(Ta,{state:ae,placeholderTestId:"flopay-paypal-placeholder",borderRadius:_,children:St})}function ys(e){return e==="apple_pay"||e==="google_pay"}var nu=200;function ou({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,l.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function ac({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:c,onErrorChange:p,onButtonClick:m,onDecline:h,onTechnicalFailure:k,runBeforeButtonClick:w,billingName:I,onBuyerIdentityReady:G,onLoadStateChange:_,placeholderBorderRadius:Z,popupCapabilityOwner:F,externalTelemetryContext:f}){let P=io(),{emitInstrument:me}=(0,o.useContext)(vn),S=(0,dr.useStripe)(),Te=(0,dr.useElements)(),T=(0,o.useMemo)(()=>pi(Er(P),f),[f,P]),[ae,ye]=(0,o.useState)("loading");(0,o.useEffect)(()=>{_?.(ae)},[ae,_]);let[pe,Re]=(0,o.useState)(!1);(0,o.useEffect)(()=>{je.current=pe},[pe]);let dt=(0,o.useRef)(!(0,l.isValidEmail)(r?.trim())||!I?.trim()).current,{request:Ge,collect:x,finish:kt}=$o(),Je=(0,o.useRef)(null),Le=(0,o.useRef)(null),[de,ee]=(0,o.useState)(0),[H,Oe]=(0,o.useState)(()=>(0,l.shouldPreferWalletPopup)()),nt=(0,o.useRef)(H),je=(0,o.useRef)(!1),[Y,W]=(0,o.useState)(!1),[$,V]=(0,o.useState)(()=>bi(e,t)?"blocked":"idle"),[He,Be]=(0,o.useState)("google_pay"),fe=(0,o.useRef)(null),B=(0,o.useRef)(!0),ge=(0,o.useRef)(!1),ft=(0,o.useRef)("google_pay"),Ne=(0,o.useRef)("google_pay"),ot=(0,o.useRef)(null),Me=(0,o.useRef)(null),tt=(0,o.useRef)(new Set),at=(0,o.useRef)(null),mr=(0,o.useRef)(null);(0,o.useEffect)(()=>(B.current=!0,()=>{B.current=!1;for(let d of tt.current)window.clearTimeout(d);tt.current.clear()}),[]);let Ft=(0,o.useRef)(new Map),{startAttempt:St,finishAttempt:Ce,invalidateAttempt:A,isAttemptInvalidated:bt,isAttemptCurrent:ut,generationRef:O}=Ca((d,L,z)=>{k?.(d,L,{...z,popupBlocked:z?.popupBlocked??(0,we.isPopupBlockedError)(L),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Be(d),W(!0),ee(se=>se+1)},{onHandoffObserved:d=>{mr.current=O.current,F.markAvailable(),T?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:O.current,...d==="apple_pay"||d==="google_pay"?{walletType:d}:{}})},defersMissingTerminal:ys,onMissingTerminalDeferred:(d,L)=>{let z=T?.now()??globalThis.performance?.now()??Date.now(),se=at.current,E=se?.generation===L?se.startedAt:z;T?.performance({stage:"overlay_return",durationMs:Math.max(0,z-E),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:L,...ys(d)?{walletType:d}:{}}),T?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{Y&&Le.current?.focus()},[Y,de]);let xe=(0,o.useRef)(0),Ot=(0,o.useRef)(!1),be=(0,o.useCallback)(()=>{if(xe.current>0){Ot.current=!0;return}ee(d=>d+1)},[]),_t=(0,o.useCallback)(()=>{xe.current-=1,!(xe.current>0||!Ot.current)&&(Ot.current=!1,B.current&&ee(d=>d+1))},[]),b=(0,o.useCallback)((d,L,z,se,E=!1)=>{A(se),k?.(d,L,{code:z,popupBlocked:(0,we.isPopupBlockedError)(L),telemetryReported:E,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Be(d),W(!0),be()},[A,k,be]),M=(0,o.useCallback)(d=>{T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...ys(d)?{walletType:d}:{}}),k?.(d,new Error("The wallet click was not ready within the time the wallet allows."),{code:Fd,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Be(d),W(!0)},[k,T]),Ae=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Je.current?.querySelector("iframe")??Je.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{ge.current&&(ge.current=!1,Ae())},[Ae,de]);let Pe=(0,o.useCallback)(()=>{W(!1),p?.(null),Ae()},[Ae,p]),pt=(0,o.useCallback)(()=>{fe.current?.()},[]);(0,o.useEffect)(()=>{let d=null,L=()=>{d=null;let se=(0,l.shouldPreferWalletPopup)();se!==nt.current&&(nt.current=se,Oe(se),!je.current&&!ut(O.current)&&be())},z=()=>{d!==null&&window.clearTimeout(d),d=window.setTimeout(L,nu)};return window.addEventListener("resize",z),()=>{window.removeEventListener("resize",z),d!==null&&window.clearTimeout(d)}},[O,ut,be]),(0,o.useEffect)(()=>{let d=bi(e,t);if(!d)return;let L=!1,z=!1,se=async()=>{if(!z){z=!0,L||V("checking");try{let E=await Ql(S,d.clientSecret,tt.current);if(L)return;let q=ps(E,d.providerObjectId,(0,l.isSetupIntentClientSecret)(d.clientSecret));if(q.kind==="confirmed"){if(!Zl(e,t,d.clientSecret))return;fe.current=null,V("idle"),c({id:q.paymentMethodId,type:"card",threeDSecureActionResultTokenId:q.intentId},{...d.accountPatch?{accountPatch:d.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(q.kind==="terminal"){us(e,t,d.clientSecret),fe.current=null,V("idle"),Be(d.paymentMethodType),W(!0),be();return}V("blocked")}catch{L||V("blocked")}finally{z=!1}}};return fe.current=se,V("blocked"),()=>{L=!0,fe.current===se&&(fe.current=null)}},[t,c,be,e,S]);let it=(0,o.useCallback)(async d=>{let L=!1,z=!1,se=rt=>{L||z||(L=!0,d.paymentFailed({reason:"fail",...rt?{message:rt}:{}}))};if(!S||!Te){se();return}let E=Ft.current.get(de);if(E&&!ut(E.generation)){Ft.current.delete(de),se();return}if(!E&&bt()){se();return}if(E&&!Ce(E.generation)){se();return}E||(Ce(),Ot.current=!1);let q=d.expressPaymentType??E?.method??ft.current,Nt=E??null,Br=nc(q),rr;q==="apple_pay"?rr="apple_pay":q==="google_pay"&&(rr="google_pay");let $t=E?.generation??O.current,Tt=T,Wr=Tt?.now()??globalThis.performance?.now()??Date.now(),Nr=new AbortController,nr=!1,Zr=!1,Mt=null,Ln=e,Jt="processing",fn="other",$r="provider_runtime",Hr,Zt=new Promise((rt,Et)=>{Hr=Et}),Cr=window.setTimeout(()=>{nr=!0,Nr.abort(),Hr(vi)},Bd),Qr=async(rt,Et,Dr)=>{Jt=rt,fn=Et,$r=Et==="intent_create"||Et==="session_claim"?"transport_error":"provider_runtime";let Ht=Tt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Dr,Zt])}finally{let or=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.performance({stage:rt,durationMs:Math.max(0,or-Ht),durationMode:"machine",requestCategory:Et,paymentMethodCategory:"wallet",provider:"stripe",...nr?{statusClass:"timeout"}:{}})}};try{if(Re(!0),p?.(null),!Nt&&w){let ve=await Qr("processing","other",w(Br));if(!ve.proceed){se();return}Nt={accountPatch:ve.accountPatch,sessionId:ve.sessionId,nonce:ve.nonce}}let rt=Nt?.sessionId??e;Ln=rt;let Et=Nt?.nonce??t,Dr=ot.current??Nt?.accountPatch,Ht=dc({event:d,fallbackEmail:Dr?.email??r,fallbackName:[Dr?.firstName,Dr?.lastName].join(" ").trim()||I});if(!(0,l.isValidEmail)(Ht.email)){se("Buyer details are required."),x(gs(q),Ht).then(ve=>{ve&&(ot.current=ve)});return}ot.current=null;let or={...Nt?.accountPatch,...(0,Cn.compactBuyerIdentity)(Ht,!0)};await Qr("processing","session_claim",Promise.resolve(G?.(Ht)));let{error:br}=await Qr("tokenization","provider_sdk",Te.submit());if(br){se(),b(q,br,"stripe_wallet_submit_failed",E?.generation);return}if(!rt)throw new Error("Missing sessionId or email for payment.");let Qt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:q,paymentMethodId:null,intentKind:a},Kt=JSON.stringify({sessionId:rt,nonce:Et??"",request:Qt}),_r=Me.current,Ze=_r?.retryIdentity===Kt?_r.authorizationAttemptId:(0,l.randomUuidV4)();Me.current={authorizationAttemptId:Ze,retryIdentity:Kt};let ar=await Qr("processing","intent_create",Si(n,me,rt,Et??"",{...Qt,authorizationAttemptId:Ze},{signal:Nr.signal}));if((0,l.isSettledSessionIntent)(ar)){se(),c({type:"card",paymentMethodType:q},{accountPatch:or,paymentMethodCategory:"wallet",sessionId:rt,nonce:Et,settledProcessResponse:ar.response});return}if(ar.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Tr=ar.clientSecret,Jn=qd({createdAt:Date.now(),sessionId:rt,...Et?{nonce:Et}:{},clientSecret:Tr,providerObjectId:ar.providerObjectId,paymentMethodType:q,accountPatch:or});window.clearTimeout(Cr),Zr=!0,Tt?.performance({stage:"callback",durationMs:Math.max(0,(Tt?.now()??globalThis.performance?.now()??Date.now())-Wr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Ur=Tt?.now()??globalThis.performance?.now()??Date.now(),zr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...rr?{walletType:rr}:{},attempt:$t},Nn=!1,cn=null;Tt?.log({name:"payment.provider_confirmation.started",...zr}),Mt=window.setTimeout(()=>{Mt!==null&&tt.current.delete(Mt),Nn=!0;let ve=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...zr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ve-Ur),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Tt?.flush?.().catch(()=>{}),cn?.()},Dd),tt.current.add(Mt);let ir=(ve,Wt)=>{Mt!==null&&(window.clearTimeout(Mt),tt.current.delete(Mt),Mt=null);let oe=Tt?.now()??globalThis.performance?.now()??Date.now(),Lt=Math.max(0,oe-Ur),wr=ve;Nn&&(ve==="resolved"?wr="resolved_late":ve==="returned_error"?wr="returned_error_late":wr="rejected_late");let qr=Wt??(ve==="resolved"?"approved":"provider_error");return Tt?.log({name:"payment.provider_confirmation.returned",...zr,operationOutcome:wr,terminalReason:qr}),Tt?.performance({...zr,durationMs:Lt,durationMode:"buyer",operationOutcome:wr,terminalReason:qr}),{durationMs:Lt,operationOutcome:wr,terminalReason:qr}},he=!1,Sr=!1,Kr=ve=>{if(!ve||typeof ve!="object")return null;let Wt=ve;if(Wt.error)return null;let oe=Wt.setupIntent??Wt.paymentIntent,Lt=ps(oe??null,void 0,!!Wt.setupIntent);return Lt.kind==="confirmed"?Lt:null},re=ve=>{if(he||E&&O.current!==E.generation)return;let Wt=Kr(ve);if(!Wt)return;if(Jn&&!Zl(rt,Et,Tr)){he=!0;return}let{intentId:oe,paymentMethodId:Lt}=Wt;he=!0,Sr=!0,Me.current=null,fe.current=null,B.current&&(V("idle"),Re(!1));let wr=`${sc}:${rt}`;ur(wr,{createdAt:Date.now(),sessionId:rt,nonce:Et,accountPatch:or,paymentMethodId:Lt,providerIntentId:oe,paymentMethodType:q});try{c({id:Lt,type:"card",threeDSecureActionResultTokenId:oe},{accountPatch:or,paymentMethodCategory:"wallet",sessionId:rt,nonce:Et})}finally{ur(wr)}},Bt=!1;cn=async()=>{if(!(Bt||he||Sr)){Bt=!0,B.current&&V("checking");try{let ve=await Ql(S,Tr,tt.current);if(he||Sr)return;let Wt=(0,l.isSetupIntentClientSecret)(Tr),oe=ps(ve,ar.providerObjectId,Wt);if(oe.kind==="confirmed"){re(Wt?{setupIntent:ve}:{paymentIntent:ve});return}if(oe.kind==="terminal"){if(Sr=!0,us(rt,Et,Tr),Me.current=null,fe.current=null,!B.current)return;V("idle"),se(),b(q,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",E?.generation,!0);return}B.current&&!Sr&&(V("blocked"),Re(!1))}catch{B.current&&!Sr&&(V("blocked"),Re(!1))}finally{Bt=!1}}},fe.current=cn;let Q,Gt;try{z=!0,xe.current+=1;let ve;try{ve=await((0,l.isSetupIntentClientSecret)(Tr)?S.confirmSetup({elements:Te,clientSecret:Tr,redirect:"if_required"}):S.confirmPayment({elements:Te,clientSecret:Tr,redirect:"if_required"}))}finally{_t()}if(!ve||typeof ve!="object")throw new Aa(zd(ve));if(Q=ve,!Q.error&&!Kr(Q))throw new Aa("confirmation_result_unconfirmed");Gt=ir(Q.error?"returned_error":"resolved",Q.error&&(0,we.isProviderDecline)(Q.error)?"provider_declined":void 0)}catch(ve){let Wt=ve instanceof Aa?ve.reason:void 0,oe=Wt!==void 0,Lt=ir(oe?"returned_error":"rejected");if(Tt?.error({...oe?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Wt}:rs(ve),...zr,operationOutcome:Lt.operationOutcome,durationMs:Lt.durationMs,statusClass:"unknown",terminalReason:Lt.terminalReason}),!B.current||he)return;await cn?.();return}let sr=Q.error;if(sr){if(!B.current||he)return;if((0,we.isProviderDecline)(sr)){Sr=!0,us(rt,Et,Tr),Me.current=null,fe.current=null,V("idle"),Ft.current.get(de)===E&&Ft.current.delete(de);let ve=sr.message??"Your payment was declined.";p?.(ve),h?.(kr(Br,ve,{code:(0,we.getProviderErrorCode)(sr),declineCode:(0,we.getProviderDeclineCode)(sr)})),wi({billingApiUrl:n,sessionId:rt,nonce:Et,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:q,providerDeclineReason:(0,we.getProviderErrorCode)(sr)??"provider_declined",...ar.intentKind==="payment"&&ar.providerObjectId.startsWith("pi_")?{providerIntentId:ar.providerObjectId}:{}}})}else Tt?.error({...rs(sr),...zr,operationOutcome:Gt.operationOutcome,durationMs:Gt.durationMs,statusClass:"unknown",terminalReason:Gt.terminalReason}),await cn?.();return}if(re(Q),!he)throw new Error("Invalid provider returned for APM intent")}catch(rt){if(rt===vi){let Et=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.error({errorCode:Vd(fn),stage:Jt,requestCategory:fn,paymentMethodCategory:"wallet",provider:"stripe",...rr?{walletType:rr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ln,durationMs:Math.max(0,Et-Wr),statusClass:"timeout",failureCategory:$r,attempt:$t,terminalReason:"provider_error"}),Tt?.flush?.().catch(()=>{})}se(),b(q,rt,rt===vi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",E?.generation,rt===vi)}finally{if(window.clearTimeout(Cr),Mt!==null&&(window.clearTimeout(Mt),tt.current.delete(Mt)),!Zr){let rt=Tt?.now()??globalThis.performance?.now()??Date.now();Tt?.performance({stage:"callback",durationMs:Math.max(0,rt-Wr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...nr?{statusClass:"timeout"}:{}})}B.current&&Re(!1)}},[S,Te,e,t,r,I,x,G,n,me,a,c,p,h,w,b,_t,Ce,ut,bt,O,T,de]),Ve=(0,o.useMemo)(()=>yi(s),[s]),We=(0,o.useMemo)(()=>s.map(l.stripeExpressMethodToOptionKey),[s]),Dt=(0,o.useMemo)(()=>(0,u.jsx)(dr.ExpressCheckoutElement,{onReady:d=>{ye(_a(d,We))},onLoadError:d=>{ye("load_error"),vs(T,"stripe","wallet","provider_error")},onClick:async d=>{let L=T?.now()??globalThis.performance?.now()??Date.now();ft.current=d.expressPaymentType,Ne.current=nc(d.expressPaymentType);let z=!0,se=window.setTimeout(()=>{z=!1,d.reject(),M(d.expressPaymentType)},Ad),E=w?await w(Ne.current,{abandoned:()=>!z}):{proceed:!0};if(window.clearTimeout(se),!z)return;if(!E.proceed){Ft.current.delete(de),d.reject();return}let q=St(d.expressPaymentType);Ot.current=!1,at.current={generation:q,startedAt:L},Ft.current.set(de,{generation:q,method:d.expressPaymentType,accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}),W(!1),T?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:q,...d.expressPaymentType==="apple_pay"||d.expressPaymentType==="google_pay"?{walletType:d.expressPaymentType}:{}}),m?.(Ne.current),d.resolve()},onConfirm:it,onCancel:()=>{let d=Ft.current.get(de);Ft.current.delete(de);let L=at.current,z=T?.now()??globalThis.performance?.now()??Date.now();if(d&&L?.generation===d.generation&&(0,l.isWalletSheetRefusedForWindowSize)({method:d.method,elapsedMs:z-L.startedAt,handoffObserved:mr.current===d.generation})){T?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:d.generation,walletType:"google_pay"}),Me.current=null,b(d.method,new Error("The browser window is too small for the Google Pay sheet."),l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,d.generation,!0);return}T?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...d?{attempt:d.generation}:{}}),A(d?.generation),Me.current=null,W(!1),ge.current=!0,be()},options:{...fi,paymentMethods:Ve,emailRequired:dt,billingAddressRequired:dt}},de),[We,Ve,it,A,m,dt,b,M,be,w,St,de,T]);return(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(Ta,{state:ae,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Z,children:(0,u.jsxs)("div",{ref:Je,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Y&&(0,u.jsxs)("button",{ref:Le,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Pe,style:fs,children:["Try ",gs(He)," again"]}),$!=="idle"&&(0,u.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,u.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,u.jsx)("button",{type:"button",onClick:pt,disabled:$==="checking",style:fs,children:$==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ge&&(0,u.jsx)(Ho,{identity:Ge.identity,methodLabel:Ge.methodLabel,onComplete:kt,onCancel:()=>kt(null)},Ge.id),(0,u.jsxs)("div",{style:{display:Ge||$!=="idle"?"none":void 0},children:[(0,u.jsx)(ou,{active:H}),Dt]})]})}),pe&&(0,u.jsx)(sn,{status:"processing"})]})}function uc(e,t,r){let n=(0,l.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function hs({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:c,onTokenizedBody:p,onErrorChange:m,onDecline:h,onCancel:k,runBeforeButtonClick:w,onButtonClick:I,isProcessing:G,submitButtonColor:_,submitButtonBorderRadius:Z,submitButtonStyle:F,errorText:f}){let P=io(),{emitInstrument:me}=(0,o.useContext)(vn),S=(0,dr.useStripe)(),Te=(0,dr.useElements)(),[T,ae]=(0,o.useState)(!1),ye=(0,o.useRef)(!1),[pe,Re]=(0,o.useState)(!1),[dt,Ge]=(0,o.useState)("loading"),[x,kt]=(0,o.useState)(""),Je=!(0,l.isValidEmail)(n?.trim()),Le=!Je||(0,l.isValidEmail)(x.trim()),de=(0,o.useCallback)(async()=>{if(!S||!Te||G||ye.current||!pe)return;ye.current=!0,ae(!0);let ee=w?await w("card"):{proceed:!0};if(!ee.proceed){ye.current=!1,ae(!1);return}I?.("card");let H=ee.sessionId??t,Oe=ee.nonce??r,nt=(0,Wo.splitFullName)(a?.trim()),je=(0,Cn.compactBuyerIdentity)({email:ee.accountPatch?.email?.trim()||n?.trim()||x.trim(),firstName:ee.accountPatch?.firstName?.trim()||nt.firstName,lastName:ee.accountPatch?.lastName?.trim()||nt.lastName}),Y=je.email,W=(0,Cn.compactBuyerIdentity)({...ee.accountPatch,...je});try{if(m?.(null),!(0,l.isValidEmail)(Y))throw new Error("A valid email address is required for payment.");await s?.(je);let $=await Te.submit();if($.error){m?.($.error.message??"Payment failed.");return}let V=[je.firstName,je.lastName].filter(Boolean).join(" "),He=await S.createPaymentMethod({elements:Te,params:{billing_details:{email:Y,...V?{name:V}:{}}}});if(He.error||!He.paymentMethod){m?.(He.error?.message??"Failed to create payment method.");return}let Be=He.paymentMethod;if(!H||!Y)throw new Error("Missing sessionId or email for payment.");let fe=Be.type||e,B=await Si(c,me,H,Oe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:fe,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(B)){p({type:"card",gateway:"stripe",paymentMethodType:fe},{accountPatch:W,paymentMethodCategory:"apm",sessionId:H,nonce:Oe,settledProcessResponse:B.response});return}if(B.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ge=B.clientSecret;ur(Gn,{clientSecret:ge,sessionId:H,nonce:Oe,accountPatch:W,paymentMethodId:Be.id,paymentMethodType:Be.type??e,gateway:"stripe"});let{error:ft,paymentIntent:Ne}=await S.confirmPayment({clientSecret:ge,confirmParams:{return_url:window.location.href,payment_method:Be.id},redirect:"if_required"});if(ft){ur(Gn);let tt=ft.message??"Payment failed.";m?.(tt),h?.(kr("card",tt,{code:ft.code})),await wi({billingApiUrl:c,sessionId:H,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ft.code??"provider_declined"}});return}let ot=Ne?.status;if(!ga(ot)){ur(Gn);let tt=ot==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(tt),h?.(kr("card",tt,{code:ot??"missing_payment_intent"}));return}ur(Gn);let Me=typeof Ne?.payment_method=="string"?Ne.payment_method:Ne?.payment_method?.id;p({id:Me??Be.id,type:"card",threeDSecureActionResultTokenId:Ne?.id,gateway:"stripe",paymentMethodType:Be.type??e},{accountPatch:W,paymentMethodCategory:"apm",sessionId:H,nonce:Oe})}catch($){m?.($ instanceof Error?$.message:"Payment failed. Please try again.")}finally{ye.current=!1,ae(!1)}},[S,Te,G,pe,w,I,t,r,n,a,x,s,c,me,e,p,m,h]);return(0,u.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Je&&(0,u.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Je&&(0,u.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,u.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:x,onChange:ee=>kt(ee.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,u.jsx)(dr.PaymentElement,{onReady:()=>Ge("ready"),onLoadError:()=>{Ge("load_error"),vs(Er(P),"stripe","apm")},onChange:ee=>{Re(!!ee.complete)},options:{layout:gi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,l.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,u.jsx)(hi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{de()},disabled:!pe||!Le||T||G||dt!=="ready",color:_,borderRadius:Z,style:F,children:T?"Processing\u2026":`Pay with ${(0,l.getStripeMethodDisplayName)(e)}`}),f&&(0,u.jsx)(Yo,{margin:"0.75rem 0 0",children:f})]})}function ic({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:c,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:h,onTokenizedBody:k,onErrorChange:w,onButtonClick:I,onDecline:G,runBeforeButtonClick:_,onLoadStateChange:Z,isProcessing:F=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:me,buttonAppearance:S,themeId:Te,onExpandApm:T,expandedApmMethod:ae}){let{emitInstrument:ye}=(0,o.useContext)(vn),[pe,Re]=(0,o.useState)(null),[dt,Ge]=(0,o.useState)(null),x=(0,o.useRef)(!1),{request:kt,collect:Je,finish:Le}=$o();(0,o.useEffect)(()=>{c.length>0&&p?Z?.("ready"):p||Z?.("loading")},[c.length,p,Z]);let de=(0,o.useCallback)(async Y=>{if(!p||x.current||F)return;x.current=!0,Ge(Y);let W=_?await _("card"):{proceed:!0};if(!W.proceed){x.current=!1,Ge(null);return}I?.("card");let $=W.sessionId??e,V=W.nonce??t,He=(0,Wo.splitFullName)([W.accountPatch?.firstName,W.accountPatch?.lastName].filter(Boolean).join(" ")||n),Be=(0,Cn.compactBuyerIdentity)({email:W.accountPatch?.email?.trim()||r?.trim(),firstName:W.accountPatch?.firstName?.trim()||He.firstName,lastName:W.accountPatch?.lastName?.trim()||He.lastName});if(!(0,l.isValidEmail)(Be.email)){Ge(null);let ge=await Je((0,l.getStripeMethodDisplayName)(Y),Be);if(!ge){x.current=!1;return}Be=ge,Ge(Y)}let fe=Be.email,B=(0,Cn.compactBuyerIdentity)({...W.accountPatch,...Be});try{if(w?.(null),!$||!(0,l.isValidEmail)(fe))throw new Error("Missing sessionId or email for payment.");await a?.(Be);let ge=await Si(s,ye,$,V??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Y,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(ge)){k({type:"card",gateway:"stripe",paymentMethodType:Y},{accountPatch:B,paymentMethodCategory:"apm",sessionId:$,nonce:V,settledProcessResponse:ge.response});return}if(ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ft=ge.clientSecret;ur(Gn,{clientSecret:ft,sessionId:$,nonce:V,accountPatch:B,paymentMethodType:Y,gateway:"stripe"});let{error:Ne,paymentIntent:ot}=await p.confirmPayment({clientSecret:ft,confirmParams:{return_url:window.location.href,payment_method_data:{type:Y,billing_details:{name:[Be.firstName,Be.lastName].filter(Boolean).join(" "),...fe?{email:fe}:{}}}},redirect:"if_required"});if(Ne){ur(Gn);let at=Ne.message??"Payment failed.";w?.(at),G?.(kr("card",at,{code:Ne.code})),await wi({billingApiUrl:s,sessionId:$,nonce:V,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Y,providerDeclineReason:Ne.code??"provider_declined"}});return}let Me=ot?.status;if(!ga(Me)){ur(Gn);let at=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";w?.(at),G?.(kr("card",at,{code:Me??"missing_payment_intent"}));return}ur(Gn);let tt=typeof ot?.payment_method=="string"?ot.payment_method:ot?.payment_method?.id;k({id:tt??ot?.id,type:"card",threeDSecureActionResultTokenId:ot?.id,gateway:"stripe",paymentMethodType:Y},{accountPatch:B,paymentMethodCategory:"apm",sessionId:$,nonce:V})}catch(ge){w?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{x.current=!1,Ge(null)}},[p,F,_,I,e,t,r,Je,s,ye,n,a,k,w,G]),[ee,H]=(0,o.useState)(null),Oe=T?ae??null:ee,nt=(0,o.useCallback)(Y=>{x.current||F||Oe&&Oe!==Y||((0,l.needsStripeMethodExplicitConfirm)(Y)?T?T(Y):H(Y):de(Y))},[Oe,F,de,T]),je=(0,o.useMemo)(()=>ee?uc(m,ee,h):null,[ee,m,h]);return(0,u.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:kt?(0,u.jsx)(Ho,{identity:kt.identity,methodLabel:kt.methodLabel,onComplete:Le,onCancel:()=>Le(null)},kt.id):c.map(Y=>{let W=ae===Y,$=dt===Y,V=dt!==null&&dt!==Y||ae!=null&&ae!==Y;return(0,u.jsxs)(o.default.Fragment,{children:[(0,u.jsx)(mi,{method:Y,themeId:Te,submitting:$,disabled:V,highlighted:W,hasNextStep:(0,l.needsStripeMethodExplicitConfirm)(Y),onClick:()=>nt(Y),backgroundColor:S?.backgroundColor,borderColor:S?.borderColor,textColor:S?.textColor,borderRadius:S?.borderRadius,fontFamily:S?.fontFamily}),!T&&ee===Y&&je&&p&&(0,u.jsx)(dr.Elements,{stripe:p,options:je,children:(0,u.jsx)(hs,{method:Y,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:k,onErrorChange:w,onDecline:G,onCancel:()=>H(null),runBeforeButtonClick:_,onButtonClick:I,isProcessing:F,submitButtonColor:f,submitButtonBorderRadius:P,submitButtonStyle:me})},Y)]},Y)})})}function au({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:c,onError:p,onDecline:m,onCancel:h,onTokenizedBody:k,firstName:w,lastName:I,chv:G,className:_,submitLabel:Z,isProcessing:F,error:f,onErrorChange:P,showPayPal:me=!0,showStripe:S=!0,walletPresentation:Te="auto",enabledPaymentMethods:T,enabledPaymentMethodCountries:ae,showApplePay:ye=!0,showGooglePay:pe=!0,layout:Re="default",theme:dt,buttonsTheme:Ge,buttonsStyles:x,appearance:kt,cardButtonContent:Je,cardBackButtonContent:Le,cardTitleContent:de,showSecurityFooter:ee,onButtonClick:H,onBeforeButtonClick:Oe,onBuyerIdentityReady:nt,enableAVS:je,cardFieldOrder:Y,cardPreFormSlot:W,avsLayout:$="row",country:V,zip:He,addressLine1:Be,addressLine2:fe,city:B,state:ge,onCountryChange:ft,onZipChange:Ne,avsCheck:ot,checkoutType:Me,checkoutLayout:tt,totalAmount:at=0,currency:mr="usd",initialCardOpen:Ft=!1,directPaypal:St,isSubscription:Ce=!1,session:A,dataAttachmentPending:bt=!1,dataAttachmentRequiresIdentity:ut=!1,debug:O=!1}){let xe=io(),Ot=ti(),be=(0,o.useContext)(An),{emitInstrument:_t}=(0,o.useContext)(vn),b=(0,o.useRef)(null);b.current||(b.current=ni());let M=b.current,[,Ae]=(0,o.useState)(0),Pe=(0,o.useRef)(null);Pe.current||(Pe.current=(0,$n.detectPayPalEnvironment)());let pt=Pe.current,it=(0,o.useMemo)(()=>({browser:pt,capability:M,presentationMode:"popup"}),[pt,M]),Ve=A??be.session,We=(0,o.useMemo)(()=>({futureUse:Ve?.futureUse,futureUseUnsupported:Ve?.futureUseUnsupported}),[Ve?.futureUse,Ve?.futureUseUnsupported]),Dt=Ve?.gateways?.paypal?.providerObjectType??St?.providerObjectType,d=bt||be.claimPending===!0,L=ut||be.claimRequiresIdentity===!0,z=d&&!L,se=Dl(),E=r||se,[q,Nt]=(0,o.useState)(!1),[Br,rr]=(0,o.useState)(null),[$t,Tt]=(0,o.useState)(V??""),[Wr,Nr]=(0,o.useState)(He??""),[nr,Zr]=(0,o.useState)(Be??""),[Mt,Ln]=(0,o.useState)(fe??""),[Jt,fn]=(0,o.useState)(B??""),[$r,Hr]=(0,o.useState)(ge??""),[Zt,Cr]=(0,o.useState)(""),[Qr,rt]=(0,o.useState)({}),Et=(0,o.useRef)(He??""),Dr=(0,o.useRef)(V??""),Ht=(0,o.useRef)(Be??""),or=(0,o.useRef)(fe??""),br=(0,o.useRef)(B??""),Qt=(0,o.useRef)(ge??""),Kt=(0,o.useRef)(""),_r=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(C,K,Ie,J,_e)=>{if(_r.current[C])return;let zt=K?.trim();!zt||zt===Ie.current||(Ie.current=zt,J(zt),_e?.(zt))};i("country",V,Dr,Tt,ft),i("zip",He,Et,Nr,Ne),i("addressLine1",Be,Ht,Zr),i("addressLine2",fe,or,Ln),i("city",B,br,fn),i("state",ge,Qt,Hr)},[V,He,Be,fe,B,ge,ft,Ne]);let Ze=(0,o.useMemo)(()=>(0,l.resolveAVSConfig)(je),[je]),ar=Ze!==null,Tr=(0,o.useMemo)(()=>(0,l.isAuthorizationOnlySession)(A),[A]),Jn=(0,l.isMountableVaultBlock)(A?.vault),Ur=!!A?.gateways?.pcivault,zr=(0,xn.hasServerSideCardGateway)(A),cn=!!(A?.gateways?.stripe?.enabledPaymentMethods??T)?.includes("card")||(0,xn.canRecoverHostedCardForm)(A),ir=Jn||cn||Ur,he=!!(S&&ir&&e),[Sr,Kr]=(0,o.useState)(()=>Re!=="buttons"||Ft?e??null:null),[re,Bt]=(0,o.useState)(0),Q=Re!=="buttons"||Ft||!!e&&Sr===e,Gt=A?.captureMethod,sr=(0,o.useRef)(xe);(0,o.useEffect)(()=>{sr.current=xe},[xe]);let[ve,Wt]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!he||!e||!Q){Wt(null);return}let i=sr.current?sr.current.cardCapture({sessionId:e,captureMethod:Gt}):new On.PciVaultCardCapture({sessionId:e,captureMethod:Gt,billingApiUrl:E,telemetry:n});return Wt({sessionId:e,captureMethod:Gt,billingApiUrl:E,telemetry:n,capture:i}),()=>{i.unmount()}},[he,e,Q,Gt,E,n]);let oe=he&&e&&Q&&ve?.sessionId===e&&ve.captureMethod===Gt&&ve.billingApiUrl===E&&ve.telemetry===n?ve.capture:null,Lt=(0,o.useMemo)(()=>{let i=$t,C=Ze?(0,l.isAVSFieldVisible)(Ze.postal_code,i):!1;return eu(i,Wr,C)},[Ze,$t,Wr]),{avsInvalid:wr,invalidAvsFields:qr}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!he||!Ze)return{avsInvalid:!1,invalidAvsFields:i};let C=$t,K=(_e,zt)=>(0,l.isAVSFieldVisible)(_e,C)&&!zt.trim(),Ie={line1:K(Ze.address_line_1,nr),city:K(Ze.city,Jt),state:K(Ze.state,$r),zip:Lt.empty||Lt.malformed};return{avsInvalid:Ie.line1||Ie.city||Ie.state||Ie.zip,invalidAvsFields:Ie}},[he,Ze,$t,nr,Jt,$r,Lt]),[er,Un]=(0,o.useState)(!1),[Zn,zn]=(0,o.useState)(!1),[qn,Qn]=(0,o.useState)(!1),[po,mo]=(0,o.useState)({line1:!1,city:!1,state:!1}),Or=(0,o.useRef)(!1),eo=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),gn=(0,o.useRef)(!1),Ut=(0,o.useCallback)(i=>{eo.current[i]=!0,gn.current=!0},[]),en=(0,o.useCallback)(i=>!Or.current&&eo.current[i],[]),tn=(0,o.useCallback)(i=>{en(i)&&mo(C=>C[i]?C:{...C,[i]:!0})},[en]),[dn,rn]=(0,o.useState)(()=>(0,l.resolveVaultMountOptions)(A?.vault,{billingApiUrl:E,sessionId:e,nonce:t})),[mt,yr]=(0,o.useState)(Ft&&ir?"card":"buttons"),[lr,Gr]=(0,o.useState)(null),ho=mt==="expanding"||mt==="card",to=A?.gateways?.stripe&&!zr?"stripe":void 0,In=(0,o.useCallback)(()=>{_t?.({class:"card_surface",provider:to})},[to,_t]),un=(0,o.useRef)(null),Mr=(0,o.useCallback)(i=>{un.current&&clearTimeout(un.current),un.current=setTimeout(()=>{un.current=null,i()},Fa)},[]);(0,o.useEffect)(()=>()=>{un.current&&clearTimeout(un.current)},[]);let ro=(0,o.useRef)(!1),[jr,N]=(0,o.useState)(0),j=(0,o.useRef)(null),ne=(0,o.useCallback)(()=>{In(),Kr(e??null),ro.current&&(ro.current=!1,N(i=>i+1)),Bt(i=>i+1),yr("expanding"),Mr(()=>yr("card"))},[Mr,In,e]),Se=(0,o.useCallback)(()=>{yr("collapsing"),Mr(()=>yr("buttons"))},[Mr]),gt=(0,o.useCallback)(i=>{Gr(i),yr("apm-expanding"),Mr(()=>yr("apm-form"))},[Mr]),Yt=(0,o.useCallback)(()=>{yr("apm-collapsing"),Mr(()=>{yr("buttons"),Gr(null)})},[Mr]);(0,o.useEffect)(()=>{Re==="buttons"&&Ft&&ir&&(Kr(e??null),yr("card"))},[Re,Ft,ir,e]);let[ke,ie]=(0,o.useState)(null),te=(0,o.useRef)(null),[Qe,Ee]=(0,o.useState)(0);(0,o.useEffect)(()=>{Qe!==0&&te.current?.focus()},[Qe]);let st=(0,o.useRef)(!1),U=(0,o.useRef)(null),ue=(0,o.useRef)("idle"),[ht,It]=(0,o.useState)(!1),Rr=(0,o.useRef)(ht);Rr.current=ht;let[y,g]=(0,o.useState)(()=>St?.existingOrderId?{orderId:St.existingOrderId,attempts:1}:null),X=(0,o.useRef)(y);(0,o.useEffect)(()=>{X.current=y},[y]);let Ke=(0,o.useRef)(null),$e=(0,o.useMemo)(()=>{if(nt||be.claimBuyerIdentity||A?.buyerIdentified!==!1||!e||!t)return;let i=`${E}|${e}|${t}`;Ke.current?.key!==i&&(Ke.current={key:i,claim:jo(new On.PaymentAPI(E,{telemetry:!1}),e,t,{...s?{userId:s}:{},...w?{firstName:w}:{},...I?{lastName:I}:{}})});let C=Ke.current.claim;return async K=>{await C(K)}},[nt,be.claimBuyerIdentity,A?.buyerIdentified,e,t,E,s,w,I]),Ue=nt??be.claimBuyerIdentity??$e,et=f??Br,qt=(0,o.useMemo)(()=>(0,l.resolveTheme)(dt),[dt]),le=(0,o.useMemo)(()=>{let i=qt?.buttonsLayout??(0,l.resolveButtonsLayoutTheme)(Ge);return x?{...i,...x,cardButton:{...i.cardButton,...x.cardButton},cardFormContainer:{...i.cardFormContainer,...x.cardFormContainer},backButton:{...i.backButton,...x.backButton},backButtonIcon:{...i.backButtonIcon,...x.backButtonIcon},submitButton:{...i.submitButton,...x.submitButton},title:{...i.title,...x.title}}:i},[qt,Ge,x]),fr=kt??qt?.appearance,_o=(0,o.useMemo)(()=>(0,l.computeVaultCardThemeColors)({appearance:fr,buttonsStyles:le,layout:Re}),[fr,le,Re]),xt=be.inlineSessionPatchProcessing??!1,Fe=(F??q)||xt,lt=E.replace(/\/+$/,""),ce=(0,o.useMemo)(()=>ts({userId:s,email:a,firstName:w,lastName:I,country:V,zip:He},Qr),[s,a,w,I,V,He,Qr]),yt=[ce.firstName,ce.lastName].filter(i=>!!i?.trim()).join(" "),nn=!(0,l.isValidEmail)(ce.email?.trim()),jt=(0,o.useRef)(null);he&&jt.current===null&&(jt.current=nn);let _n=he&&(jt.current??nn),Fi=(0,o.useMemo)(()=>tu(Zt,_n),[Zt,_n]),To=Fi.empty||Fi.malformed,pn=(0,o.useMemo)(()=>xe?xe.getRawProvider():null,[xe]),As=(0,o.useMemo)(()=>Ot?Ot.getRawProvider():null,[Ot]),na=at||100,Mo=mr.toLowerCase(),Bi=(0,o.useMemo)(()=>fr?(0,On.toStripeAppearance)(fr):null,[fr]),xo=Bi,Fs=(0,o.useMemo)(()=>{let i=Bi??{},C=i.rules??{};return{...i,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[Bi]),Bs=(0,o.useMemo)(()=>({...Al(at,Ve?.captureMethod,We),currency:Mo,...xo?{appearance:xo}:null}),[at,Mo,Ve?.captureMethod,We,xo]),Di=(0,l.resolveSetupFutureUsage)(We,"paypal","paypal"),Ds=(0,o.useMemo)(()=>({mode:"payment",amount:na,currency:Mo,captureMethod:"manual",...Di?{setupFutureUsage:Di}:null,...xo?{appearance:xo}:null}),[na,Mo,Di,xo]),ze=(0,o.useCallback)(i=>{rr(i),P?.(i)},[P]),Os=(0,o.useRef)(0);(0,o.useEffect)(()=>{jr!==Os.current&&(Os.current=jr,ze(null))},[jr,ze]);let Oi=(0,o.useRef)(""),[Ls,Bc]=(0,o.useState)(!1),Li=(0,o.useCallback)(()=>{Bc(!0)},[]);(0,o.useEffect)(()=>{if(!he||!_n||!Ue||!Ls||To||Oi.current)return;let i=(0,Cn.compactBuyerIdentity)({email:(0,l.isValidEmail)(ce.email?.trim())?ce.email?.trim():Kt.current.trim(),firstName:ce.firstName?.trim(),lastName:ce.lastName?.trim()});Oi.current=JSON.stringify(i),rt(C=>({...C,...i})),Promise.resolve(Ue(i)).catch(C=>{Oi.current="",ze(C instanceof Error?C.message:"Failed to attach buyer details.")})},[he,_n,Ue,Ls,To,ce.email,ce.firstName,ce.lastName,ze]),(0,o.useEffect)(()=>{!he||!oe||oe.setCardFieldOrder?.(Y??null,Ze==null&&!_n)},[he,oe,Y,Ze,_n]),(0,o.useEffect)(()=>{(mt==="expanding"||mt==="collapsing"||mt==="apm-expanding"||mt==="apm-collapsing")&&ze(null)},[mt,ze]);let jn=(0,o.useCallback)((i,C,K)=>{m?.(kr(i,C,K))},[m]),Ns=(0,o.useRef)(mt);Ns.current=mt;let[Us]=(0,o.useState)(ai),zs=(0,o.useCallback)(()=>{let i=Ns.current;if(Re==="buttons"&&(i==="card"||i==="expanding"))return!0;let C=ue.current;return C==="validation-window"||C==="processing"||Rr.current},[Re]),qs=(0,o.useCallback)((i,C,K)=>{Us.take(e)&&Er(xe)?.log(ko({...it,presentationMode:K?.presentationMode??"popup"},{name:oi,stage:"recovery",reason:"other_method_active",provider:K?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:K?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[it,xe,Us,e]),Na=(0,o.useCallback)((i,C,K)=>{K?.telemetryReported||Er(xe)?.error(ko({...it,presentationMode:K?.presentationMode??"popup"},{errorCode:C?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:K?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:K?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:K?.terminalReason??(C?"popup_blocked":"provider_error")}))},[it,xe]),Ao=(0,o.useCallback)((i,C,K)=>{let Ie=K?.popupBlocked??(0,we.isPopupBlockedError)(C);if(zs()){Na(i,Ie,K),qs(i,C,K);return}if(C instanceof l.FloPayError&&C.code==="checkout_processing_timeout"){Na(i,!1,K),ie(null),Re==="buttons"&&(yr("buttons"),Gr(null)),ze(C.message),p?.(C);return}Ie&&M.markBlocked()&&Ae(wt=>wt+1);let J=gs(i),_e=K?.code===l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,l.buildWalletSheetWindowMessage)(J):(0,we.buildExternalMethodRecoveryMessage)(J,Ie,pt.inAppBrowser),zt=(0,we.getProviderErrorCode)(C),Pn=(zt?.toLowerCase()==="error"?void 0:zt)??(0,we.sanitizeExternalFailureCode)(K?.code)??"external_payment_method_failed",Pt=new l.FloPayError(_e,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:Pn,popupBlocked:Ie,inAppBrowser:pt.inAppBrowser,appFamily:pt.appFamily,popupCapability:M.current(),presentationMode:K?.presentationMode??"popup"}});Na(i,Ie,K),ie(null),Re==="buttons"&&(yr("buttons"),Gr(null)),ze(_e),p?.(Pt),console.error("[FloPay] External payment method failed:",{method:i,code:Pn,popupBlocked:Ie})},[pt,zs,Re,p,M,qs,Na,ze]);(0,o.useEffect)(()=>{if(!he||!e){rn(null);return}let i={billingApiUrl:lt,sessionId:e,nonce:t},C=(0,l.resolveVaultMountOptions)(A?.vault,i);if(C){rn(C);return}if(!Q){rn(null);return}let K=`${lt}\0${e}\0${t??""}`,Ie=j.current;if(Ie&&Ie.key===K){rn(Ie.mount);return}rn(null);let J=!0;return new On.PaymentAPI(lt).getVaultCapture(e,t).then(_e=>{if(!J)return;let zt=(0,l.resolveVaultMountOptions)(_e,i);zt?.verificationRequired&&!_e.html&&(j.current={key:K,mount:zt}),zt?rn(zt):ze("Failed to load the secure card form.")}).catch(_e=>{J&&ze(_e instanceof Error?_e.message:"Failed to load the secure card form.")}),()=>{J=!1}},[he,Q,re,e,A?.vault,lt,t,ze]);let Tn=(0,o.useRef)({onComplete:c,onError:p,updateError:ze,emitDecline:jn,resolvedAccount:ce,avsConfig:Ze,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:lt,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt,serverSideCardGateway:zr});Tn.current={onComplete:c,onError:p,updateError:ze,emitDecline:jn,resolvedAccount:ce,avsConfig:Ze,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:lt,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt,serverSideCardGateway:zr};let Ni=(0,o.useRef)(!1),js=(0,o.useCallback)(()=>{let i=Tn.current,C=i.resolvedAccount.email?.trim(),K=(0,l.isValidEmail)(C)?C:Kt.current.trim();if(!(0,l.isValidEmail)(K))return null;let Ie=i.resolvedAccount.firstName?.trim(),J=i.resolvedAccount.lastName?.trim(),_e=Dr.current.trim()||i.resolvedAccount.country?.trim()||"",zt=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.state,_e):!1,Pn=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_1,_e):!1,Pt=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.postal_code,_e):!1,wt=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.city,_e):!1,At=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_2,_e):!1,gr=Pn&&!zt&&Pt?(0,l.getStateFromPostalCode)(_e,(Et.current??"").trim()):null,mn=zt?Qt.current:gr;return{accountData:{userId:i.resolvedAccount.userId??"",email:K,...Ie?{firstName:Ie}:{},...J?{lastName:J}:{},...Pt&&Et.current?{zip:Et.current}:{},...wt&&br.current?{city:br.current}:{},...mn?{state:mn}:{},...Pn&&Ht.current?{addressLine1:Ht.current}:{},...At&&or.current?{addressLine2:or.current}:{},..._e?{country:_e}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,l.isAVSFieldVisible)(i.avsConfig.country,_e),postal_code:Pt,address_line_1:Pn,address_line_2:At,city:wt,state:zt}}:{}}},[]),Vs=(0,o.useRef)(d);Vs.current=d,(0,o.useEffect)(()=>{d||et!==ec||Tn.current.updateError(null)},[d,et]),(0,o.useEffect)(()=>{!he||!oe||oe.setSubmitGate?.(wr||d||To||ht)},[he,oe,wr,d,To,ht]),(0,o.useEffect)(()=>{if(!he||!oe)return;Ni.current=!1;let i=null,C=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,ue.current="idle",ie(null)},400)},K=oe.on("submitting",()=>{Un(!0),U.current&&clearTimeout(U.current),ue.current="validation-window",U.current=setTimeout(()=>{U.current=null,ue.current==="validation-window"&&(ue.current="processing")},Wd),ie("processing");let Pt=Tn.current;if(!Pt.sessionId||!Pt.nonce)return;let wt=js();if(!wt){Pt.updateError("Enter a valid email address."),ue.current="idle",ie(null);return}new On.PaymentAPI(Pt.baseUrl).patchAccountSnapshot(Pt.sessionId,Pt.nonce,wt,{telemetryMode:"best_effort"}).catch(At=>{if(!Hd(At))return;let gr=At instanceof Error?At.message:"Please check your billing address and try again.";Pt.updateError(gr),ue.current="idle",ie(null),Pt.onError?.(At instanceof l.FloPayError?At:new l.FloPayError(gr,"api_error"))})}),Ie=oe.on("complete",Pt=>{(0,Bn.markSessionRecentlyCompleted)(Pt.sessionId??Tn.current.sessionId),ue.current="terminal",It(!1),ie("success"),setTimeout(()=>{if(Ni.current)return;Ni.current=!0;let wt=Tn.current,At=(0,l.isAuthorizationOnlySession)(wt)||Pt.outcome==="authorized",gr=wt.serverSideCardGateway?{}:{paymentIntentId:Pt.intentId};Tn.current.onComplete?.(At?{status:"authorized",...gr,paymentId:Pt.paymentId??wt.paymentId,sessionId:Pt.sessionId??wt.sessionId,authorizationExpiresAt:Pt.authorizationExpiresAt??wt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...gr,checkoutMethod:"card"})},600)}),J=oe.on("decline",Pt=>{let wt=Tn.current,At=Pt.message??"Your payment was declined. Please try another card or contact your bank.";ue.current="terminal",It(!1),wt.updateError(At),ie("error");let gr=Pt.failureOutcome??(0,l.normalizeCheckoutFailureOutcome)(Pt.declineReason)??"authorization_declined";wt.emitDecline("card",At,{code:gr,declineCode:gr}),C()}),_e=oe.on("error",Pt=>{let wt=Tn.current,At=(0,l.buyerEmailRequiredPrompt)(Pt.vaultOutcome);if(At!==null){i&&(clearTimeout(i),i=null),ue.current="idle",It(!1),wt.updateError(At),ie(null),Ee(mn=>mn+1),wt.onError?.(new l.FloPayError(At,"api_error",{code:l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let gr=Pt.message??"There was a problem processing your payment. Please try again.";ue.current="terminal",It(!1),wt.updateError(gr),ie("error"),wt.onError?.(new l.FloPayError(gr,"api_error",{code:Pt.failureOutcome??"capture_failed"})),C()}),zt=oe.on("challenge_dismissed",()=>{U.current&&(clearTimeout(U.current),U.current=null),ue.current="processing",It(!0),ie(null)}),Pn=oe.on("blocked",()=>{if(Rr.current){Tn.current.updateError($d);return}if(!Vs.current){Un(!0);return}Li(),Tn.current.updateError(ec)});return()=>{i&&(clearTimeout(i),i=null),U.current&&(clearTimeout(U.current),U.current=null),ue.current="idle",It(!1),ie(null),K(),Ie(),J(),_e(),zt(),Pn()}},[he,oe,Li,js]);let Vn=!!St?.clientId,oa=Array.isArray(T),Ua=oa&&T.length>0,Ws=oa&&T.includes("paypal"),za=(0,o.useRef)(null);za.current===null&&(za.current=(0,l.hasMatchingStripePayPalReturn)());let Fo=za.current?"redirect":(0,Hn.resolveStripePayPalPresentation)(pt,Te,M.current()),{expressMethods:qa,paymentElementMethods:Ui}=(0,o.useMemo)(()=>(0,l.partitionStripeMethods)(T,{excludePaypal:Vn}),[T,Vn]),$s=Vn||!!Ot||Ws&&Fo==="redirect",Dc=(0,o.useMemo)(()=>$s?qa.filter(i=>i!=="paypal"):qa,[qa,$s]),Oc=(0,o.useMemo)(()=>{let i=[];return ye&&i.push("apple_pay"),pe&&i.push("google_pay"),i},[ye,pe]),Bo=oa?Dc:Oc,Lc=S&&Bo.length>0,Hs=ar?$t:V,ja=(0,o.useMemo)(()=>(0,l.filterStripeMethodsByCountryGate)(Ui,Hs,ae),[Ui,Hs,ae]),zi=(0,o.useMemo)(()=>({mode:"payment",amount:na,currency:Mo,paymentMethodCreation:"manual",appearance:Fs}),[na,Mo,Fs]),[Ks,Gs]=(0,o.useState)("loading"),[Ys,Xs]=(0,o.useState)("loading"),[Js,Zs]=(0,o.useState)("loading"),[Nc,qi]=(0,o.useState)(!1),[Qs,ji]=(0,o.useState)("loading"),[Vi,Uc]=(0,o.useState)();(0,o.useEffect)(()=>{Uc((0,$n.detectPayPalEnvironment)())},[]);let Va=Vi?.inAppBrowser,Wa=Vi?(0,Hn.resolvePayPalPresentationMode)(Vi,St?.approvalPresentation,Dt??(Ce?"subscription":"order")):"popup",el=me&&(Vn||(oa?Ws:Va===!1)),zc=pt.inAppBrowser&&M.current()==="blocked",tl=S&&Lc&&!zc,aa=(!z||!!be.waitForDataAttachment)&&el&&Vn,rl=Qs==="retrying"||Qs==="exhausted",ia=null;S&&(Ot?ia=As:Fo==="redirect"&&(ia=pn));let nl=(0,o.useMemo)(()=>({...it,presentationMode:Fo}),[it,Fo]),sa=!z&&el&&!!ia&&(!Vn||rl),Do=!z&&tl&&!!pn,la=!z&&S&&Ua&&ja.length>0&&!!pn,qc=aa&&!rl?Nc:sa&&cs(Ks),jc=Do&&cs(Ys),Vc=la&&Js!=="load_error",ol=i=>i==="loading"||i==="ready",al=aa||sa&&ol(Ks)||Do&&ol(Ys)||la&&Js!=="load_error",$a=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!$a.current){if(!S&&!me){$a.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&&me&&!Vn){$a.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(Va!==void 0&&!z&&!ir&&!al){$a.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,me,Vn,Va,z,ir,al,p,ze]);let il=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(il.current||!Ua)return;let i=[];ye!==!0&&i.push("showApplePay"),pe!==!0&&i.push("showGooglePay"),i.length!==0&&(il.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.`))},[Ua,ye,pe]);let sl=(0,o.useCallback)((i,C,K)=>be.applyInlineSessionPatch?be.applyInlineSessionPatch(i).then(Ie=>({error:null,sessionId:Ie.sessionId||e,nonce:Ie.session?.clientSecret||t})).catch(Ie=>{let J=(0,l.normalizeBeforeButtonClickError)(C,Ie);return K?.abandoned?.()||(ze(J.message),p?.(J)),{error:J,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[be.applyInlineSessionPatch,t,p,e,ze]),Mn=(0,o.useCallback)(async(i,C)=>{if(i!=="card"&&z&&await be.waitForDataAttachment?.(),!Oe)return{proceed:!0};try{let K=await Oe({method:i,sessionId:e||void 0,createSession:be.inlineSessionDraft});if(K===!1)return{proceed:!1};if(K&&typeof K=="object"){K.account&&rt(J=>({...J??{},...K.account}));let Ie=await sl(K,i,C);return Ie.error?{proceed:!1,accountPatch:K.account}:{proceed:!0,accountPatch:K.account,sessionId:Ie.sessionId,nonce:Ie.nonce}}return{proceed:!0}}catch(K){if(!C?.abandoned?.()){let Ie=(0,l.normalizeBeforeButtonClickError)(i,K);ze(Ie.message),p?.(Ie)}return{proceed:!1}}},[sl,be.inlineSessionDraft,be.waitForDataAttachment,z,Oe,p,e,ze]),ll=(0,o.useCallback)(async(i,C)=>{if(st.current)return;st.current=!0,Nt(!0),ie("processing"),ze(null);let K=C?.sessionId??e,Ie=C?.nonce??t,J=ts(ce,C?.accountPatch),_e=C?.completionPaymentMethodId??ha(i),zt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,Pn=Xd(i),Pt=C?.presentationMode?pi(Er(xe),{...it,presentationMode:C.presentationMode}):void 0,wt=()=>{_t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Pn}),Pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Dn,requestCategory:"process_payment"})};try{let At=new On.PaymentAPI(lt),mn=C?.settledProcessResponse??await At.processPayment(J.userId??"",{sessionId:K,nonce:Ie,paymentMethodCategory:C?.paymentMethodCategory??Zd(i),tokenizedData:zt,accountData:{...C?.accountPatch,userId:J.userId??"",email:J.email??"",firstName:J.firstName||void 0,lastName:J.lastName||void 0,...(0,l.buildProcessPaymentAvsAccount)({avsConfig:Ze,country:Dr.current,zip:Et.current,city:br.current,state:Qt.current,addressLine1:Ht.current,addressLine2:or.current})},...(0,l.buildCheckoutProcessMetadata)({chv:G,avsCheck:ot,checkoutType:Me,checkoutLayout:tt,avsConfig:Ze,country:Dr.current})}),Xa=async xr=>{let Co=(0,l.isAuthorizationOnlySession)(A)||xr?.status==="authorized";(0,Bn.markSessionRecentlyCompleted)(K),Pt?.terminal({outcome:"payment_succeeded",...Dn}),ie("success"),g(null),await new Promise(ya=>setTimeout(ya,600));let Wn;typeof xr?.paymentId=="string"?Wn=xr.paymentId:A?.paymentId&&(Wn=A.paymentId);let bo;typeof xr?.authorizationExpiresAt=="string"?bo=xr.authorizationExpiresAt:A?.authorizationExpiresAt&&(bo=A.authorizationExpiresAt),c?.(Co?{status:"authorized",...Wn===void 0?{}:{paymentId:Wn},sessionId:typeof xr?.sessionId=="string"?xr.sessionId:K,...bo===void 0?{}:{authorizationExpiresAt:bo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:_e,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:_e,checkoutMethod:i.isPaypal?"paypal":"card"})};if(mn.ok){await Xa(mn.status===204?null:await mn.json().catch(()=>null));return}let hr=await mn.json().catch(()=>null);if(hr?.type==="paypal_redirect_required"){let xr=hr.threeDSecureToken,Co=hr.paymentMethodId||i.id||"";if(!xe||!xr){ie("error"),ze("PayPal authorization required but no token provided.");return}try{let Wn=Ot?.getRawProvider();if(!Wn){ze("PayPal is not available.");return}let bo={return_url:window.location.href};Co&&(bo.payment_method=Co);let{error:ya}=await Wn.confirmPayment({clientSecret:xr,confirmParams:bo,redirect:"if_required"});if(ya){ie("error");let Cl=ya.message??"PayPal payment failed.";ze(Cl),jn("paypal",Cl,{code:ya.code})}}catch(Wn){ie("error"),ze(Wn instanceof Error?Wn.message:"PayPal authorization failed.")}return}if(hr?.type==="paypal_direct_required"){let xr=hr.orderId;if(!xr){ie("error"),ze("PayPal retry required but no order id provided.");return}let Co=X.current?.attempts??0;if(Co>=2){ie("error"),ze("PayPal payment could not be completed after multiple attempts."),jn("paypal","paypal_direct_required retry limit exceeded");return}qi(!1),ji("loading"),g({orderId:xr,attempts:Co+1}),ie(null);return}if(mn.headers.get(Ld)===Nd){let xr=await Ud(At,K,Ie);if(xr!==void 0){await Xa(xr);return}}(0,l.classifyPaymentRejection)(mn.status,hr)?Pt?.terminal({outcome:"payment_declined",...Dn,terminalReason:"provider_declined"}):wt(),ie("error");let vl=hr?.message??"Payment failed. Please try again.";ze(vl),jn(i.isPaypal?"paypal":"card",vl,{code:hr?.code??hr?.gatewayErrorCode,declineCode:hr?.declineCode??hr?.gatewayDeclineReason}),await new Promise(xr=>setTimeout(xr,400))}catch(At){cc(At)||wt(),ie("error"),ze(At instanceof Error?At.message:"An unexpected error occurred"),await new Promise(gr=>setTimeout(gr,400))}finally{Nt(!1),ie(null),st.current=!1}},[lt,e,t,ce,Ze,ot,Me,tt,G,xe,Ot,A,c,ze,jn,_t,it]),on=(0,o.useCallback)((i,C)=>{k&&!C?.settledProcessResponse?k(i):ll(i,C)},[k,ll]),ca=`${sc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(ca);if(!i)return;let C;try{C=JSON.parse(i)}catch{ur(ca);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>lc||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!Bo.includes(C.paymentMethodType)){ur(ca);return}ur(ca),on({id:C.paymentMethodId,type:"card",threeDSecureActionResultTokenId:C.providerIntentId,gateway:"stripe",paymentMethodType:C.paymentMethodType},{...C.accountPatch?{accountPatch:C.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[on,t,e,ca,Bo]);let cl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||cl.current)return;let[i,C,K]=(0,l.readStripeRedirectParams)();if(!i||!C||za.current||!xe)return;let Ie=xe.getRawProvider();if(!Ie)return;let J=wt=>{let At=localStorage.getItem(wt);if(!At)return null;try{return JSON.parse(At)}catch{return ur(wt),null}},_e=J(Gn)??J(Jl),zt;if(_e?.clientSecret){if(_e.clientSecret!==C)return;zt={..._e.accountPatch?{accountPatch:_e.accountPatch}:{},..._e.sessionId?{sessionId:_e.sessionId}:{},..._e.nonce?{nonce:_e.nonce}:{}}}else if(_e?.sessionId&&_e.sessionId!==e)return;cl.current=!0,ur(Gn),ur(Jl),window.history.replaceState({},"",(0,l.stripeRedirectReturnUrl)());let Pn=_e?.paymentMethodType??_e?.tokenType??"card",Pt="card";(async()=>{if(K==="failed"){let hr="Payment was declined. Please try again.";ze(hr),jn(Pt,hr);return}let{paymentIntent:wt,error:At}=await Ie.retrievePaymentIntent(C);if(At){let hr=At.message??"Failed to retrieve payment status.";ze(hr),jn(Pt,hr,{code:At.code});return}let gr=wt?.status,mn=ga(gr);if(!wt||!mn){let hr=gr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ze(hr),jn(Pt,hr,{code:gr??"missing_payment_intent"});return}let Xa=typeof wt.payment_method=="string"?wt.payment_method:wt.payment_method?.id;on({id:Xa??_e?.paymentMethodId??_e?.tokenId??wt.id,type:"card",threeDSecureActionResultTokenId:wt.id,gateway:_e?.gateway??"stripe",paymentMethodType:Pn},zt)})()},[e,on,xe,ze,jn]);let Wi=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(he||xe!==null))return(0,u.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let da=Re==="buttons",an=fr?.variables,Wc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),$i=an?.colorBackground,$c=$i&&!Wc.has($i)?$i:void 0,ua=le.cardInputBorder??(da?"#e5e7eb":"#A4A4FF"),dl=an?.colorDanger??"#dc2626",tr=i=>qr[i]&&(po[i]||er),Ha=To&&(qn||er),hn=i=>i?dl:ua,Ka=(Lt.malformed||Lt.empty)&&(Zn||er),Hc=hn(Ka),Hi=le.cardFormContainer?.backgroundColor??$c??(da?"white":"#EDEDFF"),Oo=le.cardInputBackground??an?.colorBackground??"white",Ki=Uo(Le),ul=Uo(de),Lo=le.nameInput,pl=le.cardInputFontSize??ru(Lo?.fontSize)??an?.fontSizeBase??"16px",ml=typeof Lo?.fontFamily=="string"?Lo.fontFamily:an?.fontFamily??"Poppins, sans-serif",yl=(0,l.toCssWeight)(Lo?.fontWeight)??400,Kc=le.cardInputColor??(typeof Lo?.color=="string"?Lo.color:void 0)??an?.colorText??"#262833",Gc=le.cardInputPlaceholderColor??"#9ca3af",cr=an?.borderRadius??"8px",Po=an?.borderRadius??le.cardButton?.borderRadius??cr,vo=an?.colorPrimary??"#4A49FF",Yc=an?.colorPrimaryHover??(0,l.darkenHex)(vo,.12),Gi=an?.colorText??"#262833",Yi={fontSize:pl,fontFamily:ml,fontWeight:yl,color:Kc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},pa={marginTop:"0.375rem",...Yi,fontSize:"0.75rem",lineHeight:1.4,color:dl},Xc={"--flopay-input-placeholder-color":Gc,"--flopay-input-font-size":pl,"--flopay-input-font-family":ml,"--flopay-input-font-weight":String(yl)},ma=le.cardFormContainer??{},Xi=ma.padding??(da?"0":"1rem"),Ji=ma.borderRadius??cr,Jc=oe&&dn?(0,u.jsx)(go,{capture:oe,html:dn.html,messageToken:dn.messageToken,expectedOrigin:dn.expectedOrigin,verificationRequired:dn.verificationRequired,theme:_o,submitLabel:Z,onReady:()=>{if(!_n&&!Ze||typeof document>"u")return;let i=()=>{let K=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(K){Or.current=!0;try{K.focus()}finally{Or.current=!1}}};gn.current||i()},onError:i=>{i&&dn.verificationRequired&&ue.current==="idle"&&(ro.current=!0),ze(i)},onValidation:i=>{let C=ue.current;(C==="idle"||C==="validation-window")&&(ze(i),i&&ue.current==="validation-window"&&(U.current&&(clearTimeout(U.current),U.current=null),ue.current="idle",ie(null)))}},jr):(0,u.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),fl=(0,u.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&In()},style:{backgroundColor:Hi,borderRadius:Ji,...ma,padding:Xi,...Xc,display:"flex",flexDirection:"column"},children:[(0,u.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${se.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),da&&ho&&(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:he?-2:0},children:[(0,u.jsxs)("button",{type:"button",onClick:be,style:{display:"inline-flex",alignItems:"center",gap:Hi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:le.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...le.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...le.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(qo,{content:Le})]}),dl?(0,u.jsx)("div",{style:{flex:1}}):(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:le.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...le.title},children:(0,u.jsx)(fa,{content:de})})]}),!da&&!dl&&(0,u.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ki,order:he?-3:0,...le.title},children:(0,u.jsx)(fa,{content:de})}),he&&W&&(0,u.jsx)("div",{style:{order:-2,width:"100%"},children:W}),he&&_n&&(0,u.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,u.jsx)("div",{style:{backgroundColor:Oo,border:`1px solid ${gn($a)}`,borderRadius:cr,padding:"10px"},children:(0,u.jsx)("input",{ref:te,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Zt,onChange:i=>{Ut("email"),Kt.current=i.target.value,Cr(i.target.value)},onPointerDown:()=>Ut("email"),onKeyDown:()=>Ut("email"),onBlur:()=>{Qr("email")&&Qn(!0),To||Oi()},disabled:Fe,required:!0,"aria-invalid":$a||void 0,"aria-describedby":$a?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Gi}})}),$a&&(0,u.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:pa,children:Ai.empty?"Email address is required":"Enter a valid email address"})]}),Ze&&(0,u.jsx)("div",{style:{order:he?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=$t,C=(J=!1)=>({backgroundColor:Oo,border:`1px solid ${gn(J)}`,borderRadius:cr,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Gi}),Ie=(0,l.getStateOptions)(i);return(0,u.jsxs)(u.Fragment,{children:[(0,l.isAVSFieldVisible)(Ze.address_line_1,i)&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)("div",{style:C(tr("line1")),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:nr,onChange:J=>{Ut("line1"),_r.current.addressLine1=!0,Ht.current=J.target.value,Jr(J.target.value)},onPointerDown:()=>Ut("line1"),onKeyDown:()=>Ut("line1"),onBlur:()=>en("line1"),disabled:Fe,required:!0,"aria-invalid":tr("line1")||void 0,"aria-describedby":tr("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:K()})}),tr("line1")&&(0,u.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:pa,children:"Street address is required"})]}),(0,l.isAVSFieldVisible)(Ze.address_line_2,i)&&(0,u.jsx)("div",{style:C(),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Mt,onChange:J=>{_r.current.addressLine2=!0,or.current=J.target.value,Ln(J.target.value)},disabled:Fe,"data-testid":"flopay-address-line2",style:K()})}),((0,l.isAVSFieldVisible)(Ze.city,i)||(0,l.isAVSFieldVisible)(Ze.state,i))&&(0,u.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Ze.city,i)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Oo,borderTop:`1px solid ${gn(tr("city"))}`,borderRight:`1px solid ${gn(tr("city"))}`,borderBottom:`1px solid ${gn(tr("city"))}`,borderLeft:`1px solid ${gn(tr("city"))}`,padding:"10px",borderTopLeftRadius:cr,borderBottomLeftRadius:cr,...(0,l.isAVSFieldVisible)(Ze.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:cr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Jt,onChange:J=>{Ut("city"),_r.current.city=!0,br.current=J.target.value,yn(J.target.value)},onPointerDown:()=>Ut("city"),onKeyDown:()=>Ut("city"),onBlur:()=>en("city"),disabled:Fe,required:!0,"aria-invalid":tr("city")||void 0,"aria-describedby":tr("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:K()})}),(0,l.isAVSFieldVisible)(Ze.state,i)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Oo,borderTop:`1px solid ${gn(tr("state"))}`,borderRight:`1px solid ${gn(tr("state"))}`,borderBottom:`1px solid ${gn(tr("state"))}`,borderLeft:`1px solid ${gn(tr("state"))}`,padding:"10px",borderTopRightRadius:cr,borderBottomRightRadius:cr,...(0,l.isAVSFieldVisible)(Ze.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${gn(tr("state")||tr("city"))}`}:{borderRadius:cr}},children:Ie?(0,u.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:$r,onChange:J=>{Ut("state"),_r.current.state=!0,Qt.current=J.target.value,Hr(J.target.value)},onPointerDown:()=>Ut("state"),onKeyDown:()=>Ut("state"),onBlur:()=>en("state"),disabled:Fe,autoComplete:"billing address-level1",required:!0,"aria-invalid":tr("state")||void 0,"aria-describedby":tr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...K(),cursor:"pointer"},children:[(0,u.jsx)("option",{value:"",children:(0,l.getStateLabel)(i)}),Ie.map(J=>(0,u.jsx)("option",{value:J.code,children:J.name},J.code))]}):(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,l.getStateLabel)(i),autoComplete:"billing address-level1",value:$r,onChange:J=>{Ut("state"),_r.current.state=!0,Qt.current=J.target.value,Hr(J.target.value)},onPointerDown:()=>Ut("state"),onKeyDown:()=>Ut("state"),onBlur:()=>en("state"),disabled:Fe,required:!0,"aria-invalid":tr("state")||void 0,"aria-describedby":tr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:K()})})]}),tr("city")&&(0,u.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:pa,children:"City is required"}),tr("state")&&(0,u.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:pa,children:[(0,l.getStateLabel)(i)," is required"]}),((0,l.isAVSFieldVisible)(Ze.country,i)||(0,l.isAVSFieldVisible)(Ze.postal_code,i))&&(0,u.jsxs)("div",{style:{display:"flex",flexDirection:$==="column"?"column":"row",gap:$==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Ze.country,i)&&(0,u.jsx)("div",{style:{flex:$==="row"?1:void 0,backgroundColor:Oo,borderTop:`1px solid ${ua}`,borderRight:`1px solid ${ua}`,borderBottom:`1px solid ${ua}`,borderLeft:`1px solid ${ua}`,padding:"10px",...$==="row"&&(0,l.isAVSFieldVisible)(Ze.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:cr,borderBottomLeftRadius:cr,borderRight:"none"}:{borderRadius:cr}},children:(0,u.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:$t,onChange:J=>{_r.current.country=!0,Dr.current=J.target.value,Tt(J.target.value),ft?.(J.target.value),Qt.current="",Hr("")},disabled:Fe,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:[$t===""?(0,u.jsx)("option",{value:"",children:"Select country"}):null,l.COUNTRY_OPTIONS.map(J=>(0,u.jsxs)("option",{value:J.code,children:[J.flag," ",J.name]},J.code))]})}),(0,l.isAVSFieldVisible)(Ze.postal_code,i)&&(0,u.jsx)("div",{style:{flex:$==="row"?1:void 0,backgroundColor:Oo,border:`1px solid ${$c}`,padding:"10px",...$==="row"&&(0,l.isAVSFieldVisible)(Ze.country,i)?{borderRadius:"0",borderTopRightRadius:cr,borderBottomRightRadius:cr}:{borderRadius:cr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,l.getPostalCodeLabel)($t),autoComplete:"billing postal-code",value:Wr,onChange:J=>{Ut("zip"),_r.current.zip=!0,Et.current=J.target.value,Nr(J.target.value),Ne?.(J.target.value)},onPointerDown:()=>Ut("zip"),onKeyDown:()=>Ut("zip"),onBlur:()=>{Qr("zip")&&zn(!0)},disabled:Fe,required:Lt.required,"aria-invalid":Ha||void 0,"aria-describedby":Ha?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),Ha&&(0,u.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:pa,children:Lt.empty?`${(0,l.getPostalCodeLabel)(i)} is required`:Zd(i)})]})})()}),he&&Xc,rt&&(0,u.jsx)(Yo,{margin:"0.75rem 0",styleOverride:le.errorBanner,children:rt})]}),Ka={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},fl=i=>O?!me||!Vn?(0,u.jsx)("pre",{"data-testid":i,style:Ka,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":i,style:Ka,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${me}`,` directPaypalConfigured=${Vn}`,` inAppBrowserDetected=${String(ja)}`,` shouldRenderDirectPayPal=${aa}`,` shouldRenderStripePayPal=${sa}`,` hasPaypalStripeInstance=${!!xs}`].join(`
39
- `)}):null,gl=i=>O?!S||!un?(0,u.jsx)("pre",{"data-testid":i,style:Ka,children:"FloPay/Stripe-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":i,style:Ka,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${S}`,` currency=${mr}`,` amountInCents=${na}`,` enabledPaymentMethods: ${JSON.stringify(T??[])}`,` enabledPaymentMethodsProvided=${oa}`,` hasEnabledMethods=${Na}`,` expressMethods: ${JSON.stringify(za)}`,` walletExpressMethods: ${JSON.stringify(Bo)}`,` paymentElementMethods: ${JSON.stringify(Ni)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(qa)}`,` hasStripeInstance=${!!un}`,` shouldRenderWallets=${Do}`,` shouldRenderPaymentElement=${la}`].join(`
40
- `)}):null,hl=mt==="apm-expanding"||mt==="apm-form"||mt==="apm-collapsing",No;mt==="apm-expanding"?No=ec:mt==="apm-collapsing"&&(No=tc);let Ga=lr?dc(Ui,lr,Ge):null;if(we==="buttons"){let i=mt==="buttons"||mt==="expanding"||mt==="apm-expanding",C=mt==="expanding"||mt==="card"||mt==="collapsing",K=Je===void 0?{boxSizing:"border-box",height:Qo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ie;mt==="expanding"||mt==="apm-expanding"?Ie=Gd:(mt==="collapsing"||mt==="apm-collapsing")&&(Ie=Kd);let J;return mt==="expanding"?J=ec:mt==="collapsing"&&(J=tc),(0,u.jsxs)("form",{onSubmit:Vi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(ea,{}),ke&&(0,u.jsx)(an,{status:ke,errorMessage:rt,authorized:Tr}),(0,u.jsxs)("div",{style:{display:"grid"},children:[(0,u.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Ie?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Ie?Xd:{},...Ie?{animation:Ie,pointerEvents:"none"}:{}},children:[fl("flopay-direct-paypal-gate-debug"),gl("flopay-stripe-gate-debug"),aa&&St&&(0,u.jsxs)(u.Fragment,{children:[y&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(va.Provider,{value:x,children:(0,u.jsx)(ba,{sessionId:e,nonce:t,billingApiUrl:E,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:He,clientId:St.clientId,environment:St.environment,currency:mr.toUpperCase(),isSubscription:ve,providerObjectType:Dt,approvalPresentation:Va==="popup"?void 0:Va,onTokenizedBody:nn,onComplete:c,onErrorChange:Ue,onDecline:m,onCancel:h,onTechnicalFailure:Ao,onButtonClick:H,runBeforeButtonClick:Mn,isProcessing:Fe,onLoadStateChange:zi,onInitializationStateChange:qi,session:We,existingOrderId:y?.orderId,debug:O},y?.orderId??"fresh")})]}),sa&&(0,u.jsx)(dr.Elements,{stripe:ia,options:Bs,children:(0,u.jsx)(nc,{sessionId:e,nonce:t,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:He,billingApiUrl:E,onTokenizedBody:nn,onErrorChange:Ue,isProcessing:Fe,onButtonClick:H,onDecline:m,onTechnicalFailure:Ao,runBeforeButtonClick:Mn,onLoadStateChange:Ks,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:rl,presentationMode:Fo})}),Do?(0,u.jsx)(dr.Elements,{stripe:un,options:Fs,children:(0,u.jsx)(oc,{sessionId:e,nonce:t,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:He,billingApiUrl:E,intentKind:at>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:nn,onErrorChange:Ue,onButtonClick:H,onDecline:m,onTechnicalFailure:Ao,runBeforeButtonClick:Mn,onLoadStateChange:Ys,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:it})}):null,!Do&&el?(0,u.jsx)("div",{style:{height:Qo,borderRadius:Po,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,la&&(0,u.jsx)(ac,{sessionId:e,nonce:t,email:ce.email,billingName:[ce.firstName,ce.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:He,billingApiUrl:E,paymentElementMethods:qa,stripeInstance:un,paymentElementBaseOptions:Ui,futureUseSession:Ge,onTokenizedBody:nn,onErrorChange:Ue,onButtonClick:H,onDecline:m,runBeforeButtonClick:Mn,onLoadStateChange:Js,isProcessing:Fe,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:le.submitButton,onExpandApm:gt,expandedApmMethod:lr,themeId:dt,buttonAppearance:{backgroundColor:le.cardButton?.backgroundColor,borderColor:le.cardInputBorder,textColor:le.cardButton?.color,borderRadius:Po}}),he&&(0,u.jsx)("button",{type:"button",onClick:async()=>{Fe||!(await Mn("card")).proceed||(H?.("card"),oe())},disabled:Fe,style:{width:"100%",...K,...le.cardButton,...vs({themeBundle:qt,resolvedPrimaryColor:vo,resolvedBorderRadius:cr,submitButtonStyle:le.submitButton,explicitPrimaryColor:on?.colorPrimary}),fontSize:le.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Fe?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Fe?.6:1},onMouseEnter:_e=>{!Fe&&(qt||on?.colorPrimary)&&(_e.currentTarget.style.backgroundColor=Gc)},onMouseLeave:_e=>{(qt||on?.colorPrimary)&&(_e.currentTarget.style.backgroundColor=vo)},onMouseDown:_e=>{_e.currentTarget.style.transform="scale(0.985)"},onMouseUp:_e=>{_e.currentTarget.style.transform="scale(1)"},children:(0,u.jsx)(zo,{content:Je})}),rt&&mt==="buttons"&&(0,u.jsx)(Yo,{margin:"0.25rem 0",styleOverride:le.errorBanner,children:rt})]}),he&&C&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...J?{animation:J}:{},...mt==="collapsing"?{pointerEvents:"none"}:{}},children:yl}),S&&hl&&lr&&Ga&&un&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...No?{animation:No}:{},...mt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:$i,borderRadius:Xi,...ma,padding:Yi},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Yt,style:{display:"inline-flex",alignItems:"center",gap:Hi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:le.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...le.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...le.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(qo,{content:Le})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:le.titleFontSize??"1.05rem",color:Ki,paddingRight:80,...le.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(lr)}`})]}),(0,u.jsx)(dr.Elements,{stripe:un,options:Ga,children:(0,u.jsx)(gs,{method:lr,sessionId:e,nonce:t,email:ce.email,billingName:[ce.firstName,ce.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:He,billingApiUrl:E,onTokenizedBody:nn,onErrorChange:Ue,onDecline:m,onCancel:Yt,runBeforeButtonClick:Mn,onButtonClick:H,isProcessing:Fe,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:le.submitButton,errorText:rt})},lr)]})})]})]})}return hl&&lr&&Ga&&un&&S?(0,u.jsxs)("form",{onSubmit:Vi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(ea,{}),ke&&(0,u.jsx)(an,{status:ke,errorMessage:rt,authorized:Tr}),(0,u.jsx)("div",{style:{...No?{animation:No}:{},...mt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:$i,borderRadius:Xi,...ma,padding:Yi},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Yt,style:{display:"inline-flex",alignItems:"center",gap:Hi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:le.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...le.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...le.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(qo,{content:Le})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:le.titleFontSize??"1.05rem",color:Ki,paddingRight:80,...le.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(lr)}`})]}),(0,u.jsx)(dr.Elements,{stripe:un,options:Ga,children:(0,u.jsx)(gs,{method:lr,sessionId:e,nonce:t,email:ce.email,billingName:[ce.firstName,ce.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:He,billingApiUrl:E,onTokenizedBody:nn,onErrorChange:Ue,onDecline:m,onCancel:Yt,runBeforeButtonClick:Mn,onButtonClick:H,isProcessing:Fe,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:le.submitButton,errorText:rt})},lr)]})})]}):(0,u.jsxs)("form",{onSubmit:Vi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(ea,{}),ke&&(0,u.jsx)(an,{status:ke,errorMessage:rt,authorized:Tr}),(0,u.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[fl("flopay-direct-paypal-gate-debug-default"),gl("flopay-stripe-gate-debug-default"),aa&&St&&(0,u.jsxs)(u.Fragment,{children:[y&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(va.Provider,{value:x,children:(0,u.jsx)(ba,{sessionId:e,nonce:t,billingApiUrl:E,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:He,clientId:St.clientId,environment:St.environment,currency:mr.toUpperCase(),isSubscription:ve,providerObjectType:Dt,approvalPresentation:Va==="popup"?void 0:Va,onTokenizedBody:nn,onComplete:c,onErrorChange:Ue,onDecline:m,onCancel:h,onTechnicalFailure:Ao,onButtonClick:H,runBeforeButtonClick:Mn,isProcessing:Fe,onLoadStateChange:zi,onInitializationStateChange:qi,session:We,existingOrderId:y?.orderId,debug:O},y?.orderId??"fresh")})]}),sa&&(0,u.jsx)(dr.Elements,{stripe:ia,options:Bs,children:(0,u.jsx)(nc,{sessionId:e,nonce:t,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:He,billingApiUrl:E,onTokenizedBody:nn,onErrorChange:Ue,isProcessing:Fe,onButtonClick:H,onDecline:m,onTechnicalFailure:Ao,runBeforeButtonClick:Mn,onLoadStateChange:Ks,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:rl,presentationMode:Fo})}),Do&&(0,u.jsx)(dr.Elements,{stripe:un,options:Fs,children:(0,u.jsx)(oc,{sessionId:e,nonce:t,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:He,billingApiUrl:E,intentKind:at>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:nn,onErrorChange:Ue,onButtonClick:H,onDecline:m,onTechnicalFailure:Ao,runBeforeButtonClick:Mn,onLoadStateChange:Ys,placeholderBorderRadius:Po,popupCapabilityOwner:x,externalTelemetryContext:it})}),la&&(0,u.jsx)(ac,{sessionId:e,nonce:t,email:ce.email,billingName:[ce.firstName,ce.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:E,paymentElementMethods:qa,stripeInstance:un,paymentElementBaseOptions:Ui,futureUseSession:Ge,onTokenizedBody:nn,onErrorChange:Ue,onButtonClick:H,onDecline:m,runBeforeButtonClick:Mn,onLoadStateChange:Js,isProcessing:Fe,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:le.submitButton,themeId:dt,onExpandApm:gt,expandedApmMethod:lr,buttonAppearance:{backgroundColor:le.cardButton?.backgroundColor,borderColor:le.cardInputBorder,textColor:le.cardButton?.color,borderRadius:Po}})]}),he&&(qc||zc||jc)&&(0,u.jsx)(hi,{label:"or pay with card"}),he&&yl]})}var F=require("react/jsx-runtime"),ta=44,Es="flopay_checkout_saved_payment_resume",Ei=new Map,Ri=new Map;function uc(e,t){t.settled&&t.consumers===0&&Ei.get(e)===t&&Ei.delete(e)}function au(e,t,r){let n=Ri.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};Ri.set(e,s);let c=()=>{Ri.get(e)===s&&Ri.delete(e)};return a.then(c,c),a}function Fa(e){return new Promise(t=>setTimeout(t,e))}function ki(e,t,r){let n=ai({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:De.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Ba(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function bs(e,t,r,n,a,s){let c=ki(e,t,r);c.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Ba(c)}function pc(e,t,r,n){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:t,...n===void 0?{}:{attempt:n},statusClass:"2xx"})}function mc(e,t,r,n,a){let s=(0,De.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:a,statusClass:s.statusClass}),t instanceof De.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof De.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):s.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...s,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function Ss(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,De.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var iu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function su(e){return new co.FloPay(iu,{publishableKey:"provider_unavailable",...e})}async function ws(e,t){let{publishableKey:r,paypalPublishableKey:n}=is(e);return{...await ss({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Is(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function lu(){if(!Is())return null;try{let e=window.sessionStorage.getItem(Es);return e?JSON.parse(e):null}catch{return null}}function yc(e){if(Is())try{window.sessionStorage.setItem(Es,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Rs(){if(Is())try{window.sessionStorage.removeItem(Es)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function cu(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],r=!1;for(let n of t)e.searchParams.has(n)&&(e.searchParams.delete(n),r=!0);r&&window.history.replaceState(window.history.state,"",e.toString())}function fc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function ks(e,t){return(0,De.resolveCheckoutLogLayout)(!!e,t)}function du(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function gc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function uu(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function Ii({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:c,loading:p,error:m,onComplete:h,onError:k,onInstrument:w,onDecline:I,onCancel:G,onCountryChange:_,onZipChange:Z,showPayPal:A=!0,showStripe:f=!0,walletPresentation:P="auto",enabledPaymentMethods:me,showApplePay:S=!0,showGooglePay:Te=!0,debug:T=!1,layout:ae,theme:ye,buttonsTheme:pe,buttonsStyles:we,cardButtonContent:dt,cardBackButtonContent:Ke,cardTitleContent:B,showSecurityFooter:kt,onButtonClick:Je,onBeforeButtonClick:Le,enableAVS:de,cardFieldOrder:ee,cardPreFormSlot:H,avsLayout:Oe,submitLabel:nt,className:qe,initialErrorMessage:Y=null,initialPayPalOrderId:W,children:$,checkoutMode:j,confirmLabel:Ve,renderConfirmButton:Be,onSessionCompleted:fe}){let D=(0,De.resolveBillingApiUrl)(n),ge=(0,v.useMemo)(()=>(0,De.resolveTheme)(ye),[ye]),ft=s??ge?.appearance,Ne=r?"embedded_checkout":"standard_checkout",ot=ks($,ae),[Me,et]=(0,v.useState)(null),[at,mr]=(0,v.useState)(null),Ft=(0,v.useRef)(null),St=(0,v.useRef)(null),ve=(0,v.useRef)(0),[M,bt]=(0,v.useState)(null),ut=(0,v.useRef)(null),[O,xe]=(0,v.useState)(null),Ot=(0,v.useMemo)(()=>r?(0,vt.serializeCreateParams)(r):"",[r]),Ce=r?`create:${Ot}`:`session:${e??""}`,_t=gc(O),b=(0,v.useRef)(new Set),x=(0,v.useRef)(Ce),Ae=(0,v.useRef)(Ce);wo(()=>{Ae.current=Ce,x.current!==Ce&&(x.current=Ce,b.current.clear())},[Ce]);let Re=(0,v.useCallback)(z=>{if(Ae.current===Ce){if(ns.FLO_INSTRUMENT_ONCE_NAMES.has(z.name)){if(b.current.has(z.name))return;b.current.add(z.name)}(0,Ye.invokeMerchantCallback)(()=>w?.(z))}},[Ce,w]),pt=Go(Re,Ce),it=(0,v.useRef)(!1),We=(0,v.useCallback)(z=>{if(it.current)return;let q=z.gateway||!_t?z:{...z,gateway:_t};Re(q)},[Re,_t]);(0,v.useEffect)(()=>{pt({class:"lifecycle",name:"checkout.mount"})},[pt]);let[Ge,Dt]=(0,v.useState)(e??""),d=e??Ge,L=r?"":d,[V,se]=(0,v.useState)(!0),[E,U]=(0,v.useState)(null),[Nt,Br]=(0,v.useState)(0),[rr,$t]=(0,v.useState)("full"),[Tt,Wr]=(0,v.useState)(!1),[Nr,nr]=(0,v.useState)(Y),[Jr,Mt]=(0,v.useState)(null),[Ln,Jt]=(0,v.useState)(null),[yn,$r]=(0,v.useState)(!1),[Hr,Zt]=(0,v.useState)(void 0),[Cr,Zr]=(0,v.useState)(""),[tt,Et]=(0,v.useState)(!1),[Dr,Ht]=(0,v.useState)(!1),[or,br]=(0,v.useState)(!1),Qt=(0,v.useRef)(null),Kt=(0,v.useRef)(0),_r=(0,v.useRef)(void 0),[Ze,ar]=(0,v.useState)("loading"),[Tr,Jn]=(0,v.useState)(0),Ur=(0,v.useRef)(!1),zr=(0,v.useRef)(!1),Nn=(0,v.useRef)(!1),ln=(0,v.useRef)(null),ir=(0,v.useRef)(null),he=(0,v.useMemo)(()=>({checkoutMode:j??rr,layout:du($,ae)}),[j,$,rr,ae]),Sr=(0,v.useRef)(h);Sr.current=h;let Kr=(0,v.useRef)(k);Kr.current=k;let re=(0,v.useRef)(I);re.current=I;let Bt=(0,v.useCallback)(z=>li(ln,async q=>{try{return await z(q)}catch(oe){throw q.aborted?Xo(oe):oe}}),[]);(0,v.useEffect)(()=>()=>{ln.current?.abort(),ln.current=null},[]);let Q=(0,v.useCallback)((z,q)=>{Ft.current=z,mr(z),ut.current=q,bt(q)},[]),Gt=(0,v.useCallback)(()=>{let z=St.current;z&&(St.current=null,z.destroy())},[]);(0,v.useEffect)(()=>{Er(at)?.setCheckoutContext(he),M&&M!==at&&Er(M)?.setCheckoutContext(he)},[at,M,he]);let sr=(0,v.useRef)(fe);sr.current=fe;let Pe=(0,v.useCallback)(z=>{ar(z),!(z!=="exhausted"||Nn.current)&&(Nn.current=!0,Kr.current?.(new De.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Wt=(0,v.useCallback)(()=>{ar("retrying"),Jn(z=>z+1)},[]);(0,v.useEffect)(()=>{ar("loading"),Jn(0),Nn.current=!1},[d]),(0,v.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:De.SDK_VERSION,checkout_type:Ne,checkout_layout:ot,billing_api_url:D})},[ot,Ne,D]);let ne=(0,v.useMemo)(()=>r?(0,vt.serializeCreateParams)(r,!0):"",[r]),Lt=(0,v.useMemo)(()=>Cr===ne?Hr:void 0,[Hr,Cr,ne]),wr=(0,v.useMemo)(()=>r?Qi(r,Lt):void 0,[r,Lt]),qr=j??wr?.checkoutMode??"full",er=(0,v.useMemo)(()=>wr?{...wr,checkoutMode:qr}:void 0,[wr,qr]);(0,v.useEffect)(()=>{Zt(void 0),Zr(ne),_r.current=void 0,Qt.current=null,br(!1)},[ne]),(0,v.useEffect)(()=>{nr(Y)},[Y]);let Un=(0,v.useCallback)((z,q,oe)=>{(0,Ye.invokeMerchantCallback)(()=>{re.current?.(kr(z,q,oe))})},[]),Zn=(0,v.useCallback)(async(z,q)=>{nr(null),Jt(null),$r(!1),Mt("processing");let oe=q?.sessionId??z.id,be=z.clientSecret||t,gt=gc(z),Yt=Ft.current??ut.current,ke=Er(Yt),ie=Yt?null:ki(D,a,he),te={log:y=>{ke?ke.log(y):ie?.log(y)},error:y=>{ke?ke.error(y):ie?.error(y)},terminal:y=>{ke?ke.terminal(y):ie?.terminal(y)},performance:y=>{ke?ke.performance(y):ie?.performance(y)},now:()=>ke?.now()??ie?.now()??0,elapsed:y=>ke?.elapsed(y)??Math.max(0,(ie?.now()??y)-y)},Qe=te.now(),Ee=!!(q?.initialAutoProcessingError||q?.initialAutoProcessingPending),st=!1,N,ue=()=>{st||(st=!0,Ee=!0,N=te.now(),te.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ht=!1,It=()=>{ht||(ht=!0,te.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),te.performance({stage:"processing",durationMs:te.elapsed(Qe),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),N!==void 0&&te.performance({stage:"recovery",durationMs:te.elapsed(N),durationMode:"machine",paymentMethodCategory:"saved"}))};te.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),it.current=!0;try{te.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{it.current=!1}pt({class:"lifecycle",name:"payment.processing.started",provider:gt}),Ee&&ue();let Rr;try{let y=Wl(q?.initialAutoProcessingError),g=q?.initialAutoProcessingError?.type==="3ds_required"&&!q.initialAutoProcessingError.threeDSecureToken&&q.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.initialAutoProcessingError.nextActionRedirectUrl}:null,X,$e=je=>(ue(),Bt(He=>Jo(je,{billingApiUrl:D,sessionId:oe,nonce:be,session:z,signal:He})));if(g)X=await $e(g);else if(y)ue(),y.type==="paypal_redirect_required"&&ir.current?.publishableKey&&yc({sessionId:oe,publishableKey:ir.current.publishableKey,paypalPublishableKey:ir.current.paypalPublishableKey}),X=await Bt(je=>di(y,{flopay:Ft.current,paypalFlopay:ut.current,attempt3DS:q?.attempt3DS,billingApiUrl:D,sessionId:oe,session:z,telemetry:!1,signal:je})),y.type==="paypal_redirect_required"&&Rs();else if(q?.initialAutoProcessingPending){let je=q.initialAutoProcessingPending,He=new co.PaymentAPI(D,{telemetry:!1}),rt=await Bt(fr=>He.waitForCheckoutSessionCompletion(je.sessionId,{initialDelayMs:je.retryAfterMs,nonce:be,statusUrl:je.statusUrl,signal:fr})),qt=fo(rt,z),le=rt.autoProcessingError?.type==="3ds_required"&&rt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:rt.autoProcessingError.nextActionRedirectUrl}:null;if(le)X=await $e(le);else{if(!oo(qt))throw Vo(qt);X=no(qt,oe)}}else{if(q?.initialAutoProcessingError)throw Kn(q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.initialAutoProcessingError.checkoutMethod});if(q?.fromCreateSession)return q?.fallbackToFull&&($t("full"),fc("full")),!1;{let je=await Zo({billingApiUrl:D,sessionId:oe,session:z,nonce:be,telemetry:!1});je.type==="success"?X=je.result:je.type==="next_action_required"?X=await $e(je):(ue(),je.type==="paypal_redirect_required"&&ir.current?.publishableKey&&yc({sessionId:oe,publishableKey:ir.current.publishableKey,paypalPublishableKey:ir.current.paypalPublishableKey}),X=await Bt(He=>di(je,{flopay:Ft.current,paypalFlopay:ut.current,attempt3DS:q?.attempt3DS,billingApiUrl:D,sessionId:oe,session:z,telemetry:!1,signal:He})),je.type==="paypal_redirect_required"&&Rs())}}oe&&(0,Bn.markSessionRecentlyCompleted)(oe),It(),Ee&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),te.terminal({outcome:X.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),$r(X.status==="authorized"),Mt("success"),await Fa(600),Rr=()=>Sr.current?.(X)}catch(y){let g=yo(Ea(y),oe);if(g.code==="three_ds_aborted")return!1;let X=g.checkoutMethod??ka;nr(g.message),Jt(g.message),$r(!1),q?.fallbackToFull&&(te.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),$t("full"),fc("full")),It();let $e=g.statusCode===void 0?void 0:(0,De.telemetryStatusClass)(g.statusCode,"unknown"),je=$e==="4xx"?{requestCategory:"process_payment",statusClass:$e}:{},He=$e===void 0||$e==="4xx";if(He&&(g.telemetryOutcome==="payment_declined"||!!(g.declineCode||g.code?.toLowerCase().includes("declin"))))te.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...je});else if(He&&(g.telemetryOutcome==="validation_rejected"||g.type==="validation_error"))te.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...je});else{let le=(0,De.classifyTelemetryFailure)(y,Ee?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),fr=g.telemetryRequestCategory??"process_payment";it.current=!0;try{te.error({...le,...g.telemetryFailureCategory?{failureCategory:g.telemetryFailureCategory}:{},stage:Ee?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:fr})}finally{it.current=!1}pt({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:fr,provider:gt})}return(0,Ye.invokeMerchantCallback)(()=>Kr.current?.(g)),Un(X,g,{code:g.code,declineCode:g.declineCode}),Mt("error"),await Promise.allSettled([Fa(400),q?.ensureProvidersReady?q.ensureProvidersReady():Promise.resolve()]),Ee&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{It(),ie&&Ba(ie),Mt(null),Jt(null)}return(0,Ye.invokeMerchantCallback)(Rr),!0},[Un,pt,t,D,Bt,a,he]);(0,v.useEffect)(()=>{if(typeof window>"u"||zr.current)return;let z=new URLSearchParams(window.location.search),q=z.get("payment_intent_client_secret");if(!q)return;let oe=lu();oe&&(zr.current=!0,(async()=>{let be,gt=0;nr(null),Jt(null),Mt("processing"),Wr(!0);try{if(z.get("redirect_status")==="failed")throw Object.assign(new De.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Yt,paypalFlopay:ke}=await ss({publishableKey:oe.publishableKey,paypalPublishableKey:oe.paypalPublishableKey,billingApiUrl:D,locale:c,telemetry:a});be=Er(ke??Yt),be?.setCheckoutContext(he),gt=be?.now()??0,be?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),be?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let ie=(ke??Yt)?.getRawProvider();if(!ie)throw Object.assign(new De.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:te,error:Qe}=await ie.retrievePaymentIntent(q);if(Qe)throw Object.assign(new De.FloPayError(Qe.message??"Failed to retrieve PayPal payment status.","api_error",{code:Qe.code}),{checkoutMethod:"paypal"});let Ee=Tl(te?.status);if(!te||Ee==="failed")throw Object.assign(new De.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let st=typeof te.payment_method=="string"?te.payment_method:te.payment_method?.id,N=Ee;if(oe.sessionId){let It=(await new co.PaymentAPI(D,{telemetry:!1}).getUnifiedCheckoutSession(oe.sessionId)).data.session;if(It&&It.status!=="complete"){let Rr=await Zo({billingApiUrl:D,sessionId:oe.sessionId,session:It,telemetry:!1,tokenizedData:{id:st??te.id,type:"card",threeDSecureActionResultTokenId:te.id,isPaypal:!0}});if(Rr.type!=="success")throw Object.assign(new De.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});N=Rr.result.status}}oe.sessionId&&(0,Bn.markSessionRecentlyCompleted)(oe.sessionId),be?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),be?.performance({stage:"redirect_resume",durationMs:be.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),be?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Mt("success"),await Fa(600),(0,Ye.invokeMerchantCallback)(()=>Sr.current?.({status:N,paymentIntentId:te.id,paymentMethodId:st,checkoutMethod:"paypal"}))}catch(Yt){let ke=yo(Ea(Yt),oe.sessionId),ie=ke.checkoutMethod??"paypal",te=!!(ke.declineCode||ke.code?.toLowerCase().includes("declin"));if(be)be.performance({stage:"redirect_resume",durationMs:be.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),te?be.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):be.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(te){let Qe=ki(D,a,he);Qe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ba(Qe)}else bs(D,a,he,"REDIRECT_RESUME_FAILED","redirect_resume");nr(ke.message),Jt(ke.message),(0,Ye.invokeMerchantCallback)(()=>Kr.current?.(ke)),Un(ie,ke,{code:ke.code,declineCode:ke.declineCode}),Mt("error"),await Fa(400)}finally{Rs(),cu(),Mt(null),Jt(null),Wr(!1)}})())},[Un,c,D,a,he]);let zn=(0,v.useRef)(null),qn=(0,v.useMemo)(()=>er?(0,vt.serializeCreateParams)(er):"",[er]),Qn=(0,v.useRef)(er);Qn.current=er,(0,v.useEffect)(()=>{Dt(e??"")},[e]),(0,v.useEffect)(()=>{Ur.current=!1,nr(Y),Jt(null),$r(!1),Mt(null)},[qn,Y,e]);async function po(z,q,oe){let be=ki(D,a,he),gt=new co.PaymentAPI(D,{telemetry:!1}),Yt=!1;try{let ke=z.idempotencyKey===void 0?void 0:(0,De.resolveIdempotencyKey)(z.idempotencyKey),ie=(0,vt.readCachedInlineSession)(q,oe),te=(0,vt.readCachedInlineIdempotencyKey)(q,oe);ie?.canonicalIdentity===oe&&te&&te.canonicalIdentity===void 0&&((0,vt.persistCachedInlineIdempotencyKey)(q,oe,te.idempotencyKey),te={...te,canonicalIdentity:oe});let Qe=ke??(te?.canonicalIdentity===oe?te.idempotencyKey:void 0),Ee,st=!1;be.log({name:ie?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let N=ie?.sid??null,ue=null,ht,It,Rr=!1;if(N)try{ue=await gt.getUnifiedCheckoutSession(N,ie?.nonce),ie&&ie.canonicalIdentity===void 0&&((0,vt.legacyCachedSessionMatchesDraft)(ue.data.session,z)?((0,vt.persistCachedInlineSession)(q,oe,N,ie.nonce??ue.data.session?.clientSecret),te&&te.canonicalIdentity===void 0&&((0,vt.persistCachedInlineIdempotencyKey)(q,oe,te.idempotencyKey),Qe??(Qe=te.idempotencyKey))):((0,vt.clearCachedInlineCheckout)(q,oe),te=null,Qe=ke,N=null,ue=null));let g=ue?.data.session?.status,X=ue?.data.session,$e=X?.clientSecret||ie?.nonce;if(N&&X?.buyerIdentified===!1&&$e&&(It=jo(gt,N,$e,z.account)),N&&ue&&g==="complete"){if((0,Bn.wasSessionRecentlyCompleted)(N))return{sid:N,result:ue};(0,vt.clearCachedInlineCheckout)(q,oe),N=null,ue=null,st=!0}}catch{be.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ie?.canonicalIdentity===void 0?((0,vt.clearCachedInlineCheckout)(q,oe),Qe=ke):(0,vt.clearCachedInlineSession)(q,oe),N=null}if(!N){!ke&&(st||!Qe)&&(Qe=(0,De.resolveIdempotencyKey)(),Ee=Qe),Qe&&(0,vt.persistCachedInlineIdempotencyKey)(q,oe,Qe);let g=be.now(),X=0;be.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let $e={...z,idempotencyKey:Qe,avsCheck:!!de,avsConfig:typeof de=="object"?de:void 0,checkoutType:"embedded_checkout",checkoutLayout:ks($,ae)};Object.defineProperty($e,co.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:rt=>{X=Math.max(X,rt)}}});let je=()=>{pc(be,"session_create",g,X)},He=rt=>{mc(be,rt,"session_create",g,X)&&pt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,De.isDetachedSessionEligible)($e)){let rt=await gt.createDetachedSession($e);rt.claimed.catch(()=>{}),ue=rt.shell,N=rt.sessionId,It=rt.claim;let qt=be.now();be.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ht=rt.claimed.then(le=>{let fr=le.data.session?.id??rt.sessionId;return fr&&(0,vt.persistCachedInlineSession)(q,oe,fr,le.data.session?.clientSecret??rt.nonce),pc(be,"session_claim",qt),je(),le},le=>{throw(0,vt.clearCachedInlineSession)(q,oe),mc(be,le,"session_claim",qt,0)&&pt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),le}).finally(()=>Ba(be)),ht.catch(()=>{}),Yt=!0,be.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),be.performance({stage:"session_shell",durationMs:be.now()-g,durationMode:"machine",requestCategory:"session_create",attempt:X,statusClass:"2xx",paymentMethodCategory:"card"})}else ue=await gt.createAndFetchSession($e),je()}catch(rt){throw He(rt),rt}N=ue.data.session?.id??N??"",N&&!ht&&(0,vt.persistCachedInlineSession)(q,oe,N,ue.data.session?.clientSecret)}let y=ue?.data.session;return!It&&N&&y?.buyerIdentified===!1&&y.clientSecret&&(It=jo(gt,N,y.clientSecret,z.account)),{sid:N??"",result:ue,sdkGeneratedIdempotencyKey:Ee,...ht?{claimed:ht}:{},...It?{claim:It}:{},...Rr?{claimRequiresIdentity:!0}:{}}}finally{Yt||Ba(be)}}let mo=(0,v.useRef)(po);wo(()=>{mo.current=po},[po]);let Or=(0,v.useCallback)(async(z,q)=>{let oe=Qn.current;if(!oe)throw new De.FloPayError("createSession is required to bootstrap checkout.","validation_error");let be=Qi(oe,z),gt=(0,vt.serializeCreateParams)(be),Yt=(0,vt.hashCreateParams)(be),ke=Ei.get(gt);if(!ke){let Qe={canonicalIdentity:gt,promise:mo.current(be,Yt,gt),consumers:0,settled:!1};ke=Qe,Ei.set(gt,Qe);let Ee=()=>{Qe.settled=!0,uc(gt,Qe)};Qe.promise.then(Ee,Ee)}ke.consumers+=1;let ie=!1,te=()=>{ie||(ie=!0,ke.consumers-=1,uc(gt,ke))};q?.(te);try{let Qe=await ke.promise;zn.current=gt,z&&(Zr(ne),Zt(y=>wl(y,z)));let{sid:Ee,result:st,claimed:N,claim:ue,claimRequiresIdentity:ht}=Qe;if(_r.current=ue,br(ht===!0),et(st),st.data.session&&xe(st.data.session),Ee&&Dt(Ee),N){Kt.current+=1;let y=Kt.current;Qt.current=N,Ht(!0),N.then(g=>{Kt.current===y&&(Qt.current===N&&(Qt.current=null),et(g),g.data.session&&xe(g.data.session),Ht(!1),br(!1))},g=>{Kt.current===y&&(Qt.current===N&&(Qt.current=null),Ht(!1),br(!1),U(g instanceof De.FloPayError?g:new De.FloPayError(g instanceof Error?g.message:"Failed to create session","api_error")))})}else Kt.current+=1,Qt.current=null,Ht(!1),br(!1);let{flopay:It,paypalFlopay:Rr}=await ws(st,{billingApiUrl:D,locale:c,telemetry:a}).catch(y=>{throw El(y,Ee||st.data.session?.id)});return Q(It,Rr),se(!1),Qe}catch(Qe){throw zn.current===gt&&(zn.current=null),Qe}finally{q||te()}},[ne,Q,c,D,a]),eo=(0,v.useRef)(Zn);eo.current=Zn;let fn=(0,v.useRef)(Or);fn.current=Or;let Ut=(0,v.useCallback)(async z=>{if(!uu(z)||tt)return{sessionId:Ge,session:O};Et(!0);try{let q=await Or(z);return{sessionId:q.sid,session:q.result.data.session??null}}finally{Et(!1)}},[Or,tt,Ge,O]),Qr=(0,v.useCallback)(async z=>{let q=_r.current;if(!q)return;let oe=Kt.current,be=await q(z);Kt.current===oe&&(et(be),be.data.session&&xe(be.data.session))},[]),en=(0,v.useCallback)(async()=>{await Qt.current},[]),cn=(0,v.useCallback)(async()=>(await en(),{proceed:!0}),[en]);(0,v.useEffect)(()=>{let z=!1,q,oe=++ve.current;Gt(),U(null),Br(0);let be=()=>{z=!0,ve.current===oe&&(ve.current+=1,Gt())},gt=Qn.current;if(qn&&gt)return $t(qr),se(!1),zn.current===qn?be:(xe(Rl(gt,j)),(async()=>{let ie=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),te=qr==="auto"&&!Ur.current&&!ie;te&&(nr(null),Jt(null),Mt("processing"));let Qe=!1;try{let Ee=await fn.current(void 0,ht=>{q=ht});Qe=!0;let st=Ee.result.data.session??null;ir.current=is(Ee.result);let N=Ss(Ee.result),ue=(0,Bn.wasSessionRecentlyCompleted)(Ee.sid||st?.id);if(!z&&te&&st&&!N&&!ue){Ur.current=!0,await au(qn,Ee.sdkGeneratedIdempotencyKey,()=>eo.current(st,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Ee.result.autoProcessingError,initialAutoProcessingPending:Ee.result.autoProcessingPending,autoProcessingAttempted:Ee.result.autoProcessingAttempted,sessionId:Ee.sid||st.id}));return}!z&&te&&((N||ue)&&(Ur.current=!0),Mt(null),Jt(null))}catch(Ee){if(z)return;let st=Za(Ee);if(te&&st==="session_auto_completed"){Ur.current=!0,Mt("success"),await Fa(600),z||((0,Ye.invokeMerchantCallback)(()=>{Sr.current?.({status:"succeeded"})}),Mt(null),Jt(null));return}if(te&&(Mt(null),Jt(null)),!Qe){let ue=Il(Ee),ht=(0,De.toPublicCheckoutInitError)(Ee,ue?{stage:"provider_load",provider:"stripe",...ue}:{stage:"session_request"});(ue||!(Ee instanceof De.FloPayError))&&(0,Ye.invokeMerchantCallback)(()=>Kr.current?.(ht)),U(ht);return}let N=Ee instanceof De.FloPayError?Ee:new De.FloPayError(Ee instanceof Error?Ee.message:"Failed to create session","api_error");U(N)}finally{q?.(),q=void 0}})(),()=>{be(),q?.()});se(!0);async function Yt(){let ie=!1,te=!1,Qe=null;try{let Ee=new co.PaymentAPI(D,{telemetry:!1}),st=await Ee.getUnifiedCheckoutSession(d,t);if(te=!0,Qe=st,z)return;et(st);let N=st.data.session??null;if(xe(N),!N)throw new De.FloPayError("No session data returned","api_error");let ue=N.checkoutMode;if(ue==="setup")throw new De.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(N.status==="authorized"){se(!1),(0,Ye.invokeMerchantCallback)(()=>{Sr.current?.(no(N,d)),sr.current?.(N.successUrl??"")});return}if(N.status==="complete"){se(!1),(0,Ye.invokeMerchantCallback)(()=>{sr.current?.(N.successUrl??"")});return}if(N.status==="expired")throw Ja(N);ie=!0;let ht=j??ue??"full";$t(ht),Kt.current+=1;let It=N.clientSecret||t;_r.current=N.buyerIdentified===!1&&It?jo(Ee,d,It,{...N.customer?.id?{userId:N.customer.id}:{}}):void 0,Ht(!1),br(!1);let Rr=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),y=Ss(st);if(ht==="auto"&&!Ur.current&&!Rr&&!y){Ur.current=!0;let g=ke(st);try{if(await eo.current(N,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>g,sessionId:d||N.id}),z)return;await g,z||se(!1);return}catch{if(z)return;await g,z||se(!1);return}}await ke(st),z||se(!1)}catch(Ee){if(z)return;let st=Sl(Ee,ie);if(ie&&pt({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),st){let{errorCode:It,stage:Rr,...y}=st;bs(D,a,he,It,Rr,y)}if(st?.stage==="provider_load"&&(j??Qe?.data.session?.checkoutMode??"full")==="full"&&bl(Qe,A,f)){let It=su({billingApiUrl:D,locale:c,telemetry:a});St.current=It,Q(It,null),Br(1),se(!1);return}let N=st?.stage==="provider_load",ue="session_request";N?ue="provider_load":te&&(ue="post_session");let ht=(0,De.toPublicCheckoutInitError)(Ee,{stage:ue,provider:"stripe",sessionId:d||void 0});(N||!(Ee instanceof De.FloPayError))&&(0,Ye.invokeMerchantCallback)(()=>Kr.current?.(ht)),U(ht),se(!1)}}async function ke(ie){let{flopay:te,paypalFlopay:Qe,...Ee}=await ws(ie,{billingApiUrl:D,locale:c,telemetry:a});ir.current={publishableKey:Ee.publishableKey,paypalPublishableKey:Ee.paypalPublishableKey},Q(te,Qe),Br(0)}return Yt(),be},[j,qn,qr,L,t,A,f]);let tn=(0,v.useCallback)(async()=>{if(!Me||Nt!==1)return;let z=ve.current;Br(2);try{let{flopay:q,paypalFlopay:oe}=await ws(Me,{billingApiUrl:D,locale:c,telemetry:a});if(ve.current!==z)return;Gt(),Q(q,oe),Br(0)}catch(q){if(ve.current!==z)return;let{errorCode:oe,stage:be,...gt}=Zi(q);bs(D,a,he,oe,be,gt)}},[Gt,Q,c,Nt,D,a,he,Me]),mt=!!(d&&(O?.clientSecret||t)),yr=Tt||!mt,lr=(0,v.useCallback)(async()=>{if(!(Tt||!mt||!O)){Wr(!0),nr(null);try{await Zn(O,{attempt3DS:!0,fallbackToFull:!0,sessionId:d||O.id})}finally{Wr(!1)}}},[d,Tt,mt,Zn,O]),Gr=(0,De.resolveDirectPaypalConfig)(Me?.data.paypal,W),ho=Ss(Me),to=(0,v.useMemo)(()=>{if(!(!Me||!O||!Me.data.stripe?.publishableKey))return{billingApiUrl:D}},[Me,O,D]),In=!!(r&&!$&&ae==="buttons"&&Le&&qr==="full"),dn=!!(d&&((0,De.isMountableVaultBlock)(O?.vault)||(0,xn.canRecoverHostedCardForm)(O))),Mr=(0,v.useMemo)(()=>({session:O,loading:V,error:E,checkoutMode:rr,inlineSessionDraft:er,applyInlineSessionPatch:In?Ut:void 0,inlineSessionPatchProcessing:tt,claimPending:Dr,claimRequiresIdentity:or,claimBuyerIdentity:Qr,waitForDataAttachment:en}),[O,V,E,rr,er,In,Ut,tt,Dr,or,Qr,en]),ro=!!r&&ae==="buttons"&&!ho&&!dn&&(!at||!to),jr=Jr?(0,F.jsx)(an,{status:Jr,errorMessage:Ln,authorized:yn}):null;if(V&&!dn){if(p)return(0,F.jsxs)(F.Fragment,{children:[p,jr]});if(ae==="buttons"){let z=ge?.buttonsLayout?.cardButton?.borderRadius??ge?.appearance.variables?.borderRadius??8,q=oe=>(0,F.jsx)("div",{style:{height:oe,borderRadius:z,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[A&&q(ta),f&&(S||Te)&&q(ta),f&&q(ta),(0,F.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),jr]})}return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,F.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,F.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),jr]})}return E?m?(0,F.jsx)(An.Provider,{value:Mr,children:m(E)}):(0,F.jsx)(An.Provider,{value:Mr,children:(0,F.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:E.message})}):ro?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Mr,children:(0,F.jsx)(mu,{onButtonClick:Je,showPayPal:A,showStripe:f,showApplePay:S,showGooglePay:Te,theme:ye,buttonsTheme:pe,buttonsStyles:we,cardButtonContent:dt,cardBackButtonContent:Ke,cardTitleContent:B})}),jr]}):ho&&O&&Gr?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Mr,children:(0,F.jsxs)("div",{className:qe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Nr&&(0,F.jsx)(Yo,{icon:!1,children:Nr}),Ze==="retrying"&&(0,F.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ze==="exhausted"&&(0,F.jsxs)("div",{role:"alert",children:[(0,F.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,F.jsx)("button",{type:"button",onClick:Wt,children:"Retry PayPal"})]}),Ze!=="exhausted"&&(0,F.jsx)("div",{"aria-hidden":Ze==="retrying"?!0:void 0,style:Ze==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,F.jsx)(zl,{sessionId:d,nonce:O.clientSecret||void 0,billingApiUrl:D,email:O.customer?.email||er?.account?.email,billingName:[O.customer?.firstName,O.customer?.lastName].filter(Boolean).join(" ")||[er?.account?.firstName,er?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Qr,clientId:Gr.clientId,environment:Gr.environment,currency:(O.currency??"usd").toUpperCase(),isSubscription:O.mode==="subscription",providerObjectType:Gr.providerObjectType,approvalPresentation:Gr.approvalPresentation,existingOrderId:Gr.existingOrderId,onComplete:h,onErrorChange:nr,onDecline:I,onCancel:G,onButtonClick:Je,runBeforeButtonClick:cn,onInitializationStateChange:Pe,allowAutomaticRetry:Tr===0,session:O,telemetry:a,telemetryContext:he,onInstrument:We,debug:T},`${Ce}:paypal-init-${Tr}`)})]})}),jr]}):rr==="confirm"?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Mr,children:(0,F.jsx)(wa,{flopay:at,paypalFlopay:M,options:to??{billingApiUrl:D},onInstrument:We,children:(0,F.jsxs)("div",{className:qe,children:[Nr&&(0,F.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Nr}),Be?Be({onConfirm:lr,isProcessing:yr}):(0,F.jsx)("button",{type:"button",onClick:lr,disabled:yr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:yr?"not-allowed":"pointer",opacity:yr?.6:1},children:Tt?"Processing...":Ve??"Confirm Purchase"})]})},Ce)}),jr]}):(!at||!to)&&!(dn&&rr==="full")?(0,F.jsx)(F.Fragment,{children:jr}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(An.Provider,{value:Mr,children:(0,F.jsxs)(wa,{flopay:at,paypalFlopay:M,options:to??{billingApiUrl:D},onInstrument:We,children:[Nt===1&&(0,F.jsx)("button",{type:"button",onClick:tn,children:"Retry payment methods"}),$?(0,F.jsxs)(F.Fragment,{children:[Nr&&(0,F.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Nr}),(0,F.jsx)(pu,{sessionId:d,nonce:O?.clientSecret||void 0,billingApiUrl:D,session:O,submitLabel:nt,walletPresentation:P,children:$})]}):(0,F.jsx)(wi,{sessionId:d,nonce:O?.clientSecret||void 0,telemetry:a,email:O?.customer?.email||er?.account?.email,userId:O?.customer?.id||er?.account?.userId,firstName:O?.customer?.firstName||er?.account?.firstName,lastName:O?.customer?.lastName||er?.account?.lastName,totalAmount:O?Math.round((0,De.buildCheckoutDisplayData)(O).total*100):0,currency:O?.currency?.toLowerCase()??"usd",onComplete:h,onError:k,onDecline:I,onCancel:G,error:Nr,onErrorChange:nr,showPayPal:A,showStripe:f,walletPresentation:P,enabledPaymentMethods:Nt?[]:me??Me?.data.stripe?.enabledPaymentMethods??O?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Me?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:Te,layout:ae,theme:ye,buttonsTheme:pe,buttonsStyles:we,appearance:ft,cardButtonContent:dt,cardBackButtonContent:Ke,cardTitleContent:B,onButtonClick:Je,onBeforeButtonClick:Le,onBuyerIdentityReady:Qr,enableAVS:de,...ee?{cardFieldOrder:ee}:{},...H?{cardPreFormSlot:H}:{},avsLayout:Oe,country:O?.customer?.country,city:O?.customer?.city,state:O?.customer?.state,onCountryChange:_,onZipChange:Z,avsCheck:!!de,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:ks($,ae),className:qe,submitLabel:nt,directPaypal:Gr,isSubscription:O?.mode==="subscription",session:O,dataAttachmentPending:Dr,dataAttachmentRequiresIdentity:or,debug:T})]},Ce)}),jr]})}function pu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,children:c}){return(0,F.jsx)(F.Fragment,{children:v.default.Children.map(c,p=>{if(!v.default.isValidElement(p))return p;let m=p.props,h={};return m.sessionId||(h.sessionId=e),!m.nonce&&t&&(h.nonce=t),m.billingApiUrl||(h.billingApiUrl=r),m.submitLabel===void 0&&a!==void 0&&(h.submitLabel=a),m.walletPresentation===void 0&&(h.walletPresentation=s),n?.customer&&(m.email||(h.email=n.customer.email),m.userId||(h.userId=n.customer.id),m.firstName||(h.firstName=n.customer.firstName),m.lastName||(h.lastName=n.customer.lastName)),Object.keys(h).length===0?p:v.default.cloneElement(p,h)})})}function mu({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:s,buttonsTheme:c,buttonsStyles:p,cardButtonContent:m,cardBackButtonContent:h,cardTitleContent:k}){let[w,I]=(0,v.useState)(!1),G=(0,v.useMemo)(()=>(0,De.resolveTheme)(s),[s]),_=(0,v.useMemo)(()=>{let P=G?.buttonsLayout??(0,De.resolveButtonsLayoutTheme)(c);return p?{...P,...p,cardButton:{...P.cardButton,...p.cardButton},cardFormContainer:{...P.cardFormContainer,...p.cardFormContainer},backButton:{...P.backButton,...p.backButton},backButtonIcon:{...P.backButtonIcon,...p.backButtonIcon},submitButton:{...P.submitButton,...p.submitButton},title:{...P.title,...p.title}}:P},[G,c,p]),Z=G?.buttonsLayout?.cardButton?.borderRadius??G?.appearance.variables?.borderRadius??8,A=P=>(0,F.jsx)("div",{style:{height:P,borderRadius:Z,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),f=m===void 0?{boxSizing:"border-box",height:ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(w){let P=_.cardInputBorder??"#e5e7eb",me=_.cardInputBackground??"white",S=Uo(h),Te=Uo(k);return(0,F.jsxs)("div",{style:{backgroundColor:_.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",..._.cardFormContainer},children:[(0,F.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,F.jsxs)("button",{type:"button",onClick:()=>I(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:S?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",..._.backButton},children:[(0,F.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",..._.backButtonIcon},children:(0,F.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,F.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,F.jsx)(qo,{content:h})]}),Te?(0,F.jsx)("div",{style:{flex:1}}):(0,F.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,..._.title},children:(0,F.jsx)(fa,{content:k})})]}),(0,F.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsxs)("div",{style:{display:"flex"},children:[(0,F.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,F.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",..._.submitButton,opacity:.5}}),(0,F.jsx)("style",{children:`
38
+ `}),da&&ho&&(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:he?-2:0},children:[(0,u.jsxs)("button",{type:"button",onClick:Se,style:{display:"inline-flex",alignItems:"center",gap:Ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:le.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...le.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...le.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(qo,{content:Le})]}),ul?(0,u.jsx)("div",{style:{flex:1}}):(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:le.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...le.title},children:(0,u.jsx)(fa,{content:de})})]}),!da&&!ul&&(0,u.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Gi,order:he?-3:0,...le.title},children:(0,u.jsx)(fa,{content:de})}),he&&W&&(0,u.jsx)("div",{style:{order:-2,width:"100%"},children:W}),he&&_n&&(0,u.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,u.jsx)("div",{style:{backgroundColor:Oo,border:`1px solid ${hn(Ha)}`,borderRadius:cr,padding:"10px"},children:(0,u.jsx)("input",{ref:te,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Zt,onChange:i=>{Ut("email"),Kt.current=i.target.value,Cr(i.target.value)},onPointerDown:()=>Ut("email"),onKeyDown:()=>Ut("email"),onBlur:()=>{en("email")&&Qn(!0),To||Li()},disabled:Fe,required:!0,"aria-invalid":Ha||void 0,"aria-describedby":Ha?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Yi}})}),Ha&&(0,u.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:pa,children:Fi.empty?"Email address is required":"Enter a valid email address"})]}),Ze&&(0,u.jsx)("div",{style:{order:he?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=$t,C=(J=!1)=>({backgroundColor:Oo,border:`1px solid ${hn(J)}`,borderRadius:cr,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Yi}),Ie=(0,l.getStateOptions)(i);return(0,u.jsxs)(u.Fragment,{children:[(0,l.isAVSFieldVisible)(Ze.address_line_1,i)&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)("div",{style:C(tr("line1")),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:nr,onChange:J=>{Ut("line1"),_r.current.addressLine1=!0,Ht.current=J.target.value,Zr(J.target.value)},onPointerDown:()=>Ut("line1"),onKeyDown:()=>Ut("line1"),onBlur:()=>tn("line1"),disabled:Fe,required:!0,"aria-invalid":tr("line1")||void 0,"aria-describedby":tr("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:K()})}),tr("line1")&&(0,u.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:pa,children:"Street address is required"})]}),(0,l.isAVSFieldVisible)(Ze.address_line_2,i)&&(0,u.jsx)("div",{style:C(),children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Mt,onChange:J=>{_r.current.addressLine2=!0,or.current=J.target.value,Ln(J.target.value)},disabled:Fe,"data-testid":"flopay-address-line2",style:K()})}),((0,l.isAVSFieldVisible)(Ze.city,i)||(0,l.isAVSFieldVisible)(Ze.state,i))&&(0,u.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Ze.city,i)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Oo,borderTop:`1px solid ${hn(tr("city"))}`,borderRight:`1px solid ${hn(tr("city"))}`,borderBottom:`1px solid ${hn(tr("city"))}`,borderLeft:`1px solid ${hn(tr("city"))}`,padding:"10px",borderTopLeftRadius:cr,borderBottomLeftRadius:cr,...(0,l.isAVSFieldVisible)(Ze.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:cr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Jt,onChange:J=>{Ut("city"),_r.current.city=!0,br.current=J.target.value,fn(J.target.value)},onPointerDown:()=>Ut("city"),onKeyDown:()=>Ut("city"),onBlur:()=>tn("city"),disabled:Fe,required:!0,"aria-invalid":tr("city")||void 0,"aria-describedby":tr("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:K()})}),(0,l.isAVSFieldVisible)(Ze.state,i)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Oo,borderTop:`1px solid ${hn(tr("state"))}`,borderRight:`1px solid ${hn(tr("state"))}`,borderBottom:`1px solid ${hn(tr("state"))}`,borderLeft:`1px solid ${hn(tr("state"))}`,padding:"10px",borderTopRightRadius:cr,borderBottomRightRadius:cr,...(0,l.isAVSFieldVisible)(Ze.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${hn(tr("state")||tr("city"))}`}:{borderRadius:cr}},children:Ie?(0,u.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:$r,onChange:J=>{Ut("state"),_r.current.state=!0,Qt.current=J.target.value,Hr(J.target.value)},onPointerDown:()=>Ut("state"),onKeyDown:()=>Ut("state"),onBlur:()=>tn("state"),disabled:Fe,autoComplete:"billing address-level1",required:!0,"aria-invalid":tr("state")||void 0,"aria-describedby":tr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...K(),cursor:"pointer"},children:[(0,u.jsx)("option",{value:"",children:(0,l.getStateLabel)(i)}),Ie.map(J=>(0,u.jsx)("option",{value:J.code,children:J.name},J.code))]}):(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,l.getStateLabel)(i),autoComplete:"billing address-level1",value:$r,onChange:J=>{Ut("state"),_r.current.state=!0,Qt.current=J.target.value,Hr(J.target.value)},onPointerDown:()=>Ut("state"),onKeyDown:()=>Ut("state"),onBlur:()=>tn("state"),disabled:Fe,required:!0,"aria-invalid":tr("state")||void 0,"aria-describedby":tr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:K()})})]}),tr("city")&&(0,u.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:pa,children:"City is required"}),tr("state")&&(0,u.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:pa,children:[(0,l.getStateLabel)(i)," is required"]}),((0,l.isAVSFieldVisible)(Ze.country,i)||(0,l.isAVSFieldVisible)(Ze.postal_code,i))&&(0,u.jsxs)("div",{style:{display:"flex",flexDirection:$==="column"?"column":"row",gap:$==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Ze.country,i)&&(0,u.jsx)("div",{style:{flex:$==="row"?1:void 0,backgroundColor:Oo,borderTop:`1px solid ${ua}`,borderRight:`1px solid ${ua}`,borderBottom:`1px solid ${ua}`,borderLeft:`1px solid ${ua}`,padding:"10px",...$==="row"&&(0,l.isAVSFieldVisible)(Ze.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:cr,borderBottomLeftRadius:cr,borderRight:"none"}:{borderRadius:cr}},children:(0,u.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:$t,onChange:J=>{_r.current.country=!0,Dr.current=J.target.value,Tt(J.target.value),ft?.(J.target.value),Qt.current="",Hr("")},disabled:Fe,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:[$t===""?(0,u.jsx)("option",{value:"",children:"Select country"}):null,l.COUNTRY_OPTIONS.map(J=>(0,u.jsxs)("option",{value:J.code,children:[J.flag," ",J.name]},J.code))]})}),(0,l.isAVSFieldVisible)(Ze.postal_code,i)&&(0,u.jsx)("div",{style:{flex:$==="row"?1:void 0,backgroundColor:Oo,border:`1px solid ${Hc}`,padding:"10px",...$==="row"&&(0,l.isAVSFieldVisible)(Ze.country,i)?{borderRadius:"0",borderTopRightRadius:cr,borderBottomRightRadius:cr}:{borderRadius:cr}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,l.getPostalCodeLabel)($t),autoComplete:"billing postal-code",value:Wr,onChange:J=>{Ut("zip"),_r.current.zip=!0,Et.current=J.target.value,Nr(J.target.value),Ne?.(J.target.value)},onPointerDown:()=>Ut("zip"),onKeyDown:()=>Ut("zip"),onBlur:()=>{en("zip")&&zn(!0)},disabled:Fe,required:Lt.required,"aria-invalid":Ka||void 0,"aria-describedby":Ka?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),Ka&&(0,u.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:pa,children:Lt.empty?`${(0,l.getPostalCodeLabel)(i)} is required`:Qd(i)})]})})()}),he&&Jc,et&&(0,u.jsx)(Yo,{margin:"0.75rem 0",styleOverride:le.errorBanner,children:et})]}),Ga={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"},gl=i=>O?!me||!Vn?(0,u.jsx)("pre",{"data-testid":i,style:Ga,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":i,style:Ga,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${me}`,` directPaypalConfigured=${Vn}`,` inAppBrowserDetected=${String(Va)}`,` shouldRenderDirectPayPal=${aa}`,` shouldRenderStripePayPal=${sa}`,` hasPaypalStripeInstance=${!!As}`].join(`
39
+ `)}):null,hl=i=>O?!S||!pn?(0,u.jsx)("pre",{"data-testid":i,style:Ga,children:"FloPay/Stripe-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":i,style:Ga,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${S}`,` currency=${mr}`,` amountInCents=${na}`,` enabledPaymentMethods: ${JSON.stringify(T??[])}`,` enabledPaymentMethodsProvided=${oa}`,` hasEnabledMethods=${Ua}`,` expressMethods: ${JSON.stringify(qa)}`,` walletExpressMethods: ${JSON.stringify(Bo)}`,` paymentElementMethods: ${JSON.stringify(Ui)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ja)}`,` hasStripeInstance=${!!pn}`,` shouldRenderWallets=${Do}`,` shouldRenderPaymentElement=${la}`].join(`
40
+ `)}):null,Pl=mt==="apm-expanding"||mt==="apm-form"||mt==="apm-collapsing",No;mt==="apm-expanding"?No=tc:mt==="apm-collapsing"&&(No=rc);let Ya=lr?uc(zi,lr,We):null;if(Re==="buttons"){let i=mt==="buttons"||mt==="expanding"||mt==="apm-expanding",C=mt==="expanding"||mt==="card"||mt==="collapsing",K=Je===void 0?{boxSizing:"border-box",height:Qo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ie;mt==="expanding"||mt==="apm-expanding"?Ie=Yd:(mt==="collapsing"||mt==="apm-collapsing")&&(Ie=Gd);let J;return mt==="expanding"?J=tc:mt==="collapsing"&&(J=rc),(0,u.jsxs)("form",{onSubmit:Wi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(ea,{}),ke&&(0,u.jsx)(sn,{status:ke,errorMessage:et,authorized:Tr}),(0,u.jsxs)("div",{style:{display:"grid"},children:[(0,u.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Ie?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Ie?Jd:{},...Ie?{animation:Ie,pointerEvents:"none"}:{}},children:[gl("flopay-direct-paypal-gate-debug"),hl("flopay-stripe-gate-debug"),aa&&St&&(0,u.jsxs)(u.Fragment,{children:[y&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(va.Provider,{value:M,children:(0,u.jsx)(ba,{sessionId:e,nonce:t,billingApiUrl:E,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:Ue,clientId:St.clientId,environment:St.environment,currency:mr.toUpperCase(),isSubscription:Ce,providerObjectType:Dt,approvalPresentation:Wa==="popup"?void 0:Wa,onTokenizedBody:on,onComplete:c,onErrorChange:ze,onDecline:m,onCancel:h,onTechnicalFailure:Ao,onButtonClick:H,runBeforeButtonClick:Mn,isProcessing:Fe,onLoadStateChange:qi,onInitializationStateChange:ji,session:Ve,existingOrderId:y?.orderId,debug:O},y?.orderId??"fresh")})]}),sa&&(0,u.jsx)(dr.Elements,{stripe:ia,options:Ds,children:(0,u.jsx)(oc,{sessionId:e,nonce:t,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:Ue,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,isProcessing:Fe,onButtonClick:H,onDecline:m,onTechnicalFailure:Ao,runBeforeButtonClick:Mn,onLoadStateChange:Gs,placeholderBorderRadius:Po,popupCapabilityOwner:M,externalTelemetryContext:nl,presentationMode:Fo})}),Do?(0,u.jsx)(dr.Elements,{stripe:pn,options:Bs,children:(0,u.jsx)(ac,{sessionId:e,nonce:t,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:Ue,billingApiUrl:E,intentKind:at>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:on,onErrorChange:ze,onButtonClick:H,onDecline:m,onTechnicalFailure:Ao,runBeforeButtonClick:Mn,onLoadStateChange:Xs,placeholderBorderRadius:Po,popupCapabilityOwner:M,externalTelemetryContext:it})}):null,!Do&&tl?(0,u.jsx)("div",{style:{height:Qo,borderRadius:Po,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,la&&(0,u.jsx)(ic,{sessionId:e,nonce:t,email:ce.email,billingName:[ce.firstName,ce.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Ue,billingApiUrl:E,paymentElementMethods:ja,stripeInstance:pn,paymentElementBaseOptions:zi,futureUseSession:We,onTokenizedBody:on,onErrorChange:ze,onButtonClick:H,onDecline:m,runBeforeButtonClick:Mn,onLoadStateChange:Zs,isProcessing:Fe,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:le.submitButton,onExpandApm:gt,expandedApmMethod:lr,themeId:dt,buttonAppearance:{backgroundColor:le.cardButton?.backgroundColor,borderColor:le.cardInputBorder,textColor:le.cardButton?.color,borderRadius:Po}}),he&&(0,u.jsx)("button",{type:"button",onClick:async()=>{Fe||!(await Mn("card")).proceed||(H?.("card"),ne())},disabled:Fe,style:{width:"100%",...K,...le.cardButton,...Cs({themeBundle:qt,resolvedPrimaryColor:vo,resolvedBorderRadius:cr,submitButtonStyle:le.submitButton,explicitPrimaryColor:an?.colorPrimary}),fontSize:le.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Fe?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Fe?.6:1},onMouseEnter:_e=>{!Fe&&(qt||an?.colorPrimary)&&(_e.currentTarget.style.backgroundColor=Yc)},onMouseLeave:_e=>{(qt||an?.colorPrimary)&&(_e.currentTarget.style.backgroundColor=vo)},onMouseDown:_e=>{_e.currentTarget.style.transform="scale(0.985)"},onMouseUp:_e=>{_e.currentTarget.style.transform="scale(1)"},children:(0,u.jsx)(zo,{content:Je})}),et&&mt==="buttons"&&(0,u.jsx)(Yo,{margin:"0.25rem 0",styleOverride:le.errorBanner,children:et})]}),he&&C&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...J?{animation:J}:{},...mt==="collapsing"?{pointerEvents:"none"}:{}},children:fl}),S&&Pl&&lr&&Ya&&pn&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...No?{animation:No}:{},...mt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:Hi,borderRadius:Ji,...ma,padding:Xi},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Yt,style:{display:"inline-flex",alignItems:"center",gap:Ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:le.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...le.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...le.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(qo,{content:Le})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:le.titleFontSize??"1.05rem",color:Gi,paddingRight:80,...le.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(lr)}`})]}),(0,u.jsx)(dr.Elements,{stripe:pn,options:Ya,children:(0,u.jsx)(hs,{method:lr,sessionId:e,nonce:t,email:ce.email,billingName:[ce.firstName,ce.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Ue,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,onDecline:m,onCancel:Yt,runBeforeButtonClick:Mn,onButtonClick:H,isProcessing:Fe,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:le.submitButton,errorText:et})},lr)]})})]})]})}return Pl&&lr&&Ya&&pn&&S?(0,u.jsxs)("form",{onSubmit:Wi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(ea,{}),ke&&(0,u.jsx)(sn,{status:ke,errorMessage:et,authorized:Tr}),(0,u.jsx)("div",{style:{...No?{animation:No}:{},...mt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:Hi,borderRadius:Ji,...ma,padding:Xi},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Yt,style:{display:"inline-flex",alignItems:"center",gap:Ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:le.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...le.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...le.backButtonIcon},children:(0,u.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(qo,{content:Le})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:le.titleFontSize??"1.05rem",color:Gi,paddingRight:80,...le.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(lr)}`})]}),(0,u.jsx)(dr.Elements,{stripe:pn,options:Ya,children:(0,u.jsx)(hs,{method:lr,sessionId:e,nonce:t,email:ce.email,billingName:[ce.firstName,ce.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Ue,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,onDecline:m,onCancel:Yt,runBeforeButtonClick:Mn,onButtonClick:H,isProcessing:Fe,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:le.submitButton,errorText:et})},lr)]})})]}):(0,u.jsxs)("form",{onSubmit:Wi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(ea,{}),ke&&(0,u.jsx)(sn,{status:ke,errorMessage:et,authorized:Tr}),(0,u.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[gl("flopay-direct-paypal-gate-debug-default"),hl("flopay-stripe-gate-debug-default"),aa&&St&&(0,u.jsxs)(u.Fragment,{children:[y&&(0,u.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,u.jsx)(va.Provider,{value:M,children:(0,u.jsx)(ba,{sessionId:e,nonce:t,billingApiUrl:E,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:Ue,clientId:St.clientId,environment:St.environment,currency:mr.toUpperCase(),isSubscription:Ce,providerObjectType:Dt,approvalPresentation:Wa==="popup"?void 0:Wa,onTokenizedBody:on,onComplete:c,onErrorChange:ze,onDecline:m,onCancel:h,onTechnicalFailure:Ao,onButtonClick:H,runBeforeButtonClick:Mn,isProcessing:Fe,onLoadStateChange:qi,onInitializationStateChange:ji,session:Ve,existingOrderId:y?.orderId,debug:O},y?.orderId??"fresh")})]}),sa&&(0,u.jsx)(dr.Elements,{stripe:ia,options:Ds,children:(0,u.jsx)(oc,{sessionId:e,nonce:t,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:Ue,billingApiUrl:E,onTokenizedBody:on,onErrorChange:ze,isProcessing:Fe,onButtonClick:H,onDecline:m,onTechnicalFailure:Ao,runBeforeButtonClick:Mn,onLoadStateChange:Gs,placeholderBorderRadius:Po,popupCapabilityOwner:M,externalTelemetryContext:nl,presentationMode:Fo})}),Do&&(0,u.jsx)(dr.Elements,{stripe:pn,options:Bs,children:(0,u.jsx)(ac,{sessionId:e,nonce:t,email:ce.email,billingName:yt||void 0,onBuyerIdentityReady:Ue,billingApiUrl:E,intentKind:at>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:on,onErrorChange:ze,onButtonClick:H,onDecline:m,onTechnicalFailure:Ao,runBeforeButtonClick:Mn,onLoadStateChange:Xs,placeholderBorderRadius:Po,popupCapabilityOwner:M,externalTelemetryContext:it})}),la&&(0,u.jsx)(ic,{sessionId:e,nonce:t,email:ce.email,billingName:[ce.firstName,ce.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:E,paymentElementMethods:ja,stripeInstance:pn,paymentElementBaseOptions:zi,futureUseSession:We,onTokenizedBody:on,onErrorChange:ze,onButtonClick:H,onDecline:m,runBeforeButtonClick:Mn,onLoadStateChange:Zs,isProcessing:Fe,submitButtonColor:vo,submitButtonBorderRadius:cr,submitButtonStyle:le.submitButton,themeId:dt,onExpandApm:gt,expandedApmMethod:lr,buttonAppearance:{backgroundColor:le.cardButton?.backgroundColor,borderColor:le.cardInputBorder,textColor:le.cardButton?.color,borderRadius:Po}})]}),he&&(jc||qc||Vc)&&(0,u.jsx)(Pi,{label:"or pay with card"}),he&&fl]})}var D=require("react/jsx-runtime"),ta=44,Is="flopay_checkout_saved_payment_resume",Ii=new Map,ki=new Map;function pc(e,t){t.settled&&t.consumers===0&&Ii.get(e)===t&&Ii.delete(e)}function iu(e,t,r){let n=ki.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};ki.set(e,s);let c=()=>{ki.get(e)===s&&ki.delete(e)};return a.then(c,c),a}function Ba(e){return new Promise(t=>setTimeout(t,e))}function Ei(e,t,r){let n=ii({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:De.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Da(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ss(e,t,r,n,a,s){let c=Ei(e,t,r);c.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Da(c)}function mc(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 yc(e,t,r,n,a){let s=(0,De.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:a,statusClass:s.statusClass}),t instanceof De.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof De.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):s.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...s,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function ws(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,De.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var su={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function lu(e){return new co.FloPay(su,{publishableKey:"provider_unavailable",...e})}async function Rs(e,t){let{publishableKey:r,paypalPublishableKey:n}=ss(e);return{...await ls({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function _s(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function cu(){if(!_s())return null;try{let e=window.sessionStorage.getItem(Is);return e?JSON.parse(e):null}catch{return null}}function fc(e){if(_s())try{window.sessionStorage.setItem(Is,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ks(){if(_s())try{window.sessionStorage.removeItem(Is)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function du(){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 gc(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 Es(e,t){return(0,De.resolveCheckoutLogLayout)(!!e,t)}function uu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function hc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function pu(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 _i({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:c,loading:p,error:m,onComplete:h,onError:k,onInstrument:w,onDecline:I,onCancel:G,onCountryChange:_,onZipChange:Z,showPayPal:F=!0,showStripe:f=!0,walletPresentation:P="auto",enabledPaymentMethods:me,showApplePay:S=!0,showGooglePay:Te=!0,debug:T=!1,layout:ae,theme:ye,buttonsTheme:pe,buttonsStyles:Re,cardButtonContent:dt,cardBackButtonContent:Ge,cardTitleContent:x,showSecurityFooter:kt,onButtonClick:Je,onBeforeButtonClick:Le,enableAVS:de,cardFieldOrder:ee,cardPreFormSlot:H,avsLayout:Oe,submitLabel:nt,className:je,initialErrorMessage:Y=null,initialPayPalOrderId:W,children:$,checkoutMode:V,confirmLabel:He,renderConfirmButton:Be,onSessionCompleted:fe}){let B=(0,De.resolveBillingApiUrl)(n),ge=(0,v.useMemo)(()=>(0,De.resolveTheme)(ye),[ye]),ft=s??ge?.appearance,Ne=r?"embedded_checkout":"standard_checkout",ot=Es($,ae),[Me,tt]=(0,v.useState)(null),[at,mr]=(0,v.useState)(null),Ft=(0,v.useRef)(null),St=(0,v.useRef)(null),Ce=(0,v.useRef)(0),[A,bt]=(0,v.useState)(null),ut=(0,v.useRef)(null),[O,xe]=(0,v.useState)(null),Ot=(0,v.useMemo)(()=>r?(0,vt.serializeCreateParams)(r):"",[r]),be=r?`create:${Ot}`:`session:${e??""}`,_t=hc(O),b=(0,v.useRef)(new Set),M=(0,v.useRef)(be),Ae=(0,v.useRef)(be);wo(()=>{Ae.current=be,M.current!==be&&(M.current=be,b.current.clear())},[be]);let Pe=(0,v.useCallback)(N=>{if(Ae.current===be){if(os.FLO_INSTRUMENT_ONCE_NAMES.has(N.name)){if(b.current.has(N.name))return;b.current.add(N.name)}(0,Ye.invokeMerchantCallback)(()=>w?.(N))}},[be,w]),pt=Go(Pe,be),it=(0,v.useRef)(!1),Ve=(0,v.useCallback)(N=>{if(it.current)return;let j=N.gateway||!_t?N:{...N,gateway:_t};Pe(j)},[Pe,_t]);(0,v.useEffect)(()=>{pt({class:"lifecycle",name:"checkout.mount"})},[pt]);let[We,Dt]=(0,v.useState)(e??""),d=e??We,L=r?"":d,[z,se]=(0,v.useState)(!0),[E,q]=(0,v.useState)(null),[Nt,Br]=(0,v.useState)(0),[rr,$t]=(0,v.useState)("full"),[Tt,Wr]=(0,v.useState)(!1),[Nr,nr]=(0,v.useState)(Y),[Zr,Mt]=(0,v.useState)(null),[Ln,Jt]=(0,v.useState)(null),[fn,$r]=(0,v.useState)(!1),[Hr,Zt]=(0,v.useState)(void 0),[Cr,Qr]=(0,v.useState)(""),[rt,Et]=(0,v.useState)(!1),[Dr,Ht]=(0,v.useState)(!1),[or,br]=(0,v.useState)(!1),Qt=(0,v.useRef)(null),Kt=(0,v.useRef)(0),_r=(0,v.useRef)(void 0),[Ze,ar]=(0,v.useState)("loading"),[Tr,Jn]=(0,v.useState)(0),Ur=(0,v.useRef)(!1),zr=(0,v.useRef)(!1),Nn=(0,v.useRef)(!1),cn=(0,v.useRef)(null),ir=(0,v.useRef)(null),he=(0,v.useMemo)(()=>({checkoutMode:V??rr,layout:uu($,ae)}),[V,$,rr,ae]),Sr=(0,v.useRef)(h);Sr.current=h;let Kr=(0,v.useRef)(k);Kr.current=k;let re=(0,v.useRef)(I);re.current=I;let Bt=(0,v.useCallback)(N=>ci(cn,async j=>{try{return await N(j)}catch(ne){throw j.aborted?Xo(ne):ne}}),[]);(0,v.useEffect)(()=>()=>{cn.current?.abort(),cn.current=null},[]);let Q=(0,v.useCallback)((N,j)=>{Ft.current=N,mr(N),ut.current=j,bt(j)},[]),Gt=(0,v.useCallback)(()=>{let N=St.current;N&&(St.current=null,N.destroy())},[]);(0,v.useEffect)(()=>{Er(at)?.setCheckoutContext(he),A&&A!==at&&Er(A)?.setCheckoutContext(he)},[at,A,he]);let sr=(0,v.useRef)(fe);sr.current=fe;let ve=(0,v.useCallback)(N=>{ar(N),!(N!=="exhausted"||Nn.current)&&(Nn.current=!0,Kr.current?.(new De.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Wt=(0,v.useCallback)(()=>{ar("retrying"),Jn(N=>N+1)},[]);(0,v.useEffect)(()=>{ar("loading"),Jn(0),Nn.current=!1},[d]),(0,v.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:De.SDK_VERSION,checkout_type:Ne,checkout_layout:ot,billing_api_url:B})},[ot,Ne,B]);let oe=(0,v.useMemo)(()=>r?(0,vt.serializeCreateParams)(r,!0):"",[r]),Lt=(0,v.useMemo)(()=>Cr===oe?Hr:void 0,[Hr,Cr,oe]),wr=(0,v.useMemo)(()=>r?es(r,Lt):void 0,[r,Lt]),qr=V??wr?.checkoutMode??"full",er=(0,v.useMemo)(()=>wr?{...wr,checkoutMode:qr}:void 0,[wr,qr]);(0,v.useEffect)(()=>{Zt(void 0),Qr(oe),_r.current=void 0,Qt.current=null,br(!1)},[oe]),(0,v.useEffect)(()=>{nr(Y)},[Y]);let Un=(0,v.useCallback)((N,j,ne)=>{(0,Ye.invokeMerchantCallback)(()=>{re.current?.(kr(N,j,ne))})},[]),Zn=(0,v.useCallback)(async(N,j)=>{nr(null),Jt(null),$r(!1),Mt("processing");let ne=j?.sessionId??N.id,Se=N.clientSecret||t,gt=hc(N),Yt=Ft.current??ut.current,ke=Er(Yt),ie=Yt?null:Ei(B,a,he),te={log:y=>{ke?ke.log(y):ie?.log(y)},error:y=>{ke?ke.error(y):ie?.error(y)},terminal:y=>{ke?ke.terminal(y):ie?.terminal(y)},performance:y=>{ke?ke.performance(y):ie?.performance(y)},now:()=>ke?.now()??ie?.now()??0,elapsed:y=>ke?.elapsed(y)??Math.max(0,(ie?.now()??y)-y)},Qe=te.now(),Ee=!!(j?.initialAutoProcessingError||j?.initialAutoProcessingPending),st=!1,U,ue=()=>{st||(st=!0,Ee=!0,U=te.now(),te.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ht=!1,It=()=>{ht||(ht=!0,te.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),te.performance({stage:"processing",durationMs:te.elapsed(Qe),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),U!==void 0&&te.performance({stage:"recovery",durationMs:te.elapsed(U),durationMode:"machine",paymentMethodCategory:"saved"}))};te.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),it.current=!0;try{te.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{it.current=!1}pt({class:"lifecycle",name:"payment.processing.started",provider:gt}),Ee&&ue();let Rr;try{let y=$l(j?.initialAutoProcessingError),g=j?.initialAutoProcessingError?.type==="3ds_required"&&!j.initialAutoProcessingError.threeDSecureToken&&j.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:j.initialAutoProcessingError.nextActionRedirectUrl}:null,X,Ke=$e=>{ue();let Ue=Ea(B,ne,N,a!==!1);return Bt(et=>Jo($e,{billingApiUrl:B,sessionId:ne,nonce:Se,session:N,signal:et,...Ue.telemetry?{challengeTelemetry:Ue.telemetry}:{}})).finally(Ue.release)};if(g)X=await Ke(g);else if(y)ue(),y.type==="paypal_redirect_required"&&ir.current?.publishableKey&&fc({sessionId:ne,publishableKey:ir.current.publishableKey,paypalPublishableKey:ir.current.paypalPublishableKey}),X=await Bt($e=>ui(y,{flopay:Ft.current,paypalFlopay:ut.current,attempt3DS:j?.attempt3DS,billingApiUrl:B,sessionId:ne,session:N,telemetry:!1,signal:$e})),y.type==="paypal_redirect_required"&&ks();else if(j?.initialAutoProcessingPending){let $e=j.initialAutoProcessingPending,Ue=new co.PaymentAPI(B,{telemetry:!1}),et=await Bt(fr=>Ue.waitForCheckoutSessionCompletion($e.sessionId,{initialDelayMs:$e.retryAfterMs,nonce:Se,statusUrl:$e.statusUrl,signal:fr})),qt=fo(et,N),le=et.autoProcessingError?.type==="3ds_required"&&et.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:et.autoProcessingError.nextActionRedirectUrl}:null;if(le)X=await Ke(le);else{if(!oo(qt))throw Vo(qt);X=no(qt,ne)}}else{if(j?.initialAutoProcessingError)throw Kn(j.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.initialAutoProcessingError.checkoutMethod});if(j?.fromCreateSession)return j?.fallbackToFull&&($t("full"),gc("full")),!1;{let $e=await Zo({billingApiUrl:B,sessionId:ne,session:N,nonce:Se,telemetry:!1});$e.type==="success"?X=$e.result:$e.type==="next_action_required"?X=await Ke($e):(ue(),$e.type==="paypal_redirect_required"&&ir.current?.publishableKey&&fc({sessionId:ne,publishableKey:ir.current.publishableKey,paypalPublishableKey:ir.current.paypalPublishableKey}),X=await Bt(Ue=>ui($e,{flopay:Ft.current,paypalFlopay:ut.current,attempt3DS:j?.attempt3DS,billingApiUrl:B,sessionId:ne,session:N,telemetry:!1,signal:Ue})),$e.type==="paypal_redirect_required"&&ks())}}ne&&(0,Bn.markSessionRecentlyCompleted)(ne),It(),Ee&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),te.terminal({outcome:X.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),$r(X.status==="authorized"),Mt("success"),await Ba(600),Rr=()=>Sr.current?.(X)}catch(y){let g=yo(Ia(y),ne);if(g.code==="three_ds_aborted")return!1;let X=g.checkoutMethod??ka;nr(g.message),Jt(g.message),$r(!1),j?.fallbackToFull&&(te.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),$t("full"),gc("full")),It();let Ke=g.statusCode===void 0?void 0:(0,De.telemetryStatusClass)(g.statusCode,"unknown"),$e=Ke==="4xx"?{requestCategory:"process_payment",statusClass:Ke}:{},Ue=Ke===void 0||Ke==="4xx";if(Ue&&(g.telemetryOutcome==="payment_declined"||!!(g.declineCode||g.code?.toLowerCase().includes("declin"))))te.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...$e});else if(Ue&&(g.telemetryOutcome==="validation_rejected"||g.type==="validation_error"))te.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...$e});else{let le=(0,De.classifyTelemetryFailure)(y,Ee?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),fr=g.telemetryRequestCategory??"process_payment";it.current=!0;try{te.error({...le,...g.telemetryFailureCategory?{failureCategory:g.telemetryFailureCategory}:{},stage:Ee?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:fr})}finally{it.current=!1}pt({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:fr,provider:gt})}return(0,Ye.invokeMerchantCallback)(()=>Kr.current?.(g)),Un(X,g,{code:g.code,declineCode:g.declineCode}),Mt("error"),await Promise.allSettled([Ba(400),j?.ensureProvidersReady?j.ensureProvidersReady():Promise.resolve()]),Ee&&(te.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),te.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{It(),ie&&Da(ie),Mt(null),Jt(null)}return(0,Ye.invokeMerchantCallback)(Rr),!0},[Un,pt,t,B,Bt,a,he]);(0,v.useEffect)(()=>{if(typeof window>"u"||zr.current)return;let N=new URLSearchParams(window.location.search),j=N.get("payment_intent_client_secret");if(!j)return;let ne=cu();ne&&(zr.current=!0,(async()=>{let Se,gt=0;nr(null),Jt(null),Mt("processing"),Wr(!0);try{if(N.get("redirect_status")==="failed")throw Object.assign(new De.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Yt,paypalFlopay:ke}=await ls({publishableKey:ne.publishableKey,paypalPublishableKey:ne.paypalPublishableKey,billingApiUrl:B,locale:c,telemetry:a});Se=Er(ke??Yt),Se?.setCheckoutContext(he),gt=Se?.now()??0,Se?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Se?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let ie=(ke??Yt)?.getRawProvider();if(!ie)throw Object.assign(new De.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:te,error:Qe}=await ie.retrievePaymentIntent(j);if(Qe)throw Object.assign(new De.FloPayError(Qe.message??"Failed to retrieve PayPal payment status.","api_error",{code:Qe.code}),{checkoutMethod:"paypal"});let Ee=Ml(te?.status);if(!te||Ee==="failed")throw Object.assign(new De.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let st=typeof te.payment_method=="string"?te.payment_method:te.payment_method?.id,U=Ee;if(ne.sessionId){let It=(await new co.PaymentAPI(B,{telemetry:!1}).getUnifiedCheckoutSession(ne.sessionId)).data.session;if(It&&It.status!=="complete"){let Rr=await Zo({billingApiUrl:B,sessionId:ne.sessionId,session:It,telemetry:!1,tokenizedData:{id:st??te.id,type:"card",threeDSecureActionResultTokenId:te.id,isPaypal:!0}});if(Rr.type!=="success")throw Object.assign(new De.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});U=Rr.result.status}}ne.sessionId&&(0,Bn.markSessionRecentlyCompleted)(ne.sessionId),Se?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Se?.performance({stage:"redirect_resume",durationMs:Se.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Se?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Mt("success"),await Ba(600),(0,Ye.invokeMerchantCallback)(()=>Sr.current?.({status:U,paymentIntentId:te.id,paymentMethodId:st,checkoutMethod:"paypal"}))}catch(Yt){let ke=yo(Ia(Yt),ne.sessionId),ie=ke.checkoutMethod??"paypal",te=!!(ke.declineCode||ke.code?.toLowerCase().includes("declin"));if(Se)Se.performance({stage:"redirect_resume",durationMs:Se.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),te?Se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Se.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(te){let Qe=Ei(B,a,he);Qe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Da(Qe)}else Ss(B,a,he,"REDIRECT_RESUME_FAILED","redirect_resume");nr(ke.message),Jt(ke.message),(0,Ye.invokeMerchantCallback)(()=>Kr.current?.(ke)),Un(ie,ke,{code:ke.code,declineCode:ke.declineCode}),Mt("error"),await Ba(400)}finally{ks(),du(),Mt(null),Jt(null),Wr(!1)}})())},[Un,c,B,a,he]);let zn=(0,v.useRef)(null),qn=(0,v.useMemo)(()=>er?(0,vt.serializeCreateParams)(er):"",[er]),Qn=(0,v.useRef)(er);Qn.current=er,(0,v.useEffect)(()=>{Dt(e??"")},[e]),(0,v.useEffect)(()=>{Ur.current=!1,nr(Y),Jt(null),$r(!1),Mt(null)},[qn,Y,e]);async function po(N,j,ne){let Se=Ei(B,a,he),gt=new co.PaymentAPI(B,{telemetry:!1}),Yt=!1;try{let ke=N.idempotencyKey===void 0?void 0:(0,De.resolveIdempotencyKey)(N.idempotencyKey),ie=(0,vt.readCachedInlineSession)(j,ne),te=(0,vt.readCachedInlineIdempotencyKey)(j,ne);ie?.canonicalIdentity===ne&&te&&te.canonicalIdentity===void 0&&((0,vt.persistCachedInlineIdempotencyKey)(j,ne,te.idempotencyKey),te={...te,canonicalIdentity:ne});let Qe=ke??(te?.canonicalIdentity===ne?te.idempotencyKey:void 0),Ee,st=!1;Se.log({name:ie?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let U=ie?.sid??null,ue=null,ht,It,Rr=!1;if(U)try{ue=await gt.getUnifiedCheckoutSession(U,ie?.nonce),ie&&ie.canonicalIdentity===void 0&&((0,vt.legacyCachedSessionMatchesDraft)(ue.data.session,N)?((0,vt.persistCachedInlineSession)(j,ne,U,ie.nonce??ue.data.session?.clientSecret),te&&te.canonicalIdentity===void 0&&((0,vt.persistCachedInlineIdempotencyKey)(j,ne,te.idempotencyKey),Qe??(Qe=te.idempotencyKey))):((0,vt.clearCachedInlineCheckout)(j,ne),te=null,Qe=ke,U=null,ue=null));let g=ue?.data.session?.status,X=ue?.data.session,Ke=X?.clientSecret||ie?.nonce;if(U&&X?.buyerIdentified===!1&&Ke&&(It=jo(gt,U,Ke,N.account)),U&&ue&&g==="complete"){if((0,Bn.wasSessionRecentlyCompleted)(U))return{sid:U,result:ue};(0,vt.clearCachedInlineCheckout)(j,ne),U=null,ue=null,st=!0}}catch{Se.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ie?.canonicalIdentity===void 0?((0,vt.clearCachedInlineCheckout)(j,ne),Qe=ke):(0,vt.clearCachedInlineSession)(j,ne),U=null}if(!U){!ke&&(st||!Qe)&&(Qe=(0,De.resolveIdempotencyKey)(),Ee=Qe),Qe&&(0,vt.persistCachedInlineIdempotencyKey)(j,ne,Qe);let g=Se.now(),X=0;Se.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ke={...N,idempotencyKey:Qe,avsCheck:!!de,avsConfig:typeof de=="object"?de:void 0,checkoutType:"embedded_checkout",checkoutLayout:Es($,ae)};Object.defineProperty(Ke,co.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:et=>{X=Math.max(X,et)}}});let $e=()=>{mc(Se,"session_create",g,X)},Ue=et=>{yc(Se,et,"session_create",g,X)&&pt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,De.isDetachedSessionEligible)(Ke)){let et=await gt.createDetachedSession(Ke);et.claimed.catch(()=>{}),ue=et.shell,U=et.sessionId,It=et.claim;let qt=Se.now();Se.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ht=et.claimed.then(le=>{let fr=le.data.session?.id??et.sessionId;return fr&&(0,vt.persistCachedInlineSession)(j,ne,fr,le.data.session?.clientSecret??et.nonce),mc(Se,"session_claim",qt),$e(),le},le=>{throw(0,vt.clearCachedInlineSession)(j,ne),yc(Se,le,"session_claim",qt,0)&&pt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),le}).finally(()=>Da(Se)),ht.catch(()=>{}),Yt=!0,Se.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Se.performance({stage:"session_shell",durationMs:Se.now()-g,durationMode:"machine",requestCategory:"session_create",attempt:X,statusClass:"2xx",paymentMethodCategory:"card"})}else ue=await gt.createAndFetchSession(Ke),$e()}catch(et){throw Ue(et),et}U=ue.data.session?.id??U??"",U&&!ht&&(0,vt.persistCachedInlineSession)(j,ne,U,ue.data.session?.clientSecret)}let y=ue?.data.session;return!It&&U&&y?.buyerIdentified===!1&&y.clientSecret&&(It=jo(gt,U,y.clientSecret,N.account)),{sid:U??"",result:ue,sdkGeneratedIdempotencyKey:Ee,...ht?{claimed:ht}:{},...It?{claim:It}:{},...Rr?{claimRequiresIdentity:!0}:{}}}finally{Yt||Da(Se)}}let mo=(0,v.useRef)(po);wo(()=>{mo.current=po},[po]);let Or=(0,v.useCallback)(async(N,j)=>{let ne=Qn.current;if(!ne)throw new De.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Se=es(ne,N),gt=(0,vt.serializeCreateParams)(Se),Yt=(0,vt.hashCreateParams)(Se),ke=Ii.get(gt);if(!ke){let Qe={canonicalIdentity:gt,promise:mo.current(Se,Yt,gt),consumers:0,settled:!1};ke=Qe,Ii.set(gt,Qe);let Ee=()=>{Qe.settled=!0,pc(gt,Qe)};Qe.promise.then(Ee,Ee)}ke.consumers+=1;let ie=!1,te=()=>{ie||(ie=!0,ke.consumers-=1,pc(gt,ke))};j?.(te);try{let Qe=await ke.promise;zn.current=gt,N&&(Qr(oe),Zt(y=>Rl(y,N)));let{sid:Ee,result:st,claimed:U,claim:ue,claimRequiresIdentity:ht}=Qe;if(_r.current=ue,br(ht===!0),tt(st),st.data.session&&xe(st.data.session),Ee&&Dt(Ee),U){Kt.current+=1;let y=Kt.current;Qt.current=U,Ht(!0),U.then(g=>{Kt.current===y&&(Qt.current===U&&(Qt.current=null),tt(g),g.data.session&&xe(g.data.session),Ht(!1),br(!1))},g=>{Kt.current===y&&(Qt.current===U&&(Qt.current=null),Ht(!1),br(!1),q(g instanceof De.FloPayError?g:new De.FloPayError(g instanceof Error?g.message:"Failed to create session","api_error")))})}else Kt.current+=1,Qt.current=null,Ht(!1),br(!1);let{flopay:It,paypalFlopay:Rr}=await Rs(st,{billingApiUrl:B,locale:c,telemetry:a}).catch(y=>{throw Il(y,Ee||st.data.session?.id)});return Q(It,Rr),se(!1),Qe}catch(Qe){throw zn.current===gt&&(zn.current=null),Qe}finally{j||te()}},[oe,Q,c,B,a]),eo=(0,v.useRef)(Zn);eo.current=Zn;let gn=(0,v.useRef)(Or);gn.current=Or;let Ut=(0,v.useCallback)(async N=>{if(!pu(N)||rt)return{sessionId:We,session:O};Et(!0);try{let j=await Or(N);return{sessionId:j.sid,session:j.result.data.session??null}}finally{Et(!1)}},[Or,rt,We,O]),en=(0,v.useCallback)(async N=>{let j=_r.current;if(!j)return;let ne=Kt.current,Se=await j(N);Kt.current===ne&&(tt(Se),Se.data.session&&xe(Se.data.session))},[]),tn=(0,v.useCallback)(async()=>{await Qt.current},[]),dn=(0,v.useCallback)(async()=>(await tn(),{proceed:!0}),[tn]);(0,v.useEffect)(()=>{let N=!1,j,ne=++Ce.current;Gt(),q(null),Br(0);let Se=()=>{N=!0,Ce.current===ne&&(Ce.current+=1,Gt())},gt=Qn.current;if(qn&&gt)return $t(qr),se(!1),zn.current===qn?Se:(xe(kl(gt,V)),(async()=>{let ie=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),te=qr==="auto"&&!Ur.current&&!ie;te&&(nr(null),Jt(null),Mt("processing"));let Qe=!1;try{let Ee=await gn.current(void 0,ht=>{j=ht});Qe=!0;let st=Ee.result.data.session??null;ir.current=ss(Ee.result);let U=ws(Ee.result),ue=(0,Bn.wasSessionRecentlyCompleted)(Ee.sid||st?.id);if(!N&&te&&st&&!U&&!ue){Ur.current=!0,await iu(qn,Ee.sdkGeneratedIdempotencyKey,()=>eo.current(st,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Ee.result.autoProcessingError,initialAutoProcessingPending:Ee.result.autoProcessingPending,autoProcessingAttempted:Ee.result.autoProcessingAttempted,sessionId:Ee.sid||st.id}));return}!N&&te&&((U||ue)&&(Ur.current=!0),Mt(null),Jt(null))}catch(Ee){if(N)return;let st=Qa(Ee);if(te&&st==="session_auto_completed"){Ur.current=!0,Mt("success"),await Ba(600),N||((0,Ye.invokeMerchantCallback)(()=>{Sr.current?.({status:"succeeded"})}),Mt(null),Jt(null));return}if(te&&(Mt(null),Jt(null)),!Qe){let ue=_l(Ee),ht=(0,De.toPublicCheckoutInitError)(Ee,ue?{stage:"provider_load",provider:"stripe",...ue}:{stage:"session_request"});(ue||!(Ee instanceof De.FloPayError))&&(0,Ye.invokeMerchantCallback)(()=>Kr.current?.(ht)),q(ht);return}let U=Ee instanceof De.FloPayError?Ee:new De.FloPayError(Ee instanceof Error?Ee.message:"Failed to create session","api_error");q(U)}finally{j?.(),j=void 0}})(),()=>{Se(),j?.()});se(!0);async function Yt(){let ie=!1,te=!1,Qe=null;try{let Ee=new co.PaymentAPI(B,{telemetry:!1}),st=await Ee.getUnifiedCheckoutSession(d,t);if(te=!0,Qe=st,N)return;tt(st);let U=st.data.session??null;if(xe(U),!U)throw new De.FloPayError("No session data returned","api_error");let ue=U.checkoutMode;if(ue==="setup")throw new De.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(U.status==="authorized"){se(!1),(0,Ye.invokeMerchantCallback)(()=>{Sr.current?.(no(U,d)),sr.current?.(U.successUrl??"")});return}if(U.status==="complete"){se(!1),(0,Ye.invokeMerchantCallback)(()=>{sr.current?.(U.successUrl??"")});return}if(U.status==="expired")throw Za(U);ie=!0;let ht=V??ue??"full";$t(ht),Kt.current+=1;let It=U.clientSecret||t;_r.current=U.buyerIdentified===!1&&It?jo(Ee,d,It,{...U.customer?.id?{userId:U.customer.id}:{}}):void 0,Ht(!1),br(!1);let Rr=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),y=ws(st);if(ht==="auto"&&!Ur.current&&!Rr&&!y){Ur.current=!0;let g=ke(st);try{if(await eo.current(U,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>g,sessionId:d||U.id}),N)return;await g,N||se(!1);return}catch{if(N)return;await g,N||se(!1);return}}await ke(st),N||se(!1)}catch(Ee){if(N)return;let st=wl(Ee,ie);if(ie&&pt({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),st){let{errorCode:It,stage:Rr,...y}=st;Ss(B,a,he,It,Rr,y)}if(st?.stage==="provider_load"&&(V??Qe?.data.session?.checkoutMode??"full")==="full"&&Sl(Qe,F,f)){let It=lu({billingApiUrl:B,locale:c,telemetry:a});St.current=It,Q(It,null),Br(1),se(!1);return}let U=st?.stage==="provider_load",ue="session_request";U?ue="provider_load":te&&(ue="post_session");let ht=(0,De.toPublicCheckoutInitError)(Ee,{stage:ue,provider:"stripe",sessionId:d||void 0});(U||!(Ee instanceof De.FloPayError))&&(0,Ye.invokeMerchantCallback)(()=>Kr.current?.(ht)),q(ht),se(!1)}}async function ke(ie){let{flopay:te,paypalFlopay:Qe,...Ee}=await Rs(ie,{billingApiUrl:B,locale:c,telemetry:a});ir.current={publishableKey:Ee.publishableKey,paypalPublishableKey:Ee.paypalPublishableKey},Q(te,Qe),Br(0)}return Yt(),Se},[V,qn,qr,L,t,F,f]);let rn=(0,v.useCallback)(async()=>{if(!Me||Nt!==1)return;let N=Ce.current;Br(2);try{let{flopay:j,paypalFlopay:ne}=await Rs(Me,{billingApiUrl:B,locale:c,telemetry:a});if(Ce.current!==N)return;Gt(),Q(j,ne),Br(0)}catch(j){if(Ce.current!==N)return;let{errorCode:ne,stage:Se,...gt}=Qi(j);Ss(B,a,he,ne,Se,gt)}},[Gt,Q,c,Nt,B,a,he,Me]),mt=!!(d&&(O?.clientSecret||t)),yr=Tt||!mt,lr=(0,v.useCallback)(async()=>{if(!(Tt||!mt||!O)){Wr(!0),nr(null);try{await Zn(O,{attempt3DS:!0,fallbackToFull:!0,sessionId:d||O.id})}finally{Wr(!1)}}},[d,Tt,mt,Zn,O]),Gr=(0,De.resolveDirectPaypalConfig)(Me?.data.paypal,W),ho=ws(Me),to=(0,v.useMemo)(()=>{if(!(!Me||!O||!Me.data.stripe?.publishableKey))return{billingApiUrl:B}},[Me,O,B]),In=!!(r&&!$&&ae==="buttons"&&Le&&qr==="full"),un=!!(d&&((0,De.isMountableVaultBlock)(O?.vault)||(0,xn.canRecoverHostedCardForm)(O))),Mr=(0,v.useMemo)(()=>({session:O,loading:z,error:E,checkoutMode:rr,inlineSessionDraft:er,applyInlineSessionPatch:In?Ut:void 0,inlineSessionPatchProcessing:rt,claimPending:Dr,claimRequiresIdentity:or,claimBuyerIdentity:en,waitForDataAttachment:tn}),[O,z,E,rr,er,In,Ut,rt,Dr,or,en,tn]),ro=!!r&&ae==="buttons"&&!ho&&!un&&(!at||!to),jr=Zr?(0,D.jsx)(sn,{status:Zr,errorMessage:Ln,authorized:fn}):null;if(z&&!un){if(p)return(0,D.jsxs)(D.Fragment,{children:[p,jr]});if(ae==="buttons"){let N=ge?.buttonsLayout?.cardButton?.borderRadius??ge?.appearance.variables?.borderRadius??8,j=ne=>(0,D.jsx)("div",{style:{height:ne,borderRadius:N,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:[F&&j(ta),f&&(S||Te)&&j(ta),f&&j(ta),(0,D.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),jr]})}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); } }"})]}),jr]})}return E?m?(0,D.jsx)(An.Provider,{value:Mr,children:m(E)}):(0,D.jsx)(An.Provider,{value:Mr,children:(0,D.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:E.message})}):ro?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(An.Provider,{value:Mr,children:(0,D.jsx)(yu,{onButtonClick:Je,showPayPal:F,showStripe:f,showApplePay:S,showGooglePay:Te,theme:ye,buttonsTheme:pe,buttonsStyles:Re,cardButtonContent:dt,cardBackButtonContent:Ge,cardTitleContent:x})}),jr]}):ho&&O&&Gr?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(An.Provider,{value:Mr,children:(0,D.jsxs)("div",{className:je,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Nr&&(0,D.jsx)(Yo,{icon:!1,children:Nr}),Ze==="retrying"&&(0,D.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ze==="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:Wt,children:"Retry PayPal"})]}),Ze!=="exhausted"&&(0,D.jsx)("div",{"aria-hidden":Ze==="retrying"?!0:void 0,style:Ze==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,D.jsx)(ql,{sessionId:d,nonce:O.clientSecret||void 0,billingApiUrl:B,email:O.customer?.email||er?.account?.email,billingName:[O.customer?.firstName,O.customer?.lastName].filter(Boolean).join(" ")||[er?.account?.firstName,er?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:en,clientId:Gr.clientId,environment:Gr.environment,currency:(O.currency??"usd").toUpperCase(),isSubscription:O.mode==="subscription",providerObjectType:Gr.providerObjectType,approvalPresentation:Gr.approvalPresentation,existingOrderId:Gr.existingOrderId,onComplete:h,onErrorChange:nr,onDecline:I,onCancel:G,onButtonClick:Je,runBeforeButtonClick:dn,onInitializationStateChange:ve,allowAutomaticRetry:Tr===0,session:O,telemetry:a,telemetryContext:he,onInstrument:Ve,debug:T},`${be}:paypal-init-${Tr}`)})]})}),jr]}):rr==="confirm"?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(An.Provider,{value:Mr,children:(0,D.jsx)(wa,{flopay:at,paypalFlopay:A,options:to??{billingApiUrl:B},onInstrument:Ve,children:(0,D.jsxs)("div",{className:je,children:[Nr&&(0,D.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Nr}),Be?Be({onConfirm:lr,isProcessing:yr}):(0,D.jsx)("button",{type:"button",onClick:lr,disabled:yr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:yr?"not-allowed":"pointer",opacity:yr?.6:1},children:Tt?"Processing...":He??"Confirm Purchase"})]})},be)}),jr]}):(!at||!to)&&!(un&&rr==="full")?(0,D.jsx)(D.Fragment,{children:jr}):(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(An.Provider,{value:Mr,children:(0,D.jsxs)(wa,{flopay:at,paypalFlopay:A,options:to??{billingApiUrl:B},onInstrument:Ve,children:[Nt===1&&(0,D.jsx)("button",{type:"button",onClick:rn,children:"Retry payment methods"}),$?(0,D.jsxs)(D.Fragment,{children:[Nr&&(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:Nr}),(0,D.jsx)(mu,{sessionId:d,nonce:O?.clientSecret||void 0,billingApiUrl:B,session:O,submitLabel:nt,walletPresentation:P,children:$})]}):(0,D.jsx)(Ri,{sessionId:d,nonce:O?.clientSecret||void 0,telemetry:a,email:O?.customer?.email||er?.account?.email,userId:O?.customer?.id||er?.account?.userId,firstName:O?.customer?.firstName||er?.account?.firstName,lastName:O?.customer?.lastName||er?.account?.lastName,totalAmount:O?Math.round((0,De.buildCheckoutDisplayData)(O).total*100):0,currency:O?.currency?.toLowerCase()??"usd",onComplete:h,onError:k,onDecline:I,onCancel:G,error:Nr,onErrorChange:nr,showPayPal:F,showStripe:f,walletPresentation:P,enabledPaymentMethods:Nt?[]:me??Me?.data.stripe?.enabledPaymentMethods??O?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Me?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:Te,layout:ae,theme:ye,buttonsTheme:pe,buttonsStyles:Re,appearance:ft,cardButtonContent:dt,cardBackButtonContent:Ge,cardTitleContent:x,onButtonClick:Je,onBeforeButtonClick:Le,onBuyerIdentityReady:en,enableAVS:de,...ee?{cardFieldOrder:ee}:{},...H?{cardPreFormSlot:H}:{},avsLayout:Oe,country:O?.customer?.country,city:O?.customer?.city,state:O?.customer?.state,onCountryChange:_,onZipChange:Z,avsCheck:!!de,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Es($,ae),className:je,submitLabel:nt,directPaypal:Gr,isSubscription:O?.mode==="subscription",session:O,dataAttachmentPending:Dr,dataAttachmentRequiresIdentity:or,debug:T})]},be)}),jr]})}function mu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,children:c}){return(0,D.jsx)(D.Fragment,{children:v.default.Children.map(c,p=>{if(!v.default.isValidElement(p))return p;let m=p.props,h={};return m.sessionId||(h.sessionId=e),!m.nonce&&t&&(h.nonce=t),m.billingApiUrl||(h.billingApiUrl=r),m.submitLabel===void 0&&a!==void 0&&(h.submitLabel=a),m.walletPresentation===void 0&&(h.walletPresentation=s),n?.customer&&(m.email||(h.email=n.customer.email),m.userId||(h.userId=n.customer.id),m.firstName||(h.firstName=n.customer.firstName),m.lastName||(h.lastName=n.customer.lastName)),Object.keys(h).length===0?p:v.default.cloneElement(p,h)})})}function yu({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:s,buttonsTheme:c,buttonsStyles:p,cardButtonContent:m,cardBackButtonContent:h,cardTitleContent:k}){let[w,I]=(0,v.useState)(!1),G=(0,v.useMemo)(()=>(0,De.resolveTheme)(s),[s]),_=(0,v.useMemo)(()=>{let P=G?.buttonsLayout??(0,De.resolveButtonsLayoutTheme)(c);return p?{...P,...p,cardButton:{...P.cardButton,...p.cardButton},cardFormContainer:{...P.cardFormContainer,...p.cardFormContainer},backButton:{...P.backButton,...p.backButton},backButtonIcon:{...P.backButtonIcon,...p.backButtonIcon},submitButton:{...P.submitButton,...p.submitButton},title:{...P.title,...p.title}}:P},[G,c,p]),Z=G?.buttonsLayout?.cardButton?.borderRadius??G?.appearance.variables?.borderRadius??8,F=P=>(0,D.jsx)("div",{style:{height:P,borderRadius:Z,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),f=m===void 0?{boxSizing:"border-box",height:ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(w){let P=_.cardInputBorder??"#e5e7eb",me=_.cardInputBackground??"white",S=Uo(h),Te=Uo(k);return(0,D.jsxs)("div",{style:{backgroundColor:_.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",..._.cardFormContainer},children:[(0,D.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,D.jsxs)("button",{type:"button",onClick:()=>I(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:S?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",..._.backButton},children:[(0,D.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",..._.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)(qo,{content:h})]}),Te?(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,..._.title},children:(0,D.jsx)(fa,{content:k})})]}),(0,D.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${P}`,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:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,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:me,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,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:me,border:`1px solid ${P}`,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",..._.submitButton,opacity:.5}}),(0,D.jsx)("style",{children:`
41
41
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
42
42
  @keyframes flopay-interim-expand {
43
43
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
44
44
  40% { opacity: 1; }
45
45
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
46
46
  }
47
- `})]})}return(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&A(ta),r&&(n||a)&&A(ta),r&&(0,F.jsx)("button",{type:"button",onClick:()=>{e?.("card"),I(!0)},style:{width:"100%",...f,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:_.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,..._.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,F.jsx)(zo,{content:m})}),(0,F.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var wn=require("react/jsx-runtime"),yu=44;function hc(e){return new Promise(t=>setTimeout(t,e))}function fu(e,t){return e instanceof Rn.FloPayError?e:new Rn.FloPayError(e instanceof Error?e.message:t,"api_error")}function gu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function hu(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function Pc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:s,products:c,items:p,subscriptions:m,account:h,successUrl:k,cancelUrl:w,couponCodes:I,tagsData:G,utmMetadata:_,billingApiUrl:Z,locale:A,theme:f,appearance:P,buttonsTheme:me,buttonsStyles:S,onSuccess:Te,onError:T,onDecline:ae,children:ye,disabled:pe=!1,type:we="button",style:dt,...Ke}){let B=(0,Ct.useMemo)(()=>(0,Rn.resolveBillingApiUrl)(Z),[Z]),kt=(0,Ct.useMemo)(()=>hu({createSession:r,clientId:s,products:c,items:p,subscriptions:m,account:h,successUrl:k,cancelUrl:w,couponCodes:I,tagsData:G,utmMetadata:_}),[h,w,s,I,r,c,p,m,k,G,_]),[Je,Le]=(0,Ct.useState)(!1),[de,ee]=(0,Ct.useState)(null),[H,Oe]=(0,Ct.useState)(null),[nt,qe]=(0,Ct.useState)(!1),[Y,W]=(0,Ct.useState)(null),[$,j]=(0,Ct.useState)(null),Ve=(0,Ct.useRef)(!0),Be=(0,Ct.useRef)(null),fe=(0,Ct.useRef)($),D=(0,Ct.useRef)(Te),ge=(0,Ct.useRef)(T),ft=(0,Ct.useRef)(ae),Ne=(0,Ct.useCallback)(b=>li(Be,async x=>{try{return await b(x)}catch(Ae){throw x.aborted?Xo(Ae):Ae}}),[]);(0,Ct.useEffect)(()=>{fe.current=$},[$]),(0,Ct.useEffect)(()=>{D.current=Te},[Te]),(0,Ct.useEffect)(()=>{ge.current=T},[T]),(0,Ct.useEffect)(()=>{ft.current=ae},[ae]),(0,Ct.useEffect)(()=>(Ve.current=!0,()=>{Ve.current=!1,Be.current?.abort()}),[]),(0,Ct.useEffect)(()=>{if(typeof window>"u")return;let b=x=>{x.key==="Escape"&&j(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let ot=(0,Ct.useCallback)((b,x=ka)=>{ft.current?.(kr(x,b,{code:b.code,declineCode:b.declineCode}))},[]),Me=(0,Ct.useCallback)(async b=>{Ve.current&&(Oe(null),qe(b.result.status==="authorized"),ee("success"),await hc(600),Ve.current&&(0,Ye.invokeMerchantCallback)(()=>D.current?.(b)))},[]),et=(0,Ct.useCallback)(async(b,x)=>{Ve.current&&(ge.current?.(b),x?.emitDecline&&ot(b,x.method),Oe(b.message),qe(!1),ee("error"),await hc(400))},[ot]),at=(0,Ct.useCallback)(async(b,x,Ae)=>{let Re=b.data.session??null;if(!Re)throw yo(new Rn.FloPayError("No session data returned","api_error"),x);let pt=Re.clientSecret||t;if(oo(Re)){await Me({result:no(Re,x),session:Re,sessionId:Re.id||x,autoCompleted:!1});return}if(Re.status==="expired")throw yo(Ja(Re),Re.id||x);try{if(b.autoProcessingPending){let We=b.autoProcessingPending,Ge=new _i.PaymentAPI(B),Dt=await Ne(V=>Ge.waitForCheckoutSessionCompletion(We.sessionId,{initialDelayMs:We.retryAfterMs,nonce:pt,statusUrl:We.statusUrl,signal:V})),d=fo(Dt,Re),L=Dt.autoProcessingError?.type==="3ds_required"&&Dt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Dt.autoProcessingError.nextActionRedirectUrl}:null;if(L&&x&&pt){let V=await Ne(se=>Jo(L,{billingApiUrl:B,sessionId:x,nonce:pt,session:Re,signal:se,telemetry:!0}));await Me({result:V,session:Re,sessionId:Re.id||x,autoCompleted:!1});return}if(Dt.autoProcessingError)throw Kn(Dt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Dt.autoProcessingError.checkoutMethod});if(!oo(d))throw Vo(d);await Me({result:no(d,x),session:d,sessionId:d.id||x,autoCompleted:!1});return}if(b.autoProcessingError){let We=b.autoProcessingError.nextActionRedirectUrl;if(b.autoProcessingError.type==="3ds_required"&&We&&x&&pt){let Ge=await Ne(V=>$l({billingApiUrl:B,sessionId:x,nonce:pt,nextActionRedirectUrl:We,signal:V}));if(Ge.status==="declined")throw Kn({type:Ge.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ge.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let d=await new _i.PaymentAPI(B).waitForCheckoutSessionCompletion(x,{initialDelayMs:0,nonce:pt}),L=fo(d,Re);if(!oo(L))throw Kn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await Me({result:no(L,x),session:L,sessionId:L.id||x,autoCompleted:!1});return}throw Kn(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(Ae?.fromCreateSession&&b.autoProcessingAttempted===!0)throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let it=await Zo({billingApiUrl:B,sessionId:x??Re.id,session:Re,nonce:pt});if(it.type==="next_action_required"&&pt){let We=x??Re.id,Ge=await Ne(Dt=>Jo(it,{billingApiUrl:B,sessionId:We,nonce:pt,session:Re,signal:Dt,telemetry:!0}));await Me({result:Ge,session:Re,sessionId:Re.id||We,autoCompleted:!1});return}if(it.type!=="success")throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Me({result:it.result,session:Re,sessionId:Re.id||x,autoCompleted:!1})}catch(it){let We=Re.id||x,Ge=yo(Ea(it),We);if(Ge.code==="three_ds_aborted")return;if(Ge.code==="checkout_processing_timeout"){if(!Ve.current)return;W(Ge.message),(0,Ye.invokeMerchantCallback)(()=>ge.current?.(Ge));return}await et(Ge,{emitDecline:!0,method:Ge.checkoutMethod??ka}),gu(Ge,We)&&We&&Ve.current&&j({sessionId:We,errorMessage:Ge.message,nonce:pt||void 0,payPalOrderId:Ge.orderId})}},[t,B,Ne,et,Me]),mr=(0,Ct.useCallback)(async b=>{if(Ke.onClick?.(b),!(b.defaultPrevented||pe||Je)){if(j(null),W(null),e&&kt){let x=new Rn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await et(x),Ve.current&&(ee(null),Oe(null));return}if(!e&&!kt){let x=new Rn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await et(x),Ve.current&&(ee(null),Oe(null));return}Le(!0),Oe(null),qe(!1),ee("processing");try{let x=new _i.PaymentAPI(B);if(e){let Ae=await x.getUnifiedCheckoutSession(e,t);await at(Ae,e);return}try{let Ae=await x.createAndFetchSession({...kt});await at(Ae,Ae.data.session?.id??null,{fromCreateSession:!0})}catch(Ae){if(Za(Ae)==="session_auto_completed"){await Me({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ae}}catch(x){await et(yo(fu(x,"Automatic payment failed. Please try again."),e))}finally{Ve.current&&(ee(null),Oe(null),Le(!1))}}},[Ke.onClick,kt,pe,Je,t,at,B,e,et,Me]),Ft=(0,Ct.useCallback)(b=>{let x=fe.current;j(null),D.current?.({result:b,session:null,sessionId:x?.sessionId??null,autoCompleted:!1})},[]),St=(0,Ct.useCallback)(b=>{ge.current?.(b)},[]),ve=(0,Ct.useCallback)(b=>{ft.current?.(b)},[]),M=(0,Ct.useMemo)(()=>(0,Rn.resolveTheme)(f),[f]),bt=(0,Ct.useMemo)(()=>{let b=M?.buttonsLayout??(0,Rn.resolveButtonsLayoutTheme)(me);return S?{...b,...S,cardButton:{...b.cardButton,...S.cardButton}}:b},[M,me,S]),ut=(0,Ct.useMemo)(()=>{let b=M?.appearance;return P?b?{...b,...P,variables:{...b.variables,...P.variables}}:P:b},[P,M]),O=ut?.variables,xe=O?.colorPrimary??"#4A49FF",Ot=O?.colorPrimaryHover??(0,Cs.darkenHex)(xe,.12),Ce=O?.borderRadius??"8px";return(0,wn.jsxs)(wn.Fragment,{children:[(0,wn.jsx)("button",{...Ke,type:we,onClick:mr,disabled:pe||Je,"aria-busy":Je,style:{width:"100%",...ye===void 0?{boxSizing:"border-box",height:yu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...bt.cardButton,...vs({themeBundle:M,resolvedPrimaryColor:xe,resolvedBorderRadius:Ce,submitButtonStyle:bt.submitButton,explicitPrimaryColor:O?.colorPrimary}),fontSize:bt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:pe||Je?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:pe||Je?.6:1,...dt},onMouseEnter:b=>{Ke.onMouseEnter?.(b),!b.defaultPrevented&&!pe&&!Je&&(M||O?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Ot)},onMouseLeave:b=>{Ke.onMouseLeave?.(b),!b.defaultPrevented&&(M||O?.colorPrimary)&&(b.currentTarget.style.backgroundColor=xe)},onMouseDown:b=>{Ke.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{Ke.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:(0,wn.jsx)(zo,{content:ye})}),Y&&(0,wn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Y}),de&&(0,wn.jsx)(an,{status:de,errorMessage:H,authorized:nt}),$&&(0,wn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:b=>{b.target===b.currentTarget&&j(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,wn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,wn.jsx)(Ii,{sessionId:$.sessionId,nonce:$.nonce,checkoutMode:"full",billingApiUrl:B,locale:A,theme:f,...ut?{appearance:ut}:{},buttonsTheme:me,buttonsStyles:S,initialErrorMessage:$.errorMessage,initialPayPalOrderId:$.payPalOrderId,cardTitleContent:null,onComplete:Ft,onError:St,onDecline:ve})})})]})}var Mi=require("@flopay/js/card-setup"),Yr=require("@flopay/shared"),Vt=require("react");var _s=require("@flopay/shared"),Pu=require("@flopay/shared");function Ti(e){let t=(0,_s.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Yn=require("react/jsx-runtime"),Da=class extends Yr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function uo(e,t={}){let r=e instanceof Yr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new Da(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:a,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}function vc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:c,buttonsStyles:p,loading:m=null,onReady:h,onComplete:k,onDecline:w,onCancel:I,onValidation:G,onError:_}){let[Z,A]=(0,Vt.useState)(null),[f,P]=(0,Vt.useState)(null),[me,S]=(0,Vt.useState)(null),[Te,T]=(0,Vt.useState)(null),[ae,ye]=(0,Vt.useState)(null),pe=(0,Vt.useRef)(!1),we=(0,Vt.useRef)(!1),{vaultTheme:dt,surface:Ke,overlayTheme:B}=(0,Vt.useMemo)(()=>Ti({theme:a,appearance:c,buttonsStyles:p}),[a,c,p]),kt=(0,Vt.useMemo)(()=>(0,Ta.mergeCardSetupSurface)(Ke,s),[Ke,s]),Je=(0,Vt.useRef)(h),Le=(0,Vt.useRef)(_),de=(0,Vt.useRef)(k),ee=(0,Vt.useRef)(w),H=(0,Vt.useRef)(I),Oe=(0,Vt.useRef)(G),nt=(0,Vt.useRef)(!1),qe=(0,Vt.useRef)(!1),Y=(0,Vt.useRef)(0);return Je.current=h,Le.current=_,de.current=k,ee.current=w,H.current=I,Oe.current=G,(0,Vt.useEffect)(()=>{let W=Y.current+1;return Y.current=W,()=>{queueMicrotask(()=>{Y.current===W&&(nt.current||qe.current||(qe.current=!0,(0,Ye.invokeMerchantCallback)(()=>{H.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Vt.useEffect)(()=>{let W=!0,$=(0,Yr.resolveBillingApiUrl)(r),j=new Mi.PaymentAPI($,{telemetry:n});return A(null),P(null),S(null),nt.current=!1,qe.current=!1,(async()=>{try{if(!e.trim())throw new Yr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Yr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Ve=await j.getUnifiedCheckoutSession(e,t);if(!W)return;let Be=Ve.data.session;if(!Be||!(0,Yr.isCardSetupCheckoutSession)(Be))throw new Yr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let fe=Be.vault;(0,Yr.isMountableVaultBlock)(fe)||(fe=await j.getVaultCapture(e,t));let D=(0,Yr.resolveVaultMountOptions)(fe,{billingApiUrl:$,sessionId:e,nonce:t});if(!D)throw new Yr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!W)return;P(D),A(new Mi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(Ve){if(!W)return;let Be=uo(Ve);nt.current=!0,S(Be),(0,Ye.invokeMerchantCallback)(()=>Le.current?.(Be))}})(),()=>{W=!1,j.destroy()}},[r,t,e,n]),(0,Vt.useEffect)(()=>{if(!Z)return;let W=!1;we.current=!1,pe.current=!1;let $=Z.on("submitting",()=>{pe.current=!0,ye(null),T("processing")}),j=Z.on("complete",fe=>{nt.current=!0,pe.current=!1,T("success"),(async()=>(await new Promise(D=>setTimeout(D,600)),!we.current&&(we.current=!0,(0,Ye.invokeMerchantCallback)(()=>{de.current?.({status:"succeeded",sessionId:e,...fe.paymentMethod?{paymentMethod:fe.paymentMethod}:{}})}),W||T(null))))()}),Ve=Z.on("decline",fe=>{nt.current=!0,pe.current=!1,ye(fe.message??null),T("error"),(0,Ye.invokeMerchantCallback)(()=>{ee.current?.({status:"declined",sessionId:e,...fe.declineReason?{reason:fe.declineReason}:{},...fe.message?{message:fe.message}:{}})}),(async()=>(await new Promise(D=>setTimeout(D,400)),W||T(null)))()}),Be=Z.on("challenge_dismissed",()=>{T(null)});return()=>{W=!0,$(),j(),Ve(),Be()}},[Z,e]),me?(0,Yn.jsx)("div",{role:"alert",children:me.message}):!Z||!f?.html?(0,Yn.jsx)(Yn.Fragment,{children:m}):(0,Yn.jsxs)(Yn.Fragment,{children:[Te&&(0,Yn.jsx)(an,{status:Te,errorMessage:ae,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...B?{theme:B}:{}}),(0,Yn.jsx)(go,{capture:Z,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:dt,containerStyle:kt,onReady:()=>{(0,Ye.invokeMerchantCallback)(()=>Je.current?.())},onValidation:W=>{(0,Ye.invokeMerchantCallback)(()=>Oe.current?.(W))},onError:W=>{if(!W)return;pe.current&&(pe.current=!1,ye(W),T("error"),setTimeout(()=>T(null),400));let $=uo(new Error(W),{code:"card_setup_widget_failed",retryable:!0});(0,Ye.invokeMerchantCallback)(()=>Le.current?.($))}})]})}var Cc=require("@flopay/js/card-setup"),kn=require("@flopay/shared"),bc=require("@paypal/paypal-js"),Io=require("react");var wc=require("react/jsx-runtime");function Sc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:c,customer:{userId:p,email:m},onSubmitting:h,onConfirmed:k,onFailed:w,onAbandoned:I}){let G=(0,Io.useRef)(null),_=(0,Io.useRef)({onSubmitting:h,onConfirmed:k,onFailed:w,onAbandoned:I});_.current={onSubmitting:h,onConfirmed:k,onFailed:w,onAbandoned:I};let[Z]=(0,Io.useState)(()=>(0,$n.detectPayPalEnvironment)().inAppBrowser);return(0,Io.useEffect)(()=>{let A=!0,f,P=new Cc.PaymentAPI(s,{telemetry:c}),me={userId:p,email:m};return(async()=>{try{let S=await(0,bc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Te=G.current;if(!A||!Te)return;if(!S?.Buttons)throw new kn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let T=S.Buttons({createVaultSetupToken:async()=>{_.current.onSubmitting();let ae=await P.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:kn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,kn.isSettledSessionIntent)(ae))throw(0,kn.settledSessionIntentError)(n);if(ae.provider!=="paypal"||ae.providerObjectType!=="setup_token")throw new kn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ae.providerObjectId},onApprove:async ae=>{let ye=ae.vaultSetupToken;if(!ye)throw new kn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let pe=await P.processPayment(me.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:ye,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:kn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:me});if(!pe.ok)throw new kn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:pe.status});A&&_.current.onConfirmed()},onCancel:()=>{A&&_.current.onAbandoned()},onError:ae=>{if(!A)return;let{popupBlocked:ye}=(0,Se.classifyExternalMethodFailure)(ae,{inAppBrowser:Z,handoffObserved:!1});_.current.onFailed(ye?new Error((0,Se.buildExternalMethodRecoveryMessage)("PayPal",!0,Z)):ae,{code:ye?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>T.close(),await T.render(Te)}catch(S){if(!A)return;_.current.onFailed(S,{code:"paypal_unavailable",retryable:!0})}})(),()=>{A=!1,f?.().catch(()=>{}),P.destroy()}},[s,e,r,m,t,Z,a,n,c,p]),(0,wc.jsx)("div",{ref:G,"data-flopay-paypal-setup":""})}var kc=require("@flopay/js/card-setup"),En=require("@flopay/shared"),Xn=require("@stripe/react-stripe-js"),Ec=require("@stripe/stripe-js"),Xr=require("react");var Vr=require("react/jsx-runtime"),Ic={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Ts=new Map;function vu(e){let t=Ts.get(e);if(t)return t;let r=(0,Ec.loadStripe)(e).catch(n=>{throw Ts.delete(e),n});return Ts.set(e,r),r}function Cu(e){return e?(0,En.toStripeAppearance)(e):void 0}function bu(e){return(0,Se.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Rc(e){return e==="paypal"?"PayPal":(0,En.getStripeMethodDisplayName)(e)}function Su(){return typeof window>"u"?"":window.location.href}var wu={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function _c(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:c}=e,[p]=(0,Xr.useState)(()=>vu(t)),m=(0,Xr.useMemo)(()=>{let h=Cu(c),k=(0,En.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:Ic[r]?.types??[r],...k?{setupFutureUsage:k}:{},...h?{appearance:h}:{}}},[c,n,a,s,r]);return(0,Vr.jsx)(Xn.Elements,{stripe:p,options:m,children:(0,Vr.jsx)(Ru,{...e})})}function Ru({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:c,themeId:p,buttonsLayout:m,onSubmitting:h,onConfirmed:k,onDeclined:w,onFailed:I,onValidation:G,onUnavailable:_}){let Z=(0,Xn.useStripe)(),A=(0,Xn.useElements)(),[f,P]=(0,Xr.useState)(!1),[me,S]=(0,Xr.useState)("loading"),[Te,T]=(0,Xr.useState)(!1),[ae,ye]=(0,Xr.useState)(!1),pe=(0,Xr.useRef)(!1),[we]=(0,Xr.useState)(()=>(0,$n.detectPayPalEnvironment)()),[dt,Ke]=(0,Xr.useState)(!1),B=(0,Xr.useCallback)((H,Oe)=>{if((0,Se.classifyExternalMethodFailure)(H,{inAppBrowser:we.inAppBrowser,handoffObserved:!1}).popupBlocked){Ke(!0),I(new Error((0,Se.buildExternalMethodRecoveryMessage)(Rc(e),!0,we.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}I(Oe.message===void 0?H:new Error(Oe.message),{code:Oe.code,retryable:!0})},[we.inAppBrowser,e,I]),kt=(0,Xr.useCallback)(async H=>{let Oe=!1,nt=!1,qe=()=>{!H||Oe||nt||(nt=!0,H.paymentFailed({reason:"fail"}))};if(!Z||!A||pe.current){qe();return}pe.current=!0,P(!0);try{let Y=await A.submit();if(Y.error){qe(),G(Y.error.message??null);return}h();let W=await new kc.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,En.isSettledSessionIntent)(W))throw(0,En.settledSessionIntentError)(r);if(W.provider!=="stripe"||W.intentKind!=="setup")throw new En.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Oe=!0;let $=await Z.confirmSetup({elements:A,clientSecret:W.clientSecret,confirmParams:{return_url:Su()},redirect:"if_required"});if($.error){bu($.error)?w({...$.error.decline_code||$.error.code?{reason:$.error.decline_code??$.error.code}:{},...$.error.message?{message:$.error.message}:{}}):B($.error,{code:"payment_method_setup_provider_failed",message:$.error.message??"The payment method could not be saved."});return}k()}catch(Y){qe(),B(Y,{code:"payment_method_setup_failed"})}finally{pe.current=!1,P(!1)}},[a,t,A,e,n,k,w,h,G,B,r,Z,s]),Je=Ic[e]?.wallet,Le=Je==="paypal"&&(0,Hn.resolveStripePayPalPresentation)(we,"auto",dt?"blocked":we.popupCapability)==="redirect",de=c?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&Je&&!Le)return(0,Vr.jsxs)(Vr.Fragment,{children:[(0,Vr.jsx)(ea,{}),(0,Vr.jsx)(_a,{state:me,borderRadius:de,children:(0,Vr.jsx)(Xn.ExpressCheckoutElement,{options:{...yi,paymentMethods:mi([e])},onReady:H=>{let Oe=Ia(H,[Je]);S(Oe),Oe==="unavailable"&&_()},onLoadError:()=>{S("load_error"),_()},onConfirm:H=>{kt(H)}})})]});let ee=Rc(e);return(0,Vr.jsxs)(Vr.Fragment,{children:[Te?(0,Vr.jsx)(pi,{method:e,themeId:p,hasNextStep:!0,highlighted:ae,disabled:f,onClick:()=>ye(H=>!H),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:de}):null,(0,Vr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ae,style:ae?{display:"flex",flexDirection:"column"}:wu,children:[(0,Vr.jsx)(Xn.PaymentElement,{options:{layout:fi},onReady:()=>T(!0),onLoadError:()=>_(),onChange:H=>{H.complete&&G(null)}}),(0,Vr.jsx)(gi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!Z||!A||f||!ae,onClick:()=>{kt()},color:c?.variables?.colorPrimary??"#4A49FF",borderRadius:c?.variables?.borderRadius??"8px",style:m?.submitButton,children:f?"Saving\u2026":`Save ${ee}`})]})]})}var Oa=require("@flopay/js/card-setup"),Ir=require("@flopay/shared"),Xe=Ji(require("react"),1);var ra=require("@flopay/js/card-setup"),Fr=require("@flopay/shared");var pr=require("react/jsx-runtime"),ku=15,Eu=2e3;function Iu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Ms(e){return new Promise(t=>setTimeout(t,e))}async function _u(e,t,r){if(!t.trim())throw new Ir.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Ir.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,Ir.isCardSetupCheckoutSession)(a))throw new Ir.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Fr.readSetupAdvertisement)(n);if(!(0,Fr.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:c}=s,p=c.length>0?`FloPay: this setup session advertises only Stripe methods (${c.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new Ir.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function Tu(e,t,r,n,a){let s=t.vault??null;(0,Ir.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let c=(0,Ir.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!c)throw new Ir.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return c}var xi=class extends Xe.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function Tc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:c="modern-light",containerStyle:p,appearance:m,buttonsStyles:h,loading:k=null,onReady:w,onComplete:I,onDecline:G,onCancel:_,onValidation:Z,onError:A}){let[f]=(0,Xe.useState)(ra.readSetupRedirectReturn),[P,me]=(0,Xe.useState)(null),[S,Te]=(0,Xe.useState)(!1),[T,ae]=(0,Xe.useState)(null),[ye,pe]=(0,Xe.useState)(null),[we,dt]=(0,Xe.useState)(null),[Ke,B]=(0,Xe.useState)(null),[kt,Je]=(0,Xe.useState)(()=>new Set),Le=(0,Xe.useRef)(kt),de=(0,Xe.useRef)(null);de.current=P;let ee=(0,Xe.useRef)(!1),H=(0,Xe.useRef)(!1),Oe=(0,Xe.useRef)(!1),nt=(0,Xe.useRef)(!1),qe=(0,Xe.useRef)(0),Y=(0,Xe.useRef)(0),W=(0,Xe.useRef)(!1),{vaultTheme:$,surface:j,overlayTheme:Ve,appearance:Be,buttonsLayout:fe}=(0,Xe.useMemo)(()=>Ti({theme:c,appearance:m,buttonsStyles:h}),[c,m,h]),D=(0,Xe.useMemo)(()=>(0,Ta.mergeCardSetupSurface)(j,p),[j,p]),ge=(0,Xe.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:w,onComplete:I,onDecline:G,onCancel:_,onValidation:Z,onError:A});ge.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:w,onComplete:I,onDecline:G,onCancel:_,onValidation:Z,onError:A},(0,Xe.useEffect)(()=>{W.current=!0;let d=qe.current+1;return qe.current=d,()=>{W.current=!1,Y.current+=1,queueMicrotask(()=>{qe.current===d&&(Oe.current||nt.current||(nt.current=!0,(0,Ye.invokeMerchantCallback)(()=>{ge.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let ft=(0,Xe.useCallback)((d,L)=>{Oe.current=!0,ee.current=!1,B({status:"success",wording:d,message:null}),(async()=>(await Ms(600),!H.current&&(H.current=!0,(0,Ye.invokeMerchantCallback)(()=>{ge.current.onComplete?.({status:"succeeded",sessionId:ge.current.sessionId,...L?{paymentMethod:L}:{}})}),W.current&&B(null))))()},[]),Ne=(0,Xe.useCallback)((d,L)=>{Oe.current=!0,ee.current=!1,B({status:"error",wording:d,message:L.message??null}),(0,Ye.invokeMerchantCallback)(()=>{ge.current.onDecline?.({status:"declined",sessionId:ge.current.sessionId,...L.reason?{reason:L.reason}:{},...L.message?{message:L.message}:{}})}),(async()=>(await Ms(400),W.current&&B(null)))()},[]),ot=(0,Xe.useCallback)((d,L)=>{ee.current?(ee.current=!1,B({status:"error",wording:d,message:L.message}),setTimeout(()=>{W.current&&B(null)},400)):B(null),(0,Ye.invokeMerchantCallback)(()=>ge.current.onError?.(L))},[]),Me=(0,Xe.useCallback)(async d=>{let L=Y.current+1;Y.current=L;let V=()=>!W.current||L!==Y.current;ee.current=!0,B({status:"processing",wording:"payment_method",message:null});let se=new Oa.PaymentAPI((0,Ir.resolveBillingApiUrl)(ge.current.billingApiUrl),{telemetry:ge.current.telemetry});try{for(let E=0;E<ku;E+=1){if((E>0||d.waitFirst)&&await Ms(Eu),V())return;let U=await se.getUnifiedCheckoutSession(ge.current.sessionId,ge.current.nonce);if(V())return;let Nt=U.data.session?.status;if(Nt==="complete"){Te(!0),ft("payment_method");return}if(Nt==="expired")throw new Ir.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Ir.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(E){if(V())return;let U=E instanceof Ir.FloPayError&&E.code==="payment_method_setup_unverified";ot("payment_method",uo(E,U?{retryable:!0}:{}))}finally{se.destroy()}},[ot,ft]);(0,Xe.useEffect)(()=>{let d=!0,L=(0,Ir.resolveBillingApiUrl)(a),V=new Oa.PaymentAPI(L,{telemetry:s});me(null),Te(!1),ae(null),pe(null),dt(null);let se=new Set;return Le.current=se,Je(se),Oe.current=!1,nt.current=!1,H.current=!1,(async()=>{try{let{session:E,advertisement:U}=await _u(V,r,n);if(!d)return;let Nt={advertisement:U,customer:Iu(E),...E.futureUse?{futureUse:E.futureUse}:{},...E.futureUseUnsupported?{futureUseUnsupported:E.futureUseUnsupported}:{}};if(f){if((0,ra.clearSetupRedirectParams)(),E.status==="complete"){Te(!0),me(Nt),ft("payment_method");return}f.failed?Ne("payment_method",{reason:"redirect_failed"}):Me({waitFirst:!0})}let Br=U.card?await Tu(V,E,r,n,L):null;if(!d)return;me(Nt),Br&&(pe(Br),ae(new Oa.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(E){if(!d)return;let U=uo(E);Oe.current=!0,dt(U),(0,Ye.invokeMerchantCallback)(()=>ge.current.onError?.(U))}})(),()=>{d=!1,V.destroy()}},[a,n,f,Ne,ft,r,s,Me]),(0,Xe.useEffect)(()=>{if(!T)return;ee.current=!1;let d=T.on("submitting",()=>{ee.current=!0,B({status:"processing",wording:"card",message:null})}),L=T.on("complete",E=>{ft("card",E.paymentMethod)}),V=T.on("decline",E=>{Ne("card",{...E.declineReason?{reason:E.declineReason}:{},...E.message?{message:E.message}:{}})}),se=T.on("challenge_dismissed",()=>{B(null)});return()=>{d(),L(),V(),se()}},[T,Ne,ft]);let et=(0,Xe.useCallback)((d,L,V)=>{if(V.retryable){ot("payment_method",uo(L,V));return}if(Le.current.has(d))return;let se=new Set(Le.current);se.add(d),Le.current=se,Je(se);let E=de.current?.advertisement,U=E?(0,Fr.advertisedMethodKeys)(E).some(Nt=>!se.has(Nt)):!1;ot("payment_method",uo(L,{code:V.code,retryable:U}))},[ot]),at=(0,Xe.useMemo)(()=>({onSubmitting:()=>{ee.current=!0,B({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Me({waitFirst:!1})},onDeclined:d=>Ne("payment_method",d),onValidation:d=>{(0,Ye.invokeMerchantCallback)(()=>ge.current.onValidation?.(d))},onAbandoned:()=>{ee.current=!1,B(null)}}),[Ne,Me]),mr=(0,Xe.useRef)(et);mr.current=et;let Ft=(0,Xe.useRef)(new Map),St=d=>{let L=Ft.current.get(d);if(L)return L;let V=(se,E)=>mr.current(d,se,E);return Ft.current.set(d,V),V},ve=(0,Xe.useCallback)(d=>{if(Le.current.has(d))return;let L=new Set(Le.current);L.add(d),Le.current=L,Je(L);let V=de.current?.advertisement;V&&(0,Fr.advertisedMethodKeys)(V).some(E=>!L.has(E))||ot("payment_method",uo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ot]),M=(0,Xe.useRef)(ve);M.current=ve;let bt=(0,Xe.useRef)(new Map),ut=d=>{let L=bt.current.get(d);if(L)return L;let V=()=>M.current(d);return bt.current.set(d,V),V},O=Ke?(0,pr.jsx)(an,{status:Ke.status,errorMessage:Ke.message,...(0,Fr.setupOverlayLabels)(Ke.wording),successNote:null,...Ve?{theme:Ve}:{}}):null;if(we)return(0,pr.jsx)("div",{role:"alert",children:we.message});if(!P||S)return(0,pr.jsxs)(pr.Fragment,{children:[O,P?null:k]});let{advertisement:xe,customer:Ot,futureUse:Ce,futureUseUnsupported:_t}=P,b=(0,Ir.resolveBillingApiUrl)(a),x=s===void 0?{}:{telemetry:s},Ae=xe.stripe.filter(({method:d})=>!kt.has(d)),Re=kt.has("paypal")?null:xe.paypal,pt=!!(xe.card&&T&&ye?.html),it=({method:d,publishableKey:L,currency:V})=>(0,pr.jsx)("div",{"data-flopay-payment-method":d,style:{display:"contents"},children:(0,pr.jsx)(xi,{onFailed:St(d),children:(0,pr.jsx)(Xe.Suspense,{fallback:null,children:(0,pr.jsx)(e,{method:d,category:(0,Fr.stripeMethodCategory)(d),publishableKey:L,currency:V,...Ce?{futureUse:Ce}:{},..._t?{futureUseUnsupported:_t}:{},sessionId:r,nonce:n,billingApiUrl:b,...x,...Be?{appearance:Be}:{},...fe?{buttonsLayout:fe}:{},...typeof c=="string"?{themeId:c}:{},...at,onFailed:St(d),onUnavailable:ut(d)})})})},d),We=Ae.filter(({method:d})=>(0,Fr.stripeMethodCategory)(d)==="wallet"),Ge=Ae.filter(({method:d})=>(0,Fr.stripeMethodCategory)(d)!=="wallet"),Dt=Ae.length>0||Re!==null;return(0,pr.jsxs)(pr.Fragment,{children:[O,Dt?(0,pr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[We.map(it),Re?(0,pr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,pr.jsx)(xi,{onFailed:St("paypal"),children:(0,pr.jsx)(Xe.Suspense,{fallback:null,children:(0,pr.jsx)(t,{clientId:Re.clientId,...Re.environment?{environment:Re.environment}:{},...xe.currency?{currency:xe.currency}:{},sessionId:r,nonce:n,billingApiUrl:b,customer:Ot,...x,...at,onFailed:St("paypal"),onUnavailable:ut("paypal")})})})}):null,Ge.map(it)]}):null,pt&&Dt?(0,pr.jsx)(hi,{label:"or add a card"}):null,pt&&T&&ye?.html?(0,pr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,pr.jsx)(go,{capture:T,html:ye.html,messageToken:ye.messageToken,expectedOrigin:ye.expectedOrigin,verificationRequired:ye.verificationRequired,theme:$,containerStyle:D,onReady:()=>{(0,Ye.invokeMerchantCallback)(()=>ge.current.onReady?.())},onValidation:d=>{(0,Ye.invokeMerchantCallback)(()=>ge.current.onValidation?.(d))},onError:d=>{d&&ot("card",uo(new Error(d),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var xc=require("react/jsx-runtime"),Mu={StripeSetupMethod:_c,PayPalSetupMethod:Sc};function Mc(e){return(0,xc.jsx)(Tc,{...e,branches:Mu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,D.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&F(ta),r&&(n||a)&&F(ta),r&&(0,D.jsx)("button",{type:"button",onClick:()=>{e?.("card"),I(!0)},style:{width:"100%",...f,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:_.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,..._.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,D.jsx)(zo,{content:m})}),(0,D.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var wn=require("react/jsx-runtime"),fu=44;function Pc(e){return new Promise(t=>setTimeout(t,e))}function gu(e,t){return e instanceof Rn.FloPayError?e:new Rn.FloPayError(e instanceof Error?e.message:t,"api_error")}function hu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Pu(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function vc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:s,products:c,items:p,subscriptions:m,account:h,successUrl:k,cancelUrl:w,couponCodes:I,tagsData:G,utmMetadata:_,billingApiUrl:Z,locale:F,theme:f,appearance:P,buttonsTheme:me,buttonsStyles:S,onSuccess:Te,onError:T,onDecline:ae,children:ye,disabled:pe=!1,type:Re="button",style:dt,...Ge}){let x=(0,Ct.useMemo)(()=>(0,Rn.resolveBillingApiUrl)(Z),[Z]),kt=(0,Ct.useMemo)(()=>Pu({createSession:r,clientId:s,products:c,items:p,subscriptions:m,account:h,successUrl:k,cancelUrl:w,couponCodes:I,tagsData:G,utmMetadata:_}),[h,w,s,I,r,c,p,m,k,G,_]),[Je,Le]=(0,Ct.useState)(!1),[de,ee]=(0,Ct.useState)(null),[H,Oe]=(0,Ct.useState)(null),[nt,je]=(0,Ct.useState)(!1),[Y,W]=(0,Ct.useState)(null),[$,V]=(0,Ct.useState)(null),He=(0,Ct.useRef)(!0),Be=(0,Ct.useRef)(null),fe=(0,Ct.useRef)($),B=(0,Ct.useRef)(Te),ge=(0,Ct.useRef)(T),ft=(0,Ct.useRef)(ae),Ne=(0,Ct.useCallback)(b=>ci(Be,async M=>{try{return await b(M)}catch(Ae){throw M.aborted?Xo(Ae):Ae}}),[]);(0,Ct.useEffect)(()=>{fe.current=$},[$]),(0,Ct.useEffect)(()=>{B.current=Te},[Te]),(0,Ct.useEffect)(()=>{ge.current=T},[T]),(0,Ct.useEffect)(()=>{ft.current=ae},[ae]),(0,Ct.useEffect)(()=>(He.current=!0,()=>{He.current=!1,Be.current?.abort()}),[]),(0,Ct.useEffect)(()=>{if(typeof window>"u")return;let b=M=>{M.key==="Escape"&&V(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let ot=(0,Ct.useCallback)((b,M=ka)=>{ft.current?.(kr(M,b,{code:b.code,declineCode:b.declineCode}))},[]),Me=(0,Ct.useCallback)(async b=>{He.current&&(Oe(null),je(b.result.status==="authorized"),ee("success"),await Pc(600),He.current&&(0,Ye.invokeMerchantCallback)(()=>B.current?.(b)))},[]),tt=(0,Ct.useCallback)(async(b,M)=>{He.current&&(ge.current?.(b),M?.emitDecline&&ot(b,M.method),Oe(b.message),je(!1),ee("error"),await Pc(400))},[ot]),at=(0,Ct.useCallback)(async(b,M,Ae)=>{let Pe=b.data.session??null;if(!Pe)throw yo(new Rn.FloPayError("No session data returned","api_error"),M);let pt=Pe.clientSecret||t;if(oo(Pe)){await Me({result:no(Pe,M),session:Pe,sessionId:Pe.id||M,autoCompleted:!1});return}if(Pe.status==="expired")throw yo(Za(Pe),Pe.id||M);try{if(b.autoProcessingPending){let Ve=b.autoProcessingPending,We=new Ti.PaymentAPI(x),Dt=await Ne(z=>We.waitForCheckoutSessionCompletion(Ve.sessionId,{initialDelayMs:Ve.retryAfterMs,nonce:pt,statusUrl:Ve.statusUrl,signal:z})),d=fo(Dt,Pe),L=Dt.autoProcessingError?.type==="3ds_required"&&Dt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Dt.autoProcessingError.nextActionRedirectUrl}:null;if(L&&M&&pt){let z=Ea(x,M,Pe),se=await Ne(E=>Jo(L,{billingApiUrl:x,sessionId:M,nonce:pt,session:Pe,signal:E,telemetry:!0,...z.telemetry?{challengeTelemetry:z.telemetry}:{}})).finally(z.release);await Me({result:se,session:Pe,sessionId:Pe.id||M,autoCompleted:!1});return}if(Dt.autoProcessingError)throw Kn(Dt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Dt.autoProcessingError.checkoutMethod});if(!oo(d))throw Vo(d);await Me({result:no(d,M),session:d,sessionId:d.id||M,autoCompleted:!1});return}if(b.autoProcessingError){let Ve=b.autoProcessingError.nextActionRedirectUrl;if(b.autoProcessingError.type==="3ds_required"&&Ve&&M&&pt){let We=await Ne(z=>Hl({billingApiUrl:x,sessionId:M,nonce:pt,nextActionRedirectUrl:Ve,signal:z}));if(We.status==="declined")throw Kn({type:We.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:We.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let d=await new Ti.PaymentAPI(x).waitForCheckoutSessionCompletion(M,{initialDelayMs:0,nonce:pt}),L=fo(d,Pe);if(!oo(L))throw Kn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await Me({result:no(L,M),session:L,sessionId:L.id||M,autoCompleted:!1});return}throw Kn(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(Ae?.fromCreateSession&&b.autoProcessingAttempted===!0)throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let it=await Zo({billingApiUrl:x,sessionId:M??Pe.id,session:Pe,nonce:pt});if(it.type==="next_action_required"&&pt){let Ve=M??Pe.id,We=Ea(x,Ve,Pe),Dt=await Ne(d=>Jo(it,{billingApiUrl:x,sessionId:Ve,nonce:pt,session:Pe,signal:d,telemetry:!0,...We.telemetry?{challengeTelemetry:We.telemetry}:{}})).finally(We.release);await Me({result:Dt,session:Pe,sessionId:Pe.id||Ve,autoCompleted:!1});return}if(it.type!=="success")throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Me({result:it.result,session:Pe,sessionId:Pe.id||M,autoCompleted:!1})}catch(it){let Ve=Pe.id||M,We=yo(Ia(it),Ve);if(We.code==="three_ds_aborted")return;if(We.code==="checkout_processing_timeout"){if(!He.current)return;W(We.message),(0,Ye.invokeMerchantCallback)(()=>ge.current?.(We));return}await tt(We,{emitDecline:!0,method:We.checkoutMethod??ka}),hu(We,Ve)&&Ve&&He.current&&V({sessionId:Ve,errorMessage:We.message,nonce:pt||void 0,payPalOrderId:We.orderId})}},[t,x,Ne,tt,Me]),mr=(0,Ct.useCallback)(async b=>{if(Ge.onClick?.(b),!(b.defaultPrevented||pe||Je)){if(V(null),W(null),e&&kt){let M=new Rn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await tt(M),He.current&&(ee(null),Oe(null));return}if(!e&&!kt){let M=new Rn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await tt(M),He.current&&(ee(null),Oe(null));return}Le(!0),Oe(null),je(!1),ee("processing");try{let M=new Ti.PaymentAPI(x);if(e){let Ae=await M.getUnifiedCheckoutSession(e,t);await at(Ae,e);return}try{let Ae=await M.createAndFetchSession({...kt});await at(Ae,Ae.data.session?.id??null,{fromCreateSession:!0})}catch(Ae){if(Qa(Ae)==="session_auto_completed"){await Me({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ae}}catch(M){await tt(yo(gu(M,"Automatic payment failed. Please try again."),e))}finally{He.current&&(ee(null),Oe(null),Le(!1))}}},[Ge.onClick,kt,pe,Je,t,at,x,e,tt,Me]),Ft=(0,Ct.useCallback)(b=>{let M=fe.current;V(null),B.current?.({result:b,session:null,sessionId:M?.sessionId??null,autoCompleted:!1})},[]),St=(0,Ct.useCallback)(b=>{ge.current?.(b)},[]),Ce=(0,Ct.useCallback)(b=>{ft.current?.(b)},[]),A=(0,Ct.useMemo)(()=>(0,Rn.resolveTheme)(f),[f]),bt=(0,Ct.useMemo)(()=>{let b=A?.buttonsLayout??(0,Rn.resolveButtonsLayoutTheme)(me);return S?{...b,...S,cardButton:{...b.cardButton,...S.cardButton}}:b},[A,me,S]),ut=(0,Ct.useMemo)(()=>{let b=A?.appearance;return P?b?{...b,...P,variables:{...b.variables,...P.variables}}:P:b},[P,A]),O=ut?.variables,xe=O?.colorPrimary??"#4A49FF",Ot=O?.colorPrimaryHover??(0,bs.darkenHex)(xe,.12),be=O?.borderRadius??"8px";return(0,wn.jsxs)(wn.Fragment,{children:[(0,wn.jsx)("button",{...Ge,type:Re,onClick:mr,disabled:pe||Je,"aria-busy":Je,style:{width:"100%",...ye===void 0?{boxSizing:"border-box",height:fu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...bt.cardButton,...Cs({themeBundle:A,resolvedPrimaryColor:xe,resolvedBorderRadius:be,submitButtonStyle:bt.submitButton,explicitPrimaryColor:O?.colorPrimary}),fontSize:bt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:pe||Je?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:pe||Je?.6:1,...dt},onMouseEnter:b=>{Ge.onMouseEnter?.(b),!b.defaultPrevented&&!pe&&!Je&&(A||O?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Ot)},onMouseLeave:b=>{Ge.onMouseLeave?.(b),!b.defaultPrevented&&(A||O?.colorPrimary)&&(b.currentTarget.style.backgroundColor=xe)},onMouseDown:b=>{Ge.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{Ge.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:(0,wn.jsx)(zo,{content:ye})}),Y&&(0,wn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Y}),de&&(0,wn.jsx)(sn,{status:de,errorMessage:H,authorized:nt}),$&&(0,wn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:b=>{b.target===b.currentTarget&&V(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,wn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,wn.jsx)(_i,{sessionId:$.sessionId,nonce:$.nonce,checkoutMode:"full",billingApiUrl:x,locale:F,theme:f,...ut?{appearance:ut}:{},buttonsTheme:me,buttonsStyles:S,initialErrorMessage:$.errorMessage,initialPayPalOrderId:$.payPalOrderId,cardTitleContent:null,onComplete:Ft,onError:St,onDecline:Ce})})})]})}var xi=require("@flopay/js/card-setup"),Xr=require("@flopay/shared"),Vt=require("react");var Ts=require("@flopay/shared"),vu=require("@flopay/shared");function Mi(e){let t=(0,Ts.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Yn=require("react/jsx-runtime"),Oa=class extends Xr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function uo(e,t={}){let r=e instanceof Xr.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 Oa(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 Cc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:c,buttonsStyles:p,loading:m=null,onReady:h,onComplete:k,onDecline:w,onCancel:I,onValidation:G,onError:_}){let[Z,F]=(0,Vt.useState)(null),[f,P]=(0,Vt.useState)(null),[me,S]=(0,Vt.useState)(null),[Te,T]=(0,Vt.useState)(null),[ae,ye]=(0,Vt.useState)(null),pe=(0,Vt.useRef)(!1),Re=(0,Vt.useRef)(!1),{vaultTheme:dt,surface:Ge,overlayTheme:x}=(0,Vt.useMemo)(()=>Mi({theme:a,appearance:c,buttonsStyles:p}),[a,c,p]),kt=(0,Vt.useMemo)(()=>(0,Ma.mergeCardSetupSurface)(Ge,s),[Ge,s]),Je=(0,Vt.useRef)(h),Le=(0,Vt.useRef)(_),de=(0,Vt.useRef)(k),ee=(0,Vt.useRef)(w),H=(0,Vt.useRef)(I),Oe=(0,Vt.useRef)(G),nt=(0,Vt.useRef)(!1),je=(0,Vt.useRef)(!1),Y=(0,Vt.useRef)(0);return Je.current=h,Le.current=_,de.current=k,ee.current=w,H.current=I,Oe.current=G,(0,Vt.useEffect)(()=>{let W=Y.current+1;return Y.current=W,()=>{queueMicrotask(()=>{Y.current===W&&(nt.current||je.current||(je.current=!0,(0,Ye.invokeMerchantCallback)(()=>{H.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Vt.useEffect)(()=>{let W=!0,$=(0,Xr.resolveBillingApiUrl)(r),V=new xi.PaymentAPI($,{telemetry:n});return F(null),P(null),S(null),nt.current=!1,je.current=!1,(async()=>{try{if(!e.trim())throw new Xr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Xr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let He=await V.getUnifiedCheckoutSession(e,t);if(!W)return;let Be=He.data.session;if(!Be||!(0,Xr.isCardSetupCheckoutSession)(Be))throw new Xr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let fe=Be.vault;(0,Xr.isMountableVaultBlock)(fe)||(fe=await V.getVaultCapture(e,t));let B=(0,Xr.resolveVaultMountOptions)(fe,{billingApiUrl:$,sessionId:e,nonce:t});if(!B)throw new Xr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!W)return;P(B),F(new xi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(He){if(!W)return;let Be=uo(He);nt.current=!0,S(Be),(0,Ye.invokeMerchantCallback)(()=>Le.current?.(Be))}})(),()=>{W=!1,V.destroy()}},[r,t,e,n]),(0,Vt.useEffect)(()=>{if(!Z)return;let W=!1;Re.current=!1,pe.current=!1;let $=Z.on("submitting",()=>{pe.current=!0,ye(null),T("processing")}),V=Z.on("complete",fe=>{nt.current=!0,pe.current=!1,T("success"),(async()=>(await new Promise(B=>setTimeout(B,600)),!Re.current&&(Re.current=!0,(0,Ye.invokeMerchantCallback)(()=>{de.current?.({status:"succeeded",sessionId:e,...fe.paymentMethod?{paymentMethod:fe.paymentMethod}:{}})}),W||T(null))))()}),He=Z.on("decline",fe=>{nt.current=!0,pe.current=!1,ye(fe.message??null),T("error"),(0,Ye.invokeMerchantCallback)(()=>{ee.current?.({status:"declined",sessionId:e,...fe.declineReason?{reason:fe.declineReason}:{},...fe.message?{message:fe.message}:{}})}),(async()=>(await new Promise(B=>setTimeout(B,400)),W||T(null)))()}),Be=Z.on("challenge_dismissed",()=>{T(null)});return()=>{W=!0,$(),V(),He(),Be()}},[Z,e]),me?(0,Yn.jsx)("div",{role:"alert",children:me.message}):!Z||!f?.html?(0,Yn.jsx)(Yn.Fragment,{children:m}):(0,Yn.jsxs)(Yn.Fragment,{children:[Te&&(0,Yn.jsx)(sn,{status:Te,errorMessage:ae,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...x?{theme:x}:{}}),(0,Yn.jsx)(go,{capture:Z,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:dt,containerStyle:kt,onReady:()=>{(0,Ye.invokeMerchantCallback)(()=>Je.current?.())},onValidation:W=>{(0,Ye.invokeMerchantCallback)(()=>Oe.current?.(W))},onError:W=>{if(!W)return;pe.current&&(pe.current=!1,ye(W),T("error"),setTimeout(()=>T(null),400));let $=uo(new Error(W),{code:"card_setup_widget_failed",retryable:!0});(0,Ye.invokeMerchantCallback)(()=>Le.current?.($))}})]})}var bc=require("@flopay/js/card-setup"),kn=require("@flopay/shared"),Sc=require("@paypal/paypal-js"),Io=require("react");var Rc=require("react/jsx-runtime");function wc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:c,customer:{userId:p,email:m},onSubmitting:h,onConfirmed:k,onFailed:w,onAbandoned:I}){let G=(0,Io.useRef)(null),_=(0,Io.useRef)({onSubmitting:h,onConfirmed:k,onFailed:w,onAbandoned:I});_.current={onSubmitting:h,onConfirmed:k,onFailed:w,onAbandoned:I};let[Z]=(0,Io.useState)(()=>(0,$n.detectPayPalEnvironment)().inAppBrowser);return(0,Io.useEffect)(()=>{let F=!0,f,P=new bc.PaymentAPI(s,{telemetry:c}),me={userId:p,email:m};return(async()=>{try{let S=await(0,Sc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Te=G.current;if(!F||!Te)return;if(!S?.Buttons)throw new kn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let T=S.Buttons({createVaultSetupToken:async()=>{_.current.onSubmitting();let ae=await P.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:kn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,kn.isSettledSessionIntent)(ae))throw(0,kn.settledSessionIntentError)(n);if(ae.provider!=="paypal"||ae.providerObjectType!=="setup_token")throw new kn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ae.providerObjectId},onApprove:async ae=>{let ye=ae.vaultSetupToken;if(!ye)throw new kn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let pe=await P.processPayment(me.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:ye,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:kn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:me});if(!pe.ok)throw new kn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:pe.status});F&&_.current.onConfirmed()},onCancel:()=>{F&&_.current.onAbandoned()},onError:ae=>{if(!F)return;let{popupBlocked:ye}=(0,we.classifyExternalMethodFailure)(ae,{inAppBrowser:Z,handoffObserved:!1});_.current.onFailed(ye?new Error((0,we.buildExternalMethodRecoveryMessage)("PayPal",!0,Z)):ae,{code:ye?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>T.close(),await T.render(Te)}catch(S){if(!F)return;_.current.onFailed(S,{code:"paypal_unavailable",retryable:!0})}})(),()=>{F=!1,f?.().catch(()=>{}),P.destroy()}},[s,e,r,m,t,Z,a,n,c,p]),(0,Rc.jsx)("div",{ref:G,"data-flopay-paypal-setup":""})}var Ec=require("@flopay/js/card-setup"),En=require("@flopay/shared"),Xn=require("@stripe/react-stripe-js"),Ic=require("@stripe/stripe-js"),Jr=require("react");var Vr=require("react/jsx-runtime"),_c={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"}},Ms=new Map;function Cu(e){let t=Ms.get(e);if(t)return t;let r=(0,Ic.loadStripe)(e).catch(n=>{throw Ms.delete(e),n});return Ms.set(e,r),r}function bu(e){return e?(0,En.toStripeAppearance)(e):void 0}function Su(e){return(0,we.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function kc(e){return e==="paypal"?"PayPal":(0,En.getStripeMethodDisplayName)(e)}function wu(){return typeof window>"u"?"":window.location.href}var Ru={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function Tc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:c}=e,[p]=(0,Jr.useState)(()=>Cu(t)),m=(0,Jr.useMemo)(()=>{let h=bu(c),k=(0,En.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:_c[r]?.types??[r],...k?{setupFutureUsage:k}:{},...h?{appearance:h}:{}}},[c,n,a,s,r]);return(0,Vr.jsx)(Xn.Elements,{stripe:p,options:m,children:(0,Vr.jsx)(ku,{...e})})}function ku({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:c,themeId:p,buttonsLayout:m,onSubmitting:h,onConfirmed:k,onDeclined:w,onFailed:I,onValidation:G,onUnavailable:_}){let Z=(0,Xn.useStripe)(),F=(0,Xn.useElements)(),[f,P]=(0,Jr.useState)(!1),[me,S]=(0,Jr.useState)("loading"),[Te,T]=(0,Jr.useState)(!1),[ae,ye]=(0,Jr.useState)(!1),pe=(0,Jr.useRef)(!1),[Re]=(0,Jr.useState)(()=>(0,$n.detectPayPalEnvironment)()),[dt,Ge]=(0,Jr.useState)(!1),x=(0,Jr.useCallback)((H,Oe)=>{if((0,we.classifyExternalMethodFailure)(H,{inAppBrowser:Re.inAppBrowser,handoffObserved:!1}).popupBlocked){Ge(!0),I(new Error((0,we.buildExternalMethodRecoveryMessage)(kc(e),!0,Re.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}I(Oe.message===void 0?H:new Error(Oe.message),{code:Oe.code,retryable:!0})},[Re.inAppBrowser,e,I]),kt=(0,Jr.useCallback)(async H=>{let Oe=!1,nt=!1,je=()=>{!H||Oe||nt||(nt=!0,H.paymentFailed({reason:"fail"}))};if(!Z||!F||pe.current){je();return}pe.current=!0,P(!0);try{let Y=await F.submit();if(Y.error){je(),G(Y.error.message??null);return}h();let W=await new Ec.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,En.isSettledSessionIntent)(W))throw(0,En.settledSessionIntentError)(r);if(W.provider!=="stripe"||W.intentKind!=="setup")throw new En.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Oe=!0;let $=await Z.confirmSetup({elements:F,clientSecret:W.clientSecret,confirmParams:{return_url:wu()},redirect:"if_required"});if($.error){Su($.error)?w({...$.error.decline_code||$.error.code?{reason:$.error.decline_code??$.error.code}:{},...$.error.message?{message:$.error.message}:{}}):x($.error,{code:"payment_method_setup_provider_failed",message:$.error.message??"The payment method could not be saved."});return}k()}catch(Y){je(),x(Y,{code:"payment_method_setup_failed"})}finally{pe.current=!1,P(!1)}},[a,t,F,e,n,k,w,h,G,x,r,Z,s]),Je=_c[e]?.wallet,Le=Je==="paypal"&&(0,Hn.resolveStripePayPalPresentation)(Re,"auto",dt?"blocked":Re.popupCapability)==="redirect",de=c?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&Je&&!Le)return(0,Vr.jsxs)(Vr.Fragment,{children:[(0,Vr.jsx)(ea,{}),(0,Vr.jsx)(Ta,{state:me,borderRadius:de,children:(0,Vr.jsx)(Xn.ExpressCheckoutElement,{options:{...fi,paymentMethods:yi([e])},onReady:H=>{let Oe=_a(H,[Je]);S(Oe),Oe==="unavailable"&&_()},onLoadError:()=>{S("load_error"),_()},onConfirm:H=>{kt(H)}})})]});let ee=kc(e);return(0,Vr.jsxs)(Vr.Fragment,{children:[Te?(0,Vr.jsx)(mi,{method:e,themeId:p,hasNextStep:!0,highlighted:ae,disabled:f,onClick:()=>ye(H=>!H),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:de}):null,(0,Vr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ae,style:ae?{display:"flex",flexDirection:"column"}:Ru,children:[(0,Vr.jsx)(Xn.PaymentElement,{options:{layout:gi},onReady:()=>T(!0),onLoadError:()=>_(),onChange:H=>{H.complete&&G(null)}}),(0,Vr.jsx)(hi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!Z||!F||f||!ae,onClick:()=>{kt()},color:c?.variables?.colorPrimary??"#4A49FF",borderRadius:c?.variables?.borderRadius??"8px",style:m?.submitButton,children:f?"Saving\u2026":`Save ${ee}`})]})]})}var La=require("@flopay/js/card-setup"),Ir=require("@flopay/shared"),Xe=Zi(require("react"),1);var ra=require("@flopay/js/card-setup"),Fr=require("@flopay/shared");var pr=require("react/jsx-runtime"),Eu=15,Iu=2e3;function _u(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function xs(e){return new Promise(t=>setTimeout(t,e))}async function Tu(e,t,r){if(!t.trim())throw new Ir.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Ir.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,Ir.isCardSetupCheckoutSession)(a))throw new Ir.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Fr.readSetupAdvertisement)(n);if(!(0,Fr.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:c}=s,p=c.length>0?`FloPay: this setup session advertises only Stripe methods (${c.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new Ir.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function Mu(e,t,r,n,a){let s=t.vault??null;(0,Ir.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let c=(0,Ir.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!c)throw new Ir.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return c}var Ai=class extends Xe.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function Mc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:c="modern-light",containerStyle:p,appearance:m,buttonsStyles:h,loading:k=null,onReady:w,onComplete:I,onDecline:G,onCancel:_,onValidation:Z,onError:F}){let[f]=(0,Xe.useState)(ra.readSetupRedirectReturn),[P,me]=(0,Xe.useState)(null),[S,Te]=(0,Xe.useState)(!1),[T,ae]=(0,Xe.useState)(null),[ye,pe]=(0,Xe.useState)(null),[Re,dt]=(0,Xe.useState)(null),[Ge,x]=(0,Xe.useState)(null),[kt,Je]=(0,Xe.useState)(()=>new Set),Le=(0,Xe.useRef)(kt),de=(0,Xe.useRef)(null);de.current=P;let ee=(0,Xe.useRef)(!1),H=(0,Xe.useRef)(!1),Oe=(0,Xe.useRef)(!1),nt=(0,Xe.useRef)(!1),je=(0,Xe.useRef)(0),Y=(0,Xe.useRef)(0),W=(0,Xe.useRef)(!1),{vaultTheme:$,surface:V,overlayTheme:He,appearance:Be,buttonsLayout:fe}=(0,Xe.useMemo)(()=>Mi({theme:c,appearance:m,buttonsStyles:h}),[c,m,h]),B=(0,Xe.useMemo)(()=>(0,Ma.mergeCardSetupSurface)(V,p),[V,p]),ge=(0,Xe.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:w,onComplete:I,onDecline:G,onCancel:_,onValidation:Z,onError:F});ge.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:w,onComplete:I,onDecline:G,onCancel:_,onValidation:Z,onError:F},(0,Xe.useEffect)(()=>{W.current=!0;let d=je.current+1;return je.current=d,()=>{W.current=!1,Y.current+=1,queueMicrotask(()=>{je.current===d&&(Oe.current||nt.current||(nt.current=!0,(0,Ye.invokeMerchantCallback)(()=>{ge.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let ft=(0,Xe.useCallback)((d,L)=>{Oe.current=!0,ee.current=!1,x({status:"success",wording:d,message:null}),(async()=>(await xs(600),!H.current&&(H.current=!0,(0,Ye.invokeMerchantCallback)(()=>{ge.current.onComplete?.({status:"succeeded",sessionId:ge.current.sessionId,...L?{paymentMethod:L}:{}})}),W.current&&x(null))))()},[]),Ne=(0,Xe.useCallback)((d,L)=>{Oe.current=!0,ee.current=!1,x({status:"error",wording:d,message:L.message??null}),(0,Ye.invokeMerchantCallback)(()=>{ge.current.onDecline?.({status:"declined",sessionId:ge.current.sessionId,...L.reason?{reason:L.reason}:{},...L.message?{message:L.message}:{}})}),(async()=>(await xs(400),W.current&&x(null)))()},[]),ot=(0,Xe.useCallback)((d,L)=>{ee.current?(ee.current=!1,x({status:"error",wording:d,message:L.message}),setTimeout(()=>{W.current&&x(null)},400)):x(null),(0,Ye.invokeMerchantCallback)(()=>ge.current.onError?.(L))},[]),Me=(0,Xe.useCallback)(async d=>{let L=Y.current+1;Y.current=L;let z=()=>!W.current||L!==Y.current;ee.current=!0,x({status:"processing",wording:"payment_method",message:null});let se=new La.PaymentAPI((0,Ir.resolveBillingApiUrl)(ge.current.billingApiUrl),{telemetry:ge.current.telemetry});try{for(let E=0;E<Eu;E+=1){if((E>0||d.waitFirst)&&await xs(Iu),z())return;let q=await se.getUnifiedCheckoutSession(ge.current.sessionId,ge.current.nonce);if(z())return;let Nt=q.data.session?.status;if(Nt==="complete"){Te(!0),ft("payment_method");return}if(Nt==="expired")throw new Ir.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Ir.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(E){if(z())return;let q=E instanceof Ir.FloPayError&&E.code==="payment_method_setup_unverified";ot("payment_method",uo(E,q?{retryable:!0}:{}))}finally{se.destroy()}},[ot,ft]);(0,Xe.useEffect)(()=>{let d=!0,L=(0,Ir.resolveBillingApiUrl)(a),z=new La.PaymentAPI(L,{telemetry:s});me(null),Te(!1),ae(null),pe(null),dt(null);let se=new Set;return Le.current=se,Je(se),Oe.current=!1,nt.current=!1,H.current=!1,(async()=>{try{let{session:E,advertisement:q}=await Tu(z,r,n);if(!d)return;let Nt={advertisement:q,customer:_u(E),...E.futureUse?{futureUse:E.futureUse}:{},...E.futureUseUnsupported?{futureUseUnsupported:E.futureUseUnsupported}:{}};if(f){if((0,ra.clearSetupRedirectParams)(),E.status==="complete"){Te(!0),me(Nt),ft("payment_method");return}f.failed?Ne("payment_method",{reason:"redirect_failed"}):Me({waitFirst:!0})}let Br=q.card?await Mu(z,E,r,n,L):null;if(!d)return;me(Nt),Br&&(pe(Br),ae(new La.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(E){if(!d)return;let q=uo(E);Oe.current=!0,dt(q),(0,Ye.invokeMerchantCallback)(()=>ge.current.onError?.(q))}})(),()=>{d=!1,z.destroy()}},[a,n,f,Ne,ft,r,s,Me]),(0,Xe.useEffect)(()=>{if(!T)return;ee.current=!1;let d=T.on("submitting",()=>{ee.current=!0,x({status:"processing",wording:"card",message:null})}),L=T.on("complete",E=>{ft("card",E.paymentMethod)}),z=T.on("decline",E=>{Ne("card",{...E.declineReason?{reason:E.declineReason}:{},...E.message?{message:E.message}:{}})}),se=T.on("challenge_dismissed",()=>{x(null)});return()=>{d(),L(),z(),se()}},[T,Ne,ft]);let tt=(0,Xe.useCallback)((d,L,z)=>{if(z.retryable){ot("payment_method",uo(L,z));return}if(Le.current.has(d))return;let se=new Set(Le.current);se.add(d),Le.current=se,Je(se);let E=de.current?.advertisement,q=E?(0,Fr.advertisedMethodKeys)(E).some(Nt=>!se.has(Nt)):!1;ot("payment_method",uo(L,{code:z.code,retryable:q}))},[ot]),at=(0,Xe.useMemo)(()=>({onSubmitting:()=>{ee.current=!0,x({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Me({waitFirst:!1})},onDeclined:d=>Ne("payment_method",d),onValidation:d=>{(0,Ye.invokeMerchantCallback)(()=>ge.current.onValidation?.(d))},onAbandoned:()=>{ee.current=!1,x(null)}}),[Ne,Me]),mr=(0,Xe.useRef)(tt);mr.current=tt;let Ft=(0,Xe.useRef)(new Map),St=d=>{let L=Ft.current.get(d);if(L)return L;let z=(se,E)=>mr.current(d,se,E);return Ft.current.set(d,z),z},Ce=(0,Xe.useCallback)(d=>{if(Le.current.has(d))return;let L=new Set(Le.current);L.add(d),Le.current=L,Je(L);let z=de.current?.advertisement;z&&(0,Fr.advertisedMethodKeys)(z).some(E=>!L.has(E))||ot("payment_method",uo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ot]),A=(0,Xe.useRef)(Ce);A.current=Ce;let bt=(0,Xe.useRef)(new Map),ut=d=>{let L=bt.current.get(d);if(L)return L;let z=()=>A.current(d);return bt.current.set(d,z),z},O=Ge?(0,pr.jsx)(sn,{status:Ge.status,errorMessage:Ge.message,...(0,Fr.setupOverlayLabels)(Ge.wording),successNote:null,...He?{theme:He}:{}}):null;if(Re)return(0,pr.jsx)("div",{role:"alert",children:Re.message});if(!P||S)return(0,pr.jsxs)(pr.Fragment,{children:[O,P?null:k]});let{advertisement:xe,customer:Ot,futureUse:be,futureUseUnsupported:_t}=P,b=(0,Ir.resolveBillingApiUrl)(a),M=s===void 0?{}:{telemetry:s},Ae=xe.stripe.filter(({method:d})=>!kt.has(d)),Pe=kt.has("paypal")?null:xe.paypal,pt=!!(xe.card&&T&&ye?.html),it=({method:d,publishableKey:L,currency:z})=>(0,pr.jsx)("div",{"data-flopay-payment-method":d,style:{display:"contents"},children:(0,pr.jsx)(Ai,{onFailed:St(d),children:(0,pr.jsx)(Xe.Suspense,{fallback:null,children:(0,pr.jsx)(e,{method:d,category:(0,Fr.stripeMethodCategory)(d),publishableKey:L,currency:z,...be?{futureUse:be}:{},..._t?{futureUseUnsupported:_t}:{},sessionId:r,nonce:n,billingApiUrl:b,...M,...Be?{appearance:Be}:{},...fe?{buttonsLayout:fe}:{},...typeof c=="string"?{themeId:c}:{},...at,onFailed:St(d),onUnavailable:ut(d)})})})},d),Ve=Ae.filter(({method:d})=>(0,Fr.stripeMethodCategory)(d)==="wallet"),We=Ae.filter(({method:d})=>(0,Fr.stripeMethodCategory)(d)!=="wallet"),Dt=Ae.length>0||Pe!==null;return(0,pr.jsxs)(pr.Fragment,{children:[O,Dt?(0,pr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ve.map(it),Pe?(0,pr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,pr.jsx)(Ai,{onFailed:St("paypal"),children:(0,pr.jsx)(Xe.Suspense,{fallback:null,children:(0,pr.jsx)(t,{clientId:Pe.clientId,...Pe.environment?{environment:Pe.environment}:{},...xe.currency?{currency:xe.currency}:{},sessionId:r,nonce:n,billingApiUrl:b,customer:Ot,...M,...at,onFailed:St("paypal"),onUnavailable:ut("paypal")})})})}):null,We.map(it)]}):null,pt&&Dt?(0,pr.jsx)(Pi,{label:"or add a card"}):null,pt&&T&&ye?.html?(0,pr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,pr.jsx)(go,{capture:T,html:ye.html,messageToken:ye.messageToken,expectedOrigin:ye.expectedOrigin,verificationRequired:ye.verificationRequired,theme:$,containerStyle:B,onReady:()=>{(0,Ye.invokeMerchantCallback)(()=>ge.current.onReady?.())},onValidation:d=>{(0,Ye.invokeMerchantCallback)(()=>ge.current.onValidation?.(d))},onError:d=>{d&&ot("card",uo(new Error(d),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Ac=require("react/jsx-runtime"),xu={StripeSetupMethod:Tc,PayPalSetupMethod:wc};function xc(e){return(0,Ac.jsx)(Mc,{...e,branches:xu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});