@flopay/react 1.14.13 → 1.14.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var 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(),Ze=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),Ze({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),Ze({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)}),[Ze,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]),Qe=(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:Qe}),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"}),Xe=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?()=>Xe(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?`
1
+ "use strict";var Qc=Object.create;var Qa=Object.defineProperty;var ed=Object.getOwnPropertyDescriptor;var td=Object.getOwnPropertyNames;var rd=Object.getPrototypeOf,nd=Object.prototype.hasOwnProperty;var od=(e,t)=>{for(var r in t)Qa(e,r,{get:t[r],enumerable:!0})},Sl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of td(t))!nd.call(e,a)&&a!==r&&Qa(e,a,{get:()=>t[a],enumerable:!(n=ed(t,a))||n.enumerable});return e};var Qi=(e,t,r)=>(r=e!=null?Qc(rd(e)):{},Sl(t||!e||!e.__esModule?Qa(r,"default",{value:e,enumerable:!0}):r,e)),ad=e=>Sl(Qa({},"__esModule",{value:!0}),e);var Fu={};od(Fu,{DirectPayPalButton:()=>wa,FloPayAutomaticPaymentButton:()=>Cc,FloPayCardSetup:()=>bc,FloPayCardSetupError:()=>Na,FloPayCheckout:()=>Mi,FloPayPaymentMethodSetup:()=>Ac,FloPayProvider:()=>Ra,SplitCardForm:()=>Ei,VaultCardFields:()=>fo,dropThirdPartyOnlyError:()=>Bc.dropThirdPartyOnlyError,useCheckout:()=>Dl,useFloPay:()=>no,usePayPalFloPay:()=>ni});module.exports=ad(Fu);var Bc=require("@flopay/shared");var xi=require("@flopay/js"),Sn=require("@flopay/shared"),Ct=require("react");var Zt=require("react/jsx-runtime");function id(){return(0,Zt.jsxs)(Zt.Fragment,{children:[(0,Zt.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,Zt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Zt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Zt.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,Zt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function sd(){return(0,Zt.jsx)(Zt.Fragment,{children:"Go back"})}function ld(){return(0,Zt.jsx)(Zt.Fragment,{children:"Secure card checkout"})}function qo(e){return e!==void 0&&(e===""||e===null||e===!1)}function jo({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(id,{}):e})}function Vo({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(sd,{}):e})}function ha({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(ld,{}):e})}var wt=require("@flopay/shared"),An=require("@flopay/shared"),Ho=require("@flopay/shared"),wo=require("@flopay/shared");function es(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof wt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function cd(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function wl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,wt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,wt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function kl(e,t){if(t&&(!(e instanceof wt.FloPayError)||e.type==="authentication_error"))return es(e);if(!(e instanceof wt.FloPayError&&cd(e))){if(!t&&!(e instanceof wt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,wt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof wt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof wt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Wo(e,t,r,n={}){let a;return(s={})=>{if(a!==void 0)return a;let c={...n,...s,email:s.email?.trim()||n.email?.trim()},p=(0,wt.isCardHolderNamePlaceholder)(c.firstName,c.lastName);if(!(0,wt.isValidEmail)(c.email))return Promise.reject(new wt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[g,_]of Object.entries(c)){if(p&&g.endsWith("Name")||typeof _!="string")continue;let E=_.trim();E&&(m[g]=E)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function Rl(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function ts(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function El(e,t){let r=e.products??[...(e.subscriptions??[]).map(s=>({type:"subscription",code:s.code??s.providerPlanId,name:s.subscriptionName??s.providerPlanName??s.code??s.providerPlanId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata})),...(e.items??[]).map(s=>({type:"item",code:s.code??s.providerItemId,name:s.itemName??s.providerItemName??s.code??s.providerItemId??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency,metadata:s.metadata}))],n=r.reduce((s,c)=>s+(c.overrideAmount??c.totalAmount??0),0),a=e.currency??r.find(s=>s.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(s=>s.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:r.map((s,c)=>({uuid:`synthetic-${s.type??"item"}-${c}`,checkoutSessionId:"",type:s.type??"item",code:s.code,name:s.name??null,quantity:s.quantity??1,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount??null,currency:s.currency??a,metadata:s.metadata??null}))}}function rs(e,t){return t?{...e,...t}:e}function br(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,s=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,c=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...s?{declineCode:s}:{},...c?{sessionId:c}:{}}}var _l=new WeakMap;function Il(e,t){return typeof e=="object"&&e!==null&&_l.set(e,t?{sessionId:t}:{}),e}function Tl(e){return typeof e=="object"&&e!==null?_l.get(e):void 0}function mo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function eo(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function to(e){return e?.status==="authorized"||e?.status==="complete"}function yo(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function Ml(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ei(e){let t=Ml(e);return new wt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ti(e){return e instanceof wt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function $o(e){return Ml(e)?new wt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new wt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new wt.FloPayError(wt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function Pa(e,t){return e==="processing"||(0,wt.isMoneySettledOutcome)(e,t)}function xl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Al(e,t){let r=e;if((0,wt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:c}=await r.retrieveSetupIntent(t);if(c)throw new wt.FloPayError(c.message??"Failed to retrieve setup intent.","api_error",{...c.code?{code:c.code}:{}});return s??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new wt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var dd=["apple_pay","google_pay"];function Fl(e,t="automatic",r){let n=(0,wt.resolveSetupFutureUsage)(r,dd,"wallet");return{...(0,wt.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var ud=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ns(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:ud.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function va(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var io=require("@flopay/js"),Ue=require("@flopay/shared"),P=Qi(require("react"),1);var os=require("react"),hn=(0,os.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Fn=(0,os.createContext)({session:null,loading:!1,error:null});var ci=require("@flopay/js"),$e=require("@flopay/shared"),zl=require("@paypal/paypal-js"),R=require("react");var ri=require("@flopay/shared"),Bn=require("react"),Pn=require("@flopay/shared"),ro=require("react/jsx-runtime");function Ko(){let[e,t]=(0,Bn.useState)(null),r=(0,Bn.useRef)(null),n=(0,Bn.useRef)(0),a=(0,Bn.useCallback)((c,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:c,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,Bn.useCallback)(c=>{let p=r.current;r.current=null,t(null),p?.(c)},[]);return(0,Bn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function Go({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[c,p]=(0,Bn.useState)(e.email?.trim()??""),m=(0,ri.isValidEmail)(c.trim());return(0,ro.jsxs)("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,ro.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,ro.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,ro.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:c,onChange:g=>p(g.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,ro.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,ro.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,ro.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,ri.compactBuyerIdentity)({...e,email:c.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var we=require("@flopay/shared");var Bl=require("@flopay/shared"),Ca=require("react");function no(){return(0,Ca.useContext)(hn).flopay}function ni(){return(0,Ca.useContext)(hn).paypalFlopay??null}function Dl(){return(0,Ca.useContext)(Fn)}function Ol(){return(0,Ca.useContext)(hn).billingApiUrl||(0,Bl.resolveBillingApiUrl)()}var pd=require("@flopay/shared"),Wn=require("@flopay/shared"),$n=require("@flopay/shared");var Yo=require("@flopay/shared"),Ro=require("react");var oi=require("react"),ko=typeof window>"u"?oi.useEffect:oi.useLayoutEffect;var as=require("@flopay/shared");function Xo(e,t){let r=(0,Ro.useRef)(e);r.current=e;let n=(0,Ro.useRef)(new Set),a=(0,Ro.useRef)(t),s=(0,Ro.useRef)(t);return ko(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Ro.useCallback)(c=>{if(s.current!==t)return;let p=(0,Yo.projectFloInstrument)(c);if(p){if(Yo.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,Yo.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Qe=require("@flopay/shared");var Ll=require("react"),ba=(0,Ll.createContext)(null);function ai(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var ii="provider.callback.ignored";function si(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var md=Symbol.for("@flopay/js.telemetry.bridge.v1"),yd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function fd(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function gd(e){let t=fd(),r=(a,s)=>a?a.bind(e):s,n=r(e.now,t.now);return{error:r(e.error,t.error),log:r(e.log,t.log),performance:r(e.performance,t.performance),terminal:r(e.terminal,t.terminal),now:n,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,n()-a),setCheckoutContext:r(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:r(e.beginCheckout,t.beginCheckout),disable:r(e.disable,t.disable),subscribe:r(e.subscribe,t.subscribe),flush:r(e.flush,t.flush),destroy:r(e.destroy,t.destroy)}}function li(e){let t=globalThis[yd];return gd(t?.(e)??{})}function Sr(e){if(e)return e[md]}var fr=require("react");function Sa(e,t){let r=(0,fr.useRef)(0),n=(0,fr.useRef)(null),a=(0,fr.useRef)(null),s=(0,fr.useRef)(e),c=(0,fr.useRef)(t?.onHandoffObserved),p=(0,fr.useRef)(t?.defersMissingTerminal),m=(0,fr.useRef)(t?.onMissingTerminalDeferred);(0,fr.useEffect)(()=>{s.current=e,c.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let g=(0,fr.useCallback)((y=a.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),_=(0,fr.useCallback)(y=>{g();let h=r.current+1;return r.current=h,n.current=null,a.current={generation:h,method:y,timer:null,yieldedControl:!1},h},[g]),E=(0,fr.useCallback)(y=>{let h=a.current;return y!==void 0&&h?.generation!==y?!1:(g(h),a.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[g]),I=(0,fr.useCallback)(y=>{let h=a.current,ge=y??h?.generation??r.current;(y===void 0||h?.generation===y)&&(g(h),a.current=null),n.current=ge},[g]),H=(0,fr.useCallback)(y=>n.current===(y??r.current),[]),T=(0,fr.useCallback)(y=>a.current?.generation===y&&n.current!==y,[]),Y=(0,fr.useCallback)(()=>{let y=a.current;y&&(g(y),!y.yieldedControl&&(y.yieldedControl=!0,c.current?.(y.method)))},[g]),F=(0,fr.useCallback)(()=>{let y=a.current;!y?.yieldedControl||document.visibilityState!=="visible"||(g(y),y.timer=setTimeout(()=>{if(y.timer=null,a.current?.generation===y.generation){if(p.current?.(y.method)){m.current?.(y.method,y.generation);return}a.current=null,n.current=y.generation,s.current(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},we.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[g]);return(0,fr.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?F():Y()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",Y),window.addEventListener("focus",F),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",Y),window.removeEventListener("focus",F),g()}},[g,Y,F]),{startAttempt:_,finishAttempt:E,invalidateAttempt:I,isAttemptInvalidated:H,isAttemptCurrent:T,generationRef:r}}var vn=require("react/jsx-runtime"),di=45,hd=1e3,Pd=11e3,Nl="paypal_intent_settled",vd={width:"100%",minHeight:di,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},Cd={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function bd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Cd[e.kind]??null}}function Ul(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,we.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function Sd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function ql({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:c,environment:p,currency:m,isSubscription:g,providerObjectType:_,approvalPresentation:E,onTokenizedBody:I,onComplete:H,onErrorChange:T,onDecline:Y,onCancel:F,onTechnicalFailure:y,isProcessing:h=!1,onLoadStateChange:ge,onInitializationStateChange:w,allowAutomaticRetry:Te=!0,onButtonClick:x,runBeforeButtonClick:ie,session:he,existingOrderId:fe,telemetry:ke,telemetryContext:mt,onInstrument:Je,debug:A=!1}){let kt=no(),tt=Xo(Je,e),Ve=(0,R.useMemo)(()=>{if(kt)return null;let N=li({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:$e.SDK_VERSION,enabled:ke!==!1});return N.setCheckoutContext(mt??{}),N.beginCheckout(mt??{}),N},[r,kt,ke,mt?.checkoutMode,mt?.layout]),me=(0,R.useMemo)(()=>Sr(kt),[kt]);(0,R.useEffect)(()=>()=>{Ve&&Ve.flush().catch(()=>{}).finally(()=>Ve.destroy())},[Ve]);let K=(0,R.useMemo)(()=>({error:N=>{me?me.error(N):Ve?.error(N),tt({class:"technical_error",errorCode:N.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":N.errorCode,requestCategory:N.requestCategory,provider:N.provider})},log:N=>{me?me.log(N):Ve?.log(N),tt({class:"lifecycle",name:N.name,provider:N.provider})},performance:N=>{me?me.performance(N):Ve?.performance(N)},terminal:N=>{me?me.terminal(N):Ve?.terminal(N)},startTiming:()=>me?.now()??Ve?.now()??0,elapsed:N=>me?.elapsed(N)??Math.max(0,(Ve?.now()??N)-N)}),[tt,me,Ve]),W=(0,R.useRef)(null),Fe=(0,R.useRef)(0),lt=(0,R.useRef)(null),He=(0,R.useRef)(null),J=(0,R.useRef)(null),D=(0,R.useContext)(ba),se=(0,R.useRef)(null);se.current||(se.current=ai());let O=D??se.current,be=(0,R.useRef)(null),Me=(0,R.useRef)(!1),[Pe,Be]=(0,R.useState)(!1),[M,at]=(0,R.useState)(!1),[Ke,yt]=(0,R.useState)(0),Ze=(0,R.useRef)(0),[Ge,_t]=(0,R.useState)(!1),Ut=(0,R.useRef)(!1),qt=(0,R.useRef)(!1),[Ft,de]=(0,R.useState)(!1),[ue,X]=(0,R.useState)(!1),{request:bt,collect:ft,finish:V}=Ko(),rt=(0,R.useRef)({sessionId:e,required:(0,$e.paypalProviderIdentityRequired)(n,he)});rt.current.sessionId!==e&&(rt.current={sessionId:e,required:(0,$e.paypalProviderIdentityRequired)(n,he)});let Rt=rt.current.required,Re=(0,R.useMemo)(()=>r.replace(/\/+$/,""),[r]),q=he?.gateways?.paypal?.providerObjectType??_,oe=q??(g?"subscription":"order"),[xe]=(0,R.useState)(Wn.detectPayPalEnvironment),Lt=he?.gateways?.paypal?.approvalPresentation??E,it=(0,$n.resolvePayPalPresentationMode)(xe,Lt==="app_switch"?"app_switch":void 0,oe),De=(0,$e.usesPayPalVaultedChannel)(q),Oe=(0,R.useMemo)(()=>JSON.stringify([Re,c,m,p??"",oe,De,it,e,fe??""]),[Re,c,m,p,fe,oe,De,it,e]),Tt=(0,R.useRef)(Oe),u=Tt.current!==Oe,C=(0,R.useRef)(A),Q=(0,R.useRef)(null),[le,L]=(0,R.useState)([]),k=(0,R.useCallback)(N=>{C.current&&L(dt=>[...dt,`${new Date().toISOString().slice(11,23)} ${N}`])},[]);(0,R.useEffect)(()=>{C.current=A,A&&k("debug:enabled"),Q.current?.setEnabled(A)},[k,A]);let jt=(0,R.useRef)(I),Mr=(0,R.useRef)(H),dr=(0,R.useRef)(T),xr=(0,R.useRef)(Y),ct=(0,R.useRef)(F),Gr=(0,R.useRef)(y),Yr=(0,R.useRef)(x),Ar=(0,R.useRef)(ge),Gt=(0,R.useRef)(w),nr=(0,R.useRef)(s),Qt=(0,R.useRef)(ie),Rn=(0,R.useRef)(he),Yt=(0,R.useRef)(n),Nn=(0,R.useRef)(a),Fr=(0,R.useRef)(t),Xt=(0,R.useRef)(null),or=(0,R.useRef)(new Map),on=(0,R.useRef)(new Map),gt=(0,R.useRef)(!1),Mt=(0,R.useRef)(e);Mt.current=e;let[Br]=(0,R.useState)(si);(0,R.useEffect)(()=>(gt.current=!0,()=>{gt.current=!1}),[]),(0,R.useEffect)(()=>{jt.current=I},[I]),(0,R.useEffect)(()=>{nr.current=s},[s]),(0,R.useEffect)(()=>{Mr.current=H},[H]),(0,R.useEffect)(()=>{dr.current=T},[T]),(0,R.useEffect)(()=>{xr.current=Y},[Y]),(0,R.useEffect)(()=>{ct.current=F},[F]),(0,R.useEffect)(()=>{Gr.current=y},[y]),(0,R.useEffect)(()=>{Yr.current=x},[x]),(0,R.useEffect)(()=>{Ar.current=ge},[ge]),(0,R.useEffect)(()=>{Gt.current=w},[w]),(0,R.useEffect)(()=>{Qt.current=ie},[ie]),(0,R.useEffect)(()=>{Rn.current=he},[he]),(0,R.useEffect)(()=>{Yt.current=n},[n]),(0,R.useEffect)(()=>{Nn.current=a},[a]),(0,R.useEffect)(()=>{Fr.current=t},[t]),(0,R.useEffect)(()=>{Ze.current=Ke},[Ke]),(0,R.useEffect)(()=>{Ge&&be.current?.focus()},[Ge,Ke]);let ar=(0,R.useCallback)(()=>{window.setTimeout(()=>{be.current?.focus()},0)},[]),Jt=(0,R.useCallback)(()=>{Be(!1),yt(N=>N+1)},[]),Ur=(0,R.useCallback)(()=>{_t(!1),(W.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??W.current)?.focus?.()},[]);(0,R.useEffect)(()=>{!Pe||!Me.current||(Me.current=!1,Ur())},[Ur,Pe,Ke]);let hr=(0,R.useCallback)((N,dt)=>{let te=dt?.popupBlocked??(0,we.isPopupBlockedError)(N);te&&O.markBlocked();let Se=(0,we.buildExternalMethodRecoveryMessage)("PayPal",te,xe.inAppBrowser),Dt=Gr.current;if(Dt){let $t=te&&xe.inAppBrowser?new $e.FloPayError(Se,"api_error",{code:dt?.code??"paypal_popup_blocked"}):N;Dt("paypal",$t,dt);return}if(N instanceof $e.FloPayError&&N.code==="checkout_processing_timeout"){dr.current?.(N.message);return}dr.current?.(Se)},[O,xe.inAppBrowser]),Vt=(0,R.useCallback)(N=>{let dt=lt.current,te=He.current;dt===null||!te||(K.log({...te,popupCapability:O.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:N}),K.performance({...te,popupCapability:O.current(),stage:"overlay_return",durationMs:K.elapsed(dt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:N}),lt.current=null)},[O,K]),Dr=(0,R.useCallback)((N,dt,te)=>{let Se=He.current;Vt("overlay_timeout"),Se&&K.error({...Se,popupCapability:O.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),hr(dt,{...te,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:"overlay_timeout"}),_t(!0),Jt(),ar()},[Vt,ar,hr,O,it,Jt,K]),kr=(0,R.useCallback)(()=>{O.markAvailable();let N=He.current;N&&(J.current=N.attempt,K.log({...N,popupCapability:O.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[O,K]),Le=(0,R.useCallback)(()=>!0,[]),Or=(0,R.useCallback)(()=>{let N=He.current;if(!N)return;let dt=lt.current;K.performance({...N,popupCapability:O.current(),stage:"overlay_return",durationMs:dt===null?0:K.elapsed(dt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[O,K]),{finishAttempt:Xr,generationRef:Xn,invalidateAttempt:Pr,isAttemptCurrent:an,isAttemptInvalidated:sn,startAttempt:En}=Sa(Dr,{onHandoffObserved:kr,defersMissingTerminal:Le,onMissingTerminalDeferred:Or}),Wt=(0,R.useCallback)(()=>(_t(!1),En("paypal")),[En]),Ce=(0,R.useCallback)(N=>{Pr(N?.generation),N?.showRetry&&_t(!0),N?.remount&&Jt(),N?.focus!==!1&&ar()},[ar,Pr,Jt]),ln=N=>{let dt=Xt.current;return dt&&on.current.set(N,dt),N};(0,R.useEffect)(()=>{Tt.current!==Oe&&(Tt.current=Oe,Ut.current=!1,qt.current=!1,Be(!1),at(!1),de(!1),Gt.current?.("loading"))},[Oe]),(0,R.useEffect)(()=>{(0,Qe.invokeMerchantCallback)(()=>Ar.current?.(Pe&&!Ft))},[Pe,Ft]);let zr=(0,$e.normalizeGatewayEnvironment)(p);(0,R.useEffect)(()=>{let N={attempt:Xn.current+1,inAppBrowser:xe.inAppBrowser,appFamily:xe.appFamily,popupCapability:O.current(),presentationMode:it},dt=()=>({...He.current??N,popupCapability:O.current()}),te={error:f=>K.error({...f,...dt()}),log:f=>K.log({...f,...dt()}),performance:f=>K.performance({...f,...dt()}),terminal:f=>K.terminal({...f,...dt()}),startTiming:K.startTiming,elapsed:K.elapsed},Se=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",Dt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(k(`mount clientId=${Se} env=${p??"(unset)"}\u2192${zr??"live"} ccy=${m} sub=${g}`),k(`ua=${Dt.slice(0,80)}${Dt.length>80?"\u2026":""}`),!c){k("FAIL: clientId empty \u2014 gateway misconfigured"),de(!0),te.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!W.current){k("FAIL: containerRef not attached");return}Fe.current=te.startTiming(),te.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let $t=!1,nt=!1,Ye=()=>$t||nt,Jr=f=>{let S=gt.current,ne=S?f:"torn_down";S&&k(`onError ignored reason=${ne}`),Br.take(Mt.current)&&te.log({name:ii,stage:"provider_ready",reason:ne,provider:"paypal",paymentMethodCategory:"paypal"})},Un=()=>Mt.current===e?"stale_attempt":"session_changed",er=De?oe:void 0,In,Jn=!1,Zn=()=>{In=(0,$e.generateIdempotencyKey)(),In||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Jn=!0},Tn=null,lo=!1,Qn=null,go=!1,yn=()=>{!Qn||go||(go=!0,Qn.close().catch(()=>{}))},jr=!1,co=!1,Nt=W.current,Zr=null,Qr=null,cn=[],dn=null,st=!1,ur=!1,vr=null,Rr=f=>{if(!f||typeof f.getBoundingClientRect!="function")return"(no rect)";let S=f.getBoundingClientRect();return`${Math.round(S.width)}\xD7${Math.round(S.height)}`},ho=f=>{if(!f)return"(empty)";try{let S=new URL(f,typeof window>"u"?"https://localhost":window.location.href),ne=S.pathname.toLowerCase();return ne.includes("checkcaptcha")||ne.includes("captcha")?`CAPTCHA(${S.host}${ne})`:ne.includes("risk")||ne.includes("challenge")?`RISK(${S.host}${ne})`:ne.includes("smart/buttons")?`smart-buttons(${S.host})`:`${S.host}${ne}`.slice(0,100)}catch{return f.slice(0,80)}},zn=f=>{let S=f.getAttribute("src"),ne=f.getAttribute("srcdoc"),qe=f.getAttribute("name"),je=f.getAttribute("sandbox"),ye=[];return S&&ye.push(`src=${ho(S)}`),ne&&ye.push(`srcdoc[${ne.length}ch]`),!S&&!ne&&ye.push("src=(empty) srcdoc=(empty)"),qe&&ye.push(`name=${qe.slice(0,40)}`),je!==null&&ye.push(`sandbox="${je.slice(0,40)}"`),ye.join(" ")},uo=f=>{if(!(f instanceof HTMLIFrameElement))return"";try{let S=f.contentDocument;if(!S)return"cd=null";let ne=S.body?.children.length??0,qe=S.body?.innerHTML.length??0,je=S.head?.innerHTML.length??0;return`cd=same-origin readyState=${S.readyState} body[${ne}children,${qe}ch] head[${je}ch]`}catch(S){return`cd=cross-origin(${S.message.slice(0,30)})`}},Vr=[],Er=f=>{if(Ye())return;let S=f.message??String(f.error??"(no message)");S&&(S.toLowerCase().includes("paypal")||S.toLowerCase().includes("zoid")||S.toLowerCase().includes("postrobot")||S.toLowerCase().includes("storage"))&&(k(`window:error ${S.slice(0,140)}`),Vr.push(S))},po=f=>{if(Ye())return;let S=f.reason instanceof Error?f.reason.message:String(f.reason??"(no reason)");S&&(S.toLowerCase().includes("paypal")||S.toLowerCase().includes("zoid")||S.toLowerCase().includes("postrobot")||S.toLowerCase().includes("storage"))&&(k(`window:rejection ${S.slice(0,140)}`),Vr.push(S))},Lr={value:0},U=()=>{Zr?.disconnect(),Zr=null,Qr?.disconnect(),Qr=null;for(let f of cn.splice(0))clearTimeout(f);ur=!1,st&&typeof window<"u"&&(window.removeEventListener("error",Er),window.removeEventListener("unhandledrejection",po)),st=!1},z=()=>{if(!(st||Ye()||jr)){if(st=!0,Vr.length=0,Lr.value=0,typeof window<"u"&&(window.addEventListener("error",Er),window.addEventListener("unhandledrejection",po)),typeof PerformanceObserver<"u")try{Qr=new PerformanceObserver(f=>{if(!Ye())for(let S of f.getEntries()){if(!S.name.toLowerCase().includes("paypal"))continue;Lr.value+=1;let ne=Math.round(S.duration);k(`net ${ne}ms ${S.name.slice(0,90)}`)}}),Qr.observe({type:"resource",buffered:!0})}catch{}vr?.()}},ce=()=>{dn&&(clearTimeout(dn),dn=null)},ve=()=>{U(),ce()},xt={setEnabled:f=>{f?z():U()}};Q.current=xt,C.current&&z();let zt=$e.isPayPalTeardownMessage,ze=f=>{if(Ye()||zt(f))return;let S=(0,wo.applyFriendlyMessageOverride)(f)??f;(0,Qe.invokeMerchantCallback)(()=>dr.current?.(S))},Z=(f,S)=>{if($t||lo)return;lo=!0,nt=!0,ve(),yn();let ne=bd({kind:f,generationActive:!0,automaticRetryAllowed:Te,automaticRetryUsed:Ut.current});if(ne.action==="retry"){Ut.current=!0,Be(!1),X(!1),at(!0),Gt.current?.("retrying"),Tn=setTimeout(()=>{$t||yt(qe=>qe+1)},hd);return}if(Be(!1),X(!1),at(!1),de(!0),ne.action!=="ignore"){if(Gt.current?.("exhausted"),ne.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",S);return}if(ne.report){let qe=(0,we.classifyExternalMethodFailure)({code:Ul(f,S),message:S},{inAppBrowser:xe.inAppBrowser,handoffObserved:!1});qe.popupBlocked&&O.markBlocked(),te.error({errorCode:qe.popupBlocked?qe.errorCode:ne.report.errorCode,stage:ne.report.stage,operationOutcome:ne.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:qe.terminalReason})}qt.current||(qt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Ul(f,S)))}};de(!1);let re=async(f,S=Xt.current)=>{if(Ye())return;let ne=S?.sessionId??e;if(jt.current){await jt.current(f,{sessionId:ne,accountPatch:S?.accountPatch,nonce:S?.nonce});return}let qe=te.startTiming();te.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let je=()=>{te.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"processing",durationMs:te.elapsed(qe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ye=(0,$e.buildPayPalProcessPaymentRequest)({body:f,sessionId:ne,nonce:S?.nonce??Fr.current,accountPatch:S?.accountPatch,session:Rn.current,email:Yt.current}),ee=await new ci.PaymentAPI(Re,{telemetry:!1}).processPayment(ye.userId,ye.params);if(ee.ok){if(nt||$t&&gt.current)return;je(),te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Qe.invokeMerchantCallback)(()=>Mr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ye())return;let Cr=await ee.json().catch(()=>null),Po=(0,$e.describePayPalProcessFailure)(Cr),To=Po.message;je(),ee.status===400&&(typeof Cr?.declineCode=="string"||!Array.isArray(Cr?.fields))?te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ee.status===400||ee.status===422?te.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):te.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Sd(ee.status),failureCategory:ee.status>=500?"server_error":void 0}),ze(To),(0,Qe.invokeMerchantCallback)(()=>xr.current?.(br("paypal",To,{code:Po.code,declineCode:Po.declineCode})));return}catch(ye){if(Ye())return;je(),te.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let tr=(0,$e.friendlyPayPalFailureMessage)(ye instanceof Error?ye.message:void 0);ze(tr),(0,Qe.invokeMerchantCallback)(()=>xr.current?.(br("paypal",tr)));return}},Xe=()=>new $e.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ee=f=>Ye()?Promise.reject(Xe()):Promise.resolve(f),ut=async f=>{if(f.ok){te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Qe.invokeMerchantCallback)(()=>Mr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let S=await f.json().catch(()=>null),ne=(0,$e.describePayPalProcessFailure)(S);te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Qe.invokeMerchantCallback)(()=>xr.current?.(br("paypal",ne.message,{code:ne.code,declineCode:ne.declineCode})))},j=()=>{let f=Xt.current;Vt("approved"),f&&(or.current.delete(f.surfaceKey),Xr(f.generation)),Xt.current=null},pe=async f=>{if(Ye())throw Xe();Jn||Zn();let S=Xt.current,ne=S?.sessionId??e,qe=S?.nonce??Fr.current;te.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let je;try{je=await new ci.PaymentAPI(Re,{telemetry:!1}).createSessionIntent(ne,qe??"",(0,$e.buildPayPalSessionIntentRequest)(er),{idempotencyKey:In})}catch(ye){throw te.error({...(0,$e.classifyTelemetryFailure)(ye,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ye}if(Ye())throw Xe();if((0,$e.isSettledSessionIntent)(je))throw await ut(je.response),j(),new $e.FloPayError("PayPal checkout already settled.","api_error",{code:Nl});if(je.provider!=="paypal"||je.providerObjectType!==oe)throw new Error(f);return te.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),je.providerObjectId},Ot=(f,S)=>{let ne=S?.nonce??Fr.current;if(!ne)return;let qe=S?.sessionId??e,je=(0,$e.resolvePayPalDeclineReason)(f);new ci.PaymentAPI(Re,{telemetry:!1}).reportSessionIntentDecline(qe,ne,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:je}).catch(()=>{})},ot=Ke;k("loadScript:scheduled (deferred 1 tick)");let pr=null,Ne=setTimeout(()=>{if($t){k("loadScript:skipped (cancelled before defer ran)");return}k("loadScript:start");let f=zr==="live"?"production":zr,S={};oe==="subscription"?S={intent:"subscription",vault:!0}:oe==="order"&&(S={intent:"capture"}),pr=(0,zl.loadScript)({clientId:c,currency:m,...S,...f?{environment:f}:{},...f==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let ne=!1;pr.then(qe=>{if(ne=!0,k(`loadScript:resolved inactive=${Ye()} ns=${!!qe} buttons=${!!qe?.Buttons}`),Ye())return;if(!qe?.Buttons){k("FAIL: namespace missing Buttons factory"),Z("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}te.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"provider_ready",durationMs:te.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),te.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let je=async(Ae,ht)=>{if(Ye()||Ze.current!==ot)return;let ae=Ae.vaultSetupToken??Ae.subscriptionID??Ae.orderID??"",It=ae?on.current.get(ae):or.current.get(ot);if(!(!It||!an(It.generation))&&Xr(It.generation)){on.current.delete(ae),or.current.delete(It.surfaceKey),Vt("approved");try{if(X(!0),(0,Qe.invokeMerchantCallback)(()=>dr.current?.(null)),!ae)throw new $e.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Et=(0,$e.resolvePayPalApprovalIdentity)({accountPatch:It.accountPatch,email:Yt.current,billingName:Nn.current,session:Rn.current});if((0,$e.needsPayPalPayerDetails)(Et))try{Et=(0,$e.mergePayPalPayerIdentity)(Et,await ht?.order?.get?.())}catch{}if((nr.current||Rt)&&!(0,$e.isValidEmail)(Et.email)){let Bt=await ft("PayPal",Et);if(!Bt)return;Et=Bt}(0,$e.isValidEmail)(Et.email)&&(It.accountPatch=(0,Pn.compactBuyerIdentity)({...It.accountPatch,...Et}),await nr.current?.(Et));let Wr=(0,$e.buildPayPalTokenizedBody)(ae,er);await re(Wr,It)}catch(Et){ze(Et instanceof Error?Et.message:"PayPal capture failed.")}finally{Ye()||X(!1)}}},ye=Ae=>{let ht=fe?()=>Ee(fe):()=>pe(Ae);return async()=>ln(await ht())},tr=qe.Buttons({style:{layout:"horizontal",height:di,tagline:!1},...it==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Ae,ht)=>{if(Ye()){await ht.reject();return}Zn();let ae=Qt.current,It={};if(ae)try{let Bt=await ae("paypal");if(Ye()){await ht.reject();return}if(!Bt.proceed){Xt.current=null,or.current.delete(ot),await ht.reject();return}It={sessionId:Bt.sessionId,accountPatch:Bt.accountPatch,nonce:Bt.nonce}}catch(Bt){k(`onClick:runBeforeButtonClick rejected msg=${(Bt instanceof Error?Bt.message:String(Bt)).slice(0,120)}`),Xt.current=null,or.current.delete(ot),await ht.reject();return}(0,Qe.invokeMerchantCallback)(()=>Yr.current?.("paypal"));let Et=Wt(),Wr={generation:Et,surfaceKey:ot,...It};Xt.current=Wr,or.current.set(ot,Wr),He.current={...N,attempt:Et},await ht.resolve(),te.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),lt.current=te.startTiming()},createOrder:oe==="order"?ye("Failed to create PayPal order."):void 0,createSubscription:oe==="subscription"?ye("Failed to create PayPal subscription."):void 0,createVaultSetupToken:oe==="setup_token"?async()=>ln(await pe("Failed to create PayPal setup token.")):void 0,onApprove:je,onCancel:()=>{if(Ye())return;let Ae=or.current.get(ot)??Xt.current,ht=Ae&&an(Ae.generation)?(0,$e.buildPayPalCancelEvent)(Ae.sessionId??e,er):null;Ae&&or.current.delete(Ae.surfaceKey),Xt.current=null,Vt("cancelled"),te.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Me.current=!0,Ce({generation:Ae?.generation,remount:!0,focus:!1}),ht&&(0,Qe.invokeMerchantCallback)(()=>ct.current?.(ht))},onError:Ae=>{if(Ae instanceof $e.FloPayError&&Ae.code===Nl)return;let ht=Ae instanceof Error?Ae.message:"PayPal failed to render.";if(Ye()||Ze.current!==ot){zt(ht)||Jr(Un());return}if(jr){let ae=or.current.get(ot)??Xt.current;if(!ae||!an(ae.generation)){if(zt(ht)){!ae&&!sn()&&Xr();return}Jr(ae||sn()?"stale_attempt":"no_current_attempt");return}if(k(`onError rendered=${jr} msg=${ht.slice(0,120)}`),zt(ht)){Xr(ae.generation);return}let{errorCode:It,popupBlocked:Et,providerDeclined:Wr,terminalReason:Bt}=(0,we.classifyExternalMethodFailure)(Ae,{inAppBrowser:xe.inAppBrowser,handoffObserved:J.current===ae.generation});if(Et&&O.markBlocked(),Vt(Bt),Wr){te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Bt}),Ot(Ae,ae),(0,Qe.invokeMerchantCallback)(()=>xr.current?.(br("paypal",ht))),or.current.delete(ae.surfaceKey),Xt.current=null,Xr(ae.generation);return}te.error({errorCode:It,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Bt}),or.current.delete(ae.surfaceKey),Xt.current=null,Ce({generation:ae.generation,remount:!0,showRetry:!0,focus:!0}),hr(Ae,{code:"paypal_runtime_failed",popupBlocked:Et,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:it,terminalReason:Bt});return}k(`onError rendered=${jr} msg=${ht.slice(0,120)}`),Z(zt(ht)?"teardown":"pre_ready_callback",ht)}}),ee=tr.isEligible();if(k(`isEligible=${ee}`),te.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ee){Be(!1),Z("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}co=!0,Qn=tr,vr=()=>{if(!st||ur||Ye()||jr)return;ur=!0,k(`container:dims ${Rr(Nt)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Zr=new MutationObserver(ht=>{if(!Ye()){for(let ae of ht)if(ae.type==="childList")ae.addedNodes.forEach(It=>{if(!(It instanceof Element))return;let Et=It.tagName.toLowerCase(),Wr=(It.getAttribute("title")??"").slice(0,40),Bt=Et==="iframe"?` ${zn(It)}`:"";k(`child+ ${Et}${Wr?` title="${Wr}"`:""}${Bt} dims=${Rr(It)}`)});else if(ae.type==="attributes"&&ae.target instanceof Element){let It=ae.target;if(It.tagName.toLowerCase()!=="iframe")continue;let Et=ae.attributeName;(Et==="src"||Et==="srcdoc")&&k(`attr~ iframe ${Et}=${Et==="srcdoc"?`[${(It.getAttribute("srcdoc")??"").length}ch]`:ho(It.getAttribute("src"))} dims=${Rr(It)}`)}}}),Zr.observe(Nt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ae=ht=>{if(Ye()||jr)return;let ae=Nt.querySelectorAll("iframe"),It=typeof document<"u"&&"hasStorageAccess"in document;k(`watchdog:${ht} container=${Rr(Nt)} children=${Nt.childElementCount} iframes=${ae.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${It} paypalNetRequests=${Lr.value}`),ae.forEach((Et,Wr)=>{let Bt=(Et.getAttribute("title")??"").slice(0,40);k(` iframe[${Wr}] ${Rr(Et)}${Bt?` title="${Bt}"`:""} ${zn(Et)}`);let Mo=uo(Et);Mo&&k(` ${Mo}`)}),Vr.length===0&&k(" (no PayPal/zoid window errors captured)")};cn.push(setTimeout(()=>Ae("3s"),3e3)),cn.push(setTimeout(()=>Ae("8s"),8e3)),cn.push(setTimeout(()=>Ae("15s"),15e3))},vr(),k("render:start");let Po=te.startTiming();dn=setTimeout(()=>{Ye()||jr||(k("watchdog:11s retryable render timeout"),Z("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Pd);let To=tr.render(Nt);(async()=>{try{if(await To,k(`render:resolved inactive=${Ye()}`),ve(),Ye()){yn();return}jr=!0,Be(!0),at(!1),Gt.current?.("ready"),te.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"checkout_render",durationMs:te.elapsed(Po),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Ae){let ht=Ae instanceof Error?Ae.message:"PayPal failed to render.";k(`render:rejected msg=${ht.slice(0,120)}`),ve(),Z(zt(ht)?"teardown":"render_rejected",ht)}})()}).catch(qe=>{let je=qe instanceof Error?qe.message:"PayPal operation failed.";k(`provider:failed msg=${je.slice(0,120)}`);let ye="script_rejected";ne&&zt(je)?ye="teardown":ne&&co&&(ye="render_rejected"),Z(ye,je)})},0);return()=>{$t=!0,clearTimeout(Ne),Tn&&clearTimeout(Tn),ve(),Q.current===xt&&(Q.current=null),yn(),lt.current=null,He.current=null}},[Te,Re,c,m,p,oe,it,De,e,fe,Ke,K,ft,Rt,k,Vt]);let _n=A?(0,vn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ft?"#fef2f2":"#f3f4f6",border:`1px solid ${Ft?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Pe} failed=${Ft})`,le.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${se.join(`
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:`
3
+ ${le.join(`
4
+ `)}`]}):null;return Ft&&!u?A?(0,vn.jsx)("div",{children:_n}):null:(0,vn.jsxs)("div",{children:[_n,bt&&(0,vn.jsx)(Go,{identity:bt.identity,methodLabel:bt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:V,onCancel:()=>V(null)}),(0,vn.jsxs)("div",{"aria-hidden":M||bt?!0:void 0,style:M||bt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:di},children:[!Pe&&!M&&(0,vn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,vn.jsx)("div",{ref:W,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:di,display:"flex",opacity:Pe?1:0},"aria-busy":ue||h},Ke)]},Ke),Ge&&(0,vn.jsx)("button",{ref:be,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Ur,style:vd,children:"Try PayPal again"})]})}function wa(e){return(0,vn.jsx)(ql,{...e})}function jl(e){return(0,vn.jsx)(ql,{...e})}var ka=require("react/jsx-runtime");function Jo({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,ka.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...r?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...n??{}},children:[r&&(0,ka.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ka.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var vt=require("@flopay/shared");var gr=require("react/jsx-runtime");var wd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function rn({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:s="PAYMENT FAILED",successNote:c="You will be automatically redirected, do not close or navigate away from this window.",theme:p=wd}){let m={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,gr.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,gr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...p.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,gr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,gr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,gr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,gr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,gr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,gr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,gr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,gr.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,gr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,gr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,gr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,gr.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,gr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:p.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&s]}),e==="success"&&c!==null&&(0,gr.jsx)("p",{style:m,children:c}),e==="error"&&t&&(0,gr.jsx)("p",{style:m,children:t}),(0,gr.jsx)("style",{children:`
5
5
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
6
6
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
7
7
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
8
8
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
9
- `})]})})}var 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=`
9
+ `})]})})}var Vl=require("@flopay/shared"),Nr=require("react");var Wl=require("react/jsx-runtime");function Ra({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,c]=(0,Nr.useState)(e instanceof Promise?null:e),[p,m]=(0,Nr.useState)(t instanceof Promise||!t?null:t),g=(0,Nr.useRef)(null),_=(0,Nr.useRef)(null),E=Xo(n);(0,Nr.useEffect)(()=>{E({class:"lifecycle",name:"checkout.mount"})},[E]),(0,Nr.useEffect)(()=>{s&&E({class:"lifecycle",name:"sdk.initialize.ready"})},[E,s]),(0,Nr.useEffect)(()=>{if(s)return Sr(s)?.subscribe?.(E)},[E,s]),(0,Nr.useEffect)(()=>{if(!(!p||p===s))return Sr(p)?.subscribe?.(E)},[E,s,p]),(0,Nr.useEffect)(()=>{if(!s)return;let T=Sr(s);return g.current=T?.beginCheckout()??T?.now()??0,T?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{T?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Nr.useEffect)(()=>{let T=!1;return e instanceof Promise?e.then(Y=>{T||c(Y)},()=>{T||E({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{T=!0}},[E,e]),(0,Nr.useEffect)(()=>{let T=!1;if(!t){m(null);return}return t instanceof Promise?t.then(Y=>{T||m(Y)},()=>{T||E({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{T=!0}},[E,t]),(0,Nr.useEffect)(()=>{if(!s||_.current===s)return;_.current=s;let T=Sr(s);T?.log({name:"checkout.rendered",stage:"checkout_render"}),E({class:"lifecycle",name:"checkout.rendered"}),T?.performance({stage:"checkout_render",durationMs:T.elapsed(g.current??0),durationMode:"machine"})},[E,s]);let I=(0,Vl.resolveBillingApiUrl)(r?.billingApiUrl),H=(0,Nr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:I,emitInstrument:E}),[s,p,I,E]);return(0,Wl.jsx)(hn.Provider,{value:H,children:a})}var Dn=require("@flopay/shared");async function ui(e,t){e.current?.abort();let r=new AbortController;e.current=r;try{return await t(r.signal)}finally{e.current===r&&(e.current=null)}}var $r=require("@flopay/js"),pt=require("@flopay/shared");var _a="card";async function kd(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:s,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:s??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function Rd(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:p}=await e.confirmCardSetup(t,r);return{error:p,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:s}=await e.confirmCardPayment(t,r);return{error:s,intent:a??null}}function Zo(e){return new pt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ed(){return new pt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function ss(e,t){return Object.assign(e,{checkoutMethod:t})}function oo(e,t){let r=e instanceof pt.FloPayError?e:new pt.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Ea(e,t){try{return await e()}catch(r){throw oo(r,t)}}function Hl(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Kl(e){return(0,$r.runSavedCardChallenge)(e)}function Ia(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new $r.PaymentAPI(e),c=(0,$r.beginSavedCardChallengeTelemetry)(s,t,r);return c?{telemetry:c,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function Qo(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,c=new $r.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,$r.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:_=>Hn({type:_.declineReason??"authorization_declined",gatewayErrorCode:_.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},c)}catch(_){if(a.aborted||_ instanceof Error&&_.name==="AbortError")throw _ instanceof pt.FloPayError&&_.code==="three_ds_aborted"?_:Zo(_);if(!(_ instanceof pt.FloPayError)||_.code!=="three_ds_timeout"&&_.code!=="checkout_processing_timeout")throw _;try{m=await c.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(I){if(a.aborted)throw Zo(I);if(!(I instanceof pt.FloPayError)||I.code!=="checkout_processing_timeout")throw I}let E=m&&yo(m,t.session);if(!to(E)&&E?.status!=="expired"){if(t.telemetry){let I=new $r.PaymentAPI(r);try{I.reportThreeDsAbandoned(n)}finally{I.destroy()}}throw Ed()}}let g=m&&yo(m,t.session);if(!to(g))throw $o(g);return{...eo(g,n),checkoutMethod:"card"}}function Hn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,s=(0,wo.applyFriendlyMessageOverride)(a)??a,c=ss(new pt.FloPayError(s,"api_error",{code:e?.code??(0,pt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,pt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(c.orderId=e.orderId),c}function is(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function pi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Gl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||pi(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,s=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let p of s)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||pi(p)))return p;let c=a.gateways;if(c&&typeof c=="object"){let p=c.stripe;if(p&&typeof p=="object"){let m=p,g=[m.stripeClientSecret,m.clientSecret];for(let _ of g)if(typeof _=="string"&&_.length>0&&(!t?.requirePaymentIntentClientSecret||pi(_)))return _}}}}async function _d({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Gl(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let p=(await new $r.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(pi(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function ea({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:c}){let p=e.replace(/\/+$/,""),m=t??r.id,g=n??r.clientSecret,_=r.customer?.id??r.accountData?.userId??"",E=r.customer?.email??r.accountData?.email??"",I=r.customer?.firstName??r.accountData?.firstName??"",H=r.customer?.lastName??r.accountData?.lastName??"",T=r.customer?.country??r.accountData?.country??void 0,Y=r.customer?.zip??r.accountData?.zip??void 0,y=await new $r.PaymentAPI(p,c===!1?{telemetry:!1}:void 0).processPayment(_,{sessionId:m,nonce:g,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:_,email:E,firstName:I,lastName:H,country:T,zip:Y},returnUrl:s??is(r)});if(y.ok){let w=typeof y.json=="function"?await y.json().catch(()=>null):null;if((0,pt.isAuthorizationOnlySession)(r)||w?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof w?.paymentId=="string"?w.paymentId:r.paymentId,sessionId:typeof w?.sessionId=="string"?w.sessionId:m,authorizationExpiresAt:typeof w?.authorizationExpiresAt=="string"?w.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:va(a),checkoutMethod:$l(a,r)}};let Te=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Te?{paymentIntentId:Te}:{},paymentMethodId:va(a),checkoutMethod:$l(a,r)}}}let h;try{h=await y.json()}catch(w){throw new pt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status,cause:w})}if(h?.type==="3ds_required"&&typeof h.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:h.nextActionRedirectUrl};if(h?.type==="paypal_redirect_required"||h?.type==="3ds_required"){let w=Gl(h);if(!w)throw new pt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:y.status});return{type:h.type,threeDSecureToken:w,paymentMethodId:h.paymentMethodId}}if(h?.gatewayErrorCode==="authentication_required"){let w=await _d({billingApiUrl:p,sessionId:m,nonce:g,responseJson:h});if(w)return w;throw ss(new pt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ge=new pt.FloPayError(h?.message??"Payment failed. Please try again.","api_error",{code:h?.code??h?.gatewayErrorCode,declineCode:h?.declineCode??h?.gatewayDeclineReason,statusCode:y.status});throw Object.assign(ge,{telemetryOutcome:(0,pt.classifyPaymentRejection)(y.status,h)})}async function mi(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:m,signal:g}){let _=t?.getRawProvider();if(!_)throw oo(new pt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw ss(new pt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let E=(0,pt.isSetupIntentClientSecret)(e.threeDSecureToken),I=null,H=e.paymentMethodId,T=await Ea(()=>kd(_,e.threeDSecureToken,E),"card");if(T){if(T.error)throw oo(new pt.FloPayError(T.error.message??`Failed to retrieve 3DS ${E?"setup":"payment"} status.`,"api_error",{code:T.error.code}),"card");let F=T.intent;!H&&F?.payment_method&&(typeof F.payment_method=="string"?H=F.payment_method:"id"in F.payment_method&&(H=F.payment_method.id??void 0))}let Y=H?await Ea(()=>Rd(_,e.threeDSecureToken,{payment_method:H,return_url:p??is(c)??window.location.href},E),"card"):null;if(Y){if(Y.error)throw oo(new pt.FloPayError(Y.error.message??"3DS authentication failed.","api_error",{code:Y.error.code}),"card");I=Y.intent}else{let F=await Ea(()=>_.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(F.error)throw oo(new pt.FloPayError(F.error.message??"3DS authentication failed.","api_error",{code:F.error.code}),"card");I=(E?F.setupIntent:F.paymentIntent)??null}if(I&&(I.status==="requires_capture"||I.status==="succeeded"||I.status==="processing")){let F=await ea({billingApiUrl:a,sessionId:s,session:c,telemetry:m,tokenizedData:{id:I.id,type:"card",threeDSecureActionResultTokenId:I.id},returnUrl:p});return F.type==="success"?{...F.result,paymentIntentId:F.result.paymentIntentId??I.id,paymentMethodId:F.result.paymentMethodId??H}:F.type==="next_action_required"?Qo(F,{billingApiUrl:a,sessionId:s??c.id,session:c,signal:g}):mi(F,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:c,returnUrl:p,telemetry:m,signal:g})}throw oo(new pt.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let E=(r??t)?.getRawProvider();if(!E)throw oo(new pt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:H}=await Ea(()=>E.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(H)throw oo(new pt.FloPayError(H.message??"PayPal authorization failed.","api_error",{code:H.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:I}=await Ea(()=>E.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??is(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(I)throw oo(new pt.FloPayError(I.message??"PayPal authorization failed.","api_error",{code:I.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new pt.FloPayError("Unsupported payment redirect state.","api_error")}function Ta(e){if(e instanceof pt.FloPayError){let n=(0,wo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new pt.FloPayError(n,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",r=(0,wo.applyFriendlyMessageOverride)(t)??t;return new pt.FloPayError(r,"api_error")}function ls(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,pt.isMountableVaultBlock)(e.data.session?.vault)||(0,An.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new pt.FloPayError("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function $l(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,An.canRecoverHostedCardForm)(t)?"card":void 0}async function cs({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let s=t&&t!==e?t:void 0,[c,p]=await Promise.all([(0,$r.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,$r.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(g=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",g),null)):Promise.resolve(null)]);if(!c)throw new pt.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=c),{flopay:c,paypalFlopay:m}}var Ln=require("@flopay/js"),l=require("@flopay/shared"),sr=require("@stripe/react-stripe-js"),o=Qi(require("react"),1);function Eo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function yi(e,t){if(e)return{error:r=>e.error(Eo(t,r)),log:r=>e.log(Eo(t,r)),performance:r=>e.performance(Eo(t,r)),terminal:r=>e.terminal(Eo(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var ao=require("@flopay/shared"),Xl=require("react");var Yl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var Ir=require("react/jsx-runtime"),Id=`
10
10
  .paypal-buttons { margin: 0 !important; vertical-align: top !important; }
11
11
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
12
12
  @keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
@@ -27,7 +27,7 @@ ${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: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:Ze}=$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:Ze,onCancel:()=>Ze(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(),Ze=(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(()=>{(Ze.current?.querySelector("iframe")??Ze.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,Qe=_r?.retryIdentity===Kt?_r.authorizationAttemptId:(0,l.randomUuidV4)();Me.current={authorizationAttemptId:Qe,retryIdentity:Kt};let ar=await Qr("processing","intent_create",Si(n,me,rt,Et??"",{...Qt,authorizationAttemptId:Qe},{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:Ze,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)(""),Ze=!(0,l.isValidEmail)(n?.trim()),Le=!Ze||(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:[Ze&&(0,u.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ze&&(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:Ze,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 Ze((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,Ze,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:Ze,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 Qe=(0,o.useMemo)(()=>(0,l.resolveAVSConfig)(je),[je]),ar=Qe!==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=Qe?(0,l.isAVSFieldVisible)(Qe.postal_code,i):!1;return eu(i,Wr,C)},[Qe,$t,Wr]),{avsInvalid:wr,invalidAvsFields:qr}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!he||!Qe)return{avsInvalid:!1,invalidAvsFields:i};let C=$t,K=(_e,zt)=>(0,l.isAVSFieldVisible)(_e,C)&&!zt.trim(),Ie={line1:K(Qe.address_line_1,nr),city:K(Qe.city,Jt),state:K(Qe.state,$r),zip:Lt.empty||Lt.malformed};return{avsInvalid:Ie.line1||Ie.city||Ie.state||Ie.zip,invalidAvsFields:Ie}},[he,Qe,$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),[Xe,Ee]=(0,o.useState)(0);(0,o.useEffect)(()=>{Xe!==0&&te.current?.focus()},[Xe]);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,Qe==null&&!_n)},[he,oe,Y,Qe,_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:Qe,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:Qe,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:Qe,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:Qe,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,Qe,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&&!Qe||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:`
30
+ `,ta=44;function ra(){return(0,Ir.jsx)("style",{children:Id})}function Ma(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function xa({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Ir.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Ir.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,Ir.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:n})]})}function ds(e){return e!=="unavailable"&&e!=="load_error"}function fi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:c,backgroundColor:p,borderColor:m,textColor:g,borderRadius:_,fontFamily:E}){let I=(0,ao.resolveStripeMethodBrandVariant)(e,t),H=Yl[e],[T,Y]=(0,Xl.useState)(!1),F=!!H&&!T,y=I?.backgroundColor??p??"#ffffff",h=I?.borderColor??m??"#d1d5db",ge=I?.textColor??g??"#262833";return(0,Ir.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&c()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ta,padding:"0 1rem",backgroundColor:y,color:ge,border:`1px solid ${h}`,borderRadius:_??8,fontSize:"0.95rem",fontWeight:600,fontFamily:E,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,Ir.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,ao.getStripeMethodDisplayName)(e)}\u2026`}):(0,Ir.jsxs)(Ir.Fragment,{children:[(0,Ir.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,ao.hasVendoredStripeMethodLogo)(e)?8:0},children:[F?(0,Ir.jsx)("img",{src:H,alt:"","aria-hidden":"true",onError:()=>Y(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!F&&I?.logoSvg?(0,Ir.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:I.logoSvg}}):null,(0,Ir.jsx)("span",{children:(0,ao.getStripeMethodDisplayName)(e)})]}),s&&(0,Ir.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ge,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,Ir.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function gi(e){let t=new Set(e.map(ao.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var hi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Pi={type:"accordion",defaultCollapsed:!1,radios:"never"};function vi({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:c,children:p}){return(0,Ir.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:s,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...c??{}},children:p})}var mn=require("react");var Aa=require("@flopay/shared"),Td=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function Md(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Td.has(t.charAt(0).toLowerCase()+t.slice(1))}function xd(e,t){return typeof t=="number"&&t!==0&&!Md(e)?`${t}px`:String(t).trim()}function Jl(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=xd(r,n)}}}var _o=require("react/jsx-runtime"),us=new WeakSet;function fo({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:c,containerStyle:p,onReady:m,onError:g,onValidation:_}){let E=(0,mn.useRef)(null),I=(0,mn.useRef)(m),H=(0,mn.useRef)(g),T=(0,mn.useRef)(_);I.current=m,H.current=g,T.current=_;let Y=(0,mn.useRef)(s);Y.current=s;let F=(0,mn.useRef)(null),y=c??void 0,h=(0,mn.useRef)(y);h.current=y;let ge=(0,mn.useRef)(void 0);return(0,mn.useEffect)(()=>{let w=E.current;if(!w)return;let Te=!0,x=!1,ie=()=>{!Te||x||(x=!0,I.current?.())},he=e.on("ready",()=>{ie()}),fe=e.on("error",A=>{H.current?.(A.message??"There was a problem loading the secure card form.")}),ke=e.on("validation",A=>{T.current?.(A.message??null)}),mt=h.current??(us.has(e)?null:void 0),Je={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...Y.current?{theme:Y.current}:{},...mt===void 0?{}:{submitLabel:mt}};return F.current=Y.current??null,ge.current=h.current,h.current!==void 0&&us.add(e),e.mount(w,Je).then(()=>{ie()}).catch(A=>{Te&&H.current?.(A instanceof Error?A.message:"Failed to load the secure card form.")}),()=>{Te=!1,he(),fe(),ke(),e.unmount()}},[e,t,r,n,a]),ko(()=>{let w=E.current;w&&Jl(w,p)},[p]),(0,mn.useEffect)(()=>{s!==void 0&&(s===null&&F.current===null||(F.current=s,e.applyTheme?.(s)))},[e,s]),(0,mn.useEffect)(()=>{y!==ge.current&&(ge.current=y,y!==void 0&&us.add(e),e.setSubmitLabel?.(y??null))},[e,y]),(0,_o.jsx)("div",{ref:E,"data-testid":"flopay-vault-card-fields"})}function Ci({label:e}){return(0,_o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,_o.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,_o.jsx)("span",{children:e}),(0,_o.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var Ss=require("@flopay/shared"),d=require("react/jsx-runtime"),Kn="flopay_stripe_resume",Zl="flopay_wallet_resume",lc="fw1",Ad="fw2",cc=300*1e3,Fd=900,Bd="express_checkout_click_timeout",Dd=25e3,Od=25e3,Ld=1e4,On={provider:"paypal",paymentMethodCategory:"paypal"},Nd="x-flopay-process-result-source",Ud="status";async function zd(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var bi={},Ba=class{constructor(t){this.reason=t}};function qd(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function lr(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function vs(e){return`${Ad}:${e}`}function Si(e){return lr(vs(e))}function wi(e,t){if(typeof window>"u")return null;let r=vs(e);try{let n=localStorage.getItem(r);if(!n)return null;let a=JSON.parse(n);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>cc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Si(e),null):a}catch{return Si(e),null}}function jd(e){return lr(vs(e.sessionId),e)}function Ql(e,t,r){let n=wi(e,t);return!n||n.clientSecret!==r?!1:Si(e)}function ps(e,t,r){if(typeof window>"u")return;wi(e,t)?.clientSecret===r&&Si(e)}function Vd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ms(e,t,r){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let n=r?e.status==="succeeded":Pa(e.status),a=Vd(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function ec(e,t,r){let n=null;try{return await Promise.race([Al(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Ld),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Wd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function dc(e){return e instanceof l.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ki(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Ln.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw dc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var ys=l.STRIPE_PAYPAL_RESUME_KEY,Fa=new Map,$d=250,tc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Hd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Cs(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function Ri({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Ln.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Kd(e){return e instanceof l.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function uc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,Ho.splitFullName)(r),c=s.firstName?s:(0,Ho.splitFullName)(n?.name);return(0,Pn.compactBuyerIdentity)({email:(0,l.isValidEmail)(a)?a:n?.email?.trim(),firstName:c.firstName,lastName:c.lastName})}async function Gd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let c=uc({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,l.isValidEmail)(c.email)?c:s(a,c)}var Da=180,rc=`flopay-card-enter ${Da}ms cubic-bezier(0, 0, 0.2, 1) both`,nc=`flopay-card-exit ${Da}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Yd=`flopay-buttons-enter ${Da}ms cubic-bezier(0, 0, 0.2, 1) both`,Xd=`flopay-buttons-exit ${Da}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Jd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function bs(e){return(0,l.derivePrimaryTileStyle)(e)}var Zd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Qd(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var gs={width:"100%",minHeight:ta,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function oc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function hs(e){return e==="paypal"?"PayPal":(0,l.getStripeMethodDisplayName)(e)}function eu(e){let t=(0,l.getPostalCodeExample)(e);return`Enter a valid ${(0,l.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function tu(e,t,r){let n=(0,l.isPostalCodeSupported)(e),a=t.trim(),s=r&&n,c=s&&!a,p=s&&!!a&&!(0,l.isValidPostalCode)(e,a);return{visible:r,supported:n,required:s,empty:c,malformed:p}}function ru(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,l.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function nu(e){return typeof e=="number"?`${e}px`:e}function Ei(e){return(0,d.jsx)(iu,{...e})}function ac({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:c=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:g,runBeforeButtonClick:_,billingName:E,onBuyerIdentityReady:I,onLoadStateChange:H,placeholderBorderRadius:T,popupCapabilityOwner:Y,externalTelemetryContext:F,presentationMode:y}){let h=no(),{emitInstrument:ge}=(0,o.useContext)(hn),w=(0,sr.useStripe)(),Te=(0,sr.useElements)(),x=(0,o.useMemo)(()=>yi(Sr(h),F),[F,h]),[ie,he]=(0,o.useState)("loading");(0,o.useEffect)(()=>{H?.(ie)},[ie,H]);let[fe,ke]=(0,o.useState)(!1),mt=(0,o.useRef)(!1),Je=!(0,l.isValidEmail)(r?.trim())||!E?.trim(),{request:A,collect:kt,finish:tt}=Ko(),Ve=(0,o.useRef)(!1),me=(0,o.useRef)(null),K=(0,o.useRef)(null),[W,Fe]=(0,o.useState)(0),[lt,He]=(0,o.useState)(!1),J=(0,o.useRef)(!1),D=(0,o.useRef)(new Map),{startAttempt:se,finishAttempt:O,invalidateAttempt:be,isAttemptInvalidated:Me,isAttemptCurrent:Pe,generationRef:Be}=Sa((de,ue,X)=>{g?.(de,ue,{...X,popupBlocked:X?.popupBlocked??(0,we.isPopupBlockedError)(ue),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y,terminalReason:"overlay_timeout"}),He(!0),Fe(bt=>bt+1)},{onHandoffObserved:()=>{Y.markAvailable(),x?.log({name:"provider.popup.opened",stage:"overlay_open",...On,attempt:Be.current})}});(0,o.useEffect)(()=>{lt&&K.current?.focus()},[lt,W]);let M=(0,o.useCallback)(()=>{Fe(de=>de+1)},[]),at=(0,o.useCallback)((de,ue,X)=>{be(X),g?.("paypal",de,{code:ue,popupBlocked:(0,we.isPopupBlockedError)(de),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:y}),He(!0),M()},[be,g,y,M]),Ke=(0,o.useCallback)(()=>{window.setTimeout(()=>{(me.current?.querySelector("iframe")??me.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{J.current&&(J.current=!1,Ke())},[Ke,W]);let yt=(0,o.useCallback)(()=>{He(!1),s?.(null),Ke()},[Ke,s]);(0,o.useEffect)(()=>{if(!w||Ve.current)return;let[de,ue,X]=(0,l.readStripeRedirectParams)();if(!de||!ue)return;let bt=(0,l.readMatchingStripePayPalContinuation)(ue);if(!bt)return;Ve.current=!0;let ft=!0,V=Fa.get(ue);V||(V=X==="failed"?Promise.resolve(null):Promise.resolve().then(()=>w.retrievePaymentIntent(ue)),Fa.set(ue,V));let rt={accountPatch:bt.accountPatch,sessionId:bt.sessionId,nonce:bt.nonce},Rt=()=>{x?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...On,requestCategory:"provider_sdk"})};return x?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...On}),(async()=>{try{ke(!0);let v=await V;if(!ft)return;if(v?.error){Fa.delete(ue),Rt(),s?.(v.error.message??"Failed to retrieve PayPal payment status.");return}if((0,l.clearStripePayPalReturn)(),Fa.delete(ue),X==="failed"){let oe="PayPal payment was declined. Please try again.";x?.terminal({outcome:"payment_declined",...On,terminalReason:"provider_declined"}),s?.(oe),m?.(br("paypal",oe));return}let q=v?.paymentIntent;if(q&&q.id!==de){Rt(),s?.("Failed to match the returned PayPal payment.");return}if(q&&(q.status==="requires_capture"||q.status==="succeeded")){let oe=typeof q.payment_method=="string"?q.payment_method:q.payment_method?.id;a({id:oe??q.id,type:"card",threeDSecureActionResultTokenId:q.id,isPaypal:!0},{...rt,presentationMode:"redirect"})}else{let oe="PayPal payment was not completed. Please try again.";x?.terminal({outcome:q?.status==="canceled"?"payment_cancelled":"payment_declined",...On,terminalReason:q?.status==="canceled"?"cancelled":"provider_declined"}),s?.(oe),m?.(br("paypal",oe))}}catch(v){if(!ft)return;Fa.delete(ue),Rt(),s?.(v instanceof Error?v.message:"Failed to complete PayPal payment.")}finally{ft&&ke(!1)}})(),()=>{ft=!1,Ve.current=!1}},[w,a,s,m,x]);let Ze=(0,o.useCallback)(async(de=!1)=>{let ue=_?await _("paypal"):{proceed:!0};if(!ue.proceed)return D.current.delete(W),!1;let X=se("paypal");return D.current.set(W,{generation:X,accountPatch:ue.accountPatch,sessionId:ue.sessionId,nonce:ue.nonce}),He(!1),x?.log({name:`provider.${de?"redirect.started":"handoff.requested"}`,stage:de?"redirect":"overlay_open",...On,attempt:X}),p?.("paypal"),!0},[p,x,_,se,W]),Ge=(0,o.useCallback)(async de=>{if(c||fe||!await Ze()){de.reject();return}de.resolve()},[c,Ze,fe]),_t=(0,o.useCallback)(async de=>{if(!w||!Te)return;let ue=D.current.get(W);if(ue&&!Pe(ue.generation)){D.current.delete(W);return}if(!ue&&Me()||ue&&!O(ue.generation))return;ue||O();let X=ue??null;if(D.current.delete(W),!X&&_){let Re=await _("paypal");if(!Re.proceed){de.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}X={accountPatch:Re.accountPatch,sessionId:Re.sessionId,nonce:Re.nonce}}let bt=X?.sessionId??e,ft=X?.nonce??t,V=await Gd({event:de,prepared:X,email:r,billingName:E,methodLabel:"PayPal",collect:kt});if(!V){de.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let rt=V.email,Rt={...X?.accountPatch,...(0,Pn.compactBuyerIdentity)(V,!0)};try{if(ke(!0),s?.(null),!bt||!(0,l.isValidEmail)(rt))throw new Error("Missing sessionId or email for PayPal payment");await I?.(V);let Re=w.createPaymentMethod,{error:v,paymentMethod:q}=await Re({type:"paypal"});if(v){at(v,"stripe_paypal_create_payment_method_failed",ue?.generation),de.paymentFailed({reason:"fail"});return}let oe=await ki(n,ge,bt,ft??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:q?.id??null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(oe)){de.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:Rt,paymentMethodCategory:"paypal",presentationMode:y,sessionId:bt,nonce:ft,settledProcessResponse:oe.response});return}if(oe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let xe=oe.clientSecret,Lt={return_url:(0,l.stripeRedirectReturnUrl)()};if(q?.id&&(Lt.payment_method=q.id),!lr(ys,{clientSecret:xe,sessionId:bt,nonce:ft,accountPatch:Rt})&&y==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:De,paymentIntent:Oe}=await w.confirmPayment({clientSecret:xe,confirmParams:Lt,redirect:"if_required"});if(De){if(lr(ys),(0,we.isProviderDecline)(De)){let u=De.message??"Your payment was declined.";x?.terminal({outcome:"payment_declined",...On,terminalReason:"provider_declined"}),s?.(u),m?.(br("paypal",u,{code:(0,we.getProviderErrorCode)(De),declineCode:(0,we.getProviderDeclineCode)(De)})),await Ri({billingApiUrl:n,sessionId:bt,nonce:ft,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,we.getProviderErrorCode)(De)??"provider_declined"}})}else at(De,"stripe_paypal_confirm_failed",ue?.generation);return}lr(ys);let Tt=typeof Oe?.payment_method=="string"?Oe.payment_method:Oe?.payment_method?.id;a({id:Tt??Oe?.id,type:"card",threeDSecureActionResultTokenId:Oe?.id,isPaypal:!0},{accountPatch:Rt,paymentMethodCategory:"paypal",presentationMode:y,sessionId:bt,nonce:ft});return}catch(Re){at(Re,"stripe_paypal_failed",ue?.generation)}finally{ke(!1)}},[w,Te,e,t,r,E,kt,I,n,ge,a,s,m,_,at,O,Pe,Me,x,y,W]),Ut=(0,o.useCallback)(async()=>{if(!(mt.current||c||fe||!w||!Te)){mt.current=!0,ke(!0);try{if(!await Ze(!0))return;await _t({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{mt.current=!1,ke(!1)}}},[Te,_t,c,Ze,w,fe]),qt=y==="redirect"?(0,d.jsx)("button",{type:"button",disabled:c||fe,onClick:()=>{Ut()},style:{width:"100%",minHeight:ta,border:"1px solid #d1d5db",borderRadius:T??8,background:"#ffc439",color:"#111827",cursor:c||fe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(sr.ExpressCheckoutElement,{onReady:de=>he(Ma(de,["paypal"])),onLoadError:()=>{he("load_error"),Cs(x,"paypal","paypal","provider_error")},onClick:Ge,onConfirm:_t,onCancel:()=>{let de=D.current.get(W);D.current.delete(W),x?.terminal({outcome:"payment_cancelled",...On,terminalReason:"cancelled",...de?{attempt:de.generation}:{}}),be(de?.generation),He(!1),J.current=!0,M()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Je,emailRequired:Je,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},W),Ft=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[lt&&(0,d.jsx)("button",{ref:K,type:"button","data-testid":"flopay-paypal-retry-button",onClick:yt,style:gs,children:"Try PayPal again"}),A&&(0,d.jsx)(Go,{identity:A.identity,methodLabel:A.methodLabel,onComplete:tt,onCancel:()=>tt(null)},A.id),(0,d.jsx)("div",{style:{display:A?"none":void 0},children:qt})]}),fe&&!A&&(0,d.jsx)(rn,{status:"processing"})]});return y==="redirect"?Ft:(0,d.jsx)(xa,{state:ie,placeholderTestId:"flopay-paypal-placeholder",borderRadius:T,children:Ft})}function fs(e){return e==="apple_pay"||e==="google_pay"}var ou=200;function au({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,l.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function ic({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:c,onErrorChange:p,onButtonClick:m,onDecline:g,onTechnicalFailure:_,runBeforeButtonClick:E,billingName:I,onBuyerIdentityReady:H,onLoadStateChange:T,placeholderBorderRadius:Y,popupCapabilityOwner:F,externalTelemetryContext:y}){let h=no(),{emitInstrument:ge}=(0,o.useContext)(hn),w=(0,sr.useStripe)(),Te=(0,sr.useElements)(),x=(0,o.useMemo)(()=>yi(Sr(h),y),[y,h]),[ie,he]=(0,o.useState)("loading");(0,o.useEffect)(()=>{T?.(ie)},[ie,T]);let[fe,ke]=(0,o.useState)(!1);(0,o.useEffect)(()=>{He.current=fe},[fe]);let mt=(0,o.useRef)(!(0,l.isValidEmail)(r?.trim())||!I?.trim()).current,{request:Je,collect:A,finish:kt}=Ko(),tt=(0,o.useRef)(null),Ve=(0,o.useRef)(null),[me,K]=(0,o.useState)(0),[W,Fe]=(0,o.useState)(()=>(0,l.shouldPreferWalletPopup)()),lt=(0,o.useRef)(W),He=(0,o.useRef)(!1),[J,D]=(0,o.useState)(!1),[se,O]=(0,o.useState)(()=>wi(e,t)?"blocked":"idle"),[be,Me]=(0,o.useState)("google_pay"),Pe=(0,o.useRef)(null),Be=(0,o.useRef)(!0),M=(0,o.useRef)(!1),at=(0,o.useRef)("google_pay"),Ke=(0,o.useRef)("google_pay"),yt=(0,o.useRef)(null),Ze=(0,o.useRef)(null),Ge=(0,o.useRef)(new Set),_t=(0,o.useRef)(null),Ut=(0,o.useRef)(null);(0,o.useEffect)(()=>(Be.current=!0,()=>{Be.current=!1;for(let u of Ge.current)window.clearTimeout(u);Ge.current.clear()}),[]);let qt=(0,o.useRef)(new Map),{startAttempt:Ft,finishAttempt:de,invalidateAttempt:ue,isAttemptInvalidated:X,isAttemptCurrent:bt,generationRef:ft}=Sa((u,C,Q)=>{_?.(u,C,{...Q,popupBlocked:Q?.popupBlocked??(0,we.isPopupBlockedError)(C),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Me(u),D(!0),K(le=>le+1)},{onHandoffObserved:u=>{Ut.current=ft.current,F.markAvailable(),x?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ft.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:fs,onMissingTerminalDeferred:(u,C)=>{let Q=x?.now()??globalThis.performance?.now()??Date.now(),le=_t.current,L=le?.generation===C?le.startedAt:Q;x?.performance({stage:"overlay_return",durationMs:Math.max(0,Q-L),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:C,...fs(u)?{walletType:u}:{}}),x?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{J&&Ve.current?.focus()},[J,me]);let V=(0,o.useRef)(0),rt=(0,o.useRef)(!1),Rt=(0,o.useCallback)(()=>{if(V.current>0){rt.current=!0;return}K(u=>u+1)},[]),Re=(0,o.useCallback)(()=>{V.current-=1,!(V.current>0||!rt.current)&&(rt.current=!1,Be.current&&K(u=>u+1))},[]),v=(0,o.useCallback)((u,C,Q,le,L=!1)=>{ue(le),_?.(u,C,{code:Q,popupBlocked:(0,we.isPopupBlockedError)(C),telemetryReported:L,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Me(u),D(!0),Rt()},[ue,_,Rt]),q=(0,o.useCallback)(u=>{x?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...fs(u)?{walletType:u}:{}}),_?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:Bd,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Me(u),D(!0)},[_,x]),oe=(0,o.useCallback)(()=>{window.setTimeout(()=>{(tt.current?.querySelector("iframe")??tt.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{M.current&&(M.current=!1,oe())},[oe,me]);let xe=(0,o.useCallback)(()=>{D(!1),p?.(null),oe()},[oe,p]),Lt=(0,o.useCallback)(()=>{Pe.current?.()},[]);(0,o.useEffect)(()=>{let u=null,C=()=>{u=null;let le=(0,l.shouldPreferWalletPopup)();le!==lt.current&&(lt.current=le,Fe(le),!He.current&&!bt(ft.current)&&Rt())},Q=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(C,ou)};return window.addEventListener("resize",Q),()=>{window.removeEventListener("resize",Q),u!==null&&window.clearTimeout(u)}},[ft,bt,Rt]),(0,o.useEffect)(()=>{let u=wi(e,t);if(!u)return;let C=!1,Q=!1,le=async()=>{if(!Q){Q=!0,C||O("checking");try{let L=await ec(w,u.clientSecret,Ge.current);if(C)return;let k=ms(L,u.providerObjectId,(0,l.isSetupIntentClientSecret)(u.clientSecret));if(k.kind==="confirmed"){if(!Ql(e,t,u.clientSecret))return;Pe.current=null,O("idle"),c({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(k.kind==="terminal"){ps(e,t,u.clientSecret),Pe.current=null,O("idle"),Me(u.paymentMethodType),D(!0),Rt();return}O("blocked")}catch{C||O("blocked")}finally{Q=!1}}};return Pe.current=le,O("blocked"),()=>{C=!0,Pe.current===le&&(Pe.current=null)}},[t,c,Rt,e,w]);let it=(0,o.useCallback)(async u=>{let C=!1,Q=!1,le=gt=>{C||Q||(C=!0,u.paymentFailed({reason:"fail",...gt?{message:gt}:{}}))};if(!w||!Te){le();return}let L=qt.current.get(me);if(L&&!bt(L.generation)){qt.current.delete(me),le();return}if(!L&&X()){le();return}if(L&&!de(L.generation)){le();return}L||(de(),rt.current=!1);let k=u.expressPaymentType??L?.method??at.current,jt=L??null,Mr=oc(k),dr;k==="apple_pay"?dr="apple_pay":k==="google_pay"&&(dr="google_pay");let xr=L?.generation??ft.current,ct=x,Gr=ct?.now()??globalThis.performance?.now()??Date.now(),Yr=new AbortController,Ar=!1,Gt=!1,nr=null,Qt=e,Rn="processing",Yt="other",Nn="provider_runtime",Fr,Xt=new Promise((gt,Mt)=>{Fr=Mt}),or=window.setTimeout(()=>{Ar=!0,Yr.abort(),Fr(bi)},Dd),on=async(gt,Mt,Br)=>{Rn=gt,Yt=Mt,Nn=Mt==="intent_create"||Mt==="session_claim"?"transport_error":"provider_runtime";let ar=ct?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Br,Xt])}finally{let Jt=ct?.now()??globalThis.performance?.now()??Date.now();ct?.performance({stage:gt,durationMs:Math.max(0,Jt-ar),durationMode:"machine",requestCategory:Mt,paymentMethodCategory:"wallet",provider:"stripe",...Ar?{statusClass:"timeout"}:{}})}};try{if(ke(!0),p?.(null),!jt&&E){let Se=await on("processing","other",E(Mr));if(!Se.proceed){le();return}jt={accountPatch:Se.accountPatch,sessionId:Se.sessionId,nonce:Se.nonce}}let gt=jt?.sessionId??e;Qt=gt;let Mt=jt?.nonce??t,Br=yt.current??jt?.accountPatch,ar=uc({event:u,fallbackEmail:Br?.email??r,fallbackName:[Br?.firstName,Br?.lastName].join(" ").trim()||I});if(!(0,l.isValidEmail)(ar.email)){le("Buyer details are required."),A(hs(k),ar).then(Se=>{Se&&(yt.current=Se)});return}yt.current=null;let Jt={...jt?.accountPatch,...(0,Pn.compactBuyerIdentity)(ar,!0)};await on("processing","session_claim",Promise.resolve(H?.(ar)));let{error:Ur}=await on("tokenization","provider_sdk",Te.submit());if(Ur){le(),v(k,Ur,"stripe_wallet_submit_failed",L?.generation);return}if(!gt)throw new Error("Missing sessionId or email for payment.");let hr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,paymentMethodId:null,intentKind:a},Vt=JSON.stringify({sessionId:gt,nonce:Mt??"",request:hr}),Dr=Ze.current,kr=Dr?.retryIdentity===Vt?Dr.authorizationAttemptId:(0,l.randomUuidV4)();Ze.current={authorizationAttemptId:kr,retryIdentity:Vt};let Le=await on("processing","intent_create",ki(n,ge,gt,Mt??"",{...hr,authorizationAttemptId:kr},{signal:Yr.signal}));if((0,l.isSettledSessionIntent)(Le)){le(),c({type:"card",paymentMethodType:k},{accountPatch:Jt,paymentMethodCategory:"wallet",sessionId:gt,nonce:Mt,settledProcessResponse:Le.response});return}if(Le.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Or=Le.clientSecret,Xr=jd({createdAt:Date.now(),sessionId:gt,...Mt?{nonce:Mt}:{},clientSecret:Or,providerObjectId:Le.providerObjectId,paymentMethodType:k,accountPatch:Jt});window.clearTimeout(or),Gt=!0,ct?.performance({stage:"callback",durationMs:Math.max(0,(ct?.now()??globalThis.performance?.now()??Date.now())-Gr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Xn=ct?.now()??globalThis.performance?.now()??Date.now(),Pr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...dr?{walletType:dr}:{},attempt:xr},an=!1,sn=null;ct?.log({name:"payment.provider_confirmation.started",...Pr}),nr=window.setTimeout(()=>{nr!==null&&Ge.current.delete(nr),an=!0;let Se=ct?.now()??globalThis.performance?.now()??Date.now();ct?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Pr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Se-Xn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),ct?.flush?.().catch(()=>{}),sn?.()},Od),Ge.current.add(nr);let En=(Se,Dt)=>{nr!==null&&(window.clearTimeout(nr),Ge.current.delete(nr),nr=null);let $t=ct?.now()??globalThis.performance?.now()??Date.now(),nt=Math.max(0,$t-Xn),Ye=Se;an&&(Se==="resolved"?Ye="resolved_late":Se==="returned_error"?Ye="returned_error_late":Ye="rejected_late");let Jr=Dt??(Se==="resolved"?"approved":"provider_error");return ct?.log({name:"payment.provider_confirmation.returned",...Pr,operationOutcome:Ye,terminalReason:Jr}),ct?.performance({...Pr,durationMs:nt,durationMode:"buyer",operationOutcome:Ye,terminalReason:Jr}),{durationMs:nt,operationOutcome:Ye,terminalReason:Jr}},Wt=!1,Ce=!1,ln=Se=>{if(!Se||typeof Se!="object")return null;let Dt=Se;if(Dt.error)return null;let $t=Dt.setupIntent??Dt.paymentIntent,nt=ms($t??null,void 0,!!Dt.setupIntent);return nt.kind==="confirmed"?nt:null},zr=Se=>{if(Wt||L&&ft.current!==L.generation)return;let Dt=ln(Se);if(!Dt)return;if(Xr&&!Ql(gt,Mt,Or)){Wt=!0;return}let{intentId:$t,paymentMethodId:nt}=Dt;Wt=!0,Ce=!0,Ze.current=null,Pe.current=null,Be.current&&(O("idle"),ke(!1));let Ye=`${lc}:${gt}`;lr(Ye,{createdAt:Date.now(),sessionId:gt,nonce:Mt,accountPatch:Jt,paymentMethodId:nt,providerIntentId:$t,paymentMethodType:k});try{c({id:nt,type:"card",threeDSecureActionResultTokenId:$t},{accountPatch:Jt,paymentMethodCategory:"wallet",sessionId:gt,nonce:Mt})}finally{lr(Ye)}},_n=!1;sn=async()=>{if(!(_n||Wt||Ce)){_n=!0,Be.current&&O("checking");try{let Se=await ec(w,Or,Ge.current);if(Wt||Ce)return;let Dt=(0,l.isSetupIntentClientSecret)(Or),$t=ms(Se,Le.providerObjectId,Dt);if($t.kind==="confirmed"){zr(Dt?{setupIntent:Se}:{paymentIntent:Se});return}if($t.kind==="terminal"){if(Ce=!0,ps(gt,Mt,Or),Ze.current=null,Pe.current=null,!Be.current)return;O("idle"),le(),v(k,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",L?.generation,!0);return}Be.current&&!Ce&&(O("blocked"),ke(!1))}catch{Be.current&&!Ce&&(O("blocked"),ke(!1))}finally{_n=!1}}},Pe.current=sn;let N,dt;try{Q=!0,V.current+=1;let Se;try{Se=await((0,l.isSetupIntentClientSecret)(Or)?w.confirmSetup({elements:Te,clientSecret:Or,redirect:"if_required"}):w.confirmPayment({elements:Te,clientSecret:Or,redirect:"if_required"}))}finally{Re()}if(!Se||typeof Se!="object")throw new Ba(qd(Se));if(N=Se,!N.error&&!ln(N))throw new Ba("confirmation_result_unconfirmed");dt=En(N.error?"returned_error":"resolved",N.error&&(0,we.isProviderDecline)(N.error)?"provider_declined":void 0)}catch(Se){let Dt=Se instanceof Ba?Se.reason:void 0,$t=Dt!==void 0,nt=En($t?"returned_error":"rejected");if(ct?.error({...$t?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Dt}:ns(Se),...Pr,operationOutcome:nt.operationOutcome,durationMs:nt.durationMs,statusClass:"unknown",terminalReason:nt.terminalReason}),!Be.current||Wt)return;await sn?.();return}let te=N.error;if(te){if(!Be.current||Wt)return;if((0,we.isProviderDecline)(te)){Ce=!0,ps(gt,Mt,Or),Ze.current=null,Pe.current=null,O("idle"),qt.current.get(me)===L&&qt.current.delete(me);let Se=te.message??"Your payment was declined.";p?.(Se),g?.(br(Mr,Se,{code:(0,we.getProviderErrorCode)(te),declineCode:(0,we.getProviderDeclineCode)(te)})),Ri({billingApiUrl:n,sessionId:gt,nonce:Mt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,providerDeclineReason:(0,we.getProviderErrorCode)(te)??"provider_declined",...Le.intentKind==="payment"&&Le.providerObjectId.startsWith("pi_")?{providerIntentId:Le.providerObjectId}:{}}})}else ct?.error({...ns(te),...Pr,operationOutcome:dt.operationOutcome,durationMs:dt.durationMs,statusClass:"unknown",terminalReason:dt.terminalReason}),await sn?.();return}if(zr(N),!Wt)throw new Error("Invalid provider returned for APM intent")}catch(gt){if(gt===bi){let Mt=ct?.now()??globalThis.performance?.now()??Date.now();ct?.error({errorCode:Wd(Yt),stage:Rn,requestCategory:Yt,paymentMethodCategory:"wallet",provider:"stripe",...dr?{walletType:dr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Qt,durationMs:Math.max(0,Mt-Gr),statusClass:"timeout",failureCategory:Nn,attempt:xr,terminalReason:"provider_error"}),ct?.flush?.().catch(()=>{})}le(),v(k,gt,gt===bi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",L?.generation,gt===bi)}finally{if(window.clearTimeout(or),nr!==null&&(window.clearTimeout(nr),Ge.current.delete(nr)),!Gt){let gt=ct?.now()??globalThis.performance?.now()??Date.now();ct?.performance({stage:"callback",durationMs:Math.max(0,gt-Gr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Ar?{statusClass:"timeout"}:{}})}Be.current&&ke(!1)}},[w,Te,e,t,r,I,A,H,n,ge,a,c,p,g,E,v,Re,de,bt,X,ft,x,me]),De=(0,o.useMemo)(()=>gi(s),[s]),Oe=(0,o.useMemo)(()=>s.map(l.stripeExpressMethodToOptionKey),[s]),Tt=(0,o.useMemo)(()=>(0,d.jsx)(sr.ExpressCheckoutElement,{onReady:u=>{he(Ma(u,Oe))},onLoadError:u=>{he("load_error"),Cs(x,"stripe","wallet","provider_error")},onClick:async u=>{let C=x?.now()??globalThis.performance?.now()??Date.now();at.current=u.expressPaymentType,Ke.current=oc(u.expressPaymentType);let Q=!0,le=window.setTimeout(()=>{Q=!1,u.reject(),q(u.expressPaymentType)},Fd),L=E?await E(Ke.current,{abandoned:()=>!Q}):{proceed:!0};if(window.clearTimeout(le),!Q)return;if(!L.proceed){qt.current.delete(me),u.reject();return}let k=Ft(u.expressPaymentType);rt.current=!1,_t.current={generation:k,startedAt:C},qt.current.set(me,{generation:k,method:u.expressPaymentType,accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce}),D(!1),x?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:k,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),m?.(Ke.current),u.resolve()},onConfirm:it,onCancel:()=>{let u=qt.current.get(me);qt.current.delete(me);let C=_t.current,Q=x?.now()??globalThis.performance?.now()??Date.now();if(u&&C?.generation===u.generation&&(0,l.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:Q-C.startedAt,handoffObserved:Ut.current===u.generation})){x?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:u.generation,walletType:"google_pay"}),Ze.current=null,v(u.method,new Error("The browser window is too small for the Google Pay sheet."),l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,u.generation,!0);return}x?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),ue(u?.generation),Ze.current=null,D(!1),M.current=!0,Rt()},options:{...hi,paymentMethods:De,emailRequired:mt,billingAddressRequired:mt}},me),[Oe,De,it,ue,m,mt,v,q,Rt,E,Ft,me,x]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(xa,{state:ie,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Y,children:(0,d.jsxs)("div",{ref:tt,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[J&&(0,d.jsxs)("button",{ref:Ve,type:"button","data-testid":"flopay-wallet-retry-button",onClick:xe,style:gs,children:["Try ",hs(be)," again"]}),se!=="idle"&&(0,d.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,d.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,d.jsx)("button",{type:"button",onClick:Lt,disabled:se==="checking",style:gs,children:se==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Je&&(0,d.jsx)(Go,{identity:Je.identity,methodLabel:Je.methodLabel,onComplete:kt,onCancel:()=>kt(null)},Je.id),(0,d.jsxs)("div",{style:{display:Je||se!=="idle"?"none":void 0},children:[(0,d.jsx)(au,{active:W}),Tt]})]})}),fe&&(0,d.jsx)(rn,{status:"processing"})]})}function pc(e,t,r){let n=(0,l.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function Ps({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:c,onTokenizedBody:p,onErrorChange:m,onDecline:g,onCancel:_,runBeforeButtonClick:E,onButtonClick:I,isProcessing:H,submitButtonColor:T,submitButtonBorderRadius:Y,submitButtonStyle:F,errorText:y}){let h=no(),{emitInstrument:ge}=(0,o.useContext)(hn),w=(0,sr.useStripe)(),Te=(0,sr.useElements)(),[x,ie]=(0,o.useState)(!1),he=(0,o.useRef)(!1),[fe,ke]=(0,o.useState)(!1),[mt,Je]=(0,o.useState)("loading"),[A,kt]=(0,o.useState)(""),tt=!(0,l.isValidEmail)(n?.trim()),Ve=!tt||(0,l.isValidEmail)(A.trim()),me=(0,o.useCallback)(async()=>{if(!w||!Te||H||he.current||!fe)return;he.current=!0,ie(!0);let K=E?await E("card"):{proceed:!0};if(!K.proceed){he.current=!1,ie(!1);return}I?.("card");let W=K.sessionId??t,Fe=K.nonce??r,lt=(0,Ho.splitFullName)(a?.trim()),He=(0,Pn.compactBuyerIdentity)({email:K.accountPatch?.email?.trim()||n?.trim()||A.trim(),firstName:K.accountPatch?.firstName?.trim()||lt.firstName,lastName:K.accountPatch?.lastName?.trim()||lt.lastName}),J=He.email,D=(0,Pn.compactBuyerIdentity)({...K.accountPatch,...He});try{if(m?.(null),!(0,l.isValidEmail)(J))throw new Error("A valid email address is required for payment.");await s?.(He);let se=await Te.submit();if(se.error){m?.(se.error.message??"Payment failed.");return}let O=[He.firstName,He.lastName].filter(Boolean).join(" "),be=await w.createPaymentMethod({elements:Te,params:{billing_details:{email:J,...O?{name:O}:{}}}});if(be.error||!be.paymentMethod){m?.(be.error?.message??"Failed to create payment method.");return}let Me=be.paymentMethod;if(!W||!J)throw new Error("Missing sessionId or email for payment.");let Pe=Me.type||e,Be=await ki(c,ge,W,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Pe,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(Be)){p({type:"card",gateway:"stripe",paymentMethodType:Pe},{accountPatch:D,paymentMethodCategory:"apm",sessionId:W,nonce:Fe,settledProcessResponse:Be.response});return}if(Be.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let M=Be.clientSecret;lr(Kn,{clientSecret:M,sessionId:W,nonce:Fe,accountPatch:D,paymentMethodId:Me.id,paymentMethodType:Me.type??e,gateway:"stripe"});let{error:at,paymentIntent:Ke}=await w.confirmPayment({clientSecret:M,confirmParams:{return_url:window.location.href,payment_method:Me.id},redirect:"if_required"});if(at){lr(Kn);let Ge=at.message??"Payment failed.";m?.(Ge),g?.(br("card",Ge,{code:at.code})),await Ri({billingApiUrl:c,sessionId:W,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:at.code??"provider_declined"}});return}let yt=Ke?.status;if(!Pa(yt)){lr(Kn);let Ge=yt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(Ge),g?.(br("card",Ge,{code:yt??"missing_payment_intent"}));return}lr(Kn);let Ze=typeof Ke?.payment_method=="string"?Ke.payment_method:Ke?.payment_method?.id;p({id:Ze??Me.id,type:"card",threeDSecureActionResultTokenId:Ke?.id,gateway:"stripe",paymentMethodType:Me.type??e},{accountPatch:D,paymentMethodCategory:"apm",sessionId:W,nonce:Fe})}catch(se){m?.(se instanceof Error?se.message:"Payment failed. Please try again.")}finally{he.current=!1,ie(!1)}},[w,Te,H,fe,E,I,t,r,n,a,A,s,c,ge,e,p,m,g]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[tt&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:tt&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:A,onChange:K=>kt(K.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(sr.PaymentElement,{onReady:()=>Je("ready"),onLoadError:()=>{Je("load_error"),Cs(Sr(h),"stripe","apm")},onChange:K=>{ke(!!K.complete)},options:{layout:Pi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,l.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,d.jsx)(vi,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{me()},disabled:!fe||!Ve||x||H||mt!=="ready",color:T,borderRadius:Y,style:F,children:x?"Processing\u2026":`Pay with ${(0,l.getStripeMethodDisplayName)(e)}`}),y&&(0,d.jsx)(Jo,{margin:"0.75rem 0 0",children:y})]})}function sc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:c,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:g,onTokenizedBody:_,onErrorChange:E,onButtonClick:I,onDecline:H,runBeforeButtonClick:T,onLoadStateChange:Y,isProcessing:F=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:h=8,submitButtonStyle:ge,buttonAppearance:w,themeId:Te,onExpandApm:x,expandedApmMethod:ie}){let{emitInstrument:he}=(0,o.useContext)(hn),[fe,ke]=(0,o.useState)(null),[mt,Je]=(0,o.useState)(null),A=(0,o.useRef)(!1),{request:kt,collect:tt,finish:Ve}=Ko();(0,o.useEffect)(()=>{c.length>0&&p?Y?.("ready"):p||Y?.("loading")},[c.length,p,Y]);let me=(0,o.useCallback)(async J=>{if(!p||A.current||F)return;A.current=!0,Je(J);let D=T?await T("card"):{proceed:!0};if(!D.proceed){A.current=!1,Je(null);return}I?.("card");let se=D.sessionId??e,O=D.nonce??t,be=(0,Ho.splitFullName)([D.accountPatch?.firstName,D.accountPatch?.lastName].filter(Boolean).join(" ")||n),Me=(0,Pn.compactBuyerIdentity)({email:D.accountPatch?.email?.trim()||r?.trim(),firstName:D.accountPatch?.firstName?.trim()||be.firstName,lastName:D.accountPatch?.lastName?.trim()||be.lastName});if(!(0,l.isValidEmail)(Me.email)){Je(null);let M=await tt((0,l.getStripeMethodDisplayName)(J),Me);if(!M){A.current=!1;return}Me=M,Je(J)}let Pe=Me.email,Be=(0,Pn.compactBuyerIdentity)({...D.accountPatch,...Me});try{if(E?.(null),!se||!(0,l.isValidEmail)(Pe))throw new Error("Missing sessionId or email for payment.");await a?.(Me);let M=await ki(s,he,se,O??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,paymentMethodId:null,intentKind:"payment"});if((0,l.isSettledSessionIntent)(M)){_({type:"card",gateway:"stripe",paymentMethodType:J},{accountPatch:Be,paymentMethodCategory:"apm",sessionId:se,nonce:O,settledProcessResponse:M.response});return}if(M.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let at=M.clientSecret;lr(Kn,{clientSecret:at,sessionId:se,nonce:O,accountPatch:Be,paymentMethodType:J,gateway:"stripe"});let{error:Ke,paymentIntent:yt}=await p.confirmPayment({clientSecret:at,confirmParams:{return_url:window.location.href,payment_method_data:{type:J,billing_details:{name:[Me.firstName,Me.lastName].filter(Boolean).join(" "),...Pe?{email:Pe}:{}}}},redirect:"if_required"});if(Ke){lr(Kn);let _t=Ke.message??"Payment failed.";E?.(_t),H?.(br("card",_t,{code:Ke.code})),await Ri({billingApiUrl:s,sessionId:se,nonce:O,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,providerDeclineReason:Ke.code??"provider_declined"}});return}let Ze=yt?.status;if(!Pa(Ze)){lr(Kn);let _t=Ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";E?.(_t),H?.(br("card",_t,{code:Ze??"missing_payment_intent"}));return}lr(Kn);let Ge=typeof yt?.payment_method=="string"?yt.payment_method:yt?.payment_method?.id;_({id:Ge??yt?.id,type:"card",threeDSecureActionResultTokenId:yt?.id,gateway:"stripe",paymentMethodType:J},{accountPatch:Be,paymentMethodCategory:"apm",sessionId:se,nonce:O})}catch(M){E?.(M instanceof Error?M.message:"Payment failed. Please try again.")}finally{A.current=!1,Je(null)}},[p,F,T,I,e,t,r,tt,s,he,n,a,_,E,H]),[K,W]=(0,o.useState)(null),Fe=x?ie??null:K,lt=(0,o.useCallback)(J=>{A.current||F||Fe&&Fe!==J||((0,l.needsStripeMethodExplicitConfirm)(J)?x?x(J):W(J):me(J))},[Fe,F,me,x]),He=(0,o.useMemo)(()=>K?pc(m,K,g):null,[K,m,g]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:kt?(0,d.jsx)(Go,{identity:kt.identity,methodLabel:kt.methodLabel,onComplete:Ve,onCancel:()=>Ve(null)},kt.id):c.map(J=>{let D=ie===J,se=mt===J,O=mt!==null&&mt!==J||ie!=null&&ie!==J;return(0,d.jsxs)(o.default.Fragment,{children:[(0,d.jsx)(fi,{method:J,themeId:Te,submitting:se,disabled:O,highlighted:D,hasNextStep:(0,l.needsStripeMethodExplicitConfirm)(J),onClick:()=>lt(J),backgroundColor:w?.backgroundColor,borderColor:w?.borderColor,textColor:w?.textColor,borderRadius:w?.borderRadius,fontFamily:w?.fontFamily}),!x&&K===J&&He&&p&&(0,d.jsx)(sr.Elements,{stripe:p,options:He,children:(0,d.jsx)(Ps,{method:J,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:_,onErrorChange:E,onDecline:H,onCancel:()=>W(null),runBeforeButtonClick:T,onButtonClick:I,isProcessing:F,submitButtonColor:y,submitButtonBorderRadius:h,submitButtonStyle:ge})},J)]},J)})})}function iu({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:c,onError:p,onDecline:m,onCancel:g,onTokenizedBody:_,firstName:E,lastName:I,chv:H,className:T,submitLabel:Y,isProcessing:F,error:y,onErrorChange:h,showPayPal:ge=!0,showStripe:w=!0,walletPresentation:Te="auto",enabledPaymentMethods:x,enabledPaymentMethodCountries:ie,showApplePay:he=!0,showGooglePay:fe=!0,layout:ke="default",theme:mt,buttonsTheme:Je,buttonsStyles:A,appearance:kt,cardButtonContent:tt,cardBackButtonContent:Ve,cardTitleContent:me,showSecurityFooter:K,onButtonClick:W,onBeforeButtonClick:Fe,onBuyerIdentityReady:lt,enableAVS:He,cardFieldOrder:J,cardAutoFocus:D,cardPreFormSlot:se,avsLayout:O="row",country:be,zip:Me,addressLine1:Pe,addressLine2:Be,city:M,state:at,onCountryChange:Ke,onZipChange:yt,avsCheck:Ze,checkoutType:Ge,checkoutLayout:_t,totalAmount:Ut=0,currency:qt="usd",initialCardOpen:Ft=!1,directPaypal:de,isSubscription:ue=!1,session:X,dataAttachmentPending:bt=!1,dataAttachmentRequiresIdentity:ft=!1,debug:V=!1}){let rt=no(),Rt=ni(),Re=(0,o.useContext)(Fn),{emitInstrument:v}=(0,o.useContext)(hn),q=(0,o.useRef)(null);q.current||(q.current=ai());let oe=q.current,[,xe]=(0,o.useState)(0),Lt=(0,o.useRef)(null);Lt.current||(Lt.current=(0,Wn.detectPayPalEnvironment)());let it=Lt.current,De=(0,o.useMemo)(()=>({browser:it,capability:oe,presentationMode:"popup"}),[it,oe]),Oe=X??Re.session,Tt=(0,o.useMemo)(()=>({futureUse:Oe?.futureUse,futureUseUnsupported:Oe?.futureUseUnsupported}),[Oe?.futureUse,Oe?.futureUseUnsupported]),u=Oe?.gateways?.paypal?.providerObjectType??de?.providerObjectType,C=bt||Re.claimPending===!0,Q=ft||Re.claimRequiresIdentity===!0,le=C&&!Q,L=Ol(),k=r||L,[jt,Mr]=(0,o.useState)(!1),[dr,xr]=(0,o.useState)(null),[ct,Gr]=(0,o.useState)(be??""),[Yr,Ar]=(0,o.useState)(Me??""),[Gt,nr]=(0,o.useState)(Pe??""),[Qt,Rn]=(0,o.useState)(Be??""),[Yt,Nn]=(0,o.useState)(M??""),[Fr,Xt]=(0,o.useState)(at??""),[or,on]=(0,o.useState)(""),[gt,Mt]=(0,o.useState)({}),Br=(0,o.useRef)(Me??""),ar=(0,o.useRef)(be??""),Jt=(0,o.useRef)(Pe??""),Ur=(0,o.useRef)(Be??""),hr=(0,o.useRef)(M??""),Vt=(0,o.useRef)(at??""),Dr=(0,o.useRef)(""),kr=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(b,$,_e,G,Ie)=>{if(kr.current[b])return;let Ht=$?.trim();!Ht||Ht===_e.current||(_e.current=Ht,G(Ht),Ie?.(Ht))};i("country",be,ar,Gr,Ke),i("zip",Me,Br,Ar,yt),i("addressLine1",Pe,Jt,nr),i("addressLine2",Be,Ur,Rn),i("city",M,hr,Nn),i("state",at,Vt,Xt)},[be,Me,Pe,Be,M,at,Ke,yt]);let Le=(0,o.useMemo)(()=>(0,l.resolveAVSConfig)(He),[He]),Or=Le!==null,Xr=(0,o.useMemo)(()=>(0,l.isAuthorizationOnlySession)(X),[X]),Xn=(0,l.isMountableVaultBlock)(X?.vault),Pr=!!X?.gateways?.pcivault,an=(0,An.hasServerSideCardGateway)(X),En=!!(X?.gateways?.stripe?.enabledPaymentMethods??x)?.includes("card")||(0,An.canRecoverHostedCardForm)(X),Wt=Xn||En||Pr,Ce=!!(w&&Wt&&e),[ln,zr]=(0,o.useState)(()=>ke!=="buttons"||Ft?e??null:null),[_n,N]=(0,o.useState)(0),dt=ke!=="buttons"||Ft||!!e&&ln===e,te=X?.captureMethod,Se=(0,o.useRef)(rt);(0,o.useEffect)(()=>{Se.current=rt},[rt]);let[Dt,$t]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!Ce||!e||!dt){$t(null);return}let i=Se.current?Se.current.cardCapture({sessionId:e,captureMethod:te}):new Ln.PciVaultCardCapture({sessionId:e,captureMethod:te,billingApiUrl:k,telemetry:n});return $t({sessionId:e,captureMethod:te,billingApiUrl:k,telemetry:n,capture:i}),()=>{i.unmount()}},[Ce,e,dt,te,k,n]);let nt=Ce&&e&&dt&&Dt?.sessionId===e&&Dt.captureMethod===te&&Dt.billingApiUrl===k&&Dt.telemetry===n?Dt.capture:null,Ye=(0,o.useMemo)(()=>{let i=ct,b=Le?(0,l.isAVSFieldVisible)(Le.postal_code,i):!1;return tu(i,Yr,b)},[Le,ct,Yr]),{avsInvalid:Jr,invalidAvsFields:Un}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Ce||!Le)return{avsInvalid:!1,invalidAvsFields:i};let b=ct,$=(Ie,Ht)=>(0,l.isAVSFieldVisible)(Ie,b)&&!Ht.trim(),_e={line1:$(Le.address_line_1,Gt),city:$(Le.city,Yt),state:$(Le.state,Fr),zip:Ye.empty||Ye.malformed};return{avsInvalid:_e.line1||_e.city||_e.state||_e.zip,invalidAvsFields:_e}},[Ce,Le,ct,Gt,Yt,Fr,Ye]),[er,In]=(0,o.useState)(!1),[Jn,Zn]=(0,o.useState)(!1),[Tn,lo]=(0,o.useState)(!1),[Qn,go]=(0,o.useState)({line1:!1,city:!1,state:!1}),yn=(0,o.useRef)(!1),jr=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),co=(0,o.useRef)(!1),Nt=(0,o.useCallback)(i=>{jr.current[i]=!0,co.current=!0},[]),Zr=(0,o.useCallback)(i=>!yn.current&&jr.current[i],[]),Qr=(0,o.useCallback)(i=>{Zr(i)&&go(b=>b[i]?b:{...b,[i]:!0})},[Zr]),[cn,dn]=(0,o.useState)(()=>(0,l.resolveVaultMountOptions)(X?.vault,{billingApiUrl:k,sessionId:e,nonce:t})),[st,ur]=(0,o.useState)(Ft&&Wt?"card":"buttons"),[vr,Rr]=(0,o.useState)(null),ho=st==="expanding"||st==="card",zn=X?.gateways?.stripe&&!an?"stripe":void 0,uo=(0,o.useCallback)(()=>{v?.({class:"card_surface",provider:zn})},[zn,v]),Vr=(0,o.useRef)(null),Er=(0,o.useCallback)(i=>{Vr.current&&clearTimeout(Vr.current),Vr.current=setTimeout(()=>{Vr.current=null,i()},Da)},[]);(0,o.useEffect)(()=>()=>{Vr.current&&clearTimeout(Vr.current)},[]);let po=(0,o.useRef)(!1),[Lr,U]=(0,o.useState)(0),z=(0,o.useRef)(null),ce=(0,o.useCallback)(()=>{uo(),zr(e??null),po.current&&(po.current=!1,U(i=>i+1)),N(i=>i+1),ur("expanding"),Er(()=>ur("card"))},[Er,uo,e]),ve=(0,o.useCallback)(()=>{ur("collapsing"),Er(()=>ur("buttons"))},[Er]),xt=(0,o.useCallback)(i=>{Rr(i),ur("apm-expanding"),Er(()=>ur("apm-form"))},[Er]),zt=(0,o.useCallback)(()=>{ur("apm-collapsing"),Er(()=>{ur("buttons"),Rr(null)})},[Er]);(0,o.useEffect)(()=>{ke==="buttons"&&Ft&&Wt&&(zr(e??null),ur("card"))},[ke,Ft,Wt,e]);let[ze,Z]=(0,o.useState)(null),re=(0,o.useRef)(null),[Xe,Ee]=(0,o.useState)(0);(0,o.useEffect)(()=>{Xe!==0&&re.current?.focus()},[Xe]);let ut=(0,o.useRef)(!1),j=(0,o.useRef)(null),pe=(0,o.useRef)("idle"),[Ot,ot]=(0,o.useState)(!1),pr=(0,o.useRef)(Ot);pr.current=Ot;let[Ne,f]=(0,o.useState)(()=>de?.existingOrderId?{orderId:de.existingOrderId,attempts:1}:null),S=(0,o.useRef)(Ne);(0,o.useEffect)(()=>{S.current=Ne},[Ne]);let ne=(0,o.useRef)(null),qe=(0,o.useMemo)(()=>{if(lt||Re.claimBuyerIdentity||X?.buyerIdentified!==!1||!e||!t)return;let i=`${k}|${e}|${t}`;ne.current?.key!==i&&(ne.current={key:i,claim:Wo(new Ln.PaymentAPI(k,{telemetry:!1}),e,t,{...s?{userId:s}:{},...E?{firstName:E}:{},...I?{lastName:I}:{}})});let b=ne.current.claim;return async $=>{await b($)}},[lt,Re.claimBuyerIdentity,X?.buyerIdentified,e,t,k,s,E,I]),je=lt??Re.claimBuyerIdentity??qe,ye=y??dr,tr=(0,o.useMemo)(()=>(0,l.resolveTheme)(mt),[mt]),ee=(0,o.useMemo)(()=>{let i=tr?.buttonsLayout??(0,l.resolveButtonsLayoutTheme)(Je);return A?{...i,...A,cardButton:{...i.cardButton,...A.cardButton},cardFormContainer:{...i.cardFormContainer,...A.cardFormContainer},backButton:{...i.backButton,...A.backButton},backButtonIcon:{...i.backButtonIcon,...A.backButtonIcon},submitButton:{...i.submitButton,...A.submitButton},title:{...i.title,...A.title}}:i},[tr,Je,A]),Cr=kt??tr?.appearance,Po=(0,o.useMemo)(()=>(0,l.computeVaultCardThemeColors)({appearance:Cr,buttonsStyles:ee,layout:ke}),[Cr,ee,ke]),To=Re.inlineSessionPatchProcessing??!1,Ae=(F??jt)||To,ht=k.replace(/\/+$/,""),ae=(0,o.useMemo)(()=>rs({userId:s,email:a,firstName:E,lastName:I,country:be,zip:Me},gt),[s,a,E,I,be,Me,gt]),It=[ae.firstName,ae.lastName].filter(i=>!!i?.trim()).join(" "),Et=!(0,l.isValidEmail)(ae.email?.trim()),Wr=(0,o.useRef)(null);Ce&&Wr.current===null&&(Wr.current=Et);let Bt=Ce&&(Wr.current??Et),Mo=(0,o.useMemo)(()=>ru(or,Bt),[or,Bt]),xo=Mo.empty||Mo.malformed,un=(0,o.useMemo)(()=>rt?rt.getRawProvider():null,[rt]),Fs=(0,o.useMemo)(()=>Rt?Rt.getRawProvider():null,[Rt]),aa=Ut||100,Ao=qt.toLowerCase(),Di=(0,o.useMemo)(()=>Cr?(0,Ln.toStripeAppearance)(Cr):null,[Cr]),Fo=Di,Bs=(0,o.useMemo)(()=>{let i=Di??{},b=i.rules??{};return{...i,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[Di]),Ds=(0,o.useMemo)(()=>({...Fl(Ut,Oe?.captureMethod,Tt),currency:Ao,...Fo?{appearance:Fo}:null}),[Ut,Ao,Oe?.captureMethod,Tt,Fo]),Oi=(0,l.resolveSetupFutureUsage)(Tt,"paypal","paypal"),Os=(0,o.useMemo)(()=>({mode:"payment",amount:aa,currency:Ao,captureMethod:"manual",...Oi?{setupFutureUsage:Oi}:null,...Fo?{appearance:Fo}:null}),[aa,Ao,Oi,Fo]),We=(0,o.useCallback)(i=>{xr(i),h?.(i)},[h]),Ls=(0,o.useRef)(0);(0,o.useEffect)(()=>{Lr!==Ls.current&&(Ls.current=Lr,We(null))},[Lr,We]);let Li=(0,o.useRef)(""),[Ns,Dc]=(0,o.useState)(!1),Ni=(0,o.useCallback)(()=>{Dc(!0)},[]);(0,o.useEffect)(()=>{if(!Ce||!Bt||!je||!Ns||xo||Li.current)return;let i=(0,Pn.compactBuyerIdentity)({email:(0,l.isValidEmail)(ae.email?.trim())?ae.email?.trim():Dr.current.trim(),firstName:ae.firstName?.trim(),lastName:ae.lastName?.trim()});Li.current=JSON.stringify(i),Mt(b=>({...b,...i})),Promise.resolve(je(i)).catch(b=>{Li.current="",We(b instanceof Error?b.message:"Failed to attach buyer details.")})},[Ce,Bt,je,Ns,xo,ae.email,ae.firstName,ae.lastName,We]),(0,o.useEffect)(()=>{if(!Ce||!nt)return;let i=D!==!1&&Le==null&&!Bt;nt.setCardFieldOrder?.(J??null,i)},[Ce,nt,J,D,Le,Bt]),(0,o.useEffect)(()=>{(st==="expanding"||st==="collapsing"||st==="apm-expanding"||st==="apm-collapsing")&&We(null)},[st,We]);let qn=(0,o.useCallback)((i,b,$)=>{m?.(br(i,b,$))},[m]),Us=(0,o.useRef)(st);Us.current=st;let[zs]=(0,o.useState)(si),qs=(0,o.useCallback)(()=>{let i=Us.current;if(ke==="buttons"&&(i==="card"||i==="expanding"))return!0;let b=pe.current;return b==="validation-window"||b==="processing"||pr.current},[ke]),js=(0,o.useCallback)((i,b,$)=>{zs.take(e)&&Sr(rt)?.log(Eo({...De,presentationMode:$?.presentationMode??"popup"},{name:ii,stage:"recovery",reason:"other_method_active",provider:$?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:$?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[De,rt,zs,e]),za=(0,o.useCallback)((i,b,$)=>{$?.telemetryReported||Sr(rt)?.error(Eo({...De,presentationMode:$?.presentationMode??"popup"},{errorCode:b?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:$?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:$?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:$?.terminalReason??(b?"popup_blocked":"provider_error")}))},[De,rt]),Bo=(0,o.useCallback)((i,b,$)=>{let _e=$?.popupBlocked??(0,we.isPopupBlockedError)(b);if(qs()){za(i,_e,$),js(i,b,$);return}if(b instanceof l.FloPayError&&b.code==="checkout_processing_timeout"){za(i,!1,$),Z(null),ke==="buttons"&&(ur("buttons"),Rr(null)),We(b.message),p?.(b);return}_e&&oe.markBlocked()&&xe(St=>St+1);let G=hs(i),Ie=$?.code===l.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,l.buildWalletSheetWindowMessage)(G):(0,we.buildExternalMethodRecoveryMessage)(G,_e,it.inAppBrowser),Ht=(0,we.getProviderErrorCode)(b),gn=(Ht?.toLowerCase()==="error"?void 0:Ht)??(0,we.sanitizeExternalFailureCode)($?.code)??"external_payment_method_failed",Pt=new l.FloPayError(Ie,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:gn,popupBlocked:_e,inAppBrowser:it.inAppBrowser,appFamily:it.appFamily,popupCapability:oe.current(),presentationMode:$?.presentationMode??"popup"}});za(i,_e,$),Z(null),ke==="buttons"&&(ur("buttons"),Rr(null)),We(Ie),p?.(Pt),console.error("[FloPay] External payment method failed:",{method:i,code:gn,popupBlocked:_e})},[it,qs,ke,p,oe,js,za,We]);(0,o.useEffect)(()=>{if(!Ce||!e){dn(null);return}let i={billingApiUrl:ht,sessionId:e,nonce:t},b=(0,l.resolveVaultMountOptions)(X?.vault,i);if(b){dn(b);return}if(!dt){dn(null);return}let $=`${ht}\0${e}\0${t??""}`,_e=z.current;if(_e&&_e.key===$){dn(_e.mount);return}dn(null);let G=!0;return new Ln.PaymentAPI(ht).getVaultCapture(e,t).then(Ie=>{if(!G)return;let Ht=(0,l.resolveVaultMountOptions)(Ie,i);Ht?.verificationRequired&&!Ie.html&&(z.current={key:$,mount:Ht}),Ht?dn(Ht):We("Failed to load the secure card form.")}).catch(Ie=>{G&&We(Ie instanceof Error?Ie.message:"Failed to load the secure card form.")}),()=>{G=!1}},[Ce,dt,_n,e,X?.vault,ht,t,We]);let Mn=(0,o.useRef)({onComplete:c,onError:p,updateError:We,emitDecline:qn,resolvedAccount:ae,avsConfig:Le,avsCheckProp:Ze,sessionId:e,nonce:t,baseUrl:ht,captureMethod:X?.captureMethod,paymentId:X?.paymentId,authorizationExpiresAt:X?.authorizationExpiresAt,serverSideCardGateway:an});Mn.current={onComplete:c,onError:p,updateError:We,emitDecline:qn,resolvedAccount:ae,avsConfig:Le,avsCheckProp:Ze,sessionId:e,nonce:t,baseUrl:ht,captureMethod:X?.captureMethod,paymentId:X?.paymentId,authorizationExpiresAt:X?.authorizationExpiresAt,serverSideCardGateway:an};let Ui=(0,o.useRef)(!1),Vs=(0,o.useCallback)(()=>{let i=Mn.current,b=i.resolvedAccount.email?.trim(),$=(0,l.isValidEmail)(b)?b:Dr.current.trim();if(!(0,l.isValidEmail)($))return null;let _e=i.resolvedAccount.firstName?.trim(),G=i.resolvedAccount.lastName?.trim(),Ie=ar.current.trim()||i.resolvedAccount.country?.trim()||"",Ht=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.state,Ie):!1,gn=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_1,Ie):!1,Pt=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.postal_code,Ie):!1,St=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.city,Ie):!1,At=i.avsConfig?(0,l.isAVSFieldVisible)(i.avsConfig.address_line_2,Ie):!1,mr=gn&&!Ht&&Pt?(0,l.getStateFromPostalCode)(Ie,(Br.current??"").trim()):null,pn=Ht?Vt.current:mr;return{accountData:{userId:i.resolvedAccount.userId??"",email:$,..._e?{firstName:_e}:{},...G?{lastName:G}:{},...Pt&&Br.current?{zip:Br.current}:{},...St&&hr.current?{city:hr.current}:{},...pn?{state:pn}:{},...gn&&Jt.current?{addressLine1:Jt.current}:{},...At&&Ur.current?{addressLine2:Ur.current}:{},...Ie?{country:Ie}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,l.isAVSFieldVisible)(i.avsConfig.country,Ie),postal_code:Pt,address_line_1:gn,address_line_2:At,city:St,state:Ht}}:{}}},[]),Ws=(0,o.useRef)(C);Ws.current=C,(0,o.useEffect)(()=>{C||ye!==tc||Mn.current.updateError(null)},[C,ye]),(0,o.useEffect)(()=>{!Ce||!nt||nt.setSubmitGate?.(Jr||C||xo||Ot)},[Ce,nt,Jr,C,xo,Ot]),(0,o.useEffect)(()=>{if(!Ce||!nt)return;Ui.current=!1;let i=null,b=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,pe.current="idle",Z(null)},400)},$=nt.on("submitting",()=>{In(!0),j.current&&clearTimeout(j.current),pe.current="validation-window",j.current=setTimeout(()=>{j.current=null,pe.current==="validation-window"&&(pe.current="processing")},$d),Z("processing");let Pt=Mn.current;if(!Pt.sessionId||!Pt.nonce)return;let St=Vs();if(!St){Pt.updateError("Enter a valid email address."),pe.current="idle",Z(null);return}new Ln.PaymentAPI(Pt.baseUrl).patchAccountSnapshot(Pt.sessionId,Pt.nonce,St,{telemetryMode:"best_effort"}).catch(At=>{if(!Kd(At))return;let mr=At instanceof Error?At.message:"Please check your billing address and try again.";Pt.updateError(mr),pe.current="idle",Z(null),Pt.onError?.(At instanceof l.FloPayError?At:new l.FloPayError(mr,"api_error"))})}),_e=nt.on("complete",Pt=>{(0,Dn.markSessionRecentlyCompleted)(Pt.sessionId??Mn.current.sessionId),pe.current="terminal",ot(!1),Z("success"),setTimeout(()=>{if(Ui.current)return;Ui.current=!0;let St=Mn.current,At=(0,l.isAuthorizationOnlySession)(St)||Pt.outcome==="authorized",mr=St.serverSideCardGateway?{}:{paymentIntentId:Pt.intentId};Mn.current.onComplete?.(At?{status:"authorized",...mr,paymentId:Pt.paymentId??St.paymentId,sessionId:Pt.sessionId??St.sessionId,authorizationExpiresAt:Pt.authorizationExpiresAt??St.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...mr,checkoutMethod:"card"})},600)}),G=nt.on("decline",Pt=>{let St=Mn.current,At=Pt.message??"Your payment was declined. Please try another card or contact your bank.";pe.current="terminal",ot(!1),St.updateError(At),Z("error");let mr=Pt.failureOutcome??(0,l.normalizeCheckoutFailureOutcome)(Pt.declineReason)??"authorization_declined";St.emitDecline("card",At,{code:mr,declineCode:mr}),b()}),Ie=nt.on("error",Pt=>{let St=Mn.current,At=(0,l.buyerEmailRequiredPrompt)(Pt.vaultOutcome);if(At!==null){i&&(clearTimeout(i),i=null),pe.current="idle",ot(!1),St.updateError(At),Z(null),Ee(pn=>pn+1),St.onError?.(new l.FloPayError(At,"api_error",{code:l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let mr=Pt.message??"There was a problem processing your payment. Please try again.";pe.current="terminal",ot(!1),St.updateError(mr),Z("error"),St.onError?.(new l.FloPayError(mr,"api_error",{code:Pt.failureOutcome??"capture_failed"})),b()}),Ht=nt.on("challenge_dismissed",()=>{j.current&&(clearTimeout(j.current),j.current=null),pe.current="processing",ot(!0),Z(null)}),gn=nt.on("blocked",()=>{if(pr.current){Mn.current.updateError(Hd);return}if(!Ws.current){In(!0);return}Ni(),Mn.current.updateError(tc)});return()=>{i&&(clearTimeout(i),i=null),j.current&&(clearTimeout(j.current),j.current=null),pe.current="idle",ot(!1),Z(null),$(),_e(),G(),Ie(),Ht(),gn()}},[Ce,nt,Ni,Vs]);let jn=!!de?.clientId,ia=Array.isArray(x),qa=ia&&x.length>0,$s=ia&&x.includes("paypal"),ja=(0,o.useRef)(null);ja.current===null&&(ja.current=(0,l.hasMatchingStripePayPalReturn)());let Do=ja.current?"redirect":(0,$n.resolveStripePayPalPresentation)(it,Te,oe.current()),{expressMethods:Va,paymentElementMethods:zi}=(0,o.useMemo)(()=>(0,l.partitionStripeMethods)(x,{excludePaypal:jn}),[x,jn]),Hs=jn||!!Rt||$s&&Do==="redirect",Oc=(0,o.useMemo)(()=>Hs?Va.filter(i=>i!=="paypal"):Va,[Va,Hs]),Lc=(0,o.useMemo)(()=>{let i=[];return he&&i.push("apple_pay"),fe&&i.push("google_pay"),i},[he,fe]),Oo=ia?Oc:Lc,Nc=w&&Oo.length>0,Ks=Or?ct:be,Wa=(0,o.useMemo)(()=>(0,l.filterStripeMethodsByCountryGate)(zi,Ks,ie),[zi,Ks,ie]),qi=(0,o.useMemo)(()=>({mode:"payment",amount:aa,currency:Ao,paymentMethodCreation:"manual",appearance:Bs}),[aa,Ao,Bs]),[Gs,Ys]=(0,o.useState)("loading"),[Xs,Js]=(0,o.useState)("loading"),[Zs,Qs]=(0,o.useState)("loading"),[Uc,ji]=(0,o.useState)(!1),[el,Vi]=(0,o.useState)("loading"),[Wi,zc]=(0,o.useState)();(0,o.useEffect)(()=>{zc((0,Wn.detectPayPalEnvironment)())},[]);let $a=Wi?.inAppBrowser,Ha=Wi?(0,$n.resolvePayPalPresentationMode)(Wi,de?.approvalPresentation,u??(ue?"subscription":"order")):"popup",tl=ge&&(jn||(ia?$s:$a===!1)),qc=it.inAppBrowser&&oe.current()==="blocked",rl=w&&Nc&&!qc,sa=(!le||!!Re.waitForDataAttachment)&&tl&&jn,nl=el==="retrying"||el==="exhausted",la=null;w&&(Rt?la=Fs:Do==="redirect"&&(la=un));let ol=(0,o.useMemo)(()=>({...De,presentationMode:Do}),[De,Do]),ca=!le&&tl&&!!la&&(!jn||nl),Lo=!le&&rl&&!!un,da=!le&&w&&qa&&Wa.length>0&&!!un,jc=sa&&!nl?Uc:ca&&ds(Gs),Vc=Lo&&ds(Xs),Wc=da&&Zs!=="load_error",al=i=>i==="loading"||i==="ready",il=sa||ca&&al(Gs)||Lo&&al(Xs)||da&&Zs!=="load_error",Ka=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Ka.current){if(!w&&!ge){Ka.current=!0;let i=new l.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(i),We(i.message)}else if(!w&&ge&&!jn){Ka.current=!0;let i=new l.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(i),We(i.message)}else if($a!==void 0&&!le&&!Wt&&!il){Ka.current=!0;let i=new l.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});p?.(i),We(i.message)}}},[w,ge,jn,$a,le,Wt,il,p,We]);let sl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(sl.current||!qa)return;let i=[];he!==!0&&i.push("showApplePay"),fe!==!0&&i.push("showGooglePay"),i.length!==0&&(sl.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[qa,he,fe]);let ll=(0,o.useCallback)((i,b,$)=>Re.applyInlineSessionPatch?Re.applyInlineSessionPatch(i).then(_e=>({error:null,sessionId:_e.sessionId||e,nonce:_e.session?.clientSecret||t})).catch(_e=>{let G=(0,l.normalizeBeforeButtonClickError)(b,_e);return $?.abandoned?.()||(We(G.message),p?.(G)),{error:G,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Re.applyInlineSessionPatch,t,p,e,We]),xn=(0,o.useCallback)(async(i,b)=>{if(i!=="card"&&le&&await Re.waitForDataAttachment?.(),!Fe)return{proceed:!0};try{let $=await Fe({method:i,sessionId:e||void 0,createSession:Re.inlineSessionDraft});if($===!1)return{proceed:!1};if($&&typeof $=="object"){$.account&&Mt(G=>({...G??{},...$.account}));let _e=await ll($,i,b);return _e.error?{proceed:!1,accountPatch:$.account}:{proceed:!0,accountPatch:$.account,sessionId:_e.sessionId,nonce:_e.nonce}}return{proceed:!0}}catch($){if(!b?.abandoned?.()){let _e=(0,l.normalizeBeforeButtonClickError)(i,$);We(_e.message),p?.(_e)}return{proceed:!1}}},[ll,Re.inlineSessionDraft,Re.waitForDataAttachment,le,Fe,p,e,We]),cl=(0,o.useCallback)(async(i,b)=>{if(ut.current)return;ut.current=!0,Mr(!0),Z("processing"),We(null);let $=b?.sessionId??e,_e=b?.nonce??t,G=rs(ae,b?.accountPatch),Ie=b?.completionPaymentMethodId??va(i),Ht=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,gn=Jd(i),Pt=b?.presentationMode?yi(Sr(rt),{...De,presentationMode:b.presentationMode}):void 0,St=()=>{v?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:gn}),Pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...On,requestCategory:"process_payment"})};try{let At=new Ln.PaymentAPI(ht),pn=b?.settledProcessResponse??await At.processPayment(G.userId??"",{sessionId:$,nonce:_e,paymentMethodCategory:b?.paymentMethodCategory??Qd(i),tokenizedData:Ht,accountData:{...b?.accountPatch,userId:G.userId??"",email:G.email??"",firstName:G.firstName||void 0,lastName:G.lastName||void 0,...(0,l.buildProcessPaymentAvsAccount)({avsConfig:Le,country:ar.current,zip:Br.current,city:hr.current,state:Vt.current,addressLine1:Jt.current,addressLine2:Ur.current})},...(0,l.buildCheckoutProcessMetadata)({chv:H,avsCheck:Ze,checkoutType:Ge,checkoutLayout:_t,avsConfig:Le,country:ar.current})}),Za=async _r=>{let bo=(0,l.isAuthorizationOnlySession)(X)||_r?.status==="authorized";(0,Dn.markSessionRecentlyCompleted)($),Pt?.terminal({outcome:"payment_succeeded",...On}),Z("success"),f(null),await new Promise(ga=>setTimeout(ga,600));let Vn;typeof _r?.paymentId=="string"?Vn=_r.paymentId:X?.paymentId&&(Vn=X.paymentId);let So;typeof _r?.authorizationExpiresAt=="string"?So=_r.authorizationExpiresAt:X?.authorizationExpiresAt&&(So=X.authorizationExpiresAt),c?.(bo?{status:"authorized",...Vn===void 0?{}:{paymentId:Vn},sessionId:typeof _r?.sessionId=="string"?_r.sessionId:$,...So===void 0?{}:{authorizationExpiresAt:So},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Ie,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Ie,checkoutMethod:i.isPaypal?"paypal":"card"})};if(pn.ok){await Za(pn.status===204?null:await pn.json().catch(()=>null));return}let yr=await pn.json().catch(()=>null);if(yr?.type==="paypal_redirect_required"){let _r=yr.threeDSecureToken,bo=yr.paymentMethodId||i.id||"";if(!rt||!_r){Z("error"),We("PayPal authorization required but no token provided.");return}try{let Vn=Rt?.getRawProvider();if(!Vn){We("PayPal is not available.");return}let So={return_url:window.location.href};bo&&(So.payment_method=bo);let{error:ga}=await Vn.confirmPayment({clientSecret:_r,confirmParams:So,redirect:"if_required"});if(ga){Z("error");let bl=ga.message??"PayPal payment failed.";We(bl),qn("paypal",bl,{code:ga.code})}}catch(Vn){Z("error"),We(Vn instanceof Error?Vn.message:"PayPal authorization failed.")}return}if(yr?.type==="paypal_direct_required"){let _r=yr.orderId;if(!_r){Z("error"),We("PayPal retry required but no order id provided.");return}let bo=S.current?.attempts??0;if(bo>=2){Z("error"),We("PayPal payment could not be completed after multiple attempts."),qn("paypal","paypal_direct_required retry limit exceeded");return}ji(!1),Vi("loading"),f({orderId:_r,attempts:bo+1}),Z(null);return}if(pn.headers.get(Nd)===Ud){let _r=await zd(At,$,_e);if(_r!==void 0){await Za(_r);return}}(0,l.classifyPaymentRejection)(pn.status,yr)?Pt?.terminal({outcome:"payment_declined",...On,terminalReason:"provider_declined"}):St(),Z("error");let Cl=yr?.message??"Payment failed. Please try again.";We(Cl),qn(i.isPaypal?"paypal":"card",Cl,{code:yr?.code??yr?.gatewayErrorCode,declineCode:yr?.declineCode??yr?.gatewayDeclineReason}),await new Promise(_r=>setTimeout(_r,400))}catch(At){dc(At)||St(),Z("error"),We(At instanceof Error?At.message:"An unexpected error occurred"),await new Promise(mr=>setTimeout(mr,400))}finally{Mr(!1),Z(null),ut.current=!1}},[ht,e,t,ae,Le,Ze,Ge,_t,H,rt,Rt,X,c,We,qn,v,De]),en=(0,o.useCallback)((i,b)=>{_&&!b?.settledProcessResponse?_(i):cl(i,b)},[_,cl]),ua=`${lc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(ua);if(!i)return;let b;try{b=JSON.parse(i)}catch{lr(ua);return}if(!b||typeof b.createdAt!="number"||Date.now()-b.createdAt<0||Date.now()-b.createdAt>cc||typeof b.paymentMethodId!="string"||typeof b.providerIntentId!="string"||typeof b.paymentMethodType!="string"||b.sessionId!==e||!t||b.nonce!==t||!Oo.includes(b.paymentMethodType)){lr(ua);return}lr(ua),en({id:b.paymentMethodId,type:"card",threeDSecureActionResultTokenId:b.providerIntentId,gateway:"stripe",paymentMethodType:b.paymentMethodType},{...b.accountPatch?{accountPatch:b.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[en,t,e,ua,Oo]);let dl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||dl.current)return;let[i,b,$]=(0,l.readStripeRedirectParams)();if(!i||!b||ja.current||!rt)return;let _e=rt.getRawProvider();if(!_e)return;let G=St=>{let At=localStorage.getItem(St);if(!At)return null;try{return JSON.parse(At)}catch{return lr(St),null}},Ie=G(Kn)??G(Zl),Ht;if(Ie?.clientSecret){if(Ie.clientSecret!==b)return;Ht={...Ie.accountPatch?{accountPatch:Ie.accountPatch}:{},...Ie.sessionId?{sessionId:Ie.sessionId}:{},...Ie.nonce?{nonce:Ie.nonce}:{}}}else if(Ie?.sessionId&&Ie.sessionId!==e)return;dl.current=!0,lr(Kn),lr(Zl),window.history.replaceState({},"",(0,l.stripeRedirectReturnUrl)());let gn=Ie?.paymentMethodType??Ie?.tokenType??"card",Pt="card";(async()=>{if($==="failed"){let yr="Payment was declined. Please try again.";We(yr),qn(Pt,yr);return}let{paymentIntent:St,error:At}=await _e.retrievePaymentIntent(b);if(At){let yr=At.message??"Failed to retrieve payment status.";We(yr),qn(Pt,yr,{code:At.code});return}let mr=St?.status,pn=Pa(mr);if(!St||!pn){let yr=mr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";We(yr),qn(Pt,yr,{code:mr??"missing_payment_intent"});return}let Za=typeof St.payment_method=="string"?St.payment_method:St.payment_method?.id;en({id:Za??Ie?.paymentMethodId??Ie?.tokenId??St.id,type:"card",threeDSecureActionResultTokenId:St.id,gateway:Ie?.gateway??"stripe",paymentMethodType:gn},Ht)})()},[e,en,rt,We,qn]);let $i=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(Ce||rt!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let pa=ke==="buttons",tn=Cr?.variables,$c=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Hi=tn?.colorBackground,Hc=Hi&&!$c.has(Hi)?Hi:void 0,ma=ee.cardInputBorder??(pa?"#e5e7eb":"#A4A4FF"),ul=tn?.colorDanger??"#dc2626",rr=i=>Un[i]&&(Qn[i]||er),Ga=xo&&(Tn||er),fn=i=>i?ul:ma,Ya=(Ye.malformed||Ye.empty)&&(Jn||er),Kc=fn(Ya),Ki=ee.cardFormContainer?.backgroundColor??Hc??(pa?"white":"#EDEDFF"),No=ee.cardInputBackground??tn?.colorBackground??"white",Gi=qo(Ve),pl=qo(me),Uo=ee.nameInput,ml=ee.cardInputFontSize??nu(Uo?.fontSize)??tn?.fontSizeBase??"16px",yl=typeof Uo?.fontFamily=="string"?Uo.fontFamily:tn?.fontFamily??"Poppins, sans-serif",fl=(0,l.toCssWeight)(Uo?.fontWeight)??400,Gc=ee.cardInputColor??(typeof Uo?.color=="string"?Uo.color:void 0)??tn?.colorText??"#262833",Yc=ee.cardInputPlaceholderColor??"#9ca3af",ir=tn?.borderRadius??"8px",vo=tn?.borderRadius??ee.cardButton?.borderRadius??ir,Co=tn?.colorPrimary??"#4A49FF",Xc=tn?.colorPrimaryHover??(0,l.darkenHex)(Co,.12),Yi=tn?.colorText??"#262833",Xi={fontSize:ml,fontFamily:yl,fontWeight:fl,color:Gc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ya={marginTop:"0.375rem",...Xi,fontSize:"0.75rem",lineHeight:1.4,color:ul},Jc={"--flopay-input-placeholder-color":Yc,"--flopay-input-font-size":ml,"--flopay-input-font-family":yl,"--flopay-input-font-weight":String(fl)},fa=ee.cardFormContainer??{},Ji=fa.padding??(pa?"0":"1rem"),Zi=fa.borderRadius??ir,Zc=nt&&cn?(0,d.jsx)(fo,{capture:nt,html:cn.html,messageToken:cn.messageToken,expectedOrigin:cn.expectedOrigin,verificationRequired:cn.verificationRequired,theme:Po,submitLabel:Y,onReady:()=>{if(!Bt&&!Le||typeof document>"u"||D===!1)return;let i=()=>{let $=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if($){yn.current=!0;try{$.focus()}finally{yn.current=!1}}};co.current||i()},onError:i=>{i&&cn.verificationRequired&&pe.current==="idle"&&(po.current=!0),We(i)},onValidation:i=>{let b=pe.current;(b==="idle"||b==="validation-window")&&(We(i),i&&pe.current==="validation-window"&&(j.current&&(clearTimeout(j.current),j.current=null),pe.current="idle",Z(null)))}},Lr):(0,d.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),gl=(0,d.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&uo()},style:{backgroundColor:Ki,borderRadius:Zi,...fa,padding:Ji,...Jc,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${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: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"})]}),Qe&&(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)(Qe.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)(Qe.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)(Qe.city,i)||(0,l.isAVSFieldVisible)(Qe.state,i))&&(0,u.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Qe.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)(Qe.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)(Qe.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)(Qe.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)(Qe.country,i)||(0,l.isAVSFieldVisible)(Qe.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)(Qe.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)(Qe.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)(Qe.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)(Qe.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=Ze===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:Ze})}),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:Ze,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),[Qe,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)},Xe=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(Xe),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:Xe}=await ie.retrievePaymentIntent(j);if(Xe)throw Object.assign(new De.FloPayError(Xe.message??"Failed to retrieve PayPal payment status.","api_error",{code:Xe.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 Xe=Ei(B,a,he);Xe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Da(Xe)}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 Xe=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),Xe??(Xe=te.idempotencyKey))):((0,vt.clearCachedInlineCheckout)(j,ne),te=null,Xe=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),Xe=ke):(0,vt.clearCachedInlineSession)(j,ne),U=null}if(!U){!ke&&(st||!Xe)&&(Xe=(0,De.resolveIdempotencyKey)(),Ee=Xe),Xe&&(0,vt.persistCachedInlineIdempotencyKey)(j,ne,Xe);let g=Se.now(),X=0;Se.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ke={...N,idempotencyKey:Xe,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 Xe={canonicalIdentity:gt,promise:mo.current(Se,Yt,gt),consumers:0,settled:!1};ke=Xe,Ii.set(gt,Xe);let Ee=()=>{Xe.settled=!0,pc(gt,Xe)};Xe.promise.then(Ee,Ee)}ke.consumers+=1;let ie=!1,te=()=>{ie||(ie=!0,ke.consumers-=1,pc(gt,ke))};j?.(te);try{let Xe=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}=Xe;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),Xe}catch(Xe){throw zn.current===gt&&(zn.current=null),Xe}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 Xe=!1;try{let Ee=await gn.current(void 0,ht=>{j=ht});Xe=!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)),!Xe){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,Xe=null;try{let Ee=new co.PaymentAPI(B,{telemetry:!1}),st=await Ee.getUnifiedCheckoutSession(d,t);if(te=!0,Xe=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??Xe?.data.session?.checkoutMode??"full")==="full"&&Sl(Xe,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:Xe,...Ee}=await Rs(ie,{billingApiUrl:B,locale:c,telemetry:a});ir.current={publishableKey:Ee.publishableKey,paypalPublishableKey:Ee.paypalPublishableKey},Q(te,Xe),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:Ze,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}),Qe==="retrying"&&(0,D.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Qe==="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"})]}),Qe!=="exhausted"&&(0,D.jsx)("div",{"aria-hidden":Qe==="retrying"?!0:void 0,style:Qe==="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:Ze,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:Ze,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:`
38
+ `}),pa&&ho&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ce?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:ve,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ee.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ee.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ee.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Vo,{content:Ve})]}),pl?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ee.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...ee.title},children:(0,d.jsx)(ha,{content:me})})]}),!pa&&!pl&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Yi,order:Ce?-3:0,...ee.title},children:(0,d.jsx)(ha,{content:me})}),Ce&&se&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:se}),Ce&&Bt&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:No,border:`1px solid ${fn(Ga)}`,borderRadius:ir,padding:"10px"},children:(0,d.jsx)("input",{ref:re,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:or,onChange:i=>{Nt("email"),Dr.current=i.target.value,on(i.target.value)},onPointerDown:()=>Nt("email"),onKeyDown:()=>Nt("email"),onBlur:()=>{Zr("email")&&lo(!0),xo||Ni()},disabled:Ae,required:!0,"aria-invalid":Ga||void 0,"aria-describedby":Ga?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Xi}})}),Ga&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ya,children:Mo.empty?"Email address is required":"Enter a valid email address"})]}),Le&&(0,d.jsx)("div",{style:{order:Ce?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=ct,b=(G=!1)=>({backgroundColor:No,border:`1px solid ${fn(G)}`,borderRadius:ir,marginTop:"0.5rem",padding:"10px"}),$=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Xi}),_e=(0,l.getStateOptions)(i);return(0,d.jsxs)(d.Fragment,{children:[(0,l.isAVSFieldVisible)(Le.address_line_1,i)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:b(rr("line1")),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Gt,onChange:G=>{Nt("line1"),kr.current.addressLine1=!0,Jt.current=G.target.value,nr(G.target.value)},onPointerDown:()=>Nt("line1"),onKeyDown:()=>Nt("line1"),onBlur:()=>Qr("line1"),disabled:Ae,required:!0,"aria-invalid":rr("line1")||void 0,"aria-describedby":rr("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:$()})}),rr("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ya,children:"Street address is required"})]}),(0,l.isAVSFieldVisible)(Le.address_line_2,i)&&(0,d.jsx)("div",{style:b(),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Qt,onChange:G=>{kr.current.addressLine2=!0,Ur.current=G.target.value,Rn(G.target.value)},disabled:Ae,"data-testid":"flopay-address-line2",style:$()})}),((0,l.isAVSFieldVisible)(Le.city,i)||(0,l.isAVSFieldVisible)(Le.state,i))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Le.city,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:No,borderTop:`1px solid ${fn(rr("city"))}`,borderRight:`1px solid ${fn(rr("city"))}`,borderBottom:`1px solid ${fn(rr("city"))}`,borderLeft:`1px solid ${fn(rr("city"))}`,padding:"10px",borderTopLeftRadius:ir,borderBottomLeftRadius:ir,...(0,l.isAVSFieldVisible)(Le.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ir}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Yt,onChange:G=>{Nt("city"),kr.current.city=!0,hr.current=G.target.value,Nn(G.target.value)},onPointerDown:()=>Nt("city"),onKeyDown:()=>Nt("city"),onBlur:()=>Qr("city"),disabled:Ae,required:!0,"aria-invalid":rr("city")||void 0,"aria-describedby":rr("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:$()})}),(0,l.isAVSFieldVisible)(Le.state,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:No,borderTop:`1px solid ${fn(rr("state"))}`,borderRight:`1px solid ${fn(rr("state"))}`,borderBottom:`1px solid ${fn(rr("state"))}`,borderLeft:`1px solid ${fn(rr("state"))}`,padding:"10px",borderTopRightRadius:ir,borderBottomRightRadius:ir,...(0,l.isAVSFieldVisible)(Le.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${fn(rr("state")||rr("city"))}`}:{borderRadius:ir}},children:_e?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Fr,onChange:G=>{Nt("state"),kr.current.state=!0,Vt.current=G.target.value,Xt(G.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>Qr("state"),disabled:Ae,autoComplete:"billing address-level1",required:!0,"aria-invalid":rr("state")||void 0,"aria-describedby":rr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...$(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,l.getStateLabel)(i)}),_e.map(G=>(0,d.jsx)("option",{value:G.code,children:G.name},G.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,l.getStateLabel)(i),autoComplete:"billing address-level1",value:Fr,onChange:G=>{Nt("state"),kr.current.state=!0,Vt.current=G.target.value,Xt(G.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>Qr("state"),disabled:Ae,required:!0,"aria-invalid":rr("state")||void 0,"aria-describedby":rr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:$()})})]}),rr("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ya,children:"City is required"}),rr("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ya,children:[(0,l.getStateLabel)(i)," is required"]}),((0,l.isAVSFieldVisible)(Le.country,i)||(0,l.isAVSFieldVisible)(Le.postal_code,i))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:O==="column"?"column":"row",gap:O==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,l.isAVSFieldVisible)(Le.country,i)&&(0,d.jsx)("div",{style:{flex:O==="row"?1:void 0,backgroundColor:No,borderTop:`1px solid ${ma}`,borderRight:`1px solid ${ma}`,borderBottom:`1px solid ${ma}`,borderLeft:`1px solid ${ma}`,padding:"10px",...O==="row"&&(0,l.isAVSFieldVisible)(Le.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:ir,borderBottomLeftRadius:ir,borderRight:"none"}:{borderRadius:ir}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:ct,onChange:G=>{kr.current.country=!0,ar.current=G.target.value,Gr(G.target.value),Ke?.(G.target.value),Vt.current="",Xt("")},disabled:Ae,autoComplete:"billing country","data-testid":"flopay-country",style:{...$(),cursor:"pointer"},children:[ct===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,l.COUNTRY_OPTIONS.map(G=>(0,d.jsxs)("option",{value:G.code,children:[G.flag," ",G.name]},G.code))]})}),(0,l.isAVSFieldVisible)(Le.postal_code,i)&&(0,d.jsx)("div",{style:{flex:O==="row"?1:void 0,backgroundColor:No,border:`1px solid ${Kc}`,padding:"10px",...O==="row"&&(0,l.isAVSFieldVisible)(Le.country,i)?{borderRadius:"0",borderTopRightRadius:ir,borderBottomRightRadius:ir}:{borderRadius:ir}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,l.getPostalCodeLabel)(ct),autoComplete:"billing postal-code",value:Yr,onChange:G=>{Nt("zip"),kr.current.zip=!0,Br.current=G.target.value,Ar(G.target.value),yt?.(G.target.value)},onPointerDown:()=>Nt("zip"),onKeyDown:()=>Nt("zip"),onBlur:()=>{Zr("zip")&&Zn(!0)},disabled:Ae,required:Ye.required,"aria-invalid":Ya||void 0,"aria-describedby":Ya?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:$()})})]}),Ya&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ya,children:Ye.empty?`${(0,l.getPostalCodeLabel)(i)} is required`:eu(i)})]})})()}),Ce&&Zc,ye&&(0,d.jsx)(Jo,{margin:"0.75rem 0",styleOverride:ee.errorBanner,children:ye})]}),Xa={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},hl=i=>V?!ge||!jn?(0,d.jsx)("pre",{"data-testid":i,style:Xa,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Xa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ge}`,` directPaypalConfigured=${jn}`,` inAppBrowserDetected=${String($a)}`,` shouldRenderDirectPayPal=${sa}`,` shouldRenderStripePayPal=${ca}`,` hasPaypalStripeInstance=${!!Fs}`].join(`
39
+ `)}):null,Pl=i=>V?!w||!un?(0,d.jsx)("pre",{"data-testid":i,style:Xa,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Xa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${w}`,` currency=${qt}`,` amountInCents=${aa}`,` enabledPaymentMethods: ${JSON.stringify(x??[])}`,` enabledPaymentMethodsProvided=${ia}`,` hasEnabledMethods=${qa}`,` expressMethods: ${JSON.stringify(Va)}`,` walletExpressMethods: ${JSON.stringify(Oo)}`,` paymentElementMethods: ${JSON.stringify(zi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Wa)}`,` hasStripeInstance=${!!un}`,` shouldRenderWallets=${Lo}`,` shouldRenderPaymentElement=${da}`].join(`
40
+ `)}):null,vl=st==="apm-expanding"||st==="apm-form"||st==="apm-collapsing",zo;st==="apm-expanding"?zo=rc:st==="apm-collapsing"&&(zo=nc);let Ja=vr?pc(qi,vr,Tt):null;if(ke==="buttons"){let i=st==="buttons"||st==="expanding"||st==="apm-expanding",b=st==="expanding"||st==="card"||st==="collapsing",$=tt===void 0?{boxSizing:"border-box",height:ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"},_e;st==="expanding"||st==="apm-expanding"?_e=Xd:(st==="collapsing"||st==="apm-collapsing")&&(_e=Yd);let G;return st==="expanding"?G=rc:st==="collapsing"&&(G=nc),(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ra,{}),ze&&(0,d.jsx)(rn,{status:ze,errorMessage:ye,authorized:Xr}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!_e?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!_e?Zd:{},..._e?{animation:_e,pointerEvents:"none"}:{}},children:[hl("flopay-direct-paypal-gate-debug"),Pl("flopay-stripe-gate-debug"),sa&&de&&(0,d.jsxs)(d.Fragment,{children:[Ne&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(ba.Provider,{value:oe,children:(0,d.jsx)(wa,{sessionId:e,nonce:t,billingApiUrl:k,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,clientId:de.clientId,environment:de.environment,currency:qt.toUpperCase(),isSubscription:ue,providerObjectType:u,approvalPresentation:Ha==="popup"?void 0:Ha,onTokenizedBody:en,onComplete:c,onErrorChange:We,onDecline:m,onCancel:g,onTechnicalFailure:Bo,onButtonClick:W,runBeforeButtonClick:xn,isProcessing:Ae,onLoadStateChange:ji,onInitializationStateChange:Vi,session:Oe,existingOrderId:Ne?.orderId,debug:V},Ne?.orderId??"fresh")})]}),ca&&(0,d.jsx)(sr.Elements,{stripe:la,options:Os,children:(0,d.jsx)(ac,{sessionId:e,nonce:t,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,billingApiUrl:k,onTokenizedBody:en,onErrorChange:We,isProcessing:Ae,onButtonClick:W,onDecline:m,onTechnicalFailure:Bo,runBeforeButtonClick:xn,onLoadStateChange:Ys,placeholderBorderRadius:vo,popupCapabilityOwner:oe,externalTelemetryContext:ol,presentationMode:Do})}),Lo?(0,d.jsx)(sr.Elements,{stripe:un,options:Ds,children:(0,d.jsx)(ic,{sessionId:e,nonce:t,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,billingApiUrl:k,intentKind:Ut>0?"payment":"setup",expressMethods:Oo,onTokenizedBody:en,onErrorChange:We,onButtonClick:W,onDecline:m,onTechnicalFailure:Bo,runBeforeButtonClick:xn,onLoadStateChange:Js,placeholderBorderRadius:vo,popupCapabilityOwner:oe,externalTelemetryContext:De})}):null,!Lo&&rl?(0,d.jsx)("div",{style:{height:ta,borderRadius:vo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,da&&(0,d.jsx)(sc,{sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:je,billingApiUrl:k,paymentElementMethods:Wa,stripeInstance:un,paymentElementBaseOptions:qi,futureUseSession:Tt,onTokenizedBody:en,onErrorChange:We,onButtonClick:W,onDecline:m,runBeforeButtonClick:xn,onLoadStateChange:Qs,isProcessing:Ae,submitButtonColor:Co,submitButtonBorderRadius:ir,submitButtonStyle:ee.submitButton,onExpandApm:xt,expandedApmMethod:vr,themeId:mt,buttonAppearance:{backgroundColor:ee.cardButton?.backgroundColor,borderColor:ee.cardInputBorder,textColor:ee.cardButton?.color,borderRadius:vo}}),Ce&&(0,d.jsx)("button",{type:"button",onClick:async()=>{Ae||!(await xn("card")).proceed||(W?.("card"),ce())},disabled:Ae,style:{width:"100%",...$,...ee.cardButton,...bs({themeBundle:tr,resolvedPrimaryColor:Co,resolvedBorderRadius:ir,submitButtonStyle:ee.submitButton,explicitPrimaryColor:tn?.colorPrimary}),fontSize:ee.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ae?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Ae?.6:1},onMouseEnter:Ie=>{!Ae&&(tr||tn?.colorPrimary)&&(Ie.currentTarget.style.backgroundColor=Xc)},onMouseLeave:Ie=>{(tr||tn?.colorPrimary)&&(Ie.currentTarget.style.backgroundColor=Co)},onMouseDown:Ie=>{Ie.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ie=>{Ie.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(jo,{content:tt})}),ye&&st==="buttons"&&(0,d.jsx)(Jo,{margin:"0.25rem 0",styleOverride:ee.errorBanner,children:ye})]}),Ce&&b&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...G?{animation:G}:{},...st==="collapsing"?{pointerEvents:"none"}:{}},children:gl}),w&&vl&&vr&&Ja&&un&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...zo?{animation:zo}:{},...st==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ki,borderRadius:Zi,...fa,padding:Ji},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:zt,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ee.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ee.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ee.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Vo,{content:Ve})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ee.titleFontSize??"1.05rem",color:Yi,paddingRight:80,...ee.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(vr)}`})]}),(0,d.jsx)(sr.Elements,{stripe:un,options:Ja,children:(0,d.jsx)(Ps,{method:vr,sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:je,billingApiUrl:k,onTokenizedBody:en,onErrorChange:We,onDecline:m,onCancel:zt,runBeforeButtonClick:xn,onButtonClick:W,isProcessing:Ae,submitButtonColor:Co,submitButtonBorderRadius:ir,submitButtonStyle:ee.submitButton,errorText:ye})},vr)]})})]})]})}return vl&&vr&&Ja&&un&&w?(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ra,{}),ze&&(0,d.jsx)(rn,{status:ze,errorMessage:ye,authorized:Xr}),(0,d.jsx)("div",{style:{...zo?{animation:zo}:{},...st==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Ki,borderRadius:Zi,...fa,padding:Ji},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:zt,style:{display:"inline-flex",alignItems:"center",gap:Gi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ee.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ee.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ee.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Vo,{content:Ve})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ee.titleFontSize??"1.05rem",color:Yi,paddingRight:80,...ee.title},children:`Pay with ${(0,l.getStripeMethodDisplayName)(vr)}`})]}),(0,d.jsx)(sr.Elements,{stripe:un,options:Ja,children:(0,d.jsx)(Ps,{method:vr,sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:je,billingApiUrl:k,onTokenizedBody:en,onErrorChange:We,onDecline:m,onCancel:zt,runBeforeButtonClick:xn,onButtonClick:W,isProcessing:Ae,submitButtonColor:Co,submitButtonBorderRadius:ir,submitButtonStyle:ee.submitButton,errorText:ye})},vr)]})})]}):(0,d.jsxs)("form",{onSubmit:$i,className:T,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ra,{}),ze&&(0,d.jsx)(rn,{status:ze,errorMessage:ye,authorized:Xr}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[hl("flopay-direct-paypal-gate-debug-default"),Pl("flopay-stripe-gate-debug-default"),sa&&de&&(0,d.jsxs)(d.Fragment,{children:[Ne&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(ba.Provider,{value:oe,children:(0,d.jsx)(wa,{sessionId:e,nonce:t,billingApiUrl:k,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,clientId:de.clientId,environment:de.environment,currency:qt.toUpperCase(),isSubscription:ue,providerObjectType:u,approvalPresentation:Ha==="popup"?void 0:Ha,onTokenizedBody:en,onComplete:c,onErrorChange:We,onDecline:m,onCancel:g,onTechnicalFailure:Bo,onButtonClick:W,runBeforeButtonClick:xn,isProcessing:Ae,onLoadStateChange:ji,onInitializationStateChange:Vi,session:Oe,existingOrderId:Ne?.orderId,debug:V},Ne?.orderId??"fresh")})]}),ca&&(0,d.jsx)(sr.Elements,{stripe:la,options:Os,children:(0,d.jsx)(ac,{sessionId:e,nonce:t,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,billingApiUrl:k,onTokenizedBody:en,onErrorChange:We,isProcessing:Ae,onButtonClick:W,onDecline:m,onTechnicalFailure:Bo,runBeforeButtonClick:xn,onLoadStateChange:Ys,placeholderBorderRadius:vo,popupCapabilityOwner:oe,externalTelemetryContext:ol,presentationMode:Do})}),Lo&&(0,d.jsx)(sr.Elements,{stripe:un,options:Ds,children:(0,d.jsx)(ic,{sessionId:e,nonce:t,email:ae.email,billingName:It||void 0,onBuyerIdentityReady:je,billingApiUrl:k,intentKind:Ut>0?"payment":"setup",expressMethods:Oo,onTokenizedBody:en,onErrorChange:We,onButtonClick:W,onDecline:m,onTechnicalFailure:Bo,runBeforeButtonClick:xn,onLoadStateChange:Js,placeholderBorderRadius:vo,popupCapabilityOwner:oe,externalTelemetryContext:De})}),da&&(0,d.jsx)(sc,{sessionId:e,nonce:t,email:ae.email,billingName:[ae.firstName,ae.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:k,paymentElementMethods:Wa,stripeInstance:un,paymentElementBaseOptions:qi,futureUseSession:Tt,onTokenizedBody:en,onErrorChange:We,onButtonClick:W,onDecline:m,runBeforeButtonClick:xn,onLoadStateChange:Qs,isProcessing:Ae,submitButtonColor:Co,submitButtonBorderRadius:ir,submitButtonStyle:ee.submitButton,themeId:mt,onExpandApm:xt,expandedApmMethod:vr,buttonAppearance:{backgroundColor:ee.cardButton?.backgroundColor,borderColor:ee.cardInputBorder,textColor:ee.cardButton?.color,borderRadius:vo}})]}),Ce&&(Vc||jc||Wc)&&(0,d.jsx)(Ci,{label:"or pay with card"}),Ce&&gl]})}var B=require("react/jsx-runtime"),na=44,Is="flopay_checkout_saved_payment_resume",Ti=new Map,_i=new Map;function mc(e,t){t.settled&&t.consumers===0&&Ti.get(e)===t&&Ti.delete(e)}function su(e,t,r){let n=_i.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};_i.set(e,s);let c=()=>{_i.get(e)===s&&_i.delete(e)};return a.then(c,c),a}function Oa(e){return new Promise(t=>setTimeout(t,e))}function Ii(e,t,r){let n=li({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ue.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function La(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ws(e,t,r,n,a,s){let c=Ii(e,t,r);c.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),La(c)}function yc(e,t,r,n){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:t,...n===void 0?{}:{attempt:n},statusClass:"2xx"})}function fc(e,t,r,n,a){let s=(0,Ue.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:a,statusClass:s.statusClass}),t instanceof Ue.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Ue.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):s.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...s,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function ks(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,Ue.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var lu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function cu(e){return new io.FloPay(lu,{publishableKey:"provider_unavailable",...e})}async function Rs(e,t){let{publishableKey:r,paypalPublishableKey:n}=ls(e);return{...await cs({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Ts(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function du(){if(!Ts())return null;try{let e=window.sessionStorage.getItem(Is);return e?JSON.parse(e):null}catch{return null}}function gc(e){if(Ts())try{window.sessionStorage.setItem(Is,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Es(){if(Ts())try{window.sessionStorage.removeItem(Is)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function uu(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],r=!1;for(let n of t)e.searchParams.has(n)&&(e.searchParams.delete(n),r=!0);r&&window.history.replaceState(window.history.state,"",e.toString())}function hc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function _s(e,t){return(0,Ue.resolveCheckoutLogLayout)(!!e,t)}function pu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Pc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function mu(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function Mi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:c,loading:p,error:m,onComplete:g,onError:_,onInstrument:E,onDecline:I,onCancel:H,onCountryChange:T,onZipChange:Y,showPayPal:F=!0,showStripe:y=!0,walletPresentation:h="auto",enabledPaymentMethods:ge,showApplePay:w=!0,showGooglePay:Te=!0,debug:x=!1,layout:ie,theme:he,buttonsTheme:fe,buttonsStyles:ke,cardButtonContent:mt,cardBackButtonContent:Je,cardTitleContent:A,showSecurityFooter:kt,onButtonClick:tt,onBeforeButtonClick:Ve,enableAVS:me,cardFieldOrder:K,cardAutoFocus:W,cardPreFormSlot:Fe,avsLayout:lt,submitLabel:He,className:J,initialErrorMessage:D=null,initialPayPalOrderId:se,children:O,checkoutMode:be,confirmLabel:Me,renderConfirmButton:Pe,onSessionCompleted:Be}){let M=(0,Ue.resolveBillingApiUrl)(n),at=(0,P.useMemo)(()=>(0,Ue.resolveTheme)(he),[he]),Ke=s??at?.appearance,yt=r?"embedded_checkout":"standard_checkout",Ze=_s(O,ie),[Ge,_t]=(0,P.useState)(null),[Ut,qt]=(0,P.useState)(null),Ft=(0,P.useRef)(null),de=(0,P.useRef)(null),ue=(0,P.useRef)(0),[X,bt]=(0,P.useState)(null),ft=(0,P.useRef)(null),[V,rt]=(0,P.useState)(null),Rt=(0,P.useMemo)(()=>r?(0,vt.serializeCreateParams)(r):"",[r]),Re=r?`create:${Rt}`:`session:${e??""}`,v=Pc(V),q=(0,P.useRef)(new Set),oe=(0,P.useRef)(Re),xe=(0,P.useRef)(Re);ko(()=>{xe.current=Re,oe.current!==Re&&(oe.current=Re,q.current.clear())},[Re]);let Lt=(0,P.useCallback)(U=>{if(xe.current===Re){if(as.FLO_INSTRUMENT_ONCE_NAMES.has(U.name)){if(q.current.has(U.name))return;q.current.add(U.name)}(0,Qe.invokeMerchantCallback)(()=>E?.(U))}},[Re,E]),it=Xo(Lt,Re),De=(0,P.useRef)(!1),Oe=(0,P.useCallback)(U=>{if(De.current)return;let z=U.gateway||!v?U:{...U,gateway:v};Lt(z)},[Lt,v]);(0,P.useEffect)(()=>{it({class:"lifecycle",name:"checkout.mount"})},[it]);let[Tt,u]=(0,P.useState)(e??""),C=e??Tt,Q=r?"":C,[le,L]=(0,P.useState)(!0),[k,jt]=(0,P.useState)(null),[Mr,dr]=(0,P.useState)(0),[xr,ct]=(0,P.useState)("full"),[Gr,Yr]=(0,P.useState)(!1),[Ar,Gt]=(0,P.useState)(D),[nr,Qt]=(0,P.useState)(null),[Rn,Yt]=(0,P.useState)(null),[Nn,Fr]=(0,P.useState)(!1),[Xt,or]=(0,P.useState)(void 0),[on,gt]=(0,P.useState)(""),[Mt,Br]=(0,P.useState)(!1),[ar,Jt]=(0,P.useState)(!1),[Ur,hr]=(0,P.useState)(!1),Vt=(0,P.useRef)(null),Dr=(0,P.useRef)(0),kr=(0,P.useRef)(void 0),[Le,Or]=(0,P.useState)("loading"),[Xr,Xn]=(0,P.useState)(0),Pr=(0,P.useRef)(!1),an=(0,P.useRef)(!1),sn=(0,P.useRef)(!1),En=(0,P.useRef)(null),Wt=(0,P.useRef)(null),Ce=(0,P.useMemo)(()=>({checkoutMode:be??xr,layout:pu(O,ie)}),[be,O,xr,ie]),ln=(0,P.useRef)(g);ln.current=g;let zr=(0,P.useRef)(_);zr.current=_;let _n=(0,P.useRef)(I);_n.current=I;let N=(0,P.useCallback)(U=>ui(En,async z=>{try{return await U(z)}catch(ce){throw z.aborted?Zo(ce):ce}}),[]);(0,P.useEffect)(()=>()=>{En.current?.abort(),En.current=null},[]);let dt=(0,P.useCallback)((U,z)=>{Ft.current=U,qt(U),ft.current=z,bt(z)},[]),te=(0,P.useCallback)(()=>{let U=de.current;U&&(de.current=null,U.destroy())},[]);(0,P.useEffect)(()=>{Sr(Ut)?.setCheckoutContext(Ce),X&&X!==Ut&&Sr(X)?.setCheckoutContext(Ce)},[Ut,X,Ce]);let Se=(0,P.useRef)(Be);Se.current=Be;let Dt=(0,P.useCallback)(U=>{Or(U),!(U!=="exhausted"||sn.current)&&(sn.current=!0,zr.current?.(new Ue.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),$t=(0,P.useCallback)(()=>{Or("retrying"),Xn(U=>U+1)},[]);(0,P.useEffect)(()=>{Or("loading"),Xn(0),sn.current=!1},[C]),(0,P.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ue.SDK_VERSION,checkout_type:yt,checkout_layout:Ze,billing_api_url:M})},[Ze,yt,M]);let nt=(0,P.useMemo)(()=>r?(0,vt.serializeCreateParams)(r,!0):"",[r]),Ye=(0,P.useMemo)(()=>on===nt?Xt:void 0,[Xt,on,nt]),Jr=(0,P.useMemo)(()=>r?ts(r,Ye):void 0,[r,Ye]),Un=be??Jr?.checkoutMode??"full",er=(0,P.useMemo)(()=>Jr?{...Jr,checkoutMode:Un}:void 0,[Jr,Un]);(0,P.useEffect)(()=>{or(void 0),gt(nt),kr.current=void 0,Vt.current=null,hr(!1)},[nt]),(0,P.useEffect)(()=>{Gt(D)},[D]);let In=(0,P.useCallback)((U,z,ce)=>{(0,Qe.invokeMerchantCallback)(()=>{_n.current?.(br(U,z,ce))})},[]),Jn=(0,P.useCallback)(async(U,z)=>{Gt(null),Yt(null),Fr(!1),Qt("processing");let ce=z?.sessionId??U.id,ve=U.clientSecret||t,xt=Pc(U),zt=Ft.current??ft.current,ze=Sr(zt),Z=zt?null:Ii(M,a,Ce),re={log:Ne=>{ze?ze.log(Ne):Z?.log(Ne)},error:Ne=>{ze?ze.error(Ne):Z?.error(Ne)},terminal:Ne=>{ze?ze.terminal(Ne):Z?.terminal(Ne)},performance:Ne=>{ze?ze.performance(Ne):Z?.performance(Ne)},now:()=>ze?.now()??Z?.now()??0,elapsed:Ne=>ze?.elapsed(Ne)??Math.max(0,(Z?.now()??Ne)-Ne)},Xe=re.now(),Ee=!!(z?.initialAutoProcessingError||z?.initialAutoProcessingPending),ut=!1,j,pe=()=>{ut||(ut=!0,Ee=!0,j=re.now(),re.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ot=!1,ot=()=>{Ot||(Ot=!0,re.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),re.performance({stage:"processing",durationMs:re.elapsed(Xe),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),j!==void 0&&re.performance({stage:"recovery",durationMs:re.elapsed(j),durationMode:"machine",paymentMethodCategory:"saved"}))};re.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),De.current=!0;try{re.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{De.current=!1}it({class:"lifecycle",name:"payment.processing.started",provider:xt}),Ee&&pe();let pr;try{let Ne=Hl(z?.initialAutoProcessingError),f=z?.initialAutoProcessingError?.type==="3ds_required"&&!z.initialAutoProcessingError.threeDSecureToken&&z.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:z.initialAutoProcessingError.nextActionRedirectUrl}:null,S,ne=qe=>{pe();let je=Ia(M,ce,U,a!==!1);return N(ye=>Qo(qe,{billingApiUrl:M,sessionId:ce,nonce:ve,session:U,signal:ye,...je.telemetry?{challengeTelemetry:je.telemetry}:{}})).finally(je.release)};if(f)S=await ne(f);else if(Ne)pe(),Ne.type==="paypal_redirect_required"&&Wt.current?.publishableKey&&gc({sessionId:ce,publishableKey:Wt.current.publishableKey,paypalPublishableKey:Wt.current.paypalPublishableKey}),S=await N(qe=>mi(Ne,{flopay:Ft.current,paypalFlopay:ft.current,attempt3DS:z?.attempt3DS,billingApiUrl:M,sessionId:ce,session:U,telemetry:!1,signal:qe})),Ne.type==="paypal_redirect_required"&&Es();else if(z?.initialAutoProcessingPending){let qe=z.initialAutoProcessingPending,je=new io.PaymentAPI(M,{telemetry:!1}),ye=await N(Cr=>je.waitForCheckoutSessionCompletion(qe.sessionId,{initialDelayMs:qe.retryAfterMs,nonce:ve,statusUrl:qe.statusUrl,signal:Cr})),tr=yo(ye,U),ee=ye.autoProcessingError?.type==="3ds_required"&&ye.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ye.autoProcessingError.nextActionRedirectUrl}:null;if(ee)S=await ne(ee);else{if(!to(tr))throw $o(tr);S=eo(tr,ce)}}else{if(z?.initialAutoProcessingError)throw Hn(z.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:z.initialAutoProcessingError.checkoutMethod});if(z?.fromCreateSession)return z?.fallbackToFull&&(ct("full"),hc("full")),!1;{let qe=await ea({billingApiUrl:M,sessionId:ce,session:U,nonce:ve,telemetry:!1});qe.type==="success"?S=qe.result:qe.type==="next_action_required"?S=await ne(qe):(pe(),qe.type==="paypal_redirect_required"&&Wt.current?.publishableKey&&gc({sessionId:ce,publishableKey:Wt.current.publishableKey,paypalPublishableKey:Wt.current.paypalPublishableKey}),S=await N(je=>mi(qe,{flopay:Ft.current,paypalFlopay:ft.current,attempt3DS:z?.attempt3DS,billingApiUrl:M,sessionId:ce,session:U,telemetry:!1,signal:je})),qe.type==="paypal_redirect_required"&&Es())}}ce&&(0,Dn.markSessionRecentlyCompleted)(ce),ot(),Ee&&(re.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),re.terminal({outcome:S.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Fr(S.status==="authorized"),Qt("success"),await Oa(600),pr=()=>ln.current?.(S)}catch(Ne){let f=mo(Ta(Ne),ce);if(f.code==="three_ds_aborted")return!1;let S=f.checkoutMethod??_a;Gt(f.message),Yt(f.message),Fr(!1),z?.fallbackToFull&&(re.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),ct("full"),hc("full")),ot();let ne=f.statusCode===void 0?void 0:(0,Ue.telemetryStatusClass)(f.statusCode,"unknown"),qe=ne==="4xx"?{requestCategory:"process_payment",statusClass:ne}:{},je=ne===void 0||ne==="4xx";if(je&&(f.telemetryOutcome==="payment_declined"||!!(f.declineCode||f.code?.toLowerCase().includes("declin"))))re.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...qe});else if(je&&(f.telemetryOutcome==="validation_rejected"||f.type==="validation_error"))re.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...qe});else{let ee=(0,Ue.classifyTelemetryFailure)(Ne,Ee?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Cr=f.telemetryRequestCategory??"process_payment";De.current=!0;try{re.error({...ee,...f.telemetryFailureCategory?{failureCategory:f.telemetryFailureCategory}:{},stage:Ee?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Cr})}finally{De.current=!1}it({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Cr,provider:xt})}return(0,Qe.invokeMerchantCallback)(()=>zr.current?.(f)),In(S,f,{code:f.code,declineCode:f.declineCode}),Qt("error"),await Promise.allSettled([Oa(400),z?.ensureProvidersReady?z.ensureProvidersReady():Promise.resolve()]),Ee&&(re.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{ot(),Z&&La(Z),Qt(null),Yt(null)}return(0,Qe.invokeMerchantCallback)(pr),!0},[In,it,t,M,N,a,Ce]);(0,P.useEffect)(()=>{if(typeof window>"u"||an.current)return;let U=new URLSearchParams(window.location.search),z=U.get("payment_intent_client_secret");if(!z)return;let ce=du();ce&&(an.current=!0,(async()=>{let ve,xt=0;Gt(null),Yt(null),Qt("processing"),Yr(!0);try{if(U.get("redirect_status")==="failed")throw Object.assign(new Ue.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:zt,paypalFlopay:ze}=await cs({publishableKey:ce.publishableKey,paypalPublishableKey:ce.paypalPublishableKey,billingApiUrl:M,locale:c,telemetry:a});ve=Sr(ze??zt),ve?.setCheckoutContext(Ce),xt=ve?.now()??0,ve?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Z=(ze??zt)?.getRawProvider();if(!Z)throw Object.assign(new Ue.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:re,error:Xe}=await Z.retrievePaymentIntent(z);if(Xe)throw Object.assign(new Ue.FloPayError(Xe.message??"Failed to retrieve PayPal payment status.","api_error",{code:Xe.code}),{checkoutMethod:"paypal"});let Ee=xl(re?.status);if(!re||Ee==="failed")throw Object.assign(new Ue.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let ut=typeof re.payment_method=="string"?re.payment_method:re.payment_method?.id,j=Ee;if(ce.sessionId){let ot=(await new io.PaymentAPI(M,{telemetry:!1}).getUnifiedCheckoutSession(ce.sessionId)).data.session;if(ot&&ot.status!=="complete"){let pr=await ea({billingApiUrl:M,sessionId:ce.sessionId,session:ot,telemetry:!1,tokenizedData:{id:ut??re.id,type:"card",threeDSecureActionResultTokenId:re.id,isPaypal:!0}});if(pr.type!=="success")throw Object.assign(new Ue.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});j=pr.result.status}}ce.sessionId&&(0,Dn.markSessionRecentlyCompleted)(ce.sessionId),ve?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.performance({stage:"redirect_resume",durationMs:ve.elapsed(xt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Qt("success"),await Oa(600),(0,Qe.invokeMerchantCallback)(()=>ln.current?.({status:j,paymentIntentId:re.id,paymentMethodId:ut,checkoutMethod:"paypal"}))}catch(zt){let ze=mo(Ta(zt),ce.sessionId),Z=ze.checkoutMethod??"paypal",re=!!(ze.declineCode||ze.code?.toLowerCase().includes("declin"));if(ve)ve.performance({stage:"redirect_resume",durationMs:ve.elapsed(xt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),re?ve.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ve.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(re){let Xe=Ii(M,a,Ce);Xe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),La(Xe)}else ws(M,a,Ce,"REDIRECT_RESUME_FAILED","redirect_resume");Gt(ze.message),Yt(ze.message),(0,Qe.invokeMerchantCallback)(()=>zr.current?.(ze)),In(Z,ze,{code:ze.code,declineCode:ze.declineCode}),Qt("error"),await Oa(400)}finally{Es(),uu(),Qt(null),Yt(null),Yr(!1)}})())},[In,c,M,a,Ce]);let Zn=(0,P.useRef)(null),Tn=(0,P.useMemo)(()=>er?(0,vt.serializeCreateParams)(er):"",[er]),lo=(0,P.useRef)(er);lo.current=er,(0,P.useEffect)(()=>{u(e??"")},[e]),(0,P.useEffect)(()=>{Pr.current=!1,Gt(D),Yt(null),Fr(!1),Qt(null)},[Tn,D,e]);async function Qn(U,z,ce){let ve=Ii(M,a,Ce),xt=new io.PaymentAPI(M,{telemetry:!1}),zt=!1;try{let ze=U.idempotencyKey===void 0?void 0:(0,Ue.resolveIdempotencyKey)(U.idempotencyKey),Z=(0,vt.readCachedInlineSession)(z,ce),re=(0,vt.readCachedInlineIdempotencyKey)(z,ce);Z?.canonicalIdentity===ce&&re&&re.canonicalIdentity===void 0&&((0,vt.persistCachedInlineIdempotencyKey)(z,ce,re.idempotencyKey),re={...re,canonicalIdentity:ce});let Xe=ze??(re?.canonicalIdentity===ce?re.idempotencyKey:void 0),Ee,ut=!1;ve.log({name:Z?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let j=Z?.sid??null,pe=null,Ot,ot,pr=!1;if(j)try{pe=await xt.getUnifiedCheckoutSession(j,Z?.nonce),Z&&Z.canonicalIdentity===void 0&&((0,vt.legacyCachedSessionMatchesDraft)(pe.data.session,U)?((0,vt.persistCachedInlineSession)(z,ce,j,Z.nonce??pe.data.session?.clientSecret),re&&re.canonicalIdentity===void 0&&((0,vt.persistCachedInlineIdempotencyKey)(z,ce,re.idempotencyKey),Xe??(Xe=re.idempotencyKey))):((0,vt.clearCachedInlineCheckout)(z,ce),re=null,Xe=ze,j=null,pe=null));let f=pe?.data.session?.status,S=pe?.data.session,ne=S?.clientSecret||Z?.nonce;if(j&&S?.buyerIdentified===!1&&ne&&(ot=Wo(xt,j,ne,U.account)),j&&pe&&f==="complete"){if((0,Dn.wasSessionRecentlyCompleted)(j))return{sid:j,result:pe};(0,vt.clearCachedInlineCheckout)(z,ce),j=null,pe=null,ut=!0}}catch{ve.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Z?.canonicalIdentity===void 0?((0,vt.clearCachedInlineCheckout)(z,ce),Xe=ze):(0,vt.clearCachedInlineSession)(z,ce),j=null}if(!j){!ze&&(ut||!Xe)&&(Xe=(0,Ue.resolveIdempotencyKey)(),Ee=Xe),Xe&&(0,vt.persistCachedInlineIdempotencyKey)(z,ce,Xe);let f=ve.now(),S=0;ve.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ne={...U,idempotencyKey:Xe,avsCheck:!!me,avsConfig:typeof me=="object"?me:void 0,checkoutType:"embedded_checkout",checkoutLayout:_s(O,ie)};Object.defineProperty(ne,io.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ye=>{S=Math.max(S,ye)}}});let qe=()=>{yc(ve,"session_create",f,S)},je=ye=>{fc(ve,ye,"session_create",f,S)&&it({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Ue.isDetachedSessionEligible)(ne)){let ye=await xt.createDetachedSession(ne);ye.claimed.catch(()=>{}),pe=ye.shell,j=ye.sessionId,ot=ye.claim;let tr=ve.now();ve.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Ot=ye.claimed.then(ee=>{let Cr=ee.data.session?.id??ye.sessionId;return Cr&&(0,vt.persistCachedInlineSession)(z,ce,Cr,ee.data.session?.clientSecret??ye.nonce),yc(ve,"session_claim",tr),qe(),ee},ee=>{throw(0,vt.clearCachedInlineSession)(z,ce),fc(ve,ee,"session_claim",tr,0)&&it({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),ee}).finally(()=>La(ve)),Ot.catch(()=>{}),zt=!0,ve.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ve.performance({stage:"session_shell",durationMs:ve.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:S,statusClass:"2xx",paymentMethodCategory:"card"})}else pe=await xt.createAndFetchSession(ne),qe()}catch(ye){throw je(ye),ye}j=pe.data.session?.id??j??"",j&&!Ot&&(0,vt.persistCachedInlineSession)(z,ce,j,pe.data.session?.clientSecret)}let Ne=pe?.data.session;return!ot&&j&&Ne?.buyerIdentified===!1&&Ne.clientSecret&&(ot=Wo(xt,j,Ne.clientSecret,U.account)),{sid:j??"",result:pe,sdkGeneratedIdempotencyKey:Ee,...Ot?{claimed:Ot}:{},...ot?{claim:ot}:{},...pr?{claimRequiresIdentity:!0}:{}}}finally{zt||La(ve)}}let go=(0,P.useRef)(Qn);ko(()=>{go.current=Qn},[Qn]);let yn=(0,P.useCallback)(async(U,z)=>{let ce=lo.current;if(!ce)throw new Ue.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ve=ts(ce,U),xt=(0,vt.serializeCreateParams)(ve),zt=(0,vt.hashCreateParams)(ve),ze=Ti.get(xt);if(!ze){let Xe={canonicalIdentity:xt,promise:go.current(ve,zt,xt),consumers:0,settled:!1};ze=Xe,Ti.set(xt,Xe);let Ee=()=>{Xe.settled=!0,mc(xt,Xe)};Xe.promise.then(Ee,Ee)}ze.consumers+=1;let Z=!1,re=()=>{Z||(Z=!0,ze.consumers-=1,mc(xt,ze))};z?.(re);try{let Xe=await ze.promise;Zn.current=xt,U&&(gt(nt),or(Ne=>Rl(Ne,U)));let{sid:Ee,result:ut,claimed:j,claim:pe,claimRequiresIdentity:Ot}=Xe;if(kr.current=pe,hr(Ot===!0),_t(ut),ut.data.session&&rt(ut.data.session),Ee&&u(Ee),j){Dr.current+=1;let Ne=Dr.current;Vt.current=j,Jt(!0),j.then(f=>{Dr.current===Ne&&(Vt.current===j&&(Vt.current=null),_t(f),f.data.session&&rt(f.data.session),Jt(!1),hr(!1))},f=>{Dr.current===Ne&&(Vt.current===j&&(Vt.current=null),Jt(!1),hr(!1),jt(f instanceof Ue.FloPayError?f:new Ue.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error")))})}else Dr.current+=1,Vt.current=null,Jt(!1),hr(!1);let{flopay:ot,paypalFlopay:pr}=await Rs(ut,{billingApiUrl:M,locale:c,telemetry:a}).catch(Ne=>{throw Il(Ne,Ee||ut.data.session?.id)});return dt(ot,pr),L(!1),Xe}catch(Xe){throw Zn.current===xt&&(Zn.current=null),Xe}finally{z||re()}},[nt,dt,c,M,a]),jr=(0,P.useRef)(Jn);jr.current=Jn;let co=(0,P.useRef)(yn);co.current=yn;let Nt=(0,P.useCallback)(async U=>{if(!mu(U)||Mt)return{sessionId:Tt,session:V};Br(!0);try{let z=await yn(U);return{sessionId:z.sid,session:z.result.data.session??null}}finally{Br(!1)}},[yn,Mt,Tt,V]),Zr=(0,P.useCallback)(async U=>{let z=kr.current;if(!z)return;let ce=Dr.current,ve=await z(U);Dr.current===ce&&(_t(ve),ve.data.session&&rt(ve.data.session))},[]),Qr=(0,P.useCallback)(async()=>{await Vt.current},[]),cn=(0,P.useCallback)(async()=>(await Qr(),{proceed:!0}),[Qr]);(0,P.useEffect)(()=>{let U=!1,z,ce=++ue.current;te(),jt(null),dr(0);let ve=()=>{U=!0,ue.current===ce&&(ue.current+=1,te())},xt=lo.current;if(Tn&&xt)return ct(Un),L(!1),Zn.current===Tn?ve:(rt(El(xt,be)),(async()=>{let Z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),re=Un==="auto"&&!Pr.current&&!Z;re&&(Gt(null),Yt(null),Qt("processing"));let Xe=!1;try{let Ee=await co.current(void 0,Ot=>{z=Ot});Xe=!0;let ut=Ee.result.data.session??null;Wt.current=ls(Ee.result);let j=ks(Ee.result),pe=(0,Dn.wasSessionRecentlyCompleted)(Ee.sid||ut?.id);if(!U&&re&&ut&&!j&&!pe){Pr.current=!0,await su(Tn,Ee.sdkGeneratedIdempotencyKey,()=>jr.current(ut,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Ee.result.autoProcessingError,initialAutoProcessingPending:Ee.result.autoProcessingPending,autoProcessingAttempted:Ee.result.autoProcessingAttempted,sessionId:Ee.sid||ut.id}));return}!U&&re&&((j||pe)&&(Pr.current=!0),Qt(null),Yt(null))}catch(Ee){if(U)return;let ut=ti(Ee);if(re&&ut==="session_auto_completed"){Pr.current=!0,Qt("success"),await Oa(600),U||((0,Qe.invokeMerchantCallback)(()=>{ln.current?.({status:"succeeded"})}),Qt(null),Yt(null));return}if(re&&(Qt(null),Yt(null)),!Xe){let pe=Tl(Ee),Ot=(0,Ue.toPublicCheckoutInitError)(Ee,pe?{stage:"provider_load",provider:"stripe",...pe}:{stage:"session_request"});(pe||!(Ee instanceof Ue.FloPayError))&&(0,Qe.invokeMerchantCallback)(()=>zr.current?.(Ot)),jt(Ot);return}let j=Ee instanceof Ue.FloPayError?Ee:new Ue.FloPayError(Ee instanceof Error?Ee.message:"Failed to create session","api_error");jt(j)}finally{z?.(),z=void 0}})(),()=>{ve(),z?.()});L(!0);async function zt(){let Z=!1,re=!1,Xe=null;try{let Ee=new io.PaymentAPI(M,{telemetry:!1}),ut=await Ee.getUnifiedCheckoutSession(C,t);if(re=!0,Xe=ut,U)return;_t(ut);let j=ut.data.session??null;if(rt(j),!j)throw new Ue.FloPayError("No session data returned","api_error");let pe=j.checkoutMode;if(pe==="setup")throw new Ue.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(j.status==="authorized"){L(!1),(0,Qe.invokeMerchantCallback)(()=>{ln.current?.(eo(j,C)),Se.current?.(j.successUrl??"")});return}if(j.status==="complete"){L(!1),(0,Qe.invokeMerchantCallback)(()=>{Se.current?.(j.successUrl??"")});return}if(j.status==="expired")throw ei(j);Z=!0;let Ot=be??pe??"full";ct(Ot),Dr.current+=1;let ot=j.clientSecret||t;kr.current=j.buyerIdentified===!1&&ot?Wo(Ee,C,ot,{...j.customer?.id?{userId:j.customer.id}:{}}):void 0,Jt(!1),hr(!1);let pr=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ne=ks(ut);if(Ot==="auto"&&!Pr.current&&!pr&&!Ne){Pr.current=!0;let f=ze(ut);try{if(await jr.current(j,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>f,sessionId:C||j.id}),U)return;await f,U||L(!1);return}catch{if(U)return;await f,U||L(!1);return}}await ze(ut),U||L(!1)}catch(Ee){if(U)return;let ut=kl(Ee,Z);if(Z&&it({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ut){let{errorCode:ot,stage:pr,...Ne}=ut;ws(M,a,Ce,ot,pr,Ne)}if(ut?.stage==="provider_load"&&(be??Xe?.data.session?.checkoutMode??"full")==="full"&&wl(Xe,F,y)){let ot=cu({billingApiUrl:M,locale:c,telemetry:a});de.current=ot,dt(ot,null),dr(1),L(!1);return}let j=ut?.stage==="provider_load",pe="session_request";j?pe="provider_load":re&&(pe="post_session");let Ot=(0,Ue.toPublicCheckoutInitError)(Ee,{stage:pe,provider:"stripe",sessionId:C||void 0});(j||!(Ee instanceof Ue.FloPayError))&&(0,Qe.invokeMerchantCallback)(()=>zr.current?.(Ot)),jt(Ot),L(!1)}}async function ze(Z){let{flopay:re,paypalFlopay:Xe,...Ee}=await Rs(Z,{billingApiUrl:M,locale:c,telemetry:a});Wt.current={publishableKey:Ee.publishableKey,paypalPublishableKey:Ee.paypalPublishableKey},dt(re,Xe),dr(0)}return zt(),ve},[be,Tn,Un,Q,t,F,y]);let dn=(0,P.useCallback)(async()=>{if(!Ge||Mr!==1)return;let U=ue.current;dr(2);try{let{flopay:z,paypalFlopay:ce}=await Rs(Ge,{billingApiUrl:M,locale:c,telemetry:a});if(ue.current!==U)return;te(),dt(z,ce),dr(0)}catch(z){if(ue.current!==U)return;let{errorCode:ce,stage:ve,...xt}=es(z);ws(M,a,Ce,ce,ve,xt)}},[te,dt,c,Mr,M,a,Ce,Ge]),st=!!(C&&(V?.clientSecret||t)),ur=Gr||!st,vr=(0,P.useCallback)(async()=>{if(!(Gr||!st||!V)){Yr(!0),Gt(null);try{await Jn(V,{attempt3DS:!0,fallbackToFull:!0,sessionId:C||V.id})}finally{Yr(!1)}}},[C,Gr,st,Jn,V]),Rr=(0,Ue.resolveDirectPaypalConfig)(Ge?.data.paypal,se),ho=ks(Ge),zn=(0,P.useMemo)(()=>{if(!(!Ge||!V||!Ge.data.stripe?.publishableKey))return{billingApiUrl:M}},[Ge,V,M]),uo=!!(r&&!O&&ie==="buttons"&&Ve&&Un==="full"),Vr=!!(C&&((0,Ue.isMountableVaultBlock)(V?.vault)||(0,An.canRecoverHostedCardForm)(V))),Er=(0,P.useMemo)(()=>({session:V,loading:le,error:k,checkoutMode:xr,inlineSessionDraft:er,applyInlineSessionPatch:uo?Nt:void 0,inlineSessionPatchProcessing:Mt,claimPending:ar,claimRequiresIdentity:Ur,claimBuyerIdentity:Zr,waitForDataAttachment:Qr}),[V,le,k,xr,er,uo,Nt,Mt,ar,Ur,Zr,Qr]),po=!!r&&ie==="buttons"&&!ho&&!Vr&&(!Ut||!zn),Lr=nr?(0,B.jsx)(rn,{status:nr,errorMessage:Rn,authorized:Nn}):null;if(le&&!Vr){if(p)return(0,B.jsxs)(B.Fragment,{children:[p,Lr]});if(ie==="buttons"){let U=at?.buttonsLayout?.cardButton?.borderRadius??at?.appearance.variables?.borderRadius??8,z=ce=>(0,B.jsx)("div",{style:{height:ce,borderRadius:U,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[F&&z(na),y&&(w||Te)&&z(na),y&&z(na),(0,B.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Lr]})}return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,B.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,B.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Lr]})}return k?m?(0,B.jsx)(Fn.Provider,{value:Er,children:m(k)}):(0,B.jsx)(Fn.Provider,{value:Er,children:(0,B.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:k.message})}):po?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fn.Provider,{value:Er,children:(0,B.jsx)(fu,{onButtonClick:tt,showPayPal:F,showStripe:y,showApplePay:w,showGooglePay:Te,theme:he,buttonsTheme:fe,buttonsStyles:ke,cardButtonContent:mt,cardBackButtonContent:Je,cardTitleContent:A})}),Lr]}):ho&&V&&Rr?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fn.Provider,{value:Er,children:(0,B.jsxs)("div",{className:J,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ar&&(0,B.jsx)(Jo,{icon:!1,children:Ar}),Le==="retrying"&&(0,B.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Le==="exhausted"&&(0,B.jsxs)("div",{role:"alert",children:[(0,B.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,B.jsx)("button",{type:"button",onClick:$t,children:"Retry PayPal"})]}),Le!=="exhausted"&&(0,B.jsx)("div",{"aria-hidden":Le==="retrying"?!0:void 0,style:Le==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,B.jsx)(jl,{sessionId:C,nonce:V.clientSecret||void 0,billingApiUrl:M,email:V.customer?.email||er?.account?.email,billingName:[V.customer?.firstName,V.customer?.lastName].filter(Boolean).join(" ")||[er?.account?.firstName,er?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Zr,clientId:Rr.clientId,environment:Rr.environment,currency:(V.currency??"usd").toUpperCase(),isSubscription:V.mode==="subscription",providerObjectType:Rr.providerObjectType,approvalPresentation:Rr.approvalPresentation,existingOrderId:Rr.existingOrderId,onComplete:g,onErrorChange:Gt,onDecline:I,onCancel:H,onButtonClick:tt,runBeforeButtonClick:cn,onInitializationStateChange:Dt,allowAutomaticRetry:Xr===0,session:V,telemetry:a,telemetryContext:Ce,onInstrument:Oe,debug:x},`${Re}:paypal-init-${Xr}`)})]})}),Lr]}):xr==="confirm"?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fn.Provider,{value:Er,children:(0,B.jsx)(Ra,{flopay:Ut,paypalFlopay:X,options:zn??{billingApiUrl:M},onInstrument:Oe,children:(0,B.jsxs)("div",{className:J,children:[Ar&&(0,B.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ar}),Pe?Pe({onConfirm:vr,isProcessing:ur}):(0,B.jsx)("button",{type:"button",onClick:vr,disabled:ur,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:ur?"not-allowed":"pointer",opacity:ur?.6:1},children:Gr?"Processing...":Me??"Confirm Purchase"})]})},Re)}),Lr]}):(!Ut||!zn)&&!(Vr&&xr==="full")?(0,B.jsx)(B.Fragment,{children:Lr}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fn.Provider,{value:Er,children:(0,B.jsxs)(Ra,{flopay:Ut,paypalFlopay:X,options:zn??{billingApiUrl:M},onInstrument:Oe,children:[Mr===1&&(0,B.jsx)("button",{type:"button",onClick:dn,children:"Retry payment methods"}),O?(0,B.jsxs)(B.Fragment,{children:[Ar&&(0,B.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ar}),(0,B.jsx)(yu,{sessionId:C,nonce:V?.clientSecret||void 0,billingApiUrl:M,session:V,submitLabel:He,walletPresentation:h,children:O})]}):(0,B.jsx)(Ei,{sessionId:C,nonce:V?.clientSecret||void 0,telemetry:a,email:V?.customer?.email||er?.account?.email,userId:V?.customer?.id||er?.account?.userId,firstName:V?.customer?.firstName||er?.account?.firstName,lastName:V?.customer?.lastName||er?.account?.lastName,totalAmount:V?Math.round((0,Ue.buildCheckoutDisplayData)(V).total*100):0,currency:V?.currency?.toLowerCase()??"usd",onComplete:g,onError:_,onDecline:I,onCancel:H,error:Ar,onErrorChange:Gt,showPayPal:F,showStripe:y,walletPresentation:h,enabledPaymentMethods:Mr?[]:ge??Ge?.data.stripe?.enabledPaymentMethods??V?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ge?.data.stripe?.enabledPaymentMethodCountries,showApplePay:w,showGooglePay:Te,layout:ie,theme:he,buttonsTheme:fe,buttonsStyles:ke,appearance:Ke,cardButtonContent:mt,cardBackButtonContent:Je,cardTitleContent:A,onButtonClick:tt,onBeforeButtonClick:Ve,onBuyerIdentityReady:Zr,enableAVS:me,...K?{cardFieldOrder:K}:{},...W===void 0?{}:{cardAutoFocus:W},...Fe?{cardPreFormSlot:Fe}:{},avsLayout:lt,country:V?.customer?.country,city:V?.customer?.city,state:V?.customer?.state,onCountryChange:T,onZipChange:Y,avsCheck:!!me,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:_s(O,ie),className:J,submitLabel:He,directPaypal:Rr,isSubscription:V?.mode==="subscription",session:V,dataAttachmentPending:ar,dataAttachmentRequiresIdentity:Ur,debug:x})]},Re)}),Lr]})}function yu({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,children:c}){return(0,B.jsx)(B.Fragment,{children:P.default.Children.map(c,p=>{if(!P.default.isValidElement(p))return p;let m=p.props,g={};return m.sessionId||(g.sessionId=e),!m.nonce&&t&&(g.nonce=t),m.billingApiUrl||(g.billingApiUrl=r),m.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),m.walletPresentation===void 0&&(g.walletPresentation=s),n?.customer&&(m.email||(g.email=n.customer.email),m.userId||(g.userId=n.customer.id),m.firstName||(g.firstName=n.customer.firstName),m.lastName||(g.lastName=n.customer.lastName)),Object.keys(g).length===0?p:P.default.cloneElement(p,g)})})}function fu({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:s,buttonsTheme:c,buttonsStyles:p,cardButtonContent:m,cardBackButtonContent:g,cardTitleContent:_}){let[E,I]=(0,P.useState)(!1),H=(0,P.useMemo)(()=>(0,Ue.resolveTheme)(s),[s]),T=(0,P.useMemo)(()=>{let h=H?.buttonsLayout??(0,Ue.resolveButtonsLayoutTheme)(c);return p?{...h,...p,cardButton:{...h.cardButton,...p.cardButton},cardFormContainer:{...h.cardFormContainer,...p.cardFormContainer},backButton:{...h.backButton,...p.backButton},backButtonIcon:{...h.backButtonIcon,...p.backButtonIcon},submitButton:{...h.submitButton,...p.submitButton},title:{...h.title,...p.title}}:h},[H,c,p]),Y=H?.buttonsLayout?.cardButton?.borderRadius??H?.appearance.variables?.borderRadius??8,F=h=>(0,B.jsx)("div",{style:{height:h,borderRadius:Y,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),y=m===void 0?{boxSizing:"border-box",height:na,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let h=T.cardInputBorder??"#e5e7eb",ge=T.cardInputBackground??"white",w=qo(g),Te=qo(_);return(0,B.jsxs)("div",{style:{backgroundColor:T.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...T.cardFormContainer},children:[(0,B.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,B.jsxs)("button",{type:"button",onClick:()=>I(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:w?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...T.backButton},children:[(0,B.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...T.backButtonIcon},children:(0,B.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,B.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,B.jsx)(Vo,{content:g})]}),Te?(0,B.jsx)("div",{style:{flex:1}}):(0,B.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...T.title},children:(0,B.jsx)(ha,{content:_})})]}),(0,B.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${h}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsxs)("div",{style:{display:"flex"},children:[(0,B.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsx)("div",{style:{flex:1,backgroundColor:ge,borderTop:"none",borderRight:`1px solid ${h}`,borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,B.jsx)("div",{style:{backgroundColor:ge,border:`1px solid ${h}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...T.submitButton,opacity:.5}}),(0,B.jsx)("style",{children:`
41
41
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
42
42
  @keyframes flopay-interim-expand {
43
43
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
44
44
  40% { opacity: 1; }
45
45
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
46
46
  }
47
- `})]})}return(0,D.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&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,_]),[Ze,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||Ze)){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,Ze,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||Ze,"aria-busy":Ze,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||Ze?"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||Ze?.6:1,...dt},onMouseEnter:b=>{Ge.onMouseEnter?.(b),!b.defaultPrevented&&!pe&&!Ze&&(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]),Ze=(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 Ze.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)(()=>Ze.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]),Ze=_c[e]?.wallet,Le=Ze==="paypal"&&(0,Hn.resolveStripePayPalPresentation)(Re,"auto",dt?"blocked":Re.popupCapability)==="redirect",de=c?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&Ze&&!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,[Ze]);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"),Je=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 Je.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,Je.useState)(ra.readSetupRedirectReturn),[P,me]=(0,Je.useState)(null),[S,Te]=(0,Je.useState)(!1),[T,ae]=(0,Je.useState)(null),[ye,pe]=(0,Je.useState)(null),[Re,dt]=(0,Je.useState)(null),[Ge,x]=(0,Je.useState)(null),[kt,Ze]=(0,Je.useState)(()=>new Set),Le=(0,Je.useRef)(kt),de=(0,Je.useRef)(null);de.current=P;let ee=(0,Je.useRef)(!1),H=(0,Je.useRef)(!1),Oe=(0,Je.useRef)(!1),nt=(0,Je.useRef)(!1),je=(0,Je.useRef)(0),Y=(0,Je.useRef)(0),W=(0,Je.useRef)(!1),{vaultTheme:$,surface:V,overlayTheme:He,appearance:Be,buttonsLayout:fe}=(0,Je.useMemo)(()=>Mi({theme:c,appearance:m,buttonsStyles:h}),[c,m,h]),B=(0,Je.useMemo)(()=>(0,Ma.mergeCardSetupSurface)(V,p),[V,p]),ge=(0,Je.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,Je.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,Je.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,Je.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,Je.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,Je.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,Je.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,Ze(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,Je.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,Je.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,Ze(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,Je.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,Je.useRef)(tt);mr.current=tt;let Ft=(0,Je.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,Je.useCallback)(d=>{if(Le.current.has(d))return;let L=new Set(Le.current);L.add(d),Le.current=L,Ze(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,Je.useRef)(Ce);A.current=Ce;let bt=(0,Je.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)(Je.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)(Je.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});
47
+ `})]})}return(0,B.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&F(na),r&&(n||a)&&F(na),r&&(0,B.jsx)("button",{type:"button",onClick:()=>{e?.("card"),I(!0)},style:{width:"100%",...y,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:T.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...T.cardButton},onMouseDown:h=>{h.currentTarget.style.transform="scale(0.985)"},onMouseUp:h=>{h.currentTarget.style.transform="scale(1)"},children:(0,B.jsx)(jo,{content:m})}),(0,B.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var bn=require("react/jsx-runtime"),gu=44;function vc(e){return new Promise(t=>setTimeout(t,e))}function hu(e,t){return e instanceof Sn.FloPayError?e:new Sn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Pu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function vu(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function Cc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:s,products:c,items:p,subscriptions:m,account:g,successUrl:_,cancelUrl:E,couponCodes:I,tagsData:H,utmMetadata:T,billingApiUrl:Y,locale:F,theme:y,appearance:h,buttonsTheme:ge,buttonsStyles:w,onSuccess:Te,onError:x,onDecline:ie,children:he,disabled:fe=!1,type:ke="button",style:mt,...Je}){let A=(0,Ct.useMemo)(()=>(0,Sn.resolveBillingApiUrl)(Y),[Y]),kt=(0,Ct.useMemo)(()=>vu({createSession:r,clientId:s,products:c,items:p,subscriptions:m,account:g,successUrl:_,cancelUrl:E,couponCodes:I,tagsData:H,utmMetadata:T}),[g,E,s,I,r,c,p,m,_,H,T]),[tt,Ve]=(0,Ct.useState)(!1),[me,K]=(0,Ct.useState)(null),[W,Fe]=(0,Ct.useState)(null),[lt,He]=(0,Ct.useState)(!1),[J,D]=(0,Ct.useState)(null),[se,O]=(0,Ct.useState)(null),be=(0,Ct.useRef)(!0),Me=(0,Ct.useRef)(null),Pe=(0,Ct.useRef)(se),Be=(0,Ct.useRef)(Te),M=(0,Ct.useRef)(x),at=(0,Ct.useRef)(ie),Ke=(0,Ct.useCallback)(v=>ui(Me,async q=>{try{return await v(q)}catch(oe){throw q.aborted?Zo(oe):oe}}),[]);(0,Ct.useEffect)(()=>{Pe.current=se},[se]),(0,Ct.useEffect)(()=>{Be.current=Te},[Te]),(0,Ct.useEffect)(()=>{M.current=x},[x]),(0,Ct.useEffect)(()=>{at.current=ie},[ie]),(0,Ct.useEffect)(()=>(be.current=!0,()=>{be.current=!1,Me.current?.abort()}),[]),(0,Ct.useEffect)(()=>{if(typeof window>"u")return;let v=q=>{q.key==="Escape"&&O(null)};return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[]);let yt=(0,Ct.useCallback)((v,q=_a)=>{at.current?.(br(q,v,{code:v.code,declineCode:v.declineCode}))},[]),Ze=(0,Ct.useCallback)(async v=>{be.current&&(Fe(null),He(v.result.status==="authorized"),K("success"),await vc(600),be.current&&(0,Qe.invokeMerchantCallback)(()=>Be.current?.(v)))},[]),Ge=(0,Ct.useCallback)(async(v,q)=>{be.current&&(M.current?.(v),q?.emitDecline&&yt(v,q.method),Fe(v.message),He(!1),K("error"),await vc(400))},[yt]),_t=(0,Ct.useCallback)(async(v,q,oe)=>{let xe=v.data.session??null;if(!xe)throw mo(new Sn.FloPayError("No session data returned","api_error"),q);let Lt=xe.clientSecret||t;if(to(xe)){await Ze({result:eo(xe,q),session:xe,sessionId:xe.id||q,autoCompleted:!1});return}if(xe.status==="expired")throw mo(ei(xe),xe.id||q);try{if(v.autoProcessingPending){let De=v.autoProcessingPending,Oe=new xi.PaymentAPI(A),Tt=await Ke(Q=>Oe.waitForCheckoutSessionCompletion(De.sessionId,{initialDelayMs:De.retryAfterMs,nonce:Lt,statusUrl:De.statusUrl,signal:Q})),u=yo(Tt,xe),C=Tt.autoProcessingError?.type==="3ds_required"&&Tt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Tt.autoProcessingError.nextActionRedirectUrl}:null;if(C&&q&&Lt){let Q=Ia(A,q,xe),le=await Ke(L=>Qo(C,{billingApiUrl:A,sessionId:q,nonce:Lt,session:xe,signal:L,telemetry:!0,...Q.telemetry?{challengeTelemetry:Q.telemetry}:{}})).finally(Q.release);await Ze({result:le,session:xe,sessionId:xe.id||q,autoCompleted:!1});return}if(Tt.autoProcessingError)throw Hn(Tt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Tt.autoProcessingError.checkoutMethod});if(!to(u))throw $o(u);await Ze({result:eo(u,q),session:u,sessionId:u.id||q,autoCompleted:!1});return}if(v.autoProcessingError){let De=v.autoProcessingError.nextActionRedirectUrl;if(v.autoProcessingError.type==="3ds_required"&&De&&q&&Lt){let Oe=await Ke(Q=>Kl({billingApiUrl:A,sessionId:q,nonce:Lt,nextActionRedirectUrl:De,signal:Q}));if(Oe.status==="declined")throw Hn({type:Oe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Oe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:v.autoProcessingError.checkoutMethod});let u=await new xi.PaymentAPI(A).waitForCheckoutSessionCompletion(q,{initialDelayMs:0,nonce:Lt}),C=yo(u,xe);if(!to(C))throw Hn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:v.autoProcessingError.checkoutMethod});await Ze({result:eo(C,q),session:C,sessionId:C.id||q,autoCompleted:!1});return}throw Hn(v.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:v.autoProcessingError.checkoutMethod})}if(oe?.fromCreateSession&&v.autoProcessingAttempted===!0)throw Hn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let it=await ea({billingApiUrl:A,sessionId:q??xe.id,session:xe,nonce:Lt});if(it.type==="next_action_required"&&Lt){let De=q??xe.id,Oe=Ia(A,De,xe),Tt=await Ke(u=>Qo(it,{billingApiUrl:A,sessionId:De,nonce:Lt,session:xe,signal:u,telemetry:!0,...Oe.telemetry?{challengeTelemetry:Oe.telemetry}:{}})).finally(Oe.release);await Ze({result:Tt,session:xe,sessionId:xe.id||De,autoCompleted:!1});return}if(it.type!=="success")throw Hn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ze({result:it.result,session:xe,sessionId:xe.id||q,autoCompleted:!1})}catch(it){let De=xe.id||q,Oe=mo(Ta(it),De);if(Oe.code==="three_ds_aborted")return;if(Oe.code==="checkout_processing_timeout"){if(!be.current)return;D(Oe.message),(0,Qe.invokeMerchantCallback)(()=>M.current?.(Oe));return}await Ge(Oe,{emitDecline:!0,method:Oe.checkoutMethod??_a}),Pu(Oe,De)&&De&&be.current&&O({sessionId:De,errorMessage:Oe.message,nonce:Lt||void 0,payPalOrderId:Oe.orderId})}},[t,A,Ke,Ge,Ze]),Ut=(0,Ct.useCallback)(async v=>{if(Je.onClick?.(v),!(v.defaultPrevented||fe||tt)){if(O(null),D(null),e&&kt){let q=new Sn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Ge(q),be.current&&(K(null),Fe(null));return}if(!e&&!kt){let q=new Sn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Ge(q),be.current&&(K(null),Fe(null));return}Ve(!0),Fe(null),He(!1),K("processing");try{let q=new xi.PaymentAPI(A);if(e){let oe=await q.getUnifiedCheckoutSession(e,t);await _t(oe,e);return}try{let oe=await q.createAndFetchSession({...kt});await _t(oe,oe.data.session?.id??null,{fromCreateSession:!0})}catch(oe){if(ti(oe)==="session_auto_completed"){await Ze({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw oe}}catch(q){await Ge(mo(hu(q,"Automatic payment failed. Please try again."),e))}finally{be.current&&(K(null),Fe(null),Ve(!1))}}},[Je.onClick,kt,fe,tt,t,_t,A,e,Ge,Ze]),qt=(0,Ct.useCallback)(v=>{let q=Pe.current;O(null),Be.current?.({result:v,session:null,sessionId:q?.sessionId??null,autoCompleted:!1})},[]),Ft=(0,Ct.useCallback)(v=>{M.current?.(v)},[]),de=(0,Ct.useCallback)(v=>{at.current?.(v)},[]),ue=(0,Ct.useMemo)(()=>(0,Sn.resolveTheme)(y),[y]),X=(0,Ct.useMemo)(()=>{let v=ue?.buttonsLayout??(0,Sn.resolveButtonsLayoutTheme)(ge);return w?{...v,...w,cardButton:{...v.cardButton,...w.cardButton}}:v},[ue,ge,w]),bt=(0,Ct.useMemo)(()=>{let v=ue?.appearance;return h?v?{...v,...h,variables:{...v.variables,...h.variables}}:h:v},[h,ue]),ft=bt?.variables,V=ft?.colorPrimary??"#4A49FF",rt=ft?.colorPrimaryHover??(0,Ss.darkenHex)(V,.12),Rt=ft?.borderRadius??"8px";return(0,bn.jsxs)(bn.Fragment,{children:[(0,bn.jsx)("button",{...Je,type:ke,onClick:Ut,disabled:fe||tt,"aria-busy":tt,style:{width:"100%",...he===void 0?{boxSizing:"border-box",height:gu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...X.cardButton,...bs({themeBundle:ue,resolvedPrimaryColor:V,resolvedBorderRadius:Rt,submitButtonStyle:X.submitButton,explicitPrimaryColor:ft?.colorPrimary}),fontSize:X.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:fe||tt?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:fe||tt?.6:1,...mt},onMouseEnter:v=>{Je.onMouseEnter?.(v),!v.defaultPrevented&&!fe&&!tt&&(ue||ft?.colorPrimary)&&(v.currentTarget.style.backgroundColor=rt)},onMouseLeave:v=>{Je.onMouseLeave?.(v),!v.defaultPrevented&&(ue||ft?.colorPrimary)&&(v.currentTarget.style.backgroundColor=V)},onMouseDown:v=>{Je.onMouseDown?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(0.985)")},onMouseUp:v=>{Je.onMouseUp?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(1)")},children:(0,bn.jsx)(jo,{content:he})}),J&&(0,bn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:J}),me&&(0,bn.jsx)(rn,{status:me,errorMessage:W,authorized:lt}),se&&(0,bn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:v=>{v.target===v.currentTarget&&O(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,bn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,bn.jsx)(Mi,{sessionId:se.sessionId,nonce:se.nonce,checkoutMode:"full",billingApiUrl:A,locale:F,theme:y,...bt?{appearance:bt}:{},buttonsTheme:ge,buttonsStyles:w,initialErrorMessage:se.errorMessage,initialPayPalOrderId:se.payPalOrderId,cardTitleContent:null,onComplete:qt,onError:Ft,onDecline:de})})})]})}var Fi=require("@flopay/js/card-setup"),Hr=require("@flopay/shared"),Kt=require("react");var Ms=require("@flopay/shared"),Cu=require("@flopay/shared");function Ai(e){let t=(0,Ms.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Gn=require("react/jsx-runtime"),Na=class extends Hr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function so(e,t={}){let r=e instanceof Hr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new Na(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:a,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}function bc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:c,buttonsStyles:p,loading:m=null,onReady:g,onComplete:_,onDecline:E,onCancel:I,onValidation:H,onError:T}){let[Y,F]=(0,Kt.useState)(null),[y,h]=(0,Kt.useState)(null),[ge,w]=(0,Kt.useState)(null),[Te,x]=(0,Kt.useState)(null),[ie,he]=(0,Kt.useState)(null),fe=(0,Kt.useRef)(!1),ke=(0,Kt.useRef)(!1),{vaultTheme:mt,surface:Je,overlayTheme:A}=(0,Kt.useMemo)(()=>Ai({theme:a,appearance:c,buttonsStyles:p}),[a,c,p]),kt=(0,Kt.useMemo)(()=>(0,Aa.mergeCardSetupSurface)(Je,s),[Je,s]),tt=(0,Kt.useRef)(g),Ve=(0,Kt.useRef)(T),me=(0,Kt.useRef)(_),K=(0,Kt.useRef)(E),W=(0,Kt.useRef)(I),Fe=(0,Kt.useRef)(H),lt=(0,Kt.useRef)(!1),He=(0,Kt.useRef)(!1),J=(0,Kt.useRef)(0);return tt.current=g,Ve.current=T,me.current=_,K.current=E,W.current=I,Fe.current=H,(0,Kt.useEffect)(()=>{let D=J.current+1;return J.current=D,()=>{queueMicrotask(()=>{J.current===D&&(lt.current||He.current||(He.current=!0,(0,Qe.invokeMerchantCallback)(()=>{W.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Kt.useEffect)(()=>{let D=!0,se=(0,Hr.resolveBillingApiUrl)(r),O=new Fi.PaymentAPI(se,{telemetry:n});return F(null),h(null),w(null),lt.current=!1,He.current=!1,(async()=>{try{if(!e.trim())throw new Hr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Hr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let be=await O.getUnifiedCheckoutSession(e,t);if(!D)return;let Me=be.data.session;if(!Me||!(0,Hr.isCardSetupCheckoutSession)(Me))throw new Hr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Pe=Me.vault;(0,Hr.isMountableVaultBlock)(Pe)||(Pe=await O.getVaultCapture(e,t));let Be=(0,Hr.resolveVaultMountOptions)(Pe,{billingApiUrl:se,sessionId:e,nonce:t});if(!Be)throw new Hr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!D)return;h(Be),F(new Fi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(be){if(!D)return;let Me=so(be);lt.current=!0,w(Me),(0,Qe.invokeMerchantCallback)(()=>Ve.current?.(Me))}})(),()=>{D=!1,O.destroy()}},[r,t,e,n]),(0,Kt.useEffect)(()=>{if(!Y)return;let D=!1;ke.current=!1,fe.current=!1;let se=Y.on("submitting",()=>{fe.current=!0,he(null),x("processing")}),O=Y.on("complete",Pe=>{lt.current=!0,fe.current=!1,x("success"),(async()=>(await new Promise(Be=>setTimeout(Be,600)),!ke.current&&(ke.current=!0,(0,Qe.invokeMerchantCallback)(()=>{me.current?.({status:"succeeded",sessionId:e,...Pe.paymentMethod?{paymentMethod:Pe.paymentMethod}:{}})}),D||x(null))))()}),be=Y.on("decline",Pe=>{lt.current=!0,fe.current=!1,he(Pe.message??null),x("error"),(0,Qe.invokeMerchantCallback)(()=>{K.current?.({status:"declined",sessionId:e,...Pe.declineReason?{reason:Pe.declineReason}:{},...Pe.message?{message:Pe.message}:{}})}),(async()=>(await new Promise(Be=>setTimeout(Be,400)),D||x(null)))()}),Me=Y.on("challenge_dismissed",()=>{x(null)});return()=>{D=!0,se(),O(),be(),Me()}},[Y,e]),ge?(0,Gn.jsx)("div",{role:"alert",children:ge.message}):!Y||!y?.html?(0,Gn.jsx)(Gn.Fragment,{children:m}):(0,Gn.jsxs)(Gn.Fragment,{children:[Te&&(0,Gn.jsx)(rn,{status:Te,errorMessage:ie,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...A?{theme:A}:{}}),(0,Gn.jsx)(fo,{capture:Y,html:y.html,messageToken:y.messageToken,expectedOrigin:y.expectedOrigin,verificationRequired:y.verificationRequired,theme:mt,containerStyle:kt,onReady:()=>{(0,Qe.invokeMerchantCallback)(()=>tt.current?.())},onValidation:D=>{(0,Qe.invokeMerchantCallback)(()=>Fe.current?.(D))},onError:D=>{if(!D)return;fe.current&&(fe.current=!1,he(D),x("error"),setTimeout(()=>x(null),400));let se=so(new Error(D),{code:"card_setup_widget_failed",retryable:!0});(0,Qe.invokeMerchantCallback)(()=>Ve.current?.(se))}})]})}var Sc=require("@flopay/js/card-setup"),wn=require("@flopay/shared"),wc=require("@paypal/paypal-js"),Io=require("react");var Rc=require("react/jsx-runtime");function kc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:c,customer:{userId:p,email:m},onSubmitting:g,onConfirmed:_,onFailed:E,onAbandoned:I}){let H=(0,Io.useRef)(null),T=(0,Io.useRef)({onSubmitting:g,onConfirmed:_,onFailed:E,onAbandoned:I});T.current={onSubmitting:g,onConfirmed:_,onFailed:E,onAbandoned:I};let[Y]=(0,Io.useState)(()=>(0,Wn.detectPayPalEnvironment)().inAppBrowser);return(0,Io.useEffect)(()=>{let F=!0,y,h=new Sc.PaymentAPI(s,{telemetry:c}),ge={userId:p,email:m};return(async()=>{try{let w=await(0,wc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Te=H.current;if(!F||!Te)return;if(!w?.Buttons)throw new wn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let x=w.Buttons({createVaultSetupToken:async()=>{T.current.onSubmitting();let ie=await h.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:wn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,wn.isSettledSessionIntent)(ie))throw(0,wn.settledSessionIntentError)(n);if(ie.provider!=="paypal"||ie.providerObjectType!=="setup_token")throw new wn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ie.providerObjectId},onApprove:async ie=>{let he=ie.vaultSetupToken;if(!he)throw new wn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let fe=await h.processPayment(ge.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:he,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:wn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:ge});if(!fe.ok)throw new wn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:fe.status});F&&T.current.onConfirmed()},onCancel:()=>{F&&T.current.onAbandoned()},onError:ie=>{if(!F)return;let{popupBlocked:he}=(0,we.classifyExternalMethodFailure)(ie,{inAppBrowser:Y,handoffObserved:!1});T.current.onFailed(he?new Error((0,we.buildExternalMethodRecoveryMessage)("PayPal",!0,Y)):ie,{code:he?"popup_blocked":"paypal_setup_failed",retryable:!0})}});y=()=>x.close(),await x.render(Te)}catch(w){if(!F)return;T.current.onFailed(w,{code:"paypal_unavailable",retryable:!0})}})(),()=>{F=!1,y?.().catch(()=>{}),h.destroy()}},[s,e,r,m,t,Y,a,n,c,p]),(0,Rc.jsx)("div",{ref:H,"data-flopay-paypal-setup":""})}var _c=require("@flopay/js/card-setup"),kn=require("@flopay/shared"),Yn=require("@stripe/react-stripe-js"),Ic=require("@stripe/stripe-js"),Kr=require("react");var qr=require("react/jsx-runtime"),Tc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},xs=new Map;function bu(e){let t=xs.get(e);if(t)return t;let r=(0,Ic.loadStripe)(e).catch(n=>{throw xs.delete(e),n});return xs.set(e,r),r}function Su(e){return e?(0,kn.toStripeAppearance)(e):void 0}function wu(e){return(0,we.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Ec(e){return e==="paypal"?"PayPal":(0,kn.getStripeMethodDisplayName)(e)}function ku(){return typeof window>"u"?"":window.location.href}var Ru={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function Mc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:c}=e,[p]=(0,Kr.useState)(()=>bu(t)),m=(0,Kr.useMemo)(()=>{let g=Su(c),_=(0,kn.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:Tc[r]?.types??[r],..._?{setupFutureUsage:_}:{},...g?{appearance:g}:{}}},[c,n,a,s,r]);return(0,qr.jsx)(Yn.Elements,{stripe:p,options:m,children:(0,qr.jsx)(Eu,{...e})})}function Eu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:c,themeId:p,buttonsLayout:m,onSubmitting:g,onConfirmed:_,onDeclined:E,onFailed:I,onValidation:H,onUnavailable:T}){let Y=(0,Yn.useStripe)(),F=(0,Yn.useElements)(),[y,h]=(0,Kr.useState)(!1),[ge,w]=(0,Kr.useState)("loading"),[Te,x]=(0,Kr.useState)(!1),[ie,he]=(0,Kr.useState)(!1),fe=(0,Kr.useRef)(!1),[ke]=(0,Kr.useState)(()=>(0,Wn.detectPayPalEnvironment)()),[mt,Je]=(0,Kr.useState)(!1),A=(0,Kr.useCallback)((W,Fe)=>{if((0,we.classifyExternalMethodFailure)(W,{inAppBrowser:ke.inAppBrowser,handoffObserved:!1}).popupBlocked){Je(!0),I(new Error((0,we.buildExternalMethodRecoveryMessage)(Ec(e),!0,ke.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}I(Fe.message===void 0?W:new Error(Fe.message),{code:Fe.code,retryable:!0})},[ke.inAppBrowser,e,I]),kt=(0,Kr.useCallback)(async W=>{let Fe=!1,lt=!1,He=()=>{!W||Fe||lt||(lt=!0,W.paymentFailed({reason:"fail"}))};if(!Y||!F||fe.current){He();return}fe.current=!0,h(!0);try{let J=await F.submit();if(J.error){He(),H(J.error.message??null);return}g();let D=await new _c.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,kn.isSettledSessionIntent)(D))throw(0,kn.settledSessionIntentError)(r);if(D.provider!=="stripe"||D.intentKind!=="setup")throw new kn.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Fe=!0;let se=await Y.confirmSetup({elements:F,clientSecret:D.clientSecret,confirmParams:{return_url:ku()},redirect:"if_required"});if(se.error){wu(se.error)?E({...se.error.decline_code||se.error.code?{reason:se.error.decline_code??se.error.code}:{},...se.error.message?{message:se.error.message}:{}}):A(se.error,{code:"payment_method_setup_provider_failed",message:se.error.message??"The payment method could not be saved."});return}_()}catch(J){He(),A(J,{code:"payment_method_setup_failed"})}finally{fe.current=!1,h(!1)}},[a,t,F,e,n,_,E,g,H,A,r,Y,s]),tt=Tc[e]?.wallet,Ve=tt==="paypal"&&(0,$n.resolveStripePayPalPresentation)(ke,"auto",mt?"blocked":ke.popupCapability)==="redirect",me=c?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&tt&&!Ve)return(0,qr.jsxs)(qr.Fragment,{children:[(0,qr.jsx)(ra,{}),(0,qr.jsx)(xa,{state:ge,borderRadius:me,children:(0,qr.jsx)(Yn.ExpressCheckoutElement,{options:{...hi,paymentMethods:gi([e])},onReady:W=>{let Fe=Ma(W,[tt]);w(Fe),Fe==="unavailable"&&T()},onLoadError:()=>{w("load_error"),T()},onConfirm:W=>{kt(W)}})})]});let K=Ec(e);return(0,qr.jsxs)(qr.Fragment,{children:[Te?(0,qr.jsx)(fi,{method:e,themeId:p,hasNextStep:!0,highlighted:ie,disabled:y,onClick:()=>he(W=>!W),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:me}):null,(0,qr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ie,style:ie?{display:"flex",flexDirection:"column"}:Ru,children:[(0,qr.jsx)(Yn.PaymentElement,{options:{layout:Pi},onReady:()=>x(!0),onLoadError:()=>T(),onChange:W=>{W.complete&&H(null)}}),(0,qr.jsx)(vi,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!Y||!F||y||!ie,onClick:()=>{kt()},color:c?.variables?.colorPrimary??"#4A49FF",borderRadius:c?.variables?.borderRadius??"8px",style:m?.submitButton,children:y?"Saving\u2026":`Save ${K}`})]})]})}var Ua=require("@flopay/js/card-setup"),wr=require("@flopay/shared"),et=Qi(require("react"),1);var oa=require("@flopay/js/card-setup"),Tr=require("@flopay/shared");var cr=require("react/jsx-runtime"),_u=15,Iu=2e3;function Tu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function As(e){return new Promise(t=>setTimeout(t,e))}async function Mu(e,t,r){if(!t.trim())throw new wr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new wr.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,wr.isCardSetupCheckoutSession)(a))throw new wr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Tr.readSetupAdvertisement)(n);if(!(0,Tr.advertisesAnyMethod)(s)){let{skippedForMissingCurrency:c}=s,p=c.length>0?`FloPay: this setup session advertises only Stripe methods (${c.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new wr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function xu(e,t,r,n,a){let s=t.vault??null;(0,wr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let c=(0,wr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!c)throw new wr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return c}var Bi=class extends et.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function xc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:c="modern-light",containerStyle:p,appearance:m,buttonsStyles:g,loading:_=null,onReady:E,onComplete:I,onDecline:H,onCancel:T,onValidation:Y,onError:F}){let[y]=(0,et.useState)(oa.readSetupRedirectReturn),[h,ge]=(0,et.useState)(null),[w,Te]=(0,et.useState)(!1),[x,ie]=(0,et.useState)(null),[he,fe]=(0,et.useState)(null),[ke,mt]=(0,et.useState)(null),[Je,A]=(0,et.useState)(null),[kt,tt]=(0,et.useState)(()=>new Set),Ve=(0,et.useRef)(kt),me=(0,et.useRef)(null);me.current=h;let K=(0,et.useRef)(!1),W=(0,et.useRef)(!1),Fe=(0,et.useRef)(!1),lt=(0,et.useRef)(!1),He=(0,et.useRef)(0),J=(0,et.useRef)(0),D=(0,et.useRef)(!1),{vaultTheme:se,surface:O,overlayTheme:be,appearance:Me,buttonsLayout:Pe}=(0,et.useMemo)(()=>Ai({theme:c,appearance:m,buttonsStyles:g}),[c,m,g]),Be=(0,et.useMemo)(()=>(0,Aa.mergeCardSetupSurface)(O,p),[O,p]),M=(0,et.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:E,onComplete:I,onDecline:H,onCancel:T,onValidation:Y,onError:F});M.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:E,onComplete:I,onDecline:H,onCancel:T,onValidation:Y,onError:F},(0,et.useEffect)(()=>{D.current=!0;let u=He.current+1;return He.current=u,()=>{D.current=!1,J.current+=1,queueMicrotask(()=>{He.current===u&&(Fe.current||lt.current||(lt.current=!0,(0,Qe.invokeMerchantCallback)(()=>{M.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let at=(0,et.useCallback)((u,C)=>{Fe.current=!0,K.current=!1,A({status:"success",wording:u,message:null}),(async()=>(await As(600),!W.current&&(W.current=!0,(0,Qe.invokeMerchantCallback)(()=>{M.current.onComplete?.({status:"succeeded",sessionId:M.current.sessionId,...C?{paymentMethod:C}:{}})}),D.current&&A(null))))()},[]),Ke=(0,et.useCallback)((u,C)=>{Fe.current=!0,K.current=!1,A({status:"error",wording:u,message:C.message??null}),(0,Qe.invokeMerchantCallback)(()=>{M.current.onDecline?.({status:"declined",sessionId:M.current.sessionId,...C.reason?{reason:C.reason}:{},...C.message?{message:C.message}:{}})}),(async()=>(await As(400),D.current&&A(null)))()},[]),yt=(0,et.useCallback)((u,C)=>{K.current?(K.current=!1,A({status:"error",wording:u,message:C.message}),setTimeout(()=>{D.current&&A(null)},400)):A(null),(0,Qe.invokeMerchantCallback)(()=>M.current.onError?.(C))},[]),Ze=(0,et.useCallback)(async u=>{let C=J.current+1;J.current=C;let Q=()=>!D.current||C!==J.current;K.current=!0,A({status:"processing",wording:"payment_method",message:null});let le=new Ua.PaymentAPI((0,wr.resolveBillingApiUrl)(M.current.billingApiUrl),{telemetry:M.current.telemetry});try{for(let L=0;L<_u;L+=1){if((L>0||u.waitFirst)&&await As(Iu),Q())return;let k=await le.getUnifiedCheckoutSession(M.current.sessionId,M.current.nonce);if(Q())return;let jt=k.data.session?.status;if(jt==="complete"){Te(!0),at("payment_method");return}if(jt==="expired")throw new wr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new wr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(L){if(Q())return;let k=L instanceof wr.FloPayError&&L.code==="payment_method_setup_unverified";yt("payment_method",so(L,k?{retryable:!0}:{}))}finally{le.destroy()}},[yt,at]);(0,et.useEffect)(()=>{let u=!0,C=(0,wr.resolveBillingApiUrl)(a),Q=new Ua.PaymentAPI(C,{telemetry:s});ge(null),Te(!1),ie(null),fe(null),mt(null);let le=new Set;return Ve.current=le,tt(le),Fe.current=!1,lt.current=!1,W.current=!1,(async()=>{try{let{session:L,advertisement:k}=await Mu(Q,r,n);if(!u)return;let jt={advertisement:k,customer:Tu(L),...L.futureUse?{futureUse:L.futureUse}:{},...L.futureUseUnsupported?{futureUseUnsupported:L.futureUseUnsupported}:{}};if(y){if((0,oa.clearSetupRedirectParams)(),L.status==="complete"){Te(!0),ge(jt),at("payment_method");return}y.failed?Ke("payment_method",{reason:"redirect_failed"}):Ze({waitFirst:!0})}let Mr=k.card?await xu(Q,L,r,n,C):null;if(!u)return;ge(jt),Mr&&(fe(Mr),ie(new Ua.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(L){if(!u)return;let k=so(L);Fe.current=!0,mt(k),(0,Qe.invokeMerchantCallback)(()=>M.current.onError?.(k))}})(),()=>{u=!1,Q.destroy()}},[a,n,y,Ke,at,r,s,Ze]),(0,et.useEffect)(()=>{if(!x)return;K.current=!1;let u=x.on("submitting",()=>{K.current=!0,A({status:"processing",wording:"card",message:null})}),C=x.on("complete",L=>{at("card",L.paymentMethod)}),Q=x.on("decline",L=>{Ke("card",{...L.declineReason?{reason:L.declineReason}:{},...L.message?{message:L.message}:{}})}),le=x.on("challenge_dismissed",()=>{A(null)});return()=>{u(),C(),Q(),le()}},[x,Ke,at]);let Ge=(0,et.useCallback)((u,C,Q)=>{if(Q.retryable){yt("payment_method",so(C,Q));return}if(Ve.current.has(u))return;let le=new Set(Ve.current);le.add(u),Ve.current=le,tt(le);let L=me.current?.advertisement,k=L?(0,Tr.advertisedMethodKeys)(L).some(jt=>!le.has(jt)):!1;yt("payment_method",so(C,{code:Q.code,retryable:k}))},[yt]),_t=(0,et.useMemo)(()=>({onSubmitting:()=>{K.current=!0,A({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Ze({waitFirst:!1})},onDeclined:u=>Ke("payment_method",u),onValidation:u=>{(0,Qe.invokeMerchantCallback)(()=>M.current.onValidation?.(u))},onAbandoned:()=>{K.current=!1,A(null)}}),[Ke,Ze]),Ut=(0,et.useRef)(Ge);Ut.current=Ge;let qt=(0,et.useRef)(new Map),Ft=u=>{let C=qt.current.get(u);if(C)return C;let Q=(le,L)=>Ut.current(u,le,L);return qt.current.set(u,Q),Q},de=(0,et.useCallback)(u=>{if(Ve.current.has(u))return;let C=new Set(Ve.current);C.add(u),Ve.current=C,tt(C);let Q=me.current?.advertisement;Q&&(0,Tr.advertisedMethodKeys)(Q).some(L=>!C.has(L))||yt("payment_method",so(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[yt]),ue=(0,et.useRef)(de);ue.current=de;let X=(0,et.useRef)(new Map),bt=u=>{let C=X.current.get(u);if(C)return C;let Q=()=>ue.current(u);return X.current.set(u,Q),Q},ft=Je?(0,cr.jsx)(rn,{status:Je.status,errorMessage:Je.message,...(0,Tr.setupOverlayLabels)(Je.wording),successNote:null,...be?{theme:be}:{}}):null;if(ke)return(0,cr.jsx)("div",{role:"alert",children:ke.message});if(!h||w)return(0,cr.jsxs)(cr.Fragment,{children:[ft,h?null:_]});let{advertisement:V,customer:rt,futureUse:Rt,futureUseUnsupported:Re}=h,v=(0,wr.resolveBillingApiUrl)(a),q=s===void 0?{}:{telemetry:s},oe=V.stripe.filter(({method:u})=>!kt.has(u)),xe=kt.has("paypal")?null:V.paypal,Lt=!!(V.card&&x&&he?.html),it=({method:u,publishableKey:C,currency:Q})=>(0,cr.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,cr.jsx)(Bi,{onFailed:Ft(u),children:(0,cr.jsx)(et.Suspense,{fallback:null,children:(0,cr.jsx)(e,{method:u,category:(0,Tr.stripeMethodCategory)(u),publishableKey:C,currency:Q,...Rt?{futureUse:Rt}:{},...Re?{futureUseUnsupported:Re}:{},sessionId:r,nonce:n,billingApiUrl:v,...q,...Me?{appearance:Me}:{},...Pe?{buttonsLayout:Pe}:{},...typeof c=="string"?{themeId:c}:{},..._t,onFailed:Ft(u),onUnavailable:bt(u)})})})},u),De=oe.filter(({method:u})=>(0,Tr.stripeMethodCategory)(u)==="wallet"),Oe=oe.filter(({method:u})=>(0,Tr.stripeMethodCategory)(u)!=="wallet"),Tt=oe.length>0||xe!==null;return(0,cr.jsxs)(cr.Fragment,{children:[ft,Tt?(0,cr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[De.map(it),xe?(0,cr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,cr.jsx)(Bi,{onFailed:Ft("paypal"),children:(0,cr.jsx)(et.Suspense,{fallback:null,children:(0,cr.jsx)(t,{clientId:xe.clientId,...xe.environment?{environment:xe.environment}:{},...V.currency?{currency:V.currency}:{},sessionId:r,nonce:n,billingApiUrl:v,customer:rt,...q,..._t,onFailed:Ft("paypal"),onUnavailable:bt("paypal")})})})}):null,Oe.map(it)]}):null,Lt&&Tt?(0,cr.jsx)(Ci,{label:"or add a card"}):null,Lt&&x&&he?.html?(0,cr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,cr.jsx)(fo,{capture:x,html:he.html,messageToken:he.messageToken,expectedOrigin:he.expectedOrigin,verificationRequired:he.verificationRequired,theme:se,containerStyle:Be,onReady:()=>{(0,Qe.invokeMerchantCallback)(()=>M.current.onReady?.())},onValidation:u=>{(0,Qe.invokeMerchantCallback)(()=>M.current.onValidation?.(u))},onError:u=>{u&&yt("card",so(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Fc=require("react/jsx-runtime"),Au={StripeSetupMethod:Mc,PayPalSetupMethod:kc};function Ac(e){return(0,Fc.jsx)(xc,{...e,branches:Au})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});