@flopay/react 1.20.9 → 1.20.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as fc}from"./chunk-D4CVZRT4.mjs";import{c as Ft,d as Ur,e as wa,f as Cs,g as bs,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 ks,d as Rs,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 Ss,c as oc,d as ws,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 kP}from"@flopay/shared";import{PaymentAPI as pl}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 Is(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 Is(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[I,b]of Object.entries(l)){if(u&&I.endsWith("Name")||typeof b!="string")continue;let g=b.trim();g&&(m[I]=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 Es(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function 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 _s(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 Ts(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 As}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:I=>u(I.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 Ms(){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 I=yo((C=a.current)=>{C?.timer&&(clearTimeout(C.timer),C.timer=null)},[]),b=yo(C=>{I();let ne=n.current+1;return n.current=ne,o.current=null,a.current={generation:ne,method:C,timer:null,yieldedControl:!1},ne},[I]),g=yo(C=>{let ne=a.current;return C!==void 0&&ne?.generation!==C?!1:(I(ne),a.current=null,(C===void 0||o.current===C)&&(o.current=null),!0)},[I]),A=yo(C=>{let ne=a.current,re=C??ne?.generation??n.current;(C===void 0||ne?.generation===C)&&(I(ne),a.current=null),o.current=re},[I]),Y=yo(C=>o.current===(C??n.current),[]),te=yo(C=>a.current?.generation===C&&o.current!==C,[]),x=yo(()=>{let C=a.current;C&&(I(C),!C.yieldedControl&&(C.yieldedControl=!0,l.current?.(C.method)))},[I]),D=yo(()=>{let C=a.current;!C?.yieldedControl||document.visibilityState!=="visible"||(I(C),C.timer=setTimeout(()=>{if(C.timer=null,a.current?.generation===C.generation){if(u.current?.(C.method)){m.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"})}},oc))},[I]);return zc(()=>{let C=()=>{document.visibilityState==="visible"?D():x()};return document.addEventListener("visibilitychange",C),window.addEventListener("blur",x),window.addEventListener("focus",D),()=>{document.removeEventListener("visibilitychange",C),window.removeEventListener("blur",x),window.removeEventListener("focus",D),I()}},[I,x,D]),{startAttempt:b,finishAttempt:g,invalidateAttempt:A,isAttemptInvalidated:Y,isAttemptCurrent:te,generationRef:n}}import{jsx as Mo,jsxs as xs}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:I,providerObjectType:b,approvalPresentation:g,onTokenizedBody:A,onComplete:Y,onErrorChange:te,onDecline:x,onCancel:D,onTechnicalFailure:C,isProcessing:ne=!1,onLoadStateChange:re,onInitializationStateChange:k,allowAutomaticRetry:je=!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]),ce=nt(null),Kt=nt(0),$e=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,de]=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??b,q=et??(I?"subscription":"order"),[Ht]=Zr(ka),R=rt?.gateways?.paypal?.approvalPresentation??g,j=di(Ht,R==="app_switch"?"app_switch":void 0,q),$=_p(et),y=Fa(()=>JSON.stringify([Ae,l,m,u??"",q,$,j,e,dt??""]),[Ae,l,m,u,dt,q,$,j,e]),ie=nt(y),h=ie.current!==y,W=nt(be),L=nt(null),[he,Se]=Zr([]),_=yr(T=>{W.current&&Se(We=>[...We,`${new Date().toISOString().slice(11,23)} ${T}`])},[]);Wt(()=>{W.current=be,be&&_("debug:enabled"),L.current?.setEnabled(be)},[_,be]);let ut=nt(A),Mt=nt(Y),At=nt(te),Fn=nt(x),Ge=nt(D),fr=nt(C),bt=nt(G),Er=nt(re),pt=nt(k),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=Y},[Y]),Wt(()=>{At.current=te},[te]),Wt(()=>{Fn.current=x},[x]),Wt(()=>{Ge.current=D},[D]),Wt(()=>{fr.current=C},[C]),Wt(()=>{bt.current=G},[G]),Wt(()=>{Er.current=re},[re]),Wt(()=>{pt.current=k},[k]),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),(ce.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ce.current)?.focus?.()},[]);Wt(()=>{!Ve||!Ce.current||(Ce.current=!1,Qt())},[Qt,Ve,De]);let gr=yr((T,We)=>{let P=We?.popupBlocked??so(T);P&&H.markBlocked();let se=li("PayPal",P,Ht.inAppBrowser),Rt=fr.current;if(Rt){let xt=P&&Ht.inAppBrowser?new ra(se,"api_error",{code:We?.code??"paypal_popup_blocked"}):T;Rt("paypal",xt,We);return}if(T instanceof ra&&T.code==="checkout_processing_timeout"){At.current?.(T.message);return}At.current?.(se)},[H,Ht.inAppBrowser]),In=yr(T=>{let We=$e.current,P=it.current;We===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(We),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:T}),$e.current=null)},[H,Z]),_r=yr((T,We,P)=>{let se=it.current;In("overlay_timeout"),se&&Z.error({...se,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(We,{...P,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:j,terminalReason:"overlay_timeout"}),vt(!0),Bn(),St()},[In,St,gr,H,j,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 We=$e.current;Z.performance({...T,popupCapability:H.current(),stage:"overlay_return",durationMs:We===null?0:Z.elapsed(We),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 We=Xt.current;return We&&Nn.current.set(T,We),T};Wt(()=>{ie.current!==y&&(ie.current=y,Ot.current=!1,kt.current=!1,ze(!1),Pt(!1),de(!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:j},We=()=>({...it.current??T,popupCapability:H.current()}),P={error:s=>Z.error({...s,...We()}),log:s=>Z.log({...s,...We()}),performance:s=>Z.performance({...s,...We()}),terminal:s=>Z.terminal({...s,...We()}),startTiming:Z.startTiming,elapsed:Z.elapsed},se=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Rt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(_(`mount clientId=${se} env=${u??"(unset)"}\u2192${vn??"live"} ccy=${m} sub=${I}`),_(`ua=${Rt.slice(0,80)}${Rt.length>80?"\u2026":""}`),!l){_("FAIL: clientId empty \u2014 gateway misconfigured"),de(!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(!ce.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=$?q: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=ce.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"),K=s.getAttribute("name"),qe=s.getAttribute("sandbox"),J=[];return c&&J.push(`src=${Kr(c)}`),p&&J.push(`srcdoc[${p.length}ch]`),!c&&!p&&J.push("src=(empty) srcdoc=(empty)"),K&&J.push(`name=${K.slice(0,40)}`),qe!==null&&J.push(`sandbox="${qe.slice(0,40)}"`),J.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,K=c.body?.innerHTML.length??0,qe=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${p}children,${K}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()}};L.current=Vr,W.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:je,automaticRetryUsed:Ot.current});if(p.action==="retry"){Ot.current=!0,ze(!1),st(!1),Pt(!0),pt.current?.("retrying"),sr=setTimeout(()=>{xt||wt(K=>K+1)},Ap);return}if(ze(!1),st(!1),Pt(!1),de(!0),p.action!=="ignore"){if(pt.current?.("exhausted"),p.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",c);return}if(p.report){let K=Ss({code:Kc(s,c),message:c},{inAppBrowser:Ht.inAppBrowser,handoffObserved:!1});K.popupBlocked&&H.markBlocked(),P.error({errorCode:K.popupBlocked?K.errorCode:p.report.errorCode,stage:p.report.stage,operationOutcome:p.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:K.terminalReason})}kt.current||(kt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Kc(s,c)))}};de(!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 K=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(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let J=mp({body:s,sessionId:p,nonce:c?.nonce??yn.current,accountPatch:c?.accountPatch,session:Hn.current,email:Vn.current}),z=await new As(Ae,{telemetry:!1}).processPayment(J.userId,J.params);if(z.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 w=await z.json().catch(()=>null),oe=qc(w),me=oe.message;qe(),z.status===400&&(typeof w?.declineCode=="string"||!Array.isArray(w?.fields))?P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):z.status===400||z.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(z.status),failureCategory:z.status>=500?"server_error":void 0}),Xn(me),Ft(()=>Fn.current?.(gn("paypal",me,{code:oe.code,declineCode:oe.declineCode})));return}catch(J){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 ue=Pp(J instanceof Error?J.message:void 0);Xn(ue),Ft(()=>Fn.current?.(gn("paypal",ue)));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,K=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 As(Ae,{telemetry:!1}).createSessionIntent(p,K??"",fp(Mn),{idempotencyKey:Pe})}catch(J){throw P.error({...hp(J,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),J}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!==q)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 K=c?.sessionId??e,qe=Ip(s);new As(Ae,{telemetry:!1}).reportSessionIntentDecline(K,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={};q==="subscription"?c={intent:"subscription",vault:!0}:q==="order"&&(c={intent:"capture"}),cn=Tp({clientId:l,currency:m,...c,...s?{environment:s}:{},...s==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let p=!1;cn.then(K=>{if(p=!0,_(`loadScript:resolved inactive=${ye()} ns=${!!K} buttons=${!!K?.Buttons}`),ye())return;if(!K?.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(S,M)=>{if(ye()||Me.current!==bn)return;let F=S.vaultSetupToken??S.subscriptionID??S.orderID??"",N=F?Nn.current.get(F):Zt.current.get(bn);if(!(!N||!zn(N.generation))&&_n(N.generation)){Nn.current.delete(F),Zt.current.delete(N.surfaceKey),In("approved");try{if(st(!0),Ft(()=>At.current?.(null)),!F)throw new ra("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ae=Rp({accountPatch:N.accountPatch,email:Vn.current,billingName:rn.current,session:Hn.current});if(wp(ae))try{ae=Sp(ae,await M?.order?.get?.())}catch{}if((yt.current||ct)&&!jc(ae.email)){let U=await Ke("PayPal",ae);if(!U)return;ae=U}jc(ae.email)&&(N.accountPatch=kr({...N.accountPatch,...ae}),await yt.current?.(ae));let Oe=gp(F,Mn);await Ln(Oe,N)}catch(ae){Xn(ae instanceof Error?ae.message:"PayPal capture failed.")}finally{ye()||st(!1)}}},J=S=>{let M=dt?()=>Gr(dt):()=>Br(S);return async()=>Dn(await M())},ue=K.Buttons({style:{layout:"horizontal",height:Ci,tagline:!1},...j==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(S,M)=>{if(ye()){await M.reject();return}Cn();let F=Rn.current,N={};if(F)try{let U=await F("paypal");if(ye()){await M.reject();return}if(!U.proceed){Xt.current=null,Zt.current.delete(bn),await M.reject();return}N={sessionId:U.sessionId,accountPatch:U.accountPatch,nonce:U.nonce}}catch(U){_(`onClick:runBeforeButtonClick rejected msg=${(U instanceof Error?U.message:String(U)).slice(0,120)}`),Xt.current=null,Zt.current.delete(bn),await M.reject();return}Ft(()=>bt.current?.("paypal"));let ae=Ut(),Oe={generation:ae,surfaceKey:bn,...N};Xt.current=Oe,Zt.current.set(bn,Oe),it.current={...T,attempt:ae},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"}),$e.current=P.startTiming()},createOrder:q==="order"?J("Failed to create PayPal order."):void 0,createSubscription:q==="subscription"?J("Failed to create PayPal subscription."):void 0,createVaultSetupToken:q==="setup_token"?async()=>Dn(await Br("Failed to create PayPal setup token.")):void 0,onApprove:qe,onCancel:()=>{if(ye())return;let S=Zt.current.get(bn)??Xt.current,M=S&&zn(S.generation)?yp(S.sessionId??e,Mn):null;S&&Zt.current.delete(S.surfaceKey),Xt.current=null,In("cancelled"),P.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ce.current=!0,zt({generation:S?.generation,remount:!0,focus:!1}),M&&Ft(()=>Ge.current?.(M))},onError:S=>{if(S instanceof ra&&S.code===Wc)return;let M=S instanceof Error?S.message:"PayPal failed to render.";if(ye()||Me.current!==bn){On(M)||en(Wr());return}if(jn){let F=Zt.current.get(bn)??Xt.current;if(!F||!zn(F.generation)){if(On(M)){!F&&!qn()&&_n();return}en(F||qn()?"stale_attempt":"no_current_attempt");return}if(_(`onError rendered=${jn} msg=${M.slice(0,120)}`),On(M)){_n(F.generation);return}let{errorCode:N,popupBlocked:ae,providerDeclined:Oe,terminalReason:U}=Ss(S,{inAppBrowser:Ht.inAppBrowser,handoffObserved:Q.current===F.generation});if(ae&&H.markBlocked(),In(U),Oe){P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:U}),Dr(S,F),Ft(()=>Fn.current?.(gn("paypal",M))),Zt.current.delete(F.surfaceKey),Xt.current=null,_n(F.generation);return}P.error({errorCode:N,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:U}),Zt.current.delete(F.surfaceKey),Xt.current=null,zt({generation:F.generation,remount:!0,showRetry:!0,focus:!0}),gr(S,{code:"paypal_runtime_failed",popupBlocked:ae,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:j,terminalReason:U});return}_(`onError rendered=${jn} msg=${M.slice(0,120)}`),Fe(On(M)?"teardown":"pre_ready_callback",M)}}),z=ue.isEligible();if(_(`isEligible=${z}`),P.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!z){ze(!1),Fe("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ar=!0,Gn=ue,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 F of M)if(F.type==="childList")F.addedNodes.forEach(N=>{if(!(N instanceof Element))return;let ae=N.tagName.toLowerCase(),Oe=(N.getAttribute("title")??"").slice(0,40),U=ae==="iframe"?` ${xr(N)}`:"";_(`child+ ${ae}${Oe?` title="${Oe}"`:""}${U} dims=${rr(N)}`)});else if(F.type==="attributes"&&F.target instanceof Element){let N=F.target;if(N.tagName.toLowerCase()!=="iframe")continue;let ae=F.attributeName;(ae==="src"||ae==="srcdoc")&&_(`attr~ iframe ${ae}=${ae==="srcdoc"?`[${(N.getAttribute("srcdoc")??"").length}ch]`:Kr(N.getAttribute("src"))} dims=${rr(N)}`)}}}),lr.observe(vr,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let S=M=>{if(ye()||jn)return;let F=vr.querySelectorAll("iframe"),N=typeof document<"u"&&"hasStorageAccess"in document;_(`watchdog:${M} container=${rr(vr)} children=${vr.childElementCount} iframes=${F.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${N} paypalNetRequests=${Cr.value}`),F.forEach((ae,Oe)=>{let U=(ae.getAttribute("title")??"").slice(0,40);_(` iframe[${Oe}] ${rr(ae)}${U?` title="${U}"`:""} ${xr(ae)}`);let fe=vo(ae);fe&&_(` ${fe}`)}),Fr.length===0&&_(" (no PayPal/zoid window errors captured)")};ke.push(setTimeout(()=>S("3s"),3e3)),ke.push(setTimeout(()=>S("8s"),8e3)),ke.push(setTimeout(()=>S("15s"),15e3))},cr(),_("render:start");let oe=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=ue.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(oe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(S){let M=S instanceof Error?S.message:"PayPal failed to render.";_(`render:rejected msg=${M.slice(0,120)}`),Jn(),Fe(On(M)?"teardown":"render_rejected",M)}})()}).catch(K=>{let qe=K instanceof Error?K.message:"PayPal operation failed.";_(`provider:failed msg=${qe.slice(0,120)}`);let J="script_rejected";p&&On(qe)?J="teardown":p&&Ar&&(J="render_rejected"),Fe(J,qe)})},0);return()=>{xt=!0,clearTimeout(v),sr&&clearTimeout(sr),Jn(),L.current===Vr&&(L.current=null),Mr(),$e.current=null,it.current=null}},[je,Ae,l,m,u,q,j,$,e,dt,De,Z,Ke,ct,_,In]);let Tn=be?xs("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?`
|
|
1
|
+
import{a as Pc}from"./chunk-D4CVZRT4.mjs";import{c as ut,d as Ur,e as Ra,f as Ss,g as Rs,h as qd,j as jd}from"./chunk-YR36EYW2.mjs";import{a as gc}from"./chunk-BU7THP6H.mjs";import{a as Io,b as di,c as Es,d as Is,e as ka,f as dc,g as pc,h as yc,i as mc,j as fc,k as hc}from"./chunk-FGCZOMML.mjs";import{a as li,b as ws,c as sc,d as ks,e as Ho,f as lc,g as so,h as ci,i as cc,j as wa,k as ui,l as uc}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as YP}from"@flopay/shared";import{PaymentAPI as ml}from"@flopay/js";import{FloPayError as Bo,isDeclineCallbackFailure as cf,isMerchantAuthRequired as dd,resolveBillingApiUrl as uf,resolveButtonsLayoutTheme as df,resolveTheme as pf}from"@flopay/shared";import{useCallback as $r,useEffect as da,useMemo as Ga,useRef as ho,useState as pa}from"react";import{Fragment as Jo,jsx as dr,jsxs as Cc}from"react/jsx-runtime";function $d(){return Cc(Jo,{children:[Cc("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:[dr("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),dr("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",dr("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:dr("path",{d:"M9 18l6-6-6-6"})})]})}function Wd(){return dr(Jo,{children:"Go back"})}function Kd(){return dr(Jo,{children:"Secure card checkout"})}function Vo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Go({content:e}){return dr(Jo,{children:e===void 0?dr($d,{}):e})}function Yo({content:e}){return dr(Jo,{children:e===void 0?dr(Wd,{}):e})}function Ea({content:e}){return dr(Jo,{children:e===void 0?dr(Kd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as Hd,canRecoverHostedCardForm as Vd,classifyTelemetryFailure as Gd,FloPayError as er,isCardHolderNamePlaceholder as Yd,isMoneySettledOutcome as Jd,isMountableVaultBlock as Xd,isSetupIntentClientSecret as Zd,isValidEmail as Qd,resolveSetupFutureUsage as ep,resolveWalletModeOptions as tp}from"@flopay/shared";import{canRecoverHostedCardForm as _o,hasServerSideCardGateway as Ac}from"@flopay/shared";import{splitFullName as Ta}from"@flopay/shared";import{applyFriendlyMessageOverride as Qo}from"@flopay/shared";function _s(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 np(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 vc(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(Xd(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||Vd(o))||t&&e?.data.paypal?.publishableKey)}function bc(e,t){if(t&&(!(e instanceof er)||e.type==="authentication_error"))return _s(e);if(!(e instanceof er&&np(e))){if(!t&&!(e instanceof er)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Gd(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()},d=Yd(l.firstName,l.lastName);if(!Qd(l.email))return Promise.reject(new er("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[w,P]of Object.entries(l)){if(d&&w.endsWith("Name")||typeof P!="string")continue;let g=P.trim();g&&(y[w]=g)}return a=e.claimCheckoutSession(t,n,{accountData:y}),a.catch(()=>{}),a}}function Sc(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 Ts(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Rc(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 Ms(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 wc=new WeakMap;function kc(e,t){return typeof e=="object"&&e!==null&&wc.set(e,t?{sessionId:t}:{}),e}function Ec(e){return typeof e=="object"&&e!==null?wc.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 Ic(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function pi(e){let t=Ic(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 Ic(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(Hd,"api_error",{code:"checkout_processing_timeout"})}function Ia(e,t){return e==="processing"||Jd(e,t)}function _c(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Tc(e,t){let n=e;if(Zd(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 rp=["apple_pay","google_pay"];function Mc(e,t="automatic",n){let o=ep(n,rp,"wallet");return{...tp(e,t),allowedPaymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var op=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function As(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:op.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 jm,PaymentAPI as Oi,SESSION_CREATE_TELEMETRY as $m}from"@flopay/js";import{applyClaimAdvertisement as Gu,buildCheckoutDisplayData as Wm,classifyTelemetryFailure as sd,DEFAULT_PAYMENT_METHOD_ORDER as Km,FloPayError as wn,isDeclineCallbackFailure as Yu,isDetachedSessionEligible as Hm,isExpectedPaymentDecline as Ju,isMerchantAuthRequired as Vm,isMountableVaultBlock as Gm,resolveBillingApiUrl as Ym,resolveButtonsLayoutTheme as Jm,resolveDirectPaypalConfig as ld,resolveIdempotencyKey as Xu,resolveCheckoutLogLayout as Xm,resolveTheme as cd,SDK_VERSION as ud,telemetryStatusClass as Zm,toPublicCheckoutInitError as Zu}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 ap}from"@stripe/react-stripe-js";import{jsx as ip}from"react/jsx-runtime";var xc=new WeakMap,Fc=0;function Bc(e){return!!e&&typeof e=="object"}function Dc(e,t){for(let n of e)!Bc(n)||t.includes(n)||(Fc+=1,xc.set(n,`stripe-account-${Fc}`))}function uo(e){let t=Bc(e.stripe)?xc.get(e.stripe):void 0;return ip(ap,{...e},t)}import{createContext as Oc}from"react";var pr=Oc({flopay:null,paypalFlopay:null,billingApiUrl:""}),Rr=Oc({session:null,loading:!1,error:null});import{PaymentAPI as xs}from"@flopay/js";import{buildPayPalCancelEvent as bp,buildPayPalProcessPaymentRequest as Sp,buildPayPalSessionIntentRequest as Rp,buildPayPalTokenizedBody as wp,classifyTelemetryFailure as kp,describePayPalProcessFailure as Wc,FloPayError as ra,friendlyPayPalFailureMessage as Ep,generateIdempotencyKey as Ip,isPayPalTeardownMessage as _p,isSettledSessionIntent as Tp,isValidEmail as Kc,mergePayPalPayerIdentity as Mp,needsPayPalPayerDetails as Ap,normalizeGatewayEnvironment as Fp,paypalProviderIdentityRequired as Hc,resolvePayPalApprovalIdentity as xp,resolvePayPalDeclineReason as Bp,SDK_VERSION as Dp,usesPayPalVaultedChannel as Op}from"@flopay/shared";import{loadScript as Lp}from"@paypal/paypal-js";import{useCallback as yr,useContext as Np,useEffect as Wt,useMemo as xa,useRef as nt,useState as Zr}from"react";import{compactBuyerIdentity as sp,isValidEmail as lp}from"@flopay/shared";import{useCallback as Lc,useEffect as cp,useRef as Nc,useState as zc}from"react";import{compactBuyerIdentity as wr}from"@flopay/shared";import{jsx as Uc,jsxs as Ma}from"react/jsx-runtime";function ea(){let[e,t]=zc(null),n=Nc(null),o=Nc(0),a=Lc((l,d)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:l,identity:d}),new Promise(y=>{n.current=y})),[]),i=Lc(l=>{let d=n.current;n.current=null,t(null),d?.(l)},[]);return cp(()=>()=>{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,d]=zc(e.email?.trim()??""),y=lp(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",Uc("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:w=>d(w.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&&Uc("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),Ma("button",{type:"button",disabled:!y||a,onClick:()=>{n(sp({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as up}from"@flopay/shared";import{useContext as mi}from"react";function po(){return mi(pr).flopay}function Fs(){return mi(pr).paypalFlopay??null}function dp(){return mi(Rr)}function qc(){return mi(pr).billingApiUrl||up()}import{FLO_INSTRUMENT_ONCE_NAMES as pp,invokeMerchantCallback as yp,projectFloInstrument as mp}from"@flopay/shared";import{useCallback as fp,useRef as fi}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as jc}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 Ra(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),fp(l=>{if(i.current!==t)return;let d=mp(l);if(d){if(pp.has(d.name)){if(o.current.has(d.name))return;o.current.add(d.name)}yp(()=>n.current?.(d))}},[t])}import{createContext as gp}from"react";var Aa=gp(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 hp=Symbol.for("@flopay/js.telemetry.bridge.v1"),Pp=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Cp(){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 vp(e){let t=Cp(),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 Ci(e){let t=globalThis[Pp];return vp(t?.(e)??{})}function hn(e){if(e)return e[hp]}import{useCallback as yo,useEffect as $c,useRef as To}from"react";function Fa(e,t){let n=To(0),o=To(null),a=To(null),i=To(e),l=To(t?.onHandoffObserved),d=To(t?.defersMissingTerminal),y=To(t?.onMissingTerminalDeferred);$c(()=>{i.current=e,l.current=t?.onHandoffObserved,d.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let w=yo((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),P=yo(f=>{w();let $=n.current+1;return n.current=$,o.current=null,a.current={generation:$,method:f,timer:null,yieldedControl:!1},$},[w]),g=yo(f=>{let $=a.current;return f!==void 0&&$?.generation!==f?!1:(w($),a.current=null,(f===void 0||o.current===f)&&(o.current=null),!0)},[w]),_=yo(f=>{let $=a.current,ee=f??$?.generation??n.current;(f===void 0||$?.generation===f)&&(w($),a.current=null),o.current=ee},[w]),O=yo(f=>o.current===(f??n.current),[]),X=yo(f=>a.current?.generation===f&&o.current!==f,[]),F=yo(()=>{let f=a.current;f&&(w(f),!f.yieldedControl&&(f.yieldedControl=!0,l.current?.(f.method)))},[w]),I=yo(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(w(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(d.current?.(f.method)){y.current?.(f.method,f.generation);return}a.current=null,o.current=f.generation,i.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},sc))},[w]);return $c(()=>{let f=()=>{document.visibilityState==="visible"?I():F()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",F),window.addEventListener("focus",I),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",F),window.removeEventListener("focus",I),w()}},[w,F,I]),{startAttempt:P,finishAttempt:g,invalidateAttempt:_,isAttemptInvalidated:O,isAttemptCurrent:X,generationRef:n}}import{jsx as Mo,jsxs as Bs}from"react/jsx-runtime";var vi=45,Up=1e3,zp=11e3,Vc="paypal_intent_settled",qp={width:"100%",minHeight:vi,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"},jp={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 $p(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:jp[e.kind]??null}}function Gc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":lc(t)?"paypal_init_timeout":"paypal_init_failure"}function Wp(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Yc({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:l,environment:d,currency:y,isSubscription:w,providerObjectType:P,approvalPresentation:g,onTokenizedBody:_,onComplete:O,onErrorChange:X,onDecline:F,onCancel:I,onTechnicalFailure:f,isProcessing:$=!1,onLoadStateChange:ee,onInitializationStateChange:k,allowAutomaticRetry:je=!0,onButtonClick:J,runBeforeButtonClick:Ue,session:rt,existingOrderId:dt,telemetry:ke,telemetryContext:Nt,onInstrument:Dt,debug:be=!1}){let He=po(),ot=na(Dt,e),at=xa(()=>{if(He)return null;let A=Ci({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Dp,enabled:ke!==!1});return A.setCheckoutContext(Nt??{}),A.beginCheckout(Nt??{}),A},[n,He,ke,Nt?.checkoutMode,Nt?.layout]),Ee=xa(()=>hn(He),[He]);Wt(()=>()=>{at&&at.flush().catch(()=>{}).finally(()=>at.destroy())},[at]);let te=xa(()=>({error:A=>{Ee?Ee.error(A):at?.error(A),ot({class:"technical_error",errorCode:A.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":A.errorCode,requestCategory:A.requestCategory,provider:A.provider})},log:A=>{Ee?Ee.log(A):at?.log(A),ot({class:"lifecycle",name:A.name,provider:A.provider})},performance:A=>{Ee?Ee.performance(A):at?.performance(A)},terminal:A=>{Ee?Ee.terminal(A):at?.terminal(A)},startTiming:()=>Ee?.now()??at?.now()??0,elapsed:A=>Ee?.elapsed(A)??Math.max(0,(at?.now()??A)-A)}),[ot,Ee,at]),ce=nt(null),Kt=nt(0),$e=nt(null),it=nt(null),ne=nt(null),Te=Np(Aa),Xe=nt(null);Xe.current||(Xe.current=gi());let G=Te??Xe.current,Pt=nt(null),ve=nt(!1),[Ve,ze]=Zr(!1),[Ze,Ct]=Zr(!1),[De,wt]=Zr(0),Me=nt(0),[Ie,vt]=Zr(!1),Ot=nt(!1),kt=nt(!1),[Y,ue]=Zr(!1),[_e,st]=Zr(!1),{request:lt,collect:Ke,finish:bt}=ea(),Tt=nt({sessionId:e,required:Hc(o,rt)});Tt.current.sessionId!==e&&(Tt.current={sessionId:e,required:Hc(o,rt)});let ct=Tt.current.required,Ae=xa(()=>n.replace(/\/+$/,""),[n]),et=rt?.gateways?.paypal?.providerObjectType??P,j=et??(w?"subscription":"order"),[Ht]=Zr(wa),E=rt?.gateways?.paypal?.approvalPresentation??g,W=ui(Ht,E==="app_switch"?"app_switch":void 0,j),K=Op(et),m=xa(()=>JSON.stringify([Ae,l,y,d??"",j,K,W,e,dt??""]),[Ae,l,y,d,dt,j,K,W,e]),ie=nt(m),C=ie.current!==m,H=nt(be),N=nt(null),[he,Se]=Zr([]),M=yr(A=>{H.current&&Se(We=>[...We,`${new Date().toISOString().slice(11,23)} ${A}`])},[]);Wt(()=>{H.current=be,be&&M("debug:enabled"),N.current?.setEnabled(be)},[M,be]);let pt=nt(_),At=nt(O),Ft=nt(X),xn=nt(F),Ge=nt(I),fr=nt(f),St=nt(J),Ir=nt(ee),yt=nt(k),mt=nt(i),kn=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),Fe=nt(!1),Re=nt(e);Re.current=e;let[tr]=Zr(Pi);Wt(()=>(Fe.current=!0,()=>{Fe.current=!1}),[]),Wt(()=>{pt.current=_},[_]),Wt(()=>{mt.current=i},[i]),Wt(()=>{At.current=O},[O]),Wt(()=>{Ft.current=X},[X]),Wt(()=>{xn.current=F},[F]),Wt(()=>{Ge.current=I},[I]),Wt(()=>{fr.current=f},[f]),Wt(()=>{St.current=J},[J]),Wt(()=>{Ir.current=ee},[ee]),Wt(()=>{yt.current=k},[k]),Wt(()=>{kn.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(()=>{Ie&&Pt.current?.focus()},[Ie,De]);let Rt=yr(()=>{window.setTimeout(()=>{Pt.current?.focus()},0)},[]),Bn=yr(()=>{ze(!1),wt(A=>A+1)},[]),Qt=yr(()=>{vt(!1),(ce.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ce.current)?.focus?.()},[]);Wt(()=>{!Ve||!ve.current||(ve.current=!1,Qt())},[Qt,Ve,De]);let gr=yr((A,We)=>{let v=We?.popupBlocked??so(A);v&&G.markBlocked();let se=li("PayPal",v,Ht.inAppBrowser),Et=fr.current;if(Et){let xt=v&&Ht.inAppBrowser?new ra(se,"api_error",{code:We?.code??"paypal_popup_blocked"}):A;Et("paypal",xt,We);return}if(A instanceof ra&&A.code==="checkout_processing_timeout"){Ft.current?.(A.message);return}Ft.current?.(se)},[G,Ht.inAppBrowser]),En=yr(A=>{let We=$e.current,v=it.current;We===null||!v||(te.log({...v,popupCapability:G.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:A}),te.performance({...v,popupCapability:G.current(),stage:"overlay_return",durationMs:te.elapsed(We),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:A}),$e.current=null)},[G,te]),_r=yr((A,We,v)=>{let se=it.current;En("overlay_timeout"),se&&te.error({...se,popupCapability:G.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),gr(We,{...v,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:W,terminalReason:"overlay_timeout"}),vt(!0),Bn(),Rt()},[En,Rt,gr,G,W,Bn,te]),hr=yr(()=>{G.markAvailable();let A=it.current;A&&(ne.current=A.attempt,te.log({...A,popupCapability:G.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[G,te]),In=yr(()=>!0,[]),mn=yr(()=>{let A=it.current;if(!A)return;let We=$e.current;te.performance({...A,popupCapability:G.current(),stage:"overlay_return",durationMs:We===null?0:te.elapsed(We),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[G,te]),{finishAttempt:_n,generationRef:Pr,invalidateAttempt:Un,isAttemptCurrent:zn,isAttemptInvalidated:qn,startAttempt:fn}=Fa(_r,{onHandoffObserved:hr,defersMissingTerminal:In,onMissingTerminalDeferred:mn}),Ut=yr(()=>(vt(!1),fn("paypal")),[fn]),zt=yr(A=>{Un(A?.generation),A?.showRetry&&vt(!0),A?.remount&&Bn(),A?.focus!==!1&&Rt()},[Rt,Un,Bn]),Dn=A=>{let We=Xt.current;return We&&Nn.current.set(A,We),A};Wt(()=>{ie.current!==m&&(ie.current=m,Ot.current=!1,kt.current=!1,ze(!1),Ct(!1),ue(!1),yt.current?.("loading"))},[m]),Wt(()=>{ut(()=>Ir.current?.(Ve&&!Y))},[Ve,Y]);let Cn=Fp(d);Wt(()=>{let A={attempt:Pr.current+1,inAppBrowser:Ht.inAppBrowser,appFamily:Ht.appFamily,popupCapability:G.current(),presentationMode:W},We=()=>({...it.current??A,popupCapability:G.current()}),v={error:s=>te.error({...s,...We()}),log:s=>te.log({...s,...We()}),performance:s=>te.performance({...s,...We()}),terminal:s=>te.terminal({...s,...We()}),startTiming:te.startTiming,elapsed:te.elapsed},se=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Et=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(M(`mount clientId=${se} env=${d??"(unset)"}\u2192${Cn??"live"} ccy=${y} sub=${w}`),M(`ua=${Et.slice(0,80)}${Et.length>80?"\u2026":""}`),!l){M("FAIL: clientId empty \u2014 gateway misconfigured"),ue(!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(!ce.current){M("FAIL: containerRef not attached");return}Kt.current=v.startTiming(),v.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let xt=!1,Vt=!1,ye=()=>xt||Vt,en=s=>{let c=Fe.current,p=c?s:"torn_down";c&&M(`onError ignored reason=${p}`),tr.take(Re.current)&&v.log({name:hi,stage:"provider_ready",reason:p,provider:"paypal",paymentMethodCategory:"paypal"})},Wr=()=>Re.current===e?"stale_attempt":"session_changed",Mn=K?j:void 0,Pe,Tr=!1,vn=()=>{Pe=Ip(),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,Cr=ce.current,lr=null,Yn=null,we=[],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)}},Fr=s=>{let c=s.getAttribute("src"),p=s.getAttribute("srcdoc"),V=s.getAttribute("name"),qe=s.getAttribute("sandbox"),Z=[];return c&&Z.push(`src=${Kr(c)}`),p&&Z.push(`srcdoc[${p.length}ch]`),!c&&!p&&Z.push("src=(empty) srcdoc=(empty)"),V&&Z.push(`name=${V.slice(0,40)}`),qe!==null&&Z.push(`sandbox="${qe.slice(0,40)}"`),Z.join(" ")},Co=s=>{if(!(s instanceof HTMLIFrameElement))return"";try{let c=s.contentDocument;if(!c)return"cd=null";let p=c.body?.children.length??0,V=c.body?.innerHTML.length??0,qe=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${p}children,${V}ch] head[${qe}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},xr=[],vo=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"))&&(M(`window:error ${c.slice(0,140)}`),xr.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"))&&(M(`window:rejection ${c.slice(0,140)}`),xr.push(c))},vr={value:0},eo=()=>{lr?.disconnect(),lr=null,Yn?.disconnect(),Yn=null;for(let s of we.splice(0))clearTimeout(s);ln=!1,$n&&typeof window<"u"&&(window.removeEventListener("error",vo),window.removeEventListener("unhandledrejection",Hr)),$n=!1},to=()=>{if(!($n||ye()||jn)){if($n=!0,xr.length=0,vr.value=0,typeof window<"u"&&(window.addEventListener("error",vo),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;vr.value+=1;let p=Math.round(c.duration);M(`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()}};N.current=Vr,H.current&&to();let On=_p,Xn=s=>{if(ye()||On(s))return;let c=Qo(s)??s;ut(()=>Ft.current?.(c))},xe=(s,c)=>{if(xt||Po)return;Po=!0,Vt=!0,Jn(),Mr();let p=$p({kind:s,generationActive:!0,automaticRetryAllowed:je,automaticRetryUsed:Ot.current});if(p.action==="retry"){Ot.current=!0,ze(!1),st(!1),Ct(!0),yt.current?.("retrying"),sr=setTimeout(()=>{xt||wt(V=>V+1)},Up);return}if(ze(!1),st(!1),Ct(!1),ue(!0),p.action!=="ignore"){if(yt.current?.("exhausted"),p.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",c);return}if(p.report){let V=ws({code:Gc(s,c),message:c},{inAppBrowser:Ht.inAppBrowser,handoffObserved:!1});V.popupBlocked&&G.markBlocked(),v.error({errorCode:V.popupBlocked?V.errorCode:p.report.errorCode,stage:p.report.stage,operationOutcome:p.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:V.terminalReason})}kt.current||(kt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Gc(s,c)))}};ue(!1);let Ln=async(s,c=Xt.current)=>{if(ye())return;let p=c?.sessionId??e;if(pt.current){await pt.current(s,{sessionId:p,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let V=v.startTiming();v.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let qe=()=>{v.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),v.performance({stage:"processing",durationMs:v.elapsed(V),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Z=Sp({body:s,sessionId:p,nonce:c?.nonce??yn.current,accountPatch:c?.accountPatch,session:Hn.current,email:Vn.current}),q=await new xs(Ae,{telemetry:!1}).processPayment(Z.userId,Z.params);if(q.ok){if(Vt||xt&&Fe.current)return;qe(),v.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),ut(()=>At.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ye())return;let R=await q.json().catch(()=>null),oe=Wc(R),me=oe.message;qe(),q.status===400&&(typeof R?.declineCode=="string"||!Array.isArray(R?.fields))?v.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):q.status===400||q.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:Wp(q.status),failureCategory:q.status>=500?"server_error":void 0}),Xn(me),ut(()=>xn.current?.(gn("paypal",me,{code:oe.code,declineCode:oe.declineCode})));return}catch(Z){if(ye())return;qe(),v.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let de=Ep(Z instanceof Error?Z.message:void 0);Xn(de),ut(()=>xn.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){v.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),ut(()=>At.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let c=await s.json().catch(()=>null),p=Wc(c);v.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),ut(()=>xn.current?.(gn("paypal",p.message,{code:p.code,declineCode:p.declineCode})))},bo=()=>{let s=Xt.current;En("approved"),s&&(Zt.current.delete(s.surfaceKey),_n(s.generation)),Xt.current=null},Br=async s=>{if(ye())throw $t();Tr||vn();let c=Xt.current,p=c?.sessionId??e,V=c?.nonce??yn.current;v.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let qe;try{qe=await new xs(Ae,{telemetry:!1}).createSessionIntent(p,V??"",Rp(Mn),{idempotencyKey:Pe})}catch(Z){throw v.error({...kp(Z,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Z}if(ye())throw $t();if(Tp(qe))throw await no(qe.response),bo(),new ra("PayPal checkout already settled.","api_error",{code:Vc});if(qe.provider!=="paypal"||qe.providerObjectType!==j)throw new Error(s);return v.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 V=c?.sessionId??e,qe=Bp(s);new xs(Ae,{telemetry:!1}).reportSessionIntentDecline(V,p,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:qe}).catch(()=>{})},bn=De;M("loadScript:scheduled (deferred 1 tick)");let cn=null,b=setTimeout(()=>{if(xt){M("loadScript:skipped (cancelled before defer ran)");return}M("loadScript:start");let s=Cn==="live"?"production":Cn,c={};j==="subscription"?c={intent:"subscription",vault:!0}:j==="order"&&(c={intent:"capture"}),cn=Lp({clientId:l,currency:y,...c,...s?{environment:s}:{},...s==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let p=!1;cn.then(V=>{if(p=!0,M(`loadScript:resolved inactive=${ye()} ns=${!!V} buttons=${!!V?.Buttons}`),ye())return;if(!V?.Buttons){M("FAIL: namespace missing Buttons factory"),xe("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(Kt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),v.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let qe=async(S,x)=>{if(ye()||Me.current!==bn)return;let B=S.vaultSetupToken??S.subscriptionID??S.orderID??"",U=B?Nn.current.get(B):Zt.current.get(bn);if(!(!U||!zn(U.generation))&&_n(U.generation)){Nn.current.delete(B),Zt.current.delete(U.surfaceKey),En("approved");try{if(st(!0),ut(()=>Ft.current?.(null)),!B)throw new ra("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ae=xp({accountPatch:U.accountPatch,email:Vn.current,billingName:rn.current,session:Hn.current});if(Ap(ae))try{ae=Mp(ae,await x?.order?.get?.())}catch{}if((mt.current||ct)&&!Kc(ae.email)){let z=await Ke("PayPal",ae);if(!z)return;ae=z}Kc(ae.email)&&(U.accountPatch=wr({...U.accountPatch,...ae}),await mt.current?.(ae));let Oe=wp(B,Mn);await Ln(Oe,U)}catch(ae){Xn(ae instanceof Error?ae.message:"PayPal capture failed.")}finally{ye()||st(!1)}}},Z=S=>{let x=dt?()=>Gr(dt):()=>Br(S);return async()=>Dn(await x())},de=V.Buttons({style:{layout:"horizontal",height:vi,tagline:!1},...W==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(S,x)=>{if(ye()){await x.reject();return}vn();let B=kn.current,U={};if(B)try{let z=await B("paypal");if(ye()){await x.reject();return}if(!z.proceed){Xt.current=null,Zt.current.delete(bn),await x.reject();return}U={sessionId:z.sessionId,accountPatch:z.accountPatch,nonce:z.nonce}}catch(z){M(`onClick:runBeforeButtonClick rejected msg=${(z instanceof Error?z.message:String(z)).slice(0,120)}`),Xt.current=null,Zt.current.delete(bn),await x.reject();return}ut(()=>St.current?.("paypal"));let ae=Ut(),Oe={generation:ae,surfaceKey:bn,...U};Xt.current=Oe,Zt.current.set(bn,Oe),it.current={...A,attempt:ae},await x.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"}),$e.current=v.startTiming()},createOrder:j==="order"?Z("Failed to create PayPal order."):void 0,createSubscription:j==="subscription"?Z("Failed to create PayPal subscription."):void 0,createVaultSetupToken:j==="setup_token"?async()=>Dn(await Br("Failed to create PayPal setup token.")):void 0,onApprove:qe,onCancel:()=>{if(ye())return;let S=Zt.current.get(bn)??Xt.current,x=S&&zn(S.generation)?bp(S.sessionId??e,Mn):null;S&&Zt.current.delete(S.surfaceKey),Xt.current=null,En("cancelled"),v.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ve.current=!0,zt({generation:S?.generation,remount:!0,focus:!1}),x&&ut(()=>Ge.current?.(x))},onError:S=>{if(S instanceof ra&&S.code===Vc)return;let x=S instanceof Error?S.message:"PayPal failed to render.";if(ye()||Me.current!==bn){On(x)||en(Wr());return}if(jn){let B=Zt.current.get(bn)??Xt.current;if(!B||!zn(B.generation)){if(On(x)){!B&&!qn()&&_n();return}en(B||qn()?"stale_attempt":"no_current_attempt");return}if(M(`onError rendered=${jn} msg=${x.slice(0,120)}`),On(x)){_n(B.generation);return}let{errorCode:U,popupBlocked:ae,providerDeclined:Oe,terminalReason:z}=ws(S,{inAppBrowser:Ht.inAppBrowser,handoffObserved:ne.current===B.generation});if(ae&&G.markBlocked(),En(z),Oe){v.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:z}),Dr(S,B),ut(()=>xn.current?.(gn("paypal",x))),Zt.current.delete(B.surfaceKey),Xt.current=null,_n(B.generation);return}v.error({errorCode:U,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:z}),Zt.current.delete(B.surfaceKey),Xt.current=null,zt({generation:B.generation,remount:!0,showRetry:!0,focus:!0}),gr(S,{code:"paypal_runtime_failed",popupBlocked:ae,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:W,terminalReason:z});return}M(`onError rendered=${jn} msg=${x.slice(0,120)}`),xe(On(x)?"teardown":"pre_ready_callback",x)}}),q=de.isEligible();if(M(`isEligible=${q}`),v.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!q){ze(!1),xe("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,M(`container:dims ${rr(Cr)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(lr=new MutationObserver(x=>{if(!ye()){for(let B of x)if(B.type==="childList")B.addedNodes.forEach(U=>{if(!(U instanceof Element))return;let ae=U.tagName.toLowerCase(),Oe=(U.getAttribute("title")??"").slice(0,40),z=ae==="iframe"?` ${Fr(U)}`:"";M(`child+ ${ae}${Oe?` title="${Oe}"`:""}${z} dims=${rr(U)}`)});else if(B.type==="attributes"&&B.target instanceof Element){let U=B.target;if(U.tagName.toLowerCase()!=="iframe")continue;let ae=B.attributeName;(ae==="src"||ae==="srcdoc")&&M(`attr~ iframe ${ae}=${ae==="srcdoc"?`[${(U.getAttribute("srcdoc")??"").length}ch]`:Kr(U.getAttribute("src"))} dims=${rr(U)}`)}}}),lr.observe(Cr,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let S=x=>{if(ye()||jn)return;let B=Cr.querySelectorAll("iframe"),U=typeof document<"u"&&"hasStorageAccess"in document;M(`watchdog:${x} container=${rr(Cr)} children=${Cr.childElementCount} iframes=${B.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${U} paypalNetRequests=${vr.value}`),B.forEach((ae,Oe)=>{let z=(ae.getAttribute("title")??"").slice(0,40);M(` iframe[${Oe}] ${rr(ae)}${z?` title="${z}"`:""} ${Fr(ae)}`);let fe=Co(ae);fe&&M(` ${fe}`)}),xr.length===0&&M(" (no PayPal/zoid window errors captured)")};we.push(setTimeout(()=>S("3s"),3e3)),we.push(setTimeout(()=>S("8s"),8e3)),we.push(setTimeout(()=>S("15s"),15e3))},cr(),M("render:start");let oe=v.startTiming();An=setTimeout(()=>{ye()||jn||(M("watchdog:11s retryable render timeout"),xe("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},zp);let me=de.render(Cr);(async()=>{try{if(await me,M(`render:resolved inactive=${ye()}`),Jn(),ye()){Mr();return}jn=!0,ze(!0),Ct(!1),yt.current?.("ready"),v.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),v.performance({stage:"checkout_render",durationMs:v.elapsed(oe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(S){let x=S instanceof Error?S.message:"PayPal failed to render.";M(`render:rejected msg=${x.slice(0,120)}`),Jn(),xe(On(x)?"teardown":"render_rejected",x)}})()}).catch(V=>{let qe=V instanceof Error?V.message:"PayPal operation failed.";M(`provider:failed msg=${qe.slice(0,120)}`);let Z="script_rejected";p&&On(qe)?Z="teardown":p&&Ar&&(Z="render_rejected"),xe(Z,qe)})},0);return()=>{xt=!0,clearTimeout(b),sr&&clearTimeout(sr),Jn(),N.current===Vr&&(N.current=null),Mr(),$e.current=null,it.current=null}},[je,Ae,l,y,d,j,W,K,e,dt,De,te,Ke,ct,M,En]);let Tn=be?Bs("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Y?"#fef2f2":"#f3f4f6",border:`1px solid ${Y?"#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=${Y})`,he.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
3
|
${he.join(`
|
|
4
|
-
`)}`]}):null;return V&&!h?be?Mo("div",{children:Tn}):null:xs("div",{children:[Tn,lt&&Mo(ta,{identity:lt.identity,methodLabel:lt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ct,onCancel:()=>Ct(null)}),xs("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:ce,"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||ne},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 Fs,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),I=rd(null),b=rd(null),g=na(o),A=qp(x=>{Up(x)||g(x)},[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 x=hn(i);return I.current=x?.beginCheckout()??x?.now()??0,x?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{x?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),mo(()=>{let x=!1;return e instanceof Promise?e.then(D=>{x||l(D)},()=>{x||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{x=!0}},[g,e]),mo(()=>{let x=!1;if(!t){m(null);return}return t instanceof Promise?t.then(D=>{x||m(D)},()=>{x||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{x=!0}},[g,t]),mo(()=>{if(!i||b.current===i)return;b.current=i;let x=hn(i);x?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),x?.performance({stage:"checkout_render",durationMs:x.elapsed(I.current??0),durationMode:"machine"})},[g,i]);let Y=zp(n?.billingApiUrl),te=jp(()=>({flopay:i,paypalFlopay:u,billingApiUrl:Y,emitInstrument:g}),[i,u,Y,g]);return $p(pr.Provider,{value:te,children:a})}import{markSessionRecentlyCompleted as aa,wasSessionRecentlyCompleted as Bs}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 Os,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||Os(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:b=>zr({type:b.declineReason??"authorization_declined",gatewayErrorCode:b.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(b){if(a.aborted||b instanceof Error&&b.name==="AbortError")throw b instanceof Tt&&b.code==="three_ds_aborted"?b:ia(b);if(!(b instanceof Tt)||b.code!=="three_ds_timeout"&&b.code!=="checkout_processing_timeout")throw b;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 I=m&&co(m,t.session);if(!Xr(I))throw Zo(I);return{...Jr(I,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(Os(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 Ds(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,I=[m.stripeClientSecret,m.clientSecret];for(let b of I)if(typeof b=="string"&&b.length>0&&(!t?.requirePaymentIntentClientSecret||Ei(b)))return b}}}}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,I=o??n.clientSecret,b=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",A=n.customer?.firstName??n.accountData?.firstName??"",Y=n.customer?.lastName??n.accountData?.lastName??"",te=n.customer?.country??n.accountData?.country??void 0,x=n.customer?.zip??n.accountData?.zip??void 0,C=await new Oa(u,l===!1?{telemetry:!1}:void 0).processPayment(b,{sessionId:m,nonce:I,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:b,email:g,firstName:A,lastName:Y,country:te,zip:x},returnUrl:i??Ds(n)});if(C.ok){let re=typeof C.json=="function"?await C.json().catch(()=>null):null;if(Gp(n)||re?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof re?.paymentId=="string"?re.paymentId:n.paymentId,sessionId:typeof re?.sessionId=="string"?re.sessionId:m,authorizationExpiresAt:typeof re?.authorizationExpiresAt=="string"?re.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:_a(a),checkoutMethod:sd(a,n)}};let k=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...k?{paymentIntentId:k}:{},paymentMethodId:_a(a),checkoutMethod:sd(a,n)}}}let ne;try{ne=await C.json()}catch(re){throw new Tt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:C.status,cause:re})}if(Os(ne))throw La(dd(C.status),"card");if(ne?.type==="3ds_required"&&typeof ne.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:ne.nextActionRedirectUrl};if(ne?.type==="paypal_redirect_required"||ne?.type==="3ds_required"){let re=ud(ne);if(!re)throw new Tt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:C.status});return{type:ne.type,threeDSecureToken:re,paymentMethodId:ne.paymentMethodId}}if(ne?.gatewayErrorCode==="authentication_required"){let re=await ty({billingApiUrl:u,sessionId:m,nonce:I,responseJson:ne});if(re)return re;throw La(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw ny(ne,C.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:I}){let b=t?.getRawProvider();if(!b)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,Y=e.paymentMethodId,te=await Da(()=>Zp(b,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 D=te.intent;!Y&&D?.payment_method&&(typeof D.payment_method=="string"?Y=D.payment_method:"id"in D.payment_method&&(Y=D.payment_method.id??void 0))}let x=Y?await Da(()=>Qp(b,e.threeDSecureToken,{payment_method:Y,return_url:u??Ds(l)??window.location.href},g),"card"):null;if(x){if(x.error)throw Qr(new Tt(x.error.message??"3DS authentication failed.","api_error",{code:x.error.code}),"card");A=x.intent}else{let D=await Da(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(D.error)throw Qr(new Tt(D.error.message??"3DS authentication failed.","api_error",{code:D.error.code}),"card");A=(g?D.setupIntent:D.paymentIntent)??null}if(A&&(A.status==="requires_capture"||A.status==="succeeded"||A.status==="processing")){let D=await la({billingApiUrl:a,sessionId:i,session:l,telemetry:m,tokenizedData:{id:A.id,type:"card",threeDSecureActionResultTokenId:A.id},returnUrl:u});return D.type==="success"?{...D.result,paymentIntentId:D.result.paymentIntentId??A.id,paymentMethodId:D.result.paymentMethodId??Y}:D.type==="next_action_required"?sa(D,{billingApiUrl:a,sessionId:i??l.id,session:l,signal:I}):_i(D,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:l,returnUrl:u,telemetry:m,signal:I})}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:Y}=await Da(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(Y)throw Qr(new Tt(Y.message??"PayPal authorization failed.","api_error",{code:Y.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:A}=await Da(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:u??Ds(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 Ls(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 Ns({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(I=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",I),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 Ys,getStateFromPostalCode as Dy,getStateLabel as qs,getStateOptions as Oy,getStripeMethodDisplayName as Wa,hasMatchingStripePayPalReturn as Ly,invokeMerchantCallback as vd,isAuthorizationOnlySession as js,isAVSFieldVisible as nn,isCardFormFirst as Ny,isMountableVaultBlock as Uy,isPostalCodeSupported as zy,isSettledSessionIntent as Fi,isSetupIntentClientSecret as $s,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 Ws,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 Qs,useStripe as el}from"@stripe/react-stripe-js";import ja,{useCallback as Be,useContext as da,useEffect as Je,useLayoutEffect as nm,useMemo as gt,useRef as O,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 Us({label:e,open:t,showLink:n,onOpen:o,color:a,fontFamily:i,children:l}){let u=oy(),m=pd(null),I=pd(!1);return ry(()=>{t&&I.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:()=>{I.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 zs({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),I=!1,b=te=>{I||(I=!0,u(te))},g=()=>b(py(m));if(!t||!n||!o){g();return}let A=new AbortController,Y=setTimeout(()=>{g(),A.abort()},fy);return new dy(o,{telemetry:!1}).resolvePaymentMethodLayout(t,n,m,{signal:A.signal}).then(te=>{if(!te){g();return}I||hd(te.warnings),b({order:te.order,moreOptions:te.moreOptions})}).catch(g).finally(()=>clearTimeout(Y)),()=>{I=!0,clearTimeout(Y),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 tl(e){return`${rm}:${e}`}function Ai(e){return sn(tl(e))}function xi(e,t){if(typeof window>"u")return null;let n=tl(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(tl(e.sessionId),e)}function Rd(e,t,n){let o=xi(e,t);return!o||o.clientSecret!==n?!1:Ai(e)}function Ks(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 Hs(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 Vs=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 nl(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 rl(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 Js={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 Xs(e){return e==="paypal"?"PayPal":Wa(e)}function Rm(e){let t=By(e);return`Enter a valid ${Ys(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 ol(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:I,runBeforeButtonClick:b,billingName:g,onBuyerIdentityReady:A,onLoadStateChange:Y,placeholderBorderRadius:te,popupCapabilityOwner:x,externalTelemetryContext:D,presentationMode:C}){let ne=po(),{emitInstrument:re}=da(pr),k=el(),je=Qs(),G=gt(()=>Ti(hn(ne),D),[D,ne]),[Ue,rt]=ee("loading");Je(()=>{Y?.(Ue)},[Ue,Y]);let[dt,Re]=ee(!1),Nt=O(!1),Dt=!xn(n?.trim())||!g?.trim(),{request:be,collect:He,finish:ot}=ea(),at=O(!1),Ie=O(null),Z=O(null),[ce,Kt]=ee(0),[$e,it]=ee(!1),Q=O(!1),Te=O(new Map),{startAttempt:Xe,finishAttempt:H,invalidateAttempt:ht,isAttemptInvalidated:Ce,isAttemptCurrent:Ve,generationRef:ze}=xa((de,_e,st)=>{I?.(de,_e,{...st,popupBlocked:st?.popupBlocked??so(_e),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:C,terminalReason:"overlay_timeout"}),it(!0),Kt(lt=>lt+1)},{onHandoffObserved:()=>{x.markAvailable(),G?.log({name:"provider.popup.opened",stage:"overlay_open",...Ir,attempt:ze.current})}});Je(()=>{$e&&Z.current?.focus()},[$e,ce]);let Ze=Be(()=>{Kt(de=>de+1)},[]),Pt=Be((de,_e,st)=>{ht(st),I?.("paypal",de,{code:_e,popupBlocked:so(de),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:C}),it(!0),Ze()},[ht,I,C,Ze]),De=Be(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);Je(()=>{Q.current&&(Q.current=!1,De())},[De,ce]);let wt=Be(()=>{it(!1),i?.(null),De()},[De,i]);Je(()=>{if(!k||at.current)return;let[de,_e,st]=Bd();if(!de||!_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(()=>k.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 q="PayPal payment was declined. Please try again.";G?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}),i?.(q),m?.(gn("paypal",q));return}let et=Qe?.paymentIntent;if(et&&et.id!==de){ct(),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},{..._t,presentationMode:"redirect"})}else{let q="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?.(q),m?.(gn("paypal",q))}}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}},[k,a,i,m,G]);let Me=Be(async(de=!1)=>{let _e=b?await b("paypal"):{proceed:!0};if(!_e.proceed)return Te.current.delete(ce),!1;let st=Xe("paypal");return Te.current.set(ce,{generation:st,accountPatch:_e.accountPatch,sessionId:_e.sessionId,nonce:_e.nonce}),it(!1),G?.log({name:`provider.${de?"redirect.started":"handoff.requested"}`,stage:de?"redirect":"overlay_open",...Ir,attempt:st}),u?.("paypal"),!0},[u,G,b,Xe,ce]),Ee=Be(async de=>{if(l||dt||!await Me()){de.reject();return}de.resolve()},[l,Me,dt]),vt=Be(async de=>{if(!k||!je)return;let _e=Te.current.get(ce);if(_e&&!Ve(_e.generation)){Te.current.delete(ce);return}if(!_e&&Ce()||_e&&!H(_e.generation))return;_e||H();let st=_e??null;if(Te.current.delete(ce),!st&&b){let Ae=await b("paypal");if(!Ae.proceed){de.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:de,prepared:st,email:n,billingName:g,methodLabel:"PayPal",collect:He});if(!Ct){de.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=k.createPaymentMethod,{error:Qe,paymentMethod:et}=await Ae({type:"paypal"});if(Qe){Pt(Qe,"stripe_paypal_create_payment_method_failed",_e?.generation),de.paymentFailed({reason:"fail"});return}let q=await Bi(o,re,lt,Ke??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:et?.id??null,intentKind:"payment"});if(Fi(q)){de.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:ct,paymentMethodCategory:"paypal",presentationMode:C,sessionId:lt,nonce:Ke,settledProcessResponse:q.response});return}if(q.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ht=q.clientSecret,R={return_url:Od()};if(et?.id&&(R.payment_method=et.id),!sn(Vs,{clientSecret:Ht,sessionId:lt,nonce:Ke,accountPatch:ct})&&C==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:$,paymentIntent:y}=await k.confirmPayment({clientSecret:Ht,confirmParams:R,redirect:"if_required"});if($){if(sn(Vs),ci($)){let h=$.message??"Your payment was declined.";G?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}),i?.(h),m?.(gn("paypal",h,{code:Ho($),declineCode:ws($)})),await Di({billingApiUrl:o,sessionId:lt,nonce:Ke,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ho($)??"provider_declined"}})}else Pt($,"stripe_paypal_confirm_failed",_e?.generation);return}sn(Vs);let ie=typeof y?.payment_method=="string"?y.payment_method:y?.payment_method?.id;a({id:ie??y?.id,type:"card",threeDSecureActionResultTokenId:y?.id,isPaypal:!0},{accountPatch:ct,paymentMethodCategory:"paypal",presentationMode:C,sessionId:lt,nonce:Ke});return}catch(Ae){Pt(Ae,"stripe_paypal_failed",_e?.generation)}finally{Re(!1)}},[k,je,e,t,n,g,He,A,o,re,a,i,m,b,Pt,H,Ve,Ce,G,C,ce]),Ot=Be(async()=>{if(!(Nt.current||l||dt||!k||!je)){Nt.current=!0,Re(!0);try{if(!await Me(!0))return;await vt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Nt.current=!1,Re(!1)}}},[je,vt,l,Me,k,dt]),kt=C==="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:de=>rt(ks(de,["paypal"])),onLoadError:()=>{rt("load_error"),nl(G,"paypal","paypal","provider_error")},onClick:Ee,onConfirm:vt,onCancel:()=>{let de=Te.current.get(ce);Te.current.delete(ce),G?.terminal({outcome:"payment_cancelled",...Ir,terminalReason:"cancelled",...de?{attempt:de.generation}:{}}),ht(de?.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"}}},ce),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:[$e&&d("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:wt,style:Js,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 C==="redirect"?V:d(Rs,{state:Ue,placeholderTestId:"flopay-paypal-placeholder",borderRadius:te,children:V})}function Gs(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:I,onTechnicalFailure:b,runBeforeButtonClick:g,billingName:A,onBuyerIdentityReady:Y,onLoadStateChange:te,placeholderBorderRadius:x,popupCapabilityOwner:D,externalTelemetryContext:C}){let ne=po(),{emitInstrument:re}=da(pr),k=el(),je=Qs(),G=gt(()=>Ti(hn(ne),C),[C,ne]),[Ue,rt]=ee("loading");Je(()=>{te?.(Ue)},[Ue,te]);let[dt,Re]=ee(!1);Je(()=>{it.current=dt},[dt]);let Nt=O(!xn(n?.trim())||!A?.trim()).current,{request:Dt,collect:be,finish:He}=ea(),ot=O(null),at=O(null),[Ie,Z]=ee(0),[ce,Kt]=ee(()=>wd()),$e=O(ce),it=O(!1),[Q,Te]=ee(!1),[Xe,H]=ee(()=>xi(e,t)?"blocked":"idle"),[ht,Ce]=ee("google_pay"),Ve=O(null),ze=O(!0),Ze=O(!1),Pt=O("google_pay"),De=O("google_pay"),wt=O(null),Me=O(null),Ee=O(new Set),vt=O(null),Ot=O(null);Je(()=>(ze.current=!0,()=>{ze.current=!1;for(let h of Ee.current)window.clearTimeout(h);Ee.current.clear()}),[]);let kt=O(new Map),{startAttempt:V,finishAttempt:de,invalidateAttempt:_e,isAttemptInvalidated:st,isAttemptCurrent:lt,generationRef:Ke}=xa((h,W,L)=>{b?.(h,W,{...L,popupBlocked:L?.popupBlocked??so(W),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Ce(h),Te(!0),Z(he=>he+1)},{onHandoffObserved:h=>{Ot.current=Ke.current,D.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:Gs,onMissingTerminalDeferred:(h,W)=>{let L=G?.now()??globalThis.performance?.now()??Date.now(),he=vt.current,Se=he?.generation===W?he.startedAt:L;G?.performance({stage:"overlay_return",durationMs:Math.max(0,L-Se),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:W,...Gs(h)?{walletType:h}:{}}),G?.flush?.().catch(()=>{})}});Je(()=>{Q&&at.current?.focus()},[Q,Ie]);let Ct=O(0),_t=O(!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,W,L,he,Se=!1)=>{_e(he),b?.(h,W,{code:L,popupBlocked:so(W),telemetryReported:Se,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Ce(h),Te(!0),ct()},[_e,b,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",...Gs(h)?{walletType:h}:{}}),b?.(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)},[b,G]),q=Be(()=>{window.setTimeout(()=>{(ot.current?.querySelector("iframe")??ot.current)?.focus()},0)},[]);Je(()=>{Ze.current&&(Ze.current=!1,q())},[q,Ie]);let Ht=Be(()=>{Te(!1),u?.(null),q()},[q,u]),R=Be(()=>{Ve.current?.()},[]);Je(()=>{let h=null,W=()=>{h=null;let he=wd();he!==$e.current&&($e.current=he,Kt(he),!it.current&&!lt(Ke.current)&&ct())},L=()=>{h!==null&&window.clearTimeout(h),h=window.setTimeout(W,Am)};return window.addEventListener("resize",L),()=>{window.removeEventListener("resize",L),h!==null&&window.clearTimeout(h)}},[Ke,lt,ct]),Je(()=>{let h=xi(e,t);if(!h)return;let W=!1,L=!1,he=async()=>{if(!L){L=!0,W||H("checking");try{let Se=await Id(k,h.clientSecret,Ee.current);if(W)return;let _=Hs(Se,h.providerObjectId,$s(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"){Ks(e,t,h.clientSecret),Ve.current=null,H("idle"),Ce(h.paymentMethodType),Te(!0),ct();return}H("blocked")}catch{W||H("blocked")}finally{L=!1}}};return Ve.current=he,H("blocked"),()=>{W=!0,Ve.current===he&&(Ve.current=null)}},[t,l,ct,e,k]);let j=Be(async h=>{let W=!1,L=!1,he=xe=>{W||L||(W=!0,h.paymentFailed({reason:"fail",...xe?{message:xe}:{}}))};if(!k||!je){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&&!de(Se.generation)){he();return}Se||(de(),_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 se=await Nn("processing","other",g(Mt));if(!se.proceed){he();return}ut={accountPatch:se.accountPatch,sessionId:se.sessionId,nonce:se.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(Xs(_),St).then(se=>{se&&(wt.current=se)});return}wt.current=null;let Bn={...ut?.accountPatch,...kr(St,!0)};await Nn("processing","session_claim",Promise.resolve(Y?.(St)));let{error:Qt}=await Nn("tokenization","provider_sdk",je.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,re,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 se=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Un,operationOutcome:"watchdog_expired",durationMs:Math.max(0,se-Pr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Ge?.flush?.().catch(()=>{}),qn?.()},sm),Ee.current.add(yt);let fn=(se,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=se;zn&&(se==="resolved"?ye="resolved_late":se==="returned_error"?ye="returned_error_late":ye="rejected_late");let en=Rt??(se==="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=se=>{if(!se||typeof se!="object")return null;let Rt=se;if(Rt.error)return null;let xt=Rt.setupIntent??Rt.paymentIntent,Vt=Hs(xt??null,void 0,!!Rt.setupIntent);return Vt.kind==="confirmed"?Vt:null},vn=se=>{if(Ut||Se&&Ke.current!==Se.generation)return;let Rt=Dn(se);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 se=await Id(k,mn,Ee.current);if(Ut||zt)return;let Rt=$s(mn),xt=Hs(se,En.providerObjectId,Rt);if(xt.kind==="confirmed"){vn(Rt?{setupIntent:se}:{paymentIntent:se});return}if(xt.kind==="terminal"){if(zt=!0,Ks(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,We;try{L=!0,Ct.current+=1;let se;try{se=await($s(mn)?k.confirmSetup({elements:je,clientSecret:mn,redirect:"if_required"}):k.confirmPayment({elements:je,clientSecret:mn,redirect:"if_required"}))}finally{Ae()}if(!se||typeof se!="object")throw new $a(pm(se));if(T=se,!T.error&&!Dn(T))throw new $a("confirmation_result_unconfirmed");We=fn(T.error?"returned_error":"resolved",T.error&&ci(T.error)?"provider_declined":void 0)}catch(se){let Rt=se instanceof $a?se.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}:Ts(se),...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,Ks(xe,we,mn),Me.current=null,Ve.current=null,H("idle"),kt.current.get(Ie)===Se&&kt.current.delete(Ie);let se=P.message??"Your payment was declined.";u?.(se),I?.(gn(Mt,se,{code:Ho(P),declineCode:ws(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({...Ts(P),...Un,operationOutcome:We.operationOutcome,durationMs:We.durationMs,statusClass:"unknown",terminalReason:We.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)}},[k,je,e,t,n,A,be,Y,o,re,a,l,u,I,g,Qe,Ae,de,lt,st,Ke,G,Ie]),$=gt(()=>cc(i),[i]),y=gt(()=>i.map(Qy),[i]),ie=gt(()=>d(Nd,{onReady:h=>{rt(ks(h,y))},onLoadError:h=>{rt("load_error"),nl(G,"stripe","wallet","provider_error")},onClick:async h=>{let W=G?.now()??globalThis.performance?.now()??Date.now();Pt.current=h.expressPaymentType,De.current=Md(h.expressPaymentType);let L=!0,he=window.setTimeout(()=>{L=!1,h.reject(),et(h.expressPaymentType)},om),Se=g?await g(De.current,{abandoned:()=>!L}):{proceed:!0};if(window.clearTimeout(he),!L)return;if(!Se.proceed){kt.current.delete(Ie),h.reject();return}let _=V(h.expressPaymentType);_t.current=!1,vt.current={generation:_,startedAt:W},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:j,onCancel:()=>{let h=kt.current.get(Ie);kt.current.delete(Ie);let W=vt.current,L=G?.now()??globalThis.performance?.now()??Date.now();if(h&&W?.generation===h.generation&&jy({method:h.method,elapsedMs:L-W.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:$,emailRequired:Nt,billingAddressRequired:Nt}},Ie),[y,$,j,_e,m,Nt,Qe,et,ct,g,V,Ie,G]);return Ne(Kn,{children:[d(Rs,{state:Ue,placeholderTestId:"flopay-wallet-placeholder",borderRadius:x,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:Js,children:["Try ",Xs(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:R,disabled:Xe==="checking",style:Js,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:ce}),ie]})]})}),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 Zs({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:u,onErrorChange:m,onDecline:I,onCancel:b,runBeforeButtonClick:g,onButtonClick:A,isProcessing:Y,submitButtonColor:te,submitButtonBorderRadius:x,submitButtonStyle:D,errorText:C}){let ne=po(),{emitInstrument:re}=da(pr),k=el(),je=Qs(),[G,Ue]=ee(!1),rt=O(!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(!k||!je||Y||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 ce=Z.sessionId??t,Kt=Z.nonce??n,$e=Ta(a?.trim()),it=kr({email:Z.accountPatch?.email?.trim()||o?.trim()||be.trim(),firstName:Z.accountPatch?.firstName?.trim()||$e.firstName,lastName:Z.accountPatch?.lastName?.trim()||$e.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 je.submit();if(Xe.error){m?.(Xe.error.message??"Payment failed.");return}let H=[it.firstName,it.lastName].filter(Boolean).join(" "),ht=await k.createPaymentMethod({elements:je,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(!ce||!Q)throw new Error("Missing sessionId or email for payment.");let Ve=Ce.type||e,ze=await Bi(l,re,ce,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:ce,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:ce,nonce:Kt,accountPatch:Te,paymentMethodId:Ce.id,paymentMethodType:Ce.type??e,gateway:"stripe"});let{error:Pt,paymentIntent:De}=await k.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),I?.(gn("card",Ee,{code:Pt.code})),await Di({billingApiUrl:l,sessionId:ce,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),I?.(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:ce,nonce:Kt})}catch(Xe){m?.(Xe instanceof Error?Xe.message:"Payment failed. Please try again.")}finally{rt.current=!1,Ue(!1)}},[k,je,Y,dt,g,A,t,n,o,a,be,i,l,re,e,u,m,I]);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"),nl(hn(ne),"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||Y||Nt!=="ready",color:te,borderRadius:x,style:D,children:G?"Processing\u2026":`Pay with ${Wa(e)}`}),C&&d(oa,{margin:"0.75rem 0 0",children:C})]})}function Fd({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:l,stripeInstance:u,paymentElementBaseOptions:m,futureUseSession:I,onTokenizedBody:b,onErrorChange:g,onButtonClick:A,onDecline:Y,runBeforeButtonClick:te,onLoadStateChange:x,isProcessing:D=!1,submitButtonColor:C="#4A49FF",submitButtonBorderRadius:ne=8,submitButtonStyle:re,buttonAppearance:k,themeId:je,onExpandApm:G,expandedApmMethod:Ue}){let{emitInstrument:rt}=da(pr),[dt,Re]=ee(null),[Nt,Dt]=ee(null),be=O(!1),{request:He,collect:ot,finish:at}=ea();Je(()=>{l.length>0&&u?x?.("ready"):u||x?.("loading")},[l.length,u,x]);let Ie=Be(async Q=>{if(!u||be.current||D)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)){b({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),Y?.(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),Y?.(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;b({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,D,te,A,e,t,n,ot,i,rt,o,a,b,g,Y]),[Z,ce]=ee(null),Kt=G?Ue??null:Z,$e=Be(Q=>{be.current||D||Kt&&Kt!==Q||(Cd(Q)?G?G(Q):ce(Q):Ie(Q))},[Kt,D,Ie,G]),it=gt(()=>Z?$d(m,Z,I):null,[Z,m,I]);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:je,submitting:Xe,disabled:H,highlighted:Te,hasNextStep:Cd(Q),onClick:()=>$e(Q),backgroundColor:k?.backgroundColor,borderColor:k?.borderColor,textColor:k?.textColor,borderRadius:k?.borderRadius,fontFamily:k?.fontFamily}),!G&&Z===Q&&it&&u&&d(uo,{stripe:u,options:it,children:d(Zs,{method:Q,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:b,onErrorChange:g,onDecline:Y,onCancel:()=>ce(null),runBeforeButtonClick:te,onButtonClick:A,isProcessing:D,submitButtonColor:C,submitButtonBorderRadius:ne,submitButtonStyle:re})},Q)]},Q)})})}function Fm({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:l,onError:u,onDecline:m,onCancel:I,onTokenizedBody:b,firstName:g,lastName:A,chv:Y,className:te,submitLabel:x,isProcessing:D,error:C,onErrorChange:ne,showPayPal:re=!0,showStripe:k=!0,walletPresentation:je="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:ce,showSecurityFooter:Kt,onButtonClick:$e,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:de,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:q,dataAttachmentPending:Ht=!1,dataAttachmentRequiresIdentity:R=!1,debug:j=!1}){let $=po(),y=Ms(),ie=da(wr),{emitInstrument:h}=da(pr),W=O(null);W.current||(W.current=gi());let L=W.current,[,he]=ee(0),Se=O(null);Se.current||(Se.current=ka());let _=Se.current,ut=gt(()=>({browser:_,capability:L,presentationMode:"popup"}),[_,L]),Mt=q??ie.session,At=gt(()=>({futureUse:Mt?.futureUse,futureUseUnsupported:Mt?.futureUseUnsupported}),[Mt?.futureUse,Mt?.futureUseUnsupported]),Fn=Mt?.gateways?.paypal?.providerObjectType??Qe?.providerObjectType,Ge=Ht||ie.claimPending===!0,fr=R||ie.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(de??""),[Pr,Un]=ee(""),[zn,qn]=ee({}),fn=O(vt??""),Ut=O(Ee??""),zt=O(Ot??""),Dn=O(kt??""),vn=O(V??""),Tn=O(de??""),T=O(""),We=O({});Je(()=>{let r=(f,E,X,B,pe)=>{if(We.current[f])return;let It=E?.trim();!It||It===X.current||(X.current=It,B(It),pe?.(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",de,Tn,_n)},[Ee,vt,Ot,kt,V,de,_e,st]);let P=gt(()=>Gy(Te),[Te]),se=P!==null,Rt=gt(()=>js(q),[q]),xt=Uy(q?.vault),Vt=!!q?.gateways?.pcivault,ye=_c(q),Wr=!!(q?.gateways?.stripe?.enabledPaymentMethods??G)?.includes("card")||_o(q),Mn=xt||Wr||Vt,Pe=!!(k&&Mn&&e),[Tr,Cn]=ee(()=>Re!=="buttons"||Ae?e??null:null),[sr,Po]=ee(0),Gn=Re!=="buttons"||Ae||!!e&&Tr===e,nr=q?.captureMethod,Mr=O($);Je(()=>{Mr.current=$},[$]);let jn=O(De);jn.current=De;let Ar=O(t);Ar.current=t;let vr=O({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 X=vr.current;X.emitInstrument?.(Ey(E)),E.type==="card_fields_ready"?vd(()=>X.onCardFieldsReady?.(E)):vd(()=>X.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=(pe,It)=>nn(pe,f)&&!It.trim(),X={line1:E(P.address_line_1,Qt),city:E(P.city,hr),state:E(P.state,mn),zip:An.empty||An.malformed};return{avsInvalid:X.line1||X.city||X.state||X.zip,invalidAvsFields:X}},[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=O(!1),eo=O({email:!1,line1:!1,city:!1,state:!1,zip:!1}),to=O(!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(()=>Ws(q?.vault,{billingApiUrl:pt,sessionId:e,nonce:t})),[Fe,Ln]=ee(Ae&&Mn?"card":"buttons"),[$t,Gr]=ee(null),no=Fe==="expanding"||Fe==="card",bo=q?.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=O(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=O(!1),[s,c]=ee(0),p=O(null),K=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]),J=Be(r=>{Gr(r),Ln("apm-expanding"),cn(()=>Ln("apm-form"))},[cn]),ue=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[z,w]=ee(null),oe=O(null),[me,S]=ee(0);Je(()=>{me!==0&&oe.current?.focus()},[me]);let M=O(!1),F=O(null),N=O("idle"),[ae,Oe]=ee(!1),U=O(ae);U.current=ae;let[fe,Ye]=ee(()=>Qe?.existingOrderId?{orderId:Qe.existingOrderId,attempts:1}:null),Sn=O(fe);Je(()=>{Sn.current=fe},[fe]);let jt=O(null),Lt=gt(()=>{if(Q||ie.claimBuyerIdentity||q?.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,ie.claimBuyerIdentity,q?.buyerIdentified,e,t,pt,i,g,A]),Gt=Q??ie.claimBuyerIdentity??Lt,Yt=C??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=ie.inlineSessionPatchProcessing??!1,on=(D??Xt)||yu,ro=pt.replace(/\/+$/,""),mt=gt(()=>_s({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()),Wi=O(null);Pe&&Wi.current===null&&(Wi.current=ml);let oo=Pe&&(Wi.current??ml),Ki=gt(()=>Em(Pr,oo),[Pr,oo]),Lo=Ki.empty||Ki.malformed,or=gt(()=>$?$.getRawProvider():null,[$]),fl=gt(()=>y?y.getRawProvider():null,[y]),ya=_t||100,No=ct.toLowerCase(),Hi=gt(()=>Do?vy(Do):null,[Do]),Uo=Hi,gl=gt(()=>{let r=Hi??{},f=r.rules??{};return{...r,rules:{...f,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...f[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...f[".AccordionItemContents"]??{}}}}},[Hi]),hl=gt(()=>({...Ec(_t,Mt?.captureMethod,At),currency:No,...Uo?{appearance:Uo}:null}),[_t,No,Mt?.captureMethod,At,Uo]),Vi=Dd(At,"paypal","paypal"),Pl=gt(()=>({mode:"payment",amount:ya,currency:No,captureMethod:"manual",...Vi?{setupFutureUsage:Vi}:null,...Uo?{appearance:Uo}:null}),[ya,No,Vi,Uo]),ge=Be(r=>{xe(r),ne?.(r)},[ne]),vl=O(0);Je(()=>{s!==vl.current&&(vl.current=s,ge(null))},[s,ge]);let Gi=O(""),[Cl,mu]=ee(!1),Yi=Be(()=>{mu(!0)},[]);Je(()=>{if(!Pe||!oo||!Gt||!Cl||Lo||Gi.current)return;let r=kr({email:xn(mt.email?.trim())?mt.email?.trim():T.current.trim(),firstName:mt.firstName?.trim(),lastName:mt.lastName?.trim()});Gi.current=JSON.stringify(r),qn(f=>({...f,...r})),Promise.resolve(Gt(r)).catch(f=>{Gi.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 Ji=O(null);Je(()=>{if(!(!Pe||!ke)){if(ht===void 0){if(Ji.current!==ke)return;Ji.current=null,ke.setShowCardFieldLabels?.(!1);return}Ji.current=ke,ke.setShowCardFieldLabels?.(ht===!0)}},[Pe,ke,ht]);let Xi=Ce===void 0?void 0:JSON.stringify(Cy(Ce)),Zi=O(null);Je(()=>{if(!(!Pe||!ke)){if(Xi===void 0){if(Zi.current!==ke)return;Zi.current=null,ke.setCardFieldLabels?.(null);return}Zi.current=ke,ke.setCardFieldLabels?.(JSON.parse(Xi))}},[Pe,ke,Xi]);let Qi=Mm(Ve),es=O(null);Je(()=>{if(!(!Pe||!ke)){if(Qi===null){if(es.current!==ke)return;es.current=null,ke.setCardFieldPlaceholders?.(void 0);return}es.current=ke,ke.setCardFieldPlaceholders?.(JSON.parse(Qi))}},[Pe,ke,Qi]),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=O(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=N.current;return f==="validation-window"||f==="processing"||U.current},[Re]),kl=Be((r,f,E)=>{Sl.take(e)&&hn($)?.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,$,Sl,e]),Ya=Be((r,f,E)=>{E?.telemetryReported||hn($)?.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,$]),zo=Be((r,f,E)=>{let X=E?.popupBlocked??so(f);if(wl()){Ya(r,X,E),kl(r,f,E);return}if(f instanceof Rr&&f.code==="checkout_processing_timeout"){Ya(r,!1,E),w(null),Re==="buttons"&&(Ln("buttons"),Gr(null)),ge(f.message),u?.(f);return}X&&L.markBlocked()&&he(tt=>tt+1);let B=Xs(r),pe=E?.code===Ld?wy(B):li(B,X,_.inAppBrowser),It=Ho(f),Et=(It?.toLowerCase()==="error"?void 0:It)??ic(E?.code)??"external_payment_method_failed",Le=new Rr(pe,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:Et,popupBlocked:X,inAppBrowser:_.inAppBrowser,appFamily:_.appFamily,popupCapability:L.current(),presentationMode:E?.presentationMode??"popup"}});Ya(r,X,E),w(null),Re==="buttons"&&(Ln("buttons"),Gr(null)),ge(pe),u?.(Le),console.error("[FloPay] External payment method failed:",{method:r,code:Et,popupBlocked:X})},[_,wl,Re,u,L,kl,Ya,ge]);Je(()=>{if(!Pe||!e){Xn(null);return}let r={billingApiUrl:ro,sessionId:e,nonce:t},f=Ws(q?.vault,r);if(f){Xn(f);return}if(!Gn){Xn(null);return}let E=`${ro}\0${e}\0${t??""}`,X=p.current;if(X&&X.key===E){Xn(X.mount);return}Xn(null);let B=!0;return new ca(ro).getVaultCapture(e,t).then(pe=>{if(!B)return;let It=Ws(pe,r);It?.verificationRequired&&!pe.html&&(p.current={key:E,mount:It}),It?Xn(It):ge("Failed to load the secure card form.")}).catch(pe=>{B&&ge(pe instanceof Error?pe.message:"Failed to load the secure card form.")}),()=>{B=!1}},[Pe,Gn,sr,e,q?.vault,ro,t,ge]);let br=O({onComplete:l,onError:u,updateError:ge,emitDecline:Or,resolvedAccount:mt,avsConfig:P,avsCheckProp:lt,sessionId:e,nonce:t,baseUrl:ro,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.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:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:ye};let ts=O(!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 X=r.resolvedAccount.firstName?.trim(),B=r.resolvedAccount.lastName?.trim(),pe=Ut.current.trim()||r.resolvedAccount.country?.trim()||"",It=r.avsConfig?nn(r.avsConfig.state,pe):!1,Et=r.avsConfig?nn(r.avsConfig.address_line_1,pe):!1,Le=r.avsConfig?nn(r.avsConfig.postal_code,pe):!1,tt=r.avsConfig?nn(r.avsConfig.city,pe):!1,ft=r.avsConfig?nn(r.avsConfig.address_line_2,pe):!1,dn=Et&&!It&&Le?Dy(pe,(fn.current??"").trim()):null,ar=It?Tn.current:dn;return{accountData:{userId:r.resolvedAccount.userId??"",email:E,...X?{firstName:X}:{},...B?{lastName:B}:{},...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}:{},...pe?{country:pe}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:nn(r.avsConfig.country,pe),postal_code:Le,address_line_1:Et,address_line_2:ft,city:tt,state:It}}:{}}},[]),Il=O(Ge);Il.current=Ge,Je(()=>{Ge||Yt!==Ed||br.current.updateError(null)},[Ge,Yt]),Je(()=>{!Pe||!ke||ke.setSubmitGate?.($n||Ge||Lo||ae)},[Pe,ke,$n,Ge,Lo,ae]),Je(()=>{if(!Pe||!ke)return;ts.current=!1;let r=null,f=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,N.current="idle",w(null)},400)},E=ke.on("submitting",()=>{rr(!0),F.current&&clearTimeout(F.current),N.current="validation-window",F.current=setTimeout(()=>{F.current=null,N.current==="validation-window"&&(N.current="processing")},gm),w("processing");let Le=br.current;if(!Le.sessionId||!Le.nonce)return;let tt=Rl();if(!tt){Le.updateError("Enter a valid email address."),N.current="idle",w(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),N.current="idle",w(null),Le.onError?.(ft instanceof Rr?ft:new Rr(dn,"api_error"))})}),X=ke.on("complete",Le=>{aa(Le.sessionId??br.current.sessionId),N.current="terminal",Oe(!1),w("success"),setTimeout(()=>{if(ts.current)return;ts.current=!0;let tt=br.current,ft=js(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)}),B=ke.on("decline",Le=>{let tt=br.current,ft=Le.message??"Your payment was declined. Please try another card or contact your bank.";N.current="terminal",Oe(!1),tt.updateError(ft),w("error");let dn=Le.failureOutcome??Wy(Le.declineReason)??"authorization_declined";tt.emitDecline("card",ft,{code:dn,declineCode:dn}),f()}),pe=ke.on("error",Le=>{let tt=br.current,ft=ky(Le.vaultOutcome);if(ft!==null){r&&(clearTimeout(r),r=null),N.current="idle",Oe(!1),tt.updateError(ft),w(null),S(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.";N.current="terminal",Oe(!1),tt.updateError(dn),w("error"),tt.onError?.(new Rr(dn,"api_error",{code:Le.failureOutcome??"capture_failed"})),f()}),It=ke.on("challenge_dismissed",()=>{F.current&&(clearTimeout(F.current),F.current=null),N.current="processing",Oe(!0),w(null)}),Et=ke.on("blocked",()=>{if(U.current){br.current.updateError(hm);return}if(!Il.current){rr(!0);return}Yi(),br.current.updateError(Ed)});return()=>{r&&(clearTimeout(r),r=null),F.current&&(clearTimeout(F.current),F.current=null),N.current="idle",Oe(!1),w(null),E(),X(),B(),pe(),It(),Et()}},[Pe,ke,Yi,Rl]);let Lr=!!Qe?.clientId,ma=Array.isArray(G),Ja=ma&&G.length>0,El=ma&&G.includes("paypal"),Xa=O(null);Xa.current===null&&(Xa.current=Ly());let qo=Xa.current?"redirect":sc(_,je,L.current()),{expressMethods:Za,paymentElementMethods:ns}=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=k&&jo.length>0,Tl=se?we:Ee,Qa=gt(()=>Fy(ns,Tl,Ue),[ns,Tl,Ue]),rs=gt(()=>({mode:"payment",amount:ya,currency:No,paymentMethodCreation:"manual",appearance:gl}),[ya,No,gl]),[os,Ml]=ee("loading"),[as,Al]=ee("loading"),[is,xl]=ee("loading"),[Pu,ss]=ee(!1),[Fl,ls]=ee("loading"),[cs,vu]=ee();Je(()=>{vu(ka())},[]);let ei=cs?.inAppBrowser,ti=cs?di(cs,Qe?.approvalPresentation,Fn??(et?"subscription":"order")):"popup",Bl=re&&(Lr||(ma?El:ei===!1)),Cu=_.inAppBrowser&&L.current()==="blocked",Dl=k&&hu&&!Cu,So=(!bt||!!ie.waitForDataAttachment)&&Bl&&Lr,ds=Fl==="retrying"||Fl==="exhausted",fa=null;k&&(y?fa=fl:qo==="redirect"&&(fa=or));let Ol=gt(()=>({...ut,presentationMode:qo}),[ut,qo]),wo=!bt&&Bl&&!!fa&&(!Lr||ds),ao=!bt&&Dl&&!!or,ko=!bt&&k&&Ja&&Qa.length>0&&!!or,bu=So&&!ds?Pu:wo&&Ra(os),Su=ao&&Ra(as),wu=ko&&is!=="load_error",Ll=[So||wo,ao,ko,Pe].filter(Boolean).length,ku={card:Pe,paypal:So&&!ds||wo&&Ra(os),wallets:ao&&Ra(as),apms:ko&&is!=="load_error"},Nl=r=>ku[r],Ul=r=>r==="loading"||r==="ready",zl=So||wo&&Ul(os)||ao&&Ul(as)||ko&&is!=="load_error",ni=O(!1);Je(()=>{if(!ni.current){if(!k&&!re){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(!k&&re&&!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)}}},[k,re,Lr,ei,bt,Mn,zl,u,ge]);let ql=O(!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)=>ie.applyInlineSessionPatch?ie.applyInlineSessionPatch(r).then(X=>({error:null,sessionId:X.sessionId||e,nonce:X.session?.clientSecret||t})).catch(X=>{let B=bd(f,X);return E?.abandoned?.()||(ge(B.message),u?.(B)),{error:B,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ie.applyInlineSessionPatch,t,u,e,ge]),Sr=Be(async(r,f)=>{if(r!=="card"&&bt&&await ie.waitForDataAttachment?.(),!it)return{proceed:!0};try{let E=await it({method:r,sessionId:e||void 0,createSession:ie.inlineSessionDraft});if(E===!1)return{proceed:!1};if(E&&typeof E=="object"){E.account&&qn(B=>({...B??{},...E.account}));let X=await jl(E,r,f);return X.error?{proceed:!1,accountPatch:E.account}:{proceed:!0,accountPatch:E.account,sessionId:X.sessionId,nonce:X.nonce}}return{proceed:!0}}catch(E){if(!f?.abandoned?.()){let X=bd(r,E);ge(X.message),u?.(X)}return{proceed:!1}}},[jl,ie.inlineSessionDraft,ie.waitForDataAttachment,bt,it,u,e,ge]),$l=Be(async(r,f)=>{if(M.current)return;M.current=!0,Zt(!0),w("processing"),ge(null);let E=f?.sessionId??e,X=f?.nonce??t,B=_s(mt,f?.accountPatch),pe=f?.completionPaymentMethodId??_a(r),It=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,Et=Sm(r),Le=f?.presentationMode?Ti(hn($),{...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(B.userId??"",{sessionId:E,nonce:X,paymentMethodCategory:f?.paymentMethodCategory??km(r),tokenizedData:It,accountData:{...f?.accountPatch,userId:B.userId??"",email:B.email??"",firstName:B.firstName||void 0,lastName:B.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:Y,avsCheck:lt,checkoutType:Ke,checkoutLayout:Ct,avsConfig:P,country:Ut.current})}),si=async wn=>{let Ro=js(q)||wn?.status==="authorized";aa(E),Le?.terminal({outcome:"payment_succeeded",...Ir}),w("success"),Ye(null),await new Promise(Sa=>setTimeout(Sa,600));let Nr;typeof wn?.paymentId=="string"?Nr=wn.paymentId:q?.paymentId&&(Nr=q.paymentId);let Io;typeof wn?.authorizationExpiresAt=="string"?Io=wn.authorizationExpiresAt:q?.authorizationExpiresAt&&(Io=q.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:pe,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:pe,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(!$||!wn){w("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){w("error");let rc=Sa.message??"PayPal payment failed.";ge(rc),Or("paypal",rc,{code:Sa.code})}}catch(Nr){w("error"),ge(Nr instanceof Error?Nr.message:"PayPal authorization failed.")}return}if(un?.type==="paypal_direct_required"){let wn=un.orderId;if(!wn){w("error"),ge("PayPal retry required but no order id provided.");return}let Ro=Sn.current?.attempts??0;if(Ro>=2){w("error"),ge("PayPal payment could not be completed after multiple attempts."),Or("paypal","paypal_direct_required retry limit exceeded");return}ss(!1),ls("loading"),Ye({orderId:wn,attempts:Ro+1}),w(null);return}if(ar.headers.get(cm)===dm){let wn=await um(ft,E,X);if(wn!==void 0){await si(wn);return}}_y(ar.status,un)?Le?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}):tt(),w("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(),w("error"),ge(ft instanceof Error?ft.message:"An unexpected error occurred"),await new Promise(dn=>setTimeout(dn,400))}finally{Zt(!1),w(null),M.current=!1}},[ro,e,t,mt,P,lt,Ke,Ct,Y,$,y,q,l,ge,Or,h,ut]),Qn=Be((r,f)=>{b&&!f?.settledProcessResponse?b(r):$l(r,f)},[b,$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=O(!1);Je(()=>{if(typeof window>"u"||Wl.current)return;let[r,f,E]=Bd();if(!r||!f||Xa.current||!$)return;let X=$.getRawProvider();if(!X)return;let B=tt=>{let ft=localStorage.getItem(tt);if(!ft)return null;try{return JSON.parse(ft)}catch{return sn(tt),null}},pe=B(qr)??B(kd),It;if(pe?.clientSecret){if(pe.clientSecret!==f)return;It={...pe.accountPatch?{accountPatch:pe.accountPatch}:{},...pe.sessionId?{sessionId:pe.sessionId}:{},...pe.nonce?{nonce:pe.nonce}:{}}}else if(pe?.sessionId&&pe.sessionId!==e)return;Wl.current=!0,sn(qr),sn(kd),window.history.replaceState({},"",Od());let Et=pe?.paymentMethodType??pe?.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 X.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??pe?.paymentMethodId??pe?.tokenId??tt.id,type:"card",threeDSecureActionResultTokenId:tt.id,gateway:pe?.gateway??"stripe",paymentMethodType:Et},It)})()},[e,Qn,$,ge,Or]);let us=Be(r=>{r.preventDefault()},[]);if(!(Pe||$!==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"]),ps=Wn?.colorBackground,Iu=ps&&!Ru.has(ps)?ps: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),ys=ve.cardFormContainer?.backgroundColor??Iu??(ha?"white":"#EDEDFF"),$o=ve.cardInputBackground??Wn?.colorBackground??"white",ms=Vo(Z),Hl=Vo(ce),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),fs=Wn?.colorText??"#262833",gs={fontSize:Vl,fontFamily:Gl,fontWeight:Yl,color:_u,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},va={marginTop:"0.375rem",...gs,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??{},hs=Ca.padding??(ha?"0":"1rem"),Ps=Ca.borderRadius??an,xu=ke&&On?d(Cs,{capture:ke,html:On.html,messageToken:On.messageToken,expectedOrigin:On.expectedOrigin,verificationRequired:On.verificationRequired,theme:pu,submitLabel:x,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&&N.current==="idle"&&(v.current=!0),ge(r)},onValidation:r=>{let f=N.current;(f==="idle"||f==="validation-window")&&(ge(r),r&&N.current==="validation-window"&&(F.current&&(clearTimeout(F.current),F.current=null),N.current="idle",w(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"}),vs=Ne("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&Br()},style:{backgroundColor:ys,borderRadius:Ps,...Ca,padding:hs,...Au,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
4
|
+
`)}`]}):null;return Y&&!C?be?Mo("div",{children:Tn}):null:Bs("div",{children:[Tn,lt&&Mo(ta,{identity:lt.identity,methodLabel:lt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:bt,onCancel:()=>bt(null)}),Bs("div",{"aria-hidden":Ze||lt?!0:void 0,style:Ze||lt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:vi},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:ce,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:vi,display:"flex",opacity:Ve?1:0},"aria-busy":_e||$},De)]},De),Ie&&Mo("button",{ref:Pt,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Qt,style:qp,children:"Try PayPal again"})]})}function bi(e){return Mo(Yc,{...e})}function Jc(e){return Mo(Yc,{...e})}import{jsx as Xc,jsxs as Kp}from"react/jsx-runtime";function oa({children:e,margin:t,icon:n=!0,styleOverride:o}){return Kp("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&&Xc("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Xc("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 Ds,hashCreateParams as Zc,legacyCachedSessionMatchesDraft as Qc,persistCachedInlineIdempotencyKey as Ri,persistCachedInlineSession as wi,readCachedInlineIdempotencyKey as eu,readCachedInlineSession as tu,serializeCreateParams as Ba}from"@flopay/shared";var nu=new Set;function Hp(){return globalThis.process?.env?.NODE_ENV==="production"}function ru(e,t){nu.has(e)||Hp()||(nu.add(e),console.warn(t))}function ou(){ru("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 au(){ru("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 Vp,resolveBillingApiUrl as Gp}from"@flopay/shared";import{useCallback as Yp,useEffect as mo,useMemo as Jp,useRef as iu,useState as su}from"react";import{jsx as Xp}from"react/jsx-runtime";function ki({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,l]=su(e instanceof Promise?null:e),[d,y]=su(t instanceof Promise||!t?null:t),w=iu(null),P=iu(null),g=na(o),_=Yp(F=>{Vp(F)||g(F)},[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?.(_)},[_,i]),mo(()=>{if(!(!d||d===i))return hn(d)?.subscribe?.(_)},[_,i,d]),mo(()=>{if(!i)return;let F=hn(i);return w.current=F?.beginCheckout()??F?.now()??0,F?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{F?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),mo(()=>{let F=!1;return e instanceof Promise?e.then(I=>{F||l(I)},()=>{F||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{F=!0}},[g,e]),mo(()=>{let F=!1;if(!t){y(null);return}return t instanceof Promise?t.then(I=>{F||y(I)},()=>{F||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{F=!0}},[g,t]),mo(()=>{if(!i||P.current===i)return;P.current=i;let F=hn(i);F?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),F?.performance({stage:"checkout_render",durationMs:F.elapsed(w.current??0),durationMode:"machine"})},[g,i]);let O=Gp(n?.billingApiUrl),X=Jp(()=>({flopay:i,paypalFlopay:d,billingApiUrl:O,emitInstrument:g}),[i,d,O,g]);return Xp(pr.Provider,{value:X,children:a})}import{markSessionRecentlyCompleted as aa,wasSessionRecentlyCompleted as Os}from"@flopay/shared";async function Ei(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 Zp,completeSavedCardNextAction as Qp,loadFloPay as lu,PaymentAPI as Oa,runSavedCardChallenge as ey}from"@flopay/js";import{classifyPaymentRejection as ty,FloPayError as Mt,isAuthorizationOnlySession as ny,isMerchantAuthRequired as Ns,isMountableVaultBlock as ry,isSetupIntentClientSecret as oy,MERCHANT_AUTH_REQUIRED_CODE as ay,normalizeCheckoutFailureOutcome as cu}from"@flopay/shared";var Na="card";async function iy(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 sy(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:d}=await e.confirmCardSetup(t,n);return{error:d,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 Mt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function ly(){return new Mt("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 Mt?e:new Mt(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 du(e){return!e?.type||!e.threeDSecureToken||Ns(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function pu(e){return ey(e)}function Ua(e,t,n,o=!0){let a={release:()=>{}};if(!o)return a;try{let i=new Oa(e),l=Zp(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}),d=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,y;try{y=await Qp({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:P=>zr({type:P.declineReason??"authorization_declined",gatewayErrorCode:P.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(P){if(a.aborted||P instanceof Error&&P.name==="AbortError")throw P instanceof Mt&&P.code==="three_ds_aborted"?P:ia(P);if(!(P instanceof Mt)||P.code!=="three_ds_timeout"&&P.code!=="checkout_processing_timeout")throw P;try{y=await l.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:d,timeoutMs:5e3,signal:a})}catch(_){if(a.aborted)throw ia(_);if(!(_ instanceof Mt)||_.code!=="checkout_processing_timeout")throw _}let g=y&&co(y,t.session);if(!Xr(g)&&g?.status!=="expired"){if(t.telemetry){let _=new Oa(n);try{_.reportThreeDsAbandoned(o)}finally{_.destroy()}}throw ly()}}let w=y&&co(y,t.session);if(!Xr(w))throw Zo(w);return{...Jr(w,o),checkoutMethod:"card"}}function yu(e){return new Mt("This payment needs your card details. Please complete your payment below.","authentication_error",{code:ay,...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(Ns(e))return La(yu(),o);let a=e?.message??t,i=Qo(a)??a,l=La(new Mt(i,"api_error",{code:e?.code??cu(e?.outcome)??cu(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),o);return e?.orderId&&(l.orderId=e.orderId),l}function Ls(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ii(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function mu(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ii(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 d of i)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||Ii(d)))return d;let l=a.gateways;if(l&&typeof l=="object"){let d=l.stripe;if(d&&typeof d=="object"){let y=d,w=[y.stripeClientSecret,y.clientSecret];for(let P of w)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||Ii(P)))return P}}}}async function cy({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=mu(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let d=(await new Oa(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ii(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function la({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:l}){let d=e.replace(/\/+$/,""),y=t??n.id,w=o??n.clientSecret,P=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",_=n.customer?.firstName??n.accountData?.firstName??"",O=n.customer?.lastName??n.accountData?.lastName??"",X=n.customer?.country??n.accountData?.country??void 0,F=n.customer?.zip??n.accountData?.zip??void 0,f=await new Oa(d,l===!1?{telemetry:!1}:void 0).processPayment(P,{sessionId:y,nonce:w,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:P,email:g,firstName:_,lastName:O,country:X,zip:F},returnUrl:i??Ls(n)});if(f.ok){let ee=typeof f.json=="function"?await f.json().catch(()=>null):null;if(ny(n)||ee?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof ee?.paymentId=="string"?ee.paymentId:n.paymentId,sessionId:typeof ee?.sessionId=="string"?ee.sessionId:y,authorizationExpiresAt:typeof ee?.authorizationExpiresAt=="string"?ee.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:_a(a),checkoutMethod:uu(a,n)}};let k=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...k?{paymentIntentId:k}:{},paymentMethodId:_a(a),checkoutMethod:uu(a,n)}}}let $;try{$=await f.json()}catch(ee){throw new Mt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:ee})}if(Ns($))throw La(yu(f.status),"card");if($?.type==="3ds_required"&&typeof $.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:$.nextActionRedirectUrl};if($?.type==="paypal_redirect_required"||$?.type==="3ds_required"){let ee=mu($);if(!ee)throw new Mt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:$.type,threeDSecureToken:ee,paymentMethodId:$.paymentMethodId}}if($?.gatewayErrorCode==="authentication_required"){let ee=await cy({billingApiUrl:d,sessionId:y,nonce:w,responseJson:$});if(ee)return ee;throw La(new Mt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw uy($,f.status)}function uy(e,t){let n=new Mt(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:ty(t,e)})}async function _i(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:l,returnUrl:d,telemetry:y,signal:w}){let P=t?.getRawProvider();if(!P)throw Qr(new Mt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw La(new Mt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=oy(e.threeDSecureToken),_=null,O=e.paymentMethodId,X=await Da(()=>iy(P,e.threeDSecureToken,g),"card");if(X){if(X.error)throw Qr(new Mt(X.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:X.error.code}),"card");let I=X.intent;!O&&I?.payment_method&&(typeof I.payment_method=="string"?O=I.payment_method:"id"in I.payment_method&&(O=I.payment_method.id??void 0))}let F=O?await Da(()=>sy(P,e.threeDSecureToken,{payment_method:O,return_url:d??Ls(l)??window.location.href},g),"card"):null;if(F){if(F.error)throw Qr(new Mt(F.error.message??"3DS authentication failed.","api_error",{code:F.error.code}),"card");_=F.intent}else{let I=await Da(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(I.error)throw Qr(new Mt(I.error.message??"3DS authentication failed.","api_error",{code:I.error.code}),"card");_=(g?I.setupIntent:I.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let I=await la({billingApiUrl:a,sessionId:i,session:l,telemetry:y,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:d});return I.type==="success"?{...I.result,paymentIntentId:I.result.paymentIntentId??_.id,paymentMethodId:I.result.paymentMethodId??O}:I.type==="next_action_required"?sa(I,{billingApiUrl:a,sessionId:i??l.id,session:l,signal:w}):_i(I,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:l,returnUrl:d,telemetry:y,signal:w})}throw Qr(new Mt("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 Mt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:O}=await Da(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(O)throw Qr(new Mt(O.message??"PayPal authorization failed.","api_error",{code:O.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await Da(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Ls(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw Qr(new Mt(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Mt("Unsupported payment redirect state.","api_error")}function za(e){if(e instanceof Mt){let o=Qo(e.message);return o&&o!==e.message?Object.assign(new Mt(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 Mt(n,"api_error")}function Us(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=ry(e.data.session?.vault)||_o(e.data.session);if(!t&&!n&&!o)throw new Mt("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 uu(e,t){return e?e.isPaypal?"paypal":"card":t&&_o(t)?"card":void 0}async function zs({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,d]=await Promise.all([lu(e,{billingApiUrl:n,locale:o,telemetry:a}),i?lu(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(w=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",w),null)):Promise.resolve(null)]);if(!l)throw new Mt("The payment provider did not initialize.","authentication_error");let y=null;return i?y=d:t&&(y=l),{flopay:l,paypalFlopay:y}}import{PaymentAPI as ca,PciVaultCardCapture as Ey,toStripeAppearance as Iy}from"@flopay/js";import{buildCardFieldLabelsPayload as _y,buildCheckoutProcessMetadata as Ty,buildProcessPaymentAvsAccount as My,buildWalletSheetWindowMessage as Ay,buyerEmailRequiredPrompt as Fy,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as xy,COUNTRY_OPTIONS as By,cardFieldsInstrumentSource as Dy,classifyPaymentRejection as Oy,clearStripePayPalReturn as Ly,computeVaultCardThemeColors as Ny,darkenHex as Uy,denyPaymentPermissionToNewFrames as zy,FloPayError as kr,filterStripeMethodsByCountryGate as qy,getPostalCodeExample as jy,getPostalCodeLabel as Xs,getStateFromPostalCode as $y,getStateLabel as $s,getStateOptions as Wy,getStripeMethodDisplayName as Wa,hasMatchingStripePayPalReturn as Ky,invokeMerchantCallback as Su,isAuthorizationOnlySession as Ws,isAVSFieldVisible as nn,isCardFormFirst as Hy,isMountableVaultBlock as Vy,isPostalCodeSupported as Gy,isSettledSessionIntent as xi,isSetupIntentClientSecret as Ks,isValidEmail as Fn,isValidPostalCode as Yy,isWalletSheetRefusedForWindowSize as Jy,keyPaymentMethodOrder as Xy,needsStripeMethodExplicitConfirm as Ru,normalizeBeforeButtonClickError as wu,normalizeCheckoutFailureOutcome as Zy,partitionStripeMethods as Qy,placePaymentMethodGroups as ku,randomUuidV4 as em,readMatchingStripePayPalContinuation as tm,readStripeRedirectParams as Lu,resolveAVSConfig as nm,resolveButtonsLayoutTheme as rm,resolveSetupFutureUsage as Nu,resolveTheme as om,resolveVaultMountOptions as Hs,STRIPE_PAYPAL_RESUME_KEY as am,derivePrimaryTileStyle as im,shouldPreferWalletPopup as Eu,stripeExpressMethodToOptionKey as sm,stripeRedirectReturnUrl as Uu,toCssWeight as lm,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as zu}from"@flopay/shared";import{ExpressCheckoutElement as qu,PaymentElement as cm,useElements as tl,useStripe as nl}from"@stripe/react-stripe-js";import ja,{useCallback as Be,useContext as ua,useEffect as Je,useLayoutEffect as um,useMemo as ht,useRef as L,useState as re}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 dy,useId as py,useRef as fu}from"react";import{Fragment as fy,jsx as gu,jsxs as gy}from"react/jsx-runtime";var hu="More payment options",yy={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},my={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function qs({label:e,open:t,showLink:n,onOpen:o,color:a,fontFamily:i,children:l}){let d=py(),y=fu(null),w=fu(!1);return dy(()=>{t&&w.current&&y.current?.focus()},[t]),gy(fy,{children:[!t&&n&&gu("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":d,onClick:()=>{w.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}),gu("div",{id:d,ref:y,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?my:yy,children:l})]})}import{jsx as Pu}from"react/jsx-runtime";var hy=["first","second","third","fourth"];function js({rows:e,borderRadius:t}){return Pu("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:hy.slice(0,Math.max(1,e)).map(n=>Pu("div",{style:{height:Io,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},n))})}import{PaymentAPI as Py}from"@flopay/js";import{DEFAULT_PAYMENT_METHOD_ORDER as Cy,resolveDefaultPaymentMethodLayout as vy}from"@flopay/shared";import{useEffect as by,useState as Sy}from"react";var Ry=1500,Cu=new Set;function vu(e){for(let t of e)Cu.has(t)||(Cu.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function wy(e){if(e!=null)try{return JSON.stringify(e)}catch{return vu(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var ky={order:[...Cy],moreOptions:[]};function bu({rules:e,sessionId:t,nonce:n,billingApiUrl:o,waitForSession:a}){let i=wy(e),[l,d]=Sy(null);return by(()=>{if(i===void 0||a)return;let y=JSON.parse(i),w=!1,P=X=>{w||(w=!0,d(X))},g=()=>P(vy(y));if(!t||!n||!o){g();return}let _=new AbortController,O=setTimeout(()=>{g(),_.abort()},Ry);return new Py(o,{telemetry:!1}).resolvePaymentMethodLayout(t,n,y,{signal:_.signal}).then(X=>{if(!X){g();return}w||vu(X.warnings),P({order:X.order,moreOptions:X.moreOptions})}).catch(g).finally(()=>clearTimeout(O)),()=>{w=!0,clearTimeout(O),_.abort()}},[i,t,n,o,a]),i===void 0?ky:l}import{darkenHex as Vu}from"@flopay/shared";import{Fragment as Kn,jsx as u,jsxs as Ne}from"react/jsx-runtime";var qr="flopay_stripe_resume",Iu="flopay_wallet_resume",ju="fw1",dm="fw2",$u=300*1e3,pm=900,ym="express_checkout_click_timeout",mm=25e3,fm=25e3,gm=1e4,Er={provider:"paypal",paymentMethodCategory:"paypal"},hm="x-flopay-process-result-source",Pm="status";async function Cm(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 vm(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 rl(e){return`${dm}:${e}`}function Ai(e){return sn(rl(e))}function Fi(e,t){if(typeof window>"u")return null;let n=rl(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>$u||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 bm(e){return sn(rl(e.sessionId),e)}function _u(e,t,n){let o=Fi(e,t);return!o||o.clientSecret!==n?!1:Ai(e)}function Vs(e,t,n){if(typeof window>"u")return;Fi(e,t)?.clientSecret===n&&Ai(e)}function Sm(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Gs(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":Ia(e.status),a=Sm(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Tu(e,t,n){let o=null;try{return await Promise.race([Tc(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},gm),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function Rm(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Wu(e){return e instanceof kr&&(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 Wu(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var Ys=am,qa=new Map,wm=250,Mu="Just a moment \u2014 we are finalizing your order. Please press pay again.",km="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function ol(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 Em(e){return e instanceof kr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ku({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=Ta(n),l=i.firstName?i:Ta(o?.name);return wr({email:Fn(a)?a:o?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Im({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let l=Ku({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return Fn(l.email)?l:i(a,l)}var Ka=180,Au=`flopay-card-enter ${Ka}ms cubic-bezier(0, 0, 0.2, 1) both`,Fu=`flopay-card-exit ${Ka}ms cubic-bezier(0.4, 0, 0.2, 1) both`,_m=`flopay-buttons-enter ${Ka}ms cubic-bezier(0, 0, 0.2, 1) both`,Tm=`flopay-buttons-exit ${Ka}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Mm(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function al(e){return im(e)}var Am={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Fm(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 Zs={width:"100%",minHeight:Io,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 xu(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Qs(e){return e==="paypal"?"PayPal":Wa(e)}function xm(e){let t=jy(e);return`Enter a valid ${Xs(e)}${t?` (e.g. ${t})`:""}`}function Bm(e,t,n){let o=Gy(e),a=t.trim(),i=n&&o,l=i&&!a,d=i&&!!a&&!Yy(e,a);return{visible:n,supported:o,required:i,empty:l,malformed:d}}function Dm(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!Fn(n);return{required:t,empty:o,malformed:a,value:n}}function Om(e){return typeof e=="number"?`${e}px`:e}var Lm=["number","expiry","cvv","name"];function Nm(e){if(e===null||typeof e!="object")return null;let t={};for(let n of Lm){let o=e[n];typeof o=="string"&&(t[n]=o)}return JSON.stringify(t)}function il(e){return u(qm,{...e})}function Bu({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:l=!1,onButtonClick:d,onDecline:y,onTechnicalFailure:w,runBeforeButtonClick:P,billingName:g,onBuyerIdentityReady:_,onLoadStateChange:O,placeholderBorderRadius:X,popupCapabilityOwner:F,externalTelemetryContext:I,presentationMode:f}){let $=po(),{emitInstrument:ee}=ua(pr),k=nl(),je=tl(),J=ht(()=>Ti(hn($),I),[I,$]),[Ue,rt]=re("loading");Je(()=>{O?.(Ue)},[Ue,O]);let[dt,ke]=re(!1),Nt=L(!1),Dt=!Fn(n?.trim())||!g?.trim(),{request:be,collect:He,finish:ot}=ea(),at=L(!1),Ee=L(null),te=L(null),[ce,Kt]=re(0),[$e,it]=re(!1),ne=L(!1),Te=L(new Map),{startAttempt:Xe,finishAttempt:G,invalidateAttempt:Pt,isAttemptInvalidated:ve,isAttemptCurrent:Ve,generationRef:ze}=Fa((ue,_e,st)=>{w?.(ue,_e,{...st,popupBlocked:st?.popupBlocked??so(_e),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),it(!0),Kt(lt=>lt+1)},{onHandoffObserved:()=>{F.markAvailable(),J?.log({name:"provider.popup.opened",stage:"overlay_open",...Er,attempt:ze.current})}});Je(()=>{$e&&te.current?.focus()},[$e,ce]);let Ze=Be(()=>{Kt(ue=>ue+1)},[]),Ct=Be((ue,_e,st)=>{Pt(st),w?.("paypal",ue,{code:_e,popupBlocked:so(ue),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),it(!0),Ze()},[Pt,w,f,Ze]),De=Be(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);Je(()=>{ne.current&&(ne.current=!1,De())},[De,ce]);let wt=Be(()=>{it(!1),i?.(null),De()},[De,i]);Je(()=>{if(!k||at.current)return;let[ue,_e,st]=Lu();if(!ue||!_e)return;let lt=tm(_e);if(!lt)return;at.current=!0;let Ke=!0,bt=qa.get(_e);bt||(bt=st==="failed"?Promise.resolve(null):Promise.resolve().then(()=>k.retrievePaymentIntent(_e)),qa.set(_e,bt));let Tt={accountPatch:lt.accountPatch,sessionId:lt.sessionId,nonce:lt.nonce},ct=()=>{J?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Er,requestCategory:"provider_sdk"})};return J?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Er}),(async()=>{try{ke(!0);let Qe=await bt;if(!Ke)return;if(Qe?.error){qa.delete(_e),ct(),i?.(Qe.error.message??"Failed to retrieve PayPal payment status.");return}if(Ly(),qa.delete(_e),st==="failed"){let j="PayPal payment was declined. Please try again.";J?.terminal({outcome:"payment_declined",...Er,terminalReason:"provider_declined"}),i?.(j),y?.(gn("paypal",j));return}let et=Qe?.paymentIntent;if(et&&et.id!==ue){ct(),i?.("Failed to match the returned PayPal payment.");return}if(et&&(et.status==="requires_capture"||et.status==="succeeded")){let j=typeof et.payment_method=="string"?et.payment_method:et.payment_method?.id;a({id:j??et.id,type:"card",threeDSecureActionResultTokenId:et.id,isPaypal:!0},{...Tt,presentationMode:"redirect"})}else{let j="PayPal payment was not completed. Please try again.";J?.terminal({outcome:et?.status==="canceled"?"payment_cancelled":"payment_declined",...Er,terminalReason:et?.status==="canceled"?"cancelled":"provider_declined"}),i?.(j),y?.(gn("paypal",j))}}catch(Qe){if(!Ke)return;qa.delete(_e),ct(),i?.(Qe instanceof Error?Qe.message:"Failed to complete PayPal payment.")}finally{Ke&&ke(!1)}})(),()=>{Ke=!1,at.current=!1}},[k,a,i,y,J]);let Me=Be(async(ue=!1)=>{let _e=P?await P("paypal"):{proceed:!0};if(!_e.proceed)return Te.current.delete(ce),!1;let st=Xe("paypal");return Te.current.set(ce,{generation:st,accountPatch:_e.accountPatch,sessionId:_e.sessionId,nonce:_e.nonce}),it(!1),J?.log({name:`provider.${ue?"redirect.started":"handoff.requested"}`,stage:ue?"redirect":"overlay_open",...Er,attempt:st}),d?.("paypal"),!0},[d,J,P,Xe,ce]),Ie=Be(async ue=>{if(l||dt||!await Me()){ue.reject();return}ue.resolve()},[l,Me,dt]),vt=Be(async ue=>{if(!k||!je)return;let _e=Te.current.get(ce);if(_e&&!Ve(_e.generation)){Te.current.delete(ce);return}if(!_e&&ve()||_e&&!G(_e.generation))return;_e||G();let st=_e??null;if(Te.current.delete(ce),!st&&P){let Ae=await P("paypal");if(!Ae.proceed){ue.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,bt=await Im({event:ue,prepared:st,email:n,billingName:g,methodLabel:"PayPal",collect:He});if(!bt){ue.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Tt=bt.email,ct={...st?.accountPatch,...wr(bt,!0)};try{if(ke(!0),i?.(null),!lt||!Fn(Tt))throw new Error("Missing sessionId or email for PayPal payment");await _?.(bt);let Ae=k.createPaymentMethod,{error:Qe,paymentMethod:et}=await Ae({type:"paypal"});if(Qe){Ct(Qe,"stripe_paypal_create_payment_method_failed",_e?.generation),ue.paymentFailed({reason:"fail"});return}let j=await Bi(o,ee,lt,Ke??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:et?.id??null,intentKind:"payment"});if(xi(j)){ue.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:ct,paymentMethodCategory:"paypal",presentationMode:f,sessionId:lt,nonce:Ke,settledProcessResponse:j.response});return}if(j.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ht=j.clientSecret,E={return_url:Uu()};if(et?.id&&(E.payment_method=et.id),!sn(Ys,{clientSecret:Ht,sessionId:lt,nonce:Ke,accountPatch:ct})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:K,paymentIntent:m}=await k.confirmPayment({clientSecret:Ht,confirmParams:E,redirect:"if_required"});if(K){if(sn(Ys),ci(K)){let C=K.message??"Your payment was declined.";J?.terminal({outcome:"payment_declined",...Er,terminalReason:"provider_declined"}),i?.(C),y?.(gn("paypal",C,{code:Ho(K),declineCode:ks(K)})),await Di({billingApiUrl:o,sessionId:lt,nonce:Ke,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ho(K)??"provider_declined"}})}else Ct(K,"stripe_paypal_confirm_failed",_e?.generation);return}sn(Ys);let ie=typeof m?.payment_method=="string"?m.payment_method:m?.payment_method?.id;a({id:ie??m?.id,type:"card",threeDSecureActionResultTokenId:m?.id,isPaypal:!0},{accountPatch:ct,paymentMethodCategory:"paypal",presentationMode:f,sessionId:lt,nonce:Ke});return}catch(Ae){Ct(Ae,"stripe_paypal_failed",_e?.generation)}finally{ke(!1)}},[k,je,e,t,n,g,He,_,o,ee,a,i,y,P,Ct,G,Ve,ve,J,f,ce]),Ot=Be(async()=>{if(!(Nt.current||l||dt||!k||!je)){Nt.current=!0,ke(!0);try{if(!await Me(!0))return;await vt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Nt.current=!1,ke(!1)}}},[je,vt,l,Me,k,dt]),kt=f==="redirect"?u("button",{type:"button",disabled:l||dt,onClick:()=>{Ot()},style:{width:"100%",minHeight:Io,border:"1px solid #d1d5db",borderRadius:X??8,background:"#ffc439",color:"#111827",cursor:l||dt?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):u(qu,{onReady:ue=>rt(Es(ue,["paypal"])),onLoadError:()=>{rt("load_error"),ol(J,"paypal","paypal","provider_error")},onClick:Ie,onConfirm:vt,onCancel:()=>{let ue=Te.current.get(ce);Te.current.delete(ce),J?.terminal({outcome:"payment_cancelled",...Er,terminalReason:"cancelled",...ue?{attempt:ue.generation}:{}}),Pt(ue?.generation),it(!1),ne.current=!0,Ze()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Dt,emailRequired:Dt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ce),Y=Ne(Kn,{children:[Ne("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[$e&&u("button",{ref:te,type:"button","data-testid":"flopay-paypal-retry-button",onClick:wt,style:Zs,children:"Try PayPal again"}),be&&u(ta,{identity:be.identity,methodLabel:be.methodLabel,onComplete:ot,onCancel:()=>ot(null)},be.id),u("div",{style:{display:be?"none":void 0},children:kt})]}),dt&&!be&&u(Ur,{status:"processing"})]});return f==="redirect"?Y:u(Is,{state:Ue,placeholderTestId:"flopay-paypal-placeholder",borderRadius:X,children:Y})}function Js(e){return e==="apple_pay"||e==="google_pay"}var Um=200;function zm({active:e}){return um(()=>e?zy(document):void 0,[e]),null}function Du({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:l,onErrorChange:d,onButtonClick:y,onDecline:w,onTechnicalFailure:P,runBeforeButtonClick:g,billingName:_,onBuyerIdentityReady:O,onLoadStateChange:X,placeholderBorderRadius:F,popupCapabilityOwner:I,externalTelemetryContext:f}){let $=po(),{emitInstrument:ee}=ua(pr),k=nl(),je=tl(),J=ht(()=>Ti(hn($),f),[f,$]),[Ue,rt]=re("loading");Je(()=>{X?.(Ue)},[Ue,X]);let[dt,ke]=re(!1);Je(()=>{it.current=dt},[dt]);let Nt=L(!Fn(n?.trim())||!_?.trim()).current,{request:Dt,collect:be,finish:He}=ea(),ot=L(null),at=L(null),[Ee,te]=re(0),[ce,Kt]=re(()=>Eu()),$e=L(ce),it=L(!1),[ne,Te]=re(!1),[Xe,G]=re(()=>Fi(e,t)?"blocked":"idle"),[Pt,ve]=re("google_pay"),Ve=L(null),ze=L(!0),Ze=L(!1),Ct=L("google_pay"),De=L("google_pay"),wt=L(null),Me=L(null),Ie=L(new Set),vt=L(null),Ot=L(null);Je(()=>(ze.current=!0,()=>{ze.current=!1;for(let C of Ie.current)window.clearTimeout(C);Ie.current.clear()}),[]);let kt=L(new Map),{startAttempt:Y,finishAttempt:ue,invalidateAttempt:_e,isAttemptInvalidated:st,isAttemptCurrent:lt,generationRef:Ke}=Fa((C,H,N)=>{P?.(C,H,{...N,popupBlocked:N?.popupBlocked??so(H),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ve(C),Te(!0),te(he=>he+1)},{onHandoffObserved:C=>{Ot.current=Ke.current,I.markAvailable(),J?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ke.current,...C==="apple_pay"||C==="google_pay"?{walletType:C}:{}})},defersMissingTerminal:Js,onMissingTerminalDeferred:(C,H)=>{let N=J?.now()??globalThis.performance?.now()??Date.now(),he=vt.current,Se=he?.generation===H?he.startedAt:N;J?.performance({stage:"overlay_return",durationMs:Math.max(0,N-Se),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:H,...Js(C)?{walletType:C}:{}}),J?.flush?.().catch(()=>{})}});Je(()=>{ne&&at.current?.focus()},[ne,Ee]);let bt=L(0),Tt=L(!1),ct=Be(()=>{if(bt.current>0){Tt.current=!0;return}te(C=>C+1)},[]),Ae=Be(()=>{bt.current-=1,!(bt.current>0||!Tt.current)&&(Tt.current=!1,ze.current&&te(C=>C+1))},[]),Qe=Be((C,H,N,he,Se=!1)=>{_e(he),P?.(C,H,{code:N,popupBlocked:so(H),telemetryReported:Se,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ve(C),Te(!0),ct()},[_e,P,ct]),et=Be(C=>{J?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...Js(C)?{walletType:C}:{}}),P?.(C,new Error("The wallet click was not ready within the time the wallet allows."),{code:ym,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ve(C),Te(!0)},[P,J]),j=Be(()=>{window.setTimeout(()=>{(ot.current?.querySelector("iframe")??ot.current)?.focus()},0)},[]);Je(()=>{Ze.current&&(Ze.current=!1,j())},[j,Ee]);let Ht=Be(()=>{Te(!1),d?.(null),j()},[j,d]),E=Be(()=>{Ve.current?.()},[]);Je(()=>{let C=null,H=()=>{C=null;let he=Eu();he!==$e.current&&($e.current=he,Kt(he),!it.current&&!lt(Ke.current)&&ct())},N=()=>{C!==null&&window.clearTimeout(C),C=window.setTimeout(H,Um)};return window.addEventListener("resize",N),()=>{window.removeEventListener("resize",N),C!==null&&window.clearTimeout(C)}},[Ke,lt,ct]),Je(()=>{let C=Fi(e,t);if(!C)return;let H=!1,N=!1,he=async()=>{if(!N){N=!0,H||G("checking");try{let Se=await Tu(k,C.clientSecret,Ie.current);if(H)return;let M=Gs(Se,C.providerObjectId,Ks(C.clientSecret));if(M.kind==="confirmed"){if(!_u(e,t,C.clientSecret))return;Ve.current=null,G("idle"),l({id:M.paymentMethodId,type:"card",threeDSecureActionResultTokenId:M.intentId},{...C.accountPatch?{accountPatch:C.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(M.kind==="terminal"){Vs(e,t,C.clientSecret),Ve.current=null,G("idle"),ve(C.paymentMethodType),Te(!0),ct();return}G("blocked")}catch{H||G("blocked")}finally{N=!1}}};return Ve.current=he,G("blocked"),()=>{H=!0,Ve.current===he&&(Ve.current=null)}},[t,l,ct,e,k]);let W=Be(async C=>{let H=!1,N=!1,he=Fe=>{H||N||(H=!0,C.paymentFailed({reason:"fail",...Fe?{message:Fe}:{}}))};if(!k||!je){he();return}let Se=kt.current.get(Ee);if(Se&&!lt(Se.generation)){kt.current.delete(Ee),he();return}if(!Se&&st()){he();return}if(Se&&!ue(Se.generation)){he();return}Se||(ue(),Tt.current=!1);let M=C.expressPaymentType??Se?.method??Ct.current,pt=Se??null,At=xu(M),Ft;M==="apple_pay"?Ft="apple_pay":M==="google_pay"&&(Ft="google_pay");let xn=Se?.generation??Ke.current,Ge=J,fr=Ge?.now()??globalThis.performance?.now()??Date.now(),St=new AbortController,Ir=!1,yt=!1,mt=null,kn=e,Hn="processing",Vn="other",rn="provider_runtime",yn,Xt=new Promise((Fe,Re)=>{yn=Re}),Zt=window.setTimeout(()=>{Ir=!0,St.abort(),yn(Mi)},mm),Nn=async(Fe,Re,tr)=>{Hn=Fe,Vn=Re,rn=Re==="intent_create"||Re==="session_claim"?"transport_error":"provider_runtime";let Rt=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:Fe,durationMs:Math.max(0,Bn-Rt),durationMode:"machine",requestCategory:Re,paymentMethodCategory:"wallet",provider:"stripe",...Ir?{statusClass:"timeout"}:{}})}};try{if(ke(!0),d?.(null),!pt&&g){let se=await Nn("processing","other",g(At));if(!se.proceed){he();return}pt={accountPatch:se.accountPatch,sessionId:se.sessionId,nonce:se.nonce}}let Fe=pt?.sessionId??e;kn=Fe;let Re=pt?.nonce??t,tr=wt.current??pt?.accountPatch,Rt=Ku({event:C,fallbackEmail:tr?.email??n,fallbackName:[tr?.firstName,tr?.lastName].join(" ").trim()||_});if(!Fn(Rt.email)){he("Buyer details are required."),be(Qs(M),Rt).then(se=>{se&&(wt.current=se)});return}wt.current=null;let Bn={...pt?.accountPatch,...wr(Rt,!0)};await Nn("processing","session_claim",Promise.resolve(O?.(Rt)));let{error:Qt}=await Nn("tokenization","provider_sdk",je.submit());if(Qt){he(),Qe(M,Qt,"stripe_wallet_submit_failed",Se?.generation);return}if(!Fe)throw new Error("Missing sessionId or email for payment.");let gr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:M,paymentMethodId:null,intentKind:a},En=JSON.stringify({sessionId:Fe,nonce:Re??"",request:gr}),_r=Me.current,hr=_r?.retryIdentity===En?_r.authorizationAttemptId:em();Me.current={authorizationAttemptId:hr,retryIdentity:En};let In=await Nn("processing","intent_create",Bi(o,ee,Fe,Re??"",{...gr,authorizationAttemptId:hr},{signal:St.signal}));if(xi(In)){he(),l({type:"card",paymentMethodType:M},{accountPatch:Bn,paymentMethodCategory:"wallet",sessionId:Fe,nonce:Re,settledProcessResponse:In.response});return}if(In.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let mn=In.clientSecret,_n=bm({createdAt:Date.now(),sessionId:Fe,...Re?{nonce:Re}:{},clientSecret:mn,providerObjectId:In.providerObjectId,paymentMethodType:M,accountPatch:Bn});window.clearTimeout(Zt),yt=!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",...Ft?{walletType:Ft}:{},attempt:xn},zn=!1,qn=null;Ge?.log({name:"payment.provider_confirmation.started",...Un}),mt=window.setTimeout(()=>{mt!==null&&Ie.current.delete(mt),zn=!0;let se=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Un,operationOutcome:"watchdog_expired",durationMs:Math.max(0,se-Pr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Ge?.flush?.().catch(()=>{}),qn?.()},fm),Ie.current.add(mt);let fn=(se,Et)=>{mt!==null&&(window.clearTimeout(mt),Ie.current.delete(mt),mt=null);let xt=Ge?.now()??globalThis.performance?.now()??Date.now(),Vt=Math.max(0,xt-Pr),ye=se;zn&&(se==="resolved"?ye="resolved_late":se==="returned_error"?ye="returned_error_late":ye="rejected_late");let en=Et??(se==="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=se=>{if(!se||typeof se!="object")return null;let Et=se;if(Et.error)return null;let xt=Et.setupIntent??Et.paymentIntent,Vt=Gs(xt??null,void 0,!!Et.setupIntent);return Vt.kind==="confirmed"?Vt:null},Cn=se=>{if(Ut||Se&&Ke.current!==Se.generation)return;let Et=Dn(se);if(!Et)return;if(_n&&!_u(Fe,Re,mn)){Ut=!0;return}let{intentId:xt,paymentMethodId:Vt}=Et;Ut=!0,zt=!0,Me.current=null,Ve.current=null,ze.current&&(G("idle"),ke(!1));let ye=`${ju}:${Fe}`;sn(ye,{createdAt:Date.now(),sessionId:Fe,nonce:Re,accountPatch:Bn,paymentMethodId:Vt,providerIntentId:xt,paymentMethodType:M});try{l({id:Vt,type:"card",threeDSecureActionResultTokenId:xt},{accountPatch:Bn,paymentMethodCategory:"wallet",sessionId:Fe,nonce:Re})}finally{sn(ye)}},Tn=!1;qn=async()=>{if(!(Tn||Ut||zt)){Tn=!0,ze.current&&G("checking");try{let se=await Tu(k,mn,Ie.current);if(Ut||zt)return;let Et=Ks(mn),xt=Gs(se,In.providerObjectId,Et);if(xt.kind==="confirmed"){Cn(Et?{setupIntent:se}:{paymentIntent:se});return}if(xt.kind==="terminal"){if(zt=!0,Vs(Fe,Re,mn),Me.current=null,Ve.current=null,!ze.current)return;G("idle"),he(),Qe(M,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Se?.generation,!0);return}ze.current&&!zt&&(G("blocked"),ke(!1))}catch{ze.current&&!zt&&(G("blocked"),ke(!1))}finally{Tn=!1}}},Ve.current=qn;let A,We;try{N=!0,bt.current+=1;let se;try{se=await(Ks(mn)?k.confirmSetup({elements:je,clientSecret:mn,redirect:"if_required"}):k.confirmPayment({elements:je,clientSecret:mn,redirect:"if_required"}))}finally{Ae()}if(!se||typeof se!="object")throw new $a(vm(se));if(A=se,!A.error&&!Dn(A))throw new $a("confirmation_result_unconfirmed");We=fn(A.error?"returned_error":"resolved",A.error&&ci(A.error)?"provider_declined":void 0)}catch(se){let Et=se instanceof $a?se.reason:void 0,xt=Et!==void 0,Vt=fn(xt?"returned_error":"rejected");if(Ge?.error({...xt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Et}:As(se),...Un,operationOutcome:Vt.operationOutcome,durationMs:Vt.durationMs,statusClass:"unknown",terminalReason:Vt.terminalReason}),!ze.current||Ut)return;await qn?.();return}let v=A.error;if(v){if(!ze.current||Ut)return;if(ci(v)){zt=!0,Vs(Fe,Re,mn),Me.current=null,Ve.current=null,G("idle"),kt.current.get(Ee)===Se&&kt.current.delete(Ee);let se=v.message??"Your payment was declined.";d?.(se),w?.(gn(At,se,{code:Ho(v),declineCode:ks(v)})),Di({billingApiUrl:o,sessionId:Fe,nonce:Re,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:M,providerDeclineReason:Ho(v)??"provider_declined",...In.intentKind==="payment"&&In.providerObjectId.startsWith("pi_")?{providerIntentId:In.providerObjectId}:{}}})}else Ge?.error({...As(v),...Un,operationOutcome:We.operationOutcome,durationMs:We.durationMs,statusClass:"unknown",terminalReason:We.terminalReason}),await qn?.();return}if(Cn(A),!Ut)throw new Error("Invalid provider returned for APM intent")}catch(Fe){if(Fe===Mi){let Re=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.error({errorCode:Rm(Vn),stage:Hn,requestCategory:Vn,paymentMethodCategory:"wallet",provider:"stripe",...Ft?{walletType:Ft}:{},operationOutcome:"watchdog_expired",checkoutSessionId:kn,durationMs:Math.max(0,Re-fr),statusClass:"timeout",failureCategory:rn,attempt:xn,terminalReason:"provider_error"}),Ge?.flush?.().catch(()=>{})}he(),Qe(M,Fe,Fe===Mi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Se?.generation,Fe===Mi)}finally{if(window.clearTimeout(Zt),mt!==null&&(window.clearTimeout(mt),Ie.current.delete(mt)),!yt){let Fe=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.performance({stage:"callback",durationMs:Math.max(0,Fe-fr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Ir?{statusClass:"timeout"}:{}})}ze.current&&ke(!1)}},[k,je,e,t,n,_,be,O,o,ee,a,l,d,w,g,Qe,Ae,ue,lt,st,Ke,J,Ee]),K=ht(()=>pc(i),[i]),m=ht(()=>i.map(sm),[i]),ie=ht(()=>u(qu,{onReady:C=>{rt(Es(C,m))},onLoadError:C=>{rt("load_error"),ol(J,"stripe","wallet","provider_error")},onClick:async C=>{let H=J?.now()??globalThis.performance?.now()??Date.now();Ct.current=C.expressPaymentType,De.current=xu(C.expressPaymentType);let N=!0,he=window.setTimeout(()=>{N=!1,C.reject(),et(C.expressPaymentType)},pm),Se=g?await g(De.current,{abandoned:()=>!N}):{proceed:!0};if(window.clearTimeout(he),!N)return;if(!Se.proceed){kt.current.delete(Ee),C.reject();return}let M=Y(C.expressPaymentType);Tt.current=!1,vt.current={generation:M,startedAt:H},kt.current.set(Ee,{generation:M,method:C.expressPaymentType,accountPatch:Se.accountPatch,sessionId:Se.sessionId,nonce:Se.nonce}),Te(!1),J?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:M,...C.expressPaymentType==="apple_pay"||C.expressPaymentType==="google_pay"?{walletType:C.expressPaymentType}:{}}),y?.(De.current),C.resolve()},onConfirm:W,onCancel:()=>{let C=kt.current.get(Ee);kt.current.delete(Ee);let H=vt.current,N=J?.now()??globalThis.performance?.now()??Date.now();if(C&&H?.generation===C.generation&&Jy({method:C.method,elapsedMs:N-H.startedAt,handoffObserved:Ot.current===C.generation})){J?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:C.generation,walletType:"google_pay"}),Me.current=null,Qe(C.method,new Error("The browser window is too small for the Google Pay sheet."),zu,C.generation,!0);return}J?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...C?{attempt:C.generation}:{}}),_e(C?.generation),Me.current=null,Te(!1),Ze.current=!0,ct()},options:{...yc,paymentMethods:K,emailRequired:Nt,billingAddressRequired:Nt}},Ee),[m,K,W,_e,y,Nt,Qe,et,ct,g,Y,Ee,J]);return Ne(Kn,{children:[u(Is,{state:Ue,placeholderTestId:"flopay-wallet-placeholder",borderRadius:F,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:[ne&&Ne("button",{ref:at,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ht,style:Zs,children:["Try ",Qs(Pt)," again"]}),Xe!=="idle"&&Ne("div",{role:"status","aria-live":"polite",children:[u("p",{children:"We are still confirming your payment. Check its status before trying again."}),u("button",{type:"button",onClick:E,disabled:Xe==="checking",style:Zs,children:Xe==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Dt&&u(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:[u(zm,{active:ce}),ie]})]})}),dt&&u(Ur,{status:"processing"})]})}function Hu(e,t,n){let o=Nu(n,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function el({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:d,onErrorChange:y,onDecline:w,onCancel:P,runBeforeButtonClick:g,onButtonClick:_,isProcessing:O,submitButtonColor:X,submitButtonBorderRadius:F,submitButtonStyle:I,errorText:f}){let $=po(),{emitInstrument:ee}=ua(pr),k=nl(),je=tl(),[J,Ue]=re(!1),rt=L(!1),[dt,ke]=re(!1),[Nt,Dt]=re("loading"),[be,He]=re(""),ot=!Fn(o?.trim()),at=!ot||Fn(be.trim()),Ee=Be(async()=>{if(!k||!je||O||rt.current||!dt)return;rt.current=!0,Ue(!0);let te=g?await g("card"):{proceed:!0};if(!te.proceed){rt.current=!1,Ue(!1);return}_?.("card");let ce=te.sessionId??t,Kt=te.nonce??n,$e=Ta(a?.trim()),it=wr({email:te.accountPatch?.email?.trim()||o?.trim()||be.trim(),firstName:te.accountPatch?.firstName?.trim()||$e.firstName,lastName:te.accountPatch?.lastName?.trim()||$e.lastName}),ne=it.email,Te=wr({...te.accountPatch,...it});try{if(y?.(null),!Fn(ne))throw new Error("A valid email address is required for payment.");await i?.(it);let Xe=await je.submit();if(Xe.error){y?.(Xe.error.message??"Payment failed.");return}let G=[it.firstName,it.lastName].filter(Boolean).join(" "),Pt=await k.createPaymentMethod({elements:je,params:{billing_details:{email:ne,...G?{name:G}:{}}}});if(Pt.error||!Pt.paymentMethod){y?.(Pt.error?.message??"Failed to create payment method.");return}let ve=Pt.paymentMethod;if(!ce||!ne)throw new Error("Missing sessionId or email for payment.");let Ve=ve.type||e,ze=await Bi(l,ee,ce,Kt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Ve,paymentMethodId:null,intentKind:"payment"});if(xi(ze)){d({type:"card",gateway:"stripe",paymentMethodType:Ve},{accountPatch:Te,paymentMethodCategory:"apm",sessionId:ce,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:ce,nonce:Kt,accountPatch:Te,paymentMethodId:ve.id,paymentMethodType:ve.type??e,gateway:"stripe"});let{error:Ct,paymentIntent:De}=await k.confirmPayment({clientSecret:Ze,confirmParams:{return_url:window.location.href,payment_method:ve.id},redirect:"if_required"});if(Ct){sn(qr);let Ie=Ct.message??"Payment failed.";y?.(Ie),w?.(gn("card",Ie,{code:Ct.code})),await Di({billingApiUrl:l,sessionId:ce,nonce:Kt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ct.code??"provider_declined"}});return}let wt=De?.status;if(!Ia(wt)){sn(qr);let Ie=wt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(Ie),w?.(gn("card",Ie,{code:wt??"missing_payment_intent"}));return}sn(qr);let Me=typeof De?.payment_method=="string"?De.payment_method:De?.payment_method?.id;d({id:Me??ve.id,type:"card",threeDSecureActionResultTokenId:De?.id,gateway:"stripe",paymentMethodType:ve.type??e},{accountPatch:Te,paymentMethodCategory:"apm",sessionId:ce,nonce:Kt})}catch(Xe){y?.(Xe instanceof Error?Xe.message:"Payment failed. Please try again.")}finally{rt.current=!1,Ue(!1)}},[k,je,O,dt,g,_,t,n,o,a,be,i,l,ee,e,d,y,w]);return Ne("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ot&&u("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",u("input",{type:"email",autoComplete:"email",required:!0,value:be,onChange:te=>He(te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),u(cm,{onReady:()=>Dt("ready"),onLoadError:()=>{Dt("load_error"),ol(hn($),"stripe","apm")},onChange:te=>{ke(!!te.complete)},options:{layout:mc,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...Fn(o?.trim())?{email:o?.trim()}:{}}}}}),u(fc,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Ee()},disabled:!dt||!at||J||O||Nt!=="ready",color:X,borderRadius:F,style:I,children:J?"Processing\u2026":`Pay with ${Wa(e)}`}),f&&u(oa,{margin:"0.75rem 0 0",children:f})]})}function Ou({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:l,stripeInstance:d,paymentElementBaseOptions:y,futureUseSession:w,onTokenizedBody:P,onErrorChange:g,onButtonClick:_,onDecline:O,runBeforeButtonClick:X,onLoadStateChange:F,isProcessing:I=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:$=8,submitButtonStyle:ee,buttonAppearance:k,themeId:je,onExpandApm:J,expandedApmMethod:Ue}){let{emitInstrument:rt}=ua(pr),[dt,ke]=re(null),[Nt,Dt]=re(null),be=L(!1),{request:He,collect:ot,finish:at}=ea();Je(()=>{l.length>0&&d?F?.("ready"):d||F?.("loading")},[l.length,d,F]);let Ee=Be(async ne=>{if(!d||be.current||I)return;be.current=!0,Dt(ne);let Te=X?await X("card"):{proceed:!0};if(!Te.proceed){be.current=!1,Dt(null);return}_?.("card");let Xe=Te.sessionId??e,G=Te.nonce??t,Pt=Ta([Te.accountPatch?.firstName,Te.accountPatch?.lastName].filter(Boolean).join(" ")||o),ve=wr({email:Te.accountPatch?.email?.trim()||n?.trim(),firstName:Te.accountPatch?.firstName?.trim()||Pt.firstName,lastName:Te.accountPatch?.lastName?.trim()||Pt.lastName});if(!Fn(ve.email)){Dt(null);let Ze=await ot(Wa(ne),ve);if(!Ze){be.current=!1;return}ve=Ze,Dt(ne)}let Ve=ve.email,ze=wr({...Te.accountPatch,...ve});try{if(g?.(null),!Xe||!Fn(Ve))throw new Error("Missing sessionId or email for payment.");await a?.(ve);let Ze=await Bi(i,rt,Xe,G??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(xi(Ze)){P({type:"card",gateway:"stripe",paymentMethodType:ne},{accountPatch:ze,paymentMethodCategory:"apm",sessionId:Xe,nonce:G,settledProcessResponse:Ze.response});return}if(Ze.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ct=Ze.clientSecret;sn(qr,{clientSecret:Ct,sessionId:Xe,nonce:G,accountPatch:ze,paymentMethodType:ne,gateway:"stripe"});let{error:De,paymentIntent:wt}=await d.confirmPayment({clientSecret:Ct,confirmParams:{return_url:window.location.href,payment_method_data:{type:ne,billing_details:{name:[ve.firstName,ve.lastName].filter(Boolean).join(" "),...Ve?{email:Ve}:{}}}},redirect:"if_required"});if(De){sn(qr);let vt=De.message??"Payment failed.";g?.(vt),O?.(gn("card",vt,{code:De.code})),await Di({billingApiUrl:i,sessionId:Xe,nonce:G,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:De.code??"provider_declined"}});return}let Me=wt?.status;if(!Ia(Me)){sn(qr);let vt=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(vt),O?.(gn("card",vt,{code:Me??"missing_payment_intent"}));return}sn(qr);let Ie=typeof wt?.payment_method=="string"?wt.payment_method:wt?.payment_method?.id;P({id:Ie??wt?.id,type:"card",threeDSecureActionResultTokenId:wt?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:ze,paymentMethodCategory:"apm",sessionId:Xe,nonce:G})}catch(Ze){g?.(Ze instanceof Error?Ze.message:"Payment failed. Please try again.")}finally{be.current=!1,Dt(null)}},[d,I,X,_,e,t,n,ot,i,rt,o,a,P,g,O]),[te,ce]=re(null),Kt=J?Ue??null:te,$e=Be(ne=>{be.current||I||Kt&&Kt!==ne||(Ru(ne)?J?J(ne):ce(ne):Ee(ne))},[Kt,I,Ee,J]),it=ht(()=>te?Hu(y,te,w):null,[te,y,w]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:He?u(ta,{identity:He.identity,methodLabel:He.methodLabel,onComplete:at,onCancel:()=>at(null)},He.id):l.map(ne=>{let Te=Ue===ne,Xe=Nt===ne,G=Nt!==null&&Nt!==ne||Ue!=null&&Ue!==ne;return Ne(ja.Fragment,{children:[u(dc,{method:ne,themeId:je,submitting:Xe,disabled:G,highlighted:Te,hasNextStep:Ru(ne),onClick:()=>$e(ne),backgroundColor:k?.backgroundColor,borderColor:k?.borderColor,textColor:k?.textColor,borderRadius:k?.borderRadius,fontFamily:k?.fontFamily}),!J&&te===ne&&it&&d&&u(uo,{stripe:d,options:it,children:u(el,{method:ne,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:P,onErrorChange:g,onDecline:O,onCancel:()=>ce(null),runBeforeButtonClick:X,onButtonClick:_,isProcessing:I,submitButtonColor:f,submitButtonBorderRadius:$,submitButtonStyle:ee})},ne)]},ne)})})}function qm({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:l,onError:d,onDecline:y,onCancel:w,onTokenizedBody:P,firstName:g,lastName:_,chv:O,className:X,submitLabel:F,isProcessing:I,error:f,onErrorChange:$,showPayPal:ee=!0,showStripe:k=!0,walletPresentation:je="auto",enabledPaymentMethods:J,enabledPaymentMethodCountries:Ue,showApplePay:rt=!0,showGooglePay:dt=!0,layout:ke="default",paymentMethodLayout:Nt,moreOptionsLabel:Dt,theme:be,buttonsTheme:He,buttonsStyles:ot,appearance:at,cardButtonContent:Ee,cardBackButtonContent:te,cardTitleContent:ce,showSecurityFooter:Kt,onButtonClick:$e,onBeforeButtonClick:it,onBuyerIdentityReady:ne,enableAVS:Te,cardFieldOrder:Xe,showCardBrandIcons:G,showCardFieldLabels:Pt,cardFieldLabels:ve,cardFieldPlaceholders:Ve,cardAutoFocus:ze,onCardFieldsReady:Ze,onCardFieldsFailed:Ct,cardFieldsTimeoutMs:De,cardPreFormSlot:wt,avsLayout:Me="row",country:Ie,zip:vt,addressLine1:Ot,addressLine2:kt,city:Y,state:ue,onCountryChange:_e,onZipChange:st,avsCheck:lt,checkoutType:Ke,checkoutLayout:bt,totalAmount:Tt=0,currency:ct="usd",initialCardOpen:Ae=!1,directPaypal:Qe,isSubscription:et=!1,session:j,dataAttachmentPending:Ht=!1,dataAttachmentRequiresIdentity:E=!1,debug:W=!1}){let K=po(),m=Fs(),ie=ua(Rr),{emitInstrument:C}=ua(pr),H=L(null);H.current||(H.current=gi());let N=H.current,[,he]=re(0),Se=L(null);Se.current||(Se.current=wa());let M=Se.current,pt=ht(()=>({browser:M,capability:N,presentationMode:"popup"}),[M,N]),At=j??ie.session,Ft=ht(()=>({futureUse:At?.futureUse,futureUseUnsupported:At?.futureUseUnsupported}),[At?.futureUse,At?.futureUseUnsupported]),xn=At?.gateways?.paypal?.providerObjectType??Qe?.providerObjectType,Ge=Ht||ie.claimPending===!0,fr=E||ie.claimRequiresIdentity===!0,St=Ge&&!fr,Ir=qc(),yt=n||Ir,mt=bu({rules:Nt,sessionId:e,nonce:t,billingApiUrl:yt,waitForSession:St}),kn=mt?.order??null,[Hn,Vn]=re(!1),rn=ht(()=>kn?Xy(kn):null,[kn]),yn=kn!==null&&Hy(kn),[Xt,Zt]=re(!1),[Nn,Fe]=re(null),[Re,tr]=re(Ie??""),[Rt,Bn]=re(vt??""),[Qt,gr]=re(Ot??""),[En,_r]=re(kt??""),[hr,In]=re(Y??""),[mn,_n]=re(ue??""),[Pr,Un]=re(""),[zn,qn]=re({}),fn=L(vt??""),Ut=L(Ie??""),zt=L(Ot??""),Dn=L(kt??""),Cn=L(Y??""),Tn=L(ue??""),A=L(""),We=L({});Je(()=>{let r=(h,T,Q,D,pe)=>{if(We.current[h])return;let It=T?.trim();!It||It===Q.current||(Q.current=It,D(It),pe?.(It))};r("country",Ie,Ut,tr,_e),r("zip",vt,fn,Bn,st),r("addressLine1",Ot,zt,gr),r("addressLine2",kt,Dn,_r),r("city",Y,Cn,In),r("state",ue,Tn,_n)},[Ie,vt,Ot,kt,Y,ue,_e,st]);let v=ht(()=>nm(Te),[Te]),se=v!==null,Et=ht(()=>Ws(j),[j]),xt=Vy(j?.vault),Vt=!!j?.gateways?.pcivault,ye=Ac(j),Wr=!!(j?.gateways?.stripe?.enabledPaymentMethods??J)?.includes("card")||_o(j),Mn=xt||Wr||Vt,Pe=!!(k&&Mn&&e),[Tr,vn]=re(()=>ke!=="buttons"||Ae?e??null:null),[sr,Po]=re(0),Gn=ke!=="buttons"||Ae||!!e&&Tr===e,nr=j?.captureMethod,Mr=L(K);Je(()=>{Mr.current=K},[K]);let jn=L(De);jn.current=De;let Ar=L(t);Ar.current=t;let Cr=L({onCardFieldsReady:Ze,onCardFieldsFailed:Ct,emitInstrument:C});Cr.current={onCardFieldsReady:Ze,onCardFieldsFailed:Ct,emitInstrument:C};let[lr,Yn]=re(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 Ey({sessionId:e,captureMethod:nr,billingApiUrl:yt,telemetry:o,sessionToken:Ar.current,cardFieldsTimeoutMs:jn.current}),h=r.onCardFields?.(T=>{let Q=Cr.current;Q.emitInstrument?.(Dy(T)),T.type==="card_fields_ready"?Su(()=>Q.onCardFieldsReady?.(T)):Su(()=>Q.onCardFieldsFailed?.(T))});return Yn({sessionId:e,captureMethod:nr,billingApiUrl:yt,telemetry:o,capture:r}),()=>{h?.(),r.unmount()}},[Pe,e,Gn,nr,yt,o]);let we=Pe&&e&&Gn&&lr?.sessionId===e&&lr.captureMethod===nr&&lr.billingApiUrl===yt&&lr.telemetry===o?lr.capture:null,An=ht(()=>{let r=Re,h=v?nn(v.postal_code,r):!1;return Bm(r,Rt,h)},[v,Re,Rt]),{avsInvalid:$n,invalidAvsFields:ln}=ht(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!Pe||!v)return{avsInvalid:!1,invalidAvsFields:r};let h=Re,T=(pe,It)=>nn(pe,h)&&!It.trim(),Q={line1:T(v.address_line_1,Qt),city:T(v.city,hr),state:T(v.state,mn),zip:An.empty||An.malformed};return{avsInvalid:Q.line1||Q.city||Q.state||Q.zip,invalidAvsFields:Q}},[Pe,v,Re,Qt,hr,mn,An]),[cr,rr]=re(!1),[Kr,Fr]=re(!1),[Co,xr]=re(!1),[vo,Hr]=re({line1:!1,city:!1,state:!1}),vr=L(!1),eo=L({email:!1,line1:!1,city:!1,state:!1,zip:!1}),to=L(!1),qt=Be(r=>{eo.current[r]=!0,to.current=!0},[]),Jn=Be(r=>!vr.current&&eo.current[r],[]),Vr=Be(r=>{Jn(r)&&Hr(h=>h[r]?h:{...h,[r]:!0})},[Jn]),[On,Xn]=re(()=>Hs(j?.vault,{billingApiUrl:yt,sessionId:e,nonce:t})),[xe,Ln]=re(Ae&&Mn?"card":"buttons"),[$t,Gr]=re(null),no=xe==="expanding"||xe==="card",bo=j?.gateways?.stripe&&!ye?"stripe":void 0,Br=Be(()=>{C?.({class:"card_surface",provider:bo})},[bo,C]),Dr=Be(()=>{Vn(!0),C?.({class:"more_options"})},[C]),bn=L(null),cn=Be(r=>{bn.current&&clearTimeout(bn.current),bn.current=setTimeout(()=>{bn.current=null,r()},Ka)},[]);Je(()=>()=>{bn.current&&clearTimeout(bn.current)},[]);let b=L(!1),[s,c]=re(0),p=L(null),V=Be(()=>{Br(),vn(e??null),b.current&&(b.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]),Z=Be(r=>{Gr(r),Ln("apm-expanding"),cn(()=>Ln("apm-form"))},[cn]),de=Be(()=>{Ln("apm-collapsing"),cn(()=>{Ln("buttons"),Gr(null)})},[cn]);Je(()=>{ke==="buttons"&&Ae&&Mn&&(vn(e??null),Ln("card"))},[ke,Ae,Mn,e]);let[q,R]=re(null),oe=L(null),[me,S]=re(0);Je(()=>{me!==0&&oe.current?.focus()},[me]);let x=L(!1),B=L(null),U=L("idle"),[ae,Oe]=re(!1),z=L(ae);z.current=ae;let[fe,Ye]=re(()=>Qe?.existingOrderId?{orderId:Qe.existingOrderId,attempts:1}:null),Sn=L(fe);Je(()=>{Sn.current=fe},[fe]);let jt=L(null),Lt=ht(()=>{if(ne||ie.claimBuyerIdentity||j?.buyerIdentified!==!1||!e||!t)return;let r=`${yt}|${e}|${t}`;jt.current?.key!==r&&(jt.current={key:r,claim:Xo(new ca(yt,{telemetry:!1}),e,t,{...i?{userId:i}:{},...g?{firstName:g}:{},..._?{lastName:_}:{}})});let h=jt.current.claim;return async T=>{await h(T)}},[ne,ie.claimBuyerIdentity,j?.buyerIdentified,e,t,yt,i,g,_]),Gt=ne??ie.claimBuyerIdentity??Lt,Yt=f??Nn,Zn=ht(()=>om(be),[be]),Ce=ht(()=>{let r=Zn?.buttonsLayout??rm(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,vd=ht(()=>Ny({appearance:Do,buttonsStyles:Ce,layout:ke}),[Do,Ce,ke]),bd=ie.inlineSessionPatchProcessing??!1,on=(I??Xt)||bd,ro=yt.replace(/\/+$/,""),ft=ht(()=>Ms({userId:i,email:a,firstName:g,lastName:_,country:Ie,zip:vt},zn),[i,a,g,_,Ie,vt,zn]),Oo=[ft.firstName,ft.lastName].filter(r=>!!r?.trim()).join(" "),hl=!Fn(ft.email?.trim()),Hi=L(null);Pe&&Hi.current===null&&(Hi.current=hl);let oo=Pe&&(Hi.current??hl),Vi=ht(()=>Dm(Pr,oo),[Pr,oo]),Lo=Vi.empty||Vi.malformed,or=ht(()=>K?K.getRawProvider():null,[K]),Pl=ht(()=>m?m.getRawProvider():null,[m]),ya=Tt||100,No=ct.toLowerCase(),Gi=ht(()=>Do?Iy(Do):null,[Do]),Uo=Gi,Cl=ht(()=>{let r=Gi??{},h=r.rules??{};return{...r,rules:{...h,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...h[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...h[".AccordionItemContents"]??{}}}}},[Gi]),vl=ht(()=>({...Mc(Tt,At?.captureMethod,Ft),currency:No,...Uo?{appearance:Uo}:null}),[Tt,No,At?.captureMethod,Ft,Uo]),Yi=Nu(Ft,"paypal","paypal"),bl=ht(()=>({mode:"payment",amount:ya,currency:No,captureMethod:"manual",...Yi?{setupFutureUsage:Yi}:null,...Uo?{appearance:Uo}:null}),[ya,No,Yi,Uo]),ge=Be(r=>{Fe(r),$?.(r)},[$]),Sl=L(0);Je(()=>{s!==Sl.current&&(Sl.current=s,ge(null))},[s,ge]);let Ji=L(""),[Rl,Sd]=re(!1),Xi=Be(()=>{Sd(!0)},[]);Je(()=>{if(!Pe||!oo||!Gt||!Rl||Lo||Ji.current)return;let r=wr({email:Fn(ft.email?.trim())?ft.email?.trim():A.current.trim(),firstName:ft.firstName?.trim(),lastName:ft.lastName?.trim()});Ji.current=JSON.stringify(r),qn(h=>({...h,...r})),Promise.resolve(Gt(r)).catch(h=>{Ji.current="",ge(h instanceof Error?h.message:"Failed to attach buyer details.")})},[Pe,oo,Gt,Rl,Lo,ft.email,ft.firstName,ft.lastName,ge]),Je(()=>{if(!Pe||!we)return;let r=ze!==!1&&v==null&&!oo;we.setCardFieldOrder?.(Xe??null,r)},[Pe,we,Xe,ze,v,oo]),Je(()=>{!Pe||!we||we.setCardBrandIcons?.(G===!0)},[Pe,we,G]);let Zi=L(null);Je(()=>{if(!(!Pe||!we)){if(Pt===void 0){if(Zi.current!==we)return;Zi.current=null,we.setShowCardFieldLabels?.(!1);return}Zi.current=we,we.setShowCardFieldLabels?.(Pt===!0)}},[Pe,we,Pt]);let Qi=ve===void 0?void 0:JSON.stringify(_y(ve)),es=L(null);Je(()=>{if(!(!Pe||!we)){if(Qi===void 0){if(es.current!==we)return;es.current=null,we.setCardFieldLabels?.(null);return}es.current=we,we.setCardFieldLabels?.(JSON.parse(Qi))}},[Pe,we,Qi]);let ts=Nm(Ve),ns=L(null);Je(()=>{if(!(!Pe||!we)){if(ts===null){if(ns.current!==we)return;ns.current=null,we.setCardFieldPlaceholders?.(void 0);return}ns.current=we,we.setCardFieldPlaceholders?.(JSON.parse(ts))}},[Pe,we,ts]),Je(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&ge(null)},[xe,ge]);let Or=Be((r,h,T)=>{y?.(gn(r,h,T))},[y]),wl=L(xe);wl.current=xe;let[kl]=re(Pi),El=Be(()=>{let r=wl.current;if(ke==="buttons"&&(r==="card"||r==="expanding"))return!0;let h=U.current;return h==="validation-window"||h==="processing"||z.current},[ke]),Il=Be((r,h,T)=>{kl.take(e)&&hn(K)?.log(Ao({...pt,presentationMode:T?.presentationMode??"popup"},{name:hi,stage:"recovery",reason:"other_method_active",provider:T?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:T?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[pt,K,kl,e]),Ya=Be((r,h,T)=>{T?.telemetryReported||hn(K)?.error(Ao({...pt,presentationMode:T?.presentationMode??"popup"},{errorCode:h?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:T?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:T?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:T?.terminalReason??(h?"popup_blocked":"provider_error")}))},[pt,K]),zo=Be((r,h,T)=>{let Q=T?.popupBlocked??so(h);if(El()){Ya(r,Q,T),Il(r,h,T);return}if(h instanceof kr&&h.code==="checkout_processing_timeout"){Ya(r,!1,T),R(null),ke==="buttons"&&(Ln("buttons"),Gr(null)),ge(h.message),d?.(h);return}Q&&N.markBlocked()&&he(tt=>tt+1);let D=Qs(r),pe=T?.code===zu?Ay(D):li(D,Q,M.inAppBrowser),It=Ho(h),_t=(It?.toLowerCase()==="error"?void 0:It)??cc(T?.code)??"external_payment_method_failed",Le=new kr(pe,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:_t,popupBlocked:Q,inAppBrowser:M.inAppBrowser,appFamily:M.appFamily,popupCapability:N.current(),presentationMode:T?.presentationMode??"popup"}});Ya(r,Q,T),R(null),ke==="buttons"&&(Ln("buttons"),Gr(null)),ge(pe),d?.(Le),console.error("[FloPay] External payment method failed:",{method:r,code:_t,popupBlocked:Q})},[M,El,ke,d,N,Il,Ya,ge]);Je(()=>{if(!Pe||!e){Xn(null);return}let r={billingApiUrl:ro,sessionId:e,nonce:t},h=Hs(j?.vault,r);if(h){Xn(h);return}if(!Gn){Xn(null);return}let T=`${ro}\0${e}\0${t??""}`,Q=p.current;if(Q&&Q.key===T){Xn(Q.mount);return}Xn(null);let D=!0;return new ca(ro).getVaultCapture(e,t).then(pe=>{if(!D)return;let It=Hs(pe,r);It?.verificationRequired&&!pe.html&&(p.current={key:T,mount:It}),It?Xn(It):ge("Failed to load the secure card form.")}).catch(pe=>{D&&ge(pe instanceof Error?pe.message:"Failed to load the secure card form.")}),()=>{D=!1}},[Pe,Gn,sr,e,j?.vault,ro,t,ge]);let br=L({onComplete:l,onError:d,updateError:ge,emitDecline:Or,resolvedAccount:ft,avsConfig:v,avsCheckProp:lt,sessionId:e,nonce:t,baseUrl:ro,captureMethod:j?.captureMethod,paymentId:j?.paymentId,authorizationExpiresAt:j?.authorizationExpiresAt,serverSideCardGateway:ye});br.current={onComplete:l,onError:d,updateError:ge,emitDecline:Or,resolvedAccount:ft,avsConfig:v,avsCheckProp:lt,sessionId:e,nonce:t,baseUrl:ro,captureMethod:j?.captureMethod,paymentId:j?.paymentId,authorizationExpiresAt:j?.authorizationExpiresAt,serverSideCardGateway:ye};let rs=L(!1),_l=Be(()=>{let r=br.current,h=r.resolvedAccount.email?.trim(),T=Fn(h)?h:A.current.trim();if(!Fn(T))return null;let Q=r.resolvedAccount.firstName?.trim(),D=r.resolvedAccount.lastName?.trim(),pe=Ut.current.trim()||r.resolvedAccount.country?.trim()||"",It=r.avsConfig?nn(r.avsConfig.state,pe):!1,_t=r.avsConfig?nn(r.avsConfig.address_line_1,pe):!1,Le=r.avsConfig?nn(r.avsConfig.postal_code,pe):!1,tt=r.avsConfig?nn(r.avsConfig.city,pe):!1,gt=r.avsConfig?nn(r.avsConfig.address_line_2,pe):!1,un=_t&&!It&&Le?$y(pe,(fn.current??"").trim()):null,ar=It?Tn.current:un;return{accountData:{userId:r.resolvedAccount.userId??"",email:T,...Q?{firstName:Q}:{},...D?{lastName:D}:{},...Le&&fn.current?{zip:fn.current}:{},...tt&&Cn.current?{city:Cn.current}:{},...ar?{state:ar}:{},..._t&&zt.current?{addressLine1:zt.current}:{},...gt&&Dn.current?{addressLine2:Dn.current}:{},...pe?{country:pe}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:nn(r.avsConfig.country,pe),postal_code:Le,address_line_1:_t,address_line_2:gt,city:tt,state:It}}:{}}},[]),Tl=L(Ge);Tl.current=Ge,Je(()=>{Ge||Yt!==Mu||br.current.updateError(null)},[Ge,Yt]),Je(()=>{!Pe||!we||we.setSubmitGate?.($n||Ge||Lo||ae)},[Pe,we,$n,Ge,Lo,ae]),Je(()=>{if(!Pe||!we)return;rs.current=!1;let r=null,h=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,U.current="idle",R(null)},400)},T=we.on("submitting",()=>{rr(!0),B.current&&clearTimeout(B.current),U.current="validation-window",B.current=setTimeout(()=>{B.current=null,U.current==="validation-window"&&(U.current="processing")},wm),R("processing");let Le=br.current;if(!Le.sessionId||!Le.nonce)return;let tt=_l();if(!tt){Le.updateError("Enter a valid email address."),U.current="idle",R(null);return}new ca(Le.baseUrl).patchAccountSnapshot(Le.sessionId,Le.nonce,tt,{telemetryMode:"best_effort"}).catch(gt=>{if(!Em(gt))return;let un=gt instanceof Error?gt.message:"Please check your billing address and try again.";Le.updateError(un),U.current="idle",R(null),Le.onError?.(gt instanceof kr?gt:new kr(un,"api_error"))})}),Q=we.on("complete",Le=>{aa(Le.sessionId??br.current.sessionId),U.current="terminal",Oe(!1),R("success"),setTimeout(()=>{if(rs.current)return;rs.current=!0;let tt=br.current,gt=Ws(tt)||Le.outcome==="authorized",un=tt.serverSideCardGateway?{}:{paymentIntentId:Le.intentId};br.current.onComplete?.(gt?{status:"authorized",...un,paymentId:Le.paymentId??tt.paymentId,sessionId:Le.sessionId??tt.sessionId,authorizationExpiresAt:Le.authorizationExpiresAt??tt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...un,checkoutMethod:"card"})},600)}),D=we.on("decline",Le=>{let tt=br.current,gt=Le.message??"Your payment was declined. Please try another card or contact your bank.";U.current="terminal",Oe(!1),tt.updateError(gt),R("error");let un=Le.failureOutcome??Zy(Le.declineReason)??"authorization_declined";tt.emitDecline("card",gt,{code:un,declineCode:un}),h()}),pe=we.on("error",Le=>{let tt=br.current,gt=Fy(Le.vaultOutcome);if(gt!==null){r&&(clearTimeout(r),r=null),U.current="idle",Oe(!1),tt.updateError(gt),R(null),S(ar=>ar+1),tt.onError?.(new kr(gt,"api_error",{code:xy}));return}let un=Le.message??"There was a problem processing your payment. Please try again.";U.current="terminal",Oe(!1),tt.updateError(un),R("error"),tt.onError?.(new kr(un,"api_error",{code:Le.failureOutcome??"capture_failed"})),h()}),It=we.on("challenge_dismissed",()=>{B.current&&(clearTimeout(B.current),B.current=null),U.current="processing",Oe(!0),R(null)}),_t=we.on("blocked",()=>{if(z.current){br.current.updateError(km);return}if(!Tl.current){rr(!0);return}Xi(),br.current.updateError(Mu)});return()=>{r&&(clearTimeout(r),r=null),B.current&&(clearTimeout(B.current),B.current=null),U.current="idle",Oe(!1),R(null),T(),Q(),D(),pe(),It(),_t()}},[Pe,we,Xi,_l]);let Lr=!!Qe?.clientId,ma=Array.isArray(J),Ja=ma&&J.length>0,Ml=ma&&J.includes("paypal"),Xa=L(null);Xa.current===null&&(Xa.current=Ky());let qo=Xa.current?"redirect":uc(M,je,N.current()),{expressMethods:Za,paymentElementMethods:os}=ht(()=>Qy(J,{excludePaypal:Lr}),[J,Lr]),Al=Lr||!!m||Ml&&qo==="redirect",Rd=ht(()=>Al?Za.filter(r=>r!=="paypal"):Za,[Za,Al]),wd=ht(()=>{let r=[];return rt&&r.push("apple_pay"),dt&&r.push("google_pay"),r},[rt,dt]),jo=ma?Rd:wd,kd=k&&jo.length>0,Fl=se?Re:Ie,Qa=ht(()=>qy(os,Fl,Ue),[os,Fl,Ue]),as=ht(()=>({mode:"payment",amount:ya,currency:No,paymentMethodCreation:"manual",appearance:Cl}),[ya,No,Cl]),[is,xl]=re("loading"),[ss,Bl]=re("loading"),[ls,Dl]=re("loading"),[Ed,cs]=re(!1),[Ol,us]=re("loading"),[ds,Id]=re();Je(()=>{Id(wa())},[]);let ei=ds?.inAppBrowser,ti=ds?ui(ds,Qe?.approvalPresentation,xn??(et?"subscription":"order")):"popup",Ll=ee&&(Lr||(ma?Ml:ei===!1)),_d=M.inAppBrowser&&N.current()==="blocked",Nl=k&&kd&&!_d,So=(!St||!!ie.waitForDataAttachment)&&Ll&&Lr,ps=Ol==="retrying"||Ol==="exhausted",fa=null;k&&(m?fa=Pl:qo==="redirect"&&(fa=or));let Ul=ht(()=>({...pt,presentationMode:qo}),[pt,qo]),Ro=!St&&Ll&&!!fa&&(!Lr||ps),ao=!St&&Nl&&!!or,wo=!St&&k&&Ja&&Qa.length>0&&!!or,Td=So&&!ps?Ed:Ro&&ka(is),Md=ao&&ka(ss),Ad=wo&&ls!=="load_error",zl=[So||Ro,ao,wo,Pe].filter(Boolean).length,Fd={card:Pe,paypal:So&&!ps||Ro&&ka(is),wallets:ao&&ka(ss),apms:wo&&ls!=="load_error"},ql=r=>Fd[r],jl=r=>r==="loading"||r==="ready",$l=So||Ro&&jl(is)||ao&&jl(ss)||wo&&ls!=="load_error",ni=L(!1);Je(()=>{if(!ni.current){if(!k&&!ee){ni.current=!0;let r=new kr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(r),ge(r.message)}else if(!k&&ee&&!Lr){ni.current=!0;let r=new kr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(r),ge(r.message)}else if(ei!==void 0&&!St&&!Mn&&!$l){ni.current=!0;let r=new kr("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"});d?.(r),ge(r.message)}}},[k,ee,Lr,ei,St,Mn,$l,d,ge]);let Wl=L(!1);Je(()=>{if(Wl.current||!Ja)return;let r=[];rt!==!0&&r.push("showApplePay"),dt!==!0&&r.push("showGooglePay"),r.length!==0&&(Wl.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 Kl=Be((r,h,T)=>ie.applyInlineSessionPatch?ie.applyInlineSessionPatch(r).then(Q=>({error:null,sessionId:Q.sessionId||e,nonce:Q.session?.clientSecret||t})).catch(Q=>{let D=wu(h,Q);return T?.abandoned?.()||(ge(D.message),d?.(D)),{error:D,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ie.applyInlineSessionPatch,t,d,e,ge]),Sr=Be(async(r,h)=>{if(r!=="card"&&St&&await ie.waitForDataAttachment?.(),!it)return{proceed:!0};try{let T=await it({method:r,sessionId:e||void 0,createSession:ie.inlineSessionDraft});if(T===!1)return{proceed:!1};if(T&&typeof T=="object"){T.account&&qn(D=>({...D??{},...T.account}));let Q=await Kl(T,r,h);return Q.error?{proceed:!1,accountPatch:T.account}:{proceed:!0,accountPatch:T.account,sessionId:Q.sessionId,nonce:Q.nonce}}return{proceed:!0}}catch(T){if(!h?.abandoned?.()){let Q=wu(r,T);ge(Q.message),d?.(Q)}return{proceed:!1}}},[Kl,ie.inlineSessionDraft,ie.waitForDataAttachment,St,it,d,e,ge]),Hl=Be(async(r,h)=>{if(x.current)return;x.current=!0,Zt(!0),R("processing"),ge(null);let T=h?.sessionId??e,Q=h?.nonce??t,D=Ms(ft,h?.accountPatch),pe=h?.completionPaymentMethodId??_a(r),It=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,_t=Mm(r),Le=h?.presentationMode?Ti(hn(K),{...pt,presentationMode:h.presentationMode}):void 0,tt=()=>{C?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:_t}),Le?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Er,requestCategory:"process_payment"})};try{let gt=new ca(ro),ar=h?.settledProcessResponse??await gt.processPayment(D.userId??"",{sessionId:T,nonce:Q,paymentMethodCategory:h?.paymentMethodCategory??Fm(r),tokenizedData:It,accountData:{...h?.accountPatch,userId:D.userId??"",email:D.email??"",firstName:D.firstName||void 0,lastName:D.lastName||void 0,...My({avsConfig:v,country:Ut.current,zip:fn.current,city:Cn.current,state:Tn.current,addressLine1:zt.current,addressLine2:Dn.current})},...Ty({chv:O,avsCheck:lt,checkoutType:Ke,checkoutLayout:bt,avsConfig:v,country:Ut.current})}),si=async Rn=>{let ko=Ws(j)||Rn?.status==="authorized";aa(T),Le?.terminal({outcome:"payment_succeeded",...Er}),R("success"),Ye(null),await new Promise(Sa=>setTimeout(Sa,600));let Nr;typeof Rn?.paymentId=="string"?Nr=Rn.paymentId:j?.paymentId&&(Nr=j.paymentId);let Eo;typeof Rn?.authorizationExpiresAt=="string"?Eo=Rn.authorizationExpiresAt:j?.authorizationExpiresAt&&(Eo=j.authorizationExpiresAt),l?.(ko?{status:"authorized",...Nr===void 0?{}:{paymentId:Nr},sessionId:typeof Rn?.sessionId=="string"?Rn.sessionId:T,...Eo===void 0?{}:{authorizationExpiresAt:Eo},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:pe,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:pe,checkoutMethod:r.isPaypal?"paypal":"card"})};if(ar.ok){await si(ar.status===204?null:await ar.json().catch(()=>null));return}let dn=await ar.json().catch(()=>null);if(dn?.type==="paypal_redirect_required"){let Rn=dn.threeDSecureToken,ko=dn.paymentMethodId||r.id||"";if(!K||!Rn){R("error"),ge("PayPal authorization required but no token provided.");return}try{let Nr=m?.getRawProvider();if(!Nr){ge("PayPal is not available.");return}let Eo={return_url:window.location.href};ko&&(Eo.payment_method=ko);let{error:Sa}=await Nr.confirmPayment({clientSecret:Rn,confirmParams:Eo,redirect:"if_required"});if(Sa){R("error");let ic=Sa.message??"PayPal payment failed.";ge(ic),Or("paypal",ic,{code:Sa.code})}}catch(Nr){R("error"),ge(Nr instanceof Error?Nr.message:"PayPal authorization failed.")}return}if(dn?.type==="paypal_direct_required"){let Rn=dn.orderId;if(!Rn){R("error"),ge("PayPal retry required but no order id provided.");return}let ko=Sn.current?.attempts??0;if(ko>=2){R("error"),ge("PayPal payment could not be completed after multiple attempts."),Or("paypal","paypal_direct_required retry limit exceeded");return}cs(!1),us("loading"),Ye({orderId:Rn,attempts:ko+1}),R(null);return}if(ar.headers.get(hm)===Pm){let Rn=await Cm(gt,T,Q);if(Rn!==void 0){await si(Rn);return}}Oy(ar.status,dn)?Le?.terminal({outcome:"payment_declined",...Er,terminalReason:"provider_declined"}):tt(),R("error");let ac=dn?.message??"Payment failed. Please try again.";ge(ac),Or(r.isPaypal?"paypal":"card",ac,{code:dn?.code??dn?.gatewayErrorCode,declineCode:dn?.declineCode??dn?.gatewayDeclineReason}),await new Promise(Rn=>setTimeout(Rn,400))}catch(gt){Wu(gt)||tt(),R("error"),ge(gt instanceof Error?gt.message:"An unexpected error occurred"),await new Promise(un=>setTimeout(un,400))}finally{Zt(!1),R(null),x.current=!1}},[ro,e,t,ft,v,lt,Ke,bt,O,K,m,j,l,ge,Or,C,pt]),Qn=Be((r,h)=>{P&&!h?.settledProcessResponse?P(r):Hl(r,h)},[P,Hl]),ga=`${ju}:${e}`;Je(()=>{if(typeof window>"u")return;let r=localStorage.getItem(ga);if(!r)return;let h;try{h=JSON.parse(r)}catch{sn(ga);return}if(!h||typeof h.createdAt!="number"||Date.now()-h.createdAt<0||Date.now()-h.createdAt>$u||typeof h.paymentMethodId!="string"||typeof h.providerIntentId!="string"||typeof h.paymentMethodType!="string"||h.sessionId!==e||!t||h.nonce!==t||!jo.includes(h.paymentMethodType)){sn(ga);return}sn(ga),Qn({id:h.paymentMethodId,type:"card",threeDSecureActionResultTokenId:h.providerIntentId,gateway:"stripe",paymentMethodType:h.paymentMethodType},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Qn,t,e,ga,jo]);let Vl=L(!1);Je(()=>{if(typeof window>"u"||Vl.current)return;let[r,h,T]=Lu();if(!r||!h||Xa.current||!K)return;let Q=K.getRawProvider();if(!Q)return;let D=tt=>{let gt=localStorage.getItem(tt);if(!gt)return null;try{return JSON.parse(gt)}catch{return sn(tt),null}},pe=D(qr)??D(Iu),It;if(pe?.clientSecret){if(pe.clientSecret!==h)return;It={...pe.accountPatch?{accountPatch:pe.accountPatch}:{},...pe.sessionId?{sessionId:pe.sessionId}:{},...pe.nonce?{nonce:pe.nonce}:{}}}else if(pe?.sessionId&&pe.sessionId!==e)return;Vl.current=!0,sn(qr),sn(Iu),window.history.replaceState({},"",Uu());let _t=pe?.paymentMethodType??pe?.tokenType??"card",Le="card";(async()=>{if(T==="failed"){let dn="Payment was declined. Please try again.";ge(dn),Or(Le,dn);return}let{paymentIntent:tt,error:gt}=await Q.retrievePaymentIntent(h);if(gt){let dn=gt.message??"Failed to retrieve payment status.";ge(dn),Or(Le,dn,{code:gt.code});return}let un=tt?.status,ar=Ia(un);if(!tt||!ar){let dn=un==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ge(dn),Or(Le,dn,{code:un??"missing_payment_intent"});return}let si=typeof tt.payment_method=="string"?tt.payment_method:tt.payment_method?.id;Qn({id:si??pe?.paymentMethodId??pe?.tokenId??tt.id,type:"card",threeDSecureActionResultTokenId:tt.id,gateway:pe?.gateway??"stripe",paymentMethodType:_t},It)})()},[e,Qn,K,ge,Or]);let ys=Be(r=>{r.preventDefault()},[]);if(!(Pe||K!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ha=ke==="buttons",Wn=Do?.variables,xd=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ms=Wn?.colorBackground,Bd=ms&&!xd.has(ms)?ms:void 0,Pa=Ce.cardInputBorder??(ha?"#e5e7eb":"#A4A4FF"),Gl=Wn?.colorDanger??"#dc2626",tn=r=>ln[r]&&(vo[r]||cr),ri=Lo&&(Co||cr),ur=r=>r?Gl:Pa,oi=(An.malformed||An.empty)&&(Kr||cr),Dd=ur(oi),fs=Ce.cardFormContainer?.backgroundColor??Bd??(ha?"white":"#EDEDFF"),$o=Ce.cardInputBackground??Wn?.colorBackground??"white",gs=Vo(te),Yl=Vo(ce),Wo=Ce.nameInput,Jl=Ce.cardInputFontSize??Om(Wo?.fontSize)??Wn?.fontSizeBase??"16px",Xl=typeof Wo?.fontFamily=="string"?Wo.fontFamily:Wn?.fontFamily??"Poppins, sans-serif",Zl=lm(Wo?.fontWeight)??400,Od=Ce.cardInputColor??(typeof Wo?.color=="string"?Wo.color:void 0)??Wn?.colorText??"#262833",Ld=Ce.cardInputPlaceholderColor??"#9ca3af",an=Wn?.borderRadius??"8px",Yr=Wn?.borderRadius??Ce.cardButton?.borderRadius??an,io=Wn?.colorPrimary??"#4A49FF",Nd=Wn?.colorPrimaryHover??Uy(io,.12),hs=Wn?.colorText??"#262833",Ps={fontSize:Jl,fontFamily:Xl,fontWeight:Zl,color:Od,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ca={marginTop:"0.375rem",...Ps,fontSize:"0.75rem",lineHeight:1.4,color:Gl},Ud={"--flopay-input-placeholder-color":Ld,"--flopay-input-font-size":Jl,"--flopay-input-font-family":Xl,"--flopay-input-font-weight":String(Zl)},va=Ce.cardFormContainer??{},Cs=va.padding??(ha?"0":"1rem"),vs=va.borderRadius??an,zd=we&&On?u(Ss,{capture:we,html:On.html,messageToken:On.messageToken,expectedOrigin:On.expectedOrigin,verificationRequired:On.verificationRequired,theme:vd,submitLabel:F,onReady:()=>{if(!oo&&!v||typeof document>"u"||ze===!1)return;let r=()=>{let T=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(T){vr.current=!0;try{T.focus()}finally{vr.current=!1}}};to.current||r()},onError:r=>{r&&On.verificationRequired&&U.current==="idle"&&(b.current=!0),ge(r)},onValidation:r=>{let h=U.current;(h==="idle"||h==="validation-window")&&(ge(r),r&&U.current==="validation-window"&&(B.current&&(clearTimeout(B.current),B.current=null),U.current="idle",R(null)))}},s):u("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"}),bs=Ne("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&Br()},style:{backgroundColor:fs,borderRadius:vs,...va,padding:Cs,...Ud,display:"flex",flexDirection:"column"},children:[u("style",{children:`
|
|
5
5
|
.flopay-shared-input::placeholder {
|
|
6
6
|
color: var(--flopay-input-placeholder-color);
|
|
7
7
|
opacity: 1;
|
|
@@ -9,13 +9,13 @@ ${he.join(`
|
|
|
9
9
|
font-family: var(--flopay-input-font-family);
|
|
10
10
|
font-weight: var(--flopay-input-font-weight);
|
|
11
11
|
}
|
|
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:
|
|
13
|
-
`)}):null,
|
|
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(rs,$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"},X;Fe==="expanding"||Fe==="apm-expanding"?X=bm:(Fe==="collapsing"||Fe==="apm-collapsing")&&(X=Cm);let B;Fe==="expanding"?B=_d:Fe==="collapsing"&&(B=Td);let pe=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:L,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:I,onTechnicalFailure:zo,onButtonClick:$e,runBeforeButtonClick:Sr,isProcessing:on,onLoadStateChange:ss,onInitializationStateChange:ls,session:Mt,existingOrderId:fe?.orderId,debug:j},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:$e,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Ml,placeholderBorderRadius:Yr,popupCapabilityOwner:L,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:$e,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Al,placeholderBorderRadius:Yr,popupCapabilityOwner:L,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:rs,futureUseSession:At,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:$e,onDecline:m,runBeforeButtonClick:Sr,onLoadStateChange:xl,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,onExpandApm:J,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||($e?.("card"),K())},disabled:on,style:{width:"100%",...E,...ve.cardButton,...rl({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:us,className:te,noValidate:!0,style:{position:"relative"},children:[d(ui,{}),z&&d(Ur,{status:z,errorMessage:Yt,authorized:Rt}),Ne("div",{style:{display:"grid"},children:[Ne("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!X?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!X?wm:{},...X?{animation:X,pointerEvents:"none"}:{}},children:[Jl("flopay-direct-paypal-gate-debug"),Xl("flopay-stripe-gate-debug"),rn&&pe?Ne(Kn,{children:[rn.filter(({group:Et})=>pe.inView.includes(Et)).map(({group:Et,key:Le})=>d(ja.Fragment,{children:It[Et]},Le)),pe.behindLink.length>0&&d(Us,{...Ql,showLink:pe.showLink,children:rn.filter(({group:Et})=>pe.behindLink.includes(Et)).map(({group:Et,key:Le})=>d(ja.Fragment,{children:It[Et]},Le))})]}):d(zs,{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",...B?{animation:B}:{},...Fe==="collapsing"?{pointerEvents:"none"}:{}},children:vs}),k&&Zl&&$t&&ii&&or&&d("div",{style:{gridArea:"1 / 1",...Ko?{animation:Ko}:{},...Fe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ne("div",{style:{backgroundColor:ys,borderRadius:Ps,...Ca,padding:hs},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:ue,style:{display:"inline-flex",alignItems:"center",gap:ms?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:fs,paddingRight:80,...ve.title},children:`Pay with ${Wa($t)}`})]}),d(uo,{stripe:or,options:ii,children:d(Zs,{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:ue,runBeforeButtonClick:Sr,onButtonClick:$e,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,errorText:Yt})},$t)]})})]})]})}if(Zl&&$t&&ii&&or&&k)return Ne("form",{onSubmit:us,className:te,noValidate:!0,style:{position:"relative"},children:[d(ui,{}),z&&d(Ur,{status:z,errorMessage:Yt,authorized:Rt}),d("div",{style:{...Ko?{animation:Ko}:{},...Fe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ne("div",{style:{backgroundColor:ys,borderRadius:Ps,...Ca,padding:hs},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:ue,style:{display:"inline-flex",alignItems:"center",gap:ms?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:fs,paddingRight:80,...ve.title},children:`Pay with ${Wa($t)}`})]}),d(uo,{stripe:or,options:ii,children:d(Zs,{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:ue,runBeforeButtonClick:Sr,onButtonClick:$e,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:L,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:I,onTechnicalFailure:zo,onButtonClick:$e,runBeforeButtonClick:Sr,isProcessing:on,onLoadStateChange:ss,onInitializationStateChange:ls,session:Mt,existingOrderId:fe?.orderId,debug:j},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:$e,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Ml,placeholderBorderRadius:Yr,popupCapabilityOwner:L,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:$e,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Al,placeholderBorderRadius:Yr,popupCapabilityOwner:L,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:rs,futureUseSession:At,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:$e,onDecline:m,runBeforeButtonClick:Sr,onLoadStateChange:xl,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,themeId:be,onExpandApm:J,expandedApmMethod:$t,buttonAppearance:{backgroundColor:ve.cardButton?.backgroundColor,borderColor:ve.cardInputBorder,textColor:ve.cardButton?.color,borderRadius:Yr}})})};return Ne("form",{onSubmit:us,className:te,noValidate:!0,style:{position:"relative"},children:[d(ui,{}),z&&d(Ur,{status:z,errorMessage:Yt,authorized:Rt}),rn===null?d(zs,{rows:Ll,borderRadius:Yr}):Ne(Kn,{children:[yn&&Pe&&vs,yn&&Pe&&ec&&d(bs,{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(Us,{...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(bs,{label:"or pay with card"}),!yn&&Pe&&vs]})]})}import{Fragment as jr,jsx as le,jsxs as Pn}from"react/jsx-runtime";var xo=44,cl="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 al(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 il(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}=Ls(e);return{...await Ns({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 dl(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Gm(){if(!dl())return null;try{let e=window.sessionStorage.getItem(cl);return e?JSON.parse(e):null}catch{return null}}function tu(e){if(dl())try{window.sessionStorage.setItem(cl,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function sl(){if(dl())try{window.sessionStorage.removeItem(cl)}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 ll(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 ul({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:l,loading:u,error:m,onComplete:I,onError:b,onInstrument:g,onDecline:A,onCancel:Y,onCountryChange:te,onZipChange:x,showPayPal:D=!0,showStripe:C=!0,walletPresentation:ne="auto",enabledPaymentMethods:re,showApplePay:k=!0,showGooglePay:je=!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:ce,cardFieldOrder:Kt,showCardBrandIcons:$e,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),de=mr(()=>iu(Re),[Re]),_e=i??de?.appearance,st=n?"embedded_checkout":"standard_checkout",lt=ll(Me,Ue),[Ke,Ct]=Jt(null),_t=Bt(null),ct=pn(v=>{_t.current=v,Ct(v)},[]),[Ae,Qe]=Jt(null),et=Bt(null),q=Bt(null),Ht=Bt(0),[R,j]=Jt(null),$=Bt(null),[y,ie]=Jt(null),h=mr(()=>n?Ba(n):"",[n]),W=n?`create:${h}`:`session:${e??""}`,L=ru(y),he=Bt(new Set),Se=Bt(W),_=Bt(W);wa(()=>{_.current=W,Se.current!==W&&(Se.current=W,he.current.clear())},[W]);let ut=pn(v=>{if(_.current===W){if(Uc.has(v.name)){if(he.current.has(v.name))return;he.current.add(v.name)}Ft(()=>g?.(v))}},[W,g]),Mt=na(ut,W),At=Bt(!1),Fn=pn(v=>{if(At.current)return;let s=v.gateway||!L?v:{...v,gateway:L};ut(s)},[ut,L]);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,We]=Jt(0),P=Bt(!1),se=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(I);Wr.current=I;let Mn=Bt(b);Mn.current=b;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),$.current=s,j(s)},[]),sr=pn(()=>{let v=q.current;v&&(q.current=null,v.destroy())},[]),Po=pn(()=>{let v=et.current,s=$.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&&ie(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(),$.current?.getRawProvider()]),Cn(p.flopay,p.paypalFlopay),rn(0),Mr({flopay:p.flopay,apply:c});return}let K=Qd({billingApiUrl:V,locale:l,telemetry:a});q.current=K,Cn(K,null),rn(1),c()},[sr,Cn,l,V,a]);ir(()=>{hn(Ae)?.setCheckoutContext(en),R&&R!==Ae&&hn(R)?.setCheckoutContext(en)},[Ae,R,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"),We(v=>v+1)},[]);ir(()=>{Tn("loading"),We(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?Es(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,K=v.clientSecret||t,qe=ru(v),J=et.current??$.current,ue=hn(J),z=J?null:zi(V,a,en),w={log:U=>{ue?ue.log(U):z?.log(U)},error:U=>{ue?ue.error(U):z?.error(U)},terminal:U=>{ue?ue.terminal(U):z?.terminal(U)},performance:U=>{ue?ue.performance(U):z?.performance(U)},now:()=>ue?.now()??z?.now()??0,elapsed:U=>ue?.elapsed(U)??Math.max(0,(z?.now()??U)-U)},oe=w.now(),me=!!(s?.initialAutoProcessingError||s?.initialAutoProcessingPending),S=!1,M,F=()=>{S||(S=!0,me=!0,M=w.now(),w.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),w.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},N=!1,ae=()=>{N||(N=!0,w.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),w.performance({stage:"processing",durationMs:w.elapsed(oe),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),M!==void 0&&w.performance({stage:"recovery",durationMs:w.elapsed(M),durationMode:"machine",paymentMethodCategory:"saved"}))};w.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),At.current=!0;try{w.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{At.current=!1}Mt({class:"lifecycle",name:"payment.processing.started",provider:qe}),me&&F();let Oe;try{let U=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=>{F();let Lt=Ua(V,p,v,a!==!1);return Tr(Gt=>sa(jt,{billingApiUrl:V,sessionId:p,nonce:K,session:v,signal:Gt,...Lt.telemetry?{challengeTelemetry:Lt.telemetry}:{}})).finally(Lt.release)};if(fe)Ye=await Sn(fe);else if(U)F(),U.type==="paypal_redirect_required"&&ye.current?.publishableKey&&tu({sessionId:p,publishableKey:ye.current.publishableKey,paypalPublishableKey:ye.current.paypalPublishableKey,nonce:K}),Ye=await Tr(jt=>_i(U,{flopay:et.current,paypalFlopay:$.current,attempt3DS:s?.attempt3DS,billingApiUrl:V,sessionId:p,session:v,telemetry:!1,signal:jt})),U.type==="paypal_redirect_required"&&sl();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:K,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:K,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):(F(),jt.type==="paypal_redirect_required"&&ye.current?.publishableKey&&tu({sessionId:p,publishableKey:ye.current.publishableKey,paypalPublishableKey:ye.current.paypalPublishableKey,nonce:K}),Ye=await Tr(Lt=>_i(jt,{flopay:et.current,paypalFlopay:$.current,attempt3DS:s?.attempt3DS,billingApiUrl:V,sessionId:p,session:v,telemetry:!1,signal:Lt})),jt.type==="paypal_redirect_required"&&sl())}}if(p&&aa(p),!c.active)return!1;ae(),me&&(w.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),w.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),w.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(U){if(!c.active)return!1;let fe=lo(za(U),p);if(fe.code==="three_ds_aborted")return!1;let Ye=fe.checkoutMethod??Na;we(fe.message),Qt(fe.message),In(!1),s?.fallbackToFull&&(w.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Xt("full"),nu("full")),ae();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))w.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...jt});else if(Lt&&(fe.telemetryOutcome==="validation_rejected"||fe.type==="validation_error"))w.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...jt});else{let Zn=ou(U,me?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),ve=fe.telemetryRequestCategory??"process_payment";At.current=!0;try{w.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&&(w.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),w.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{ae(),z&&Va(z),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"||se.current)return;let v=new URLSearchParams(window.location.search),s=v.get("payment_intent_client_secret");if(!s)return;let c=Gm();c&&(se.current=!0,(async()=>{await Promise.resolve();let p,K=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:J}=await Ns({publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey,billingApiUrl:V,locale:l,telemetry:a});p=hn(J??qe),p?.setCheckoutContext(en),K=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 ue=(J??qe)?.getRawProvider();if(!ue)throw Object.assign(new kn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:z,error:w}=await ue.retrievePaymentIntent(s);if(w)throw Object.assign(new kn(w.message??"Failed to retrieve PayPal payment status.","api_error",{code:w.code}),{checkoutMethod:"paypal"});let oe=Rc(z?.status);if(!z||oe==="failed")throw Object.assign(new kn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let me=typeof z.payment_method=="string"?z.payment_method:z.payment_method?.id,S=oe;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 ae=(await new Oi(V,{telemetry:!1}).getUnifiedCheckoutSession(c.sessionId,M)).data.session;if(ae&&ae.status!=="complete"){let Oe=await la({billingApiUrl:V,sessionId:c.sessionId,session:ae,nonce:M,telemetry:!1,tokenizedData:{id:me??z.id,type:"card",threeDSecureActionResultTokenId:z.id,isPaypal:!0}});if(Oe.type!=="success")throw Object.assign(new kn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});S=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(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),p?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),St("success"),await Ha(600),Ft(()=>Wr.current?.({status:S,paymentIntentId:z.id,paymentMethodId:me,checkoutMethod:"paypal"}))}catch(qe){let J=lo(za(qe),c.sessionId),ue=J.checkoutMethod??"paypal",z=Vd(J);if(p)p.performance({stage:"redirect_resume",durationMs:p.elapsed(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z?p.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):p.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(z){let w=zi(V,a,en);w.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Va(w)}else al(V,a,en,"REDIRECT_RESUME_FAILED","redirect_resume");we(J.message),Qt(J.message),Hd(J)?cr(ue,J,{code:J.code,declineCode:J.declineCode}):Ft(()=>Mn.current?.(J)),St("error"),await Ha(400)}finally{sl(),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),K=new Oi(V,{telemetry:!1,stripeAccountSwitch:!0}),qe=!1;try{let J=v.idempotencyKey===void 0?void 0:Gd(v.idempotencyKey),ue=Zc(s,c),z=Xc(s,c);ue?.canonicalIdentity===c&&z&&z.canonicalIdentity===void 0&&(wi(s,c,z.idempotencyKey),z={...z,canonicalIdentity:c});let w=J??(z?.canonicalIdentity===c?z.idempotencyKey:void 0),oe,me=!1;p.log({name:ue?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let S=ue?.sid??null,M=null,F,N,ae=!1;if(S)try{M=await K.getUnifiedCheckoutSession(S,ue?.nonce),ue&&ue.canonicalIdentity===void 0&&(Jc(M.data.session,v)?(ki(s,c,S,ue.nonce??M.data.session?.clientSecret),z&&z.canonicalIdentity===void 0&&(wi(s,c,z.idempotencyKey),w??(w=z.idempotencyKey))):(Si(s,c),z=null,w=J,S=null,M=null));let U=M?.data.session?.status,fe=M?.data.session,Ye=fe?.clientSecret||ue?.nonce;if(S&&fe?.buyerIdentified===!1&&Ye&&(N=Xo(K,S,Ye,v.account)),S&&M&&U==="complete"){if(Bs(S))return{sid:S,result:M};Si(s,c),S=null,M=null,me=!0}}catch{p.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ue?.canonicalIdentity===void 0?(Si(s,c),w=J):Fs(s,c),S=null}if(!S){!J&&(me||!w)&&(w=Gd(),oe=w),w&&wi(s,c,w);let U=p.now(),fe=0;p.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ye={...v,idempotencyKey:w,avsCheck:!!ce,avsConfig:typeof ce=="object"?ce:void 0,checkoutType:"embedded_checkout",checkoutLayout:ll(Me,Ue)};Object.defineProperty(Ye,Dm,{configurable:!1,enumerable:!1,value:{onAttempt:Lt=>{fe=Math.max(fe,Lt)}}});let Sn=()=>{Xd(p,"session_create",U,fe)},jt=Lt=>{Zd(p,Lt,"session_create",U,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 K.createDetachedSession(Ye);Lt.claimed.catch(()=>{}),M=Lt.shell,S=Lt.sessionId,N=Lt.claim;let Gt=p.now();p.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),F=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 Fs(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)),F.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()-U,durationMode:"machine",requestCategory:"session_create",attempt:fe,statusClass:"2xx",paymentMethodCategory:"card"})}else M=await K.createAndFetchSession(Ye),Sn()}catch(Lt){throw jt(Lt),Lt}S=M.data.session?.id??S??"",S&&!F&&ki(s,c,S,M.data.session?.clientSecret)}let Oe=M?.data.session;return!N&&S&&Oe?.buyerIdentified===!1&&Oe.clientSecret&&(N=Xo(K,S,Oe.clientSecret,v.account)),{sid:S??"",result:M,sdkGeneratedIdempotencyKey:oe,...F?{claimed:F}:{},...N?{claim:N}:{},...ae?{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=Es(c,v),K=Ba(p),qe=Yc(p),J=qi.get(K);if(!J){let w={canonicalIdentity:K,promise:Co.current(p,qe,K),consumers:0,settled:!1};J=w,qi.set(K,w);let oe=()=>{w.settled=!0,Jd(K,w)};w.promise.then(oe,oe)}J.consumers+=1;let ue=!1,z=()=>{ue||(ue=!0,J.consumers-=1,Jd(K,J))};s?.(z);try{let w=await J.promise;Kr.current=K,v&&(mn(Yn),hr(Oe=>vc(Oe,v)));let{sid:oe,result:me,claimed:S,claim:M,claimRequiresIdentity:F}=w;Dn.current=M,fn(F===!0),ct(me),me.data.session&&ie(me.data.session),oe&&fr(oe);let N=()=>{},ae=new Promise(Oe=>{N=Oe});if(S){zt.current+=1;let Oe=zt.current,U=()=>zt.current===Oe;Ut.current=S,zn(!0);let fe=Ye=>{U()&&(Ut.current===S&&(Ut.current=null),Gn(Ye),zn(!1),fn(!1))};S.then(async Ye=>{if(!U())return;let Sn=Kd(_t.current??me,Ye);if(!Sn.data.stripe?.publishableKey||eu(Sn)===eu(me)){fe(Ye);return}await ae,U()&&await jn(Sn,U,()=>fe(Ye))},Ye=>{zt.current===Oe&&(Ut.current===S&&(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:U}=await Ni(me,{billingApiUrl:V,locale:l,telemetry:a}).catch(Ye=>{throw Sc(Ye,oe||me.data.session?.id)}),fe=_t.current;S&&fe!==me&&!fe?.data.stripe?.publishableKey?Cn(null,null):Cn(Oe,U)}finally{N()}return yt(!1),w}catch(w){throw Kr.current===K&&(Kr.current=null),w}finally{s||z()}},[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())},K=vo.current;if(xr&&K)return Xt($n),yt(!1),Kr.current===xr?p:(ie(Cc(K,Ee)),(async()=>{let ue=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),z=$n==="auto"&&!P.current&&!ue;z&&(we(null),Qt(null),St("processing"));let w=!1;try{let oe=await eo.current(void 0,F=>{s=F});w=!0;let me=oe.result.data.session??null;ye.current=Ls(oe.result);let S=il(oe.result),M=Bs(oe.sid||me?.id);if(!v&&z&&me&&!S&&!M){P.current=!0,await Hm(xr,oe.sdkGeneratedIdempotencyKey,()=>Cr.current(me,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:oe.result.autoProcessingError,initialAutoProcessingPending:oe.result.autoProcessingPending,autoProcessingAttempted:oe.result.autoProcessingAttempted,sessionId:oe.sid||me.id}));return}!v&&z&&((S||M)&&(P.current=!0),St(null),Qt(null))}catch(oe){if(v)return;let me=yi(oe);if(z&&me==="session_auto_completed"){P.current=!0,St("success"),await Ha(600),v||(Ft(()=>{Wr.current?.({status:"succeeded"})}),St(null),Qt(null));return}if(z&&(St(null),Qt(null)),!w){let M=wc(oe),F=Yd(oe,M?{stage:"provider_load",provider:"stripe",...M}:{stage:"session_request"});(M||!(oe instanceof kn))&&Ft(()=>Mn.current?.(F)),Hn(F);return}let S=oe instanceof kn?oe:new kn(oe instanceof Error?oe.message:"Failed to create session","api_error");Hn(S)}finally{s?.(),s=void 0}})(),()=>{p(),s?.()});yt(!0);async function qe(){let ue=!1,z=!1,w=null;try{let oe=new Oi(V,{telemetry:!1}),me=await oe.getUnifiedCheckoutSession(bt,t);if(z=!0,w=me,v)return;ct(me);let S=me.data.session??null;if(ie(S),!S)throw new kn("No session data returned","api_error");let M=S.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(S.status==="authorized"){yt(!1),Ft(()=>{Wr.current?.(Jr(S,bt)),Ar.current?.(S.successUrl??"")});return}if(S.status==="complete"){yt(!1),Ft(()=>{Ar.current?.(S.successUrl??"")});return}if(S.status==="expired")throw pi(S);ue=!0;let F=Ee??M??"full";Xt(F),zt.current+=1;let N=S.clientSecret||t;Dn.current=S.buyerIdentified===!1&&N?Xo(oe,bt,N,{...S.customer?.id?{userId:S.customer.id}:{}}):void 0,zn(!1),fn(!1);let ae=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Oe=il(me);if(F==="auto"&&!P.current&&!ae&&!Oe){P.current=!0;let U=J(me);try{if(await Cr.current(S,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>U,sessionId:bt||S.id}),v)return;await U,v||yt(!1);return}catch{if(v)return;await U,v||yt(!1);return}}await J(me),v||yt(!1)}catch(oe){if(v)return;let me=Pc(oe,ue);if(ue&&Mt({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),me){let{errorCode:N,stage:ae,...Oe}=me;al(V,a,en,N,ae,Oe)}if(me?.stage==="provider_load"&&(Ee??w?.data.session?.checkoutMode??"full")==="full"&&hc(w,D,C)){let N=Qd({billingApiUrl:V,locale:l,telemetry:a});q.current=N,Cn(N,null),rn(1),yt(!1);return}let S=me?.stage==="provider_load",M="session_request";S?M="provider_load":z&&(M="post_session");let F=Yd(oe,{stage:M,provider:"stripe",sessionId:bt||void 0});(S||!(oe instanceof kn))&&Ft(()=>Mn.current?.(F)),Hn(F),yt(!1)}}async function J(ue){let{flopay:z,paypalFlopay:w,...oe}=await Ni(ue,{billingApiUrl:V,locale:l,telemetry:a});ye.current={publishableKey:oe.publishableKey,paypalPublishableKey:oe.paypalPublishableKey},Cn(z,w),rn(0)}return qe(),p},[Ee,xr,$n,Er,t,D,C]);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,...K}=Is(s);al(V,a,en,c,p,K)}},[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=il(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?le(Ur,{status:tr,errorMessage:Bn,authorized:gr}):null;if(pt&&!Br){if(u)return Pn(jr,{children:[u,cn]});if(Ue==="buttons"){let v=de?.buttonsLayout?.cardButton?.borderRadius??de?.appearance.variables?.borderRadius??8,s=c=>le("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:[D&&s(xo),C&&(k||je)&&s(xo),C&&s(xo),le("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:[le("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),le("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),cn]})}return Rn?m?le(wr.Provider,{value:Dr,children:m(Rn)}):le(wr.Provider,{value:Dr,children:le("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Rn.message})}):bn?Pn(jr,{children:[le(wr.Provider,{value:Dr,children:le(Qm,{onButtonClick:Ie,paymentMethodLayout:rt,showPayPal:D,showStripe:C,showApplePay:k,showGooglePay:je,theme:Re,buttonsTheme:Nt,buttonsStyles:Dt,cardButtonContent:be,cardBackButtonContent:He,cardTitleContent:ot})}),cn]}):Gr&&y&&$t?Pn(jr,{children:[le(wr.Provider,{value:Dr,children:Pn("div",{className:Pt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xe&&le(oa,{icon:!1,children:xe}),vn==="retrying"&&le("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),vn==="exhausted"&&Pn("div",{role:"alert",children:[le("div",{children:"PayPal is temporarily unavailable. Please try again."}),le("button",{type:"button",onClick:lr,children:"Retry PayPal"})]}),vn!=="exhausted"&&le("div",{"aria-hidden":vn==="retrying"?!0:void 0,style:vn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:le(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:I,onErrorChange:we,onDecline:A,onCancel:Y,onButtonClick:Ie,runBeforeButtonClick:Vr,onInitializationStateChange:vr,allowAutomaticRetry:T===0,session:y,telemetry:a,telemetryContext:en,onInstrument:Fn,debug:G},`${W}:paypal-init-${T}`)})]})}),cn]}):yn==="confirm"?Pn(jr,{children:[le(wr.Provider,{value:Dr,children:le(Ri,{flopay:Ae,paypalFlopay:R,options:no??{billingApiUrl:V},onInstrument:Fn,children:Pn("div",{className:Pt,children:[xe&&le("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:xe}),Ot?Ot({onConfirm:Ln,isProcessing:Fe}):le("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"})]})},W)}),cn]}):(!Ae||!no)&&!(Br&&yn==="full")?le(jr,{children:cn}):Pn(jr,{children:[le(wr.Provider,{value:Dr,children:Pn(Ri,{flopay:Ae,paypalFlopay:R,options:no??{billingApiUrl:V},onInstrument:Fn,children:[Vn===1&&le("button",{type:"button",onClick:On,children:"Retry payment methods"}),Me?Pn(jr,{children:[xe&&le("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:xe}),le(Zm,{sessionId:bt,nonce:y?.clientSecret||void 0,billingApiUrl:V,session:y,submitLabel:Ze,walletPresentation:ne,paymentMethodLayout:rt,moreOptionsLabel:dt,children:Me})]}):le(ol,{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:I,onError:b,onDecline:A,onCancel:Y,error:xe,onErrorChange:we,showPayPal:D,showStripe:C,walletPresentation:ne,enabledPaymentMethods:Vn?[]:re??Ke?.data.stripe?.enabledPaymentMethods??y?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:k,showGooglePay:je,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:ce,...Kt?{cardFieldOrder:Kt}:{},...$e===void 0?{}:{showCardBrandIcons:$e},...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:x,avsCheck:!!ce,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ll(Me,Ue),className:Pt,submitLabel:Ze,directPaypal:$t,isSubscription:y?.mode==="subscription",session:y,dataAttachmentPending:Un,dataAttachmentRequiresIdentity:qn,debug:G})]},W)}),cn]})}function Zm({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,paymentMethodLayout:l,moreOptionsLabel:u,children:m}){return le(jr,{children:Ui.Children.map(m,I=>{if(!Ui.isValidElement(I))return I;let b=I.props,g={};return b.sessionId||(g.sessionId=e),!b.nonce&&t&&(g.nonce=t),b.billingApiUrl||(g.billingApiUrl=n),b.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),b.walletPresentation===void 0&&(g.walletPresentation=i),b.paymentMethodLayout===void 0&&l!==void 0&&(g.paymentMethodLayout=l),b.moreOptionsLabel===void 0&&u!==void 0&&(g.moreOptionsLabel=u),o?.customer&&(b.email||(g.email=o.customer.email),b.userId||(g.userId=o.customer.id),b.firstName||(g.firstName=o.customer.firstName),b.lastName||(g.lastName=o.customer.lastName)),Object.keys(g).length===0?I:Ui.cloneElement(I,g)})})}function Qm({onButtonClick:e,paymentMethodLayout:t,showPayPal:n,showStripe:o=!0,showApplePay:a,showGooglePay:i,theme:l,buttonsTheme:u,buttonsStyles:m,cardButtonContent:I,cardBackButtonContent:b,cardTitleContent:g}){let[A,Y]=Jt(!1),te=mr(()=>iu(l),[l]),x=mr(()=>{let k=te?.buttonsLayout??jm(u);return m?{...k,...m,cardButton:{...k.cardButton,...m.cardButton},cardFormContainer:{...k.cardFormContainer,...m.cardFormContainer},backButton:{...k.backButton,...m.backButton},backButtonIcon:{...k.backButtonIcon,...m.backButtonIcon},submitButton:{...k.submitButton,...m.submitButton},title:{...k.title,...m.title}}:k},[te,u,m]),D=te?.buttonsLayout?.cardButton?.borderRadius??te?.appearance.variables?.borderRadius??8,C=k=>le("div",{style:{height:k,borderRadius:D,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),ne=I===void 0?{boxSizing:"border-box",height:xo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(A){let k=x.cardInputBorder??"#e5e7eb",je=x.cardInputBackground??"white",G=Vo(b),Ue=Vo(g);return Pn("div",{style:{backgroundColor:x.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...x.cardFormContainer},children:[Pn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Pn("button",{type:"button",onClick:()=>Y(!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",...x.backButton},children:[le("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...x.backButtonIcon},children:le("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:le("path",{d:"M15 18l-6-6 6-6"})})}),le(Yo,{content:b})]}),Ue?le("div",{style:{flex:1}}):le("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...x.title},children:le(Ia,{content:g})})]}),le("div",{style:{backgroundColor:je,border:`1px solid ${k}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:le("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:[le("div",{style:{flex:1,backgroundColor:je,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${k}`,borderLeft:`1px solid ${k}`,borderBottomLeftRadius:8,padding:12,height:45},children:le("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),le("div",{style:{flex:1,backgroundColor:je,borderTop:"none",borderRight:`1px solid ${k}`,borderBottom:`1px solid ${k}`,borderLeft:`1px solid ${k}`,borderBottomRightRadius:8,padding:12,height:45},children:le("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),le("div",{style:{backgroundColor:je,border:`1px solid ${k}`,borderRadius:8,marginTop:8,padding:12,height:45},children:le("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),le("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...x.submitButton,opacity:.5}}),le("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:gs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Ce.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Ce.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Ce.backButtonIcon},children:u("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:u("path",{d:"M15 18l-6-6 6-6"})})}),u(Yo,{content:te})]}),Yl?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Ce.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...Ce.title},children:u(Ea,{content:ce})})]}),!ha&&!Yl&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:hs,order:Pe?-3:0,...Ce.title},children:u(Ea,{content:ce})}),Pe&&wt&&u("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:[u("div",{style:{backgroundColor:$o,border:`1px solid ${ur(ri)}`,borderRadius:an,padding:"10px"},children:u("input",{ref:oe,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"),A.current=r.target.value,Un(r.target.value)},onPointerDown:()=>qt("email"),onKeyDown:()=>qt("email"),onBlur:()=>{Jn("email")&&xr(!0),Lo||Xi()},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",...Ps}})}),ri&&u("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Ca,children:Vi.empty?"Email address is required":"Enter a valid email address"})]}),v&&u("div",{style:{order:Pe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=Re,h=(D=!1)=>({backgroundColor:$o,border:`1px solid ${ur(D)}`,borderRadius:an,marginTop:"0.5rem",padding:"10px"}),T=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ps}),Q=Wy(r);return Ne(Kn,{children:[nn(v.address_line_1,r)&&Ne(Kn,{children:[u("div",{style:h(tn("line1")),children:u("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:D=>{qt("line1"),We.current.addressLine1=!0,zt.current=D.target.value,gr(D.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:T()})}),tn("line1")&&u("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Ca,children:"Street address is required"})]}),nn(v.address_line_2,r)&&u("div",{style:h(),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:En,onChange:D=>{We.current.addressLine2=!0,Dn.current=D.target.value,_r(D.target.value)},disabled:on,"data-testid":"flopay-address-line2",style:T()})}),(nn(v.city,r)||nn(v.state,r))&&Ne("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[nn(v.city,r)&&u("div",{style:{flex:1,backgroundColor:$o,borderTop:`1px solid ${ur(tn("city"))}`,borderRight:`1px solid ${ur(tn("city"))}`,borderBottom:`1px solid ${ur(tn("city"))}`,borderLeft:`1px solid ${ur(tn("city"))}`,padding:"10px",borderTopLeftRadius:an,borderBottomLeftRadius:an,...nn(v.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:an}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:hr,onChange:D=>{qt("city"),We.current.city=!0,Cn.current=D.target.value,In(D.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:T()})}),nn(v.state,r)&&u("div",{style:{flex:1,backgroundColor:$o,borderTop:`1px solid ${ur(tn("state"))}`,borderRight:`1px solid ${ur(tn("state"))}`,borderBottom:`1px solid ${ur(tn("state"))}`,borderLeft:`1px solid ${ur(tn("state"))}`,padding:"10px",borderTopRightRadius:an,borderBottomRightRadius:an,...nn(v.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${ur(tn("state")||tn("city"))}`}:{borderRadius:an}},children:Q?Ne("select",{id:"flopay-billing-state",name:"billing-state",value:mn,onChange:D=>{qt("state"),We.current.state=!0,Tn.current=D.target.value,_n(D.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:{...T(),cursor:"pointer"},children:[u("option",{value:"",children:$s(r)}),Q.map(D=>u("option",{value:D.code,children:D.name},D.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:$s(r),autoComplete:"billing address-level1",value:mn,onChange:D=>{qt("state"),We.current.state=!0,Tn.current=D.target.value,_n(D.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:T()})})]}),tn("city")&&u("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Ca,children:"City is required"}),tn("state")&&Ne("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Ca,children:[$s(r)," is required"]}),(nn(v.country,r)||nn(v.postal_code,r))&&Ne("div",{style:{display:"flex",flexDirection:Me==="column"?"column":"row",gap:Me==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[nn(v.country,r)&&u("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(v.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:an,borderBottomLeftRadius:an,borderRight:"none"}:{borderRadius:an}},children:Ne("select",{id:"flopay-billing-country",name:"billing-country",value:Re,onChange:D=>{We.current.country=!0,Ut.current=D.target.value,tr(D.target.value),_e?.(D.target.value),Tn.current="",_n("")},disabled:on,autoComplete:"billing country","data-testid":"flopay-country",style:{...T(),cursor:"pointer"},children:[Re===""?u("option",{value:"",children:"Select country"}):null,By.map(D=>Ne("option",{value:D.code,children:[D.flag," ",D.name]},D.code))]})}),nn(v.postal_code,r)&&u("div",{style:{flex:Me==="row"?1:void 0,backgroundColor:$o,border:`1px solid ${Dd}`,padding:"10px",...Me==="row"&&nn(v.country,r)?{borderRadius:"0",borderTopRightRadius:an,borderBottomRightRadius:an}:{borderRadius:an}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Xs(Re),autoComplete:"billing postal-code",value:Rt,onChange:D=>{qt("zip"),We.current.zip=!0,fn.current=D.target.value,Bn(D.target.value),st?.(D.target.value)},onPointerDown:()=>qt("zip"),onKeyDown:()=>qt("zip"),onBlur:()=>{Jn("zip")&&Fr(!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:T()})})]}),oi&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Ca,children:An.empty?`${Xs(r)} is required`:xm(r)})]})})()}),Pe&&zd,Yt&&u(oa,{margin:"0.75rem 0",styleOverride:Ce.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"},Ql=r=>W?!ee||!Lr?u("pre",{"data-testid":r,style:ai,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":r,style:ai,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ee}`,` directPaypalConfigured=${Lr}`,` inAppBrowserDetected=${String(ei)}`,` shouldRenderDirectPayPal=${So}`,` shouldRenderStripePayPal=${Ro}`,` hasPaypalStripeInstance=${!!Pl}`].join(`
|
|
13
|
+
`)}):null,ec=r=>W?!k||!or?u("pre",{"data-testid":r,style:ai,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":r,style:ai,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${k}`,` currency=${ct}`,` amountInCents=${ya}`,` enabledPaymentMethods: ${JSON.stringify(J??[])}`,` enabledPaymentMethodsProvided=${ma}`,` hasEnabledMethods=${Ja}`,` expressMethods: ${JSON.stringify(Za)}`,` walletExpressMethods: ${JSON.stringify(jo)}`,` paymentElementMethods: ${JSON.stringify(os)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Qa)}`,` hasStripeInstance=${!!or}`,` shouldRenderWallets=${ao}`,` shouldRenderPaymentElement=${wo}`].join(`
|
|
14
|
+
`)}):null,tc=xe==="apm-expanding"||xe==="apm-form"||xe==="apm-collapsing",Ko;xe==="apm-expanding"?Ko=Au:xe==="apm-collapsing"&&(Ko=Fu);let ii=$t?Hu(as,$t,Ft):null,nc={label:Dt||hu,open:Hn,onOpen:Dr,color:io,fontFamily:Wn?.fontFamily};if(ke==="buttons"){let r=xe==="buttons"||xe==="expanding"||xe==="apm-expanding",h=xe==="expanding"||xe==="card"||xe==="collapsing",T=Ee===void 0?{boxSizing:"border-box",height:Io,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Q;xe==="expanding"||xe==="apm-expanding"?Q=Tm:(xe==="collapsing"||xe==="apm-collapsing")&&(Q=_m);let D;xe==="expanding"?D=Au:xe==="collapsing"&&(D=Fu);let pe=mt&&ku(mt,{canHide:()=>!0,available:ql}),It={paypal:Ne(Kn,{children:[So&&Qe&&Ne(Kn,{children:[fe&&u("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."}),u(Aa.Provider,{value:N,children:u(bi,{sessionId:e,nonce:t,billingApiUrl:yt,email:ft.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,clientId:Qe.clientId,environment:Qe.environment,currency:ct.toUpperCase(),isSubscription:et,providerObjectType:xn,approvalPresentation:ti==="popup"?void 0:ti,onTokenizedBody:Qn,onComplete:l,onErrorChange:ge,onDecline:y,onCancel:w,onTechnicalFailure:zo,onButtonClick:$e,runBeforeButtonClick:Sr,isProcessing:on,onLoadStateChange:cs,onInitializationStateChange:us,session:At,existingOrderId:fe?.orderId,debug:W},fe?.orderId??"fresh")})]}),Ro&&u(uo,{stripe:fa,options:bl,children:u(Bu,{sessionId:e,nonce:t,email:ft.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:yt,onTokenizedBody:Qn,onErrorChange:ge,isProcessing:on,onButtonClick:$e,onDecline:y,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:xl,placeholderBorderRadius:Yr,popupCapabilityOwner:N,externalTelemetryContext:Ul,presentationMode:qo})})]}),wallets:Ne(Kn,{children:[ao?u(uo,{stripe:or,options:vl,children:u(Du,{sessionId:e,nonce:t,email:ft.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:yt,intentKind:Tt>0?"payment":"setup",expressMethods:jo,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:$e,onDecline:y,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Bl,placeholderBorderRadius:Yr,popupCapabilityOwner:N,externalTelemetryContext:pt})}):null,!ao&&Nl?u("div",{style:{height:Io,borderRadius:Yr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:u(Kn,{children:wo&&u(Ou,{sessionId:e,nonce:t,email:ft.email,billingName:[ft.firstName,ft.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Gt,billingApiUrl:yt,paymentElementMethods:Qa,stripeInstance:or,paymentElementBaseOptions:as,futureUseSession:Ft,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:$e,onDecline:y,runBeforeButtonClick:Sr,onLoadStateChange:Dl,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:Ce.submitButton,onExpandApm:Z,expandedApmMethod:$t,themeId:be,buttonAppearance:{backgroundColor:Ce.cardButton?.backgroundColor,borderColor:Ce.cardInputBorder,textColor:Ce.cardButton?.color,borderRadius:Yr}})}),card:u(Kn,{children:Pe&&u("button",{type:"button",onClick:async()=>{on||!(await Sr("card")).proceed||($e?.("card"),V())},disabled:on,style:{width:"100%",...T,...Ce.cardButton,...al({themeBundle:Zn,resolvedPrimaryColor:io,resolvedBorderRadius:an,submitButtonStyle:Ce.submitButton,explicitPrimaryColor:Wn?.colorPrimary}),fontSize:Ce.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:_t=>{!on&&(Zn||Wn?.colorPrimary)&&(_t.currentTarget.style.backgroundColor=Nd)},onMouseLeave:_t=>{(Zn||Wn?.colorPrimary)&&(_t.currentTarget.style.backgroundColor=io)},onMouseDown:_t=>{_t.currentTarget.style.transform="scale(0.985)"},onMouseUp:_t=>{_t.currentTarget.style.transform="scale(1)"},children:u(Go,{content:Ee})})})};return Ne("form",{onSubmit:ys,className:X,noValidate:!0,style:{position:"relative"},children:[u(di,{}),q&&u(Ur,{status:q,errorMessage:Yt,authorized:Et}),Ne("div",{style:{display:"grid"},children:[Ne("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!Q?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!Q?Am:{},...Q?{animation:Q,pointerEvents:"none"}:{}},children:[Ql("flopay-direct-paypal-gate-debug"),ec("flopay-stripe-gate-debug"),rn&&pe?Ne(Kn,{children:[rn.filter(({group:_t})=>pe.inView.includes(_t)).map(({group:_t,key:Le})=>u(ja.Fragment,{children:It[_t]},Le)),pe.behindLink.length>0&&u(qs,{...nc,showLink:pe.showLink,children:rn.filter(({group:_t})=>pe.behindLink.includes(_t)).map(({group:_t,key:Le})=>u(ja.Fragment,{children:It[_t]},Le))})]}):u(js,{rows:zl,borderRadius:Yr}),Yt&&xe==="buttons"&&u(oa,{margin:"0.25rem 0",styleOverride:Ce.errorBanner,children:Yt})]}),Pe&&h&&u("div",{style:{gridArea:"1 / 1",...D?{animation:D}:{},...xe==="collapsing"?{pointerEvents:"none"}:{}},children:bs}),k&&tc&&$t&&ii&&or&&u("div",{style:{gridArea:"1 / 1",...Ko?{animation:Ko}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ne("div",{style:{backgroundColor:fs,borderRadius:vs,...va,padding:Cs},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:gs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Ce.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Ce.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Ce.backButtonIcon},children:u("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:u("path",{d:"M15 18l-6-6 6-6"})})}),u(Yo,{content:te})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Ce.titleFontSize??"1.05rem",color:hs,paddingRight:80,...Ce.title},children:`Pay with ${Wa($t)}`})]}),u(uo,{stripe:or,options:ii,children:u(el,{method:$t,sessionId:e,nonce:t,email:ft.email,billingName:[ft.firstName,ft.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Gt,billingApiUrl:yt,onTokenizedBody:Qn,onErrorChange:ge,onDecline:y,onCancel:de,runBeforeButtonClick:Sr,onButtonClick:$e,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:Ce.submitButton,errorText:Yt})},$t)]})})]})]})}if(tc&&$t&&ii&&or&&k)return Ne("form",{onSubmit:ys,className:X,noValidate:!0,style:{position:"relative"},children:[u(di,{}),q&&u(Ur,{status:q,errorMessage:Yt,authorized:Et}),u("div",{style:{...Ko?{animation:Ko}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ne("div",{style:{backgroundColor:fs,borderRadius:vs,...va,padding:Cs},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:gs?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Ce.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Ce.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Ce.backButtonIcon},children:u("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:u("path",{d:"M15 18l-6-6 6-6"})})}),u(Yo,{content:te})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Ce.titleFontSize??"1.05rem",color:hs,paddingRight:80,...Ce.title},children:`Pay with ${Wa($t)}`})]}),u(uo,{stripe:or,options:ii,children:u(el,{method:$t,sessionId:e,nonce:t,email:ft.email,billingName:[ft.firstName,ft.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Gt,billingApiUrl:yt,onTokenizedBody:Qn,onErrorChange:ge,onDecline:y,onCancel:de,runBeforeButtonClick:Sr,onButtonClick:$e,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:Ce.submitButton,errorText:Yt})},$t)]})})]});let rc=Md||Td||Ad,ba=mt&&ku(mt,{canHide:r=>r!=="card",available:ql}),oc={paypal:Ne(Kn,{children:[So&&Qe&&Ne(Kn,{children:[fe&&u("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."}),u(Aa.Provider,{value:N,children:u(bi,{sessionId:e,nonce:t,billingApiUrl:yt,email:ft.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,clientId:Qe.clientId,environment:Qe.environment,currency:ct.toUpperCase(),isSubscription:et,providerObjectType:xn,approvalPresentation:ti==="popup"?void 0:ti,onTokenizedBody:Qn,onComplete:l,onErrorChange:ge,onDecline:y,onCancel:w,onTechnicalFailure:zo,onButtonClick:$e,runBeforeButtonClick:Sr,isProcessing:on,onLoadStateChange:cs,onInitializationStateChange:us,session:At,existingOrderId:fe?.orderId,debug:W},fe?.orderId??"fresh")})]}),Ro&&u(uo,{stripe:fa,options:bl,children:u(Bu,{sessionId:e,nonce:t,email:ft.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:yt,onTokenizedBody:Qn,onErrorChange:ge,isProcessing:on,onButtonClick:$e,onDecline:y,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:xl,placeholderBorderRadius:Yr,popupCapabilityOwner:N,externalTelemetryContext:Ul,presentationMode:qo})})]}),wallets:u(Kn,{children:ao&&u(uo,{stripe:or,options:vl,children:u(Du,{sessionId:e,nonce:t,email:ft.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:yt,intentKind:Tt>0?"payment":"setup",expressMethods:jo,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:$e,onDecline:y,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Bl,placeholderBorderRadius:Yr,popupCapabilityOwner:N,externalTelemetryContext:pt})})}),apms:u(Kn,{children:wo&&u(Ou,{sessionId:e,nonce:t,email:ft.email,billingName:[ft.firstName,ft.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:yt,paymentElementMethods:Qa,stripeInstance:or,paymentElementBaseOptions:as,futureUseSession:Ft,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:$e,onDecline:y,runBeforeButtonClick:Sr,onLoadStateChange:Dl,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:Ce.submitButton,themeId:be,onExpandApm:Z,expandedApmMethod:$t,buttonAppearance:{backgroundColor:Ce.cardButton?.backgroundColor,borderColor:Ce.cardInputBorder,textColor:Ce.cardButton?.color,borderRadius:Yr}})})};return Ne("form",{onSubmit:ys,className:X,noValidate:!0,style:{position:"relative"},children:[u(di,{}),q&&u(Ur,{status:q,errorMessage:Yt,authorized:Et}),rn===null?u(js,{rows:zl,borderRadius:Yr}):Ne(Kn,{children:[yn&&Pe&&bs,yn&&Pe&&rc&&u(Rs,{label:"or pay another way"}),Ne("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ql("flopay-direct-paypal-gate-debug-default"),ec("flopay-stripe-gate-debug-default"),rn.map(({group:r,key:h})=>r==="card"||!ba?.inView.includes(r)?null:u(ja.Fragment,{children:oc[r]},h)),ba&&ba.behindLink.length>0&&u(qs,{...nc,showLink:ba.showLink,children:rn.map(({group:r,key:h})=>ba.behindLink.includes(r)&&r!=="card"?u(ja.Fragment,{children:oc[r]},h):null)})]}),!yn&&Pe&&rc&&u(Rs,{label:"or pay with card"}),!yn&&Pe&&bs]})]})}import{Fragment as jr,jsx as le,jsxs as Pn}from"react/jsx-runtime";var Fo=44,dl="flopay_checkout_saved_payment_resume",Qm="paypal_resume_nonce_missing",qi=new Map,Li=new Map;function Qu(e,t){t.settled&&t.consumers===0&&qi.get(e)===t&&qi.delete(e)}function ef(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=Ci({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ud,enabled:t!==!1});return o.beginCheckout(n),o}function Va(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function sl(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 ed(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 td(e,t,n,o,a){let i=sd(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 wn&&t.code==="session_auto_completed"?!1:t instanceof wn&&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 ll(e){return!e||e.data.stripe?.publishableKey?!1:!!ld(e.data.paypal)?.clientId}var tf={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function nd(e){return new jm(tf,{publishableKey:"provider_unavailable",...e})}async function Ni(e,t){let{publishableKey:n,paypalPublishableKey:o}=Us(e);return{...await zs({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function rd(e){let t=e.data.stripe;return JSON.stringify([t?.publishableKey??null,t?.paypalPublishableKey??null])}function pl(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function nf(){if(!pl())return null;try{let e=window.sessionStorage.getItem(dl);return e?JSON.parse(e):null}catch{return null}}function od(e){if(pl())try{window.sessionStorage.setItem(dl,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function cl(){if(pl())try{window.sessionStorage.removeItem(dl)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function rf(){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 ad(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 ul(e,t){return Xm(!!e,t)}function of(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function id(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function af(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 yl({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:l,loading:d,error:y,onComplete:w,onError:P,onInstrument:g,onDecline:_,onCancel:O,onCountryChange:X,onZipChange:F,showPayPal:I=!0,showStripe:f=!0,walletPresentation:$="auto",enabledPaymentMethods:ee,showApplePay:k=!0,showGooglePay:je=!0,debug:J=!1,layout:Ue,paymentMethodLayout:rt,moreOptionsLabel:dt,theme:ke,buttonsTheme:Nt,buttonsStyles:Dt,cardButtonContent:be,cardBackButtonContent:He,cardTitleContent:ot,showSecurityFooter:at,onButtonClick:Ee,onBeforeButtonClick:te,enableAVS:ce,cardFieldOrder:Kt,showCardBrandIcons:$e,showCardFieldLabels:it,cardFieldLabels:ne,cardFieldPlaceholders:Te,cardAutoFocus:Xe,onCardFieldsReady:G,onCardFieldsFailed:Pt,cardFieldsTimeoutMs:ve,cardPreFormSlot:Ve,avsLayout:ze,submitLabel:Ze,className:Ct,initialErrorMessage:De=null,initialPayPalOrderId:wt,children:Me,checkoutMode:Ie,confirmLabel:vt,renderConfirmButton:Ot,onSessionCompleted:kt}){let Y=Ym(o),ue=mr(()=>cd(ke),[ke]),_e=i??ue?.appearance,st=n?"embedded_checkout":"standard_checkout",lt=ul(Me,Ue),[Ke,bt]=Jt(null),Tt=Bt(null),ct=pn(b=>{Tt.current=b,bt(b)},[]),[Ae,Qe]=Jt(null),et=Bt(null),j=Bt(null),Ht=Bt(0),[E,W]=Jt(null),K=Bt(null),[m,ie]=Jt(null),C=mr(()=>n?Ba(n):"",[n]),H=n?`create:${C}`:`session:${e??""}`,N=id(m),he=Bt(new Set),Se=Bt(H),M=Bt(H);Ra(()=>{M.current=H,Se.current!==H&&(Se.current=H,he.current.clear())},[H]);let pt=pn(b=>{if(M.current===H){if(jc.has(b.name)){if(he.current.has(b.name))return;he.current.add(b.name)}ut(()=>g?.(b))}},[H,g]),At=na(pt,H),Ft=Bt(!1),xn=pn(b=>{if(Ft.current)return;let s=b.gateway||!N?b:{...b,gateway:N};pt(s)},[pt,N]);ir(()=>{At({class:"lifecycle",name:"checkout.mount"})},[At]);let[Ge,fr]=Jt(e??""),St=e??Ge,Ir=n?"":St,[yt,mt]=Jt(!0),[kn,Hn]=Jt(null),[Vn,rn]=Jt(0),[yn,Xt]=Jt("full"),[Zt,Nn]=Jt(!1),[Fe,Re]=Jt(De),[tr,Rt]=Jt(null),[Bn,Qt]=Jt(null),[gr,En]=Jt(!1),[_r,hr]=Jt(void 0),[In,mn]=Jt(""),[_n,Pr]=Jt(!1),[Un,zn]=Jt(!1),[qn,fn]=Jt(!1),Ut=Bt(null),zt=Bt(0),Dn=Bt(void 0),[Cn,Tn]=Jt("loading"),[A,We]=Jt(0),v=Bt(!1),se=Bt(!1),Et=Bt(!1),xt=Bt(null),Vt=Bt({active:!0});ir(()=>{let b={active:!0};return Vt.current=b,()=>{b.active=!1}},[]);let ye=Bt(null),en=mr(()=>({checkoutMode:Ie??yn,layout:of(Me,Ue)}),[Ie,Me,yn,Ue]),Wr=Bt(w);Wr.current=w;let Mn=Bt(P);Mn.current=P;let Pe=Bt(_);Pe.current=_;let Tr=pn(b=>Ei(xt,async s=>{try{return await b(s)}catch(c){throw s.aborted?ia(c):c}}),[]);ir(()=>()=>{xt.current?.abort(),xt.current=null},[]);let vn=pn((b,s)=>{et.current=b,Qe(b),K.current=s,W(s)},[]),sr=pn(()=>{let b=j.current;b&&(j.current=null,b.destroy())},[]),Po=pn(()=>{let b=et.current,s=K.current;!b&&!s||(vn(null,null),rn(0))},[vn]),Gn=pn(b=>{let s=Tt.current,c=s?Gu(s,b):b;ct(c),c.data.session&&ie(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(b,s,c)=>{let p=null;try{p=await Ni(b,{billingApiUrl:Y,locale:l,telemetry:a})}catch{p=null}if(!s())return;if(sr(),p){Dc([p.flopay?.getRawProvider(),p.paypalFlopay?.getRawProvider()],[et.current?.getRawProvider(),K.current?.getRawProvider()]),vn(p.flopay,p.paypalFlopay),rn(0),Mr({flopay:p.flopay,apply:c});return}let V=nd({billingApiUrl:Y,locale:l,telemetry:a});j.current=V,vn(V,null),rn(1),c()},[sr,vn,l,Y,a]);ir(()=>{hn(Ae)?.setCheckoutContext(en),E&&E!==Ae&&hn(E)?.setCheckoutContext(en)},[Ae,E,en]);let Ar=Bt(kt);Ar.current=kt;let Cr=pn(b=>{Tn(b),!(b!=="exhausted"||Et.current)&&(Et.current=!0,Mn.current?.(new wn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),lr=pn(()=>{Tn("retrying"),We(b=>b+1)},[]);ir(()=>{Tn("loading"),We(0),Et.current=!1},[St]),ir(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ud,checkout_type:st,checkout_layout:lt,billing_api_url:Y})},[lt,st,Y]);let Yn=mr(()=>n?Ba(n,!0):"",[n]),we=mr(()=>In===Yn?_r:void 0,[_r,In,Yn]),An=mr(()=>n?Ts(n,we):void 0,[n,we]),$n=Ie??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(()=>{Re(De)},[De]);let cr=pn((b,s,c)=>{ut(()=>{Pe.current?.(gn(b,s,c))})},[]),rr=pn(async(b,s)=>{let c=Vt.current;if(!c.active)return!1;Re(null),Qt(null),En(!1),Rt("processing");let p=s?.sessionId??b.id,V=b.clientSecret||t,qe=id(b),Z=et.current??K.current,de=hn(Z),q=Z?null:zi(Y,a,en),R={log:z=>{de?de.log(z):q?.log(z)},error:z=>{de?de.error(z):q?.error(z)},terminal:z=>{de?de.terminal(z):q?.terminal(z)},performance:z=>{de?de.performance(z):q?.performance(z)},now:()=>de?.now()??q?.now()??0,elapsed:z=>de?.elapsed(z)??Math.max(0,(q?.now()??z)-z)},oe=R.now(),me=!!(s?.initialAutoProcessingError||s?.initialAutoProcessingPending),S=!1,x,B=()=>{S||(S=!0,me=!0,x=R.now(),R.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),R.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},U=!1,ae=()=>{U||(U=!0,R.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),R.performance({stage:"processing",durationMs:R.elapsed(oe),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),x!==void 0&&R.performance({stage:"recovery",durationMs:R.elapsed(x),durationMode:"machine",paymentMethodCategory:"saved"}))};R.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Ft.current=!0;try{R.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Ft.current=!1}At({class:"lifecycle",name:"payment.processing.started",provider:qe}),me&&B();let Oe;try{let z=du(s?.initialAutoProcessingError),fe=s?.initialAutoProcessingError?.type==="3ds_required"&&!Vm(s.initialAutoProcessingError)&&!s.initialAutoProcessingError.threeDSecureToken&&s.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:s.initialAutoProcessingError.nextActionRedirectUrl}:null,Ye,Sn=jt=>{B();let Lt=Ua(Y,p,b,a!==!1);return Tr(Gt=>sa(jt,{billingApiUrl:Y,sessionId:p,nonce:V,session:b,signal:Gt,...Lt.telemetry?{challengeTelemetry:Lt.telemetry}:{}})).finally(Lt.release)};if(fe)Ye=await Sn(fe);else if(z)B(),z.type==="paypal_redirect_required"&&ye.current?.publishableKey&&od({sessionId:p,publishableKey:ye.current.publishableKey,paypalPublishableKey:ye.current.paypalPublishableKey,nonce:V}),Ye=await Tr(jt=>_i(z,{flopay:et.current,paypalFlopay:K.current,attempt3DS:s?.attempt3DS,billingApiUrl:Y,sessionId:p,session:b,telemetry:!1,signal:jt})),z.type==="paypal_redirect_required"&&cl();else if(s?.initialAutoProcessingPending){let jt=s.initialAutoProcessingPending,Lt=new Oi(Y,{telemetry:!1}),Gt=await Tr(Ce=>Lt.waitForCheckoutSessionCompletion(jt.sessionId,{initialDelayMs:jt.retryAfterMs,nonce:V,statusUrl:jt.statusUrl,signal:Ce})),Yt=co(Gt,b),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"),ad("full")),!1;{let jt=await la({billingApiUrl:Y,sessionId:p,session:b,nonce:V,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):(B(),jt.type==="paypal_redirect_required"&&ye.current?.publishableKey&&od({sessionId:p,publishableKey:ye.current.publishableKey,paypalPublishableKey:ye.current.paypalPublishableKey,nonce:V}),Ye=await Tr(Lt=>_i(jt,{flopay:et.current,paypalFlopay:K.current,attempt3DS:s?.attempt3DS,billingApiUrl:Y,sessionId:p,session:b,telemetry:!1,signal:Lt})),jt.type==="paypal_redirect_required"&&cl())}}if(p&&aa(p),!c.active)return!1;ae(),me&&(R.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),R.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),R.terminal({outcome:Ye.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),En(Ye.status==="authorized"),Rt("success"),await Ha(600),Oe=()=>Wr.current?.(Ye)}catch(z){if(!c.active)return!1;let fe=lo(za(z),p);if(fe.code==="three_ds_aborted")return!1;let Ye=fe.checkoutMethod??Na;Re(fe.message),Qt(fe.message),En(!1),s?.fallbackToFull&&(R.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Xt("full"),ad("full")),ae();let Sn=fe.statusCode===void 0?void 0:Zm(fe.statusCode,"unknown"),jt=Sn==="4xx"?{requestCategory:"process_payment",statusClass:Sn}:{},Lt=Sn===void 0||Sn==="4xx";if(Ju(fe))R.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...jt});else if(Lt&&(fe.telemetryOutcome==="validation_rejected"||fe.type==="validation_error"))R.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...jt});else{let Zn=sd(z,me?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ce=fe.telemetryRequestCategory??"process_payment";Ft.current=!0;try{R.error({...Zn,...fe.telemetryFailureCategory?{failureCategory:fe.telemetryFailureCategory}:{},stage:me?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ce})}finally{Ft.current=!1}At({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ce,provider:qe})}return Yu(fe)?cr(Ye,fe,{code:fe.code,declineCode:fe.declineCode}):ut(()=>Mn.current?.(fe)),Rt("error"),await Promise.allSettled([Ha(400),s?.ensureProvidersReady?s.ensureProvidersReady():Promise.resolve()]),me&&(R.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),R.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{ae(),q&&Va(q),c.active&&(Rt(null),Qt(null))}return c.active?(ut(Oe),!0):!1},[cr,At,t,Y,Tr,a,en]);ir(()=>{if(typeof window>"u"||se.current)return;let b=new URLSearchParams(window.location.search),s=b.get("payment_intent_client_secret");if(!s)return;let c=nf();c&&(se.current=!0,(async()=>{await Promise.resolve();let p,V=0;Re(null),Qt(null),Rt("processing"),Nn(!0);try{if(b.get("redirect_status")==="failed")throw Object.assign(new wn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:qe,paypalFlopay:Z}=await zs({publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey,billingApiUrl:Y,locale:l,telemetry:a});p=hn(Z??qe),p?.setCheckoutContext(en),V=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=(Z??qe)?.getRawProvider();if(!de)throw Object.assign(new wn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:q,error:R}=await de.retrievePaymentIntent(s);if(R)throw Object.assign(new wn(R.message??"Failed to retrieve PayPal payment status.","api_error",{code:R.code}),{checkoutMethod:"paypal"});let oe=_c(q?.status);if(!q||oe==="failed")throw Object.assign(new wn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let me=typeof q.payment_method=="string"?q.payment_method:q.payment_method?.id,S=oe;if(c.sessionId){let x=c.nonce||t;if(!x)throw Object.assign(new wn("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:Qm}),{checkoutMethod:"paypal"});let ae=(await new Oi(Y,{telemetry:!1}).getUnifiedCheckoutSession(c.sessionId,x)).data.session;if(ae&&ae.status!=="complete"){let Oe=await la({billingApiUrl:Y,sessionId:c.sessionId,session:ae,nonce:x,telemetry:!1,tokenizedData:{id:me??q.id,type:"card",threeDSecureActionResultTokenId:q.id,isPaypal:!0}});if(Oe.type!=="success")throw Object.assign(new wn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});S=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(V),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),p?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Rt("success"),await Ha(600),ut(()=>Wr.current?.({status:S,paymentIntentId:q.id,paymentMethodId:me,checkoutMethod:"paypal"}))}catch(qe){let Z=lo(za(qe),c.sessionId),de=Z.checkoutMethod??"paypal",q=Ju(Z);if(p)p.performance({stage:"redirect_resume",durationMs:p.elapsed(V),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),q?p.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):p.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(q){let R=zi(Y,a,en);R.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Va(R)}else sl(Y,a,en,"REDIRECT_RESUME_FAILED","redirect_resume");Re(Z.message),Qt(Z.message),Yu(Z)?cr(de,Z,{code:Z.code,declineCode:Z.declineCode}):ut(()=>Mn.current?.(Z)),Rt("error"),await Ha(400)}finally{cl(),rf(),Rt(null),Qt(null),Nn(!1)}})())},[cr,l,t,Y,a,en]);let Kr=Bt(null),Fr=mr(()=>ln?Ba(ln):"",[ln]),Co=Bt(ln);Co.current=ln,ir(()=>{fr(e??"")},[e]),ir(()=>{v.current=!1,Re(De),Qt(null),En(!1),Rt(null)},[Fr,De,e]);async function xr(b,s,c){let p=zi(Y,a,en),V=new Oi(Y,{telemetry:!1,stripeAccountSwitch:!0}),qe=!1;try{let Z=b.idempotencyKey===void 0?void 0:Xu(b.idempotencyKey),de=tu(s,c),q=eu(s,c);de?.canonicalIdentity===c&&q&&q.canonicalIdentity===void 0&&(Ri(s,c,q.idempotencyKey),q={...q,canonicalIdentity:c});let R=Z??(q?.canonicalIdentity===c?q.idempotencyKey:void 0),oe,me=!1;p.log({name:de?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let S=de?.sid??null,x=null,B,U,ae=!1;if(S)try{x=await V.getUnifiedCheckoutSession(S,de?.nonce),de&&de.canonicalIdentity===void 0&&(Qc(x.data.session,b)?(wi(s,c,S,de.nonce??x.data.session?.clientSecret),q&&q.canonicalIdentity===void 0&&(Ri(s,c,q.idempotencyKey),R??(R=q.idempotencyKey))):(Si(s,c),q=null,R=Z,S=null,x=null));let z=x?.data.session?.status,fe=x?.data.session,Ye=fe?.clientSecret||de?.nonce;if(S&&fe?.buyerIdentified===!1&&Ye&&(U=Xo(V,S,Ye,b.account)),S&&x&&z==="complete"){if(Os(S))return{sid:S,result:x};Si(s,c),S=null,x=null,me=!0}}catch{p.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),de?.canonicalIdentity===void 0?(Si(s,c),R=Z):Ds(s,c),S=null}if(!S){!Z&&(me||!R)&&(R=Xu(),oe=R),R&&Ri(s,c,R);let z=p.now(),fe=0;p.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ye={...b,idempotencyKey:R,avsCheck:!!ce,avsConfig:typeof ce=="object"?ce:void 0,checkoutType:"embedded_checkout",checkoutLayout:ul(Me,Ue)};Object.defineProperty(Ye,$m,{configurable:!1,enumerable:!1,value:{onAttempt:Lt=>{fe=Math.max(fe,Lt)}}});let Sn=()=>{ed(p,"session_create",z,fe)},jt=Lt=>{td(p,Lt,"session_create",z,fe)&&At({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(b.checkoutMode==="confirm"||b.checkoutMode==="auto")&&au();try{if(Hm(Ye)){let Lt=await V.createDetachedSession(Ye);Lt.claimed.catch(()=>{}),x=Lt.shell,S=Lt.sessionId,U=Lt.claim;let Gt=p.now();p.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),B=Lt.claimed.then(Yt=>{let Zn=Yt.data.session?.id??Lt.sessionId;return Zn&&wi(s,c,Zn,Yt.data.session?.clientSecret??Lt.nonce),ed(p,"session_claim",Gt),Sn(),Yt},Yt=>{throw Ds(s,c),td(p,Yt,"session_claim",Gt,0)&&At({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Yt}).finally(()=>Va(p)),B.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()-z,durationMode:"machine",requestCategory:"session_create",attempt:fe,statusClass:"2xx",paymentMethodCategory:"card"})}else x=await V.createAndFetchSession(Ye),Sn()}catch(Lt){throw jt(Lt),Lt}S=x.data.session?.id??S??"",S&&!B&&wi(s,c,S,x.data.session?.clientSecret)}let Oe=x?.data.session;return!U&&S&&Oe?.buyerIdentified===!1&&Oe.clientSecret&&(U=Xo(V,S,Oe.clientSecret,b.account)),{sid:S??"",result:x,sdkGeneratedIdempotencyKey:oe,...B?{claimed:B}:{},...U?{claim:U}:{},...ae?{claimRequiresIdentity:!0}:{}}}finally{qe||Va(p)}}let vo=Bt(xr);Ra(()=>{vo.current=xr},[xr]);let Hr=pn(async(b,s)=>{let c=Co.current;if(!c)throw new wn("createSession is required to bootstrap checkout.","validation_error");let p=Ts(c,b),V=Ba(p),qe=Zc(p),Z=qi.get(V);if(!Z){let R={canonicalIdentity:V,promise:vo.current(p,qe,V),consumers:0,settled:!1};Z=R,qi.set(V,R);let oe=()=>{R.settled=!0,Qu(V,R)};R.promise.then(oe,oe)}Z.consumers+=1;let de=!1,q=()=>{de||(de=!0,Z.consumers-=1,Qu(V,Z))};s?.(q);try{let R=await Z.promise;Kr.current=V,b&&(mn(Yn),hr(Oe=>Sc(Oe,b)));let{sid:oe,result:me,claimed:S,claim:x,claimRequiresIdentity:B}=R;Dn.current=x,fn(B===!0),ct(me),me.data.session&&ie(me.data.session),oe&&fr(oe);let U=()=>{},ae=new Promise(Oe=>{U=Oe});if(S){zt.current+=1;let Oe=zt.current,z=()=>zt.current===Oe;Ut.current=S,zn(!0);let fe=Ye=>{z()&&(Ut.current===S&&(Ut.current=null),Gn(Ye),zn(!1),fn(!1))};S.then(async Ye=>{if(!z())return;let Sn=Gu(Tt.current??me,Ye);if(!Sn.data.stripe?.publishableKey||rd(Sn)===rd(me)){fe(Ye);return}await ae,z()&&await jn(Sn,z,()=>fe(Ye))},Ye=>{zt.current===Oe&&(Ut.current===S&&(Ut.current=null),zn(!1),fn(!1),Hn(Ye instanceof wn?Ye:new wn(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:z}=await Ni(me,{billingApiUrl:Y,locale:l,telemetry:a}).catch(Ye=>{throw kc(Ye,oe||me.data.session?.id)}),fe=Tt.current;S&&fe!==me&&!fe?.data.stripe?.publishableKey?vn(null,null):vn(Oe,z)}finally{U()}return mt(!1),R}catch(R){throw Kr.current===V&&(Kr.current=null),R}finally{s||q()}},[Gn,Yn,vn,l,Y,ct,jn,a]),vr=Bt(rr);vr.current=rr;let eo=Bt(Hr);eo.current=Hr;let to=pn(async b=>{if(!af(b)||_n)return{sessionId:Ge,session:m};Pr(!0);try{let s=await Hr(b);return{sessionId:s.sid,session:s.result.data.session??null}}finally{Pr(!1)}},[Hr,_n,Ge,m]),qt=pn(async b=>{let s=Dn.current;if(!s)return;let c=zt.current,p=await s(b);zt.current===c&&Gn(p)},[Gn]),Jn=pn(async()=>{await Ut.current},[]),Vr=pn(async()=>(await Jn(),{proceed:!0}),[Jn]);ir(()=>{let b=!1,s,c=++Ht.current;sr(),Hn(null),rn(0);let p=()=>{b=!0,Ht.current===c&&(Ht.current+=1,sr())},V=Co.current;if(Fr&&V)return Xt($n),mt(!1),Kr.current===Fr?p:(ie(Rc(V,Ie)),(async()=>{let de=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),q=$n==="auto"&&!v.current&&!de;q&&(Re(null),Qt(null),Rt("processing"));let R=!1;try{let oe=await eo.current(void 0,B=>{s=B});R=!0;let me=oe.result.data.session??null;ye.current=Us(oe.result);let S=ll(oe.result),x=Os(oe.sid||me?.id);if(!b&&q&&me&&!S&&!x){v.current=!0,await ef(Fr,oe.sdkGeneratedIdempotencyKey,()=>vr.current(me,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:oe.result.autoProcessingError,initialAutoProcessingPending:oe.result.autoProcessingPending,autoProcessingAttempted:oe.result.autoProcessingAttempted,sessionId:oe.sid||me.id}));return}!b&&q&&((S||x)&&(v.current=!0),Rt(null),Qt(null))}catch(oe){if(b)return;let me=yi(oe);if(q&&me==="session_auto_completed"){v.current=!0,Rt("success"),await Ha(600),b||(ut(()=>{Wr.current?.({status:"succeeded"})}),Rt(null),Qt(null));return}if(q&&(Rt(null),Qt(null)),!R){let x=Ec(oe),B=Zu(oe,x?{stage:"provider_load",provider:"stripe",...x}:{stage:"session_request"});(x||!(oe instanceof wn))&&ut(()=>Mn.current?.(B)),Hn(B);return}let S=oe instanceof wn?oe:new wn(oe instanceof Error?oe.message:"Failed to create session","api_error");Hn(S)}finally{s?.(),s=void 0}})(),()=>{p(),s?.()});mt(!0);async function qe(){let de=!1,q=!1,R=null;try{let oe=new Oi(Y,{telemetry:!1}),me=await oe.getUnifiedCheckoutSession(St,t);if(q=!0,R=me,b)return;ct(me);let S=me.data.session??null;if(ie(S),!S)throw new wn("No session data returned","api_error");let x=S.checkoutMode;if(x==="setup")throw new wn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(S.status==="authorized"){mt(!1),ut(()=>{Wr.current?.(Jr(S,St)),Ar.current?.(S.successUrl??"")});return}if(S.status==="complete"){mt(!1),ut(()=>{Ar.current?.(S.successUrl??"")});return}if(S.status==="expired")throw pi(S);de=!0;let B=Ie??x??"full";Xt(B),zt.current+=1;let U=S.clientSecret||t;Dn.current=S.buyerIdentified===!1&&U?Xo(oe,St,U,{...S.customer?.id?{userId:S.customer.id}:{}}):void 0,zn(!1),fn(!1);let ae=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Oe=ll(me);if(B==="auto"&&!v.current&&!ae&&!Oe){v.current=!0;let z=Z(me);try{if(await vr.current(S,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>z,sessionId:St||S.id}),b)return;await z,b||mt(!1);return}catch{if(b)return;await z,b||mt(!1);return}}await Z(me),b||mt(!1)}catch(oe){if(b)return;let me=bc(oe,de);if(de&&At({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),me){let{errorCode:U,stage:ae,...Oe}=me;sl(Y,a,en,U,ae,Oe)}if(me?.stage==="provider_load"&&(Ie??R?.data.session?.checkoutMode??"full")==="full"&&vc(R,I,f)){let U=nd({billingApiUrl:Y,locale:l,telemetry:a});j.current=U,vn(U,null),rn(1),mt(!1);return}let S=me?.stage==="provider_load",x="session_request";S?x="provider_load":q&&(x="post_session");let B=Zu(oe,{stage:x,provider:"stripe",sessionId:St||void 0});(S||!(oe instanceof wn))&&ut(()=>Mn.current?.(B)),Hn(B),mt(!1)}}async function Z(de){let{flopay:q,paypalFlopay:R,...oe}=await Ni(de,{billingApiUrl:Y,locale:l,telemetry:a});ye.current={publishableKey:oe.publishableKey,paypalPublishableKey:oe.paypalPublishableKey},vn(q,R),rn(0)}return qe(),p},[Ie,Fr,$n,Ir,t,I,f]);let On=pn(async()=>{if(!Ke||Vn!==1)return;let b=Ht.current;rn(2);try{let{flopay:s,paypalFlopay:c}=await Ni(Ke,{billingApiUrl:Y,locale:l,telemetry:a});if(Ht.current!==b)return;sr(),vn(s,c),rn(0)}catch(s){if(Ht.current!==b)return;let{errorCode:c,stage:p,...V}=_s(s);sl(Y,a,en,c,p,V)}},[sr,vn,l,Vn,Y,a,en,Ke]),Xn=!!(St&&(m?.clientSecret||t)),xe=Zt||!Xn,Ln=pn(async()=>{let b=Vt.current;if(!(!b.active||Zt||!Xn||!m)){Nn(!0),Re(null);try{await rr(m,{attempt3DS:!0,fallbackToFull:!0,sessionId:St||m.id})}finally{b.active&&Nn(!1)}}},[St,Zt,Xn,rr,m]),$t=ld(Ke?.data.paypal,wt),Gr=ll(Ke),no=mr(()=>{if(!(!Ke||!m||!Ke.data.stripe?.publishableKey))return{billingApiUrl:Y}},[Ke,m,Y]),bo=!!(n&&!Me&&Ue==="buttons"&&te&&$n==="full"),Br=!!(St&&(Gm(m?.vault)||_o(m))),Dr=mr(()=>({session:m,loading:yt,error:kn,checkoutMode:yn,inlineSessionDraft:ln,applyInlineSessionPatch:bo?to:void 0,inlineSessionPatchProcessing:_n,claimPending:Un,claimRequiresIdentity:qn,claimBuyerIdentity:qt,waitForDataAttachment:Jn}),[m,yt,kn,yn,ln,bo,to,_n,Un,qn,qt,Jn]),bn=!!n&&Ue==="buttons"&&!Gr&&!Br&&(!Ae||!no),cn=tr?le(Ur,{status:tr,errorMessage:Bn,authorized:gr}):null;if(yt&&!Br){if(d)return Pn(jr,{children:[d,cn]});if(Ue==="buttons"){let b=ue?.buttonsLayout?.cardButton?.borderRadius??ue?.appearance.variables?.borderRadius??8,s=c=>le("div",{style:{height:c,borderRadius:b,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:[I&&s(Fo),f&&(k||je)&&s(Fo),f&&s(Fo),le("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:[le("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),le("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),cn]})}return kn?y?le(Rr.Provider,{value:Dr,children:y(kn)}):le(Rr.Provider,{value:Dr,children:le("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:kn.message})}):bn?Pn(jr,{children:[le(Rr.Provider,{value:Dr,children:le(lf,{onButtonClick:Ee,paymentMethodLayout:rt,showPayPal:I,showStripe:f,showApplePay:k,showGooglePay:je,theme:ke,buttonsTheme:Nt,buttonsStyles:Dt,cardButtonContent:be,cardBackButtonContent:He,cardTitleContent:ot})}),cn]}):Gr&&m&&$t?Pn(jr,{children:[le(Rr.Provider,{value:Dr,children:Pn("div",{className:Ct,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Fe&&le(oa,{icon:!1,children:Fe}),Cn==="retrying"&&le("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Cn==="exhausted"&&Pn("div",{role:"alert",children:[le("div",{children:"PayPal is temporarily unavailable. Please try again."}),le("button",{type:"button",onClick:lr,children:"Retry PayPal"})]}),Cn!=="exhausted"&&le("div",{"aria-hidden":Cn==="retrying"?!0:void 0,style:Cn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:le(Jc,{sessionId:St,nonce:m.clientSecret||void 0,billingApiUrl:Y,email:m.customer?.email||ln?.account?.email,billingName:[m.customer?.firstName,m.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:(m.currency??"usd").toUpperCase(),isSubscription:m.mode==="subscription",providerObjectType:$t.providerObjectType,approvalPresentation:$t.approvalPresentation,existingOrderId:$t.existingOrderId,onComplete:w,onErrorChange:Re,onDecline:_,onCancel:O,onButtonClick:Ee,runBeforeButtonClick:Vr,onInitializationStateChange:Cr,allowAutomaticRetry:A===0,session:m,telemetry:a,telemetryContext:en,onInstrument:xn,debug:J},`${H}:paypal-init-${A}`)})]})}),cn]}):yn==="confirm"?Pn(jr,{children:[le(Rr.Provider,{value:Dr,children:le(ki,{flopay:Ae,paypalFlopay:E,options:no??{billingApiUrl:Y},onInstrument:xn,children:Pn("div",{className:Ct,children:[Fe&&le("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Fe}),Ot?Ot({onConfirm:Ln,isProcessing:xe}):le("button",{type:"button",onClick:Ln,disabled:xe,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:xe?"not-allowed":"pointer",opacity:xe?.6:1},children:Zt?"Processing...":vt??"Confirm Purchase"})]})},H)}),cn]}):(!Ae||!no)&&!(Br&&yn==="full")?le(jr,{children:cn}):Pn(jr,{children:[le(Rr.Provider,{value:Dr,children:Pn(ki,{flopay:Ae,paypalFlopay:E,options:no??{billingApiUrl:Y},onInstrument:xn,children:[Vn===1&&le("button",{type:"button",onClick:On,children:"Retry payment methods"}),Me?Pn(jr,{children:[Fe&&le("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Fe}),le(sf,{sessionId:St,nonce:m?.clientSecret||void 0,billingApiUrl:Y,session:m,submitLabel:Ze,walletPresentation:$,paymentMethodLayout:rt,moreOptionsLabel:dt,children:Me})]}):le(il,{sessionId:St,nonce:m?.clientSecret||void 0,telemetry:a,email:m?.customer?.email||ln?.account?.email,userId:m?.customer?.id||ln?.account?.userId,firstName:m?.customer?.firstName||ln?.account?.firstName,lastName:m?.customer?.lastName||ln?.account?.lastName,totalAmount:m?Math.round(Wm(m).total*100):0,currency:m?.currency?.toLowerCase()??"usd",onComplete:w,onError:P,onDecline:_,onCancel:O,error:Fe,onErrorChange:Re,showPayPal:I,showStripe:f,walletPresentation:$,enabledPaymentMethods:Vn?[]:ee??Ke?.data.stripe?.enabledPaymentMethods??m?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:k,showGooglePay:je,layout:Ue,paymentMethodLayout:rt,moreOptionsLabel:dt,theme:ke,buttonsTheme:Nt,buttonsStyles:Dt,appearance:_e,cardButtonContent:be,cardBackButtonContent:He,cardTitleContent:ot,onButtonClick:Ee,onBeforeButtonClick:te,onBuyerIdentityReady:qt,enableAVS:ce,...Kt?{cardFieldOrder:Kt}:{},...$e===void 0?{}:{showCardBrandIcons:$e},...it===void 0?{}:{showCardFieldLabels:it},...ne===void 0?{}:{cardFieldLabels:ne},...Te===void 0?{}:{cardFieldPlaceholders:Te},...Xe===void 0?{}:{cardAutoFocus:Xe},...G?{onCardFieldsReady:G}:{},...Pt?{onCardFieldsFailed:Pt}:{},...ve===void 0?{}:{cardFieldsTimeoutMs:ve},...Ve?{cardPreFormSlot:Ve}:{},avsLayout:ze,country:m?.customer?.country,city:m?.customer?.city,state:m?.customer?.state,onCountryChange:X,onZipChange:F,avsCheck:!!ce,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ul(Me,Ue),className:Ct,submitLabel:Ze,directPaypal:$t,isSubscription:m?.mode==="subscription",session:m,dataAttachmentPending:Un,dataAttachmentRequiresIdentity:qn,debug:J})]},H)}),cn]})}function sf({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,paymentMethodLayout:l,moreOptionsLabel:d,children:y}){return le(jr,{children:Ui.Children.map(y,w=>{if(!Ui.isValidElement(w))return w;let P=w.props,g={};return P.sessionId||(g.sessionId=e),!P.nonce&&t&&(g.nonce=t),P.billingApiUrl||(g.billingApiUrl=n),P.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),P.walletPresentation===void 0&&(g.walletPresentation=i),P.paymentMethodLayout===void 0&&l!==void 0&&(g.paymentMethodLayout=l),P.moreOptionsLabel===void 0&&d!==void 0&&(g.moreOptionsLabel=d),o?.customer&&(P.email||(g.email=o.customer.email),P.userId||(g.userId=o.customer.id),P.firstName||(g.firstName=o.customer.firstName),P.lastName||(g.lastName=o.customer.lastName)),Object.keys(g).length===0?w:Ui.cloneElement(w,g)})})}function lf({onButtonClick:e,paymentMethodLayout:t,showPayPal:n,showStripe:o=!0,showApplePay:a,showGooglePay:i,theme:l,buttonsTheme:d,buttonsStyles:y,cardButtonContent:w,cardBackButtonContent:P,cardTitleContent:g}){let[_,O]=Jt(!1),X=mr(()=>cd(l),[l]),F=mr(()=>{let k=X?.buttonsLayout??Jm(d);return y?{...k,...y,cardButton:{...k.cardButton,...y.cardButton},cardFormContainer:{...k.cardFormContainer,...y.cardFormContainer},backButton:{...k.backButton,...y.backButton},backButtonIcon:{...k.backButtonIcon,...y.backButtonIcon},submitButton:{...k.submitButton,...y.submitButton},title:{...k.title,...y.title}}:k},[X,d,y]),I=X?.buttonsLayout?.cardButton?.borderRadius??X?.appearance.variables?.borderRadius??8,f=k=>le("div",{style:{height:k,borderRadius:I,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),$=w===void 0?{boxSizing:"border-box",height:Fo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(_){let k=F.cardInputBorder??"#e5e7eb",je=F.cardInputBackground??"white",J=Vo(P),Ue=Vo(g);return Pn("div",{style:{backgroundColor:F.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...F.cardFormContainer},children:[Pn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Pn("button",{type:"button",onClick:()=>O(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:J?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...F.backButton},children:[le("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...F.backButtonIcon},children:le("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:le("path",{d:"M15 18l-6-6 6-6"})})}),le(Yo,{content:P})]}),Ue?le("div",{style:{flex:1}}):le("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...F.title},children:le(Ea,{content:g})})]}),le("div",{style:{backgroundColor:je,border:`1px solid ${k}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:le("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:[le("div",{style:{flex:1,backgroundColor:je,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${k}`,borderLeft:`1px solid ${k}`,borderBottomLeftRadius:8,padding:12,height:45},children:le("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),le("div",{style:{flex:1,backgroundColor:je,borderTop:"none",borderRight:`1px solid ${k}`,borderBottom:`1px solid ${k}`,borderLeft:`1px solid ${k}`,borderBottomRightRadius:8,padding:12,height:45},children:le("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),le("div",{style:{backgroundColor:je,border:`1px solid ${k}`,borderRadius:8,marginTop:8,padding:12,height:45},children:le("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),le("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...F.submitButton,opacity:.5}}),le("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 re={paypal:n&&C(xo),wallets:o&&(a||i)&&C(xo),card:o&&(t?C(xo):le("button",{type:"button",onClick:()=>{e?.("card"),Y(!0)},style:{width:"100%",...ne,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:x.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,...x.cardButton},onMouseDown:k=>{k.currentTarget.style.transform="scale(0.985)"},onMouseUp:k=>{k.currentTarget.style.transform="scale(1)"},children:le(Go,{content:I})}))};return Pn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Lm.map(k=>le(Ui.Fragment,{children:re[k]},k)),le("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 yl(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:I,account:b,successUrl:g,cancelUrl:A,couponCodes:Y,tagsData:te,utmMetadata:x,billingApiUrl:D,locale:C,theme:ne,appearance:re,buttonsTheme:k,buttonsStyles:je,onSuccess:G,onError:Ue,onDecline:rt,children:dt,disabled:Re=!1,type:Nt="button",style:Dt,...be}){let He=Ga(()=>tf(D),[D]),ot=Ga(()=>df({createSession:n,clientId:l,products:u,items:m,subscriptions:I,account:b,successUrl:g,cancelUrl:A,couponCodes:Y,tagsData:te,utmMetadata:x}),[b,A,l,Y,n,u,m,I,g,te,x]),[at,Ie]=pa(!1),[Z,ce]=pa(null),[Kt,$e]=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(R=>Ii(Ve,async j=>{try{return await R(j)}catch($){throw j.aborted?ia($):$}}),[]);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 R=j=>{j.key==="Escape"&&ht(null)};return window.addEventListener("keydown",R),()=>{window.removeEventListener("keydown",R)}},[]);let vt=$r((R,j=Na)=>{Me.current?.(gn(j,R,{code:R.code,declineCode:R.declineCode}))},[]),Ot=$r(async R=>{Ce.current&&($e(null),Q(R.result.status==="authorized"),ce("success"),await cu(600),Ce.current&&Ft(()=>De.current?.(R)))},[]),kt=$r(async(R,j)=>{if(!Ce.current)return;!!j?.emitDecline&&ef(R)?vt(R,j?.method):wt.current?.(R),$e(R.message),Q(!1),ce("error"),await cu(400)},[vt]),V=$r(async(R,j,$)=>{let y=R.data.session??null;if(!y)throw lo(new Bo("No session data returned","api_error"),j);let ie=$?.nonce||y.clientSecret||t;if(Xr(y)){await Ot({result:Jr(y,j),session:y,sessionId:y.id||j,autoCompleted:!1});return}if(y.status==="expired")throw lo(pi(y),y.id||j);try{if(R.autoProcessingPending){let W=R.autoProcessingPending,L=new pl(He),he=await Ee(ut=>L.waitForCheckoutSessionCompletion(W.sessionId,{initialDelayMs:W.retryAfterMs,nonce:ie,statusUrl:W.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(_&&j&&ie){let ut=Ua(He,j,y),Mt=await Ee(At=>sa(_,{billingApiUrl:He,sessionId:j,nonce:ie,session:y,signal:At,telemetry:!0,...ut.telemetry?{challengeTelemetry:ut.telemetry}:{}})).finally(ut.release);await Ot({result:Mt,session:y,sessionId:y.id||j,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,j),session:Se,sessionId:Se.id||j,autoCompleted:!1});return}if(R.autoProcessingError){let W=R.autoProcessingError.nextActionRedirectUrl;if(R.autoProcessingError.type==="3ds_required"&&!lu(R.autoProcessingError)&&W&&j&&ie){let L=await Ee(ut=>cd({billingApiUrl:He,sessionId:j,nonce:ie,nextActionRedirectUrl:W,signal:ut}));if(L.status==="declined")throw zr({type:L.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:L.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:R.autoProcessingError.checkoutMethod});let Se=await new pl(He).waitForCheckoutSessionCompletion(j,{initialDelayMs:0,nonce:ie}),_=co(Se,y);if(!Xr(_))throw zr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:R.autoProcessingError.checkoutMethod});await Ot({result:Jr(_,j),session:_,sessionId:_.id||j,autoCompleted:!1});return}throw zr(R.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:R.autoProcessingError.checkoutMethod})}if($?.fromCreateSession&&R.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:j??y.id,session:y,nonce:ie});if(h.type==="next_action_required"&&ie){let W=j??y.id,L=Ua(He,W,y),he=await Ee(Se=>sa(h,{billingApiUrl:He,sessionId:W,nonce:ie,session:y,signal:Se,telemetry:!0,...L.telemetry?{challengeTelemetry:L.telemetry}:{}})).finally(L.release);await Ot({result:he,session:y,sessionId:y.id||W,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||j,autoCompleted:!1})}catch(h){let W=y.id||j,L=lo(za(h),W);if(L.code==="three_ds_aborted")return;if(L.code==="checkout_processing_timeout"){if(!Ce.current)return;Xe(L.message),Ft(()=>wt.current?.(L));return}await kt(L,{emitDecline:!0,method:L.checkoutMethod??Na}),cf(L,W)&&W&&Ce.current&&ht({sessionId:W,errorMessage:L.message,nonce:ie||void 0,payPalOrderId:L.orderId})}},[t,He,Ee,kt,Ot]),de=$r(async R=>{let j=new AbortController;ze.current=j;let $=!1,y=setTimeout(()=>{$=!0,j.abort()},du);try{let ie=await af((async()=>R({signal:j.signal}))(),j.signal);if(!Ce.current)return null;if(!sf(ie))throw yl("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:ie.sessionId,nonce:ie.nonce}}catch(ie){if(!Ce.current)return null;throw ie instanceof Bo&&ie.code==="session_fetch_failed"?ie:$?yl(`getSession did not resolve within ${du/1e3} seconds.`):yl("Could not fetch the one-click session.",ie)}finally{clearTimeout(y),ze.current===j&&(ze.current=null)}},[]),_e=$r(async R=>{if(be.onClick?.(R),R.defaultPrevented||Re||at||(ht(null),Xe(null),Ze.current))return;let j=[e,o,ot].filter(Boolean).length;if(j>1){let $=new Bo("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await kt($),Ce.current&&(ce(null),$e(null));return}if(j===0){let $=new Bo("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await kt($),Ce.current&&(ce(null),$e(null));return}Ze.current=!0,Ie(!0),$e(null),Q(!1),ce("processing");try{let $=new pl(He);if(e){let y=await $.getUnifiedCheckoutSession(e,t);await V(y,e);return}if(o){let y=await de(o);if(!y)return;let ie=await $.getUnifiedCheckoutSession(y.sessionId,y.nonce);await V(ie,y.sessionId,{nonce:y.nonce});return}td();try{let y=await $.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($){await kt(lo(lf($,"Automatic payment failed. Please try again."),e))}finally{Ze.current=!1,Ce.current&&(ce(null),$e(null),Ie(!1))}},[be.onClick,ot,Re,de,o,at,t,V,He,e,kt,Ot]),st=$r(R=>{let j=Pt.current;ht(null),De.current?.({result:R,session:null,sessionId:j?.sessionId??null,autoCompleted:!1})},[]),lt=$r(R=>{wt.current?.(R)},[]),Ke=$r(R=>{Me.current?.(R)},[]),Ct=Ga(()=>rf(ne),[ne]),_t=Ga(()=>{let R=Ct?.buttonsLayout??nf(k);return je?{...R,...je,cardButton:{...R.cardButton,...je.cardButton}}:R},[Ct,k,je]),ct=Ga(()=>{let R=Ct?.appearance;return re?R?{...R,...re,variables:{...R.variables,...re.variables}}:re:R},[re,Ct]),Ae=ct?.variables,Qe=Ae?.colorPrimary??"#4A49FF",et=Ae?.colorPrimaryHover??Wd(Qe,.12),q=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,...rl({themeBundle:Ct,resolvedPrimaryColor:Qe,resolvedBorderRadius:q,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:R=>{be.onMouseEnter?.(R),!R.defaultPrevented&&!Re&&!at&&(Ct||Ae?.colorPrimary)&&(R.currentTarget.style.backgroundColor=et)},onMouseLeave:R=>{be.onMouseLeave?.(R),!R.defaultPrevented&&(Ct||Ae?.colorPrimary)&&(R.currentTarget.style.backgroundColor=Qe)},onMouseDown:R=>{be.onMouseDown?.(R),R.defaultPrevented||(R.currentTarget.style.transform="scale(0.985)")},onMouseUp:R=>{be.onMouseUp?.(R),R.defaultPrevented||(R.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:R=>{R.target===R.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(ul,{sessionId:H.sessionId,nonce:H.nonce,checkoutMode:"full",billingApiUrl:He,locale:C,theme:ne,...ct?{appearance:ct}:{},buttonsTheme:k,buttonsStyles:je,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 ji,useRef as $i}from"react";import{jsx as wf}from"react/jsx-runtime";var Pf="2.2.0",vf="2.3.0";function Cf(e,t){let n={mode:e};return t&&Object.defineProperty(n,"getSession",{enumerable:!0,get:t}),n}function bf(e){return e instanceof uu?e:new uu("The checkout runtime failed to load.","network_error",{code:"runtime_load_failed",cause:e})}function Sf(e){let{publishableKey:t,sessionId:n,nonce:o,appearance:a,strings:i,layout:l,runtimeUrl:u,runtimeTimeoutMs:m}=e,I=e.createSession===void 0?void 0:JSON.stringify(e.createSession),b=e.paymentMethodLayout===void 0?void 0:JSON.stringify(e.paymentMethodLayout),g=e.automaticPayment?.mode,A=e.automaticPayment?.getSession!==void 0,Y=$i(void 0),te=$i(null),x=$i(null),D=$i(e);return D.current=e,ji(()=>{let C=!0;return hf({runtimeUrl:u,timeoutMs:m}).then(ne=>{let re=te.current;if(!C||!re)return;let k=D.current.paymentMethodLayout;Y.current=k===void 0?void 0:JSON.stringify(k),x.current=ne.mount(re,{contractVersion:g?vf:Pf,...g?{automaticPayment:Cf(g,A?()=>D.current.automaticPayment?.getSession:void 0)}:{},publishableKey:t,sessionId:n,nonce:o,createSession:I===void 0?void 0:JSON.parse(I),appearance:D.current.appearance,strings:D.current.strings,paymentMethodLayout:Y.current===void 0?void 0:JSON.parse(Y.current),...l?{layout:l}:{},onEvent:je=>D.current.onEvent?.(je)})},ne=>{C&&D.current.onError?.(bf(ne))}),()=>{C=!1,x.current?.unmount(),x.current=null}},[t,n,o,I,l,g,A,u,m]),ji(()=>{a!==void 0&&x.current?.update({appearance:a})},[a]),ji(()=>{i!==void 0&&x.current?.update({strings:i})},[i]),ji(()=>{if(b===void 0||b===Y.current)return;let C=x.current;C&&(Y.current=b,C.update({paymentMethodLayout:JSON.parse(b)}))},[b]),wf("div",{ref:te,"data-flopay-runtime-checkout":""})}export{bi as DirectPayPalButton,uf as FloPayAutomaticPaymentButton,Bu as FloPayCardSetup,Fu as FloPayCardSetupError,ul as FloPayCheckout,ff as FloPayPaymentMethodSetup,Ri as FloPayProvider,Sf as FloPayRuntimeCheckout,ol as SplitCardForm,Cs as VaultCardFields,kP as dropThirdPartyOnlyError,rp as useCheckout,po as useFloPay,Ms as usePayPalFloPay};
|
|
21
|
+
`})]})}let ee={paypal:n&&f(Fo),wallets:o&&(a||i)&&f(Fo),card:o&&(t?f(Fo):le("button",{type:"button",onClick:()=>{e?.("card"),O(!0)},style:{width:"100%",...$,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:F.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,...F.cardButton},onMouseDown:k=>{k.currentTarget.style.transform="scale(0.985)"},onMouseUp:k=>{k.currentTarget.style.transform="scale(1)"},children:le(Go,{content:w})}))};return Pn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Km.map(k=>le(Ui.Fragment,{children:ee[k]},k)),le("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as vf,jsx as xo,jsxs as bf}from"react/jsx-runtime";var yf=44;function pd(e){return new Promise(t=>setTimeout(t,e))}var yd=15e3;function fl(e,t){return new Bo(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function mf(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 ff(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function gf(e,t){return e instanceof Bo?e:new Bo(e instanceof Error?e.message:t,"api_error")}function hf(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Pf(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 Cf({sessionId:e,nonce:t,createSession:n,getSession:o,paymentMethodId:a,checkoutMethod:i,clientId:l,products:d,items:y,subscriptions:w,account:P,successUrl:g,cancelUrl:_,couponCodes:O,tagsData:X,utmMetadata:F,billingApiUrl:I,locale:f,theme:$,appearance:ee,buttonsTheme:k,buttonsStyles:je,onSuccess:J,onError:Ue,onDecline:rt,children:dt,disabled:ke=!1,type:Nt="button",style:Dt,...be}){let He=Ga(()=>uf(I),[I]),ot=Ga(()=>Pf({createSession:n,clientId:l,products:d,items:y,subscriptions:w,account:P,successUrl:g,cancelUrl:_,couponCodes:O,tagsData:X,utmMetadata:F}),[P,_,l,O,n,d,y,w,g,X,F]),[at,Ee]=pa(!1),[te,ce]=pa(null),[Kt,$e]=pa(null),[it,ne]=pa(!1),[Te,Xe]=pa(null),[G,Pt]=pa(null),ve=ho(!0),Ve=ho(null),ze=ho(null),Ze=ho(!1),Ct=ho(G),De=ho(J),wt=ho(Ue),Me=ho(rt),Ie=$r(E=>Ei(Ve,async W=>{try{return await E(W)}catch(K){throw W.aborted?ia(K):K}}),[]);da(()=>{Ct.current=G},[G]),da(()=>{De.current=J},[J]),da(()=>{wt.current=Ue},[Ue]),da(()=>{Me.current=rt},[rt]),da(()=>(ve.current=!0,()=>{ve.current=!1,Ve.current?.abort(),ze.current?.abort()}),[]),da(()=>{if(typeof window>"u")return;let E=W=>{W.key==="Escape"&&Pt(null)};return window.addEventListener("keydown",E),()=>{window.removeEventListener("keydown",E)}},[]);let vt=$r((E,W=Na)=>{Me.current?.(gn(W,E,{code:E.code,declineCode:E.declineCode}))},[]),Ot=$r(async E=>{ve.current&&($e(null),ne(E.result.status==="authorized"),ce("success"),await pd(600),ve.current&&ut(()=>De.current?.(E)))},[]),kt=$r(async(E,W)=>{if(!ve.current)return;!!W?.emitDecline&&cf(E)?vt(E,W?.method):wt.current?.(E),$e(E.message),ne(!1),ce("error"),await pd(400)},[vt]),Y=$r(async(E,W,K)=>{let m=E.data.session??null;if(!m)throw lo(new Bo("No session data returned","api_error"),W);let ie=K?.nonce||m.clientSecret||t;if(Xr(m)){await Ot({result:Jr(m,W),session:m,sessionId:m.id||W,autoCompleted:!1});return}if(m.status==="expired")throw lo(pi(m),m.id||W);try{if(E.autoProcessingPending){let H=E.autoProcessingPending,N=new ml(He),he=await Ie(pt=>N.waitForCheckoutSessionCompletion(H.sessionId,{initialDelayMs:H.retryAfterMs,nonce:ie,statusUrl:H.statusUrl,signal:pt})),Se=co(he,m),M=he.autoProcessingError?.type==="3ds_required"&&!dd(he.autoProcessingError)&&he.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:he.autoProcessingError.nextActionRedirectUrl}:null;if(M&&W&&ie){let pt=Ua(He,W,m),At=await Ie(Ft=>sa(M,{billingApiUrl:He,sessionId:W,nonce:ie,session:m,signal:Ft,telemetry:!0,...pt.telemetry?{challengeTelemetry:pt.telemetry}:{}})).finally(pt.release);await Ot({result:At,session:m,sessionId:m.id||W,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,W),session:Se,sessionId:Se.id||W,autoCompleted:!1});return}if(E.autoProcessingError){let H=E.autoProcessingError.nextActionRedirectUrl;if(E.autoProcessingError.type==="3ds_required"&&!dd(E.autoProcessingError)&&H&&W&&ie){let N=await Ie(pt=>pu({billingApiUrl:He,sessionId:W,nonce:ie,nextActionRedirectUrl:H,signal:pt}));if(N.status==="declined")throw zr({type:N.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:N.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:E.autoProcessingError.checkoutMethod});let Se=await new ml(He).waitForCheckoutSessionCompletion(W,{initialDelayMs:0,nonce:ie}),M=co(Se,m);if(!Xr(M))throw zr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:E.autoProcessingError.checkoutMethod});await Ot({result:Jr(M,W),session:M,sessionId:M.id||W,autoCompleted:!1});return}throw zr(E.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:E.autoProcessingError.checkoutMethod})}if(K?.fromCreateSession&&E.autoProcessingAttempted===!0)throw zr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let C=await la({billingApiUrl:He,sessionId:W??m.id,session:m,nonce:ie});if(C.type==="next_action_required"&&ie){let H=W??m.id,N=Ua(He,H,m),he=await Ie(Se=>sa(C,{billingApiUrl:He,sessionId:H,nonce:ie,session:m,signal:Se,telemetry:!0,...N.telemetry?{challengeTelemetry:N.telemetry}:{}})).finally(N.release);await Ot({result:he,session:m,sessionId:m.id||H,autoCompleted:!1});return}if(C.type!=="success")throw zr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ot({result:C.result,session:m,sessionId:m.id||W,autoCompleted:!1})}catch(C){let H=m.id||W,N=lo(za(C),H);if(N.code==="three_ds_aborted")return;if(N.code==="checkout_processing_timeout"){if(!ve.current)return;Xe(N.message),ut(()=>wt.current?.(N));return}await kt(N,{emitDecline:!0,method:N.checkoutMethod??Na}),hf(N,H)&&H&&ve.current&&Pt({sessionId:H,errorMessage:N.message,nonce:ie||void 0,payPalOrderId:N.orderId})}},[t,He,Ie,kt,Ot]),ue=$r(async E=>{let W=new AbortController;ze.current=W;let K=!1,m=setTimeout(()=>{K=!0,W.abort()},yd);try{let ie=await mf((async()=>E({signal:W.signal}))(),W.signal);if(!ve.current)return null;if(!ff(ie))throw fl("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:ie.sessionId,nonce:ie.nonce}}catch(ie){if(!ve.current)return null;throw ie instanceof Bo&&ie.code==="session_fetch_failed"?ie:K?fl(`getSession did not resolve within ${yd/1e3} seconds.`):fl("Could not fetch the one-click session.",ie)}finally{clearTimeout(m),ze.current===W&&(ze.current=null)}},[]),_e=$r(async E=>{if(be.onClick?.(E),E.defaultPrevented||ke||at||(Pt(null),Xe(null),Ze.current))return;let W=[e,o,ot].filter(Boolean).length;if(W>1){let K=new Bo("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await kt(K),ve.current&&(ce(null),$e(null));return}if(W===0){let K=new Bo("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await kt(K),ve.current&&(ce(null),$e(null));return}Ze.current=!0,Ee(!0),$e(null),ne(!1),ce("processing");try{let K=new ml(He);if(e){let m=await K.getUnifiedCheckoutSession(e,t);await Y(m,e);return}if(o){let m=await ue(o);if(!m)return;let ie=await K.getUnifiedCheckoutSession(m.sessionId,m.nonce);await Y(ie,m.sessionId,{nonce:m.nonce});return}ou();try{let m=await K.createAndFetchSession({...ot});await Y(m,m.data.session?.id??null,{fromCreateSession:!0})}catch(m){if(yi(m)==="session_auto_completed"){await Ot({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw m}}catch(K){await kt(lo(gf(K,"Automatic payment failed. Please try again."),e))}finally{Ze.current=!1,ve.current&&(ce(null),$e(null),Ee(!1))}},[be.onClick,ot,ke,ue,o,at,t,Y,He,e,kt,Ot]),st=$r(E=>{let W=Ct.current;Pt(null),De.current?.({result:E,session:null,sessionId:W?.sessionId??null,autoCompleted:!1})},[]),lt=$r(E=>{wt.current?.(E)},[]),Ke=$r(E=>{Me.current?.(E)},[]),bt=Ga(()=>pf($),[$]),Tt=Ga(()=>{let E=bt?.buttonsLayout??df(k);return je?{...E,...je,cardButton:{...E.cardButton,...je.cardButton}}:E},[bt,k,je]),ct=Ga(()=>{let E=bt?.appearance;return ee?E?{...E,...ee,variables:{...E.variables,...ee.variables}}:ee:E},[ee,bt]),Ae=ct?.variables,Qe=Ae?.colorPrimary??"#4A49FF",et=Ae?.colorPrimaryHover??Vu(Qe,.12),j=Ae?.borderRadius??"8px";return bf(vf,{children:[xo("button",{...be,type:Nt,onClick:_e,disabled:ke||at,"aria-busy":at,style:{width:"100%",...dt===void 0?{boxSizing:"border-box",height:yf,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Tt.cardButton,...al({themeBundle:bt,resolvedPrimaryColor:Qe,resolvedBorderRadius:j,submitButtonStyle:Tt.submitButton,explicitPrimaryColor:Ae?.colorPrimary}),fontSize:Tt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ke||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:ke||at?.6:1,...Dt},onMouseEnter:E=>{be.onMouseEnter?.(E),!E.defaultPrevented&&!ke&&!at&&(bt||Ae?.colorPrimary)&&(E.currentTarget.style.backgroundColor=et)},onMouseLeave:E=>{be.onMouseLeave?.(E),!E.defaultPrevented&&(bt||Ae?.colorPrimary)&&(E.currentTarget.style.backgroundColor=Qe)},onMouseDown:E=>{be.onMouseDown?.(E),E.defaultPrevented||(E.currentTarget.style.transform="scale(0.985)")},onMouseUp:E=>{be.onMouseUp?.(E),E.defaultPrevented||(E.currentTarget.style.transform="scale(1)")},children:xo(Go,{content:dt})}),Te&&xo("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Te}),te&&xo(Ur,{status:te,errorMessage:Kt,authorized:it}),G&&xo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:E=>{E.target===E.currentTarget&&Pt(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:xo("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:xo(yl,{sessionId:G.sessionId,nonce:G.nonce,checkoutMode:"full",billingApiUrl:He,locale:f,theme:$,...ct?{appearance:ct}:{},buttonsTheme:k,buttonsStyles:je,initialErrorMessage:G.errorMessage,initialPayPalOrderId:G.payPalOrderId,cardTitleContent:null,onComplete:st,onError:lt,onDecline:Ke})})})]})}import{jsx as wf}from"react/jsx-runtime";var Sf={StripeSetupMethod:hc,PayPalSetupMethod:gc};function Rf(e){return wf(Pc,{...e,branches:Sf})}import{loadCheckoutRuntime as kf}from"@flopay/js";import{FloPayError as gd}from"@flopay/shared";import{useEffect as md,useRef as ji}from"react";import{jsx as Pd}from"react/jsx-runtime";var Ef="2.4.0";function hd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var If=new Set(["validation_error","api_error","authentication_error","rate_limit_error","network_error"]);function $i(e,t,n,o={}){return Object.assign(new gd(e,t,o),{retryable:n})}function _f(e){let t=hd(e)?e:{},n=typeof t.type=="string"&&If.has(t.type)?t.type:"";return $i(typeof t.message=="string"?t.message:"The setup failed.",n||"api_error",t.retryable===!0,{...typeof t.code=="string"?{code:t.code}:{},...typeof t.param=="string"?{param:t.param}:{},...typeof t.statusCode=="number"?{statusCode:t.statusCode}:{}})}function Tf(e){return e instanceof gd?$i(e.message,e.type,!0,{code:e.code??"runtime_load_failed",cause:e}):$i("The checkout runtime failed to load.","network_error",!0,{code:"runtime_load_failed",cause:e})}function fd(e){return{...e.theme===void 0?{}:{theme:e.theme},...e.appearance===void 0?{}:{appearance:e.appearance},...e.buttonsStyles===void 0?{}:{buttonsStyles:e.buttonsStyles},...e.containerStyle===void 0?{}:{containerStyle:e.containerStyle},...e.strings===void 0?{}:{strings:e.strings}}}function gl({kind:e,props:t}){let{sessionId:n,nonce:o,runtimeUrl:a,runtimeTimeoutMs:i}=t,l=ji(null),d=ji(null),y=ji(t);y.current=t;let w=fd(t),P=JSON.stringify(w),g=ji(P);return md(()=>{let _=l.current;if(!_)return;let O=!0,X=I=>{ut(()=>y.current.onError?.(I))},F=I=>{let f=y.current,$=I.payload;switch(I.name){case"setupReady":ut(()=>f.onReady?.());return;case"setupValidation":{let ee=hd($)&&typeof $.message=="string"?$.message:null;ut(()=>f.onValidation?.(ee));return}case"complete":ut(()=>f.onComplete?.($));return;case"decline":ut(()=>f.onDecline?.($));return;case"cancel":ut(()=>f.onCancel?.($));return;case"error":X(_f($));return;default:return}};return kf({runtimeUrl:a,...i===void 0?{}:{timeoutMs:i}}).then(I=>{if(!O)return;if(typeof I.mountSetup!="function"){X($i("The checkout runtime on this page is too old to run setup.","api_error",!1,{code:"runtime_setup_unsupported"}));return}let f=fd(y.current);g.current=JSON.stringify(f),d.current=I.mountSetup(_,{setup:e,sessionId:n,nonce:o,contractVersion:Ef,...f,onEvent:F})},I=>{O&&X(Tf(I))}),()=>{O=!1;let I=d.current;d.current=null,I?.unmount()}},[e,n,o,a,i]),md(()=>{let _=d.current;if(!_||g.current===P)return;g.current=P;let O=y.current;_.update({theme:O.theme,appearance:O.appearance,buttonsStyles:O.buttonsStyles,containerStyle:O.containerStyle,strings:O.strings})},[P]),Pd("div",{ref:l})}function Mf(e){return Pd(gl,{kind:"card",props:e})}import{loadCheckoutRuntime as Af}from"@flopay/js";import{FloPayError as Cd}from"@flopay/shared";import{useEffect as Wi,useRef as Ki}from"react";import{jsx as Lf}from"react/jsx-runtime";var Ff="2.2.0",xf="2.3.0";function Bf(e,t){let n={mode:e};return t&&Object.defineProperty(n,"getSession",{enumerable:!0,get:t}),n}function Df(e){return e instanceof Cd?e:new Cd("The checkout runtime failed to load.","network_error",{code:"runtime_load_failed",cause:e})}function Of(e){let{publishableKey:t,sessionId:n,nonce:o,appearance:a,strings:i,layout:l,runtimeUrl:d,runtimeTimeoutMs:y}=e,w=e.createSession===void 0?void 0:JSON.stringify(e.createSession),P=e.paymentMethodLayout===void 0?void 0:JSON.stringify(e.paymentMethodLayout),g=e.automaticPayment?.mode,_=e.automaticPayment?.getSession!==void 0,O=Ki(void 0),X=Ki(null),F=Ki(null),I=Ki(e);return I.current=e,Wi(()=>{let f=!0;return Af({runtimeUrl:d,timeoutMs:y}).then($=>{let ee=X.current;if(!f||!ee)return;let k=I.current.paymentMethodLayout;O.current=k===void 0?void 0:JSON.stringify(k),F.current=$.mount(ee,{contractVersion:g?xf:Ff,...g?{automaticPayment:Bf(g,_?()=>I.current.automaticPayment?.getSession:void 0)}:{},publishableKey:t,sessionId:n,nonce:o,createSession:w===void 0?void 0:JSON.parse(w),appearance:I.current.appearance,strings:I.current.strings,paymentMethodLayout:O.current===void 0?void 0:JSON.parse(O.current),...l?{layout:l}:{},onEvent:je=>I.current.onEvent?.(je)})},$=>{f&&I.current.onError?.(Df($))}),()=>{f=!1,F.current?.unmount(),F.current=null}},[t,n,o,w,l,g,_,d,y]),Wi(()=>{a!==void 0&&F.current?.update({appearance:a})},[a]),Wi(()=>{i!==void 0&&F.current?.update({strings:i})},[i]),Wi(()=>{if(P===void 0||P===O.current)return;let f=F.current;f&&(O.current=P,f.update({paymentMethodLayout:JSON.parse(P)}))},[P]),Lf("div",{ref:X,"data-flopay-runtime-checkout":""})}import{jsx as Uf}from"react/jsx-runtime";function Nf(e){return Uf(gl,{kind:"payment_method",props:e})}export{bi as DirectPayPalButton,Cf as FloPayAutomaticPaymentButton,jd as FloPayCardSetup,qd as FloPayCardSetupError,yl as FloPayCheckout,Rf as FloPayPaymentMethodSetup,ki as FloPayProvider,Mf as FloPayRuntimeCardSetup,Of as FloPayRuntimeCheckout,Nf as FloPayRuntimePaymentMethodSetup,il as SplitCardForm,Ss as VaultCardFields,YP as dropThirdPartyOnlyError,dp as useCheckout,po as useFloPay,Fs as usePayPalFloPay};
|