@flopay/react 1.16.1 → 1.16.2

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 _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?`
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"),fn=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"),ge=require("@flopay/shared"),w=hs(require("react"),1);var Ss=require("react"),wn=(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"),Rn=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 Ee=require("@flopay/shared");var tc=require("@flopay/shared"),_a=require("react");function yo(){return(0,_a.useContext)(wn).flopay}function yi(){return(0,_a.useContext)(wn).paypalFlopay??null}function rc(){return(0,_a.useContext)(Un)}function nc(){return(0,_a.useContext)(wn).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 We=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,_e=f??U?.generation??r.current;(f===void 0||U?.generation===f)&&(v(U),a.current=null),n.current=_e},[v]),V=(0,vr.useCallback)(f=>n.current===(f??r.current),[]),E=(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"})}},Ee.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:E,generationRef:r}}var kn=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,Ee.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:E,onDecline:N,onCancel:x,onTechnicalFailure:f,isProcessing:U=!1,onLoadStateChange:_e,onInitializationStateChange:m,allowAutomaticRetry:he=!0,onButtonClick:I,runBeforeButtonClick:re,session:Pe,existingOrderId:fe,telemetry:ve,telemetryContext:bt,onInstrument:$e,debug:L=!1}){let mt=yo(),xe=sa($e,e),Ge=(0,R.useMemo)(()=>{if(mt)return null;let D=Pi({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:ze.SDK_VERSION,enabled:ve!==!1});return D.setCheckoutContext(bt??{}),D.beginCheckout(bt??{}),D},[r,mt,ve,bt?.checkoutMode,bt?.layout]),Ce=(0,R.useMemo)(()=>Er(mt),[mt]);(0,R.useEffect)(()=>()=>{Ge&&Ge.flush().catch(()=>{}).finally(()=>Ge.destroy())},[Ge]);let q=(0,R.useMemo)(()=>({error:D=>{Ce?Ce.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=>{Ce?Ce.log(D):Ge?.log(D),xe({class:"lifecycle",name:D.name,provider:D.provider})},performance:D=>{Ce?Ce.performance(D):Ge?.performance(D)},terminal:D=>{Ce?Ce.terminal(D):Ge?.terminal(D)},startTiming:()=>Ce?.now()??Ge?.now()??0,elapsed:D=>Ce?.elapsed(D)??Math.max(0,(Ge?.now()??D)-D)}),[xe,Ce,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),[be,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,Pe)});Jt.current.sessionId!==e&&(Jt.current={sessionId:e,required:(0,ze.paypalProviderIdentityRequired)(n,Pe)});let K=Jt.current.required,je=(0,R.useMemo)(()=>r.replace(/\/+$/,""),[r]),S=Pe?.gateways?.paypal?.providerObjectType??P,ye=S??(v?"subscription":"order"),[Se]=(0,R.useState)(Zn.detectPayPalEnvironment),ft=Pe?.gateways?.paypal?.approvalPresentation??g,Vt=(0,Qn.resolvePayPalPresentationMode)(Se,ft==="app_switch"?"app_switch":void 0,ye),et=(0,ze.usesPayPalVaultedChannel)(S),we=(0,R.useMemo)(()=>JSON.stringify([je,d,y,p??"",ye,et,Vt,e,fe??""]),[je,d,y,p,fe,ye,et,Vt,e]),ut=(0,R.useRef)(we),u=ut.current!==we,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)(E),br=(0,R.useRef)(N),_t=(0,R.useRef)(x),Hr=(0,R.useRef)(f),Dr=(0,R.useRef)(I),Nr=(0,R.useRef)(_e),Kr=(0,R.useRef)(m),Ht=(0,R.useRef)(s),Ir=(0,R.useRef)(re),Mn=(0,R.useRef)(Pe),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),gt=(0,R.useRef)(!1),Bt=(0,R.useRef)(e);Bt.current=e;let[on]=(0,R.useState)(hi);(0,R.useEffect)(()=>(gt.current=!0,()=>{gt.current=!1}),[]),(0,R.useEffect)(()=>{At.current=k},[k]),(0,R.useEffect)(()=>{Ht.current=s},[s]),(0,R.useEffect)(()=>{vt.current=V},[V]),(0,R.useEffect)(()=>{Zt.current=E},[E]),(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=_e},[_e]),(0,R.useEffect)(()=>{Kr.current=m},[m]),(0,R.useEffect)(()=>{Ir.current=re},[re]),(0,R.useEffect)(()=>{Mn.current=Pe},[Pe]),(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,Ee.isPopupBlockedError)(D);ie&&H.markBlocked();let ce=(0,Ee.buildExternalMethodRecoveryMessage)("PayPal",ie,Se.inAppBrowser),de=Hr.current;if(de){let $t=ie&&Se.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,Se.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)(()=>{ut.current!==we&&(ut.current=we,qt.current=!1,jt.current=!1,Me(!1),ot(!1),Fe(!1),Kr.current?.("loading"))},[we]),(0,R.useEffect)(()=>{(0,We.invokeMerchantCallback)(()=>Nr.current?.(ne&&!kt))},[ne,kt]);let tr=(0,ze.normalizeGatewayEnvironment)(p);(0,R.useEffect)(()=>{let D={attempt:sn.current+1,inAppBrowser:Se.inAppBrowser,appFamily:Se.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=gt.current,_=h?T:"torn_down";h&&B(`onError ignored reason=${_}`),on.take(Bt.current)&&ie.log({name:gi,stage:"provider_ready",reason:_,provider:"paypal",paymentMethodCategory:"paypal"})},$n=()=>Bt.current===e?"stale_attempt":"session_changed",cn=et?ye: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,Cn=null,Po=!1,An=()=>{!Cn||Po||(Po=!0,Cn.close().catch(()=>{}))},un=!1,oo=!1,bn=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),_=h.pathname.toLowerCase();return _.includes("checkcaptcha")||_.includes("captcha")?`CAPTCHA(${h.host}${_})`:_.includes("risk")||_.includes("challenge")?`RISK(${h.host}${_})`:_.includes("smart/buttons")?`smart-buttons(${h.host})`:`${h.host}${_}`.slice(0,100)}catch{return T.slice(0,80)}},Jr=T=>{let h=T.getAttribute("src"),_=T.getAttribute("srcdoc"),le=T.getAttribute("name"),me=T.getAttribute("sandbox"),Be=[];return h&&Be.push(`src=${Gn(h)}`),_&&Be.push(`srcdoc[${_.length}ch]`),!h&&!_&&Be.push("src=(empty) srcdoc=(empty)"),le&&Be.push(`name=${le.slice(0,40)}`),me!==null&&Be.push(`sandbox="${me.slice(0,40)}"`),Be.join(" ")},Dn=T=>{if(!(T instanceof HTMLIFrameElement))return"";try{let h=T.contentDocument;if(!h)return"cd=null";let _=h.body?.children.length??0,le=h.body?.innerHTML.length??0,me=h.head?.innerHTML.length??0;return`cd=same-origin readyState=${h.readyState} body[${_}children,${le}ch] head[${me}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},gn=()=>{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 _=Math.round(h.duration);B(`net ${_}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?gn():so()}};G.current=se,M.current&&gn();let oe=ze.isPayPalTeardownMessage,st=T=>{if(it()||oe(T))return;let h=(0,Fo.applyFriendlyMessageOverride)(T)??T;(0,We.invokeMerchantCallback)(()=>Zt.current?.(h))},Yt=(T,h)=>{if($t||Xr)return;Xr=!0,ir=!0,O(),An();let _=Yd({kind:T,generationActive:!0,automaticRetryAllowed:he,automaticRetryUsed:qt.current});if(_.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),_.action!=="ignore"){if(Kr.current?.("exhausted"),_.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",h);return}if(_.report){let le=(0,Ee.classifyExternalMethodFailure)({code:ic(T,h),message:h},{inAppBrowser:Se.inAppBrowser,handoffObserved:!1});le.popupBlocked&&H.markBlocked(),ie.error({errorCode:le.popupBlocked?le.errorCode:_.report.errorCode,stage:_.report.stage,operationOutcome:_.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 He=async(T,h=mr.current)=>{if(it())return;let _=h?.sessionId??e;if(At.current){await At.current(T,{sessionId:_,accountPatch:h?.accountPatch,nonce:h?.nonce});return}let le=ie.startTiming();ie.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let me=()=>{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:_,nonce:h?.nonce??Qt.current,accountPatch:h?.accountPatch,session:Mn.current,email:It.current}),ct=await new vi.PaymentAPI(je,{telemetry:!1}).processPayment(Be.userId,Be.params);if(ct.ok){if(ir||$t&&gt.current)return;me(),ie.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,We.invokeMerchantCallback)(()=>vt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(it())return;let sr=await ct.json().catch(()=>null),gr=(0,ze.describePayPalProcessFailure)(sr),Zr=gr.message;me(),ct.status===400&&(typeof sr?.declineCode=="string"||!Array.isArray(sr?.fields))?ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ct.status===400||ct.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(ct.status),failureCategory:ct.status>=500?"server_error":void 0}),st(Zr),(0,We.invokeMerchantCallback)(()=>br.current?.(kr("paypal",Zr,{code:gr.code,declineCode:gr.declineCode})));return}catch(Be){if(it())return;me(),ie.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Kt=(0,ze.friendlyPayPalFailureMessage)(Be instanceof Error?Be.message:void 0);st(Kt),(0,We.invokeMerchantCallback)(()=>br.current?.(kr("paypal",Kt)));return}},nt=()=>new ze.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ee=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,We.invokeMerchantCallback)(()=>vt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let h=await T.json().catch(()=>null),_=(0,ze.describePayPalProcessFailure)(h);ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,We.invokeMerchantCallback)(()=>br.current?.(kr("paypal",_.message,{code:_.code,declineCode:_.declineCode})))},Ie=()=>{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,_=h?.sessionId??e,le=h?.nonce??Qt.current;ie.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let me;try{me=await new vi.PaymentAPI(je,{telemetry:!1}).createSessionIntent(_,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)(me))throw await Xe(me.response),Ie(),new ze.FloPayError("PayPal checkout already settled.","api_error",{code:ac});if(me.provider!=="paypal"||me.providerObjectType!==ye)throw new Error(T);return ie.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),me.providerObjectId},te=(T,h)=>{let _=h?.nonce??Qt.current;if(!_)return;let le=h?.sessionId??e,me=(0,ze.resolvePayPalDeclineReason)(T);new vi.PaymentAPI(je,{telemetry:!1}).reportSessionIntentDecline(le,_,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:me}).catch(()=>{})},Re=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={};ye==="subscription"?h={intent:"subscription",vault:!0}:ye==="order"&&(h={intent:"capture"}),Ae=(0,sc.loadScript)({clientId:d,currency:y,...h,...T?{environment:T}:{},...T==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let _=!1;Ae.then(le=>{if(_=!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 me=async(Et,xt)=>{if(it()||Ye.current!==Re)return;let Je=Et.vaultSetupToken??Et.subscriptionID??Et.orderID??"",pt=Je?nn.current.get(Je):er.current.get(Re);if(!(!pt||!jr(pt.generation))&&Rr(pt.generation)){nn.current.delete(Je),er.current.delete(pt.surfaceKey),zr("approved");try{if(Ne(!0),(0,We.invokeMerchantCallback)(()=>Zt.current?.(null)),!Je)throw new ze.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let yt=(0,ze.resolvePayPalApprovalIdentity)({accountPatch:pt.accountPatch,email:It.current,billingName:Wn.current,session:Mn.current});if((0,ze.needsPayPalPayerDetails)(yt))try{yt=(0,ze.mergePayPalPayerIdentity)(yt,await xt?.order?.get?.())}catch{}if((Ht.current||K)&&!(0,ze.isValidEmail)(yt.email)){let zt=await X("PayPal",yt);if(!zt)return;yt=zt}(0,ze.isValidEmail)(yt.email)&&(pt.accountPatch=(0,Rn.compactBuyerIdentity)({...pt.accountPatch,...yt}),await Ht.current?.(yt));let ke=(0,ze.buildPayPalTokenizedBody)(Je,cn);await He(ke,pt)}catch(yt){st(yt instanceof Error?yt.message:"PayPal capture failed.")}finally{it()||Ne(!1)}}},Be=Et=>{let xt=fe?()=>ee(fe):()=>lt(Et);return async()=>Mr(await xt())},Kt=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,pt={};if(Je)try{let zt=await Je("paypal");if(it()){await xt.reject();return}if(!zt.proceed){mr.current=null,er.current.delete(Re),await xt.reject();return}pt={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(Re),await xt.reject();return}(0,We.invokeMerchantCallback)(()=>Dr.current?.("paypal"));let yt=Ve(),ke={generation:yt,surfaceKey:Re,...pt};mr.current=ke,er.current.set(Re,ke),Le.current={...D,attempt:yt},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:ye==="order"?Be("Failed to create PayPal order."):void 0,createSubscription:ye==="subscription"?Be("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ye==="setup_token"?async()=>Mr(await lt("Failed to create PayPal setup token.")):void 0,onApprove:me,onCancel:()=>{if(it())return;let Et=er.current.get(Re)??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,We.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!==Re){oe(xt)||Yr($n());return}if(un){let Je=er.current.get(Re)??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:pt,popupBlocked:yt,providerDeclined:ke,terminalReason:zt}=(0,Ee.classifyExternalMethodFailure)(Et,{inAppBrowser:Se.inAppBrowser,handoffObserved:Q.current===Je.generation});if(yt&&H.markBlocked(),zr(zt),ke){ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:zt}),te(Et,Je),(0,We.invokeMerchantCallback)(()=>br.current?.(kr("paypal",xt))),er.current.delete(Je.surfaceKey),mr.current=null,Rr(Je.generation);return}ie.error({errorCode:pt,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:yt,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)}}),ct=Kt.isEligible();if(B(`isEligible=${ct}`),ie.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ct){Me(!1),Yt("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}oo=!0,Cn=Kt,Kn=()=>{if(!Bn||vo||it()||un)return;vo=!0,B(`container:dims ${Ot(bn)} 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(pt=>{if(!(pt instanceof Element))return;let yt=pt.tagName.toLowerCase(),ke=(pt.getAttribute("title")??"").slice(0,40),zt=yt==="iframe"?` ${Jr(pt)}`:"";B(`child+ ${yt}${ke?` title="${ke}"`:""}${zt} dims=${Ot(pt)}`)});else if(Je.type==="attributes"&&Je.target instanceof Element){let pt=Je.target;if(pt.tagName.toLowerCase()!=="iframe")continue;let yt=Je.attributeName;(yt==="src"||yt==="srcdoc")&&B(`attr~ iframe ${yt}=${yt==="srcdoc"?`[${(pt.getAttribute("srcdoc")??"").length}ch]`:Gn(pt.getAttribute("src"))} dims=${Ot(pt)}`)}}}),ao.observe(bn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Et=xt=>{if(it()||un)return;let Je=bn.querySelectorAll("iframe"),pt=typeof document<"u"&&"hasStorageAccess"in document;B(`watchdog:${xt} container=${Ot(bn)} children=${bn.childElementCount} iframes=${Je.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${pt} paypalNetRequests=${nr.value}`),Je.forEach((yt,ke)=>{let zt=(yt.getAttribute("title")??"").slice(0,40);B(` iframe[${ke}] ${Ot(yt)}${zt?` title="${zt}"`:""} ${Jr(yt)}`);let Ya=Dn(yt);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=Kt.render(bn);(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 me=le instanceof Error?le.message:"PayPal operation failed.";B(`provider:failed msg=${me.slice(0,120)}`);let Be="script_rejected";_&&oe(me)?Be="teardown":_&&oo&&(Be="render_rejected"),Yt(Be,me)})},0);return()=>{$t=!0,clearTimeout(Lt),Gt&&clearTimeout(Gt),O(),G.current===se&&(G.current=null),An(),Oe.current=null,Le.current=null}},[he,je,d,y,p,ye,Vt,et,e,fe,F,q,X,K,B,zr]);let ln=L?(0,kn.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
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:`
4
+ `)}`]}):null;return kt&&!u?L?(0,kn.jsx)("div",{children:ln}):null:(0,kn.jsxs)("div",{children:[ln,Qe&&(0,kn.jsx)(aa,{identity:Qe.identity,methodLabel:Qe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Mt,onCancel:()=>Mt(null)}),(0,kn.jsxs)("div",{"aria-hidden":be||Qe?!0:void 0,style:be||Qe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ci},children:[!ne&&!be&&(0,kn.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,kn.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,kn.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,kn.jsx)(lc,{...e})}function cc(e){return(0,kn.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 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=`
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 E=Er(s);return v.current=E?.beginCheckout()??E?.now()??0,E?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{E?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Lr.useEffect)(()=>{let E=!1;return e instanceof Promise?e.then(N=>{E||d(N)},()=>{E||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{E=!0}},[g,e]),(0,Lr.useEffect)(()=>{let E=!1;if(!t){y(null);return}return t instanceof Promise?t.then(N=>{E||y(N)},()=>{E||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{E=!0}},[g,t]),(0,Lr.useEffect)(()=>{if(!s||P.current===s)return;P.current=s;let E=Er(s);E?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),E?.performance({stage:"checkout_render",durationMs:E.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)(wn.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"),dt=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 dt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function eu(){return new dt.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 dt.FloPayError?e:new dt.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 dt.FloPayError&&P.code==="three_ds_aborted"?P:ca(P);if(!(P instanceof dt.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 dt.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 dt.FloPayError(s,"api_error",{code:e?.code??(0,dt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,dt.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??"",E=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:E,zip:N},returnUrl:s??Rs(r)});if(f.ok){let m=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,dt.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 he=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...he?{paymentIntentId:he}:{},paymentMethodId:Ea(a),checkoutMethod:pc(a,r)}}}let U;try{U=await f.json()}catch(m){throw new dt.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 dt.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 dt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let _e=new dt.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(_e,{telemetryOutcome:(0,dt.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 dt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw ks(new dt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=(0,dt.isSetupIntentClientSecret)(e.threeDSecureToken),k=null,V=e.paymentMethodId,E=await Fa(()=>Zd(P,e.threeDSecureToken,g),"card");if(E){if(E.error)throw mo(new dt.FloPayError(E.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:E.error.code}),"card");let x=E.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 dt.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 dt.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 dt.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 dt.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 dt.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 dt.FloPayError(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new dt.FloPayError("Unsupported payment redirect state.","api_error")}function Oa(e){if(e instanceof dt.FloPayError){let n=(0,Fo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new dt.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 dt.FloPayError(r,"api_error")}function Es(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,dt.isMountableVaultBlock)(e.data.session?.vault)||(0,Nn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new dt.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 dt.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 @@ ${W.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
- `,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:`
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],[E,N]=(0,Pc.useState)(!1),x=!!V&&!E,f=k?.backgroundColor??p??"#ffffff",U=k?.borderColor??y??"#d1d5db",_e=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:_e,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:_e,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=E=>{v||(v=!0,p(E))},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(E=>{if(!E){g();return}v||bc(E.warnings),P({order:E.order,moreOptions:E.moreOptions})}).catch(g).finally(()=>clearTimeout(V)),()=>{v=!0,clearTimeout(V),k.abort()}},[s,t,r,n,a]),s===void 0?lu:d}var vn=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,vn.useRef)(null),k=(0,vn.useRef)(y),V=(0,vn.useRef)(v),E=(0,vn.useRef)(P);k.current=y,V.current=v,E.current=P;let N=(0,vn.useRef)(s);N.current=s;let x=(0,vn.useRef)(null),f=d??void 0,U=(0,vn.useRef)(f);U.current=f;let _e=(0,vn.useRef)(void 0);return(0,vn.useEffect)(()=>{let m=g.current;if(!m)return;let he=!0,I=!1,re=()=>{!he||I||(I=!0,k.current?.())},Pe=e.on("ready",()=>{re()}),fe=e.on("error",L=>{V.current?.(L.message??"There was a problem loading the secure card form.")}),ve=e.on("validation",L=>{E.current?.(L.message??null)}),bt=U.current??(As.has(e)?null:void 0),$e={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,_e.current=U.current,U.current!==void 0&&As.add(e),e.mount(m,$e).then(()=>{re()}).catch(L=>{he&&V.current?.(L instanceof Error?L.message:"Failed to load the secure card form.")}),()=>{he=!1,Pe(),fe(),ve(),e.unmount()}},[e,t,r,n,a]),Bo(()=>{let m=g.current;m&&wc(m,p)},[p]),(0,vn.useEffect)(()=>{s!==void 0&&(s===null&&x.current===null||(x.current=s,e.applyTheme?.(s)))},[e,s]),(0,vn.useEffect)(()=>{f!==_e.current&&(_e.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,Rn.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:E,popupCapabilityOwner:N,externalTelemetryContext:x,presentationMode:f}){let U=yo(),{emitInstrument:_e}=(0,o.useContext)(wn),m=(0,ur.useStripe)(),he=(0,ur.useElements)(),I=(0,o.useMemo)(()=>Ri(Er(U),x),[x,U]),[re,Pe]=(0,o.useState)("loading");(0,o.useEffect)(()=>{V?.(re)},[re,V]);let[fe,ve]=(0,o.useState)(!1),bt=(0,o.useRef)(!1),$e=!(0,c.isValidEmail)(r?.trim())||!g?.trim(),{request:L,collect:mt,finish:xe}=oa(),Ge=(0,o.useRef)(!1),Ce=(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,Ee.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 be=(0,o.useCallback)(()=>{qe(Fe=>Fe+1)},[]),ot=(0,o.useCallback)((Fe,pe,Ne)=>{Ze(Ne),v?.("paypal",Fe,{code:pe,popupBlocked:(0,Ee.isPopupBlockedError)(Fe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),Le(!0),be()},[Ze,v,f,be]),F=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Ce.current?.querySelector("iframe")??Ce.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{ve(!0);let b=await Mt;if(!X)return;if(b?.error){ja.delete(pe),K(),s?.(b.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),ja.delete(pe),Ne==="failed"){let ye="PayPal payment was declined. Please try again.";I?.terminal({outcome:"payment_declined",...jn,terminalReason:"provider_declined"}),s?.(ye),y?.(kr("paypal",ye));return}let S=b?.paymentIntent;if(S&&S.id!==Fe){K(),s?.("Failed to match the returned PayPal payment.");return}if(S&&(S.status==="requires_capture"||S.status==="succeeded")){let ye=typeof S.payment_method=="string"?S.payment_method:S.payment_method?.id;a({id:ye??S.id,type:"card",threeDSecureActionResultTokenId:S.id,isPaypal:!0},{...Jt,presentationMode:"redirect"})}else{let ye="PayPal payment was not completed. Please try again.";I?.terminal({outcome:S?.status==="canceled"?"payment_cancelled":"payment_declined",...jn,terminalReason:S?.status==="canceled"?"cancelled":"provider_declined"}),s?.(ye),y?.(kr("paypal",ye))}}catch(b){if(!X)return;ja.delete(pe),K(),s?.(b instanceof Error?b.message:"Failed to complete PayPal payment.")}finally{X&&ve(!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||!he)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:mt});if(!Mt){Fe.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Jt=Mt.email,K={...Ne?.accountPatch,...(0,Rn.compactBuyerIdentity)(Mt,!0)};try{if(ve(!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:b,paymentMethod:S}=await je({type:"paypal"});if(b){ot(b,"stripe_paypal_create_payment_method_failed",pe?.generation),Fe.paymentFailed({reason:"fail"});return}let ye=await Di(n,_e,Qe,X??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:S?.id??null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(ye)){Fe.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:K,paymentMethodCategory:"paypal",presentationMode:f,sessionId:Qe,nonce:X,settledProcessResponse:ye.response});return}if(ye.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Se=ye.clientSecret,ft={return_url:(0,c.stripeRedirectReturnUrl)()};if(S?.id&&(ft.payment_method=S.id),!pr(Bs,{clientSecret:Se,sessionId:Qe,nonce:X,accountPatch:K})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:et,paymentIntent:we}=await m.confirmPayment({clientSecret:Se,confirmParams:ft,redirect:"if_required"});if(et){if(pr(Bs),(0,Ee.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,Ee.getProviderErrorCode)(et),declineCode:(0,Ee.getProviderDeclineCode)(et)})),await Oi({billingApiUrl:n,sessionId:Qe,nonce:X,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,Ee.getProviderErrorCode)(et)??"provider_declined"}})}else ot(et,"stripe_paypal_confirm_failed",pe?.generation);return}pr(Bs);let ut=typeof we?.payment_method=="string"?we.payment_method:we?.payment_method?.id;a({id:ut??we?.id,type:"card",threeDSecureActionResultTokenId:we?.id,isPaypal:!0},{accountPatch:K,paymentMethodCategory:"paypal",presentationMode:f,sessionId:Qe,nonce:X});return}catch(je){ot(je,"stripe_paypal_failed",pe?.generation)}finally{ve(!1)}},[m,he,e,t,r,g,mt,k,n,_e,a,s,y,P,ot,H,ne,ue,I,f,Z]),qt=(0,o.useCallback)(async()=>{if(!(bt.current||d||fe||!m||!he)){bt.current=!0,ve(!0);try{if(!await Ye(!0))return;await Rt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{bt.current=!1,ve(!1)}}},[he,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:E??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=>Pe(La(Fe,["paypal"])),onLoadError:()=>{Pe("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,be()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:$e,emailRequired:$e,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:Ce,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:E,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:E,placeholderBorderRadius:N,popupCapabilityOwner:x,externalTelemetryContext:f}){let U=yo(),{emitInstrument:_e}=(0,o.useContext)(wn),m=(0,ur.useStripe)(),he=(0,ur.useElements)(),I=(0,o.useMemo)(()=>Ri(Er(U),f),[f,U]),[re,Pe]=(0,o.useState)("loading");(0,o.useEffect)(()=>{E?.(re)},[re,E]);let[fe,ve]=(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:$e,collect:L,finish:mt}=oa(),xe=(0,o.useRef)(null),Ge=(0,o.useRef)(null),[Ce,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),be=(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,Ee.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,Ce]);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))},[]),b=(0,o.useCallback)((u,M,G,W,J=!1)=>{pe(W),P?.(u,M,{code:G,popupBlocked:(0,Ee.isPopupBlockedError)(M),telemetryReported:J,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ue(u),j(!0),K()},[pe,P,K]),S=(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]),ye=(0,o.useCallback)(()=>{window.setTimeout(()=>{(xe.current?.querySelector("iframe")??xe.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{be.current&&(be.current=!1,ye())},[ye,Ce]);let Se=(0,o.useCallback)(()=>{j(!1),p?.(null),ye()},[ye,p]),ft=(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=gt=>{M||G||(M=!0,u.paymentFailed({reason:"fail",...gt?{message:gt}:{}}))};if(!m||!he){W();return}let J=jt.current.get(Ce);if(J&&!Qe(J.generation)){jt.current.delete(Ce),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,Ht=null,Ir=e,Mn="processing",It="other",Wn="provider_runtime",Qt,mr=new Promise((gt,Bt)=>{Qt=Bt}),er=window.setTimeout(()=>{Nr=!0,Dr.abort(),Qt(xi)},fu),nn=async(gt,Bt,on)=>{Mn=gt,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:gt,durationMs:Math.max(0,wr-Sr),durationMode:"machine",requestCategory:Bt,paymentMethodCategory:"wallet",provider:"stripe",...Nr?{statusClass:"timeout"}:{}})}};try{if(ve(!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 gt=At?.sessionId??e;Ir=gt;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,Rn.compactBuyerIdentity)(Sr,!0)};await nn("processing","session_claim",Promise.resolve(V?.(Sr)));let{error:Gr}=await nn("tokenization","provider_sdk",he.submit());if(Gr){W(),b(B,Gr,"stripe_wallet_submit_failed",J?.generation);return}if(!gt)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:gt,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,_e,gt,Bt??"",{...Ur,authorizationAttemptId:qr},{signal:Dr.signal}));if((0,c.isSettledSessionIntent)(Wt)){W(),d({type:"card",paymentMethodType:B},{accountPatch:wr,paymentMethodCategory:"wallet",sessionId:gt,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:gt,...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}),Ht=window.setTimeout(()=>{Ht!==null&&at.current.delete(Ht),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(Ht);let Or=(ce,de)=>{Ht!==null&&(window.clearTimeout(Ht),at.current.delete(Ht),Ht=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(gt,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"),ve(!1));let it=`${Bc}:${gt}`;pr(it,{createdAt:Date.now(),sessionId:gt,nonce:Bt,accountPatch:wr,paymentMethodId:ir,providerIntentId:$t,paymentMethodType:B});try{d({id:ir,type:"card",threeDSecureActionResultTokenId:$t},{accountPatch:wr,paymentMethodCategory:"wallet",sessionId:gt,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(gt,Bt,ar),Ye.current=null,ne.current=null,!Me.current)return;H("idle"),W(),b(B,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",J?.generation,!0);return}Me.current&&!Vr&&(H("blocked"),ve(!1))}catch{Me.current&&!Vr&&(H("blocked"),ve(!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:he,clientSecret:ar,redirect:"if_required"}):m.confirmPayment({elements:he,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,Ee.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,Ee.isProviderDecline)(ie)){Vr=!0,xs(gt,Bt,ar),Ye.current=null,ne.current=null,H("idle"),jt.current.get(Ce)===J&&jt.current.delete(Ce);let ce=ie.message??"Your payment was declined.";p?.(ce),v?.(kr(vt,ce,{code:(0,Ee.getProviderErrorCode)(ie),declineCode:(0,Ee.getProviderDeclineCode)(ie)})),Oi({billingApiUrl:n,sessionId:gt,nonce:Bt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,providerDeclineReason:(0,Ee.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(gt){if(gt===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(),b(B,gt,gt===xi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",J?.generation,gt===xi)}finally{if(window.clearTimeout(er),Ht!==null&&(window.clearTimeout(Ht),at.current.delete(Ht)),!Kr){let gt=_t?.now()??globalThis.performance?.now()??Date.now();_t?.performance({stage:"callback",durationMs:Math.max(0,gt-Hr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Nr?{statusClass:"timeout"}:{}})}Me.current&&ve(!1)}},[m,he,e,t,r,k,L,V,n,_e,a,d,p,v,g,b,je,Fe,Qe,Ne,X,I,Ce]),et=(0,o.useMemo)(()=>Ei(s),[s]),we=(0,o.useMemo)(()=>s.map(c.stripeExpressMethodToOptionKey),[s]),ut=(0,o.useMemo)(()=>(0,l.jsx)(ur.ExpressCheckoutElement,{onReady:u=>{Pe(La(u,we))},onLoadError:u=>{Pe("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(),S(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(Ce),u.reject();return}let B=kt(u.expressPaymentType);Jt.current=!1,Rt.current={generation:B,startedAt:M},jt.current.set(Ce,{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(Ce);jt.current.delete(Ce);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,b(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),be.current=!0,K()},options:{..._i,paymentMethods:et,emailRequired:bt,billingAddressRequired:bt}},Ce),[we,et,Vt,pe,y,bt,b,S,K,g,kt,Ce,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:Se,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:ft,disabled:ae==="checking",style:Os,children:ae==="checking"?"Checking payment status\u2026":"Check payment status"})]}),$e&&(0,l.jsx)(aa,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:mt,onCancel:()=>mt(null)},$e.id),(0,l.jsxs)("div",{style:{display:$e||ae!=="idle"?"none":void 0},children:[(0,l.jsx)(Uu,{active:Z}),ut]})]})}),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:E,submitButtonBorderRadius:N,submitButtonStyle:x,errorText:f}){let U=yo(),{emitInstrument:_e}=(0,o.useContext)(wn),m=(0,ur.useStripe)(),he=(0,ur.useElements)(),[I,re]=(0,o.useState)(!1),Pe=(0,o.useRef)(!1),[fe,ve]=(0,o.useState)(!1),[bt,$e]=(0,o.useState)("loading"),[L,mt]=(0,o.useState)(""),xe=!(0,c.isValidEmail)(n?.trim()),Ge=!xe||(0,c.isValidEmail)(L.trim()),Ce=(0,o.useCallback)(async()=>{if(!m||!he||V||Pe.current||!fe)return;Pe.current=!0,re(!0);let q=g?await g("card"):{proceed:!0};if(!q.proceed){Pe.current=!1,re(!1);return}k?.("card");let Z=q.sessionId??t,qe=q.nonce??r,Oe=(0,na.splitFullName)(a?.trim()),Le=(0,Rn.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,Rn.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 he.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:he,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,_e,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 be=Me.clientSecret;pr(to,{clientSecret:be,sessionId:Z,nonce:qe,accountPatch:j,paymentMethodId:ue.id,paymentMethodType:ue.type??e,gateway:"stripe"});let{error:ot,paymentIntent:F}=await m.confirmPayment({clientSecret:be,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{Pe.current=!1,re(!1)}},[m,he,V,fe,g,k,t,r,n,a,L,s,d,_e,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=>mt(q.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(ur.PaymentElement,{onReady:()=>$e("ready"),onLoadError:()=>{$e("load_error"),zs(Er(U),"stripe","apm")},onChange:q=>{ve(!!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:()=>{Ce()},disabled:!fe||!Ge||I||V||bt!=="ready",color:E,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:E,onLoadStateChange:N,isProcessing:x=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:U=8,submitButtonStyle:_e,buttonAppearance:m,themeId:he,onExpandApm:I,expandedApmMethod:re}){let{emitInstrument:Pe}=(0,o.useContext)(wn),[fe,ve]=(0,o.useState)(null),[bt,$e]=(0,o.useState)(null),L=(0,o.useRef)(!1),{request:mt,collect:xe,finish:Ge}=oa();(0,o.useEffect)(()=>{d.length>0&&p?N?.("ready"):p||N?.("loading")},[d.length,p,N]);let Ce=(0,o.useCallback)(async Q=>{if(!p||L.current||x)return;L.current=!0,$e(Q);let j=E?await E("card"):{proceed:!0};if(!j.proceed){L.current=!1,$e(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,Rn.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)){$e(null);let be=await xe((0,c.getStripeMethodDisplayName)(Q),ue);if(!be){L.current=!1;return}ue=be,$e(Q)}let ne=ue.email,Me=(0,Rn.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 be=await Di(s,Pe,ae,H??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(be)){P({type:"card",gateway:"stripe",paymentMethodType:Q},{accountPatch:Me,paymentMethodCategory:"apm",sessionId:ae,nonce:H,settledProcessResponse:be.response});return}if(be.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ot=be.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(be){g?.(be instanceof Error?be.message:"Payment failed. Please try again.")}finally{L.current=!1,$e(null)}},[p,x,E,k,e,t,r,xe,s,Pe,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):Ce(Q))},[qe,x,Ce,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:mt?(0,l.jsx)(aa,{identity:mt.identity,methodLabel:mt.methodLabel,onComplete:Ge,onCancel:()=>Ge(null)},mt.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:he,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:E,onButtonClick:k,isProcessing:x,submitButtonColor:f,submitButtonBorderRadius:U,submitButtonStyle:_e})},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:E,submitLabel:N,isProcessing:x,error:f,onErrorChange:U,showPayPal:_e=!0,showStripe:m=!0,walletPresentation:he="auto",enabledPaymentMethods:I,enabledPaymentMethodCountries:re,showApplePay:Pe=!0,showGooglePay:fe=!0,layout:ve="default",paymentMethodLayout:bt,moreOptionsLabel:$e,theme:L,buttonsTheme:mt,buttonsStyles:xe,appearance:Ge,cardButtonContent:Ce,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:be,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(),b=yi(),S=(0,o.useContext)(Un),{emitInstrument:ye}=(0,o.useContext)(wn),Se=(0,o.useRef)(null);Se.current||(Se.current=fi());let ft=Se.current,[,Vt]=(0,o.useState)(0),et=(0,o.useRef)(null);et.current||(et.current=(0,Zn.detectPayPalEnvironment)());let we=et.current,ut=(0,o.useMemo)(()=>({browser:we,capability:ft,presentationMode:"popup"}),[we,ft]),u=X??S.session,M=(0,o.useMemo)(()=>({futureUse:u?.futureUse,futureUseUnsupported:u?.futureUseUnsupported}),[u?.futureUse,u?.futureUseUnsupported]),G=u?.gateways?.paypal?.providerObjectType??Ne?.providerObjectType,W=Mt||S.claimPending===!0,J=Jt||S.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,Ht]=(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)(be??""),[gt,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)(be??""),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,$,Te,Y,De)=>{if(Or.current[C])return;let Nt=$?.trim();!Nt||Nt===Te.current||(Te.current=Nt,Y(Nt),De?.(Nt))};i("country",ne,ar,Wn,Ye),i("zip",Me,Wt,mr,at),i("addressLine1",be,Rr,nn),i("addressLine2",ot,sn,Bt),i("city",F,Tr,Sr),i("state",rt,jr,Gr)},[ne,Me,be,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)(()=>ve!=="buttons"||pe?e??null:null),[it,Yr]=(0,o.useState)(0),$n=ve!=="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:Cn,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(),Te={line1:$(Ve.address_line_1,er),city:$(Ve.city,on),state:$(Ve.state,wr),zip:Xr.empty||Xr.malformed};return{avsInvalid:Te.line1||Te.city||Te.state||Te.zip,invalidAvsFields:Te}},[de,Ve,It,er,on,wr,Xr]),[An,un]=(0,o.useState)(!1),[oo,bn]=(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),gn=Ct==="expanding"||Ct==="card",z=X?.gateways?.stripe&&!D?"stripe":void 0,O=(0,o.useCallback)(()=>{ye?.({class:"card_surface",provider:z})},[z,ye]),se=(0,o.useCallback)(()=>{Hr(!0),ye?.({class:"more_options"})},[ye]),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),[He,nt]=(0,o.useState)(0),ee=(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]),Ie=(0,o.useCallback)(()=>{Ar("collapsing"),st(()=>Ar("buttons"))},[st]),lt=(0,o.useCallback)(i=>{so(i),Ar("apm-expanding"),st(()=>Ar("apm-form"))},[st]),te=(0,o.useCallback)(()=>{Ar("apm-collapsing"),st(()=>{Ar("buttons"),so(null)})},[st]);(0,o.useEffect)(()=>{ve==="buttons"&&pe&&ce&&(ir(e??null),Ar("card"))},[ve,pe,ce,e]);let[Re,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 _=(0,o.useRef)(!1),le=(0,o.useRef)(null),me=(0,o.useRef)("idle"),[Be,Kt]=(0,o.useState)(!1),ct=(0,o.useRef)(Be);ct.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||S.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,S.claimBuyerIdentity,X?.buyerIdentified,e,t,vt,s,g,k]),Je=Q??S.claimBuyerIdentity??xt,pt=f??Ir,yt=(0,o.useMemo)(()=>(0,c.resolveTheme)(L),[L]),ke=(0,o.useMemo)(()=>{let i=yt?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(mt);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},[yt,mt,xe]),zt=Ge??yt?.appearance,Ya=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:zt,buttonsStyles:ke,layout:ve}),[zt,ke,ve]),sd=S.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,hn=(0,o.useMemo)(()=>je?je.getRawProvider():null,[je]),el=(0,o.useMemo)(()=>b?b.getRawProvider():null,[b]),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)(()=>{He!==ol.current&&(ol.current=He,Ue(null))},[He,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,Rn.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(ve==="buttons"&&(i==="card"||i==="expanding"))return!0;let C=me.current;return C==="validation-window"||C==="processing"||ct.current},[ve]),cl=(0,o.useCallback)((i,C,$)=>{sl.take(e)&&Er(je)?.log(Oo({...ut,presentationMode:$?.presentationMode??"popup"},{name:gi,stage:"recovery",reason:"other_method_active",provider:$?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:$?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[ut,je,sl,e]),Xa=(0,o.useCallback)((i,C,$)=>{$?.telemetryReported||Er(je)?.error(Oo({...ut,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")}))},[ut,je]),Ho=(0,o.useCallback)((i,C,$)=>{let Te=$?.popupBlocked??(0,Ee.isPopupBlockedError)(C);if(ll()){Xa(i,Te,$),cl(i,C,$);return}if(C instanceof c.FloPayError&&C.code==="checkout_processing_timeout"){Xa(i,!1,$),Ae(null),ve==="buttons"&&(Ar("buttons"),so(null)),Ue(C.message),p?.(C);return}Te&&ft.markBlocked()&&Vt(St=>St+1);let Y=Ls(i),De=$?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(Y):(0,Ee.buildExternalMethodRecoveryMessage)(Y,Te,we.inAppBrowser),Nt=(0,Ee.getProviderErrorCode)(C),Ut=(Nt?.toLowerCase()==="error"?void 0:Nt)??(0,Ee.sanitizeExternalFailureCode)($?.code)??"external_payment_method_failed",tt=new c.FloPayError(De,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:Ut,popupBlocked:Te,inAppBrowser:we.inAppBrowser,appFamily:we.appFamily,popupCapability:ft.current(),presentationMode:$?.presentationMode??"popup"}});Xa(i,Te,$),Ae(null),ve==="buttons"&&(Ar("buttons"),so(null)),Ue(De),p?.(tt),console.error("[FloPay] External payment method failed:",{method:i,code:Ut,popupBlocked:Te})},[we,ll,ve,p,ft,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??""}`,Te=ee.current;if(Te&&Te.key===$){Wr(Te.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&&(ee.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 Te=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,Pn=Nt?jr.current:hr;return{accountData:{userId:i.resolvedAccount.userId??"",email:$,...Te?{firstName:Te}:{},...Y?{lastName:Y}:{},...tt&&Wt.current?{zip:Wt.current}:{},...St&&Tr.current?{city:Tr.current}:{},...Pn?{state:Pn}:{},...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||pt!==_c||On.current.updateError(null)},[W,pt]),(0,o.useEffect)(()=>{!de||!Gt||Gt.setSubmitGate?.(Cn||W||Vo||Be)},[de,Gt,Cn,W,Vo,Be]),(0,o.useEffect)(()=>{if(!de||!Gt)return;Zi.current=!1;let i=null,C=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,me.current="idle",Ae(null)},400)},$=Gt.on("submitting",()=>{un(!0),le.current&&clearTimeout(le.current),me.current="validation-window",le.current=setTimeout(()=>{le.current=null,me.current==="validation-window"&&(me.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."),me.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),me.current="idle",Ae(null),tt.onError?.(Ft instanceof c.FloPayError?Ft:new c.FloPayError(hr,"api_error"))})}),Te=Gt.on("complete",tt=>{(0,qn.markSessionRecentlyCompleted)(tt.sessionId??On.current.sessionId),me.current="terminal",Kt(!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.";me.current="terminal",Kt(!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),me.current="idle",Kt(!1),St.updateError(Ft),Ae(null),h(Pn=>Pn+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.";me.current="terminal",Kt(!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),me.current="processing",Kt(!0),Ae(null)}),Ut=Gt.on("blocked",()=>{if(ct.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),me.current="idle",Kt(!1),Ae(null),$(),Te(),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)(we,he,ft.current()),{expressMethods:Qa,paymentElementMethods:Qi}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(I,{excludePaypal:Xn}),[I,Xn]),yl=Xn||!!b||pl&&Ko==="redirect",cd=(0,o.useMemo)(()=>yl?Qa.filter(i=>i!=="paypal"):Qa,[Qa,yl]),dd=(0,o.useMemo)(()=>{let i=[];return Pe&&i.push("apple_pay"),fe&&i.push("google_pay"),i},[Pe,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=_e&&(Xn||(fa?pl:ti===!1)),md=we.inAppBrowser&&ft.current()==="blocked",Cl=m&&ud&&!md,Io=(!B||!!S.waitForDataAttachment)&&vl&&Xn,ss=Pl==="retrying"||Pl==="exhausted",ga=null;m&&(b?ga=el:Ko==="redirect"&&(ga=hn));let bl=(0,o.useMemo)(()=>({...ut,presentationMode:Ko}),[ut,Ko]),To=!B&&vl&&!!ga&&(!Xn||ss),So=!B&&Cl&&!!hn,Mo=!B&&m&&Ja&&ei.length>0&&!!hn,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&&!_e){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&&_e&&!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,_e,Xn,ti,B,ce,kl,p,Ue]);let El=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(El.current||!Ja)return;let i=[];Pe!==!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,Pe,fe]);let _l=(0,o.useCallback)((i,C,$)=>S.applyInlineSessionPatch?S.applyInlineSessionPatch(i).then(Te=>({error:null,sessionId:Te.sessionId||e,nonce:Te.session?.clientSecret||t})).catch(Te=>{let Y=(0,c.normalizeBeforeButtonClickError)(C,Te);return $?.abandoned?.()||(Ue(Y.message),p?.(Y)),{error:Y,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[S.applyInlineSessionPatch,t,p,e,Ue]),Ln=(0,o.useCallback)(async(i,C)=>{if(i!=="card"&&B&&await S.waitForDataAttachment?.(),!Le)return{proceed:!0};try{let $=await Le({method:i,sessionId:e||void 0,createSession:S.inlineSessionDraft});if($===!1)return{proceed:!1};if($&&typeof $=="object"){$.account&&qr(Y=>({...Y??{},...$.account}));let Te=await _l($,i,C);return Te.error?{proceed:!1,accountPatch:$.account}:{proceed:!0,accountPatch:$.account,sessionId:Te.sessionId,nonce:Te.nonce}}return{proceed:!0}}catch($){if(!C?.abandoned?.()){let Te=(0,c.normalizeBeforeButtonClickError)(i,$);Ue(Te.message),p?.(Te)}return{proceed:!1}}},[_l,S.inlineSessionDraft,S.waitForDataAttachment,B,Le,p,e,Ue]),Il=(0,o.useCallback)(async(i,C)=>{if(_.current)return;_.current=!0,Ht(!0),Ae("processing"),Ue(null);let $=C?.sessionId??e,Te=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),{...ut,presentationMode:C.presentationMode}):void 0,St=()=>{ye?.({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),Pn=C?.settledProcessResponse??await Ft.processPayment(Y.userId??"",{sessionId:$,nonce:Te,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(Pn.ok){await li(Pn.status===204?null:await Pn.json().catch(()=>null));return}let Pr=await Pn.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=b?.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(Pn.headers.get(Pu)===vu){let xr=await Cu(Ft,$,Te);if(xr!==void 0){await li(xr);return}}(0,c.classifyPaymentRejection)(Pn.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{Ht(!1),Ae(null),_.current=!1}},[Co,e,t,Tt,Ve,Rt,qt,jt,V,je,b,X,d,Ue,Yn,ye,ut]),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 Te=je.getRawProvider();if(!Te)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 Te.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,Pn=ka(hr);if(!St||!Pn){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=ve==="buttons",Qr=zt?.variables,vd=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),cs=Qr?.colorBackground,Cd=cs&&!vd.has(cs)?cs:void 0,va=ke.cardInputBorder??(Pa?"#e5e7eb":"#A4A4FF"),Ml=Qr?.colorDanger??"#dc2626",lr=i=>Po[i]&&(xn[i]||An),oi=Vo&&(ao||An),Sn=i=>i?Ml:va,ai=(Xr.malformed||Xr.empty)&&(oo||An),bd=Sn(ai),ds=ke.cardFormContainer?.backgroundColor??Cd??(Pa?"white":"#EDEDFF"),Yo=ke.cardInputBackground??Qr?.colorBackground??"white",us=Zo(q),Al=Zo(Z),Xo=ke.nameInput,xl=ke.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=ke.cardInputColor??(typeof Xo?.color=="string"?Xo.color:void 0)??Qr?.colorText??"#262833",wd=ke.cardInputPlaceholderColor??"#9ca3af",dr=Qr?.borderRadius??"8px",lo=Qr?.borderRadius??ke.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=ke.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&&me.current==="idle"&&(Yt.current=!0),Ue(i)},onValidation:i=>{let C=me.current;(C==="idle"||C==="validation-window")&&(Ue(i),i&&me.current==="validation-window"&&(le.current&&(clearTimeout(le.current),le.current=null),me.current="idle",Ae(null)))}},He):(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 @@ ${W.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
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:`
38
+ `}),Pa&&gn&&(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:Ie,style:{display:"inline-flex",alignItems:"center",gap:us?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ke.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ke.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",...ke.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:ke.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...ke.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,...ke.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 ${Sn(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 ${Sn(Y)}`,borderRadius:dr,marginTop:"0.5rem",padding:"10px"}),$=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ys}),Te=(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:gt,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 ${Sn(lr("city"))}`,borderRight:`1px solid ${Sn(lr("city"))}`,borderBottom:`1px solid ${Sn(lr("city"))}`,borderLeft:`1px solid ${Sn(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 ${Sn(lr("state"))}`,borderRight:`1px solid ${Sn(lr("state"))}`,borderBottom:`1px solid ${Sn(lr("state"))}`,borderLeft:`1px solid ${Sn(lr("state"))}`,padding:"10px",borderTopRightRadius:dr,borderBottomRightRadius:dr,...(0,c.isAVSFieldVisible)(Ve.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Sn(lr("state")||lr("city"))}`}:{borderRadius:dr}},children:Te?(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)}),Te.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")&&bn(!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,pt&&(0,l.jsx)(la,{margin:"0.75rem 0",styleOverride:ke.errorBanner,children:pt})]}),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?!_e||!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=${_e}`,` directPaypalConfigured=${Xn}`,` inAppBrowserDetected=${String(ti)}`,` shouldRenderDirectPayPal=${Io}`,` shouldRenderStripePayPal=${To}`,` hasPaypalStripeInstance=${!!el}`].join(`
39
+ `)}):null,Ol=i=>K?!m||!hn?(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=${!!hn}`,` 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:$e||gc,open:_t,onOpen:se,color:wo,fontFamily:Qr?.fontFamily};if(ve==="buttons"){let i=Ct==="buttons"||Ct==="expanding"||Ct==="apm-expanding",C=Ct==="expanding"||Ct==="card"||Ct==="collapsing",$=Ce===void 0?{boxSizing:"border-box",height:Eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Te;Ct==="expanding"||Ct==="apm-expanding"?Te=Mu:(Ct==="collapsing"||Ct==="apm-collapsing")&&(Te=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:ft,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:ft,externalTelemetryContext:bl,presentationMode:Ko})})]}),wallets:(0,l.jsxs)(l.Fragment,{children:[So?(0,l.jsx)(ur.Elements,{stripe:hn,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:ft,externalTelemetryContext:ut})}):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:hn,paymentElementBaseOptions:es,futureUseSession:M,onTokenizedBody:pn,onErrorChange:Ue,onButtonClick:Oe,onDecline:y,runBeforeButtonClick:Ln,onLoadStateChange:hl,isProcessing:cr,submitButtonColor:wo,submitButtonBorderRadius:dr,submitButtonStyle:ke.submitButton,onExpandApm:lt,expandedApmMethod:nr,themeId:L,buttonAppearance:{backgroundColor:ke.cardButton?.backgroundColor,borderColor:ke.cardInputBorder,textColor:ke.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%",...$,...ke.cardButton,...qs({themeBundle:yt,resolvedPrimaryColor:wo,resolvedBorderRadius:dr,submitButtonStyle:ke.submitButton,explicitPrimaryColor:Qr?.colorPrimary}),fontSize:ke.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&&(yt||Qr?.colorPrimary)&&(Ut.currentTarget.style.backgroundColor=Rd)},onMouseLeave:Ut=>{(yt||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:Ce})})})};return(0,l.jsxs)("form",{onSubmit:ls,className:E,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(pa,{}),Re&&(0,l.jsx)(yn,{status:Re,errorMessage:pt,authorized:Mr}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Te?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Te?xu:{},...Te?{animation:Te,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}),pt&&Ct==="buttons"&&(0,l.jsx)(la,{margin:"0.25rem 0",styleOverride:ke.errorBanner,children:pt})]}),de&&C&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...Ct==="collapsing"?{pointerEvents:"none"}:{}},children:gs}),m&&Ll&&nr&&si&&hn&&(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:te,style:{display:"inline-flex",alignItems:"center",gap:us?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ke.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ke.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",...ke.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:ke.titleFontSize??"1.05rem",color:ps,paddingRight:80,...ke.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(nr)}`})]}),(0,l.jsx)(ur.Elements,{stripe:hn,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:te,runBeforeButtonClick:Ln,onButtonClick:Oe,isProcessing:cr,submitButtonColor:wo,submitButtonBorderRadius:dr,submitButtonStyle:ke.submitButton,errorText:pt})},nr)]})})]})]})}if(Ll&&nr&&si&&hn&&m)return(0,l.jsxs)("form",{onSubmit:ls,className:E,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(pa,{}),Re&&(0,l.jsx)(yn,{status:Re,errorMessage:pt,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:te,style:{display:"inline-flex",alignItems:"center",gap:us?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ke.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ke.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",...ke.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:ke.titleFontSize??"1.05rem",color:ps,paddingRight:80,...ke.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(nr)}`})]}),(0,l.jsx)(ur.Elements,{stripe:hn,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:te,runBeforeButtonClick:Ln,onButtonClick:Oe,isProcessing:cr,submitButtonColor:wo,submitButtonBorderRadius:dr,submitButtonStyle:ke.submitButton,errorText:pt})},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:ft,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:ft,externalTelemetryContext:bl,presentationMode:Ko})})]}),wallets:(0,l.jsx)(l.Fragment,{children:So&&(0,l.jsx)(ur.Elements,{stripe:hn,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:ft,externalTelemetryContext:ut})})}),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:hn,paymentElementBaseOptions:es,futureUseSession:M,onTokenizedBody:pn,onErrorChange:Ue,onButtonClick:Oe,onDecline:y,runBeforeButtonClick:Ln,onLoadStateChange:hl,isProcessing:cr,submitButtonColor:wo,submitButtonBorderRadius:dr,submitButtonStyle:ke.submitButton,themeId:L,onExpandApm:lt,expandedApmMethod:nr,buttonAppearance:{backgroundColor:ke.cardButton?.backgroundColor,borderColor:ke.cardInputBorder,textColor:ke.cardButton?.color,borderRadius:lo}})})};return(0,l.jsxs)("form",{onSubmit:ls,className:E,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(pa,{}),Re&&(0,l.jsx)(yn,{status:Re,errorMessage:pt,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:ge.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,ge.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 ge.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof ge.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,ge.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,ge.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:E,onZipChange:N,showPayPal:x=!0,showStripe:f=!0,walletPresentation:U="auto",enabledPaymentMethods:_e,showApplePay:m=!0,showGooglePay:he=!0,debug:I=!1,layout:re,paymentMethodLayout:Pe,moreOptionsLabel:fe,theme:ve,buttonsTheme:bt,buttonsStyles:$e,cardButtonContent:L,cardBackButtonContent:mt,cardTitleContent:xe,showSecurityFooter:Ge,onButtonClick:Ce,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:be,onSessionCompleted:ot}){let F=(0,ge.resolveBillingApiUrl)(n),rt=(0,w.useMemo)(()=>(0,ge.resolveTheme)(ve),[ve]),Ye=s??rt?.appearance,at=r?"embedded_checkout":"standard_checkout",Rt=Ks(ue,re),[qt,jt]=(0,w.useState)(null),[kt,Fe]=(0,w.useState)(null),pe=(0,w.useRef)(null),Ne=(0,w.useRef)(null),Qe=(0,w.useRef)(0),[X,Mt]=(0,w.useState)(null),Jt=(0,w.useRef)(null),[K,je]=(0,w.useState)(null),b=(0,w.useMemo)(()=>r?(0,ht.serializeCreateParams)(r):"",[r]),S=r?`create:${b}`:`session:${e??""}`,ye=Wc(K),Se=(0,w.useRef)(new Set),ft=(0,w.useRef)(S),Vt=(0,w.useRef)(S);Bo(()=>{Vt.current=S,ft.current!==S&&(ft.current=S,Se.current.clear())},[S]);let et=(0,w.useCallback)(z=>{if(Vt.current===S){if(ws.FLO_INSTRUMENT_ONCE_NAMES.has(z.name)){if(Se.current.has(z.name))return;Se.current.add(z.name)}(0,We.invokeMerchantCallback)(()=>g?.(z))}},[S,g]),we=sa(et,S),ut=(0,w.useRef)(!1),u=(0,w.useCallback)(z=>{if(ut.current)return;let O=z.gateway||!ye?z:{...z,gateway:ye};et(O)},[et,ye]);(0,w.useEffect)(()=>{we({class:"lifecycle",name:"checkout.mount"})},[we]);let[M,G]=(0,w.useState)(e??""),W=e??M,J=r?"":W,[B,At]=(0,w.useState)(!0),[vt,Zt]=(0,w.useState)(null),[br,_t]=(0,w.useState)(0),[Hr,Dr]=(0,w.useState)("full"),[Nr,Kr]=(0,w.useState)(!1),[Ht,Ir]=(0,w.useState)(H),[Mn,It]=(0,w.useState)(null),[Wn,Qt]=(0,w.useState)(null),[mr,er]=(0,w.useState)(!1),[nn,gt]=(0,w.useState)(void 0),[Bt,on]=(0,w.useState)(""),[Sr,wr]=(0,w.useState)(!1),[Gr,Ur]=(0,w.useState)(!1),[zr,an]=(0,w.useState)(!1),qr=(0,w.useRef)(null),Wt=(0,w.useRef)(0),ar=(0,w.useRef)(void 0),[Rr,sn]=(0,w.useState)("loading"),[Tr,jr]=(0,w.useState)(0),fr=(0,w.useRef)(!1),Or=(0,w.useRef)(!1),Ve=(0,w.useRef)(!1),Vr=(0,w.useRef)(null),Mr=(0,w.useRef)(null),tr=(0,w.useMemo)(()=>({checkoutMode:ne??Hr,layout:Hu(ue,re)}),[ne,ue,Hr,re]),ln=(0,w.useRef)(v);ln.current=v;let D=(0,w.useRef)(P);D.current=P;let Dt=(0,w.useRef)(k);Dt.current=k;let ie=(0,w.useCallback)(z=>bi(Vr,async O=>{try{return await z(O)}catch(se){throw O.aborted?ca(se):se}}),[]);(0,w.useEffect)(()=>()=>{Vr.current?.abort(),Vr.current=null},[]);let ce=(0,w.useCallback)((z,O)=>{pe.current=z,Fe(z),Jt.current=O,Mt(O)},[]),de=(0,w.useCallback)(()=>{let z=Ne.current;z&&(Ne.current=null,z.destroy())},[]);(0,w.useEffect)(()=>{Er(kt)?.setCheckoutContext(tr),X&&X!==kt&&Er(X)?.setCheckoutContext(tr)},[kt,X,tr]);let $t=(0,w.useRef)(ot);$t.current=ot;let ir=(0,w.useCallback)(z=>{sn(z),!(z!=="exhausted"||Ve.current)&&(Ve.current=!0,D.current?.(new ge.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),it=(0,w.useCallback)(()=>{sn("retrying"),jr(z=>z+1)},[]);(0,w.useEffect)(()=>{sn("loading"),jr(0),Ve.current=!1},[W]),(0,w.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ge.SDK_VERSION,checkout_type:at,checkout_layout:Rt,billing_api_url:F})},[Rt,at,F]);let Yr=(0,w.useMemo)(()=>r?(0,ht.serializeCreateParams)(r,!0):"",[r]),$n=(0,w.useMemo)(()=>Bt===Yr?nn:void 0,[nn,Bt,Yr]),cn=(0,w.useMemo)(()=>r?vs(r,$n):void 0,[r,$n]),dn=ne??cn?.checkoutMode??"full",rr=(0,w.useMemo)(()=>cn?{...cn,checkoutMode:dn}:void 0,[cn,dn]);(0,w.useEffect)(()=>{gt(void 0),on(Yr),ar.current=void 0,qr.current=null,an(!1)},[Yr]),(0,w.useEffect)(()=>{Ir(H)},[H]);let Hn=(0,w.useCallback)((z,O,se)=>{(0,We.invokeMerchantCallback)(()=>{Dt.current?.(kr(z,O,se))})},[]),Gt=(0,w.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,He=Er(Yt),nt=Yt?null:Ui(F,a,tr),ee={log:h=>{He?He.log(h):nt?.log(h)},error:h=>{He?He.error(h):nt?.error(h)},terminal:h=>{He?He.terminal(h):nt?.terminal(h)},performance:h=>{He?He.performance(h):nt?.performance(h)},now:()=>He?.now()??nt?.now()??0,elapsed:h=>He?.elapsed(h)??Math.max(0,(nt?.now()??h)-h)},Xe=ee.now(),Ie=!!(O?.initialAutoProcessingError||O?.initialAutoProcessingPending),lt=!1,te,Re=()=>{lt||(lt=!0,Ie=!0,te=ee.now(),ee.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ae=!1,Lt=()=>{Ae||(Ae=!0,ee.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),ee.performance({stage:"processing",durationMs:ee.elapsed(Xe),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),te!==void 0&&ee.performance({stage:"recovery",durationMs:ee.elapsed(te),durationMode:"machine",paymentMethodCategory:"saved"}))};ee.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ut.current=!0;try{ee.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ut.current=!1}we({class:"lifecycle",name:"payment.processing.started",provider:st}),Ie&&Re();let T;try{let h=yc(O?.initialAutoProcessingError),_=O?.initialAutoProcessingError?.type==="3ds_required"&&!O.initialAutoProcessingError.threeDSecureToken&&O.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:O.initialAutoProcessingError.nextActionRedirectUrl}:null,le,me=Be=>{Re();let Kt=Da(F,se,z,a!==!1);return ie(ct=>da(Be,{billingApiUrl:F,sessionId:se,nonce:oe,session:z,signal:ct,...Kt.telemetry?{challengeTelemetry:Kt.telemetry}:{}})).finally(Kt.release)};if(_)le=await me(_);else if(h)Re(),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,Kt=new go.PaymentAPI(F,{telemetry:!1}),ct=await ie(Zr=>Kt.waitForCheckoutSessionCompletion(Be.sessionId,{initialDelayMs:Be.retryAfterMs,nonce:oe,statusUrl:Be.statusUrl,signal:Zr})),sr=ko(ct,z),gr=ct.autoProcessingError?.type==="3ds_required"&&ct.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ct.autoProcessingError.nextActionRedirectUrl}:null;if(gr)le=await me(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 me(Be):(Re(),Be.type==="paypal_redirect_required"&&Mr.current?.publishableKey&&jc({sessionId:se,publishableKey:Mr.current.publishableKey,paypalPublishableKey:Mr.current.paypalPublishableKey}),le=await ie(Kt=>wi(Be,{flopay:pe.current,paypalFlopay:Jt.current,attempt3DS:O?.attempt3DS,billingApiUrl:F,sessionId:se,session:z,telemetry:!1,signal:Kt})),Be.type==="paypal_redirect_required"&&Hs())}}se&&(0,qn.markSessionRecentlyCompleted)(se),Lt(),Ie&&(ee.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),ee.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 _=Ro(Oa(h),se);if(_.code==="three_ds_aborted")return!1;let le=_.checkoutMethod??Ba;Ir(_.message),Qt(_.message),er(!1),O?.fallbackToFull&&(ee.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Dr("full"),Vc("full")),Lt();let me=_.statusCode===void 0?void 0:(0,ge.telemetryStatusClass)(_.statusCode,"unknown"),Be=me==="4xx"?{requestCategory:"process_payment",statusClass:me}:{},Kt=me===void 0||me==="4xx",ct=(0,ge.isExpectedPaymentDecline)(_);if(ct)ee.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Be});else if(Kt&&(_.telemetryOutcome==="validation_rejected"||_.type==="validation_error"))ee.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Be});else{let gr=(0,ge.classifyTelemetryFailure)(h,Ie?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Zr=_.telemetryRequestCategory??"process_payment";ut.current=!0;try{ee.error({...gr,..._.telemetryFailureCategory?{failureCategory:_.telemetryFailureCategory}:{},stage:Ie?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Zr})}finally{ut.current=!1}we({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Zr,provider:st})}return ct||(0,We.invokeMerchantCallback)(()=>D.current?.(_)),Hn(le,_,{code:_.code,declineCode:_.declineCode}),It("error"),await Promise.allSettled([$a(400),O?.ensureProvidersReady?O.ensureProvidersReady():Promise.resolve()]),Ie&&(ee.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),ee.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Lt(),nt&&Ha(nt),It(null),Qt(null)}return(0,We.invokeMerchantCallback)(T),!0},[Hn,we,t,F,ie,a,tr]);(0,w.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()=>{await Promise.resolve();let oe,st=0;Ir(null),Qt(null),It("processing"),Kr(!0);try{if(z.get("redirect_status")==="failed")throw Object.assign(new ge.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Yt,paypalFlopay:He}=await _s({publishableKey:se.publishableKey,paypalPublishableKey:se.paypalPublishableKey,billingApiUrl:F,locale:d,telemetry:a});oe=Er(He??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=(He??Yt)?.getRawProvider();if(!nt)throw Object.assign(new ge.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:ee,error:Xe}=await nt.retrievePaymentIntent(O);if(Xe)throw Object.assign(new ge.FloPayError(Xe.message??"Failed to retrieve PayPal payment status.","api_error",{code:Xe.code}),{checkoutMethod:"paypal"});let Ie=Zl(ee?.status);if(!ee||Ie==="failed")throw Object.assign(new ge.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let lt=typeof ee.payment_method=="string"?ee.payment_method:ee.payment_method?.id,te=Ie;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??ee.id,type:"card",threeDSecureActionResultTokenId:ee.id,isPaypal:!0}});if(T.type!=="success")throw Object.assign(new ge.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});te=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,We.invokeMerchantCallback)(()=>ln.current?.({status:te,paymentIntentId:ee.id,paymentMethodId:lt,checkoutMethod:"paypal"}))}catch(Yt){let He=Ro(Oa(Yt),se.sessionId),nt=He.checkoutMethod??"paypal",ee=(0,ge.isExpectedPaymentDecline)(He);if(oe)oe.performance({stage:"redirect_resume",durationMs:oe.elapsed(st),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ee?oe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):oe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(ee){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(He.message),Qt(He.message),ee||(0,We.invokeMerchantCallback)(()=>D.current?.(He)),Hn(nt,He,{code:He.code,declineCode:He.declineCode}),It("error"),await $a(400)}finally{Hs(),$u(),It(null),Qt(null),Kr(!1)}})())},[Hn,d,F,a,tr]);let Xr=(0,w.useRef)(null),Cn=(0,w.useMemo)(()=>rr?(0,ht.serializeCreateParams)(rr):"",[rr]),Po=(0,w.useRef)(rr);Po.current=rr,(0,w.useEffect)(()=>{G(e??"")},[e]),(0,w.useEffect)(()=>{fr.current=!1,Ir(H),Qt(null),er(!1),It(null)},[Cn,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 He=z.idempotencyKey===void 0?void 0:(0,ge.resolveIdempotencyKey)(z.idempotencyKey),nt=(0,ht.readCachedInlineSession)(O,se),ee=(0,ht.readCachedInlineIdempotencyKey)(O,se);nt?.canonicalIdentity===se&&ee&&ee.canonicalIdentity===void 0&&((0,ht.persistCachedInlineIdempotencyKey)(O,se,ee.idempotencyKey),ee={...ee,canonicalIdentity:se});let Xe=He??(ee?.canonicalIdentity===se?ee.idempotencyKey:void 0),Ie,lt=!1;oe.log({name:nt?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let te=nt?.sid??null,Re=null,Ae,Lt,T=!1;if(te)try{Re=await st.getUnifiedCheckoutSession(te,nt?.nonce),nt&&nt.canonicalIdentity===void 0&&((0,ht.legacyCachedSessionMatchesDraft)(Re.data.session,z)?((0,ht.persistCachedInlineSession)(O,se,te,nt.nonce??Re.data.session?.clientSecret),ee&&ee.canonicalIdentity===void 0&&((0,ht.persistCachedInlineIdempotencyKey)(O,se,ee.idempotencyKey),Xe??(Xe=ee.idempotencyKey))):((0,ht.clearCachedInlineCheckout)(O,se),ee=null,Xe=He,te=null,Re=null));let _=Re?.data.session?.status,le=Re?.data.session,me=le?.clientSecret||nt?.nonce;if(te&&le?.buyerIdentified===!1&&me&&(Lt=ta(st,te,me,z.account)),te&&Re&&_==="complete"){if((0,qn.wasSessionRecentlyCompleted)(te))return{sid:te,result:Re};(0,ht.clearCachedInlineCheckout)(O,se),te=null,Re=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=He):(0,ht.clearCachedInlineSession)(O,se),te=null}if(!te){!He&&(lt||!Xe)&&(Xe=(0,ge.resolveIdempotencyKey)(),Ie=Xe),Xe&&(0,ht.persistCachedInlineIdempotencyKey)(O,se,Xe);let _=oe.now(),le=0;oe.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let me={...z,idempotencyKey:Xe,avsCheck:!!Z,avsConfig:typeof Z=="object"?Z:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ks(ue,re)};Object.defineProperty(me,go.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ct=>{le=Math.max(le,ct)}}});let Be=()=>{zc(oe,"session_create",_,le)},Kt=ct=>{qc(oe,ct,"session_create",_,le)&&we({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,ge.isDetachedSessionEligible)(me)){let ct=await st.createDetachedSession(me);ct.claimed.catch(()=>{}),Re=ct.shell,te=ct.sessionId,Lt=ct.claim;let sr=oe.now();oe.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Ae=ct.claimed.then(gr=>{let Zr=gr.data.session?.id??ct.sessionId;return Zr&&(0,ht.persistCachedInlineSession)(O,se,Zr,gr.data.session?.clientSecret??ct.nonce),zc(oe,"session_claim",sr),Be(),gr},gr=>{throw(0,ht.clearCachedInlineSession)(O,se),qc(oe,gr,"session_claim",sr,0)&&we({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()-_,durationMode:"machine",requestCategory:"session_create",attempt:le,statusClass:"2xx",paymentMethodCategory:"card"})}else Re=await st.createAndFetchSession(me),Be()}catch(ct){throw Kt(ct),ct}te=Re.data.session?.id??te??"",te&&!Ae&&(0,ht.persistCachedInlineSession)(O,se,te,Re.data.session?.clientSecret)}let h=Re?.data.session;return!Lt&&te&&h?.buyerIdentified===!1&&h.clientSecret&&(Lt=ta(st,te,h.clientSecret,z.account)),{sid:te??"",result:Re,sdkGeneratedIdempotencyKey:Ie,...Ae?{claimed:Ae}:{},...Lt?{claim:Lt}:{},...T?{claimRequiresIdentity:!0}:{}}}finally{Yt||Ha(oe)}}let un=(0,w.useRef)(An);Bo(()=>{un.current=An},[An]);let oo=(0,w.useCallback)(async(z,O)=>{let se=Po.current;if(!se)throw new ge.FloPayError("createSession is required to bootstrap checkout.","validation_error");let oe=vs(se,z),st=(0,ht.serializeCreateParams)(oe),Yt=(0,ht.hashCreateParams)(oe),He=zi.get(st);if(!He){let Xe={canonicalIdentity:st,promise:un.current(oe,Yt,st),consumers:0,settled:!1};He=Xe,zi.set(st,Xe);let Ie=()=>{Xe.settled=!0,Uc(st,Xe)};Xe.promise.then(Ie,Ie)}He.consumers+=1;let nt=!1,ee=()=>{nt||(nt=!0,He.consumers-=1,Uc(st,He))};O?.(ee);try{let Xe=await He.promise;Xr.current=st,z&&(on(Yr),gt(h=>Hl(h,z)));let{sid:Ie,result:lt,claimed:te,claim:Re,claimRequiresIdentity:Ae}=Xe;if(ar.current=Re,an(Ae===!0),jt(lt),lt.data.session&&je(lt.data.session),Ie&&G(Ie),te){Wt.current+=1;let h=Wt.current;qr.current=te,Ur(!0),te.then(_=>{Wt.current===h&&(qr.current===te&&(qr.current=null),jt(_),_.data.session&&je(_.data.session),Ur(!1),an(!1))},_=>{Wt.current===h&&(qr.current===te&&(qr.current=null),Ur(!1),an(!1),Zt(_ instanceof ge.FloPayError?_:new ge.FloPayError(_ instanceof Error?_.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,Ie||lt.data.session?.id)});return ce(Lt,T),At(!1),Xe}catch(Xe){throw Xr.current===st&&(Xr.current=null),Xe}finally{O||ee()}},[Yr,ce,d,F,a]),bn=(0,w.useRef)(Gt);bn.current=Gt;let ao=(0,w.useRef)(oo);ao.current=oo;let io=(0,w.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,w.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,w.useCallback)(async()=>{await qr.current},[]),Bn=(0,w.useCallback)(async()=>(await Fn(),{proceed:!0}),[Fn]);(0,w.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(Cn&&st)return Dr(dn),At(!1),Xr.current===Cn?oe:(je(Kl(st,ne)),(async()=>{let nt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ee=dn==="auto"&&!fr.current&&!nt;ee&&(Ir(null),Qt(null),It("processing"));let Xe=!1;try{let Ie=await ao.current(void 0,Ae=>{O=Ae});Xe=!0;let lt=Ie.result.data.session??null;Mr.current=Es(Ie.result);let te=Ws(Ie.result),Re=(0,qn.wasSessionRecentlyCompleted)(Ie.sid||lt?.id);if(!z&&ee&&lt&&!te&&!Re){fr.current=!0,await qu(Cn,Ie.sdkGeneratedIdempotencyKey,()=>bn.current(lt,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Ie.result.autoProcessingError,initialAutoProcessingPending:Ie.result.autoProcessingPending,autoProcessingAttempted:Ie.result.autoProcessingAttempted,sessionId:Ie.sid||lt.id}));return}!z&&ee&&((te||Re)&&(fr.current=!0),It(null),Qt(null))}catch(Ie){if(z)return;let lt=ui(Ie);if(ee&&lt==="session_auto_completed"){fr.current=!0,It("success"),await $a(600),z||((0,We.invokeMerchantCallback)(()=>{ln.current?.({status:"succeeded"})}),It(null),Qt(null));return}if(ee&&(It(null),Qt(null)),!Xe){let Re=Xl(Ie),Ae=(0,ge.toPublicCheckoutInitError)(Ie,Re?{stage:"provider_load",provider:"stripe",...Re}:{stage:"session_request"});(Re||!(Ie instanceof ge.FloPayError))&&(0,We.invokeMerchantCallback)(()=>D.current?.(Ae)),Zt(Ae);return}let te=Ie instanceof ge.FloPayError?Ie:new ge.FloPayError(Ie instanceof Error?Ie.message:"Failed to create session","api_error");Zt(te)}finally{O?.(),O=void 0}})(),()=>{oe(),O?.()});At(!0);async function Yt(){let nt=!1,ee=!1,Xe=null;try{let Ie=new go.PaymentAPI(F,{telemetry:!1}),lt=await Ie.getUnifiedCheckoutSession(W,t);if(ee=!0,Xe=lt,z)return;jt(lt);let te=lt.data.session??null;if(je(te),!te)throw new ge.FloPayError("No session data returned","api_error");let Re=te.checkoutMode;if(Re==="setup")throw new ge.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(te.status==="authorized"){At(!1),(0,We.invokeMerchantCallback)(()=>{ln.current?.(co(te,W)),$t.current?.(te.successUrl??"")});return}if(te.status==="complete"){At(!1),(0,We.invokeMerchantCallback)(()=>{$t.current?.(te.successUrl??"")});return}if(te.status==="expired")throw di(te);nt=!0;let Ae=ne??Re??"full";Dr(Ae),Wt.current+=1;let Lt=te.clientSecret||t;ar.current=te.buyerIdentified===!1&&Lt?ta(Ie,W,Lt,{...te.customer?.id?{userId:te.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 _=He(lt);try{if(await bn.current(te,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>_,sessionId:W||te.id}),z)return;await _,z||At(!1);return}catch{if(z)return;await _,z||At(!1);return}}await He(lt),z||At(!1)}catch(Ie){if(z)return;let lt=$l(Ie,nt);if(nt&&we({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 te=lt?.stage==="provider_load",Re="session_request";te?Re="provider_load":ee&&(Re="post_session");let Ae=(0,ge.toPublicCheckoutInitError)(Ie,{stage:Re,provider:"stripe",sessionId:W||void 0});(te||!(Ie instanceof ge.FloPayError))&&(0,We.invokeMerchantCallback)(()=>D.current?.(Ae)),Zt(Ae),At(!1)}}async function He(nt){let{flopay:ee,paypalFlopay:Xe,...Ie}=await $s(nt,{billingApiUrl:F,locale:d,telemetry:a});Mr.current={publishableKey:Ie.publishableKey,paypalPublishableKey:Ie.paypalPublishableKey},ce(ee,Xe),_t(0)}return Yt(),oe},[ne,Cn,dn,J,t,x,f]);let vo=(0,w.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,w.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,ge.resolveDirectPaypalConfig)(qt?.data.paypal,Ze),Dn=Ws(qt),Wr=(0,w.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,ge.isMountableVaultBlock)(K?.vault)||(0,Nn.canRecoverHostedCardForm)(K))),nr=(0,w.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),gn=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,gn]});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||he)&&O(zo),f&&O(zo),(0,A.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),gn]})}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); } }"})]}),gn]})}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:Ce,paymentMethodLayout:Pe,showPayPal:x,showStripe:f,showApplePay:m,showGooglePay:he,theme:ve,buttonsTheme:bt,buttonsStyles:$e,cardButtonContent:L,cardBackButtonContent:mt,cardTitleContent:xe})}),gn]}):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:[Ht&&(0,A.jsx)(la,{icon:!1,children:Ht}),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:Ce,runBeforeButtonClick:Bn,onInitializationStateChange:ir,allowAutomaticRetry:Tr===0,session:K,telemetry:a,telemetryContext:tr,onInstrument:u,debug:I},`${S}:paypal-init-${Tr}`)})]})}),gn]}):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:[Ht&&(0,A.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ht}),be?be({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"})]})},S)}),gn]}):(!kt||!Wr)&&!(Ar&&Hr==="full")?(0,A.jsx)(A.Fragment,{children:gn}):(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:[Ht&&(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:Ht}),(0,A.jsx)(Gu,{sessionId:W,nonce:K?.clientSecret||void 0,billingApiUrl:F,session:K,submitLabel:j,walletPresentation:U,paymentMethodLayout:Pe,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,ge.buildCheckoutDisplayData)(K).total*100):0,currency:K?.currency?.toLowerCase()??"usd",onComplete:v,onError:P,onDecline:k,onCancel:V,error:Ht,onErrorChange:Ir,showPayPal:x,showStripe:f,walletPresentation:U,enabledPaymentMethods:br?[]:_e??qt?.data.stripe?.enabledPaymentMethods??K?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:qt?.data.stripe?.enabledPaymentMethodCountries,showApplePay:m,showGooglePay:he,layout:re,paymentMethodLayout:Pe,moreOptionsLabel:fe,theme:ve,buttonsTheme:bt,buttonsStyles:$e,appearance:Ye,cardButtonContent:L,cardBackButtonContent:mt,cardTitleContent:xe,onButtonClick:Ce,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:E,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})]},S)}),gn]})}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:w.default.Children.map(y,v=>{if(!w.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:w.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,w.useState)(!1),E=(0,w.useMemo)(()=>(0,ge.resolveTheme)(d),[d]),N=(0,w.useMemo)(()=>{let m=E?.buttonsLayout??(0,ge.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},[E,p,y]),x=E?.buttonsLayout?.cardButton?.borderRadius??E?.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",he=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:he,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:he,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:he,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:he,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
- `})]})}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});
47
+ `})]})}let _e={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:[ge.DEFAULT_PAYMENT_METHOD_ORDER.map(m=>(0,A.jsx)(w.default.Fragment,{children:_e[m]},m)),(0,A.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var _n=require("react/jsx-runtime"),Xu=44;function $c(e){return new Promise(t=>setTimeout(t,e))}function Ju(e,t){return e instanceof fn.FloPayError?e:new fn.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:E,billingApiUrl:N,locale:x,theme:f,appearance:U,buttonsTheme:_e,buttonsStyles:m,onSuccess:he,onError:I,onDecline:re,children:Pe,disabled:fe=!1,type:ve="button",style:bt,...$e}){let L=(0,Pt.useMemo)(()=>(0,fn.resolveBillingApiUrl)(N),[N]),mt=(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:E}),[v,g,s,k,r,d,p,y,P,V,E]),[xe,Ge]=(0,Pt.useState)(!1),[Ce,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)(he),be=(0,Pt.useRef)(I),ot=(0,Pt.useRef)(re),F=(0,Pt.useCallback)(b=>bi(ue,async S=>{try{return await b(S)}catch(ye){throw S.aborted?ca(ye):ye}}),[]);(0,Pt.useEffect)(()=>{ne.current=ae},[ae]),(0,Pt.useEffect)(()=>{Me.current=he},[he]),(0,Pt.useEffect)(()=>{be.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 b=S=>{S.key==="Escape"&&H(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let rt=(0,Pt.useCallback)((b,S=Ba)=>{ot.current?.(kr(S,b,{code:b.code,declineCode:b.declineCode}))},[]),Ye=(0,Pt.useCallback)(async b=>{Ze.current&&(qe(null),Le(b.result.status==="authorized"),q("success"),await $c(600),Ze.current&&(0,We.invokeMerchantCallback)(()=>Me.current?.(b)))},[]),at=(0,Pt.useCallback)(async(b,S)=>{if(!Ze.current)return;S?.emitDecline&&(0,fn.isExpectedPaymentDecline)(b)||be.current?.(b),S?.emitDecline&&rt(b,S.method),qe(b.message),Le(!1),q("error"),await $c(400)},[rt]),Rt=(0,Pt.useCallback)(async(b,S,ye)=>{let Se=b.data.session??null;if(!Se)throw Ro(new fn.FloPayError("No session data returned","api_error"),S);let ft=Se.clientSecret||t;if(uo(Se)){await Ye({result:co(Se,S),session:Se,sessionId:Se.id||S,autoCompleted:!1});return}if(Se.status==="expired")throw Ro(di(Se),Se.id||S);try{if(b.autoProcessingPending){let et=b.autoProcessingPending,we=new ji.PaymentAPI(L),ut=await F(G=>we.waitForCheckoutSessionCompletion(et.sessionId,{initialDelayMs:et.retryAfterMs,nonce:ft,statusUrl:et.statusUrl,signal:G})),u=ko(ut,Se),M=ut.autoProcessingError?.type==="3ds_required"&&ut.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ut.autoProcessingError.nextActionRedirectUrl}:null;if(M&&S&&ft){let G=Da(L,S,Se),W=await F(J=>da(M,{billingApiUrl:L,sessionId:S,nonce:ft,session:Se,signal:J,telemetry:!0,...G.telemetry?{challengeTelemetry:G.telemetry}:{}})).finally(G.release);await Ye({result:W,session:Se,sessionId:Se.id||S,autoCompleted:!1});return}if(ut.autoProcessingError)throw eo(ut.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:ut.autoProcessingError.checkoutMethod});if(!uo(u))throw ra(u);await Ye({result:co(u,S),session:u,sessionId:u.id||S,autoCompleted:!1});return}if(b.autoProcessingError){let et=b.autoProcessingError.nextActionRedirectUrl;if(b.autoProcessingError.type==="3ds_required"&&et&&S&&ft){let we=await F(G=>mc({billingApiUrl:L,sessionId:S,nonce:ft,nextActionRedirectUrl:et,signal:G}));if(we.status==="declined")throw eo({type:we.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:we.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let u=await new ji.PaymentAPI(L).waitForCheckoutSessionCompletion(S,{initialDelayMs:0,nonce:ft}),M=ko(u,Se);if(!uo(M))throw eo({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await Ye({result:co(M,S),session:M,sessionId:M.id||S,autoCompleted:!1});return}throw eo(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(ye?.fromCreateSession&&b.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:S??Se.id,session:Se,nonce:ft});if(Vt.type==="next_action_required"&&ft){let et=S??Se.id,we=Da(L,et,Se),ut=await F(u=>da(Vt,{billingApiUrl:L,sessionId:et,nonce:ft,session:Se,signal:u,telemetry:!0,...we.telemetry?{challengeTelemetry:we.telemetry}:{}})).finally(we.release);await Ye({result:ut,session:Se,sessionId:Se.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:Se,sessionId:Se.id||S,autoCompleted:!1})}catch(Vt){let et=Se.id||S,we=Ro(Oa(Vt),et);if(we.code==="three_ds_aborted")return;if(we.code==="checkout_processing_timeout"){if(!Ze.current)return;j(we.message),(0,We.invokeMerchantCallback)(()=>be.current?.(we));return}await at(we,{emitDecline:!0,method:we.checkoutMethod??Ba}),Zu(we,et)&&et&&Ze.current&&H({sessionId:et,errorMessage:we.message,nonce:ft||void 0,payPalOrderId:we.orderId})}},[t,L,F,at,Ye]),qt=(0,Pt.useCallback)(async b=>{if($e.onClick?.(b),!(b.defaultPrevented||fe||xe)){if(H(null),j(null),e&&mt){let S=new fn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await at(S),Ze.current&&(q(null),qe(null));return}if(!e&&!mt){let S=new fn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await at(S),Ze.current&&(q(null),qe(null));return}Ge(!0),qe(null),Le(!1),q("processing");try{let S=new ji.PaymentAPI(L);if(e){let ye=await S.getUnifiedCheckoutSession(e,t);await Rt(ye,e);return}try{let ye=await S.createAndFetchSession({...mt});await Rt(ye,ye.data.session?.id??null,{fromCreateSession:!0})}catch(ye){if(ui(ye)==="session_auto_completed"){await Ye({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ye}}catch(S){await at(Ro(Ju(S,"Automatic payment failed. Please try again."),e))}finally{Ze.current&&(q(null),qe(null),Ge(!1))}}},[$e.onClick,mt,fe,xe,t,Rt,L,e,at,Ye]),jt=(0,Pt.useCallback)(b=>{let S=ne.current;H(null),Me.current?.({result:b,session:null,sessionId:S?.sessionId??null,autoCompleted:!1})},[]),kt=(0,Pt.useCallback)(b=>{be.current?.(b)},[]),Fe=(0,Pt.useCallback)(b=>{ot.current?.(b)},[]),pe=(0,Pt.useMemo)(()=>(0,fn.resolveTheme)(f),[f]),Ne=(0,Pt.useMemo)(()=>{let b=pe?.buttonsLayout??(0,fn.resolveButtonsLayoutTheme)(_e);return m?{...b,...m,cardButton:{...b.cardButton,...m.cardButton}}:b},[pe,_e,m]),Qe=(0,Pt.useMemo)(()=>{let b=pe?.appearance;return U?b?{...b,...U,variables:{...b.variables,...U.variables}}:U:b},[U,pe]),X=Qe?.variables,Mt=X?.colorPrimary??"#4A49FF",Jt=X?.colorPrimaryHover??(0,js.darkenHex)(Mt,.12),K=X?.borderRadius??"8px";return(0,_n.jsxs)(_n.Fragment,{children:[(0,_n.jsx)("button",{...$e,type:ve,onClick:qt,disabled:fe||xe,"aria-busy":xe,style:{width:"100%",...Pe===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:b=>{$e.onMouseEnter?.(b),!b.defaultPrevented&&!fe&&!xe&&(pe||X?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Jt)},onMouseLeave:b=>{$e.onMouseLeave?.(b),!b.defaultPrevented&&(pe||X?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Mt)},onMouseDown:b=>{$e.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{$e.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:(0,_n.jsx)(Qo,{content:Pe})}),Q&&(0,_n.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Q}),Ce&&(0,_n.jsx)(yn,{status:Ce,errorMessage:Z,authorized:Oe}),ae&&(0,_n.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:b=>{b.target===b.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,_n.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,_n.jsx)(qi,{sessionId:ae.sessionId,nonce:ae.nonce,checkoutMode:"full",billingApiUrl:L,locale:x,theme:f,...Qe?{appearance:Qe}:{},buttonsTheme:_e,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:E}){let[N,x]=(0,Xt.useState)(null),[f,U]=(0,Xt.useState)(null),[_e,m]=(0,Xt.useState)(null),[he,I]=(0,Xt.useState)(null),[re,Pe]=(0,Xt.useState)(null),fe=(0,Xt.useRef)(!1),ve=(0,Xt.useRef)(!1),{vaultTheme:bt,surface:$e,overlayTheme:L}=(0,Xt.useMemo)(()=>Vi({theme:a,appearance:d,buttonsStyles:p}),[a,d,p]),mt=(0,Xt.useMemo)(()=>(0,za.mergeCardSetupSurface)($e,s),[$e,s]),xe=(0,Xt.useRef)(v),Ge=(0,Xt.useRef)(E),Ce=(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=E,Ce.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,We.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,We.invokeMerchantCallback)(()=>Ge.current?.(ue))}})(),()=>{j=!1,H.destroy()}},[r,t,e,n]),(0,Xt.useEffect)(()=>{if(!N)return;let j=!1;ve.current=!1,fe.current=!1;let ae=N.on("submitting",()=>{fe.current=!0,Pe(null),I("processing")}),H=N.on("complete",ne=>{Oe.current=!0,fe.current=!1,I("success"),(async()=>(await new Promise(Me=>setTimeout(Me,600)),!ve.current&&(ve.current=!0,(0,We.invokeMerchantCallback)(()=>{Ce.current?.({status:"succeeded",sessionId:e,...ne.paymentMethod?{paymentMethod:ne.paymentMethod}:{}})}),j||I(null))))()}),Ze=N.on("decline",ne=>{Oe.current=!0,fe.current=!1,Pe(ne.message??null),I("error"),(0,We.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]),_e?(0,ro.jsx)("div",{role:"alert",children:_e.message}):!N||!f?.html?(0,ro.jsx)(ro.Fragment,{children:y}):(0,ro.jsxs)(ro.Fragment,{children:[he&&(0,ro.jsx)(yn,{status:he,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:mt,onReady:()=>{(0,We.invokeMerchantCallback)(()=>xe.current?.())},onValidation:j=>{(0,We.invokeMerchantCallback)(()=>qe.current?.(j))},onError:j=>{if(!j)return;fe.current&&(fe.current=!1,Pe(j),I("error"),setTimeout(()=>I(null),400));let ae=ho(new Error(j),{code:"card_setup_widget_failed",retryable:!0});(0,We.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),E=(0,qo.useRef)({onSubmitting:v,onConfirmed:P,onFailed:g,onAbandoned:k});E.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}),_e={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}:{}}),he=V.current;if(!x||!he)return;if(!m?.Buttons)throw new In.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let I=m.Buttons({createVaultSetupToken:async()=>{E.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 Pe=re.vaultSetupToken;if(!Pe)throw new In.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let fe=await U.processPayment(_e.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:Pe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:In.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:_e});if(!fe.ok)throw new In.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:fe.status});x&&E.current.onConfirmed()},onCancel:()=>{x&&E.current.onAbandoned()},onError:re=>{if(!x)return;let{popupBlocked:Pe}=(0,Ee.classifyExternalMethodFailure)(re,{inAppBrowser:N,handoffObserved:!1});E.current.onFailed(Pe?new Error((0,Ee.buildExternalMethodRecoveryMessage)("PayPal",!0,N)):re,{code:Pe?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>I.close(),await I.render(he)}catch(m){if(!x)return;E.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,Ee.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:E}){let N=(0,no.useStripe)(),x=(0,no.useElements)(),[f,U]=(0,rn.useState)(!1),[_e,m]=(0,rn.useState)("loading"),[he,I]=(0,rn.useState)(!1),[re,Pe]=(0,rn.useState)(!1),fe=(0,rn.useRef)(!1),[ve]=(0,rn.useState)(()=>(0,Zn.detectPayPalEnvironment)()),[bt,$e]=(0,rn.useState)(!1),L=(0,rn.useCallback)((Z,qe)=>{if((0,Ee.classifyExternalMethodFailure)(Z,{inAppBrowser:ve.inAppBrowser,handoffObserved:!1}).popupBlocked){$e(!0),k(new Error((0,Ee.buildExternalMethodRecoveryMessage)(Zc(e),!0,ve.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}k(qe.message===void 0?Z:new Error(qe.message),{code:qe.code,retryable:!0})},[ve.inAppBrowser,e,k]),mt=(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)(ve,"auto",bt?"blocked":ve.popupCapability)==="redirect",Ce=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:_e,borderRadius:Ce,children:(0,$r.jsx)(no.ExpressCheckoutElement,{options:{..._i,paymentMethods:Ei([e])},onReady:Z=>{let qe=La(Z,[xe]);m(qe),qe==="unavailable"&&E()},onLoadError:()=>{m("load_error"),E()},onConfirm:Z=>{mt(Z)}})})]});let q=Zc(e);return(0,$r.jsxs)($r.Fragment,{children:[he?(0,$r.jsx)(ki,{method:e,themeId:p,hasNextStep:!0,highlighted:re,disabled:f,onClick:()=>Pe(Z=>!Z),backgroundColor:y?.cardButton?.backgroundColor,borderColor:y?.cardInputBorder,textColor:y?.cardButton?.color,borderRadius:Ce}):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:()=>E(),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:()=>{mt()},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:E,onValidation:N,onError:x}){let[f]=(0,Ke.useState)(ya.readSetupRedirectReturn),[U,_e]=(0,Ke.useState)(null),[m,he]=(0,Ke.useState)(!1),[I,re]=(0,Ke.useState)(null),[Pe,fe]=(0,Ke.useState)(null),[ve,bt]=(0,Ke.useState)(null),[$e,L]=(0,Ke.useState)(null),[mt,xe]=(0,Ke.useState)(()=>new Set),Ge=(0,Ke.useRef)(mt),Ce=(0,Ke.useRef)(null);Ce.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]),be=(0,Ke.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:g,onComplete:k,onDecline:V,onCancel:E,onValidation:N,onError:x});be.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:g,onComplete:k,onDecline:V,onCancel:E,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,We.invokeMerchantCallback)(()=>{be.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,We.invokeMerchantCallback)(()=>{be.current.onComplete?.({status:"succeeded",sessionId:be.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,We.invokeMerchantCallback)(()=>{be.current.onDecline?.({status:"declined",sessionId:be.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,We.invokeMerchantCallback)(()=>be.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)(be.current.billingApiUrl),{telemetry:be.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(be.current.sessionId,be.current.nonce);if(G())return;let At=B.data.session?.status;if(At==="complete"){he(!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});_e(null),he(!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"){he(!0),_e(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;_e(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,We.invokeMerchantCallback)(()=>be.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=Ce.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,We.invokeMerchantCallback)(()=>be.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=Ce.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=$e?(0,yr.jsx)(yn,{status:$e.status,errorMessage:$e.message,...(0,Br.setupOverlayLabels)($e.wording),successNote:null,...Ze?{theme:Ze}:{}}):null;if(ve)return(0,yr.jsx)("div",{role:"alert",children:ve.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,b=(0,_r.resolveBillingApiUrl)(a),S=s===void 0?{}:{telemetry:s},ye=Mt.stripe.filter(({method:u})=>!mt.has(u)),Se=mt.has("paypal")?null:Mt.paypal,ft=!!(Mt.card&&I&&Pe?.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:b,...S,...ue?{appearance:ue}:{},...ne?{buttonsLayout:ne}:{},...typeof d=="string"?{themeId:d}:{},...Rt,onFailed:kt(u),onUnavailable:Qe(u)})})})},u),et=ye.filter(({method:u})=>(0,Br.stripeMethodCategory)(u)==="wallet"),we=ye.filter(({method:u})=>(0,Br.stripeMethodCategory)(u)!=="wallet"),ut=ye.length>0||Se!==null;return(0,yr.jsxs)(yr.Fragment,{children:[X,ut?(0,yr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[et.map(Vt),Se?(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:Se.clientId,...Se.environment?{environment:Se.environment}:{},...Mt.currency?{currency:Mt.currency}:{},sessionId:r,nonce:n,billingApiUrl:b,customer:Jt,...S,...Rt,onFailed:kt("paypal"),onUnavailable:Qe("paypal")})})})}):null,we.map(Vt)]}):null,ft&&ut?(0,yr.jsx)(qa,{label:"or add a card"}):null,ft&&I&&Pe?.html?(0,yr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,yr.jsx)(_o,{capture:I,html:Pe.html,messageToken:Pe.messageToken,expectedOrigin:Pe.expectedOrigin,verificationRequired:Pe.verificationRequired,theme:ae,containerStyle:Me,onReady:()=>{(0,We.invokeMerchantCallback)(()=>be.current.onReady?.())},onValidation:u=>{(0,We.invokeMerchantCallback)(()=>be.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});