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