@flopay/react 1.17.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var zd=Object.create;var fi=Object.defineProperty;var qd=Object.getOwnPropertyDescriptor;var jd=Object.getOwnPropertyNames;var Vd=Object.getPrototypeOf,Wd=Object.prototype.hasOwnProperty;var $d=(e,t)=>{for(var r in t)fi(e,r,{get:t[r],enumerable:!0})},Xl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of jd(t))!Wd.call(e,a)&&a!==r&&fi(e,a,{get:()=>t[a],enumerable:!(n=qd(t,a))||n.enumerable});return e};var Rs=(e,t,r)=>(r=e!=null?zd(Vd(e)):{},Xl(t||!e||!e.__esModule?fi(r,"default",{value:e,enumerable:!0}):r,e)),Hd=e=>Xl(fi({},"__esModule",{value:!0}),e);var Ap={};$d(Ap,{DirectPayPalButton:()=>Oa,FloPayAutomaticPaymentButton:()=>od,FloPayCardSetup:()=>ad,FloPayCardSetupError:()=>Qa,FloPayCheckout:()=>Gi,FloPayPaymentMethodSetup:()=>gd,FloPayProvider:()=>La,SplitCardForm:()=>Wi,VaultCardFields:()=>Eo,dropThirdPartyOnlyError:()=>Pd.dropThirdPartyOnlyError,useCheckout:()=>cc,useFloPay:()=>uo,usePayPalFloPay:()=>vi});module.exports=Hd(Ap);var Pd=require("@flopay/shared");var Yi=require("@flopay/js"),wr=require("@flopay/shared"),ct=require("react");var tr=require("react/jsx-runtime");function Kd(){return(0,tr.jsxs)(tr.Fragment,{children:[(0,tr.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,tr.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,tr.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,tr.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,tr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Gd(){return(0,tr.jsx)(tr.Fragment,{children:"Go back"})}function Yd(){return(0,tr.jsx)(tr.Fragment,{children:"Secure card checkout"})}function na(e){return e!==void 0&&(e===""||e===null||e===!1)}function oa({content:e}){return(0,tr.jsx)(tr.Fragment,{children:e===void 0?(0,tr.jsx)(Kd,{}):e})}function aa({content:e}){return(0,tr.jsx)(tr.Fragment,{children:e===void 0?(0,tr.jsx)(Gd,{}):e})}function Ta({content:e}){return(0,tr.jsx)(tr.Fragment,{children:e===void 0?(0,tr.jsx)(Yd,{}):e})}var Rt=require("@flopay/shared"),zn=require("@flopay/shared"),la=require("@flopay/shared"),Bo=require("@flopay/shared");function ks(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Rt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Xd(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 Jl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,Rt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,Rt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function Zl(e,t){if(t&&(!(e instanceof Rt.FloPayError)||e.type==="authentication_error"))return ks(e);if(!(e instanceof Rt.FloPayError&&Xd(e))){if(!t&&!(e instanceof Rt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Rt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Rt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Rt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ia(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,Rt.isCardHolderNamePlaceholder)(d.firstName,d.lastName);if(!(0,Rt.isValidEmail)(d.email))return Promise.reject(new Rt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[b,P]of Object.entries(d)){if(p&&b.endsWith("Name")||typeof P!="string")continue;let h=P.trim();h&&(y[b]=h)}return a=e.claimCheckoutSession(t,r,{accountData:y}),a.catch(()=>{}),a}}function Ql(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Es(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ec(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 _s(e,t){return t?{...e,...t}:e}function Cr(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 tc=new WeakMap;function rc(e,t){return typeof e=="object"&&e!==null&&tc.set(e,t?{sessionId:t}:{}),e}function nc(e){return typeof e=="object"&&e!==null?tc.get(e):void 0}function wo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function so(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function lo(e){return e?.status==="authorized"||e?.status==="complete"}function Ro(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 oc(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function gi(e){let t=oc(e);return new Rt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function hi(e){return e instanceof Rt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function sa(e){return oc(e)?new Rt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Rt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Rt.FloPayError(Rt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function Ma(e,t){return e==="processing"||(0,Rt.isMoneySettledOutcome)(e,t)}function ac(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function ic(e,t){let r=e;if((0,Rt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:d}=await r.retrieveSetupIntent(t);if(d)throw new Rt.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 Rt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var Jd=["apple_pay","google_pay"];function sc(e,t="automatic",r){let n=(0,Rt.resolveSetupFutureUsage)(r,Jd,"wallet");return{...(0,Rt.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Zd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Is(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:Zd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Aa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var yo=require("@flopay/js"),le=require("@flopay/shared"),S=Rs(require("react"),1);var Ts=require("react"),kn=(0,Ts.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),qn=(0,Ts.createContext)({session:null,loading:!1,error:null});var ki=require("@flopay/js"),ze=require("@flopay/shared"),yc=require("@paypal/paypal-js"),R=require("react");var Pi=require("@flopay/shared"),jn=require("react"),En=require("@flopay/shared"),co=require("react/jsx-runtime");function ca(){let[e,t]=(0,jn.useState)(null),r=(0,jn.useRef)(null),n=(0,jn.useRef)(0),a=(0,jn.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,jn.useCallback)(d=>{let p=r.current;r.current=null,t(null),p?.(d)},[]);return(0,jn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function da({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[d,p]=(0,jn.useState)(e.email?.trim()??""),y=(0,Pi.isValidEmail)(d.trim());return(0,co.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,co.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,co.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,co.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:d,onChange:b=>p(b.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,co.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,co.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,co.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 lc=require("@flopay/shared"),xa=require("react");function uo(){return(0,xa.useContext)(kn).flopay}function vi(){return(0,xa.useContext)(kn).paypalFlopay??null}function cc(){return(0,xa.useContext)(qn)}function dc(){return(0,xa.useContext)(kn).billingApiUrl||(0,lc.resolveBillingApiUrl)()}var Qd=require("@flopay/shared"),Zn=require("@flopay/shared"),Qn=require("@flopay/shared");var ua=require("@flopay/shared"),Do=require("react");var Ci=require("react"),Oo=typeof window>"u"?Ci.useEffect:Ci.useLayoutEffect;var Ms=require("@flopay/shared");function pa(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 Oo(()=>{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,ua.projectFloInstrument)(d);if(p){if(ua.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,ua.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var Ge=require("@flopay/shared");var uc=require("react"),Fa=(0,uc.createContext)(null);function bi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Si="provider.callback.ignored";function wi(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var eu=Symbol.for("@flopay/js.telemetry.bridge.v1"),tu=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ru(){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 nu(e){let t=ru(),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 Ri(e){let t=globalThis[tu];return nu(t?.(e)??{})}function br(e){if(e)return e[eu]}var hr=require("react");function Ba(e,t){let r=(0,hr.useRef)(0),n=(0,hr.useRef)(null),a=(0,hr.useRef)(null),s=(0,hr.useRef)(e),d=(0,hr.useRef)(t?.onHandoffObserved),p=(0,hr.useRef)(t?.defersMissingTerminal),y=(0,hr.useRef)(t?.onMissingTerminalDeferred);(0,hr.useEffect)(()=>{s.current=e,d.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let b=(0,hr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),P=(0,hr.useCallback)(f=>{b();let H=r.current+1;return r.current=H,n.current=null,a.current={generation:H,method:f,timer:null,yieldedControl:!1},H},[b]),h=(0,hr.useCallback)(f=>{let H=a.current;return f!==void 0&&H?.generation!==f?!1:(b(H),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[b]),E=(0,hr.useCallback)(f=>{let H=a.current,X=f??H?.generation??r.current;(f===void 0||H?.generation===f)&&(b(H),a.current=null),n.current=X},[b]),V=(0,hr.useCallback)(f=>n.current===(f??r.current),[]),W=(0,hr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),w=(0,hr.useCallback)(()=>{let f=a.current;f&&(b(f),!f.yieldedControl&&(f.yieldedControl=!0,d.current?.(f.method)))},[b]),T=(0,hr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(b(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))},[b]);return(0,hr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?T():w()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",w),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",w),window.removeEventListener("focus",T),b()}},[b,w,T]),{startAttempt:P,finishAttempt:h,invalidateAttempt:E,isAttemptInvalidated:V,isAttemptCurrent:W,generationRef:r}}var _n=require("react/jsx-runtime"),Ei=45,ou=1e3,au=11e3,pc="paypal_intent_settled",iu={width:"100%",minHeight:Ei,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"},su={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 lu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:su[e.kind]??null}}function mc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,ke.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function cu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function fc({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:d,environment:p,currency:y,isSubscription:b,providerObjectType:P,approvalPresentation:h,onTokenizedBody:E,onComplete:V,onErrorChange:W,onDecline:w,onCancel:T,onTechnicalFailure:f,isProcessing:H=!1,onLoadStateChange:X,onInitializationStateChange:v,allowAutomaticRetry:Se=!0,onButtonClick:M,runBeforeButtonClick:oe,session:ye,existingOrderId:Ee,telemetry:ce,telemetryContext:bt,onInstrument:yt,debug:q=!1}){let He=uo(),Ke=pa(yt,e),Le=(0,R.useMemo)(()=>{if(He)return null;let z=Ri({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:ze.SDK_VERSION,enabled:ce!==!1});return z.setCheckoutContext(bt??{}),z.beginCheckout(bt??{}),z},[r,He,ce,bt?.checkoutMode,bt?.layout]),Pe=(0,R.useMemo)(()=>br(He),[He]);(0,R.useEffect)(()=>()=>{Le&&Le.flush().catch(()=>{}).finally(()=>Le.destroy())},[Le]);let Y=(0,R.useMemo)(()=>({error:z=>{Pe?Pe.error(z):Le?.error(z),Ke({class:"technical_error",errorCode:z.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":z.errorCode,requestCategory:z.requestCategory,provider:z.provider})},log:z=>{Pe?Pe.log(z):Le?.log(z),Ke({class:"lifecycle",name:z.name,provider:z.provider})},performance:z=>{Pe?Pe.performance(z):Le?.performance(z)},terminal:z=>{Pe?Pe.terminal(z):Le?.terminal(z)},startTiming:()=>Pe?.now()??Le?.now()??0,elapsed:z=>Pe?.elapsed(z)??Math.max(0,(Le?.now()??z)-z)}),[Ke,Pe,Le]),K=(0,R.useRef)(null),tt=(0,R.useRef)(0),we=(0,R.useRef)(null),qe=(0,R.useRef)(null),Q=(0,R.useRef)(null),j=(0,R.useContext)(Fa),fe=(0,R.useRef)(null);fe.current||(fe.current=bi());let J=j??fe.current,ft=(0,R.useRef)(null),de=(0,R.useRef)(!1),[ve,_e]=(0,R.useState)(!1),[Me,je]=(0,R.useState)(!1),[ge,rt]=(0,R.useState)(0),dt=(0,R.useRef)(0),[ut,ae]=(0,R.useState)(!1),Dt=(0,R.useRef)(!1),Lt=(0,R.useRef)(!1),[Ut,Ie]=(0,R.useState)(!1),[he,gt]=(0,R.useState)(!1),{request:Qe,collect:Mt,finish:nt}=ca(),St=(0,R.useRef)({sessionId:e,required:(0,ze.paypalProviderIdentityRequired)(n,ye)});St.current.sessionId!==e&&(St.current={sessionId:e,required:(0,ze.paypalProviderIdentityRequired)(n,ye)});let ht=St.current.required,ne=(0,R.useMemo)(()=>r.replace(/\/+$/,""),[r]),kt=ye?.gateways?.paypal?.providerObjectType??P,D=kt??(b?"subscription":"order"),[Ye]=(0,R.useState)(Zn.detectPayPalEnvironment),_=ye?.gateways?.paypal?.approvalPresentation??h,A=(0,Qn.resolvePayPalPresentationMode)(Ye,_==="app_switch"?"app_switch":void 0,D),Ae=(0,ze.usesPayPalVaultedChannel)(kt),te=(0,R.useMemo)(()=>JSON.stringify([ne,d,y,p??"",D,Ae,A,e,Ee??""]),[ne,d,y,p,Ee,D,Ae,A,e]),xe=(0,R.useRef)(te),u=xe.current!==te,I=(0,R.useRef)(q),k=(0,R.useRef)(null),[U,F]=(0,R.useState)([]),x=(0,R.useCallback)(z=>{I.current&&F(mt=>[...mt,`${new Date().toISOString().slice(11,23)} ${z}`])},[]);(0,R.useEffect)(()=>{I.current=q,q&&x("debug:enabled"),k.current?.setEnabled(q)},[x,q]);let At=(0,R.useRef)(E),Et=(0,R.useRef)(V),kr=(0,R.useRef)(W),rr=(0,R.useRef)(w),Pt=(0,R.useRef)(T),xt=(0,R.useRef)(f),xr=(0,R.useRef)(M),Fr=(0,R.useRef)(X),zr=(0,R.useRef)(v),Qt=(0,R.useRef)(s),Br=(0,R.useRef)(oe),qr=(0,R.useRef)(ye),en=(0,R.useRef)(n),jr=(0,R.useRef)(a),ur=(0,R.useRef)(t),pr=(0,R.useRef)(null),pt=(0,R.useRef)(new Map),ln=(0,R.useRef)(new Map),Ne=(0,R.useRef)(!1),zt=(0,R.useRef)(e);zt.current=e;let[Vr]=(0,R.useState)(wi);(0,R.useEffect)(()=>(Ne.current=!0,()=>{Ne.current=!1}),[]),(0,R.useEffect)(()=>{At.current=E},[E]),(0,R.useEffect)(()=>{Qt.current=s},[s]),(0,R.useEffect)(()=>{Et.current=V},[V]),(0,R.useEffect)(()=>{kr.current=W},[W]),(0,R.useEffect)(()=>{rr.current=w},[w]),(0,R.useEffect)(()=>{Pt.current=T},[T]),(0,R.useEffect)(()=>{xt.current=f},[f]),(0,R.useEffect)(()=>{xr.current=M},[M]),(0,R.useEffect)(()=>{Fr.current=X},[X]),(0,R.useEffect)(()=>{zr.current=v},[v]),(0,R.useEffect)(()=>{Br.current=oe},[oe]),(0,R.useEffect)(()=>{qr.current=ye},[ye]),(0,R.useEffect)(()=>{en.current=n},[n]),(0,R.useEffect)(()=>{jr.current=a},[a]),(0,R.useEffect)(()=>{ur.current=t},[t]),(0,R.useEffect)(()=>{dt.current=ge},[ge]),(0,R.useEffect)(()=>{ut&&ft.current?.focus()},[ut,ge]);let Or=(0,R.useCallback)(()=>{window.setTimeout(()=>{ft.current?.focus()},0)},[]),Wr=(0,R.useCallback)(()=>{_e(!1),rt(z=>z+1)},[]),gn=(0,R.useCallback)(()=>{ae(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);(0,R.useEffect)(()=>{!ve||!de.current||(de.current=!1,gn())},[gn,ve,ge]);let cn=(0,R.useCallback)((z,mt)=>{let G=mt?.popupBlocked??(0,ke.isPopupBlockedError)(z);G&&J.markBlocked();let Re=(0,ke.buildExternalMethodRecoveryMessage)("PayPal",G,Ye.inAppBrowser),Ft=xt.current;if(Ft){let Gt=G&&Ye.inAppBrowser?new ze.FloPayError(Re,"api_error",{code:mt?.code??"paypal_popup_blocked"}):z;Ft("paypal",Gt,mt);return}if(z instanceof ze.FloPayError&&z.code==="checkout_processing_timeout"){kr.current?.(z.message);return}kr.current?.(Re)},[J,Ye.inAppBrowser]),Er=(0,R.useCallback)(z=>{let mt=we.current,G=qe.current;mt===null||!G||(Y.log({...G,popupCapability:J.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:z}),Y.performance({...G,popupCapability:J.current(),stage:"overlay_return",durationMs:Y.elapsed(mt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:z}),we.current=null)},[J,Y]),hn=(0,R.useCallback)((z,mt,G)=>{let Re=qe.current;Er("overlay_timeout"),Re&&Y.error({...Re,popupCapability:J.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),cn(mt,{...G,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:A,terminalReason:"overlay_timeout"}),ae(!0),Wr(),Or()},[Er,Or,cn,J,A,Wr,Y]),dn=(0,R.useCallback)(()=>{J.markAvailable();let z=qe.current;z&&(Q.current=z.attempt,Y.log({...z,popupCapability:J.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[J,Y]),ar=(0,R.useCallback)(()=>!0,[]),Dr=(0,R.useCallback)(()=>{let z=qe.current;if(!z)return;let mt=we.current;Y.performance({...z,popupCapability:J.current(),stage:"overlay_return",durationMs:mt===null?0:Y.elapsed(mt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[J,Y]),{finishAttempt:Lr,generationRef:$r,invalidateAttempt:Kt,isAttemptCurrent:Nr,isAttemptInvalidated:mr,startAttempt:Yr}=Ba(hn,{onHandoffObserved:dn,defersMissingTerminal:ar,onMissingTerminalDeferred:Dr}),vr=(0,R.useCallback)(()=>(ae(!1),Yr("paypal")),[Yr]),yr=(0,R.useCallback)(z=>{Kt(z?.generation),z?.showRetry&&ae(!0),z?.remount&&Wr(),z?.focus!==!1&&Or()},[Or,Kt,Wr]),Ur=z=>{let mt=pr.current;return mt&&ln.current.set(z,mt),z};(0,R.useEffect)(()=>{xe.current!==te&&(xe.current=te,Dt.current=!1,Lt.current=!1,_e(!1),je(!1),Ie(!1),zr.current?.("loading"))},[te]),(0,R.useEffect)(()=>{(0,Ge.invokeMerchantCallback)(()=>Fr.current?.(ve&&!Ut))},[ve,Ut]);let _r=(0,ze.normalizeGatewayEnvironment)(p);(0,R.useEffect)(()=>{let z={attempt:$r.current+1,inAppBrowser:Ye.inAppBrowser,appFamily:Ye.appFamily,popupCapability:J.current(),presentationMode:A},mt=()=>({...qe.current??z,popupCapability:J.current()}),G={error:m=>Y.error({...m,...mt()}),log:m=>Y.log({...m,...mt()}),performance:m=>Y.performance({...m,...mt()}),terminal:m=>Y.terminal({...m,...mt()}),startTiming:Y.startTiming,elapsed:Y.elapsed},Re=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",Ft=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(x(`mount clientId=${Re} env=${p??"(unset)"}\u2192${_r??"live"} ccy=${y} sub=${b}`),x(`ua=${Ft.slice(0,80)}${Ft.length>80?"\u2026":""}`),!d){x("FAIL: clientId empty \u2014 gateway misconfigured"),Ie(!0),G.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(!K.current){x("FAIL: containerRef not attached");return}tt.current=G.startTiming(),G.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,Yt=!1,Be=()=>Gt||Yt,Ve=m=>{let g=Ne.current,$=g?m:"torn_down";g&&x(`onError ignored reason=${$}`),Vr.take(zt.current)&&G.log({name:Si,stage:"provider_ready",reason:$,provider:"paypal",paymentMethodCategory:"paypal"})},_o=()=>zt.current===e?"stale_attempt":"session_changed",go=Ae?D:void 0,Io,xn=!1,Fn=()=>{Io=(0,ze.generateIdempotencyKey)(),Io||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),xn=!0},tn=null,un=!1,nr=null,Hn=!1,rn=()=>{!nr||Hn||(Hn=!0,nr.close().catch(()=>{}))},Hr=!1,Ht=!1,Ir=K.current,Bn=null,oo=null,pn=[],On=null,Kn=!1,ho=!1,Gn=null,Pn=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let g=m.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},Vo=m=>{if(!m)return"(empty)";try{let g=new URL(m,typeof window>"u"?"https://localhost":window.location.href),$=g.pathname.toLowerCase();return $.includes("checkcaptcha")||$.includes("captcha")?`CAPTCHA(${g.host}${$})`:$.includes("risk")||$.includes("challenge")?`RISK(${g.host}${$})`:$.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${$}`.slice(0,100)}catch{return m.slice(0,80)}},Wo=m=>{let g=m.getAttribute("src"),$=m.getAttribute("srcdoc"),be=m.getAttribute("name"),ie=m.getAttribute("sandbox"),ee=[];return g&&ee.push(`src=${Vo(g)}`),$&&ee.push(`srcdoc[${$.length}ch]`),!g&&!$&&ee.push("src=(empty) srcdoc=(empty)"),be&&ee.push(`name=${be.slice(0,40)}`),ie!==null&&ee.push(`sandbox="${ie.slice(0,40)}"`),ee.join(" ")},ao=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let g=m.contentDocument;if(!g)return"cd=null";let $=g.body?.children.length??0,be=g.body?.innerHTML.length??0,ie=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${$}children,${be}ch] head[${ie}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},vn=[],Po=m=>{if(Be())return;let g=m.message??String(m.error??"(no message)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(x(`window:error ${g.slice(0,140)}`),vn.push(g))},qt=m=>{if(Be())return;let g=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(x(`window:rejection ${g.slice(0,140)}`),vn.push(g))},Dn={value:0},Cn=()=>{Bn?.disconnect(),Bn=null,oo?.disconnect(),oo=null;for(let m of pn.splice(0))clearTimeout(m);ho=!1,Kn&&typeof window<"u"&&(window.removeEventListener("error",Po),window.removeEventListener("unhandledrejection",qt)),Kn=!1},bn=()=>{if(!(Kn||Be()||Hr)){if(Kn=!0,vn.length=0,Dn.value=0,typeof window<"u"&&(window.addEventListener("error",Po),window.addEventListener("unhandledrejection",qt)),typeof PerformanceObserver<"u")try{oo=new PerformanceObserver(m=>{if(!Be())for(let g of m.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;Dn.value+=1;let $=Math.round(g.duration);x(`net ${$}ms ${g.name.slice(0,90)}`)}}),oo.observe({type:"resource",buffered:!0})}catch{}Gn?.()}},Sn=()=>{On&&(clearTimeout(On),On=null)},ot=()=>{Cn(),Sn()},Kr={setEnabled:m=>{m?bn():Cn()}};k.current=Kr,I.current&&bn();let jt=ze.isPayPalTeardownMessage,O=m=>{if(Be()||jt(m))return;let g=(0,Bo.applyFriendlyMessageOverride)(m)??m;(0,Ge.invokeMerchantCallback)(()=>kr.current?.(g))},L=(m,g)=>{if(Gt||un)return;un=!0,Yt=!0,ot(),rn();let $=lu({kind:m,generationActive:!0,automaticRetryAllowed:Se,automaticRetryUsed:Dt.current});if($.action==="retry"){Dt.current=!0,_e(!1),gt(!1),je(!0),zr.current?.("retrying"),tn=setTimeout(()=>{Gt||rt(be=>be+1)},ou);return}if(_e(!1),gt(!1),je(!1),Ie(!0),$.action!=="ignore"){if(zr.current?.("exhausted"),$.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if($.report){let be=(0,ke.classifyExternalMethodFailure)({code:mc(m,g),message:g},{inAppBrowser:Ye.inAppBrowser,handoffObserved:!1});be.popupBlocked&&J.markBlocked(),G.error({errorCode:be.popupBlocked?be.errorCode:$.report.errorCode,stage:$.report.stage,operationOutcome:$.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:be.terminalReason})}Lt.current||(Lt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",mc(m,g)))}};Ie(!1);let se=async(m,g=pr.current)=>{if(Be())return;let $=g?.sessionId??e;if(At.current){await At.current(m,{sessionId:$,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let be=G.startTiming();G.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ie=()=>{G.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),G.performance({stage:"processing",durationMs:G.elapsed(be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ee=(0,ze.buildPayPalProcessPaymentRequest)({body:m,sessionId:$,nonce:g?.nonce??ur.current,accountPatch:g?.accountPatch,session:qr.current,email:en.current}),_t=await new ki.PaymentAPI(ne,{telemetry:!1}).processPayment(ee.userId,ee.params);if(_t.ok){if(Yt||Gt&&Ne.current)return;ie(),G.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>Et.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Be())return;let Xt=await _t.json().catch(()=>null),st=(0,ze.describePayPalProcessFailure)(Xt),It=st.message;ie(),_t.status===400&&(typeof Xt?.declineCode=="string"||!Array.isArray(Xt?.fields))?G.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):_t.status===400||_t.status===422?G.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):G.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:cu(_t.status),failureCategory:_t.status>=500?"server_error":void 0}),O(It),(0,Ge.invokeMerchantCallback)(()=>rr.current?.(Cr("paypal",It,{code:st.code,declineCode:st.declineCode})));return}catch(ee){if(Be())return;ie(),G.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Fe=(0,ze.friendlyPayPalFailureMessage)(ee instanceof Error?ee.message:void 0);O(Fe),(0,Ge.invokeMerchantCallback)(()=>rr.current?.(Cr("paypal",Fe)));return}},ue=()=>new ze.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Nt=m=>Be()?Promise.reject(ue()):Promise.resolve(m),er=async m=>{if(m.ok){G.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>Et.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let g=await m.json().catch(()=>null),$=(0,ze.describePayPalProcessFailure)(g);G.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,Ge.invokeMerchantCallback)(()=>rr.current?.(Cr("paypal",$.message,{code:$.code,declineCode:$.declineCode})))},Oe=()=>{let m=pr.current;Er("approved"),m&&(pt.current.delete(m.surfaceKey),Lr(m.generation)),pr.current=null},it=async m=>{if(Be())throw ue();xn||Fn();let g=pr.current,$=g?.sessionId??e,be=g?.nonce??ur.current;G.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ie;try{ie=await new ki.PaymentAPI(ne,{telemetry:!1}).createSessionIntent($,be??"",(0,ze.buildPayPalSessionIntentRequest)(go),{idempotencyKey:Io})}catch(ee){throw G.error({...(0,ze.classifyTelemetryFailure)(ee,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ee}if(Be())throw ue();if((0,ze.isSettledSessionIntent)(ie))throw await er(ie.response),Oe(),new ze.FloPayError("PayPal checkout already settled.","api_error",{code:pc});if(ie.provider!=="paypal"||ie.providerObjectType!==D)throw new Error(m);return G.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ie.providerObjectId},re=(m,g)=>{let $=g?.nonce??ur.current;if(!$)return;let be=g?.sessionId??e,ie=(0,ze.resolvePayPalDeclineReason)(m);new ki.PaymentAPI(ne,{telemetry:!1}).reportSessionIntentDecline(be,$,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ie}).catch(()=>{})},Te=ge;x("loadScript:scheduled (deferred 1 tick)");let Ce=null,vt=setTimeout(()=>{if(Gt){x("loadScript:skipped (cancelled before defer ran)");return}x("loadScript:start");let m=_r==="live"?"production":_r,g={};D==="subscription"?g={intent:"subscription",vault:!0}:D==="order"&&(g={intent:"capture"}),Ce=(0,yc.loadScript)({clientId:d,currency:y,...g,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let $=!1;Ce.then(be=>{if($=!0,x(`loadScript:resolved inactive=${Be()} ns=${!!be} buttons=${!!be?.Buttons}`),Be())return;if(!be?.Buttons){x("FAIL: namespace missing Buttons factory"),L("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}G.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),G.performance({stage:"provider_ready",durationMs:G.elapsed(tt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),G.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ie=async(pe,Xe)=>{if(Be()||dt.current!==Te)return;let We=pe.vaultSetupToken??pe.subscriptionID??pe.orderID??"",Je=We?ln.current.get(We):pt.current.get(Te);if(!(!Je||!Nr(Je.generation))&&Lr(Je.generation)){ln.current.delete(We),pt.current.delete(Je.surfaceKey),Er("approved");try{if(gt(!0),(0,Ge.invokeMerchantCallback)(()=>kr.current?.(null)),!We)throw new ze.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Tt=(0,ze.resolvePayPalApprovalIdentity)({accountPatch:Je.accountPatch,email:en.current,billingName:jr.current,session:qr.current});if((0,ze.needsPayPalPayerDetails)(Tt))try{Tt=(0,ze.mergePayPalPayerIdentity)(Tt,await Xe?.order?.get?.())}catch{}if((Qt.current||ht)&&!(0,ze.isValidEmail)(Tt.email)){let Jt=await Mt("PayPal",Tt);if(!Jt)return;Tt=Jt}(0,ze.isValidEmail)(Tt.email)&&(Je.accountPatch=(0,En.compactBuyerIdentity)({...Je.accountPatch,...Tt}),await Qt.current?.(Tt));let nn=(0,ze.buildPayPalTokenizedBody)(We,go);await se(nn,Je)}catch(Tt){O(Tt instanceof Error?Tt.message:"PayPal capture failed.")}finally{Be()||gt(!1)}}},ee=pe=>{let Xe=Ee?()=>Nt(Ee):()=>it(pe);return async()=>Ur(await Xe())},Fe=be.Buttons({style:{layout:"horizontal",height:Ei,tagline:!1},...A==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(pe,Xe)=>{if(Be()){await Xe.reject();return}Fn();let We=Br.current,Je={};if(We)try{let Jt=await We("paypal");if(Be()){await Xe.reject();return}if(!Jt.proceed){pr.current=null,pt.current.delete(Te),await Xe.reject();return}Je={sessionId:Jt.sessionId,accountPatch:Jt.accountPatch,nonce:Jt.nonce}}catch(Jt){x(`onClick:runBeforeButtonClick rejected msg=${(Jt instanceof Error?Jt.message:String(Jt)).slice(0,120)}`),pr.current=null,pt.current.delete(Te),await Xe.reject();return}(0,Ge.invokeMerchantCallback)(()=>xr.current?.("paypal"));let Tt=vr(),nn={generation:Tt,surfaceKey:Te,...Je};pr.current=nn,pt.current.set(Te,nn),qe.current={...z,attempt:Tt},await Xe.resolve(),G.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),G.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),we.current=G.startTiming()},createOrder:D==="order"?ee("Failed to create PayPal order."):void 0,createSubscription:D==="subscription"?ee("Failed to create PayPal subscription."):void 0,createVaultSetupToken:D==="setup_token"?async()=>Ur(await it("Failed to create PayPal setup token.")):void 0,onApprove:ie,onCancel:()=>{if(Be())return;let pe=pt.current.get(Te)??pr.current,Xe=pe&&Nr(pe.generation)?(0,ze.buildPayPalCancelEvent)(pe.sessionId??e,go):null;pe&&pt.current.delete(pe.surfaceKey),pr.current=null,Er("cancelled"),G.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),de.current=!0,yr({generation:pe?.generation,remount:!0,focus:!1}),Xe&&(0,Ge.invokeMerchantCallback)(()=>Pt.current?.(Xe))},onError:pe=>{if(pe instanceof ze.FloPayError&&pe.code===pc)return;let Xe=pe instanceof Error?pe.message:"PayPal failed to render.";if(Be()||dt.current!==Te){jt(Xe)||Ve(_o());return}if(Hr){let We=pt.current.get(Te)??pr.current;if(!We||!Nr(We.generation)){if(jt(Xe)){!We&&!mr()&&Lr();return}Ve(We||mr()?"stale_attempt":"no_current_attempt");return}if(x(`onError rendered=${Hr} msg=${Xe.slice(0,120)}`),jt(Xe)){Lr(We.generation);return}let{errorCode:Je,popupBlocked:Tt,providerDeclined:nn,terminalReason:Jt}=(0,ke.classifyExternalMethodFailure)(pe,{inAppBrowser:Ye.inAppBrowser,handoffObserved:Q.current===We.generation});if(Tt&&J.markBlocked(),Er(Jt),nn){G.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Jt}),re(pe,We),(0,Ge.invokeMerchantCallback)(()=>rr.current?.(Cr("paypal",Xe))),pt.current.delete(We.surfaceKey),pr.current=null,Lr(We.generation);return}G.error({errorCode:Je,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Jt}),pt.current.delete(We.surfaceKey),pr.current=null,yr({generation:We.generation,remount:!0,showRetry:!0,focus:!0}),cn(pe,{code:"paypal_runtime_failed",popupBlocked:Tt,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:A,terminalReason:Jt});return}x(`onError rendered=${Hr} msg=${Xe.slice(0,120)}`),L(jt(Xe)?"teardown":"pre_ready_callback",Xe)}}),_t=Fe.isEligible();if(x(`isEligible=${_t}`),G.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!_t){_e(!1),L("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ht=!0,nr=Fe,Gn=()=>{if(!Kn||ho||Be()||Hr)return;ho=!0,x(`container:dims ${Pn(Ir)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Bn=new MutationObserver(Xe=>{if(!Be()){for(let We of Xe)if(We.type==="childList")We.addedNodes.forEach(Je=>{if(!(Je instanceof Element))return;let Tt=Je.tagName.toLowerCase(),nn=(Je.getAttribute("title")??"").slice(0,40),Jt=Tt==="iframe"?` ${Wo(Je)}`:"";x(`child+ ${Tt}${nn?` title="${nn}"`:""}${Jt} dims=${Pn(Je)}`)});else if(We.type==="attributes"&&We.target instanceof Element){let Je=We.target;if(Je.tagName.toLowerCase()!=="iframe")continue;let Tt=We.attributeName;(Tt==="src"||Tt==="srcdoc")&&x(`attr~ iframe ${Tt}=${Tt==="srcdoc"?`[${(Je.getAttribute("srcdoc")??"").length}ch]`:Vo(Je.getAttribute("src"))} dims=${Pn(Je)}`)}}}),Bn.observe(Ir,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let pe=Xe=>{if(Be()||Hr)return;let We=Ir.querySelectorAll("iframe"),Je=typeof document<"u"&&"hasStorageAccess"in document;x(`watchdog:${Xe} container=${Pn(Ir)} children=${Ir.childElementCount} iframes=${We.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Je} paypalNetRequests=${Dn.value}`),We.forEach((Tt,nn)=>{let Jt=(Tt.getAttribute("title")??"").slice(0,40);x(` iframe[${nn}] ${Pn(Tt)}${Jt?` title="${Jt}"`:""} ${Wo(Tt)}`);let ti=ao(Tt);ti&&x(` ${ti}`)}),vn.length===0&&x(" (no PayPal/zoid window errors captured)")};pn.push(setTimeout(()=>pe("3s"),3e3)),pn.push(setTimeout(()=>pe("8s"),8e3)),pn.push(setTimeout(()=>pe("15s"),15e3))},Gn(),x("render:start");let st=G.startTiming();On=setTimeout(()=>{Be()||Hr||(x("watchdog:11s retryable render timeout"),L("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},au);let It=Fe.render(Ir);(async()=>{try{if(await It,x(`render:resolved inactive=${Be()}`),ot(),Be()){rn();return}Hr=!0,_e(!0),je(!1),zr.current?.("ready"),G.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),G.performance({stage:"checkout_render",durationMs:G.elapsed(st),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(pe){let Xe=pe instanceof Error?pe.message:"PayPal failed to render.";x(`render:rejected msg=${Xe.slice(0,120)}`),ot(),L(jt(Xe)?"teardown":"render_rejected",Xe)}})()}).catch(be=>{let ie=be instanceof Error?be.message:"PayPal operation failed.";x(`provider:failed msg=${ie.slice(0,120)}`);let ee="script_rejected";$&&jt(ie)?ee="teardown":$&&Ht&&(ee="render_rejected"),L(ee,ie)})},0);return()=>{Gt=!0,clearTimeout(vt),tn&&clearTimeout(tn),ot(),k.current===Kr&&(k.current=null),rn(),we.current=null,qe.current=null}},[Se,ne,d,y,p,D,A,Ae,e,Ee,ge,Y,Mt,ht,x,Er]);let et=q?(0,_n.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ut?"#fef2f2":"#f3f4f6",border:`1px solid ${Ut?"#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=${ve} failed=${Ut})`,U.length===0?`
1
+ "use strict";var Vd=Object.create;var fi=Object.defineProperty;var Wd=Object.getOwnPropertyDescriptor;var $d=Object.getOwnPropertyNames;var Hd=Object.getPrototypeOf,Kd=Object.prototype.hasOwnProperty;var Gd=(e,t)=>{for(var r in t)fi(e,r,{get:t[r],enumerable:!0})},Zl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of $d(t))!Kd.call(e,a)&&a!==r&&fi(e,a,{get:()=>t[a],enumerable:!(n=Wd(t,a))||n.enumerable});return e};var Es=(e,t,r)=>(r=e!=null?Vd(Hd(e)):{},Zl(t||!e||!e.__esModule?fi(r,"default",{value:e,enumerable:!0}):r,e)),Yd=e=>Zl(fi({},"__esModule",{value:!0}),e);var Dp={};Gd(Dp,{DirectPayPalButton:()=>Da,FloPayAutomaticPaymentButton:()=>id,FloPayCardSetup:()=>sd,FloPayCardSetupError:()=>ei,FloPayCheckout:()=>Gi,FloPayPaymentMethodSetup:()=>Pd,FloPayProvider:()=>Na,SplitCardForm:()=>Wi,VaultCardFields:()=>_o,dropThirdPartyOnlyError:()=>Cd.dropThirdPartyOnlyError,useCheckout:()=>uc,useFloPay:()=>uo,usePayPalFloPay:()=>vi});module.exports=Yd(Dp);var Cd=require("@flopay/shared");var Yi=require("@flopay/js"),Ir=require("@flopay/shared"),pt=require("react");var Zt=require("react/jsx-runtime");function Xd(){return(0,Zt.jsxs)(Zt.Fragment,{children:[(0,Zt.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,Zt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Zt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Zt.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,Zt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Jd(){return(0,Zt.jsx)(Zt.Fragment,{children:"Go back"})}function Zd(){return(0,Zt.jsx)(Zt.Fragment,{children:"Secure card checkout"})}function na(e){return e!==void 0&&(e===""||e===null||e===!1)}function oa({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(Xd,{}):e})}function aa({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(Jd,{}):e})}function Ma({content:e}){return(0,Zt.jsx)(Zt.Fragment,{children:e===void 0?(0,Zt.jsx)(Zd,{}):e})}var _t=require("@flopay/shared"),Un=require("@flopay/shared"),la=require("@flopay/shared"),Fo=require("@flopay/shared");function _s(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof _t.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Qd(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 Ql(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,_t.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,_t.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function ec(e,t){if(t&&(!(e instanceof _t.FloPayError)||e.type==="authentication_error"))return _s(e);if(!(e instanceof _t.FloPayError&&Qd(e))){if(!t&&!(e instanceof _t.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,_t.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof _t.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof _t.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function ia(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,_t.isCardHolderNamePlaceholder)(d.firstName,d.lastName);if(!(0,_t.isValidEmail)(d.email))return Promise.reject(new _t.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[w,h]of Object.entries(d)){if(p&&w.endsWith("Name")||typeof h!="string")continue;let g=h.trim();g&&(m[w]=g)}return a=e.claimCheckoutSession(t,r,{accountData:m}),a.catch(()=>{}),a}}function tc(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 Is(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 rc(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 Ts(e,t){return t?{...e,...t}:e}function kr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,s=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,d=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...s?{declineCode:s}:{},...d?{sessionId:d}:{}}}var nc=new WeakMap;function oc(e,t){return typeof e=="object"&&e!==null&&nc.set(e,t?{sessionId:t}:{}),e}function ac(e){return typeof e=="object"&&e!==null?nc.get(e):void 0}function Ro(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function so(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function lo(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 ic(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function gi(e){let t=ic(e);return new _t.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function hi(e){return e instanceof _t.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function sa(e){return ic(e)?new _t.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new _t.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new _t.FloPayError(_t.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function Aa(e,t){return e==="processing"||(0,_t.isMoneySettledOutcome)(e,t)}function sc(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function lc(e,t){let r=e;if((0,_t.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:s,error:d}=await r.retrieveSetupIntent(t);if(d)throw new _t.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 _t.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var eu=["apple_pay","google_pay"];function cc(e,t="automatic",r){let n=(0,_t.resolveSetupFutureUsage)(r,eu,"wallet");return{...(0,_t.resolveWalletModeOptions)(e,t),allowedPaymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var tu=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Ms(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:tu.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function xa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var mo=require("@flopay/js"),se=require("@flopay/shared"),R=Es(require("react"),1);var As=require("react"),Rn=(0,As.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),zn=(0,As.createContext)({session:null,loading:!1,error:null});var ki=require("@flopay/js"),ze=require("@flopay/shared"),gc=require("@paypal/paypal-js"),E=require("react");var Pi=require("@flopay/shared"),qn=require("react"),kn=require("@flopay/shared"),co=require("react/jsx-runtime");function ca(){let[e,t]=(0,qn.useState)(null),r=(0,qn.useRef)(null),n=(0,qn.useRef)(0),a=(0,qn.useCallback)((d,p)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:d,identity:p}),new Promise(m=>{r.current=m})),[]),s=(0,qn.useCallback)(d=>{let p=r.current;r.current=null,t(null),p?.(d)},[]);return(0,qn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:s}}function da({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:s="flopay-buyer-identity-pane"}){let[d,p]=(0,qn.useState)(e.email?.trim()??""),m=(0,Pi.isValidEmail)(d.trim());return(0,co.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,co.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,co.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,co.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:d,onChange:w=>p(w.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,co.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,co.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,co.jsxs)("button",{type:"button",disabled:!m||a,onClick:()=>{r((0,Pi.compactBuyerIdentity)({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var _e=require("@flopay/shared");var dc=require("@flopay/shared"),Fa=require("react");function uo(){return(0,Fa.useContext)(Rn).flopay}function vi(){return(0,Fa.useContext)(Rn).paypalFlopay??null}function uc(){return(0,Fa.useContext)(zn)}function pc(){return(0,Fa.useContext)(Rn).billingApiUrl||(0,dc.resolveBillingApiUrl)()}var ru=require("@flopay/shared"),Jn=require("@flopay/shared"),Zn=require("@flopay/shared");var ua=require("@flopay/shared"),Oo=require("react");var Ci=require("react"),Bo=typeof window>"u"?Ci.useEffect:Ci.useLayoutEffect;var xs=require("@flopay/shared");function pa(e,t){let r=(0,Oo.useRef)(e);r.current=e;let n=(0,Oo.useRef)(new Set),a=(0,Oo.useRef)(t),s=(0,Oo.useRef)(t);return Bo(()=>{s.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,Oo.useCallback)(d=>{if(s.current!==t)return;let p=(0,ua.projectFloInstrument)(d);if(p){if(ua.FLO_INSTRUMENT_ONCE_NAMES.has(p.name)){if(n.current.has(p.name))return;n.current.add(p.name)}(0,ua.invokeMerchantCallback)(()=>r.current?.(p))}},[t])}var He=require("@flopay/shared");var yc=require("react"),Ba=(0,yc.createContext)(null);function bi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Si="provider.callback.ignored";function wi(){let e,t=0;return{take(r){return r!==e&&(e=r,t=0),t>=5?!1:(t+=1,!0)}}}var nu=Symbol.for("@flopay/js.telemetry.bridge.v1"),ou=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function au(){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 iu(e){let t=au(),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 Ri(e){let t=globalThis[ou];return iu(t?.(e)??{})}function Er(e){if(e)return e[nu]}var hr=require("react");function Oa(e,t){let r=(0,hr.useRef)(0),n=(0,hr.useRef)(null),a=(0,hr.useRef)(null),s=(0,hr.useRef)(e),d=(0,hr.useRef)(t?.onHandoffObserved),p=(0,hr.useRef)(t?.defersMissingTerminal),m=(0,hr.useRef)(t?.onMissingTerminalDeferred);(0,hr.useEffect)(()=>{s.current=e,d.current=t?.onHandoffObserved,p.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let w=(0,hr.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),h=(0,hr.useCallback)(f=>{w();let H=r.current+1;return r.current=H,n.current=null,a.current={generation:H,method:f,timer:null,yieldedControl:!1},H},[w]),g=(0,hr.useCallback)(f=>{let H=a.current;return f!==void 0&&H?.generation!==f?!1:(w(H),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[w]),_=(0,hr.useCallback)(f=>{let H=a.current,Y=f??H?.generation??r.current;(f===void 0||H?.generation===f)&&(w(H),a.current=null),n.current=Y},[w]),V=(0,hr.useCallback)(f=>n.current===(f??r.current),[]),W=(0,hr.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),k=(0,hr.useCallback)(()=>{let f=a.current;f&&(w(f),!f.yieldedControl&&(f.yieldedControl=!0,d.current?.(f.method)))},[w]),A=(0,hr.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(w(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(p.current?.(f.method)){m.current?.(f.method,f.generation);return}a.current=null,n.current=f.generation,s.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},_e.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[w]);return(0,hr.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?A():k()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",k),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",k),window.removeEventListener("focus",A),w()}},[w,k,A]),{startAttempt:h,finishAttempt:g,invalidateAttempt:_,isAttemptInvalidated:V,isAttemptCurrent:W,generationRef:r}}var En=require("react/jsx-runtime"),Ei=45,su=1e3,lu=11e3,mc="paypal_intent_settled",cu={width:"100%",minHeight:Ei,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"},du={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 uu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:du[e.kind]??null}}function fc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,_e.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function pu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function hc({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:s,clientId:d,environment:p,currency:m,isSubscription:w,providerObjectType:h,approvalPresentation:g,onTokenizedBody:_,onComplete:V,onErrorChange:W,onDecline:k,onCancel:A,onTechnicalFailure:f,isProcessing:H=!1,onLoadStateChange:Y,onInitializationStateChange:b,allowAutomaticRetry:be=!0,onButtonClick:x,runBeforeButtonClick:oe,session:ge,existingOrderId:Ie,telemetry:ce,telemetryContext:Rt,onInstrument:mt,debug:q=!1}){let Ve=uo(),We=pa(mt,e),Ne=(0,E.useMemo)(()=>{if(Ve)return null;let P=Ri({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:ze.SDK_VERSION,enabled:ce!==!1});return P.setCheckoutContext(Rt??{}),P.beginCheckout(Rt??{}),P},[r,Ve,ce,Rt?.checkoutMode,Rt?.layout]),ve=(0,E.useMemo)(()=>Er(Ve),[Ve]);(0,E.useEffect)(()=>()=>{Ne&&Ne.flush().catch(()=>{}).finally(()=>Ne.destroy())},[Ne]);let G=(0,E.useMemo)(()=>({error:P=>{ve?ve.error(P):Ne?.error(P),We({class:"technical_error",errorCode:P.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":P.errorCode,requestCategory:P.requestCategory,provider:P.provider})},log:P=>{ve?ve.log(P):Ne?.log(P),We({class:"lifecycle",name:P.name,provider:P.provider})},performance:P=>{ve?ve.performance(P):Ne?.performance(P)},terminal:P=>{ve?ve.terminal(P):Ne?.terminal(P)},startTiming:()=>ve?.now()??Ne?.now()??0,elapsed:P=>ve?.elapsed(P)??Math.max(0,(Ne?.now()??P)-P)}),[We,ve,Ne]),K=(0,E.useRef)(null),Ze=(0,E.useRef)(0),Se=(0,E.useRef)(null),qe=(0,E.useRef)(null),Z=(0,E.useRef)(null),j=(0,E.useContext)(Ba),he=(0,E.useRef)(null);he.current||(he.current=bi());let X=j??he.current,Pt=(0,E.useRef)(null),pe=(0,E.useRef)(!1),[we,Ae]=(0,E.useState)(!1),[Ce,kt]=(0,E.useState)(!1),[Pe,Be]=(0,E.useState)(0),at=(0,E.useRef)(0),[yt,Mt]=(0,E.useState)(!1),le=(0,E.useRef)(!1),It=(0,E.useRef)(!1),[Vt,xe]=(0,E.useState)(!1),[Oe,Ke]=(0,E.useState)(!1),{request:vt,collect:it,finish:ft}=ca(),Lt=(0,E.useRef)({sessionId:e,required:(0,ze.paypalProviderIdentityRequired)(n,ge)});Lt.current.sessionId!==e&&(Lt.current={sessionId:e,required:(0,ze.paypalProviderIdentityRequired)(n,ge)});let Qe=Lt.current.required,st=(0,E.useMemo)(()=>r.replace(/\/+$/,""),[r]),Ot=ge?.gateways?.paypal?.providerObjectType??h,et=Ot??(w?"subscription":"order"),[re]=(0,E.useState)(Jn.detectPayPalEnvironment),v=ge?.gateways?.paypal?.approvalPresentation??g,Q=(0,Zn.resolvePayPalPresentationMode)(re,v==="app_switch"?"app_switch":void 0,et),ee=(0,ze.usesPayPalVaultedChannel)(Ot),$=(0,E.useMemo)(()=>JSON.stringify([st,d,m,p??"",et,ee,Q,e,Ie??""]),[st,d,m,p,Ie,et,ee,Q,e]),nt=(0,E.useRef)($),u=nt.current!==$,F=(0,E.useRef)(q),D=(0,E.useRef)(null),[L,T]=(0,E.useState)([]),I=(0,E.useCallback)(P=>{F.current&&T(xt=>[...xt,`${new Date().toISOString().slice(11,23)} ${P}`])},[]);(0,E.useEffect)(()=>{F.current=q,q&&I("debug:enabled"),D.current?.setEnabled(q)},[I,q]);let Ct=(0,E.useRef)(_),Mr=(0,E.useRef)(V),bt=(0,E.useRef)(W),un=(0,E.useRef)(k),gt=(0,E.useRef)(A),vr=(0,E.useRef)(f),At=(0,E.useRef)(x),Ar=(0,E.useRef)(Y),Cr=(0,E.useRef)(b),Xt=(0,E.useRef)(s),Jr=(0,E.useRef)(oe),xr=(0,E.useRef)(ge),Ur=(0,E.useRef)(n),pn=(0,E.useRef)(a),Fr=(0,E.useRef)(t),Wt=(0,E.useRef)(null),br=(0,E.useRef)(new Map),Tt=(0,E.useRef)(new Map),St=(0,E.useRef)(!1),lt=(0,E.useRef)(e);lt.current=e;let[yn]=(0,E.useState)(wi);(0,E.useEffect)(()=>(St.current=!0,()=>{St.current=!1}),[]),(0,E.useEffect)(()=>{Ct.current=_},[_]),(0,E.useEffect)(()=>{Xt.current=s},[s]),(0,E.useEffect)(()=>{Mr.current=V},[V]),(0,E.useEffect)(()=>{bt.current=W},[W]),(0,E.useEffect)(()=>{un.current=k},[k]),(0,E.useEffect)(()=>{gt.current=A},[A]),(0,E.useEffect)(()=>{vr.current=f},[f]),(0,E.useEffect)(()=>{At.current=x},[x]),(0,E.useEffect)(()=>{Ar.current=Y},[Y]),(0,E.useEffect)(()=>{Cr.current=b},[b]),(0,E.useEffect)(()=>{Jr.current=oe},[oe]),(0,E.useEffect)(()=>{xr.current=ge},[ge]),(0,E.useEffect)(()=>{Ur.current=n},[n]),(0,E.useEffect)(()=>{pn.current=a},[a]),(0,E.useEffect)(()=>{Fr.current=t},[t]),(0,E.useEffect)(()=>{at.current=Pe},[Pe]),(0,E.useEffect)(()=>{yt&&Pt.current?.focus()},[yt,Pe]);let ur=(0,E.useCallback)(()=>{window.setTimeout(()=>{Pt.current?.focus()},0)},[]),zr=(0,E.useCallback)(()=>{Ae(!1),Be(P=>P+1)},[]),An=(0,E.useCallback)(()=>{Mt(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);(0,E.useEffect)(()=>{!we||!pe.current||(pe.current=!1,An())},[An,we,Pe]);let mn=(0,E.useCallback)((P,xt)=>{let te=xt?.popupBlocked??(0,_e.isPopupBlockedError)(P);te&&X.markBlocked();let ae=(0,_e.buildExternalMethodRecoveryMessage)("PayPal",te,re.inAppBrowser),zt=vr.current;if(zt){let Ft=te&&re.inAppBrowser?new ze.FloPayError(ae,"api_error",{code:xt?.code??"paypal_popup_blocked"}):P;zt("paypal",Ft,xt);return}if(P instanceof ze.FloPayError&&P.code==="checkout_processing_timeout"){bt.current?.(P.message);return}bt.current?.(ae)},[X,re.inAppBrowser]),qr=(0,E.useCallback)(P=>{let xt=Se.current,te=qe.current;xt===null||!te||(G.log({...te,popupCapability:X.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:P}),G.performance({...te,popupCapability:X.current(),stage:"overlay_return",durationMs:G.elapsed(xt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:P}),Se.current=null)},[X,G]),fn=(0,E.useCallback)((P,xt,te)=>{let ae=qe.current;qr("overlay_timeout"),ae&&G.error({...ae,popupCapability:X.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),mn(xt,{...te,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Q,terminalReason:"overlay_timeout"}),Mt(!0),zr(),ur()},[qr,ur,mn,X,Q,zr,G]),gn=(0,E.useCallback)(()=>{X.markAvailable();let P=qe.current;P&&(Z.current=P.attempt,G.log({...P,popupCapability:X.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[X,G]),pr=(0,E.useCallback)(()=>!0,[]),tr=(0,E.useCallback)(()=>{let P=qe.current;if(!P)return;let xt=Se.current;G.performance({...P,popupCapability:X.current(),stage:"overlay_return",durationMs:xt===null?0:G.elapsed(xt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[X,G]),{finishAttempt:on,generationRef:Zr,invalidateAttempt:rr,isAttemptCurrent:Qt,isAttemptInvalidated:Sr,startAttempt:jr}=Oa(fn,{onHandoffObserved:gn,defersMissingTerminal:pr,onMissingTerminalDeferred:tr}),yr=(0,E.useCallback)(()=>(Mt(!1),jr("paypal")),[jr]),wr=(0,E.useCallback)(P=>{rr(P?.generation),P?.showRetry&&Mt(!0),P?.remount&&zr(),P?.focus!==!1&&ur()},[ur,rr,zr]),$r=P=>{let xt=Wt.current;return xt&&Tt.current.set(P,xt),P};(0,E.useEffect)(()=>{nt.current!==$&&(nt.current=$,le.current=!1,It.current=!1,Ae(!1),kt(!1),xe(!1),Cr.current?.("loading"))},[$]),(0,E.useEffect)(()=>{(0,He.invokeMerchantCallback)(()=>Ar.current?.(we&&!Vt))},[we,Vt]);let Br=(0,ze.normalizeGatewayEnvironment)(p);(0,E.useEffect)(()=>{let P={attempt:Zr.current+1,inAppBrowser:re.inAppBrowser,appFamily:re.appFamily,popupCapability:X.current(),presentationMode:Q},xt=()=>({...qe.current??P,popupCapability:X.current()}),te={error:C=>G.error({...C,...xt()}),log:C=>G.log({...C,...xt()}),performance:C=>G.performance({...C,...xt()}),terminal:C=>G.terminal({...C,...xt()}),startTiming:G.startTiming,elapsed:G.elapsed},ae=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",zt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(I(`mount clientId=${ae} env=${p??"(unset)"}\u2192${Br??"live"} ccy=${m} sub=${w}`),I(`ua=${zt.slice(0,80)}${zt.length>80?"\u2026":""}`),!d){I("FAIL: clientId empty \u2014 gateway misconfigured"),xe(!0),te.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!K.current){I("FAIL: containerRef not attached");return}Ze.current=te.startTiming(),te.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ft=!1,nr=!1,Xe=()=>Ft||nr,mr=C=>{let y=St.current,M=y?C:"torn_down";y&&I(`onError ignored reason=${M}`),yn.take(lt.current)&&te.log({name:Si,stage:"provider_ready",reason:M,provider:"paypal",paymentMethodCategory:"paypal"})},Je=()=>lt.current===e?"stale_attempt":"session_changed",no=ee?et:void 0,go,jo=!1,xn=()=>{go=(0,ze.generateIdempotencyKey)(),go||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),jo=!0},hn=null,an=!1,Qr=null,or=!1,Fn=()=>{!Qr||or||(or=!0,Qr.close().catch(()=>{}))},Rr=!1,$n=!1,ht=K.current,Vr=null,Bn=null,oo=[],sn=null,Pn=!1,ho=!1,Po=null,vn=C=>{if(!C||typeof C.getBoundingClientRect!="function")return"(no rect)";let y=C.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},ao=C=>{if(!C)return"(empty)";try{let y=new URL(C,typeof window>"u"?"https://localhost":window.location.href),M=y.pathname.toLowerCase();return M.includes("checkcaptcha")||M.includes("captcha")?`CAPTCHA(${y.host}${M})`:M.includes("risk")||M.includes("challenge")?`RISK(${y.host}${M})`:M.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${M}`.slice(0,100)}catch{return C.slice(0,80)}},Vo=C=>{let y=C.getAttribute("src"),M=C.getAttribute("srcdoc"),ke=C.getAttribute("name"),Te=C.getAttribute("sandbox"),ie=[];return y&&ie.push(`src=${ao(y)}`),M&&ie.push(`srcdoc[${M.length}ch]`),!y&&!M&&ie.push("src=(empty) srcdoc=(empty)"),ke&&ie.push(`name=${ke.slice(0,40)}`),Te!==null&&ie.push(`sandbox="${Te.slice(0,40)}"`),ie.join(" ")},va=C=>{if(!(C instanceof HTMLIFrameElement))return"";try{let y=C.contentDocument;if(!y)return"cd=null";let M=y.body?.children.length??0,ke=y.body?.innerHTML.length??0,Te=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${M}children,${ke}ch] head[${Te}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},Cn=[],Hn=C=>{if(Xe())return;let y=C.message??String(C.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(I(`window:error ${y.slice(0,140)}`),Cn.push(y))},vo=C=>{if(Xe())return;let y=C.reason instanceof Error?C.reason.message:String(C.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(I(`window:rejection ${y.slice(0,140)}`),Cn.push(y))},Nt={value:0},Kn=()=>{Vr?.disconnect(),Vr=null,Bn?.disconnect(),Bn=null;for(let C of oo.splice(0))clearTimeout(C);ho=!1,Pn&&typeof window<"u"&&(window.removeEventListener("error",Hn),window.removeEventListener("unhandledrejection",vo)),Pn=!1},bn=()=>{if(!(Pn||Xe()||Rr)){if(Pn=!0,Cn.length=0,Nt.value=0,typeof window<"u"&&(window.addEventListener("error",Hn),window.addEventListener("unhandledrejection",vo)),typeof PerformanceObserver<"u")try{Bn=new PerformanceObserver(C=>{if(!Xe())for(let y of C.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Nt.value+=1;let M=Math.round(y.duration);I(`net ${M}ms ${y.name.slice(0,90)}`)}}),Bn.observe({type:"resource",buffered:!0})}catch{}Po?.()}},On=()=>{sn&&(clearTimeout(sn),sn=null)},Hr=()=>{Kn(),On()},ct={setEnabled:C=>{C?bn():Kn()}};D.current=ct,F.current&&bn();let ar=ze.isPayPalTeardownMessage,Kt=C=>{if(Xe()||ar(C))return;let y=(0,Fo.applyFriendlyMessageOverride)(C)??C;(0,He.invokeMerchantCallback)(()=>bt.current?.(y))},B=(C,y)=>{if(Ft||an)return;an=!0,nr=!0,Hr(),Fn();let M=uu({kind:C,generationActive:!0,automaticRetryAllowed:be,automaticRetryUsed:le.current});if(M.action==="retry"){le.current=!0,Ae(!1),Ke(!1),kt(!0),Cr.current?.("retrying"),hn=setTimeout(()=>{Ft||Be(ke=>ke+1)},su);return}if(Ae(!1),Ke(!1),kt(!1),xe(!0),M.action!=="ignore"){if(Cr.current?.("exhausted"),M.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}if(M.report){let ke=(0,_e.classifyExternalMethodFailure)({code:fc(C,y),message:y},{inAppBrowser:re.inAppBrowser,handoffObserved:!1});ke.popupBlocked&&X.markBlocked(),te.error({errorCode:ke.popupBlocked?ke.errorCode:M.report.errorCode,stage:M.report.stage,operationOutcome:M.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:ke.terminalReason})}It.current||(It.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",fc(C,y)))}};xe(!1);let U=async(C,y=Wt.current)=>{if(Xe())return;let M=y?.sessionId??e;if(Ct.current){await Ct.current(C,{sessionId:M,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let ke=te.startTiming();te.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Te=()=>{te.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"processing",durationMs:te.elapsed(ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let ie=(0,ze.buildPayPalProcessPaymentRequest)({body:C,sessionId:M,nonce:y?.nonce??Fr.current,accountPatch:y?.accountPatch,session:xr.current,email:Ur.current}),Ee=await new ki.PaymentAPI(st,{telemetry:!1}).processPayment(ie.userId,ie.params);if(Ee.ok){if(nr||Ft&&St.current)return;Te(),te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,He.invokeMerchantCallback)(()=>Mr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Xe())return;let $t=await Ee.json().catch(()=>null),Ht=(0,ze.describePayPalProcessFailure)($t),ut=Ht.message;Te(),Ee.status===400&&(typeof $t?.declineCode=="string"||!Array.isArray($t?.fields))?te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Ee.status===400||Ee.status===422?te.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):te.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:pu(Ee.status),failureCategory:Ee.status>=500?"server_error":void 0}),Kt(ut),(0,He.invokeMerchantCallback)(()=>un.current?.(kr("paypal",ut,{code:Ht.code,declineCode:Ht.declineCode})));return}catch(ie){if(Xe())return;Te(),te.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Me=(0,ze.friendlyPayPalFailureMessage)(ie instanceof Error?ie.message:void 0);Kt(Me),(0,He.invokeMerchantCallback)(()=>un.current?.(kr("paypal",Me)));return}},ne=()=>new ze.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),me=C=>Xe()?Promise.reject(ne()):Promise.resolve(C),Ut=async C=>{if(C.ok){te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,He.invokeMerchantCallback)(()=>Mr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let y=await C.json().catch(()=>null),M=(0,ze.describePayPalProcessFailure)(y);te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,He.invokeMerchantCallback)(()=>un.current?.(kr("paypal",M.message,{code:M.code,declineCode:M.declineCode})))},Jt=()=>{let C=Wt.current;qr("approved"),C&&(br.current.delete(C.surfaceKey),on(C.generation)),Wt.current=null},Fe=async C=>{if(Xe())throw ne();jo||xn();let y=Wt.current,M=y?.sessionId??e,ke=y?.nonce??Fr.current;te.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Te;try{Te=await new ki.PaymentAPI(st,{telemetry:!1}).createSessionIntent(M,ke??"",(0,ze.buildPayPalSessionIntentRequest)(no),{idempotencyKey:go})}catch(ie){throw te.error({...(0,ze.classifyTelemetryFailure)(ie,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ie}if(Xe())throw ne();if((0,ze.isSettledSessionIntent)(Te))throw await Ut(Te.response),Jt(),new ze.FloPayError("PayPal checkout already settled.","api_error",{code:mc});if(Te.provider!=="paypal"||Te.providerObjectType!==et)throw new Error(C);return te.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Te.providerObjectId},dt=(C,y)=>{let M=y?.nonce??Fr.current;if(!M)return;let ke=y?.sessionId??e,Te=(0,ze.resolvePayPalDeclineReason)(C);new ki.PaymentAPI(st,{telemetry:!1}).reportSessionIntentDecline(ke,M,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Te}).catch(()=>{})},z=Pe;I("loadScript:scheduled (deferred 1 tick)");let Ge=null,Re=setTimeout(()=>{if(Ft){I("loadScript:skipped (cancelled before defer ran)");return}I("loadScript:start");let C=Br==="live"?"production":Br,y={};et==="subscription"?y={intent:"subscription",vault:!0}:et==="order"&&(y={intent:"capture"}),Ge=(0,gc.loadScript)({clientId:d,currency:m,...y,...C?{environment:C}:{},...C==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let M=!1;Ge.then(ke=>{if(M=!0,I(`loadScript:resolved inactive=${Xe()} ns=${!!ke} buttons=${!!ke?.Buttons}`),Xe())return;if(!ke?.Buttons){I("FAIL: namespace missing Buttons factory"),B("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}te.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"provider_ready",durationMs:te.elapsed(Ze.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),te.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Te=async(ue,ye)=>{if(Xe()||at.current!==z)return;let $e=ue.vaultSetupToken??ue.subscriptionID??ue.orderID??"",tt=$e?Tt.current.get($e):br.current.get(z);if(!(!tt||!Qt(tt.generation))&&on(tt.generation)){Tt.current.delete($e),br.current.delete(tt.surfaceKey),qr("approved");try{if(Ke(!0),(0,He.invokeMerchantCallback)(()=>bt.current?.(null)),!$e)throw new ze.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let De=(0,ze.resolvePayPalApprovalIdentity)({accountPatch:tt.accountPatch,email:Ur.current,billingName:pn.current,session:xr.current});if((0,ze.needsPayPalPayerDetails)(De))try{De=(0,ze.mergePayPalPayerIdentity)(De,await ye?.order?.get?.())}catch{}if((Xt.current||Qe)&&!(0,ze.isValidEmail)(De.email)){let Yt=await it("PayPal",De);if(!Yt)return;De=Yt}(0,ze.isValidEmail)(De.email)&&(tt.accountPatch=(0,kn.compactBuyerIdentity)({...tt.accountPatch,...De}),await Xt.current?.(De));let en=(0,ze.buildPayPalTokenizedBody)($e,no);await U(en,tt)}catch(De){Kt(De instanceof Error?De.message:"PayPal capture failed.")}finally{Xe()||Ke(!1)}}},ie=ue=>{let ye=Ie?()=>me(Ie):()=>Fe(ue);return async()=>$r(await ye())},Me=ke.Buttons({style:{layout:"horizontal",height:Ei,tagline:!1},...Q==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ue,ye)=>{if(Xe()){await ye.reject();return}xn();let $e=Jr.current,tt={};if($e)try{let Yt=await $e("paypal");if(Xe()){await ye.reject();return}if(!Yt.proceed){Wt.current=null,br.current.delete(z),await ye.reject();return}tt={sessionId:Yt.sessionId,accountPatch:Yt.accountPatch,nonce:Yt.nonce}}catch(Yt){I(`onClick:runBeforeButtonClick rejected msg=${(Yt instanceof Error?Yt.message:String(Yt)).slice(0,120)}`),Wt.current=null,br.current.delete(z),await ye.reject();return}(0,He.invokeMerchantCallback)(()=>At.current?.("paypal"));let De=yr(),en={generation:De,surfaceKey:z,...tt};Wt.current=en,br.current.set(z,en),qe.current={...P,attempt:De},await ye.resolve(),te.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Se.current=te.startTiming()},createOrder:et==="order"?ie("Failed to create PayPal order."):void 0,createSubscription:et==="subscription"?ie("Failed to create PayPal subscription."):void 0,createVaultSetupToken:et==="setup_token"?async()=>$r(await Fe("Failed to create PayPal setup token.")):void 0,onApprove:Te,onCancel:()=>{if(Xe())return;let ue=br.current.get(z)??Wt.current,ye=ue&&Qt(ue.generation)?(0,ze.buildPayPalCancelEvent)(ue.sessionId??e,no):null;ue&&br.current.delete(ue.surfaceKey),Wt.current=null,qr("cancelled"),te.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),pe.current=!0,wr({generation:ue?.generation,remount:!0,focus:!1}),ye&&(0,He.invokeMerchantCallback)(()=>gt.current?.(ye))},onError:ue=>{if(ue instanceof ze.FloPayError&&ue.code===mc)return;let ye=ue instanceof Error?ue.message:"PayPal failed to render.";if(Xe()||at.current!==z){ar(ye)||mr(Je());return}if(Rr){let $e=br.current.get(z)??Wt.current;if(!$e||!Qt($e.generation)){if(ar(ye)){!$e&&!Sr()&&on();return}mr($e||Sr()?"stale_attempt":"no_current_attempt");return}if(I(`onError rendered=${Rr} msg=${ye.slice(0,120)}`),ar(ye)){on($e.generation);return}let{errorCode:tt,popupBlocked:De,providerDeclined:en,terminalReason:Yt}=(0,_e.classifyExternalMethodFailure)(ue,{inAppBrowser:re.inAppBrowser,handoffObserved:Z.current===$e.generation});if(De&&X.markBlocked(),qr(Yt),en){te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Yt}),dt(ue,$e),(0,He.invokeMerchantCallback)(()=>un.current?.(kr("paypal",ye))),br.current.delete($e.surfaceKey),Wt.current=null,on($e.generation);return}te.error({errorCode:tt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Yt}),br.current.delete($e.surfaceKey),Wt.current=null,wr({generation:$e.generation,remount:!0,showRetry:!0,focus:!0}),mn(ue,{code:"paypal_runtime_failed",popupBlocked:De,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Q,terminalReason:Yt});return}I(`onError rendered=${Rr} msg=${ye.slice(0,120)}`),B(ar(ye)?"teardown":"pre_ready_callback",ye)}}),Ee=Me.isEligible();if(I(`isEligible=${Ee}`),te.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Ee){Ae(!1),B("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}$n=!0,Qr=Me,Po=()=>{if(!Pn||ho||Xe()||Rr)return;ho=!0,I(`container:dims ${vn(ht)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Vr=new MutationObserver(ye=>{if(!Xe()){for(let $e of ye)if($e.type==="childList")$e.addedNodes.forEach(tt=>{if(!(tt instanceof Element))return;let De=tt.tagName.toLowerCase(),en=(tt.getAttribute("title")??"").slice(0,40),Yt=De==="iframe"?` ${Vo(tt)}`:"";I(`child+ ${De}${en?` title="${en}"`:""}${Yt} dims=${vn(tt)}`)});else if($e.type==="attributes"&&$e.target instanceof Element){let tt=$e.target;if(tt.tagName.toLowerCase()!=="iframe")continue;let De=$e.attributeName;(De==="src"||De==="srcdoc")&&I(`attr~ iframe ${De}=${De==="srcdoc"?`[${(tt.getAttribute("srcdoc")??"").length}ch]`:ao(tt.getAttribute("src"))} dims=${vn(tt)}`)}}}),Vr.observe(ht,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ue=ye=>{if(Xe()||Rr)return;let $e=ht.querySelectorAll("iframe"),tt=typeof document<"u"&&"hasStorageAccess"in document;I(`watchdog:${ye} container=${vn(ht)} children=${ht.childElementCount} iframes=${$e.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${tt} paypalNetRequests=${Nt.value}`),$e.forEach((De,en)=>{let Yt=(De.getAttribute("title")??"").slice(0,40);I(` iframe[${en}] ${vn(De)}${Yt?` title="${Yt}"`:""} ${Vo(De)}`);let Wo=va(De);Wo&&I(` ${Wo}`)}),Cn.length===0&&I(" (no PayPal/zoid window errors captured)")};oo.push(setTimeout(()=>ue("3s"),3e3)),oo.push(setTimeout(()=>ue("8s"),8e3)),oo.push(setTimeout(()=>ue("15s"),15e3))},Po(),I("render:start");let Ht=te.startTiming();sn=setTimeout(()=>{Xe()||Rr||(I("watchdog:11s retryable render timeout"),B("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},lu);let ut=Me.render(ht);(async()=>{try{if(await ut,I(`render:resolved inactive=${Xe()}`),Hr(),Xe()){Fn();return}Rr=!0,Ae(!0),kt(!1),Cr.current?.("ready"),te.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"checkout_render",durationMs:te.elapsed(Ht),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ue){let ye=ue instanceof Error?ue.message:"PayPal failed to render.";I(`render:rejected msg=${ye.slice(0,120)}`),Hr(),B(ar(ye)?"teardown":"render_rejected",ye)}})()}).catch(ke=>{let Te=ke instanceof Error?ke.message:"PayPal operation failed.";I(`provider:failed msg=${Te.slice(0,120)}`);let ie="script_rejected";M&&ar(Te)?ie="teardown":M&&$n&&(ie="render_rejected"),B(ie,Te)})},0);return()=>{Ft=!0,clearTimeout(Re),hn&&clearTimeout(hn),Hr(),D.current===ct&&(D.current=null),Fn(),Se.current=null,qe.current=null}},[be,st,d,m,p,et,Q,ee,e,Ie,Pe,G,it,Qe,I,qr]);let Or=q?(0,En.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Vt?"#fef2f2":"#f3f4f6",border:`1px solid ${Vt?"#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=${we} failed=${Vt})`,L.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${U.join(`
4
- `)}`]}):null;return Ut&&!u?q?(0,_n.jsx)("div",{children:et}):null:(0,_n.jsxs)("div",{children:[et,Qe&&(0,_n.jsx)(da,{identity:Qe.identity,methodLabel:Qe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:nt,onCancel:()=>nt(null)}),(0,_n.jsxs)("div",{"aria-hidden":Me||Qe?!0:void 0,style:Me||Qe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ei},children:[!ve&&!Me&&(0,_n.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,_n.jsx)("div",{ref:K,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ei,display:"flex",opacity:ve?1:0},"aria-busy":he||H},ge)]},ge),ut&&(0,_n.jsx)("button",{ref:ft,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:gn,style:iu,children:"Try PayPal again"})]})}function Oa(e){return(0,_n.jsx)(fc,{...e})}function gc(e){return(0,_n.jsx)(fc,{...e})}var Da=require("react/jsx-runtime");function ma({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,Da.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,Da.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Da.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 Ct=require("@flopay/shared");var hc=new Set;function du(){return globalThis.process?.env?.NODE_ENV==="production"}function Pc(e,t){hc.has(e)||du()||(hc.add(e),console.warn(t))}function vc(){Pc("automatic-payment-button-inline-create","[FloPay] FloPayAutomaticPaymentButton: creating the session from inline props is deprecated and may be downgraded to a Full checkout. Mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and pass `getSession` instead.")}function Cc(){Pc("checkout-keyless-create","[FloPay] FloPayCheckout: `createSession` with checkoutMode confirm/auto is deprecated and may be downgraded to a Full checkout. For one-click, mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and use FloPayAutomaticPaymentButton `getSession`.")}var Pr=require("react/jsx-runtime");var uu={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function an({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:s="PAYMENT FAILED",successNote:d="You will be automatically redirected, do not close or navigate away from this window.",theme:p=uu}){let y={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,Pr.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,Pr.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,Pr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Pr.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,Pr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,Pr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,Pr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Pr.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,Pr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Pr.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,Pr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Pr.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,Pr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Pr.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,Pr.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,Pr.jsx)("p",{style:y,children:d}),e==="error"&&t&&(0,Pr.jsx)("p",{style:y,children:t}),(0,Pr.jsx)("style",{children:`
3
+ ${L.join(`
4
+ `)}`]}):null;return Vt&&!u?q?(0,En.jsx)("div",{children:Or}):null:(0,En.jsxs)("div",{children:[Or,vt&&(0,En.jsx)(da,{identity:vt.identity,methodLabel:vt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:ft,onCancel:()=>ft(null)}),(0,En.jsxs)("div",{"aria-hidden":Ce||vt?!0:void 0,style:Ce||vt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ei},children:[!we&&!Ce&&(0,En.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,En.jsx)("div",{ref:K,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ei,display:"flex",opacity:we?1:0},"aria-busy":Oe||H},Pe)]},Pe),yt&&(0,En.jsx)("button",{ref:Pt,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:An,style:cu,children:"Try PayPal again"})]})}function Da(e){return(0,En.jsx)(hc,{...e})}function Pc(e){return(0,En.jsx)(hc,{...e})}var La=require("react/jsx-runtime");function ya({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,La.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,La.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,La.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 wt=require("@flopay/shared");var vc=new Set;function yu(){return globalThis.process?.env?.NODE_ENV==="production"}function Cc(e,t){vc.has(e)||yu()||(vc.add(e),console.warn(t))}function bc(){Cc("automatic-payment-button-inline-create","[FloPay] FloPayAutomaticPaymentButton: creating the session from inline props is deprecated and may be downgraded to a Full checkout. Mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and pass `getSession` instead.")}function Sc(){Cc("checkout-keyless-create","[FloPay] FloPayCheckout: `createSession` with checkoutMode confirm/auto is deprecated and may be downgraded to a Full checkout. For one-click, mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and use FloPayAutomaticPaymentButton `getSession`.")}var Pr=require("react/jsx-runtime");var mu={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function rn({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:s="PAYMENT FAILED",successNote:d="You will be automatically redirected, do not close or navigate away from this window.",theme:p=mu}){let m={fontSize:13,color:p.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,Pr.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,Pr.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,Pr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Pr.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,Pr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:p.spinnerTrackColor,strokeWidth:"3"}),(0,Pr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:p.spinnerAccentColor})]}),e==="success"&&(0,Pr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Pr.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,Pr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Pr.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,Pr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Pr.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,Pr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Pr.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,Pr.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,Pr.jsx)("p",{style:m,children:d}),e==="error"&&t&&(0,Pr.jsx)("p",{style:m,children:t}),(0,Pr.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 _i=require("@flopay/shared"),Sr=require("react");var bc=require("react/jsx-runtime");function La({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,d]=(0,Sr.useState)(e instanceof Promise?null:e),[p,y]=(0,Sr.useState)(t instanceof Promise||!t?null:t),b=(0,Sr.useRef)(null),P=(0,Sr.useRef)(null),h=pa(n),E=(0,Sr.useCallback)(w=>{(0,_i.isCardFieldsInstrumentSource)(w)||h(w)},[h]);(0,Sr.useEffect)(()=>{h({class:"lifecycle",name:"checkout.mount"})},[h]),(0,Sr.useEffect)(()=>{s&&h({class:"lifecycle",name:"sdk.initialize.ready"})},[h,s]),(0,Sr.useEffect)(()=>{if(s)return br(s)?.subscribe?.(E)},[E,s]),(0,Sr.useEffect)(()=>{if(!(!p||p===s))return br(p)?.subscribe?.(E)},[E,s,p]),(0,Sr.useEffect)(()=>{if(!s)return;let w=br(s);return b.current=w?.beginCheckout()??w?.now()??0,w?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{w?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,Sr.useEffect)(()=>{let w=!1;return e instanceof Promise?e.then(T=>{w||d(T)},()=>{w||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{w=!0}},[h,e]),(0,Sr.useEffect)(()=>{let w=!1;if(!t){y(null);return}return t instanceof Promise?t.then(T=>{w||y(T)},()=>{w||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{w=!0}},[h,t]),(0,Sr.useEffect)(()=>{if(!s||P.current===s)return;P.current=s;let w=br(s);w?.log({name:"checkout.rendered",stage:"checkout_render"}),h({class:"lifecycle",name:"checkout.rendered"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(b.current??0),durationMode:"machine"})},[h,s]);let V=(0,_i.resolveBillingApiUrl)(r?.billingApiUrl),W=(0,Sr.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:V,emitInstrument:h}),[s,p,V,h]);return(0,bc.jsx)(kn.Provider,{value:W,children:a})}var Vn=require("@flopay/shared");async function Ii(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 Jr=require("@flopay/js"),$e=require("@flopay/shared");var za="card";async function pu(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 mu(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 ya(e){return new $e.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function yu(){return new $e.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Ua(e,t){return Object.assign(e,{checkoutMethod:t})}function po(e,t){let r=e instanceof $e.FloPayError?e:new $e.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 Na(e,t){try{return await e()}catch(r){throw po(r,t)}}function wc(e){return!e?.type||!e.threeDSecureToken||(0,$e.isMerchantAuthRequired)(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Rc(e){return(0,Jr.runSavedCardChallenge)(e)}function qa(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new Jr.PaymentAPI(e),d=(0,Jr.beginSavedCardChallengeTelemetry)(s,t,r);return d?{telemetry:d,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function fa(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,d=new Jr.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,y;try{y=await(0,Jr.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 $e.FloPayError&&P.code==="three_ds_aborted"?P:ya(P);if(!(P instanceof $e.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(E){if(a.aborted)throw ya(E);if(!(E instanceof $e.FloPayError)||E.code!=="checkout_processing_timeout")throw E}let h=y&&Ro(y,t.session);if(!lo(h)&&h?.status!=="expired"){if(t.telemetry){let E=new Jr.PaymentAPI(r);try{E.reportThreeDsAbandoned(n)}finally{E.destroy()}}throw yu()}}let b=y&&Ro(y,t.session);if(!lo(b))throw sa(b);return{...so(b,n),checkoutMethod:"card"}}function kc(e){return new $e.FloPayError("This payment needs your card details. Please complete your payment below.","authentication_error",{code:$e.MERCHANT_AUTH_REQUIRED_CODE,...e===void 0?{}:{statusCode:e}})}function eo(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if((0,$e.isMerchantAuthRequired)(e))return Ua(kc(),n);let a=e?.message??t,s=(0,Bo.applyFriendlyMessageOverride)(a)??a,d=Ua(new $e.FloPayError(s,"api_error",{code:e?.code??(0,$e.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,$e.normalizeCheckoutFailureOutcome)(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),n);return e?.orderId&&(d.orderId=e.orderId),d}function As(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Ec(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ti(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||Ti(p)))return p;let d=a.gateways;if(d&&typeof d=="object"){let p=d.stripe;if(p&&typeof p=="object"){let y=p,b=[y.stripeClientSecret,y.clientSecret];for(let P of b)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||Ti(P)))return P}}}}async function fu({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Ec(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 Jr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(Ti(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function ga({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:d}){let p=e.replace(/\/+$/,""),y=t??r.id,b=n??r.clientSecret,P=r.customer?.id??r.accountData?.userId??"",h=r.customer?.email??r.accountData?.email??"",E=r.customer?.firstName??r.accountData?.firstName??"",V=r.customer?.lastName??r.accountData?.lastName??"",W=r.customer?.country??r.accountData?.country??void 0,w=r.customer?.zip??r.accountData?.zip??void 0,f=await new Jr.PaymentAPI(p,d===!1?{telemetry:!1}:void 0).processPayment(P,{sessionId:y,nonce:b,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:P,email:h,firstName:E,lastName:V,country:W,zip:w},returnUrl:s??As(r)});if(f.ok){let X=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,$e.isAuthorizationOnlySession)(r)||X?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof X?.paymentId=="string"?X.paymentId:r.paymentId,sessionId:typeof X?.sessionId=="string"?X.sessionId:y,authorizationExpiresAt:typeof X?.authorizationExpiresAt=="string"?X.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:Aa(a),checkoutMethod:Sc(a,r)}};let v=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...v?{paymentIntentId:v}:{},paymentMethodId:Aa(a),checkoutMethod:Sc(a,r)}}}let H;try{H=await f.json()}catch(X){throw new $e.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:X})}if((0,$e.isMerchantAuthRequired)(H))throw Ua(kc(f.status),"card");if(H?.type==="3ds_required"&&typeof H.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:H.nextActionRedirectUrl};if(H?.type==="paypal_redirect_required"||H?.type==="3ds_required"){let X=Ec(H);if(!X)throw new $e.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:H.type,threeDSecureToken:X,paymentMethodId:H.paymentMethodId}}if(H?.gatewayErrorCode==="authentication_required"){let X=await fu({billingApiUrl:p,sessionId:y,nonce:b,responseJson:H});if(X)return X;throw Ua(new $e.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw gu(H,f.status)}function gu(e,t){let r=new $e.FloPayError(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(r,{telemetryOutcome:(0,$e.classifyPaymentRejection)(t,e)})}async function Mi(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:y,signal:b}){let P=t?.getRawProvider();if(!P)throw po(new $e.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw Ua(new $e.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=(0,$e.isSetupIntentClientSecret)(e.threeDSecureToken),E=null,V=e.paymentMethodId,W=await Na(()=>pu(P,e.threeDSecureToken,h),"card");if(W){if(W.error)throw po(new $e.FloPayError(W.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:W.error.code}),"card");let T=W.intent;!V&&T?.payment_method&&(typeof T.payment_method=="string"?V=T.payment_method:"id"in T.payment_method&&(V=T.payment_method.id??void 0))}let w=V?await Na(()=>mu(P,e.threeDSecureToken,{payment_method:V,return_url:p??As(d)??window.location.href},h),"card"):null;if(w){if(w.error)throw po(new $e.FloPayError(w.error.message??"3DS authentication failed.","api_error",{code:w.error.code}),"card");E=w.intent}else{let T=await Na(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(T.error)throw po(new $e.FloPayError(T.error.message??"3DS authentication failed.","api_error",{code:T.error.code}),"card");E=(h?T.setupIntent:T.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let T=await ga({billingApiUrl:a,sessionId:s,session:d,telemetry:y,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:p});return T.type==="success"?{...T.result,paymentIntentId:T.result.paymentIntentId??E.id,paymentMethodId:T.result.paymentMethodId??V}:T.type==="next_action_required"?fa(T,{billingApiUrl:a,sessionId:s??d.id,session:d,signal:b}):Mi(T,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:y,signal:b})}throw po(new $e.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(r??t)?.getRawProvider();if(!h)throw po(new $e.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:V}=await Na(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(V)throw po(new $e.FloPayError(V.message??"PayPal authorization failed.","api_error",{code:V.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await Na(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??As(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(E)throw po(new $e.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new $e.FloPayError("Unsupported payment redirect state.","api_error")}function ja(e){if(e instanceof $e.FloPayError){let n=(0,Bo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new $e.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,Bo.applyFriendlyMessageOverride)(t)??t;return new $e.FloPayError(r,"api_error")}function xs(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,$e.isMountableVaultBlock)(e.data.session?.vault)||(0,zn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new $e.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 Sc(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,zn.canRecoverHostedCardForm)(t)?"card":void 0}async function Fs({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let s=t&&t!==e?t:void 0,[d,p]=await Promise.all([(0,Jr.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,Jr.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(b=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",b),null)):Promise.resolve(null)]);if(!d)throw new $e.FloPayError("The payment provider did not initialize.","authentication_error");let y=null;return s?y=p:t&&(y=d),{flopay:d,paypalFlopay:y}}var $n=require("@flopay/js"),c=require("@flopay/shared"),lr=require("@stripe/react-stripe-js"),o=Rs(require("react"),1);function Lo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ai(e,t){if(e)return{error:r=>e.error(Lo(t,r)),log:r=>e.log(Lo(t,r)),performance:r=>e.performance(Lo(t,r)),terminal:r=>e.terminal(Lo(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 No=require("react"),Uo=require("react/jsx-runtime"),_c="More payment options",hu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Pu={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Bs({label:e,open:t,showLink:r,onOpen:n,color:a,fontFamily:s,children:d}){let p=(0,No.useId)(),y=(0,No.useRef)(null),b=(0,No.useRef)(!1);return(0,No.useEffect)(()=>{t&&b.current&&y.current?.focus()},[t]),(0,Uo.jsxs)(Uo.Fragment,{children:[!t&&r&&(0,Uo.jsx)("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":p,onClick:()=>{b.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,Uo.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?Pu:hu,children:d})]})}var mo=require("@flopay/shared"),Tc=require("react");var Ic={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 Mr=require("react/jsx-runtime"),vu=`
9
+ `})]})})}var _i=require("@flopay/shared"),_r=require("react");var wc=require("react/jsx-runtime");function Na({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[s,d]=(0,_r.useState)(e instanceof Promise?null:e),[p,m]=(0,_r.useState)(t instanceof Promise||!t?null:t),w=(0,_r.useRef)(null),h=(0,_r.useRef)(null),g=pa(n),_=(0,_r.useCallback)(k=>{(0,_i.isCardFieldsInstrumentSource)(k)||g(k)},[g]);(0,_r.useEffect)(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),(0,_r.useEffect)(()=>{s&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,s]),(0,_r.useEffect)(()=>{if(s)return Er(s)?.subscribe?.(_)},[_,s]),(0,_r.useEffect)(()=>{if(!(!p||p===s))return Er(p)?.subscribe?.(_)},[_,s,p]),(0,_r.useEffect)(()=>{if(!s)return;let k=Er(s);return w.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[s]),(0,_r.useEffect)(()=>{let k=!1;return e instanceof Promise?e.then(A=>{k||d(A)},()=>{k||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{k=!0}},[g,e]),(0,_r.useEffect)(()=>{let k=!1;if(!t){m(null);return}return t instanceof Promise?t.then(A=>{k||m(A)},()=>{k||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{k=!0}},[g,t]),(0,_r.useEffect)(()=>{if(!s||h.current===s)return;h.current=s;let k=Er(s);k?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(w.current??0),durationMode:"machine"})},[g,s]);let V=(0,_i.resolveBillingApiUrl)(r?.billingApiUrl),W=(0,_r.useMemo)(()=>({flopay:s,paypalFlopay:p,billingApiUrl:V,emitInstrument:g}),[s,p,V,g]);return(0,wc.jsx)(Rn.Provider,{value:W,children:a})}var jn=require("@flopay/shared");async function Ii(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 Gr=require("@flopay/js"),je=require("@flopay/shared");var qa="card";async function fu(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 gu(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 ma(e){return new je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function hu(){return new je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function za(e,t){return Object.assign(e,{checkoutMethod:t})}function po(e,t){let r=e instanceof je.FloPayError?e:new je.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 Ua(e,t){try{return await e()}catch(r){throw po(r,t)}}function kc(e){return!e?.type||!e.threeDSecureToken||(0,je.isMerchantAuthRequired)(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Ec(e){return(0,Gr.runSavedCardChallenge)(e)}function ja(e,t,r,n=!0){let a={release:()=>{}};if(!n)return a;try{let s=new Gr.PaymentAPI(e),d=(0,Gr.beginSavedCardChallengeTelemetry)(s,t,r);return d?{telemetry:d,release:()=>{setTimeout(()=>{try{s.destroy()}catch{}},0)}}:a}catch{return a}}async function fa(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,s=t.nonce??t.session.clientSecret,d=new Gr.PaymentAPI(r,{telemetry:!1}),p=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,m;try{m=await(0,Gr.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:s,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:h=>Qn({type:h.declineReason??"authorization_declined",gatewayErrorCode:h.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},d)}catch(h){if(a.aborted||h instanceof Error&&h.name==="AbortError")throw h instanceof je.FloPayError&&h.code==="three_ds_aborted"?h:ma(h);if(!(h instanceof je.FloPayError)||h.code!=="three_ds_timeout"&&h.code!=="checkout_processing_timeout")throw h;try{m=await d.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:s,statusUrl:p,timeoutMs:5e3,signal:a})}catch(_){if(a.aborted)throw ma(_);if(!(_ instanceof je.FloPayError)||_.code!=="checkout_processing_timeout")throw _}let g=m&&ko(m,t.session);if(!lo(g)&&g?.status!=="expired"){if(t.telemetry){let _=new Gr.PaymentAPI(r);try{_.reportThreeDsAbandoned(n)}finally{_.destroy()}}throw hu()}}let w=m&&ko(m,t.session);if(!lo(w))throw sa(w);return{...so(w,n),checkoutMethod:"card"}}function _c(e){return new je.FloPayError("This payment needs your card details. Please complete your payment below.","authentication_error",{code:je.MERCHANT_AUTH_REQUIRED_CODE,...e===void 0?{}:{statusCode:e}})}function Qn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if((0,je.isMerchantAuthRequired)(e))return za(_c(),n);let a=e?.message??t,s=(0,Fo.applyFriendlyMessageOverride)(a)??a,d=za(new je.FloPayError(s,"api_error",{code:e?.code??(0,je.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,je.normalizeCheckoutFailureOutcome)(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),n);return e?.orderId&&(d.orderId=e.orderId),d}function Fs(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Ic(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ti(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||Ti(p)))return p;let d=a.gateways;if(d&&typeof d=="object"){let p=d.stripe;if(p&&typeof p=="object"){let m=p,w=[m.stripeClientSecret,m.clientSecret];for(let h of w)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Ti(h)))return h}}}}async function Pu({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=Ic(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 Gr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(Ti(p))return{type:"3ds_required",threeDSecureToken:p}}catch{}return null}async function ga({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:s,telemetry:d}){let p=e.replace(/\/+$/,""),m=t??r.id,w=n??r.clientSecret,h=r.customer?.id??r.accountData?.userId??"",g=r.customer?.email??r.accountData?.email??"",_=r.customer?.firstName??r.accountData?.firstName??"",V=r.customer?.lastName??r.accountData?.lastName??"",W=r.customer?.country??r.accountData?.country??void 0,k=r.customer?.zip??r.accountData?.zip??void 0,f=await new Gr.PaymentAPI(p,d===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:m,nonce:w,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:h,email:g,firstName:_,lastName:V,country:W,zip:k},returnUrl:s??Fs(r)});if(f.ok){let Y=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,je.isAuthorizationOnlySession)(r)||Y?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof Y?.paymentId=="string"?Y.paymentId:r.paymentId,sessionId:typeof Y?.sessionId=="string"?Y.sessionId:m,authorizationExpiresAt:typeof Y?.authorizationExpiresAt=="string"?Y.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:xa(a),checkoutMethod:Rc(a,r)}};let b=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...b?{paymentIntentId:b}:{},paymentMethodId:xa(a),checkoutMethod:Rc(a,r)}}}let H;try{H=await f.json()}catch(Y){throw new je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:Y})}if((0,je.isMerchantAuthRequired)(H))throw za(_c(f.status),"card");if(H?.type==="3ds_required"&&typeof H.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:H.nextActionRedirectUrl};if(H?.type==="paypal_redirect_required"||H?.type==="3ds_required"){let Y=Ic(H);if(!Y)throw new je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:H.type,threeDSecureToken:Y,paymentMethodId:H.paymentMethodId}}if(H?.gatewayErrorCode==="authentication_required"){let Y=await Pu({billingApiUrl:p,sessionId:m,nonce:w,responseJson:H});if(Y)return Y;throw za(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw vu(H,f.status)}function vu(e,t){let r=new je.FloPayError(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(r,{telemetryOutcome:(0,je.classifyPaymentRejection)(t,e)})}async function Mi(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:m,signal:w}){let h=t?.getRawProvider();if(!h)throw po(new je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw za(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=(0,je.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,V=e.paymentMethodId,W=await Ua(()=>fu(h,e.threeDSecureToken,g),"card");if(W){if(W.error)throw po(new je.FloPayError(W.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:W.error.code}),"card");let A=W.intent;!V&&A?.payment_method&&(typeof A.payment_method=="string"?V=A.payment_method:"id"in A.payment_method&&(V=A.payment_method.id??void 0))}let k=V?await Ua(()=>gu(h,e.threeDSecureToken,{payment_method:V,return_url:p??Fs(d)??window.location.href},g),"card"):null;if(k){if(k.error)throw po(new je.FloPayError(k.error.message??"3DS authentication failed.","api_error",{code:k.error.code}),"card");_=k.intent}else{let A=await Ua(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(A.error)throw po(new je.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");_=(g?A.setupIntent:A.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let A=await ga({billingApiUrl:a,sessionId:s,session:d,telemetry:m,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:p});return A.type==="success"?{...A.result,paymentIntentId:A.result.paymentIntentId??_.id,paymentMethodId:A.result.paymentMethodId??V}:A.type==="next_action_required"?fa(A,{billingApiUrl:a,sessionId:s??d.id,session:d,signal:w}):Mi(A,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:s,session:d,returnUrl:p,telemetry:m,signal:w})}throw po(new je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(r??t)?.getRawProvider();if(!g)throw po(new je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:V}=await Ua(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(V)throw po(new je.FloPayError(V.message??"PayPal authorization failed.","api_error",{code:V.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await Ua(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:p??Fs(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw po(new je.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new je.FloPayError("Unsupported payment redirect state.","api_error")}function Va(e){if(e instanceof je.FloPayError){let n=(0,Fo.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new je.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 je.FloPayError(r,"api_error")}function Bs(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,je.isMountableVaultBlock)(e.data.session?.vault)||(0,Un.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new je.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 Rc(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Un.canRecoverHostedCardForm)(t)?"card":void 0}async function Os({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,Gr.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),s?(0,Gr.loadFloPay)(s,{billingApiUrl:r,locale:n,telemetry:a}).catch(w=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",w),null)):Promise.resolve(null)]);if(!d)throw new je.FloPayError("The payment provider did not initialize.","authentication_error");let m=null;return s?m=p:t&&(m=d),{flopay:d,paypalFlopay:m}}var Wn=require("@flopay/js"),c=require("@flopay/shared"),lr=require("@stripe/react-stripe-js"),o=Es(require("react"),1);function Do(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ai(e,t){if(e)return{error:r=>e.error(Do(t,r)),log:r=>e.log(Do(t,r)),performance:r=>e.performance(Do(t,r)),terminal:r=>e.terminal(Do(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"),Tc="More payment options",Cu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},bu={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Ds({label:e,open:t,showLink:r,onOpen:n,color:a,fontFamily:s,children:d}){let p=(0,Lo.useId)(),m=(0,Lo.useRef)(null),w=(0,Lo.useRef)(!1);return(0,Lo.useEffect)(()=>{t&&w.current&&m.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:()=>{w.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:m,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?bu:Cu,children:d})]})}var yo=require("@flopay/shared"),Ac=require("react");var Mc={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 Lr=require("react/jsx-runtime"),Su=`
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 @@ ${U.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
- `,ko=44;function ha(){return(0,Mr.jsx)("style",{children:vu})}function Va(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function Wa({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Mr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Mr.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,Mr.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 $a(e){return e!=="unavailable"&&e!=="load_error"}function xi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:d,backgroundColor:p,borderColor:y,textColor:b,borderRadius:P,fontFamily:h}){let E=(0,mo.resolveStripeMethodBrandVariant)(e,t),V=Ic[e],[W,w]=(0,Tc.useState)(!1),T=!!V&&!W,f=E?.backgroundColor??p??"#ffffff",H=E?.borderColor??y??"#d1d5db",X=E?.textColor??b??"#262833";return(0,Mr.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:ko,padding:"0 1rem",backgroundColor:f,color:X,border:`1px solid ${H}`,borderRadius:P??8,fontSize:"0.95rem",fontWeight:600,fontFamily:h,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,Mr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,mo.getStripeMethodDisplayName)(e)}\u2026`}):(0,Mr.jsxs)(Mr.Fragment,{children:[(0,Mr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,mo.hasVendoredStripeMethodLogo)(e)?8:0},children:[T?(0,Mr.jsx)("img",{src:V,alt:"","aria-hidden":"true",onError:()=>w(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!T&&E?.logoSvg?(0,Mr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:E.logoSvg}}):null,(0,Mr.jsx)("span",{children:(0,mo.getStripeMethodDisplayName)(e)})]}),s&&(0,Mr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:X,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,Mr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Fi(e){let t=new Set(e.map(mo.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var Bi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Oi={type:"accordion",defaultCollapsed:!1,radios:"never"};function Di({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:d,children:p}){return(0,Mr.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 Os=require("react/jsx-runtime"),Cu=["first","second","third","fourth"];function Ds({rows:e,borderRadius:t}){return(0,Os.jsx)("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Cu.slice(0,Math.max(1,e)).map(r=>(0,Os.jsx)("div",{style:{height:ko,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},r))})}var Ac=require("@flopay/js"),Li=require("@flopay/shared"),Ni=require("react"),bu=1500,Mc=new Set;function xc(e){for(let t of e)Mc.has(t)||(Mc.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function Su(e){if(e!=null)try{return JSON.stringify(e)}catch{return xc(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var wu={order:[...Li.DEFAULT_PAYMENT_METHOD_ORDER],moreOptions:[]};function Fc({rules:e,sessionId:t,nonce:r,billingApiUrl:n,waitForSession:a}){let s=Su(e),[d,p]=(0,Ni.useState)(null);return(0,Ni.useEffect)(()=>{if(s===void 0||a)return;let y=JSON.parse(s),b=!1,P=W=>{b||(b=!0,p(W))},h=()=>P((0,Li.resolveDefaultPaymentMethodLayout)(y));if(!t||!r||!n){h();return}let E=new AbortController,V=setTimeout(()=>{h(),E.abort()},bu);return new Ac.PaymentAPI(n,{telemetry:!1}).resolvePaymentMethodLayout(t,r,y,{signal:E.signal}).then(W=>{if(!W){h();return}b||xc(W.warnings),P({order:W.order,moreOptions:W.moreOptions})}).catch(h).finally(()=>clearTimeout(V)),()=>{b=!0,clearTimeout(V),E.abort()}},[s,t,r,n,a]),s===void 0?wu:d}var fn=require("react");var Ha=require("@flopay/shared"),Ru=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 ku(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Ru.has(t.charAt(0).toLowerCase()+t.slice(1))}function Eu(e,t){return typeof t=="number"&&t!==0&&!ku(e)?`${t}px`:String(t).trim()}function Bc(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]=Eu(r,n)}}}var zo=require("react/jsx-runtime"),Ls=new WeakSet;function Eo({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:d,containerStyle:p,onReady:y,onError:b,onValidation:P}){let h=(0,fn.useRef)(null),E=(0,fn.useRef)(y),V=(0,fn.useRef)(b),W=(0,fn.useRef)(P);E.current=y,V.current=b,W.current=P;let w=(0,fn.useRef)(s);w.current=s;let T=(0,fn.useRef)(null),f=d??void 0,H=(0,fn.useRef)(f);H.current=f;let X=(0,fn.useRef)(void 0);return(0,fn.useEffect)(()=>{let v=h.current;if(!v)return;let Se=!0,M=!1,oe=()=>{!Se||M||(M=!0,E.current?.())},ye=e.on("ready",()=>{oe()}),Ee=e.on("error",q=>{V.current?.(q.message??"There was a problem loading the secure card form.")}),ce=e.on("validation",q=>{W.current?.(q.message??null)}),bt=H.current??(Ls.has(e)?null:void 0),yt={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...w.current?{theme:w.current}:{},...bt===void 0?{}:{submitLabel:bt}};return T.current=w.current??null,X.current=H.current,H.current!==void 0&&Ls.add(e),e.mount(v,yt).then(()=>{oe()}).catch(q=>{Se&&V.current?.(q instanceof Error?q.message:"Failed to load the secure card form.")}),()=>{Se=!1,ye(),Ee(),ce(),e.unmount()}},[e,t,r,n,a]),Oo(()=>{let v=h.current;v&&Bc(v,p)},[p]),(0,fn.useEffect)(()=>{s!==void 0&&(s===null&&T.current===null||(T.current=s,e.applyTheme?.(s)))},[e,s]),(0,fn.useEffect)(()=>{f!==X.current&&(X.current=f,f!==void 0&&Ls.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,zo.jsx)("div",{ref:h,"data-testid":"flopay-vault-card-fields"})}function Ka({label:e}){return(0,zo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,zo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,zo.jsx)("span",{children:e}),(0,zo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var Gs=require("@flopay/shared"),l=require("react/jsx-runtime"),to="flopay_stripe_resume",Oc="flopay_wallet_resume",$c="fw1",_u="fw2",Hc=300*1e3,Iu=900,Tu="express_checkout_click_timeout",Mu=25e3,Au=25e3,xu=1e4,Wn={provider:"paypal",paymentMethodCategory:"paypal"},Fu="x-flopay-process-result-source",Bu="status";async function Ou(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var Ui={},Ya=class{constructor(t){this.reason=t}};function Du(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function cr(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function $s(e){return`${_u}:${e}`}function zi(e){return cr($s(e))}function qi(e,t){if(typeof window>"u")return null;let r=$s(e);try{let n=localStorage.getItem(r);if(!n)return null;let a=JSON.parse(n);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>Hc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(zi(e),null):a}catch{return zi(e),null}}function Lu(e){return cr($s(e.sessionId),e)}function Dc(e,t,r){let n=qi(e,t);return!n||n.clientSecret!==r?!1:zi(e)}function Ns(e,t,r){if(typeof window>"u")return;qi(e,t)?.clientSecret===r&&zi(e)}function Nu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Us(e,t,r){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let n=r?e.status==="succeeded":Ma(e.status),a=Nu(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Lc(e,t,r){let n=null;try{return await Promise.race([ic(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},xu),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Uu(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Kc(e){return e instanceof c.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ji(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new $n.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw Kc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var zs=c.STRIPE_PAYPAL_RESUME_KEY,Ga=new Map,zu=250,Nc="Just a moment \u2014 we are finalizing your order. Please press pay again.",qu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Hs(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 Vi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new $n.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function ju(e){return e instanceof c.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Gc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,la.splitFullName)(r),d=s.firstName?s:(0,la.splitFullName)(n?.name);return(0,En.compactBuyerIdentity)({email:(0,c.isValidEmail)(a)?a:n?.email?.trim(),firstName:d.firstName,lastName:d.lastName})}async function Vu({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let d=Gc({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 Xa=180,Uc=`flopay-card-enter ${Xa}ms cubic-bezier(0, 0, 0.2, 1) both`,zc=`flopay-card-exit ${Xa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Wu=`flopay-buttons-enter ${Xa}ms cubic-bezier(0, 0, 0.2, 1) both`,$u=`flopay-buttons-exit ${Xa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Hu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ks(e){return(0,c.derivePrimaryTileStyle)(e)}var Ku={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Gu(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 js={width:"100%",minHeight:ko,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 qc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Vs(e){return e==="paypal"?"PayPal":(0,c.getStripeMethodDisplayName)(e)}function Yu(e){let t=(0,c.getPostalCodeExample)(e);return`Enter a valid ${(0,c.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Xu(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 Ju(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 Zu(e){return typeof e=="number"?`${e}px`:e}function Wi(e){return(0,l.jsx)(tp,{...e})}function jc({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:d=!1,onButtonClick:p,onDecline:y,onTechnicalFailure:b,runBeforeButtonClick:P,billingName:h,onBuyerIdentityReady:E,onLoadStateChange:V,placeholderBorderRadius:W,popupCapabilityOwner:w,externalTelemetryContext:T,presentationMode:f}){let H=uo(),{emitInstrument:X}=(0,o.useContext)(kn),v=(0,lr.useStripe)(),Se=(0,lr.useElements)(),M=(0,o.useMemo)(()=>Ai(br(H),T),[T,H]),[oe,ye]=(0,o.useState)("loading");(0,o.useEffect)(()=>{V?.(oe)},[oe,V]);let[Ee,ce]=(0,o.useState)(!1),bt=(0,o.useRef)(!1),yt=!(0,c.isValidEmail)(r?.trim())||!h?.trim(),{request:q,collect:He,finish:Ke}=ca(),Le=(0,o.useRef)(!1),Pe=(0,o.useRef)(null),Y=(0,o.useRef)(null),[K,tt]=(0,o.useState)(0),[we,qe]=(0,o.useState)(!1),Q=(0,o.useRef)(!1),j=(0,o.useRef)(new Map),{startAttempt:fe,finishAttempt:J,invalidateAttempt:ft,isAttemptInvalidated:de,isAttemptCurrent:ve,generationRef:_e}=Ba((Ie,he,gt)=>{b?.(Ie,he,{...gt,popupBlocked:gt?.popupBlocked??(0,ke.isPopupBlockedError)(he),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),qe(!0),tt(Qe=>Qe+1)},{onHandoffObserved:()=>{w.markAvailable(),M?.log({name:"provider.popup.opened",stage:"overlay_open",...Wn,attempt:_e.current})}});(0,o.useEffect)(()=>{we&&Y.current?.focus()},[we,K]);let Me=(0,o.useCallback)(()=>{tt(Ie=>Ie+1)},[]),je=(0,o.useCallback)((Ie,he,gt)=>{ft(gt),b?.("paypal",Ie,{code:he,popupBlocked:(0,ke.isPopupBlockedError)(Ie),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),qe(!0),Me()},[ft,b,f,Me]),ge=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Pe.current?.querySelector("iframe")??Pe.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Q.current&&(Q.current=!1,ge())},[ge,K]);let rt=(0,o.useCallback)(()=>{qe(!1),s?.(null),ge()},[ge,s]);(0,o.useEffect)(()=>{if(!v||Le.current)return;let[Ie,he,gt]=(0,c.readStripeRedirectParams)();if(!Ie||!he)return;let Qe=(0,c.readMatchingStripePayPalContinuation)(he);if(!Qe)return;Le.current=!0;let Mt=!0,nt=Ga.get(he);nt||(nt=gt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>v.retrievePaymentIntent(he)),Ga.set(he,nt));let St={accountPatch:Qe.accountPatch,sessionId:Qe.sessionId,nonce:Qe.nonce},ht=()=>{M?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Wn,requestCategory:"provider_sdk"})};return M?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Wn}),(async()=>{try{ce(!0);let $t=await nt;if(!Mt)return;if($t?.error){Ga.delete(he),ht(),s?.($t.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),Ga.delete(he),gt==="failed"){let D="PayPal payment was declined. Please try again.";M?.terminal({outcome:"payment_declined",...Wn,terminalReason:"provider_declined"}),s?.(D),y?.(Cr("paypal",D));return}let kt=$t?.paymentIntent;if(kt&&kt.id!==Ie){ht(),s?.("Failed to match the returned PayPal payment.");return}if(kt&&(kt.status==="requires_capture"||kt.status==="succeeded")){let D=typeof kt.payment_method=="string"?kt.payment_method:kt.payment_method?.id;a({id:D??kt.id,type:"card",threeDSecureActionResultTokenId:kt.id,isPaypal:!0},{...St,presentationMode:"redirect"})}else{let D="PayPal payment was not completed. Please try again.";M?.terminal({outcome:kt?.status==="canceled"?"payment_cancelled":"payment_declined",...Wn,terminalReason:kt?.status==="canceled"?"cancelled":"provider_declined"}),s?.(D),y?.(Cr("paypal",D))}}catch($t){if(!Mt)return;Ga.delete(he),ht(),s?.($t instanceof Error?$t.message:"Failed to complete PayPal payment.")}finally{Mt&&ce(!1)}})(),()=>{Mt=!1,Le.current=!1}},[v,a,s,y,M]);let dt=(0,o.useCallback)(async(Ie=!1)=>{let he=P?await P("paypal"):{proceed:!0};if(!he.proceed)return j.current.delete(K),!1;let gt=fe("paypal");return j.current.set(K,{generation:gt,accountPatch:he.accountPatch,sessionId:he.sessionId,nonce:he.nonce}),qe(!1),M?.log({name:`provider.${Ie?"redirect.started":"handoff.requested"}`,stage:Ie?"redirect":"overlay_open",...Wn,attempt:gt}),p?.("paypal"),!0},[p,M,P,fe,K]),ut=(0,o.useCallback)(async Ie=>{if(d||Ee||!await dt()){Ie.reject();return}Ie.resolve()},[d,dt,Ee]),ae=(0,o.useCallback)(async Ie=>{if(!v||!Se)return;let he=j.current.get(K);if(he&&!ve(he.generation)){j.current.delete(K);return}if(!he&&de()||he&&!J(he.generation))return;he||J();let gt=he??null;if(j.current.delete(K),!gt&&P){let ne=await P("paypal");if(!ne.proceed){Ie.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}gt={accountPatch:ne.accountPatch,sessionId:ne.sessionId,nonce:ne.nonce}}let Qe=gt?.sessionId??e,Mt=gt?.nonce??t,nt=await Vu({event:Ie,prepared:gt,email:r,billingName:h,methodLabel:"PayPal",collect:He});if(!nt){Ie.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let St=nt.email,ht={...gt?.accountPatch,...(0,En.compactBuyerIdentity)(nt,!0)};try{if(ce(!0),s?.(null),!Qe||!(0,c.isValidEmail)(St))throw new Error("Missing sessionId or email for PayPal payment");await E?.(nt);let ne=v.createPaymentMethod,{error:$t,paymentMethod:kt}=await ne({type:"paypal"});if($t){je($t,"stripe_paypal_create_payment_method_failed",he?.generation),Ie.paymentFailed({reason:"fail"});return}let D=await ji(n,X,Qe,Mt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:kt?.id??null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(D)){Ie.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:ht,paymentMethodCategory:"paypal",presentationMode:f,sessionId:Qe,nonce:Mt,settledProcessResponse:D.response});return}if(D.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ye=D.clientSecret,_={return_url:(0,c.stripeRedirectReturnUrl)()};if(kt?.id&&(_.payment_method=kt.id),!cr(zs,{clientSecret:Ye,sessionId:Qe,nonce:Mt,accountPatch:ht})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Ae,paymentIntent:te}=await v.confirmPayment({clientSecret:Ye,confirmParams:_,redirect:"if_required"});if(Ae){if(cr(zs),(0,ke.isProviderDecline)(Ae)){let u=Ae.message??"Your payment was declined.";M?.terminal({outcome:"payment_declined",...Wn,terminalReason:"provider_declined"}),s?.(u),y?.(Cr("paypal",u,{code:(0,ke.getProviderErrorCode)(Ae),declineCode:(0,ke.getProviderDeclineCode)(Ae)})),await Vi({billingApiUrl:n,sessionId:Qe,nonce:Mt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,ke.getProviderErrorCode)(Ae)??"provider_declined"}})}else je(Ae,"stripe_paypal_confirm_failed",he?.generation);return}cr(zs);let xe=typeof te?.payment_method=="string"?te.payment_method:te?.payment_method?.id;a({id:xe??te?.id,type:"card",threeDSecureActionResultTokenId:te?.id,isPaypal:!0},{accountPatch:ht,paymentMethodCategory:"paypal",presentationMode:f,sessionId:Qe,nonce:Mt});return}catch(ne){je(ne,"stripe_paypal_failed",he?.generation)}finally{ce(!1)}},[v,Se,e,t,r,h,He,E,n,X,a,s,y,P,je,J,ve,de,M,f,K]),Dt=(0,o.useCallback)(async()=>{if(!(bt.current||d||Ee||!v||!Se)){bt.current=!0,ce(!0);try{if(!await dt(!0))return;await ae({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{bt.current=!1,ce(!1)}}},[Se,ae,d,dt,v,Ee]),Lt=f==="redirect"?(0,l.jsx)("button",{type:"button",disabled:d||Ee,onClick:()=>{Dt()},style:{width:"100%",minHeight:ko,border:"1px solid #d1d5db",borderRadius:W??8,background:"#ffc439",color:"#111827",cursor:d||Ee?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,l.jsx)(lr.ExpressCheckoutElement,{onReady:Ie=>ye(Va(Ie,["paypal"])),onLoadError:()=>{ye("load_error"),Hs(M,"paypal","paypal","provider_error")},onClick:ut,onConfirm:ae,onCancel:()=>{let Ie=j.current.get(K);j.current.delete(K),M?.terminal({outcome:"payment_cancelled",...Wn,terminalReason:"cancelled",...Ie?{attempt:Ie.generation}:{}}),ft(Ie?.generation),qe(!1),Q.current=!0,Me()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:yt,emailRequired:yt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},K),Ut=(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{ref:Pe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[we&&(0,l.jsx)("button",{ref:Y,type:"button","data-testid":"flopay-paypal-retry-button",onClick:rt,style:js,children:"Try PayPal again"}),q&&(0,l.jsx)(da,{identity:q.identity,methodLabel:q.methodLabel,onComplete:Ke,onCancel:()=>Ke(null)},q.id),(0,l.jsx)("div",{style:{display:q?"none":void 0},children:Lt})]}),Ee&&!q&&(0,l.jsx)(an,{status:"processing"})]});return f==="redirect"?Ut:(0,l.jsx)(Wa,{state:oe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:W,children:Ut})}function qs(e){return e==="apple_pay"||e==="google_pay"}var Qu=200;function ep({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,c.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function Vc({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:d,onErrorChange:p,onButtonClick:y,onDecline:b,onTechnicalFailure:P,runBeforeButtonClick:h,billingName:E,onBuyerIdentityReady:V,onLoadStateChange:W,placeholderBorderRadius:w,popupCapabilityOwner:T,externalTelemetryContext:f}){let H=uo(),{emitInstrument:X}=(0,o.useContext)(kn),v=(0,lr.useStripe)(),Se=(0,lr.useElements)(),M=(0,o.useMemo)(()=>Ai(br(H),f),[f,H]),[oe,ye]=(0,o.useState)("loading");(0,o.useEffect)(()=>{W?.(oe)},[oe,W]);let[Ee,ce]=(0,o.useState)(!1);(0,o.useEffect)(()=>{qe.current=Ee},[Ee]);let bt=(0,o.useRef)(!(0,c.isValidEmail)(r?.trim())||!E?.trim()).current,{request:yt,collect:q,finish:He}=ca(),Ke=(0,o.useRef)(null),Le=(0,o.useRef)(null),[Pe,Y]=(0,o.useState)(0),[K,tt]=(0,o.useState)(()=>(0,c.shouldPreferWalletPopup)()),we=(0,o.useRef)(K),qe=(0,o.useRef)(!1),[Q,j]=(0,o.useState)(!1),[fe,J]=(0,o.useState)(()=>qi(e,t)?"blocked":"idle"),[ft,de]=(0,o.useState)("google_pay"),ve=(0,o.useRef)(null),_e=(0,o.useRef)(!0),Me=(0,o.useRef)(!1),je=(0,o.useRef)("google_pay"),ge=(0,o.useRef)("google_pay"),rt=(0,o.useRef)(null),dt=(0,o.useRef)(null),ut=(0,o.useRef)(new Set),ae=(0,o.useRef)(null),Dt=(0,o.useRef)(null);(0,o.useEffect)(()=>(_e.current=!0,()=>{_e.current=!1;for(let u of ut.current)window.clearTimeout(u);ut.current.clear()}),[]);let Lt=(0,o.useRef)(new Map),{startAttempt:Ut,finishAttempt:Ie,invalidateAttempt:he,isAttemptInvalidated:gt,isAttemptCurrent:Qe,generationRef:Mt}=Ba((u,I,k)=>{P?.(u,I,{...k,popupBlocked:k?.popupBlocked??(0,ke.isPopupBlockedError)(I),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),de(u),j(!0),Y(U=>U+1)},{onHandoffObserved:u=>{Dt.current=Mt.current,T.markAvailable(),M?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Mt.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:qs,onMissingTerminalDeferred:(u,I)=>{let k=M?.now()??globalThis.performance?.now()??Date.now(),U=ae.current,F=U?.generation===I?U.startedAt:k;M?.performance({stage:"overlay_return",durationMs:Math.max(0,k-F),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:I,...qs(u)?{walletType:u}:{}}),M?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{Q&&Le.current?.focus()},[Q,Pe]);let nt=(0,o.useRef)(0),St=(0,o.useRef)(!1),ht=(0,o.useCallback)(()=>{if(nt.current>0){St.current=!0;return}Y(u=>u+1)},[]),ne=(0,o.useCallback)(()=>{nt.current-=1,!(nt.current>0||!St.current)&&(St.current=!1,_e.current&&Y(u=>u+1))},[]),$t=(0,o.useCallback)((u,I,k,U,F=!1)=>{he(U),P?.(u,I,{code:k,popupBlocked:(0,ke.isPopupBlockedError)(I),telemetryReported:F,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),de(u),j(!0),ht()},[he,P,ht]),kt=(0,o.useCallback)(u=>{M?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...qs(u)?{walletType:u}:{}}),P?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:Tu,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),de(u),j(!0)},[P,M]),D=(0,o.useCallback)(()=>{window.setTimeout(()=>{(Ke.current?.querySelector("iframe")??Ke.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Me.current&&(Me.current=!1,D())},[D,Pe]);let Ye=(0,o.useCallback)(()=>{j(!1),p?.(null),D()},[D,p]),_=(0,o.useCallback)(()=>{ve.current?.()},[]);(0,o.useEffect)(()=>{let u=null,I=()=>{u=null;let U=(0,c.shouldPreferWalletPopup)();U!==we.current&&(we.current=U,tt(U),!qe.current&&!Qe(Mt.current)&&ht())},k=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(I,Qu)};return window.addEventListener("resize",k),()=>{window.removeEventListener("resize",k),u!==null&&window.clearTimeout(u)}},[Mt,Qe,ht]),(0,o.useEffect)(()=>{let u=qi(e,t);if(!u)return;let I=!1,k=!1,U=async()=>{if(!k){k=!0,I||J("checking");try{let F=await Lc(v,u.clientSecret,ut.current);if(I)return;let x=Us(F,u.providerObjectId,(0,c.isSetupIntentClientSecret)(u.clientSecret));if(x.kind==="confirmed"){if(!Dc(e,t,u.clientSecret))return;ve.current=null,J("idle"),d({id:x.paymentMethodId,type:"card",threeDSecureActionResultTokenId:x.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(x.kind==="terminal"){Ns(e,t,u.clientSecret),ve.current=null,J("idle"),de(u.paymentMethodType),j(!0),ht();return}J("blocked")}catch{I||J("blocked")}finally{k=!1}}};return ve.current=U,J("blocked"),()=>{I=!0,ve.current===U&&(ve.current=null)}},[t,d,ht,e,v]);let A=(0,o.useCallback)(async u=>{let I=!1,k=!1,U=Ne=>{I||k||(I=!0,u.paymentFailed({reason:"fail",...Ne?{message:Ne}:{}}))};if(!v||!Se){U();return}let F=Lt.current.get(Pe);if(F&&!Qe(F.generation)){Lt.current.delete(Pe),U();return}if(!F&&gt()){U();return}if(F&&!Ie(F.generation)){U();return}F||(Ie(),St.current=!1);let x=u.expressPaymentType??F?.method??je.current,At=F??null,Et=qc(x),kr;x==="apple_pay"?kr="apple_pay":x==="google_pay"&&(kr="google_pay");let rr=F?.generation??Mt.current,Pt=M,xt=Pt?.now()??globalThis.performance?.now()??Date.now(),xr=new AbortController,Fr=!1,zr=!1,Qt=null,Br=e,qr="processing",en="other",jr="provider_runtime",ur,pr=new Promise((Ne,zt)=>{ur=zt}),pt=window.setTimeout(()=>{Fr=!0,xr.abort(),ur(Ui)},Mu),ln=async(Ne,zt,Vr)=>{qr=Ne,en=zt,jr=zt==="intent_create"||zt==="session_claim"?"transport_error":"provider_runtime";let Or=Pt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Vr,pr])}finally{let Wr=Pt?.now()??globalThis.performance?.now()??Date.now();Pt?.performance({stage:Ne,durationMs:Math.max(0,Wr-Or),durationMode:"machine",requestCategory:zt,paymentMethodCategory:"wallet",provider:"stripe",...Fr?{statusClass:"timeout"}:{}})}};try{if(ce(!0),p?.(null),!At&&h){let Re=await ln("processing","other",h(Et));if(!Re.proceed){U();return}At={accountPatch:Re.accountPatch,sessionId:Re.sessionId,nonce:Re.nonce}}let Ne=At?.sessionId??e;Br=Ne;let zt=At?.nonce??t,Vr=rt.current??At?.accountPatch,Or=Gc({event:u,fallbackEmail:Vr?.email??r,fallbackName:[Vr?.firstName,Vr?.lastName].join(" ").trim()||E});if(!(0,c.isValidEmail)(Or.email)){U("Buyer details are required."),q(Vs(x),Or).then(Re=>{Re&&(rt.current=Re)});return}rt.current=null;let Wr={...At?.accountPatch,...(0,En.compactBuyerIdentity)(Or,!0)};await ln("processing","session_claim",Promise.resolve(V?.(Or)));let{error:gn}=await ln("tokenization","provider_sdk",Se.submit());if(gn){U(),$t(x,gn,"stripe_wallet_submit_failed",F?.generation);return}if(!Ne)throw new Error("Missing sessionId or email for payment.");let cn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:x,paymentMethodId:null,intentKind:a},Er=JSON.stringify({sessionId:Ne,nonce:zt??"",request:cn}),hn=dt.current,dn=hn?.retryIdentity===Er?hn.authorizationAttemptId:(0,c.randomUuidV4)();dt.current={authorizationAttemptId:dn,retryIdentity:Er};let ar=await ln("processing","intent_create",ji(n,X,Ne,zt??"",{...cn,authorizationAttemptId:dn},{signal:xr.signal}));if((0,c.isSettledSessionIntent)(ar)){U(),d({type:"card",paymentMethodType:x},{accountPatch:Wr,paymentMethodCategory:"wallet",sessionId:Ne,nonce:zt,settledProcessResponse:ar.response});return}if(ar.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Dr=ar.clientSecret,Lr=Lu({createdAt:Date.now(),sessionId:Ne,...zt?{nonce:zt}:{},clientSecret:Dr,providerObjectId:ar.providerObjectId,paymentMethodType:x,accountPatch:Wr});window.clearTimeout(pt),zr=!0,Pt?.performance({stage:"callback",durationMs:Math.max(0,(Pt?.now()??globalThis.performance?.now()??Date.now())-xt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let $r=Pt?.now()??globalThis.performance?.now()??Date.now(),Kt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...kr?{walletType:kr}:{},attempt:rr},Nr=!1,mr=null;Pt?.log({name:"payment.provider_confirmation.started",...Kt}),Qt=window.setTimeout(()=>{Qt!==null&&ut.current.delete(Qt),Nr=!0;let Re=Pt?.now()??globalThis.performance?.now()??Date.now();Pt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Kt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Re-$r),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Pt?.flush?.().catch(()=>{}),mr?.()},Au),ut.current.add(Qt);let Yr=(Re,Ft)=>{Qt!==null&&(window.clearTimeout(Qt),ut.current.delete(Qt),Qt=null);let Gt=Pt?.now()??globalThis.performance?.now()??Date.now(),Yt=Math.max(0,Gt-$r),Be=Re;Nr&&(Re==="resolved"?Be="resolved_late":Re==="returned_error"?Be="returned_error_late":Be="rejected_late");let Ve=Ft??(Re==="resolved"?"approved":"provider_error");return Pt?.log({name:"payment.provider_confirmation.returned",...Kt,operationOutcome:Be,terminalReason:Ve}),Pt?.performance({...Kt,durationMs:Yt,durationMode:"buyer",operationOutcome:Be,terminalReason:Ve}),{durationMs:Yt,operationOutcome:Be,terminalReason:Ve}},vr=!1,yr=!1,Ur=Re=>{if(!Re||typeof Re!="object")return null;let Ft=Re;if(Ft.error)return null;let Gt=Ft.setupIntent??Ft.paymentIntent,Yt=Us(Gt??null,void 0,!!Ft.setupIntent);return Yt.kind==="confirmed"?Yt:null},_r=Re=>{if(vr||F&&Mt.current!==F.generation)return;let Ft=Ur(Re);if(!Ft)return;if(Lr&&!Dc(Ne,zt,Dr)){vr=!0;return}let{intentId:Gt,paymentMethodId:Yt}=Ft;vr=!0,yr=!0,dt.current=null,ve.current=null,_e.current&&(J("idle"),ce(!1));let Be=`${$c}:${Ne}`;cr(Be,{createdAt:Date.now(),sessionId:Ne,nonce:zt,accountPatch:Wr,paymentMethodId:Yt,providerIntentId:Gt,paymentMethodType:x});try{d({id:Yt,type:"card",threeDSecureActionResultTokenId:Gt},{accountPatch:Wr,paymentMethodCategory:"wallet",sessionId:Ne,nonce:zt})}finally{cr(Be)}},et=!1;mr=async()=>{if(!(et||vr||yr)){et=!0,_e.current&&J("checking");try{let Re=await Lc(v,Dr,ut.current);if(vr||yr)return;let Ft=(0,c.isSetupIntentClientSecret)(Dr),Gt=Us(Re,ar.providerObjectId,Ft);if(Gt.kind==="confirmed"){_r(Ft?{setupIntent:Re}:{paymentIntent:Re});return}if(Gt.kind==="terminal"){if(yr=!0,Ns(Ne,zt,Dr),dt.current=null,ve.current=null,!_e.current)return;J("idle"),U(),$t(x,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",F?.generation,!0);return}_e.current&&!yr&&(J("blocked"),ce(!1))}catch{_e.current&&!yr&&(J("blocked"),ce(!1))}finally{et=!1}}},ve.current=mr;let z,mt;try{k=!0,nt.current+=1;let Re;try{Re=await((0,c.isSetupIntentClientSecret)(Dr)?v.confirmSetup({elements:Se,clientSecret:Dr,redirect:"if_required"}):v.confirmPayment({elements:Se,clientSecret:Dr,redirect:"if_required"}))}finally{ne()}if(!Re||typeof Re!="object")throw new Ya(Du(Re));if(z=Re,!z.error&&!Ur(z))throw new Ya("confirmation_result_unconfirmed");mt=Yr(z.error?"returned_error":"resolved",z.error&&(0,ke.isProviderDecline)(z.error)?"provider_declined":void 0)}catch(Re){let Ft=Re instanceof Ya?Re.reason:void 0,Gt=Ft!==void 0,Yt=Yr(Gt?"returned_error":"rejected");if(Pt?.error({...Gt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Ft}:Is(Re),...Kt,operationOutcome:Yt.operationOutcome,durationMs:Yt.durationMs,statusClass:"unknown",terminalReason:Yt.terminalReason}),!_e.current||vr)return;await mr?.();return}let G=z.error;if(G){if(!_e.current||vr)return;if((0,ke.isProviderDecline)(G)){yr=!0,Ns(Ne,zt,Dr),dt.current=null,ve.current=null,J("idle"),Lt.current.get(Pe)===F&&Lt.current.delete(Pe);let Re=G.message??"Your payment was declined.";p?.(Re),b?.(Cr(Et,Re,{code:(0,ke.getProviderErrorCode)(G),declineCode:(0,ke.getProviderDeclineCode)(G)})),Vi({billingApiUrl:n,sessionId:Ne,nonce:zt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:x,providerDeclineReason:(0,ke.getProviderErrorCode)(G)??"provider_declined",...ar.intentKind==="payment"&&ar.providerObjectId.startsWith("pi_")?{providerIntentId:ar.providerObjectId}:{}}})}else Pt?.error({...Is(G),...Kt,operationOutcome:mt.operationOutcome,durationMs:mt.durationMs,statusClass:"unknown",terminalReason:mt.terminalReason}),await mr?.();return}if(_r(z),!vr)throw new Error("Invalid provider returned for APM intent")}catch(Ne){if(Ne===Ui){let zt=Pt?.now()??globalThis.performance?.now()??Date.now();Pt?.error({errorCode:Uu(en),stage:qr,requestCategory:en,paymentMethodCategory:"wallet",provider:"stripe",...kr?{walletType:kr}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Br,durationMs:Math.max(0,zt-xt),statusClass:"timeout",failureCategory:jr,attempt:rr,terminalReason:"provider_error"}),Pt?.flush?.().catch(()=>{})}U(),$t(x,Ne,Ne===Ui?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",F?.generation,Ne===Ui)}finally{if(window.clearTimeout(pt),Qt!==null&&(window.clearTimeout(Qt),ut.current.delete(Qt)),!zr){let Ne=Pt?.now()??globalThis.performance?.now()??Date.now();Pt?.performance({stage:"callback",durationMs:Math.max(0,Ne-xt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Fr?{statusClass:"timeout"}:{}})}_e.current&&ce(!1)}},[v,Se,e,t,r,E,q,V,n,X,a,d,p,b,h,$t,ne,Ie,Qe,gt,Mt,M,Pe]),Ae=(0,o.useMemo)(()=>Fi(s),[s]),te=(0,o.useMemo)(()=>s.map(c.stripeExpressMethodToOptionKey),[s]),xe=(0,o.useMemo)(()=>(0,l.jsx)(lr.ExpressCheckoutElement,{onReady:u=>{ye(Va(u,te))},onLoadError:u=>{ye("load_error"),Hs(M,"stripe","wallet","provider_error")},onClick:async u=>{let I=M?.now()??globalThis.performance?.now()??Date.now();je.current=u.expressPaymentType,ge.current=qc(u.expressPaymentType);let k=!0,U=window.setTimeout(()=>{k=!1,u.reject(),kt(u.expressPaymentType)},Iu),F=h?await h(ge.current,{abandoned:()=>!k}):{proceed:!0};if(window.clearTimeout(U),!k)return;if(!F.proceed){Lt.current.delete(Pe),u.reject();return}let x=Ut(u.expressPaymentType);St.current=!1,ae.current={generation:x,startedAt:I},Lt.current.set(Pe,{generation:x,method:u.expressPaymentType,accountPatch:F.accountPatch,sessionId:F.sessionId,nonce:F.nonce}),j(!1),M?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:x,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),y?.(ge.current),u.resolve()},onConfirm:A,onCancel:()=>{let u=Lt.current.get(Pe);Lt.current.delete(Pe);let I=ae.current,k=M?.now()??globalThis.performance?.now()??Date.now();if(u&&I?.generation===u.generation&&(0,c.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:k-I.startedAt,handoffObserved:Dt.current===u.generation})){M?.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"}),dt.current=null,$t(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}M?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),he(u?.generation),dt.current=null,j(!1),Me.current=!0,ht()},options:{...Bi,paymentMethods:Ae,emailRequired:bt,billingAddressRequired:bt}},Pe),[te,Ae,A,he,y,bt,$t,kt,ht,h,Ut,Pe,M]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Wa,{state:oe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:w,children:(0,l.jsxs)("div",{ref:Ke,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:Le,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ye,style:js,children:["Try ",Vs(ft)," again"]}),fe!=="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:_,disabled:fe==="checking",style:js,children:fe==="checking"?"Checking payment status\u2026":"Check payment status"})]}),yt&&(0,l.jsx)(da,{identity:yt.identity,methodLabel:yt.methodLabel,onComplete:He,onCancel:()=>He(null)},yt.id),(0,l.jsxs)("div",{style:{display:yt||fe!=="idle"?"none":void 0},children:[(0,l.jsx)(ep,{active:K}),xe]})]})}),Ee&&(0,l.jsx)(an,{status:"processing"})]})}function Yc(e,t,r){let n=(0,c.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function Ws({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:d,onTokenizedBody:p,onErrorChange:y,onDecline:b,onCancel:P,runBeforeButtonClick:h,onButtonClick:E,isProcessing:V,submitButtonColor:W,submitButtonBorderRadius:w,submitButtonStyle:T,errorText:f}){let H=uo(),{emitInstrument:X}=(0,o.useContext)(kn),v=(0,lr.useStripe)(),Se=(0,lr.useElements)(),[M,oe]=(0,o.useState)(!1),ye=(0,o.useRef)(!1),[Ee,ce]=(0,o.useState)(!1),[bt,yt]=(0,o.useState)("loading"),[q,He]=(0,o.useState)(""),Ke=!(0,c.isValidEmail)(n?.trim()),Le=!Ke||(0,c.isValidEmail)(q.trim()),Pe=(0,o.useCallback)(async()=>{if(!v||!Se||V||ye.current||!Ee)return;ye.current=!0,oe(!0);let Y=h?await h("card"):{proceed:!0};if(!Y.proceed){ye.current=!1,oe(!1);return}E?.("card");let K=Y.sessionId??t,tt=Y.nonce??r,we=(0,la.splitFullName)(a?.trim()),qe=(0,En.compactBuyerIdentity)({email:Y.accountPatch?.email?.trim()||n?.trim()||q.trim(),firstName:Y.accountPatch?.firstName?.trim()||we.firstName,lastName:Y.accountPatch?.lastName?.trim()||we.lastName}),Q=qe.email,j=(0,En.compactBuyerIdentity)({...Y.accountPatch,...qe});try{if(y?.(null),!(0,c.isValidEmail)(Q))throw new Error("A valid email address is required for payment.");await s?.(qe);let fe=await Se.submit();if(fe.error){y?.(fe.error.message??"Payment failed.");return}let J=[qe.firstName,qe.lastName].filter(Boolean).join(" "),ft=await v.createPaymentMethod({elements:Se,params:{billing_details:{email:Q,...J?{name:J}:{}}}});if(ft.error||!ft.paymentMethod){y?.(ft.error?.message??"Failed to create payment method.");return}let de=ft.paymentMethod;if(!K||!Q)throw new Error("Missing sessionId or email for payment.");let ve=de.type||e,_e=await ji(d,X,K,tt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ve,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(_e)){p({type:"card",gateway:"stripe",paymentMethodType:ve},{accountPatch:j,paymentMethodCategory:"apm",sessionId:K,nonce:tt,settledProcessResponse:_e.response});return}if(_e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Me=_e.clientSecret;cr(to,{clientSecret:Me,sessionId:K,nonce:tt,accountPatch:j,paymentMethodId:de.id,paymentMethodType:de.type??e,gateway:"stripe"});let{error:je,paymentIntent:ge}=await v.confirmPayment({clientSecret:Me,confirmParams:{return_url:window.location.href,payment_method:de.id},redirect:"if_required"});if(je){cr(to);let ut=je.message??"Payment failed.";y?.(ut),b?.(Cr("card",ut,{code:je.code})),await Vi({billingApiUrl:d,sessionId:K,nonce:tt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:je.code??"provider_declined"}});return}let rt=ge?.status;if(!Ma(rt)){cr(to);let ut=rt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(ut),b?.(Cr("card",ut,{code:rt??"missing_payment_intent"}));return}cr(to);let dt=typeof ge?.payment_method=="string"?ge.payment_method:ge?.payment_method?.id;p({id:dt??de.id,type:"card",threeDSecureActionResultTokenId:ge?.id,gateway:"stripe",paymentMethodType:de.type??e},{accountPatch:j,paymentMethodCategory:"apm",sessionId:K,nonce:tt})}catch(fe){y?.(fe instanceof Error?fe.message:"Payment failed. Please try again.")}finally{ye.current=!1,oe(!1)}},[v,Se,V,Ee,h,E,t,r,n,a,q,s,d,X,e,p,y,b]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ke&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ke&&(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:q,onChange:Y=>He(Y.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(lr.PaymentElement,{onReady:()=>yt("ready"),onLoadError:()=>{yt("load_error"),Hs(br(H),"stripe","apm")},onChange:Y=>{ce(!!Y.complete)},options:{layout:Oi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,c.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,l.jsx)(Di,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Pe()},disabled:!Ee||!Le||M||V||bt!=="ready",color:W,borderRadius:w,style:T,children:M?"Processing\u2026":`Pay with ${(0,c.getStripeMethodDisplayName)(e)}`}),f&&(0,l.jsx)(ma,{margin:"0.75rem 0 0",children:f})]})}function Wc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:d,stripeInstance:p,paymentElementBaseOptions:y,futureUseSession:b,onTokenizedBody:P,onErrorChange:h,onButtonClick:E,onDecline:V,runBeforeButtonClick:W,onLoadStateChange:w,isProcessing:T=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:X,buttonAppearance:v,themeId:Se,onExpandApm:M,expandedApmMethod:oe}){let{emitInstrument:ye}=(0,o.useContext)(kn),[Ee,ce]=(0,o.useState)(null),[bt,yt]=(0,o.useState)(null),q=(0,o.useRef)(!1),{request:He,collect:Ke,finish:Le}=ca();(0,o.useEffect)(()=>{d.length>0&&p?w?.("ready"):p||w?.("loading")},[d.length,p,w]);let Pe=(0,o.useCallback)(async Q=>{if(!p||q.current||T)return;q.current=!0,yt(Q);let j=W?await W("card"):{proceed:!0};if(!j.proceed){q.current=!1,yt(null);return}E?.("card");let fe=j.sessionId??e,J=j.nonce??t,ft=(0,la.splitFullName)([j.accountPatch?.firstName,j.accountPatch?.lastName].filter(Boolean).join(" ")||n),de=(0,En.compactBuyerIdentity)({email:j.accountPatch?.email?.trim()||r?.trim(),firstName:j.accountPatch?.firstName?.trim()||ft.firstName,lastName:j.accountPatch?.lastName?.trim()||ft.lastName});if(!(0,c.isValidEmail)(de.email)){yt(null);let Me=await Ke((0,c.getStripeMethodDisplayName)(Q),de);if(!Me){q.current=!1;return}de=Me,yt(Q)}let ve=de.email,_e=(0,En.compactBuyerIdentity)({...j.accountPatch,...de});try{if(h?.(null),!fe||!(0,c.isValidEmail)(ve))throw new Error("Missing sessionId or email for payment.");await a?.(de);let Me=await ji(s,ye,fe,J??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(Me)){P({type:"card",gateway:"stripe",paymentMethodType:Q},{accountPatch:_e,paymentMethodCategory:"apm",sessionId:fe,nonce:J,settledProcessResponse:Me.response});return}if(Me.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let je=Me.clientSecret;cr(to,{clientSecret:je,sessionId:fe,nonce:J,accountPatch:_e,paymentMethodType:Q,gateway:"stripe"});let{error:ge,paymentIntent:rt}=await p.confirmPayment({clientSecret:je,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:[de.firstName,de.lastName].filter(Boolean).join(" "),...ve?{email:ve}:{}}}},redirect:"if_required"});if(ge){cr(to);let ae=ge.message??"Payment failed.";h?.(ae),V?.(Cr("card",ae,{code:ge.code})),await Vi({billingApiUrl:s,sessionId:fe,nonce:J,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:ge.code??"provider_declined"}});return}let dt=rt?.status;if(!Ma(dt)){cr(to);let ae=dt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(ae),V?.(Cr("card",ae,{code:dt??"missing_payment_intent"}));return}cr(to);let ut=typeof rt?.payment_method=="string"?rt.payment_method:rt?.payment_method?.id;P({id:ut??rt?.id,type:"card",threeDSecureActionResultTokenId:rt?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:_e,paymentMethodCategory:"apm",sessionId:fe,nonce:J})}catch(Me){h?.(Me instanceof Error?Me.message:"Payment failed. Please try again.")}finally{q.current=!1,yt(null)}},[p,T,W,E,e,t,r,Ke,s,ye,n,a,P,h,V]),[Y,K]=(0,o.useState)(null),tt=M?oe??null:Y,we=(0,o.useCallback)(Q=>{q.current||T||tt&&tt!==Q||((0,c.needsStripeMethodExplicitConfirm)(Q)?M?M(Q):K(Q):Pe(Q))},[tt,T,Pe,M]),qe=(0,o.useMemo)(()=>Y?Yc(y,Y,b):null,[Y,y,b]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:He?(0,l.jsx)(da,{identity:He.identity,methodLabel:He.methodLabel,onComplete:Le,onCancel:()=>Le(null)},He.id):d.map(Q=>{let j=oe===Q,fe=bt===Q,J=bt!==null&&bt!==Q||oe!=null&&oe!==Q;return(0,l.jsxs)(o.default.Fragment,{children:[(0,l.jsx)(xi,{method:Q,themeId:Se,submitting:fe,disabled:J,highlighted:j,hasNextStep:(0,c.needsStripeMethodExplicitConfirm)(Q),onClick:()=>we(Q),backgroundColor:v?.backgroundColor,borderColor:v?.borderColor,textColor:v?.textColor,borderRadius:v?.borderRadius,fontFamily:v?.fontFamily}),!M&&Y===Q&&qe&&p&&(0,l.jsx)(lr.Elements,{stripe:p,options:qe,children:(0,l.jsx)(Ws,{method:Q,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:P,onErrorChange:h,onDecline:V,onCancel:()=>K(null),runBeforeButtonClick:W,onButtonClick:E,isProcessing:T,submitButtonColor:f,submitButtonBorderRadius:H,submitButtonStyle:X})},Q)]},Q)})})}function tp({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:d,onError:p,onDecline:y,onCancel:b,onTokenizedBody:P,firstName:h,lastName:E,chv:V,className:W,submitLabel:w,isProcessing:T,error:f,onErrorChange:H,showPayPal:X=!0,showStripe:v=!0,walletPresentation:Se="auto",enabledPaymentMethods:M,enabledPaymentMethodCountries:oe,showApplePay:ye=!0,showGooglePay:Ee=!0,layout:ce="default",paymentMethodLayout:bt,moreOptionsLabel:yt,theme:q,buttonsTheme:He,buttonsStyles:Ke,appearance:Le,cardButtonContent:Pe,cardBackButtonContent:Y,cardTitleContent:K,showSecurityFooter:tt,onButtonClick:we,onBeforeButtonClick:qe,onBuyerIdentityReady:Q,enableAVS:j,cardFieldOrder:fe,showCardBrandIcons:J,cardAutoFocus:ft,onCardFieldsReady:de,onCardFieldsFailed:ve,cardFieldsTimeoutMs:_e,cardPreFormSlot:Me,avsLayout:je="row",country:ge,zip:rt,addressLine1:dt,addressLine2:ut,city:ae,state:Dt,onCountryChange:Lt,onZipChange:Ut,avsCheck:Ie,checkoutType:he,checkoutLayout:gt,totalAmount:Qe=0,currency:Mt="usd",initialCardOpen:nt=!1,directPaypal:St,isSubscription:ht=!1,session:ne,dataAttachmentPending:$t=!1,dataAttachmentRequiresIdentity:kt=!1,debug:D=!1}){let Ye=uo(),_=vi(),A=(0,o.useContext)(qn),{emitInstrument:Ae}=(0,o.useContext)(kn),te=(0,o.useRef)(null);te.current||(te.current=bi());let xe=te.current,[,u]=(0,o.useState)(0),I=(0,o.useRef)(null);I.current||(I.current=(0,Zn.detectPayPalEnvironment)());let k=I.current,U=(0,o.useMemo)(()=>({browser:k,capability:xe,presentationMode:"popup"}),[k,xe]),F=ne??A.session,x=(0,o.useMemo)(()=>({futureUse:F?.futureUse,futureUseUnsupported:F?.futureUseUnsupported}),[F?.futureUse,F?.futureUseUnsupported]),At=F?.gateways?.paypal?.providerObjectType??St?.providerObjectType,Et=$t||A.claimPending===!0,kr=kt||A.claimRequiresIdentity===!0,rr=Et&&!kr,Pt=dc(),xt=r||Pt,xr=Fc({rules:bt,sessionId:e,nonce:t,billingApiUrl:xt,waitForSession:rr}),Fr=xr?.order??null,[zr,Qt]=(0,o.useState)(!1),Br=(0,o.useMemo)(()=>Fr?(0,c.keyPaymentMethodOrder)(Fr):null,[Fr]),qr=Fr!==null&&(0,c.isCardFormFirst)(Fr),[en,jr]=(0,o.useState)(!1),[ur,pr]=(0,o.useState)(null),[pt,ln]=(0,o.useState)(ge??""),[Ne,zt]=(0,o.useState)(rt??""),[Vr,Or]=(0,o.useState)(dt??""),[Wr,gn]=(0,o.useState)(ut??""),[cn,Er]=(0,o.useState)(ae??""),[hn,dn]=(0,o.useState)(Dt??""),[ar,Dr]=(0,o.useState)(""),[Lr,$r]=(0,o.useState)({}),Kt=(0,o.useRef)(rt??""),Nr=(0,o.useRef)(ge??""),mr=(0,o.useRef)(dt??""),Yr=(0,o.useRef)(ut??""),vr=(0,o.useRef)(ae??""),yr=(0,o.useRef)(Dt??""),Ur=(0,o.useRef)(""),_r=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(C,N,me,Z,De)=>{if(_r.current[C])return;let Vt=N?.trim();!Vt||Vt===me.current||(me.current=Vt,Z(Vt),De?.(Vt))};i("country",ge,Nr,ln,Lt),i("zip",rt,Kt,zt,Ut),i("addressLine1",dt,mr,Or),i("addressLine2",ut,Yr,gn),i("city",ae,vr,Er),i("state",Dt,yr,dn)},[ge,rt,dt,ut,ae,Dt,Lt,Ut]);let et=(0,o.useMemo)(()=>(0,c.resolveAVSConfig)(j),[j]),z=et!==null,mt=(0,o.useMemo)(()=>(0,c.isAuthorizationOnlySession)(ne),[ne]),G=(0,c.isMountableVaultBlock)(ne?.vault),Re=!!ne?.gateways?.pcivault,Ft=(0,zn.hasServerSideCardGateway)(ne),Yt=!!(ne?.gateways?.stripe?.enabledPaymentMethods??M)?.includes("card")||(0,zn.canRecoverHostedCardForm)(ne),Be=G||Yt||Re,Ve=!!(v&&Be&&e),[_o,go]=(0,o.useState)(()=>ce!=="buttons"||nt?e??null:null),[Io,xn]=(0,o.useState)(0),Fn=ce!=="buttons"||nt||!!e&&_o===e,tn=ne?.captureMethod,un=(0,o.useRef)(Ye);(0,o.useEffect)(()=>{un.current=Ye},[Ye]);let nr=(0,o.useRef)(_e);nr.current=_e;let Hn=(0,o.useRef)({onCardFieldsReady:de,onCardFieldsFailed:ve,emitInstrument:Ae});Hn.current={onCardFieldsReady:de,onCardFieldsFailed:ve,emitInstrument:Ae};let[rn,Hr]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!Ve||!e||!Fn){Hr(null);return}let i=un.current?un.current.cardCapture({sessionId:e,captureMethod:tn,cardFieldsTimeoutMs:nr.current}):new $n.PciVaultCardCapture({sessionId:e,captureMethod:tn,billingApiUrl:xt,telemetry:n,cardFieldsTimeoutMs:nr.current}),C=i.onCardFields?.(N=>{let me=Hn.current;me.emitInstrument?.((0,c.cardFieldsInstrumentSource)(N)),N.type==="card_fields_ready"?(0,c.invokeMerchantCallback)(()=>me.onCardFieldsReady?.(N)):(0,c.invokeMerchantCallback)(()=>me.onCardFieldsFailed?.(N))});return Hr({sessionId:e,captureMethod:tn,billingApiUrl:xt,telemetry:n,capture:i}),()=>{C?.(),i.unmount()}},[Ve,e,Fn,tn,xt,n]);let Ht=Ve&&e&&Fn&&rn?.sessionId===e&&rn.captureMethod===tn&&rn.billingApiUrl===xt&&rn.telemetry===n?rn.capture:null,Ir=(0,o.useMemo)(()=>{let i=pt,C=et?(0,c.isAVSFieldVisible)(et.postal_code,i):!1;return Xu(i,Ne,C)},[et,pt,Ne]),{avsInvalid:Bn,invalidAvsFields:oo}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Ve||!et)return{avsInvalid:!1,invalidAvsFields:i};let C=pt,N=(De,Vt)=>(0,c.isAVSFieldVisible)(De,C)&&!Vt.trim(),me={line1:N(et.address_line_1,Vr),city:N(et.city,cn),state:N(et.state,hn),zip:Ir.empty||Ir.malformed};return{avsInvalid:me.line1||me.city||me.state||me.zip,invalidAvsFields:me}},[Ve,et,pt,Vr,cn,hn,Ir]),[pn,On]=(0,o.useState)(!1),[Kn,ho]=(0,o.useState)(!1),[Gn,Pn]=(0,o.useState)(!1),[Vo,Wo]=(0,o.useState)({line1:!1,city:!1,state:!1}),ao=(0,o.useRef)(!1),vn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Po=(0,o.useRef)(!1),qt=(0,o.useCallback)(i=>{vn.current[i]=!0,Po.current=!0},[]),Dn=(0,o.useCallback)(i=>!ao.current&&vn.current[i],[]),Cn=(0,o.useCallback)(i=>{Dn(i)&&Wo(C=>C[i]?C:{...C,[i]:!0})},[Dn]),[bn,Sn]=(0,o.useState)(()=>(0,c.resolveVaultMountOptions)(ne?.vault,{billingApiUrl:xt,sessionId:e,nonce:t})),[ot,Kr]=(0,o.useState)(nt&&Be?"card":"buttons"),[jt,O]=(0,o.useState)(null),L=ot==="expanding"||ot==="card",se=ne?.gateways?.stripe&&!Ft?"stripe":void 0,ue=(0,o.useCallback)(()=>{Ae?.({class:"card_surface",provider:se})},[se,Ae]),Nt=(0,o.useCallback)(()=>{Qt(!0),Ae?.({class:"more_options"})},[Ae]),er=(0,o.useRef)(null),Oe=(0,o.useCallback)(i=>{er.current&&clearTimeout(er.current),er.current=setTimeout(()=>{er.current=null,i()},Xa)},[]);(0,o.useEffect)(()=>()=>{er.current&&clearTimeout(er.current)},[]);let it=(0,o.useRef)(!1),[re,Te]=(0,o.useState)(0),Ce=(0,o.useRef)(null),vt=(0,o.useCallback)(()=>{ue(),go(e??null),it.current&&(it.current=!1,Te(i=>i+1)),xn(i=>i+1),Kr("expanding"),Oe(()=>Kr("card"))},[Oe,ue,e]),m=(0,o.useCallback)(()=>{Kr("collapsing"),Oe(()=>Kr("buttons"))},[Oe]),g=(0,o.useCallback)(i=>{O(i),Kr("apm-expanding"),Oe(()=>Kr("apm-form"))},[Oe]),$=(0,o.useCallback)(()=>{Kr("apm-collapsing"),Oe(()=>{Kr("buttons"),O(null)})},[Oe]);(0,o.useEffect)(()=>{ce==="buttons"&&nt&&Be&&(go(e??null),Kr("card"))},[ce,nt,Be,e]);let[be,ie]=(0,o.useState)(null),ee=(0,o.useRef)(null),[Fe,_t]=(0,o.useState)(0);(0,o.useEffect)(()=>{Fe!==0&&ee.current?.focus()},[Fe]);let Xt=(0,o.useRef)(!1),st=(0,o.useRef)(null),It=(0,o.useRef)("idle"),[pe,Xe]=(0,o.useState)(!1),We=(0,o.useRef)(pe);We.current=pe;let[Je,Tt]=(0,o.useState)(()=>St?.existingOrderId?{orderId:St.existingOrderId,attempts:1}:null),nn=(0,o.useRef)(Je);(0,o.useEffect)(()=>{nn.current=Je},[Je]);let Jt=(0,o.useRef)(null),ti=(0,o.useMemo)(()=>{if(Q||A.claimBuyerIdentity||ne?.buyerIdentified!==!1||!e||!t)return;let i=`${xt}|${e}|${t}`;Jt.current?.key!==i&&(Jt.current={key:i,claim:ia(new $n.PaymentAPI(xt,{telemetry:!1}),e,t,{...s?{userId:s}:{},...h?{firstName:h}:{},...E?{lastName:E}:{}})});let C=Jt.current.claim;return async N=>{await C(N)}},[Q,A.claimBuyerIdentity,ne?.buyerIdentified,e,t,xt,s,h,E]),wn=Q??A.claimBuyerIdentity??ti,Ln=f??ur,$o=(0,o.useMemo)(()=>(0,c.resolveTheme)(q),[q]),at=(0,o.useMemo)(()=>{let i=$o?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(He);return Ke?{...i,...Ke,cardButton:{...i.cardButton,...Ke.cardButton},cardFormContainer:{...i.cardFormContainer,...Ke.cardFormContainer},backButton:{...i.backButton,...Ke.backButton},backButtonIcon:{...i.backButtonIcon,...Ke.backButtonIcon},submitButton:{...i.submitButton,...Ke.submitButton},title:{...i.title,...Ke.title}}:i},[$o,He,Ke]),Ho=Le??$o?.appearance,vd=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:Ho,buttonsStyles:at,layout:ce}),[Ho,at,ce]),Cd=A.inlineSessionPatchProcessing??!1,ir=(T??en)||Cd,vo=xt.replace(/\/+$/,""),Bt=(0,o.useMemo)(()=>_s({userId:s,email:a,firstName:h,lastName:E,country:ge,zip:rt},Lr),[s,a,h,E,ge,rt,Lr]),Ko=[Bt.firstName,Bt.lastName].filter(i=>!!i?.trim()).join(" "),il=!(0,c.isValidEmail)(Bt.email?.trim()),Qi=(0,o.useRef)(null);Ve&&Qi.current===null&&(Qi.current=il);let Co=Ve&&(Qi.current??il),es=(0,o.useMemo)(()=>Ju(ar,Co),[ar,Co]),Go=es.empty||es.malformed,mn=(0,o.useMemo)(()=>Ye?Ye.getRawProvider():null,[Ye]),sl=(0,o.useMemo)(()=>_?_.getRawProvider():null,[_]),va=Qe||100,Yo=Mt.toLowerCase(),ts=(0,o.useMemo)(()=>Ho?(0,$n.toStripeAppearance)(Ho):null,[Ho]),Xo=ts,ll=(0,o.useMemo)(()=>{let i=ts??{},C=i.rules??{};return{...i,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[ts]),cl=(0,o.useMemo)(()=>({...sc(Qe,F?.captureMethod,x),currency:Yo,...Xo?{appearance:Xo}:null}),[Qe,Yo,F?.captureMethod,x,Xo]),rs=(0,c.resolveSetupFutureUsage)(x,"paypal","paypal"),dl=(0,o.useMemo)(()=>({mode:"payment",amount:va,currency:Yo,captureMethod:"manual",...rs?{setupFutureUsage:rs}:null,...Xo?{appearance:Xo}:null}),[va,Yo,rs,Xo]),Ue=(0,o.useCallback)(i=>{pr(i),H?.(i)},[H]),ul=(0,o.useRef)(0);(0,o.useEffect)(()=>{re!==ul.current&&(ul.current=re,Ue(null))},[re,Ue]);let ns=(0,o.useRef)(""),[pl,bd]=(0,o.useState)(!1),os=(0,o.useCallback)(()=>{bd(!0)},[]);(0,o.useEffect)(()=>{if(!Ve||!Co||!wn||!pl||Go||ns.current)return;let i=(0,En.compactBuyerIdentity)({email:(0,c.isValidEmail)(Bt.email?.trim())?Bt.email?.trim():Ur.current.trim(),firstName:Bt.firstName?.trim(),lastName:Bt.lastName?.trim()});ns.current=JSON.stringify(i),$r(C=>({...C,...i})),Promise.resolve(wn(i)).catch(C=>{ns.current="",Ue(C instanceof Error?C.message:"Failed to attach buyer details.")})},[Ve,Co,wn,pl,Go,Bt.email,Bt.firstName,Bt.lastName,Ue]),(0,o.useEffect)(()=>{if(!Ve||!Ht)return;let i=ft!==!1&&et==null&&!Co;Ht.setCardFieldOrder?.(fe??null,i)},[Ve,Ht,fe,ft,et,Co]),(0,o.useEffect)(()=>{!Ve||!Ht||Ht.setCardBrandIcons?.(J===!0)},[Ve,Ht,J]),(0,o.useEffect)(()=>{(ot==="expanding"||ot==="collapsing"||ot==="apm-expanding"||ot==="apm-collapsing")&&Ue(null)},[ot,Ue]);let Yn=(0,o.useCallback)((i,C,N)=>{y?.(Cr(i,C,N))},[y]),ml=(0,o.useRef)(ot);ml.current=ot;let[yl]=(0,o.useState)(wi),fl=(0,o.useCallback)(()=>{let i=ml.current;if(ce==="buttons"&&(i==="card"||i==="expanding"))return!0;let C=It.current;return C==="validation-window"||C==="processing"||We.current},[ce]),gl=(0,o.useCallback)((i,C,N)=>{yl.take(e)&&br(Ye)?.log(Lo({...U,presentationMode:N?.presentationMode??"popup"},{name:Si,stage:"recovery",reason:"other_method_active",provider:N?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:N?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[U,Ye,yl,e]),ri=(0,o.useCallback)((i,C,N)=>{N?.telemetryReported||br(Ye)?.error(Lo({...U,presentationMode:N?.presentationMode??"popup"},{errorCode:C?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:N?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:N?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:N?.terminalReason??(C?"popup_blocked":"provider_error")}))},[U,Ye]),Jo=(0,o.useCallback)((i,C,N)=>{let me=N?.popupBlocked??(0,ke.isPopupBlockedError)(C);if(fl()){ri(i,me,N),gl(i,C,N);return}if(C instanceof c.FloPayError&&C.code==="checkout_processing_timeout"){ri(i,!1,N),ie(null),ce==="buttons"&&(Kr("buttons"),O(null)),Ue(C.message),p?.(C);return}me&&xe.markBlocked()&&u(wt=>wt+1);let Z=Vs(i),De=N?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(Z):(0,ke.buildExternalMethodRecoveryMessage)(Z,me,k.inAppBrowser),Vt=(0,ke.getProviderErrorCode)(C),Wt=(Vt?.toLowerCase()==="error"?void 0:Vt)??(0,ke.sanitizeExternalFailureCode)(N?.code)??"external_payment_method_failed",lt=new c.FloPayError(De,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:Wt,popupBlocked:me,inAppBrowser:k.inAppBrowser,appFamily:k.appFamily,popupCapability:xe.current(),presentationMode:N?.presentationMode??"popup"}});ri(i,me,N),ie(null),ce==="buttons"&&(Kr("buttons"),O(null)),Ue(De),p?.(lt),console.error("[FloPay] External payment method failed:",{method:i,code:Wt,popupBlocked:me})},[k,fl,ce,p,xe,gl,ri,Ue]);(0,o.useEffect)(()=>{if(!Ve||!e){Sn(null);return}let i={billingApiUrl:vo,sessionId:e,nonce:t},C=(0,c.resolveVaultMountOptions)(ne?.vault,i);if(C){Sn(C);return}if(!Fn){Sn(null);return}let N=`${vo}\0${e}\0${t??""}`,me=Ce.current;if(me&&me.key===N){Sn(me.mount);return}Sn(null);let Z=!0;return new $n.PaymentAPI(vo).getVaultCapture(e,t).then(De=>{if(!Z)return;let Vt=(0,c.resolveVaultMountOptions)(De,i);Vt?.verificationRequired&&!De.html&&(Ce.current={key:N,mount:Vt}),Vt?Sn(Vt):Ue("Failed to load the secure card form.")}).catch(De=>{Z&&Ue(De instanceof Error?De.message:"Failed to load the secure card form.")}),()=>{Z=!1}},[Ve,Fn,Io,e,ne?.vault,vo,t,Ue]);let Nn=(0,o.useRef)({onComplete:d,onError:p,updateError:Ue,emitDecline:Yn,resolvedAccount:Bt,avsConfig:et,avsCheckProp:Ie,sessionId:e,nonce:t,baseUrl:vo,captureMethod:ne?.captureMethod,paymentId:ne?.paymentId,authorizationExpiresAt:ne?.authorizationExpiresAt,serverSideCardGateway:Ft});Nn.current={onComplete:d,onError:p,updateError:Ue,emitDecline:Yn,resolvedAccount:Bt,avsConfig:et,avsCheckProp:Ie,sessionId:e,nonce:t,baseUrl:vo,captureMethod:ne?.captureMethod,paymentId:ne?.paymentId,authorizationExpiresAt:ne?.authorizationExpiresAt,serverSideCardGateway:Ft};let as=(0,o.useRef)(!1),hl=(0,o.useCallback)(()=>{let i=Nn.current,C=i.resolvedAccount.email?.trim(),N=(0,c.isValidEmail)(C)?C:Ur.current.trim();if(!(0,c.isValidEmail)(N))return null;let me=i.resolvedAccount.firstName?.trim(),Z=i.resolvedAccount.lastName?.trim(),De=Nr.current.trim()||i.resolvedAccount.country?.trim()||"",Vt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.state,De):!1,Wt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_1,De):!1,lt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.postal_code,De):!1,wt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.city,De):!1,Ot=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_2,De):!1,fr=Wt&&!Vt&&lt?(0,c.getStateFromPostalCode)(De,(Kt.current??"").trim()):null,yn=Vt?yr.current:fr;return{accountData:{userId:i.resolvedAccount.userId??"",email:N,...me?{firstName:me}:{},...Z?{lastName:Z}:{},...lt&&Kt.current?{zip:Kt.current}:{},...wt&&vr.current?{city:vr.current}:{},...yn?{state:yn}:{},...Wt&&mr.current?{addressLine1:mr.current}:{},...Ot&&Yr.current?{addressLine2:Yr.current}:{},...De?{country:De}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,c.isAVSFieldVisible)(i.avsConfig.country,De),postal_code:lt,address_line_1:Wt,address_line_2:Ot,city:wt,state:Vt}}:{}}},[]),Pl=(0,o.useRef)(Et);Pl.current=Et,(0,o.useEffect)(()=>{Et||Ln!==Nc||Nn.current.updateError(null)},[Et,Ln]),(0,o.useEffect)(()=>{!Ve||!Ht||Ht.setSubmitGate?.(Bn||Et||Go||pe)},[Ve,Ht,Bn,Et,Go,pe]),(0,o.useEffect)(()=>{if(!Ve||!Ht)return;as.current=!1;let i=null,C=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,It.current="idle",ie(null)},400)},N=Ht.on("submitting",()=>{On(!0),st.current&&clearTimeout(st.current),It.current="validation-window",st.current=setTimeout(()=>{st.current=null,It.current==="validation-window"&&(It.current="processing")},zu),ie("processing");let lt=Nn.current;if(!lt.sessionId||!lt.nonce)return;let wt=hl();if(!wt){lt.updateError("Enter a valid email address."),It.current="idle",ie(null);return}new $n.PaymentAPI(lt.baseUrl).patchAccountSnapshot(lt.sessionId,lt.nonce,wt,{telemetryMode:"best_effort"}).catch(Ot=>{if(!ju(Ot))return;let fr=Ot instanceof Error?Ot.message:"Please check your billing address and try again.";lt.updateError(fr),It.current="idle",ie(null),lt.onError?.(Ot instanceof c.FloPayError?Ot:new c.FloPayError(fr,"api_error"))})}),me=Ht.on("complete",lt=>{(0,Vn.markSessionRecentlyCompleted)(lt.sessionId??Nn.current.sessionId),It.current="terminal",Xe(!1),ie("success"),setTimeout(()=>{if(as.current)return;as.current=!0;let wt=Nn.current,Ot=(0,c.isAuthorizationOnlySession)(wt)||lt.outcome==="authorized",fr=wt.serverSideCardGateway?{}:{paymentIntentId:lt.intentId};Nn.current.onComplete?.(Ot?{status:"authorized",...fr,paymentId:lt.paymentId??wt.paymentId,sessionId:lt.sessionId??wt.sessionId,authorizationExpiresAt:lt.authorizationExpiresAt??wt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...fr,checkoutMethod:"card"})},600)}),Z=Ht.on("decline",lt=>{let wt=Nn.current,Ot=lt.message??"Your payment was declined. Please try another card or contact your bank.";It.current="terminal",Xe(!1),wt.updateError(Ot),ie("error");let fr=lt.failureOutcome??(0,c.normalizeCheckoutFailureOutcome)(lt.declineReason)??"authorization_declined";wt.emitDecline("card",Ot,{code:fr,declineCode:fr}),C()}),De=Ht.on("error",lt=>{let wt=Nn.current,Ot=(0,c.buyerEmailRequiredPrompt)(lt.vaultOutcome);if(Ot!==null){i&&(clearTimeout(i),i=null),It.current="idle",Xe(!1),wt.updateError(Ot),ie(null),_t(yn=>yn+1),wt.onError?.(new c.FloPayError(Ot,"api_error",{code:c.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let fr=lt.message??"There was a problem processing your payment. Please try again.";It.current="terminal",Xe(!1),wt.updateError(fr),ie("error"),wt.onError?.(new c.FloPayError(fr,"api_error",{code:lt.failureOutcome??"capture_failed"})),C()}),Vt=Ht.on("challenge_dismissed",()=>{st.current&&(clearTimeout(st.current),st.current=null),It.current="processing",Xe(!0),ie(null)}),Wt=Ht.on("blocked",()=>{if(We.current){Nn.current.updateError(qu);return}if(!Pl.current){On(!0);return}os(),Nn.current.updateError(Nc)});return()=>{i&&(clearTimeout(i),i=null),st.current&&(clearTimeout(st.current),st.current=null),It.current="idle",Xe(!1),ie(null),N(),me(),Z(),De(),Vt(),Wt()}},[Ve,Ht,os,hl]);let Xn=!!St?.clientId,Ca=Array.isArray(M),ni=Ca&&M.length>0,vl=Ca&&M.includes("paypal"),oi=(0,o.useRef)(null);oi.current===null&&(oi.current=(0,c.hasMatchingStripePayPalReturn)());let Zo=oi.current?"redirect":(0,Qn.resolveStripePayPalPresentation)(k,Se,xe.current()),{expressMethods:ai,paymentElementMethods:is}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(M,{excludePaypal:Xn}),[M,Xn]),Cl=Xn||!!_||vl&&Zo==="redirect",Sd=(0,o.useMemo)(()=>Cl?ai.filter(i=>i!=="paypal"):ai,[ai,Cl]),wd=(0,o.useMemo)(()=>{let i=[];return ye&&i.push("apple_pay"),Ee&&i.push("google_pay"),i},[ye,Ee]),Qo=Ca?Sd:wd,Rd=v&&Qo.length>0,bl=z?pt:ge,ii=(0,o.useMemo)(()=>(0,c.filterStripeMethodsByCountryGate)(is,bl,oe),[is,bl,oe]),ss=(0,o.useMemo)(()=>({mode:"payment",amount:va,currency:Yo,paymentMethodCreation:"manual",appearance:ll}),[va,Yo,ll]),[ls,Sl]=(0,o.useState)("loading"),[cs,wl]=(0,o.useState)("loading"),[ds,Rl]=(0,o.useState)("loading"),[kd,us]=(0,o.useState)(!1),[kl,ps]=(0,o.useState)("loading"),[ms,Ed]=(0,o.useState)();(0,o.useEffect)(()=>{Ed((0,Zn.detectPayPalEnvironment)())},[]);let si=ms?.inAppBrowser,li=ms?(0,Qn.resolvePayPalPresentationMode)(ms,St?.approvalPresentation,At??(ht?"subscription":"order")):"popup",El=X&&(Xn||(Ca?vl:si===!1)),_d=k.inAppBrowser&&xe.current()==="blocked",_l=v&&Rd&&!_d,To=(!rr||!!A.waitForDataAttachment)&&El&&Xn,ys=kl==="retrying"||kl==="exhausted",ba=null;v&&(_?ba=sl:Zo==="redirect"&&(ba=mn));let Il=(0,o.useMemo)(()=>({...U,presentationMode:Zo}),[U,Zo]),Mo=!rr&&El&&!!ba&&(!Xn||ys),bo=!rr&&_l&&!!mn,Ao=!rr&&v&&ni&&ii.length>0&&!!mn,Id=To&&!ys?kd:Mo&&$a(ls),Td=bo&&$a(cs),Md=Ao&&ds!=="load_error",Tl=[To||Mo,bo,Ao,Ve].filter(Boolean).length,Ad={card:Ve,paypal:To&&!ys||Mo&&$a(ls),wallets:bo&&$a(cs),apms:Ao&&ds!=="load_error"},Ml=i=>Ad[i],Al=i=>i==="loading"||i==="ready",xl=To||Mo&&Al(ls)||bo&&Al(cs)||Ao&&ds!=="load_error",ci=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!ci.current){if(!v&&!X){ci.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(!v&&X&&!Xn){ci.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(si!==void 0&&!rr&&!Be&&!xl){ci.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)}}},[v,X,Xn,si,rr,Be,xl,p,Ue]);let Fl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(Fl.current||!ni)return;let i=[];ye!==!0&&i.push("showApplePay"),Ee!==!0&&i.push("showGooglePay"),i.length!==0&&(Fl.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.`))},[ni,ye,Ee]);let Bl=(0,o.useCallback)((i,C,N)=>A.applyInlineSessionPatch?A.applyInlineSessionPatch(i).then(me=>({error:null,sessionId:me.sessionId||e,nonce:me.session?.clientSecret||t})).catch(me=>{let Z=(0,c.normalizeBeforeButtonClickError)(C,me);return N?.abandoned?.()||(Ue(Z.message),p?.(Z)),{error:Z,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[A.applyInlineSessionPatch,t,p,e,Ue]),Un=(0,o.useCallback)(async(i,C)=>{if(i!=="card"&&rr&&await A.waitForDataAttachment?.(),!qe)return{proceed:!0};try{let N=await qe({method:i,sessionId:e||void 0,createSession:A.inlineSessionDraft});if(N===!1)return{proceed:!1};if(N&&typeof N=="object"){N.account&&$r(Z=>({...Z??{},...N.account}));let me=await Bl(N,i,C);return me.error?{proceed:!1,accountPatch:N.account}:{proceed:!0,accountPatch:N.account,sessionId:me.sessionId,nonce:me.nonce}}return{proceed:!0}}catch(N){if(!C?.abandoned?.()){let me=(0,c.normalizeBeforeButtonClickError)(i,N);Ue(me.message),p?.(me)}return{proceed:!1}}},[Bl,A.inlineSessionDraft,A.waitForDataAttachment,rr,qe,p,e,Ue]),Ol=(0,o.useCallback)(async(i,C)=>{if(Xt.current)return;Xt.current=!0,jr(!0),ie("processing"),Ue(null);let N=C?.sessionId??e,me=C?.nonce??t,Z=_s(Bt,C?.accountPatch),De=C?.completionPaymentMethodId??Aa(i),Vt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,Wt=Hu(i),lt=C?.presentationMode?Ai(br(Ye),{...U,presentationMode:C.presentationMode}):void 0,wt=()=>{Ae?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Wt}),lt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Wn,requestCategory:"process_payment"})};try{let Ot=new $n.PaymentAPI(vo),yn=C?.settledProcessResponse??await Ot.processPayment(Z.userId??"",{sessionId:N,nonce:me,paymentMethodCategory:C?.paymentMethodCategory??Gu(i),tokenizedData:Vt,accountData:{...C?.accountPatch,userId:Z.userId??"",email:Z.email??"",firstName:Z.firstName||void 0,lastName:Z.lastName||void 0,...(0,c.buildProcessPaymentAvsAccount)({avsConfig:et,country:Nr.current,zip:Kt.current,city:vr.current,state:yr.current,addressLine1:mr.current,addressLine2:Yr.current})},...(0,c.buildCheckoutProcessMetadata)({chv:V,avsCheck:Ie,checkoutType:he,checkoutLayout:gt,avsConfig:et,country:Nr.current})}),yi=async Tr=>{let xo=(0,c.isAuthorizationOnlySession)(ne)||Tr?.status==="authorized";(0,Vn.markSessionRecentlyCompleted)(N),lt?.terminal({outcome:"payment_succeeded",...Wn}),ie("success"),Tt(null),await new Promise(Ia=>setTimeout(Ia,600));let Jn;typeof Tr?.paymentId=="string"?Jn=Tr.paymentId:ne?.paymentId&&(Jn=ne.paymentId);let Fo;typeof Tr?.authorizationExpiresAt=="string"?Fo=Tr.authorizationExpiresAt:ne?.authorizationExpiresAt&&(Fo=ne.authorizationExpiresAt),d?.(xo?{status:"authorized",...Jn===void 0?{}:{paymentId:Jn},sessionId:typeof Tr?.sessionId=="string"?Tr.sessionId:N,...Fo===void 0?{}:{authorizationExpiresAt:Fo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:i.isPaypal?"paypal":"card"})};if(yn.ok){await yi(yn.status===204?null:await yn.json().catch(()=>null));return}let gr=await yn.json().catch(()=>null);if(gr?.type==="paypal_redirect_required"){let Tr=gr.threeDSecureToken,xo=gr.paymentMethodId||i.id||"";if(!Ye||!Tr){ie("error"),Ue("PayPal authorization required but no token provided.");return}try{let Jn=_?.getRawProvider();if(!Jn){Ue("PayPal is not available.");return}let Fo={return_url:window.location.href};xo&&(Fo.payment_method=xo);let{error:Ia}=await Jn.confirmPayment({clientSecret:Tr,confirmParams:Fo,redirect:"if_required"});if(Ia){ie("error");let Yl=Ia.message??"PayPal payment failed.";Ue(Yl),Yn("paypal",Yl,{code:Ia.code})}}catch(Jn){ie("error"),Ue(Jn instanceof Error?Jn.message:"PayPal authorization failed.")}return}if(gr?.type==="paypal_direct_required"){let Tr=gr.orderId;if(!Tr){ie("error"),Ue("PayPal retry required but no order id provided.");return}let xo=nn.current?.attempts??0;if(xo>=2){ie("error"),Ue("PayPal payment could not be completed after multiple attempts."),Yn("paypal","paypal_direct_required retry limit exceeded");return}us(!1),ps("loading"),Tt({orderId:Tr,attempts:xo+1}),ie(null);return}if(yn.headers.get(Fu)===Bu){let Tr=await Ou(Ot,N,me);if(Tr!==void 0){await yi(Tr);return}}(0,c.classifyPaymentRejection)(yn.status,gr)?lt?.terminal({outcome:"payment_declined",...Wn,terminalReason:"provider_declined"}):wt(),ie("error");let Gl=gr?.message??"Payment failed. Please try again.";Ue(Gl),Yn(i.isPaypal?"paypal":"card",Gl,{code:gr?.code??gr?.gatewayErrorCode,declineCode:gr?.declineCode??gr?.gatewayDeclineReason}),await new Promise(Tr=>setTimeout(Tr,400))}catch(Ot){Kc(Ot)||wt(),ie("error"),Ue(Ot instanceof Error?Ot.message:"An unexpected error occurred"),await new Promise(fr=>setTimeout(fr,400))}finally{jr(!1),ie(null),Xt.current=!1}},[vo,e,t,Bt,et,Ie,he,gt,V,Ye,_,ne,d,Ue,Yn,Ae,U]),on=(0,o.useCallback)((i,C)=>{P&&!C?.settledProcessResponse?P(i):Ol(i,C)},[P,Ol]),Sa=`${$c}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(Sa);if(!i)return;let C;try{C=JSON.parse(i)}catch{cr(Sa);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>Hc||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!Qo.includes(C.paymentMethodType)){cr(Sa);return}cr(Sa),on({id:C.paymentMethodId,type:"card",threeDSecureActionResultTokenId:C.providerIntentId,gateway:"stripe",paymentMethodType:C.paymentMethodType},{...C.accountPatch?{accountPatch:C.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[on,t,e,Sa,Qo]);let Dl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Dl.current)return;let[i,C,N]=(0,c.readStripeRedirectParams)();if(!i||!C||oi.current||!Ye)return;let me=Ye.getRawProvider();if(!me)return;let Z=wt=>{let Ot=localStorage.getItem(wt);if(!Ot)return null;try{return JSON.parse(Ot)}catch{return cr(wt),null}},De=Z(to)??Z(Oc),Vt;if(De?.clientSecret){if(De.clientSecret!==C)return;Vt={...De.accountPatch?{accountPatch:De.accountPatch}:{},...De.sessionId?{sessionId:De.sessionId}:{},...De.nonce?{nonce:De.nonce}:{}}}else if(De?.sessionId&&De.sessionId!==e)return;Dl.current=!0,cr(to),cr(Oc),window.history.replaceState({},"",(0,c.stripeRedirectReturnUrl)());let Wt=De?.paymentMethodType??De?.tokenType??"card",lt="card";(async()=>{if(N==="failed"){let gr="Payment was declined. Please try again.";Ue(gr),Yn(lt,gr);return}let{paymentIntent:wt,error:Ot}=await me.retrievePaymentIntent(C);if(Ot){let gr=Ot.message??"Failed to retrieve payment status.";Ue(gr),Yn(lt,gr,{code:Ot.code});return}let fr=wt?.status,yn=Ma(fr);if(!wt||!yn){let gr=fr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ue(gr),Yn(lt,gr,{code:fr??"missing_payment_intent"});return}let yi=typeof wt.payment_method=="string"?wt.payment_method:wt.payment_method?.id;on({id:yi??De?.paymentMethodId??De?.tokenId??wt.id,type:"card",threeDSecureActionResultTokenId:wt.id,gateway:De?.gateway??"stripe",paymentMethodType:Wt},Vt)})()},[e,on,Ye,Ue,Yn]);let fs=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(Ve||Ye!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let wa=ce==="buttons",Xr=Ho?.variables,xd=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),gs=Xr?.colorBackground,Fd=gs&&!xd.has(gs)?gs:void 0,Ra=at.cardInputBorder??(wa?"#e5e7eb":"#A4A4FF"),Ll=Xr?.colorDanger??"#dc2626",or=i=>oo[i]&&(Vo[i]||pn),di=Go&&(Gn||pn),Rn=i=>i?Ll:Ra,ui=(Ir.malformed||Ir.empty)&&(Kn||pn),Bd=Rn(ui),hs=at.cardFormContainer?.backgroundColor??Fd??(wa?"white":"#EDEDFF"),ea=at.cardInputBackground??Xr?.colorBackground??"white",Ps=na(Y),Nl=na(K),ta=at.nameInput,Ul=at.cardInputFontSize??Zu(ta?.fontSize)??Xr?.fontSizeBase??"16px",zl=typeof ta?.fontFamily=="string"?ta.fontFamily:Xr?.fontFamily??"Poppins, sans-serif",ql=(0,c.toCssWeight)(ta?.fontWeight)??400,Od=at.cardInputColor??(typeof ta?.color=="string"?ta.color:void 0)??Xr?.colorText??"#262833",Dd=at.cardInputPlaceholderColor??"#9ca3af",sr=Xr?.borderRadius??"8px",io=Xr?.borderRadius??at.cardButton?.borderRadius??sr,So=Xr?.colorPrimary??"#4A49FF",Ld=Xr?.colorPrimaryHover??(0,c.darkenHex)(So,.12),vs=Xr?.colorText??"#262833",Cs={fontSize:Ul,fontFamily:zl,fontWeight:ql,color:Od,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ka={marginTop:"0.375rem",...Cs,fontSize:"0.75rem",lineHeight:1.4,color:Ll},Nd={"--flopay-input-placeholder-color":Dd,"--flopay-input-font-size":Ul,"--flopay-input-font-family":zl,"--flopay-input-font-weight":String(ql)},Ea=at.cardFormContainer??{},bs=Ea.padding??(wa?"0":"1rem"),Ss=Ea.borderRadius??sr,Ud=Ht&&bn?(0,l.jsx)(Eo,{capture:Ht,html:bn.html,messageToken:bn.messageToken,expectedOrigin:bn.expectedOrigin,verificationRequired:bn.verificationRequired,theme:vd,submitLabel:w,onReady:()=>{if(!Co&&!et||typeof document>"u"||ft===!1)return;let i=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){ao.current=!0;try{N.focus()}finally{ao.current=!1}}};Po.current||i()},onError:i=>{i&&bn.verificationRequired&&It.current==="idle"&&(it.current=!0),Ue(i)},onValidation:i=>{let C=It.current;(C==="idle"||C==="validation-window")&&(Ue(i),i&&It.current==="validation-window"&&(st.current&&(clearTimeout(st.current),st.current=null),It.current="idle",ie(null)))}},re):(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"}),ws=(0,l.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&ue()},style:{backgroundColor:hs,borderRadius:Ss,...Ea,padding:bs,...Nd,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
30
+ `,Eo=44;function ha(){return(0,Lr.jsx)("style",{children:Su})}function Wa(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function $a({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Lr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Lr.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,Lr.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 Ha(e){return e!=="unavailable"&&e!=="load_error"}function xi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:s=!1,onClick:d,backgroundColor:p,borderColor:m,textColor:w,borderRadius:h,fontFamily:g}){let _=(0,yo.resolveStripeMethodBrandVariant)(e,t),V=Mc[e],[W,k]=(0,Ac.useState)(!1),A=!!V&&!W,f=_?.backgroundColor??p??"#ffffff",H=_?.borderColor??m??"#d1d5db",Y=_?.textColor??w??"#262833";return(0,Lr.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:Y,border:`1px solid ${H}`,borderRadius:h??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,Lr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,yo.getStripeMethodDisplayName)(e)}\u2026`}):(0,Lr.jsxs)(Lr.Fragment,{children:[(0,Lr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,yo.hasVendoredStripeMethodLogo)(e)?8:0},children:[A?(0,Lr.jsx)("img",{src:V,alt:"","aria-hidden":"true",onError:()=>k(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!A&&_?.logoSvg?(0,Lr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:_.logoSvg}}):null,(0,Lr.jsx)("span",{children:(0,yo.getStripeMethodDisplayName)(e)})]}),s&&(0,Lr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:Y,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,Lr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Fi(e){let t=new Set(e.map(yo.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?"auto":"never"]))}var Bi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Oi={type:"accordion",defaultCollapsed:!1,radios:"never"};function Di({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:s,style:d,children:p}){return(0,Lr.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 Ls=require("react/jsx-runtime"),wu=["first","second","third","fourth"];function Ns({rows:e,borderRadius:t}){return(0,Ls.jsx)("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:wu.slice(0,Math.max(1,e)).map(r=>(0,Ls.jsx)("div",{style:{height:Eo,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},r))})}var Fc=require("@flopay/js"),Li=require("@flopay/shared"),Ni=require("react"),Ru=1500,xc=new Set;function Bc(e){for(let t of e)xc.has(t)||(xc.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function ku(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 Eu={order:[...Li.DEFAULT_PAYMENT_METHOD_ORDER],moreOptions:[]};function Oc({rules:e,sessionId:t,nonce:r,billingApiUrl:n,waitForSession:a}){let s=ku(e),[d,p]=(0,Ni.useState)(null);return(0,Ni.useEffect)(()=>{if(s===void 0||a)return;let m=JSON.parse(s),w=!1,h=W=>{w||(w=!0,p(W))},g=()=>h((0,Li.resolveDefaultPaymentMethodLayout)(m));if(!t||!r||!n){g();return}let _=new AbortController,V=setTimeout(()=>{g(),_.abort()},Ru);return new Fc.PaymentAPI(n,{telemetry:!1}).resolvePaymentMethodLayout(t,r,m,{signal:_.signal}).then(W=>{if(!W){g();return}w||Bc(W.warnings),h({order:W.order,moreOptions:W.moreOptions})}).catch(g).finally(()=>clearTimeout(V)),()=>{w=!0,clearTimeout(V),_.abort()}},[s,t,r,n,a]),s===void 0?Eu:d}var dn=require("react");var Ka=require("@flopay/shared"),_u=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 Iu(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return _u.has(t.charAt(0).toLowerCase()+t.slice(1))}function Tu(e,t){return typeof t=="number"&&t!==0&&!Iu(e)?`${t}px`:String(t).trim()}function Dc(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]=Tu(r,n)}}}var Uo=require("react/jsx-runtime"),Us=new WeakSet;function _o({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:s,submitLabel:d,containerStyle:p,onReady:m,onError:w,onValidation:h}){let g=(0,dn.useRef)(null),_=(0,dn.useRef)(m),V=(0,dn.useRef)(w),W=(0,dn.useRef)(h);_.current=m,V.current=w,W.current=h;let k=(0,dn.useRef)(s);k.current=s;let A=(0,dn.useRef)(null),f=d??void 0,H=(0,dn.useRef)(f);H.current=f;let Y=(0,dn.useRef)(void 0);return(0,dn.useEffect)(()=>{let b=g.current;if(!b)return;let be=!0,x=!1,oe=()=>{!be||x||(x=!0,_.current?.())},ge=e.on("ready",()=>{oe()}),Ie=e.on("error",q=>{V.current?.(q.message??"There was a problem loading the secure card form.")}),ce=e.on("validation",q=>{W.current?.(q.message??null)}),Rt=H.current??(Us.has(e)?null:void 0),mt={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...k.current?{theme:k.current}:{},...Rt===void 0?{}:{submitLabel:Rt}};return A.current=k.current??null,Y.current=H.current,H.current!==void 0&&Us.add(e),e.mount(b,mt).then(()=>{oe()}).catch(q=>{be&&V.current?.(q instanceof Error?q.message:"Failed to load the secure card form.")}),()=>{be=!1,ge(),Ie(),ce(),e.unmount()}},[e,t,r,n,a]),Bo(()=>{let b=g.current;b&&Dc(b,p)},[p]),(0,dn.useEffect)(()=>{s!==void 0&&(s===null&&A.current===null||(A.current=s,e.applyTheme?.(s)))},[e,s]),(0,dn.useEffect)(()=>{f!==Y.current&&(Y.current=f,f!==void 0&&Us.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,Uo.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields"})}function Ga({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 Xs=require("@flopay/shared"),l=require("react/jsx-runtime"),eo="flopay_stripe_resume",Lc="flopay_wallet_resume",Kc="fw1",Mu="fw2",Gc=300*1e3,Au=900,xu="express_checkout_click_timeout",Fu=25e3,Bu=25e3,Ou=1e4,Vn={provider:"paypal",paymentMethodCategory:"paypal"},Du="x-flopay-process-result-source",Lu="status";async function Nu(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 Ui={},Xa=class{constructor(t){this.reason=t}};function Uu(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function cr(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 Ks(e){return`${Mu}:${e}`}function zi(e){return cr(Ks(e))}function qi(e,t){if(typeof window>"u")return null;let r=Ks(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>Gc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(zi(e),null):a}catch{return zi(e),null}}function zu(e){return cr(Ks(e.sessionId),e)}function Nc(e,t,r){let n=qi(e,t);return!n||n.clientSecret!==r?!1:zi(e)}function zs(e,t,r){if(typeof window>"u")return;qi(e,t)?.clientSecret===r&&zi(e)}function qu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function qs(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":Aa(e.status),a=qu(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Uc(e,t,r){let n=null;try{return await Promise.race([lc(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},Ou),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function ju(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Yc(e){return e instanceof c.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ji(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Wn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw Yc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var js=c.STRIPE_PAYPAL_RESUME_KEY,Ya=new Map,Vu=250,zc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Wu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Gs(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 Vi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Wn.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 Xc({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),s=(0,la.splitFullName)(r),d=s.firstName?s:(0,la.splitFullName)(n?.name);return(0,kn.compactBuyerIdentity)({email:(0,c.isValidEmail)(a)?a:n?.email?.trim(),firstName:d.firstName,lastName:d.lastName})}async function Hu({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:s}){let d=Xc({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 Ja=180,qc=`flopay-card-enter ${Ja}ms cubic-bezier(0, 0, 0.2, 1) both`,jc=`flopay-card-exit ${Ja}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Ku=`flopay-buttons-enter ${Ja}ms cubic-bezier(0, 0, 0.2, 1) both`,Gu=`flopay-buttons-exit ${Ja}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Yu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ys(e){return(0,c.derivePrimaryTileStyle)(e)}var Xu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ju(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 Ws={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 Vc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function $s(e){return e==="paypal"?"PayPal":(0,c.getStripeMethodDisplayName)(e)}function Zu(e){let t=(0,c.getPostalCodeExample)(e);return`Enter a valid ${(0,c.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Qu(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 ep(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 tp(e){return typeof e=="number"?`${e}px`:e}var rp=["number","expiry","cvv","name"];function np(e){if(e===null||typeof e!="object")return null;let t={};for(let r of rp){let n=e[r];typeof n=="string"&&(t[r]=n)}return JSON.stringify(t)}function Wi(e){return(0,l.jsx)(ip,{...e})}function Wc({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:s,isProcessing:d=!1,onButtonClick:p,onDecline:m,onTechnicalFailure:w,runBeforeButtonClick:h,billingName:g,onBuyerIdentityReady:_,onLoadStateChange:V,placeholderBorderRadius:W,popupCapabilityOwner:k,externalTelemetryContext:A,presentationMode:f}){let H=uo(),{emitInstrument:Y}=(0,o.useContext)(Rn),b=(0,lr.useStripe)(),be=(0,lr.useElements)(),x=(0,o.useMemo)(()=>Ai(Er(H),A),[A,H]),[oe,ge]=(0,o.useState)("loading");(0,o.useEffect)(()=>{V?.(oe)},[oe,V]);let[Ie,ce]=(0,o.useState)(!1),Rt=(0,o.useRef)(!1),mt=!(0,c.isValidEmail)(r?.trim())||!g?.trim(),{request:q,collect:Ve,finish:We}=ca(),Ne=(0,o.useRef)(!1),ve=(0,o.useRef)(null),G=(0,o.useRef)(null),[K,Ze]=(0,o.useState)(0),[Se,qe]=(0,o.useState)(!1),Z=(0,o.useRef)(!1),j=(0,o.useRef)(new Map),{startAttempt:he,finishAttempt:X,invalidateAttempt:Pt,isAttemptInvalidated:pe,isAttemptCurrent:we,generationRef:Ae}=Oa((xe,Oe,Ke)=>{w?.(xe,Oe,{...Ke,popupBlocked:Ke?.popupBlocked??(0,_e.isPopupBlockedError)(Oe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),qe(!0),Ze(vt=>vt+1)},{onHandoffObserved:()=>{k.markAvailable(),x?.log({name:"provider.popup.opened",stage:"overlay_open",...Vn,attempt:Ae.current})}});(0,o.useEffect)(()=>{Se&&G.current?.focus()},[Se,K]);let Ce=(0,o.useCallback)(()=>{Ze(xe=>xe+1)},[]),kt=(0,o.useCallback)((xe,Oe,Ke)=>{Pt(Ke),w?.("paypal",xe,{code:Oe,popupBlocked:(0,_e.isPopupBlockedError)(xe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),qe(!0),Ce()},[Pt,w,f,Ce]),Pe=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ve.current?.querySelector("iframe")??ve.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Z.current&&(Z.current=!1,Pe())},[Pe,K]);let Be=(0,o.useCallback)(()=>{qe(!1),s?.(null),Pe()},[Pe,s]);(0,o.useEffect)(()=>{if(!b||Ne.current)return;let[xe,Oe,Ke]=(0,c.readStripeRedirectParams)();if(!xe||!Oe)return;let vt=(0,c.readMatchingStripePayPalContinuation)(Oe);if(!vt)return;Ne.current=!0;let it=!0,ft=Ya.get(Oe);ft||(ft=Ke==="failed"?Promise.resolve(null):Promise.resolve().then(()=>b.retrievePaymentIntent(Oe)),Ya.set(Oe,ft));let Lt={accountPatch:vt.accountPatch,sessionId:vt.sessionId,nonce:vt.nonce},Qe=()=>{x?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Vn,requestCategory:"provider_sdk"})};return x?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Vn}),(async()=>{try{ce(!0);let de=await ft;if(!it)return;if(de?.error){Ya.delete(Oe),Qe(),s?.(de.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),Ya.delete(Oe),Ke==="failed"){let et="PayPal payment was declined. Please try again.";x?.terminal({outcome:"payment_declined",...Vn,terminalReason:"provider_declined"}),s?.(et),m?.(kr("paypal",et));return}let Ot=de?.paymentIntent;if(Ot&&Ot.id!==xe){Qe(),s?.("Failed to match the returned PayPal payment.");return}if(Ot&&(Ot.status==="requires_capture"||Ot.status==="succeeded")){let et=typeof Ot.payment_method=="string"?Ot.payment_method:Ot.payment_method?.id;a({id:et??Ot.id,type:"card",threeDSecureActionResultTokenId:Ot.id,isPaypal:!0},{...Lt,presentationMode:"redirect"})}else{let et="PayPal payment was not completed. Please try again.";x?.terminal({outcome:Ot?.status==="canceled"?"payment_cancelled":"payment_declined",...Vn,terminalReason:Ot?.status==="canceled"?"cancelled":"provider_declined"}),s?.(et),m?.(kr("paypal",et))}}catch(de){if(!it)return;Ya.delete(Oe),Qe(),s?.(de instanceof Error?de.message:"Failed to complete PayPal payment.")}finally{it&&ce(!1)}})(),()=>{it=!1,Ne.current=!1}},[b,a,s,m,x]);let at=(0,o.useCallback)(async(xe=!1)=>{let Oe=h?await h("paypal"):{proceed:!0};if(!Oe.proceed)return j.current.delete(K),!1;let Ke=he("paypal");return j.current.set(K,{generation:Ke,accountPatch:Oe.accountPatch,sessionId:Oe.sessionId,nonce:Oe.nonce}),qe(!1),x?.log({name:`provider.${xe?"redirect.started":"handoff.requested"}`,stage:xe?"redirect":"overlay_open",...Vn,attempt:Ke}),p?.("paypal"),!0},[p,x,h,he,K]),yt=(0,o.useCallback)(async xe=>{if(d||Ie||!await at()){xe.reject();return}xe.resolve()},[d,at,Ie]),Mt=(0,o.useCallback)(async xe=>{if(!b||!be)return;let Oe=j.current.get(K);if(Oe&&!we(Oe.generation)){j.current.delete(K);return}if(!Oe&&pe()||Oe&&!X(Oe.generation))return;Oe||X();let Ke=Oe??null;if(j.current.delete(K),!Ke&&h){let st=await h("paypal");if(!st.proceed){xe.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ke={accountPatch:st.accountPatch,sessionId:st.sessionId,nonce:st.nonce}}let vt=Ke?.sessionId??e,it=Ke?.nonce??t,ft=await Hu({event:xe,prepared:Ke,email:r,billingName:g,methodLabel:"PayPal",collect:Ve});if(!ft){xe.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Lt=ft.email,Qe={...Ke?.accountPatch,...(0,kn.compactBuyerIdentity)(ft,!0)};try{if(ce(!0),s?.(null),!vt||!(0,c.isValidEmail)(Lt))throw new Error("Missing sessionId or email for PayPal payment");await _?.(ft);let st=b.createPaymentMethod,{error:de,paymentMethod:Ot}=await st({type:"paypal"});if(de){kt(de,"stripe_paypal_create_payment_method_failed",Oe?.generation),xe.paymentFailed({reason:"fail"});return}let et=await ji(n,Y,vt,it??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Ot?.id??null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(et)){xe.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:Qe,paymentMethodCategory:"paypal",presentationMode:f,sessionId:vt,nonce:it,settledProcessResponse:et.response});return}if(et.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let re=et.clientSecret,v={return_url:(0,c.stripeRedirectReturnUrl)()};if(Ot?.id&&(v.payment_method=Ot.id),!cr(js,{clientSecret:re,sessionId:vt,nonce:it,accountPatch:Qe})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:ee,paymentIntent:$}=await b.confirmPayment({clientSecret:re,confirmParams:v,redirect:"if_required"});if(ee){if(cr(js),(0,_e.isProviderDecline)(ee)){let u=ee.message??"Your payment was declined.";x?.terminal({outcome:"payment_declined",...Vn,terminalReason:"provider_declined"}),s?.(u),m?.(kr("paypal",u,{code:(0,_e.getProviderErrorCode)(ee),declineCode:(0,_e.getProviderDeclineCode)(ee)})),await Vi({billingApiUrl:n,sessionId:vt,nonce:it,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,_e.getProviderErrorCode)(ee)??"provider_declined"}})}else kt(ee,"stripe_paypal_confirm_failed",Oe?.generation);return}cr(js);let nt=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;a({id:nt??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,isPaypal:!0},{accountPatch:Qe,paymentMethodCategory:"paypal",presentationMode:f,sessionId:vt,nonce:it});return}catch(st){kt(st,"stripe_paypal_failed",Oe?.generation)}finally{ce(!1)}},[b,be,e,t,r,g,Ve,_,n,Y,a,s,m,h,kt,X,we,pe,x,f,K]),le=(0,o.useCallback)(async()=>{if(!(Rt.current||d||Ie||!b||!be)){Rt.current=!0,ce(!0);try{if(!await at(!0))return;await Mt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Rt.current=!1,ce(!1)}}},[be,Mt,d,at,b,Ie]),It=f==="redirect"?(0,l.jsx)("button",{type:"button",disabled:d||Ie,onClick:()=>{le()},style:{width:"100%",minHeight:Eo,border:"1px solid #d1d5db",borderRadius:W??8,background:"#ffc439",color:"#111827",cursor:d||Ie?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,l.jsx)(lr.ExpressCheckoutElement,{onReady:xe=>ge(Wa(xe,["paypal"])),onLoadError:()=>{ge("load_error"),Gs(x,"paypal","paypal","provider_error")},onClick:yt,onConfirm:Mt,onCancel:()=>{let xe=j.current.get(K);j.current.delete(K),x?.terminal({outcome:"payment_cancelled",...Vn,terminalReason:"cancelled",...xe?{attempt:xe.generation}:{}}),Pt(xe?.generation),qe(!1),Z.current=!0,Ce()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:mt,emailRequired:mt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},K),Vt=(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:[Se&&(0,l.jsx)("button",{ref:G,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Be,style:Ws,children:"Try PayPal again"}),q&&(0,l.jsx)(da,{identity:q.identity,methodLabel:q.methodLabel,onComplete:We,onCancel:()=>We(null)},q.id),(0,l.jsx)("div",{style:{display:q?"none":void 0},children:It})]}),Ie&&!q&&(0,l.jsx)(rn,{status:"processing"})]});return f==="redirect"?Vt:(0,l.jsx)($a,{state:oe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:W,children:Vt})}function Vs(e){return e==="apple_pay"||e==="google_pay"}var op=200;function ap({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,c.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function $c({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:s,onTokenizedBody:d,onErrorChange:p,onButtonClick:m,onDecline:w,onTechnicalFailure:h,runBeforeButtonClick:g,billingName:_,onBuyerIdentityReady:V,onLoadStateChange:W,placeholderBorderRadius:k,popupCapabilityOwner:A,externalTelemetryContext:f}){let H=uo(),{emitInstrument:Y}=(0,o.useContext)(Rn),b=(0,lr.useStripe)(),be=(0,lr.useElements)(),x=(0,o.useMemo)(()=>Ai(Er(H),f),[f,H]),[oe,ge]=(0,o.useState)("loading");(0,o.useEffect)(()=>{W?.(oe)},[oe,W]);let[Ie,ce]=(0,o.useState)(!1);(0,o.useEffect)(()=>{qe.current=Ie},[Ie]);let Rt=(0,o.useRef)(!(0,c.isValidEmail)(r?.trim())||!_?.trim()).current,{request:mt,collect:q,finish:Ve}=ca(),We=(0,o.useRef)(null),Ne=(0,o.useRef)(null),[ve,G]=(0,o.useState)(0),[K,Ze]=(0,o.useState)(()=>(0,c.shouldPreferWalletPopup)()),Se=(0,o.useRef)(K),qe=(0,o.useRef)(!1),[Z,j]=(0,o.useState)(!1),[he,X]=(0,o.useState)(()=>qi(e,t)?"blocked":"idle"),[Pt,pe]=(0,o.useState)("google_pay"),we=(0,o.useRef)(null),Ae=(0,o.useRef)(!0),Ce=(0,o.useRef)(!1),kt=(0,o.useRef)("google_pay"),Pe=(0,o.useRef)("google_pay"),Be=(0,o.useRef)(null),at=(0,o.useRef)(null),yt=(0,o.useRef)(new Set),Mt=(0,o.useRef)(null),le=(0,o.useRef)(null);(0,o.useEffect)(()=>(Ae.current=!0,()=>{Ae.current=!1;for(let u of yt.current)window.clearTimeout(u);yt.current.clear()}),[]);let It=(0,o.useRef)(new Map),{startAttempt:Vt,finishAttempt:xe,invalidateAttempt:Oe,isAttemptInvalidated:Ke,isAttemptCurrent:vt,generationRef:it}=Oa((u,F,D)=>{h?.(u,F,{...D,popupBlocked:D?.popupBlocked??(0,_e.isPopupBlockedError)(F),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),pe(u),j(!0),G(L=>L+1)},{onHandoffObserved:u=>{le.current=it.current,A.markAvailable(),x?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:it.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:Vs,onMissingTerminalDeferred:(u,F)=>{let D=x?.now()??globalThis.performance?.now()??Date.now(),L=Mt.current,T=L?.generation===F?L.startedAt:D;x?.performance({stage:"overlay_return",durationMs:Math.max(0,D-T),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:F,...Vs(u)?{walletType:u}:{}}),x?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{Z&&Ne.current?.focus()},[Z,ve]);let ft=(0,o.useRef)(0),Lt=(0,o.useRef)(!1),Qe=(0,o.useCallback)(()=>{if(ft.current>0){Lt.current=!0;return}G(u=>u+1)},[]),st=(0,o.useCallback)(()=>{ft.current-=1,!(ft.current>0||!Lt.current)&&(Lt.current=!1,Ae.current&&G(u=>u+1))},[]),de=(0,o.useCallback)((u,F,D,L,T=!1)=>{Oe(L),h?.(u,F,{code:D,popupBlocked:(0,_e.isPopupBlockedError)(F),telemetryReported:T,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),pe(u),j(!0),Qe()},[Oe,h,Qe]),Ot=(0,o.useCallback)(u=>{x?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...Vs(u)?{walletType:u}:{}}),h?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:xu,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),pe(u),j(!0)},[h,x]),et=(0,o.useCallback)(()=>{window.setTimeout(()=>{(We.current?.querySelector("iframe")??We.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Ce.current&&(Ce.current=!1,et())},[et,ve]);let re=(0,o.useCallback)(()=>{j(!1),p?.(null),et()},[et,p]),v=(0,o.useCallback)(()=>{we.current?.()},[]);(0,o.useEffect)(()=>{let u=null,F=()=>{u=null;let L=(0,c.shouldPreferWalletPopup)();L!==Se.current&&(Se.current=L,Ze(L),!qe.current&&!vt(it.current)&&Qe())},D=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(F,op)};return window.addEventListener("resize",D),()=>{window.removeEventListener("resize",D),u!==null&&window.clearTimeout(u)}},[it,vt,Qe]),(0,o.useEffect)(()=>{let u=qi(e,t);if(!u)return;let F=!1,D=!1,L=async()=>{if(!D){D=!0,F||X("checking");try{let T=await Uc(b,u.clientSecret,yt.current);if(F)return;let I=qs(T,u.providerObjectId,(0,c.isSetupIntentClientSecret)(u.clientSecret));if(I.kind==="confirmed"){if(!Nc(e,t,u.clientSecret))return;we.current=null,X("idle"),d({id:I.paymentMethodId,type:"card",threeDSecureActionResultTokenId:I.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(I.kind==="terminal"){zs(e,t,u.clientSecret),we.current=null,X("idle"),pe(u.paymentMethodType),j(!0),Qe();return}X("blocked")}catch{F||X("blocked")}finally{D=!1}}};return we.current=L,X("blocked"),()=>{F=!0,we.current===L&&(we.current=null)}},[t,d,Qe,e,b]);let Q=(0,o.useCallback)(async u=>{let F=!1,D=!1,L=St=>{F||D||(F=!0,u.paymentFailed({reason:"fail",...St?{message:St}:{}}))};if(!b||!be){L();return}let T=It.current.get(ve);if(T&&!vt(T.generation)){It.current.delete(ve),L();return}if(!T&&Ke()){L();return}if(T&&!xe(T.generation)){L();return}T||(xe(),Lt.current=!1);let I=u.expressPaymentType??T?.method??kt.current,Ct=T??null,Mr=Vc(I),bt;I==="apple_pay"?bt="apple_pay":I==="google_pay"&&(bt="google_pay");let un=T?.generation??it.current,gt=x,vr=gt?.now()??globalThis.performance?.now()??Date.now(),At=new AbortController,Ar=!1,Cr=!1,Xt=null,Jr=e,xr="processing",Ur="other",pn="provider_runtime",Fr,Wt=new Promise((St,lt)=>{Fr=lt}),br=window.setTimeout(()=>{Ar=!0,At.abort(),Fr(Ui)},Fu),Tt=async(St,lt,yn)=>{xr=St,Ur=lt,pn=lt==="intent_create"||lt==="session_claim"?"transport_error":"provider_runtime";let ur=gt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([yn,Wt])}finally{let zr=gt?.now()??globalThis.performance?.now()??Date.now();gt?.performance({stage:St,durationMs:Math.max(0,zr-ur),durationMode:"machine",requestCategory:lt,paymentMethodCategory:"wallet",provider:"stripe",...Ar?{statusClass:"timeout"}:{}})}};try{if(ce(!0),p?.(null),!Ct&&g){let ae=await Tt("processing","other",g(Mr));if(!ae.proceed){L();return}Ct={accountPatch:ae.accountPatch,sessionId:ae.sessionId,nonce:ae.nonce}}let St=Ct?.sessionId??e;Jr=St;let lt=Ct?.nonce??t,yn=Be.current??Ct?.accountPatch,ur=Xc({event:u,fallbackEmail:yn?.email??r,fallbackName:[yn?.firstName,yn?.lastName].join(" ").trim()||_});if(!(0,c.isValidEmail)(ur.email)){L("Buyer details are required."),q($s(I),ur).then(ae=>{ae&&(Be.current=ae)});return}Be.current=null;let zr={...Ct?.accountPatch,...(0,kn.compactBuyerIdentity)(ur,!0)};await Tt("processing","session_claim",Promise.resolve(V?.(ur)));let{error:An}=await Tt("tokenization","provider_sdk",be.submit());if(An){L(),de(I,An,"stripe_wallet_submit_failed",T?.generation);return}if(!St)throw new Error("Missing sessionId or email for payment.");let mn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I,paymentMethodId:null,intentKind:a},qr=JSON.stringify({sessionId:St,nonce:lt??"",request:mn}),fn=at.current,gn=fn?.retryIdentity===qr?fn.authorizationAttemptId:(0,c.randomUuidV4)();at.current={authorizationAttemptId:gn,retryIdentity:qr};let pr=await Tt("processing","intent_create",ji(n,Y,St,lt??"",{...mn,authorizationAttemptId:gn},{signal:At.signal}));if((0,c.isSettledSessionIntent)(pr)){L(),d({type:"card",paymentMethodType:I},{accountPatch:zr,paymentMethodCategory:"wallet",sessionId:St,nonce:lt,settledProcessResponse:pr.response});return}if(pr.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let tr=pr.clientSecret,on=zu({createdAt:Date.now(),sessionId:St,...lt?{nonce:lt}:{},clientSecret:tr,providerObjectId:pr.providerObjectId,paymentMethodType:I,accountPatch:zr});window.clearTimeout(br),Cr=!0,gt?.performance({stage:"callback",durationMs:Math.max(0,(gt?.now()??globalThis.performance?.now()??Date.now())-vr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Zr=gt?.now()??globalThis.performance?.now()??Date.now(),rr={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...bt?{walletType:bt}:{},attempt:un},Qt=!1,Sr=null;gt?.log({name:"payment.provider_confirmation.started",...rr}),Xt=window.setTimeout(()=>{Xt!==null&&yt.current.delete(Xt),Qt=!0;let ae=gt?.now()??globalThis.performance?.now()??Date.now();gt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...rr,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ae-Zr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),gt?.flush?.().catch(()=>{}),Sr?.()},Bu),yt.current.add(Xt);let jr=(ae,zt)=>{Xt!==null&&(window.clearTimeout(Xt),yt.current.delete(Xt),Xt=null);let Ft=gt?.now()??globalThis.performance?.now()??Date.now(),nr=Math.max(0,Ft-Zr),Xe=ae;Qt&&(ae==="resolved"?Xe="resolved_late":ae==="returned_error"?Xe="returned_error_late":Xe="rejected_late");let mr=zt??(ae==="resolved"?"approved":"provider_error");return gt?.log({name:"payment.provider_confirmation.returned",...rr,operationOutcome:Xe,terminalReason:mr}),gt?.performance({...rr,durationMs:nr,durationMode:"buyer",operationOutcome:Xe,terminalReason:mr}),{durationMs:nr,operationOutcome:Xe,terminalReason:mr}},yr=!1,wr=!1,$r=ae=>{if(!ae||typeof ae!="object")return null;let zt=ae;if(zt.error)return null;let Ft=zt.setupIntent??zt.paymentIntent,nr=qs(Ft??null,void 0,!!zt.setupIntent);return nr.kind==="confirmed"?nr:null},Br=ae=>{if(yr||T&&it.current!==T.generation)return;let zt=$r(ae);if(!zt)return;if(on&&!Nc(St,lt,tr)){yr=!0;return}let{intentId:Ft,paymentMethodId:nr}=zt;yr=!0,wr=!0,at.current=null,we.current=null,Ae.current&&(X("idle"),ce(!1));let Xe=`${Kc}:${St}`;cr(Xe,{createdAt:Date.now(),sessionId:St,nonce:lt,accountPatch:zr,paymentMethodId:nr,providerIntentId:Ft,paymentMethodType:I});try{d({id:nr,type:"card",threeDSecureActionResultTokenId:Ft},{accountPatch:zr,paymentMethodCategory:"wallet",sessionId:St,nonce:lt})}finally{cr(Xe)}},Or=!1;Sr=async()=>{if(!(Or||yr||wr)){Or=!0,Ae.current&&X("checking");try{let ae=await Uc(b,tr,yt.current);if(yr||wr)return;let zt=(0,c.isSetupIntentClientSecret)(tr),Ft=qs(ae,pr.providerObjectId,zt);if(Ft.kind==="confirmed"){Br(zt?{setupIntent:ae}:{paymentIntent:ae});return}if(Ft.kind==="terminal"){if(wr=!0,zs(St,lt,tr),at.current=null,we.current=null,!Ae.current)return;X("idle"),L(),de(I,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",T?.generation,!0);return}Ae.current&&!wr&&(X("blocked"),ce(!1))}catch{Ae.current&&!wr&&(X("blocked"),ce(!1))}finally{Or=!1}}},we.current=Sr;let P,xt;try{D=!0,ft.current+=1;let ae;try{ae=await((0,c.isSetupIntentClientSecret)(tr)?b.confirmSetup({elements:be,clientSecret:tr,redirect:"if_required"}):b.confirmPayment({elements:be,clientSecret:tr,redirect:"if_required"}))}finally{st()}if(!ae||typeof ae!="object")throw new Xa(Uu(ae));if(P=ae,!P.error&&!$r(P))throw new Xa("confirmation_result_unconfirmed");xt=jr(P.error?"returned_error":"resolved",P.error&&(0,_e.isProviderDecline)(P.error)?"provider_declined":void 0)}catch(ae){let zt=ae instanceof Xa?ae.reason:void 0,Ft=zt!==void 0,nr=jr(Ft?"returned_error":"rejected");if(gt?.error({...Ft?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:zt}:Ms(ae),...rr,operationOutcome:nr.operationOutcome,durationMs:nr.durationMs,statusClass:"unknown",terminalReason:nr.terminalReason}),!Ae.current||yr)return;await Sr?.();return}let te=P.error;if(te){if(!Ae.current||yr)return;if((0,_e.isProviderDecline)(te)){wr=!0,zs(St,lt,tr),at.current=null,we.current=null,X("idle"),It.current.get(ve)===T&&It.current.delete(ve);let ae=te.message??"Your payment was declined.";p?.(ae),w?.(kr(Mr,ae,{code:(0,_e.getProviderErrorCode)(te),declineCode:(0,_e.getProviderDeclineCode)(te)})),Vi({billingApiUrl:n,sessionId:St,nonce:lt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I,providerDeclineReason:(0,_e.getProviderErrorCode)(te)??"provider_declined",...pr.intentKind==="payment"&&pr.providerObjectId.startsWith("pi_")?{providerIntentId:pr.providerObjectId}:{}}})}else gt?.error({...Ms(te),...rr,operationOutcome:xt.operationOutcome,durationMs:xt.durationMs,statusClass:"unknown",terminalReason:xt.terminalReason}),await Sr?.();return}if(Br(P),!yr)throw new Error("Invalid provider returned for APM intent")}catch(St){if(St===Ui){let lt=gt?.now()??globalThis.performance?.now()??Date.now();gt?.error({errorCode:ju(Ur),stage:xr,requestCategory:Ur,paymentMethodCategory:"wallet",provider:"stripe",...bt?{walletType:bt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Jr,durationMs:Math.max(0,lt-vr),statusClass:"timeout",failureCategory:pn,attempt:un,terminalReason:"provider_error"}),gt?.flush?.().catch(()=>{})}L(),de(I,St,St===Ui?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",T?.generation,St===Ui)}finally{if(window.clearTimeout(br),Xt!==null&&(window.clearTimeout(Xt),yt.current.delete(Xt)),!Cr){let St=gt?.now()??globalThis.performance?.now()??Date.now();gt?.performance({stage:"callback",durationMs:Math.max(0,St-vr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Ar?{statusClass:"timeout"}:{}})}Ae.current&&ce(!1)}},[b,be,e,t,r,_,q,V,n,Y,a,d,p,w,g,de,st,xe,vt,Ke,it,x,ve]),ee=(0,o.useMemo)(()=>Fi(s),[s]),$=(0,o.useMemo)(()=>s.map(c.stripeExpressMethodToOptionKey),[s]),nt=(0,o.useMemo)(()=>(0,l.jsx)(lr.ExpressCheckoutElement,{onReady:u=>{ge(Wa(u,$))},onLoadError:u=>{ge("load_error"),Gs(x,"stripe","wallet","provider_error")},onClick:async u=>{let F=x?.now()??globalThis.performance?.now()??Date.now();kt.current=u.expressPaymentType,Pe.current=Vc(u.expressPaymentType);let D=!0,L=window.setTimeout(()=>{D=!1,u.reject(),Ot(u.expressPaymentType)},Au),T=g?await g(Pe.current,{abandoned:()=>!D}):{proceed:!0};if(window.clearTimeout(L),!D)return;if(!T.proceed){It.current.delete(ve),u.reject();return}let I=Vt(u.expressPaymentType);Lt.current=!1,Mt.current={generation:I,startedAt:F},It.current.set(ve,{generation:I,method:u.expressPaymentType,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),j(!1),x?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:I,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),m?.(Pe.current),u.resolve()},onConfirm:Q,onCancel:()=>{let u=It.current.get(ve);It.current.delete(ve);let F=Mt.current,D=x?.now()??globalThis.performance?.now()??Date.now();if(u&&F?.generation===u.generation&&(0,c.isWalletSheetRefusedForWindowSize)({method:u.method,elapsedMs:D-F.startedAt,handoffObserved:le.current===u.generation})){x?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:u.generation,walletType:"google_pay"}),at.current=null,de(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}x?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),Oe(u?.generation),at.current=null,j(!1),Ce.current=!0,Qe()},options:{...Bi,paymentMethods:ee,emailRequired:Rt,billingAddressRequired:Rt}},ve),[$,ee,Q,Oe,m,Rt,de,Ot,Qe,g,Vt,ve,x]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)($a,{state:oe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:k,children:(0,l.jsxs)("div",{ref:We,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Z&&(0,l.jsxs)("button",{ref:Ne,type:"button","data-testid":"flopay-wallet-retry-button",onClick:re,style:Ws,children:["Try ",$s(Pt)," again"]}),he!=="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:v,disabled:he==="checking",style:Ws,children:he==="checking"?"Checking payment status\u2026":"Check payment status"})]}),mt&&(0,l.jsx)(da,{identity:mt.identity,methodLabel:mt.methodLabel,onComplete:Ve,onCancel:()=>Ve(null)},mt.id),(0,l.jsxs)("div",{style:{display:mt||he!=="idle"?"none":void 0},children:[(0,l.jsx)(ap,{active:K}),nt]})]})}),Ie&&(0,l.jsx)(rn,{status:"processing"})]})}function Jc(e,t,r){let n=(0,c.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function Hs({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:s,billingApiUrl:d,onTokenizedBody:p,onErrorChange:m,onDecline:w,onCancel:h,runBeforeButtonClick:g,onButtonClick:_,isProcessing:V,submitButtonColor:W,submitButtonBorderRadius:k,submitButtonStyle:A,errorText:f}){let H=uo(),{emitInstrument:Y}=(0,o.useContext)(Rn),b=(0,lr.useStripe)(),be=(0,lr.useElements)(),[x,oe]=(0,o.useState)(!1),ge=(0,o.useRef)(!1),[Ie,ce]=(0,o.useState)(!1),[Rt,mt]=(0,o.useState)("loading"),[q,Ve]=(0,o.useState)(""),We=!(0,c.isValidEmail)(n?.trim()),Ne=!We||(0,c.isValidEmail)(q.trim()),ve=(0,o.useCallback)(async()=>{if(!b||!be||V||ge.current||!Ie)return;ge.current=!0,oe(!0);let G=g?await g("card"):{proceed:!0};if(!G.proceed){ge.current=!1,oe(!1);return}_?.("card");let K=G.sessionId??t,Ze=G.nonce??r,Se=(0,la.splitFullName)(a?.trim()),qe=(0,kn.compactBuyerIdentity)({email:G.accountPatch?.email?.trim()||n?.trim()||q.trim(),firstName:G.accountPatch?.firstName?.trim()||Se.firstName,lastName:G.accountPatch?.lastName?.trim()||Se.lastName}),Z=qe.email,j=(0,kn.compactBuyerIdentity)({...G.accountPatch,...qe});try{if(m?.(null),!(0,c.isValidEmail)(Z))throw new Error("A valid email address is required for payment.");await s?.(qe);let he=await be.submit();if(he.error){m?.(he.error.message??"Payment failed.");return}let X=[qe.firstName,qe.lastName].filter(Boolean).join(" "),Pt=await b.createPaymentMethod({elements:be,params:{billing_details:{email:Z,...X?{name:X}:{}}}});if(Pt.error||!Pt.paymentMethod){m?.(Pt.error?.message??"Failed to create payment method.");return}let pe=Pt.paymentMethod;if(!K||!Z)throw new Error("Missing sessionId or email for payment.");let we=pe.type||e,Ae=await ji(d,Y,K,Ze??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:we,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(Ae)){p({type:"card",gateway:"stripe",paymentMethodType:we},{accountPatch:j,paymentMethodCategory:"apm",sessionId:K,nonce:Ze,settledProcessResponse:Ae.response});return}if(Ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ce=Ae.clientSecret;cr(eo,{clientSecret:Ce,sessionId:K,nonce:Ze,accountPatch:j,paymentMethodId:pe.id,paymentMethodType:pe.type??e,gateway:"stripe"});let{error:kt,paymentIntent:Pe}=await b.confirmPayment({clientSecret:Ce,confirmParams:{return_url:window.location.href,payment_method:pe.id},redirect:"if_required"});if(kt){cr(eo);let yt=kt.message??"Payment failed.";m?.(yt),w?.(kr("card",yt,{code:kt.code})),await Vi({billingApiUrl:d,sessionId:K,nonce:Ze,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:kt.code??"provider_declined"}});return}let Be=Pe?.status;if(!Aa(Be)){cr(eo);let yt=Be==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(yt),w?.(kr("card",yt,{code:Be??"missing_payment_intent"}));return}cr(eo);let at=typeof Pe?.payment_method=="string"?Pe.payment_method:Pe?.payment_method?.id;p({id:at??pe.id,type:"card",threeDSecureActionResultTokenId:Pe?.id,gateway:"stripe",paymentMethodType:pe.type??e},{accountPatch:j,paymentMethodCategory:"apm",sessionId:K,nonce:Ze})}catch(he){m?.(he instanceof Error?he.message:"Payment failed. Please try again.")}finally{ge.current=!1,oe(!1)}},[b,be,V,Ie,g,_,t,r,n,a,q,s,d,Y,e,p,m,w]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[We&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:We&&(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:q,onChange:G=>Ve(G.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(lr.PaymentElement,{onReady:()=>mt("ready"),onLoadError:()=>{mt("load_error"),Gs(Er(H),"stripe","apm")},onChange:G=>{ce(!!G.complete)},options:{layout:Oi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,c.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,l.jsx)(Di,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ve()},disabled:!Ie||!Ne||x||V||Rt!=="ready",color:W,borderRadius:k,style:A,children:x?"Processing\u2026":`Pay with ${(0,c.getStripeMethodDisplayName)(e)}`}),f&&(0,l.jsx)(ya,{margin:"0.75rem 0 0",children:f})]})}function Hc({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,paymentElementMethods:d,stripeInstance:p,paymentElementBaseOptions:m,futureUseSession:w,onTokenizedBody:h,onErrorChange:g,onButtonClick:_,onDecline:V,runBeforeButtonClick:W,onLoadStateChange:k,isProcessing:A=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:Y,buttonAppearance:b,themeId:be,onExpandApm:x,expandedApmMethod:oe}){let{emitInstrument:ge}=(0,o.useContext)(Rn),[Ie,ce]=(0,o.useState)(null),[Rt,mt]=(0,o.useState)(null),q=(0,o.useRef)(!1),{request:Ve,collect:We,finish:Ne}=ca();(0,o.useEffect)(()=>{d.length>0&&p?k?.("ready"):p||k?.("loading")},[d.length,p,k]);let ve=(0,o.useCallback)(async Z=>{if(!p||q.current||A)return;q.current=!0,mt(Z);let j=W?await W("card"):{proceed:!0};if(!j.proceed){q.current=!1,mt(null);return}_?.("card");let he=j.sessionId??e,X=j.nonce??t,Pt=(0,la.splitFullName)([j.accountPatch?.firstName,j.accountPatch?.lastName].filter(Boolean).join(" ")||n),pe=(0,kn.compactBuyerIdentity)({email:j.accountPatch?.email?.trim()||r?.trim(),firstName:j.accountPatch?.firstName?.trim()||Pt.firstName,lastName:j.accountPatch?.lastName?.trim()||Pt.lastName});if(!(0,c.isValidEmail)(pe.email)){mt(null);let Ce=await We((0,c.getStripeMethodDisplayName)(Z),pe);if(!Ce){q.current=!1;return}pe=Ce,mt(Z)}let we=pe.email,Ae=(0,kn.compactBuyerIdentity)({...j.accountPatch,...pe});try{if(g?.(null),!he||!(0,c.isValidEmail)(we))throw new Error("Missing sessionId or email for payment.");await a?.(pe);let Ce=await ji(s,ge,he,X??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if((0,c.isSettledSessionIntent)(Ce)){h({type:"card",gateway:"stripe",paymentMethodType:Z},{accountPatch:Ae,paymentMethodCategory:"apm",sessionId:he,nonce:X,settledProcessResponse:Ce.response});return}if(Ce.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let kt=Ce.clientSecret;cr(eo,{clientSecret:kt,sessionId:he,nonce:X,accountPatch:Ae,paymentMethodType:Z,gateway:"stripe"});let{error:Pe,paymentIntent:Be}=await p.confirmPayment({clientSecret:kt,confirmParams:{return_url:window.location.href,payment_method_data:{type:Z,billing_details:{name:[pe.firstName,pe.lastName].filter(Boolean).join(" "),...we?{email:we}:{}}}},redirect:"if_required"});if(Pe){cr(eo);let Mt=Pe.message??"Payment failed.";g?.(Mt),V?.(kr("card",Mt,{code:Pe.code})),await Vi({billingApiUrl:s,sessionId:he,nonce:X,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,providerDeclineReason:Pe.code??"provider_declined"}});return}let at=Be?.status;if(!Aa(at)){cr(eo);let Mt=at==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(Mt),V?.(kr("card",Mt,{code:at??"missing_payment_intent"}));return}cr(eo);let yt=typeof Be?.payment_method=="string"?Be.payment_method:Be?.payment_method?.id;h({id:yt??Be?.id,type:"card",threeDSecureActionResultTokenId:Be?.id,gateway:"stripe",paymentMethodType:Z},{accountPatch:Ae,paymentMethodCategory:"apm",sessionId:he,nonce:X})}catch(Ce){g?.(Ce instanceof Error?Ce.message:"Payment failed. Please try again.")}finally{q.current=!1,mt(null)}},[p,A,W,_,e,t,r,We,s,ge,n,a,h,g,V]),[G,K]=(0,o.useState)(null),Ze=x?oe??null:G,Se=(0,o.useCallback)(Z=>{q.current||A||Ze&&Ze!==Z||((0,c.needsStripeMethodExplicitConfirm)(Z)?x?x(Z):K(Z):ve(Z))},[Ze,A,ve,x]),qe=(0,o.useMemo)(()=>G?Jc(m,G,w):null,[G,m,w]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ve?(0,l.jsx)(da,{identity:Ve.identity,methodLabel:Ve.methodLabel,onComplete:Ne,onCancel:()=>Ne(null)},Ve.id):d.map(Z=>{let j=oe===Z,he=Rt===Z,X=Rt!==null&&Rt!==Z||oe!=null&&oe!==Z;return(0,l.jsxs)(o.default.Fragment,{children:[(0,l.jsx)(xi,{method:Z,themeId:be,submitting:he,disabled:X,highlighted:j,hasNextStep:(0,c.needsStripeMethodExplicitConfirm)(Z),onClick:()=>Se(Z),backgroundColor:b?.backgroundColor,borderColor:b?.borderColor,textColor:b?.textColor,borderRadius:b?.borderRadius,fontFamily:b?.fontFamily}),!x&&G===Z&&qe&&p&&(0,l.jsx)(lr.Elements,{stripe:p,options:qe,children:(0,l.jsx)(Hs,{method:Z,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:s,onTokenizedBody:h,onErrorChange:g,onDecline:V,onCancel:()=>K(null),runBeforeButtonClick:W,onButtonClick:_,isProcessing:A,submitButtonColor:f,submitButtonBorderRadius:H,submitButtonStyle:Y})},Z)]},Z)})})}function ip({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:s,onComplete:d,onError:p,onDecline:m,onCancel:w,onTokenizedBody:h,firstName:g,lastName:_,chv:V,className:W,submitLabel:k,isProcessing:A,error:f,onErrorChange:H,showPayPal:Y=!0,showStripe:b=!0,walletPresentation:be="auto",enabledPaymentMethods:x,enabledPaymentMethodCountries:oe,showApplePay:ge=!0,showGooglePay:Ie=!0,layout:ce="default",paymentMethodLayout:Rt,moreOptionsLabel:mt,theme:q,buttonsTheme:Ve,buttonsStyles:We,appearance:Ne,cardButtonContent:ve,cardBackButtonContent:G,cardTitleContent:K,showSecurityFooter:Ze,onButtonClick:Se,onBeforeButtonClick:qe,onBuyerIdentityReady:Z,enableAVS:j,cardFieldOrder:he,showCardBrandIcons:X,cardFieldPlaceholders:Pt,cardAutoFocus:pe,onCardFieldsReady:we,onCardFieldsFailed:Ae,cardFieldsTimeoutMs:Ce,cardPreFormSlot:kt,avsLayout:Pe="row",country:Be,zip:at,addressLine1:yt,addressLine2:Mt,city:le,state:It,onCountryChange:Vt,onZipChange:xe,avsCheck:Oe,checkoutType:Ke,checkoutLayout:vt,totalAmount:it=0,currency:ft="usd",initialCardOpen:Lt=!1,directPaypal:Qe,isSubscription:st=!1,session:de,dataAttachmentPending:Ot=!1,dataAttachmentRequiresIdentity:et=!1,debug:re=!1}){let v=uo(),Q=vi(),ee=(0,o.useContext)(zn),{emitInstrument:$}=(0,o.useContext)(Rn),nt=(0,o.useRef)(null);nt.current||(nt.current=bi());let u=nt.current,[,F]=(0,o.useState)(0),D=(0,o.useRef)(null);D.current||(D.current=(0,Jn.detectPayPalEnvironment)());let L=D.current,T=(0,o.useMemo)(()=>({browser:L,capability:u,presentationMode:"popup"}),[L,u]),I=de??ee.session,Ct=(0,o.useMemo)(()=>({futureUse:I?.futureUse,futureUseUnsupported:I?.futureUseUnsupported}),[I?.futureUse,I?.futureUseUnsupported]),Mr=I?.gateways?.paypal?.providerObjectType??Qe?.providerObjectType,bt=Ot||ee.claimPending===!0,un=et||ee.claimRequiresIdentity===!0,gt=bt&&!un,vr=pc(),At=r||vr,Ar=Oc({rules:Rt,sessionId:e,nonce:t,billingApiUrl:At,waitForSession:gt}),Cr=Ar?.order??null,[Xt,Jr]=(0,o.useState)(!1),xr=(0,o.useMemo)(()=>Cr?(0,c.keyPaymentMethodOrder)(Cr):null,[Cr]),Ur=Cr!==null&&(0,c.isCardFormFirst)(Cr),[pn,Fr]=(0,o.useState)(!1),[Wt,br]=(0,o.useState)(null),[Tt,St]=(0,o.useState)(Be??""),[lt,yn]=(0,o.useState)(at??""),[ur,zr]=(0,o.useState)(yt??""),[An,mn]=(0,o.useState)(Mt??""),[qr,fn]=(0,o.useState)(le??""),[gn,pr]=(0,o.useState)(It??""),[tr,on]=(0,o.useState)(""),[Zr,rr]=(0,o.useState)({}),Qt=(0,o.useRef)(at??""),Sr=(0,o.useRef)(Be??""),jr=(0,o.useRef)(yt??""),yr=(0,o.useRef)(Mt??""),wr=(0,o.useRef)(le??""),$r=(0,o.useRef)(It??""),Br=(0,o.useRef)(""),Or=(0,o.useRef)({});(0,o.useEffect)(()=>{let i=(S,N,fe,J,Le)=>{if(Or.current[S])return;let qt=N?.trim();!qt||qt===fe.current||(fe.current=qt,J(qt),Le?.(qt))};i("country",Be,Sr,St,Vt),i("zip",at,Qt,yn,xe),i("addressLine1",yt,jr,zr),i("addressLine2",Mt,yr,mn),i("city",le,wr,fn),i("state",It,$r,pr)},[Be,at,yt,Mt,le,It,Vt,xe]);let P=(0,o.useMemo)(()=>(0,c.resolveAVSConfig)(j),[j]),xt=P!==null,te=(0,o.useMemo)(()=>(0,c.isAuthorizationOnlySession)(de),[de]),ae=(0,c.isMountableVaultBlock)(de?.vault),zt=!!de?.gateways?.pcivault,Ft=(0,Un.hasServerSideCardGateway)(de),Xe=!!(de?.gateways?.stripe?.enabledPaymentMethods??x)?.includes("card")||(0,Un.canRecoverHostedCardForm)(de),mr=ae||Xe||zt,Je=!!(b&&mr&&e),[no,go]=(0,o.useState)(()=>ce!=="buttons"||Lt?e??null:null),[jo,xn]=(0,o.useState)(0),hn=ce!=="buttons"||Lt||!!e&&no===e,an=de?.captureMethod,Qr=(0,o.useRef)(v);(0,o.useEffect)(()=>{Qr.current=v},[v]);let or=(0,o.useRef)(Ce);or.current=Ce;let Fn=(0,o.useRef)({onCardFieldsReady:we,onCardFieldsFailed:Ae,emitInstrument:$});Fn.current={onCardFieldsReady:we,onCardFieldsFailed:Ae,emitInstrument:$};let[Rr,$n]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!Je||!e||!hn){$n(null);return}let i=Qr.current?Qr.current.cardCapture({sessionId:e,captureMethod:an,cardFieldsTimeoutMs:or.current}):new Wn.PciVaultCardCapture({sessionId:e,captureMethod:an,billingApiUrl:At,telemetry:n,cardFieldsTimeoutMs:or.current}),S=i.onCardFields?.(N=>{let fe=Fn.current;fe.emitInstrument?.((0,c.cardFieldsInstrumentSource)(N)),N.type==="card_fields_ready"?(0,c.invokeMerchantCallback)(()=>fe.onCardFieldsReady?.(N)):(0,c.invokeMerchantCallback)(()=>fe.onCardFieldsFailed?.(N))});return $n({sessionId:e,captureMethod:an,billingApiUrl:At,telemetry:n,capture:i}),()=>{S?.(),i.unmount()}},[Je,e,hn,an,At,n]);let ht=Je&&e&&hn&&Rr?.sessionId===e&&Rr.captureMethod===an&&Rr.billingApiUrl===At&&Rr.telemetry===n?Rr.capture:null,Vr=(0,o.useMemo)(()=>{let i=Tt,S=P?(0,c.isAVSFieldVisible)(P.postal_code,i):!1;return Qu(i,lt,S)},[P,Tt,lt]),{avsInvalid:Bn,invalidAvsFields:oo}=(0,o.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Je||!P)return{avsInvalid:!1,invalidAvsFields:i};let S=Tt,N=(Le,qt)=>(0,c.isAVSFieldVisible)(Le,S)&&!qt.trim(),fe={line1:N(P.address_line_1,ur),city:N(P.city,qr),state:N(P.state,gn),zip:Vr.empty||Vr.malformed};return{avsInvalid:fe.line1||fe.city||fe.state||fe.zip,invalidAvsFields:fe}},[Je,P,Tt,ur,qr,gn,Vr]),[sn,Pn]=(0,o.useState)(!1),[ho,Po]=(0,o.useState)(!1),[vn,ao]=(0,o.useState)(!1),[Vo,va]=(0,o.useState)({line1:!1,city:!1,state:!1}),Cn=(0,o.useRef)(!1),Hn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),vo=(0,o.useRef)(!1),Nt=(0,o.useCallback)(i=>{Hn.current[i]=!0,vo.current=!0},[]),Kn=(0,o.useCallback)(i=>!Cn.current&&Hn.current[i],[]),bn=(0,o.useCallback)(i=>{Kn(i)&&va(S=>S[i]?S:{...S,[i]:!0})},[Kn]),[On,Hr]=(0,o.useState)(()=>(0,c.resolveVaultMountOptions)(de?.vault,{billingApiUrl:At,sessionId:e,nonce:t})),[ct,ar]=(0,o.useState)(Lt&&mr?"card":"buttons"),[Kt,B]=(0,o.useState)(null),U=ct==="expanding"||ct==="card",ne=de?.gateways?.stripe&&!Ft?"stripe":void 0,me=(0,o.useCallback)(()=>{$?.({class:"card_surface",provider:ne})},[ne,$]),Ut=(0,o.useCallback)(()=>{Jr(!0),$?.({class:"more_options"})},[$]),Jt=(0,o.useRef)(null),Fe=(0,o.useCallback)(i=>{Jt.current&&clearTimeout(Jt.current),Jt.current=setTimeout(()=>{Jt.current=null,i()},Ja)},[]);(0,o.useEffect)(()=>()=>{Jt.current&&clearTimeout(Jt.current)},[]);let dt=(0,o.useRef)(!1),[z,Ge]=(0,o.useState)(0),Re=(0,o.useRef)(null),C=(0,o.useCallback)(()=>{me(),go(e??null),dt.current&&(dt.current=!1,Ge(i=>i+1)),xn(i=>i+1),ar("expanding"),Fe(()=>ar("card"))},[Fe,me,e]),y=(0,o.useCallback)(()=>{ar("collapsing"),Fe(()=>ar("buttons"))},[Fe]),M=(0,o.useCallback)(i=>{B(i),ar("apm-expanding"),Fe(()=>ar("apm-form"))},[Fe]),ke=(0,o.useCallback)(()=>{ar("apm-collapsing"),Fe(()=>{ar("buttons"),B(null)})},[Fe]);(0,o.useEffect)(()=>{ce==="buttons"&&Lt&&mr&&(go(e??null),ar("card"))},[ce,Lt,mr,e]);let[Te,ie]=(0,o.useState)(null),Me=(0,o.useRef)(null),[Ee,$t]=(0,o.useState)(0);(0,o.useEffect)(()=>{Ee!==0&&Me.current?.focus()},[Ee]);let Ht=(0,o.useRef)(!1),ut=(0,o.useRef)(null),ue=(0,o.useRef)("idle"),[ye,$e]=(0,o.useState)(!1),tt=(0,o.useRef)(ye);tt.current=ye;let[De,en]=(0,o.useState)(()=>Qe?.existingOrderId?{orderId:Qe.existingOrderId,attempts:1}:null),Yt=(0,o.useRef)(De);(0,o.useEffect)(()=>{Yt.current=De},[De]);let Wo=(0,o.useRef)(null),bd=(0,o.useMemo)(()=>{if(Z||ee.claimBuyerIdentity||de?.buyerIdentified!==!1||!e||!t)return;let i=`${At}|${e}|${t}`;Wo.current?.key!==i&&(Wo.current={key:i,claim:ia(new Wn.PaymentAPI(At,{telemetry:!1}),e,t,{...s?{userId:s}:{},...g?{firstName:g}:{},..._?{lastName:_}:{}})});let S=Wo.current.claim;return async N=>{await S(N)}},[Z,ee.claimBuyerIdentity,de?.buyerIdentified,e,t,At,s,g,_]),Sn=Z??ee.claimBuyerIdentity??bd,Dn=f??Wt,$o=(0,o.useMemo)(()=>(0,c.resolveTheme)(q),[q]),rt=(0,o.useMemo)(()=>{let i=$o?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(Ve);return We?{...i,...We,cardButton:{...i.cardButton,...We.cardButton},cardFormContainer:{...i.cardFormContainer,...We.cardFormContainer},backButton:{...i.backButton,...We.backButton},backButtonIcon:{...i.backButtonIcon,...We.backButtonIcon},submitButton:{...i.submitButton,...We.submitButton},title:{...i.title,...We.title}}:i},[$o,Ve,We]),Ho=Ne??$o?.appearance,Sd=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:Ho,buttonsStyles:rt,layout:ce}),[Ho,rt,ce]),wd=ee.inlineSessionPatchProcessing??!1,ir=(A??pn)||wd,Co=At.replace(/\/+$/,""),Bt=(0,o.useMemo)(()=>Ts({userId:s,email:a,firstName:g,lastName:_,country:Be,zip:at},Zr),[s,a,g,_,Be,at,Zr]),Ko=[Bt.firstName,Bt.lastName].filter(i=>!!i?.trim()).join(" "),ll=!(0,c.isValidEmail)(Bt.email?.trim()),Qi=(0,o.useRef)(null);Je&&Qi.current===null&&(Qi.current=ll);let bo=Je&&(Qi.current??ll),es=(0,o.useMemo)(()=>ep(tr,bo),[tr,bo]),Go=es.empty||es.malformed,ln=(0,o.useMemo)(()=>v?v.getRawProvider():null,[v]),cl=(0,o.useMemo)(()=>Q?Q.getRawProvider():null,[Q]),Ca=it||100,Yo=ft.toLowerCase(),ts=(0,o.useMemo)(()=>Ho?(0,Wn.toStripeAppearance)(Ho):null,[Ho]),Xo=ts,dl=(0,o.useMemo)(()=>{let i=ts??{},S=i.rules??{};return{...i,rules:{...S,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...S[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...S[".AccordionItemContents"]??{}}}}},[ts]),ul=(0,o.useMemo)(()=>({...cc(it,I?.captureMethod,Ct),currency:Yo,...Xo?{appearance:Xo}:null}),[it,Yo,I?.captureMethod,Ct,Xo]),rs=(0,c.resolveSetupFutureUsage)(Ct,"paypal","paypal"),pl=(0,o.useMemo)(()=>({mode:"payment",amount:Ca,currency:Yo,captureMethod:"manual",...rs?{setupFutureUsage:rs}:null,...Xo?{appearance:Xo}:null}),[Ca,Yo,rs,Xo]),Ue=(0,o.useCallback)(i=>{br(i),H?.(i)},[H]),yl=(0,o.useRef)(0);(0,o.useEffect)(()=>{z!==yl.current&&(yl.current=z,Ue(null))},[z,Ue]);let ns=(0,o.useRef)(""),[ml,Rd]=(0,o.useState)(!1),os=(0,o.useCallback)(()=>{Rd(!0)},[]);(0,o.useEffect)(()=>{if(!Je||!bo||!Sn||!ml||Go||ns.current)return;let i=(0,kn.compactBuyerIdentity)({email:(0,c.isValidEmail)(Bt.email?.trim())?Bt.email?.trim():Br.current.trim(),firstName:Bt.firstName?.trim(),lastName:Bt.lastName?.trim()});ns.current=JSON.stringify(i),rr(S=>({...S,...i})),Promise.resolve(Sn(i)).catch(S=>{ns.current="",Ue(S instanceof Error?S.message:"Failed to attach buyer details.")})},[Je,bo,Sn,ml,Go,Bt.email,Bt.firstName,Bt.lastName,Ue]),(0,o.useEffect)(()=>{if(!Je||!ht)return;let i=pe!==!1&&P==null&&!bo;ht.setCardFieldOrder?.(he??null,i)},[Je,ht,he,pe,P,bo]),(0,o.useEffect)(()=>{!Je||!ht||ht.setCardBrandIcons?.(X===!0)},[Je,ht,X]);let as=np(Pt),is=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(!(!Je||!ht)){if(as===null){if(is.current!==ht)return;is.current=null,ht.setCardFieldPlaceholders?.(void 0);return}is.current=ht,ht.setCardFieldPlaceholders?.(JSON.parse(as))}},[Je,ht,as]),(0,o.useEffect)(()=>{(ct==="expanding"||ct==="collapsing"||ct==="apm-expanding"||ct==="apm-collapsing")&&Ue(null)},[ct,Ue]);let Gn=(0,o.useCallback)((i,S,N)=>{m?.(kr(i,S,N))},[m]),fl=(0,o.useRef)(ct);fl.current=ct;let[gl]=(0,o.useState)(wi),hl=(0,o.useCallback)(()=>{let i=fl.current;if(ce==="buttons"&&(i==="card"||i==="expanding"))return!0;let S=ue.current;return S==="validation-window"||S==="processing"||tt.current},[ce]),Pl=(0,o.useCallback)((i,S,N)=>{gl.take(e)&&Er(v)?.log(Do({...T,presentationMode:N?.presentationMode??"popup"},{name:Si,stage:"recovery",reason:"other_method_active",provider:N?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:N?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet")}))},[T,v,gl,e]),ri=(0,o.useCallback)((i,S,N)=>{N?.telemetryReported||Er(v)?.error(Do({...T,presentationMode:N?.presentationMode??"popup"},{errorCode:S?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:N?.provider??(i==="paypal"?"paypal":"stripe"),paymentMethodCategory:N?.paymentMethodCategory??(i==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:N?.terminalReason??(S?"popup_blocked":"provider_error")}))},[T,v]),Jo=(0,o.useCallback)((i,S,N)=>{let fe=N?.popupBlocked??(0,_e.isPopupBlockedError)(S);if(hl()){ri(i,fe,N),Pl(i,S,N);return}if(S instanceof c.FloPayError&&S.code==="checkout_processing_timeout"){ri(i,!1,N),ie(null),ce==="buttons"&&(ar("buttons"),B(null)),Ue(S.message),p?.(S);return}fe&&u.markBlocked()&&F(Et=>Et+1);let J=$s(i),Le=N?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(J):(0,_e.buildExternalMethodRecoveryMessage)(J,fe,L.inAppBrowser),qt=(0,_e.getProviderErrorCode)(S),jt=(qt?.toLowerCase()==="error"?void 0:qt)??(0,_e.sanitizeExternalFailureCode)(N?.code)??"external_payment_method_failed",ot=new c.FloPayError(Le,"api_error",{code:"external_payment_method_failed",param:i,details:{providerCode:jt,popupBlocked:fe,inAppBrowser:L.inAppBrowser,appFamily:L.appFamily,popupCapability:u.current(),presentationMode:N?.presentationMode??"popup"}});ri(i,fe,N),ie(null),ce==="buttons"&&(ar("buttons"),B(null)),Ue(Le),p?.(ot),console.error("[FloPay] External payment method failed:",{method:i,code:jt,popupBlocked:fe})},[L,hl,ce,p,u,Pl,ri,Ue]);(0,o.useEffect)(()=>{if(!Je||!e){Hr(null);return}let i={billingApiUrl:Co,sessionId:e,nonce:t},S=(0,c.resolveVaultMountOptions)(de?.vault,i);if(S){Hr(S);return}if(!hn){Hr(null);return}let N=`${Co}\0${e}\0${t??""}`,fe=Re.current;if(fe&&fe.key===N){Hr(fe.mount);return}Hr(null);let J=!0;return new Wn.PaymentAPI(Co).getVaultCapture(e,t).then(Le=>{if(!J)return;let qt=(0,c.resolveVaultMountOptions)(Le,i);qt?.verificationRequired&&!Le.html&&(Re.current={key:N,mount:qt}),qt?Hr(qt):Ue("Failed to load the secure card form.")}).catch(Le=>{J&&Ue(Le instanceof Error?Le.message:"Failed to load the secure card form.")}),()=>{J=!1}},[Je,hn,jo,e,de?.vault,Co,t,Ue]);let Ln=(0,o.useRef)({onComplete:d,onError:p,updateError:Ue,emitDecline:Gn,resolvedAccount:Bt,avsConfig:P,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:Co,captureMethod:de?.captureMethod,paymentId:de?.paymentId,authorizationExpiresAt:de?.authorizationExpiresAt,serverSideCardGateway:Ft});Ln.current={onComplete:d,onError:p,updateError:Ue,emitDecline:Gn,resolvedAccount:Bt,avsConfig:P,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:Co,captureMethod:de?.captureMethod,paymentId:de?.paymentId,authorizationExpiresAt:de?.authorizationExpiresAt,serverSideCardGateway:Ft};let ss=(0,o.useRef)(!1),vl=(0,o.useCallback)(()=>{let i=Ln.current,S=i.resolvedAccount.email?.trim(),N=(0,c.isValidEmail)(S)?S:Br.current.trim();if(!(0,c.isValidEmail)(N))return null;let fe=i.resolvedAccount.firstName?.trim(),J=i.resolvedAccount.lastName?.trim(),Le=Sr.current.trim()||i.resolvedAccount.country?.trim()||"",qt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.state,Le):!1,jt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_1,Le):!1,ot=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.postal_code,Le):!1,Et=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.city,Le):!1,Dt=i.avsConfig?(0,c.isAVSFieldVisible)(i.avsConfig.address_line_2,Le):!1,fr=jt&&!qt&&ot?(0,c.getStateFromPostalCode)(Le,(Qt.current??"").trim()):null,cn=qt?$r.current:fr;return{accountData:{userId:i.resolvedAccount.userId??"",email:N,...fe?{firstName:fe}:{},...J?{lastName:J}:{},...ot&&Qt.current?{zip:Qt.current}:{},...Et&&wr.current?{city:wr.current}:{},...cn?{state:cn}:{},...jt&&jr.current?{addressLine1:jr.current}:{},...Dt&&yr.current?{addressLine2:yr.current}:{},...Le?{country:Le}:{}},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,c.isAVSFieldVisible)(i.avsConfig.country,Le),postal_code:ot,address_line_1:jt,address_line_2:Dt,city:Et,state:qt}}:{}}},[]),Cl=(0,o.useRef)(bt);Cl.current=bt,(0,o.useEffect)(()=>{bt||Dn!==zc||Ln.current.updateError(null)},[bt,Dn]),(0,o.useEffect)(()=>{!Je||!ht||ht.setSubmitGate?.(Bn||bt||Go||ye)},[Je,ht,Bn,bt,Go,ye]),(0,o.useEffect)(()=>{if(!Je||!ht)return;ss.current=!1;let i=null,S=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,ue.current="idle",ie(null)},400)},N=ht.on("submitting",()=>{Pn(!0),ut.current&&clearTimeout(ut.current),ue.current="validation-window",ut.current=setTimeout(()=>{ut.current=null,ue.current==="validation-window"&&(ue.current="processing")},Vu),ie("processing");let ot=Ln.current;if(!ot.sessionId||!ot.nonce)return;let Et=vl();if(!Et){ot.updateError("Enter a valid email address."),ue.current="idle",ie(null);return}new Wn.PaymentAPI(ot.baseUrl).patchAccountSnapshot(ot.sessionId,ot.nonce,Et,{telemetryMode:"best_effort"}).catch(Dt=>{if(!$u(Dt))return;let fr=Dt instanceof Error?Dt.message:"Please check your billing address and try again.";ot.updateError(fr),ue.current="idle",ie(null),ot.onError?.(Dt instanceof c.FloPayError?Dt:new c.FloPayError(fr,"api_error"))})}),fe=ht.on("complete",ot=>{(0,jn.markSessionRecentlyCompleted)(ot.sessionId??Ln.current.sessionId),ue.current="terminal",$e(!1),ie("success"),setTimeout(()=>{if(ss.current)return;ss.current=!0;let Et=Ln.current,Dt=(0,c.isAuthorizationOnlySession)(Et)||ot.outcome==="authorized",fr=Et.serverSideCardGateway?{}:{paymentIntentId:ot.intentId};Ln.current.onComplete?.(Dt?{status:"authorized",...fr,paymentId:ot.paymentId??Et.paymentId,sessionId:ot.sessionId??Et.sessionId,authorizationExpiresAt:ot.authorizationExpiresAt??Et.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...fr,checkoutMethod:"card"})},600)}),J=ht.on("decline",ot=>{let Et=Ln.current,Dt=ot.message??"Your payment was declined. Please try another card or contact your bank.";ue.current="terminal",$e(!1),Et.updateError(Dt),ie("error");let fr=ot.failureOutcome??(0,c.normalizeCheckoutFailureOutcome)(ot.declineReason)??"authorization_declined";Et.emitDecline("card",Dt,{code:fr,declineCode:fr}),S()}),Le=ht.on("error",ot=>{let Et=Ln.current,Dt=(0,c.buyerEmailRequiredPrompt)(ot.vaultOutcome);if(Dt!==null){i&&(clearTimeout(i),i=null),ue.current="idle",$e(!1),Et.updateError(Dt),ie(null),$t(cn=>cn+1),Et.onError?.(new c.FloPayError(Dt,"api_error",{code:c.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED}));return}let fr=ot.message??"There was a problem processing your payment. Please try again.";ue.current="terminal",$e(!1),Et.updateError(fr),ie("error"),Et.onError?.(new c.FloPayError(fr,"api_error",{code:ot.failureOutcome??"capture_failed"})),S()}),qt=ht.on("challenge_dismissed",()=>{ut.current&&(clearTimeout(ut.current),ut.current=null),ue.current="processing",$e(!0),ie(null)}),jt=ht.on("blocked",()=>{if(tt.current){Ln.current.updateError(Wu);return}if(!Cl.current){Pn(!0);return}os(),Ln.current.updateError(zc)});return()=>{i&&(clearTimeout(i),i=null),ut.current&&(clearTimeout(ut.current),ut.current=null),ue.current="idle",$e(!1),ie(null),N(),fe(),J(),Le(),qt(),jt()}},[Je,ht,os,vl]);let Yn=!!Qe?.clientId,ba=Array.isArray(x),ni=ba&&x.length>0,bl=ba&&x.includes("paypal"),oi=(0,o.useRef)(null);oi.current===null&&(oi.current=(0,c.hasMatchingStripePayPalReturn)());let Zo=oi.current?"redirect":(0,Zn.resolveStripePayPalPresentation)(L,be,u.current()),{expressMethods:ai,paymentElementMethods:ls}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(x,{excludePaypal:Yn}),[x,Yn]),Sl=Yn||!!Q||bl&&Zo==="redirect",kd=(0,o.useMemo)(()=>Sl?ai.filter(i=>i!=="paypal"):ai,[ai,Sl]),Ed=(0,o.useMemo)(()=>{let i=[];return ge&&i.push("apple_pay"),Ie&&i.push("google_pay"),i},[ge,Ie]),Qo=ba?kd:Ed,_d=b&&Qo.length>0,wl=xt?Tt:Be,ii=(0,o.useMemo)(()=>(0,c.filterStripeMethodsByCountryGate)(ls,wl,oe),[ls,wl,oe]),cs=(0,o.useMemo)(()=>({mode:"payment",amount:Ca,currency:Yo,paymentMethodCreation:"manual",appearance:dl}),[Ca,Yo,dl]),[ds,Rl]=(0,o.useState)("loading"),[us,kl]=(0,o.useState)("loading"),[ps,El]=(0,o.useState)("loading"),[Id,ys]=(0,o.useState)(!1),[_l,ms]=(0,o.useState)("loading"),[fs,Td]=(0,o.useState)();(0,o.useEffect)(()=>{Td((0,Jn.detectPayPalEnvironment)())},[]);let si=fs?.inAppBrowser,li=fs?(0,Zn.resolvePayPalPresentationMode)(fs,Qe?.approvalPresentation,Mr??(st?"subscription":"order")):"popup",Il=Y&&(Yn||(ba?bl:si===!1)),Md=L.inAppBrowser&&u.current()==="blocked",Tl=b&&_d&&!Md,Io=(!gt||!!ee.waitForDataAttachment)&&Il&&Yn,gs=_l==="retrying"||_l==="exhausted",Sa=null;b&&(Q?Sa=cl:Zo==="redirect"&&(Sa=ln));let Ml=(0,o.useMemo)(()=>({...T,presentationMode:Zo}),[T,Zo]),To=!gt&&Il&&!!Sa&&(!Yn||gs),So=!gt&&Tl&&!!ln,Mo=!gt&&b&&ni&&ii.length>0&&!!ln,Ad=Io&&!gs?Id:To&&Ha(ds),xd=So&&Ha(us),Fd=Mo&&ps!=="load_error",Al=[Io||To,So,Mo,Je].filter(Boolean).length,Bd={card:Je,paypal:Io&&!gs||To&&Ha(ds),wallets:So&&Ha(us),apms:Mo&&ps!=="load_error"},xl=i=>Bd[i],Fl=i=>i==="loading"||i==="ready",Bl=Io||To&&Fl(ds)||So&&Fl(us)||Mo&&ps!=="load_error",ci=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!ci.current){if(!b&&!Y){ci.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(!b&&Y&&!Yn){ci.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(si!==void 0&&!gt&&!mr&&!Bl){ci.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)}}},[b,Y,Yn,si,gt,mr,Bl,p,Ue]);let Ol=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(Ol.current||!ni)return;let i=[];ge!==!0&&i.push("showApplePay"),Ie!==!0&&i.push("showGooglePay"),i.length!==0&&(Ol.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.`))},[ni,ge,Ie]);let Dl=(0,o.useCallback)((i,S,N)=>ee.applyInlineSessionPatch?ee.applyInlineSessionPatch(i).then(fe=>({error:null,sessionId:fe.sessionId||e,nonce:fe.session?.clientSecret||t})).catch(fe=>{let J=(0,c.normalizeBeforeButtonClickError)(S,fe);return N?.abandoned?.()||(Ue(J.message),p?.(J)),{error:J,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ee.applyInlineSessionPatch,t,p,e,Ue]),Nn=(0,o.useCallback)(async(i,S)=>{if(i!=="card"&&gt&&await ee.waitForDataAttachment?.(),!qe)return{proceed:!0};try{let N=await qe({method:i,sessionId:e||void 0,createSession:ee.inlineSessionDraft});if(N===!1)return{proceed:!1};if(N&&typeof N=="object"){N.account&&rr(J=>({...J??{},...N.account}));let fe=await Dl(N,i,S);return fe.error?{proceed:!1,accountPatch:N.account}:{proceed:!0,accountPatch:N.account,sessionId:fe.sessionId,nonce:fe.nonce}}return{proceed:!0}}catch(N){if(!S?.abandoned?.()){let fe=(0,c.normalizeBeforeButtonClickError)(i,N);Ue(fe.message),p?.(fe)}return{proceed:!1}}},[Dl,ee.inlineSessionDraft,ee.waitForDataAttachment,gt,qe,p,e,Ue]),Ll=(0,o.useCallback)(async(i,S)=>{if(Ht.current)return;Ht.current=!0,Fr(!0),ie("processing"),Ue(null);let N=S?.sessionId??e,fe=S?.nonce??t,J=Ts(Bt,S?.accountPatch),Le=S?.completionPaymentMethodId??xa(i),qt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,jt=Yu(i),ot=S?.presentationMode?Ai(Er(v),{...T,presentationMode:S.presentationMode}):void 0,Et=()=>{$?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:jt}),ot?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Vn,requestCategory:"process_payment"})};try{let Dt=new Wn.PaymentAPI(Co),cn=S?.settledProcessResponse??await Dt.processPayment(J.userId??"",{sessionId:N,nonce:fe,paymentMethodCategory:S?.paymentMethodCategory??Ju(i),tokenizedData:qt,accountData:{...S?.accountPatch,userId:J.userId??"",email:J.email??"",firstName:J.firstName||void 0,lastName:J.lastName||void 0,...(0,c.buildProcessPaymentAvsAccount)({avsConfig:P,country:Sr.current,zip:Qt.current,city:wr.current,state:$r.current,addressLine1:jr.current,addressLine2:yr.current})},...(0,c.buildCheckoutProcessMetadata)({chv:V,avsCheck:Oe,checkoutType:Ke,checkoutLayout:vt,avsConfig:P,country:Sr.current})}),mi=async Dr=>{let Ao=(0,c.isAuthorizationOnlySession)(de)||Dr?.status==="authorized";(0,jn.markSessionRecentlyCompleted)(N),ot?.terminal({outcome:"payment_succeeded",...Vn}),ie("success"),en(null),await new Promise(Ta=>setTimeout(Ta,600));let Xn;typeof Dr?.paymentId=="string"?Xn=Dr.paymentId:de?.paymentId&&(Xn=de.paymentId);let xo;typeof Dr?.authorizationExpiresAt=="string"?xo=Dr.authorizationExpiresAt:de?.authorizationExpiresAt&&(xo=de.authorizationExpiresAt),d?.(Ao?{status:"authorized",...Xn===void 0?{}:{paymentId:Xn},sessionId:typeof Dr?.sessionId=="string"?Dr.sessionId:N,...xo===void 0?{}:{authorizationExpiresAt:xo},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Le,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Le,checkoutMethod:i.isPaypal?"paypal":"card"})};if(cn.ok){await mi(cn.status===204?null:await cn.json().catch(()=>null));return}let gr=await cn.json().catch(()=>null);if(gr?.type==="paypal_redirect_required"){let Dr=gr.threeDSecureToken,Ao=gr.paymentMethodId||i.id||"";if(!v||!Dr){ie("error"),Ue("PayPal authorization required but no token provided.");return}try{let Xn=Q?.getRawProvider();if(!Xn){Ue("PayPal is not available.");return}let xo={return_url:window.location.href};Ao&&(xo.payment_method=Ao);let{error:Ta}=await Xn.confirmPayment({clientSecret:Dr,confirmParams:xo,redirect:"if_required"});if(Ta){ie("error");let Jl=Ta.message??"PayPal payment failed.";Ue(Jl),Gn("paypal",Jl,{code:Ta.code})}}catch(Xn){ie("error"),Ue(Xn instanceof Error?Xn.message:"PayPal authorization failed.")}return}if(gr?.type==="paypal_direct_required"){let Dr=gr.orderId;if(!Dr){ie("error"),Ue("PayPal retry required but no order id provided.");return}let Ao=Yt.current?.attempts??0;if(Ao>=2){ie("error"),Ue("PayPal payment could not be completed after multiple attempts."),Gn("paypal","paypal_direct_required retry limit exceeded");return}ys(!1),ms("loading"),en({orderId:Dr,attempts:Ao+1}),ie(null);return}if(cn.headers.get(Du)===Lu){let Dr=await Nu(Dt,N,fe);if(Dr!==void 0){await mi(Dr);return}}(0,c.classifyPaymentRejection)(cn.status,gr)?ot?.terminal({outcome:"payment_declined",...Vn,terminalReason:"provider_declined"}):Et(),ie("error");let Xl=gr?.message??"Payment failed. Please try again.";Ue(Xl),Gn(i.isPaypal?"paypal":"card",Xl,{code:gr?.code??gr?.gatewayErrorCode,declineCode:gr?.declineCode??gr?.gatewayDeclineReason}),await new Promise(Dr=>setTimeout(Dr,400))}catch(Dt){Yc(Dt)||Et(),ie("error"),Ue(Dt instanceof Error?Dt.message:"An unexpected error occurred"),await new Promise(fr=>setTimeout(fr,400))}finally{Fr(!1),ie(null),Ht.current=!1}},[Co,e,t,Bt,P,Oe,Ke,vt,V,v,Q,de,d,Ue,Gn,$,T]),tn=(0,o.useCallback)((i,S)=>{h&&!S?.settledProcessResponse?h(i):Ll(i,S)},[h,Ll]),wa=`${Kc}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(wa);if(!i)return;let S;try{S=JSON.parse(i)}catch{cr(wa);return}if(!S||typeof S.createdAt!="number"||Date.now()-S.createdAt<0||Date.now()-S.createdAt>Gc||typeof S.paymentMethodId!="string"||typeof S.providerIntentId!="string"||typeof S.paymentMethodType!="string"||S.sessionId!==e||!t||S.nonce!==t||!Qo.includes(S.paymentMethodType)){cr(wa);return}cr(wa),tn({id:S.paymentMethodId,type:"card",threeDSecureActionResultTokenId:S.providerIntentId,gateway:"stripe",paymentMethodType:S.paymentMethodType},{...S.accountPatch?{accountPatch:S.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[tn,t,e,wa,Qo]);let Nl=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Nl.current)return;let[i,S,N]=(0,c.readStripeRedirectParams)();if(!i||!S||oi.current||!v)return;let fe=v.getRawProvider();if(!fe)return;let J=Et=>{let Dt=localStorage.getItem(Et);if(!Dt)return null;try{return JSON.parse(Dt)}catch{return cr(Et),null}},Le=J(eo)??J(Lc),qt;if(Le?.clientSecret){if(Le.clientSecret!==S)return;qt={...Le.accountPatch?{accountPatch:Le.accountPatch}:{},...Le.sessionId?{sessionId:Le.sessionId}:{},...Le.nonce?{nonce:Le.nonce}:{}}}else if(Le?.sessionId&&Le.sessionId!==e)return;Nl.current=!0,cr(eo),cr(Lc),window.history.replaceState({},"",(0,c.stripeRedirectReturnUrl)());let jt=Le?.paymentMethodType??Le?.tokenType??"card",ot="card";(async()=>{if(N==="failed"){let gr="Payment was declined. Please try again.";Ue(gr),Gn(ot,gr);return}let{paymentIntent:Et,error:Dt}=await fe.retrievePaymentIntent(S);if(Dt){let gr=Dt.message??"Failed to retrieve payment status.";Ue(gr),Gn(ot,gr,{code:Dt.code});return}let fr=Et?.status,cn=Aa(fr);if(!Et||!cn){let gr=fr==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ue(gr),Gn(ot,gr,{code:fr??"missing_payment_intent"});return}let mi=typeof Et.payment_method=="string"?Et.payment_method:Et.payment_method?.id;tn({id:mi??Le?.paymentMethodId??Le?.tokenId??Et.id,type:"card",threeDSecureActionResultTokenId:Et.id,gateway:Le?.gateway??"stripe",paymentMethodType:jt},qt)})()},[e,tn,v,Ue,Gn]);let hs=(0,o.useCallback)(i=>{i.preventDefault()},[]);if(!(Je||v!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ra=ce==="buttons",Kr=Ho?.variables,Od=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ps=Kr?.colorBackground,Dd=Ps&&!Od.has(Ps)?Ps:void 0,ka=rt.cardInputBorder??(Ra?"#e5e7eb":"#A4A4FF"),Ul=Kr?.colorDanger??"#dc2626",er=i=>oo[i]&&(Vo[i]||sn),di=Go&&(vn||sn),wn=i=>i?Ul:ka,ui=(Vr.malformed||Vr.empty)&&(ho||sn),Ld=wn(ui),vs=rt.cardFormContainer?.backgroundColor??Dd??(Ra?"white":"#EDEDFF"),ea=rt.cardInputBackground??Kr?.colorBackground??"white",Cs=na(G),zl=na(K),ta=rt.nameInput,ql=rt.cardInputFontSize??tp(ta?.fontSize)??Kr?.fontSizeBase??"16px",jl=typeof ta?.fontFamily=="string"?ta.fontFamily:Kr?.fontFamily??"Poppins, sans-serif",Vl=(0,c.toCssWeight)(ta?.fontWeight)??400,Nd=rt.cardInputColor??(typeof ta?.color=="string"?ta.color:void 0)??Kr?.colorText??"#262833",Ud=rt.cardInputPlaceholderColor??"#9ca3af",sr=Kr?.borderRadius??"8px",io=Kr?.borderRadius??rt.cardButton?.borderRadius??sr,wo=Kr?.colorPrimary??"#4A49FF",zd=Kr?.colorPrimaryHover??(0,c.darkenHex)(wo,.12),bs=Kr?.colorText??"#262833",Ss={fontSize:ql,fontFamily:jl,fontWeight:Vl,color:Nd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ea={marginTop:"0.375rem",...Ss,fontSize:"0.75rem",lineHeight:1.4,color:Ul},qd={"--flopay-input-placeholder-color":Ud,"--flopay-input-font-size":ql,"--flopay-input-font-family":jl,"--flopay-input-font-weight":String(Vl)},_a=rt.cardFormContainer??{},ws=_a.padding??(Ra?"0":"1rem"),Rs=_a.borderRadius??sr,jd=ht&&On?(0,l.jsx)(_o,{capture:ht,html:On.html,messageToken:On.messageToken,expectedOrigin:On.expectedOrigin,verificationRequired:On.verificationRequired,theme:Sd,submitLabel:k,onReady:()=>{if(!bo&&!P||typeof document>"u"||pe===!1)return;let i=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){Cn.current=!0;try{N.focus()}finally{Cn.current=!1}}};vo.current||i()},onError:i=>{i&&On.verificationRequired&&ue.current==="idle"&&(dt.current=!0),Ue(i)},onValidation:i=>{let S=ue.current;(S==="idle"||S==="validation-window")&&(Ue(i),i&&ue.current==="validation-window"&&(ut.current&&(clearTimeout(ut.current),ut.current=null),ue.current="idle",ie(null)))}},z):(0,l.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ks=(0,l.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&me()},style:{backgroundColor:vs,borderRadius:Rs,..._a,padding:ws,...qd,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 @@ ${U.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),wa&&L&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ve?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:m,style:{display:"inline-flex",alignItems:"center",gap:Ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:at.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...at.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",...at.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)(aa,{content:Y})]}),Nl?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:at.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...at.title},children:(0,l.jsx)(Ta,{content:K})})]}),!wa&&!Nl&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:vs,order:Ve?-3:0,...at.title},children:(0,l.jsx)(Ta,{content:K})}),Ve&&Me&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:Me}),Ve&&Co&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:ea,border:`1px solid ${Rn(di)}`,borderRadius:sr,padding:"10px"},children:(0,l.jsx)("input",{ref:ee,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:ar,onChange:i=>{qt("email"),Ur.current=i.target.value,Dr(i.target.value)},onPointerDown:()=>qt("email"),onKeyDown:()=>qt("email"),onBlur:()=>{Dn("email")&&Pn(!0),Go||os()},disabled:ir,required:!0,"aria-invalid":di||void 0,"aria-describedby":di?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Cs}})}),di&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ka,children:es.empty?"Email address is required":"Enter a valid email address"})]}),et&&(0,l.jsx)("div",{style:{order:Ve?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=pt,C=(Z=!1)=>({backgroundColor:ea,border:`1px solid ${Rn(Z)}`,borderRadius:sr,marginTop:"0.5rem",padding:"10px"}),N=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Cs}),me=(0,c.getStateOptions)(i);return(0,l.jsxs)(l.Fragment,{children:[(0,c.isAVSFieldVisible)(et.address_line_1,i)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:C(or("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:Vr,onChange:Z=>{qt("line1"),_r.current.addressLine1=!0,mr.current=Z.target.value,Or(Z.target.value)},onPointerDown:()=>qt("line1"),onKeyDown:()=>qt("line1"),onBlur:()=>Cn("line1"),disabled:ir,required:!0,"aria-invalid":or("line1")||void 0,"aria-describedby":or("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:N()})}),or("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ka,children:"Street address is required"})]}),(0,c.isAVSFieldVisible)(et.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:Wr,onChange:Z=>{_r.current.addressLine2=!0,Yr.current=Z.target.value,gn(Z.target.value)},disabled:ir,"data-testid":"flopay-address-line2",style:N()})}),((0,c.isAVSFieldVisible)(et.city,i)||(0,c.isAVSFieldVisible)(et.state,i))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(et.city,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${Rn(or("city"))}`,borderRight:`1px solid ${Rn(or("city"))}`,borderBottom:`1px solid ${Rn(or("city"))}`,borderLeft:`1px solid ${Rn(or("city"))}`,padding:"10px",borderTopLeftRadius:sr,borderBottomLeftRadius:sr,...(0,c.isAVSFieldVisible)(et.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:sr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:cn,onChange:Z=>{qt("city"),_r.current.city=!0,vr.current=Z.target.value,Er(Z.target.value)},onPointerDown:()=>qt("city"),onKeyDown:()=>qt("city"),onBlur:()=>Cn("city"),disabled:ir,required:!0,"aria-invalid":or("city")||void 0,"aria-describedby":or("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:N()})}),(0,c.isAVSFieldVisible)(et.state,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${Rn(or("state"))}`,borderRight:`1px solid ${Rn(or("state"))}`,borderBottom:`1px solid ${Rn(or("state"))}`,borderLeft:`1px solid ${Rn(or("state"))}`,padding:"10px",borderTopRightRadius:sr,borderBottomRightRadius:sr,...(0,c.isAVSFieldVisible)(et.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Rn(or("state")||or("city"))}`}:{borderRadius:sr}},children:me?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:hn,onChange:Z=>{qt("state"),_r.current.state=!0,yr.current=Z.target.value,dn(Z.target.value)},onPointerDown:()=>qt("state"),onKeyDown:()=>qt("state"),onBlur:()=>Cn("state"),disabled:ir,autoComplete:"billing address-level1",required:!0,"aria-invalid":or("state")||void 0,"aria-describedby":or("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...N(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,c.getStateLabel)(i)}),me.map(Z=>(0,l.jsx)("option",{value:Z.code,children:Z.name},Z.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:hn,onChange:Z=>{qt("state"),_r.current.state=!0,yr.current=Z.target.value,dn(Z.target.value)},onPointerDown:()=>qt("state"),onKeyDown:()=>qt("state"),onBlur:()=>Cn("state"),disabled:ir,required:!0,"aria-invalid":or("state")||void 0,"aria-describedby":or("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:N()})})]}),or("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ka,children:"City is required"}),or("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ka,children:[(0,c.getStateLabel)(i)," is required"]}),((0,c.isAVSFieldVisible)(et.country,i)||(0,c.isAVSFieldVisible)(et.postal_code,i))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:je==="column"?"column":"row",gap:je==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(et.country,i)&&(0,l.jsx)("div",{style:{flex:je==="row"?1:void 0,backgroundColor:ea,borderTop:`1px solid ${Ra}`,borderRight:`1px solid ${Ra}`,borderBottom:`1px solid ${Ra}`,borderLeft:`1px solid ${Ra}`,padding:"10px",...je==="row"&&(0,c.isAVSFieldVisible)(et.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:sr,borderBottomLeftRadius:sr,borderRight:"none"}:{borderRadius:sr}},children:(0,l.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:pt,onChange:Z=>{_r.current.country=!0,Nr.current=Z.target.value,ln(Z.target.value),Lt?.(Z.target.value),yr.current="",dn("")},disabled:ir,autoComplete:"billing country","data-testid":"flopay-country",style:{...N(),cursor:"pointer"},children:[pt===""?(0,l.jsx)("option",{value:"",children:"Select country"}):null,c.COUNTRY_OPTIONS.map(Z=>(0,l.jsxs)("option",{value:Z.code,children:[Z.flag," ",Z.name]},Z.code))]})}),(0,c.isAVSFieldVisible)(et.postal_code,i)&&(0,l.jsx)("div",{style:{flex:je==="row"?1:void 0,backgroundColor:ea,border:`1px solid ${Bd}`,padding:"10px",...je==="row"&&(0,c.isAVSFieldVisible)(et.country,i)?{borderRadius:"0",borderTopRightRadius:sr,borderBottomRightRadius:sr}:{borderRadius:sr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,c.getPostalCodeLabel)(pt),autoComplete:"billing postal-code",value:Ne,onChange:Z=>{qt("zip"),_r.current.zip=!0,Kt.current=Z.target.value,zt(Z.target.value),Ut?.(Z.target.value)},onPointerDown:()=>qt("zip"),onKeyDown:()=>qt("zip"),onBlur:()=>{Dn("zip")&&ho(!0)},disabled:ir,required:Ir.required,"aria-invalid":ui||void 0,"aria-describedby":ui?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:N()})})]}),ui&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ka,children:Ir.empty?`${(0,c.getPostalCodeLabel)(i)} is required`:Yu(i)})]})})()}),Ve&&Ud,Ln&&(0,l.jsx)(ma,{margin:"0.75rem 0",styleOverride:at.errorBanner,children:Ln})]}),pi={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"},jl=i=>D?!X||!Xn?(0,l.jsx)("pre",{"data-testid":i,style:pi,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:pi,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${X}`,` directPaypalConfigured=${Xn}`,` inAppBrowserDetected=${String(si)}`,` shouldRenderDirectPayPal=${To}`,` shouldRenderStripePayPal=${Mo}`,` hasPaypalStripeInstance=${!!sl}`].join(`
39
- `)}):null,Vl=i=>D?!v||!mn?(0,l.jsx)("pre",{"data-testid":i,style:pi,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:pi,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${v}`,` currency=${Mt}`,` amountInCents=${va}`,` enabledPaymentMethods: ${JSON.stringify(M??[])}`,` enabledPaymentMethodsProvided=${Ca}`,` hasEnabledMethods=${ni}`,` expressMethods: ${JSON.stringify(ai)}`,` walletExpressMethods: ${JSON.stringify(Qo)}`,` paymentElementMethods: ${JSON.stringify(is)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ii)}`,` hasStripeInstance=${!!mn}`,` shouldRenderWallets=${bo}`,` shouldRenderPaymentElement=${Ao}`].join(`
40
- `)}):null,Wl=ot==="apm-expanding"||ot==="apm-form"||ot==="apm-collapsing",ra;ot==="apm-expanding"?ra=Uc:ot==="apm-collapsing"&&(ra=zc);let mi=jt?Yc(ss,jt,x):null,$l={label:yt||_c,open:zr,onOpen:Nt,color:So,fontFamily:Xr?.fontFamily};if(ce==="buttons"){let i=ot==="buttons"||ot==="expanding"||ot==="apm-expanding",C=ot==="expanding"||ot==="card"||ot==="collapsing",N=Pe===void 0?{boxSizing:"border-box",height:ko,padding:"0 1rem"}:{padding:"0.9rem 1rem"},me;ot==="expanding"||ot==="apm-expanding"?me=$u:(ot==="collapsing"||ot==="apm-collapsing")&&(me=Wu);let Z;ot==="expanding"?Z=Uc:ot==="collapsing"&&(Z=zc);let De=xr&&(0,c.placePaymentMethodGroups)(xr,{canHide:()=>!0,available:Ml}),Vt={paypal:(0,l.jsxs)(l.Fragment,{children:[To&&St&&(0,l.jsxs)(l.Fragment,{children:[Je&&(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)(Fa.Provider,{value:xe,children:(0,l.jsx)(Oa,{sessionId:e,nonce:t,billingApiUrl:xt,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:wn,clientId:St.clientId,environment:St.environment,currency:Mt.toUpperCase(),isSubscription:ht,providerObjectType:At,approvalPresentation:li==="popup"?void 0:li,onTokenizedBody:on,onComplete:d,onErrorChange:Ue,onDecline:y,onCancel:b,onTechnicalFailure:Jo,onButtonClick:we,runBeforeButtonClick:Un,isProcessing:ir,onLoadStateChange:us,onInitializationStateChange:ps,session:F,existingOrderId:Je?.orderId,debug:D},Je?.orderId??"fresh")})]}),Mo&&(0,l.jsx)(lr.Elements,{stripe:ba,options:dl,children:(0,l.jsx)(jc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:wn,billingApiUrl:xt,onTokenizedBody:on,onErrorChange:Ue,isProcessing:ir,onButtonClick:we,onDecline:y,onTechnicalFailure:Jo,runBeforeButtonClick:Un,onLoadStateChange:Sl,placeholderBorderRadius:io,popupCapabilityOwner:xe,externalTelemetryContext:Il,presentationMode:Zo})})]}),wallets:(0,l.jsxs)(l.Fragment,{children:[bo?(0,l.jsx)(lr.Elements,{stripe:mn,options:cl,children:(0,l.jsx)(Vc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:wn,billingApiUrl:xt,intentKind:Qe>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:on,onErrorChange:Ue,onButtonClick:we,onDecline:y,onTechnicalFailure:Jo,runBeforeButtonClick:Un,onLoadStateChange:wl,placeholderBorderRadius:io,popupCapabilityOwner:xe,externalTelemetryContext:U})}):null,!bo&&_l?(0,l.jsx)("div",{style:{height:ko,borderRadius:io,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:(0,l.jsx)(l.Fragment,{children:Ao&&(0,l.jsx)(Wc,{sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:wn,billingApiUrl:xt,paymentElementMethods:ii,stripeInstance:mn,paymentElementBaseOptions:ss,futureUseSession:x,onTokenizedBody:on,onErrorChange:Ue,onButtonClick:we,onDecline:y,runBeforeButtonClick:Un,onLoadStateChange:Rl,isProcessing:ir,submitButtonColor:So,submitButtonBorderRadius:sr,submitButtonStyle:at.submitButton,onExpandApm:g,expandedApmMethod:jt,themeId:q,buttonAppearance:{backgroundColor:at.cardButton?.backgroundColor,borderColor:at.cardInputBorder,textColor:at.cardButton?.color,borderRadius:io}})}),card:(0,l.jsx)(l.Fragment,{children:Ve&&(0,l.jsx)("button",{type:"button",onClick:async()=>{ir||!(await Un("card")).proceed||(we?.("card"),vt())},disabled:ir,style:{width:"100%",...N,...at.cardButton,...Ks({themeBundle:$o,resolvedPrimaryColor:So,resolvedBorderRadius:sr,submitButtonStyle:at.submitButton,explicitPrimaryColor:Xr?.colorPrimary}),fontSize:at.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ir?"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:ir?.6:1},onMouseEnter:Wt=>{!ir&&($o||Xr?.colorPrimary)&&(Wt.currentTarget.style.backgroundColor=Ld)},onMouseLeave:Wt=>{($o||Xr?.colorPrimary)&&(Wt.currentTarget.style.backgroundColor=So)},onMouseDown:Wt=>{Wt.currentTarget.style.transform="scale(0.985)"},onMouseUp:Wt=>{Wt.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(oa,{content:Pe})})})};return(0,l.jsxs)("form",{onSubmit:fs,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),be&&(0,l.jsx)(an,{status:be,errorMessage:Ln,authorized:mt}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!me?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!me?Ku:{},...me?{animation:me,pointerEvents:"none"}:{}},children:[jl("flopay-direct-paypal-gate-debug"),Vl("flopay-stripe-gate-debug"),Br&&De?(0,l.jsxs)(l.Fragment,{children:[Br.filter(({group:Wt})=>De.inView.includes(Wt)).map(({group:Wt,key:lt})=>(0,l.jsx)(o.default.Fragment,{children:Vt[Wt]},lt)),De.behindLink.length>0&&(0,l.jsx)(Bs,{...$l,showLink:De.showLink,children:Br.filter(({group:Wt})=>De.behindLink.includes(Wt)).map(({group:Wt,key:lt})=>(0,l.jsx)(o.default.Fragment,{children:Vt[Wt]},lt))})]}):(0,l.jsx)(Ds,{rows:Tl,borderRadius:io}),Ln&&ot==="buttons"&&(0,l.jsx)(ma,{margin:"0.25rem 0",styleOverride:at.errorBanner,children:Ln})]}),Ve&&C&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Z?{animation:Z}:{},...ot==="collapsing"?{pointerEvents:"none"}:{}},children:ws}),v&&Wl&&jt&&mi&&mn&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...ra?{animation:ra}:{},...ot==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:hs,borderRadius:Ss,...Ea,padding:bs},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:$,style:{display:"inline-flex",alignItems:"center",gap:Ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:at.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...at.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",...at.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)(aa,{content:Y})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:at.titleFontSize??"1.05rem",color:vs,paddingRight:80,...at.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(jt)}`})]}),(0,l.jsx)(lr.Elements,{stripe:mn,options:mi,children:(0,l.jsx)(Ws,{method:jt,sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:wn,billingApiUrl:xt,onTokenizedBody:on,onErrorChange:Ue,onDecline:y,onCancel:$,runBeforeButtonClick:Un,onButtonClick:we,isProcessing:ir,submitButtonColor:So,submitButtonBorderRadius:sr,submitButtonStyle:at.submitButton,errorText:Ln})},jt)]})})]})]})}if(Wl&&jt&&mi&&mn&&v)return(0,l.jsxs)("form",{onSubmit:fs,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),be&&(0,l.jsx)(an,{status:be,errorMessage:Ln,authorized:mt}),(0,l.jsx)("div",{style:{...ra?{animation:ra}:{},...ot==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:hs,borderRadius:Ss,...Ea,padding:bs},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:$,style:{display:"inline-flex",alignItems:"center",gap:Ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:at.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...at.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",...at.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)(aa,{content:Y})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:at.titleFontSize??"1.05rem",color:vs,paddingRight:80,...at.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(jt)}`})]}),(0,l.jsx)(lr.Elements,{stripe:mn,options:mi,children:(0,l.jsx)(Ws,{method:jt,sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:wn,billingApiUrl:xt,onTokenizedBody:on,onErrorChange:Ue,onDecline:y,onCancel:$,runBeforeButtonClick:Un,onButtonClick:we,isProcessing:ir,submitButtonColor:So,submitButtonBorderRadius:sr,submitButtonStyle:at.submitButton,errorText:Ln})},jt)]})})]});let Hl=Td||Id||Md,_a=xr&&(0,c.placePaymentMethodGroups)(xr,{canHide:i=>i!=="card",available:Ml}),Kl={paypal:(0,l.jsxs)(l.Fragment,{children:[To&&St&&(0,l.jsxs)(l.Fragment,{children:[Je&&(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)(Fa.Provider,{value:xe,children:(0,l.jsx)(Oa,{sessionId:e,nonce:t,billingApiUrl:xt,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:wn,clientId:St.clientId,environment:St.environment,currency:Mt.toUpperCase(),isSubscription:ht,providerObjectType:At,approvalPresentation:li==="popup"?void 0:li,onTokenizedBody:on,onComplete:d,onErrorChange:Ue,onDecline:y,onCancel:b,onTechnicalFailure:Jo,onButtonClick:we,runBeforeButtonClick:Un,isProcessing:ir,onLoadStateChange:us,onInitializationStateChange:ps,session:F,existingOrderId:Je?.orderId,debug:D},Je?.orderId??"fresh")})]}),Mo&&(0,l.jsx)(lr.Elements,{stripe:ba,options:dl,children:(0,l.jsx)(jc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:wn,billingApiUrl:xt,onTokenizedBody:on,onErrorChange:Ue,isProcessing:ir,onButtonClick:we,onDecline:y,onTechnicalFailure:Jo,runBeforeButtonClick:Un,onLoadStateChange:Sl,placeholderBorderRadius:io,popupCapabilityOwner:xe,externalTelemetryContext:Il,presentationMode:Zo})})]}),wallets:(0,l.jsx)(l.Fragment,{children:bo&&(0,l.jsx)(lr.Elements,{stripe:mn,options:cl,children:(0,l.jsx)(Vc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:wn,billingApiUrl:xt,intentKind:Qe>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:on,onErrorChange:Ue,onButtonClick:we,onDecline:y,onTechnicalFailure:Jo,runBeforeButtonClick:Un,onLoadStateChange:wl,placeholderBorderRadius:io,popupCapabilityOwner:xe,externalTelemetryContext:U})})}),apms:(0,l.jsx)(l.Fragment,{children:Ao&&(0,l.jsx)(Wc,{sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:xt,paymentElementMethods:ii,stripeInstance:mn,paymentElementBaseOptions:ss,futureUseSession:x,onTokenizedBody:on,onErrorChange:Ue,onButtonClick:we,onDecline:y,runBeforeButtonClick:Un,onLoadStateChange:Rl,isProcessing:ir,submitButtonColor:So,submitButtonBorderRadius:sr,submitButtonStyle:at.submitButton,themeId:q,onExpandApm:g,expandedApmMethod:jt,buttonAppearance:{backgroundColor:at.cardButton?.backgroundColor,borderColor:at.cardInputBorder,textColor:at.cardButton?.color,borderRadius:io}})})};return(0,l.jsxs)("form",{onSubmit:fs,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),be&&(0,l.jsx)(an,{status:be,errorMessage:Ln,authorized:mt}),Br===null?(0,l.jsx)(Ds,{rows:Tl,borderRadius:io}):(0,l.jsxs)(l.Fragment,{children:[qr&&Ve&&ws,qr&&Ve&&Hl&&(0,l.jsx)(Ka,{label:"or pay another way"}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jl("flopay-direct-paypal-gate-debug-default"),Vl("flopay-stripe-gate-debug-default"),Br.map(({group:i,key:C})=>i==="card"||!_a?.inView.includes(i)?null:(0,l.jsx)(o.default.Fragment,{children:Kl[i]},C)),_a&&_a.behindLink.length>0&&(0,l.jsx)(Bs,{...$l,showLink:_a.showLink,children:Br.map(({group:i,key:C})=>_a.behindLink.includes(i)&&i!=="card"?(0,l.jsx)(o.default.Fragment,{children:Kl[i]},C):null)})]}),!qr&&Ve&&Hl&&(0,l.jsx)(Ka,{label:"or pay with card"}),!qr&&Ve&&ws]})]})}var B=require("react/jsx-runtime"),qo=44,el="flopay_checkout_saved_payment_resume",rp="paypal_resume_nonce_missing",Ki=new Map,$i=new Map;function Xc(e,t){t.settled&&t.consumers===0&&Ki.get(e)===t&&Ki.delete(e)}function np(e,t,r){let n=$i.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};$i.set(e,s);let d=()=>{$i.get(e)===s&&$i.delete(e)};return a.then(d,d),a}function Ja(e){return new Promise(t=>setTimeout(t,e))}function Hi(e,t,r){let n=Ri({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:le.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Za(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ys(e,t,r,n,a,s){let d=Hi(e,t,r);d.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Za(d)}function Jc(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 Zc(e,t,r,n,a){let s=(0,le.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 le.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof le.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):s.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...s,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function Xs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,le.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var op={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function ap(e){return new yo.FloPay(op,{publishableKey:"provider_unavailable",...e})}async function Js(e,t){let{publishableKey:r,paypalPublishableKey:n}=xs(e);return{...await Fs({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function tl(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ip(){if(!tl())return null;try{let e=window.sessionStorage.getItem(el);return e?JSON.parse(e):null}catch{return null}}function Qc(e){if(tl())try{window.sessionStorage.setItem(el,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Zs(){if(tl())try{window.sessionStorage.removeItem(el)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function sp(){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 ed(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 Qs(e,t){return(0,le.resolveCheckoutLogLayout)(!!e,t)}function lp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function td(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function cp(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 Gi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:d,loading:p,error:y,onComplete:b,onError:P,onInstrument:h,onDecline:E,onCancel:V,onCountryChange:W,onZipChange:w,showPayPal:T=!0,showStripe:f=!0,walletPresentation:H="auto",enabledPaymentMethods:X,showApplePay:v=!0,showGooglePay:Se=!0,debug:M=!1,layout:oe,paymentMethodLayout:ye,moreOptionsLabel:Ee,theme:ce,buttonsTheme:bt,buttonsStyles:yt,cardButtonContent:q,cardBackButtonContent:He,cardTitleContent:Ke,showSecurityFooter:Le,onButtonClick:Pe,onBeforeButtonClick:Y,enableAVS:K,cardFieldOrder:tt,showCardBrandIcons:we,cardAutoFocus:qe,onCardFieldsReady:Q,onCardFieldsFailed:j,cardFieldsTimeoutMs:fe,cardPreFormSlot:J,avsLayout:ft,submitLabel:de,className:ve,initialErrorMessage:_e=null,initialPayPalOrderId:Me,children:je,checkoutMode:ge,confirmLabel:rt,renderConfirmButton:dt,onSessionCompleted:ut}){let ae=(0,le.resolveBillingApiUrl)(n),Dt=(0,S.useMemo)(()=>(0,le.resolveTheme)(ce),[ce]),Lt=s??Dt?.appearance,Ut=r?"embedded_checkout":"standard_checkout",Ie=Qs(je,oe),[he,gt]=(0,S.useState)(null),[Qe,Mt]=(0,S.useState)(null),nt=(0,S.useRef)(null),St=(0,S.useRef)(null),ht=(0,S.useRef)(0),[ne,$t]=(0,S.useState)(null),kt=(0,S.useRef)(null),[D,Ye]=(0,S.useState)(null),_=(0,S.useMemo)(()=>r?(0,Ct.serializeCreateParams)(r):"",[r]),A=r?`create:${_}`:`session:${e??""}`,Ae=td(D),te=(0,S.useRef)(new Set),xe=(0,S.useRef)(A),u=(0,S.useRef)(A);Oo(()=>{u.current=A,xe.current!==A&&(xe.current=A,te.current.clear())},[A]);let I=(0,S.useCallback)(O=>{if(u.current===A){if(Ms.FLO_INSTRUMENT_ONCE_NAMES.has(O.name)){if(te.current.has(O.name))return;te.current.add(O.name)}(0,Ge.invokeMerchantCallback)(()=>h?.(O))}},[A,h]),k=pa(I,A),U=(0,S.useRef)(!1),F=(0,S.useCallback)(O=>{if(U.current)return;let L=O.gateway||!Ae?O:{...O,gateway:Ae};I(L)},[I,Ae]);(0,S.useEffect)(()=>{k({class:"lifecycle",name:"checkout.mount"})},[k]);let[x,At]=(0,S.useState)(e??""),Et=e??x,kr=r?"":Et,[rr,Pt]=(0,S.useState)(!0),[xt,xr]=(0,S.useState)(null),[Fr,zr]=(0,S.useState)(0),[Qt,Br]=(0,S.useState)("full"),[qr,en]=(0,S.useState)(!1),[jr,ur]=(0,S.useState)(_e),[pr,pt]=(0,S.useState)(null),[ln,Ne]=(0,S.useState)(null),[zt,Vr]=(0,S.useState)(!1),[Or,Wr]=(0,S.useState)(void 0),[gn,cn]=(0,S.useState)(""),[Er,hn]=(0,S.useState)(!1),[dn,ar]=(0,S.useState)(!1),[Dr,Lr]=(0,S.useState)(!1),$r=(0,S.useRef)(null),Kt=(0,S.useRef)(0),Nr=(0,S.useRef)(void 0),[mr,Yr]=(0,S.useState)("loading"),[vr,yr]=(0,S.useState)(0),Ur=(0,S.useRef)(!1),_r=(0,S.useRef)(!1),et=(0,S.useRef)(!1),z=(0,S.useRef)(null),mt=(0,S.useRef)(null),G=(0,S.useMemo)(()=>({checkoutMode:ge??Qt,layout:lp(je,oe)}),[ge,je,Qt,oe]),Re=(0,S.useRef)(b);Re.current=b;let Ft=(0,S.useRef)(P);Ft.current=P;let Gt=(0,S.useRef)(E);Gt.current=E;let Yt=(0,S.useCallback)(O=>Ii(z,async L=>{try{return await O(L)}catch(se){throw L.aborted?ya(se):se}}),[]);(0,S.useEffect)(()=>()=>{z.current?.abort(),z.current=null},[]);let Be=(0,S.useCallback)((O,L)=>{nt.current=O,Mt(O),kt.current=L,$t(L)},[]),Ve=(0,S.useCallback)(()=>{let O=St.current;O&&(St.current=null,O.destroy())},[]);(0,S.useEffect)(()=>{br(Qe)?.setCheckoutContext(G),ne&&ne!==Qe&&br(ne)?.setCheckoutContext(G)},[Qe,ne,G]);let _o=(0,S.useRef)(ut);_o.current=ut;let go=(0,S.useCallback)(O=>{Yr(O),!(O!=="exhausted"||et.current)&&(et.current=!0,Ft.current?.(new le.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Io=(0,S.useCallback)(()=>{Yr("retrying"),yr(O=>O+1)},[]);(0,S.useEffect)(()=>{Yr("loading"),yr(0),et.current=!1},[Et]),(0,S.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:le.SDK_VERSION,checkout_type:Ut,checkout_layout:Ie,billing_api_url:ae})},[Ie,Ut,ae]);let xn=(0,S.useMemo)(()=>r?(0,Ct.serializeCreateParams)(r,!0):"",[r]),Fn=(0,S.useMemo)(()=>gn===xn?Or:void 0,[Or,gn,xn]),tn=(0,S.useMemo)(()=>r?Es(r,Fn):void 0,[r,Fn]),un=ge??tn?.checkoutMode??"full",nr=(0,S.useMemo)(()=>tn?{...tn,checkoutMode:un}:void 0,[tn,un]);(0,S.useEffect)(()=>{Wr(void 0),cn(xn),Nr.current=void 0,$r.current=null,Lr(!1)},[xn]),(0,S.useEffect)(()=>{ur(_e)},[_e]);let Hn=(0,S.useCallback)((O,L,se)=>{(0,Ge.invokeMerchantCallback)(()=>{Gt.current?.(Cr(O,L,se))})},[]),rn=(0,S.useCallback)(async(O,L)=>{ur(null),Ne(null),Vr(!1),pt("processing");let se=L?.sessionId??O.id,ue=O.clientSecret||t,Nt=td(O),er=nt.current??kt.current,Oe=br(er),it=er?null:Hi(ae,a,G),re={log:ee=>{Oe?Oe.log(ee):it?.log(ee)},error:ee=>{Oe?Oe.error(ee):it?.error(ee)},terminal:ee=>{Oe?Oe.terminal(ee):it?.terminal(ee)},performance:ee=>{Oe?Oe.performance(ee):it?.performance(ee)},now:()=>Oe?.now()??it?.now()??0,elapsed:ee=>Oe?.elapsed(ee)??Math.max(0,(it?.now()??ee)-ee)},Te=re.now(),Ce=!!(L?.initialAutoProcessingError||L?.initialAutoProcessingPending),vt=!1,m,g=()=>{vt||(vt=!0,Ce=!0,m=re.now(),re.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},$=!1,be=()=>{$||($=!0,re.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),re.performance({stage:"processing",durationMs:re.elapsed(Te),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),m!==void 0&&re.performance({stage:"recovery",durationMs:re.elapsed(m),durationMode:"machine",paymentMethodCategory:"saved"}))};re.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),U.current=!0;try{re.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{U.current=!1}k({class:"lifecycle",name:"payment.processing.started",provider:Nt}),Ce&&g();let ie;try{let ee=wc(L?.initialAutoProcessingError),Fe=L?.initialAutoProcessingError?.type==="3ds_required"&&!(0,le.isMerchantAuthRequired)(L.initialAutoProcessingError)&&!L.initialAutoProcessingError.threeDSecureToken&&L.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:L.initialAutoProcessingError.nextActionRedirectUrl}:null,_t,Xt=st=>{g();let It=qa(ae,se,O,a!==!1);return Yt(pe=>fa(st,{billingApiUrl:ae,sessionId:se,nonce:ue,session:O,signal:pe,...It.telemetry?{challengeTelemetry:It.telemetry}:{}})).finally(It.release)};if(Fe)_t=await Xt(Fe);else if(ee)g(),ee.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Qc({sessionId:se,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey,nonce:ue}),_t=await Yt(st=>Mi(ee,{flopay:nt.current,paypalFlopay:kt.current,attempt3DS:L?.attempt3DS,billingApiUrl:ae,sessionId:se,session:O,telemetry:!1,signal:st})),ee.type==="paypal_redirect_required"&&Zs();else if(L?.initialAutoProcessingPending){let st=L.initialAutoProcessingPending,It=new yo.PaymentAPI(ae,{telemetry:!1}),pe=await Yt(Je=>It.waitForCheckoutSessionCompletion(st.sessionId,{initialDelayMs:st.retryAfterMs,nonce:ue,statusUrl:st.statusUrl,signal:Je})),Xe=Ro(pe,O),We=pe.autoProcessingError?.type==="3ds_required"&&pe.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:pe.autoProcessingError.nextActionRedirectUrl}:null;if(We)_t=await Xt(We);else{if(!lo(Xe))throw sa(Xe);_t=so(Xe,se)}}else{if(L?.initialAutoProcessingError)throw eo(L.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.initialAutoProcessingError.checkoutMethod});if(L?.fromCreateSession)return L?.fallbackToFull&&(Br("full"),ed("full")),!1;{let st=await ga({billingApiUrl:ae,sessionId:se,session:O,nonce:ue,telemetry:!1});st.type==="success"?_t=st.result:st.type==="next_action_required"?_t=await Xt(st):(g(),st.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Qc({sessionId:se,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey,nonce:ue}),_t=await Yt(It=>Mi(st,{flopay:nt.current,paypalFlopay:kt.current,attempt3DS:L?.attempt3DS,billingApiUrl:ae,sessionId:se,session:O,telemetry:!1,signal:It})),st.type==="paypal_redirect_required"&&Zs())}}se&&(0,Vn.markSessionRecentlyCompleted)(se),be(),Ce&&(re.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),re.terminal({outcome:_t.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Vr(_t.status==="authorized"),pt("success"),await Ja(600),ie=()=>Re.current?.(_t)}catch(ee){let Fe=wo(ja(ee),se);if(Fe.code==="three_ds_aborted")return!1;let _t=Fe.checkoutMethod??za;ur(Fe.message),Ne(Fe.message),Vr(!1),L?.fallbackToFull&&(re.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Br("full"),ed("full")),be();let Xt=Fe.statusCode===void 0?void 0:(0,le.telemetryStatusClass)(Fe.statusCode,"unknown"),st=Xt==="4xx"?{requestCategory:"process_payment",statusClass:Xt}:{},It=Xt===void 0||Xt==="4xx";if((0,le.isExpectedPaymentDecline)(Fe))re.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...st});else if(It&&(Fe.telemetryOutcome==="validation_rejected"||Fe.type==="validation_error"))re.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...st});else{let We=(0,le.classifyTelemetryFailure)(ee,Ce?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Je=Fe.telemetryRequestCategory??"process_payment";U.current=!0;try{re.error({...We,...Fe.telemetryFailureCategory?{failureCategory:Fe.telemetryFailureCategory}:{},stage:Ce?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Je})}finally{U.current=!1}k({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Je,provider:Nt})}return(0,le.isDeclineCallbackFailure)(Fe)?Hn(_t,Fe,{code:Fe.code,declineCode:Fe.declineCode}):(0,Ge.invokeMerchantCallback)(()=>Ft.current?.(Fe)),pt("error"),await Promise.allSettled([Ja(400),L?.ensureProvidersReady?L.ensureProvidersReady():Promise.resolve()]),Ce&&(re.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),re.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{be(),it&&Za(it),pt(null),Ne(null)}return(0,Ge.invokeMerchantCallback)(ie),!0},[Hn,k,t,ae,Yt,a,G]);(0,S.useEffect)(()=>{if(typeof window>"u"||_r.current)return;let O=new URLSearchParams(window.location.search),L=O.get("payment_intent_client_secret");if(!L)return;let se=ip();se&&(_r.current=!0,(async()=>{await Promise.resolve();let ue,Nt=0;ur(null),Ne(null),pt("processing"),en(!0);try{if(O.get("redirect_status")==="failed")throw Object.assign(new le.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:er,paypalFlopay:Oe}=await Fs({publishableKey:se.publishableKey,paypalPublishableKey:se.paypalPublishableKey,billingApiUrl:ae,locale:d,telemetry:a});ue=br(Oe??er),ue?.setCheckoutContext(G),Nt=ue?.now()??0,ue?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ue?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let it=(Oe??er)?.getRawProvider();if(!it)throw Object.assign(new le.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:re,error:Te}=await it.retrievePaymentIntent(L);if(Te)throw Object.assign(new le.FloPayError(Te.message??"Failed to retrieve PayPal payment status.","api_error",{code:Te.code}),{checkoutMethod:"paypal"});let Ce=ac(re?.status);if(!re||Ce==="failed")throw Object.assign(new le.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let vt=typeof re.payment_method=="string"?re.payment_method:re.payment_method?.id,m=Ce;if(se.sessionId){let g=se.nonce||t;if(!g)throw Object.assign(new le.FloPayError("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:rp}),{checkoutMethod:"paypal"});let ie=(await new yo.PaymentAPI(ae,{telemetry:!1}).getUnifiedCheckoutSession(se.sessionId,g)).data.session;if(ie&&ie.status!=="complete"){let ee=await ga({billingApiUrl:ae,sessionId:se.sessionId,session:ie,nonce:g,telemetry:!1,tokenizedData:{id:vt??re.id,type:"card",threeDSecureActionResultTokenId:re.id,isPaypal:!0}});if(ee.type!=="success")throw Object.assign(new le.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});m=ee.result.status}}se.sessionId&&(0,Vn.markSessionRecentlyCompleted)(se.sessionId),ue?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ue?.performance({stage:"redirect_resume",durationMs:ue.elapsed(Nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ue?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),pt("success"),await Ja(600),(0,Ge.invokeMerchantCallback)(()=>Re.current?.({status:m,paymentIntentId:re.id,paymentMethodId:vt,checkoutMethod:"paypal"}))}catch(er){let Oe=wo(ja(er),se.sessionId),it=Oe.checkoutMethod??"paypal",re=(0,le.isExpectedPaymentDecline)(Oe);if(ue)ue.performance({stage:"redirect_resume",durationMs:ue.elapsed(Nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),re?ue.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ue.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(re){let Te=Hi(ae,a,G);Te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Za(Te)}else Ys(ae,a,G,"REDIRECT_RESUME_FAILED","redirect_resume");ur(Oe.message),Ne(Oe.message),(0,le.isDeclineCallbackFailure)(Oe)?Hn(it,Oe,{code:Oe.code,declineCode:Oe.declineCode}):(0,Ge.invokeMerchantCallback)(()=>Ft.current?.(Oe)),pt("error"),await Ja(400)}finally{Zs(),sp(),pt(null),Ne(null),en(!1)}})())},[Hn,d,t,ae,a,G]);let Hr=(0,S.useRef)(null),Ht=(0,S.useMemo)(()=>nr?(0,Ct.serializeCreateParams)(nr):"",[nr]),Ir=(0,S.useRef)(nr);Ir.current=nr,(0,S.useEffect)(()=>{At(e??"")},[e]),(0,S.useEffect)(()=>{Ur.current=!1,ur(_e),Ne(null),Vr(!1),pt(null)},[Ht,_e,e]);async function Bn(O,L,se){let ue=Hi(ae,a,G),Nt=new yo.PaymentAPI(ae,{telemetry:!1}),er=!1;try{let Oe=O.idempotencyKey===void 0?void 0:(0,le.resolveIdempotencyKey)(O.idempotencyKey),it=(0,Ct.readCachedInlineSession)(L,se),re=(0,Ct.readCachedInlineIdempotencyKey)(L,se);it?.canonicalIdentity===se&&re&&re.canonicalIdentity===void 0&&((0,Ct.persistCachedInlineIdempotencyKey)(L,se,re.idempotencyKey),re={...re,canonicalIdentity:se});let Te=Oe??(re?.canonicalIdentity===se?re.idempotencyKey:void 0),Ce,vt=!1;ue.log({name:it?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let m=it?.sid??null,g=null,$,be,ie=!1;if(m)try{g=await Nt.getUnifiedCheckoutSession(m,it?.nonce),it&&it.canonicalIdentity===void 0&&((0,Ct.legacyCachedSessionMatchesDraft)(g.data.session,O)?((0,Ct.persistCachedInlineSession)(L,se,m,it.nonce??g.data.session?.clientSecret),re&&re.canonicalIdentity===void 0&&((0,Ct.persistCachedInlineIdempotencyKey)(L,se,re.idempotencyKey),Te??(Te=re.idempotencyKey))):((0,Ct.clearCachedInlineCheckout)(L,se),re=null,Te=Oe,m=null,g=null));let Fe=g?.data.session?.status,_t=g?.data.session,Xt=_t?.clientSecret||it?.nonce;if(m&&_t?.buyerIdentified===!1&&Xt&&(be=ia(Nt,m,Xt,O.account)),m&&g&&Fe==="complete"){if((0,Vn.wasSessionRecentlyCompleted)(m))return{sid:m,result:g};(0,Ct.clearCachedInlineCheckout)(L,se),m=null,g=null,vt=!0}}catch{ue.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),it?.canonicalIdentity===void 0?((0,Ct.clearCachedInlineCheckout)(L,se),Te=Oe):(0,Ct.clearCachedInlineSession)(L,se),m=null}if(!m){!Oe&&(vt||!Te)&&(Te=(0,le.resolveIdempotencyKey)(),Ce=Te),Te&&(0,Ct.persistCachedInlineIdempotencyKey)(L,se,Te);let Fe=ue.now(),_t=0;ue.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Xt={...O,idempotencyKey:Te,avsCheck:!!K,avsConfig:typeof K=="object"?K:void 0,checkoutType:"embedded_checkout",checkoutLayout:Qs(je,oe)};Object.defineProperty(Xt,yo.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:pe=>{_t=Math.max(_t,pe)}}});let st=()=>{Jc(ue,"session_create",Fe,_t)},It=pe=>{Zc(ue,pe,"session_create",Fe,_t)&&k({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(O.checkoutMode==="confirm"||O.checkoutMode==="auto")&&Cc();try{if((0,le.isDetachedSessionEligible)(Xt)){let pe=await Nt.createDetachedSession(Xt);pe.claimed.catch(()=>{}),g=pe.shell,m=pe.sessionId,be=pe.claim;let Xe=ue.now();ue.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),$=pe.claimed.then(We=>{let Je=We.data.session?.id??pe.sessionId;return Je&&(0,Ct.persistCachedInlineSession)(L,se,Je,We.data.session?.clientSecret??pe.nonce),Jc(ue,"session_claim",Xe),st(),We},We=>{throw(0,Ct.clearCachedInlineSession)(L,se),Zc(ue,We,"session_claim",Xe,0)&&k({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),We}).finally(()=>Za(ue)),$.catch(()=>{}),er=!0,ue.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ue.performance({stage:"session_shell",durationMs:ue.now()-Fe,durationMode:"machine",requestCategory:"session_create",attempt:_t,statusClass:"2xx",paymentMethodCategory:"card"})}else g=await Nt.createAndFetchSession(Xt),st()}catch(pe){throw It(pe),pe}m=g.data.session?.id??m??"",m&&!$&&(0,Ct.persistCachedInlineSession)(L,se,m,g.data.session?.clientSecret)}let ee=g?.data.session;return!be&&m&&ee?.buyerIdentified===!1&&ee.clientSecret&&(be=ia(Nt,m,ee.clientSecret,O.account)),{sid:m??"",result:g,sdkGeneratedIdempotencyKey:Ce,...$?{claimed:$}:{},...be?{claim:be}:{},...ie?{claimRequiresIdentity:!0}:{}}}finally{er||Za(ue)}}let oo=(0,S.useRef)(Bn);Oo(()=>{oo.current=Bn},[Bn]);let pn=(0,S.useCallback)(async(O,L)=>{let se=Ir.current;if(!se)throw new le.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ue=Es(se,O),Nt=(0,Ct.serializeCreateParams)(ue),er=(0,Ct.hashCreateParams)(ue),Oe=Ki.get(Nt);if(!Oe){let Te={canonicalIdentity:Nt,promise:oo.current(ue,er,Nt),consumers:0,settled:!1};Oe=Te,Ki.set(Nt,Te);let Ce=()=>{Te.settled=!0,Xc(Nt,Te)};Te.promise.then(Ce,Ce)}Oe.consumers+=1;let it=!1,re=()=>{it||(it=!0,Oe.consumers-=1,Xc(Nt,Oe))};L?.(re);try{let Te=await Oe.promise;Hr.current=Nt,O&&(cn(xn),Wr(ee=>Ql(ee,O)));let{sid:Ce,result:vt,claimed:m,claim:g,claimRequiresIdentity:$}=Te;if(Nr.current=g,Lr($===!0),gt(vt),vt.data.session&&Ye(vt.data.session),Ce&&At(Ce),m){Kt.current+=1;let ee=Kt.current;$r.current=m,ar(!0),m.then(Fe=>{Kt.current===ee&&($r.current===m&&($r.current=null),gt(Fe),Fe.data.session&&Ye(Fe.data.session),ar(!1),Lr(!1))},Fe=>{Kt.current===ee&&($r.current===m&&($r.current=null),ar(!1),Lr(!1),xr(Fe instanceof le.FloPayError?Fe:new le.FloPayError(Fe instanceof Error?Fe.message:"Failed to create session","api_error")))})}else Kt.current+=1,$r.current=null,ar(!1),Lr(!1);let{flopay:be,paypalFlopay:ie}=await Js(vt,{billingApiUrl:ae,locale:d,telemetry:a}).catch(ee=>{throw rc(ee,Ce||vt.data.session?.id)});return Be(be,ie),Pt(!1),Te}catch(Te){throw Hr.current===Nt&&(Hr.current=null),Te}finally{L||re()}},[xn,Be,d,ae,a]),On=(0,S.useRef)(rn);On.current=rn;let Kn=(0,S.useRef)(pn);Kn.current=pn;let ho=(0,S.useCallback)(async O=>{if(!cp(O)||Er)return{sessionId:x,session:D};hn(!0);try{let L=await pn(O);return{sessionId:L.sid,session:L.result.data.session??null}}finally{hn(!1)}},[pn,Er,x,D]),Gn=(0,S.useCallback)(async O=>{let L=Nr.current;if(!L)return;let se=Kt.current,ue=await L(O);Kt.current===se&&(gt(ue),ue.data.session&&Ye(ue.data.session))},[]),Pn=(0,S.useCallback)(async()=>{await $r.current},[]),Vo=(0,S.useCallback)(async()=>(await Pn(),{proceed:!0}),[Pn]);(0,S.useEffect)(()=>{let O=!1,L,se=++ht.current;Ve(),xr(null),zr(0);let ue=()=>{O=!0,ht.current===se&&(ht.current+=1,Ve())},Nt=Ir.current;if(Ht&&Nt)return Br(un),Pt(!1),Hr.current===Ht?ue:(Ye(ec(Nt,ge)),(async()=>{let it=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),re=un==="auto"&&!Ur.current&&!it;re&&(ur(null),Ne(null),pt("processing"));let Te=!1;try{let Ce=await Kn.current(void 0,$=>{L=$});Te=!0;let vt=Ce.result.data.session??null;mt.current=xs(Ce.result);let m=Xs(Ce.result),g=(0,Vn.wasSessionRecentlyCompleted)(Ce.sid||vt?.id);if(!O&&re&&vt&&!m&&!g){Ur.current=!0,await np(Ht,Ce.sdkGeneratedIdempotencyKey,()=>On.current(vt,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Ce.result.autoProcessingError,initialAutoProcessingPending:Ce.result.autoProcessingPending,autoProcessingAttempted:Ce.result.autoProcessingAttempted,sessionId:Ce.sid||vt.id}));return}!O&&re&&((m||g)&&(Ur.current=!0),pt(null),Ne(null))}catch(Ce){if(O)return;let vt=hi(Ce);if(re&&vt==="session_auto_completed"){Ur.current=!0,pt("success"),await Ja(600),O||((0,Ge.invokeMerchantCallback)(()=>{Re.current?.({status:"succeeded"})}),pt(null),Ne(null));return}if(re&&(pt(null),Ne(null)),!Te){let g=nc(Ce),$=(0,le.toPublicCheckoutInitError)(Ce,g?{stage:"provider_load",provider:"stripe",...g}:{stage:"session_request"});(g||!(Ce instanceof le.FloPayError))&&(0,Ge.invokeMerchantCallback)(()=>Ft.current?.($)),xr($);return}let m=Ce instanceof le.FloPayError?Ce:new le.FloPayError(Ce instanceof Error?Ce.message:"Failed to create session","api_error");xr(m)}finally{L?.(),L=void 0}})(),()=>{ue(),L?.()});Pt(!0);async function er(){let it=!1,re=!1,Te=null;try{let Ce=new yo.PaymentAPI(ae,{telemetry:!1}),vt=await Ce.getUnifiedCheckoutSession(Et,t);if(re=!0,Te=vt,O)return;gt(vt);let m=vt.data.session??null;if(Ye(m),!m)throw new le.FloPayError("No session data returned","api_error");let g=m.checkoutMode;if(g==="setup")throw new le.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(m.status==="authorized"){Pt(!1),(0,Ge.invokeMerchantCallback)(()=>{Re.current?.(so(m,Et)),_o.current?.(m.successUrl??"")});return}if(m.status==="complete"){Pt(!1),(0,Ge.invokeMerchantCallback)(()=>{_o.current?.(m.successUrl??"")});return}if(m.status==="expired")throw gi(m);it=!0;let $=ge??g??"full";Br($),Kt.current+=1;let be=m.clientSecret||t;Nr.current=m.buyerIdentified===!1&&be?ia(Ce,Et,be,{...m.customer?.id?{userId:m.customer.id}:{}}):void 0,ar(!1),Lr(!1);let ie=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ee=Xs(vt);if($==="auto"&&!Ur.current&&!ie&&!ee){Ur.current=!0;let Fe=Oe(vt);try{if(await On.current(m,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Fe,sessionId:Et||m.id}),O)return;await Fe,O||Pt(!1);return}catch{if(O)return;await Fe,O||Pt(!1);return}}await Oe(vt),O||Pt(!1)}catch(Ce){if(O)return;let vt=Zl(Ce,it);if(it&&k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),vt){let{errorCode:be,stage:ie,...ee}=vt;Ys(ae,a,G,be,ie,ee)}if(vt?.stage==="provider_load"&&(ge??Te?.data.session?.checkoutMode??"full")==="full"&&Jl(Te,T,f)){let be=ap({billingApiUrl:ae,locale:d,telemetry:a});St.current=be,Be(be,null),zr(1),Pt(!1);return}let m=vt?.stage==="provider_load",g="session_request";m?g="provider_load":re&&(g="post_session");let $=(0,le.toPublicCheckoutInitError)(Ce,{stage:g,provider:"stripe",sessionId:Et||void 0});(m||!(Ce instanceof le.FloPayError))&&(0,Ge.invokeMerchantCallback)(()=>Ft.current?.($)),xr($),Pt(!1)}}async function Oe(it){let{flopay:re,paypalFlopay:Te,...Ce}=await Js(it,{billingApiUrl:ae,locale:d,telemetry:a});mt.current={publishableKey:Ce.publishableKey,paypalPublishableKey:Ce.paypalPublishableKey},Be(re,Te),zr(0)}return er(),ue},[ge,Ht,un,kr,t,T,f]);let Wo=(0,S.useCallback)(async()=>{if(!he||Fr!==1)return;let O=ht.current;zr(2);try{let{flopay:L,paypalFlopay:se}=await Js(he,{billingApiUrl:ae,locale:d,telemetry:a});if(ht.current!==O)return;Ve(),Be(L,se),zr(0)}catch(L){if(ht.current!==O)return;let{errorCode:se,stage:ue,...Nt}=ks(L);Ys(ae,a,G,se,ue,Nt)}},[Ve,Be,d,Fr,ae,a,G,he]),ao=!!(Et&&(D?.clientSecret||t)),vn=qr||!ao,Po=(0,S.useCallback)(async()=>{if(!(qr||!ao||!D)){en(!0),ur(null);try{await rn(D,{attempt3DS:!0,fallbackToFull:!0,sessionId:Et||D.id})}finally{en(!1)}}},[Et,qr,ao,rn,D]),qt=(0,le.resolveDirectPaypalConfig)(he?.data.paypal,Me),Dn=Xs(he),Cn=(0,S.useMemo)(()=>{if(!(!he||!D||!he.data.stripe?.publishableKey))return{billingApiUrl:ae}},[he,D,ae]),bn=!!(r&&!je&&oe==="buttons"&&Y&&un==="full"),Sn=!!(Et&&((0,le.isMountableVaultBlock)(D?.vault)||(0,zn.canRecoverHostedCardForm)(D))),ot=(0,S.useMemo)(()=>({session:D,loading:rr,error:xt,checkoutMode:Qt,inlineSessionDraft:nr,applyInlineSessionPatch:bn?ho:void 0,inlineSessionPatchProcessing:Er,claimPending:dn,claimRequiresIdentity:Dr,claimBuyerIdentity:Gn,waitForDataAttachment:Pn}),[D,rr,xt,Qt,nr,bn,ho,Er,dn,Dr,Gn,Pn]),Kr=!!r&&oe==="buttons"&&!Dn&&!Sn&&(!Qe||!Cn),jt=pr?(0,B.jsx)(an,{status:pr,errorMessage:ln,authorized:zt}):null;if(rr&&!Sn){if(p)return(0,B.jsxs)(B.Fragment,{children:[p,jt]});if(oe==="buttons"){let O=Dt?.buttonsLayout?.cardButton?.borderRadius??Dt?.appearance.variables?.borderRadius??8,L=se=>(0,B.jsx)("div",{style:{height:se,borderRadius:O,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[T&&L(qo),f&&(v||Se)&&L(qo),f&&L(qo),(0,B.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),jt]})}return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,B.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,B.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),jt]})}return xt?y?(0,B.jsx)(qn.Provider,{value:ot,children:y(xt)}):(0,B.jsx)(qn.Provider,{value:ot,children:(0,B.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:xt.message})}):Kr?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(qn.Provider,{value:ot,children:(0,B.jsx)(up,{onButtonClick:Pe,paymentMethodLayout:ye,showPayPal:T,showStripe:f,showApplePay:v,showGooglePay:Se,theme:ce,buttonsTheme:bt,buttonsStyles:yt,cardButtonContent:q,cardBackButtonContent:He,cardTitleContent:Ke})}),jt]}):Dn&&D&&qt?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(qn.Provider,{value:ot,children:(0,B.jsxs)("div",{className:ve,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jr&&(0,B.jsx)(ma,{icon:!1,children:jr}),mr==="retrying"&&(0,B.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),mr==="exhausted"&&(0,B.jsxs)("div",{role:"alert",children:[(0,B.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,B.jsx)("button",{type:"button",onClick:Io,children:"Retry PayPal"})]}),mr!=="exhausted"&&(0,B.jsx)("div",{"aria-hidden":mr==="retrying"?!0:void 0,style:mr==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,B.jsx)(gc,{sessionId:Et,nonce:D.clientSecret||void 0,billingApiUrl:ae,email:D.customer?.email||nr?.account?.email,billingName:[D.customer?.firstName,D.customer?.lastName].filter(Boolean).join(" ")||[nr?.account?.firstName,nr?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Gn,clientId:qt.clientId,environment:qt.environment,currency:(D.currency??"usd").toUpperCase(),isSubscription:D.mode==="subscription",providerObjectType:qt.providerObjectType,approvalPresentation:qt.approvalPresentation,existingOrderId:qt.existingOrderId,onComplete:b,onErrorChange:ur,onDecline:E,onCancel:V,onButtonClick:Pe,runBeforeButtonClick:Vo,onInitializationStateChange:go,allowAutomaticRetry:vr===0,session:D,telemetry:a,telemetryContext:G,onInstrument:F,debug:M},`${A}:paypal-init-${vr}`)})]})}),jt]}):Qt==="confirm"?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(qn.Provider,{value:ot,children:(0,B.jsx)(La,{flopay:Qe,paypalFlopay:ne,options:Cn??{billingApiUrl:ae},onInstrument:F,children:(0,B.jsxs)("div",{className:ve,children:[jr&&(0,B.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:jr}),dt?dt({onConfirm:Po,isProcessing:vn}):(0,B.jsx)("button",{type:"button",onClick:Po,disabled:vn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:vn?"not-allowed":"pointer",opacity:vn?.6:1},children:qr?"Processing...":rt??"Confirm Purchase"})]})},A)}),jt]}):(!Qe||!Cn)&&!(Sn&&Qt==="full")?(0,B.jsx)(B.Fragment,{children:jt}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(qn.Provider,{value:ot,children:(0,B.jsxs)(La,{flopay:Qe,paypalFlopay:ne,options:Cn??{billingApiUrl:ae},onInstrument:F,children:[Fr===1&&(0,B.jsx)("button",{type:"button",onClick:Wo,children:"Retry payment methods"}),je?(0,B.jsxs)(B.Fragment,{children:[jr&&(0,B.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:jr}),(0,B.jsx)(dp,{sessionId:Et,nonce:D?.clientSecret||void 0,billingApiUrl:ae,session:D,submitLabel:de,walletPresentation:H,paymentMethodLayout:ye,moreOptionsLabel:Ee,children:je})]}):(0,B.jsx)(Wi,{sessionId:Et,nonce:D?.clientSecret||void 0,telemetry:a,email:D?.customer?.email||nr?.account?.email,userId:D?.customer?.id||nr?.account?.userId,firstName:D?.customer?.firstName||nr?.account?.firstName,lastName:D?.customer?.lastName||nr?.account?.lastName,totalAmount:D?Math.round((0,le.buildCheckoutDisplayData)(D).total*100):0,currency:D?.currency?.toLowerCase()??"usd",onComplete:b,onError:P,onDecline:E,onCancel:V,error:jr,onErrorChange:ur,showPayPal:T,showStripe:f,walletPresentation:H,enabledPaymentMethods:Fr?[]:X??he?.data.stripe?.enabledPaymentMethods??D?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:he?.data.stripe?.enabledPaymentMethodCountries,showApplePay:v,showGooglePay:Se,layout:oe,paymentMethodLayout:ye,moreOptionsLabel:Ee,theme:ce,buttonsTheme:bt,buttonsStyles:yt,appearance:Lt,cardButtonContent:q,cardBackButtonContent:He,cardTitleContent:Ke,onButtonClick:Pe,onBeforeButtonClick:Y,onBuyerIdentityReady:Gn,enableAVS:K,...tt?{cardFieldOrder:tt}:{},...we===void 0?{}:{showCardBrandIcons:we},...qe===void 0?{}:{cardAutoFocus:qe},...Q?{onCardFieldsReady:Q}:{},...j?{onCardFieldsFailed:j}:{},...fe===void 0?{}:{cardFieldsTimeoutMs:fe},...J?{cardPreFormSlot:J}:{},avsLayout:ft,country:D?.customer?.country,city:D?.customer?.city,state:D?.customer?.state,onCountryChange:W,onZipChange:w,avsCheck:!!K,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:Qs(je,oe),className:ve,submitLabel:de,directPaypal:qt,isSubscription:D?.mode==="subscription",session:D,dataAttachmentPending:dn,dataAttachmentRequiresIdentity:Dr,debug:M})]},A)}),jt]})}function dp({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,paymentMethodLayout:d,moreOptionsLabel:p,children:y}){return(0,B.jsx)(B.Fragment,{children:S.default.Children.map(y,b=>{if(!S.default.isValidElement(b))return b;let P=b.props,h={};return P.sessionId||(h.sessionId=e),!P.nonce&&t&&(h.nonce=t),P.billingApiUrl||(h.billingApiUrl=r),P.submitLabel===void 0&&a!==void 0&&(h.submitLabel=a),P.walletPresentation===void 0&&(h.walletPresentation=s),P.paymentMethodLayout===void 0&&d!==void 0&&(h.paymentMethodLayout=d),P.moreOptionsLabel===void 0&&p!==void 0&&(h.moreOptionsLabel=p),n?.customer&&(P.email||(h.email=n.customer.email),P.userId||(h.userId=n.customer.id),P.firstName||(h.firstName=n.customer.firstName),P.lastName||(h.lastName=n.customer.lastName)),Object.keys(h).length===0?b:S.default.cloneElement(b,h)})})}function up({onButtonClick:e,paymentMethodLayout:t,showPayPal:r,showStripe:n=!0,showApplePay:a,showGooglePay:s,theme:d,buttonsTheme:p,buttonsStyles:y,cardButtonContent:b,cardBackButtonContent:P,cardTitleContent:h}){let[E,V]=(0,S.useState)(!1),W=(0,S.useMemo)(()=>(0,le.resolveTheme)(d),[d]),w=(0,S.useMemo)(()=>{let v=W?.buttonsLayout??(0,le.resolveButtonsLayoutTheme)(p);return y?{...v,...y,cardButton:{...v.cardButton,...y.cardButton},cardFormContainer:{...v.cardFormContainer,...y.cardFormContainer},backButton:{...v.backButton,...y.backButton},backButtonIcon:{...v.backButtonIcon,...y.backButtonIcon},submitButton:{...v.submitButton,...y.submitButton},title:{...v.title,...y.title}}:v},[W,p,y]),T=W?.buttonsLayout?.cardButton?.borderRadius??W?.appearance.variables?.borderRadius??8,f=v=>(0,B.jsx)("div",{style:{height:v,borderRadius:T,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),H=b===void 0?{boxSizing:"border-box",height:qo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let v=w.cardInputBorder??"#e5e7eb",Se=w.cardInputBackground??"white",M=na(P),oe=na(h);return(0,B.jsxs)("div",{style:{backgroundColor:w.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...w.cardFormContainer},children:[(0,B.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,B.jsxs)("button",{type:"button",onClick:()=>V(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:M?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...w.backButton},children:[(0,B.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...w.backButtonIcon},children:(0,B.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,B.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,B.jsx)(aa,{content:P})]}),oe?(0,B.jsx)("div",{style:{flex:1}}):(0,B.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...w.title},children:(0,B.jsx)(Ta,{content:h})})]}),(0,B.jsx)("div",{style:{backgroundColor:Se,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsxs)("div",{style:{display:"flex"},children:[(0,B.jsx)("div",{style:{flex:1,backgroundColor:Se,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsx)("div",{style:{flex:1,backgroundColor:Se,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,B.jsx)("div",{style:{backgroundColor:Se,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...w.submitButton,opacity:.5}}),(0,B.jsx)("style",{children:`
38
+ `}),Ra&&U&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Je?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:y,style:{display:"inline-flex",alignItems:"center",gap:Cs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.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",...rt.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)(aa,{content:G})]}),zl?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...rt.title},children:(0,l.jsx)(Ma,{content:K})})]}),!Ra&&!zl&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:bs,order:Je?-3:0,...rt.title},children:(0,l.jsx)(Ma,{content:K})}),Je&&kt&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:kt}),Je&&bo&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:ea,border:`1px solid ${wn(di)}`,borderRadius:sr,padding:"10px"},children:(0,l.jsx)("input",{ref:Me,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:tr,onChange:i=>{Nt("email"),Br.current=i.target.value,on(i.target.value)},onPointerDown:()=>Nt("email"),onKeyDown:()=>Nt("email"),onBlur:()=>{Kn("email")&&ao(!0),Go||os()},disabled:ir,required:!0,"aria-invalid":di||void 0,"aria-describedby":di?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ss}})}),di&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Ea,children:es.empty?"Email address is required":"Enter a valid email address"})]}),P&&(0,l.jsx)("div",{style:{order:Je?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Tt,S=(J=!1)=>({backgroundColor:ea,border:`1px solid ${wn(J)}`,borderRadius:sr,marginTop:"0.5rem",padding:"10px"}),N=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ss}),fe=(0,c.getStateOptions)(i);return(0,l.jsxs)(l.Fragment,{children:[(0,c.isAVSFieldVisible)(P.address_line_1,i)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:S(er("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:ur,onChange:J=>{Nt("line1"),Or.current.addressLine1=!0,jr.current=J.target.value,zr(J.target.value)},onPointerDown:()=>Nt("line1"),onKeyDown:()=>Nt("line1"),onBlur:()=>bn("line1"),disabled:ir,required:!0,"aria-invalid":er("line1")||void 0,"aria-describedby":er("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:N()})}),er("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Ea,children:"Street address is required"})]}),(0,c.isAVSFieldVisible)(P.address_line_2,i)&&(0,l.jsx)("div",{style:S(),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:An,onChange:J=>{Or.current.addressLine2=!0,yr.current=J.target.value,mn(J.target.value)},disabled:ir,"data-testid":"flopay-address-line2",style:N()})}),((0,c.isAVSFieldVisible)(P.city,i)||(0,c.isAVSFieldVisible)(P.state,i))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(P.city,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${wn(er("city"))}`,borderRight:`1px solid ${wn(er("city"))}`,borderBottom:`1px solid ${wn(er("city"))}`,borderLeft:`1px solid ${wn(er("city"))}`,padding:"10px",borderTopLeftRadius:sr,borderBottomLeftRadius:sr,...(0,c.isAVSFieldVisible)(P.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:sr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:qr,onChange:J=>{Nt("city"),Or.current.city=!0,wr.current=J.target.value,fn(J.target.value)},onPointerDown:()=>Nt("city"),onKeyDown:()=>Nt("city"),onBlur:()=>bn("city"),disabled:ir,required:!0,"aria-invalid":er("city")||void 0,"aria-describedby":er("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:N()})}),(0,c.isAVSFieldVisible)(P.state,i)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:ea,borderTop:`1px solid ${wn(er("state"))}`,borderRight:`1px solid ${wn(er("state"))}`,borderBottom:`1px solid ${wn(er("state"))}`,borderLeft:`1px solid ${wn(er("state"))}`,padding:"10px",borderTopRightRadius:sr,borderBottomRightRadius:sr,...(0,c.isAVSFieldVisible)(P.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${wn(er("state")||er("city"))}`}:{borderRadius:sr}},children:fe?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:gn,onChange:J=>{Nt("state"),Or.current.state=!0,$r.current=J.target.value,pr(J.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>bn("state"),disabled:ir,autoComplete:"billing address-level1",required:!0,"aria-invalid":er("state")||void 0,"aria-describedby":er("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...N(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,c.getStateLabel)(i)}),fe.map(J=>(0,l.jsx)("option",{value:J.code,children:J.name},J.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:gn,onChange:J=>{Nt("state"),Or.current.state=!0,$r.current=J.target.value,pr(J.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>bn("state"),disabled:ir,required:!0,"aria-invalid":er("state")||void 0,"aria-describedby":er("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:N()})})]}),er("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Ea,children:"City is required"}),er("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Ea,children:[(0,c.getStateLabel)(i)," is required"]}),((0,c.isAVSFieldVisible)(P.country,i)||(0,c.isAVSFieldVisible)(P.postal_code,i))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:Pe==="column"?"column":"row",gap:Pe==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(P.country,i)&&(0,l.jsx)("div",{style:{flex:Pe==="row"?1:void 0,backgroundColor:ea,borderTop:`1px solid ${ka}`,borderRight:`1px solid ${ka}`,borderBottom:`1px solid ${ka}`,borderLeft:`1px solid ${ka}`,padding:"10px",...Pe==="row"&&(0,c.isAVSFieldVisible)(P.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:sr,borderBottomLeftRadius:sr,borderRight:"none"}:{borderRadius:sr}},children:(0,l.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Tt,onChange:J=>{Or.current.country=!0,Sr.current=J.target.value,St(J.target.value),Vt?.(J.target.value),$r.current="",pr("")},disabled:ir,autoComplete:"billing country","data-testid":"flopay-country",style:{...N(),cursor:"pointer"},children:[Tt===""?(0,l.jsx)("option",{value:"",children:"Select country"}):null,c.COUNTRY_OPTIONS.map(J=>(0,l.jsxs)("option",{value:J.code,children:[J.flag," ",J.name]},J.code))]})}),(0,c.isAVSFieldVisible)(P.postal_code,i)&&(0,l.jsx)("div",{style:{flex:Pe==="row"?1:void 0,backgroundColor:ea,border:`1px solid ${Ld}`,padding:"10px",...Pe==="row"&&(0,c.isAVSFieldVisible)(P.country,i)?{borderRadius:"0",borderTopRightRadius:sr,borderBottomRightRadius:sr}:{borderRadius:sr}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,c.getPostalCodeLabel)(Tt),autoComplete:"billing postal-code",value:lt,onChange:J=>{Nt("zip"),Or.current.zip=!0,Qt.current=J.target.value,yn(J.target.value),xe?.(J.target.value)},onPointerDown:()=>Nt("zip"),onKeyDown:()=>Nt("zip"),onBlur:()=>{Kn("zip")&&Po(!0)},disabled:ir,required:Vr.required,"aria-invalid":ui||void 0,"aria-describedby":ui?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:N()})})]}),ui&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Ea,children:Vr.empty?`${(0,c.getPostalCodeLabel)(i)} is required`:Zu(i)})]})})()}),Je&&jd,Dn&&(0,l.jsx)(ya,{margin:"0.75rem 0",styleOverride:rt.errorBanner,children:Dn})]}),pi={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"},Wl=i=>re?!Y||!Yn?(0,l.jsx)("pre",{"data-testid":i,style:pi,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:pi,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${Y}`,` directPaypalConfigured=${Yn}`,` inAppBrowserDetected=${String(si)}`,` shouldRenderDirectPayPal=${Io}`,` shouldRenderStripePayPal=${To}`,` hasPaypalStripeInstance=${!!cl}`].join(`
39
+ `)}):null,$l=i=>re?!b||!ln?(0,l.jsx)("pre",{"data-testid":i,style:pi,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":i,style:pi,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${b}`,` currency=${ft}`,` amountInCents=${Ca}`,` enabledPaymentMethods: ${JSON.stringify(x??[])}`,` enabledPaymentMethodsProvided=${ba}`,` hasEnabledMethods=${ni}`,` expressMethods: ${JSON.stringify(ai)}`,` walletExpressMethods: ${JSON.stringify(Qo)}`,` paymentElementMethods: ${JSON.stringify(ls)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ii)}`,` hasStripeInstance=${!!ln}`,` shouldRenderWallets=${So}`,` shouldRenderPaymentElement=${Mo}`].join(`
40
+ `)}):null,Hl=ct==="apm-expanding"||ct==="apm-form"||ct==="apm-collapsing",ra;ct==="apm-expanding"?ra=qc:ct==="apm-collapsing"&&(ra=jc);let yi=Kt?Jc(cs,Kt,Ct):null,Kl={label:mt||Tc,open:Xt,onOpen:Ut,color:wo,fontFamily:Kr?.fontFamily};if(ce==="buttons"){let i=ct==="buttons"||ct==="expanding"||ct==="apm-expanding",S=ct==="expanding"||ct==="card"||ct==="collapsing",N=ve===void 0?{boxSizing:"border-box",height:Eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},fe;ct==="expanding"||ct==="apm-expanding"?fe=Gu:(ct==="collapsing"||ct==="apm-collapsing")&&(fe=Ku);let J;ct==="expanding"?J=qc:ct==="collapsing"&&(J=jc);let Le=Ar&&(0,c.placePaymentMethodGroups)(Ar,{canHide:()=>!0,available:xl}),qt={paypal:(0,l.jsxs)(l.Fragment,{children:[Io&&Qe&&(0,l.jsxs)(l.Fragment,{children:[De&&(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)(Ba.Provider,{value:u,children:(0,l.jsx)(Da,{sessionId:e,nonce:t,billingApiUrl:At,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,clientId:Qe.clientId,environment:Qe.environment,currency:ft.toUpperCase(),isSubscription:st,providerObjectType:Mr,approvalPresentation:li==="popup"?void 0:li,onTokenizedBody:tn,onComplete:d,onErrorChange:Ue,onDecline:m,onCancel:w,onTechnicalFailure:Jo,onButtonClick:Se,runBeforeButtonClick:Nn,isProcessing:ir,onLoadStateChange:ys,onInitializationStateChange:ms,session:I,existingOrderId:De?.orderId,debug:re},De?.orderId??"fresh")})]}),To&&(0,l.jsx)(lr.Elements,{stripe:Sa,options:pl,children:(0,l.jsx)(Wc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,onTokenizedBody:tn,onErrorChange:Ue,isProcessing:ir,onButtonClick:Se,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:Rl,placeholderBorderRadius:io,popupCapabilityOwner:u,externalTelemetryContext:Ml,presentationMode:Zo})})]}),wallets:(0,l.jsxs)(l.Fragment,{children:[So?(0,l.jsx)(lr.Elements,{stripe:ln,options:ul,children:(0,l.jsx)($c,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,intentKind:it>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:tn,onErrorChange:Ue,onButtonClick:Se,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:kl,placeholderBorderRadius:io,popupCapabilityOwner:u,externalTelemetryContext:T})}):null,!So&&Tl?(0,l.jsx)("div",{style:{height:Eo,borderRadius:io,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:(0,l.jsx)(l.Fragment,{children:Mo&&(0,l.jsx)(Hc,{sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,paymentElementMethods:ii,stripeInstance:ln,paymentElementBaseOptions:cs,futureUseSession:Ct,onTokenizedBody:tn,onErrorChange:Ue,onButtonClick:Se,onDecline:m,runBeforeButtonClick:Nn,onLoadStateChange:El,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,onExpandApm:M,expandedApmMethod:Kt,themeId:q,buttonAppearance:{backgroundColor:rt.cardButton?.backgroundColor,borderColor:rt.cardInputBorder,textColor:rt.cardButton?.color,borderRadius:io}})}),card:(0,l.jsx)(l.Fragment,{children:Je&&(0,l.jsx)("button",{type:"button",onClick:async()=>{ir||!(await Nn("card")).proceed||(Se?.("card"),C())},disabled:ir,style:{width:"100%",...N,...rt.cardButton,...Ys({themeBundle:$o,resolvedPrimaryColor:wo,resolvedBorderRadius:sr,submitButtonStyle:rt.submitButton,explicitPrimaryColor:Kr?.colorPrimary}),fontSize:rt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ir?"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:ir?.6:1},onMouseEnter:jt=>{!ir&&($o||Kr?.colorPrimary)&&(jt.currentTarget.style.backgroundColor=zd)},onMouseLeave:jt=>{($o||Kr?.colorPrimary)&&(jt.currentTarget.style.backgroundColor=wo)},onMouseDown:jt=>{jt.currentTarget.style.transform="scale(0.985)"},onMouseUp:jt=>{jt.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(oa,{content:ve})})})};return(0,l.jsxs)("form",{onSubmit:hs,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),Te&&(0,l.jsx)(rn,{status:Te,errorMessage:Dn,authorized:te}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!fe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!fe?Xu:{},...fe?{animation:fe,pointerEvents:"none"}:{}},children:[Wl("flopay-direct-paypal-gate-debug"),$l("flopay-stripe-gate-debug"),xr&&Le?(0,l.jsxs)(l.Fragment,{children:[xr.filter(({group:jt})=>Le.inView.includes(jt)).map(({group:jt,key:ot})=>(0,l.jsx)(o.default.Fragment,{children:qt[jt]},ot)),Le.behindLink.length>0&&(0,l.jsx)(Ds,{...Kl,showLink:Le.showLink,children:xr.filter(({group:jt})=>Le.behindLink.includes(jt)).map(({group:jt,key:ot})=>(0,l.jsx)(o.default.Fragment,{children:qt[jt]},ot))})]}):(0,l.jsx)(Ns,{rows:Al,borderRadius:io}),Dn&&ct==="buttons"&&(0,l.jsx)(ya,{margin:"0.25rem 0",styleOverride:rt.errorBanner,children:Dn})]}),Je&&S&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...J?{animation:J}:{},...ct==="collapsing"?{pointerEvents:"none"}:{}},children:ks}),b&&Hl&&Kt&&yi&&ln&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...ra?{animation:ra}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:vs,borderRadius:Rs,..._a,padding:ws},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:ke,style:{display:"inline-flex",alignItems:"center",gap:Cs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.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",...rt.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)(aa,{content:G})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:bs,paddingRight:80,...rt.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Kt)}`})]}),(0,l.jsx)(lr.Elements,{stripe:ln,options:yi,children:(0,l.jsx)(Hs,{method:Kt,sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,onTokenizedBody:tn,onErrorChange:Ue,onDecline:m,onCancel:ke,runBeforeButtonClick:Nn,onButtonClick:Se,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,errorText:Dn})},Kt)]})})]})]})}if(Hl&&Kt&&yi&&ln&&b)return(0,l.jsxs)("form",{onSubmit:hs,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),Te&&(0,l.jsx)(rn,{status:Te,errorMessage:Dn,authorized:te}),(0,l.jsx)("div",{style:{...ra?{animation:ra}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:vs,borderRadius:Rs,..._a,padding:ws},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:ke,style:{display:"inline-flex",alignItems:"center",gap:Cs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:rt.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...rt.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",...rt.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)(aa,{content:G})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:rt.titleFontSize??"1.05rem",color:bs,paddingRight:80,...rt.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(Kt)}`})]}),(0,l.jsx)(lr.Elements,{stripe:ln,options:yi,children:(0,l.jsx)(Hs,{method:Kt,sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,onTokenizedBody:tn,onErrorChange:Ue,onDecline:m,onCancel:ke,runBeforeButtonClick:Nn,onButtonClick:Se,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,errorText:Dn})},Kt)]})})]});let Gl=xd||Ad||Fd,Ia=Ar&&(0,c.placePaymentMethodGroups)(Ar,{canHide:i=>i!=="card",available:xl}),Yl={paypal:(0,l.jsxs)(l.Fragment,{children:[Io&&Qe&&(0,l.jsxs)(l.Fragment,{children:[De&&(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)(Ba.Provider,{value:u,children:(0,l.jsx)(Da,{sessionId:e,nonce:t,billingApiUrl:At,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,clientId:Qe.clientId,environment:Qe.environment,currency:ft.toUpperCase(),isSubscription:st,providerObjectType:Mr,approvalPresentation:li==="popup"?void 0:li,onTokenizedBody:tn,onComplete:d,onErrorChange:Ue,onDecline:m,onCancel:w,onTechnicalFailure:Jo,onButtonClick:Se,runBeforeButtonClick:Nn,isProcessing:ir,onLoadStateChange:ys,onInitializationStateChange:ms,session:I,existingOrderId:De?.orderId,debug:re},De?.orderId??"fresh")})]}),To&&(0,l.jsx)(lr.Elements,{stripe:Sa,options:pl,children:(0,l.jsx)(Wc,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,onTokenizedBody:tn,onErrorChange:Ue,isProcessing:ir,onButtonClick:Se,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:Rl,placeholderBorderRadius:io,popupCapabilityOwner:u,externalTelemetryContext:Ml,presentationMode:Zo})})]}),wallets:(0,l.jsx)(l.Fragment,{children:So&&(0,l.jsx)(lr.Elements,{stripe:ln,options:ul,children:(0,l.jsx)($c,{sessionId:e,nonce:t,email:Bt.email,billingName:Ko||void 0,onBuyerIdentityReady:Sn,billingApiUrl:At,intentKind:it>0?"payment":"setup",expressMethods:Qo,onTokenizedBody:tn,onErrorChange:Ue,onButtonClick:Se,onDecline:m,onTechnicalFailure:Jo,runBeforeButtonClick:Nn,onLoadStateChange:kl,placeholderBorderRadius:io,popupCapabilityOwner:u,externalTelemetryContext:T})})}),apms:(0,l.jsx)(l.Fragment,{children:Mo&&(0,l.jsx)(Hc,{sessionId:e,nonce:t,email:Bt.email,billingName:[Bt.firstName,Bt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:At,paymentElementMethods:ii,stripeInstance:ln,paymentElementBaseOptions:cs,futureUseSession:Ct,onTokenizedBody:tn,onErrorChange:Ue,onButtonClick:Se,onDecline:m,runBeforeButtonClick:Nn,onLoadStateChange:El,isProcessing:ir,submitButtonColor:wo,submitButtonBorderRadius:sr,submitButtonStyle:rt.submitButton,themeId:q,onExpandApm:M,expandedApmMethod:Kt,buttonAppearance:{backgroundColor:rt.cardButton?.backgroundColor,borderColor:rt.cardInputBorder,textColor:rt.cardButton?.color,borderRadius:io}})})};return(0,l.jsxs)("form",{onSubmit:hs,className:W,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ha,{}),Te&&(0,l.jsx)(rn,{status:Te,errorMessage:Dn,authorized:te}),xr===null?(0,l.jsx)(Ns,{rows:Al,borderRadius:io}):(0,l.jsxs)(l.Fragment,{children:[Ur&&Je&&ks,Ur&&Je&&Gl&&(0,l.jsx)(Ga,{label:"or pay another way"}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Wl("flopay-direct-paypal-gate-debug-default"),$l("flopay-stripe-gate-debug-default"),xr.map(({group:i,key:S})=>i==="card"||!Ia?.inView.includes(i)?null:(0,l.jsx)(o.default.Fragment,{children:Yl[i]},S)),Ia&&Ia.behindLink.length>0&&(0,l.jsx)(Ds,{...Kl,showLink:Ia.showLink,children:xr.map(({group:i,key:S})=>Ia.behindLink.includes(i)&&i!=="card"?(0,l.jsx)(o.default.Fragment,{children:Yl[i]},S):null)})]}),!Ur&&Je&&Gl&&(0,l.jsx)(Ga,{label:"or pay with card"}),!Ur&&Je&&ks]})]})}var O=require("react/jsx-runtime"),zo=44,rl="flopay_checkout_saved_payment_resume",sp="paypal_resume_nonce_missing",Ki=new Map,$i=new Map;function Zc(e,t){t.settled&&t.consumers===0&&Ki.get(e)===t&&Ki.delete(e)}function lp(e,t,r){let n=$i.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),s={attempt:a,sdkGeneratedIdempotencyKey:t};$i.set(e,s);let d=()=>{$i.get(e)===s&&$i.delete(e)};return a.then(d,d),a}function Za(e){return new Promise(t=>setTimeout(t,e))}function Hi(e,t,r){let n=Ri({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:se.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Qa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Js(e,t,r,n,a,s){let d=Hi(e,t,r);d.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...s,...a==="session_read"?{requestCategory:"session_read"}:{}}),Qa(d)}function Qc(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 ed(e,t,r,n,a){let s=(0,se.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 se.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof se.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 Zs(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,se.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var cp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function dp(e){return new mo.FloPay(cp,{publishableKey:"provider_unavailable",...e})}async function Qs(e,t){let{publishableKey:r,paypalPublishableKey:n}=Bs(e);return{...await Os({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function nl(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function up(){if(!nl())return null;try{let e=window.sessionStorage.getItem(rl);return e?JSON.parse(e):null}catch{return null}}function td(e){if(nl())try{window.sessionStorage.setItem(rl,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function el(){if(nl())try{window.sessionStorage.removeItem(rl)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function pp(){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 rd(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 tl(e,t){return(0,se.resolveCheckoutLogLayout)(!!e,t)}function yp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function nd(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function mp(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 Gi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:s,locale:d,loading:p,error:m,onComplete:w,onError:h,onInstrument:g,onDecline:_,onCancel:V,onCountryChange:W,onZipChange:k,showPayPal:A=!0,showStripe:f=!0,walletPresentation:H="auto",enabledPaymentMethods:Y,showApplePay:b=!0,showGooglePay:be=!0,debug:x=!1,layout:oe,paymentMethodLayout:ge,moreOptionsLabel:Ie,theme:ce,buttonsTheme:Rt,buttonsStyles:mt,cardButtonContent:q,cardBackButtonContent:Ve,cardTitleContent:We,showSecurityFooter:Ne,onButtonClick:ve,onBeforeButtonClick:G,enableAVS:K,cardFieldOrder:Ze,showCardBrandIcons:Se,cardFieldPlaceholders:qe,cardAutoFocus:Z,onCardFieldsReady:j,onCardFieldsFailed:he,cardFieldsTimeoutMs:X,cardPreFormSlot:Pt,avsLayout:pe,submitLabel:we,className:Ae,initialErrorMessage:Ce=null,initialPayPalOrderId:kt,children:Pe,checkoutMode:Be,confirmLabel:at,renderConfirmButton:yt,onSessionCompleted:Mt}){let le=(0,se.resolveBillingApiUrl)(n),It=(0,R.useMemo)(()=>(0,se.resolveTheme)(ce),[ce]),Vt=s??It?.appearance,xe=r?"embedded_checkout":"standard_checkout",Oe=tl(Pe,oe),[Ke,vt]=(0,R.useState)(null),[it,ft]=(0,R.useState)(null),Lt=(0,R.useRef)(null),Qe=(0,R.useRef)(null),st=(0,R.useRef)(0),[de,Ot]=(0,R.useState)(null),et=(0,R.useRef)(null),[re,v]=(0,R.useState)(null),Q=(0,R.useMemo)(()=>r?(0,wt.serializeCreateParams)(r):"",[r]),ee=r?`create:${Q}`:`session:${e??""}`,$=nd(re),nt=(0,R.useRef)(new Set),u=(0,R.useRef)(ee),F=(0,R.useRef)(ee);Bo(()=>{F.current=ee,u.current!==ee&&(u.current=ee,nt.current.clear())},[ee]);let D=(0,R.useCallback)(B=>{if(F.current===ee){if(xs.FLO_INSTRUMENT_ONCE_NAMES.has(B.name)){if(nt.current.has(B.name))return;nt.current.add(B.name)}(0,He.invokeMerchantCallback)(()=>g?.(B))}},[ee,g]),L=pa(D,ee),T=(0,R.useRef)(!1),I=(0,R.useCallback)(B=>{if(T.current)return;let U=B.gateway||!$?B:{...B,gateway:$};D(U)},[D,$]);(0,R.useEffect)(()=>{L({class:"lifecycle",name:"checkout.mount"})},[L]);let[Ct,Mr]=(0,R.useState)(e??""),bt=e??Ct,un=r?"":bt,[gt,vr]=(0,R.useState)(!0),[At,Ar]=(0,R.useState)(null),[Cr,Xt]=(0,R.useState)(0),[Jr,xr]=(0,R.useState)("full"),[Ur,pn]=(0,R.useState)(!1),[Fr,Wt]=(0,R.useState)(Ce),[br,Tt]=(0,R.useState)(null),[St,lt]=(0,R.useState)(null),[yn,ur]=(0,R.useState)(!1),[zr,An]=(0,R.useState)(void 0),[mn,qr]=(0,R.useState)(""),[fn,gn]=(0,R.useState)(!1),[pr,tr]=(0,R.useState)(!1),[on,Zr]=(0,R.useState)(!1),rr=(0,R.useRef)(null),Qt=(0,R.useRef)(0),Sr=(0,R.useRef)(void 0),[jr,yr]=(0,R.useState)("loading"),[wr,$r]=(0,R.useState)(0),Br=(0,R.useRef)(!1),Or=(0,R.useRef)(!1),P=(0,R.useRef)(!1),xt=(0,R.useRef)(null),te=(0,R.useRef)(null),ae=(0,R.useMemo)(()=>({checkoutMode:Be??Jr,layout:yp(Pe,oe)}),[Be,Pe,Jr,oe]),zt=(0,R.useRef)(w);zt.current=w;let Ft=(0,R.useRef)(h);Ft.current=h;let nr=(0,R.useRef)(_);nr.current=_;let Xe=(0,R.useCallback)(B=>Ii(xt,async U=>{try{return await B(U)}catch(ne){throw U.aborted?ma(ne):ne}}),[]);(0,R.useEffect)(()=>()=>{xt.current?.abort(),xt.current=null},[]);let mr=(0,R.useCallback)((B,U)=>{Lt.current=B,ft(B),et.current=U,Ot(U)},[]),Je=(0,R.useCallback)(()=>{let B=Qe.current;B&&(Qe.current=null,B.destroy())},[]);(0,R.useEffect)(()=>{Er(it)?.setCheckoutContext(ae),de&&de!==it&&Er(de)?.setCheckoutContext(ae)},[it,de,ae]);let no=(0,R.useRef)(Mt);no.current=Mt;let go=(0,R.useCallback)(B=>{yr(B),!(B!=="exhausted"||P.current)&&(P.current=!0,Ft.current?.(new se.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),jo=(0,R.useCallback)(()=>{yr("retrying"),$r(B=>B+1)},[]);(0,R.useEffect)(()=>{yr("loading"),$r(0),P.current=!1},[bt]),(0,R.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:se.SDK_VERSION,checkout_type:xe,checkout_layout:Oe,billing_api_url:le})},[Oe,xe,le]);let xn=(0,R.useMemo)(()=>r?(0,wt.serializeCreateParams)(r,!0):"",[r]),hn=(0,R.useMemo)(()=>mn===xn?zr:void 0,[zr,mn,xn]),an=(0,R.useMemo)(()=>r?Is(r,hn):void 0,[r,hn]),Qr=Be??an?.checkoutMode??"full",or=(0,R.useMemo)(()=>an?{...an,checkoutMode:Qr}:void 0,[an,Qr]);(0,R.useEffect)(()=>{An(void 0),qr(xn),Sr.current=void 0,rr.current=null,Zr(!1)},[xn]),(0,R.useEffect)(()=>{Wt(Ce)},[Ce]);let Fn=(0,R.useCallback)((B,U,ne)=>{(0,He.invokeMerchantCallback)(()=>{nr.current?.(kr(B,U,ne))})},[]),Rr=(0,R.useCallback)(async(B,U)=>{Wt(null),lt(null),ur(!1),Tt("processing");let ne=U?.sessionId??B.id,me=B.clientSecret||t,Ut=nd(B),Jt=Lt.current??et.current,Fe=Er(Jt),dt=Jt?null:Hi(le,a,ae),z={log:Me=>{Fe?Fe.log(Me):dt?.log(Me)},error:Me=>{Fe?Fe.error(Me):dt?.error(Me)},terminal:Me=>{Fe?Fe.terminal(Me):dt?.terminal(Me)},performance:Me=>{Fe?Fe.performance(Me):dt?.performance(Me)},now:()=>Fe?.now()??dt?.now()??0,elapsed:Me=>Fe?.elapsed(Me)??Math.max(0,(dt?.now()??Me)-Me)},Ge=z.now(),Re=!!(U?.initialAutoProcessingError||U?.initialAutoProcessingPending),C=!1,y,M=()=>{C||(C=!0,Re=!0,y=z.now(),z.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ke=!1,Te=()=>{ke||(ke=!0,z.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),z.performance({stage:"processing",durationMs:z.elapsed(Ge),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),y!==void 0&&z.performance({stage:"recovery",durationMs:z.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}))};z.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),T.current=!0;try{z.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{T.current=!1}L({class:"lifecycle",name:"payment.processing.started",provider:Ut}),Re&&M();let ie;try{let Me=kc(U?.initialAutoProcessingError),Ee=U?.initialAutoProcessingError?.type==="3ds_required"&&!(0,se.isMerchantAuthRequired)(U.initialAutoProcessingError)&&!U.initialAutoProcessingError.threeDSecureToken&&U.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:U.initialAutoProcessingError.nextActionRedirectUrl}:null,$t,Ht=ut=>{M();let ue=ja(le,ne,B,a!==!1);return Xe(ye=>fa(ut,{billingApiUrl:le,sessionId:ne,nonce:me,session:B,signal:ye,...ue.telemetry?{challengeTelemetry:ue.telemetry}:{}})).finally(ue.release)};if(Ee)$t=await Ht(Ee);else if(Me)M(),Me.type==="paypal_redirect_required"&&te.current?.publishableKey&&td({sessionId:ne,publishableKey:te.current.publishableKey,paypalPublishableKey:te.current.paypalPublishableKey,nonce:me}),$t=await Xe(ut=>Mi(Me,{flopay:Lt.current,paypalFlopay:et.current,attempt3DS:U?.attempt3DS,billingApiUrl:le,sessionId:ne,session:B,telemetry:!1,signal:ut})),Me.type==="paypal_redirect_required"&&el();else if(U?.initialAutoProcessingPending){let ut=U.initialAutoProcessingPending,ue=new mo.PaymentAPI(le,{telemetry:!1}),ye=await Xe(De=>ue.waitForCheckoutSessionCompletion(ut.sessionId,{initialDelayMs:ut.retryAfterMs,nonce:me,statusUrl:ut.statusUrl,signal:De})),$e=ko(ye,B),tt=ye.autoProcessingError?.type==="3ds_required"&&ye.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ye.autoProcessingError.nextActionRedirectUrl}:null;if(tt)$t=await Ht(tt);else{if(!lo($e))throw sa($e);$t=so($e,ne)}}else{if(U?.initialAutoProcessingError)throw Qn(U.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:U.initialAutoProcessingError.checkoutMethod});if(U?.fromCreateSession)return U?.fallbackToFull&&(xr("full"),rd("full")),!1;{let ut=await ga({billingApiUrl:le,sessionId:ne,session:B,nonce:me,telemetry:!1});ut.type==="success"?$t=ut.result:ut.type==="next_action_required"?$t=await Ht(ut):(M(),ut.type==="paypal_redirect_required"&&te.current?.publishableKey&&td({sessionId:ne,publishableKey:te.current.publishableKey,paypalPublishableKey:te.current.paypalPublishableKey,nonce:me}),$t=await Xe(ue=>Mi(ut,{flopay:Lt.current,paypalFlopay:et.current,attempt3DS:U?.attempt3DS,billingApiUrl:le,sessionId:ne,session:B,telemetry:!1,signal:ue})),ut.type==="paypal_redirect_required"&&el())}}ne&&(0,jn.markSessionRecentlyCompleted)(ne),Te(),Re&&(z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),z.terminal({outcome:$t.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),ur($t.status==="authorized"),Tt("success"),await Za(600),ie=()=>zt.current?.($t)}catch(Me){let Ee=Ro(Va(Me),ne);if(Ee.code==="three_ds_aborted")return!1;let $t=Ee.checkoutMethod??qa;Wt(Ee.message),lt(Ee.message),ur(!1),U?.fallbackToFull&&(z.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),xr("full"),rd("full")),Te();let Ht=Ee.statusCode===void 0?void 0:(0,se.telemetryStatusClass)(Ee.statusCode,"unknown"),ut=Ht==="4xx"?{requestCategory:"process_payment",statusClass:Ht}:{},ue=Ht===void 0||Ht==="4xx";if((0,se.isExpectedPaymentDecline)(Ee))z.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ut});else if(ue&&(Ee.telemetryOutcome==="validation_rejected"||Ee.type==="validation_error"))z.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ut});else{let tt=(0,se.classifyTelemetryFailure)(Me,Re?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),De=Ee.telemetryRequestCategory??"process_payment";T.current=!0;try{z.error({...tt,...Ee.telemetryFailureCategory?{failureCategory:Ee.telemetryFailureCategory}:{},stage:Re?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:De})}finally{T.current=!1}L({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:De,provider:Ut})}return(0,se.isDeclineCallbackFailure)(Ee)?Fn($t,Ee,{code:Ee.code,declineCode:Ee.declineCode}):(0,He.invokeMerchantCallback)(()=>Ft.current?.(Ee)),Tt("error"),await Promise.allSettled([Za(400),U?.ensureProvidersReady?U.ensureProvidersReady():Promise.resolve()]),Re&&(z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Te(),dt&&Qa(dt),Tt(null),lt(null)}return(0,He.invokeMerchantCallback)(ie),!0},[Fn,L,t,le,Xe,a,ae]);(0,R.useEffect)(()=>{if(typeof window>"u"||Or.current)return;let B=new URLSearchParams(window.location.search),U=B.get("payment_intent_client_secret");if(!U)return;let ne=up();ne&&(Or.current=!0,(async()=>{await Promise.resolve();let me,Ut=0;Wt(null),lt(null),Tt("processing"),pn(!0);try{if(B.get("redirect_status")==="failed")throw Object.assign(new se.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Jt,paypalFlopay:Fe}=await Os({publishableKey:ne.publishableKey,paypalPublishableKey:ne.paypalPublishableKey,billingApiUrl:le,locale:d,telemetry:a});me=Er(Fe??Jt),me?.setCheckoutContext(ae),Ut=me?.now()??0,me?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),me?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let dt=(Fe??Jt)?.getRawProvider();if(!dt)throw Object.assign(new se.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:z,error:Ge}=await dt.retrievePaymentIntent(U);if(Ge)throw Object.assign(new se.FloPayError(Ge.message??"Failed to retrieve PayPal payment status.","api_error",{code:Ge.code}),{checkoutMethod:"paypal"});let Re=sc(z?.status);if(!z||Re==="failed")throw Object.assign(new se.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let C=typeof z.payment_method=="string"?z.payment_method:z.payment_method?.id,y=Re;if(ne.sessionId){let M=ne.nonce||t;if(!M)throw Object.assign(new se.FloPayError("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:sp}),{checkoutMethod:"paypal"});let ie=(await new mo.PaymentAPI(le,{telemetry:!1}).getUnifiedCheckoutSession(ne.sessionId,M)).data.session;if(ie&&ie.status!=="complete"){let Me=await ga({billingApiUrl:le,sessionId:ne.sessionId,session:ie,nonce:M,telemetry:!1,tokenizedData:{id:C??z.id,type:"card",threeDSecureActionResultTokenId:z.id,isPaypal:!0}});if(Me.type!=="success")throw Object.assign(new se.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});y=Me.result.status}}ne.sessionId&&(0,jn.markSessionRecentlyCompleted)(ne.sessionId),me?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),me?.performance({stage:"redirect_resume",durationMs:me.elapsed(Ut),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),me?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Tt("success"),await Za(600),(0,He.invokeMerchantCallback)(()=>zt.current?.({status:y,paymentIntentId:z.id,paymentMethodId:C,checkoutMethod:"paypal"}))}catch(Jt){let Fe=Ro(Va(Jt),ne.sessionId),dt=Fe.checkoutMethod??"paypal",z=(0,se.isExpectedPaymentDecline)(Fe);if(me)me.performance({stage:"redirect_resume",durationMs:me.elapsed(Ut),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z?me.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):me.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(z){let Ge=Hi(le,a,ae);Ge.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Qa(Ge)}else Js(le,a,ae,"REDIRECT_RESUME_FAILED","redirect_resume");Wt(Fe.message),lt(Fe.message),(0,se.isDeclineCallbackFailure)(Fe)?Fn(dt,Fe,{code:Fe.code,declineCode:Fe.declineCode}):(0,He.invokeMerchantCallback)(()=>Ft.current?.(Fe)),Tt("error"),await Za(400)}finally{el(),pp(),Tt(null),lt(null),pn(!1)}})())},[Fn,d,t,le,a,ae]);let $n=(0,R.useRef)(null),ht=(0,R.useMemo)(()=>or?(0,wt.serializeCreateParams)(or):"",[or]),Vr=(0,R.useRef)(or);Vr.current=or,(0,R.useEffect)(()=>{Mr(e??"")},[e]),(0,R.useEffect)(()=>{Br.current=!1,Wt(Ce),lt(null),ur(!1),Tt(null)},[ht,Ce,e]);async function Bn(B,U,ne){let me=Hi(le,a,ae),Ut=new mo.PaymentAPI(le,{telemetry:!1}),Jt=!1;try{let Fe=B.idempotencyKey===void 0?void 0:(0,se.resolveIdempotencyKey)(B.idempotencyKey),dt=(0,wt.readCachedInlineSession)(U,ne),z=(0,wt.readCachedInlineIdempotencyKey)(U,ne);dt?.canonicalIdentity===ne&&z&&z.canonicalIdentity===void 0&&((0,wt.persistCachedInlineIdempotencyKey)(U,ne,z.idempotencyKey),z={...z,canonicalIdentity:ne});let Ge=Fe??(z?.canonicalIdentity===ne?z.idempotencyKey:void 0),Re,C=!1;me.log({name:dt?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let y=dt?.sid??null,M=null,ke,Te,ie=!1;if(y)try{M=await Ut.getUnifiedCheckoutSession(y,dt?.nonce),dt&&dt.canonicalIdentity===void 0&&((0,wt.legacyCachedSessionMatchesDraft)(M.data.session,B)?((0,wt.persistCachedInlineSession)(U,ne,y,dt.nonce??M.data.session?.clientSecret),z&&z.canonicalIdentity===void 0&&((0,wt.persistCachedInlineIdempotencyKey)(U,ne,z.idempotencyKey),Ge??(Ge=z.idempotencyKey))):((0,wt.clearCachedInlineCheckout)(U,ne),z=null,Ge=Fe,y=null,M=null));let Ee=M?.data.session?.status,$t=M?.data.session,Ht=$t?.clientSecret||dt?.nonce;if(y&&$t?.buyerIdentified===!1&&Ht&&(Te=ia(Ut,y,Ht,B.account)),y&&M&&Ee==="complete"){if((0,jn.wasSessionRecentlyCompleted)(y))return{sid:y,result:M};(0,wt.clearCachedInlineCheckout)(U,ne),y=null,M=null,C=!0}}catch{me.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),dt?.canonicalIdentity===void 0?((0,wt.clearCachedInlineCheckout)(U,ne),Ge=Fe):(0,wt.clearCachedInlineSession)(U,ne),y=null}if(!y){!Fe&&(C||!Ge)&&(Ge=(0,se.resolveIdempotencyKey)(),Re=Ge),Ge&&(0,wt.persistCachedInlineIdempotencyKey)(U,ne,Ge);let Ee=me.now(),$t=0;me.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ht={...B,idempotencyKey:Ge,avsCheck:!!K,avsConfig:typeof K=="object"?K:void 0,checkoutType:"embedded_checkout",checkoutLayout:tl(Pe,oe)};Object.defineProperty(Ht,mo.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ye=>{$t=Math.max($t,ye)}}});let ut=()=>{Qc(me,"session_create",Ee,$t)},ue=ye=>{ed(me,ye,"session_create",Ee,$t)&&L({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(B.checkoutMode==="confirm"||B.checkoutMode==="auto")&&Sc();try{if((0,se.isDetachedSessionEligible)(Ht)){let ye=await Ut.createDetachedSession(Ht);ye.claimed.catch(()=>{}),M=ye.shell,y=ye.sessionId,Te=ye.claim;let $e=me.now();me.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ke=ye.claimed.then(tt=>{let De=tt.data.session?.id??ye.sessionId;return De&&(0,wt.persistCachedInlineSession)(U,ne,De,tt.data.session?.clientSecret??ye.nonce),Qc(me,"session_claim",$e),ut(),tt},tt=>{throw(0,wt.clearCachedInlineSession)(U,ne),ed(me,tt,"session_claim",$e,0)&&L({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),tt}).finally(()=>Qa(me)),ke.catch(()=>{}),Jt=!0,me.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),me.performance({stage:"session_shell",durationMs:me.now()-Ee,durationMode:"machine",requestCategory:"session_create",attempt:$t,statusClass:"2xx",paymentMethodCategory:"card"})}else M=await Ut.createAndFetchSession(Ht),ut()}catch(ye){throw ue(ye),ye}y=M.data.session?.id??y??"",y&&!ke&&(0,wt.persistCachedInlineSession)(U,ne,y,M.data.session?.clientSecret)}let Me=M?.data.session;return!Te&&y&&Me?.buyerIdentified===!1&&Me.clientSecret&&(Te=ia(Ut,y,Me.clientSecret,B.account)),{sid:y??"",result:M,sdkGeneratedIdempotencyKey:Re,...ke?{claimed:ke}:{},...Te?{claim:Te}:{},...ie?{claimRequiresIdentity:!0}:{}}}finally{Jt||Qa(me)}}let oo=(0,R.useRef)(Bn);Bo(()=>{oo.current=Bn},[Bn]);let sn=(0,R.useCallback)(async(B,U)=>{let ne=Vr.current;if(!ne)throw new se.FloPayError("createSession is required to bootstrap checkout.","validation_error");let me=Is(ne,B),Ut=(0,wt.serializeCreateParams)(me),Jt=(0,wt.hashCreateParams)(me),Fe=Ki.get(Ut);if(!Fe){let Ge={canonicalIdentity:Ut,promise:oo.current(me,Jt,Ut),consumers:0,settled:!1};Fe=Ge,Ki.set(Ut,Ge);let Re=()=>{Ge.settled=!0,Zc(Ut,Ge)};Ge.promise.then(Re,Re)}Fe.consumers+=1;let dt=!1,z=()=>{dt||(dt=!0,Fe.consumers-=1,Zc(Ut,Fe))};U?.(z);try{let Ge=await Fe.promise;$n.current=Ut,B&&(qr(xn),An(Me=>tc(Me,B)));let{sid:Re,result:C,claimed:y,claim:M,claimRequiresIdentity:ke}=Ge;if(Sr.current=M,Zr(ke===!0),vt(C),C.data.session&&v(C.data.session),Re&&Mr(Re),y){Qt.current+=1;let Me=Qt.current;rr.current=y,tr(!0),y.then(Ee=>{Qt.current===Me&&(rr.current===y&&(rr.current=null),vt(Ee),Ee.data.session&&v(Ee.data.session),tr(!1),Zr(!1))},Ee=>{Qt.current===Me&&(rr.current===y&&(rr.current=null),tr(!1),Zr(!1),Ar(Ee instanceof se.FloPayError?Ee:new se.FloPayError(Ee instanceof Error?Ee.message:"Failed to create session","api_error")))})}else Qt.current+=1,rr.current=null,tr(!1),Zr(!1);let{flopay:Te,paypalFlopay:ie}=await Qs(C,{billingApiUrl:le,locale:d,telemetry:a}).catch(Me=>{throw oc(Me,Re||C.data.session?.id)});return mr(Te,ie),vr(!1),Ge}catch(Ge){throw $n.current===Ut&&($n.current=null),Ge}finally{U||z()}},[xn,mr,d,le,a]),Pn=(0,R.useRef)(Rr);Pn.current=Rr;let ho=(0,R.useRef)(sn);ho.current=sn;let Po=(0,R.useCallback)(async B=>{if(!mp(B)||fn)return{sessionId:Ct,session:re};gn(!0);try{let U=await sn(B);return{sessionId:U.sid,session:U.result.data.session??null}}finally{gn(!1)}},[sn,fn,Ct,re]),vn=(0,R.useCallback)(async B=>{let U=Sr.current;if(!U)return;let ne=Qt.current,me=await U(B);Qt.current===ne&&(vt(me),me.data.session&&v(me.data.session))},[]),ao=(0,R.useCallback)(async()=>{await rr.current},[]),Vo=(0,R.useCallback)(async()=>(await ao(),{proceed:!0}),[ao]);(0,R.useEffect)(()=>{let B=!1,U,ne=++st.current;Je(),Ar(null),Xt(0);let me=()=>{B=!0,st.current===ne&&(st.current+=1,Je())},Ut=Vr.current;if(ht&&Ut)return xr(Qr),vr(!1),$n.current===ht?me:(v(rc(Ut,Be)),(async()=>{let dt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),z=Qr==="auto"&&!Br.current&&!dt;z&&(Wt(null),lt(null),Tt("processing"));let Ge=!1;try{let Re=await ho.current(void 0,ke=>{U=ke});Ge=!0;let C=Re.result.data.session??null;te.current=Bs(Re.result);let y=Zs(Re.result),M=(0,jn.wasSessionRecentlyCompleted)(Re.sid||C?.id);if(!B&&z&&C&&!y&&!M){Br.current=!0,await lp(ht,Re.sdkGeneratedIdempotencyKey,()=>Pn.current(C,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Re.result.autoProcessingError,initialAutoProcessingPending:Re.result.autoProcessingPending,autoProcessingAttempted:Re.result.autoProcessingAttempted,sessionId:Re.sid||C.id}));return}!B&&z&&((y||M)&&(Br.current=!0),Tt(null),lt(null))}catch(Re){if(B)return;let C=hi(Re);if(z&&C==="session_auto_completed"){Br.current=!0,Tt("success"),await Za(600),B||((0,He.invokeMerchantCallback)(()=>{zt.current?.({status:"succeeded"})}),Tt(null),lt(null));return}if(z&&(Tt(null),lt(null)),!Ge){let M=ac(Re),ke=(0,se.toPublicCheckoutInitError)(Re,M?{stage:"provider_load",provider:"stripe",...M}:{stage:"session_request"});(M||!(Re instanceof se.FloPayError))&&(0,He.invokeMerchantCallback)(()=>Ft.current?.(ke)),Ar(ke);return}let y=Re instanceof se.FloPayError?Re:new se.FloPayError(Re instanceof Error?Re.message:"Failed to create session","api_error");Ar(y)}finally{U?.(),U=void 0}})(),()=>{me(),U?.()});vr(!0);async function Jt(){let dt=!1,z=!1,Ge=null;try{let Re=new mo.PaymentAPI(le,{telemetry:!1}),C=await Re.getUnifiedCheckoutSession(bt,t);if(z=!0,Ge=C,B)return;vt(C);let y=C.data.session??null;if(v(y),!y)throw new se.FloPayError("No session data returned","api_error");let M=y.checkoutMode;if(M==="setup")throw new se.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){vr(!1),(0,He.invokeMerchantCallback)(()=>{zt.current?.(so(y,bt)),no.current?.(y.successUrl??"")});return}if(y.status==="complete"){vr(!1),(0,He.invokeMerchantCallback)(()=>{no.current?.(y.successUrl??"")});return}if(y.status==="expired")throw gi(y);dt=!0;let ke=Be??M??"full";xr(ke),Qt.current+=1;let Te=y.clientSecret||t;Sr.current=y.buyerIdentified===!1&&Te?ia(Re,bt,Te,{...y.customer?.id?{userId:y.customer.id}:{}}):void 0,tr(!1),Zr(!1);let ie=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Me=Zs(C);if(ke==="auto"&&!Br.current&&!ie&&!Me){Br.current=!0;let Ee=Fe(C);try{if(await Pn.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Ee,sessionId:bt||y.id}),B)return;await Ee,B||vr(!1);return}catch{if(B)return;await Ee,B||vr(!1);return}}await Fe(C),B||vr(!1)}catch(Re){if(B)return;let C=ec(Re,dt);if(dt&&L({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),C){let{errorCode:Te,stage:ie,...Me}=C;Js(le,a,ae,Te,ie,Me)}if(C?.stage==="provider_load"&&(Be??Ge?.data.session?.checkoutMode??"full")==="full"&&Ql(Ge,A,f)){let Te=dp({billingApiUrl:le,locale:d,telemetry:a});Qe.current=Te,mr(Te,null),Xt(1),vr(!1);return}let y=C?.stage==="provider_load",M="session_request";y?M="provider_load":z&&(M="post_session");let ke=(0,se.toPublicCheckoutInitError)(Re,{stage:M,provider:"stripe",sessionId:bt||void 0});(y||!(Re instanceof se.FloPayError))&&(0,He.invokeMerchantCallback)(()=>Ft.current?.(ke)),Ar(ke),vr(!1)}}async function Fe(dt){let{flopay:z,paypalFlopay:Ge,...Re}=await Qs(dt,{billingApiUrl:le,locale:d,telemetry:a});te.current={publishableKey:Re.publishableKey,paypalPublishableKey:Re.paypalPublishableKey},mr(z,Ge),Xt(0)}return Jt(),me},[Be,ht,Qr,un,t,A,f]);let va=(0,R.useCallback)(async()=>{if(!Ke||Cr!==1)return;let B=st.current;Xt(2);try{let{flopay:U,paypalFlopay:ne}=await Qs(Ke,{billingApiUrl:le,locale:d,telemetry:a});if(st.current!==B)return;Je(),mr(U,ne),Xt(0)}catch(U){if(st.current!==B)return;let{errorCode:ne,stage:me,...Ut}=_s(U);Js(le,a,ae,ne,me,Ut)}},[Je,mr,d,Cr,le,a,ae,Ke]),Cn=!!(bt&&(re?.clientSecret||t)),Hn=Ur||!Cn,vo=(0,R.useCallback)(async()=>{if(!(Ur||!Cn||!re)){pn(!0),Wt(null);try{await Rr(re,{attempt3DS:!0,fallbackToFull:!0,sessionId:bt||re.id})}finally{pn(!1)}}},[bt,Ur,Cn,Rr,re]),Nt=(0,se.resolveDirectPaypalConfig)(Ke?.data.paypal,kt),Kn=Zs(Ke),bn=(0,R.useMemo)(()=>{if(!(!Ke||!re||!Ke.data.stripe?.publishableKey))return{billingApiUrl:le}},[Ke,re,le]),On=!!(r&&!Pe&&oe==="buttons"&&G&&Qr==="full"),Hr=!!(bt&&((0,se.isMountableVaultBlock)(re?.vault)||(0,Un.canRecoverHostedCardForm)(re))),ct=(0,R.useMemo)(()=>({session:re,loading:gt,error:At,checkoutMode:Jr,inlineSessionDraft:or,applyInlineSessionPatch:On?Po:void 0,inlineSessionPatchProcessing:fn,claimPending:pr,claimRequiresIdentity:on,claimBuyerIdentity:vn,waitForDataAttachment:ao}),[re,gt,At,Jr,or,On,Po,fn,pr,on,vn,ao]),ar=!!r&&oe==="buttons"&&!Kn&&!Hr&&(!it||!bn),Kt=br?(0,O.jsx)(rn,{status:br,errorMessage:St,authorized:yn}):null;if(gt&&!Hr){if(p)return(0,O.jsxs)(O.Fragment,{children:[p,Kt]});if(oe==="buttons"){let B=It?.buttonsLayout?.cardButton?.borderRadius??It?.appearance.variables?.borderRadius??8,U=ne=>(0,O.jsx)("div",{style:{height:ne,borderRadius:B,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[A&&U(zo),f&&(b||be)&&U(zo),f&&U(zo),(0,O.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Kt]})}return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,O.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,O.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Kt]})}return At?m?(0,O.jsx)(zn.Provider,{value:ct,children:m(At)}):(0,O.jsx)(zn.Provider,{value:ct,children:(0,O.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:At.message})}):ar?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(zn.Provider,{value:ct,children:(0,O.jsx)(gp,{onButtonClick:ve,paymentMethodLayout:ge,showPayPal:A,showStripe:f,showApplePay:b,showGooglePay:be,theme:ce,buttonsTheme:Rt,buttonsStyles:mt,cardButtonContent:q,cardBackButtonContent:Ve,cardTitleContent:We})}),Kt]}):Kn&&re&&Nt?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(zn.Provider,{value:ct,children:(0,O.jsxs)("div",{className:Ae,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Fr&&(0,O.jsx)(ya,{icon:!1,children:Fr}),jr==="retrying"&&(0,O.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),jr==="exhausted"&&(0,O.jsxs)("div",{role:"alert",children:[(0,O.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,O.jsx)("button",{type:"button",onClick:jo,children:"Retry PayPal"})]}),jr!=="exhausted"&&(0,O.jsx)("div",{"aria-hidden":jr==="retrying"?!0:void 0,style:jr==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,O.jsx)(Pc,{sessionId:bt,nonce:re.clientSecret||void 0,billingApiUrl:le,email:re.customer?.email||or?.account?.email,billingName:[re.customer?.firstName,re.customer?.lastName].filter(Boolean).join(" ")||[or?.account?.firstName,or?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:vn,clientId:Nt.clientId,environment:Nt.environment,currency:(re.currency??"usd").toUpperCase(),isSubscription:re.mode==="subscription",providerObjectType:Nt.providerObjectType,approvalPresentation:Nt.approvalPresentation,existingOrderId:Nt.existingOrderId,onComplete:w,onErrorChange:Wt,onDecline:_,onCancel:V,onButtonClick:ve,runBeforeButtonClick:Vo,onInitializationStateChange:go,allowAutomaticRetry:wr===0,session:re,telemetry:a,telemetryContext:ae,onInstrument:I,debug:x},`${ee}:paypal-init-${wr}`)})]})}),Kt]}):Jr==="confirm"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(zn.Provider,{value:ct,children:(0,O.jsx)(Na,{flopay:it,paypalFlopay:de,options:bn??{billingApiUrl:le},onInstrument:I,children:(0,O.jsxs)("div",{className:Ae,children:[Fr&&(0,O.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Fr}),yt?yt({onConfirm:vo,isProcessing:Hn}):(0,O.jsx)("button",{type:"button",onClick:vo,disabled:Hn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Hn?"not-allowed":"pointer",opacity:Hn?.6:1},children:Ur?"Processing...":at??"Confirm Purchase"})]})},ee)}),Kt]}):(!it||!bn)&&!(Hr&&Jr==="full")?(0,O.jsx)(O.Fragment,{children:Kt}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(zn.Provider,{value:ct,children:(0,O.jsxs)(Na,{flopay:it,paypalFlopay:de,options:bn??{billingApiUrl:le},onInstrument:I,children:[Cr===1&&(0,O.jsx)("button",{type:"button",onClick:va,children:"Retry payment methods"}),Pe?(0,O.jsxs)(O.Fragment,{children:[Fr&&(0,O.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Fr}),(0,O.jsx)(fp,{sessionId:bt,nonce:re?.clientSecret||void 0,billingApiUrl:le,session:re,submitLabel:we,walletPresentation:H,paymentMethodLayout:ge,moreOptionsLabel:Ie,children:Pe})]}):(0,O.jsx)(Wi,{sessionId:bt,nonce:re?.clientSecret||void 0,telemetry:a,email:re?.customer?.email||or?.account?.email,userId:re?.customer?.id||or?.account?.userId,firstName:re?.customer?.firstName||or?.account?.firstName,lastName:re?.customer?.lastName||or?.account?.lastName,totalAmount:re?Math.round((0,se.buildCheckoutDisplayData)(re).total*100):0,currency:re?.currency?.toLowerCase()??"usd",onComplete:w,onError:h,onDecline:_,onCancel:V,error:Fr,onErrorChange:Wt,showPayPal:A,showStripe:f,walletPresentation:H,enabledPaymentMethods:Cr?[]:Y??Ke?.data.stripe?.enabledPaymentMethods??re?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:b,showGooglePay:be,layout:oe,paymentMethodLayout:ge,moreOptionsLabel:Ie,theme:ce,buttonsTheme:Rt,buttonsStyles:mt,appearance:Vt,cardButtonContent:q,cardBackButtonContent:Ve,cardTitleContent:We,onButtonClick:ve,onBeforeButtonClick:G,onBuyerIdentityReady:vn,enableAVS:K,...Ze?{cardFieldOrder:Ze}:{},...Se===void 0?{}:{showCardBrandIcons:Se},...qe===void 0?{}:{cardFieldPlaceholders:qe},...Z===void 0?{}:{cardAutoFocus:Z},...j?{onCardFieldsReady:j}:{},...he?{onCardFieldsFailed:he}:{},...X===void 0?{}:{cardFieldsTimeoutMs:X},...Pt?{cardPreFormSlot:Pt}:{},avsLayout:pe,country:re?.customer?.country,city:re?.customer?.city,state:re?.customer?.state,onCountryChange:W,onZipChange:k,avsCheck:!!K,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:tl(Pe,oe),className:Ae,submitLabel:we,directPaypal:Nt,isSubscription:re?.mode==="subscription",session:re,dataAttachmentPending:pr,dataAttachmentRequiresIdentity:on,debug:x})]},ee)}),Kt]})}function fp({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:s,paymentMethodLayout:d,moreOptionsLabel:p,children:m}){return(0,O.jsx)(O.Fragment,{children:R.default.Children.map(m,w=>{if(!R.default.isValidElement(w))return w;let h=w.props,g={};return h.sessionId||(g.sessionId=e),!h.nonce&&t&&(g.nonce=t),h.billingApiUrl||(g.billingApiUrl=r),h.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),h.walletPresentation===void 0&&(g.walletPresentation=s),h.paymentMethodLayout===void 0&&d!==void 0&&(g.paymentMethodLayout=d),h.moreOptionsLabel===void 0&&p!==void 0&&(g.moreOptionsLabel=p),n?.customer&&(h.email||(g.email=n.customer.email),h.userId||(g.userId=n.customer.id),h.firstName||(g.firstName=n.customer.firstName),h.lastName||(g.lastName=n.customer.lastName)),Object.keys(g).length===0?w:R.default.cloneElement(w,g)})})}function gp({onButtonClick:e,paymentMethodLayout:t,showPayPal:r,showStripe:n=!0,showApplePay:a,showGooglePay:s,theme:d,buttonsTheme:p,buttonsStyles:m,cardButtonContent:w,cardBackButtonContent:h,cardTitleContent:g}){let[_,V]=(0,R.useState)(!1),W=(0,R.useMemo)(()=>(0,se.resolveTheme)(d),[d]),k=(0,R.useMemo)(()=>{let b=W?.buttonsLayout??(0,se.resolveButtonsLayoutTheme)(p);return m?{...b,...m,cardButton:{...b.cardButton,...m.cardButton},cardFormContainer:{...b.cardFormContainer,...m.cardFormContainer},backButton:{...b.backButton,...m.backButton},backButtonIcon:{...b.backButtonIcon,...m.backButtonIcon},submitButton:{...b.submitButton,...m.submitButton},title:{...b.title,...m.title}}:b},[W,p,m]),A=W?.buttonsLayout?.cardButton?.borderRadius??W?.appearance.variables?.borderRadius??8,f=b=>(0,O.jsx)("div",{style:{height:b,borderRadius:A,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),H=w===void 0?{boxSizing:"border-box",height:zo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let b=k.cardInputBorder??"#e5e7eb",be=k.cardInputBackground??"white",x=na(h),oe=na(g);return(0,O.jsxs)("div",{style:{backgroundColor:k.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...k.cardFormContainer},children:[(0,O.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,O.jsxs)("button",{type:"button",onClick:()=>V(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:x?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...k.backButton},children:[(0,O.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...k.backButtonIcon},children:(0,O.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,O.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,O.jsx)(aa,{content:h})]}),oe?(0,O.jsx)("div",{style:{flex:1}}):(0,O.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...k.title},children:(0,O.jsx)(Ma,{content:g})})]}),(0,O.jsx)("div",{style:{backgroundColor:be,border:`1px solid ${b}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsxs)("div",{style:{display:"flex"},children:[(0,O.jsx)("div",{style:{flex:1,backgroundColor:be,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{flex:1,backgroundColor:be,borderTop:"none",borderRight:`1px solid ${b}`,borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,O.jsx)("div",{style:{backgroundColor:be,border:`1px solid ${b}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...k.submitButton,opacity:.5}}),(0,O.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 X={paypal:r&&f(qo),wallets:n&&(a||s)&&f(qo),card:n&&(t?f(qo):(0,B.jsx)("button",{type:"button",onClick:()=>{e?.("card"),V(!0)},style:{width:"100%",...H,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:w.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,...w.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:(0,B.jsx)(oa,{content:b})}))};return(0,B.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[le.DEFAULT_PAYMENT_METHOD_ORDER.map(v=>(0,B.jsx)(S.default.Fragment,{children:X[v]},v)),(0,B.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Tn=require("react/jsx-runtime"),pp=44;function rd(e){return new Promise(t=>setTimeout(t,e))}var nd=15e3;function rl(e,t){return new wr.FloPayError(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function mp(e,t){return new Promise((r,n)=>{let a=()=>n(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(s=>{t.removeEventListener("abort",a),r(s)},s=>{t.removeEventListener("abort",a),n(s)})})}function yp(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function fp(e,t){return e instanceof wr.FloPayError?e:new wr.FloPayError(e instanceof Error?e.message:t,"api_error")}function gp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function hp(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 od({sessionId:e,nonce:t,createSession:r,getSession:n,paymentMethodId:a,checkoutMethod:s,clientId:d,products:p,items:y,subscriptions:b,account:P,successUrl:h,cancelUrl:E,couponCodes:V,tagsData:W,utmMetadata:w,billingApiUrl:T,locale:f,theme:H,appearance:X,buttonsTheme:v,buttonsStyles:Se,onSuccess:M,onError:oe,onDecline:ye,children:Ee,disabled:ce=!1,type:bt="button",style:yt,...q}){let He=(0,ct.useMemo)(()=>(0,wr.resolveBillingApiUrl)(T),[T]),Ke=(0,ct.useMemo)(()=>hp({createSession:r,clientId:d,products:p,items:y,subscriptions:b,account:P,successUrl:h,cancelUrl:E,couponCodes:V,tagsData:W,utmMetadata:w}),[P,E,d,V,r,p,y,b,h,W,w]),[Le,Pe]=(0,ct.useState)(!1),[Y,K]=(0,ct.useState)(null),[tt,we]=(0,ct.useState)(null),[qe,Q]=(0,ct.useState)(!1),[j,fe]=(0,ct.useState)(null),[J,ft]=(0,ct.useState)(null),de=(0,ct.useRef)(!0),ve=(0,ct.useRef)(null),_e=(0,ct.useRef)(null),Me=(0,ct.useRef)(!1),je=(0,ct.useRef)(J),ge=(0,ct.useRef)(M),rt=(0,ct.useRef)(oe),dt=(0,ct.useRef)(ye),ut=(0,ct.useCallback)(_=>Ii(ve,async A=>{try{return await _(A)}catch(Ae){throw A.aborted?ya(Ae):Ae}}),[]);(0,ct.useEffect)(()=>{je.current=J},[J]),(0,ct.useEffect)(()=>{ge.current=M},[M]),(0,ct.useEffect)(()=>{rt.current=oe},[oe]),(0,ct.useEffect)(()=>{dt.current=ye},[ye]),(0,ct.useEffect)(()=>(de.current=!0,()=>{de.current=!1,ve.current?.abort(),_e.current?.abort()}),[]),(0,ct.useEffect)(()=>{if(typeof window>"u")return;let _=A=>{A.key==="Escape"&&ft(null)};return window.addEventListener("keydown",_),()=>{window.removeEventListener("keydown",_)}},[]);let ae=(0,ct.useCallback)((_,A=za)=>{dt.current?.(Cr(A,_,{code:_.code,declineCode:_.declineCode}))},[]),Dt=(0,ct.useCallback)(async _=>{de.current&&(we(null),Q(_.result.status==="authorized"),K("success"),await rd(600),de.current&&(0,Ge.invokeMerchantCallback)(()=>ge.current?.(_)))},[]),Lt=(0,ct.useCallback)(async(_,A)=>{if(!de.current)return;!!A?.emitDecline&&(0,wr.isDeclineCallbackFailure)(_)?ae(_,A?.method):rt.current?.(_),we(_.message),Q(!1),K("error"),await rd(400)},[ae]),Ut=(0,ct.useCallback)(async(_,A,Ae)=>{let te=_.data.session??null;if(!te)throw wo(new wr.FloPayError("No session data returned","api_error"),A);let xe=Ae?.nonce||te.clientSecret||t;if(lo(te)){await Dt({result:so(te,A),session:te,sessionId:te.id||A,autoCompleted:!1});return}if(te.status==="expired")throw wo(gi(te),te.id||A);try{if(_.autoProcessingPending){let I=_.autoProcessingPending,k=new Yi.PaymentAPI(He),U=await ut(At=>k.waitForCheckoutSessionCompletion(I.sessionId,{initialDelayMs:I.retryAfterMs,nonce:xe,statusUrl:I.statusUrl,signal:At})),F=Ro(U,te),x=U.autoProcessingError?.type==="3ds_required"&&!(0,wr.isMerchantAuthRequired)(U.autoProcessingError)&&U.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:U.autoProcessingError.nextActionRedirectUrl}:null;if(x&&A&&xe){let At=qa(He,A,te),Et=await ut(kr=>fa(x,{billingApiUrl:He,sessionId:A,nonce:xe,session:te,signal:kr,telemetry:!0,...At.telemetry?{challengeTelemetry:At.telemetry}:{}})).finally(At.release);await Dt({result:Et,session:te,sessionId:te.id||A,autoCompleted:!1});return}if(U.autoProcessingError)throw eo(U.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:U.autoProcessingError.checkoutMethod});if(!lo(F))throw sa(F);await Dt({result:so(F,A),session:F,sessionId:F.id||A,autoCompleted:!1});return}if(_.autoProcessingError){let I=_.autoProcessingError.nextActionRedirectUrl;if(_.autoProcessingError.type==="3ds_required"&&!(0,wr.isMerchantAuthRequired)(_.autoProcessingError)&&I&&A&&xe){let k=await ut(At=>Rc({billingApiUrl:He,sessionId:A,nonce:xe,nextActionRedirectUrl:I,signal:At}));if(k.status==="declined")throw eo({type:k.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:k.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:_.autoProcessingError.checkoutMethod});let F=await new Yi.PaymentAPI(He).waitForCheckoutSessionCompletion(A,{initialDelayMs:0,nonce:xe}),x=Ro(F,te);if(!lo(x))throw eo({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:_.autoProcessingError.checkoutMethod});await Dt({result:so(x,A),session:x,sessionId:x.id||A,autoCompleted:!1});return}throw eo(_.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:_.autoProcessingError.checkoutMethod})}if(Ae?.fromCreateSession&&_.autoProcessingAttempted===!0)throw eo({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let u=await ga({billingApiUrl:He,sessionId:A??te.id,session:te,nonce:xe});if(u.type==="next_action_required"&&xe){let I=A??te.id,k=qa(He,I,te),U=await ut(F=>fa(u,{billingApiUrl:He,sessionId:I,nonce:xe,session:te,signal:F,telemetry:!0,...k.telemetry?{challengeTelemetry:k.telemetry}:{}})).finally(k.release);await Dt({result:U,session:te,sessionId:te.id||I,autoCompleted:!1});return}if(u.type!=="success")throw eo({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Dt({result:u.result,session:te,sessionId:te.id||A,autoCompleted:!1})}catch(u){let I=te.id||A,k=wo(ja(u),I);if(k.code==="three_ds_aborted")return;if(k.code==="checkout_processing_timeout"){if(!de.current)return;fe(k.message),(0,Ge.invokeMerchantCallback)(()=>rt.current?.(k));return}await Lt(k,{emitDecline:!0,method:k.checkoutMethod??za}),gp(k,I)&&I&&de.current&&ft({sessionId:I,errorMessage:k.message,nonce:xe||void 0,payPalOrderId:k.orderId})}},[t,He,ut,Lt,Dt]),Ie=(0,ct.useCallback)(async _=>{let A=new AbortController;_e.current=A;let Ae=!1,te=setTimeout(()=>{Ae=!0,A.abort()},nd);try{let xe=await mp((async()=>_({signal:A.signal}))(),A.signal);if(!de.current)return null;if(!yp(xe))throw rl("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:xe.sessionId,nonce:xe.nonce}}catch(xe){if(!de.current)return null;throw xe instanceof wr.FloPayError&&xe.code==="session_fetch_failed"?xe:Ae?rl(`getSession did not resolve within ${nd/1e3} seconds.`):rl("Could not fetch the one-click session.",xe)}finally{clearTimeout(te),_e.current===A&&(_e.current=null)}},[]),he=(0,ct.useCallback)(async _=>{if(q.onClick?.(_),_.defaultPrevented||ce||Le||(ft(null),fe(null),Me.current))return;let A=[e,n,Ke].filter(Boolean).length;if(A>1){let Ae=new wr.FloPayError("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await Lt(Ae),de.current&&(K(null),we(null));return}if(A===0){let Ae=new wr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Lt(Ae),de.current&&(K(null),we(null));return}Me.current=!0,Pe(!0),we(null),Q(!1),K("processing");try{let Ae=new Yi.PaymentAPI(He);if(e){let te=await Ae.getUnifiedCheckoutSession(e,t);await Ut(te,e);return}if(n){let te=await Ie(n);if(!te)return;let xe=await Ae.getUnifiedCheckoutSession(te.sessionId,te.nonce);await Ut(xe,te.sessionId,{nonce:te.nonce});return}vc();try{let te=await Ae.createAndFetchSession({...Ke});await Ut(te,te.data.session?.id??null,{fromCreateSession:!0})}catch(te){if(hi(te)==="session_auto_completed"){await Dt({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw te}}catch(Ae){await Lt(wo(fp(Ae,"Automatic payment failed. Please try again."),e))}finally{Me.current=!1,de.current&&(K(null),we(null),Pe(!1))}},[q.onClick,Ke,ce,Ie,n,Le,t,Ut,He,e,Lt,Dt]),gt=(0,ct.useCallback)(_=>{let A=je.current;ft(null),ge.current?.({result:_,session:null,sessionId:A?.sessionId??null,autoCompleted:!1})},[]),Qe=(0,ct.useCallback)(_=>{rt.current?.(_)},[]),Mt=(0,ct.useCallback)(_=>{dt.current?.(_)},[]),nt=(0,ct.useMemo)(()=>(0,wr.resolveTheme)(H),[H]),St=(0,ct.useMemo)(()=>{let _=nt?.buttonsLayout??(0,wr.resolveButtonsLayoutTheme)(v);return Se?{..._,...Se,cardButton:{..._.cardButton,...Se.cardButton}}:_},[nt,v,Se]),ht=(0,ct.useMemo)(()=>{let _=nt?.appearance;return X?_?{..._,...X,variables:{..._.variables,...X.variables}}:X:_},[X,nt]),ne=ht?.variables,$t=ne?.colorPrimary??"#4A49FF",kt=ne?.colorPrimaryHover??(0,Gs.darkenHex)($t,.12),D=ne?.borderRadius??"8px";return(0,Tn.jsxs)(Tn.Fragment,{children:[(0,Tn.jsx)("button",{...q,type:bt,onClick:he,disabled:ce||Le,"aria-busy":Le,style:{width:"100%",...Ee===void 0?{boxSizing:"border-box",height:pp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...St.cardButton,...Ks({themeBundle:nt,resolvedPrimaryColor:$t,resolvedBorderRadius:D,submitButtonStyle:St.submitButton,explicitPrimaryColor:ne?.colorPrimary}),fontSize:St.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ce||Le?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ce||Le?.6:1,...yt},onMouseEnter:_=>{q.onMouseEnter?.(_),!_.defaultPrevented&&!ce&&!Le&&(nt||ne?.colorPrimary)&&(_.currentTarget.style.backgroundColor=kt)},onMouseLeave:_=>{q.onMouseLeave?.(_),!_.defaultPrevented&&(nt||ne?.colorPrimary)&&(_.currentTarget.style.backgroundColor=$t)},onMouseDown:_=>{q.onMouseDown?.(_),_.defaultPrevented||(_.currentTarget.style.transform="scale(0.985)")},onMouseUp:_=>{q.onMouseUp?.(_),_.defaultPrevented||(_.currentTarget.style.transform="scale(1)")},children:(0,Tn.jsx)(oa,{content:Ee})}),j&&(0,Tn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:j}),Y&&(0,Tn.jsx)(an,{status:Y,errorMessage:tt,authorized:qe}),J&&(0,Tn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:_=>{_.target===_.currentTarget&&ft(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,Tn.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,Tn.jsx)(Gi,{sessionId:J.sessionId,nonce:J.nonce,checkoutMode:"full",billingApiUrl:He,locale:f,theme:H,...ht?{appearance:ht}:{},buttonsTheme:v,buttonsStyles:Se,initialErrorMessage:J.errorMessage,initialPayPalOrderId:J.payPalOrderId,cardTitleContent:null,onComplete:gt,onError:Qe,onDecline:Mt})})})]})}var Ji=require("@flopay/js/card-setup"),Zr=require("@flopay/shared"),Zt=require("react");var nl=require("@flopay/shared"),Pp=require("@flopay/shared");function Xi(e){let t=(0,nl.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var ro=require("react/jsx-runtime"),Qa=class extends Zr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function fo(e,t={}){let r=e instanceof Zr.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 Qa(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 ad({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:d,buttonsStyles:p,loading:y=null,onReady:b,onComplete:P,onDecline:h,onCancel:E,onValidation:V,onError:W}){let[w,T]=(0,Zt.useState)(null),[f,H]=(0,Zt.useState)(null),[X,v]=(0,Zt.useState)(null),[Se,M]=(0,Zt.useState)(null),[oe,ye]=(0,Zt.useState)(null),Ee=(0,Zt.useRef)(!1),ce=(0,Zt.useRef)(!1),{vaultTheme:bt,surface:yt,overlayTheme:q}=(0,Zt.useMemo)(()=>Xi({theme:a,appearance:d,buttonsStyles:p}),[a,d,p]),He=(0,Zt.useMemo)(()=>(0,Ha.mergeCardSetupSurface)(yt,s),[yt,s]),Ke=(0,Zt.useRef)(b),Le=(0,Zt.useRef)(W),Pe=(0,Zt.useRef)(P),Y=(0,Zt.useRef)(h),K=(0,Zt.useRef)(E),tt=(0,Zt.useRef)(V),we=(0,Zt.useRef)(!1),qe=(0,Zt.useRef)(!1),Q=(0,Zt.useRef)(0);return Ke.current=b,Le.current=W,Pe.current=P,Y.current=h,K.current=E,tt.current=V,(0,Zt.useEffect)(()=>{let j=Q.current+1;return Q.current=j,()=>{queueMicrotask(()=>{Q.current===j&&(we.current||qe.current||(qe.current=!0,(0,Ge.invokeMerchantCallback)(()=>{K.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Zt.useEffect)(()=>{let j=!0,fe=(0,Zr.resolveBillingApiUrl)(r),J=new Ji.PaymentAPI(fe,{telemetry:n});return T(null),H(null),v(null),we.current=!1,qe.current=!1,(async()=>{try{if(!e.trim())throw new Zr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Zr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ft=await J.getUnifiedCheckoutSession(e,t);if(!j)return;let de=ft.data.session;if(!de||!(0,Zr.isCardSetupCheckoutSession)(de))throw new Zr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let ve=de.vault;(0,Zr.isMountableVaultBlock)(ve)||(ve=await J.getVaultCapture(e,t));let _e=(0,Zr.resolveVaultMountOptions)(ve,{billingApiUrl:fe,sessionId:e,nonce:t});if(!_e)throw new Zr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!j)return;H(_e),T(new Ji.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(ft){if(!j)return;let de=fo(ft);we.current=!0,v(de),(0,Ge.invokeMerchantCallback)(()=>Le.current?.(de))}})(),()=>{j=!1,J.destroy()}},[r,t,e,n]),(0,Zt.useEffect)(()=>{if(!w)return;let j=!1;ce.current=!1,Ee.current=!1;let fe=w.on("submitting",()=>{Ee.current=!0,ye(null),M("processing")}),J=w.on("complete",ve=>{we.current=!0,Ee.current=!1,M("success"),(async()=>(await new Promise(_e=>setTimeout(_e,600)),!ce.current&&(ce.current=!0,(0,Ge.invokeMerchantCallback)(()=>{Pe.current?.({status:"succeeded",sessionId:e,...ve.paymentMethod?{paymentMethod:ve.paymentMethod}:{}})}),j||M(null))))()}),ft=w.on("decline",ve=>{we.current=!0,Ee.current=!1,ye(ve.message??null),M("error"),(0,Ge.invokeMerchantCallback)(()=>{Y.current?.({status:"declined",sessionId:e,...ve.declineReason?{reason:ve.declineReason}:{},...ve.message?{message:ve.message}:{}})}),(async()=>(await new Promise(_e=>setTimeout(_e,400)),j||M(null)))()}),de=w.on("challenge_dismissed",()=>{M(null)});return()=>{j=!0,fe(),J(),ft(),de()}},[w,e]),X?(0,ro.jsx)("div",{role:"alert",children:X.message}):!w||!f?.html?(0,ro.jsx)(ro.Fragment,{children:y}):(0,ro.jsxs)(ro.Fragment,{children:[Se&&(0,ro.jsx)(an,{status:Se,errorMessage:oe,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...q?{theme:q}:{}}),(0,ro.jsx)(Eo,{capture:w,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:bt,containerStyle:He,onReady:()=>{(0,Ge.invokeMerchantCallback)(()=>Ke.current?.())},onValidation:j=>{(0,Ge.invokeMerchantCallback)(()=>tt.current?.(j))},onError:j=>{if(!j)return;Ee.current&&(Ee.current=!1,ye(j),M("error"),setTimeout(()=>M(null),400));let fe=fo(new Error(j),{code:"card_setup_widget_failed",retryable:!0});(0,Ge.invokeMerchantCallback)(()=>Le.current?.(fe))}})]})}var id=require("@flopay/js/card-setup"),Mn=require("@flopay/shared"),sd=require("@paypal/paypal-js"),jo=require("react");var cd=require("react/jsx-runtime");function ld({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:d,customer:{userId:p,email:y},onSubmitting:b,onConfirmed:P,onFailed:h,onAbandoned:E}){let V=(0,jo.useRef)(null),W=(0,jo.useRef)({onSubmitting:b,onConfirmed:P,onFailed:h,onAbandoned:E});W.current={onSubmitting:b,onConfirmed:P,onFailed:h,onAbandoned:E};let[w]=(0,jo.useState)(()=>(0,Zn.detectPayPalEnvironment)().inAppBrowser);return(0,jo.useEffect)(()=>{let T=!0,f,H=new id.PaymentAPI(s,{telemetry:d}),X={userId:p,email:y};return(async()=>{try{let v=await(0,sd.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Se=V.current;if(!T||!Se)return;if(!v?.Buttons)throw new Mn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let M=v.Buttons({createVaultSetupToken:async()=>{W.current.onSubmitting();let oe=await H.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Mn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,Mn.isSettledSessionIntent)(oe))throw(0,Mn.settledSessionIntentError)(n);if(oe.provider!=="paypal"||oe.providerObjectType!=="setup_token")throw new Mn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return oe.providerObjectId},onApprove:async oe=>{let ye=oe.vaultSetupToken;if(!ye)throw new Mn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let Ee=await H.processPayment(X.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:ye,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Mn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:X});if(!Ee.ok)throw new Mn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:Ee.status});T&&W.current.onConfirmed()},onCancel:()=>{T&&W.current.onAbandoned()},onError:oe=>{if(!T)return;let{popupBlocked:ye}=(0,ke.classifyExternalMethodFailure)(oe,{inAppBrowser:w,handoffObserved:!1});W.current.onFailed(ye?new Error((0,ke.buildExternalMethodRecoveryMessage)("PayPal",!0,w)):oe,{code:ye?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>M.close(),await M.render(Se)}catch(v){if(!T)return;W.current.onFailed(v,{code:"paypal_unavailable",retryable:!0})}})(),()=>{T=!1,f?.().catch(()=>{}),H.destroy()}},[s,e,r,y,t,w,a,n,d,p]),(0,cd.jsx)("div",{ref:V,"data-flopay-paypal-setup":""})}var ud=require("@flopay/js/card-setup"),An=require("@flopay/shared"),no=require("@stripe/react-stripe-js"),pd=require("@stripe/stripe-js"),Qr=require("react");var Gr=require("react/jsx-runtime"),md={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"}},ol=new Map;function vp(e){let t=ol.get(e);if(t)return t;let r=(0,pd.loadStripe)(e).catch(n=>{throw ol.delete(e),n});return ol.set(e,r),r}function Cp(e){return e?(0,An.toStripeAppearance)(e):void 0}function bp(e){return(0,ke.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function dd(e){return e==="paypal"?"PayPal":(0,An.getStripeMethodDisplayName)(e)}function Sp(){return typeof window>"u"?"":window.location.href}var wp={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function yd(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:d}=e,[p]=(0,Qr.useState)(()=>vp(t)),y=(0,Qr.useMemo)(()=>{let b=Cp(d),P=(0,An.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:md[r]?.types??[r],...P?{setupFutureUsage:P}:{},...b?{appearance:b}:{}}},[d,n,a,s,r]);return(0,Gr.jsx)(no.Elements,{stripe:p,options:y,children:(0,Gr.jsx)(Rp,{...e})})}function Rp({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:d,themeId:p,buttonsLayout:y,onSubmitting:b,onConfirmed:P,onDeclined:h,onFailed:E,onValidation:V,onUnavailable:W}){let w=(0,no.useStripe)(),T=(0,no.useElements)(),[f,H]=(0,Qr.useState)(!1),[X,v]=(0,Qr.useState)("loading"),[Se,M]=(0,Qr.useState)(!1),[oe,ye]=(0,Qr.useState)(!1),Ee=(0,Qr.useRef)(!1),[ce]=(0,Qr.useState)(()=>(0,Zn.detectPayPalEnvironment)()),[bt,yt]=(0,Qr.useState)(!1),q=(0,Qr.useCallback)((K,tt)=>{if((0,ke.classifyExternalMethodFailure)(K,{inAppBrowser:ce.inAppBrowser,handoffObserved:!1}).popupBlocked){yt(!0),E(new Error((0,ke.buildExternalMethodRecoveryMessage)(dd(e),!0,ce.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}E(tt.message===void 0?K:new Error(tt.message),{code:tt.code,retryable:!0})},[ce.inAppBrowser,e,E]),He=(0,Qr.useCallback)(async K=>{let tt=!1,we=!1,qe=()=>{!K||tt||we||(we=!0,K.paymentFailed({reason:"fail"}))};if(!w||!T||Ee.current){qe();return}Ee.current=!0,H(!0);try{let Q=await T.submit();if(Q.error){qe(),V(Q.error.message??null);return}b();let j=await new ud.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,An.isSettledSessionIntent)(j))throw(0,An.settledSessionIntentError)(r);if(j.provider!=="stripe"||j.intentKind!=="setup")throw new An.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});tt=!0;let fe=await w.confirmSetup({elements:T,clientSecret:j.clientSecret,confirmParams:{return_url:Sp()},redirect:"if_required"});if(fe.error){bp(fe.error)?h({...fe.error.decline_code||fe.error.code?{reason:fe.error.decline_code??fe.error.code}:{},...fe.error.message?{message:fe.error.message}:{}}):q(fe.error,{code:"payment_method_setup_provider_failed",message:fe.error.message??"The payment method could not be saved."});return}P()}catch(Q){qe(),q(Q,{code:"payment_method_setup_failed"})}finally{Ee.current=!1,H(!1)}},[a,t,T,e,n,P,h,b,V,q,r,w,s]),Ke=md[e]?.wallet,Le=Ke==="paypal"&&(0,Qn.resolveStripePayPalPresentation)(ce,"auto",bt?"blocked":ce.popupCapability)==="redirect",Pe=d?.variables?.borderRadius??y?.cardButton?.borderRadius??8;if(t==="wallet"&&Ke&&!Le)return(0,Gr.jsxs)(Gr.Fragment,{children:[(0,Gr.jsx)(ha,{}),(0,Gr.jsx)(Wa,{state:X,borderRadius:Pe,children:(0,Gr.jsx)(no.ExpressCheckoutElement,{options:{...Bi,paymentMethods:Fi([e])},onReady:K=>{let tt=Va(K,[Ke]);v(tt),tt==="unavailable"&&W()},onLoadError:()=>{v("load_error"),W()},onConfirm:K=>{He(K)}})})]});let Y=dd(e);return(0,Gr.jsxs)(Gr.Fragment,{children:[Se?(0,Gr.jsx)(xi,{method:e,themeId:p,hasNextStep:!0,highlighted:oe,disabled:f,onClick:()=>ye(K=>!K),backgroundColor:y?.cardButton?.backgroundColor,borderColor:y?.cardInputBorder,textColor:y?.cardButton?.color,borderRadius:Pe}):null,(0,Gr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!oe,style:oe?{display:"flex",flexDirection:"column"}:wp,children:[(0,Gr.jsx)(no.PaymentElement,{options:{layout:Oi},onReady:()=>M(!0),onLoadError:()=>W(),onChange:K=>{K.complete&&V(null)}}),(0,Gr.jsx)(Di,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!w||!T||f||!oe,onClick:()=>{He()},color:d?.variables?.colorPrimary??"#4A49FF",borderRadius:d?.variables?.borderRadius??"8px",style:y?.submitButton,children:f?"Saving\u2026":`Save ${Y}`})]})]})}var ei=require("@flopay/js/card-setup"),Rr=require("@flopay/shared"),Ze=Rs(require("react"),1);var Pa=require("@flopay/js/card-setup"),Ar=require("@flopay/shared");var dr=require("react/jsx-runtime"),kp=15,Ep=2e3;function _p(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function al(e){return new Promise(t=>setTimeout(t,e))}async function Ip(e,t,r){if(!t.trim())throw new Rr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Rr.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,Rr.isCardSetupCheckoutSession)(a))throw new Rr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Ar.readSetupAdvertisement)(n);if(!(0,Ar.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 Rr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function Tp(e,t,r,n,a){let s=t.vault??null;(0,Rr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let d=(0,Rr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!d)throw new Rr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return d}var Zi=class extends Ze.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 fd({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:d="modern-light",containerStyle:p,appearance:y,buttonsStyles:b,loading:P=null,onReady:h,onComplete:E,onDecline:V,onCancel:W,onValidation:w,onError:T}){let[f]=(0,Ze.useState)(Pa.readSetupRedirectReturn),[H,X]=(0,Ze.useState)(null),[v,Se]=(0,Ze.useState)(!1),[M,oe]=(0,Ze.useState)(null),[ye,Ee]=(0,Ze.useState)(null),[ce,bt]=(0,Ze.useState)(null),[yt,q]=(0,Ze.useState)(null),[He,Ke]=(0,Ze.useState)(()=>new Set),Le=(0,Ze.useRef)(He),Pe=(0,Ze.useRef)(null);Pe.current=H;let Y=(0,Ze.useRef)(!1),K=(0,Ze.useRef)(!1),tt=(0,Ze.useRef)(!1),we=(0,Ze.useRef)(!1),qe=(0,Ze.useRef)(0),Q=(0,Ze.useRef)(0),j=(0,Ze.useRef)(!1),{vaultTheme:fe,surface:J,overlayTheme:ft,appearance:de,buttonsLayout:ve}=(0,Ze.useMemo)(()=>Xi({theme:d,appearance:y,buttonsStyles:b}),[d,y,b]),_e=(0,Ze.useMemo)(()=>(0,Ha.mergeCardSetupSurface)(J,p),[J,p]),Me=(0,Ze.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:h,onComplete:E,onDecline:V,onCancel:W,onValidation:w,onError:T});Me.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:h,onComplete:E,onDecline:V,onCancel:W,onValidation:w,onError:T},(0,Ze.useEffect)(()=>{j.current=!0;let u=qe.current+1;return qe.current=u,()=>{j.current=!1,Q.current+=1,queueMicrotask(()=>{qe.current===u&&(tt.current||we.current||(we.current=!0,(0,Ge.invokeMerchantCallback)(()=>{Me.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let je=(0,Ze.useCallback)((u,I)=>{tt.current=!0,Y.current=!1,q({status:"success",wording:u,message:null}),(async()=>(await al(600),!K.current&&(K.current=!0,(0,Ge.invokeMerchantCallback)(()=>{Me.current.onComplete?.({status:"succeeded",sessionId:Me.current.sessionId,...I?{paymentMethod:I}:{}})}),j.current&&q(null))))()},[]),ge=(0,Ze.useCallback)((u,I)=>{tt.current=!0,Y.current=!1,q({status:"error",wording:u,message:I.message??null}),(0,Ge.invokeMerchantCallback)(()=>{Me.current.onDecline?.({status:"declined",sessionId:Me.current.sessionId,...I.reason?{reason:I.reason}:{},...I.message?{message:I.message}:{}})}),(async()=>(await al(400),j.current&&q(null)))()},[]),rt=(0,Ze.useCallback)((u,I)=>{Y.current?(Y.current=!1,q({status:"error",wording:u,message:I.message}),setTimeout(()=>{j.current&&q(null)},400)):q(null),(0,Ge.invokeMerchantCallback)(()=>Me.current.onError?.(I))},[]),dt=(0,Ze.useCallback)(async u=>{let I=Q.current+1;Q.current=I;let k=()=>!j.current||I!==Q.current;Y.current=!0,q({status:"processing",wording:"payment_method",message:null});let U=new ei.PaymentAPI((0,Rr.resolveBillingApiUrl)(Me.current.billingApiUrl),{telemetry:Me.current.telemetry});try{for(let F=0;F<kp;F+=1){if((F>0||u.waitFirst)&&await al(Ep),k())return;let x=await U.getUnifiedCheckoutSession(Me.current.sessionId,Me.current.nonce);if(k())return;let At=x.data.session?.status;if(At==="complete"){Se(!0),je("payment_method");return}if(At==="expired")throw new Rr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Rr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(F){if(k())return;let x=F instanceof Rr.FloPayError&&F.code==="payment_method_setup_unverified";rt("payment_method",fo(F,x?{retryable:!0}:{}))}finally{U.destroy()}},[rt,je]);(0,Ze.useEffect)(()=>{let u=!0,I=(0,Rr.resolveBillingApiUrl)(a),k=new ei.PaymentAPI(I,{telemetry:s});X(null),Se(!1),oe(null),Ee(null),bt(null);let U=new Set;return Le.current=U,Ke(U),tt.current=!1,we.current=!1,K.current=!1,(async()=>{try{let{session:F,advertisement:x}=await Ip(k,r,n);if(!u)return;let At={advertisement:x,customer:_p(F),...F.futureUse?{futureUse:F.futureUse}:{},...F.futureUseUnsupported?{futureUseUnsupported:F.futureUseUnsupported}:{}};if(f){if((0,Pa.clearSetupRedirectParams)(),F.status==="complete"){Se(!0),X(At),je("payment_method");return}f.failed?ge("payment_method",{reason:"redirect_failed"}):dt({waitFirst:!0})}let Et=x.card?await Tp(k,F,r,n,I):null;if(!u)return;X(At),Et&&(Ee(Et),oe(new ei.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(F){if(!u)return;let x=fo(F);tt.current=!0,bt(x),(0,Ge.invokeMerchantCallback)(()=>Me.current.onError?.(x))}})(),()=>{u=!1,k.destroy()}},[a,n,f,ge,je,r,s,dt]),(0,Ze.useEffect)(()=>{if(!M)return;Y.current=!1;let u=M.on("submitting",()=>{Y.current=!0,q({status:"processing",wording:"card",message:null})}),I=M.on("complete",F=>{je("card",F.paymentMethod)}),k=M.on("decline",F=>{ge("card",{...F.declineReason?{reason:F.declineReason}:{},...F.message?{message:F.message}:{}})}),U=M.on("challenge_dismissed",()=>{q(null)});return()=>{u(),I(),k(),U()}},[M,ge,je]);let ut=(0,Ze.useCallback)((u,I,k)=>{if(k.retryable){rt("payment_method",fo(I,k));return}if(Le.current.has(u))return;let U=new Set(Le.current);U.add(u),Le.current=U,Ke(U);let F=Pe.current?.advertisement,x=F?(0,Ar.advertisedMethodKeys)(F).some(At=>!U.has(At)):!1;rt("payment_method",fo(I,{code:k.code,retryable:x}))},[rt]),ae=(0,Ze.useMemo)(()=>({onSubmitting:()=>{Y.current=!0,q({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{dt({waitFirst:!1})},onDeclined:u=>ge("payment_method",u),onValidation:u=>{(0,Ge.invokeMerchantCallback)(()=>Me.current.onValidation?.(u))},onAbandoned:()=>{Y.current=!1,q(null)}}),[ge,dt]),Dt=(0,Ze.useRef)(ut);Dt.current=ut;let Lt=(0,Ze.useRef)(new Map),Ut=u=>{let I=Lt.current.get(u);if(I)return I;let k=(U,F)=>Dt.current(u,U,F);return Lt.current.set(u,k),k},Ie=(0,Ze.useCallback)(u=>{if(Le.current.has(u))return;let I=new Set(Le.current);I.add(u),Le.current=I,Ke(I);let k=Pe.current?.advertisement;k&&(0,Ar.advertisedMethodKeys)(k).some(F=>!I.has(F))||rt("payment_method",fo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[rt]),he=(0,Ze.useRef)(Ie);he.current=Ie;let gt=(0,Ze.useRef)(new Map),Qe=u=>{let I=gt.current.get(u);if(I)return I;let k=()=>he.current(u);return gt.current.set(u,k),k},Mt=yt?(0,dr.jsx)(an,{status:yt.status,errorMessage:yt.message,...(0,Ar.setupOverlayLabels)(yt.wording),successNote:null,...ft?{theme:ft}:{}}):null;if(ce)return(0,dr.jsx)("div",{role:"alert",children:ce.message});if(!H||v)return(0,dr.jsxs)(dr.Fragment,{children:[Mt,H?null:P]});let{advertisement:nt,customer:St,futureUse:ht,futureUseUnsupported:ne}=H,$t=(0,Rr.resolveBillingApiUrl)(a),kt=s===void 0?{}:{telemetry:s},D=nt.stripe.filter(({method:u})=>!He.has(u)),Ye=He.has("paypal")?null:nt.paypal,_=!!(nt.card&&M&&ye?.html),A=({method:u,publishableKey:I,currency:k})=>(0,dr.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,dr.jsx)(Zi,{onFailed:Ut(u),children:(0,dr.jsx)(Ze.Suspense,{fallback:null,children:(0,dr.jsx)(e,{method:u,category:(0,Ar.stripeMethodCategory)(u),publishableKey:I,currency:k,...ht?{futureUse:ht}:{},...ne?{futureUseUnsupported:ne}:{},sessionId:r,nonce:n,billingApiUrl:$t,...kt,...de?{appearance:de}:{},...ve?{buttonsLayout:ve}:{},...typeof d=="string"?{themeId:d}:{},...ae,onFailed:Ut(u),onUnavailable:Qe(u)})})})},u),Ae=D.filter(({method:u})=>(0,Ar.stripeMethodCategory)(u)==="wallet"),te=D.filter(({method:u})=>(0,Ar.stripeMethodCategory)(u)!=="wallet"),xe=D.length>0||Ye!==null;return(0,dr.jsxs)(dr.Fragment,{children:[Mt,xe?(0,dr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ae.map(A),Ye?(0,dr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,dr.jsx)(Zi,{onFailed:Ut("paypal"),children:(0,dr.jsx)(Ze.Suspense,{fallback:null,children:(0,dr.jsx)(t,{clientId:Ye.clientId,...Ye.environment?{environment:Ye.environment}:{},...nt.currency?{currency:nt.currency}:{},sessionId:r,nonce:n,billingApiUrl:$t,customer:St,...kt,...ae,onFailed:Ut("paypal"),onUnavailable:Qe("paypal")})})})}):null,te.map(A)]}):null,_&&xe?(0,dr.jsx)(Ka,{label:"or add a card"}):null,_&&M&&ye?.html?(0,dr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,dr.jsx)(Eo,{capture:M,html:ye.html,messageToken:ye.messageToken,expectedOrigin:ye.expectedOrigin,verificationRequired:ye.verificationRequired,theme:fe,containerStyle:_e,onReady:()=>{(0,Ge.invokeMerchantCallback)(()=>Me.current.onReady?.())},onValidation:u=>{(0,Ge.invokeMerchantCallback)(()=>Me.current.onValidation?.(u))},onError:u=>{u&&rt("card",fo(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var hd=require("react/jsx-runtime"),Mp={StripeSetupMethod:yd,PayPalSetupMethod:ld};function gd(e){return(0,hd.jsx)(fd,{...e,branches:Mp})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}let Y={paypal:r&&f(zo),wallets:n&&(a||s)&&f(zo),card:n&&(t?f(zo):(0,O.jsx)("button",{type:"button",onClick:()=>{e?.("card"),V(!0)},style:{width:"100%",...H,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:k.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,...k.cardButton},onMouseDown:b=>{b.currentTarget.style.transform="scale(0.985)"},onMouseUp:b=>{b.currentTarget.style.transform="scale(1)"},children:(0,O.jsx)(oa,{content:w})}))};return(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[se.DEFAULT_PAYMENT_METHOD_ORDER.map(b=>(0,O.jsx)(R.default.Fragment,{children:Y[b]},b)),(0,O.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var In=require("react/jsx-runtime"),hp=44;function od(e){return new Promise(t=>setTimeout(t,e))}var ad=15e3;function ol(e,t){return new Ir.FloPayError(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function Pp(e,t){return new Promise((r,n)=>{let a=()=>n(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(s=>{t.removeEventListener("abort",a),r(s)},s=>{t.removeEventListener("abort",a),n(s)})})}function vp(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function Cp(e,t){return e instanceof Ir.FloPayError?e:new Ir.FloPayError(e instanceof Error?e.message:t,"api_error")}function bp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Sp(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 id({sessionId:e,nonce:t,createSession:r,getSession:n,paymentMethodId:a,checkoutMethod:s,clientId:d,products:p,items:m,subscriptions:w,account:h,successUrl:g,cancelUrl:_,couponCodes:V,tagsData:W,utmMetadata:k,billingApiUrl:A,locale:f,theme:H,appearance:Y,buttonsTheme:b,buttonsStyles:be,onSuccess:x,onError:oe,onDecline:ge,children:Ie,disabled:ce=!1,type:Rt="button",style:mt,...q}){let Ve=(0,pt.useMemo)(()=>(0,Ir.resolveBillingApiUrl)(A),[A]),We=(0,pt.useMemo)(()=>Sp({createSession:r,clientId:d,products:p,items:m,subscriptions:w,account:h,successUrl:g,cancelUrl:_,couponCodes:V,tagsData:W,utmMetadata:k}),[h,_,d,V,r,p,m,w,g,W,k]),[Ne,ve]=(0,pt.useState)(!1),[G,K]=(0,pt.useState)(null),[Ze,Se]=(0,pt.useState)(null),[qe,Z]=(0,pt.useState)(!1),[j,he]=(0,pt.useState)(null),[X,Pt]=(0,pt.useState)(null),pe=(0,pt.useRef)(!0),we=(0,pt.useRef)(null),Ae=(0,pt.useRef)(null),Ce=(0,pt.useRef)(!1),kt=(0,pt.useRef)(X),Pe=(0,pt.useRef)(x),Be=(0,pt.useRef)(oe),at=(0,pt.useRef)(ge),yt=(0,pt.useCallback)(v=>Ii(we,async Q=>{try{return await v(Q)}catch(ee){throw Q.aborted?ma(ee):ee}}),[]);(0,pt.useEffect)(()=>{kt.current=X},[X]),(0,pt.useEffect)(()=>{Pe.current=x},[x]),(0,pt.useEffect)(()=>{Be.current=oe},[oe]),(0,pt.useEffect)(()=>{at.current=ge},[ge]),(0,pt.useEffect)(()=>(pe.current=!0,()=>{pe.current=!1,we.current?.abort(),Ae.current?.abort()}),[]),(0,pt.useEffect)(()=>{if(typeof window>"u")return;let v=Q=>{Q.key==="Escape"&&Pt(null)};return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[]);let Mt=(0,pt.useCallback)((v,Q=qa)=>{at.current?.(kr(Q,v,{code:v.code,declineCode:v.declineCode}))},[]),le=(0,pt.useCallback)(async v=>{pe.current&&(Se(null),Z(v.result.status==="authorized"),K("success"),await od(600),pe.current&&(0,He.invokeMerchantCallback)(()=>Pe.current?.(v)))},[]),It=(0,pt.useCallback)(async(v,Q)=>{if(!pe.current)return;!!Q?.emitDecline&&(0,Ir.isDeclineCallbackFailure)(v)?Mt(v,Q?.method):Be.current?.(v),Se(v.message),Z(!1),K("error"),await od(400)},[Mt]),Vt=(0,pt.useCallback)(async(v,Q,ee)=>{let $=v.data.session??null;if(!$)throw Ro(new Ir.FloPayError("No session data returned","api_error"),Q);let nt=ee?.nonce||$.clientSecret||t;if(lo($)){await le({result:so($,Q),session:$,sessionId:$.id||Q,autoCompleted:!1});return}if($.status==="expired")throw Ro(gi($),$.id||Q);try{if(v.autoProcessingPending){let F=v.autoProcessingPending,D=new Yi.PaymentAPI(Ve),L=await yt(Ct=>D.waitForCheckoutSessionCompletion(F.sessionId,{initialDelayMs:F.retryAfterMs,nonce:nt,statusUrl:F.statusUrl,signal:Ct})),T=ko(L,$),I=L.autoProcessingError?.type==="3ds_required"&&!(0,Ir.isMerchantAuthRequired)(L.autoProcessingError)&&L.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:L.autoProcessingError.nextActionRedirectUrl}:null;if(I&&Q&&nt){let Ct=ja(Ve,Q,$),Mr=await yt(bt=>fa(I,{billingApiUrl:Ve,sessionId:Q,nonce:nt,session:$,signal:bt,telemetry:!0,...Ct.telemetry?{challengeTelemetry:Ct.telemetry}:{}})).finally(Ct.release);await le({result:Mr,session:$,sessionId:$.id||Q,autoCompleted:!1});return}if(L.autoProcessingError)throw Qn(L.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.autoProcessingError.checkoutMethod});if(!lo(T))throw sa(T);await le({result:so(T,Q),session:T,sessionId:T.id||Q,autoCompleted:!1});return}if(v.autoProcessingError){let F=v.autoProcessingError.nextActionRedirectUrl;if(v.autoProcessingError.type==="3ds_required"&&!(0,Ir.isMerchantAuthRequired)(v.autoProcessingError)&&F&&Q&&nt){let D=await yt(Ct=>Ec({billingApiUrl:Ve,sessionId:Q,nonce:nt,nextActionRedirectUrl:F,signal:Ct}));if(D.status==="declined")throw Qn({type:D.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:D.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:v.autoProcessingError.checkoutMethod});let T=await new Yi.PaymentAPI(Ve).waitForCheckoutSessionCompletion(Q,{initialDelayMs:0,nonce:nt}),I=ko(T,$);if(!lo(I))throw Qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:v.autoProcessingError.checkoutMethod});await le({result:so(I,Q),session:I,sessionId:I.id||Q,autoCompleted:!1});return}throw Qn(v.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:v.autoProcessingError.checkoutMethod})}if(ee?.fromCreateSession&&v.autoProcessingAttempted===!0)throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let u=await ga({billingApiUrl:Ve,sessionId:Q??$.id,session:$,nonce:nt});if(u.type==="next_action_required"&&nt){let F=Q??$.id,D=ja(Ve,F,$),L=await yt(T=>fa(u,{billingApiUrl:Ve,sessionId:F,nonce:nt,session:$,signal:T,telemetry:!0,...D.telemetry?{challengeTelemetry:D.telemetry}:{}})).finally(D.release);await le({result:L,session:$,sessionId:$.id||F,autoCompleted:!1});return}if(u.type!=="success")throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await le({result:u.result,session:$,sessionId:$.id||Q,autoCompleted:!1})}catch(u){let F=$.id||Q,D=Ro(Va(u),F);if(D.code==="three_ds_aborted")return;if(D.code==="checkout_processing_timeout"){if(!pe.current)return;he(D.message),(0,He.invokeMerchantCallback)(()=>Be.current?.(D));return}await It(D,{emitDecline:!0,method:D.checkoutMethod??qa}),bp(D,F)&&F&&pe.current&&Pt({sessionId:F,errorMessage:D.message,nonce:nt||void 0,payPalOrderId:D.orderId})}},[t,Ve,yt,It,le]),xe=(0,pt.useCallback)(async v=>{let Q=new AbortController;Ae.current=Q;let ee=!1,$=setTimeout(()=>{ee=!0,Q.abort()},ad);try{let nt=await Pp((async()=>v({signal:Q.signal}))(),Q.signal);if(!pe.current)return null;if(!vp(nt))throw ol("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:nt.sessionId,nonce:nt.nonce}}catch(nt){if(!pe.current)return null;throw nt instanceof Ir.FloPayError&&nt.code==="session_fetch_failed"?nt:ee?ol(`getSession did not resolve within ${ad/1e3} seconds.`):ol("Could not fetch the one-click session.",nt)}finally{clearTimeout($),Ae.current===Q&&(Ae.current=null)}},[]),Oe=(0,pt.useCallback)(async v=>{if(q.onClick?.(v),v.defaultPrevented||ce||Ne||(Pt(null),he(null),Ce.current))return;let Q=[e,n,We].filter(Boolean).length;if(Q>1){let ee=new Ir.FloPayError("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await It(ee),pe.current&&(K(null),Se(null));return}if(Q===0){let ee=new Ir.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await It(ee),pe.current&&(K(null),Se(null));return}Ce.current=!0,ve(!0),Se(null),Z(!1),K("processing");try{let ee=new Yi.PaymentAPI(Ve);if(e){let $=await ee.getUnifiedCheckoutSession(e,t);await Vt($,e);return}if(n){let $=await xe(n);if(!$)return;let nt=await ee.getUnifiedCheckoutSession($.sessionId,$.nonce);await Vt(nt,$.sessionId,{nonce:$.nonce});return}bc();try{let $=await ee.createAndFetchSession({...We});await Vt($,$.data.session?.id??null,{fromCreateSession:!0})}catch($){if(hi($)==="session_auto_completed"){await le({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw $}}catch(ee){await It(Ro(Cp(ee,"Automatic payment failed. Please try again."),e))}finally{Ce.current=!1,pe.current&&(K(null),Se(null),ve(!1))}},[q.onClick,We,ce,xe,n,Ne,t,Vt,Ve,e,It,le]),Ke=(0,pt.useCallback)(v=>{let Q=kt.current;Pt(null),Pe.current?.({result:v,session:null,sessionId:Q?.sessionId??null,autoCompleted:!1})},[]),vt=(0,pt.useCallback)(v=>{Be.current?.(v)},[]),it=(0,pt.useCallback)(v=>{at.current?.(v)},[]),ft=(0,pt.useMemo)(()=>(0,Ir.resolveTheme)(H),[H]),Lt=(0,pt.useMemo)(()=>{let v=ft?.buttonsLayout??(0,Ir.resolveButtonsLayoutTheme)(b);return be?{...v,...be,cardButton:{...v.cardButton,...be.cardButton}}:v},[ft,b,be]),Qe=(0,pt.useMemo)(()=>{let v=ft?.appearance;return Y?v?{...v,...Y,variables:{...v.variables,...Y.variables}}:Y:v},[Y,ft]),st=Qe?.variables,de=st?.colorPrimary??"#4A49FF",Ot=st?.colorPrimaryHover??(0,Xs.darkenHex)(de,.12),et=st?.borderRadius??"8px";return(0,In.jsxs)(In.Fragment,{children:[(0,In.jsx)("button",{...q,type:Rt,onClick:Oe,disabled:ce||Ne,"aria-busy":Ne,style:{width:"100%",...Ie===void 0?{boxSizing:"border-box",height:hp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Lt.cardButton,...Ys({themeBundle:ft,resolvedPrimaryColor:de,resolvedBorderRadius:et,submitButtonStyle:Lt.submitButton,explicitPrimaryColor:st?.colorPrimary}),fontSize:Lt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ce||Ne?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ce||Ne?.6:1,...mt},onMouseEnter:v=>{q.onMouseEnter?.(v),!v.defaultPrevented&&!ce&&!Ne&&(ft||st?.colorPrimary)&&(v.currentTarget.style.backgroundColor=Ot)},onMouseLeave:v=>{q.onMouseLeave?.(v),!v.defaultPrevented&&(ft||st?.colorPrimary)&&(v.currentTarget.style.backgroundColor=de)},onMouseDown:v=>{q.onMouseDown?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(0.985)")},onMouseUp:v=>{q.onMouseUp?.(v),v.defaultPrevented||(v.currentTarget.style.transform="scale(1)")},children:(0,In.jsx)(oa,{content:Ie})}),j&&(0,In.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:j}),G&&(0,In.jsx)(rn,{status:G,errorMessage:Ze,authorized:qe}),X&&(0,In.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:v=>{v.target===v.currentTarget&&Pt(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,In.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,In.jsx)(Gi,{sessionId:X.sessionId,nonce:X.nonce,checkoutMode:"full",billingApiUrl:Ve,locale:f,theme:H,...Qe?{appearance:Qe}:{},buttonsTheme:b,buttonsStyles:be,initialErrorMessage:X.errorMessage,initialPayPalOrderId:X.payPalOrderId,cardTitleContent:null,onComplete:Ke,onError:vt,onDecline:it})})})]})}var Ji=require("@flopay/js/card-setup"),Yr=require("@flopay/shared"),Gt=require("react");var al=require("@flopay/shared"),wp=require("@flopay/shared");function Xi(e){let t=(0,al.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var to=require("react/jsx-runtime"),ei=class extends Yr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function fo(e,t={}){let r=e instanceof Yr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new ei(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 sd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:s,appearance:d,buttonsStyles:p,loading:m=null,onReady:w,onComplete:h,onDecline:g,onCancel:_,onValidation:V,onError:W}){let[k,A]=(0,Gt.useState)(null),[f,H]=(0,Gt.useState)(null),[Y,b]=(0,Gt.useState)(null),[be,x]=(0,Gt.useState)(null),[oe,ge]=(0,Gt.useState)(null),Ie=(0,Gt.useRef)(!1),ce=(0,Gt.useRef)(!1),{vaultTheme:Rt,surface:mt,overlayTheme:q}=(0,Gt.useMemo)(()=>Xi({theme:a,appearance:d,buttonsStyles:p}),[a,d,p]),Ve=(0,Gt.useMemo)(()=>(0,Ka.mergeCardSetupSurface)(mt,s),[mt,s]),We=(0,Gt.useRef)(w),Ne=(0,Gt.useRef)(W),ve=(0,Gt.useRef)(h),G=(0,Gt.useRef)(g),K=(0,Gt.useRef)(_),Ze=(0,Gt.useRef)(V),Se=(0,Gt.useRef)(!1),qe=(0,Gt.useRef)(!1),Z=(0,Gt.useRef)(0);return We.current=w,Ne.current=W,ve.current=h,G.current=g,K.current=_,Ze.current=V,(0,Gt.useEffect)(()=>{let j=Z.current+1;return Z.current=j,()=>{queueMicrotask(()=>{Z.current===j&&(Se.current||qe.current||(qe.current=!0,(0,He.invokeMerchantCallback)(()=>{K.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Gt.useEffect)(()=>{let j=!0,he=(0,Yr.resolveBillingApiUrl)(r),X=new Ji.PaymentAPI(he,{telemetry:n});return A(null),H(null),b(null),Se.current=!1,qe.current=!1,(async()=>{try{if(!e.trim())throw new Yr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Yr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Pt=await X.getUnifiedCheckoutSession(e,t);if(!j)return;let pe=Pt.data.session;if(!pe||!(0,Yr.isCardSetupCheckoutSession)(pe))throw new Yr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let we=pe.vault;(0,Yr.isMountableVaultBlock)(we)||(we=await X.getVaultCapture(e,t));let Ae=(0,Yr.resolveVaultMountOptions)(we,{billingApiUrl:he,sessionId:e,nonce:t});if(!Ae)throw new Yr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!j)return;H(Ae),A(new Ji.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(Pt){if(!j)return;let pe=fo(Pt);Se.current=!0,b(pe),(0,He.invokeMerchantCallback)(()=>Ne.current?.(pe))}})(),()=>{j=!1,X.destroy()}},[r,t,e,n]),(0,Gt.useEffect)(()=>{if(!k)return;let j=!1;ce.current=!1,Ie.current=!1;let he=k.on("submitting",()=>{Ie.current=!0,ge(null),x("processing")}),X=k.on("complete",we=>{Se.current=!0,Ie.current=!1,x("success"),(async()=>(await new Promise(Ae=>setTimeout(Ae,600)),!ce.current&&(ce.current=!0,(0,He.invokeMerchantCallback)(()=>{ve.current?.({status:"succeeded",sessionId:e,...we.paymentMethod?{paymentMethod:we.paymentMethod}:{}})}),j||x(null))))()}),Pt=k.on("decline",we=>{Se.current=!0,Ie.current=!1,ge(we.message??null),x("error"),(0,He.invokeMerchantCallback)(()=>{G.current?.({status:"declined",sessionId:e,...we.declineReason?{reason:we.declineReason}:{},...we.message?{message:we.message}:{}})}),(async()=>(await new Promise(Ae=>setTimeout(Ae,400)),j||x(null)))()}),pe=k.on("challenge_dismissed",()=>{x(null)});return()=>{j=!0,he(),X(),Pt(),pe()}},[k,e]),Y?(0,to.jsx)("div",{role:"alert",children:Y.message}):!k||!f?.html?(0,to.jsx)(to.Fragment,{children:m}):(0,to.jsxs)(to.Fragment,{children:[be&&(0,to.jsx)(rn,{status:be,errorMessage:oe,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...q?{theme:q}:{}}),(0,to.jsx)(_o,{capture:k,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:Rt,containerStyle:Ve,onReady:()=>{(0,He.invokeMerchantCallback)(()=>We.current?.())},onValidation:j=>{(0,He.invokeMerchantCallback)(()=>Ze.current?.(j))},onError:j=>{if(!j)return;Ie.current&&(Ie.current=!1,ge(j),x("error"),setTimeout(()=>x(null),400));let he=fo(new Error(j),{code:"card_setup_widget_failed",retryable:!0});(0,He.invokeMerchantCallback)(()=>Ne.current?.(he))}})]})}var ld=require("@flopay/js/card-setup"),Tn=require("@flopay/shared"),cd=require("@paypal/paypal-js"),qo=require("react");var ud=require("react/jsx-runtime");function dd({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:s,telemetry:d,customer:{userId:p,email:m},onSubmitting:w,onConfirmed:h,onFailed:g,onAbandoned:_}){let V=(0,qo.useRef)(null),W=(0,qo.useRef)({onSubmitting:w,onConfirmed:h,onFailed:g,onAbandoned:_});W.current={onSubmitting:w,onConfirmed:h,onFailed:g,onAbandoned:_};let[k]=(0,qo.useState)(()=>(0,Jn.detectPayPalEnvironment)().inAppBrowser);return(0,qo.useEffect)(()=>{let A=!0,f,H=new ld.PaymentAPI(s,{telemetry:d}),Y={userId:p,email:m};return(async()=>{try{let b=await(0,cd.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),be=V.current;if(!A||!be)return;if(!b?.Buttons)throw new Tn.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let x=b.Buttons({createVaultSetupToken:async()=>{W.current.onSubmitting();let oe=await H.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Tn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,Tn.isSettledSessionIntent)(oe))throw(0,Tn.settledSessionIntentError)(n);if(oe.provider!=="paypal"||oe.providerObjectType!=="setup_token")throw new Tn.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return oe.providerObjectId},onApprove:async oe=>{let ge=oe.vaultSetupToken;if(!ge)throw new Tn.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let Ie=await H.processPayment(Y.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:ge,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Tn.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:Y});if(!Ie.ok)throw new Tn.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:Ie.status});A&&W.current.onConfirmed()},onCancel:()=>{A&&W.current.onAbandoned()},onError:oe=>{if(!A)return;let{popupBlocked:ge}=(0,_e.classifyExternalMethodFailure)(oe,{inAppBrowser:k,handoffObserved:!1});W.current.onFailed(ge?new Error((0,_e.buildExternalMethodRecoveryMessage)("PayPal",!0,k)):oe,{code:ge?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>x.close(),await x.render(be)}catch(b){if(!A)return;W.current.onFailed(b,{code:"paypal_unavailable",retryable:!0})}})(),()=>{A=!1,f?.().catch(()=>{}),H.destroy()}},[s,e,r,m,t,k,a,n,d,p]),(0,ud.jsx)("div",{ref:V,"data-flopay-paypal-setup":""})}var yd=require("@flopay/js/card-setup"),Mn=require("@flopay/shared"),ro=require("@stripe/react-stripe-js"),md=require("@stripe/stripe-js"),Xr=require("react");var Wr=require("react/jsx-runtime"),fd={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"}},il=new Map;function Rp(e){let t=il.get(e);if(t)return t;let r=(0,md.loadStripe)(e).catch(n=>{throw il.delete(e),n});return il.set(e,r),r}function kp(e){return e?(0,Mn.toStripeAppearance)(e):void 0}function Ep(e){return(0,_e.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function pd(e){return e==="paypal"?"PayPal":(0,Mn.getStripeMethodDisplayName)(e)}function _p(){return typeof window>"u"?"":window.location.href}var Ip={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function gd(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:s,appearance:d}=e,[p]=(0,Xr.useState)(()=>Rp(t)),m=(0,Xr.useMemo)(()=>{let w=kp(d),h=(0,Mn.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:s},r,"setup");return{mode:"setup",currency:n.toLowerCase(),allowedPaymentMethodTypes:fd[r]?.types??[r],...h?{setupFutureUsage:h}:{},...w?{appearance:w}:{}}},[d,n,a,s,r]);return(0,Wr.jsx)(ro.Elements,{stripe:p,options:m,children:(0,Wr.jsx)(Tp,{...e})})}function Tp({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,appearance:d,themeId:p,buttonsLayout:m,onSubmitting:w,onConfirmed:h,onDeclined:g,onFailed:_,onValidation:V,onUnavailable:W}){let k=(0,ro.useStripe)(),A=(0,ro.useElements)(),[f,H]=(0,Xr.useState)(!1),[Y,b]=(0,Xr.useState)("loading"),[be,x]=(0,Xr.useState)(!1),[oe,ge]=(0,Xr.useState)(!1),Ie=(0,Xr.useRef)(!1),[ce]=(0,Xr.useState)(()=>(0,Jn.detectPayPalEnvironment)()),[Rt,mt]=(0,Xr.useState)(!1),q=(0,Xr.useCallback)((K,Ze)=>{if((0,_e.classifyExternalMethodFailure)(K,{inAppBrowser:ce.inAppBrowser,handoffObserved:!1}).popupBlocked){mt(!0),_(new Error((0,_e.buildExternalMethodRecoveryMessage)(pd(e),!0,ce.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}_(Ze.message===void 0?K:new Error(Ze.message),{code:Ze.code,retryable:!0})},[ce.inAppBrowser,e,_]),Ve=(0,Xr.useCallback)(async K=>{let Ze=!1,Se=!1,qe=()=>{!K||Ze||Se||(Se=!0,K.paymentFailed({reason:"fail"}))};if(!k||!A||Ie.current){qe();return}Ie.current=!0,H(!0);try{let Z=await A.submit();if(Z.error){qe(),V(Z.error.message??null);return}w();let j=await new yd.PaymentAPI(a,{telemetry:s}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,Mn.isSettledSessionIntent)(j))throw(0,Mn.settledSessionIntentError)(r);if(j.provider!=="stripe"||j.intentKind!=="setup")throw new Mn.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});Ze=!0;let he=await k.confirmSetup({elements:A,clientSecret:j.clientSecret,confirmParams:{return_url:_p()},redirect:"if_required"});if(he.error){Ep(he.error)?g({...he.error.decline_code||he.error.code?{reason:he.error.decline_code??he.error.code}:{},...he.error.message?{message:he.error.message}:{}}):q(he.error,{code:"payment_method_setup_provider_failed",message:he.error.message??"The payment method could not be saved."});return}h()}catch(Z){qe(),q(Z,{code:"payment_method_setup_failed"})}finally{Ie.current=!1,H(!1)}},[a,t,A,e,n,h,g,w,V,q,r,k,s]),We=fd[e]?.wallet,Ne=We==="paypal"&&(0,Zn.resolveStripePayPalPresentation)(ce,"auto",Rt?"blocked":ce.popupCapability)==="redirect",ve=d?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&We&&!Ne)return(0,Wr.jsxs)(Wr.Fragment,{children:[(0,Wr.jsx)(ha,{}),(0,Wr.jsx)($a,{state:Y,borderRadius:ve,children:(0,Wr.jsx)(ro.ExpressCheckoutElement,{options:{...Bi,paymentMethods:Fi([e])},onReady:K=>{let Ze=Wa(K,[We]);b(Ze),Ze==="unavailable"&&W()},onLoadError:()=>{b("load_error"),W()},onConfirm:K=>{Ve(K)}})})]});let G=pd(e);return(0,Wr.jsxs)(Wr.Fragment,{children:[be?(0,Wr.jsx)(xi,{method:e,themeId:p,hasNextStep:!0,highlighted:oe,disabled:f,onClick:()=>ge(K=>!K),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:ve}):null,(0,Wr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!oe,style:oe?{display:"flex",flexDirection:"column"}:Ip,children:[(0,Wr.jsx)(ro.PaymentElement,{options:{layout:Oi},onReady:()=>x(!0),onLoadError:()=>W(),onChange:K=>{K.complete&&V(null)}}),(0,Wr.jsx)(Di,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!k||!A||f||!oe,onClick:()=>{Ve()},color:d?.variables?.colorPrimary??"#4A49FF",borderRadius:d?.variables?.borderRadius??"8px",style:m?.submitButton,children:f?"Saving\u2026":`Save ${G}`})]})]})}var ti=require("@flopay/js/card-setup"),Tr=require("@flopay/shared"),Ye=Es(require("react"),1);var Pa=require("@flopay/js/card-setup"),Nr=require("@flopay/shared");var dr=require("react/jsx-runtime"),Mp=15,Ap=2e3;function xp(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function sl(e){return new Promise(t=>setTimeout(t,e))}async function Fp(e,t,r){if(!t.trim())throw new Tr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new Tr.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,Tr.isCardSetupCheckoutSession)(a))throw new Tr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let s=(0,Nr.readSetupAdvertisement)(n);if(!(0,Nr.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 Tr.FloPayError(p,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:s}}async function Bp(e,t,r,n,a){let s=t.vault??null;(0,Tr.isMountableVaultBlock)(s)||(s=await e.getVaultCapture(r,n));let d=(0,Tr.resolveVaultMountOptions)(s,{billingApiUrl:a,sessionId:r,nonce:n});if(!d)throw new Tr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return d}var Zi=class extends Ye.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 hd({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,theme:d="modern-light",containerStyle:p,appearance:m,buttonsStyles:w,loading:h=null,onReady:g,onComplete:_,onDecline:V,onCancel:W,onValidation:k,onError:A}){let[f]=(0,Ye.useState)(Pa.readSetupRedirectReturn),[H,Y]=(0,Ye.useState)(null),[b,be]=(0,Ye.useState)(!1),[x,oe]=(0,Ye.useState)(null),[ge,Ie]=(0,Ye.useState)(null),[ce,Rt]=(0,Ye.useState)(null),[mt,q]=(0,Ye.useState)(null),[Ve,We]=(0,Ye.useState)(()=>new Set),Ne=(0,Ye.useRef)(Ve),ve=(0,Ye.useRef)(null);ve.current=H;let G=(0,Ye.useRef)(!1),K=(0,Ye.useRef)(!1),Ze=(0,Ye.useRef)(!1),Se=(0,Ye.useRef)(!1),qe=(0,Ye.useRef)(0),Z=(0,Ye.useRef)(0),j=(0,Ye.useRef)(!1),{vaultTheme:he,surface:X,overlayTheme:Pt,appearance:pe,buttonsLayout:we}=(0,Ye.useMemo)(()=>Xi({theme:d,appearance:m,buttonsStyles:w}),[d,m,w]),Ae=(0,Ye.useMemo)(()=>(0,Ka.mergeCardSetupSurface)(X,p),[X,p]),Ce=(0,Ye.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:g,onComplete:_,onDecline:V,onCancel:W,onValidation:k,onError:A});Ce.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:s,onReady:g,onComplete:_,onDecline:V,onCancel:W,onValidation:k,onError:A},(0,Ye.useEffect)(()=>{j.current=!0;let u=qe.current+1;return qe.current=u,()=>{j.current=!1,Z.current+=1,queueMicrotask(()=>{qe.current===u&&(Ze.current||Se.current||(Se.current=!0,(0,He.invokeMerchantCallback)(()=>{Ce.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let kt=(0,Ye.useCallback)((u,F)=>{Ze.current=!0,G.current=!1,q({status:"success",wording:u,message:null}),(async()=>(await sl(600),!K.current&&(K.current=!0,(0,He.invokeMerchantCallback)(()=>{Ce.current.onComplete?.({status:"succeeded",sessionId:Ce.current.sessionId,...F?{paymentMethod:F}:{}})}),j.current&&q(null))))()},[]),Pe=(0,Ye.useCallback)((u,F)=>{Ze.current=!0,G.current=!1,q({status:"error",wording:u,message:F.message??null}),(0,He.invokeMerchantCallback)(()=>{Ce.current.onDecline?.({status:"declined",sessionId:Ce.current.sessionId,...F.reason?{reason:F.reason}:{},...F.message?{message:F.message}:{}})}),(async()=>(await sl(400),j.current&&q(null)))()},[]),Be=(0,Ye.useCallback)((u,F)=>{G.current?(G.current=!1,q({status:"error",wording:u,message:F.message}),setTimeout(()=>{j.current&&q(null)},400)):q(null),(0,He.invokeMerchantCallback)(()=>Ce.current.onError?.(F))},[]),at=(0,Ye.useCallback)(async u=>{let F=Z.current+1;Z.current=F;let D=()=>!j.current||F!==Z.current;G.current=!0,q({status:"processing",wording:"payment_method",message:null});let L=new ti.PaymentAPI((0,Tr.resolveBillingApiUrl)(Ce.current.billingApiUrl),{telemetry:Ce.current.telemetry});try{for(let T=0;T<Mp;T+=1){if((T>0||u.waitFirst)&&await sl(Ap),D())return;let I=await L.getUnifiedCheckoutSession(Ce.current.sessionId,Ce.current.nonce);if(D())return;let Ct=I.data.session?.status;if(Ct==="complete"){be(!0),kt("payment_method");return}if(Ct==="expired")throw new Tr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Tr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(T){if(D())return;let I=T instanceof Tr.FloPayError&&T.code==="payment_method_setup_unverified";Be("payment_method",fo(T,I?{retryable:!0}:{}))}finally{L.destroy()}},[Be,kt]);(0,Ye.useEffect)(()=>{let u=!0,F=(0,Tr.resolveBillingApiUrl)(a),D=new ti.PaymentAPI(F,{telemetry:s});Y(null),be(!1),oe(null),Ie(null),Rt(null);let L=new Set;return Ne.current=L,We(L),Ze.current=!1,Se.current=!1,K.current=!1,(async()=>{try{let{session:T,advertisement:I}=await Fp(D,r,n);if(!u)return;let Ct={advertisement:I,customer:xp(T),...T.futureUse?{futureUse:T.futureUse}:{},...T.futureUseUnsupported?{futureUseUnsupported:T.futureUseUnsupported}:{}};if(f){if((0,Pa.clearSetupRedirectParams)(),T.status==="complete"){be(!0),Y(Ct),kt("payment_method");return}f.failed?Pe("payment_method",{reason:"redirect_failed"}):at({waitFirst:!0})}let Mr=I.card?await Bp(D,T,r,n,F):null;if(!u)return;Y(Ct),Mr&&(Ie(Mr),oe(new ti.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:s})))}catch(T){if(!u)return;let I=fo(T);Ze.current=!0,Rt(I),(0,He.invokeMerchantCallback)(()=>Ce.current.onError?.(I))}})(),()=>{u=!1,D.destroy()}},[a,n,f,Pe,kt,r,s,at]),(0,Ye.useEffect)(()=>{if(!x)return;G.current=!1;let u=x.on("submitting",()=>{G.current=!0,q({status:"processing",wording:"card",message:null})}),F=x.on("complete",T=>{kt("card",T.paymentMethod)}),D=x.on("decline",T=>{Pe("card",{...T.declineReason?{reason:T.declineReason}:{},...T.message?{message:T.message}:{}})}),L=x.on("challenge_dismissed",()=>{q(null)});return()=>{u(),F(),D(),L()}},[x,Pe,kt]);let yt=(0,Ye.useCallback)((u,F,D)=>{if(D.retryable){Be("payment_method",fo(F,D));return}if(Ne.current.has(u))return;let L=new Set(Ne.current);L.add(u),Ne.current=L,We(L);let T=ve.current?.advertisement,I=T?(0,Nr.advertisedMethodKeys)(T).some(Ct=>!L.has(Ct)):!1;Be("payment_method",fo(F,{code:D.code,retryable:I}))},[Be]),Mt=(0,Ye.useMemo)(()=>({onSubmitting:()=>{G.current=!0,q({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{at({waitFirst:!1})},onDeclined:u=>Pe("payment_method",u),onValidation:u=>{(0,He.invokeMerchantCallback)(()=>Ce.current.onValidation?.(u))},onAbandoned:()=>{G.current=!1,q(null)}}),[Pe,at]),le=(0,Ye.useRef)(yt);le.current=yt;let It=(0,Ye.useRef)(new Map),Vt=u=>{let F=It.current.get(u);if(F)return F;let D=(L,T)=>le.current(u,L,T);return It.current.set(u,D),D},xe=(0,Ye.useCallback)(u=>{if(Ne.current.has(u))return;let F=new Set(Ne.current);F.add(u),Ne.current=F,We(F);let D=ve.current?.advertisement;D&&(0,Nr.advertisedMethodKeys)(D).some(T=>!F.has(T))||Be("payment_method",fo(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[Be]),Oe=(0,Ye.useRef)(xe);Oe.current=xe;let Ke=(0,Ye.useRef)(new Map),vt=u=>{let F=Ke.current.get(u);if(F)return F;let D=()=>Oe.current(u);return Ke.current.set(u,D),D},it=mt?(0,dr.jsx)(rn,{status:mt.status,errorMessage:mt.message,...(0,Nr.setupOverlayLabels)(mt.wording),successNote:null,...Pt?{theme:Pt}:{}}):null;if(ce)return(0,dr.jsx)("div",{role:"alert",children:ce.message});if(!H||b)return(0,dr.jsxs)(dr.Fragment,{children:[it,H?null:h]});let{advertisement:ft,customer:Lt,futureUse:Qe,futureUseUnsupported:st}=H,de=(0,Tr.resolveBillingApiUrl)(a),Ot=s===void 0?{}:{telemetry:s},et=ft.stripe.filter(({method:u})=>!Ve.has(u)),re=Ve.has("paypal")?null:ft.paypal,v=!!(ft.card&&x&&ge?.html),Q=({method:u,publishableKey:F,currency:D})=>(0,dr.jsx)("div",{"data-flopay-payment-method":u,style:{display:"contents"},children:(0,dr.jsx)(Zi,{onFailed:Vt(u),children:(0,dr.jsx)(Ye.Suspense,{fallback:null,children:(0,dr.jsx)(e,{method:u,category:(0,Nr.stripeMethodCategory)(u),publishableKey:F,currency:D,...Qe?{futureUse:Qe}:{},...st?{futureUseUnsupported:st}:{},sessionId:r,nonce:n,billingApiUrl:de,...Ot,...pe?{appearance:pe}:{},...we?{buttonsLayout:we}:{},...typeof d=="string"?{themeId:d}:{},...Mt,onFailed:Vt(u),onUnavailable:vt(u)})})})},u),ee=et.filter(({method:u})=>(0,Nr.stripeMethodCategory)(u)==="wallet"),$=et.filter(({method:u})=>(0,Nr.stripeMethodCategory)(u)!=="wallet"),nt=et.length>0||re!==null;return(0,dr.jsxs)(dr.Fragment,{children:[it,nt?(0,dr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ee.map(Q),re?(0,dr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,dr.jsx)(Zi,{onFailed:Vt("paypal"),children:(0,dr.jsx)(Ye.Suspense,{fallback:null,children:(0,dr.jsx)(t,{clientId:re.clientId,...re.environment?{environment:re.environment}:{},...ft.currency?{currency:ft.currency}:{},sessionId:r,nonce:n,billingApiUrl:de,customer:Lt,...Ot,...Mt,onFailed:Vt("paypal"),onUnavailable:vt("paypal")})})})}):null,$.map(Q)]}):null,v&&nt?(0,dr.jsx)(Ga,{label:"or add a card"}):null,v&&x&&ge?.html?(0,dr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,dr.jsx)(_o,{capture:x,html:ge.html,messageToken:ge.messageToken,expectedOrigin:ge.expectedOrigin,verificationRequired:ge.verificationRequired,theme:he,containerStyle:Ae,onReady:()=>{(0,He.invokeMerchantCallback)(()=>Ce.current.onReady?.())},onValidation:u=>{(0,He.invokeMerchantCallback)(()=>Ce.current.onValidation?.(u))},onError:u=>{u&&Be("card",fo(new Error(u),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var vd=require("react/jsx-runtime"),Op={StripeSetupMethod:gd,PayPalSetupMethod:dd};function Pd(e){return(0,vd.jsx)(hd,{...e,branches:Op})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});