@flopay/react 1.14.15 → 1.15.0

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