@flopay/react 1.20.1 → 1.20.3
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/README.md +1 -0
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +7 -7
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as mc}from"./chunk-D4CVZRT4.mjs";import{c as At,d as xr,e as ba,f as hs,g as Ps,h as xu,j as Fu}from"./chunk-YR36EYW2.mjs";import{a as pc}from"./chunk-BU7THP6H.mjs";import{a as wo,b as ci,c as bs,d as Ss,e as wa,f as sc,g as lc,h as cc,i as dc,j as uc,k as yc}from"./chunk-FGCZOMML.mjs";import{a as ii,b as vs,c as rc,d as Cs,e as Wo,f as oc,g as io,h as si,i as ac,j as Sa,k as li,l as ic}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as CP}from"@flopay/shared";import{PaymentAPI as cl}from"@flopay/js";import{FloPayError as Mo,isDeclineCallbackFailure as Qm,isMerchantAuthRequired as iu,resolveBillingApiUrl as ef,resolveButtonsLayoutTheme as tf,resolveTheme as nf}from"@flopay/shared";import{useCallback as Or,useEffect as ca,useMemo as Ka,useRef as go,useState as da}from"react";import{Fragment as Go,jsx as sr,jsxs as fc}from"react/jsx-runtime";function Bu(){return fc(Go,{children:[fc("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:[sr("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),sr("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",sr("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:sr("path",{d:"M9 18l6-6-6-6"})})]})}function Du(){return sr(Go,{children:"Go back"})}function Ou(){return sr(Go,{children:"Secure card checkout"})}function Ho(e){return e!==void 0&&(e===""||e===null||e===!1)}function Ko({content:e}){return sr(Go,{children:e===void 0?sr(Bu,{}):e})}function Vo({content:e}){return sr(Go,{children:e===void 0?sr(Du,{}):e})}function ka({content:e}){return sr(Go,{children:e===void 0?sr(Ou,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as Lu,canRecoverHostedCardForm as Nu,classifyTelemetryFailure as Uu,FloPayError as Xn,isCardHolderNamePlaceholder as zu,isMoneySettledOutcome as qu,isMountableVaultBlock as ju,isSetupIntentClientSecret as $u,isValidEmail as Wu,resolveSetupFutureUsage as Hu,resolveWalletModeOptions as Ku}from"@flopay/shared";import{canRecoverHostedCardForm as ko,hasServerSideCardGateway as Ec}from"@flopay/shared";import{splitFullName as Ea}from"@flopay/shared";import{applyFriendlyMessageOverride as Xo}from"@flopay/shared";function ws(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Xn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Vu(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 gc(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(ju(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||Nu(o))||t&&e?.data.paypal?.publishableKey)}function hc(e,t){if(t&&(!(e instanceof Xn)||e.type==="authentication_error"))return ws(e);if(!(e instanceof Xn&&Vu(e))){if(!t&&!(e instanceof Xn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Uu(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Xn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Xn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Yo(e,t,n,o={}){let a;return(i={})=>{if(a!==void 0)return a;let s={...o,...i,email:i.email?.trim()||o.email?.trim()},c=zu(s.firstName,s.lastName);if(!Wu(s.email))return Promise.reject(new Xn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[S,P]of Object.entries(s)){if(c&&S.endsWith("Name")||typeof P!="string")continue;let f=P.trim();f&&(y[S]=f)}return a=e.claimCheckoutSession(t,n,{accountData:y}),a.catch(()=>{}),a}}function Pc(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function ks(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 vc(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],o=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(o*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:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Rs(e,t){return t?{...e,...t}:e}function mn(e,t,n){let o=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:o,...a?{code:a}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}var Cc=new WeakMap;function bc(e,t){return typeof e=="object"&&e!==null&&Cc.set(e,t?{sessionId:t}:{}),e}function Sc(e){return typeof e=="object"&&e!==null?Cc.get(e):void 0}function so(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Vr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Gr(e){return e?.status==="authorized"||e?.status==="complete"}function lo(e,t){if(e.data.session)return e.data.session;let n=e.raw,o=n?.latestTransactionAttempt?.result,a=n?.status==="authorized"||o==="AUTHORIZED";return a||n?.status==="completed"||o==="SUCCESS"?{...t,status:a?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function wc(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function di(e){let t=wc(e);return new Xn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ui(e){return e instanceof Xn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Jo(e){return wc(e)?new Xn("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Xn("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Xn(Lu,"api_error",{code:"checkout_processing_timeout"})}function Ra(e,t){return e==="processing"||qu(e,t)}function kc(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Rc(e,t){let n=e;if($u(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new Xn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:o,error:a}=await n.retrievePaymentIntent(t);if(a)throw new Xn(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var Gu=["apple_pay","google_pay"];function Ic(e,t="automatic",n){let o=Hu(n,Gu,"wallet");return{...Ku(e,t),allowedPaymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Yu=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:Yu.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Ia(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Fm,PaymentAPI as Bi,SESSION_CREATE_TELEMETRY as Bm}from"@flopay/js";import{buildCheckoutDisplayData as Dm,classifyTelemetryFailure as nu,DEFAULT_PAYMENT_METHOD_ORDER as Om,FloPayError as vn,isDeclineCallbackFailure as Wd,isDetachedSessionEligible as Lm,isExpectedPaymentDecline as Hd,isMerchantAuthRequired as Nm,isMountableVaultBlock as Um,resolveBillingApiUrl as zm,resolveButtonsLayoutTheme as qm,resolveDirectPaypalConfig as ru,resolveIdempotencyKey as Kd,resolveCheckoutLogLayout as jm,resolveTheme as ou,SDK_VERSION as au,telemetryStatusClass as $m,toPublicCheckoutInitError as Vd}from"@flopay/shared";import Li,{useCallback as In,useEffect as dr,useMemo as ur,useRef as zt,useState as Wt}from"react";import{Elements as Ju}from"@stripe/react-stripe-js";import{jsx as Xu}from"react/jsx-runtime";var Tc=new WeakMap,_c=0;function Mc(e){return!!e&&typeof e=="object"}function Ac(e,t){for(let n of e)!Mc(n)||t.includes(n)||(_c+=1,Tc.set(n,`stripe-account-${_c}`))}function co(e){let t=Mc(e.stripe)?Tc.get(e.stripe):void 0;return Xu(Ju,{...e},t)}import{createContext as xc}from"react";var lr=xc({flopay:null,paypalFlopay:null,billingApiUrl:""}),Cr=xc({session:null,loading:!1,error:null});import{PaymentAPI as _s}from"@flopay/js";import{buildPayPalCancelEvent as pp,buildPayPalProcessPaymentRequest as yp,buildPayPalSessionIntentRequest as mp,buildPayPalTokenizedBody as fp,classifyTelemetryFailure as gp,describePayPalProcessFailure as zc,FloPayError as ta,friendlyPayPalFailureMessage as hp,generateIdempotencyKey as Pp,isPayPalTeardownMessage as vp,isSettledSessionIntent as Cp,isValidEmail as qc,mergePayPalPayerIdentity as bp,needsPayPalPayerDetails as Sp,normalizeGatewayEnvironment as wp,paypalProviderIdentityRequired as jc,resolvePayPalApprovalIdentity as kp,resolvePayPalDeclineReason as Rp,SDK_VERSION as Ip,usesPayPalVaultedChannel as Ep}from"@flopay/shared";import{loadScript as _p}from"@paypal/paypal-js";import{useCallback as cr,useContext as Tp,useEffect as qt,useMemo as Aa,useRef as ot,useState as Yr}from"react";import{compactBuyerIdentity as Zu,isValidEmail as Qu}from"@flopay/shared";import{useCallback as Fc,useEffect as ep,useRef as Bc,useState as Oc}from"react";import{compactBuyerIdentity as br}from"@flopay/shared";import{jsx as Dc,jsxs as _a}from"react/jsx-runtime";function Zo(){let[e,t]=Oc(null),n=Bc(null),o=Bc(0),a=Fc((s,c)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:c}),new Promise(y=>{n.current=y})),[]),i=Fc(s=>{let c=n.current;n.current=null,t(null),c?.(s)},[]);return ep(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function Qo({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,c]=Oc(e.email?.trim()??""),y=Qu(s.trim());return _a("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[_a("div",{style:{fontWeight:700},children:["Continue with ",t]}),_a("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Dc("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:S=>c(S.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),_a("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&Dc("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),_a("button",{type:"button",disabled:!y||a,onClick:()=>{n(Zu({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as tp}from"@flopay/shared";import{useContext as pi}from"react";function uo(){return pi(lr).flopay}function Es(){return pi(lr).paypalFlopay??null}function np(){return pi(Cr)}function Lc(){return pi(lr).billingApiUrl||tp()}import{FLO_INSTRUMENT_ONCE_NAMES as rp,invokeMerchantCallback as op,projectFloInstrument as ap}from"@flopay/shared";import{useCallback as ip,useRef as yi}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Nc}from"@flopay/shared";function ea(e,t){let n=yi(e);n.current=e;let o=yi(new Set),a=yi(t),i=yi(t);return ba(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),ip(s=>{if(i.current!==t)return;let c=ap(s);if(c){if(rp.has(c.name)){if(o.current.has(c.name))return;o.current.add(c.name)}op(()=>n.current?.(c))}},[t])}import{createContext as sp}from"react";var Ta=sp(null);function mi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var fi="provider.callback.ignored";function gi(){let e,t=0;return{take(n){return n!==e&&(e=n,t=0),t>=5?!1:(t+=1,!0)}}}var lp=Symbol.for("@flopay/js.telemetry.bridge.v1"),cp=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function dp(){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 up(e){let t=dp(),n=(a,i)=>a?a.bind(e):i,o=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:o,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,o()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function hi(e){let t=globalThis[cp];return up(t?.(e)??{})}function fn(e){if(e)return e[lp]}import{useCallback as po,useEffect as Uc,useRef as Ro}from"react";function Ma(e,t){let n=Ro(0),o=Ro(null),a=Ro(null),i=Ro(e),s=Ro(t?.onHandoffObserved),c=Ro(t?.defersMissingTerminal),y=Ro(t?.onMissingTerminalDeferred);Uc(()=>{i.current=e,s.current=t?.onHandoffObserved,c.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let S=po((C=a.current)=>{C?.timer&&(clearTimeout(C.timer),C.timer=null)},[]),P=po(C=>{S();let ge=n.current+1;return n.current=ge,o.current=null,a.current={generation:ge,method:C,timer:null,yieldedControl:!1},ge},[S]),f=po(C=>{let ge=a.current;return C!==void 0&&ge?.generation!==C?!1:(S(ge),a.current=null,(C===void 0||o.current===C)&&(o.current=null),!0)},[S]),F=po(C=>{let ge=a.current,ue=C??ge?.generation??n.current;(C===void 0||ge?.generation===C)&&(S(ge),a.current=null),o.current=ue},[S]),te=po(C=>o.current===(C??n.current),[]),ae=po(C=>a.current?.generation===C&&o.current!==C,[]),z=po(()=>{let C=a.current;C&&(S(C),!C.yieldedControl&&(C.yieldedControl=!0,s.current?.(C.method)))},[S]),K=po(()=>{let C=a.current;!C?.yieldedControl||document.visibilityState!=="visible"||(S(C),C.timer=setTimeout(()=>{if(C.timer=null,a.current?.generation===C.generation){if(c.current?.(C.method)){y.current?.(C.method,C.generation);return}a.current=null,o.current=C.generation,i.current(C.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},rc))},[S]);return Uc(()=>{let C=()=>{document.visibilityState==="visible"?K():z()};return document.addEventListener("visibilitychange",C),window.addEventListener("blur",z),window.addEventListener("focus",K),()=>{document.removeEventListener("visibilitychange",C),window.removeEventListener("blur",z),window.removeEventListener("focus",K),S()}},[S,z,K]),{startAttempt:P,finishAttempt:f,invalidateAttempt:F,isAttemptInvalidated:te,isAttemptCurrent:ae,generationRef:n}}import{jsx as Io,jsxs as Ts}from"react/jsx-runtime";var Pi=45,Mp=1e3,Ap=11e3,$c="paypal_intent_settled",xp={width:"100%",minHeight:Pi,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},Fp={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 Bp(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Fp[e.kind]??null}}function Wc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":oc(t)?"paypal_init_timeout":"paypal_init_failure"}function Dp(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Hc({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:c,currency:y,isSubscription:S,providerObjectType:P,approvalPresentation:f,onTokenizedBody:F,onComplete:te,onErrorChange:ae,onDecline:z,onCancel:K,onTechnicalFailure:C,isProcessing:ge=!1,onLoadStateChange:ue,onInitializationStateChange:w,allowAutomaticRetry:Ke=!0,onButtonClick:X,runBeforeButtonClick:Ne,session:at,existingOrderId:pt,telemetry:Ie,telemetryContext:Bt,onInstrument:xt,debug:Re=!1}){let Ye=uo(),it=ea(xt,e),st=Aa(()=>{if(Ye)return null;let R=hi({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ip,enabled:Ie!==!1});return R.setCheckoutContext(Bt??{}),R.beginCheckout(Bt??{}),R},[n,Ye,Ie,Bt?.checkoutMode,Bt?.layout]),Ee=Aa(()=>fn(Ye),[Ye]);qt(()=>()=>{st&&st.flush().catch(()=>{}).finally(()=>st.destroy())},[st]);let ne=Aa(()=>({error:R=>{Ee?Ee.error(R):st?.error(R),it({class:"technical_error",errorCode:R.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":R.errorCode,requestCategory:R.requestCategory,provider:R.provider})},log:R=>{Ee?Ee.log(R):st?.log(R),it({class:"lifecycle",name:R.name,provider:R.provider})},performance:R=>{Ee?Ee.performance(R):st?.performance(R)},terminal:R=>{Ee?Ee.terminal(R):st?.terminal(R)},startTiming:()=>Ee?.now()??st?.now()??0,elapsed:R=>Ee?.elapsed(R)??Math.max(0,(st?.now()??R)-R)}),[it,Ee,st]),pe=ot(null),jt=ot(0),qe=ot(null),lt=ot(null),re=ot(null),Me=Tp(Ta),Ze=ot(null);Ze.current||(Ze.current=mi());let V=Me??Ze.current,vt=ot(null),be=ot(!1),[Je,Ue]=Yr(!1),[Qe,Ct]=Yr(!1),[Be,kt]=Yr(0),Ae=ot(0),[_e,bt]=Yr(!1),Ft=ot(!1),Rt=ot(!1),[G,ye]=Yr(!1),[Te,ct]=Yr(!1),{request:dt,collect:Ve,finish:yt}=Zo(),mt=ot({sessionId:e,required:jc(o,at)});mt.current.sessionId!==e&&(mt.current={sessionId:e,required:jc(o,at)});let St=mt.current.required,je=Aa(()=>n.replace(/\/+$/,""),[n]),et=at?.gateways?.paypal?.providerObjectType??P,q=et??(S?"subscription":"order"),[hn]=Yr(Sa),b=at?.gateways?.paypal?.approvalPresentation??f,g=li(hn,b==="app_switch"?"app_switch":void 0,q),Y=Ep(et),j=Aa(()=>JSON.stringify([je,s,y,c??"",q,Y,g,e,pt??""]),[je,s,y,c,pt,q,Y,g,e]),J=ot(j),h=J.current!==j,se=ot(Re),$=ot(null),[Se,we]=Yr([]),k=cr(R=>{se.current&&we(We=>[...We,`${new Date().toISOString().slice(11,23)} ${R}`])},[]);qt(()=>{se.current=Re,Re&&k("debug:enabled"),$.current?.setEnabled(Re)},[k,Re]);let tt=ot(F),Ht=ot(te),Dt=ot(ae),Dn=ot(z),ve=ot(K),kr=ot(C),dn=ot(X),un=ot(ue),nt=ot(w),Tt=ot(i),En=ot(Ne),_n=ot(at),Tn=ot(o),Cn=ot(a),bn=ot(t),Kt=ot(null),Ot=ot(new Map),Xt=ot(new Map),Ge=ot(!1),me=ot(e);me.current=e;let[er]=Yr(gi);qt(()=>(Ge.current=!0,()=>{Ge.current=!1}),[]),qt(()=>{tt.current=F},[F]),qt(()=>{Tt.current=i},[i]),qt(()=>{Ht.current=te},[te]),qt(()=>{Dt.current=ae},[ae]),qt(()=>{Dn.current=z},[z]),qt(()=>{ve.current=K},[K]),qt(()=>{kr.current=C},[C]),qt(()=>{dn.current=X},[X]),qt(()=>{un.current=ue},[ue]),qt(()=>{nt.current=w},[w]),qt(()=>{En.current=Ne},[Ne]),qt(()=>{_n.current=at},[at]),qt(()=>{Tn.current=o},[o]),qt(()=>{Cn.current=a},[a]),qt(()=>{bn.current=t},[t]),qt(()=>{Ae.current=Be},[Be]),qt(()=>{_e&&vt.current?.focus()},[_e,Be]);let Mt=cr(()=>{window.setTimeout(()=>{vt.current?.focus()},0)},[]),Mn=cr(()=>{Ue(!1),kt(R=>R+1)},[]),On=cr(()=>{bt(!1),(pe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??pe.current)?.focus?.()},[]);qt(()=>{!Je||!be.current||(be.current=!1,On())},[On,Je,Be]);let tr=cr((R,We)=>{let v=We?.popupBlocked??io(R);v&&V.markBlocked();let le=ii("PayPal",v,hn.inAppBrowser),ut=kr.current;if(ut){let He=v&&hn.inAppBrowser?new ta(le,"api_error",{code:We?.code??"paypal_popup_blocked"}):R;ut("paypal",He,We);return}if(R instanceof ta&&R.code==="checkout_processing_timeout"){Dt.current?.(R.message);return}Dt.current?.(le)},[V,hn.inAppBrowser]),Ln=cr(R=>{let We=qe.current,v=lt.current;We===null||!v||(ne.log({...v,popupCapability:V.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:R}),ne.performance({...v,popupCapability:V.current(),stage:"overlay_return",durationMs:ne.elapsed(We),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:R}),qe.current=null)},[V,ne]),Rr=cr((R,We,v)=>{let le=lt.current;Ln("overlay_timeout"),le&&ne.error({...le,popupCapability:V.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),tr(We,{...v,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:g,terminalReason:"overlay_timeout"}),bt(!0),Mn(),Mt()},[Ln,Mt,tr,V,g,Mn,ne]),pr=cr(()=>{V.markAvailable();let R=lt.current;R&&(re.current=R.attempt,ne.log({...R,popupCapability:V.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[V,ne]),pn=cr(()=>!0,[]),yn=cr(()=>{let R=lt.current;if(!R)return;let We=qe.current;ne.performance({...R,popupCapability:V.current(),stage:"overlay_return",durationMs:We===null?0:ne.elapsed(We),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[V,ne]),{finishAttempt:An,generationRef:Kn,invalidateAttempt:Nn,isAttemptCurrent:xn,isAttemptInvalidated:rn,startAttempt:Zt}=Ma(Rr,{onHandoffObserved:pr,defersMissingTerminal:pn,onMissingTerminalDeferred:yn}),Qt=cr(()=>(bt(!1),Zt("paypal")),[Zt]),Vt=cr(R=>{Nn(R?.generation),R?.showRetry&&bt(!0),R?.remount&&Mn(),R?.focus!==!1&&Mt()},[Mt,Nn,Mn]),Un=R=>{let We=Kt.current;return We&&Xt.current.set(R,We),R};qt(()=>{J.current!==j&&(J.current=j,Ft.current=!1,Rt.current=!1,Ue(!1),Ct(!1),ye(!1),nt.current?.("loading"))},[j]),qt(()=>{At(()=>un.current?.(Je&&!G))},[Je,G]);let zn=wp(c);qt(()=>{let R={attempt:Kn.current+1,inAppBrowser:hn.inAppBrowser,appFamily:hn.appFamily,popupCapability:V.current(),presentationMode:g},We=()=>({...lt.current??R,popupCapability:V.current()}),v={error:d=>ne.error({...d,...We()}),log:d=>ne.log({...d,...We()}),performance:d=>ne.performance({...d,...We()}),terminal:d=>ne.terminal({...d,...We()}),startTiming:ne.startTiming,elapsed:ne.elapsed},le=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",ut=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(k(`mount clientId=${le} env=${c??"(unset)"}\u2192${zn??"live"} ccy=${y} sub=${S}`),k(`ua=${ut.slice(0,80)}${ut.length>80?"\u2026":""}`),!s){k("FAIL: clientId empty \u2014 gateway misconfigured"),ye(!0),v.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(!pe.current){k("FAIL: containerRef not attached");return}jt.current=v.startTiming(),v.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let He=!1,Lt=!1,ke=()=>He||Lt,Ir=d=>{let p=Ge.current,u=p?d:"torn_down";p&&k(`onError ignored reason=${u}`),er.take(me.current)&&v.log({name:fi,stage:"provider_ready",reason:u,provider:"paypal",paymentMethodCategory:"paypal"})},Lr=()=>me.current===e?"stale_attempt":"session_changed",on=Y?q:void 0,ce,Nr=!1,Xr=()=>{ce=Pp(),ce||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Nr=!0},Zr=null,Qr=!1,yr=null,Er=!1,Vn=()=>{!yr||Er||(Er=!0,yr.close().catch(()=>{}))},qn=!1,mr=!1,Bn=pe.current,Nt=null,nr=null,Ce=[],Sn=null,Gn=!1,Ur=!1,fr=null,gr=d=>{if(!d||typeof d.getBoundingClientRect!="function")return"(no rect)";let p=d.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},zr=d=>{if(!d)return"(empty)";try{let p=new URL(d,typeof window>"u"?"https://localhost":window.location.href),u=p.pathname.toLowerCase();return u.includes("checkcaptcha")||u.includes("captcha")?`CAPTCHA(${p.host}${u})`:u.includes("risk")||u.includes("challenge")?`RISK(${p.host}${u})`:u.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${u}`.slice(0,100)}catch{return d.slice(0,80)}},eo=d=>{let p=d.getAttribute("src"),u=d.getAttribute("srcdoc"),N=d.getAttribute("name"),x=d.getAttribute("sandbox"),H=[];return p&&H.push(`src=${zr(p)}`),u&&H.push(`srcdoc[${u.length}ch]`),!p&&!u&&H.push("src=(empty) srcdoc=(empty)"),N&&H.push(`name=${N.slice(0,40)}`),x!==null&&H.push(`sandbox="${x.slice(0,40)}"`),H.join(" ")},Ao=d=>{if(!(d instanceof HTMLIFrameElement))return"";try{let p=d.contentDocument;if(!p)return"cd=null";let u=p.body?.children.length??0,N=p.body?.innerHTML.length??0,x=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${u}children,${N}ch] head[${x}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},qr=[],jr=d=>{if(ke())return;let p=d.message??String(d.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(k(`window:error ${p.slice(0,140)}`),qr.push(p))},$r=d=>{if(ke())return;let p=d.reason instanceof Error?d.reason.message:String(d.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(k(`window:rejection ${p.slice(0,140)}`),qr.push(p))},Wr={value:0},ho=()=>{Nt?.disconnect(),Nt=null,nr?.disconnect(),nr=null;for(let d of Ce.splice(0))clearTimeout(d);Ur=!1,Gn&&typeof window<"u"&&(window.removeEventListener("error",jr),window.removeEventListener("unhandledrejection",$r)),Gn=!1},Hr=()=>{if(!(Gn||ke()||qn)){if(Gn=!0,qr.length=0,Wr.value=0,typeof window<"u"&&(window.addEventListener("error",jr),window.addEventListener("unhandledrejection",$r)),typeof PerformanceObserver<"u")try{nr=new PerformanceObserver(d=>{if(!ke())for(let p of d.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;Wr.value+=1;let u=Math.round(p.duration);k(`net ${u}ms ${p.name.slice(0,90)}`)}}),nr.observe({type:"resource",buffered:!0})}catch{}fr?.()}},Ut=()=>{Sn&&(clearTimeout(Sn),Sn=null)},rr=()=>{ho(),Ut()},jn={setEnabled:d=>{d?Hr():ho()}};$.current=jn,se.current&&Hr();let wn=vp,$n=d=>{if(ke()||wn(d))return;let p=Xo(d)??d;At(()=>Dt.current?.(p))},ze=(d,p)=>{if(He||Qr)return;Qr=!0,Lt=!0,rr(),Vn();let u=Bp({kind:d,generationActive:!0,automaticRetryAllowed:Ke,automaticRetryUsed:Ft.current});if(u.action==="retry"){Ft.current=!0,Ue(!1),ct(!1),Ct(!0),nt.current?.("retrying"),Zr=setTimeout(()=>{He||kt(N=>N+1)},Mp);return}if(Ue(!1),ct(!1),Ct(!1),ye(!0),u.action!=="ignore"){if(nt.current?.("exhausted"),u.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",p);return}if(u.report){let N=vs({code:Wc(d,p),message:p},{inAppBrowser:hn.inAppBrowser,handoffObserved:!1});N.popupBlocked&&V.markBlocked(),v.error({errorCode:N.popupBlocked?N.errorCode:u.report.errorCode,stage:u.report.stage,operationOutcome:u.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:N.terminalReason})}Rt.current||(Rt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Wc(d,p)))}};ye(!1);let kn=async(d,p=Kt.current)=>{if(ke())return;let u=p?.sessionId??e;if(tt.current){await tt.current(d,{sessionId:u,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let N=v.startTiming();v.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let x=()=>{v.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),v.performance({stage:"processing",durationMs:v.elapsed(N),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let H=yp({body:d,sessionId:u,nonce:p?.nonce??bn.current,accountPatch:p?.accountPatch,session:_n.current,email:Tn.current}),Z=await new _s(je,{telemetry:!1}).processPayment(H.userId,H.params);if(Z.ok){if(Lt||He&&Ge.current)return;x(),v.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),At(()=>Ht.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ke())return;let ie=await Z.json().catch(()=>null),gt=zc(ie),Gt=gt.message;x(),Z.status===400&&(typeof ie?.declineCode=="string"||!Array.isArray(ie?.fields))?v.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Z.status===400||Z.status===422?v.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):v.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Dp(Z.status),failureCategory:Z.status>=500?"server_error":void 0}),$n(Gt),At(()=>Dn.current?.(mn("paypal",Gt,{code:gt.code,declineCode:gt.declineCode})));return}catch(H){if(ke())return;x(),v.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let B=hp(H instanceof Error?H.message:void 0);$n(B),At(()=>Dn.current?.(mn("paypal",B)));return}},$t=()=>new ta("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),to=d=>ke()?Promise.reject($t()):Promise.resolve(d),or=async d=>{if(d.ok){v.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),At(()=>Ht.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let p=await d.json().catch(()=>null),u=zc(p);v.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),At(()=>Dn.current?.(mn("paypal",u.message,{code:u.code,declineCode:u.declineCode})))},I=()=>{let d=Kt.current;Ln("approved"),d&&(Ot.current.delete(d.surfaceKey),An(d.generation)),Kt.current=null},E=async d=>{if(ke())throw $t();Nr||Xr();let p=Kt.current,u=p?.sessionId??e,N=p?.nonce??bn.current;v.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let x;try{x=await new _s(je,{telemetry:!1}).createSessionIntent(u,N??"",mp(on),{idempotencyKey:ce})}catch(H){throw v.error({...gp(H,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),H}if(ke())throw $t();if(Cp(x))throw await or(x.response),I(),new ta("PayPal checkout already settled.","api_error",{code:$c});if(x.provider!=="paypal"||x.providerObjectType!==q)throw new Error(d);return v.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),x.providerObjectId},W=(d,p)=>{let u=p?.nonce??bn.current;if(!u)return;let N=p?.sessionId??e,x=Rp(d);new _s(je,{telemetry:!1}).reportSessionIntentDecline(N,u,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:x}).catch(()=>{})},_=Be;k("loadScript:scheduled (deferred 1 tick)");let De=null,an=setTimeout(()=>{if(He){k("loadScript:skipped (cancelled before defer ran)");return}k("loadScript:start");let d=zn==="live"?"production":zn,p={};q==="subscription"?p={intent:"subscription",vault:!0}:q==="order"&&(p={intent:"capture"}),De=_p({clientId:s,currency:y,...p,...d?{environment:d}:{},...d==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let u=!1;De.then(N=>{if(u=!0,k(`loadScript:resolved inactive=${ke()} ns=${!!N} buttons=${!!N?.Buttons}`),ke())return;if(!N?.Buttons){k("FAIL: namespace missing Buttons factory"),ze("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}v.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),v.performance({stage:"provider_ready",durationMs:v.elapsed(jt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),v.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let x=async(T,D)=>{if(ke()||Ae.current!==_)return;let O=T.vaultSetupToken??T.subscriptionID??T.orderID??"",M=O?Xt.current.get(O):Ot.current.get(_);if(!(!M||!xn(M.generation))&&An(M.generation)){Xt.current.delete(O),Ot.current.delete(M.surfaceKey),Ln("approved");try{if(ct(!0),At(()=>Dt.current?.(null)),!O)throw new ta("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Q=kp({accountPatch:M.accountPatch,email:Tn.current,billingName:Cn.current,session:_n.current});if(Sp(Q))try{Q=bp(Q,await D?.order?.get?.())}catch{}if((Tt.current||St)&&!qc(Q.email)){let he=await Ve("PayPal",Q);if(!he)return;Q=he}qc(Q.email)&&(M.accountPatch=br({...M.accountPatch,...Q}),await Tt.current?.(Q));let wt=fp(O,on);await kn(wt,M)}catch(Q){$n(Q instanceof Error?Q.message:"PayPal capture failed.")}finally{ke()||ct(!1)}}},H=T=>{let D=pt?()=>to(pt):()=>E(T);return async()=>Un(await D())},B=N.Buttons({style:{layout:"horizontal",height:Pi,tagline:!1},...g==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(T,D)=>{if(ke()){await D.reject();return}Xr();let O=En.current,M={};if(O)try{let he=await O("paypal");if(ke()){await D.reject();return}if(!he.proceed){Kt.current=null,Ot.current.delete(_),await D.reject();return}M={sessionId:he.sessionId,accountPatch:he.accountPatch,nonce:he.nonce}}catch(he){k(`onClick:runBeforeButtonClick rejected msg=${(he instanceof Error?he.message:String(he)).slice(0,120)}`),Kt.current=null,Ot.current.delete(_),await D.reject();return}At(()=>dn.current?.("paypal"));let Q=Qt(),wt={generation:Q,surfaceKey:_,...M};Kt.current=wt,Ot.current.set(_,wt),lt.current={...R,attempt:Q},await D.resolve(),v.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),v.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),qe.current=v.startTiming()},createOrder:q==="order"?H("Failed to create PayPal order."):void 0,createSubscription:q==="subscription"?H("Failed to create PayPal subscription."):void 0,createVaultSetupToken:q==="setup_token"?async()=>Un(await E("Failed to create PayPal setup token.")):void 0,onApprove:x,onCancel:()=>{if(ke())return;let T=Ot.current.get(_)??Kt.current,D=T&&xn(T.generation)?pp(T.sessionId??e,on):null;T&&Ot.current.delete(T.surfaceKey),Kt.current=null,Ln("cancelled"),v.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be.current=!0,Vt({generation:T?.generation,remount:!0,focus:!1}),D&&At(()=>ve.current?.(D))},onError:T=>{if(T instanceof ta&&T.code===$c)return;let D=T instanceof Error?T.message:"PayPal failed to render.";if(ke()||Ae.current!==_){wn(D)||Ir(Lr());return}if(qn){let O=Ot.current.get(_)??Kt.current;if(!O||!xn(O.generation)){if(wn(D)){!O&&!rn()&&An();return}Ir(O||rn()?"stale_attempt":"no_current_attempt");return}if(k(`onError rendered=${qn} msg=${D.slice(0,120)}`),wn(D)){An(O.generation);return}let{errorCode:M,popupBlocked:Q,providerDeclined:wt,terminalReason:he}=vs(T,{inAppBrowser:hn.inAppBrowser,handoffObserved:re.current===O.generation});if(Q&&V.markBlocked(),Ln(he),wt){v.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:he}),W(T,O),At(()=>Dn.current?.(mn("paypal",D))),Ot.current.delete(O.surfaceKey),Kt.current=null,An(O.generation);return}v.error({errorCode:M,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:he}),Ot.current.delete(O.surfaceKey),Kt.current=null,Vt({generation:O.generation,remount:!0,showRetry:!0,focus:!0}),tr(T,{code:"paypal_runtime_failed",popupBlocked:Q,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:g,terminalReason:he});return}k(`onError rendered=${qn} msg=${D.slice(0,120)}`),ze(wn(D)?"teardown":"pre_ready_callback",D)}}),Z=B.isEligible();if(k(`isEligible=${Z}`),v.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Z){Ue(!1),ze("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}mr=!0,yr=B,fr=()=>{if(!Gn||Ur||ke()||qn)return;Ur=!0,k(`container:dims ${gr(Bn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Nt=new MutationObserver(D=>{if(!ke()){for(let O of D)if(O.type==="childList")O.addedNodes.forEach(M=>{if(!(M instanceof Element))return;let Q=M.tagName.toLowerCase(),wt=(M.getAttribute("title")??"").slice(0,40),he=Q==="iframe"?` ${eo(M)}`:"";k(`child+ ${Q}${wt?` title="${wt}"`:""}${he} dims=${gr(M)}`)});else if(O.type==="attributes"&&O.target instanceof Element){let M=O.target;if(M.tagName.toLowerCase()!=="iframe")continue;let Q=O.attributeName;(Q==="src"||Q==="srcdoc")&&k(`attr~ iframe ${Q}=${Q==="srcdoc"?`[${(M.getAttribute("srcdoc")??"").length}ch]`:zr(M.getAttribute("src"))} dims=${gr(M)}`)}}}),Nt.observe(Bn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let T=D=>{if(ke()||qn)return;let O=Bn.querySelectorAll("iframe"),M=typeof document<"u"&&"hasStorageAccess"in document;k(`watchdog:${D} container=${gr(Bn)} children=${Bn.childElementCount} iframes=${O.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${M} paypalNetRequests=${Wr.value}`),O.forEach((Q,wt)=>{let he=(Q.getAttribute("title")??"").slice(0,40);k(` iframe[${wt}] ${gr(Q)}${he?` title="${he}"`:""} ${eo(Q)}`);let sn=Ao(Q);sn&&k(` ${sn}`)}),qr.length===0&&k(" (no PayPal/zoid window errors captured)")};Ce.push(setTimeout(()=>T("3s"),3e3)),Ce.push(setTimeout(()=>T("8s"),8e3)),Ce.push(setTimeout(()=>T("15s"),15e3))},fr(),k("render:start");let gt=v.startTiming();Sn=setTimeout(()=>{ke()||qn||(k("watchdog:11s retryable render timeout"),ze("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Ap);let Gt=B.render(Bn);(async()=>{try{if(await Gt,k(`render:resolved inactive=${ke()}`),rr(),ke()){Vn();return}qn=!0,Ue(!0),Ct(!1),nt.current?.("ready"),v.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),v.performance({stage:"checkout_render",durationMs:v.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(T){let D=T instanceof Error?T.message:"PayPal failed to render.";k(`render:rejected msg=${D.slice(0,120)}`),rr(),ze(wn(D)?"teardown":"render_rejected",D)}})()}).catch(N=>{let x=N instanceof Error?N.message:"PayPal operation failed.";k(`provider:failed msg=${x.slice(0,120)}`);let H="script_rejected";u&&wn(x)?H="teardown":u&&mr&&(H="render_rejected"),ze(H,x)})},0);return()=>{He=!0,clearTimeout(an),Zr&&clearTimeout(Zr),rr(),$.current===jn&&($.current=null),Vn(),qe.current=null,lt.current=null}},[Ke,je,s,y,c,q,g,Y,e,pt,Be,ne,Ve,St,k,Ln]);let Fn=Re?Ts("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:G?"#fef2f2":"#f3f4f6",border:`1px solid ${G?"#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=${Je} failed=${G})`,Se.length===0?`
|
|
1
|
+
import{a as fc}from"./chunk-D4CVZRT4.mjs";import{c as Ft,d as Ur,e as wa,f as Ps,g as vs,h as Fu,j as Bu}from"./chunk-YR36EYW2.mjs";import{a as yc}from"./chunk-BU7THP6H.mjs";import{a as Eo,b as ui,c as Ss,d as ws,e as Ra,f as lc,g as cc,h as dc,i as uc,j as pc,k as mc}from"./chunk-FGCZOMML.mjs";import{a as li,b as Cs,c as oc,d as bs,e as Ho,f as ac,g as so,h as ci,i as ic,j as ka,k as di,l as sc}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as bP}from"@flopay/shared";import{PaymentAPI as dl}from"@flopay/js";import{FloPayError as Bo,isDeclineCallbackFailure as ef,isMerchantAuthRequired as lu,resolveBillingApiUrl as tf,resolveButtonsLayoutTheme as nf,resolveTheme as rf}from"@flopay/shared";import{useCallback as $r,useEffect as ua,useMemo as Ga,useRef as ho,useState as pa}from"react";import{Fragment as Jo,jsx as ur,jsxs as gc}from"react/jsx-runtime";function Du(){return gc(Jo,{children:[gc("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:[ur("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),ur("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",ur("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:ur("path",{d:"M9 18l6-6-6-6"})})]})}function Ou(){return ur(Jo,{children:"Go back"})}function Lu(){return ur(Jo,{children:"Secure card checkout"})}function Vo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Go({content:e}){return ur(Jo,{children:e===void 0?ur(Du,{}):e})}function Yo({content:e}){return ur(Jo,{children:e===void 0?ur(Ou,{}):e})}function Ia({content:e}){return ur(Jo,{children:e===void 0?ur(Lu,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as Nu,canRecoverHostedCardForm as Uu,classifyTelemetryFailure as zu,FloPayError as er,isCardHolderNamePlaceholder as qu,isMoneySettledOutcome as ju,isMountableVaultBlock as $u,isSetupIntentClientSecret as Wu,isValidEmail as Ku,resolveSetupFutureUsage as Hu,resolveWalletModeOptions as Vu}from"@flopay/shared";import{canRecoverHostedCardForm as _o,hasServerSideCardGateway as _c}from"@flopay/shared";import{splitFullName as Ta}from"@flopay/shared";import{applyFriendlyMessageOverride as Qo}from"@flopay/shared";function ks(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof er&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Gu(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 hc(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&($u(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||Uu(o))||t&&e?.data.paypal?.publishableKey)}function Pc(e,t){if(t&&(!(e instanceof er)||e.type==="authentication_error"))return ks(e);if(!(e instanceof er&&Gu(e))){if(!t&&!(e instanceof er)&&(e instanceof TypeError||e instanceof SyntaxError))return{...zu(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof er)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof er))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Xo(e,t,n,o={}){let a;return(i={})=>{if(a!==void 0)return a;let l={...o,...i,email:i.email?.trim()||o.email?.trim()},u=qu(l.firstName,l.lastName);if(!Ku(l.email))return Promise.reject(new er("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[R,C]of Object.entries(l)){if(u&&R.endsWith("Name")||typeof C!="string")continue;let g=C.trim();g&&(m[R]=g)}return a=e.claimCheckoutSession(t,n,{accountData:m}),a.catch(()=>{}),a}}function vc(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Rs(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 Cc(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],o=n.reduce((i,l)=>i+(l.overrideAmount??l.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(o*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:n.map((i,l)=>({uuid:`synthetic-${i.type??"item"}-${l}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Is(e,t){return t?{...e,...t}:e}function gn(e,t,n){let o=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,l=typeof t=="string"?void 0:t.sessionId;return{method:e,message:o,...a?{code:a}:{},...i?{declineCode:i}:{},...l?{sessionId:l}:{}}}var bc=new WeakMap;function Sc(e,t){return typeof e=="object"&&e!==null&&bc.set(e,t?{sessionId:t}:{}),e}function wc(e){return typeof e=="object"&&e!==null?bc.get(e):void 0}function lo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Jr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Xr(e){return e?.status==="authorized"||e?.status==="complete"}function co(e,t){if(e.data.session)return e.data.session;let n=e.raw,o=n?.latestTransactionAttempt?.result,a=n?.status==="authorized"||o==="AUTHORIZED";return a||n?.status==="completed"||o==="SUCCESS"?{...t,status:a?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function kc(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function pi(e){let t=kc(e);return new er(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function yi(e){return e instanceof er||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Zo(e){return kc(e)?new er("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new er("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new er(Nu,"api_error",{code:"checkout_processing_timeout"})}function Ea(e,t){return e==="processing"||ju(e,t)}function Rc(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Ic(e,t){let n=e;if(Wu(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:l}=await n.retrieveSetupIntent(t);if(l)throw new er(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:o,error:a}=await n.retrievePaymentIntent(t);if(a)throw new er(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var Yu=["apple_pay","google_pay"];function Ec(e,t="automatic",n){let o=Hu(n,Yu,"wallet");return{...Vu(e,t),allowedPaymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Ju=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Es(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:Ju.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function _a(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Bm,PaymentAPI as Oi,SESSION_CREATE_TELEMETRY as Dm}from"@flopay/js";import{applyClaimAdvertisement as Kd,buildCheckoutDisplayData as Om,classifyTelemetryFailure as ou,DEFAULT_PAYMENT_METHOD_ORDER as Lm,FloPayError as kn,isDeclineCallbackFailure as Hd,isDetachedSessionEligible as Nm,isExpectedPaymentDecline as Vd,isMerchantAuthRequired as Um,isMountableVaultBlock as zm,resolveBillingApiUrl as qm,resolveButtonsLayoutTheme as jm,resolveDirectPaypalConfig as au,resolveIdempotencyKey as Gd,resolveCheckoutLogLayout as $m,resolveTheme as iu,SDK_VERSION as su,telemetryStatusClass as Wm,toPublicCheckoutInitError as Yd}from"@flopay/shared";import Ui,{useCallback as pn,useEffect as ir,useMemo as mr,useRef as Bt,useState as Jt}from"react";import{Elements as Xu}from"@stripe/react-stripe-js";import{jsx as Zu}from"react/jsx-runtime";var Mc=new WeakMap,Tc=0;function Ac(e){return!!e&&typeof e=="object"}function xc(e,t){for(let n of e)!Ac(n)||t.includes(n)||(Tc+=1,Mc.set(n,`stripe-account-${Tc}`))}function uo(e){let t=Ac(e.stripe)?Mc.get(e.stripe):void 0;return Zu(Xu,{...e},t)}import{createContext as Fc}from"react";var pr=Fc({flopay:null,paypalFlopay:null,billingApiUrl:""}),wr=Fc({session:null,loading:!1,error:null});import{PaymentAPI as Ts}from"@flopay/js";import{buildPayPalCancelEvent as yp,buildPayPalProcessPaymentRequest as mp,buildPayPalSessionIntentRequest as fp,buildPayPalTokenizedBody as gp,classifyTelemetryFailure as hp,describePayPalProcessFailure as qc,FloPayError as ra,friendlyPayPalFailureMessage as Pp,generateIdempotencyKey as vp,isPayPalTeardownMessage as Cp,isSettledSessionIntent as bp,isValidEmail as jc,mergePayPalPayerIdentity as Sp,needsPayPalPayerDetails as wp,normalizeGatewayEnvironment as kp,paypalProviderIdentityRequired as $c,resolvePayPalApprovalIdentity as Rp,resolvePayPalDeclineReason as Ip,SDK_VERSION as Ep,usesPayPalVaultedChannel as _p}from"@flopay/shared";import{loadScript as Tp}from"@paypal/paypal-js";import{useCallback as yr,useContext as Mp,useEffect as Wt,useMemo as Fa,useRef as nt,useState as Zr}from"react";import{compactBuyerIdentity as Qu,isValidEmail as ep}from"@flopay/shared";import{useCallback as Bc,useEffect as tp,useRef as Dc,useState as Lc}from"react";import{compactBuyerIdentity as kr}from"@flopay/shared";import{jsx as Oc,jsxs as Ma}from"react/jsx-runtime";function ea(){let[e,t]=Lc(null),n=Dc(null),o=Dc(0),a=Bc((l,u)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:l,identity:u}),new Promise(m=>{n.current=m})),[]),i=Bc(l=>{let u=n.current;n.current=null,t(null),u?.(l)},[]);return tp(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function ta({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[l,u]=Lc(e.email?.trim()??""),m=ep(l.trim());return Ma("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[Ma("div",{style:{fontWeight:700},children:["Continue with ",t]}),Ma("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Oc("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:R=>u(R.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ma("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&Oc("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),Ma("button",{type:"button",disabled:!m||a,onClick:()=>{n(Qu({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as np}from"@flopay/shared";import{useContext as mi}from"react";function po(){return mi(pr).flopay}function _s(){return mi(pr).paypalFlopay??null}function rp(){return mi(wr)}function Nc(){return mi(pr).billingApiUrl||np()}import{FLO_INSTRUMENT_ONCE_NAMES as op,invokeMerchantCallback as ap,projectFloInstrument as ip}from"@flopay/shared";import{useCallback as sp,useRef as fi}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Uc}from"@flopay/shared";function na(e,t){let n=fi(e);n.current=e;let o=fi(new Set),a=fi(t),i=fi(t);return wa(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),sp(l=>{if(i.current!==t)return;let u=ip(l);if(u){if(op.has(u.name)){if(o.current.has(u.name))return;o.current.add(u.name)}ap(()=>n.current?.(u))}},[t])}import{createContext as lp}from"react";var Aa=lp(null);function gi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var hi="provider.callback.ignored";function Pi(){let e,t=0;return{take(n){return n!==e&&(e=n,t=0),t>=5?!1:(t+=1,!0)}}}var cp=Symbol.for("@flopay/js.telemetry.bridge.v1"),dp=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function up(){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 pp(e){let t=up(),n=(a,i)=>a?a.bind(e):i,o=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:o,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,o()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function vi(e){let t=globalThis[dp];return pp(t?.(e)??{})}function hn(e){if(e)return e[cp]}import{useCallback as yo,useEffect as zc,useRef as To}from"react";function xa(e,t){let n=To(0),o=To(null),a=To(null),i=To(e),l=To(t?.onHandoffObserved),u=To(t?.defersMissingTerminal),m=To(t?.onMissingTerminalDeferred);zc(()=>{i.current=e,l.current=t?.onHandoffObserved,u.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let R=yo((w=a.current)=>{w?.timer&&(clearTimeout(w.timer),w.timer=null)},[]),C=yo(w=>{R();let pe=n.current+1;return n.current=pe,o.current=null,a.current={generation:pe,method:w,timer:null,yieldedControl:!1},pe},[R]),g=yo(w=>{let pe=a.current;return w!==void 0&&pe?.generation!==w?!1:(R(pe),a.current=null,(w===void 0||o.current===w)&&(o.current=null),!0)},[R]),A=yo(w=>{let pe=a.current,se=w??pe?.generation??n.current;(w===void 0||pe?.generation===w)&&(R(pe),a.current=null),o.current=se},[R]),X=yo(w=>o.current===(w??n.current),[]),te=yo(w=>a.current?.generation===w&&o.current!==w,[]),D=yo(()=>{let w=a.current;w&&(R(w),!w.yieldedControl&&(w.yieldedControl=!0,l.current?.(w.method)))},[R]),K=yo(()=>{let w=a.current;!w?.yieldedControl||document.visibilityState!=="visible"||(R(w),w.timer=setTimeout(()=>{if(w.timer=null,a.current?.generation===w.generation){if(u.current?.(w.method)){m.current?.(w.method,w.generation);return}a.current=null,o.current=w.generation,i.current(w.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},oc))},[R]);return zc(()=>{let w=()=>{document.visibilityState==="visible"?K():D()};return document.addEventListener("visibilitychange",w),window.addEventListener("blur",D),window.addEventListener("focus",K),()=>{document.removeEventListener("visibilitychange",w),window.removeEventListener("blur",D),window.removeEventListener("focus",K),R()}},[R,D,K]),{startAttempt:C,finishAttempt:g,invalidateAttempt:A,isAttemptInvalidated:X,isAttemptCurrent:te,generationRef:n}}import{jsx as Mo,jsxs as Ms}from"react/jsx-runtime";var Ci=45,Ap=1e3,xp=11e3,Wc="paypal_intent_settled",Fp={width:"100%",minHeight:Ci,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},Bp={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 Dp(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Bp[e.kind]??null}}function Kc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":ac(t)?"paypal_init_timeout":"paypal_init_failure"}function Op(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Hc({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:l,environment:u,currency:m,isSubscription:R,providerObjectType:C,approvalPresentation:g,onTokenizedBody:A,onComplete:X,onErrorChange:te,onDecline:D,onCancel:K,onTechnicalFailure:w,isProcessing:pe=!1,onLoadStateChange:se,onInitializationStateChange:I,allowAutomaticRetry:We=!0,onButtonClick:G,runBeforeButtonClick:Ue,session:rt,existingOrderId:dt,telemetry:Re,telemetryContext:Nt,onInstrument:Dt,debug:be=!1}){let He=po(),ot=na(Dt,e),at=Fa(()=>{if(He)return null;let T=vi({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ep,enabled:Re!==!1});return T.setCheckoutContext(Nt??{}),T.beginCheckout(Nt??{}),T},[n,He,Re,Nt?.checkoutMode,Nt?.layout]),Ie=Fa(()=>hn(He),[He]);Wt(()=>()=>{at&&at.flush().catch(()=>{}).finally(()=>at.destroy())},[at]);let Z=Fa(()=>({error:T=>{Ie?Ie.error(T):at?.error(T),ot({class:"technical_error",errorCode:T.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":T.errorCode,requestCategory:T.requestCategory,provider:T.provider})},log:T=>{Ie?Ie.log(T):at?.log(T),ot({class:"lifecycle",name:T.name,provider:T.provider})},performance:T=>{Ie?Ie.performance(T):at?.performance(T)},terminal:T=>{Ie?Ie.terminal(T):at?.terminal(T)},startTiming:()=>Ie?.now()??at?.now()??0,elapsed:T=>Ie?.elapsed(T)??Math.max(0,(at?.now()??T)-T)}),[ot,Ie,at]),le=nt(null),Kt=nt(0),je=nt(null),it=nt(null),Q=nt(null),Te=Mp(Aa),Xe=nt(null);Xe.current||(Xe.current=gi());let H=Te??Xe.current,ht=nt(null),Ce=nt(!1),[Ve,ze]=Zr(!1),[Ze,Pt]=Zr(!1),[De,wt]=Zr(0),Me=nt(0),[Ee,vt]=Zr(!1),Ot=nt(!1),kt=nt(!1),[V,ce]=Zr(!1),[_e,st]=Zr(!1),{request:lt,collect:Ke,finish:Ct}=ea(),_t=nt({sessionId:e,required:$c(o,rt)});_t.current.sessionId!==e&&(_t.current={sessionId:e,required:$c(o,rt)});let ct=_t.current.required,Ae=Fa(()=>n.replace(/\/+$/,""),[n]),et=rt?.gateways?.paypal?.providerObjectType??C,z=et??(R?"subscription":"order"),[Ht]=Zr(ka),k=rt?.gateways?.paypal?.approvalPresentation??g,q=di(Ht,k==="app_switch"?"app_switch":void 0,z),j=_p(et),y=Fa(()=>JSON.stringify([Ae,l,m,u??"",z,j,q,e,dt??""]),[Ae,l,m,u,dt,z,j,q,e]),oe=nt(y),h=oe.current!==y,$=nt(be),O=nt(null),[he,Se]=Zr([]),_=yr(T=>{$.current&&Se($e=>[...$e,`${new Date().toISOString().slice(11,23)} ${T}`])},[]);Wt(()=>{$.current=be,be&&_("debug:enabled"),O.current?.setEnabled(be)},[_,be]);let ut=nt(A),Mt=nt(X),At=nt(te),Fn=nt(D),Ge=nt(K),fr=nt(w),bt=nt(G),Er=nt(se),pt=nt(I),yt=nt(i),Rn=nt(Ue),Hn=nt(rt),Vn=nt(o),rn=nt(a),yn=nt(t),Xt=nt(null),Zt=nt(new Map),Nn=nt(new Map),xe=nt(!1),we=nt(e);we.current=e;let[tr]=Zr(Pi);Wt(()=>(xe.current=!0,()=>{xe.current=!1}),[]),Wt(()=>{ut.current=A},[A]),Wt(()=>{yt.current=i},[i]),Wt(()=>{Mt.current=X},[X]),Wt(()=>{At.current=te},[te]),Wt(()=>{Fn.current=D},[D]),Wt(()=>{Ge.current=K},[K]),Wt(()=>{fr.current=w},[w]),Wt(()=>{bt.current=G},[G]),Wt(()=>{Er.current=se},[se]),Wt(()=>{pt.current=I},[I]),Wt(()=>{Rn.current=Ue},[Ue]),Wt(()=>{Hn.current=rt},[rt]),Wt(()=>{Vn.current=o},[o]),Wt(()=>{rn.current=a},[a]),Wt(()=>{yn.current=t},[t]),Wt(()=>{Me.current=De},[De]),Wt(()=>{Ee&&ht.current?.focus()},[Ee,De]);let St=yr(()=>{window.setTimeout(()=>{ht.current?.focus()},0)},[]),Bn=yr(()=>{ze(!1),wt(T=>T+1)},[]),Qt=yr(()=>{vt(!1),(le.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??le.current)?.focus?.()},[]);Wt(()=>{!Ve||!Ce.current||(Ce.current=!1,Qt())},[Qt,Ve,De]);let gr=yr((T,$e)=>{let P=$e?.popupBlocked??so(T);P&&H.markBlocked();let ae=li("PayPal",P,Ht.inAppBrowser),Rt=fr.current;if(Rt){let xt=P&&Ht.inAppBrowser?new ra(ae,"api_error",{code:$e?.code??"paypal_popup_blocked"}):T;Rt("paypal",xt,$e);return}if(T instanceof ra&&T.code==="checkout_processing_timeout"){At.current?.(T.message);return}At.current?.(ae)},[H,Ht.inAppBrowser]),In=yr(T=>{let $e=je.current,P=it.current;$e===null||!P||(Z.log({...P,popupCapability:H.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:T}),Z.performance({...P,popupCapability:H.current(),stage:"overlay_return",durationMs:Z.elapsed($e),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:T}),je.current=null)},[H,Z]),_r=yr((T,$e,P)=>{let ae=it.current;In("overlay_timeout"),ae&&Z.error({...ae,popupCapability:H.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),gr($e,{...P,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:q,terminalReason:"overlay_timeout"}),vt(!0),Bn(),St()},[In,St,gr,H,q,Bn,Z]),hr=yr(()=>{H.markAvailable();let T=it.current;T&&(Q.current=T.attempt,Z.log({...T,popupCapability:H.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[H,Z]),En=yr(()=>!0,[]),mn=yr(()=>{let T=it.current;if(!T)return;let $e=je.current;Z.performance({...T,popupCapability:H.current(),stage:"overlay_return",durationMs:$e===null?0:Z.elapsed($e),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[H,Z]),{finishAttempt:_n,generationRef:Pr,invalidateAttempt:Un,isAttemptCurrent:zn,isAttemptInvalidated:qn,startAttempt:fn}=xa(_r,{onHandoffObserved:hr,defersMissingTerminal:En,onMissingTerminalDeferred:mn}),Ut=yr(()=>(vt(!1),fn("paypal")),[fn]),zt=yr(T=>{Un(T?.generation),T?.showRetry&&vt(!0),T?.remount&&Bn(),T?.focus!==!1&&St()},[St,Un,Bn]),Dn=T=>{let $e=Xt.current;return $e&&Nn.current.set(T,$e),T};Wt(()=>{oe.current!==y&&(oe.current=y,Ot.current=!1,kt.current=!1,ze(!1),Pt(!1),ce(!1),pt.current?.("loading"))},[y]),Wt(()=>{Ft(()=>Er.current?.(Ve&&!V))},[Ve,V]);let vn=kp(u);Wt(()=>{let T={attempt:Pr.current+1,inAppBrowser:Ht.inAppBrowser,appFamily:Ht.appFamily,popupCapability:H.current(),presentationMode:q},$e=()=>({...it.current??T,popupCapability:H.current()}),P={error:s=>Z.error({...s,...$e()}),log:s=>Z.log({...s,...$e()}),performance:s=>Z.performance({...s,...$e()}),terminal:s=>Z.terminal({...s,...$e()}),startTiming:Z.startTiming,elapsed:Z.elapsed},ae=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Rt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(_(`mount clientId=${ae} env=${u??"(unset)"}\u2192${vn??"live"} ccy=${m} sub=${R}`),_(`ua=${Rt.slice(0,80)}${Rt.length>80?"\u2026":""}`),!l){_("FAIL: clientId empty \u2014 gateway misconfigured"),ce(!0),P.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!le.current){_("FAIL: containerRef not attached");return}Kt.current=P.startTiming(),P.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let xt=!1,Vt=!1,ye=()=>xt||Vt,en=s=>{let c=xe.current,p=c?s:"torn_down";c&&_(`onError ignored reason=${p}`),tr.take(we.current)&&P.log({name:hi,stage:"provider_ready",reason:p,provider:"paypal",paymentMethodCategory:"paypal"})},Wr=()=>we.current===e?"stale_attempt":"session_changed",Mn=j?z:void 0,Pe,Tr=!1,Cn=()=>{Pe=vp(),Pe||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Tr=!0},sr=null,Po=!1,Gn=null,nr=!1,Mr=()=>{!Gn||nr||(nr=!0,Gn.close().catch(()=>{}))},jn=!1,Ar=!1,vr=le.current,lr=null,Yn=null,ke=[],An=null,$n=!1,ln=!1,cr=null,rr=s=>{if(!s||typeof s.getBoundingClientRect!="function")return"(no rect)";let c=s.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},Kr=s=>{if(!s)return"(empty)";try{let c=new URL(s,typeof window>"u"?"https://localhost":window.location.href),p=c.pathname.toLowerCase();return p.includes("checkcaptcha")||p.includes("captcha")?`CAPTCHA(${c.host}${p})`:p.includes("risk")||p.includes("challenge")?`RISK(${c.host}${p})`:p.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${p}`.slice(0,100)}catch{return s.slice(0,80)}},xr=s=>{let c=s.getAttribute("src"),p=s.getAttribute("srcdoc"),W=s.getAttribute("name"),qe=s.getAttribute("sandbox"),Y=[];return c&&Y.push(`src=${Kr(c)}`),p&&Y.push(`srcdoc[${p.length}ch]`),!c&&!p&&Y.push("src=(empty) srcdoc=(empty)"),W&&Y.push(`name=${W.slice(0,40)}`),qe!==null&&Y.push(`sandbox="${qe.slice(0,40)}"`),Y.join(" ")},vo=s=>{if(!(s instanceof HTMLIFrameElement))return"";try{let c=s.contentDocument;if(!c)return"cd=null";let p=c.body?.children.length??0,W=c.body?.innerHTML.length??0,qe=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${p}children,${W}ch] head[${qe}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},Fr=[],Co=s=>{if(ye())return;let c=s.message??String(s.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(_(`window:error ${c.slice(0,140)}`),Fr.push(c))},Hr=s=>{if(ye())return;let c=s.reason instanceof Error?s.reason.message:String(s.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(_(`window:rejection ${c.slice(0,140)}`),Fr.push(c))},Cr={value:0},eo=()=>{lr?.disconnect(),lr=null,Yn?.disconnect(),Yn=null;for(let s of ke.splice(0))clearTimeout(s);ln=!1,$n&&typeof window<"u"&&(window.removeEventListener("error",Co),window.removeEventListener("unhandledrejection",Hr)),$n=!1},to=()=>{if(!($n||ye()||jn)){if($n=!0,Fr.length=0,Cr.value=0,typeof window<"u"&&(window.addEventListener("error",Co),window.addEventListener("unhandledrejection",Hr)),typeof PerformanceObserver<"u")try{Yn=new PerformanceObserver(s=>{if(!ye())for(let c of s.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Cr.value+=1;let p=Math.round(c.duration);_(`net ${p}ms ${c.name.slice(0,90)}`)}}),Yn.observe({type:"resource",buffered:!0})}catch{}cr?.()}},qt=()=>{An&&(clearTimeout(An),An=null)},Jn=()=>{eo(),qt()},Vr={setEnabled:s=>{s?to():eo()}};O.current=Vr,$.current&&to();let On=Cp,Xn=s=>{if(ye()||On(s))return;let c=Qo(s)??s;Ft(()=>At.current?.(c))},Fe=(s,c)=>{if(xt||Po)return;Po=!0,Vt=!0,Jn(),Mr();let p=Dp({kind:s,generationActive:!0,automaticRetryAllowed:We,automaticRetryUsed:Ot.current});if(p.action==="retry"){Ot.current=!0,ze(!1),st(!1),Pt(!0),pt.current?.("retrying"),sr=setTimeout(()=>{xt||wt(W=>W+1)},Ap);return}if(ze(!1),st(!1),Pt(!1),ce(!0),p.action!=="ignore"){if(pt.current?.("exhausted"),p.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",c);return}if(p.report){let W=Cs({code:Kc(s,c),message:c},{inAppBrowser:Ht.inAppBrowser,handoffObserved:!1});W.popupBlocked&&H.markBlocked(),P.error({errorCode:W.popupBlocked?W.errorCode:p.report.errorCode,stage:p.report.stage,operationOutcome:p.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:W.terminalReason})}kt.current||(kt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Kc(s,c)))}};ce(!1);let Ln=async(s,c=Xt.current)=>{if(ye())return;let p=c?.sessionId??e;if(ut.current){await ut.current(s,{sessionId:p,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let W=P.startTiming();P.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let qe=()=>{P.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),P.performance({stage:"processing",durationMs:P.elapsed(W),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Y=mp({body:s,sessionId:p,nonce:c?.nonce??yn.current,accountPatch:c?.accountPatch,session:Hn.current,email:Vn.current}),U=await new Ts(Ae,{telemetry:!1}).processPayment(Y.userId,Y.params);if(U.ok){if(Vt||xt&&xe.current)return;qe(),P.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Ft(()=>Mt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ye())return;let S=await U.json().catch(()=>null),ne=qc(S),me=ne.message;qe(),U.status===400&&(typeof S?.declineCode=="string"||!Array.isArray(S?.fields))?P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):U.status===400||U.status===422?P.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):P.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Op(U.status),failureCategory:U.status>=500?"server_error":void 0}),Xn(me),Ft(()=>Fn.current?.(gn("paypal",me,{code:ne.code,declineCode:ne.declineCode})));return}catch(Y){if(ye())return;qe(),P.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let de=Pp(Y instanceof Error?Y.message:void 0);Xn(de),Ft(()=>Fn.current?.(gn("paypal",de)));return}},$t=()=>new ra("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Gr=s=>ye()?Promise.reject($t()):Promise.resolve(s),no=async s=>{if(s.ok){P.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Ft(()=>Mt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let c=await s.json().catch(()=>null),p=qc(c);P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Ft(()=>Fn.current?.(gn("paypal",p.message,{code:p.code,declineCode:p.declineCode})))},bo=()=>{let s=Xt.current;In("approved"),s&&(Zt.current.delete(s.surfaceKey),_n(s.generation)),Xt.current=null},Br=async s=>{if(ye())throw $t();Tr||Cn();let c=Xt.current,p=c?.sessionId??e,W=c?.nonce??yn.current;P.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let qe;try{qe=await new Ts(Ae,{telemetry:!1}).createSessionIntent(p,W??"",fp(Mn),{idempotencyKey:Pe})}catch(Y){throw P.error({...hp(Y,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Y}if(ye())throw $t();if(bp(qe))throw await no(qe.response),bo(),new ra("PayPal checkout already settled.","api_error",{code:Wc});if(qe.provider!=="paypal"||qe.providerObjectType!==z)throw new Error(s);return P.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),qe.providerObjectId},Dr=(s,c)=>{let p=c?.nonce??yn.current;if(!p)return;let W=c?.sessionId??e,qe=Ip(s);new Ts(Ae,{telemetry:!1}).reportSessionIntentDecline(W,p,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:qe}).catch(()=>{})},bn=De;_("loadScript:scheduled (deferred 1 tick)");let cn=null,v=setTimeout(()=>{if(xt){_("loadScript:skipped (cancelled before defer ran)");return}_("loadScript:start");let s=vn==="live"?"production":vn,c={};z==="subscription"?c={intent:"subscription",vault:!0}:z==="order"&&(c={intent:"capture"}),cn=Tp({clientId:l,currency:m,...c,...s?{environment:s}:{},...s==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let p=!1;cn.then(W=>{if(p=!0,_(`loadScript:resolved inactive=${ye()} ns=${!!W} buttons=${!!W?.Buttons}`),ye())return;if(!W?.Buttons){_("FAIL: namespace missing Buttons factory"),Fe("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}P.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),P.performance({stage:"provider_ready",durationMs:P.elapsed(Kt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),P.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let qe=async(b,M)=>{if(ye()||Me.current!==bn)return;let x=b.vaultSetupToken??b.subscriptionID??b.orderID??"",L=x?Nn.current.get(x):Zt.current.get(bn);if(!(!L||!zn(L.generation))&&_n(L.generation)){Nn.current.delete(x),Zt.current.delete(L.surfaceKey),In("approved");try{if(st(!0),Ft(()=>At.current?.(null)),!x)throw new ra("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let re=Rp({accountPatch:L.accountPatch,email:Vn.current,billingName:rn.current,session:Hn.current});if(wp(re))try{re=Sp(re,await M?.order?.get?.())}catch{}if((yt.current||ct)&&!jc(re.email)){let N=await Ke("PayPal",re);if(!N)return;re=N}jc(re.email)&&(L.accountPatch=kr({...L.accountPatch,...re}),await yt.current?.(re));let Oe=gp(x,Mn);await Ln(Oe,L)}catch(re){Xn(re instanceof Error?re.message:"PayPal capture failed.")}finally{ye()||st(!1)}}},Y=b=>{let M=dt?()=>Gr(dt):()=>Br(b);return async()=>Dn(await M())},de=W.Buttons({style:{layout:"horizontal",height:Ci,tagline:!1},...q==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(b,M)=>{if(ye()){await M.reject();return}Cn();let x=Rn.current,L={};if(x)try{let N=await x("paypal");if(ye()){await M.reject();return}if(!N.proceed){Xt.current=null,Zt.current.delete(bn),await M.reject();return}L={sessionId:N.sessionId,accountPatch:N.accountPatch,nonce:N.nonce}}catch(N){_(`onClick:runBeforeButtonClick rejected msg=${(N instanceof Error?N.message:String(N)).slice(0,120)}`),Xt.current=null,Zt.current.delete(bn),await M.reject();return}Ft(()=>bt.current?.("paypal"));let re=Ut(),Oe={generation:re,surfaceKey:bn,...L};Xt.current=Oe,Zt.current.set(bn,Oe),it.current={...T,attempt:re},await M.resolve(),P.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),P.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),je.current=P.startTiming()},createOrder:z==="order"?Y("Failed to create PayPal order."):void 0,createSubscription:z==="subscription"?Y("Failed to create PayPal subscription."):void 0,createVaultSetupToken:z==="setup_token"?async()=>Dn(await Br("Failed to create PayPal setup token.")):void 0,onApprove:qe,onCancel:()=>{if(ye())return;let b=Zt.current.get(bn)??Xt.current,M=b&&zn(b.generation)?yp(b.sessionId??e,Mn):null;b&&Zt.current.delete(b.surfaceKey),Xt.current=null,In("cancelled"),P.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ce.current=!0,zt({generation:b?.generation,remount:!0,focus:!1}),M&&Ft(()=>Ge.current?.(M))},onError:b=>{if(b instanceof ra&&b.code===Wc)return;let M=b instanceof Error?b.message:"PayPal failed to render.";if(ye()||Me.current!==bn){On(M)||en(Wr());return}if(jn){let x=Zt.current.get(bn)??Xt.current;if(!x||!zn(x.generation)){if(On(M)){!x&&!qn()&&_n();return}en(x||qn()?"stale_attempt":"no_current_attempt");return}if(_(`onError rendered=${jn} msg=${M.slice(0,120)}`),On(M)){_n(x.generation);return}let{errorCode:L,popupBlocked:re,providerDeclined:Oe,terminalReason:N}=Cs(b,{inAppBrowser:Ht.inAppBrowser,handoffObserved:Q.current===x.generation});if(re&&H.markBlocked(),In(N),Oe){P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:N}),Dr(b,x),Ft(()=>Fn.current?.(gn("paypal",M))),Zt.current.delete(x.surfaceKey),Xt.current=null,_n(x.generation);return}P.error({errorCode:L,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:N}),Zt.current.delete(x.surfaceKey),Xt.current=null,zt({generation:x.generation,remount:!0,showRetry:!0,focus:!0}),gr(b,{code:"paypal_runtime_failed",popupBlocked:re,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:q,terminalReason:N});return}_(`onError rendered=${jn} msg=${M.slice(0,120)}`),Fe(On(M)?"teardown":"pre_ready_callback",M)}}),U=de.isEligible();if(_(`isEligible=${U}`),P.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!U){ze(!1),Fe("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ar=!0,Gn=de,cr=()=>{if(!$n||ln||ye()||jn)return;ln=!0,_(`container:dims ${rr(vr)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(lr=new MutationObserver(M=>{if(!ye()){for(let x of M)if(x.type==="childList")x.addedNodes.forEach(L=>{if(!(L instanceof Element))return;let re=L.tagName.toLowerCase(),Oe=(L.getAttribute("title")??"").slice(0,40),N=re==="iframe"?` ${xr(L)}`:"";_(`child+ ${re}${Oe?` title="${Oe}"`:""}${N} dims=${rr(L)}`)});else if(x.type==="attributes"&&x.target instanceof Element){let L=x.target;if(L.tagName.toLowerCase()!=="iframe")continue;let re=x.attributeName;(re==="src"||re==="srcdoc")&&_(`attr~ iframe ${re}=${re==="srcdoc"?`[${(L.getAttribute("srcdoc")??"").length}ch]`:Kr(L.getAttribute("src"))} dims=${rr(L)}`)}}}),lr.observe(vr,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let b=M=>{if(ye()||jn)return;let x=vr.querySelectorAll("iframe"),L=typeof document<"u"&&"hasStorageAccess"in document;_(`watchdog:${M} container=${rr(vr)} children=${vr.childElementCount} iframes=${x.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${L} paypalNetRequests=${Cr.value}`),x.forEach((re,Oe)=>{let N=(re.getAttribute("title")??"").slice(0,40);_(` iframe[${Oe}] ${rr(re)}${N?` title="${N}"`:""} ${xr(re)}`);let fe=vo(re);fe&&_(` ${fe}`)}),Fr.length===0&&_(" (no PayPal/zoid window errors captured)")};ke.push(setTimeout(()=>b("3s"),3e3)),ke.push(setTimeout(()=>b("8s"),8e3)),ke.push(setTimeout(()=>b("15s"),15e3))},cr(),_("render:start");let ne=P.startTiming();An=setTimeout(()=>{ye()||jn||(_("watchdog:11s retryable render timeout"),Fe("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},xp);let me=de.render(vr);(async()=>{try{if(await me,_(`render:resolved inactive=${ye()}`),Jn(),ye()){Mr();return}jn=!0,ze(!0),Pt(!1),pt.current?.("ready"),P.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),P.performance({stage:"checkout_render",durationMs:P.elapsed(ne),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(b){let M=b instanceof Error?b.message:"PayPal failed to render.";_(`render:rejected msg=${M.slice(0,120)}`),Jn(),Fe(On(M)?"teardown":"render_rejected",M)}})()}).catch(W=>{let qe=W instanceof Error?W.message:"PayPal operation failed.";_(`provider:failed msg=${qe.slice(0,120)}`);let Y="script_rejected";p&&On(qe)?Y="teardown":p&&Ar&&(Y="render_rejected"),Fe(Y,qe)})},0);return()=>{xt=!0,clearTimeout(v),sr&&clearTimeout(sr),Jn(),O.current===Vr&&(O.current=null),Mr(),je.current=null,it.current=null}},[We,Ae,l,m,u,z,q,j,e,dt,De,Z,Ke,ct,_,In]);let Tn=be?Ms("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:V?"#fef2f2":"#f3f4f6",border:`1px solid ${V?"#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=${V})`,he.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return G&&!h?Re?Io("div",{children:Fn}):null:Ts("div",{children:[Fn,dt&&Io(Qo,{identity:dt.identity,methodLabel:dt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:yt,onCancel:()=>yt(null)}),Ts("div",{"aria-hidden":Qe||dt?!0:void 0,style:Qe||dt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Pi},children:[!Je&&!Qe&&Io("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"}}),Io("div",{ref:pe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Pi,display:"flex",opacity:Je?1:0},"aria-busy":Te||ge},Be)]},Be),_e&&Io("button",{ref:vt,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:On,style:xp,children:"Try PayPal again"})]})}function vi(e){return Io(Hc,{...e})}function Kc(e){return Io(Hc,{...e})}import{jsx as Vc,jsxs as Op}from"react/jsx-runtime";function na({children:e,margin:t,icon:n=!0,styleOverride:o}){return Op("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,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...o??{}},children:[n&&Vc("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Vc("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]})}import{clearCachedInlineCheckout as Ci,clearCachedInlineSession as Ms,hashCreateParams as Gc,legacyCachedSessionMatchesDraft as Yc,persistCachedInlineIdempotencyKey as bi,persistCachedInlineSession as Si,readCachedInlineIdempotencyKey as Jc,readCachedInlineSession as Xc,serializeCreateParams as xa}from"@flopay/shared";var Zc=new Set;function Lp(){return globalThis.process?.env?.NODE_ENV==="production"}function Qc(e,t){Zc.has(e)||Lp()||(Zc.add(e),console.warn(t))}function ed(){Qc("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 td(){Qc("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`.")}import{isCardFieldsInstrumentSource as Np,resolveBillingApiUrl as Up}from"@flopay/shared";import{useCallback as zp,useEffect as yo,useMemo as qp,useRef as nd,useState as rd}from"react";import{jsx as jp}from"react/jsx-runtime";function wi({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=rd(e instanceof Promise?null:e),[c,y]=rd(t instanceof Promise||!t?null:t),S=nd(null),P=nd(null),f=ea(o),F=zp(z=>{Np(z)||f(z)},[f]);yo(()=>{f({class:"lifecycle",name:"checkout.mount"})},[f]),yo(()=>{i&&f({class:"lifecycle",name:"sdk.initialize.ready"})},[f,i]),yo(()=>{if(i)return fn(i)?.subscribe?.(F)},[F,i]),yo(()=>{if(!(!c||c===i))return fn(c)?.subscribe?.(F)},[F,i,c]),yo(()=>{if(!i)return;let z=fn(i);return S.current=z?.beginCheckout()??z?.now()??0,z?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{z?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),yo(()=>{let z=!1;return e instanceof Promise?e.then(K=>{z||s(K)},()=>{z||f({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{z=!0}},[f,e]),yo(()=>{let z=!1;if(!t){y(null);return}return t instanceof Promise?t.then(K=>{z||y(K)},()=>{z||f({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{z=!0}},[f,t]),yo(()=>{if(!i||P.current===i)return;P.current=i;let z=fn(i);z?.log({name:"checkout.rendered",stage:"checkout_render"}),f({class:"lifecycle",name:"checkout.rendered"}),z?.performance({stage:"checkout_render",durationMs:z.elapsed(S.current??0),durationMode:"machine"})},[f,i]);let te=Up(n?.billingApiUrl),ae=qp(()=>({flopay:i,paypalFlopay:c,billingApiUrl:te,emitInstrument:f}),[i,c,te,f]);return jp(lr.Provider,{value:ae,children:a})}import{markSessionRecentlyCompleted as ra,wasSessionRecentlyCompleted as As}from"@flopay/shared";async function ki(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{beginSavedCardChallengeTelemetry as $p,completeSavedCardNextAction as Wp,loadFloPay as od,PaymentAPI as Ba,runSavedCardChallenge as Hp}from"@flopay/js";import{classifyPaymentRejection as Kp,FloPayError as _t,isAuthorizationOnlySession as Vp,isMerchantAuthRequired as Fs,isMountableVaultBlock as Gp,isSetupIntentClientSecret as Yp,MERCHANT_AUTH_REQUIRED_CODE as Jp,normalizeCheckoutFailureOutcome as ad}from"@flopay/shared";var Oa="card";async function Xp(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:o??null}}async function Zp(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function oa(e){return new _t("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Qp(){return new _t("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Da(e,t){return Object.assign(e,{checkoutMethod:t})}function Jr(e,t){let n=e instanceof _t?e:new _t(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Fa(e,t){try{return await e()}catch(n){throw Jr(n,t)}}function sd(e){return!e?.type||!e.threeDSecureToken||Fs(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function ld(e){return Hp(e)}function La(e,t,n,o=!0){let a={release:()=>{}};if(!o)return a;try{let i=new Ba(e),s=$p(i,t,n);return s?{telemetry:s,release:()=>{setTimeout(()=>{try{i.destroy()}catch{}},0)}}:a}catch{return a}}async function aa(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new Ba(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,y;try{y=await Wp({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:P=>Fr({type:P.declineReason??"authorization_declined",gatewayErrorCode:P.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(P){if(a.aborted||P instanceof Error&&P.name==="AbortError")throw P instanceof _t&&P.code==="three_ds_aborted"?P:oa(P);if(!(P instanceof _t)||P.code!=="three_ds_timeout"&&P.code!=="checkout_processing_timeout")throw P;try{y=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:c,timeoutMs:5e3,signal:a})}catch(F){if(a.aborted)throw oa(F);if(!(F instanceof _t)||F.code!=="checkout_processing_timeout")throw F}let f=y&&lo(y,t.session);if(!Gr(f)&&f?.status!=="expired"){if(t.telemetry){let F=new Ba(n);try{F.reportThreeDsAbandoned(o)}finally{F.destroy()}}throw Qp()}}let S=y&&lo(y,t.session);if(!Gr(S))throw Jo(S);return{...Vr(S,o),checkoutMethod:"card"}}function cd(e){return new _t("This payment needs your card details. Please complete your payment below.","authentication_error",{code:Jp,...e===void 0?{}:{statusCode:e}})}function Fr(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if(Fs(e))return Da(cd(),o);let a=e?.message??t,i=Xo(a)??a,s=Da(new _t(i,"api_error",{code:e?.code??ad(e?.outcome)??ad(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function xs(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ri(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function dd(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ri(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let c of i)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||Ri(c)))return c;let s=a.gateways;if(s&&typeof s=="object"){let c=s.stripe;if(c&&typeof c=="object"){let y=c,S=[y.stripeClientSecret,y.clientSecret];for(let P of S)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||Ri(P)))return P}}}}async function ey({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=dd(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let c=(await new Ba(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ri(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function ia({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:s}){let c=e.replace(/\/+$/,""),y=t??n.id,S=o??n.clientSecret,P=n.customer?.id??n.accountData?.userId??"",f=n.customer?.email??n.accountData?.email??"",F=n.customer?.firstName??n.accountData?.firstName??"",te=n.customer?.lastName??n.accountData?.lastName??"",ae=n.customer?.country??n.accountData?.country??void 0,z=n.customer?.zip??n.accountData?.zip??void 0,C=await new Ba(c,s===!1?{telemetry:!1}:void 0).processPayment(P,{sessionId:y,nonce:S,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:P,email:f,firstName:F,lastName:te,country:ae,zip:z},returnUrl:i??xs(n)});if(C.ok){let ue=typeof C.json=="function"?await C.json().catch(()=>null):null;if(Vp(n)||ue?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof ue?.paymentId=="string"?ue.paymentId:n.paymentId,sessionId:typeof ue?.sessionId=="string"?ue.sessionId:y,authorizationExpiresAt:typeof ue?.authorizationExpiresAt=="string"?ue.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Ia(a),checkoutMethod:id(a,n)}};let w=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...w?{paymentIntentId:w}:{},paymentMethodId:Ia(a),checkoutMethod:id(a,n)}}}let ge;try{ge=await C.json()}catch(ue){throw new _t("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:C.status,cause:ue})}if(Fs(ge))throw Da(cd(C.status),"card");if(ge?.type==="3ds_required"&&typeof ge.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:ge.nextActionRedirectUrl};if(ge?.type==="paypal_redirect_required"||ge?.type==="3ds_required"){let ue=dd(ge);if(!ue)throw new _t("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:C.status});return{type:ge.type,threeDSecureToken:ue,paymentMethodId:ge.paymentMethodId}}if(ge?.gatewayErrorCode==="authentication_required"){let ue=await ey({billingApiUrl:c,sessionId:y,nonce:S,responseJson:ge});if(ue)return ue;throw Da(new _t("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw ty(ge,C.status)}function ty(e,t){let n=new _t(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(n,{telemetryOutcome:Kp(t,e)})}async function Ii(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:y,signal:S}){let P=t?.getRawProvider();if(!P)throw Jr(new _t("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Da(new _t("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let f=Yp(e.threeDSecureToken),F=null,te=e.paymentMethodId,ae=await Fa(()=>Xp(P,e.threeDSecureToken,f),"card");if(ae){if(ae.error)throw Jr(new _t(ae.error.message??`Failed to retrieve 3DS ${f?"setup":"payment"} status.`,"api_error",{code:ae.error.code}),"card");let K=ae.intent;!te&&K?.payment_method&&(typeof K.payment_method=="string"?te=K.payment_method:"id"in K.payment_method&&(te=K.payment_method.id??void 0))}let z=te?await Fa(()=>Zp(P,e.threeDSecureToken,{payment_method:te,return_url:c??xs(s)??window.location.href},f),"card"):null;if(z){if(z.error)throw Jr(new _t(z.error.message??"3DS authentication failed.","api_error",{code:z.error.code}),"card");F=z.intent}else{let K=await Fa(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(K.error)throw Jr(new _t(K.error.message??"3DS authentication failed.","api_error",{code:K.error.code}),"card");F=(f?K.setupIntent:K.paymentIntent)??null}if(F&&(F.status==="requires_capture"||F.status==="succeeded"||F.status==="processing")){let K=await ia({billingApiUrl:a,sessionId:i,session:s,telemetry:y,tokenizedData:{id:F.id,type:"card",threeDSecureActionResultTokenId:F.id},returnUrl:c});return K.type==="success"?{...K.result,paymentIntentId:K.result.paymentIntentId??F.id,paymentMethodId:K.result.paymentMethodId??te}:K.type==="next_action_required"?aa(K,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:S}):Ii(K,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:y,signal:S})}throw Jr(new _t("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let f=(n??t)?.getRawProvider();if(!f)throw Jr(new _t("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:te}=await Fa(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(te)throw Jr(new _t(te.message??"PayPal authorization failed.","api_error",{code:te.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:F}=await Fa(()=>f.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??xs(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(F)throw Jr(new _t(F.message??"PayPal authorization failed.","api_error",{code:F.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new _t("Unsupported payment redirect state.","api_error")}function Na(e){if(e instanceof _t){let o=Xo(e.message);return o&&o!==e.message?Object.assign(new _t(o,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.",n=Xo(t)??t;return new _t(n,"api_error")}function Bs(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=Gp(e.data.session?.vault)||ko(e.data.session);if(!t&&!n&&!o)throw new _t("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 id(e,t){return e?e.isPaypal?"paypal":"card":t&&ko(t)?"card":void 0}async function Ds({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:o,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,c]=await Promise.all([od(e,{billingApiUrl:n,locale:o,telemetry:a}),i?od(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);if(!s)throw new _t("The payment provider did not initialize.","authentication_error");let y=null;return i?y=c:t&&(y=s),{flopay:s,paypalFlopay:y}}import{PaymentAPI as sa,PciVaultCardCapture as hy,toStripeAppearance as Py}from"@flopay/js";import{buildCardFieldLabelsPayload as vy,buildCheckoutProcessMetadata as Cy,buildProcessPaymentAvsAccount as by,buildWalletSheetWindowMessage as Sy,buyerEmailRequiredPrompt as wy,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as ky,COUNTRY_OPTIONS as Ry,cardFieldsInstrumentSource as Iy,classifyPaymentRejection as Ey,clearStripePayPalReturn as _y,computeVaultCardThemeColors as Ty,darkenHex as My,denyPaymentPermissionToNewFrames as Ay,FloPayError as Sr,filterStripeMethodsByCountryGate as xy,getPostalCodeExample as Fy,getPostalCodeLabel as Ks,getStateFromPostalCode as By,getStateLabel as Ns,getStateOptions as Dy,getStripeMethodDisplayName as ja,hasMatchingStripePayPalReturn as Oy,invokeMerchantCallback as Pd,isAuthorizationOnlySession as Us,isAVSFieldVisible as Jt,isCardFormFirst as Ly,isMountableVaultBlock as Ny,isPostalCodeSupported as Uy,isSettledSessionIntent as Ai,isSetupIntentClientSecret as zs,isValidEmail as Rn,isValidPostalCode as zy,isWalletSheetRefusedForWindowSize as qy,keyPaymentMethodOrder as jy,needsStripeMethodExplicitConfirm as vd,normalizeBeforeButtonClickError as Cd,normalizeCheckoutFailureOutcome as $y,partitionStripeMethods as Wy,placePaymentMethodGroups as bd,randomUuidV4 as Hy,readMatchingStripePayPalContinuation as Ky,readStripeRedirectParams as Fd,resolveAVSConfig as Vy,resolveButtonsLayoutTheme as Gy,resolveSetupFutureUsage as Bd,resolveTheme as Yy,resolveVaultMountOptions as qs,STRIPE_PAYPAL_RESUME_KEY as Jy,derivePrimaryTileStyle as Xy,shouldPreferWalletPopup as Sd,stripeExpressMethodToOptionKey as Zy,stripeRedirectReturnUrl as Dd,toCssWeight as Qy,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as Od}from"@flopay/shared";import{ExpressCheckoutElement as Ld,PaymentElement as em,useElements as Js,useStripe as Xs}from"@stripe/react-stripe-js";import za,{useCallback as Fe,useContext as la,useEffect as Xe,useLayoutEffect as tm,useMemo as Pt,useRef as U,useState as oe}from"react";function Eo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ei(e,t){if(e)return{error:n=>e.error(Eo(t,n)),log:n=>e.log(Eo(t,n)),performance:n=>e.performance(Eo(t,n)),terminal:n=>e.terminal(Eo(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}import{useEffect as ny,useId as ry,useRef as ud}from"react";import{Fragment as iy,jsx as pd,jsxs as sy}from"react/jsx-runtime";var yd="More payment options",oy={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ay={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Os({label:e,open:t,showLink:n,onOpen:o,color:a,fontFamily:i,children:s}){let c=ry(),y=ud(null),S=ud(!1);return ny(()=>{t&&S.current&&y.current?.focus()},[t]),sy(iy,{children:[!t&&n&&pd("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":c,onClick:()=>{S.current=!0,o()},style:{alignSelf:"center",margin:0,padding:"0.25rem 0",border:0,background:"none",cursor:"pointer",color:a,fontFamily:i,fontSize:"0.9rem",fontWeight:500,textDecoration:"underline",textUnderlineOffset:"0.2em"},children:e}),pd("div",{id:c,ref:y,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?ay:oy,children:s})]})}import{jsx as md}from"react/jsx-runtime";var ly=["first","second","third","fourth"];function Ls({rows:e,borderRadius:t}){return md("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:ly.slice(0,Math.max(1,e)).map(n=>md("div",{style:{height:wo,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},n))})}import{PaymentAPI as cy}from"@flopay/js";import{DEFAULT_PAYMENT_METHOD_ORDER as dy,resolveDefaultPaymentMethodLayout as uy}from"@flopay/shared";import{useEffect as py,useState as yy}from"react";var my=1500,fd=new Set;function gd(e){for(let t of e)fd.has(t)||(fd.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function fy(e){if(e!=null)try{return JSON.stringify(e)}catch{return gd(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var gy={order:[...dy],moreOptions:[]};function hd({rules:e,sessionId:t,nonce:n,billingApiUrl:o,waitForSession:a}){let i=fy(e),[s,c]=yy(null);return py(()=>{if(i===void 0||a)return;let y=JSON.parse(i),S=!1,P=ae=>{S||(S=!0,c(ae))},f=()=>P(uy(y));if(!t||!n||!o){f();return}let F=new AbortController,te=setTimeout(()=>{f(),F.abort()},my);return new cy(o,{telemetry:!1}).resolvePaymentMethodLayout(t,n,y,{signal:F.signal}).then(ae=>{if(!ae){f();return}S||gd(ae.warnings),P({order:ae.order,moreOptions:ae.moreOptions})}).catch(f).finally(()=>clearTimeout(te)),()=>{S=!0,clearTimeout(te),F.abort()}},[i,t,n,o,a]),i===void 0?gy:s}import{darkenHex as $d}from"@flopay/shared";import{Fragment as Hn,jsx as l,jsxs as Le}from"react/jsx-runtime";var Br="flopay_stripe_resume",wd="flopay_wallet_resume",Nd="fw1",nm="fw2",Ud=300*1e3,rm=900,om="express_checkout_click_timeout",am=25e3,im=25e3,sm=1e4,wr={provider:"paypal",paymentMethodCategory:"paypal"},lm="x-flopay-process-result-source",cm="status";async function dm(e,t,n){try{let o=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(o?.status==="complete")return null;if(o?.status==="authorized")return{status:"authorized",paymentId:o.paymentId,sessionId:o.id||t,authorizationExpiresAt:o.authorizationExpiresAt}}catch{}}var _i={},qa=class{constructor(t){this.reason=t}};function um(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function nn(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 Zs(e){return`${nm}:${e}`}function Ti(e){return nn(Zs(e))}function Mi(e,t){if(typeof window>"u")return null;let n=Zs(e);try{let o=localStorage.getItem(n);if(!o)return null;let a=JSON.parse(o);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>Ud||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Ti(e),null):a}catch{return Ti(e),null}}function pm(e){return nn(Zs(e.sessionId),e)}function kd(e,t,n){let o=Mi(e,t);return!o||o.clientSecret!==n?!1:Ti(e)}function js(e,t,n){if(typeof window>"u")return;Mi(e,t)?.clientSecret===n&&Ti(e)}function ym(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function $s(e,t,n){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 o=n?e.status==="succeeded":Ra(e.status),a=ym(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Rd(e,t,n){let o=null;try{return await Promise.race([Rc(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},sm),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function mm(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function zd(e){return e instanceof Sr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function xi(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new sa(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw zd(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var Ws=Jy,Ua=new Map,fm=250,Id="Just a moment \u2014 we are finalizing your order. Please press pay again.",gm="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Qs(e,t,n,o){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...o?{terminalReason:o}:{}})}async function Fi({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new sa(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function hm(e){return e instanceof Sr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function qd({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=Ea(n),s=i.firstName?i:Ea(o?.name);return br({email:Rn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Pm({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=qd({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return Rn(s.email)?s:i(a,s)}var $a=180,Ed=`flopay-card-enter ${$a}ms cubic-bezier(0, 0, 0.2, 1) both`,_d=`flopay-card-exit ${$a}ms cubic-bezier(0.4, 0, 0.2, 1) both`,vm=`flopay-buttons-enter ${$a}ms cubic-bezier(0, 0, 0.2, 1) both`,Cm=`flopay-buttons-exit ${$a}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function bm(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function el(e){return Xy(e)}var Sm={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function wm(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 Vs={width:"100%",minHeight:wo,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 Td(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Gs(e){return e==="paypal"?"PayPal":ja(e)}function km(e){let t=Fy(e);return`Enter a valid ${Ks(e)}${t?` (e.g. ${t})`:""}`}function Rm(e,t,n){let o=Uy(e),a=t.trim(),i=n&&o,s=i&&!a,c=i&&!!a&&!zy(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:c}}function Im(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!Rn(n);return{required:t,empty:o,malformed:a,value:n}}function Em(e){return typeof e=="number"?`${e}px`:e}var _m=["number","expiry","cvv","name"];function Tm(e){if(e===null||typeof e!="object")return null;let t={};for(let n of _m){let o=e[n];typeof o=="string"&&(t[n]=o)}return JSON.stringify(t)}function tl(e){return l(xm,{...e})}function Md({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:c,onDecline:y,onTechnicalFailure:S,runBeforeButtonClick:P,billingName:f,onBuyerIdentityReady:F,onLoadStateChange:te,placeholderBorderRadius:ae,popupCapabilityOwner:z,externalTelemetryContext:K,presentationMode:C}){let ge=uo(),{emitInstrument:ue}=la(lr),w=Xs(),Ke=Js(),X=Pt(()=>Ei(fn(ge),K),[K,ge]),[Ne,at]=oe("loading");Xe(()=>{te?.(Ne)},[Ne,te]);let[pt,Ie]=oe(!1),Bt=U(!1),xt=!Rn(n?.trim())||!f?.trim(),{request:Re,collect:Ye,finish:it}=Zo(),st=U(!1),Ee=U(null),ne=U(null),[pe,jt]=oe(0),[qe,lt]=oe(!1),re=U(!1),Me=U(new Map),{startAttempt:Ze,finishAttempt:V,invalidateAttempt:vt,isAttemptInvalidated:be,isAttemptCurrent:Je,generationRef:Ue}=Ma((ye,Te,ct)=>{S?.(ye,Te,{...ct,popupBlocked:ct?.popupBlocked??io(Te),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:C,terminalReason:"overlay_timeout"}),lt(!0),jt(dt=>dt+1)},{onHandoffObserved:()=>{z.markAvailable(),X?.log({name:"provider.popup.opened",stage:"overlay_open",...wr,attempt:Ue.current})}});Xe(()=>{qe&&ne.current?.focus()},[qe,pe]);let Qe=Fe(()=>{jt(ye=>ye+1)},[]),Ct=Fe((ye,Te,ct)=>{vt(ct),S?.("paypal",ye,{code:Te,popupBlocked:io(ye),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:C}),lt(!0),Qe()},[vt,S,C,Qe]),Be=Fe(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);Xe(()=>{re.current&&(re.current=!1,Be())},[Be,pe]);let kt=Fe(()=>{lt(!1),i?.(null),Be()},[Be,i]);Xe(()=>{if(!w||st.current)return;let[ye,Te,ct]=Fd();if(!ye||!Te)return;let dt=Ky(Te);if(!dt)return;st.current=!0;let Ve=!0,yt=Ua.get(Te);yt||(yt=ct==="failed"?Promise.resolve(null):Promise.resolve().then(()=>w.retrievePaymentIntent(Te)),Ua.set(Te,yt));let mt={accountPatch:dt.accountPatch,sessionId:dt.sessionId,nonce:dt.nonce},St=()=>{X?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...wr,requestCategory:"provider_sdk"})};return X?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...wr}),(async()=>{try{Ie(!0);let $e=await yt;if(!Ve)return;if($e?.error){Ua.delete(Te),St(),i?.($e.error.message??"Failed to retrieve PayPal payment status.");return}if(_y(),Ua.delete(Te),ct==="failed"){let q="PayPal payment was declined. Please try again.";X?.terminal({outcome:"payment_declined",...wr,terminalReason:"provider_declined"}),i?.(q),y?.(mn("paypal",q));return}let et=$e?.paymentIntent;if(et&&et.id!==ye){St(),i?.("Failed to match the returned PayPal payment.");return}if(et&&(et.status==="requires_capture"||et.status==="succeeded")){let q=typeof et.payment_method=="string"?et.payment_method:et.payment_method?.id;a({id:q??et.id,type:"card",threeDSecureActionResultTokenId:et.id,isPaypal:!0},{...mt,presentationMode:"redirect"})}else{let q="PayPal payment was not completed. Please try again.";X?.terminal({outcome:et?.status==="canceled"?"payment_cancelled":"payment_declined",...wr,terminalReason:et?.status==="canceled"?"cancelled":"provider_declined"}),i?.(q),y?.(mn("paypal",q))}}catch($e){if(!Ve)return;Ua.delete(Te),St(),i?.($e instanceof Error?$e.message:"Failed to complete PayPal payment.")}finally{Ve&&Ie(!1)}})(),()=>{Ve=!1,st.current=!1}},[w,a,i,y,X]);let Ae=Fe(async(ye=!1)=>{let Te=P?await P("paypal"):{proceed:!0};if(!Te.proceed)return Me.current.delete(pe),!1;let ct=Ze("paypal");return Me.current.set(pe,{generation:ct,accountPatch:Te.accountPatch,sessionId:Te.sessionId,nonce:Te.nonce}),lt(!1),X?.log({name:`provider.${ye?"redirect.started":"handoff.requested"}`,stage:ye?"redirect":"overlay_open",...wr,attempt:ct}),c?.("paypal"),!0},[c,X,P,Ze,pe]),_e=Fe(async ye=>{if(s||pt||!await Ae()){ye.reject();return}ye.resolve()},[s,Ae,pt]),bt=Fe(async ye=>{if(!w||!Ke)return;let Te=Me.current.get(pe);if(Te&&!Je(Te.generation)){Me.current.delete(pe);return}if(!Te&&be()||Te&&!V(Te.generation))return;Te||V();let ct=Te??null;if(Me.current.delete(pe),!ct&&P){let je=await P("paypal");if(!je.proceed){ye.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ct={accountPatch:je.accountPatch,sessionId:je.sessionId,nonce:je.nonce}}let dt=ct?.sessionId??e,Ve=ct?.nonce??t,yt=await Pm({event:ye,prepared:ct,email:n,billingName:f,methodLabel:"PayPal",collect:Ye});if(!yt){ye.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let mt=yt.email,St={...ct?.accountPatch,...br(yt,!0)};try{if(Ie(!0),i?.(null),!dt||!Rn(mt))throw new Error("Missing sessionId or email for PayPal payment");await F?.(yt);let je=w.createPaymentMethod,{error:$e,paymentMethod:et}=await je({type:"paypal"});if($e){Ct($e,"stripe_paypal_create_payment_method_failed",Te?.generation),ye.paymentFailed({reason:"fail"});return}let q=await xi(o,ue,dt,Ve??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:et?.id??null,intentKind:"payment"});if(Ai(q)){ye.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:St,paymentMethodCategory:"paypal",presentationMode:C,sessionId:dt,nonce:Ve,settledProcessResponse:q.response});return}if(q.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let hn=q.clientSecret,b={return_url:Dd()};if(et?.id&&(b.payment_method=et.id),!nn(Ws,{clientSecret:hn,sessionId:dt,nonce:Ve,accountPatch:St})&&C==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Y,paymentIntent:j}=await w.confirmPayment({clientSecret:hn,confirmParams:b,redirect:"if_required"});if(Y){if(nn(Ws),si(Y)){let h=Y.message??"Your payment was declined.";X?.terminal({outcome:"payment_declined",...wr,terminalReason:"provider_declined"}),i?.(h),y?.(mn("paypal",h,{code:Wo(Y),declineCode:Cs(Y)})),await Fi({billingApiUrl:o,sessionId:dt,nonce:Ve,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Wo(Y)??"provider_declined"}})}else Ct(Y,"stripe_paypal_confirm_failed",Te?.generation);return}nn(Ws);let J=typeof j?.payment_method=="string"?j.payment_method:j?.payment_method?.id;a({id:J??j?.id,type:"card",threeDSecureActionResultTokenId:j?.id,isPaypal:!0},{accountPatch:St,paymentMethodCategory:"paypal",presentationMode:C,sessionId:dt,nonce:Ve});return}catch(je){Ct(je,"stripe_paypal_failed",Te?.generation)}finally{Ie(!1)}},[w,Ke,e,t,n,f,Ye,F,o,ue,a,i,y,P,Ct,V,Je,be,X,C,pe]),Ft=Fe(async()=>{if(!(Bt.current||s||pt||!w||!Ke)){Bt.current=!0,Ie(!0);try{if(!await Ae(!0))return;await bt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Bt.current=!1,Ie(!1)}}},[Ke,bt,s,Ae,w,pt]),Rt=C==="redirect"?l("button",{type:"button",disabled:s||pt,onClick:()=>{Ft()},style:{width:"100%",minHeight:wo,border:"1px solid #d1d5db",borderRadius:ae??8,background:"#ffc439",color:"#111827",cursor:s||pt?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):l(Ld,{onReady:ye=>at(bs(ye,["paypal"])),onLoadError:()=>{at("load_error"),Qs(X,"paypal","paypal","provider_error")},onClick:_e,onConfirm:bt,onCancel:()=>{let ye=Me.current.get(pe);Me.current.delete(pe),X?.terminal({outcome:"payment_cancelled",...wr,terminalReason:"cancelled",...ye?{attempt:ye.generation}:{}}),vt(ye?.generation),lt(!1),re.current=!0,Qe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:xt,emailRequired:xt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},pe),G=Le(Hn,{children:[Le("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[qe&&l("button",{ref:ne,type:"button","data-testid":"flopay-paypal-retry-button",onClick:kt,style:Vs,children:"Try PayPal again"}),Re&&l(Qo,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:it,onCancel:()=>it(null)},Re.id),l("div",{style:{display:Re?"none":void 0},children:Rt})]}),pt&&!Re&&l(xr,{status:"processing"})]});return C==="redirect"?G:l(Ss,{state:Ne,placeholderTestId:"flopay-paypal-placeholder",borderRadius:ae,children:G})}function Hs(e){return e==="apple_pay"||e==="google_pay"}var Mm=200;function Am({active:e}){return tm(()=>e?Ay(document):void 0,[e]),null}function Ad({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:c,onButtonClick:y,onDecline:S,onTechnicalFailure:P,runBeforeButtonClick:f,billingName:F,onBuyerIdentityReady:te,onLoadStateChange:ae,placeholderBorderRadius:z,popupCapabilityOwner:K,externalTelemetryContext:C}){let ge=uo(),{emitInstrument:ue}=la(lr),w=Xs(),Ke=Js(),X=Pt(()=>Ei(fn(ge),C),[C,ge]),[Ne,at]=oe("loading");Xe(()=>{ae?.(Ne)},[Ne,ae]);let[pt,Ie]=oe(!1);Xe(()=>{lt.current=pt},[pt]);let Bt=U(!Rn(n?.trim())||!F?.trim()).current,{request:xt,collect:Re,finish:Ye}=Zo(),it=U(null),st=U(null),[Ee,ne]=oe(0),[pe,jt]=oe(()=>Sd()),qe=U(pe),lt=U(!1),[re,Me]=oe(!1),[Ze,V]=oe(()=>Mi(e,t)?"blocked":"idle"),[vt,be]=oe("google_pay"),Je=U(null),Ue=U(!0),Qe=U(!1),Ct=U("google_pay"),Be=U("google_pay"),kt=U(null),Ae=U(null),_e=U(new Set),bt=U(null),Ft=U(null);Xe(()=>(Ue.current=!0,()=>{Ue.current=!1;for(let h of _e.current)window.clearTimeout(h);_e.current.clear()}),[]);let Rt=U(new Map),{startAttempt:G,finishAttempt:ye,invalidateAttempt:Te,isAttemptInvalidated:ct,isAttemptCurrent:dt,generationRef:Ve}=Ma((h,se,$)=>{P?.(h,se,{...$,popupBlocked:$?.popupBlocked??io(se),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),be(h),Me(!0),ne(Se=>Se+1)},{onHandoffObserved:h=>{Ft.current=Ve.current,K.markAvailable(),X?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ve.current,...h==="apple_pay"||h==="google_pay"?{walletType:h}:{}})},defersMissingTerminal:Hs,onMissingTerminalDeferred:(h,se)=>{let $=X?.now()??globalThis.performance?.now()??Date.now(),Se=bt.current,we=Se?.generation===se?Se.startedAt:$;X?.performance({stage:"overlay_return",durationMs:Math.max(0,$-we),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:se,...Hs(h)?{walletType:h}:{}}),X?.flush?.().catch(()=>{})}});Xe(()=>{re&&st.current?.focus()},[re,Ee]);let yt=U(0),mt=U(!1),St=Fe(()=>{if(yt.current>0){mt.current=!0;return}ne(h=>h+1)},[]),je=Fe(()=>{yt.current-=1,!(yt.current>0||!mt.current)&&(mt.current=!1,Ue.current&&ne(h=>h+1))},[]),$e=Fe((h,se,$,Se,we=!1)=>{Te(Se),P?.(h,se,{code:$,popupBlocked:io(se),telemetryReported:we,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),be(h),Me(!0),St()},[Te,P,St]),et=Fe(h=>{X?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...Hs(h)?{walletType:h}:{}}),P?.(h,new Error("The wallet click was not ready within the time the wallet allows."),{code:om,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),be(h),Me(!0)},[P,X]),q=Fe(()=>{window.setTimeout(()=>{(it.current?.querySelector("iframe")??it.current)?.focus()},0)},[]);Xe(()=>{Qe.current&&(Qe.current=!1,q())},[q,Ee]);let hn=Fe(()=>{Me(!1),c?.(null),q()},[q,c]),b=Fe(()=>{Je.current?.()},[]);Xe(()=>{let h=null,se=()=>{h=null;let Se=Sd();Se!==qe.current&&(qe.current=Se,jt(Se),!lt.current&&!dt(Ve.current)&&St())},$=()=>{h!==null&&window.clearTimeout(h),h=window.setTimeout(se,Mm)};return window.addEventListener("resize",$),()=>{window.removeEventListener("resize",$),h!==null&&window.clearTimeout(h)}},[Ve,dt,St]),Xe(()=>{let h=Mi(e,t);if(!h)return;let se=!1,$=!1,Se=async()=>{if(!$){$=!0,se||V("checking");try{let we=await Rd(w,h.clientSecret,_e.current);if(se)return;let k=$s(we,h.providerObjectId,zs(h.clientSecret));if(k.kind==="confirmed"){if(!kd(e,t,h.clientSecret))return;Je.current=null,V("idle"),s({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.intentId},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(k.kind==="terminal"){js(e,t,h.clientSecret),Je.current=null,V("idle"),be(h.paymentMethodType),Me(!0),St();return}V("blocked")}catch{se||V("blocked")}finally{$=!1}}};return Je.current=Se,V("blocked"),()=>{se=!0,Je.current===Se&&(Je.current=null)}},[t,s,St,e,w]);let g=Fe(async h=>{let se=!1,$=!1,Se=Ge=>{se||$||(se=!0,h.paymentFailed({reason:"fail",...Ge?{message:Ge}:{}}))};if(!w||!Ke){Se();return}let we=Rt.current.get(Ee);if(we&&!dt(we.generation)){Rt.current.delete(Ee),Se();return}if(!we&&ct()){Se();return}if(we&&!ye(we.generation)){Se();return}we||(ye(),mt.current=!1);let k=h.expressPaymentType??we?.method??Ct.current,tt=we??null,Ht=Td(k),Dt;k==="apple_pay"?Dt="apple_pay":k==="google_pay"&&(Dt="google_pay");let Dn=we?.generation??Ve.current,ve=X,kr=ve?.now()??globalThis.performance?.now()??Date.now(),dn=new AbortController,un=!1,nt=!1,Tt=null,En=e,_n="processing",Tn="other",Cn="provider_runtime",bn,Kt=new Promise((Ge,me)=>{bn=me}),Ot=window.setTimeout(()=>{un=!0,dn.abort(),bn(_i)},am),Xt=async(Ge,me,er)=>{_n=Ge,Tn=me,Cn=me==="intent_create"||me==="session_claim"?"transport_error":"provider_runtime";let Mt=ve?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([er,Kt])}finally{let Mn=ve?.now()??globalThis.performance?.now()??Date.now();ve?.performance({stage:Ge,durationMs:Math.max(0,Mn-Mt),durationMode:"machine",requestCategory:me,paymentMethodCategory:"wallet",provider:"stripe",...un?{statusClass:"timeout"}:{}})}};try{if(Ie(!0),c?.(null),!tt&&f){let le=await Xt("processing","other",f(Ht));if(!le.proceed){Se();return}tt={accountPatch:le.accountPatch,sessionId:le.sessionId,nonce:le.nonce}}let Ge=tt?.sessionId??e;En=Ge;let me=tt?.nonce??t,er=kt.current??tt?.accountPatch,Mt=qd({event:h,fallbackEmail:er?.email??n,fallbackName:[er?.firstName,er?.lastName].join(" ").trim()||F});if(!Rn(Mt.email)){Se("Buyer details are required."),Re(Gs(k),Mt).then(le=>{le&&(kt.current=le)});return}kt.current=null;let Mn={...tt?.accountPatch,...br(Mt,!0)};await Xt("processing","session_claim",Promise.resolve(te?.(Mt)));let{error:On}=await Xt("tokenization","provider_sdk",Ke.submit());if(On){Se(),$e(k,On,"stripe_wallet_submit_failed",we?.generation);return}if(!Ge)throw new Error("Missing sessionId or email for payment.");let tr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,paymentMethodId:null,intentKind:a},Ln=JSON.stringify({sessionId:Ge,nonce:me??"",request:tr}),Rr=Ae.current,pr=Rr?.retryIdentity===Ln?Rr.authorizationAttemptId:Hy();Ae.current={authorizationAttemptId:pr,retryIdentity:Ln};let pn=await Xt("processing","intent_create",xi(o,ue,Ge,me??"",{...tr,authorizationAttemptId:pr},{signal:dn.signal}));if(Ai(pn)){Se(),s({type:"card",paymentMethodType:k},{accountPatch:Mn,paymentMethodCategory:"wallet",sessionId:Ge,nonce:me,settledProcessResponse:pn.response});return}if(pn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let yn=pn.clientSecret,An=pm({createdAt:Date.now(),sessionId:Ge,...me?{nonce:me}:{},clientSecret:yn,providerObjectId:pn.providerObjectId,paymentMethodType:k,accountPatch:Mn});window.clearTimeout(Ot),nt=!0,ve?.performance({stage:"callback",durationMs:Math.max(0,(ve?.now()??globalThis.performance?.now()??Date.now())-kr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Kn=ve?.now()??globalThis.performance?.now()??Date.now(),Nn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Dt?{walletType:Dt}:{},attempt:Dn},xn=!1,rn=null;ve?.log({name:"payment.provider_confirmation.started",...Nn}),Tt=window.setTimeout(()=>{Tt!==null&&_e.current.delete(Tt),xn=!0;let le=ve?.now()??globalThis.performance?.now()??Date.now();ve?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Nn,operationOutcome:"watchdog_expired",durationMs:Math.max(0,le-Kn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),ve?.flush?.().catch(()=>{}),rn?.()},im),_e.current.add(Tt);let Zt=(le,ut)=>{Tt!==null&&(window.clearTimeout(Tt),_e.current.delete(Tt),Tt=null);let He=ve?.now()??globalThis.performance?.now()??Date.now(),Lt=Math.max(0,He-Kn),ke=le;xn&&(le==="resolved"?ke="resolved_late":le==="returned_error"?ke="returned_error_late":ke="rejected_late");let Ir=ut??(le==="resolved"?"approved":"provider_error");return ve?.log({name:"payment.provider_confirmation.returned",...Nn,operationOutcome:ke,terminalReason:Ir}),ve?.performance({...Nn,durationMs:Lt,durationMode:"buyer",operationOutcome:ke,terminalReason:Ir}),{durationMs:Lt,operationOutcome:ke,terminalReason:Ir}},Qt=!1,Vt=!1,Un=le=>{if(!le||typeof le!="object")return null;let ut=le;if(ut.error)return null;let He=ut.setupIntent??ut.paymentIntent,Lt=$s(He??null,void 0,!!ut.setupIntent);return Lt.kind==="confirmed"?Lt:null},zn=le=>{if(Qt||we&&Ve.current!==we.generation)return;let ut=Un(le);if(!ut)return;if(An&&!kd(Ge,me,yn)){Qt=!0;return}let{intentId:He,paymentMethodId:Lt}=ut;Qt=!0,Vt=!0,Ae.current=null,Je.current=null,Ue.current&&(V("idle"),Ie(!1));let ke=`${Nd}:${Ge}`;nn(ke,{createdAt:Date.now(),sessionId:Ge,nonce:me,accountPatch:Mn,paymentMethodId:Lt,providerIntentId:He,paymentMethodType:k});try{s({id:Lt,type:"card",threeDSecureActionResultTokenId:He},{accountPatch:Mn,paymentMethodCategory:"wallet",sessionId:Ge,nonce:me})}finally{nn(ke)}},Fn=!1;rn=async()=>{if(!(Fn||Qt||Vt)){Fn=!0,Ue.current&&V("checking");try{let le=await Rd(w,yn,_e.current);if(Qt||Vt)return;let ut=zs(yn),He=$s(le,pn.providerObjectId,ut);if(He.kind==="confirmed"){zn(ut?{setupIntent:le}:{paymentIntent:le});return}if(He.kind==="terminal"){if(Vt=!0,js(Ge,me,yn),Ae.current=null,Je.current=null,!Ue.current)return;V("idle"),Se(),$e(k,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",we?.generation,!0);return}Ue.current&&!Vt&&(V("blocked"),Ie(!1))}catch{Ue.current&&!Vt&&(V("blocked"),Ie(!1))}finally{Fn=!1}}},Je.current=rn;let R,We;try{$=!0,yt.current+=1;let le;try{le=await(zs(yn)?w.confirmSetup({elements:Ke,clientSecret:yn,redirect:"if_required"}):w.confirmPayment({elements:Ke,clientSecret:yn,redirect:"if_required"}))}finally{je()}if(!le||typeof le!="object")throw new qa(um(le));if(R=le,!R.error&&!Un(R))throw new qa("confirmation_result_unconfirmed");We=Zt(R.error?"returned_error":"resolved",R.error&&si(R.error)?"provider_declined":void 0)}catch(le){let ut=le instanceof qa?le.reason:void 0,He=ut!==void 0,Lt=Zt(He?"returned_error":"rejected");if(ve?.error({...He?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:ut}:Is(le),...Nn,operationOutcome:Lt.operationOutcome,durationMs:Lt.durationMs,statusClass:"unknown",terminalReason:Lt.terminalReason}),!Ue.current||Qt)return;await rn?.();return}let v=R.error;if(v){if(!Ue.current||Qt)return;if(si(v)){Vt=!0,js(Ge,me,yn),Ae.current=null,Je.current=null,V("idle"),Rt.current.get(Ee)===we&&Rt.current.delete(Ee);let le=v.message??"Your payment was declined.";c?.(le),S?.(mn(Ht,le,{code:Wo(v),declineCode:Cs(v)})),Fi({billingApiUrl:o,sessionId:Ge,nonce:me,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,providerDeclineReason:Wo(v)??"provider_declined",...pn.intentKind==="payment"&&pn.providerObjectId.startsWith("pi_")?{providerIntentId:pn.providerObjectId}:{}}})}else ve?.error({...Is(v),...Nn,operationOutcome:We.operationOutcome,durationMs:We.durationMs,statusClass:"unknown",terminalReason:We.terminalReason}),await rn?.();return}if(zn(R),!Qt)throw new Error("Invalid provider returned for APM intent")}catch(Ge){if(Ge===_i){let me=ve?.now()??globalThis.performance?.now()??Date.now();ve?.error({errorCode:mm(Tn),stage:_n,requestCategory:Tn,paymentMethodCategory:"wallet",provider:"stripe",...Dt?{walletType:Dt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:En,durationMs:Math.max(0,me-kr),statusClass:"timeout",failureCategory:Cn,attempt:Dn,terminalReason:"provider_error"}),ve?.flush?.().catch(()=>{})}Se(),$e(k,Ge,Ge===_i?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",we?.generation,Ge===_i)}finally{if(window.clearTimeout(Ot),Tt!==null&&(window.clearTimeout(Tt),_e.current.delete(Tt)),!nt){let Ge=ve?.now()??globalThis.performance?.now()??Date.now();ve?.performance({stage:"callback",durationMs:Math.max(0,Ge-kr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...un?{statusClass:"timeout"}:{}})}Ue.current&&Ie(!1)}},[w,Ke,e,t,n,F,Re,te,o,ue,a,s,c,S,f,$e,je,ye,dt,ct,Ve,X,Ee]),Y=Pt(()=>lc(i),[i]),j=Pt(()=>i.map(Zy),[i]),J=Pt(()=>l(Ld,{onReady:h=>{at(bs(h,j))},onLoadError:h=>{at("load_error"),Qs(X,"stripe","wallet","provider_error")},onClick:async h=>{let se=X?.now()??globalThis.performance?.now()??Date.now();Ct.current=h.expressPaymentType,Be.current=Td(h.expressPaymentType);let $=!0,Se=window.setTimeout(()=>{$=!1,h.reject(),et(h.expressPaymentType)},rm),we=f?await f(Be.current,{abandoned:()=>!$}):{proceed:!0};if(window.clearTimeout(Se),!$)return;if(!we.proceed){Rt.current.delete(Ee),h.reject();return}let k=G(h.expressPaymentType);mt.current=!1,bt.current={generation:k,startedAt:se},Rt.current.set(Ee,{generation:k,method:h.expressPaymentType,accountPatch:we.accountPatch,sessionId:we.sessionId,nonce:we.nonce}),Me(!1),X?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:k,...h.expressPaymentType==="apple_pay"||h.expressPaymentType==="google_pay"?{walletType:h.expressPaymentType}:{}}),y?.(Be.current),h.resolve()},onConfirm:g,onCancel:()=>{let h=Rt.current.get(Ee);Rt.current.delete(Ee);let se=bt.current,$=X?.now()??globalThis.performance?.now()??Date.now();if(h&&se?.generation===h.generation&&qy({method:h.method,elapsedMs:$-se.startedAt,handoffObserved:Ft.current===h.generation})){X?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:h.generation,walletType:"google_pay"}),Ae.current=null,$e(h.method,new Error("The browser window is too small for the Google Pay sheet."),Od,h.generation,!0);return}X?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...h?{attempt:h.generation}:{}}),Te(h?.generation),Ae.current=null,Me(!1),Qe.current=!0,St()},options:{...cc,paymentMethods:Y,emailRequired:Bt,billingAddressRequired:Bt}},Ee),[j,Y,g,Te,y,Bt,$e,et,St,f,G,Ee,X]);return Le(Hn,{children:[l(Ss,{state:Ne,placeholderTestId:"flopay-wallet-placeholder",borderRadius:z,children:Le("div",{ref:it,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[re&&Le("button",{ref:st,type:"button","data-testid":"flopay-wallet-retry-button",onClick:hn,style:Vs,children:["Try ",Gs(vt)," again"]}),Ze!=="idle"&&Le("div",{role:"status","aria-live":"polite",children:[l("p",{children:"We are still confirming your payment. Check its status before trying again."}),l("button",{type:"button",onClick:b,disabled:Ze==="checking",style:Vs,children:Ze==="checking"?"Checking payment status\u2026":"Check payment status"})]}),xt&&l(Qo,{identity:xt.identity,methodLabel:xt.methodLabel,onComplete:Ye,onCancel:()=>Ye(null)},xt.id),Le("div",{style:{display:xt||Ze!=="idle"?"none":void 0},children:[l(Am,{active:pe}),J]})]})}),pt&&l(xr,{status:"processing"})]})}function jd(e,t,n){let o=Bd(n,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function Ys({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:c,onErrorChange:y,onDecline:S,onCancel:P,runBeforeButtonClick:f,onButtonClick:F,isProcessing:te,submitButtonColor:ae,submitButtonBorderRadius:z,submitButtonStyle:K,errorText:C}){let ge=uo(),{emitInstrument:ue}=la(lr),w=Xs(),Ke=Js(),[X,Ne]=oe(!1),at=U(!1),[pt,Ie]=oe(!1),[Bt,xt]=oe("loading"),[Re,Ye]=oe(""),it=!Rn(o?.trim()),st=!it||Rn(Re.trim()),Ee=Fe(async()=>{if(!w||!Ke||te||at.current||!pt)return;at.current=!0,Ne(!0);let ne=f?await f("card"):{proceed:!0};if(!ne.proceed){at.current=!1,Ne(!1);return}F?.("card");let pe=ne.sessionId??t,jt=ne.nonce??n,qe=Ea(a?.trim()),lt=br({email:ne.accountPatch?.email?.trim()||o?.trim()||Re.trim(),firstName:ne.accountPatch?.firstName?.trim()||qe.firstName,lastName:ne.accountPatch?.lastName?.trim()||qe.lastName}),re=lt.email,Me=br({...ne.accountPatch,...lt});try{if(y?.(null),!Rn(re))throw new Error("A valid email address is required for payment.");await i?.(lt);let Ze=await Ke.submit();if(Ze.error){y?.(Ze.error.message??"Payment failed.");return}let V=[lt.firstName,lt.lastName].filter(Boolean).join(" "),vt=await w.createPaymentMethod({elements:Ke,params:{billing_details:{email:re,...V?{name:V}:{}}}});if(vt.error||!vt.paymentMethod){y?.(vt.error?.message??"Failed to create payment method.");return}let be=vt.paymentMethod;if(!pe||!re)throw new Error("Missing sessionId or email for payment.");let Je=be.type||e,Ue=await xi(s,ue,pe,jt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Je,paymentMethodId:null,intentKind:"payment"});if(Ai(Ue)){c({type:"card",gateway:"stripe",paymentMethodType:Je},{accountPatch:Me,paymentMethodCategory:"apm",sessionId:pe,nonce:jt,settledProcessResponse:Ue.response});return}if(Ue.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Qe=Ue.clientSecret;nn(Br,{clientSecret:Qe,sessionId:pe,nonce:jt,accountPatch:Me,paymentMethodId:be.id,paymentMethodType:be.type??e,gateway:"stripe"});let{error:Ct,paymentIntent:Be}=await w.confirmPayment({clientSecret:Qe,confirmParams:{return_url:window.location.href,payment_method:be.id},redirect:"if_required"});if(Ct){nn(Br);let _e=Ct.message??"Payment failed.";y?.(_e),S?.(mn("card",_e,{code:Ct.code})),await Fi({billingApiUrl:s,sessionId:pe,nonce:jt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ct.code??"provider_declined"}});return}let kt=Be?.status;if(!Ra(kt)){nn(Br);let _e=kt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(_e),S?.(mn("card",_e,{code:kt??"missing_payment_intent"}));return}nn(Br);let Ae=typeof Be?.payment_method=="string"?Be.payment_method:Be?.payment_method?.id;c({id:Ae??be.id,type:"card",threeDSecureActionResultTokenId:Be?.id,gateway:"stripe",paymentMethodType:be.type??e},{accountPatch:Me,paymentMethodCategory:"apm",sessionId:pe,nonce:jt})}catch(Ze){y?.(Ze instanceof Error?Ze.message:"Payment failed. Please try again.")}finally{at.current=!1,Ne(!1)}},[w,Ke,te,pt,f,F,t,n,o,a,Re,i,s,ue,e,c,y,S]);return Le("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[it&&l("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:it&&Le("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",l("input",{type:"email",autoComplete:"email",required:!0,value:Re,onChange:ne=>Ye(ne.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),l(em,{onReady:()=>xt("ready"),onLoadError:()=>{xt("load_error"),Qs(fn(ge),"stripe","apm")},onChange:ne=>{Ie(!!ne.complete)},options:{layout:dc,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...Rn(o?.trim())?{email:o?.trim()}:{}}}}}),l(uc,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Ee()},disabled:!pt||!st||X||te||Bt!=="ready",color:ae,borderRadius:z,style:K,children:X?"Processing\u2026":`Pay with ${ja(e)}`}),C&&l(na,{margin:"0.75rem 0 0",children:C})]})}function xd({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:c,paymentElementBaseOptions:y,futureUseSession:S,onTokenizedBody:P,onErrorChange:f,onButtonClick:F,onDecline:te,runBeforeButtonClick:ae,onLoadStateChange:z,isProcessing:K=!1,submitButtonColor:C="#4A49FF",submitButtonBorderRadius:ge=8,submitButtonStyle:ue,buttonAppearance:w,themeId:Ke,onExpandApm:X,expandedApmMethod:Ne}){let{emitInstrument:at}=la(lr),[pt,Ie]=oe(null),[Bt,xt]=oe(null),Re=U(!1),{request:Ye,collect:it,finish:st}=Zo();Xe(()=>{s.length>0&&c?z?.("ready"):c||z?.("loading")},[s.length,c,z]);let Ee=Fe(async re=>{if(!c||Re.current||K)return;Re.current=!0,xt(re);let Me=ae?await ae("card"):{proceed:!0};if(!Me.proceed){Re.current=!1,xt(null);return}F?.("card");let Ze=Me.sessionId??e,V=Me.nonce??t,vt=Ea([Me.accountPatch?.firstName,Me.accountPatch?.lastName].filter(Boolean).join(" ")||o),be=br({email:Me.accountPatch?.email?.trim()||n?.trim(),firstName:Me.accountPatch?.firstName?.trim()||vt.firstName,lastName:Me.accountPatch?.lastName?.trim()||vt.lastName});if(!Rn(be.email)){xt(null);let Qe=await it(ja(re),be);if(!Qe){Re.current=!1;return}be=Qe,xt(re)}let Je=be.email,Ue=br({...Me.accountPatch,...be});try{if(f?.(null),!Ze||!Rn(Je))throw new Error("Missing sessionId or email for payment.");await a?.(be);let Qe=await xi(i,at,Ze,V??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,paymentMethodId:null,intentKind:"payment"});if(Ai(Qe)){P({type:"card",gateway:"stripe",paymentMethodType:re},{accountPatch:Ue,paymentMethodCategory:"apm",sessionId:Ze,nonce:V,settledProcessResponse:Qe.response});return}if(Qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ct=Qe.clientSecret;nn(Br,{clientSecret:Ct,sessionId:Ze,nonce:V,accountPatch:Ue,paymentMethodType:re,gateway:"stripe"});let{error:Be,paymentIntent:kt}=await c.confirmPayment({clientSecret:Ct,confirmParams:{return_url:window.location.href,payment_method_data:{type:re,billing_details:{name:[be.firstName,be.lastName].filter(Boolean).join(" "),...Je?{email:Je}:{}}}},redirect:"if_required"});if(Be){nn(Br);let bt=Be.message??"Payment failed.";f?.(bt),te?.(mn("card",bt,{code:Be.code})),await Fi({billingApiUrl:i,sessionId:Ze,nonce:V,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,providerDeclineReason:Be.code??"provider_declined"}});return}let Ae=kt?.status;if(!Ra(Ae)){nn(Br);let bt=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(bt),te?.(mn("card",bt,{code:Ae??"missing_payment_intent"}));return}nn(Br);let _e=typeof kt?.payment_method=="string"?kt.payment_method:kt?.payment_method?.id;P({id:_e??kt?.id,type:"card",threeDSecureActionResultTokenId:kt?.id,gateway:"stripe",paymentMethodType:re},{accountPatch:Ue,paymentMethodCategory:"apm",sessionId:Ze,nonce:V})}catch(Qe){f?.(Qe instanceof Error?Qe.message:"Payment failed. Please try again.")}finally{Re.current=!1,xt(null)}},[c,K,ae,F,e,t,n,it,i,at,o,a,P,f,te]),[ne,pe]=oe(null),jt=X?Ne??null:ne,qe=Fe(re=>{Re.current||K||jt&&jt!==re||(vd(re)?X?X(re):pe(re):Ee(re))},[jt,K,Ee,X]),lt=Pt(()=>ne?jd(y,ne,S):null,[ne,y,S]);return l("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ye?l(Qo,{identity:Ye.identity,methodLabel:Ye.methodLabel,onComplete:st,onCancel:()=>st(null)},Ye.id):s.map(re=>{let Me=Ne===re,Ze=Bt===re,V=Bt!==null&&Bt!==re||Ne!=null&&Ne!==re;return Le(za.Fragment,{children:[l(sc,{method:re,themeId:Ke,submitting:Ze,disabled:V,highlighted:Me,hasNextStep:vd(re),onClick:()=>qe(re),backgroundColor:w?.backgroundColor,borderColor:w?.borderColor,textColor:w?.textColor,borderRadius:w?.borderRadius,fontFamily:w?.fontFamily}),!X&&ne===re&<&&c&&l(co,{stripe:c,options:lt,children:l(Ys,{method:re,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:P,onErrorChange:f,onDecline:te,onCancel:()=>pe(null),runBeforeButtonClick:ae,onButtonClick:F,isProcessing:K,submitButtonColor:C,submitButtonBorderRadius:ge,submitButtonStyle:ue})},re)]},re)})})}function xm({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:c,onDecline:y,onCancel:S,onTokenizedBody:P,firstName:f,lastName:F,chv:te,className:ae,submitLabel:z,isProcessing:K,error:C,onErrorChange:ge,showPayPal:ue=!0,showStripe:w=!0,walletPresentation:Ke="auto",enabledPaymentMethods:X,enabledPaymentMethodCountries:Ne,showApplePay:at=!0,showGooglePay:pt=!0,layout:Ie="default",paymentMethodLayout:Bt,moreOptionsLabel:xt,theme:Re,buttonsTheme:Ye,buttonsStyles:it,appearance:st,cardButtonContent:Ee,cardBackButtonContent:ne,cardTitleContent:pe,showSecurityFooter:jt,onButtonClick:qe,onBeforeButtonClick:lt,onBuyerIdentityReady:re,enableAVS:Me,cardFieldOrder:Ze,showCardBrandIcons:V,showCardFieldLabels:vt,cardFieldLabels:be,cardFieldPlaceholders:Je,cardAutoFocus:Ue,onCardFieldsReady:Qe,onCardFieldsFailed:Ct,cardFieldsTimeoutMs:Be,cardPreFormSlot:kt,avsLayout:Ae="row",country:_e,zip:bt,addressLine1:Ft,addressLine2:Rt,city:G,state:ye,onCountryChange:Te,onZipChange:ct,avsCheck:dt,checkoutType:Ve,checkoutLayout:yt,totalAmount:mt=0,currency:St="usd",initialCardOpen:je=!1,directPaypal:$e,isSubscription:et=!1,session:q,dataAttachmentPending:hn=!1,dataAttachmentRequiresIdentity:b=!1,debug:g=!1}){let Y=uo(),j=Es(),J=la(Cr),{emitInstrument:h}=la(lr),se=U(null);se.current||(se.current=mi());let $=se.current,[,Se]=oe(0),we=U(null);we.current||(we.current=Sa());let k=we.current,tt=Pt(()=>({browser:k,capability:$,presentationMode:"popup"}),[k,$]),Ht=q??J.session,Dt=Pt(()=>({futureUse:Ht?.futureUse,futureUseUnsupported:Ht?.futureUseUnsupported}),[Ht?.futureUse,Ht?.futureUseUnsupported]),Dn=Ht?.gateways?.paypal?.providerObjectType??$e?.providerObjectType,ve=hn||J.claimPending===!0,kr=b||J.claimRequiresIdentity===!0,dn=ve&&!kr,un=Lc(),nt=n||un,Tt=hd({rules:Bt,sessionId:e,nonce:t,billingApiUrl:nt,waitForSession:dn}),En=Tt?.order??null,[_n,Tn]=oe(!1),Cn=Pt(()=>En?jy(En):null,[En]),bn=En!==null&&Ly(En),[Kt,Ot]=oe(!1),[Xt,Ge]=oe(null),[me,er]=oe(_e??""),[Mt,Mn]=oe(bt??""),[On,tr]=oe(Ft??""),[Ln,Rr]=oe(Rt??""),[pr,pn]=oe(G??""),[yn,An]=oe(ye??""),[Kn,Nn]=oe(""),[xn,rn]=oe({}),Zt=U(bt??""),Qt=U(_e??""),Vt=U(Ft??""),Un=U(Rt??""),zn=U(G??""),Fn=U(ye??""),R=U(""),We=U({});Xe(()=>{let r=(m,A,ee,L,fe)=>{if(We.current[m])return;let It=A?.trim();!It||It===ee.current||(ee.current=It,L(It),fe?.(It))};r("country",_e,Qt,er,Te),r("zip",bt,Zt,Mn,ct),r("addressLine1",Ft,Vt,tr),r("addressLine2",Rt,Un,Rr),r("city",G,zn,pn),r("state",ye,Fn,An)},[_e,bt,Ft,Rt,G,ye,Te,ct]);let v=Pt(()=>Vy(Me),[Me]),le=v!==null,ut=Pt(()=>Us(q),[q]),He=Ny(q?.vault),Lt=!!q?.gateways?.pcivault,ke=Ec(q),Lr=!!(q?.gateways?.stripe?.enabledPaymentMethods??X)?.includes("card")||ko(q),on=He||Lr||Lt,ce=!!(w&&on&&e),[Nr,Xr]=oe(()=>Ie!=="buttons"||je?e??null:null),[Zr,Qr]=oe(0),yr=Ie!=="buttons"||je||!!e&&Nr===e,Er=q?.captureMethod,Vn=U(Y);Xe(()=>{Vn.current=Y},[Y]);let qn=U(Be);qn.current=Be;let mr=U(t);mr.current=t;let Bn=U({onCardFieldsReady:Qe,onCardFieldsFailed:Ct,emitInstrument:h});Bn.current={onCardFieldsReady:Qe,onCardFieldsFailed:Ct,emitInstrument:h};let[Nt,nr]=oe(null);Xe(()=>{if(!ce||!e||!yr){nr(null);return}let r=Vn.current?Vn.current.cardCapture({sessionId:e,captureMethod:Er,sessionToken:mr.current,cardFieldsTimeoutMs:qn.current}):new hy({sessionId:e,captureMethod:Er,billingApiUrl:nt,telemetry:o,sessionToken:mr.current,cardFieldsTimeoutMs:qn.current}),m=r.onCardFields?.(A=>{let ee=Bn.current;ee.emitInstrument?.(Iy(A)),A.type==="card_fields_ready"?Pd(()=>ee.onCardFieldsReady?.(A)):Pd(()=>ee.onCardFieldsFailed?.(A))});return nr({sessionId:e,captureMethod:Er,billingApiUrl:nt,telemetry:o,capture:r}),()=>{m?.(),r.unmount()}},[ce,e,yr,Er,nt,o]);let Ce=ce&&e&&yr&&Nt?.sessionId===e&&Nt.captureMethod===Er&&Nt.billingApiUrl===nt&&Nt.telemetry===o?Nt.capture:null,Sn=Pt(()=>{let r=me,m=v?Jt(v.postal_code,r):!1;return Rm(r,Mt,m)},[v,me,Mt]),{avsInvalid:Gn,invalidAvsFields:Ur}=Pt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!ce||!v)return{avsInvalid:!1,invalidAvsFields:r};let m=me,A=(fe,It)=>Jt(fe,m)&&!It.trim(),ee={line1:A(v.address_line_1,On),city:A(v.city,pr),state:A(v.state,yn),zip:Sn.empty||Sn.malformed};return{avsInvalid:ee.line1||ee.city||ee.state||ee.zip,invalidAvsFields:ee}},[ce,v,me,On,pr,yn,Sn]),[fr,gr]=oe(!1),[zr,eo]=oe(!1),[Ao,qr]=oe(!1),[jr,$r]=oe({line1:!1,city:!1,state:!1}),Wr=U(!1),ho=U({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Hr=U(!1),Ut=Fe(r=>{ho.current[r]=!0,Hr.current=!0},[]),rr=Fe(r=>!Wr.current&&ho.current[r],[]),jn=Fe(r=>{rr(r)&&$r(m=>m[r]?m:{...m,[r]:!0})},[rr]),[wn,$n]=oe(()=>qs(q?.vault,{billingApiUrl:nt,sessionId:e,nonce:t})),[ze,kn]=oe(je&&on?"card":"buttons"),[$t,to]=oe(null),or=ze==="expanding"||ze==="card",I=q?.gateways?.stripe&&!ke?"stripe":void 0,E=Fe(()=>{h?.({class:"card_surface",provider:I})},[I,h]),W=Fe(()=>{Tn(!0),h?.({class:"more_options"})},[h]),_=U(null),De=Fe(r=>{_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{_.current=null,r()},$a)},[]);Xe(()=>()=>{_.current&&clearTimeout(_.current)},[]);let an=U(!1),[d,p]=oe(0),u=U(null),N=Fe(()=>{E(),Xr(e??null),an.current&&(an.current=!1,p(r=>r+1)),Qr(r=>r+1),kn("expanding"),De(()=>kn("card"))},[De,E,e]),x=Fe(()=>{kn("collapsing"),De(()=>kn("buttons"))},[De]),H=Fe(r=>{to(r),kn("apm-expanding"),De(()=>kn("apm-form"))},[De]),B=Fe(()=>{kn("apm-collapsing"),De(()=>{kn("buttons"),to(null)})},[De]);Xe(()=>{Ie==="buttons"&&je&&on&&(Xr(e??null),kn("card"))},[Ie,je,on,e]);let[Z,ie]=oe(null),gt=U(null),[Gt,T]=oe(0);Xe(()=>{Gt!==0&>.current?.focus()},[Gt]);let D=U(!1),O=U(null),M=U("idle"),[Q,wt]=oe(!1),he=U(Q);he.current=Q;let[sn,Yn]=oe(()=>$e?.existingOrderId?{orderId:$e.existingOrderId,attempts:1}:null),_r=U(sn);Xe(()=>{_r.current=sn},[sn]);let zi=U(null),du=Pt(()=>{if(re||J.claimBuyerIdentity||q?.buyerIdentified!==!1||!e||!t)return;let r=`${nt}|${e}|${t}`;zi.current?.key!==r&&(zi.current={key:r,claim:Yo(new sa(nt,{telemetry:!1}),e,t,{...i?{userId:i}:{},...f?{firstName:f}:{},...F?{lastName:F}:{}})});let m=zi.current.claim;return async A=>{await m(A)}},[re,J.claimBuyerIdentity,q?.buyerIdentified,e,t,nt,i,f,F]),ar=re??J.claimBuyerIdentity??du,hr=C??Xt,xo=Pt(()=>Yy(Re),[Re]),xe=Pt(()=>{let r=xo?.buttonsLayout??Gy(Ye);return it?{...r,...it,cardButton:{...r.cardButton,...it.cardButton},cardFormContainer:{...r.cardFormContainer,...it.cardFormContainer},backButton:{...r.backButton,...it.backButton},backButtonIcon:{...r.backButtonIcon,...it.backButtonIcon},submitButton:{...r.submitButton,...it.submitButton},title:{...r.title,...it.title}}:r},[xo,Ye,it]),Fo=st??xo?.appearance,uu=Pt(()=>Ty({appearance:Fo,buttonsStyles:xe,layout:Ie}),[Fo,xe,Ie]),pu=J.inlineSessionPatchProcessing??!1,en=(K??Kt)||pu,no=nt.replace(/\/+$/,""),ft=Pt(()=>Rs({userId:i,email:a,firstName:f,lastName:F,country:_e,zip:bt},xn),[i,a,f,F,_e,bt,xn]),Bo=[ft.firstName,ft.lastName].filter(r=>!!r?.trim()).join(" "),yl=!Rn(ft.email?.trim()),qi=U(null);ce&&qi.current===null&&(qi.current=yl);let ro=ce&&(qi.current??yl),ji=Pt(()=>Im(Kn,ro),[Kn,ro]),Do=ji.empty||ji.malformed,Zn=Pt(()=>Y?Y.getRawProvider():null,[Y]),ml=Pt(()=>j?j.getRawProvider():null,[j]),ua=mt||100,Oo=St.toLowerCase(),$i=Pt(()=>Fo?Py(Fo):null,[Fo]),Lo=$i,fl=Pt(()=>{let r=$i??{},m=r.rules??{};return{...r,rules:{...m,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...m[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...m[".AccordionItemContents"]??{}}}}},[$i]),gl=Pt(()=>({...Ic(mt,Ht?.captureMethod,Dt),currency:Oo,...Lo?{appearance:Lo}:null}),[mt,Oo,Ht?.captureMethod,Dt,Lo]),Wi=Bd(Dt,"paypal","paypal"),hl=Pt(()=>({mode:"payment",amount:ua,currency:Oo,captureMethod:"manual",...Wi?{setupFutureUsage:Wi}:null,...Lo?{appearance:Lo}:null}),[ua,Oo,Wi,Lo]),Pe=Fe(r=>{Ge(r),ge?.(r)},[ge]),Pl=U(0);Xe(()=>{d!==Pl.current&&(Pl.current=d,Pe(null))},[d,Pe]);let Hi=U(""),[vl,yu]=oe(!1),Ki=Fe(()=>{yu(!0)},[]);Xe(()=>{if(!ce||!ro||!ar||!vl||Do||Hi.current)return;let r=br({email:Rn(ft.email?.trim())?ft.email?.trim():R.current.trim(),firstName:ft.firstName?.trim(),lastName:ft.lastName?.trim()});Hi.current=JSON.stringify(r),rn(m=>({...m,...r})),Promise.resolve(ar(r)).catch(m=>{Hi.current="",Pe(m instanceof Error?m.message:"Failed to attach buyer details.")})},[ce,ro,ar,vl,Do,ft.email,ft.firstName,ft.lastName,Pe]),Xe(()=>{if(!ce||!Ce)return;let r=Ue!==!1&&v==null&&!ro;Ce.setCardFieldOrder?.(Ze??null,r)},[ce,Ce,Ze,Ue,v,ro]),Xe(()=>{!ce||!Ce||Ce.setCardBrandIcons?.(V===!0)},[ce,Ce,V]);let Vi=U(null);Xe(()=>{if(!(!ce||!Ce)){if(vt===void 0){if(Vi.current!==Ce)return;Vi.current=null,Ce.setShowCardFieldLabels?.(!1);return}Vi.current=Ce,Ce.setShowCardFieldLabels?.(vt===!0)}},[ce,Ce,vt]);let Gi=be===void 0?void 0:JSON.stringify(vy(be)),Yi=U(null);Xe(()=>{if(!(!ce||!Ce)){if(Gi===void 0){if(Yi.current!==Ce)return;Yi.current=null,Ce.setCardFieldLabels?.(null);return}Yi.current=Ce,Ce.setCardFieldLabels?.(JSON.parse(Gi))}},[ce,Ce,Gi]);let Ji=Tm(Je),Xi=U(null);Xe(()=>{if(!(!ce||!Ce)){if(Ji===null){if(Xi.current!==Ce)return;Xi.current=null,Ce.setCardFieldPlaceholders?.(void 0);return}Xi.current=Ce,Ce.setCardFieldPlaceholders?.(JSON.parse(Ji))}},[ce,Ce,Ji]),Xe(()=>{(ze==="expanding"||ze==="collapsing"||ze==="apm-expanding"||ze==="apm-collapsing")&&Pe(null)},[ze,Pe]);let Tr=Fe((r,m,A)=>{y?.(mn(r,m,A))},[y]),Cl=U(ze);Cl.current=ze;let[bl]=oe(gi),Sl=Fe(()=>{let r=Cl.current;if(Ie==="buttons"&&(r==="card"||r==="expanding"))return!0;let m=M.current;return m==="validation-window"||m==="processing"||he.current},[Ie]),wl=Fe((r,m,A)=>{bl.take(e)&&fn(Y)?.log(Eo({...tt,presentationMode:A?.presentationMode??"popup"},{name:fi,stage:"recovery",reason:"other_method_active",provider:A?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:A?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[tt,Y,bl,e]),Va=Fe((r,m,A)=>{A?.telemetryReported||fn(Y)?.error(Eo({...tt,presentationMode:A?.presentationMode??"popup"},{errorCode:m?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:A?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:A?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:A?.terminalReason??(m?"popup_blocked":"provider_error")}))},[tt,Y]),No=Fe((r,m,A)=>{let ee=A?.popupBlocked??io(m);if(Sl()){Va(r,ee,A),wl(r,m,A);return}if(m instanceof Sr&&m.code==="checkout_processing_timeout"){Va(r,!1,A),ie(null),Ie==="buttons"&&(kn("buttons"),to(null)),Pe(m.message),c?.(m);return}ee&&$.markBlocked()&&Se(rt=>rt+1);let L=Gs(r),fe=A?.code===Od?Sy(L):ii(L,ee,k.inAppBrowser),It=Wo(m),Et=(It?.toLowerCase()==="error"?void 0:It)??ac(A?.code)??"external_payment_method_failed",Oe=new Sr(fe,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:Et,popupBlocked:ee,inAppBrowser:k.inAppBrowser,appFamily:k.appFamily,popupCapability:$.current(),presentationMode:A?.presentationMode??"popup"}});Va(r,ee,A),ie(null),Ie==="buttons"&&(kn("buttons"),to(null)),Pe(fe),c?.(Oe),console.error("[FloPay] External payment method failed:",{method:r,code:Et,popupBlocked:ee})},[k,Sl,Ie,c,$,wl,Va,Pe]);Xe(()=>{if(!ce||!e){$n(null);return}let r={billingApiUrl:no,sessionId:e,nonce:t},m=qs(q?.vault,r);if(m){$n(m);return}if(!yr){$n(null);return}let A=`${no}\0${e}\0${t??""}`,ee=u.current;if(ee&&ee.key===A){$n(ee.mount);return}$n(null);let L=!0;return new sa(no).getVaultCapture(e,t).then(fe=>{if(!L)return;let It=qs(fe,r);It?.verificationRequired&&!fe.html&&(u.current={key:A,mount:It}),It?$n(It):Pe("Failed to load the secure card form.")}).catch(fe=>{L&&Pe(fe instanceof Error?fe.message:"Failed to load the secure card form.")}),()=>{L=!1}},[ce,yr,Zr,e,q?.vault,no,t,Pe]);let Pr=U({onComplete:s,onError:c,updateError:Pe,emitDecline:Tr,resolvedAccount:ft,avsConfig:v,avsCheckProp:dt,sessionId:e,nonce:t,baseUrl:no,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:ke});Pr.current={onComplete:s,onError:c,updateError:Pe,emitDecline:Tr,resolvedAccount:ft,avsConfig:v,avsCheckProp:dt,sessionId:e,nonce:t,baseUrl:no,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:ke};let Zi=U(!1),kl=Fe(()=>{let r=Pr.current,m=r.resolvedAccount.email?.trim(),A=Rn(m)?m:R.current.trim();if(!Rn(A))return null;let ee=r.resolvedAccount.firstName?.trim(),L=r.resolvedAccount.lastName?.trim(),fe=Qt.current.trim()||r.resolvedAccount.country?.trim()||"",It=r.avsConfig?Jt(r.avsConfig.state,fe):!1,Et=r.avsConfig?Jt(r.avsConfig.address_line_1,fe):!1,Oe=r.avsConfig?Jt(r.avsConfig.postal_code,fe):!1,rt=r.avsConfig?Jt(r.avsConfig.city,fe):!1,ht=r.avsConfig?Jt(r.avsConfig.address_line_2,fe):!1,ln=Et&&!It&&Oe?By(fe,(Zt.current??"").trim()):null,Qn=It?Fn.current:ln;return{accountData:{userId:r.resolvedAccount.userId??"",email:A,...ee?{firstName:ee}:{},...L?{lastName:L}:{},...Oe&&Zt.current?{zip:Zt.current}:{},...rt&&zn.current?{city:zn.current}:{},...Qn?{state:Qn}:{},...Et&&Vt.current?{addressLine1:Vt.current}:{},...ht&&Un.current?{addressLine2:Un.current}:{},...fe?{country:fe}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Jt(r.avsConfig.country,fe),postal_code:Oe,address_line_1:Et,address_line_2:ht,city:rt,state:It}}:{}}},[]),Rl=U(ve);Rl.current=ve,Xe(()=>{ve||hr!==Id||Pr.current.updateError(null)},[ve,hr]),Xe(()=>{!ce||!Ce||Ce.setSubmitGate?.(Gn||ve||Do||Q)},[ce,Ce,Gn,ve,Do,Q]),Xe(()=>{if(!ce||!Ce)return;Zi.current=!1;let r=null,m=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,M.current="idle",ie(null)},400)},A=Ce.on("submitting",()=>{gr(!0),O.current&&clearTimeout(O.current),M.current="validation-window",O.current=setTimeout(()=>{O.current=null,M.current==="validation-window"&&(M.current="processing")},fm),ie("processing");let Oe=Pr.current;if(!Oe.sessionId||!Oe.nonce)return;let rt=kl();if(!rt){Oe.updateError("Enter a valid email address."),M.current="idle",ie(null);return}new sa(Oe.baseUrl).patchAccountSnapshot(Oe.sessionId,Oe.nonce,rt,{telemetryMode:"best_effort"}).catch(ht=>{if(!hm(ht))return;let ln=ht instanceof Error?ht.message:"Please check your billing address and try again.";Oe.updateError(ln),M.current="idle",ie(null),Oe.onError?.(ht instanceof Sr?ht:new Sr(ln,"api_error"))})}),ee=Ce.on("complete",Oe=>{ra(Oe.sessionId??Pr.current.sessionId),M.current="terminal",wt(!1),ie("success"),setTimeout(()=>{if(Zi.current)return;Zi.current=!0;let rt=Pr.current,ht=Us(rt)||Oe.outcome==="authorized",ln=rt.serverSideCardGateway?{}:{paymentIntentId:Oe.intentId};Pr.current.onComplete?.(ht?{status:"authorized",...ln,paymentId:Oe.paymentId??rt.paymentId,sessionId:Oe.sessionId??rt.sessionId,authorizationExpiresAt:Oe.authorizationExpiresAt??rt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...ln,checkoutMethod:"card"})},600)}),L=Ce.on("decline",Oe=>{let rt=Pr.current,ht=Oe.message??"Your payment was declined. Please try another card or contact your bank.";M.current="terminal",wt(!1),rt.updateError(ht),ie("error");let ln=Oe.failureOutcome??$y(Oe.declineReason)??"authorization_declined";rt.emitDecline("card",ht,{code:ln,declineCode:ln}),m()}),fe=Ce.on("error",Oe=>{let rt=Pr.current,ht=wy(Oe.vaultOutcome);if(ht!==null){r&&(clearTimeout(r),r=null),M.current="idle",wt(!1),rt.updateError(ht),ie(null),T(Qn=>Qn+1),rt.onError?.(new Sr(ht,"api_error",{code:ky}));return}let ln=Oe.message??"There was a problem processing your payment. Please try again.";M.current="terminal",wt(!1),rt.updateError(ln),ie("error"),rt.onError?.(new Sr(ln,"api_error",{code:Oe.failureOutcome??"capture_failed"})),m()}),It=Ce.on("challenge_dismissed",()=>{O.current&&(clearTimeout(O.current),O.current=null),M.current="processing",wt(!0),ie(null)}),Et=Ce.on("blocked",()=>{if(he.current){Pr.current.updateError(gm);return}if(!Rl.current){gr(!0);return}Ki(),Pr.current.updateError(Id)});return()=>{r&&(clearTimeout(r),r=null),O.current&&(clearTimeout(O.current),O.current=null),M.current="idle",wt(!1),ie(null),A(),ee(),L(),fe(),It(),Et()}},[ce,Ce,Ki,kl]);let Mr=!!$e?.clientId,pa=Array.isArray(X),Ga=pa&&X.length>0,Il=pa&&X.includes("paypal"),Ya=U(null);Ya.current===null&&(Ya.current=Oy());let Uo=Ya.current?"redirect":ic(k,Ke,$.current()),{expressMethods:Ja,paymentElementMethods:Qi}=Pt(()=>Wy(X,{excludePaypal:Mr}),[X,Mr]),El=Mr||!!j||Il&&Uo==="redirect",mu=Pt(()=>El?Ja.filter(r=>r!=="paypal"):Ja,[Ja,El]),fu=Pt(()=>{let r=[];return at&&r.push("apple_pay"),pt&&r.push("google_pay"),r},[at,pt]),zo=pa?mu:fu,gu=w&&zo.length>0,_l=le?me:_e,Xa=Pt(()=>xy(Qi,_l,Ne),[Qi,_l,Ne]),es=Pt(()=>({mode:"payment",amount:ua,currency:Oo,paymentMethodCreation:"manual",appearance:fl}),[ua,Oo,fl]),[ts,Tl]=oe("loading"),[ns,Ml]=oe("loading"),[rs,Al]=oe("loading"),[hu,os]=oe(!1),[xl,as]=oe("loading"),[is,Pu]=oe();Xe(()=>{Pu(Sa())},[]);let Za=is?.inAppBrowser,Qa=is?li(is,$e?.approvalPresentation,Dn??(et?"subscription":"order")):"popup",Fl=ue&&(Mr||(pa?Il:Za===!1)),vu=k.inAppBrowser&&$.current()==="blocked",Bl=w&&gu&&!vu,Po=(!dn||!!J.waitForDataAttachment)&&Fl&&Mr,ss=xl==="retrying"||xl==="exhausted",ya=null;w&&(j?ya=ml:Uo==="redirect"&&(ya=Zn));let Dl=Pt(()=>({...tt,presentationMode:Uo}),[tt,Uo]),vo=!dn&&Fl&&!!ya&&(!Mr||ss),oo=!dn&&Bl&&!!Zn,Co=!dn&&w&&Ga&&Xa.length>0&&!!Zn,Cu=Po&&!ss?hu:vo&&wa(ts),bu=oo&&wa(ns),Su=Co&&rs!=="load_error",Ol=[Po||vo,oo,Co,ce].filter(Boolean).length,wu={card:ce,paypal:Po&&!ss||vo&&wa(ts),wallets:oo&&wa(ns),apms:Co&&rs!=="load_error"},Ll=r=>wu[r],Nl=r=>r==="loading"||r==="ready",Ul=Po||vo&&Nl(ts)||oo&&Nl(ns)||Co&&rs!=="load_error",ei=U(!1);Xe(()=>{if(!ei.current){if(!w&&!ue){ei.current=!0;let r=new Sr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(r),Pe(r.message)}else if(!w&&ue&&!Mr){ei.current=!0;let r=new Sr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(r),Pe(r.message)}else if(Za!==void 0&&!dn&&!on&&!Ul){ei.current=!0;let r=new Sr("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"});c?.(r),Pe(r.message)}}},[w,ue,Mr,Za,dn,on,Ul,c,Pe]);let zl=U(!1);Xe(()=>{if(zl.current||!Ga)return;let r=[];at!==!0&&r.push("showApplePay"),pt!==!0&&r.push("showGooglePay"),r.length!==0&&(zl.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.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.`))},[Ga,at,pt]);let ql=Fe((r,m,A)=>J.applyInlineSessionPatch?J.applyInlineSessionPatch(r).then(ee=>({error:null,sessionId:ee.sessionId||e,nonce:ee.session?.clientSecret||t})).catch(ee=>{let L=Cd(m,ee);return A?.abandoned?.()||(Pe(L.message),c?.(L)),{error:L,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[J.applyInlineSessionPatch,t,c,e,Pe]),vr=Fe(async(r,m)=>{if(r!=="card"&&dn&&await J.waitForDataAttachment?.(),!lt)return{proceed:!0};try{let A=await lt({method:r,sessionId:e||void 0,createSession:J.inlineSessionDraft});if(A===!1)return{proceed:!1};if(A&&typeof A=="object"){A.account&&rn(L=>({...L??{},...A.account}));let ee=await ql(A,r,m);return ee.error?{proceed:!1,accountPatch:A.account}:{proceed:!0,accountPatch:A.account,sessionId:ee.sessionId,nonce:ee.nonce}}return{proceed:!0}}catch(A){if(!m?.abandoned?.()){let ee=Cd(r,A);Pe(ee.message),c?.(ee)}return{proceed:!1}}},[ql,J.inlineSessionDraft,J.waitForDataAttachment,dn,lt,c,e,Pe]),jl=Fe(async(r,m)=>{if(D.current)return;D.current=!0,Ot(!0),ie("processing"),Pe(null);let A=m?.sessionId??e,ee=m?.nonce??t,L=Rs(ft,m?.accountPatch),fe=m?.completionPaymentMethodId??Ia(r),It=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,Et=bm(r),Oe=m?.presentationMode?Ei(fn(Y),{...tt,presentationMode:m.presentationMode}):void 0,rt=()=>{h?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Et}),Oe?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...wr,requestCategory:"process_payment"})};try{let ht=new sa(no),Qn=m?.settledProcessResponse??await ht.processPayment(L.userId??"",{sessionId:A,nonce:ee,paymentMethodCategory:m?.paymentMethodCategory??wm(r),tokenizedData:It,accountData:{...m?.accountPatch,userId:L.userId??"",email:L.email??"",firstName:L.firstName||void 0,lastName:L.lastName||void 0,...by({avsConfig:v,country:Qt.current,zip:Zt.current,city:zn.current,state:Fn.current,addressLine1:Vt.current,addressLine2:Un.current})},...Cy({chv:te,avsCheck:dt,checkoutType:Ve,checkoutLayout:yt,avsConfig:v,country:Qt.current})}),ai=async Pn=>{let bo=Us(q)||Pn?.status==="authorized";ra(A),Oe?.terminal({outcome:"payment_succeeded",...wr}),ie("success"),Yn(null),await new Promise(Ca=>setTimeout(Ca,600));let Ar;typeof Pn?.paymentId=="string"?Ar=Pn.paymentId:q?.paymentId&&(Ar=q.paymentId);let So;typeof Pn?.authorizationExpiresAt=="string"?So=Pn.authorizationExpiresAt:q?.authorizationExpiresAt&&(So=q.authorizationExpiresAt),s?.(bo?{status:"authorized",...Ar===void 0?{}:{paymentId:Ar},sessionId:typeof Pn?.sessionId=="string"?Pn.sessionId:A,...So===void 0?{}:{authorizationExpiresAt:So},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:r.isPaypal?"paypal":"card"})};if(Qn.ok){await ai(Qn.status===204?null:await Qn.json().catch(()=>null));return}let cn=await Qn.json().catch(()=>null);if(cn?.type==="paypal_redirect_required"){let Pn=cn.threeDSecureToken,bo=cn.paymentMethodId||r.id||"";if(!Y||!Pn){ie("error"),Pe("PayPal authorization required but no token provided.");return}try{let Ar=j?.getRawProvider();if(!Ar){Pe("PayPal is not available.");return}let So={return_url:window.location.href};bo&&(So.payment_method=bo);let{error:Ca}=await Ar.confirmPayment({clientSecret:Pn,confirmParams:So,redirect:"if_required"});if(Ca){ie("error");let nc=Ca.message??"PayPal payment failed.";Pe(nc),Tr("paypal",nc,{code:Ca.code})}}catch(Ar){ie("error"),Pe(Ar instanceof Error?Ar.message:"PayPal authorization failed.")}return}if(cn?.type==="paypal_direct_required"){let Pn=cn.orderId;if(!Pn){ie("error"),Pe("PayPal retry required but no order id provided.");return}let bo=_r.current?.attempts??0;if(bo>=2){ie("error"),Pe("PayPal payment could not be completed after multiple attempts."),Tr("paypal","paypal_direct_required retry limit exceeded");return}os(!1),as("loading"),Yn({orderId:Pn,attempts:bo+1}),ie(null);return}if(Qn.headers.get(lm)===cm){let Pn=await dm(ht,A,ee);if(Pn!==void 0){await ai(Pn);return}}Ey(Qn.status,cn)?Oe?.terminal({outcome:"payment_declined",...wr,terminalReason:"provider_declined"}):rt(),ie("error");let tc=cn?.message??"Payment failed. Please try again.";Pe(tc),Tr(r.isPaypal?"paypal":"card",tc,{code:cn?.code??cn?.gatewayErrorCode,declineCode:cn?.declineCode??cn?.gatewayDeclineReason}),await new Promise(Pn=>setTimeout(Pn,400))}catch(ht){zd(ht)||rt(),ie("error"),Pe(ht instanceof Error?ht.message:"An unexpected error occurred"),await new Promise(ln=>setTimeout(ln,400))}finally{Ot(!1),ie(null),D.current=!1}},[no,e,t,ft,v,dt,Ve,yt,te,Y,j,q,s,Pe,Tr,h,tt]),Jn=Fe((r,m)=>{P&&!m?.settledProcessResponse?P(r):jl(r,m)},[P,jl]),ma=`${Nd}:${e}`;Xe(()=>{if(typeof window>"u")return;let r=localStorage.getItem(ma);if(!r)return;let m;try{m=JSON.parse(r)}catch{nn(ma);return}if(!m||typeof m.createdAt!="number"||Date.now()-m.createdAt<0||Date.now()-m.createdAt>Ud||typeof m.paymentMethodId!="string"||typeof m.providerIntentId!="string"||typeof m.paymentMethodType!="string"||m.sessionId!==e||!t||m.nonce!==t||!zo.includes(m.paymentMethodType)){nn(ma);return}nn(ma),Jn({id:m.paymentMethodId,type:"card",threeDSecureActionResultTokenId:m.providerIntentId,gateway:"stripe",paymentMethodType:m.paymentMethodType},{...m.accountPatch?{accountPatch:m.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Jn,t,e,ma,zo]);let $l=U(!1);Xe(()=>{if(typeof window>"u"||$l.current)return;let[r,m,A]=Fd();if(!r||!m||Ya.current||!Y)return;let ee=Y.getRawProvider();if(!ee)return;let L=rt=>{let ht=localStorage.getItem(rt);if(!ht)return null;try{return JSON.parse(ht)}catch{return nn(rt),null}},fe=L(Br)??L(wd),It;if(fe?.clientSecret){if(fe.clientSecret!==m)return;It={...fe.accountPatch?{accountPatch:fe.accountPatch}:{},...fe.sessionId?{sessionId:fe.sessionId}:{},...fe.nonce?{nonce:fe.nonce}:{}}}else if(fe?.sessionId&&fe.sessionId!==e)return;$l.current=!0,nn(Br),nn(wd),window.history.replaceState({},"",Dd());let Et=fe?.paymentMethodType??fe?.tokenType??"card",Oe="card";(async()=>{if(A==="failed"){let cn="Payment was declined. Please try again.";Pe(cn),Tr(Oe,cn);return}let{paymentIntent:rt,error:ht}=await ee.retrievePaymentIntent(m);if(ht){let cn=ht.message??"Failed to retrieve payment status.";Pe(cn),Tr(Oe,cn,{code:ht.code});return}let ln=rt?.status,Qn=Ra(ln);if(!rt||!Qn){let cn=ln==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Pe(cn),Tr(Oe,cn,{code:ln??"missing_payment_intent"});return}let ai=typeof rt.payment_method=="string"?rt.payment_method:rt.payment_method?.id;Jn({id:ai??fe?.paymentMethodId??fe?.tokenId??rt.id,type:"card",threeDSecureActionResultTokenId:rt.id,gateway:fe?.gateway??"stripe",paymentMethodType:Et},It)})()},[e,Jn,Y,Pe,Tr]);let ls=Fe(r=>{r.preventDefault()},[]);if(!(ce||Y!==null))return l("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let fa=Ie==="buttons",Wn=Fo?.variables,ku=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),cs=Wn?.colorBackground,Ru=cs&&!ku.has(cs)?cs:void 0,ga=xe.cardInputBorder??(fa?"#e5e7eb":"#A4A4FF"),Wl=Wn?.colorDanger??"#dc2626",Yt=r=>Ur[r]&&(jr[r]||fr),ti=Do&&(Ao||fr),ir=r=>r?Wl:ga,ni=(Sn.malformed||Sn.empty)&&(zr||fr),Iu=ir(ni),ds=xe.cardFormContainer?.backgroundColor??Ru??(fa?"white":"#EDEDFF"),qo=xe.cardInputBackground??Wn?.colorBackground??"white",us=Ho(ne),Hl=Ho(pe),jo=xe.nameInput,Kl=xe.cardInputFontSize??Em(jo?.fontSize)??Wn?.fontSizeBase??"16px",Vl=typeof jo?.fontFamily=="string"?jo.fontFamily:Wn?.fontFamily??"Poppins, sans-serif",Gl=Qy(jo?.fontWeight)??400,Eu=xe.cardInputColor??(typeof jo?.color=="string"?jo.color:void 0)??Wn?.colorText??"#262833",_u=xe.cardInputPlaceholderColor??"#9ca3af",tn=Wn?.borderRadius??"8px",Kr=Wn?.borderRadius??xe.cardButton?.borderRadius??tn,ao=Wn?.colorPrimary??"#4A49FF",Tu=Wn?.colorPrimaryHover??My(ao,.12),ps=Wn?.colorText??"#262833",ys={fontSize:Kl,fontFamily:Vl,fontWeight:Gl,color:Eu,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ha={marginTop:"0.375rem",...ys,fontSize:"0.75rem",lineHeight:1.4,color:Wl},Mu={"--flopay-input-placeholder-color":_u,"--flopay-input-font-size":Kl,"--flopay-input-font-family":Vl,"--flopay-input-font-weight":String(Gl)},Pa=xe.cardFormContainer??{},ms=Pa.padding??(fa?"0":"1rem"),fs=Pa.borderRadius??tn,Au=Ce&&wn?l(hs,{capture:Ce,html:wn.html,messageToken:wn.messageToken,expectedOrigin:wn.expectedOrigin,verificationRequired:wn.verificationRequired,theme:uu,submitLabel:z,onReady:()=>{if(!ro&&!v||typeof document>"u"||Ue===!1)return;let r=()=>{let A=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(A){Wr.current=!0;try{A.focus()}finally{Wr.current=!1}}};Hr.current||r()},onError:r=>{r&&wn.verificationRequired&&M.current==="idle"&&(an.current=!0),Pe(r)},onValidation:r=>{let m=M.current;(m==="idle"||m==="validation-window")&&(Pe(r),r&&M.current==="validation-window"&&(O.current&&(clearTimeout(O.current),O.current=null),M.current="idle",ie(null)))}},d):l("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),gs=Le("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&E()},style:{backgroundColor:ds,borderRadius:fs,...Pa,padding:ms,...Mu,display:"flex",flexDirection:"column"},children:[l("style",{children:`
|
|
3
|
+
${he.join(`
|
|
4
|
+
`)}`]}):null;return V&&!h?be?Mo("div",{children:Tn}):null:Ms("div",{children:[Tn,lt&&Mo(ta,{identity:lt.identity,methodLabel:lt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ct,onCancel:()=>Ct(null)}),Ms("div",{"aria-hidden":Ze||lt?!0:void 0,style:Ze||lt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ci},children:[!Ve&&!Ze&&Mo("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"}}),Mo("div",{ref:le,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ci,display:"flex",opacity:Ve?1:0},"aria-busy":_e||pe},De)]},De),Ee&&Mo("button",{ref:ht,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Qt,style:Fp,children:"Try PayPal again"})]})}function bi(e){return Mo(Hc,{...e})}function Vc(e){return Mo(Hc,{...e})}import{jsx as Gc,jsxs as Lp}from"react/jsx-runtime";function oa({children:e,margin:t,icon:n=!0,styleOverride:o}){return Lp("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,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...o??{}},children:[n&&Gc("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Gc("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]})}import{clearCachedInlineCheckout as Si,clearCachedInlineSession as As,hashCreateParams as Yc,legacyCachedSessionMatchesDraft as Jc,persistCachedInlineIdempotencyKey as wi,persistCachedInlineSession as ki,readCachedInlineIdempotencyKey as Xc,readCachedInlineSession as Zc,serializeCreateParams as Ba}from"@flopay/shared";var Qc=new Set;function Np(){return globalThis.process?.env?.NODE_ENV==="production"}function ed(e,t){Qc.has(e)||Np()||(Qc.add(e),console.warn(t))}function td(){ed("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 nd(){ed("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`.")}import{isCardFieldsInstrumentSource as Up,resolveBillingApiUrl as zp}from"@flopay/shared";import{useCallback as qp,useEffect as mo,useMemo as jp,useRef as rd,useState as od}from"react";import{jsx as $p}from"react/jsx-runtime";function Ri({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,l]=od(e instanceof Promise?null:e),[u,m]=od(t instanceof Promise||!t?null:t),R=rd(null),C=rd(null),g=na(o),A=qp(D=>{Up(D)||g(D)},[g]);mo(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),mo(()=>{i&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,i]),mo(()=>{if(i)return hn(i)?.subscribe?.(A)},[A,i]),mo(()=>{if(!(!u||u===i))return hn(u)?.subscribe?.(A)},[A,i,u]),mo(()=>{if(!i)return;let D=hn(i);return R.current=D?.beginCheckout()??D?.now()??0,D?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{D?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),mo(()=>{let D=!1;return e instanceof Promise?e.then(K=>{D||l(K)},()=>{D||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{D=!0}},[g,e]),mo(()=>{let D=!1;if(!t){m(null);return}return t instanceof Promise?t.then(K=>{D||m(K)},()=>{D||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{D=!0}},[g,t]),mo(()=>{if(!i||C.current===i)return;C.current=i;let D=hn(i);D?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),D?.performance({stage:"checkout_render",durationMs:D.elapsed(R.current??0),durationMode:"machine"})},[g,i]);let X=zp(n?.billingApiUrl),te=jp(()=>({flopay:i,paypalFlopay:u,billingApiUrl:X,emitInstrument:g}),[i,u,X,g]);return $p(pr.Provider,{value:te,children:a})}import{markSessionRecentlyCompleted as aa,wasSessionRecentlyCompleted as xs}from"@flopay/shared";async function Ii(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{beginSavedCardChallengeTelemetry as Wp,completeSavedCardNextAction as Kp,loadFloPay as ad,PaymentAPI as Oa,runSavedCardChallenge as Hp}from"@flopay/js";import{classifyPaymentRejection as Vp,FloPayError as Tt,isAuthorizationOnlySession as Gp,isMerchantAuthRequired as Bs,isMountableVaultBlock as Yp,isSetupIntentClientSecret as Jp,MERCHANT_AUTH_REQUIRED_CODE as Xp,normalizeCheckoutFailureOutcome as id}from"@flopay/shared";var Na="card";async function Zp(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:o??null}}async function Qp(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:u}=await e.confirmCardSetup(t,n);return{error:u,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function ia(e){return new Tt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function ey(){return new Tt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function La(e,t){return Object.assign(e,{checkoutMethod:t})}function Qr(e,t){let n=e instanceof Tt?e:new Tt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Da(e,t){try{return await e()}catch(n){throw Qr(n,t)}}function ld(e){return!e?.type||!e.threeDSecureToken||Bs(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function cd(e){return Hp(e)}function Ua(e,t,n,o=!0){let a={release:()=>{}};if(!o)return a;try{let i=new Oa(e),l=Wp(i,t,n);return l?{telemetry:l,release:()=>{setTimeout(()=>{try{i.destroy()}catch{}},0)}}:a}catch{return a}}async function sa(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,l=new Oa(n,{telemetry:!1}),u=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,m;try{m=await Kp({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:C=>zr({type:C.declineReason??"authorization_declined",gatewayErrorCode:C.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(C){if(a.aborted||C instanceof Error&&C.name==="AbortError")throw C instanceof Tt&&C.code==="three_ds_aborted"?C:ia(C);if(!(C instanceof Tt)||C.code!=="three_ds_timeout"&&C.code!=="checkout_processing_timeout")throw C;try{m=await l.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:u,timeoutMs:5e3,signal:a})}catch(A){if(a.aborted)throw ia(A);if(!(A instanceof Tt)||A.code!=="checkout_processing_timeout")throw A}let g=m&&co(m,t.session);if(!Xr(g)&&g?.status!=="expired"){if(t.telemetry){let A=new Oa(n);try{A.reportThreeDsAbandoned(o)}finally{A.destroy()}}throw ey()}}let R=m&&co(m,t.session);if(!Xr(R))throw Zo(R);return{...Jr(R,o),checkoutMethod:"card"}}function dd(e){return new Tt("This payment needs your card details. Please complete your payment below.","authentication_error",{code:Xp,...e===void 0?{}:{statusCode:e}})}function zr(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if(Bs(e))return La(dd(),o);let a=e?.message??t,i=Qo(a)??a,l=La(new Tt(i,"api_error",{code:e?.code??id(e?.outcome)??id(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),o);return e?.orderId&&(l.orderId=e.orderId),l}function Fs(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ei(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ud(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ei(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let u of i)if(typeof u=="string"&&u.length>0&&(!t?.requirePaymentIntentClientSecret||Ei(u)))return u;let l=a.gateways;if(l&&typeof l=="object"){let u=l.stripe;if(u&&typeof u=="object"){let m=u,R=[m.stripeClientSecret,m.clientSecret];for(let C of R)if(typeof C=="string"&&C.length>0&&(!t?.requirePaymentIntentClientSecret||Ei(C)))return C}}}}async function ty({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=ud(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let u=(await new Oa(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ei(u))return{type:"3ds_required",threeDSecureToken:u}}catch{}return null}async function la({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:l}){let u=e.replace(/\/+$/,""),m=t??n.id,R=o??n.clientSecret,C=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",A=n.customer?.firstName??n.accountData?.firstName??"",X=n.customer?.lastName??n.accountData?.lastName??"",te=n.customer?.country??n.accountData?.country??void 0,D=n.customer?.zip??n.accountData?.zip??void 0,w=await new Oa(u,l===!1?{telemetry:!1}:void 0).processPayment(C,{sessionId:m,nonce:R,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:C,email:g,firstName:A,lastName:X,country:te,zip:D},returnUrl:i??Fs(n)});if(w.ok){let se=typeof w.json=="function"?await w.json().catch(()=>null):null;if(Gp(n)||se?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof se?.paymentId=="string"?se.paymentId:n.paymentId,sessionId:typeof se?.sessionId=="string"?se.sessionId:m,authorizationExpiresAt:typeof se?.authorizationExpiresAt=="string"?se.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:_a(a),checkoutMethod:sd(a,n)}};let I=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...I?{paymentIntentId:I}:{},paymentMethodId:_a(a),checkoutMethod:sd(a,n)}}}let pe;try{pe=await w.json()}catch(se){throw new Tt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:w.status,cause:se})}if(Bs(pe))throw La(dd(w.status),"card");if(pe?.type==="3ds_required"&&typeof pe.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:pe.nextActionRedirectUrl};if(pe?.type==="paypal_redirect_required"||pe?.type==="3ds_required"){let se=ud(pe);if(!se)throw new Tt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:w.status});return{type:pe.type,threeDSecureToken:se,paymentMethodId:pe.paymentMethodId}}if(pe?.gatewayErrorCode==="authentication_required"){let se=await ty({billingApiUrl:u,sessionId:m,nonce:R,responseJson:pe});if(se)return se;throw La(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw ny(pe,w.status)}function ny(e,t){let n=new Tt(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(n,{telemetryOutcome:Vp(t,e)})}async function _i(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:l,returnUrl:u,telemetry:m,signal:R}){let C=t?.getRawProvider();if(!C)throw Qr(new Tt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw La(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Jp(e.threeDSecureToken),A=null,X=e.paymentMethodId,te=await Da(()=>Zp(C,e.threeDSecureToken,g),"card");if(te){if(te.error)throw Qr(new Tt(te.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:te.error.code}),"card");let K=te.intent;!X&&K?.payment_method&&(typeof K.payment_method=="string"?X=K.payment_method:"id"in K.payment_method&&(X=K.payment_method.id??void 0))}let D=X?await Da(()=>Qp(C,e.threeDSecureToken,{payment_method:X,return_url:u??Fs(l)??window.location.href},g),"card"):null;if(D){if(D.error)throw Qr(new Tt(D.error.message??"3DS authentication failed.","api_error",{code:D.error.code}),"card");A=D.intent}else{let K=await Da(()=>C.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(K.error)throw Qr(new Tt(K.error.message??"3DS authentication failed.","api_error",{code:K.error.code}),"card");A=(g?K.setupIntent:K.paymentIntent)??null}if(A&&(A.status==="requires_capture"||A.status==="succeeded"||A.status==="processing")){let K=await la({billingApiUrl:a,sessionId:i,session:l,telemetry:m,tokenizedData:{id:A.id,type:"card",threeDSecureActionResultTokenId:A.id},returnUrl:u});return K.type==="success"?{...K.result,paymentIntentId:K.result.paymentIntentId??A.id,paymentMethodId:K.result.paymentMethodId??X}:K.type==="next_action_required"?sa(K,{billingApiUrl:a,sessionId:i??l.id,session:l,signal:R}):_i(K,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:l,returnUrl:u,telemetry:m,signal:R})}throw Qr(new Tt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Qr(new Tt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:X}=await Da(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(X)throw Qr(new Tt(X.message??"PayPal authorization failed.","api_error",{code:X.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:A}=await Da(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:u??Fs(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(A)throw Qr(new Tt(A.message??"PayPal authorization failed.","api_error",{code:A.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Tt("Unsupported payment redirect state.","api_error")}function za(e){if(e instanceof Tt){let o=Qo(e.message);return o&&o!==e.message?Object.assign(new Tt(o,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.",n=Qo(t)??t;return new Tt(n,"api_error")}function Ds(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=Yp(e.data.session?.vault)||_o(e.data.session);if(!t&&!n&&!o)throw new Tt("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 sd(e,t){return e?e.isPaypal?"paypal":"card":t&&_o(t)?"card":void 0}async function Os({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:o,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[l,u]=await Promise.all([ad(e,{billingApiUrl:n,locale:o,telemetry:a}),i?ad(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(R=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",R),null)):Promise.resolve(null)]);if(!l)throw new Tt("The payment provider did not initialize.","authentication_error");let m=null;return i?m=u:t&&(m=l),{flopay:l,paypalFlopay:m}}import{PaymentAPI as ca,PciVaultCardCapture as Py,toStripeAppearance as vy}from"@flopay/js";import{buildCardFieldLabelsPayload as Cy,buildCheckoutProcessMetadata as by,buildProcessPaymentAvsAccount as Sy,buildWalletSheetWindowMessage as wy,buyerEmailRequiredPrompt as ky,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as Ry,COUNTRY_OPTIONS as Iy,cardFieldsInstrumentSource as Ey,classifyPaymentRejection as _y,clearStripePayPalReturn as Ty,computeVaultCardThemeColors as My,darkenHex as Ay,denyPaymentPermissionToNewFrames as xy,FloPayError as Rr,filterStripeMethodsByCountryGate as Fy,getPostalCodeExample as By,getPostalCodeLabel as Vs,getStateFromPostalCode as Dy,getStateLabel as Us,getStateOptions as Oy,getStripeMethodDisplayName as Wa,hasMatchingStripePayPalReturn as Ly,invokeMerchantCallback as vd,isAuthorizationOnlySession as zs,isAVSFieldVisible as nn,isCardFormFirst as Ny,isMountableVaultBlock as Uy,isPostalCodeSupported as zy,isSettledSessionIntent as Fi,isSetupIntentClientSecret as qs,isValidEmail as xn,isValidPostalCode as qy,isWalletSheetRefusedForWindowSize as jy,keyPaymentMethodOrder as $y,needsStripeMethodExplicitConfirm as Cd,normalizeBeforeButtonClickError as bd,normalizeCheckoutFailureOutcome as Wy,partitionStripeMethods as Ky,placePaymentMethodGroups as Sd,randomUuidV4 as Hy,readMatchingStripePayPalContinuation as Vy,readStripeRedirectParams as Bd,resolveAVSConfig as Gy,resolveButtonsLayoutTheme as Yy,resolveSetupFutureUsage as Dd,resolveTheme as Jy,resolveVaultMountOptions as js,STRIPE_PAYPAL_RESUME_KEY as Xy,derivePrimaryTileStyle as Zy,shouldPreferWalletPopup as wd,stripeExpressMethodToOptionKey as Qy,stripeRedirectReturnUrl as Od,toCssWeight as em,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as Ld}from"@flopay/shared";import{ExpressCheckoutElement as Nd,PaymentElement as tm,useElements as Xs,useStripe as Zs}from"@stripe/react-stripe-js";import ja,{useCallback as Be,useContext as da,useEffect as Je,useLayoutEffect as nm,useMemo as gt,useRef as B,useState as ee}from"react";function Ao(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ti(e,t){if(e)return{error:n=>e.error(Ao(t,n)),log:n=>e.log(Ao(t,n)),performance:n=>e.performance(Ao(t,n)),terminal:n=>e.terminal(Ao(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}import{useEffect as ry,useId as oy,useRef as pd}from"react";import{Fragment as sy,jsx as yd,jsxs as ly}from"react/jsx-runtime";var md="More payment options",ay={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},iy={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Ls({label:e,open:t,showLink:n,onOpen:o,color:a,fontFamily:i,children:l}){let u=oy(),m=pd(null),R=pd(!1);return ry(()=>{t&&R.current&&m.current?.focus()},[t]),ly(sy,{children:[!t&&n&&yd("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":u,onClick:()=>{R.current=!0,o()},style:{alignSelf:"center",margin:0,padding:"0.25rem 0",border:0,background:"none",cursor:"pointer",color:a,fontFamily:i,fontSize:"0.9rem",fontWeight:500,textDecoration:"underline",textUnderlineOffset:"0.2em"},children:e}),yd("div",{id:u,ref:m,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?iy:ay,children:l})]})}import{jsx as fd}from"react/jsx-runtime";var cy=["first","second","third","fourth"];function Ns({rows:e,borderRadius:t}){return fd("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:cy.slice(0,Math.max(1,e)).map(n=>fd("div",{style:{height:Eo,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},n))})}import{PaymentAPI as dy}from"@flopay/js";import{DEFAULT_PAYMENT_METHOD_ORDER as uy,resolveDefaultPaymentMethodLayout as py}from"@flopay/shared";import{useEffect as yy,useState as my}from"react";var fy=1500,gd=new Set;function hd(e){for(let t of e)gd.has(t)||(gd.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function gy(e){if(e!=null)try{return JSON.stringify(e)}catch{return hd(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var hy={order:[...uy],moreOptions:[]};function Pd({rules:e,sessionId:t,nonce:n,billingApiUrl:o,waitForSession:a}){let i=gy(e),[l,u]=my(null);return yy(()=>{if(i===void 0||a)return;let m=JSON.parse(i),R=!1,C=te=>{R||(R=!0,u(te))},g=()=>C(py(m));if(!t||!n||!o){g();return}let A=new AbortController,X=setTimeout(()=>{g(),A.abort()},fy);return new dy(o,{telemetry:!1}).resolvePaymentMethodLayout(t,n,m,{signal:A.signal}).then(te=>{if(!te){g();return}R||hd(te.warnings),C({order:te.order,moreOptions:te.moreOptions})}).catch(g).finally(()=>clearTimeout(X)),()=>{R=!0,clearTimeout(X),A.abort()}},[i,t,n,o,a]),i===void 0?hy:l}import{darkenHex as Wd}from"@flopay/shared";import{Fragment as Kn,jsx as d,jsxs as Ne}from"react/jsx-runtime";var qr="flopay_stripe_resume",kd="flopay_wallet_resume",Ud="fw1",rm="fw2",zd=300*1e3,om=900,am="express_checkout_click_timeout",im=25e3,sm=25e3,lm=1e4,Ir={provider:"paypal",paymentMethodCategory:"paypal"},cm="x-flopay-process-result-source",dm="status";async function um(e,t,n){try{let o=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(o?.status==="complete")return null;if(o?.status==="authorized")return{status:"authorized",paymentId:o.paymentId,sessionId:o.id||t,authorizationExpiresAt:o.authorizationExpiresAt}}catch{}}var Mi={},$a=class{constructor(t){this.reason=t}};function pm(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function sn(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 Qs(e){return`${rm}:${e}`}function Ai(e){return sn(Qs(e))}function xi(e,t){if(typeof window>"u")return null;let n=Qs(e);try{let o=localStorage.getItem(n);if(!o)return null;let a=JSON.parse(o);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>zd||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Ai(e),null):a}catch{return Ai(e),null}}function ym(e){return sn(Qs(e.sessionId),e)}function Rd(e,t,n){let o=xi(e,t);return!o||o.clientSecret!==n?!1:Ai(e)}function $s(e,t,n){if(typeof window>"u")return;xi(e,t)?.clientSecret===n&&Ai(e)}function mm(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ws(e,t,n){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 o=n?e.status==="succeeded":Ea(e.status),a=mm(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Id(e,t,n){let o=null;try{return await Promise.race([Ic(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},lm),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function fm(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function qd(e){return e instanceof Rr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Bi(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new ca(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw qd(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var Ks=Xy,qa=new Map,gm=250,Ed="Just a moment \u2014 we are finalizing your order. Please press pay again.",hm="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function el(e,t,n,o){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...o?{terminalReason:o}:{}})}async function Di({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new ca(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function Pm(e){return e instanceof Rr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function jd({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=Ta(n),l=i.firstName?i:Ta(o?.name);return kr({email:xn(a)?a:o?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function vm({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let l=jd({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return xn(l.email)?l:i(a,l)}var Ka=180,_d=`flopay-card-enter ${Ka}ms cubic-bezier(0, 0, 0.2, 1) both`,Td=`flopay-card-exit ${Ka}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Cm=`flopay-buttons-enter ${Ka}ms cubic-bezier(0, 0, 0.2, 1) both`,bm=`flopay-buttons-exit ${Ka}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Sm(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function tl(e){return Zy(e)}var wm={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function km(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var Gs={width:"100%",minHeight: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 Md(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ys(e){return e==="paypal"?"PayPal":Wa(e)}function Rm(e){let t=By(e);return`Enter a valid ${Vs(e)}${t?` (e.g. ${t})`:""}`}function Im(e,t,n){let o=zy(e),a=t.trim(),i=n&&o,l=i&&!a,u=i&&!!a&&!qy(e,a);return{visible:n,supported:o,required:i,empty:l,malformed:u}}function Em(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!xn(n);return{required:t,empty:o,malformed:a,value:n}}function _m(e){return typeof e=="number"?`${e}px`:e}var Tm=["number","expiry","cvv","name"];function Mm(e){if(e===null||typeof e!="object")return null;let t={};for(let n of Tm){let o=e[n];typeof o=="string"&&(t[n]=o)}return JSON.stringify(t)}function nl(e){return d(Fm,{...e})}function Ad({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:l=!1,onButtonClick:u,onDecline:m,onTechnicalFailure:R,runBeforeButtonClick:C,billingName:g,onBuyerIdentityReady:A,onLoadStateChange:X,placeholderBorderRadius:te,popupCapabilityOwner:D,externalTelemetryContext:K,presentationMode:w}){let pe=po(),{emitInstrument:se}=da(pr),I=Zs(),We=Xs(),G=gt(()=>Ti(hn(pe),K),[K,pe]),[Ue,rt]=ee("loading");Je(()=>{X?.(Ue)},[Ue,X]);let[dt,Re]=ee(!1),Nt=B(!1),Dt=!xn(n?.trim())||!g?.trim(),{request:be,collect:He,finish:ot}=ea(),at=B(!1),Ie=B(null),Z=B(null),[le,Kt]=ee(0),[je,it]=ee(!1),Q=B(!1),Te=B(new Map),{startAttempt:Xe,finishAttempt:H,invalidateAttempt:ht,isAttemptInvalidated:Ce,isAttemptCurrent:Ve,generationRef:ze}=xa((ce,_e,st)=>{R?.(ce,_e,{...st,popupBlocked:st?.popupBlocked??so(_e),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:w,terminalReason:"overlay_timeout"}),it(!0),Kt(lt=>lt+1)},{onHandoffObserved:()=>{D.markAvailable(),G?.log({name:"provider.popup.opened",stage:"overlay_open",...Ir,attempt:ze.current})}});Je(()=>{je&&Z.current?.focus()},[je,le]);let Ze=Be(()=>{Kt(ce=>ce+1)},[]),Pt=Be((ce,_e,st)=>{ht(st),R?.("paypal",ce,{code:_e,popupBlocked:so(ce),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:w}),it(!0),Ze()},[ht,R,w,Ze]),De=Be(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);Je(()=>{Q.current&&(Q.current=!1,De())},[De,le]);let wt=Be(()=>{it(!1),i?.(null),De()},[De,i]);Je(()=>{if(!I||at.current)return;let[ce,_e,st]=Bd();if(!ce||!_e)return;let lt=Vy(_e);if(!lt)return;at.current=!0;let Ke=!0,Ct=qa.get(_e);Ct||(Ct=st==="failed"?Promise.resolve(null):Promise.resolve().then(()=>I.retrievePaymentIntent(_e)),qa.set(_e,Ct));let _t={accountPatch:lt.accountPatch,sessionId:lt.sessionId,nonce:lt.nonce},ct=()=>{G?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Ir,requestCategory:"provider_sdk"})};return G?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Ir}),(async()=>{try{Re(!0);let Qe=await Ct;if(!Ke)return;if(Qe?.error){qa.delete(_e),ct(),i?.(Qe.error.message??"Failed to retrieve PayPal payment status.");return}if(Ty(),qa.delete(_e),st==="failed"){let z="PayPal payment was declined. Please try again.";G?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}),i?.(z),m?.(gn("paypal",z));return}let et=Qe?.paymentIntent;if(et&&et.id!==ce){ct(),i?.("Failed to match the returned PayPal payment.");return}if(et&&(et.status==="requires_capture"||et.status==="succeeded")){let z=typeof et.payment_method=="string"?et.payment_method:et.payment_method?.id;a({id:z??et.id,type:"card",threeDSecureActionResultTokenId:et.id,isPaypal:!0},{..._t,presentationMode:"redirect"})}else{let z="PayPal payment was not completed. Please try again.";G?.terminal({outcome:et?.status==="canceled"?"payment_cancelled":"payment_declined",...Ir,terminalReason:et?.status==="canceled"?"cancelled":"provider_declined"}),i?.(z),m?.(gn("paypal",z))}}catch(Qe){if(!Ke)return;qa.delete(_e),ct(),i?.(Qe instanceof Error?Qe.message:"Failed to complete PayPal payment.")}finally{Ke&&Re(!1)}})(),()=>{Ke=!1,at.current=!1}},[I,a,i,m,G]);let Me=Be(async(ce=!1)=>{let _e=C?await C("paypal"):{proceed:!0};if(!_e.proceed)return Te.current.delete(le),!1;let st=Xe("paypal");return Te.current.set(le,{generation:st,accountPatch:_e.accountPatch,sessionId:_e.sessionId,nonce:_e.nonce}),it(!1),G?.log({name:`provider.${ce?"redirect.started":"handoff.requested"}`,stage:ce?"redirect":"overlay_open",...Ir,attempt:st}),u?.("paypal"),!0},[u,G,C,Xe,le]),Ee=Be(async ce=>{if(l||dt||!await Me()){ce.reject();return}ce.resolve()},[l,Me,dt]),vt=Be(async ce=>{if(!I||!We)return;let _e=Te.current.get(le);if(_e&&!Ve(_e.generation)){Te.current.delete(le);return}if(!_e&&Ce()||_e&&!H(_e.generation))return;_e||H();let st=_e??null;if(Te.current.delete(le),!st&&C){let Ae=await C("paypal");if(!Ae.proceed){ce.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}st={accountPatch:Ae.accountPatch,sessionId:Ae.sessionId,nonce:Ae.nonce}}let lt=st?.sessionId??e,Ke=st?.nonce??t,Ct=await vm({event:ce,prepared:st,email:n,billingName:g,methodLabel:"PayPal",collect:He});if(!Ct){ce.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let _t=Ct.email,ct={...st?.accountPatch,...kr(Ct,!0)};try{if(Re(!0),i?.(null),!lt||!xn(_t))throw new Error("Missing sessionId or email for PayPal payment");await A?.(Ct);let Ae=I.createPaymentMethod,{error:Qe,paymentMethod:et}=await Ae({type:"paypal"});if(Qe){Pt(Qe,"stripe_paypal_create_payment_method_failed",_e?.generation),ce.paymentFailed({reason:"fail"});return}let z=await Bi(o,se,lt,Ke??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:et?.id??null,intentKind:"payment"});if(Fi(z)){ce.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:ct,paymentMethodCategory:"paypal",presentationMode:w,sessionId:lt,nonce:Ke,settledProcessResponse:z.response});return}if(z.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ht=z.clientSecret,k={return_url:Od()};if(et?.id&&(k.payment_method=et.id),!sn(Ks,{clientSecret:Ht,sessionId:lt,nonce:Ke,accountPatch:ct})&&w==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:j,paymentIntent:y}=await I.confirmPayment({clientSecret:Ht,confirmParams:k,redirect:"if_required"});if(j){if(sn(Ks),ci(j)){let h=j.message??"Your payment was declined.";G?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}),i?.(h),m?.(gn("paypal",h,{code:Ho(j),declineCode:bs(j)})),await Di({billingApiUrl:o,sessionId:lt,nonce:Ke,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ho(j)??"provider_declined"}})}else Pt(j,"stripe_paypal_confirm_failed",_e?.generation);return}sn(Ks);let oe=typeof y?.payment_method=="string"?y.payment_method:y?.payment_method?.id;a({id:oe??y?.id,type:"card",threeDSecureActionResultTokenId:y?.id,isPaypal:!0},{accountPatch:ct,paymentMethodCategory:"paypal",presentationMode:w,sessionId:lt,nonce:Ke});return}catch(Ae){Pt(Ae,"stripe_paypal_failed",_e?.generation)}finally{Re(!1)}},[I,We,e,t,n,g,He,A,o,se,a,i,m,C,Pt,H,Ve,Ce,G,w,le]),Ot=Be(async()=>{if(!(Nt.current||l||dt||!I||!We)){Nt.current=!0,Re(!0);try{if(!await Me(!0))return;await vt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Nt.current=!1,Re(!1)}}},[We,vt,l,Me,I,dt]),kt=w==="redirect"?d("button",{type:"button",disabled:l||dt,onClick:()=>{Ot()},style:{width:"100%",minHeight:Eo,border:"1px solid #d1d5db",borderRadius:te??8,background:"#ffc439",color:"#111827",cursor:l||dt?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):d(Nd,{onReady:ce=>rt(Ss(ce,["paypal"])),onLoadError:()=>{rt("load_error"),el(G,"paypal","paypal","provider_error")},onClick:Ee,onConfirm:vt,onCancel:()=>{let ce=Te.current.get(le);Te.current.delete(le),G?.terminal({outcome:"payment_cancelled",...Ir,terminalReason:"cancelled",...ce?{attempt:ce.generation}:{}}),ht(ce?.generation),it(!1),Q.current=!0,Ze()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Dt,emailRequired:Dt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},le),V=Ne(Kn,{children:[Ne("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[je&&d("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:wt,style:Gs,children:"Try PayPal again"}),be&&d(ta,{identity:be.identity,methodLabel:be.methodLabel,onComplete:ot,onCancel:()=>ot(null)},be.id),d("div",{style:{display:be?"none":void 0},children:kt})]}),dt&&!be&&d(Ur,{status:"processing"})]});return w==="redirect"?V:d(ws,{state:Ue,placeholderTestId:"flopay-paypal-placeholder",borderRadius:te,children:V})}function Hs(e){return e==="apple_pay"||e==="google_pay"}var Am=200;function xm({active:e}){return nm(()=>e?xy(document):void 0,[e]),null}function xd({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:l,onErrorChange:u,onButtonClick:m,onDecline:R,onTechnicalFailure:C,runBeforeButtonClick:g,billingName:A,onBuyerIdentityReady:X,onLoadStateChange:te,placeholderBorderRadius:D,popupCapabilityOwner:K,externalTelemetryContext:w}){let pe=po(),{emitInstrument:se}=da(pr),I=Zs(),We=Xs(),G=gt(()=>Ti(hn(pe),w),[w,pe]),[Ue,rt]=ee("loading");Je(()=>{te?.(Ue)},[Ue,te]);let[dt,Re]=ee(!1);Je(()=>{it.current=dt},[dt]);let Nt=B(!xn(n?.trim())||!A?.trim()).current,{request:Dt,collect:be,finish:He}=ea(),ot=B(null),at=B(null),[Ie,Z]=ee(0),[le,Kt]=ee(()=>wd()),je=B(le),it=B(!1),[Q,Te]=ee(!1),[Xe,H]=ee(()=>xi(e,t)?"blocked":"idle"),[ht,Ce]=ee("google_pay"),Ve=B(null),ze=B(!0),Ze=B(!1),Pt=B("google_pay"),De=B("google_pay"),wt=B(null),Me=B(null),Ee=B(new Set),vt=B(null),Ot=B(null);Je(()=>(ze.current=!0,()=>{ze.current=!1;for(let h of Ee.current)window.clearTimeout(h);Ee.current.clear()}),[]);let kt=B(new Map),{startAttempt:V,finishAttempt:ce,invalidateAttempt:_e,isAttemptInvalidated:st,isAttemptCurrent:lt,generationRef:Ke}=xa((h,$,O)=>{C?.(h,$,{...O,popupBlocked:O?.popupBlocked??so($),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Ce(h),Te(!0),Z(he=>he+1)},{onHandoffObserved:h=>{Ot.current=Ke.current,K.markAvailable(),G?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ke.current,...h==="apple_pay"||h==="google_pay"?{walletType:h}:{}})},defersMissingTerminal:Hs,onMissingTerminalDeferred:(h,$)=>{let O=G?.now()??globalThis.performance?.now()??Date.now(),he=vt.current,Se=he?.generation===$?he.startedAt:O;G?.performance({stage:"overlay_return",durationMs:Math.max(0,O-Se),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:$,...Hs(h)?{walletType:h}:{}}),G?.flush?.().catch(()=>{})}});Je(()=>{Q&&at.current?.focus()},[Q,Ie]);let Ct=B(0),_t=B(!1),ct=Be(()=>{if(Ct.current>0){_t.current=!0;return}Z(h=>h+1)},[]),Ae=Be(()=>{Ct.current-=1,!(Ct.current>0||!_t.current)&&(_t.current=!1,ze.current&&Z(h=>h+1))},[]),Qe=Be((h,$,O,he,Se=!1)=>{_e(he),C?.(h,$,{code:O,popupBlocked:so($),telemetryReported:Se,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Ce(h),Te(!0),ct()},[_e,C,ct]),et=Be(h=>{G?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...Hs(h)?{walletType:h}:{}}),C?.(h,new Error("The wallet click was not ready within the time the wallet allows."),{code:am,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Ce(h),Te(!0)},[C,G]),z=Be(()=>{window.setTimeout(()=>{(ot.current?.querySelector("iframe")??ot.current)?.focus()},0)},[]);Je(()=>{Ze.current&&(Ze.current=!1,z())},[z,Ie]);let Ht=Be(()=>{Te(!1),u?.(null),z()},[z,u]),k=Be(()=>{Ve.current?.()},[]);Je(()=>{let h=null,$=()=>{h=null;let he=wd();he!==je.current&&(je.current=he,Kt(he),!it.current&&!lt(Ke.current)&&ct())},O=()=>{h!==null&&window.clearTimeout(h),h=window.setTimeout($,Am)};return window.addEventListener("resize",O),()=>{window.removeEventListener("resize",O),h!==null&&window.clearTimeout(h)}},[Ke,lt,ct]),Je(()=>{let h=xi(e,t);if(!h)return;let $=!1,O=!1,he=async()=>{if(!O){O=!0,$||H("checking");try{let Se=await Id(I,h.clientSecret,Ee.current);if($)return;let _=Ws(Se,h.providerObjectId,qs(h.clientSecret));if(_.kind==="confirmed"){if(!Rd(e,t,h.clientSecret))return;Ve.current=null,H("idle"),l({id:_.paymentMethodId,type:"card",threeDSecureActionResultTokenId:_.intentId},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(_.kind==="terminal"){$s(e,t,h.clientSecret),Ve.current=null,H("idle"),Ce(h.paymentMethodType),Te(!0),ct();return}H("blocked")}catch{$||H("blocked")}finally{O=!1}}};return Ve.current=he,H("blocked"),()=>{$=!0,Ve.current===he&&(Ve.current=null)}},[t,l,ct,e,I]);let q=Be(async h=>{let $=!1,O=!1,he=xe=>{$||O||($=!0,h.paymentFailed({reason:"fail",...xe?{message:xe}:{}}))};if(!I||!We){he();return}let Se=kt.current.get(Ie);if(Se&&!lt(Se.generation)){kt.current.delete(Ie),he();return}if(!Se&&st()){he();return}if(Se&&!ce(Se.generation)){he();return}Se||(ce(),_t.current=!1);let _=h.expressPaymentType??Se?.method??Pt.current,ut=Se??null,Mt=Md(_),At;_==="apple_pay"?At="apple_pay":_==="google_pay"&&(At="google_pay");let Fn=Se?.generation??Ke.current,Ge=G,fr=Ge?.now()??globalThis.performance?.now()??Date.now(),bt=new AbortController,Er=!1,pt=!1,yt=null,Rn=e,Hn="processing",Vn="other",rn="provider_runtime",yn,Xt=new Promise((xe,we)=>{yn=we}),Zt=window.setTimeout(()=>{Er=!0,bt.abort(),yn(Mi)},im),Nn=async(xe,we,tr)=>{Hn=xe,Vn=we,rn=we==="intent_create"||we==="session_claim"?"transport_error":"provider_runtime";let St=Ge?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([tr,Xt])}finally{let Bn=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.performance({stage:xe,durationMs:Math.max(0,Bn-St),durationMode:"machine",requestCategory:we,paymentMethodCategory:"wallet",provider:"stripe",...Er?{statusClass:"timeout"}:{}})}};try{if(Re(!0),u?.(null),!ut&&g){let ae=await Nn("processing","other",g(Mt));if(!ae.proceed){he();return}ut={accountPatch:ae.accountPatch,sessionId:ae.sessionId,nonce:ae.nonce}}let xe=ut?.sessionId??e;Rn=xe;let we=ut?.nonce??t,tr=wt.current??ut?.accountPatch,St=jd({event:h,fallbackEmail:tr?.email??n,fallbackName:[tr?.firstName,tr?.lastName].join(" ").trim()||A});if(!xn(St.email)){he("Buyer details are required."),be(Ys(_),St).then(ae=>{ae&&(wt.current=ae)});return}wt.current=null;let Bn={...ut?.accountPatch,...kr(St,!0)};await Nn("processing","session_claim",Promise.resolve(X?.(St)));let{error:Qt}=await Nn("tokenization","provider_sdk",We.submit());if(Qt){he(),Qe(_,Qt,"stripe_wallet_submit_failed",Se?.generation);return}if(!xe)throw new Error("Missing sessionId or email for payment.");let gr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:_,paymentMethodId:null,intentKind:a},In=JSON.stringify({sessionId:xe,nonce:we??"",request:gr}),_r=Me.current,hr=_r?.retryIdentity===In?_r.authorizationAttemptId:Hy();Me.current={authorizationAttemptId:hr,retryIdentity:In};let En=await Nn("processing","intent_create",Bi(o,se,xe,we??"",{...gr,authorizationAttemptId:hr},{signal:bt.signal}));if(Fi(En)){he(),l({type:"card",paymentMethodType:_},{accountPatch:Bn,paymentMethodCategory:"wallet",sessionId:xe,nonce:we,settledProcessResponse:En.response});return}if(En.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let mn=En.clientSecret,_n=ym({createdAt:Date.now(),sessionId:xe,...we?{nonce:we}:{},clientSecret:mn,providerObjectId:En.providerObjectId,paymentMethodType:_,accountPatch:Bn});window.clearTimeout(Zt),pt=!0,Ge?.performance({stage:"callback",durationMs:Math.max(0,(Ge?.now()??globalThis.performance?.now()??Date.now())-fr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Pr=Ge?.now()??globalThis.performance?.now()??Date.now(),Un={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...At?{walletType:At}:{},attempt:Fn},zn=!1,qn=null;Ge?.log({name:"payment.provider_confirmation.started",...Un}),yt=window.setTimeout(()=>{yt!==null&&Ee.current.delete(yt),zn=!0;let ae=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Un,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ae-Pr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Ge?.flush?.().catch(()=>{}),qn?.()},sm),Ee.current.add(yt);let fn=(ae,Rt)=>{yt!==null&&(window.clearTimeout(yt),Ee.current.delete(yt),yt=null);let xt=Ge?.now()??globalThis.performance?.now()??Date.now(),Vt=Math.max(0,xt-Pr),ye=ae;zn&&(ae==="resolved"?ye="resolved_late":ae==="returned_error"?ye="returned_error_late":ye="rejected_late");let en=Rt??(ae==="resolved"?"approved":"provider_error");return Ge?.log({name:"payment.provider_confirmation.returned",...Un,operationOutcome:ye,terminalReason:en}),Ge?.performance({...Un,durationMs:Vt,durationMode:"buyer",operationOutcome:ye,terminalReason:en}),{durationMs:Vt,operationOutcome:ye,terminalReason:en}},Ut=!1,zt=!1,Dn=ae=>{if(!ae||typeof ae!="object")return null;let Rt=ae;if(Rt.error)return null;let xt=Rt.setupIntent??Rt.paymentIntent,Vt=Ws(xt??null,void 0,!!Rt.setupIntent);return Vt.kind==="confirmed"?Vt:null},vn=ae=>{if(Ut||Se&&Ke.current!==Se.generation)return;let Rt=Dn(ae);if(!Rt)return;if(_n&&!Rd(xe,we,mn)){Ut=!0;return}let{intentId:xt,paymentMethodId:Vt}=Rt;Ut=!0,zt=!0,Me.current=null,Ve.current=null,ze.current&&(H("idle"),Re(!1));let ye=`${Ud}:${xe}`;sn(ye,{createdAt:Date.now(),sessionId:xe,nonce:we,accountPatch:Bn,paymentMethodId:Vt,providerIntentId:xt,paymentMethodType:_});try{l({id:Vt,type:"card",threeDSecureActionResultTokenId:xt},{accountPatch:Bn,paymentMethodCategory:"wallet",sessionId:xe,nonce:we})}finally{sn(ye)}},Tn=!1;qn=async()=>{if(!(Tn||Ut||zt)){Tn=!0,ze.current&&H("checking");try{let ae=await Id(I,mn,Ee.current);if(Ut||zt)return;let Rt=qs(mn),xt=Ws(ae,En.providerObjectId,Rt);if(xt.kind==="confirmed"){vn(Rt?{setupIntent:ae}:{paymentIntent:ae});return}if(xt.kind==="terminal"){if(zt=!0,$s(xe,we,mn),Me.current=null,Ve.current=null,!ze.current)return;H("idle"),he(),Qe(_,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Se?.generation,!0);return}ze.current&&!zt&&(H("blocked"),Re(!1))}catch{ze.current&&!zt&&(H("blocked"),Re(!1))}finally{Tn=!1}}},Ve.current=qn;let T,$e;try{O=!0,Ct.current+=1;let ae;try{ae=await(qs(mn)?I.confirmSetup({elements:We,clientSecret:mn,redirect:"if_required"}):I.confirmPayment({elements:We,clientSecret:mn,redirect:"if_required"}))}finally{Ae()}if(!ae||typeof ae!="object")throw new $a(pm(ae));if(T=ae,!T.error&&!Dn(T))throw new $a("confirmation_result_unconfirmed");$e=fn(T.error?"returned_error":"resolved",T.error&&ci(T.error)?"provider_declined":void 0)}catch(ae){let Rt=ae instanceof $a?ae.reason:void 0,xt=Rt!==void 0,Vt=fn(xt?"returned_error":"rejected");if(Ge?.error({...xt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Rt}:Es(ae),...Un,operationOutcome:Vt.operationOutcome,durationMs:Vt.durationMs,statusClass:"unknown",terminalReason:Vt.terminalReason}),!ze.current||Ut)return;await qn?.();return}let P=T.error;if(P){if(!ze.current||Ut)return;if(ci(P)){zt=!0,$s(xe,we,mn),Me.current=null,Ve.current=null,H("idle"),kt.current.get(Ie)===Se&&kt.current.delete(Ie);let ae=P.message??"Your payment was declined.";u?.(ae),R?.(gn(Mt,ae,{code:Ho(P),declineCode:bs(P)})),Di({billingApiUrl:o,sessionId:xe,nonce:we,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:_,providerDeclineReason:Ho(P)??"provider_declined",...En.intentKind==="payment"&&En.providerObjectId.startsWith("pi_")?{providerIntentId:En.providerObjectId}:{}}})}else Ge?.error({...Es(P),...Un,operationOutcome:$e.operationOutcome,durationMs:$e.durationMs,statusClass:"unknown",terminalReason:$e.terminalReason}),await qn?.();return}if(vn(T),!Ut)throw new Error("Invalid provider returned for APM intent")}catch(xe){if(xe===Mi){let we=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.error({errorCode:fm(Vn),stage:Hn,requestCategory:Vn,paymentMethodCategory:"wallet",provider:"stripe",...At?{walletType:At}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Rn,durationMs:Math.max(0,we-fr),statusClass:"timeout",failureCategory:rn,attempt:Fn,terminalReason:"provider_error"}),Ge?.flush?.().catch(()=>{})}he(),Qe(_,xe,xe===Mi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Se?.generation,xe===Mi)}finally{if(window.clearTimeout(Zt),yt!==null&&(window.clearTimeout(yt),Ee.current.delete(yt)),!pt){let xe=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.performance({stage:"callback",durationMs:Math.max(0,xe-fr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Er?{statusClass:"timeout"}:{}})}ze.current&&Re(!1)}},[I,We,e,t,n,A,be,X,o,se,a,l,u,R,g,Qe,Ae,ce,lt,st,Ke,G,Ie]),j=gt(()=>cc(i),[i]),y=gt(()=>i.map(Qy),[i]),oe=gt(()=>d(Nd,{onReady:h=>{rt(Ss(h,y))},onLoadError:h=>{rt("load_error"),el(G,"stripe","wallet","provider_error")},onClick:async h=>{let $=G?.now()??globalThis.performance?.now()??Date.now();Pt.current=h.expressPaymentType,De.current=Md(h.expressPaymentType);let O=!0,he=window.setTimeout(()=>{O=!1,h.reject(),et(h.expressPaymentType)},om),Se=g?await g(De.current,{abandoned:()=>!O}):{proceed:!0};if(window.clearTimeout(he),!O)return;if(!Se.proceed){kt.current.delete(Ie),h.reject();return}let _=V(h.expressPaymentType);_t.current=!1,vt.current={generation:_,startedAt:$},kt.current.set(Ie,{generation:_,method:h.expressPaymentType,accountPatch:Se.accountPatch,sessionId:Se.sessionId,nonce:Se.nonce}),Te(!1),G?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:_,...h.expressPaymentType==="apple_pay"||h.expressPaymentType==="google_pay"?{walletType:h.expressPaymentType}:{}}),m?.(De.current),h.resolve()},onConfirm:q,onCancel:()=>{let h=kt.current.get(Ie);kt.current.delete(Ie);let $=vt.current,O=G?.now()??globalThis.performance?.now()??Date.now();if(h&&$?.generation===h.generation&&jy({method:h.method,elapsedMs:O-$.startedAt,handoffObserved:Ot.current===h.generation})){G?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:h.generation,walletType:"google_pay"}),Me.current=null,Qe(h.method,new Error("The browser window is too small for the Google Pay sheet."),Ld,h.generation,!0);return}G?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...h?{attempt:h.generation}:{}}),_e(h?.generation),Me.current=null,Te(!1),Ze.current=!0,ct()},options:{...dc,paymentMethods:j,emailRequired:Nt,billingAddressRequired:Nt}},Ie),[y,j,q,_e,m,Nt,Qe,et,ct,g,V,Ie,G]);return Ne(Kn,{children:[d(ws,{state:Ue,placeholderTestId:"flopay-wallet-placeholder",borderRadius:D,children:Ne("div",{ref:ot,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Q&&Ne("button",{ref:at,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ht,style:Gs,children:["Try ",Ys(ht)," again"]}),Xe!=="idle"&&Ne("div",{role:"status","aria-live":"polite",children:[d("p",{children:"We are still confirming your payment. Check its status before trying again."}),d("button",{type:"button",onClick:k,disabled:Xe==="checking",style:Gs,children:Xe==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Dt&&d(ta,{identity:Dt.identity,methodLabel:Dt.methodLabel,onComplete:He,onCancel:()=>He(null)},Dt.id),Ne("div",{style:{display:Dt||Xe!=="idle"?"none":void 0},children:[d(xm,{active:le}),oe]})]})}),dt&&d(Ur,{status:"processing"})]})}function $d(e,t,n){let o=Dd(n,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function Js({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:u,onErrorChange:m,onDecline:R,onCancel:C,runBeforeButtonClick:g,onButtonClick:A,isProcessing:X,submitButtonColor:te,submitButtonBorderRadius:D,submitButtonStyle:K,errorText:w}){let pe=po(),{emitInstrument:se}=da(pr),I=Zs(),We=Xs(),[G,Ue]=ee(!1),rt=B(!1),[dt,Re]=ee(!1),[Nt,Dt]=ee("loading"),[be,He]=ee(""),ot=!xn(o?.trim()),at=!ot||xn(be.trim()),Ie=Be(async()=>{if(!I||!We||X||rt.current||!dt)return;rt.current=!0,Ue(!0);let Z=g?await g("card"):{proceed:!0};if(!Z.proceed){rt.current=!1,Ue(!1);return}A?.("card");let le=Z.sessionId??t,Kt=Z.nonce??n,je=Ta(a?.trim()),it=kr({email:Z.accountPatch?.email?.trim()||o?.trim()||be.trim(),firstName:Z.accountPatch?.firstName?.trim()||je.firstName,lastName:Z.accountPatch?.lastName?.trim()||je.lastName}),Q=it.email,Te=kr({...Z.accountPatch,...it});try{if(m?.(null),!xn(Q))throw new Error("A valid email address is required for payment.");await i?.(it);let Xe=await We.submit();if(Xe.error){m?.(Xe.error.message??"Payment failed.");return}let H=[it.firstName,it.lastName].filter(Boolean).join(" "),ht=await I.createPaymentMethod({elements:We,params:{billing_details:{email:Q,...H?{name:H}:{}}}});if(ht.error||!ht.paymentMethod){m?.(ht.error?.message??"Failed to create payment method.");return}let Ce=ht.paymentMethod;if(!le||!Q)throw new Error("Missing sessionId or email for payment.");let Ve=Ce.type||e,ze=await Bi(l,se,le,Kt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Ve,paymentMethodId:null,intentKind:"payment"});if(Fi(ze)){u({type:"card",gateway:"stripe",paymentMethodType:Ve},{accountPatch:Te,paymentMethodCategory:"apm",sessionId:le,nonce:Kt,settledProcessResponse:ze.response});return}if(ze.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ze=ze.clientSecret;sn(qr,{clientSecret:Ze,sessionId:le,nonce:Kt,accountPatch:Te,paymentMethodId:Ce.id,paymentMethodType:Ce.type??e,gateway:"stripe"});let{error:Pt,paymentIntent:De}=await I.confirmPayment({clientSecret:Ze,confirmParams:{return_url:window.location.href,payment_method:Ce.id},redirect:"if_required"});if(Pt){sn(qr);let Ee=Pt.message??"Payment failed.";m?.(Ee),R?.(gn("card",Ee,{code:Pt.code})),await Di({billingApiUrl:l,sessionId:le,nonce:Kt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Pt.code??"provider_declined"}});return}let wt=De?.status;if(!Ea(wt)){sn(qr);let Ee=wt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(Ee),R?.(gn("card",Ee,{code:wt??"missing_payment_intent"}));return}sn(qr);let Me=typeof De?.payment_method=="string"?De.payment_method:De?.payment_method?.id;u({id:Me??Ce.id,type:"card",threeDSecureActionResultTokenId:De?.id,gateway:"stripe",paymentMethodType:Ce.type??e},{accountPatch:Te,paymentMethodCategory:"apm",sessionId:le,nonce:Kt})}catch(Xe){m?.(Xe instanceof Error?Xe.message:"Payment failed. Please try again.")}finally{rt.current=!1,Ue(!1)}},[I,We,X,dt,g,A,t,n,o,a,be,i,l,se,e,u,m,R]);return Ne("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ot&&d("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ot&&Ne("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",d("input",{type:"email",autoComplete:"email",required:!0,value:be,onChange:Z=>He(Z.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),d(tm,{onReady:()=>Dt("ready"),onLoadError:()=>{Dt("load_error"),el(hn(pe),"stripe","apm")},onChange:Z=>{Re(!!Z.complete)},options:{layout:uc,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...xn(o?.trim())?{email:o?.trim()}:{}}}}}),d(pc,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Ie()},disabled:!dt||!at||G||X||Nt!=="ready",color:te,borderRadius:D,style:K,children:G?"Processing\u2026":`Pay with ${Wa(e)}`}),w&&d(oa,{margin:"0.75rem 0 0",children:w})]})}function Fd({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:l,stripeInstance:u,paymentElementBaseOptions:m,futureUseSession:R,onTokenizedBody:C,onErrorChange:g,onButtonClick:A,onDecline:X,runBeforeButtonClick:te,onLoadStateChange:D,isProcessing:K=!1,submitButtonColor:w="#4A49FF",submitButtonBorderRadius:pe=8,submitButtonStyle:se,buttonAppearance:I,themeId:We,onExpandApm:G,expandedApmMethod:Ue}){let{emitInstrument:rt}=da(pr),[dt,Re]=ee(null),[Nt,Dt]=ee(null),be=B(!1),{request:He,collect:ot,finish:at}=ea();Je(()=>{l.length>0&&u?D?.("ready"):u||D?.("loading")},[l.length,u,D]);let Ie=Be(async Q=>{if(!u||be.current||K)return;be.current=!0,Dt(Q);let Te=te?await te("card"):{proceed:!0};if(!Te.proceed){be.current=!1,Dt(null);return}A?.("card");let Xe=Te.sessionId??e,H=Te.nonce??t,ht=Ta([Te.accountPatch?.firstName,Te.accountPatch?.lastName].filter(Boolean).join(" ")||o),Ce=kr({email:Te.accountPatch?.email?.trim()||n?.trim(),firstName:Te.accountPatch?.firstName?.trim()||ht.firstName,lastName:Te.accountPatch?.lastName?.trim()||ht.lastName});if(!xn(Ce.email)){Dt(null);let Ze=await ot(Wa(Q),Ce);if(!Ze){be.current=!1;return}Ce=Ze,Dt(Q)}let Ve=Ce.email,ze=kr({...Te.accountPatch,...Ce});try{if(g?.(null),!Xe||!xn(Ve))throw new Error("Missing sessionId or email for payment.");await a?.(Ce);let Ze=await Bi(i,rt,Xe,H??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if(Fi(Ze)){C({type:"card",gateway:"stripe",paymentMethodType:Q},{accountPatch:ze,paymentMethodCategory:"apm",sessionId:Xe,nonce:H,settledProcessResponse:Ze.response});return}if(Ze.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Pt=Ze.clientSecret;sn(qr,{clientSecret:Pt,sessionId:Xe,nonce:H,accountPatch:ze,paymentMethodType:Q,gateway:"stripe"});let{error:De,paymentIntent:wt}=await u.confirmPayment({clientSecret:Pt,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:[Ce.firstName,Ce.lastName].filter(Boolean).join(" "),...Ve?{email:Ve}:{}}}},redirect:"if_required"});if(De){sn(qr);let vt=De.message??"Payment failed.";g?.(vt),X?.(gn("card",vt,{code:De.code})),await Di({billingApiUrl:i,sessionId:Xe,nonce:H,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:De.code??"provider_declined"}});return}let Me=wt?.status;if(!Ea(Me)){sn(qr);let vt=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(vt),X?.(gn("card",vt,{code:Me??"missing_payment_intent"}));return}sn(qr);let Ee=typeof wt?.payment_method=="string"?wt.payment_method:wt?.payment_method?.id;C({id:Ee??wt?.id,type:"card",threeDSecureActionResultTokenId:wt?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:ze,paymentMethodCategory:"apm",sessionId:Xe,nonce:H})}catch(Ze){g?.(Ze instanceof Error?Ze.message:"Payment failed. Please try again.")}finally{be.current=!1,Dt(null)}},[u,K,te,A,e,t,n,ot,i,rt,o,a,C,g,X]),[Z,le]=ee(null),Kt=G?Ue??null:Z,je=Be(Q=>{be.current||K||Kt&&Kt!==Q||(Cd(Q)?G?G(Q):le(Q):Ie(Q))},[Kt,K,Ie,G]),it=gt(()=>Z?$d(m,Z,R):null,[Z,m,R]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:He?d(ta,{identity:He.identity,methodLabel:He.methodLabel,onComplete:at,onCancel:()=>at(null)},He.id):l.map(Q=>{let Te=Ue===Q,Xe=Nt===Q,H=Nt!==null&&Nt!==Q||Ue!=null&&Ue!==Q;return Ne(ja.Fragment,{children:[d(lc,{method:Q,themeId:We,submitting:Xe,disabled:H,highlighted:Te,hasNextStep:Cd(Q),onClick:()=>je(Q),backgroundColor:I?.backgroundColor,borderColor:I?.borderColor,textColor:I?.textColor,borderRadius:I?.borderRadius,fontFamily:I?.fontFamily}),!G&&Z===Q&&it&&u&&d(uo,{stripe:u,options:it,children:d(Js,{method:Q,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:C,onErrorChange:g,onDecline:X,onCancel:()=>le(null),runBeforeButtonClick:te,onButtonClick:A,isProcessing:K,submitButtonColor:w,submitButtonBorderRadius:pe,submitButtonStyle:se})},Q)]},Q)})})}function Fm({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:l,onError:u,onDecline:m,onCancel:R,onTokenizedBody:C,firstName:g,lastName:A,chv:X,className:te,submitLabel:D,isProcessing:K,error:w,onErrorChange:pe,showPayPal:se=!0,showStripe:I=!0,walletPresentation:We="auto",enabledPaymentMethods:G,enabledPaymentMethodCountries:Ue,showApplePay:rt=!0,showGooglePay:dt=!0,layout:Re="default",paymentMethodLayout:Nt,moreOptionsLabel:Dt,theme:be,buttonsTheme:He,buttonsStyles:ot,appearance:at,cardButtonContent:Ie,cardBackButtonContent:Z,cardTitleContent:le,showSecurityFooter:Kt,onButtonClick:je,onBeforeButtonClick:it,onBuyerIdentityReady:Q,enableAVS:Te,cardFieldOrder:Xe,showCardBrandIcons:H,showCardFieldLabels:ht,cardFieldLabels:Ce,cardFieldPlaceholders:Ve,cardAutoFocus:ze,onCardFieldsReady:Ze,onCardFieldsFailed:Pt,cardFieldsTimeoutMs:De,cardPreFormSlot:wt,avsLayout:Me="row",country:Ee,zip:vt,addressLine1:Ot,addressLine2:kt,city:V,state:ce,onCountryChange:_e,onZipChange:st,avsCheck:lt,checkoutType:Ke,checkoutLayout:Ct,totalAmount:_t=0,currency:ct="usd",initialCardOpen:Ae=!1,directPaypal:Qe,isSubscription:et=!1,session:z,dataAttachmentPending:Ht=!1,dataAttachmentRequiresIdentity:k=!1,debug:q=!1}){let j=po(),y=_s(),oe=da(wr),{emitInstrument:h}=da(pr),$=B(null);$.current||($.current=gi());let O=$.current,[,he]=ee(0),Se=B(null);Se.current||(Se.current=ka());let _=Se.current,ut=gt(()=>({browser:_,capability:O,presentationMode:"popup"}),[_,O]),Mt=z??oe.session,At=gt(()=>({futureUse:Mt?.futureUse,futureUseUnsupported:Mt?.futureUseUnsupported}),[Mt?.futureUse,Mt?.futureUseUnsupported]),Fn=Mt?.gateways?.paypal?.providerObjectType??Qe?.providerObjectType,Ge=Ht||oe.claimPending===!0,fr=k||oe.claimRequiresIdentity===!0,bt=Ge&&!fr,Er=Nc(),pt=n||Er,yt=Pd({rules:Nt,sessionId:e,nonce:t,billingApiUrl:pt,waitForSession:bt}),Rn=yt?.order??null,[Hn,Vn]=ee(!1),rn=gt(()=>Rn?$y(Rn):null,[Rn]),yn=Rn!==null&&Ny(Rn),[Xt,Zt]=ee(!1),[Nn,xe]=ee(null),[we,tr]=ee(Ee??""),[St,Bn]=ee(vt??""),[Qt,gr]=ee(Ot??""),[In,_r]=ee(kt??""),[hr,En]=ee(V??""),[mn,_n]=ee(ce??""),[Pr,Un]=ee(""),[zn,qn]=ee({}),fn=B(vt??""),Ut=B(Ee??""),zt=B(Ot??""),Dn=B(kt??""),vn=B(V??""),Tn=B(ce??""),T=B(""),$e=B({});Je(()=>{let r=(f,E,J,F,ue)=>{if($e.current[f])return;let It=E?.trim();!It||It===J.current||(J.current=It,F(It),ue?.(It))};r("country",Ee,Ut,tr,_e),r("zip",vt,fn,Bn,st),r("addressLine1",Ot,zt,gr),r("addressLine2",kt,Dn,_r),r("city",V,vn,En),r("state",ce,Tn,_n)},[Ee,vt,Ot,kt,V,ce,_e,st]);let P=gt(()=>Gy(Te),[Te]),ae=P!==null,Rt=gt(()=>zs(z),[z]),xt=Uy(z?.vault),Vt=!!z?.gateways?.pcivault,ye=_c(z),Wr=!!(z?.gateways?.stripe?.enabledPaymentMethods??G)?.includes("card")||_o(z),Mn=xt||Wr||Vt,Pe=!!(I&&Mn&&e),[Tr,Cn]=ee(()=>Re!=="buttons"||Ae?e??null:null),[sr,Po]=ee(0),Gn=Re!=="buttons"||Ae||!!e&&Tr===e,nr=z?.captureMethod,Mr=B(j);Je(()=>{Mr.current=j},[j]);let jn=B(De);jn.current=De;let Ar=B(t);Ar.current=t;let vr=B({onCardFieldsReady:Ze,onCardFieldsFailed:Pt,emitInstrument:h});vr.current={onCardFieldsReady:Ze,onCardFieldsFailed:Pt,emitInstrument:h};let[lr,Yn]=ee(null);Je(()=>{if(!Pe||!e||!Gn){Yn(null);return}let r=Mr.current?Mr.current.cardCapture({sessionId:e,captureMethod:nr,sessionToken:Ar.current,cardFieldsTimeoutMs:jn.current}):new Py({sessionId:e,captureMethod:nr,billingApiUrl:pt,telemetry:o,sessionToken:Ar.current,cardFieldsTimeoutMs:jn.current}),f=r.onCardFields?.(E=>{let J=vr.current;J.emitInstrument?.(Ey(E)),E.type==="card_fields_ready"?vd(()=>J.onCardFieldsReady?.(E)):vd(()=>J.onCardFieldsFailed?.(E))});return Yn({sessionId:e,captureMethod:nr,billingApiUrl:pt,telemetry:o,capture:r}),()=>{f?.(),r.unmount()}},[Pe,e,Gn,nr,pt,o]);let ke=Pe&&e&&Gn&&lr?.sessionId===e&&lr.captureMethod===nr&&lr.billingApiUrl===pt&&lr.telemetry===o?lr.capture:null,An=gt(()=>{let r=we,f=P?nn(P.postal_code,r):!1;return Im(r,St,f)},[P,we,St]),{avsInvalid:$n,invalidAvsFields:ln}=gt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!Pe||!P)return{avsInvalid:!1,invalidAvsFields:r};let f=we,E=(ue,It)=>nn(ue,f)&&!It.trim(),J={line1:E(P.address_line_1,Qt),city:E(P.city,hr),state:E(P.state,mn),zip:An.empty||An.malformed};return{avsInvalid:J.line1||J.city||J.state||J.zip,invalidAvsFields:J}},[Pe,P,we,Qt,hr,mn,An]),[cr,rr]=ee(!1),[Kr,xr]=ee(!1),[vo,Fr]=ee(!1),[Co,Hr]=ee({line1:!1,city:!1,state:!1}),Cr=B(!1),eo=B({email:!1,line1:!1,city:!1,state:!1,zip:!1}),to=B(!1),qt=Be(r=>{eo.current[r]=!0,to.current=!0},[]),Jn=Be(r=>!Cr.current&&eo.current[r],[]),Vr=Be(r=>{Jn(r)&&Hr(f=>f[r]?f:{...f,[r]:!0})},[Jn]),[On,Xn]=ee(()=>js(z?.vault,{billingApiUrl:pt,sessionId:e,nonce:t})),[Fe,Ln]=ee(Ae&&Mn?"card":"buttons"),[$t,Gr]=ee(null),no=Fe==="expanding"||Fe==="card",bo=z?.gateways?.stripe&&!ye?"stripe":void 0,Br=Be(()=>{h?.({class:"card_surface",provider:bo})},[bo,h]),Dr=Be(()=>{Vn(!0),h?.({class:"more_options"})},[h]),bn=B(null),cn=Be(r=>{bn.current&&clearTimeout(bn.current),bn.current=setTimeout(()=>{bn.current=null,r()},Ka)},[]);Je(()=>()=>{bn.current&&clearTimeout(bn.current)},[]);let v=B(!1),[s,c]=ee(0),p=B(null),W=Be(()=>{Br(),Cn(e??null),v.current&&(v.current=!1,c(r=>r+1)),Po(r=>r+1),Ln("expanding"),cn(()=>Ln("card"))},[cn,Br,e]),qe=Be(()=>{Ln("collapsing"),cn(()=>Ln("buttons"))},[cn]),Y=Be(r=>{Gr(r),Ln("apm-expanding"),cn(()=>Ln("apm-form"))},[cn]),de=Be(()=>{Ln("apm-collapsing"),cn(()=>{Ln("buttons"),Gr(null)})},[cn]);Je(()=>{Re==="buttons"&&Ae&&Mn&&(Cn(e??null),Ln("card"))},[Re,Ae,Mn,e]);let[U,S]=ee(null),ne=B(null),[me,b]=ee(0);Je(()=>{me!==0&&ne.current?.focus()},[me]);let M=B(!1),x=B(null),L=B("idle"),[re,Oe]=ee(!1),N=B(re);N.current=re;let[fe,Ye]=ee(()=>Qe?.existingOrderId?{orderId:Qe.existingOrderId,attempts:1}:null),Sn=B(fe);Je(()=>{Sn.current=fe},[fe]);let jt=B(null),Lt=gt(()=>{if(Q||oe.claimBuyerIdentity||z?.buyerIdentified!==!1||!e||!t)return;let r=`${pt}|${e}|${t}`;jt.current?.key!==r&&(jt.current={key:r,claim:Xo(new ca(pt,{telemetry:!1}),e,t,{...i?{userId:i}:{},...g?{firstName:g}:{},...A?{lastName:A}:{}})});let f=jt.current.claim;return async E=>{await f(E)}},[Q,oe.claimBuyerIdentity,z?.buyerIdentified,e,t,pt,i,g,A]),Gt=Q??oe.claimBuyerIdentity??Lt,Yt=w??Nn,Zn=gt(()=>Jy(be),[be]),ve=gt(()=>{let r=Zn?.buttonsLayout??Yy(He);return ot?{...r,...ot,cardButton:{...r.cardButton,...ot.cardButton},cardFormContainer:{...r.cardFormContainer,...ot.cardFormContainer},backButton:{...r.backButton,...ot.backButton},backButtonIcon:{...r.backButtonIcon,...ot.backButtonIcon},submitButton:{...r.submitButton,...ot.submitButton},title:{...r.title,...ot.title}}:r},[Zn,He,ot]),Do=at??Zn?.appearance,pu=gt(()=>My({appearance:Do,buttonsStyles:ve,layout:Re}),[Do,ve,Re]),yu=oe.inlineSessionPatchProcessing??!1,on=(K??Xt)||yu,ro=pt.replace(/\/+$/,""),mt=gt(()=>Is({userId:i,email:a,firstName:g,lastName:A,country:Ee,zip:vt},zn),[i,a,g,A,Ee,vt,zn]),Oo=[mt.firstName,mt.lastName].filter(r=>!!r?.trim()).join(" "),ml=!xn(mt.email?.trim()),ji=B(null);Pe&&ji.current===null&&(ji.current=ml);let oo=Pe&&(ji.current??ml),$i=gt(()=>Em(Pr,oo),[Pr,oo]),Lo=$i.empty||$i.malformed,or=gt(()=>j?j.getRawProvider():null,[j]),fl=gt(()=>y?y.getRawProvider():null,[y]),ya=_t||100,No=ct.toLowerCase(),Wi=gt(()=>Do?vy(Do):null,[Do]),Uo=Wi,gl=gt(()=>{let r=Wi??{},f=r.rules??{};return{...r,rules:{...f,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...f[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...f[".AccordionItemContents"]??{}}}}},[Wi]),hl=gt(()=>({...Ec(_t,Mt?.captureMethod,At),currency:No,...Uo?{appearance:Uo}:null}),[_t,No,Mt?.captureMethod,At,Uo]),Ki=Dd(At,"paypal","paypal"),Pl=gt(()=>({mode:"payment",amount:ya,currency:No,captureMethod:"manual",...Ki?{setupFutureUsage:Ki}:null,...Uo?{appearance:Uo}:null}),[ya,No,Ki,Uo]),ge=Be(r=>{xe(r),pe?.(r)},[pe]),vl=B(0);Je(()=>{s!==vl.current&&(vl.current=s,ge(null))},[s,ge]);let Hi=B(""),[Cl,mu]=ee(!1),Vi=Be(()=>{mu(!0)},[]);Je(()=>{if(!Pe||!oo||!Gt||!Cl||Lo||Hi.current)return;let r=kr({email:xn(mt.email?.trim())?mt.email?.trim():T.current.trim(),firstName:mt.firstName?.trim(),lastName:mt.lastName?.trim()});Hi.current=JSON.stringify(r),qn(f=>({...f,...r})),Promise.resolve(Gt(r)).catch(f=>{Hi.current="",ge(f instanceof Error?f.message:"Failed to attach buyer details.")})},[Pe,oo,Gt,Cl,Lo,mt.email,mt.firstName,mt.lastName,ge]),Je(()=>{if(!Pe||!ke)return;let r=ze!==!1&&P==null&&!oo;ke.setCardFieldOrder?.(Xe??null,r)},[Pe,ke,Xe,ze,P,oo]),Je(()=>{!Pe||!ke||ke.setCardBrandIcons?.(H===!0)},[Pe,ke,H]);let Gi=B(null);Je(()=>{if(!(!Pe||!ke)){if(ht===void 0){if(Gi.current!==ke)return;Gi.current=null,ke.setShowCardFieldLabels?.(!1);return}Gi.current=ke,ke.setShowCardFieldLabels?.(ht===!0)}},[Pe,ke,ht]);let Yi=Ce===void 0?void 0:JSON.stringify(Cy(Ce)),Ji=B(null);Je(()=>{if(!(!Pe||!ke)){if(Yi===void 0){if(Ji.current!==ke)return;Ji.current=null,ke.setCardFieldLabels?.(null);return}Ji.current=ke,ke.setCardFieldLabels?.(JSON.parse(Yi))}},[Pe,ke,Yi]);let Xi=Mm(Ve),Zi=B(null);Je(()=>{if(!(!Pe||!ke)){if(Xi===null){if(Zi.current!==ke)return;Zi.current=null,ke.setCardFieldPlaceholders?.(void 0);return}Zi.current=ke,ke.setCardFieldPlaceholders?.(JSON.parse(Xi))}},[Pe,ke,Xi]),Je(()=>{(Fe==="expanding"||Fe==="collapsing"||Fe==="apm-expanding"||Fe==="apm-collapsing")&&ge(null)},[Fe,ge]);let Or=Be((r,f,E)=>{m?.(gn(r,f,E))},[m]),bl=B(Fe);bl.current=Fe;let[Sl]=ee(Pi),wl=Be(()=>{let r=bl.current;if(Re==="buttons"&&(r==="card"||r==="expanding"))return!0;let f=L.current;return f==="validation-window"||f==="processing"||N.current},[Re]),kl=Be((r,f,E)=>{Sl.take(e)&&hn(j)?.log(Ao({...ut,presentationMode:E?.presentationMode??"popup"},{name:hi,stage:"recovery",reason:"other_method_active",provider:E?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:E?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[ut,j,Sl,e]),Ya=Be((r,f,E)=>{E?.telemetryReported||hn(j)?.error(Ao({...ut,presentationMode:E?.presentationMode??"popup"},{errorCode:f?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:E?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:E?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:E?.terminalReason??(f?"popup_blocked":"provider_error")}))},[ut,j]),zo=Be((r,f,E)=>{let J=E?.popupBlocked??so(f);if(wl()){Ya(r,J,E),kl(r,f,E);return}if(f instanceof Rr&&f.code==="checkout_processing_timeout"){Ya(r,!1,E),S(null),Re==="buttons"&&(Ln("buttons"),Gr(null)),ge(f.message),u?.(f);return}J&&O.markBlocked()&&he(tt=>tt+1);let F=Ys(r),ue=E?.code===Ld?wy(F):li(F,J,_.inAppBrowser),It=Ho(f),Et=(It?.toLowerCase()==="error"?void 0:It)??ic(E?.code)??"external_payment_method_failed",Le=new Rr(ue,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:Et,popupBlocked:J,inAppBrowser:_.inAppBrowser,appFamily:_.appFamily,popupCapability:O.current(),presentationMode:E?.presentationMode??"popup"}});Ya(r,J,E),S(null),Re==="buttons"&&(Ln("buttons"),Gr(null)),ge(ue),u?.(Le),console.error("[FloPay] External payment method failed:",{method:r,code:Et,popupBlocked:J})},[_,wl,Re,u,O,kl,Ya,ge]);Je(()=>{if(!Pe||!e){Xn(null);return}let r={billingApiUrl:ro,sessionId:e,nonce:t},f=js(z?.vault,r);if(f){Xn(f);return}if(!Gn){Xn(null);return}let E=`${ro}\0${e}\0${t??""}`,J=p.current;if(J&&J.key===E){Xn(J.mount);return}Xn(null);let F=!0;return new ca(ro).getVaultCapture(e,t).then(ue=>{if(!F)return;let It=js(ue,r);It?.verificationRequired&&!ue.html&&(p.current={key:E,mount:It}),It?Xn(It):ge("Failed to load the secure card form.")}).catch(ue=>{F&&ge(ue instanceof Error?ue.message:"Failed to load the secure card form.")}),()=>{F=!1}},[Pe,Gn,sr,e,z?.vault,ro,t,ge]);let br=B({onComplete:l,onError:u,updateError:ge,emitDecline:Or,resolvedAccount:mt,avsConfig:P,avsCheckProp:lt,sessionId:e,nonce:t,baseUrl:ro,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:ye});br.current={onComplete:l,onError:u,updateError:ge,emitDecline:Or,resolvedAccount:mt,avsConfig:P,avsCheckProp:lt,sessionId:e,nonce:t,baseUrl:ro,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:ye};let Qi=B(!1),Rl=Be(()=>{let r=br.current,f=r.resolvedAccount.email?.trim(),E=xn(f)?f:T.current.trim();if(!xn(E))return null;let J=r.resolvedAccount.firstName?.trim(),F=r.resolvedAccount.lastName?.trim(),ue=Ut.current.trim()||r.resolvedAccount.country?.trim()||"",It=r.avsConfig?nn(r.avsConfig.state,ue):!1,Et=r.avsConfig?nn(r.avsConfig.address_line_1,ue):!1,Le=r.avsConfig?nn(r.avsConfig.postal_code,ue):!1,tt=r.avsConfig?nn(r.avsConfig.city,ue):!1,ft=r.avsConfig?nn(r.avsConfig.address_line_2,ue):!1,dn=Et&&!It&&Le?Dy(ue,(fn.current??"").trim()):null,ar=It?Tn.current:dn;return{accountData:{userId:r.resolvedAccount.userId??"",email:E,...J?{firstName:J}:{},...F?{lastName:F}:{},...Le&&fn.current?{zip:fn.current}:{},...tt&&vn.current?{city:vn.current}:{},...ar?{state:ar}:{},...Et&&zt.current?{addressLine1:zt.current}:{},...ft&&Dn.current?{addressLine2:Dn.current}:{},...ue?{country:ue}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:nn(r.avsConfig.country,ue),postal_code:Le,address_line_1:Et,address_line_2:ft,city:tt,state:It}}:{}}},[]),Il=B(Ge);Il.current=Ge,Je(()=>{Ge||Yt!==Ed||br.current.updateError(null)},[Ge,Yt]),Je(()=>{!Pe||!ke||ke.setSubmitGate?.($n||Ge||Lo||re)},[Pe,ke,$n,Ge,Lo,re]),Je(()=>{if(!Pe||!ke)return;Qi.current=!1;let r=null,f=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,L.current="idle",S(null)},400)},E=ke.on("submitting",()=>{rr(!0),x.current&&clearTimeout(x.current),L.current="validation-window",x.current=setTimeout(()=>{x.current=null,L.current==="validation-window"&&(L.current="processing")},gm),S("processing");let Le=br.current;if(!Le.sessionId||!Le.nonce)return;let tt=Rl();if(!tt){Le.updateError("Enter a valid email address."),L.current="idle",S(null);return}new ca(Le.baseUrl).patchAccountSnapshot(Le.sessionId,Le.nonce,tt,{telemetryMode:"best_effort"}).catch(ft=>{if(!Pm(ft))return;let dn=ft instanceof Error?ft.message:"Please check your billing address and try again.";Le.updateError(dn),L.current="idle",S(null),Le.onError?.(ft instanceof Rr?ft:new Rr(dn,"api_error"))})}),J=ke.on("complete",Le=>{aa(Le.sessionId??br.current.sessionId),L.current="terminal",Oe(!1),S("success"),setTimeout(()=>{if(Qi.current)return;Qi.current=!0;let tt=br.current,ft=zs(tt)||Le.outcome==="authorized",dn=tt.serverSideCardGateway?{}:{paymentIntentId:Le.intentId};br.current.onComplete?.(ft?{status:"authorized",...dn,paymentId:Le.paymentId??tt.paymentId,sessionId:Le.sessionId??tt.sessionId,authorizationExpiresAt:Le.authorizationExpiresAt??tt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...dn,checkoutMethod:"card"})},600)}),F=ke.on("decline",Le=>{let tt=br.current,ft=Le.message??"Your payment was declined. Please try another card or contact your bank.";L.current="terminal",Oe(!1),tt.updateError(ft),S("error");let dn=Le.failureOutcome??Wy(Le.declineReason)??"authorization_declined";tt.emitDecline("card",ft,{code:dn,declineCode:dn}),f()}),ue=ke.on("error",Le=>{let tt=br.current,ft=ky(Le.vaultOutcome);if(ft!==null){r&&(clearTimeout(r),r=null),L.current="idle",Oe(!1),tt.updateError(ft),S(null),b(ar=>ar+1),tt.onError?.(new Rr(ft,"api_error",{code:Ry}));return}let dn=Le.message??"There was a problem processing your payment. Please try again.";L.current="terminal",Oe(!1),tt.updateError(dn),S("error"),tt.onError?.(new Rr(dn,"api_error",{code:Le.failureOutcome??"capture_failed"})),f()}),It=ke.on("challenge_dismissed",()=>{x.current&&(clearTimeout(x.current),x.current=null),L.current="processing",Oe(!0),S(null)}),Et=ke.on("blocked",()=>{if(N.current){br.current.updateError(hm);return}if(!Il.current){rr(!0);return}Vi(),br.current.updateError(Ed)});return()=>{r&&(clearTimeout(r),r=null),x.current&&(clearTimeout(x.current),x.current=null),L.current="idle",Oe(!1),S(null),E(),J(),F(),ue(),It(),Et()}},[Pe,ke,Vi,Rl]);let Lr=!!Qe?.clientId,ma=Array.isArray(G),Ja=ma&&G.length>0,El=ma&&G.includes("paypal"),Xa=B(null);Xa.current===null&&(Xa.current=Ly());let qo=Xa.current?"redirect":sc(_,We,O.current()),{expressMethods:Za,paymentElementMethods:es}=gt(()=>Ky(G,{excludePaypal:Lr}),[G,Lr]),_l=Lr||!!y||El&&qo==="redirect",fu=gt(()=>_l?Za.filter(r=>r!=="paypal"):Za,[Za,_l]),gu=gt(()=>{let r=[];return rt&&r.push("apple_pay"),dt&&r.push("google_pay"),r},[rt,dt]),jo=ma?fu:gu,hu=I&&jo.length>0,Tl=ae?we:Ee,Qa=gt(()=>Fy(es,Tl,Ue),[es,Tl,Ue]),ts=gt(()=>({mode:"payment",amount:ya,currency:No,paymentMethodCreation:"manual",appearance:gl}),[ya,No,gl]),[ns,Ml]=ee("loading"),[rs,Al]=ee("loading"),[os,xl]=ee("loading"),[Pu,as]=ee(!1),[Fl,is]=ee("loading"),[ss,vu]=ee();Je(()=>{vu(ka())},[]);let ei=ss?.inAppBrowser,ti=ss?di(ss,Qe?.approvalPresentation,Fn??(et?"subscription":"order")):"popup",Bl=se&&(Lr||(ma?El:ei===!1)),Cu=_.inAppBrowser&&O.current()==="blocked",Dl=I&&hu&&!Cu,So=(!bt||!!oe.waitForDataAttachment)&&Bl&&Lr,ls=Fl==="retrying"||Fl==="exhausted",fa=null;I&&(y?fa=fl:qo==="redirect"&&(fa=or));let Ol=gt(()=>({...ut,presentationMode:qo}),[ut,qo]),wo=!bt&&Bl&&!!fa&&(!Lr||ls),ao=!bt&&Dl&&!!or,ko=!bt&&I&&Ja&&Qa.length>0&&!!or,bu=So&&!ls?Pu:wo&&Ra(ns),Su=ao&&Ra(rs),wu=ko&&os!=="load_error",Ll=[So||wo,ao,ko,Pe].filter(Boolean).length,ku={card:Pe,paypal:So&&!ls||wo&&Ra(ns),wallets:ao&&Ra(rs),apms:ko&&os!=="load_error"},Nl=r=>ku[r],Ul=r=>r==="loading"||r==="ready",zl=So||wo&&Ul(ns)||ao&&Ul(rs)||ko&&os!=="load_error",ni=B(!1);Je(()=>{if(!ni.current){if(!I&&!se){ni.current=!0;let r=new Rr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(r),ge(r.message)}else if(!I&&se&&!Lr){ni.current=!0;let r=new Rr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(r),ge(r.message)}else if(ei!==void 0&&!bt&&!Mn&&!zl){ni.current=!0;let r=new Rr("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"});u?.(r),ge(r.message)}}},[I,se,Lr,ei,bt,Mn,zl,u,ge]);let ql=B(!1);Je(()=>{if(ql.current||!Ja)return;let r=[];rt!==!0&&r.push("showApplePay"),dt!==!0&&r.push("showGooglePay"),r.length!==0&&(ql.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Ja,rt,dt]);let jl=Be((r,f,E)=>oe.applyInlineSessionPatch?oe.applyInlineSessionPatch(r).then(J=>({error:null,sessionId:J.sessionId||e,nonce:J.session?.clientSecret||t})).catch(J=>{let F=bd(f,J);return E?.abandoned?.()||(ge(F.message),u?.(F)),{error:F,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[oe.applyInlineSessionPatch,t,u,e,ge]),Sr=Be(async(r,f)=>{if(r!=="card"&&bt&&await oe.waitForDataAttachment?.(),!it)return{proceed:!0};try{let E=await it({method:r,sessionId:e||void 0,createSession:oe.inlineSessionDraft});if(E===!1)return{proceed:!1};if(E&&typeof E=="object"){E.account&&qn(F=>({...F??{},...E.account}));let J=await jl(E,r,f);return J.error?{proceed:!1,accountPatch:E.account}:{proceed:!0,accountPatch:E.account,sessionId:J.sessionId,nonce:J.nonce}}return{proceed:!0}}catch(E){if(!f?.abandoned?.()){let J=bd(r,E);ge(J.message),u?.(J)}return{proceed:!1}}},[jl,oe.inlineSessionDraft,oe.waitForDataAttachment,bt,it,u,e,ge]),$l=Be(async(r,f)=>{if(M.current)return;M.current=!0,Zt(!0),S("processing"),ge(null);let E=f?.sessionId??e,J=f?.nonce??t,F=Is(mt,f?.accountPatch),ue=f?.completionPaymentMethodId??_a(r),It=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,Et=Sm(r),Le=f?.presentationMode?Ti(hn(j),{...ut,presentationMode:f.presentationMode}):void 0,tt=()=>{h?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Et}),Le?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Ir,requestCategory:"process_payment"})};try{let ft=new ca(ro),ar=f?.settledProcessResponse??await ft.processPayment(F.userId??"",{sessionId:E,nonce:J,paymentMethodCategory:f?.paymentMethodCategory??km(r),tokenizedData:It,accountData:{...f?.accountPatch,userId:F.userId??"",email:F.email??"",firstName:F.firstName||void 0,lastName:F.lastName||void 0,...Sy({avsConfig:P,country:Ut.current,zip:fn.current,city:vn.current,state:Tn.current,addressLine1:zt.current,addressLine2:Dn.current})},...by({chv:X,avsCheck:lt,checkoutType:Ke,checkoutLayout:Ct,avsConfig:P,country:Ut.current})}),si=async wn=>{let Ro=zs(z)||wn?.status==="authorized";aa(E),Le?.terminal({outcome:"payment_succeeded",...Ir}),S("success"),Ye(null),await new Promise(Sa=>setTimeout(Sa,600));let Nr;typeof wn?.paymentId=="string"?Nr=wn.paymentId:z?.paymentId&&(Nr=z.paymentId);let Io;typeof wn?.authorizationExpiresAt=="string"?Io=wn.authorizationExpiresAt:z?.authorizationExpiresAt&&(Io=z.authorizationExpiresAt),l?.(Ro?{status:"authorized",...Nr===void 0?{}:{paymentId:Nr},sessionId:typeof wn?.sessionId=="string"?wn.sessionId:E,...Io===void 0?{}:{authorizationExpiresAt:Io},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ue,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ue,checkoutMethod:r.isPaypal?"paypal":"card"})};if(ar.ok){await si(ar.status===204?null:await ar.json().catch(()=>null));return}let un=await ar.json().catch(()=>null);if(un?.type==="paypal_redirect_required"){let wn=un.threeDSecureToken,Ro=un.paymentMethodId||r.id||"";if(!j||!wn){S("error"),ge("PayPal authorization required but no token provided.");return}try{let Nr=y?.getRawProvider();if(!Nr){ge("PayPal is not available.");return}let Io={return_url:window.location.href};Ro&&(Io.payment_method=Ro);let{error:Sa}=await Nr.confirmPayment({clientSecret:wn,confirmParams:Io,redirect:"if_required"});if(Sa){S("error");let rc=Sa.message??"PayPal payment failed.";ge(rc),Or("paypal",rc,{code:Sa.code})}}catch(Nr){S("error"),ge(Nr instanceof Error?Nr.message:"PayPal authorization failed.")}return}if(un?.type==="paypal_direct_required"){let wn=un.orderId;if(!wn){S("error"),ge("PayPal retry required but no order id provided.");return}let Ro=Sn.current?.attempts??0;if(Ro>=2){S("error"),ge("PayPal payment could not be completed after multiple attempts."),Or("paypal","paypal_direct_required retry limit exceeded");return}as(!1),is("loading"),Ye({orderId:wn,attempts:Ro+1}),S(null);return}if(ar.headers.get(cm)===dm){let wn=await um(ft,E,J);if(wn!==void 0){await si(wn);return}}_y(ar.status,un)?Le?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}):tt(),S("error");let nc=un?.message??"Payment failed. Please try again.";ge(nc),Or(r.isPaypal?"paypal":"card",nc,{code:un?.code??un?.gatewayErrorCode,declineCode:un?.declineCode??un?.gatewayDeclineReason}),await new Promise(wn=>setTimeout(wn,400))}catch(ft){qd(ft)||tt(),S("error"),ge(ft instanceof Error?ft.message:"An unexpected error occurred"),await new Promise(dn=>setTimeout(dn,400))}finally{Zt(!1),S(null),M.current=!1}},[ro,e,t,mt,P,lt,Ke,Ct,X,j,y,z,l,ge,Or,h,ut]),Qn=Be((r,f)=>{C&&!f?.settledProcessResponse?C(r):$l(r,f)},[C,$l]),ga=`${Ud}:${e}`;Je(()=>{if(typeof window>"u")return;let r=localStorage.getItem(ga);if(!r)return;let f;try{f=JSON.parse(r)}catch{sn(ga);return}if(!f||typeof f.createdAt!="number"||Date.now()-f.createdAt<0||Date.now()-f.createdAt>zd||typeof f.paymentMethodId!="string"||typeof f.providerIntentId!="string"||typeof f.paymentMethodType!="string"||f.sessionId!==e||!t||f.nonce!==t||!jo.includes(f.paymentMethodType)){sn(ga);return}sn(ga),Qn({id:f.paymentMethodId,type:"card",threeDSecureActionResultTokenId:f.providerIntentId,gateway:"stripe",paymentMethodType:f.paymentMethodType},{...f.accountPatch?{accountPatch:f.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Qn,t,e,ga,jo]);let Wl=B(!1);Je(()=>{if(typeof window>"u"||Wl.current)return;let[r,f,E]=Bd();if(!r||!f||Xa.current||!j)return;let J=j.getRawProvider();if(!J)return;let F=tt=>{let ft=localStorage.getItem(tt);if(!ft)return null;try{return JSON.parse(ft)}catch{return sn(tt),null}},ue=F(qr)??F(kd),It;if(ue?.clientSecret){if(ue.clientSecret!==f)return;It={...ue.accountPatch?{accountPatch:ue.accountPatch}:{},...ue.sessionId?{sessionId:ue.sessionId}:{},...ue.nonce?{nonce:ue.nonce}:{}}}else if(ue?.sessionId&&ue.sessionId!==e)return;Wl.current=!0,sn(qr),sn(kd),window.history.replaceState({},"",Od());let Et=ue?.paymentMethodType??ue?.tokenType??"card",Le="card";(async()=>{if(E==="failed"){let un="Payment was declined. Please try again.";ge(un),Or(Le,un);return}let{paymentIntent:tt,error:ft}=await J.retrievePaymentIntent(f);if(ft){let un=ft.message??"Failed to retrieve payment status.";ge(un),Or(Le,un,{code:ft.code});return}let dn=tt?.status,ar=Ea(dn);if(!tt||!ar){let un=dn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ge(un),Or(Le,un,{code:dn??"missing_payment_intent"});return}let si=typeof tt.payment_method=="string"?tt.payment_method:tt.payment_method?.id;Qn({id:si??ue?.paymentMethodId??ue?.tokenId??tt.id,type:"card",threeDSecureActionResultTokenId:tt.id,gateway:ue?.gateway??"stripe",paymentMethodType:Et},It)})()},[e,Qn,j,ge,Or]);let cs=Be(r=>{r.preventDefault()},[]);if(!(Pe||j!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ha=Re==="buttons",Wn=Do?.variables,Ru=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ds=Wn?.colorBackground,Iu=ds&&!Ru.has(ds)?ds:void 0,Pa=ve.cardInputBorder??(ha?"#e5e7eb":"#A4A4FF"),Kl=Wn?.colorDanger??"#dc2626",tn=r=>ln[r]&&(Co[r]||cr),ri=Lo&&(vo||cr),dr=r=>r?Kl:Pa,oi=(An.malformed||An.empty)&&(Kr||cr),Eu=dr(oi),us=ve.cardFormContainer?.backgroundColor??Iu??(ha?"white":"#EDEDFF"),$o=ve.cardInputBackground??Wn?.colorBackground??"white",ps=Vo(Z),Hl=Vo(le),Wo=ve.nameInput,Vl=ve.cardInputFontSize??_m(Wo?.fontSize)??Wn?.fontSizeBase??"16px",Gl=typeof Wo?.fontFamily=="string"?Wo.fontFamily:Wn?.fontFamily??"Poppins, sans-serif",Yl=em(Wo?.fontWeight)??400,_u=ve.cardInputColor??(typeof Wo?.color=="string"?Wo.color:void 0)??Wn?.colorText??"#262833",Tu=ve.cardInputPlaceholderColor??"#9ca3af",an=Wn?.borderRadius??"8px",Yr=Wn?.borderRadius??ve.cardButton?.borderRadius??an,io=Wn?.colorPrimary??"#4A49FF",Mu=Wn?.colorPrimaryHover??Ay(io,.12),ys=Wn?.colorText??"#262833",ms={fontSize:Vl,fontFamily:Gl,fontWeight:Yl,color:_u,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},va={marginTop:"0.375rem",...ms,fontSize:"0.75rem",lineHeight:1.4,color:Kl},Au={"--flopay-input-placeholder-color":Tu,"--flopay-input-font-size":Vl,"--flopay-input-font-family":Gl,"--flopay-input-font-weight":String(Yl)},Ca=ve.cardFormContainer??{},fs=Ca.padding??(ha?"0":"1rem"),gs=Ca.borderRadius??an,xu=ke&&On?d(Ps,{capture:ke,html:On.html,messageToken:On.messageToken,expectedOrigin:On.expectedOrigin,verificationRequired:On.verificationRequired,theme:pu,submitLabel:D,onReady:()=>{if(!oo&&!P||typeof document>"u"||ze===!1)return;let r=()=>{let E=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(E){Cr.current=!0;try{E.focus()}finally{Cr.current=!1}}};to.current||r()},onError:r=>{r&&On.verificationRequired&&L.current==="idle"&&(v.current=!0),ge(r)},onValidation:r=>{let f=L.current;(f==="idle"||f==="validation-window")&&(ge(r),r&&L.current==="validation-window"&&(x.current&&(clearTimeout(x.current),x.current=null),L.current="idle",S(null)))}},s):d("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"}),hs=Ne("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&Br()},style:{backgroundColor:us,borderRadius:gs,...Ca,padding:fs,...Au,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
5
5
|
.flopay-shared-input::placeholder {
|
|
6
6
|
color: var(--flopay-input-placeholder-color);
|
|
7
7
|
opacity: 1;
|
|
@@ -9,13 +9,13 @@ ${Se.join(`
|
|
|
9
9
|
font-family: var(--flopay-input-font-family);
|
|
10
10
|
font-weight: var(--flopay-input-font-weight);
|
|
11
11
|
}
|
|
12
|
-
`}),
|
|
13
|
-
`)}):null,
|
|
14
|
-
`)}):null,Xl=ze==="apm-expanding"||ze==="apm-form"||ze==="apm-collapsing",$o;ze==="apm-expanding"?$o=Ed:ze==="apm-collapsing"&&($o=_d);let oi=$t?jd(es,$t,Dt):null,Zl={label:xt||yd,open:_n,onOpen:W,color:ao,fontFamily:Wn?.fontFamily};if(Ie==="buttons"){let r=ze==="buttons"||ze==="expanding"||ze==="apm-expanding",m=ze==="expanding"||ze==="card"||ze==="collapsing",A=Ee===void 0?{boxSizing:"border-box",height:wo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ee;ze==="expanding"||ze==="apm-expanding"?ee=Cm:(ze==="collapsing"||ze==="apm-collapsing")&&(ee=vm);let L;ze==="expanding"?L=Ed:ze==="collapsing"&&(L=_d);let fe=Tt&&bd(Tt,{canHide:()=>!0,available:Ll}),It={paypal:Le(Hn,{children:[Po&&$e&&Le(Hn,{children:[sn&&l("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."}),l(Ta.Provider,{value:$,children:l(vi,{sessionId:e,nonce:t,billingApiUrl:nt,email:ft.email,billingName:Bo||void 0,onBuyerIdentityReady:ar,clientId:$e.clientId,environment:$e.environment,currency:St.toUpperCase(),isSubscription:et,providerObjectType:Dn,approvalPresentation:Qa==="popup"?void 0:Qa,onTokenizedBody:Jn,onComplete:s,onErrorChange:Pe,onDecline:y,onCancel:S,onTechnicalFailure:No,onButtonClick:qe,runBeforeButtonClick:vr,isProcessing:en,onLoadStateChange:os,onInitializationStateChange:as,session:Ht,existingOrderId:sn?.orderId,debug:g},sn?.orderId??"fresh")})]}),vo&&l(co,{stripe:ya,options:hl,children:l(Md,{sessionId:e,nonce:t,email:ft.email,billingName:Bo||void 0,onBuyerIdentityReady:ar,billingApiUrl:nt,onTokenizedBody:Jn,onErrorChange:Pe,isProcessing:en,onButtonClick:qe,onDecline:y,onTechnicalFailure:No,runBeforeButtonClick:vr,onLoadStateChange:Tl,placeholderBorderRadius:Kr,popupCapabilityOwner:$,externalTelemetryContext:Dl,presentationMode:Uo})})]}),wallets:Le(Hn,{children:[oo?l(co,{stripe:Zn,options:gl,children:l(Ad,{sessionId:e,nonce:t,email:ft.email,billingName:Bo||void 0,onBuyerIdentityReady:ar,billingApiUrl:nt,intentKind:mt>0?"payment":"setup",expressMethods:zo,onTokenizedBody:Jn,onErrorChange:Pe,onButtonClick:qe,onDecline:y,onTechnicalFailure:No,runBeforeButtonClick:vr,onLoadStateChange:Ml,placeholderBorderRadius:Kr,popupCapabilityOwner:$,externalTelemetryContext:tt})}):null,!oo&&Bl?l("div",{style:{height:wo,borderRadius:Kr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:l(Hn,{children:Co&&l(xd,{sessionId:e,nonce:t,email:ft.email,billingName:[ft.firstName,ft.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ar,billingApiUrl:nt,paymentElementMethods:Xa,stripeInstance:Zn,paymentElementBaseOptions:es,futureUseSession:Dt,onTokenizedBody:Jn,onErrorChange:Pe,onButtonClick:qe,onDecline:y,runBeforeButtonClick:vr,onLoadStateChange:Al,isProcessing:en,submitButtonColor:ao,submitButtonBorderRadius:tn,submitButtonStyle:xe.submitButton,onExpandApm:H,expandedApmMethod:$t,themeId:Re,buttonAppearance:{backgroundColor:xe.cardButton?.backgroundColor,borderColor:xe.cardInputBorder,textColor:xe.cardButton?.color,borderRadius:Kr}})}),card:l(Hn,{children:ce&&l("button",{type:"button",onClick:async()=>{en||!(await vr("card")).proceed||(qe?.("card"),N())},disabled:en,style:{width:"100%",...A,...xe.cardButton,...el({themeBundle:xo,resolvedPrimaryColor:ao,resolvedBorderRadius:tn,submitButtonStyle:xe.submitButton,explicitPrimaryColor:Wn?.colorPrimary}),fontSize:xe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:en?"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:en?.6:1},onMouseEnter:Et=>{!en&&(xo||Wn?.colorPrimary)&&(Et.currentTarget.style.backgroundColor=Tu)},onMouseLeave:Et=>{(xo||Wn?.colorPrimary)&&(Et.currentTarget.style.backgroundColor=ao)},onMouseDown:Et=>{Et.currentTarget.style.transform="scale(0.985)"},onMouseUp:Et=>{Et.currentTarget.style.transform="scale(1)"},children:l(Ko,{content:Ee})})})};return Le("form",{onSubmit:ls,className:ae,noValidate:!0,style:{position:"relative"},children:[l(ci,{}),Z&&l(xr,{status:Z,errorMessage:hr,authorized:ut}),Le("div",{style:{display:"grid"},children:[Le("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!ee?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!ee?Sm:{},...ee?{animation:ee,pointerEvents:"none"}:{}},children:[Yl("flopay-direct-paypal-gate-debug"),Jl("flopay-stripe-gate-debug"),Cn&&fe?Le(Hn,{children:[Cn.filter(({group:Et})=>fe.inView.includes(Et)).map(({group:Et,key:Oe})=>l(za.Fragment,{children:It[Et]},Oe)),fe.behindLink.length>0&&l(Os,{...Zl,showLink:fe.showLink,children:Cn.filter(({group:Et})=>fe.behindLink.includes(Et)).map(({group:Et,key:Oe})=>l(za.Fragment,{children:It[Et]},Oe))})]}):l(Ls,{rows:Ol,borderRadius:Kr}),hr&&ze==="buttons"&&l(na,{margin:"0.25rem 0",styleOverride:xe.errorBanner,children:hr})]}),ce&&m&&l("div",{style:{gridArea:"1 / 1",...L?{animation:L}:{},...ze==="collapsing"?{pointerEvents:"none"}:{}},children:gs}),w&&Xl&&$t&&oi&&Zn&&l("div",{style:{gridArea:"1 / 1",...$o?{animation:$o}:{},...ze==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:ds,borderRadius:fs,...Pa,padding:ms},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:B,style:{display:"inline-flex",alignItems:"center",gap:us?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:xe.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...xe.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...xe.backButtonIcon},children:l("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:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Vo,{content:ne})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:xe.titleFontSize??"1.05rem",color:ps,paddingRight:80,...xe.title},children:`Pay with ${ja($t)}`})]}),l(co,{stripe:Zn,options:oi,children:l(Ys,{method:$t,sessionId:e,nonce:t,email:ft.email,billingName:[ft.firstName,ft.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ar,billingApiUrl:nt,onTokenizedBody:Jn,onErrorChange:Pe,onDecline:y,onCancel:B,runBeforeButtonClick:vr,onButtonClick:qe,isProcessing:en,submitButtonColor:ao,submitButtonBorderRadius:tn,submitButtonStyle:xe.submitButton,errorText:hr})},$t)]})})]})]})}if(Xl&&$t&&oi&&Zn&&w)return Le("form",{onSubmit:ls,className:ae,noValidate:!0,style:{position:"relative"},children:[l(ci,{}),Z&&l(xr,{status:Z,errorMessage:hr,authorized:ut}),l("div",{style:{...$o?{animation:$o}:{},...ze==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:ds,borderRadius:fs,...Pa,padding:ms},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:B,style:{display:"inline-flex",alignItems:"center",gap:us?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:xe.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...xe.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...xe.backButtonIcon},children:l("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:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Vo,{content:ne})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:xe.titleFontSize??"1.05rem",color:ps,paddingRight:80,...xe.title},children:`Pay with ${ja($t)}`})]}),l(co,{stripe:Zn,options:oi,children:l(Ys,{method:$t,sessionId:e,nonce:t,email:ft.email,billingName:[ft.firstName,ft.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ar,billingApiUrl:nt,onTokenizedBody:Jn,onErrorChange:Pe,onDecline:y,onCancel:B,runBeforeButtonClick:vr,onButtonClick:qe,isProcessing:en,submitButtonColor:ao,submitButtonBorderRadius:tn,submitButtonStyle:xe.submitButton,errorText:hr})},$t)]})})]});let Ql=bu||Cu||Su,va=Tt&&bd(Tt,{canHide:r=>r!=="card",available:Ll}),ec={paypal:Le(Hn,{children:[Po&&$e&&Le(Hn,{children:[sn&&l("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."}),l(Ta.Provider,{value:$,children:l(vi,{sessionId:e,nonce:t,billingApiUrl:nt,email:ft.email,billingName:Bo||void 0,onBuyerIdentityReady:ar,clientId:$e.clientId,environment:$e.environment,currency:St.toUpperCase(),isSubscription:et,providerObjectType:Dn,approvalPresentation:Qa==="popup"?void 0:Qa,onTokenizedBody:Jn,onComplete:s,onErrorChange:Pe,onDecline:y,onCancel:S,onTechnicalFailure:No,onButtonClick:qe,runBeforeButtonClick:vr,isProcessing:en,onLoadStateChange:os,onInitializationStateChange:as,session:Ht,existingOrderId:sn?.orderId,debug:g},sn?.orderId??"fresh")})]}),vo&&l(co,{stripe:ya,options:hl,children:l(Md,{sessionId:e,nonce:t,email:ft.email,billingName:Bo||void 0,onBuyerIdentityReady:ar,billingApiUrl:nt,onTokenizedBody:Jn,onErrorChange:Pe,isProcessing:en,onButtonClick:qe,onDecline:y,onTechnicalFailure:No,runBeforeButtonClick:vr,onLoadStateChange:Tl,placeholderBorderRadius:Kr,popupCapabilityOwner:$,externalTelemetryContext:Dl,presentationMode:Uo})})]}),wallets:l(Hn,{children:oo&&l(co,{stripe:Zn,options:gl,children:l(Ad,{sessionId:e,nonce:t,email:ft.email,billingName:Bo||void 0,onBuyerIdentityReady:ar,billingApiUrl:nt,intentKind:mt>0?"payment":"setup",expressMethods:zo,onTokenizedBody:Jn,onErrorChange:Pe,onButtonClick:qe,onDecline:y,onTechnicalFailure:No,runBeforeButtonClick:vr,onLoadStateChange:Ml,placeholderBorderRadius:Kr,popupCapabilityOwner:$,externalTelemetryContext:tt})})}),apms:l(Hn,{children:Co&&l(xd,{sessionId:e,nonce:t,email:ft.email,billingName:[ft.firstName,ft.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:nt,paymentElementMethods:Xa,stripeInstance:Zn,paymentElementBaseOptions:es,futureUseSession:Dt,onTokenizedBody:Jn,onErrorChange:Pe,onButtonClick:qe,onDecline:y,runBeforeButtonClick:vr,onLoadStateChange:Al,isProcessing:en,submitButtonColor:ao,submitButtonBorderRadius:tn,submitButtonStyle:xe.submitButton,themeId:Re,onExpandApm:H,expandedApmMethod:$t,buttonAppearance:{backgroundColor:xe.cardButton?.backgroundColor,borderColor:xe.cardInputBorder,textColor:xe.cardButton?.color,borderRadius:Kr}})})};return Le("form",{onSubmit:ls,className:ae,noValidate:!0,style:{position:"relative"},children:[l(ci,{}),Z&&l(xr,{status:Z,errorMessage:hr,authorized:ut}),Cn===null?l(Ls,{rows:Ol,borderRadius:Kr}):Le(Hn,{children:[bn&&ce&&gs,bn&&ce&&Ql&&l(Ps,{label:"or pay another way"}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Yl("flopay-direct-paypal-gate-debug-default"),Jl("flopay-stripe-gate-debug-default"),Cn.map(({group:r,key:m})=>r==="card"||!va?.inView.includes(r)?null:l(za.Fragment,{children:ec[r]},m)),va&&va.behindLink.length>0&&l(Os,{...Zl,showLink:va.showLink,children:Cn.map(({group:r,key:m})=>va.behindLink.includes(r)&&r!=="card"?l(za.Fragment,{children:ec[r]},m):null)})]}),!bn&&ce&&Ql&&l(Ps,{label:"or pay with card"}),!bn&&ce&&gs]})]})}import{Fragment as Dr,jsx as de,jsxs as gn}from"react/jsx-runtime";var _o=44,il="flopay_checkout_saved_payment_resume",Wm="paypal_resume_nonce_missing",Ui=new Map,Di=new Map;function Gd(e,t){t.settled&&t.consumers===0&&Ui.get(e)===t&&Ui.delete(e)}function Hm(e,t,n){let o=Di.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};Di.set(e,i);let s=()=>{Di.get(e)===i&&Di.delete(e)};return a.then(s,s),a}function Wa(e){return new Promise(t=>setTimeout(t,e))}function Ni(e,t,n){let o=hi({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:au,enabled:t!==!1});return o.beginCheckout(n),o}function Ha(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function nl(e,t,n,o,a,i){let s=Ni(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Ha(s)}function Yd(e,t,n,o){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()-n),durationMode:"machine",requestCategory:t,...o===void 0?{}:{attempt:o},statusClass:"2xx"})}function Jd(e,t,n,o,a){let i=nu(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-o),durationMode:"machine",requestCategory:n,attempt:a,statusClass:i.statusClass}),t instanceof vn&&t.code==="session_auto_completed"?!1:t instanceof vn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function rl(e){return!e||e.data.stripe?.publishableKey?!1:!!ru(e.data.paypal)?.clientId}var Km={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Xd(e){return new Fm(Km,{publishableKey:"provider_unavailable",...e})}async function Oi(e,t){let{publishableKey:n,paypalPublishableKey:o}=Bs(e);return{...await Ds({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function Zd(e){let t=e.data.stripe;return JSON.stringify([t?.publishableKey??null,t?.paypalPublishableKey??null])}function sl(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Vm(){if(!sl())return null;try{let e=window.sessionStorage.getItem(il);return e?JSON.parse(e):null}catch{return null}}function Qd(e){if(sl())try{window.sessionStorage.setItem(il,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ol(){if(sl())try{window.sessionStorage.removeItem(il)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Gm(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let o of t)e.searchParams.has(o)&&(e.searchParams.delete(o),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function eu(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 al(e,t){return jm(!!e,t)}function Ym(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function tu(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Jm(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 ll({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:c,error:y,onComplete:S,onError:P,onInstrument:f,onDecline:F,onCancel:te,onCountryChange:ae,onZipChange:z,showPayPal:K=!0,showStripe:C=!0,walletPresentation:ge="auto",enabledPaymentMethods:ue,showApplePay:w=!0,showGooglePay:Ke=!0,debug:X=!1,layout:Ne,paymentMethodLayout:at,moreOptionsLabel:pt,theme:Ie,buttonsTheme:Bt,buttonsStyles:xt,cardButtonContent:Re,cardBackButtonContent:Ye,cardTitleContent:it,showSecurityFooter:st,onButtonClick:Ee,onBeforeButtonClick:ne,enableAVS:pe,cardFieldOrder:jt,showCardBrandIcons:qe,showCardFieldLabels:lt,cardFieldLabels:re,cardFieldPlaceholders:Me,cardAutoFocus:Ze,onCardFieldsReady:V,onCardFieldsFailed:vt,cardFieldsTimeoutMs:be,cardPreFormSlot:Je,avsLayout:Ue,submitLabel:Qe,className:Ct,initialErrorMessage:Be=null,initialPayPalOrderId:kt,children:Ae,checkoutMode:_e,confirmLabel:bt,renderConfirmButton:Ft,onSessionCompleted:Rt}){let G=zm(o),ye=ur(()=>ou(Ie),[Ie]),Te=i??ye?.appearance,ct=n?"embedded_checkout":"standard_checkout",dt=al(Ae,Ne),[Ve,yt]=Wt(null),[mt,St]=Wt(null),je=zt(null),$e=zt(null),et=zt(0),[q,hn]=Wt(null),b=zt(null),[g,Y]=Wt(null),j=ur(()=>n?xa(n):"",[n]),J=n?`create:${j}`:`session:${e??""}`,h=tu(g),se=zt(new Set),$=zt(J),Se=zt(J);ba(()=>{Se.current=J,$.current!==J&&($.current=J,se.current.clear())},[J]);let we=In(I=>{if(Se.current===J){if(Nc.has(I.name)){if(se.current.has(I.name))return;se.current.add(I.name)}At(()=>f?.(I))}},[J,f]),k=ea(we,J),tt=zt(!1),Ht=In(I=>{if(tt.current)return;let E=I.gateway||!h?I:{...I,gateway:h};we(E)},[we,h]);dr(()=>{k({class:"lifecycle",name:"checkout.mount"})},[k]);let[Dt,Dn]=Wt(e??""),ve=e??Dt,kr=n?"":ve,[dn,un]=Wt(!0),[nt,Tt]=Wt(null),[En,_n]=Wt(0),[Tn,Cn]=Wt("full"),[bn,Kt]=Wt(!1),[Ot,Xt]=Wt(Be),[Ge,me]=Wt(null),[er,Mt]=Wt(null),[Mn,On]=Wt(!1),[tr,Ln]=Wt(void 0),[Rr,pr]=Wt(""),[pn,yn]=Wt(!1),[An,Kn]=Wt(!1),[Nn,xn]=Wt(!1),rn=zt(null),Zt=zt(0),Qt=zt(void 0),[Vt,Un]=Wt("loading"),[zn,Fn]=Wt(0),R=zt(!1),We=zt(!1),v=zt(!1),le=zt(null),ut=zt(null),He=ur(()=>({checkoutMode:_e??Tn,layout:Ym(Ae,Ne)}),[_e,Ae,Tn,Ne]),Lt=zt(S);Lt.current=S;let ke=zt(P);ke.current=P;let Ir=zt(F);Ir.current=F;let Lr=In(I=>ki(le,async E=>{try{return await I(E)}catch(W){throw E.aborted?oa(W):W}}),[]);dr(()=>()=>{le.current?.abort(),le.current=null},[]);let on=In((I,E)=>{je.current=I,St(I),b.current=E,hn(E)},[]),ce=In(()=>{let I=$e.current;I&&($e.current=null,I.destroy())},[]),[Nr,Xr]=Wt(null);dr(()=>{!Nr||mt!==Nr.flopay||(Xr(null),Nr.apply())},[mt,Nr]);let Zr=In(async(I,E,W)=>{let _=null;try{_=await Oi(I,{billingApiUrl:G,locale:s,telemetry:a})}catch{_=null}if(!E())return;if(ce(),_){Ac([_.flopay?.getRawProvider(),_.paypalFlopay?.getRawProvider()],[je.current?.getRawProvider(),b.current?.getRawProvider()]),on(_.flopay,_.paypalFlopay),_n(0),Xr({flopay:_.flopay,apply:W});return}let De=Xd({billingApiUrl:G,locale:s,telemetry:a});$e.current=De,on(De,null),_n(1),W()},[ce,on,s,G,a]);dr(()=>{fn(mt)?.setCheckoutContext(He),q&&q!==mt&&fn(q)?.setCheckoutContext(He)},[mt,q,He]);let Qr=zt(Rt);Qr.current=Rt;let yr=In(I=>{Un(I),!(I!=="exhausted"||v.current)&&(v.current=!0,ke.current?.(new vn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Er=In(()=>{Un("retrying"),Fn(I=>I+1)},[]);dr(()=>{Un("loading"),Fn(0),v.current=!1},[ve]),dr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:au,checkout_type:ct,checkout_layout:dt,billing_api_url:G})},[dt,ct,G]);let Vn=ur(()=>n?xa(n,!0):"",[n]),qn=ur(()=>Rr===Vn?tr:void 0,[tr,Rr,Vn]),mr=ur(()=>n?ks(n,qn):void 0,[n,qn]),Bn=_e??mr?.checkoutMode??"full",Nt=ur(()=>mr?{...mr,checkoutMode:Bn}:void 0,[mr,Bn]);dr(()=>{Ln(void 0),pr(Vn),Qt.current=void 0,rn.current=null,xn(!1)},[Vn]),dr(()=>{Xt(Be)},[Be]);let nr=In((I,E,W)=>{At(()=>{Ir.current?.(mn(I,E,W))})},[]),Ce=In(async(I,E)=>{Xt(null),Mt(null),On(!1),me("processing");let W=E?.sessionId??I.id,_=I.clientSecret||t,De=tu(I),an=je.current??b.current,d=fn(an),p=an?null:Ni(G,a,He),u={log:T=>{d?d.log(T):p?.log(T)},error:T=>{d?d.error(T):p?.error(T)},terminal:T=>{d?d.terminal(T):p?.terminal(T)},performance:T=>{d?d.performance(T):p?.performance(T)},now:()=>d?.now()??p?.now()??0,elapsed:T=>d?.elapsed(T)??Math.max(0,(p?.now()??T)-T)},N=u.now(),x=!!(E?.initialAutoProcessingError||E?.initialAutoProcessingPending),H=!1,B,Z=()=>{H||(H=!0,x=!0,B=u.now(),u.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),u.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ie=!1,gt=()=>{ie||(ie=!0,u.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),u.performance({stage:"processing",durationMs:u.elapsed(N),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),B!==void 0&&u.performance({stage:"recovery",durationMs:u.elapsed(B),durationMode:"machine",paymentMethodCategory:"saved"}))};u.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),tt.current=!0;try{u.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{tt.current=!1}k({class:"lifecycle",name:"payment.processing.started",provider:De}),x&&Z();let Gt;try{let T=sd(E?.initialAutoProcessingError),D=E?.initialAutoProcessingError?.type==="3ds_required"&&!Nm(E.initialAutoProcessingError)&&!E.initialAutoProcessingError.threeDSecureToken&&E.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:E.initialAutoProcessingError.nextActionRedirectUrl}:null,O,M=Q=>{Z();let wt=La(G,W,I,a!==!1);return Lr(he=>aa(Q,{billingApiUrl:G,sessionId:W,nonce:_,session:I,signal:he,...wt.telemetry?{challengeTelemetry:wt.telemetry}:{}})).finally(wt.release)};if(D)O=await M(D);else if(T)Z(),T.type==="paypal_redirect_required"&&ut.current?.publishableKey&&Qd({sessionId:W,publishableKey:ut.current.publishableKey,paypalPublishableKey:ut.current.paypalPublishableKey,nonce:_}),O=await Lr(Q=>Ii(T,{flopay:je.current,paypalFlopay:b.current,attempt3DS:E?.attempt3DS,billingApiUrl:G,sessionId:W,session:I,telemetry:!1,signal:Q})),T.type==="paypal_redirect_required"&&ol();else if(E?.initialAutoProcessingPending){let Q=E.initialAutoProcessingPending,wt=new Bi(G,{telemetry:!1}),he=await Lr(_r=>wt.waitForCheckoutSessionCompletion(Q.sessionId,{initialDelayMs:Q.retryAfterMs,nonce:_,statusUrl:Q.statusUrl,signal:_r})),sn=lo(he,I),Yn=he.autoProcessingError?.type==="3ds_required"&&he.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:he.autoProcessingError.nextActionRedirectUrl}:null;if(Yn)O=await M(Yn);else{if(!Gr(sn))throw Jo(sn);O=Vr(sn,W)}}else{if(E?.initialAutoProcessingError)throw Fr(E.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:E.initialAutoProcessingError.checkoutMethod});if(E?.fromCreateSession)return E?.fallbackToFull&&(Cn("full"),eu("full")),!1;{let Q=await ia({billingApiUrl:G,sessionId:W,session:I,nonce:_,telemetry:!1});Q.type==="success"?O=Q.result:Q.type==="next_action_required"?O=await M(Q):(Z(),Q.type==="paypal_redirect_required"&&ut.current?.publishableKey&&Qd({sessionId:W,publishableKey:ut.current.publishableKey,paypalPublishableKey:ut.current.paypalPublishableKey,nonce:_}),O=await Lr(wt=>Ii(Q,{flopay:je.current,paypalFlopay:b.current,attempt3DS:E?.attempt3DS,billingApiUrl:G,sessionId:W,session:I,telemetry:!1,signal:wt})),Q.type==="paypal_redirect_required"&&ol())}}W&&ra(W),gt(),x&&(u.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),u.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),u.terminal({outcome:O.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),On(O.status==="authorized"),me("success"),await Wa(600),Gt=()=>Lt.current?.(O)}catch(T){let D=so(Na(T),W);if(D.code==="three_ds_aborted")return!1;let O=D.checkoutMethod??Oa;Xt(D.message),Mt(D.message),On(!1),E?.fallbackToFull&&(u.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Cn("full"),eu("full")),gt();let M=D.statusCode===void 0?void 0:$m(D.statusCode,"unknown"),Q=M==="4xx"?{requestCategory:"process_payment",statusClass:M}:{},wt=M===void 0||M==="4xx";if(Hd(D))u.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Q});else if(wt&&(D.telemetryOutcome==="validation_rejected"||D.type==="validation_error"))u.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Q});else{let Yn=nu(T,x?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),_r=D.telemetryRequestCategory??"process_payment";tt.current=!0;try{u.error({...Yn,...D.telemetryFailureCategory?{failureCategory:D.telemetryFailureCategory}:{},stage:x?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:_r})}finally{tt.current=!1}k({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:_r,provider:De})}return Wd(D)?nr(O,D,{code:D.code,declineCode:D.declineCode}):At(()=>ke.current?.(D)),me("error"),await Promise.allSettled([Wa(400),E?.ensureProvidersReady?E.ensureProvidersReady():Promise.resolve()]),x&&(u.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),u.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{gt(),p&&Ha(p),me(null),Mt(null)}return At(Gt),!0},[nr,k,t,G,Lr,a,He]);dr(()=>{if(typeof window>"u"||We.current)return;let I=new URLSearchParams(window.location.search),E=I.get("payment_intent_client_secret");if(!E)return;let W=Vm();W&&(We.current=!0,(async()=>{await Promise.resolve();let _,De=0;Xt(null),Mt(null),me("processing"),Kt(!0);try{if(I.get("redirect_status")==="failed")throw Object.assign(new vn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:an,paypalFlopay:d}=await Ds({publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey,billingApiUrl:G,locale:s,telemetry:a});_=fn(d??an),_?.setCheckoutContext(He),De=_?.now()??0,_?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),_?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let p=(d??an)?.getRawProvider();if(!p)throw Object.assign(new vn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:u,error:N}=await p.retrievePaymentIntent(E);if(N)throw Object.assign(new vn(N.message??"Failed to retrieve PayPal payment status.","api_error",{code:N.code}),{checkoutMethod:"paypal"});let x=kc(u?.status);if(!u||x==="failed")throw Object.assign(new vn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let H=typeof u.payment_method=="string"?u.payment_method:u.payment_method?.id,B=x;if(W.sessionId){let Z=W.nonce||t;if(!Z)throw Object.assign(new vn("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:Wm}),{checkoutMethod:"paypal"});let Gt=(await new Bi(G,{telemetry:!1}).getUnifiedCheckoutSession(W.sessionId,Z)).data.session;if(Gt&&Gt.status!=="complete"){let T=await ia({billingApiUrl:G,sessionId:W.sessionId,session:Gt,nonce:Z,telemetry:!1,tokenizedData:{id:H??u.id,type:"card",threeDSecureActionResultTokenId:u.id,isPaypal:!0}});if(T.type!=="success")throw Object.assign(new vn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});B=T.result.status}}W.sessionId&&ra(W.sessionId),_?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),_?.performance({stage:"redirect_resume",durationMs:_.elapsed(De),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),_?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),me("success"),await Wa(600),At(()=>Lt.current?.({status:B,paymentIntentId:u.id,paymentMethodId:H,checkoutMethod:"paypal"}))}catch(an){let d=so(Na(an),W.sessionId),p=d.checkoutMethod??"paypal",u=Hd(d);if(_)_.performance({stage:"redirect_resume",durationMs:_.elapsed(De),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),u?_.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):_.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(u){let N=Ni(G,a,He);N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ha(N)}else nl(G,a,He,"REDIRECT_RESUME_FAILED","redirect_resume");Xt(d.message),Mt(d.message),Wd(d)?nr(p,d,{code:d.code,declineCode:d.declineCode}):At(()=>ke.current?.(d)),me("error"),await Wa(400)}finally{ol(),Gm(),me(null),Mt(null),Kt(!1)}})())},[nr,s,t,G,a,He]);let Sn=zt(null),Gn=ur(()=>Nt?xa(Nt):"",[Nt]),Ur=zt(Nt);Ur.current=Nt,dr(()=>{Dn(e??"")},[e]),dr(()=>{R.current=!1,Xt(Be),Mt(null),On(!1),me(null)},[Gn,Be,e]);async function fr(I,E,W){let _=Ni(G,a,He),De=new Bi(G,{telemetry:!1,stripeAccountSwitch:!0}),an=!1;try{let d=I.idempotencyKey===void 0?void 0:Kd(I.idempotencyKey),p=Xc(E,W),u=Jc(E,W);p?.canonicalIdentity===W&&u&&u.canonicalIdentity===void 0&&(bi(E,W,u.idempotencyKey),u={...u,canonicalIdentity:W});let N=d??(u?.canonicalIdentity===W?u.idempotencyKey:void 0),x,H=!1;_.log({name:p?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let B=p?.sid??null,Z=null,ie,gt,Gt=!1;if(B)try{Z=await De.getUnifiedCheckoutSession(B,p?.nonce),p&&p.canonicalIdentity===void 0&&(Yc(Z.data.session,I)?(Si(E,W,B,p.nonce??Z.data.session?.clientSecret),u&&u.canonicalIdentity===void 0&&(bi(E,W,u.idempotencyKey),N??(N=u.idempotencyKey))):(Ci(E,W),u=null,N=d,B=null,Z=null));let D=Z?.data.session?.status,O=Z?.data.session,M=O?.clientSecret||p?.nonce;if(B&&O?.buyerIdentified===!1&&M&&(gt=Yo(De,B,M,I.account)),B&&Z&&D==="complete"){if(As(B))return{sid:B,result:Z};Ci(E,W),B=null,Z=null,H=!0}}catch{_.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),p?.canonicalIdentity===void 0?(Ci(E,W),N=d):Ms(E,W),B=null}if(!B){!d&&(H||!N)&&(N=Kd(),x=N),N&&bi(E,W,N);let D=_.now(),O=0;_.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let M={...I,idempotencyKey:N,avsCheck:!!pe,avsConfig:typeof pe=="object"?pe:void 0,checkoutType:"embedded_checkout",checkoutLayout:al(Ae,Ne)};Object.defineProperty(M,Bm,{configurable:!1,enumerable:!1,value:{onAttempt:he=>{O=Math.max(O,he)}}});let Q=()=>{Yd(_,"session_create",D,O)},wt=he=>{Jd(_,he,"session_create",D,O)&&k({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(I.checkoutMode==="confirm"||I.checkoutMode==="auto")&&td();try{if(Lm(M)){let he=await De.createDetachedSession(M);he.claimed.catch(()=>{}),Z=he.shell,B=he.sessionId,gt=he.claim;let sn=_.now();_.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ie=he.claimed.then(Yn=>{let _r=Yn.data.session?.id??he.sessionId;return _r&&Si(E,W,_r,Yn.data.session?.clientSecret??he.nonce),Yd(_,"session_claim",sn),Q(),Yn},Yn=>{throw Ms(E,W),Jd(_,Yn,"session_claim",sn,0)&&k({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Yn}).finally(()=>Ha(_)),ie.catch(()=>{}),an=!0,_.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),_.performance({stage:"session_shell",durationMs:_.now()-D,durationMode:"machine",requestCategory:"session_create",attempt:O,statusClass:"2xx",paymentMethodCategory:"card"})}else Z=await De.createAndFetchSession(M),Q()}catch(he){throw wt(he),he}B=Z.data.session?.id??B??"",B&&!ie&&Si(E,W,B,Z.data.session?.clientSecret)}let T=Z?.data.session;return!gt&&B&&T?.buyerIdentified===!1&&T.clientSecret&&(gt=Yo(De,B,T.clientSecret,I.account)),{sid:B??"",result:Z,sdkGeneratedIdempotencyKey:x,...ie?{claimed:ie}:{},...gt?{claim:gt}:{},...Gt?{claimRequiresIdentity:!0}:{}}}finally{an||Ha(_)}}let gr=zt(fr);ba(()=>{gr.current=fr},[fr]);let zr=In(async(I,E)=>{let W=Ur.current;if(!W)throw new vn("createSession is required to bootstrap checkout.","validation_error");let _=ks(W,I),De=xa(_),an=Gc(_),d=Ui.get(De);if(!d){let N={canonicalIdentity:De,promise:gr.current(_,an,De),consumers:0,settled:!1};d=N,Ui.set(De,N);let x=()=>{N.settled=!0,Gd(De,N)};N.promise.then(x,x)}d.consumers+=1;let p=!1,u=()=>{p||(p=!0,d.consumers-=1,Gd(De,d))};E?.(u);try{let N=await d.promise;Sn.current=De,I&&(pr(Vn),Ln(T=>Pc(T,I)));let{sid:x,result:H,claimed:B,claim:Z,claimRequiresIdentity:ie}=N;Qt.current=Z,xn(ie===!0),yt(H),H.data.session&&Y(H.data.session),x&&Dn(x);let gt=()=>{},Gt=new Promise(T=>{gt=T});if(B){Zt.current+=1;let T=Zt.current,D=()=>Zt.current===T;rn.current=B,Kn(!0);let O=M=>{D()&&(rn.current===B&&(rn.current=null),yt(M),M.data.session&&Y(M.data.session),Kn(!1),xn(!1))};B.then(async M=>{if(D()){if(Zd(M)===Zd(H)){O(M);return}await Gt,D()&&await Zr(M,D,()=>O(M))}},M=>{Zt.current===T&&(rn.current===B&&(rn.current=null),Kn(!1),xn(!1),Tt(M instanceof vn?M:new vn(M instanceof Error?M.message:"Failed to create session","api_error")))})}else Zt.current+=1,rn.current=null,Kn(!1),xn(!1);try{let{flopay:T,paypalFlopay:D}=await Oi(H,{billingApiUrl:G,locale:s,telemetry:a}).catch(O=>{throw bc(O,x||H.data.session?.id)});on(T,D)}finally{gt()}return un(!1),N}catch(N){throw Sn.current===De&&(Sn.current=null),N}finally{E||u()}},[Vn,on,s,G,Zr,a]),eo=zt(Ce);eo.current=Ce;let Ao=zt(zr);Ao.current=zr;let qr=In(async I=>{if(!Jm(I)||pn)return{sessionId:Dt,session:g};yn(!0);try{let E=await zr(I);return{sessionId:E.sid,session:E.result.data.session??null}}finally{yn(!1)}},[zr,pn,Dt,g]),jr=In(async I=>{let E=Qt.current;if(!E)return;let W=Zt.current,_=await E(I);Zt.current===W&&(yt(_),_.data.session&&Y(_.data.session))},[]),$r=In(async()=>{await rn.current},[]),Wr=In(async()=>(await $r(),{proceed:!0}),[$r]);dr(()=>{let I=!1,E,W=++et.current;ce(),Tt(null),_n(0);let _=()=>{I=!0,et.current===W&&(et.current+=1,ce())},De=Ur.current;if(Gn&&De)return Cn(Bn),un(!1),Sn.current===Gn?_:(Y(vc(De,_e)),(async()=>{let p=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),u=Bn==="auto"&&!R.current&&!p;u&&(Xt(null),Mt(null),me("processing"));let N=!1;try{let x=await Ao.current(void 0,ie=>{E=ie});N=!0;let H=x.result.data.session??null;ut.current=Bs(x.result);let B=rl(x.result),Z=As(x.sid||H?.id);if(!I&&u&&H&&!B&&!Z){R.current=!0,await Hm(Gn,x.sdkGeneratedIdempotencyKey,()=>eo.current(H,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:x.result.autoProcessingError,initialAutoProcessingPending:x.result.autoProcessingPending,autoProcessingAttempted:x.result.autoProcessingAttempted,sessionId:x.sid||H.id}));return}!I&&u&&((B||Z)&&(R.current=!0),me(null),Mt(null))}catch(x){if(I)return;let H=ui(x);if(u&&H==="session_auto_completed"){R.current=!0,me("success"),await Wa(600),I||(At(()=>{Lt.current?.({status:"succeeded"})}),me(null),Mt(null));return}if(u&&(me(null),Mt(null)),!N){let Z=Sc(x),ie=Vd(x,Z?{stage:"provider_load",provider:"stripe",...Z}:{stage:"session_request"});(Z||!(x instanceof vn))&&At(()=>ke.current?.(ie)),Tt(ie);return}let B=x instanceof vn?x:new vn(x instanceof Error?x.message:"Failed to create session","api_error");Tt(B)}finally{E?.(),E=void 0}})(),()=>{_(),E?.()});un(!0);async function an(){let p=!1,u=!1,N=null;try{let x=new Bi(G,{telemetry:!1}),H=await x.getUnifiedCheckoutSession(ve,t);if(u=!0,N=H,I)return;yt(H);let B=H.data.session??null;if(Y(B),!B)throw new vn("No session data returned","api_error");let Z=B.checkoutMode;if(Z==="setup")throw new vn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(B.status==="authorized"){un(!1),At(()=>{Lt.current?.(Vr(B,ve)),Qr.current?.(B.successUrl??"")});return}if(B.status==="complete"){un(!1),At(()=>{Qr.current?.(B.successUrl??"")});return}if(B.status==="expired")throw di(B);p=!0;let ie=_e??Z??"full";Cn(ie),Zt.current+=1;let gt=B.clientSecret||t;Qt.current=B.buyerIdentified===!1&>?Yo(x,ve,gt,{...B.customer?.id?{userId:B.customer.id}:{}}):void 0,Kn(!1),xn(!1);let Gt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),T=rl(H);if(ie==="auto"&&!R.current&&!Gt&&!T){R.current=!0;let D=d(H);try{if(await eo.current(B,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>D,sessionId:ve||B.id}),I)return;await D,I||un(!1);return}catch{if(I)return;await D,I||un(!1);return}}await d(H),I||un(!1)}catch(x){if(I)return;let H=hc(x,p);if(p&&k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),H){let{errorCode:gt,stage:Gt,...T}=H;nl(G,a,He,gt,Gt,T)}if(H?.stage==="provider_load"&&(_e??N?.data.session?.checkoutMode??"full")==="full"&&gc(N,K,C)){let gt=Xd({billingApiUrl:G,locale:s,telemetry:a});$e.current=gt,on(gt,null),_n(1),un(!1);return}let B=H?.stage==="provider_load",Z="session_request";B?Z="provider_load":u&&(Z="post_session");let ie=Vd(x,{stage:Z,provider:"stripe",sessionId:ve||void 0});(B||!(x instanceof vn))&&At(()=>ke.current?.(ie)),Tt(ie),un(!1)}}async function d(p){let{flopay:u,paypalFlopay:N,...x}=await Oi(p,{billingApiUrl:G,locale:s,telemetry:a});ut.current={publishableKey:x.publishableKey,paypalPublishableKey:x.paypalPublishableKey},on(u,N),_n(0)}return an(),_},[_e,Gn,Bn,kr,t,K,C]);let ho=In(async()=>{if(!Ve||En!==1)return;let I=et.current;_n(2);try{let{flopay:E,paypalFlopay:W}=await Oi(Ve,{billingApiUrl:G,locale:s,telemetry:a});if(et.current!==I)return;ce(),on(E,W),_n(0)}catch(E){if(et.current!==I)return;let{errorCode:W,stage:_,...De}=ws(E);nl(G,a,He,W,_,De)}},[ce,on,s,En,G,a,He,Ve]),Hr=!!(ve&&(g?.clientSecret||t)),Ut=bn||!Hr,rr=In(async()=>{if(!(bn||!Hr||!g)){Kt(!0),Xt(null);try{await Ce(g,{attempt3DS:!0,fallbackToFull:!0,sessionId:ve||g.id})}finally{Kt(!1)}}},[ve,bn,Hr,Ce,g]),jn=ru(Ve?.data.paypal,kt),wn=rl(Ve),$n=ur(()=>{if(!(!Ve||!g||!Ve.data.stripe?.publishableKey))return{billingApiUrl:G}},[Ve,g,G]),ze=!!(n&&!Ae&&Ne==="buttons"&&ne&&Bn==="full"),kn=!!(ve&&(Um(g?.vault)||ko(g))),$t=ur(()=>({session:g,loading:dn,error:nt,checkoutMode:Tn,inlineSessionDraft:Nt,applyInlineSessionPatch:ze?qr:void 0,inlineSessionPatchProcessing:pn,claimPending:An,claimRequiresIdentity:Nn,claimBuyerIdentity:jr,waitForDataAttachment:$r}),[g,dn,nt,Tn,Nt,ze,qr,pn,An,Nn,jr,$r]),to=!!n&&Ne==="buttons"&&!wn&&!kn&&(!mt||!$n),or=Ge?de(xr,{status:Ge,errorMessage:er,authorized:Mn}):null;if(dn&&!kn){if(c)return gn(Dr,{children:[c,or]});if(Ne==="buttons"){let I=ye?.buttonsLayout?.cardButton?.borderRadius??ye?.appearance.variables?.borderRadius??8,E=W=>de("div",{style:{height:W,borderRadius:I,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return gn(Dr,{children:[gn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[K&&E(_o),C&&(w||Ke)&&E(_o),C&&E(_o),de("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),or]})}return gn(Dr,{children:[gn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[de("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),de("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),or]})}return nt?y?de(Cr.Provider,{value:$t,children:y(nt)}):de(Cr.Provider,{value:$t,children:de("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:nt.message})}):to?gn(Dr,{children:[de(Cr.Provider,{value:$t,children:de(Zm,{onButtonClick:Ee,paymentMethodLayout:at,showPayPal:K,showStripe:C,showApplePay:w,showGooglePay:Ke,theme:Ie,buttonsTheme:Bt,buttonsStyles:xt,cardButtonContent:Re,cardBackButtonContent:Ye,cardTitleContent:it})}),or]}):wn&&g&&jn?gn(Dr,{children:[de(Cr.Provider,{value:$t,children:gn("div",{className:Ct,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ot&&de(na,{icon:!1,children:Ot}),Vt==="retrying"&&de("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Vt==="exhausted"&&gn("div",{role:"alert",children:[de("div",{children:"PayPal is temporarily unavailable. Please try again."}),de("button",{type:"button",onClick:Er,children:"Retry PayPal"})]}),Vt!=="exhausted"&&de("div",{"aria-hidden":Vt==="retrying"?!0:void 0,style:Vt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:de(Kc,{sessionId:ve,nonce:g.clientSecret||void 0,billingApiUrl:G,email:g.customer?.email||Nt?.account?.email,billingName:[g.customer?.firstName,g.customer?.lastName].filter(Boolean).join(" ")||[Nt?.account?.firstName,Nt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:jr,clientId:jn.clientId,environment:jn.environment,currency:(g.currency??"usd").toUpperCase(),isSubscription:g.mode==="subscription",providerObjectType:jn.providerObjectType,approvalPresentation:jn.approvalPresentation,existingOrderId:jn.existingOrderId,onComplete:S,onErrorChange:Xt,onDecline:F,onCancel:te,onButtonClick:Ee,runBeforeButtonClick:Wr,onInitializationStateChange:yr,allowAutomaticRetry:zn===0,session:g,telemetry:a,telemetryContext:He,onInstrument:Ht,debug:X},`${J}:paypal-init-${zn}`)})]})}),or]}):Tn==="confirm"?gn(Dr,{children:[de(Cr.Provider,{value:$t,children:de(wi,{flopay:mt,paypalFlopay:q,options:$n??{billingApiUrl:G},onInstrument:Ht,children:gn("div",{className:Ct,children:[Ot&&de("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ot}),Ft?Ft({onConfirm:rr,isProcessing:Ut}):de("button",{type:"button",onClick:rr,disabled:Ut,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ut?"not-allowed":"pointer",opacity:Ut?.6:1},children:bn?"Processing...":bt??"Confirm Purchase"})]})},J)}),or]}):(!mt||!$n)&&!(kn&&Tn==="full")?de(Dr,{children:or}):gn(Dr,{children:[de(Cr.Provider,{value:$t,children:gn(wi,{flopay:mt,paypalFlopay:q,options:$n??{billingApiUrl:G},onInstrument:Ht,children:[En===1&&de("button",{type:"button",onClick:ho,children:"Retry payment methods"}),Ae?gn(Dr,{children:[Ot&&de("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ot}),de(Xm,{sessionId:ve,nonce:g?.clientSecret||void 0,billingApiUrl:G,session:g,submitLabel:Qe,walletPresentation:ge,paymentMethodLayout:at,moreOptionsLabel:pt,children:Ae})]}):de(tl,{sessionId:ve,nonce:g?.clientSecret||void 0,telemetry:a,email:g?.customer?.email||Nt?.account?.email,userId:g?.customer?.id||Nt?.account?.userId,firstName:g?.customer?.firstName||Nt?.account?.firstName,lastName:g?.customer?.lastName||Nt?.account?.lastName,totalAmount:g?Math.round(Dm(g).total*100):0,currency:g?.currency?.toLowerCase()??"usd",onComplete:S,onError:P,onDecline:F,onCancel:te,error:Ot,onErrorChange:Xt,showPayPal:K,showStripe:C,walletPresentation:ge,enabledPaymentMethods:En?[]:ue??Ve?.data.stripe?.enabledPaymentMethods??g?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ve?.data.stripe?.enabledPaymentMethodCountries,showApplePay:w,showGooglePay:Ke,layout:Ne,paymentMethodLayout:at,moreOptionsLabel:pt,theme:Ie,buttonsTheme:Bt,buttonsStyles:xt,appearance:Te,cardButtonContent:Re,cardBackButtonContent:Ye,cardTitleContent:it,onButtonClick:Ee,onBeforeButtonClick:ne,onBuyerIdentityReady:jr,enableAVS:pe,...jt?{cardFieldOrder:jt}:{},...qe===void 0?{}:{showCardBrandIcons:qe},...lt===void 0?{}:{showCardFieldLabels:lt},...re===void 0?{}:{cardFieldLabels:re},...Me===void 0?{}:{cardFieldPlaceholders:Me},...Ze===void 0?{}:{cardAutoFocus:Ze},...V?{onCardFieldsReady:V}:{},...vt?{onCardFieldsFailed:vt}:{},...be===void 0?{}:{cardFieldsTimeoutMs:be},...Je?{cardPreFormSlot:Je}:{},avsLayout:Ue,country:g?.customer?.country,city:g?.customer?.city,state:g?.customer?.state,onCountryChange:ae,onZipChange:z,avsCheck:!!pe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:al(Ae,Ne),className:Ct,submitLabel:Qe,directPaypal:jn,isSubscription:g?.mode==="subscription",session:g,dataAttachmentPending:An,dataAttachmentRequiresIdentity:Nn,debug:X})]},J)}),or]})}function Xm({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,paymentMethodLayout:s,moreOptionsLabel:c,children:y}){return de(Dr,{children:Li.Children.map(y,S=>{if(!Li.isValidElement(S))return S;let P=S.props,f={};return P.sessionId||(f.sessionId=e),!P.nonce&&t&&(f.nonce=t),P.billingApiUrl||(f.billingApiUrl=n),P.submitLabel===void 0&&a!==void 0&&(f.submitLabel=a),P.walletPresentation===void 0&&(f.walletPresentation=i),P.paymentMethodLayout===void 0&&s!==void 0&&(f.paymentMethodLayout=s),P.moreOptionsLabel===void 0&&c!==void 0&&(f.moreOptionsLabel=c),o?.customer&&(P.email||(f.email=o.customer.email),P.userId||(f.userId=o.customer.id),P.firstName||(f.firstName=o.customer.firstName),P.lastName||(f.lastName=o.customer.lastName)),Object.keys(f).length===0?S:Li.cloneElement(S,f)})})}function Zm({onButtonClick:e,paymentMethodLayout:t,showPayPal:n,showStripe:o=!0,showApplePay:a,showGooglePay:i,theme:s,buttonsTheme:c,buttonsStyles:y,cardButtonContent:S,cardBackButtonContent:P,cardTitleContent:f}){let[F,te]=Wt(!1),ae=ur(()=>ou(s),[s]),z=ur(()=>{let w=ae?.buttonsLayout??qm(c);return y?{...w,...y,cardButton:{...w.cardButton,...y.cardButton},cardFormContainer:{...w.cardFormContainer,...y.cardFormContainer},backButton:{...w.backButton,...y.backButton},backButtonIcon:{...w.backButtonIcon,...y.backButtonIcon},submitButton:{...w.submitButton,...y.submitButton},title:{...w.title,...y.title}}:w},[ae,c,y]),K=ae?.buttonsLayout?.cardButton?.borderRadius??ae?.appearance.variables?.borderRadius??8,C=w=>de("div",{style:{height:w,borderRadius:K,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),ge=S===void 0?{boxSizing:"border-box",height:_o,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(F){let w=z.cardInputBorder??"#e5e7eb",Ke=z.cardInputBackground??"white",X=Ho(P),Ne=Ho(f);return gn("div",{style:{backgroundColor:z.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...z.cardFormContainer},children:[gn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[gn("button",{type:"button",onClick:()=>te(!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",...z.backButton},children:[de("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...z.backButtonIcon},children:de("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:de("path",{d:"M15 18l-6-6 6-6"})})}),de(Vo,{content:P})]}),Ne?de("div",{style:{flex:1}}):de("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...z.title},children:de(ka,{content:f})})]}),de("div",{style:{backgroundColor:Ke,border:`1px solid ${w}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:de("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),gn("div",{style:{display:"flex"},children:[de("div",{style:{flex:1,backgroundColor:Ke,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomLeftRadius:8,padding:12,height:45},children:de("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),de("div",{style:{flex:1,backgroundColor:Ke,borderTop:"none",borderRight:`1px solid ${w}`,borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomRightRadius:8,padding:12,height:45},children:de("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),de("div",{style:{backgroundColor:Ke,border:`1px solid ${w}`,borderRadius:8,marginTop:8,padding:12,height:45},children:de("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),de("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...z.submitButton,opacity:.5}}),de("style",{children:`
|
|
12
|
+
`}),ha&&no&&Ne("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Pe?-2:0},children:[Ne("button",{type:"button",onClick:qe,style:{display:"inline-flex",alignItems:"center",gap:ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ve.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ve.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ve.backButtonIcon},children:d("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:d("path",{d:"M15 18l-6-6 6-6"})})}),d(Yo,{content:Z})]}),Hl?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ve.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...ve.title},children:d(Ia,{content:le})})]}),!ha&&!Hl&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ys,order:Pe?-3:0,...ve.title},children:d(Ia,{content:le})}),Pe&&wt&&d("div",{style:{order:-2,width:"100%"},children:wt}),Pe&&oo&&Ne("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[d("div",{style:{backgroundColor:$o,border:`1px solid ${dr(ri)}`,borderRadius:an,padding:"10px"},children:d("input",{ref:ne,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Pr,onChange:r=>{qt("email"),T.current=r.target.value,Un(r.target.value)},onPointerDown:()=>qt("email"),onKeyDown:()=>qt("email"),onBlur:()=>{Jn("email")&&Fr(!0),Lo||Vi()},disabled:on,required:!0,"aria-invalid":ri||void 0,"aria-describedby":ri?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...ms}})}),ri&&d("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:va,children:$i.empty?"Email address is required":"Enter a valid email address"})]}),P&&d("div",{style:{order:Pe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=we,f=(F=!1)=>({backgroundColor:$o,border:`1px solid ${dr(F)}`,borderRadius:an,marginTop:"0.5rem",padding:"10px"}),E=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ms}),J=Oy(r);return Ne(Kn,{children:[nn(P.address_line_1,r)&&Ne(Kn,{children:[d("div",{style:f(tn("line1")),children:d("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:Qt,onChange:F=>{qt("line1"),$e.current.addressLine1=!0,zt.current=F.target.value,gr(F.target.value)},onPointerDown:()=>qt("line1"),onKeyDown:()=>qt("line1"),onBlur:()=>Vr("line1"),disabled:on,required:!0,"aria-invalid":tn("line1")||void 0,"aria-describedby":tn("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:E()})}),tn("line1")&&d("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:va,children:"Street address is required"})]}),nn(P.address_line_2,r)&&d("div",{style:f(),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:In,onChange:F=>{$e.current.addressLine2=!0,Dn.current=F.target.value,_r(F.target.value)},disabled:on,"data-testid":"flopay-address-line2",style:E()})}),(nn(P.city,r)||nn(P.state,r))&&Ne("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[nn(P.city,r)&&d("div",{style:{flex:1,backgroundColor:$o,borderTop:`1px solid ${dr(tn("city"))}`,borderRight:`1px solid ${dr(tn("city"))}`,borderBottom:`1px solid ${dr(tn("city"))}`,borderLeft:`1px solid ${dr(tn("city"))}`,padding:"10px",borderTopLeftRadius:an,borderBottomLeftRadius:an,...nn(P.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:an}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:hr,onChange:F=>{qt("city"),$e.current.city=!0,vn.current=F.target.value,En(F.target.value)},onPointerDown:()=>qt("city"),onKeyDown:()=>qt("city"),onBlur:()=>Vr("city"),disabled:on,required:!0,"aria-invalid":tn("city")||void 0,"aria-describedby":tn("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:E()})}),nn(P.state,r)&&d("div",{style:{flex:1,backgroundColor:$o,borderTop:`1px solid ${dr(tn("state"))}`,borderRight:`1px solid ${dr(tn("state"))}`,borderBottom:`1px solid ${dr(tn("state"))}`,borderLeft:`1px solid ${dr(tn("state"))}`,padding:"10px",borderTopRightRadius:an,borderBottomRightRadius:an,...nn(P.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${dr(tn("state")||tn("city"))}`}:{borderRadius:an}},children:J?Ne("select",{id:"flopay-billing-state",name:"billing-state",value:mn,onChange:F=>{qt("state"),$e.current.state=!0,Tn.current=F.target.value,_n(F.target.value)},onPointerDown:()=>qt("state"),onKeyDown:()=>qt("state"),onBlur:()=>Vr("state"),disabled:on,autoComplete:"billing address-level1",required:!0,"aria-invalid":tn("state")||void 0,"aria-describedby":tn("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...E(),cursor:"pointer"},children:[d("option",{value:"",children:Us(r)}),J.map(F=>d("option",{value:F.code,children:F.name},F.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Us(r),autoComplete:"billing address-level1",value:mn,onChange:F=>{qt("state"),$e.current.state=!0,Tn.current=F.target.value,_n(F.target.value)},onPointerDown:()=>qt("state"),onKeyDown:()=>qt("state"),onBlur:()=>Vr("state"),disabled:on,required:!0,"aria-invalid":tn("state")||void 0,"aria-describedby":tn("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:E()})})]}),tn("city")&&d("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:va,children:"City is required"}),tn("state")&&Ne("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:va,children:[Us(r)," is required"]}),(nn(P.country,r)||nn(P.postal_code,r))&&Ne("div",{style:{display:"flex",flexDirection:Me==="column"?"column":"row",gap:Me==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[nn(P.country,r)&&d("div",{style:{flex:Me==="row"?1:void 0,backgroundColor:$o,borderTop:`1px solid ${Pa}`,borderRight:`1px solid ${Pa}`,borderBottom:`1px solid ${Pa}`,borderLeft:`1px solid ${Pa}`,padding:"10px",...Me==="row"&&nn(P.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:an,borderBottomLeftRadius:an,borderRight:"none"}:{borderRadius:an}},children:Ne("select",{id:"flopay-billing-country",name:"billing-country",value:we,onChange:F=>{$e.current.country=!0,Ut.current=F.target.value,tr(F.target.value),_e?.(F.target.value),Tn.current="",_n("")},disabled:on,autoComplete:"billing country","data-testid":"flopay-country",style:{...E(),cursor:"pointer"},children:[we===""?d("option",{value:"",children:"Select country"}):null,Iy.map(F=>Ne("option",{value:F.code,children:[F.flag," ",F.name]},F.code))]})}),nn(P.postal_code,r)&&d("div",{style:{flex:Me==="row"?1:void 0,backgroundColor:$o,border:`1px solid ${Eu}`,padding:"10px",...Me==="row"&&nn(P.country,r)?{borderRadius:"0",borderTopRightRadius:an,borderBottomRightRadius:an}:{borderRadius:an}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Vs(we),autoComplete:"billing postal-code",value:St,onChange:F=>{qt("zip"),$e.current.zip=!0,fn.current=F.target.value,Bn(F.target.value),st?.(F.target.value)},onPointerDown:()=>qt("zip"),onKeyDown:()=>qt("zip"),onBlur:()=>{Jn("zip")&&xr(!0)},disabled:on,required:An.required,"aria-invalid":oi||void 0,"aria-describedby":oi?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:E()})})]}),oi&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:va,children:An.empty?`${Vs(r)} is required`:Rm(r)})]})})()}),Pe&&xu,Yt&&d(oa,{margin:"0.75rem 0",styleOverride:ve.errorBanner,children:Yt})]}),ai={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=r=>q?!se||!Lr?d("pre",{"data-testid":r,style:ai,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":r,style:ai,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${se}`,` directPaypalConfigured=${Lr}`,` inAppBrowserDetected=${String(ei)}`,` shouldRenderDirectPayPal=${So}`,` shouldRenderStripePayPal=${wo}`,` hasPaypalStripeInstance=${!!fl}`].join(`
|
|
13
|
+
`)}):null,Xl=r=>q?!I||!or?d("pre",{"data-testid":r,style:ai,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":r,style:ai,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${I}`,` currency=${ct}`,` amountInCents=${ya}`,` enabledPaymentMethods: ${JSON.stringify(G??[])}`,` enabledPaymentMethodsProvided=${ma}`,` hasEnabledMethods=${Ja}`,` expressMethods: ${JSON.stringify(Za)}`,` walletExpressMethods: ${JSON.stringify(jo)}`,` paymentElementMethods: ${JSON.stringify(es)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Qa)}`,` hasStripeInstance=${!!or}`,` shouldRenderWallets=${ao}`,` shouldRenderPaymentElement=${ko}`].join(`
|
|
14
|
+
`)}):null,Zl=Fe==="apm-expanding"||Fe==="apm-form"||Fe==="apm-collapsing",Ko;Fe==="apm-expanding"?Ko=_d:Fe==="apm-collapsing"&&(Ko=Td);let ii=$t?$d(ts,$t,At):null,Ql={label:Dt||md,open:Hn,onOpen:Dr,color:io,fontFamily:Wn?.fontFamily};if(Re==="buttons"){let r=Fe==="buttons"||Fe==="expanding"||Fe==="apm-expanding",f=Fe==="expanding"||Fe==="card"||Fe==="collapsing",E=Ie===void 0?{boxSizing:"border-box",height:Eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},J;Fe==="expanding"||Fe==="apm-expanding"?J=bm:(Fe==="collapsing"||Fe==="apm-collapsing")&&(J=Cm);let F;Fe==="expanding"?F=_d:Fe==="collapsing"&&(F=Td);let ue=yt&&Sd(yt,{canHide:()=>!0,available:Nl}),It={paypal:Ne(Kn,{children:[So&&Qe&&Ne(Kn,{children:[fe&&d("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."}),d(Aa.Provider,{value:O,children:d(bi,{sessionId:e,nonce:t,billingApiUrl:pt,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,clientId:Qe.clientId,environment:Qe.environment,currency:ct.toUpperCase(),isSubscription:et,providerObjectType:Fn,approvalPresentation:ti==="popup"?void 0:ti,onTokenizedBody:Qn,onComplete:l,onErrorChange:ge,onDecline:m,onCancel:R,onTechnicalFailure:zo,onButtonClick:je,runBeforeButtonClick:Sr,isProcessing:on,onLoadStateChange:as,onInitializationStateChange:is,session:Mt,existingOrderId:fe?.orderId,debug:q},fe?.orderId??"fresh")})]}),wo&&d(uo,{stripe:fa,options:Pl,children:d(Ad,{sessionId:e,nonce:t,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,onTokenizedBody:Qn,onErrorChange:ge,isProcessing:on,onButtonClick:je,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Ml,placeholderBorderRadius:Yr,popupCapabilityOwner:O,externalTelemetryContext:Ol,presentationMode:qo})})]}),wallets:Ne(Kn,{children:[ao?d(uo,{stripe:or,options:hl,children:d(xd,{sessionId:e,nonce:t,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,intentKind:_t>0?"payment":"setup",expressMethods:jo,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:je,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Al,placeholderBorderRadius:Yr,popupCapabilityOwner:O,externalTelemetryContext:ut})}):null,!ao&&Dl?d("div",{style:{height:Eo,borderRadius:Yr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:d(Kn,{children:ko&&d(Fd,{sessionId:e,nonce:t,email:mt.email,billingName:[mt.firstName,mt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,paymentElementMethods:Qa,stripeInstance:or,paymentElementBaseOptions:ts,futureUseSession:At,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:je,onDecline:m,runBeforeButtonClick:Sr,onLoadStateChange:xl,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,onExpandApm:Y,expandedApmMethod:$t,themeId:be,buttonAppearance:{backgroundColor:ve.cardButton?.backgroundColor,borderColor:ve.cardInputBorder,textColor:ve.cardButton?.color,borderRadius:Yr}})}),card:d(Kn,{children:Pe&&d("button",{type:"button",onClick:async()=>{on||!(await Sr("card")).proceed||(je?.("card"),W())},disabled:on,style:{width:"100%",...E,...ve.cardButton,...tl({themeBundle:Zn,resolvedPrimaryColor:io,resolvedBorderRadius:an,submitButtonStyle:ve.submitButton,explicitPrimaryColor:Wn?.colorPrimary}),fontSize:ve.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:on?"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:on?.6:1},onMouseEnter:Et=>{!on&&(Zn||Wn?.colorPrimary)&&(Et.currentTarget.style.backgroundColor=Mu)},onMouseLeave:Et=>{(Zn||Wn?.colorPrimary)&&(Et.currentTarget.style.backgroundColor=io)},onMouseDown:Et=>{Et.currentTarget.style.transform="scale(0.985)"},onMouseUp:Et=>{Et.currentTarget.style.transform="scale(1)"},children:d(Go,{content:Ie})})})};return Ne("form",{onSubmit:cs,className:te,noValidate:!0,style:{position:"relative"},children:[d(ui,{}),U&&d(Ur,{status:U,errorMessage:Yt,authorized:Rt}),Ne("div",{style:{display:"grid"},children:[Ne("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!J?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!J?wm:{},...J?{animation:J,pointerEvents:"none"}:{}},children:[Jl("flopay-direct-paypal-gate-debug"),Xl("flopay-stripe-gate-debug"),rn&&ue?Ne(Kn,{children:[rn.filter(({group:Et})=>ue.inView.includes(Et)).map(({group:Et,key:Le})=>d(ja.Fragment,{children:It[Et]},Le)),ue.behindLink.length>0&&d(Ls,{...Ql,showLink:ue.showLink,children:rn.filter(({group:Et})=>ue.behindLink.includes(Et)).map(({group:Et,key:Le})=>d(ja.Fragment,{children:It[Et]},Le))})]}):d(Ns,{rows:Ll,borderRadius:Yr}),Yt&&Fe==="buttons"&&d(oa,{margin:"0.25rem 0",styleOverride:ve.errorBanner,children:Yt})]}),Pe&&f&&d("div",{style:{gridArea:"1 / 1",...F?{animation:F}:{},...Fe==="collapsing"?{pointerEvents:"none"}:{}},children:hs}),I&&Zl&&$t&&ii&&or&&d("div",{style:{gridArea:"1 / 1",...Ko?{animation:Ko}:{},...Fe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ne("div",{style:{backgroundColor:us,borderRadius:gs,...Ca,padding:fs},children:[Ne("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ne("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:de,style:{display:"inline-flex",alignItems:"center",gap:ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ve.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ve.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ve.backButtonIcon},children:d("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:d("path",{d:"M15 18l-6-6 6-6"})})}),d(Yo,{content:Z})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ve.titleFontSize??"1.05rem",color:ys,paddingRight:80,...ve.title},children:`Pay with ${Wa($t)}`})]}),d(uo,{stripe:or,options:ii,children:d(Js,{method:$t,sessionId:e,nonce:t,email:mt.email,billingName:[mt.firstName,mt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,onTokenizedBody:Qn,onErrorChange:ge,onDecline:m,onCancel:de,runBeforeButtonClick:Sr,onButtonClick:je,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,errorText:Yt})},$t)]})})]})]})}if(Zl&&$t&&ii&&or&&I)return Ne("form",{onSubmit:cs,className:te,noValidate:!0,style:{position:"relative"},children:[d(ui,{}),U&&d(Ur,{status:U,errorMessage:Yt,authorized:Rt}),d("div",{style:{...Ko?{animation:Ko}:{},...Fe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ne("div",{style:{backgroundColor:us,borderRadius:gs,...Ca,padding:fs},children:[Ne("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ne("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:de,style:{display:"inline-flex",alignItems:"center",gap:ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ve.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ve.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ve.backButtonIcon},children:d("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:d("path",{d:"M15 18l-6-6 6-6"})})}),d(Yo,{content:Z})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ve.titleFontSize??"1.05rem",color:ys,paddingRight:80,...ve.title},children:`Pay with ${Wa($t)}`})]}),d(uo,{stripe:or,options:ii,children:d(Js,{method:$t,sessionId:e,nonce:t,email:mt.email,billingName:[mt.firstName,mt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,onTokenizedBody:Qn,onErrorChange:ge,onDecline:m,onCancel:de,runBeforeButtonClick:Sr,onButtonClick:je,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,errorText:Yt})},$t)]})})]});let ec=Su||bu||wu,ba=yt&&Sd(yt,{canHide:r=>r!=="card",available:Nl}),tc={paypal:Ne(Kn,{children:[So&&Qe&&Ne(Kn,{children:[fe&&d("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."}),d(Aa.Provider,{value:O,children:d(bi,{sessionId:e,nonce:t,billingApiUrl:pt,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,clientId:Qe.clientId,environment:Qe.environment,currency:ct.toUpperCase(),isSubscription:et,providerObjectType:Fn,approvalPresentation:ti==="popup"?void 0:ti,onTokenizedBody:Qn,onComplete:l,onErrorChange:ge,onDecline:m,onCancel:R,onTechnicalFailure:zo,onButtonClick:je,runBeforeButtonClick:Sr,isProcessing:on,onLoadStateChange:as,onInitializationStateChange:is,session:Mt,existingOrderId:fe?.orderId,debug:q},fe?.orderId??"fresh")})]}),wo&&d(uo,{stripe:fa,options:Pl,children:d(Ad,{sessionId:e,nonce:t,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,onTokenizedBody:Qn,onErrorChange:ge,isProcessing:on,onButtonClick:je,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Ml,placeholderBorderRadius:Yr,popupCapabilityOwner:O,externalTelemetryContext:Ol,presentationMode:qo})})]}),wallets:d(Kn,{children:ao&&d(uo,{stripe:or,options:hl,children:d(xd,{sessionId:e,nonce:t,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,intentKind:_t>0?"payment":"setup",expressMethods:jo,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:je,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Al,placeholderBorderRadius:Yr,popupCapabilityOwner:O,externalTelemetryContext:ut})})}),apms:d(Kn,{children:ko&&d(Fd,{sessionId:e,nonce:t,email:mt.email,billingName:[mt.firstName,mt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,paymentElementMethods:Qa,stripeInstance:or,paymentElementBaseOptions:ts,futureUseSession:At,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:je,onDecline:m,runBeforeButtonClick:Sr,onLoadStateChange:xl,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,themeId:be,onExpandApm:Y,expandedApmMethod:$t,buttonAppearance:{backgroundColor:ve.cardButton?.backgroundColor,borderColor:ve.cardInputBorder,textColor:ve.cardButton?.color,borderRadius:Yr}})})};return Ne("form",{onSubmit:cs,className:te,noValidate:!0,style:{position:"relative"},children:[d(ui,{}),U&&d(Ur,{status:U,errorMessage:Yt,authorized:Rt}),rn===null?d(Ns,{rows:Ll,borderRadius:Yr}):Ne(Kn,{children:[yn&&Pe&&hs,yn&&Pe&&ec&&d(vs,{label:"or pay another way"}),Ne("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Jl("flopay-direct-paypal-gate-debug-default"),Xl("flopay-stripe-gate-debug-default"),rn.map(({group:r,key:f})=>r==="card"||!ba?.inView.includes(r)?null:d(ja.Fragment,{children:tc[r]},f)),ba&&ba.behindLink.length>0&&d(Ls,{...Ql,showLink:ba.showLink,children:rn.map(({group:r,key:f})=>ba.behindLink.includes(r)&&r!=="card"?d(ja.Fragment,{children:tc[r]},f):null)})]}),!yn&&Pe&&ec&&d(vs,{label:"or pay with card"}),!yn&&Pe&&hs]})]})}import{Fragment as jr,jsx as ie,jsxs as Pn}from"react/jsx-runtime";var xo=44,sl="flopay_checkout_saved_payment_resume",Km="paypal_resume_nonce_missing",qi=new Map,Li=new Map;function Jd(e,t){t.settled&&t.consumers===0&&qi.get(e)===t&&qi.delete(e)}function Hm(e,t,n){let o=Li.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};Li.set(e,i);let l=()=>{Li.get(e)===i&&Li.delete(e)};return a.then(l,l),a}function Ha(e){return new Promise(t=>setTimeout(t,e))}function zi(e,t,n){let o=vi({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:su,enabled:t!==!1});return o.beginCheckout(n),o}function Va(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function rl(e,t,n,o,a,i){let l=zi(e,t,n);l.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Va(l)}function Xd(e,t,n,o){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()-n),durationMode:"machine",requestCategory:t,...o===void 0?{}:{attempt:o},statusClass:"2xx"})}function Zd(e,t,n,o,a){let i=ou(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-o),durationMode:"machine",requestCategory:n,attempt:a,statusClass:i.statusClass}),t instanceof kn&&t.code==="session_auto_completed"?!1:t instanceof kn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function ol(e){return!e||e.data.stripe?.publishableKey?!1:!!au(e.data.paypal)?.clientId}var Vm={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Qd(e){return new Bm(Vm,{publishableKey:"provider_unavailable",...e})}async function Ni(e,t){let{publishableKey:n,paypalPublishableKey:o}=Ds(e);return{...await Os({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function eu(e){let t=e.data.stripe;return JSON.stringify([t?.publishableKey??null,t?.paypalPublishableKey??null])}function ll(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Gm(){if(!ll())return null;try{let e=window.sessionStorage.getItem(sl);return e?JSON.parse(e):null}catch{return null}}function tu(e){if(ll())try{window.sessionStorage.setItem(sl,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function al(){if(ll())try{window.sessionStorage.removeItem(sl)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Ym(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let o of t)e.searchParams.has(o)&&(e.searchParams.delete(o),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function nu(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 il(e,t){return $m(!!e,t)}function Jm(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function ru(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Xm(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 cl({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:l,loading:u,error:m,onComplete:R,onError:C,onInstrument:g,onDecline:A,onCancel:X,onCountryChange:te,onZipChange:D,showPayPal:K=!0,showStripe:w=!0,walletPresentation:pe="auto",enabledPaymentMethods:se,showApplePay:I=!0,showGooglePay:We=!0,debug:G=!1,layout:Ue,paymentMethodLayout:rt,moreOptionsLabel:dt,theme:Re,buttonsTheme:Nt,buttonsStyles:Dt,cardButtonContent:be,cardBackButtonContent:He,cardTitleContent:ot,showSecurityFooter:at,onButtonClick:Ie,onBeforeButtonClick:Z,enableAVS:le,cardFieldOrder:Kt,showCardBrandIcons:je,showCardFieldLabels:it,cardFieldLabels:Q,cardFieldPlaceholders:Te,cardAutoFocus:Xe,onCardFieldsReady:H,onCardFieldsFailed:ht,cardFieldsTimeoutMs:Ce,cardPreFormSlot:Ve,avsLayout:ze,submitLabel:Ze,className:Pt,initialErrorMessage:De=null,initialPayPalOrderId:wt,children:Me,checkoutMode:Ee,confirmLabel:vt,renderConfirmButton:Ot,onSessionCompleted:kt}){let V=qm(o),ce=mr(()=>iu(Re),[Re]),_e=i??ce?.appearance,st=n?"embedded_checkout":"standard_checkout",lt=il(Me,Ue),[Ke,Ct]=Jt(null),_t=Bt(null),ct=pn(v=>{_t.current=v,Ct(v)},[]),[Ae,Qe]=Jt(null),et=Bt(null),z=Bt(null),Ht=Bt(0),[k,q]=Jt(null),j=Bt(null),[y,oe]=Jt(null),h=mr(()=>n?Ba(n):"",[n]),$=n?`create:${h}`:`session:${e??""}`,O=ru(y),he=Bt(new Set),Se=Bt($),_=Bt($);wa(()=>{_.current=$,Se.current!==$&&(Se.current=$,he.current.clear())},[$]);let ut=pn(v=>{if(_.current===$){if(Uc.has(v.name)){if(he.current.has(v.name))return;he.current.add(v.name)}Ft(()=>g?.(v))}},[$,g]),Mt=na(ut,$),At=Bt(!1),Fn=pn(v=>{if(At.current)return;let s=v.gateway||!O?v:{...v,gateway:O};ut(s)},[ut,O]);ir(()=>{Mt({class:"lifecycle",name:"checkout.mount"})},[Mt]);let[Ge,fr]=Jt(e??""),bt=e??Ge,Er=n?"":bt,[pt,yt]=Jt(!0),[Rn,Hn]=Jt(null),[Vn,rn]=Jt(0),[yn,Xt]=Jt("full"),[Zt,Nn]=Jt(!1),[xe,we]=Jt(De),[tr,St]=Jt(null),[Bn,Qt]=Jt(null),[gr,In]=Jt(!1),[_r,hr]=Jt(void 0),[En,mn]=Jt(""),[_n,Pr]=Jt(!1),[Un,zn]=Jt(!1),[qn,fn]=Jt(!1),Ut=Bt(null),zt=Bt(0),Dn=Bt(void 0),[vn,Tn]=Jt("loading"),[T,$e]=Jt(0),P=Bt(!1),ae=Bt(!1),Rt=Bt(!1),xt=Bt(null),Vt=Bt({active:!0});ir(()=>{let v={active:!0};return Vt.current=v,()=>{v.active=!1}},[]);let ye=Bt(null),en=mr(()=>({checkoutMode:Ee??yn,layout:Jm(Me,Ue)}),[Ee,Me,yn,Ue]),Wr=Bt(R);Wr.current=R;let Mn=Bt(C);Mn.current=C;let Pe=Bt(A);Pe.current=A;let Tr=pn(v=>Ii(xt,async s=>{try{return await v(s)}catch(c){throw s.aborted?ia(c):c}}),[]);ir(()=>()=>{xt.current?.abort(),xt.current=null},[]);let Cn=pn((v,s)=>{et.current=v,Qe(v),j.current=s,q(s)},[]),sr=pn(()=>{let v=z.current;v&&(z.current=null,v.destroy())},[]),Po=pn(()=>{let v=et.current,s=j.current;!v&&!s||(Cn(null,null),rn(0))},[Cn]),Gn=pn(v=>{let s=_t.current,c=s?Kd(s,v):v;ct(c),c.data.session&&oe(c.data.session),c.data.stripe?.publishableKey||Po()},[Po,ct]),[nr,Mr]=Jt(null);ir(()=>{!nr||Ae!==nr.flopay||(Mr(null),nr.apply())},[Ae,nr]);let jn=pn(async(v,s,c)=>{let p=null;try{p=await Ni(v,{billingApiUrl:V,locale:l,telemetry:a})}catch{p=null}if(!s())return;if(sr(),p){xc([p.flopay?.getRawProvider(),p.paypalFlopay?.getRawProvider()],[et.current?.getRawProvider(),j.current?.getRawProvider()]),Cn(p.flopay,p.paypalFlopay),rn(0),Mr({flopay:p.flopay,apply:c});return}let W=Qd({billingApiUrl:V,locale:l,telemetry:a});z.current=W,Cn(W,null),rn(1),c()},[sr,Cn,l,V,a]);ir(()=>{hn(Ae)?.setCheckoutContext(en),k&&k!==Ae&&hn(k)?.setCheckoutContext(en)},[Ae,k,en]);let Ar=Bt(kt);Ar.current=kt;let vr=pn(v=>{Tn(v),!(v!=="exhausted"||Rt.current)&&(Rt.current=!0,Mn.current?.(new kn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),lr=pn(()=>{Tn("retrying"),$e(v=>v+1)},[]);ir(()=>{Tn("loading"),$e(0),Rt.current=!1},[bt]),ir(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:su,checkout_type:st,checkout_layout:lt,billing_api_url:V})},[lt,st,V]);let Yn=mr(()=>n?Ba(n,!0):"",[n]),ke=mr(()=>En===Yn?_r:void 0,[_r,En,Yn]),An=mr(()=>n?Rs(n,ke):void 0,[n,ke]),$n=Ee??An?.checkoutMode??"full",ln=mr(()=>An?{...An,checkoutMode:$n}:void 0,[An,$n]);ir(()=>{hr(void 0),mn(Yn),Dn.current=void 0,Ut.current=null,fn(!1)},[Yn]),ir(()=>{we(De)},[De]);let cr=pn((v,s,c)=>{Ft(()=>{Pe.current?.(gn(v,s,c))})},[]),rr=pn(async(v,s)=>{let c=Vt.current;if(!c.active)return!1;we(null),Qt(null),In(!1),St("processing");let p=s?.sessionId??v.id,W=v.clientSecret||t,qe=ru(v),Y=et.current??j.current,de=hn(Y),U=Y?null:zi(V,a,en),S={log:N=>{de?de.log(N):U?.log(N)},error:N=>{de?de.error(N):U?.error(N)},terminal:N=>{de?de.terminal(N):U?.terminal(N)},performance:N=>{de?de.performance(N):U?.performance(N)},now:()=>de?.now()??U?.now()??0,elapsed:N=>de?.elapsed(N)??Math.max(0,(U?.now()??N)-N)},ne=S.now(),me=!!(s?.initialAutoProcessingError||s?.initialAutoProcessingPending),b=!1,M,x=()=>{b||(b=!0,me=!0,M=S.now(),S.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},L=!1,re=()=>{L||(L=!0,S.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),S.performance({stage:"processing",durationMs:S.elapsed(ne),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),M!==void 0&&S.performance({stage:"recovery",durationMs:S.elapsed(M),durationMode:"machine",paymentMethodCategory:"saved"}))};S.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),At.current=!0;try{S.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{At.current=!1}Mt({class:"lifecycle",name:"payment.processing.started",provider:qe}),me&&x();let Oe;try{let N=ld(s?.initialAutoProcessingError),fe=s?.initialAutoProcessingError?.type==="3ds_required"&&!Um(s.initialAutoProcessingError)&&!s.initialAutoProcessingError.threeDSecureToken&&s.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:s.initialAutoProcessingError.nextActionRedirectUrl}:null,Ye,Sn=jt=>{x();let Lt=Ua(V,p,v,a!==!1);return Tr(Gt=>sa(jt,{billingApiUrl:V,sessionId:p,nonce:W,session:v,signal:Gt,...Lt.telemetry?{challengeTelemetry:Lt.telemetry}:{}})).finally(Lt.release)};if(fe)Ye=await Sn(fe);else if(N)x(),N.type==="paypal_redirect_required"&&ye.current?.publishableKey&&tu({sessionId:p,publishableKey:ye.current.publishableKey,paypalPublishableKey:ye.current.paypalPublishableKey,nonce:W}),Ye=await Tr(jt=>_i(N,{flopay:et.current,paypalFlopay:j.current,attempt3DS:s?.attempt3DS,billingApiUrl:V,sessionId:p,session:v,telemetry:!1,signal:jt})),N.type==="paypal_redirect_required"&&al();else if(s?.initialAutoProcessingPending){let jt=s.initialAutoProcessingPending,Lt=new Oi(V,{telemetry:!1}),Gt=await Tr(ve=>Lt.waitForCheckoutSessionCompletion(jt.sessionId,{initialDelayMs:jt.retryAfterMs,nonce:W,statusUrl:jt.statusUrl,signal:ve})),Yt=co(Gt,v),Zn=Gt.autoProcessingError?.type==="3ds_required"&&Gt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Gt.autoProcessingError.nextActionRedirectUrl}:null;if(Zn)Ye=await Sn(Zn);else{if(!Xr(Yt))throw Zo(Yt);Ye=Jr(Yt,p)}}else{if(s?.initialAutoProcessingError)throw zr(s.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:s.initialAutoProcessingError.checkoutMethod});if(s?.fromCreateSession)return s?.fallbackToFull&&(Xt("full"),nu("full")),!1;{let jt=await la({billingApiUrl:V,sessionId:p,session:v,nonce:W,telemetry:!1});if(!c.active&&jt.type!=="success")return!1;jt.type==="success"?Ye=jt.result:jt.type==="next_action_required"?Ye=await Sn(jt):(x(),jt.type==="paypal_redirect_required"&&ye.current?.publishableKey&&tu({sessionId:p,publishableKey:ye.current.publishableKey,paypalPublishableKey:ye.current.paypalPublishableKey,nonce:W}),Ye=await Tr(Lt=>_i(jt,{flopay:et.current,paypalFlopay:j.current,attempt3DS:s?.attempt3DS,billingApiUrl:V,sessionId:p,session:v,telemetry:!1,signal:Lt})),jt.type==="paypal_redirect_required"&&al())}}if(p&&aa(p),!c.active)return!1;re(),me&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),S.terminal({outcome:Ye.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),In(Ye.status==="authorized"),St("success"),await Ha(600),Oe=()=>Wr.current?.(Ye)}catch(N){if(!c.active)return!1;let fe=lo(za(N),p);if(fe.code==="three_ds_aborted")return!1;let Ye=fe.checkoutMethod??Na;we(fe.message),Qt(fe.message),In(!1),s?.fallbackToFull&&(S.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Xt("full"),nu("full")),re();let Sn=fe.statusCode===void 0?void 0:Wm(fe.statusCode,"unknown"),jt=Sn==="4xx"?{requestCategory:"process_payment",statusClass:Sn}:{},Lt=Sn===void 0||Sn==="4xx";if(Vd(fe))S.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...jt});else if(Lt&&(fe.telemetryOutcome==="validation_rejected"||fe.type==="validation_error"))S.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...jt});else{let Zn=ou(N,me?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),ve=fe.telemetryRequestCategory??"process_payment";At.current=!0;try{S.error({...Zn,...fe.telemetryFailureCategory?{failureCategory:fe.telemetryFailureCategory}:{},stage:me?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:ve})}finally{At.current=!1}Mt({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:ve,provider:qe})}return Hd(fe)?cr(Ye,fe,{code:fe.code,declineCode:fe.declineCode}):Ft(()=>Mn.current?.(fe)),St("error"),await Promise.allSettled([Ha(400),s?.ensureProvidersReady?s.ensureProvidersReady():Promise.resolve()]),me&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{re(),U&&Va(U),c.active&&(St(null),Qt(null))}return c.active?(Ft(Oe),!0):!1},[cr,Mt,t,V,Tr,a,en]);ir(()=>{if(typeof window>"u"||ae.current)return;let v=new URLSearchParams(window.location.search),s=v.get("payment_intent_client_secret");if(!s)return;let c=Gm();c&&(ae.current=!0,(async()=>{await Promise.resolve();let p,W=0;we(null),Qt(null),St("processing"),Nn(!0);try{if(v.get("redirect_status")==="failed")throw Object.assign(new kn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:qe,paypalFlopay:Y}=await Os({publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey,billingApiUrl:V,locale:l,telemetry:a});p=hn(Y??qe),p?.setCheckoutContext(en),W=p?.now()??0,p?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),p?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let de=(Y??qe)?.getRawProvider();if(!de)throw Object.assign(new kn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:U,error:S}=await de.retrievePaymentIntent(s);if(S)throw Object.assign(new kn(S.message??"Failed to retrieve PayPal payment status.","api_error",{code:S.code}),{checkoutMethod:"paypal"});let ne=Rc(U?.status);if(!U||ne==="failed")throw Object.assign(new kn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let me=typeof U.payment_method=="string"?U.payment_method:U.payment_method?.id,b=ne;if(c.sessionId){let M=c.nonce||t;if(!M)throw Object.assign(new kn("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:Km}),{checkoutMethod:"paypal"});let re=(await new Oi(V,{telemetry:!1}).getUnifiedCheckoutSession(c.sessionId,M)).data.session;if(re&&re.status!=="complete"){let Oe=await la({billingApiUrl:V,sessionId:c.sessionId,session:re,nonce:M,telemetry:!1,tokenizedData:{id:me??U.id,type:"card",threeDSecureActionResultTokenId:U.id,isPaypal:!0}});if(Oe.type!=="success")throw Object.assign(new kn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});b=Oe.result.status}}c.sessionId&&aa(c.sessionId),p?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),p?.performance({stage:"redirect_resume",durationMs:p.elapsed(W),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),p?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),St("success"),await Ha(600),Ft(()=>Wr.current?.({status:b,paymentIntentId:U.id,paymentMethodId:me,checkoutMethod:"paypal"}))}catch(qe){let Y=lo(za(qe),c.sessionId),de=Y.checkoutMethod??"paypal",U=Vd(Y);if(p)p.performance({stage:"redirect_resume",durationMs:p.elapsed(W),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),U?p.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):p.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(U){let S=zi(V,a,en);S.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Va(S)}else rl(V,a,en,"REDIRECT_RESUME_FAILED","redirect_resume");we(Y.message),Qt(Y.message),Hd(Y)?cr(de,Y,{code:Y.code,declineCode:Y.declineCode}):Ft(()=>Mn.current?.(Y)),St("error"),await Ha(400)}finally{al(),Ym(),St(null),Qt(null),Nn(!1)}})())},[cr,l,t,V,a,en]);let Kr=Bt(null),xr=mr(()=>ln?Ba(ln):"",[ln]),vo=Bt(ln);vo.current=ln,ir(()=>{fr(e??"")},[e]),ir(()=>{P.current=!1,we(De),Qt(null),In(!1),St(null)},[xr,De,e]);async function Fr(v,s,c){let p=zi(V,a,en),W=new Oi(V,{telemetry:!1,stripeAccountSwitch:!0}),qe=!1;try{let Y=v.idempotencyKey===void 0?void 0:Gd(v.idempotencyKey),de=Zc(s,c),U=Xc(s,c);de?.canonicalIdentity===c&&U&&U.canonicalIdentity===void 0&&(wi(s,c,U.idempotencyKey),U={...U,canonicalIdentity:c});let S=Y??(U?.canonicalIdentity===c?U.idempotencyKey:void 0),ne,me=!1;p.log({name:de?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let b=de?.sid??null,M=null,x,L,re=!1;if(b)try{M=await W.getUnifiedCheckoutSession(b,de?.nonce),de&&de.canonicalIdentity===void 0&&(Jc(M.data.session,v)?(ki(s,c,b,de.nonce??M.data.session?.clientSecret),U&&U.canonicalIdentity===void 0&&(wi(s,c,U.idempotencyKey),S??(S=U.idempotencyKey))):(Si(s,c),U=null,S=Y,b=null,M=null));let N=M?.data.session?.status,fe=M?.data.session,Ye=fe?.clientSecret||de?.nonce;if(b&&fe?.buyerIdentified===!1&&Ye&&(L=Xo(W,b,Ye,v.account)),b&&M&&N==="complete"){if(xs(b))return{sid:b,result:M};Si(s,c),b=null,M=null,me=!0}}catch{p.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),de?.canonicalIdentity===void 0?(Si(s,c),S=Y):As(s,c),b=null}if(!b){!Y&&(me||!S)&&(S=Gd(),ne=S),S&&wi(s,c,S);let N=p.now(),fe=0;p.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ye={...v,idempotencyKey:S,avsCheck:!!le,avsConfig:typeof le=="object"?le:void 0,checkoutType:"embedded_checkout",checkoutLayout:il(Me,Ue)};Object.defineProperty(Ye,Dm,{configurable:!1,enumerable:!1,value:{onAttempt:Lt=>{fe=Math.max(fe,Lt)}}});let Sn=()=>{Xd(p,"session_create",N,fe)},jt=Lt=>{Zd(p,Lt,"session_create",N,fe)&&Mt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(v.checkoutMode==="confirm"||v.checkoutMode==="auto")&&nd();try{if(Nm(Ye)){let Lt=await W.createDetachedSession(Ye);Lt.claimed.catch(()=>{}),M=Lt.shell,b=Lt.sessionId,L=Lt.claim;let Gt=p.now();p.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),x=Lt.claimed.then(Yt=>{let Zn=Yt.data.session?.id??Lt.sessionId;return Zn&&ki(s,c,Zn,Yt.data.session?.clientSecret??Lt.nonce),Xd(p,"session_claim",Gt),Sn(),Yt},Yt=>{throw As(s,c),Zd(p,Yt,"session_claim",Gt,0)&&Mt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Yt}).finally(()=>Va(p)),x.catch(()=>{}),qe=!0,p.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),p.performance({stage:"session_shell",durationMs:p.now()-N,durationMode:"machine",requestCategory:"session_create",attempt:fe,statusClass:"2xx",paymentMethodCategory:"card"})}else M=await W.createAndFetchSession(Ye),Sn()}catch(Lt){throw jt(Lt),Lt}b=M.data.session?.id??b??"",b&&!x&&ki(s,c,b,M.data.session?.clientSecret)}let Oe=M?.data.session;return!L&&b&&Oe?.buyerIdentified===!1&&Oe.clientSecret&&(L=Xo(W,b,Oe.clientSecret,v.account)),{sid:b??"",result:M,sdkGeneratedIdempotencyKey:ne,...x?{claimed:x}:{},...L?{claim:L}:{},...re?{claimRequiresIdentity:!0}:{}}}finally{qe||Va(p)}}let Co=Bt(Fr);wa(()=>{Co.current=Fr},[Fr]);let Hr=pn(async(v,s)=>{let c=vo.current;if(!c)throw new kn("createSession is required to bootstrap checkout.","validation_error");let p=Rs(c,v),W=Ba(p),qe=Yc(p),Y=qi.get(W);if(!Y){let S={canonicalIdentity:W,promise:Co.current(p,qe,W),consumers:0,settled:!1};Y=S,qi.set(W,S);let ne=()=>{S.settled=!0,Jd(W,S)};S.promise.then(ne,ne)}Y.consumers+=1;let de=!1,U=()=>{de||(de=!0,Y.consumers-=1,Jd(W,Y))};s?.(U);try{let S=await Y.promise;Kr.current=W,v&&(mn(Yn),hr(Oe=>vc(Oe,v)));let{sid:ne,result:me,claimed:b,claim:M,claimRequiresIdentity:x}=S;Dn.current=M,fn(x===!0),ct(me),me.data.session&&oe(me.data.session),ne&&fr(ne);let L=()=>{},re=new Promise(Oe=>{L=Oe});if(b){zt.current+=1;let Oe=zt.current,N=()=>zt.current===Oe;Ut.current=b,zn(!0);let fe=Ye=>{N()&&(Ut.current===b&&(Ut.current=null),Gn(Ye),zn(!1),fn(!1))};b.then(async Ye=>{if(!N())return;let Sn=Kd(_t.current??me,Ye);if(!Sn.data.stripe?.publishableKey||eu(Sn)===eu(me)){fe(Ye);return}await re,N()&&await jn(Sn,N,()=>fe(Ye))},Ye=>{zt.current===Oe&&(Ut.current===b&&(Ut.current=null),zn(!1),fn(!1),Hn(Ye instanceof kn?Ye:new kn(Ye instanceof Error?Ye.message:"Failed to create session","api_error")))})}else zt.current+=1,Ut.current=null,zn(!1),fn(!1);try{let{flopay:Oe,paypalFlopay:N}=await Ni(me,{billingApiUrl:V,locale:l,telemetry:a}).catch(Ye=>{throw Sc(Ye,ne||me.data.session?.id)}),fe=_t.current;b&&fe!==me&&!fe?.data.stripe?.publishableKey?Cn(null,null):Cn(Oe,N)}finally{L()}return yt(!1),S}catch(S){throw Kr.current===W&&(Kr.current=null),S}finally{s||U()}},[Gn,Yn,Cn,l,V,ct,jn,a]),Cr=Bt(rr);Cr.current=rr;let eo=Bt(Hr);eo.current=Hr;let to=pn(async v=>{if(!Xm(v)||_n)return{sessionId:Ge,session:y};Pr(!0);try{let s=await Hr(v);return{sessionId:s.sid,session:s.result.data.session??null}}finally{Pr(!1)}},[Hr,_n,Ge,y]),qt=pn(async v=>{let s=Dn.current;if(!s)return;let c=zt.current,p=await s(v);zt.current===c&&Gn(p)},[Gn]),Jn=pn(async()=>{await Ut.current},[]),Vr=pn(async()=>(await Jn(),{proceed:!0}),[Jn]);ir(()=>{let v=!1,s,c=++Ht.current;sr(),Hn(null),rn(0);let p=()=>{v=!0,Ht.current===c&&(Ht.current+=1,sr())},W=vo.current;if(xr&&W)return Xt($n),yt(!1),Kr.current===xr?p:(oe(Cc(W,Ee)),(async()=>{let de=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),U=$n==="auto"&&!P.current&&!de;U&&(we(null),Qt(null),St("processing"));let S=!1;try{let ne=await eo.current(void 0,x=>{s=x});S=!0;let me=ne.result.data.session??null;ye.current=Ds(ne.result);let b=ol(ne.result),M=xs(ne.sid||me?.id);if(!v&&U&&me&&!b&&!M){P.current=!0,await Hm(xr,ne.sdkGeneratedIdempotencyKey,()=>Cr.current(me,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:ne.result.autoProcessingError,initialAutoProcessingPending:ne.result.autoProcessingPending,autoProcessingAttempted:ne.result.autoProcessingAttempted,sessionId:ne.sid||me.id}));return}!v&&U&&((b||M)&&(P.current=!0),St(null),Qt(null))}catch(ne){if(v)return;let me=yi(ne);if(U&&me==="session_auto_completed"){P.current=!0,St("success"),await Ha(600),v||(Ft(()=>{Wr.current?.({status:"succeeded"})}),St(null),Qt(null));return}if(U&&(St(null),Qt(null)),!S){let M=wc(ne),x=Yd(ne,M?{stage:"provider_load",provider:"stripe",...M}:{stage:"session_request"});(M||!(ne instanceof kn))&&Ft(()=>Mn.current?.(x)),Hn(x);return}let b=ne instanceof kn?ne:new kn(ne instanceof Error?ne.message:"Failed to create session","api_error");Hn(b)}finally{s?.(),s=void 0}})(),()=>{p(),s?.()});yt(!0);async function qe(){let de=!1,U=!1,S=null;try{let ne=new Oi(V,{telemetry:!1}),me=await ne.getUnifiedCheckoutSession(bt,t);if(U=!0,S=me,v)return;ct(me);let b=me.data.session??null;if(oe(b),!b)throw new kn("No session data returned","api_error");let M=b.checkoutMode;if(M==="setup")throw new kn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(b.status==="authorized"){yt(!1),Ft(()=>{Wr.current?.(Jr(b,bt)),Ar.current?.(b.successUrl??"")});return}if(b.status==="complete"){yt(!1),Ft(()=>{Ar.current?.(b.successUrl??"")});return}if(b.status==="expired")throw pi(b);de=!0;let x=Ee??M??"full";Xt(x),zt.current+=1;let L=b.clientSecret||t;Dn.current=b.buyerIdentified===!1&&L?Xo(ne,bt,L,{...b.customer?.id?{userId:b.customer.id}:{}}):void 0,zn(!1),fn(!1);let re=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Oe=ol(me);if(x==="auto"&&!P.current&&!re&&!Oe){P.current=!0;let N=Y(me);try{if(await Cr.current(b,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>N,sessionId:bt||b.id}),v)return;await N,v||yt(!1);return}catch{if(v)return;await N,v||yt(!1);return}}await Y(me),v||yt(!1)}catch(ne){if(v)return;let me=Pc(ne,de);if(de&&Mt({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),me){let{errorCode:L,stage:re,...Oe}=me;rl(V,a,en,L,re,Oe)}if(me?.stage==="provider_load"&&(Ee??S?.data.session?.checkoutMode??"full")==="full"&&hc(S,K,w)){let L=Qd({billingApiUrl:V,locale:l,telemetry:a});z.current=L,Cn(L,null),rn(1),yt(!1);return}let b=me?.stage==="provider_load",M="session_request";b?M="provider_load":U&&(M="post_session");let x=Yd(ne,{stage:M,provider:"stripe",sessionId:bt||void 0});(b||!(ne instanceof kn))&&Ft(()=>Mn.current?.(x)),Hn(x),yt(!1)}}async function Y(de){let{flopay:U,paypalFlopay:S,...ne}=await Ni(de,{billingApiUrl:V,locale:l,telemetry:a});ye.current={publishableKey:ne.publishableKey,paypalPublishableKey:ne.paypalPublishableKey},Cn(U,S),rn(0)}return qe(),p},[Ee,xr,$n,Er,t,K,w]);let On=pn(async()=>{if(!Ke||Vn!==1)return;let v=Ht.current;rn(2);try{let{flopay:s,paypalFlopay:c}=await Ni(Ke,{billingApiUrl:V,locale:l,telemetry:a});if(Ht.current!==v)return;sr(),Cn(s,c),rn(0)}catch(s){if(Ht.current!==v)return;let{errorCode:c,stage:p,...W}=ks(s);rl(V,a,en,c,p,W)}},[sr,Cn,l,Vn,V,a,en,Ke]),Xn=!!(bt&&(y?.clientSecret||t)),Fe=Zt||!Xn,Ln=pn(async()=>{let v=Vt.current;if(!(!v.active||Zt||!Xn||!y)){Nn(!0),we(null);try{await rr(y,{attempt3DS:!0,fallbackToFull:!0,sessionId:bt||y.id})}finally{v.active&&Nn(!1)}}},[bt,Zt,Xn,rr,y]),$t=au(Ke?.data.paypal,wt),Gr=ol(Ke),no=mr(()=>{if(!(!Ke||!y||!Ke.data.stripe?.publishableKey))return{billingApiUrl:V}},[Ke,y,V]),bo=!!(n&&!Me&&Ue==="buttons"&&Z&&$n==="full"),Br=!!(bt&&(zm(y?.vault)||_o(y))),Dr=mr(()=>({session:y,loading:pt,error:Rn,checkoutMode:yn,inlineSessionDraft:ln,applyInlineSessionPatch:bo?to:void 0,inlineSessionPatchProcessing:_n,claimPending:Un,claimRequiresIdentity:qn,claimBuyerIdentity:qt,waitForDataAttachment:Jn}),[y,pt,Rn,yn,ln,bo,to,_n,Un,qn,qt,Jn]),bn=!!n&&Ue==="buttons"&&!Gr&&!Br&&(!Ae||!no),cn=tr?ie(Ur,{status:tr,errorMessage:Bn,authorized:gr}):null;if(pt&&!Br){if(u)return Pn(jr,{children:[u,cn]});if(Ue==="buttons"){let v=ce?.buttonsLayout?.cardButton?.borderRadius??ce?.appearance.variables?.borderRadius??8,s=c=>ie("div",{style:{height:c,borderRadius:v,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Pn(jr,{children:[Pn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[K&&s(xo),w&&(I||We)&&s(xo),w&&s(xo),ie("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),cn]})}return Pn(jr,{children:[Pn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ie("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ie("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),cn]})}return Rn?m?ie(wr.Provider,{value:Dr,children:m(Rn)}):ie(wr.Provider,{value:Dr,children:ie("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Rn.message})}):bn?Pn(jr,{children:[ie(wr.Provider,{value:Dr,children:ie(Qm,{onButtonClick:Ie,paymentMethodLayout:rt,showPayPal:K,showStripe:w,showApplePay:I,showGooglePay:We,theme:Re,buttonsTheme:Nt,buttonsStyles:Dt,cardButtonContent:be,cardBackButtonContent:He,cardTitleContent:ot})}),cn]}):Gr&&y&&$t?Pn(jr,{children:[ie(wr.Provider,{value:Dr,children:Pn("div",{className:Pt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xe&&ie(oa,{icon:!1,children:xe}),vn==="retrying"&&ie("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),vn==="exhausted"&&Pn("div",{role:"alert",children:[ie("div",{children:"PayPal is temporarily unavailable. Please try again."}),ie("button",{type:"button",onClick:lr,children:"Retry PayPal"})]}),vn!=="exhausted"&&ie("div",{"aria-hidden":vn==="retrying"?!0:void 0,style:vn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ie(Vc,{sessionId:bt,nonce:y.clientSecret||void 0,billingApiUrl:V,email:y.customer?.email||ln?.account?.email,billingName:[y.customer?.firstName,y.customer?.lastName].filter(Boolean).join(" ")||[ln?.account?.firstName,ln?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:qt,clientId:$t.clientId,environment:$t.environment,currency:(y.currency??"usd").toUpperCase(),isSubscription:y.mode==="subscription",providerObjectType:$t.providerObjectType,approvalPresentation:$t.approvalPresentation,existingOrderId:$t.existingOrderId,onComplete:R,onErrorChange:we,onDecline:A,onCancel:X,onButtonClick:Ie,runBeforeButtonClick:Vr,onInitializationStateChange:vr,allowAutomaticRetry:T===0,session:y,telemetry:a,telemetryContext:en,onInstrument:Fn,debug:G},`${$}:paypal-init-${T}`)})]})}),cn]}):yn==="confirm"?Pn(jr,{children:[ie(wr.Provider,{value:Dr,children:ie(Ri,{flopay:Ae,paypalFlopay:k,options:no??{billingApiUrl:V},onInstrument:Fn,children:Pn("div",{className:Pt,children:[xe&&ie("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:xe}),Ot?Ot({onConfirm:Ln,isProcessing:Fe}):ie("button",{type:"button",onClick:Ln,disabled:Fe,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Fe?"not-allowed":"pointer",opacity:Fe?.6:1},children:Zt?"Processing...":vt??"Confirm Purchase"})]})},$)}),cn]}):(!Ae||!no)&&!(Br&&yn==="full")?ie(jr,{children:cn}):Pn(jr,{children:[ie(wr.Provider,{value:Dr,children:Pn(Ri,{flopay:Ae,paypalFlopay:k,options:no??{billingApiUrl:V},onInstrument:Fn,children:[Vn===1&&ie("button",{type:"button",onClick:On,children:"Retry payment methods"}),Me?Pn(jr,{children:[xe&&ie("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:xe}),ie(Zm,{sessionId:bt,nonce:y?.clientSecret||void 0,billingApiUrl:V,session:y,submitLabel:Ze,walletPresentation:pe,paymentMethodLayout:rt,moreOptionsLabel:dt,children:Me})]}):ie(nl,{sessionId:bt,nonce:y?.clientSecret||void 0,telemetry:a,email:y?.customer?.email||ln?.account?.email,userId:y?.customer?.id||ln?.account?.userId,firstName:y?.customer?.firstName||ln?.account?.firstName,lastName:y?.customer?.lastName||ln?.account?.lastName,totalAmount:y?Math.round(Om(y).total*100):0,currency:y?.currency?.toLowerCase()??"usd",onComplete:R,onError:C,onDecline:A,onCancel:X,error:xe,onErrorChange:we,showPayPal:K,showStripe:w,walletPresentation:pe,enabledPaymentMethods:Vn?[]:se??Ke?.data.stripe?.enabledPaymentMethods??y?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:We,layout:Ue,paymentMethodLayout:rt,moreOptionsLabel:dt,theme:Re,buttonsTheme:Nt,buttonsStyles:Dt,appearance:_e,cardButtonContent:be,cardBackButtonContent:He,cardTitleContent:ot,onButtonClick:Ie,onBeforeButtonClick:Z,onBuyerIdentityReady:qt,enableAVS:le,...Kt?{cardFieldOrder:Kt}:{},...je===void 0?{}:{showCardBrandIcons:je},...it===void 0?{}:{showCardFieldLabels:it},...Q===void 0?{}:{cardFieldLabels:Q},...Te===void 0?{}:{cardFieldPlaceholders:Te},...Xe===void 0?{}:{cardAutoFocus:Xe},...H?{onCardFieldsReady:H}:{},...ht?{onCardFieldsFailed:ht}:{},...Ce===void 0?{}:{cardFieldsTimeoutMs:Ce},...Ve?{cardPreFormSlot:Ve}:{},avsLayout:ze,country:y?.customer?.country,city:y?.customer?.city,state:y?.customer?.state,onCountryChange:te,onZipChange:D,avsCheck:!!le,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:il(Me,Ue),className:Pt,submitLabel:Ze,directPaypal:$t,isSubscription:y?.mode==="subscription",session:y,dataAttachmentPending:Un,dataAttachmentRequiresIdentity:qn,debug:G})]},$)}),cn]})}function Zm({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,paymentMethodLayout:l,moreOptionsLabel:u,children:m}){return ie(jr,{children:Ui.Children.map(m,R=>{if(!Ui.isValidElement(R))return R;let C=R.props,g={};return C.sessionId||(g.sessionId=e),!C.nonce&&t&&(g.nonce=t),C.billingApiUrl||(g.billingApiUrl=n),C.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),C.walletPresentation===void 0&&(g.walletPresentation=i),C.paymentMethodLayout===void 0&&l!==void 0&&(g.paymentMethodLayout=l),C.moreOptionsLabel===void 0&&u!==void 0&&(g.moreOptionsLabel=u),o?.customer&&(C.email||(g.email=o.customer.email),C.userId||(g.userId=o.customer.id),C.firstName||(g.firstName=o.customer.firstName),C.lastName||(g.lastName=o.customer.lastName)),Object.keys(g).length===0?R:Ui.cloneElement(R,g)})})}function Qm({onButtonClick:e,paymentMethodLayout:t,showPayPal:n,showStripe:o=!0,showApplePay:a,showGooglePay:i,theme:l,buttonsTheme:u,buttonsStyles:m,cardButtonContent:R,cardBackButtonContent:C,cardTitleContent:g}){let[A,X]=Jt(!1),te=mr(()=>iu(l),[l]),D=mr(()=>{let I=te?.buttonsLayout??jm(u);return m?{...I,...m,cardButton:{...I.cardButton,...m.cardButton},cardFormContainer:{...I.cardFormContainer,...m.cardFormContainer},backButton:{...I.backButton,...m.backButton},backButtonIcon:{...I.backButtonIcon,...m.backButtonIcon},submitButton:{...I.submitButton,...m.submitButton},title:{...I.title,...m.title}}:I},[te,u,m]),K=te?.buttonsLayout?.cardButton?.borderRadius??te?.appearance.variables?.borderRadius??8,w=I=>ie("div",{style:{height:I,borderRadius:K,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),pe=R===void 0?{boxSizing:"border-box",height:xo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(A){let I=D.cardInputBorder??"#e5e7eb",We=D.cardInputBackground??"white",G=Vo(C),Ue=Vo(g);return Pn("div",{style:{backgroundColor:D.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...D.cardFormContainer},children:[Pn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Pn("button",{type:"button",onClick:()=>X(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:G?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...D.backButton},children:[ie("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...D.backButtonIcon},children:ie("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:ie("path",{d:"M15 18l-6-6 6-6"})})}),ie(Yo,{content:C})]}),Ue?ie("div",{style:{flex:1}}):ie("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...D.title},children:ie(Ia,{content:g})})]}),ie("div",{style:{backgroundColor:We,border:`1px solid ${I}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ie("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Pn("div",{style:{display:"flex"},children:[ie("div",{style:{flex:1,backgroundColor:We,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,borderBottomLeftRadius:8,padding:12,height:45},children:ie("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ie("div",{style:{flex:1,backgroundColor:We,borderTop:"none",borderRight:`1px solid ${I}`,borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,borderBottomRightRadius:8,padding:12,height:45},children:ie("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ie("div",{style:{backgroundColor:We,border:`1px solid ${I}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ie("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ie("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...D.submitButton,opacity:.5}}),ie("style",{children:`
|
|
15
15
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
16
16
|
@keyframes flopay-interim-expand {
|
|
17
17
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
18
18
|
40% { opacity: 1; }
|
|
19
19
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
20
20
|
}
|
|
21
|
-
`})]})}let ue={paypal:n&&C(_o),wallets:o&&(a||i)&&C(_o),card:o&&(t?C(_o):de("button",{type:"button",onClick:()=>{e?.("card"),te(!0)},style:{width:"100%",...ge,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:z.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,...z.cardButton},onMouseDown:w=>{w.currentTarget.style.transform="scale(0.985)"},onMouseUp:w=>{w.currentTarget.style.transform="scale(1)"},children:de(Ko,{content:S})}))};return gn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Om.map(w=>de(Li.Fragment,{children:ue[w]},w)),de("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as uf,jsx as To,jsxs as pf}from"react/jsx-runtime";var rf=44;function su(e){return new Promise(t=>setTimeout(t,e))}var lu=15e3;function dl(e,t){return new Mo(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function of(e,t){return new Promise((n,o)=>{let a=()=>o(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(i=>{t.removeEventListener("abort",a),n(i)},i=>{t.removeEventListener("abort",a),o(i)})})}function af(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function sf(e,t){return e instanceof Mo?e:new Mo(e instanceof Error?e.message:t,"api_error")}function lf(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function cf(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 df({sessionId:e,nonce:t,createSession:n,getSession:o,paymentMethodId:a,checkoutMethod:i,clientId:s,products:c,items:y,subscriptions:S,account:P,successUrl:f,cancelUrl:F,couponCodes:te,tagsData:ae,utmMetadata:z,billingApiUrl:K,locale:C,theme:ge,appearance:ue,buttonsTheme:w,buttonsStyles:Ke,onSuccess:X,onError:Ne,onDecline:at,children:pt,disabled:Ie=!1,type:Bt="button",style:xt,...Re}){let Ye=Ka(()=>ef(K),[K]),it=Ka(()=>cf({createSession:n,clientId:s,products:c,items:y,subscriptions:S,account:P,successUrl:f,cancelUrl:F,couponCodes:te,tagsData:ae,utmMetadata:z}),[P,F,s,te,n,c,y,S,f,ae,z]),[st,Ee]=da(!1),[ne,pe]=da(null),[jt,qe]=da(null),[lt,re]=da(!1),[Me,Ze]=da(null),[V,vt]=da(null),be=go(!0),Je=go(null),Ue=go(null),Qe=go(!1),Ct=go(V),Be=go(X),kt=go(Ne),Ae=go(at),_e=Or(b=>ki(Je,async g=>{try{return await b(g)}catch(Y){throw g.aborted?oa(Y):Y}}),[]);ca(()=>{Ct.current=V},[V]),ca(()=>{Be.current=X},[X]),ca(()=>{kt.current=Ne},[Ne]),ca(()=>{Ae.current=at},[at]),ca(()=>(be.current=!0,()=>{be.current=!1,Je.current?.abort(),Ue.current?.abort()}),[]),ca(()=>{if(typeof window>"u")return;let b=g=>{g.key==="Escape"&&vt(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let bt=Or((b,g=Oa)=>{Ae.current?.(mn(g,b,{code:b.code,declineCode:b.declineCode}))},[]),Ft=Or(async b=>{be.current&&(qe(null),re(b.result.status==="authorized"),pe("success"),await su(600),be.current&&At(()=>Be.current?.(b)))},[]),Rt=Or(async(b,g)=>{if(!be.current)return;!!g?.emitDecline&&Qm(b)?bt(b,g?.method):kt.current?.(b),qe(b.message),re(!1),pe("error"),await su(400)},[bt]),G=Or(async(b,g,Y)=>{let j=b.data.session??null;if(!j)throw so(new Mo("No session data returned","api_error"),g);let J=Y?.nonce||j.clientSecret||t;if(Gr(j)){await Ft({result:Vr(j,g),session:j,sessionId:j.id||g,autoCompleted:!1});return}if(j.status==="expired")throw so(di(j),j.id||g);try{if(b.autoProcessingPending){let se=b.autoProcessingPending,$=new cl(Ye),Se=await _e(tt=>$.waitForCheckoutSessionCompletion(se.sessionId,{initialDelayMs:se.retryAfterMs,nonce:J,statusUrl:se.statusUrl,signal:tt})),we=lo(Se,j),k=Se.autoProcessingError?.type==="3ds_required"&&!iu(Se.autoProcessingError)&&Se.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Se.autoProcessingError.nextActionRedirectUrl}:null;if(k&&g&&J){let tt=La(Ye,g,j),Ht=await _e(Dt=>aa(k,{billingApiUrl:Ye,sessionId:g,nonce:J,session:j,signal:Dt,telemetry:!0,...tt.telemetry?{challengeTelemetry:tt.telemetry}:{}})).finally(tt.release);await Ft({result:Ht,session:j,sessionId:j.id||g,autoCompleted:!1});return}if(Se.autoProcessingError)throw Fr(Se.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Se.autoProcessingError.checkoutMethod});if(!Gr(we))throw Jo(we);await Ft({result:Vr(we,g),session:we,sessionId:we.id||g,autoCompleted:!1});return}if(b.autoProcessingError){let se=b.autoProcessingError.nextActionRedirectUrl;if(b.autoProcessingError.type==="3ds_required"&&!iu(b.autoProcessingError)&&se&&g&&J){let $=await _e(tt=>ld({billingApiUrl:Ye,sessionId:g,nonce:J,nextActionRedirectUrl:se,signal:tt}));if($.status==="declined")throw Fr({type:$.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:$.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let we=await new cl(Ye).waitForCheckoutSessionCompletion(g,{initialDelayMs:0,nonce:J}),k=lo(we,j);if(!Gr(k))throw Fr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await Ft({result:Vr(k,g),session:k,sessionId:k.id||g,autoCompleted:!1});return}throw Fr(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(Y?.fromCreateSession&&b.autoProcessingAttempted===!0)throw Fr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let h=await ia({billingApiUrl:Ye,sessionId:g??j.id,session:j,nonce:J});if(h.type==="next_action_required"&&J){let se=g??j.id,$=La(Ye,se,j),Se=await _e(we=>aa(h,{billingApiUrl:Ye,sessionId:se,nonce:J,session:j,signal:we,telemetry:!0,...$.telemetry?{challengeTelemetry:$.telemetry}:{}})).finally($.release);await Ft({result:Se,session:j,sessionId:j.id||se,autoCompleted:!1});return}if(h.type!=="success")throw Fr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ft({result:h.result,session:j,sessionId:j.id||g,autoCompleted:!1})}catch(h){let se=j.id||g,$=so(Na(h),se);if($.code==="three_ds_aborted")return;if($.code==="checkout_processing_timeout"){if(!be.current)return;Ze($.message),At(()=>kt.current?.($));return}await Rt($,{emitDecline:!0,method:$.checkoutMethod??Oa}),lf($,se)&&se&&be.current&&vt({sessionId:se,errorMessage:$.message,nonce:J||void 0,payPalOrderId:$.orderId})}},[t,Ye,_e,Rt,Ft]),ye=Or(async b=>{let g=new AbortController;Ue.current=g;let Y=!1,j=setTimeout(()=>{Y=!0,g.abort()},lu);try{let J=await of((async()=>b({signal:g.signal}))(),g.signal);if(!be.current)return null;if(!af(J))throw dl("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:J.sessionId,nonce:J.nonce}}catch(J){if(!be.current)return null;throw J instanceof Mo&&J.code==="session_fetch_failed"?J:Y?dl(`getSession did not resolve within ${lu/1e3} seconds.`):dl("Could not fetch the one-click session.",J)}finally{clearTimeout(j),Ue.current===g&&(Ue.current=null)}},[]),Te=Or(async b=>{if(Re.onClick?.(b),b.defaultPrevented||Ie||st||(vt(null),Ze(null),Qe.current))return;let g=[e,o,it].filter(Boolean).length;if(g>1){let Y=new Mo("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await Rt(Y),be.current&&(pe(null),qe(null));return}if(g===0){let Y=new Mo("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Rt(Y),be.current&&(pe(null),qe(null));return}Qe.current=!0,Ee(!0),qe(null),re(!1),pe("processing");try{let Y=new cl(Ye);if(e){let j=await Y.getUnifiedCheckoutSession(e,t);await G(j,e);return}if(o){let j=await ye(o);if(!j)return;let J=await Y.getUnifiedCheckoutSession(j.sessionId,j.nonce);await G(J,j.sessionId,{nonce:j.nonce});return}ed();try{let j=await Y.createAndFetchSession({...it});await G(j,j.data.session?.id??null,{fromCreateSession:!0})}catch(j){if(ui(j)==="session_auto_completed"){await Ft({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw j}}catch(Y){await Rt(so(sf(Y,"Automatic payment failed. Please try again."),e))}finally{Qe.current=!1,be.current&&(pe(null),qe(null),Ee(!1))}},[Re.onClick,it,Ie,ye,o,st,t,G,Ye,e,Rt,Ft]),ct=Or(b=>{let g=Ct.current;vt(null),Be.current?.({result:b,session:null,sessionId:g?.sessionId??null,autoCompleted:!1})},[]),dt=Or(b=>{kt.current?.(b)},[]),Ve=Or(b=>{Ae.current?.(b)},[]),yt=Ka(()=>nf(ge),[ge]),mt=Ka(()=>{let b=yt?.buttonsLayout??tf(w);return Ke?{...b,...Ke,cardButton:{...b.cardButton,...Ke.cardButton}}:b},[yt,w,Ke]),St=Ka(()=>{let b=yt?.appearance;return ue?b?{...b,...ue,variables:{...b.variables,...ue.variables}}:ue:b},[ue,yt]),je=St?.variables,$e=je?.colorPrimary??"#4A49FF",et=je?.colorPrimaryHover??$d($e,.12),q=je?.borderRadius??"8px";return pf(uf,{children:[To("button",{...Re,type:Bt,onClick:Te,disabled:Ie||st,"aria-busy":st,style:{width:"100%",...pt===void 0?{boxSizing:"border-box",height:rf,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...mt.cardButton,...el({themeBundle:yt,resolvedPrimaryColor:$e,resolvedBorderRadius:q,submitButtonStyle:mt.submitButton,explicitPrimaryColor:je?.colorPrimary}),fontSize:mt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ie||st?"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:Ie||st?.6:1,...xt},onMouseEnter:b=>{Re.onMouseEnter?.(b),!b.defaultPrevented&&!Ie&&!st&&(yt||je?.colorPrimary)&&(b.currentTarget.style.backgroundColor=et)},onMouseLeave:b=>{Re.onMouseLeave?.(b),!b.defaultPrevented&&(yt||je?.colorPrimary)&&(b.currentTarget.style.backgroundColor=$e)},onMouseDown:b=>{Re.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{Re.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:To(Ko,{content:pt})}),Me&&To("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Me}),ne&&To(xr,{status:ne,errorMessage:jt,authorized:lt}),V&&To("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:b=>{b.target===b.currentTarget&&vt(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:To("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:To(ll,{sessionId:V.sessionId,nonce:V.nonce,checkoutMode:"full",billingApiUrl:Ye,locale:C,theme:ge,...St?{appearance:St}:{},buttonsTheme:w,buttonsStyles:Ke,initialErrorMessage:V.errorMessage,initialPayPalOrderId:V.payPalOrderId,cardTitleContent:null,onComplete:ct,onError:dt,onDecline:Ve})})})]})}import{jsx as ff}from"react/jsx-runtime";var yf={StripeSetupMethod:yc,PayPalSetupMethod:pc};function mf(e){return ff(mc,{...e,branches:yf})}import{loadCheckoutRuntime as gf}from"@flopay/js";import{FloPayError as cu}from"@flopay/shared";import{useEffect as ul,useRef as pl}from"react";import{jsx as vf}from"react/jsx-runtime";function hf(e){return e instanceof cu?e:new cu("The checkout runtime failed to load.","network_error",{code:"runtime_load_failed",cause:e})}function Pf(e){let{publishableKey:t,sessionId:n,nonce:o,appearance:a,strings:i,runtimeUrl:s,runtimeTimeoutMs:c}=e,y=e.createSession===void 0?void 0:JSON.stringify(e.createSession),S=pl(null),P=pl(null),f=pl(e);return f.current=e,ul(()=>{let F=!0;return gf({runtimeUrl:s,timeoutMs:c}).then(te=>{let ae=S.current;!F||!ae||(P.current=te.mount(ae,{publishableKey:t,sessionId:n,nonce:o,createSession:y===void 0?void 0:JSON.parse(y),appearance:f.current.appearance,strings:f.current.strings,onEvent:z=>f.current.onEvent?.(z)}))},te=>{F&&f.current.onError?.(hf(te))}),()=>{F=!1,P.current?.unmount(),P.current=null}},[t,n,o,y,s,c]),ul(()=>{a!==void 0&&P.current?.update({appearance:a})},[a]),ul(()=>{i!==void 0&&P.current?.update({strings:i})},[i]),vf("div",{ref:S,"data-flopay-runtime-checkout":""})}export{vi as DirectPayPalButton,df as FloPayAutomaticPaymentButton,Fu as FloPayCardSetup,xu as FloPayCardSetupError,ll as FloPayCheckout,mf as FloPayPaymentMethodSetup,wi as FloPayProvider,Pf as FloPayRuntimeCheckout,tl as SplitCardForm,hs as VaultCardFields,CP as dropThirdPartyOnlyError,np as useCheckout,uo as useFloPay,Es as usePayPalFloPay};
|
|
21
|
+
`})]})}let se={paypal:n&&w(xo),wallets:o&&(a||i)&&w(xo),card:o&&(t?w(xo):ie("button",{type:"button",onClick:()=>{e?.("card"),X(!0)},style:{width:"100%",...pe,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:D.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...D.cardButton},onMouseDown:I=>{I.currentTarget.style.transform="scale(0.985)"},onMouseUp:I=>{I.currentTarget.style.transform="scale(1)"},children:ie(Go,{content:R})}))};return Pn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Lm.map(I=>ie(Ui.Fragment,{children:se[I]},I)),ie("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as pf,jsx as Fo,jsxs as yf}from"react/jsx-runtime";var of=44;function cu(e){return new Promise(t=>setTimeout(t,e))}var du=15e3;function ul(e,t){return new Bo(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function af(e,t){return new Promise((n,o)=>{let a=()=>o(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(i=>{t.removeEventListener("abort",a),n(i)},i=>{t.removeEventListener("abort",a),o(i)})})}function sf(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function lf(e,t){return e instanceof Bo?e:new Bo(e instanceof Error?e.message:t,"api_error")}function cf(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function df(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 uf({sessionId:e,nonce:t,createSession:n,getSession:o,paymentMethodId:a,checkoutMethod:i,clientId:l,products:u,items:m,subscriptions:R,account:C,successUrl:g,cancelUrl:A,couponCodes:X,tagsData:te,utmMetadata:D,billingApiUrl:K,locale:w,theme:pe,appearance:se,buttonsTheme:I,buttonsStyles:We,onSuccess:G,onError:Ue,onDecline:rt,children:dt,disabled:Re=!1,type:Nt="button",style:Dt,...be}){let He=Ga(()=>tf(K),[K]),ot=Ga(()=>df({createSession:n,clientId:l,products:u,items:m,subscriptions:R,account:C,successUrl:g,cancelUrl:A,couponCodes:X,tagsData:te,utmMetadata:D}),[C,A,l,X,n,u,m,R,g,te,D]),[at,Ie]=pa(!1),[Z,le]=pa(null),[Kt,je]=pa(null),[it,Q]=pa(!1),[Te,Xe]=pa(null),[H,ht]=pa(null),Ce=ho(!0),Ve=ho(null),ze=ho(null),Ze=ho(!1),Pt=ho(H),De=ho(G),wt=ho(Ue),Me=ho(rt),Ee=$r(k=>Ii(Ve,async q=>{try{return await k(q)}catch(j){throw q.aborted?ia(j):j}}),[]);ua(()=>{Pt.current=H},[H]),ua(()=>{De.current=G},[G]),ua(()=>{wt.current=Ue},[Ue]),ua(()=>{Me.current=rt},[rt]),ua(()=>(Ce.current=!0,()=>{Ce.current=!1,Ve.current?.abort(),ze.current?.abort()}),[]),ua(()=>{if(typeof window>"u")return;let k=q=>{q.key==="Escape"&&ht(null)};return window.addEventListener("keydown",k),()=>{window.removeEventListener("keydown",k)}},[]);let vt=$r((k,q=Na)=>{Me.current?.(gn(q,k,{code:k.code,declineCode:k.declineCode}))},[]),Ot=$r(async k=>{Ce.current&&(je(null),Q(k.result.status==="authorized"),le("success"),await cu(600),Ce.current&&Ft(()=>De.current?.(k)))},[]),kt=$r(async(k,q)=>{if(!Ce.current)return;!!q?.emitDecline&&ef(k)?vt(k,q?.method):wt.current?.(k),je(k.message),Q(!1),le("error"),await cu(400)},[vt]),V=$r(async(k,q,j)=>{let y=k.data.session??null;if(!y)throw lo(new Bo("No session data returned","api_error"),q);let oe=j?.nonce||y.clientSecret||t;if(Xr(y)){await Ot({result:Jr(y,q),session:y,sessionId:y.id||q,autoCompleted:!1});return}if(y.status==="expired")throw lo(pi(y),y.id||q);try{if(k.autoProcessingPending){let $=k.autoProcessingPending,O=new dl(He),he=await Ee(ut=>O.waitForCheckoutSessionCompletion($.sessionId,{initialDelayMs:$.retryAfterMs,nonce:oe,statusUrl:$.statusUrl,signal:ut})),Se=co(he,y),_=he.autoProcessingError?.type==="3ds_required"&&!lu(he.autoProcessingError)&&he.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:he.autoProcessingError.nextActionRedirectUrl}:null;if(_&&q&&oe){let ut=Ua(He,q,y),Mt=await Ee(At=>sa(_,{billingApiUrl:He,sessionId:q,nonce:oe,session:y,signal:At,telemetry:!0,...ut.telemetry?{challengeTelemetry:ut.telemetry}:{}})).finally(ut.release);await Ot({result:Mt,session:y,sessionId:y.id||q,autoCompleted:!1});return}if(he.autoProcessingError)throw zr(he.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:he.autoProcessingError.checkoutMethod});if(!Xr(Se))throw Zo(Se);await Ot({result:Jr(Se,q),session:Se,sessionId:Se.id||q,autoCompleted:!1});return}if(k.autoProcessingError){let $=k.autoProcessingError.nextActionRedirectUrl;if(k.autoProcessingError.type==="3ds_required"&&!lu(k.autoProcessingError)&&$&&q&&oe){let O=await Ee(ut=>cd({billingApiUrl:He,sessionId:q,nonce:oe,nextActionRedirectUrl:$,signal:ut}));if(O.status==="declined")throw zr({type:O.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:O.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:k.autoProcessingError.checkoutMethod});let Se=await new dl(He).waitForCheckoutSessionCompletion(q,{initialDelayMs:0,nonce:oe}),_=co(Se,y);if(!Xr(_))throw zr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:k.autoProcessingError.checkoutMethod});await Ot({result:Jr(_,q),session:_,sessionId:_.id||q,autoCompleted:!1});return}throw zr(k.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:k.autoProcessingError.checkoutMethod})}if(j?.fromCreateSession&&k.autoProcessingAttempted===!0)throw zr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let h=await la({billingApiUrl:He,sessionId:q??y.id,session:y,nonce:oe});if(h.type==="next_action_required"&&oe){let $=q??y.id,O=Ua(He,$,y),he=await Ee(Se=>sa(h,{billingApiUrl:He,sessionId:$,nonce:oe,session:y,signal:Se,telemetry:!0,...O.telemetry?{challengeTelemetry:O.telemetry}:{}})).finally(O.release);await Ot({result:he,session:y,sessionId:y.id||$,autoCompleted:!1});return}if(h.type!=="success")throw zr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ot({result:h.result,session:y,sessionId:y.id||q,autoCompleted:!1})}catch(h){let $=y.id||q,O=lo(za(h),$);if(O.code==="three_ds_aborted")return;if(O.code==="checkout_processing_timeout"){if(!Ce.current)return;Xe(O.message),Ft(()=>wt.current?.(O));return}await kt(O,{emitDecline:!0,method:O.checkoutMethod??Na}),cf(O,$)&&$&&Ce.current&&ht({sessionId:$,errorMessage:O.message,nonce:oe||void 0,payPalOrderId:O.orderId})}},[t,He,Ee,kt,Ot]),ce=$r(async k=>{let q=new AbortController;ze.current=q;let j=!1,y=setTimeout(()=>{j=!0,q.abort()},du);try{let oe=await af((async()=>k({signal:q.signal}))(),q.signal);if(!Ce.current)return null;if(!sf(oe))throw ul("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:oe.sessionId,nonce:oe.nonce}}catch(oe){if(!Ce.current)return null;throw oe instanceof Bo&&oe.code==="session_fetch_failed"?oe:j?ul(`getSession did not resolve within ${du/1e3} seconds.`):ul("Could not fetch the one-click session.",oe)}finally{clearTimeout(y),ze.current===q&&(ze.current=null)}},[]),_e=$r(async k=>{if(be.onClick?.(k),k.defaultPrevented||Re||at||(ht(null),Xe(null),Ze.current))return;let q=[e,o,ot].filter(Boolean).length;if(q>1){let j=new Bo("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await kt(j),Ce.current&&(le(null),je(null));return}if(q===0){let j=new Bo("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await kt(j),Ce.current&&(le(null),je(null));return}Ze.current=!0,Ie(!0),je(null),Q(!1),le("processing");try{let j=new dl(He);if(e){let y=await j.getUnifiedCheckoutSession(e,t);await V(y,e);return}if(o){let y=await ce(o);if(!y)return;let oe=await j.getUnifiedCheckoutSession(y.sessionId,y.nonce);await V(oe,y.sessionId,{nonce:y.nonce});return}td();try{let y=await j.createAndFetchSession({...ot});await V(y,y.data.session?.id??null,{fromCreateSession:!0})}catch(y){if(yi(y)==="session_auto_completed"){await Ot({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw y}}catch(j){await kt(lo(lf(j,"Automatic payment failed. Please try again."),e))}finally{Ze.current=!1,Ce.current&&(le(null),je(null),Ie(!1))}},[be.onClick,ot,Re,ce,o,at,t,V,He,e,kt,Ot]),st=$r(k=>{let q=Pt.current;ht(null),De.current?.({result:k,session:null,sessionId:q?.sessionId??null,autoCompleted:!1})},[]),lt=$r(k=>{wt.current?.(k)},[]),Ke=$r(k=>{Me.current?.(k)},[]),Ct=Ga(()=>rf(pe),[pe]),_t=Ga(()=>{let k=Ct?.buttonsLayout??nf(I);return We?{...k,...We,cardButton:{...k.cardButton,...We.cardButton}}:k},[Ct,I,We]),ct=Ga(()=>{let k=Ct?.appearance;return se?k?{...k,...se,variables:{...k.variables,...se.variables}}:se:k},[se,Ct]),Ae=ct?.variables,Qe=Ae?.colorPrimary??"#4A49FF",et=Ae?.colorPrimaryHover??Wd(Qe,.12),z=Ae?.borderRadius??"8px";return yf(pf,{children:[Fo("button",{...be,type:Nt,onClick:_e,disabled:Re||at,"aria-busy":at,style:{width:"100%",...dt===void 0?{boxSizing:"border-box",height:of,padding:"0 1rem"}:{padding:"0.9rem 1rem"},..._t.cardButton,...tl({themeBundle:Ct,resolvedPrimaryColor:Qe,resolvedBorderRadius:z,submitButtonStyle:_t.submitButton,explicitPrimaryColor:Ae?.colorPrimary}),fontSize:_t.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Re||at?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Re||at?.6:1,...Dt},onMouseEnter:k=>{be.onMouseEnter?.(k),!k.defaultPrevented&&!Re&&!at&&(Ct||Ae?.colorPrimary)&&(k.currentTarget.style.backgroundColor=et)},onMouseLeave:k=>{be.onMouseLeave?.(k),!k.defaultPrevented&&(Ct||Ae?.colorPrimary)&&(k.currentTarget.style.backgroundColor=Qe)},onMouseDown:k=>{be.onMouseDown?.(k),k.defaultPrevented||(k.currentTarget.style.transform="scale(0.985)")},onMouseUp:k=>{be.onMouseUp?.(k),k.defaultPrevented||(k.currentTarget.style.transform="scale(1)")},children:Fo(Go,{content:dt})}),Te&&Fo("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Te}),Z&&Fo(Ur,{status:Z,errorMessage:Kt,authorized:it}),H&&Fo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:k=>{k.target===k.currentTarget&&ht(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:Fo("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:Fo(cl,{sessionId:H.sessionId,nonce:H.nonce,checkoutMode:"full",billingApiUrl:He,locale:w,theme:pe,...ct?{appearance:ct}:{},buttonsTheme:I,buttonsStyles:We,initialErrorMessage:H.errorMessage,initialPayPalOrderId:H.payPalOrderId,cardTitleContent:null,onComplete:st,onError:lt,onDecline:Ke})})})]})}import{jsx as gf}from"react/jsx-runtime";var mf={StripeSetupMethod:mc,PayPalSetupMethod:yc};function ff(e){return gf(fc,{...e,branches:mf})}import{loadCheckoutRuntime as hf}from"@flopay/js";import{FloPayError as uu}from"@flopay/shared";import{useEffect as pl,useRef as yl}from"react";import{jsx as Cf}from"react/jsx-runtime";function Pf(e){return e instanceof uu?e:new uu("The checkout runtime failed to load.","network_error",{code:"runtime_load_failed",cause:e})}function vf(e){let{publishableKey:t,sessionId:n,nonce:o,appearance:a,strings:i,runtimeUrl:l,runtimeTimeoutMs:u}=e,m=e.createSession===void 0?void 0:JSON.stringify(e.createSession),R=yl(null),C=yl(null),g=yl(e);return g.current=e,pl(()=>{let A=!0;return hf({runtimeUrl:l,timeoutMs:u}).then(X=>{let te=R.current;!A||!te||(C.current=X.mount(te,{publishableKey:t,sessionId:n,nonce:o,createSession:m===void 0?void 0:JSON.parse(m),appearance:g.current.appearance,strings:g.current.strings,onEvent:D=>g.current.onEvent?.(D)}))},X=>{A&&g.current.onError?.(Pf(X))}),()=>{A=!1,C.current?.unmount(),C.current=null}},[t,n,o,m,l,u]),pl(()=>{a!==void 0&&C.current?.update({appearance:a})},[a]),pl(()=>{i!==void 0&&C.current?.update({strings:i})},[i]),Cf("div",{ref:R,"data-flopay-runtime-checkout":""})}export{bi as DirectPayPalButton,uf as FloPayAutomaticPaymentButton,Bu as FloPayCardSetup,Fu as FloPayCardSetupError,cl as FloPayCheckout,ff as FloPayPaymentMethodSetup,Ri as FloPayProvider,vf as FloPayRuntimeCheckout,nl as SplitCardForm,Ps as VaultCardFields,bP as dropThirdPartyOnlyError,rp as useCheckout,po as useFloPay,_s as usePayPalFloPay};
|