@flopay/react 1.20.2 → 1.20.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +7 -7
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as fc}from"./chunk-D4CVZRT4.mjs";import{c as Bt,d as Dr,e as wa,f as Ps,g as vs,h as xu,j as Fu}from"./chunk-YR36EYW2.mjs";import{a as yc}from"./chunk-BU7THP6H.mjs";import{a as wo,b as ui,c as Ss,d as ws,e as Ra,f as lc,g as cc,h as dc,i as uc,j as pc,k as mc}from"./chunk-FGCZOMML.mjs";import{a as li,b as Cs,c as oc,d as bs,e as Ho,f as ac,g as to,h as ci,i as ic,j as ka,k as di,l as sc}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as CP}from"@flopay/shared";import{PaymentAPI as dl}from"@flopay/js";import{FloPayError as Mo,isDeclineCallbackFailure as Qm,isMerchantAuthRequired as su,resolveBillingApiUrl as ef,resolveButtonsLayoutTheme as tf,resolveTheme as nf}from"@flopay/shared";import{useCallback as Ur,useEffect as da,useMemo as Ga,useRef as uo,useState as ua}from"react";import{Fragment as Yo,jsx as ur,jsxs as gc}from"react/jsx-runtime";function Bu(){return gc(Yo,{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 Du(){return ur(Yo,{children:"Go back"})}function Ou(){return ur(Yo,{children:"Secure card checkout"})}function Ko(e){return e!==void 0&&(e===""||e===null||e===!1)}function Vo({content:e}){return ur(Yo,{children:e===void 0?ur(Bu,{}):e})}function Go({content:e}){return ur(Yo,{children:e===void 0?ur(Du,{}):e})}function Ia({content:e}){return ur(Yo,{children:e===void 0?ur(Ou,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as Lu,canRecoverHostedCardForm as Nu,classifyTelemetryFailure as Uu,FloPayError as Yn,isCardHolderNamePlaceholder as zu,isMoneySettledOutcome as qu,isMountableVaultBlock as ju,isSetupIntentClientSecret as $u,isValidEmail as Wu,resolveSetupFutureUsage as Hu,resolveWalletModeOptions as Ku}from"@flopay/shared";import{canRecoverHostedCardForm as ko,hasServerSideCardGateway as _c}from"@flopay/shared";import{splitFullName as Ta}from"@flopay/shared";import{applyFriendlyMessageOverride as Zo}from"@flopay/shared";function ks(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Yn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Vu(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function hc(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(ju(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||Nu(o))||t&&e?.data.paypal?.publishableKey)}function Pc(e,t){if(t&&(!(e instanceof Yn)||e.type==="authentication_error"))return ks(e);if(!(e instanceof Yn&&Vu(e))){if(!t&&!(e instanceof Yn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Uu(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Yn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Yn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Jo(e,t,n,o={}){let a;return(i={})=>{if(a!==void 0)return a;let s={...o,...i,email:i.email?.trim()||o.email?.trim()},c=zu(s.firstName,s.lastName);if(!Wu(s.email))return Promise.reject(new Yn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let d={};for(let[R,g]of Object.entries(s)){if(c&&R.endsWith("Name")||typeof g!="string")continue;let y=g.trim();y&&(d[R]=y)}return a=e.claimCheckoutSession(t,n,{accountData:d}),a.catch(()=>{}),a}}function vc(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Rs(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Cc(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],o=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(o*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Is(e,t){return t?{...e,...t}:e}function mn(e,t,n){let o=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:o,...a?{code:a}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}var 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 no(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Kr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Vr(e){return e?.status==="authorized"||e?.status==="complete"}function ro(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 Yn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function yi(e){return e instanceof Yn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Xo(e){return kc(e)?new Yn("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Yn("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Yn(Lu,"api_error",{code:"checkout_processing_timeout"})}function Ea(e,t){return e==="processing"||qu(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($u(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new Yn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:o,error:a}=await n.retrievePaymentIntent(t);if(a)throw new Yn(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var Gu=["apple_pay","google_pay"];function Ec(e,t="automatic",n){let o=Hu(n,Gu,"wallet");return{...Ku(e,t),allowedPaymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Yu=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Es(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Yu.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 Fm,PaymentAPI as Oi,SESSION_CREATE_TELEMETRY as Bm}from"@flopay/js";import{buildCheckoutDisplayData as Dm,classifyTelemetryFailure as ru,DEFAULT_PAYMENT_METHOD_ORDER as Om,FloPayError as vn,isDeclineCallbackFailure as Hd,isDetachedSessionEligible as Lm,isExpectedPaymentDecline as Kd,isMerchantAuthRequired as Nm,isMountableVaultBlock as Um,resolveBillingApiUrl as zm,resolveButtonsLayoutTheme as qm,resolveDirectPaypalConfig as ou,resolveIdempotencyKey as Vd,resolveCheckoutLogLayout as jm,resolveTheme as au,SDK_VERSION as iu,telemetryStatusClass as $m,toPublicCheckoutInitError as Gd}from"@flopay/shared";import Ui,{useCallback as Rn,useEffect as or,useMemo as mr,useRef as Lt,useState as Wt}from"react";import{Elements as Ju}from"@stripe/react-stripe-js";import{jsx as Xu}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 oo(e){let t=Ac(e.stripe)?Mc.get(e.stripe):void 0;return Xu(Ju,{...e},t)}import{createContext as Fc}from"react";var pr=Fc({flopay:null,paypalFlopay:null,billingApiUrl:""}),wr=Fc({session:null,loading:!1,error:null});import{PaymentAPI as Ts}from"@flopay/js";import{buildPayPalCancelEvent as pp,buildPayPalProcessPaymentRequest as yp,buildPayPalSessionIntentRequest as mp,buildPayPalTokenizedBody as fp,classifyTelemetryFailure as gp,describePayPalProcessFailure as qc,FloPayError as na,friendlyPayPalFailureMessage as hp,generateIdempotencyKey as Pp,isPayPalTeardownMessage as vp,isSettledSessionIntent as Cp,isValidEmail as jc,mergePayPalPayerIdentity as bp,needsPayPalPayerDetails as Sp,normalizeGatewayEnvironment as wp,paypalProviderIdentityRequired as $c,resolvePayPalApprovalIdentity as kp,resolvePayPalDeclineReason as Rp,SDK_VERSION as Ip,usesPayPalVaultedChannel as Ep}from"@flopay/shared";import{loadScript as _p}from"@paypal/paypal-js";import{useCallback as yr,useContext as Tp,useEffect as jt,useMemo as Fa,useRef as ot,useState as Gr}from"react";import{compactBuyerIdentity as Zu,isValidEmail as Qu}from"@flopay/shared";import{useCallback as Bc,useEffect as ep,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 Qo(){let[e,t]=Lc(null),n=Dc(null),o=Dc(0),a=Bc((s,c)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:c}),new Promise(d=>{n.current=d})),[]),i=Bc(s=>{let c=n.current;n.current=null,t(null),c?.(s)},[]);return ep(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function ea({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,c]=Lc(e.email?.trim()??""),d=Qu(s.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:s,onChange:R=>c(R.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ma("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&Oc("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),Ma("button",{type:"button",disabled:!d||a,onClick:()=>{n(Zu({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as tp}from"@flopay/shared";import{useContext as mi}from"react";function ao(){return mi(pr).flopay}function _s(){return mi(pr).paypalFlopay??null}function np(){return mi(wr)}function Nc(){return mi(pr).billingApiUrl||tp()}import{FLO_INSTRUMENT_ONCE_NAMES as rp,invokeMerchantCallback as op,projectFloInstrument as ap}from"@flopay/shared";import{useCallback as ip,useRef as fi}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Uc}from"@flopay/shared";function ta(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]),ip(s=>{if(i.current!==t)return;let c=ap(s);if(c){if(rp.has(c.name)){if(o.current.has(c.name))return;o.current.add(c.name)}op(()=>n.current?.(c))}},[t])}import{createContext as sp}from"react";var Aa=sp(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 lp=Symbol.for("@flopay/js.telemetry.bridge.v1"),cp=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function dp(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function up(e){let t=dp(),n=(a,i)=>a?a.bind(e):i,o=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:o,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,o()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function vi(e){let t=globalThis[cp];return up(t?.(e)??{})}function fn(e){if(e)return e[lp]}import{useCallback as io,useEffect as zc,useRef as Ro}from"react";function xa(e,t){let n=Ro(0),o=Ro(null),a=Ro(null),i=Ro(e),s=Ro(t?.onHandoffObserved),c=Ro(t?.defersMissingTerminal),d=Ro(t?.onMissingTerminalDeferred);zc(()=>{i.current=e,s.current=t?.onHandoffObserved,c.current=t?.defersMissingTerminal,d.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let R=io((C=a.current)=>{C?.timer&&(clearTimeout(C.timer),C.timer=null)},[]),g=io(C=>{R();let fe=n.current+1;return n.current=fe,o.current=null,a.current={generation:fe,method:C,timer:null,yieldedControl:!1},fe},[R]),y=io(C=>{let fe=a.current;return C!==void 0&&fe?.generation!==C?!1:(R(fe),a.current=null,(C===void 0||o.current===C)&&(o.current=null),!0)},[R]),D=io(C=>{let fe=a.current,de=C??fe?.generation??n.current;(C===void 0||fe?.generation===C)&&(R(fe),a.current=null),o.current=de},[R]),ee=io(C=>o.current===(C??n.current),[]),ae=io(C=>a.current?.generation===C&&o.current!==C,[]),j=io(()=>{let C=a.current;C&&(R(C),!C.yieldedControl&&(C.yieldedControl=!0,s.current?.(C.method)))},[R]),K=io(()=>{let C=a.current;!C?.yieldedControl||document.visibilityState!=="visible"||(R(C),C.timer=setTimeout(()=>{if(C.timer=null,a.current?.generation===C.generation){if(c.current?.(C.method)){d.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))},[R]);return zc(()=>{let C=()=>{document.visibilityState==="visible"?K():j()};return document.addEventListener("visibilitychange",C),window.addEventListener("blur",j),window.addEventListener("focus",K),()=>{document.removeEventListener("visibilitychange",C),window.removeEventListener("blur",j),window.removeEventListener("focus",K),R()}},[R,j,K]),{startAttempt:g,finishAttempt:y,invalidateAttempt:D,isAttemptInvalidated:ee,isAttemptCurrent:ae,generationRef:n}}import{jsx as Io,jsxs as Ms}from"react/jsx-runtime";var Ci=45,Mp=1e3,Ap=11e3,Wc="paypal_intent_settled",xp={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"},Fp={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function Bp(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Fp[e.kind]??null}}function Hc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":ac(t)?"paypal_init_timeout":"paypal_init_failure"}function Dp(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Kc({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:c,currency:d,isSubscription:R,providerObjectType:g,approvalPresentation:y,onTokenizedBody:D,onComplete:ee,onErrorChange:ae,onDecline:j,onCancel:K,onTechnicalFailure:C,isProcessing:fe=!1,onLoadStateChange:de,onInitializationStateChange:I,allowAutomaticRetry:He=!0,onButtonClick:X,runBeforeButtonClick:Ne,session:at,existingOrderId:pt,telemetry:Ie,telemetryContext:Nt,onInstrument:Dt,debug:ke=!1}){let Ye=ao(),it=ta(Dt,e),st=Fa(()=>{if(Ye)return null;let _=vi({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ip,enabled:Ie!==!1});return _.setCheckoutContext(Nt??{}),_.beginCheckout(Nt??{}),_},[n,Ye,Ie,Nt?.checkoutMode,Nt?.layout]),Ee=Fa(()=>fn(Ye),[Ye]);jt(()=>()=>{st&&st.flush().catch(()=>{}).finally(()=>st.destroy())},[st]);let te=Fa(()=>({error:_=>{Ee?Ee.error(_):st?.error(_),it({class:"technical_error",errorCode:_.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":_.errorCode,requestCategory:_.requestCategory,provider:_.provider})},log:_=>{Ee?Ee.log(_):st?.log(_),it({class:"lifecycle",name:_.name,provider:_.provider})},performance:_=>{Ee?Ee.performance(_):st?.performance(_)},terminal:_=>{Ee?Ee.terminal(_):st?.terminal(_)},startTiming:()=>Ee?.now()??st?.now()??0,elapsed:_=>Ee?.elapsed(_)??Math.max(0,(st?.now()??_)-_)}),[it,Ee,st]),ue=ot(null),$t=ot(0),ze=ot(null),lt=ot(null),re=ot(null),Me=Tp(Aa),Ze=ot(null);Ze.current||(Ze.current=gi());let V=Me??Ze.current,Ct=ot(null),be=ot(!1),[Je,Ue]=Gr(!1),[Qe,bt]=Gr(!1),[De,Rt]=Gr(0),Ae=ot(0),[_e,St]=Gr(!1),Ot=ot(!1),It=ot(!1),[G,pe]=Gr(!1),[Te,ct]=Gr(!1),{request:dt,collect:Ke,finish:yt}=Qo(),mt=ot({sessionId:e,required:$c(o,at)});mt.current.sessionId!==e&&(mt.current={sessionId:e,required:$c(o,at)});let wt=mt.current.required,qe=Fa(()=>n.replace(/\/+$/,""),[n]),et=at?.gateways?.paypal?.providerObjectType??g,$=et??(R?"subscription":"order"),[hn]=Gr(ka),w=at?.gateways?.paypal?.approvalPresentation??y,m=di(hn,w==="app_switch"?"app_switch":void 0,$),Y=Ep(et),W=Fa(()=>JSON.stringify([qe,s,d,c??"",$,Y,m,e,pt??""]),[qe,s,d,c,pt,$,Y,m,e]),J=ot(W),f=J.current!==W,ie=ot(ke),H=ot(null),[Se,we]=Gr([]),E=yr(_=>{ie.current&&we($e=>[...$e,`${new Date().toISOString().slice(11,23)} ${_}`])},[]);jt(()=>{ie.current=ke,ke&&E("debug:enabled"),H.current?.setEnabled(ke)},[E,ke]);let tt=ot(D),Ht=ot(ee),Ut=ot(ae),Dn=ot(j),he=ot(K),Er=ot(C),cn=ot(X),dn=ot(de),nt=ot(I),xt=ot(i),In=ot(Ne),En=ot(at),_n=ot(o),Cn=ot(a),bn=ot(t),Kt=ot(null),zt=ot(new Map),Zt=ot(new Map),Ve=ot(!1),ye=ot(e);ye.current=e;let[ar]=Gr(Pi);jt(()=>(Ve.current=!0,()=>{Ve.current=!1}),[]),jt(()=>{tt.current=D},[D]),jt(()=>{xt.current=i},[i]),jt(()=>{Ht.current=ee},[ee]),jt(()=>{Ut.current=ae},[ae]),jt(()=>{Dn.current=j},[j]),jt(()=>{he.current=K},[K]),jt(()=>{Er.current=C},[C]),jt(()=>{cn.current=X},[X]),jt(()=>{dn.current=de},[de]),jt(()=>{nt.current=I},[I]),jt(()=>{In.current=Ne},[Ne]),jt(()=>{En.current=at},[at]),jt(()=>{_n.current=o},[o]),jt(()=>{Cn.current=a},[a]),jt(()=>{bn.current=t},[t]),jt(()=>{Ae.current=De},[De]),jt(()=>{_e&&Ct.current?.focus()},[_e,De]);let Ft=yr(()=>{window.setTimeout(()=>{Ct.current?.focus()},0)},[]),Tn=yr(()=>{Ue(!1),Rt(_=>_+1)},[]),On=yr(()=>{St(!1),(ue.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ue.current)?.focus?.()},[]);jt(()=>{!Je||!be.current||(be.current=!1,On())},[On,Je,De]);let ir=yr((_,$e)=>{let h=$e?.popupBlocked??to(_);h&&V.markBlocked();let se=li("PayPal",h,hn.inAppBrowser),Et=Er.current;if(Et){let gt=h&&hn.inAppBrowser?new na(se,"api_error",{code:$e?.code??"paypal_popup_blocked"}):_;Et("paypal",gt,$e);return}if(_ instanceof na&&_.code==="checkout_processing_timeout"){Ut.current?.(_.message);return}Ut.current?.(se)},[V,hn.inAppBrowser]),Ln=yr(_=>{let $e=ze.current,h=lt.current;$e===null||!h||(te.log({...h,popupCapability:V.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:_}),te.performance({...h,popupCapability:V.current(),stage:"overlay_return",durationMs:te.elapsed($e),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:_}),ze.current=null)},[V,te]),_r=yr((_,$e,h)=>{let se=lt.current;Ln("overlay_timeout"),se&&te.error({...se,popupCapability:V.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),ir($e,{...h,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:m,terminalReason:"overlay_timeout"}),St(!0),Tn(),Ft()},[Ln,Ft,ir,V,m,Tn,te]),fr=yr(()=>{V.markAvailable();let _=lt.current;_&&(re.current=_.attempt,te.log({..._,popupCapability:V.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[V,te]),un=yr(()=>!0,[]),pn=yr(()=>{let _=lt.current;if(!_)return;let $e=ze.current;te.performance({..._,popupCapability:V.current(),stage:"overlay_return",durationMs:$e===null?0:te.elapsed($e),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[V,te]),{finishAttempt:Mn,generationRef:$n,invalidateAttempt:Nn,isAttemptCurrent:An,isAttemptInvalidated:on,startAttempt:Qt}=xa(_r,{onHandoffObserved:fr,defersMissingTerminal:un,onMissingTerminalDeferred:pn}),en=yr(()=>(St(!1),Qt("paypal")),[Qt]),Vt=yr(_=>{Nn(_?.generation),_?.showRetry&&St(!0),_?.remount&&Tn(),_?.focus!==!1&&Ft()},[Ft,Nn,Tn]),Un=_=>{let $e=Kt.current;return $e&&Zt.current.set(_,$e),_};jt(()=>{J.current!==W&&(J.current=W,Ot.current=!1,It.current=!1,Ue(!1),bt(!1),pe(!1),nt.current?.("loading"))},[W]),jt(()=>{Bt(()=>dn.current?.(Je&&!G))},[Je,G]);let zn=wp(c);jt(()=>{let _={attempt:$n.current+1,inAppBrowser:hn.inAppBrowser,appFamily:hn.appFamily,popupCapability:V.current(),presentationMode:m},$e=()=>({...lt.current??_,popupCapability:V.current()}),h={error:v=>te.error({...v,...$e()}),log:v=>te.log({...v,...$e()}),performance:v=>te.performance({...v,...$e()}),terminal:v=>te.terminal({...v,...$e()}),startTiming:te.startTiming,elapsed:te.elapsed},se=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Et=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(E(`mount clientId=${se} env=${c??"(unset)"}\u2192${zn??"live"} ccy=${d} sub=${R}`),E(`ua=${Et.slice(0,80)}${Et.length>80?"\u2026":""}`),!s){E("FAIL: clientId empty \u2014 gateway misconfigured"),pe(!0),h.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(!ue.current){E("FAIL: containerRef not attached");return}$t.current=h.startTiming(),h.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let gt=!1,ut=!1,Re=()=>gt||ut,Wn=v=>{let u=Ve.current,k=u?v:"torn_down";u&&E(`onError ignored reason=${k}`),ar.take(ye.current)&&h.log({name:hi,stage:"provider_ready",reason:k,provider:"paypal",paymentMethodCategory:"paypal"})},Ao=()=>ye.current===e?"stale_attempt":"session_changed",Fn=Y?$:void 0,ne,gr=!1,Tr=()=>{ne=Pp(),ne||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),gr=!0},Jr=null,po=!1,Jn=null,Mr=!1,zr=()=>{!Jn||Mr||(Mr=!0,Jn.close().catch(()=>{}))},yn=!1,qr=!1,Hn=ue.current,Sn=null,Gt=null,Pe=[],wn=null,Xn=!1,hr=!1,Pr=null,sr=v=>{if(!v||typeof v.getBoundingClientRect!="function")return"(no rect)";let u=v.getBoundingClientRect();return`${Math.round(u.width)}\xD7${Math.round(u.height)}`},yo=v=>{if(!v)return"(empty)";try{let u=new URL(v,typeof window>"u"?"https://localhost":window.location.href),k=u.pathname.toLowerCase();return k.includes("checkcaptcha")||k.includes("captcha")?`CAPTCHA(${u.host}${k})`:k.includes("risk")||k.includes("challenge")?`RISK(${u.host}${k})`:k.includes("smart/buttons")?`smart-buttons(${u.host})`:`${u.host}${k}`.slice(0,100)}catch{return v.slice(0,80)}},jr=v=>{let u=v.getAttribute("src"),k=v.getAttribute("srcdoc"),x=v.getAttribute("name"),S=v.getAttribute("sandbox"),N=[];return u&&N.push(`src=${yo(u)}`),k&&N.push(`srcdoc[${k.length}ch]`),!u&&!k&&N.push("src=(empty) srcdoc=(empty)"),x&&N.push(`name=${x.slice(0,40)}`),S!==null&&N.push(`sandbox="${S.slice(0,40)}"`),N.join(" ")},mo=v=>{if(!(v instanceof HTMLIFrameElement))return"";try{let u=v.contentDocument;if(!u)return"cd=null";let k=u.body?.children.length??0,x=u.body?.innerHTML.length??0,S=u.head?.innerHTML.length??0;return`cd=same-origin readyState=${u.readyState} body[${k}children,${x}ch] head[${S}ch]`}catch(u){return`cd=cross-origin(${u.message.slice(0,30)})`}},$r=[],fo=v=>{if(Re())return;let u=v.message??String(v.error??"(no message)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(E(`window:error ${u.slice(0,140)}`),$r.push(u))},Wr=v=>{if(Re())return;let u=v.reason instanceof Error?v.reason.message:String(v.reason??"(no reason)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(E(`window:rejection ${u.slice(0,140)}`),$r.push(u))},lr={value:0},go=()=>{Sn?.disconnect(),Sn=null,Gt?.disconnect(),Gt=null;for(let v of Pe.splice(0))clearTimeout(v);hr=!1,Xn&&typeof window<"u"&&(window.removeEventListener("error",fo),window.removeEventListener("unhandledrejection",Wr)),Xn=!1},ho=()=>{if(!(Xn||Re()||yn)){if(Xn=!0,$r.length=0,lr.value=0,typeof window<"u"&&(window.addEventListener("error",fo),window.addEventListener("unhandledrejection",Wr)),typeof PerformanceObserver<"u")try{Gt=new PerformanceObserver(v=>{if(!Re())for(let u of v.getEntries()){if(!u.name.toLowerCase().includes("paypal"))continue;lr.value+=1;let k=Math.round(u.duration);E(`net ${k}ms ${u.name.slice(0,90)}`)}}),Gt.observe({type:"resource",buffered:!0})}catch{}Pr?.()}},qt=()=>{wn&&(clearTimeout(wn),wn=null)},Kn=()=>{go(),qt()},Ar={setEnabled:v=>{v?ho():go()}};H.current=Ar,ie.current&&ho();let Yt=vp,Zn=v=>{if(Re()||Yt(v))return;let u=Zo(v)??v;Bt(()=>Ut.current?.(u))},xe=(v,u)=>{if(gt||po)return;po=!0,ut=!0,Kn(),zr();let k=Bp({kind:v,generationActive:!0,automaticRetryAllowed:He,automaticRetryUsed:Ot.current});if(k.action==="retry"){Ot.current=!0,Ue(!1),ct(!1),bt(!0),nt.current?.("retrying"),Jr=setTimeout(()=>{gt||Rt(x=>x+1)},Mp);return}if(Ue(!1),ct(!1),bt(!1),pe(!0),k.action!=="ignore"){if(nt.current?.("exhausted"),k.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",u);return}if(k.report){let x=Cs({code:Hc(v,u),message:u},{inAppBrowser:hn.inAppBrowser,handoffObserved:!1});x.popupBlocked&&V.markBlocked(),h.error({errorCode:x.popupBlocked?x.errorCode:k.report.errorCode,stage:k.report.stage,operationOutcome:k.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:x.terminalReason})}It.current||(It.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Hc(v,u)))}};pe(!1);let Bn=async(v,u=Kt.current)=>{if(Re())return;let k=u?.sessionId??e;if(tt.current){await tt.current(v,{sessionId:k,accountPatch:u?.accountPatch,nonce:u?.nonce});return}let x=h.startTiming();h.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let S=()=>{h.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),h.performance({stage:"processing",durationMs:h.elapsed(x),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let N=yp({body:v,sessionId:k,nonce:u?.nonce??bn.current,accountPatch:u?.accountPatch,session:En.current,email:_n.current}),F=await new Ts(qe,{telemetry:!1}).processPayment(N.userId,N.params);if(F.ok){if(ut||gt&&Ve.current)return;S(),h.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Bt(()=>Ht.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Re())return;let U=await F.json().catch(()=>null),ft=qc(U),_t=ft.message;S(),F.status===400&&(typeof U?.declineCode=="string"||!Array.isArray(U?.fields))?h.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):F.status===400||F.status===422?h.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):h.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Dp(F.status),failureCategory:F.status>=500?"server_error":void 0}),Zn(_t),Bt(()=>Dn.current?.(mn("paypal",_t,{code:ft.code,declineCode:ft.declineCode})));return}catch(N){if(Re())return;S(),h.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let le=hp(N instanceof Error?N.message:void 0);Zn(le),Bt(()=>Dn.current?.(mn("paypal",le)));return}},an=()=>new na("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Qn=v=>Re()?Promise.reject(an()):Promise.resolve(v),pa=async v=>{if(v.ok){h.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Bt(()=>Ht.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let u=await v.json().catch(()=>null),k=qc(u);h.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Bt(()=>Dn.current?.(mn("paypal",k.message,{code:k.code,declineCode:k.declineCode})))},er=()=>{let v=Kt.current;Ln("approved"),v&&(zt.current.delete(v.surfaceKey),Mn(v.generation)),Kt.current=null},P=async v=>{if(Re())throw an();gr||Tr();let u=Kt.current,k=u?.sessionId??e,x=u?.nonce??bn.current;h.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let S;try{S=await new Ts(qe,{telemetry:!1}).createSessionIntent(k,x??"",mp(Fn),{idempotencyKey:ne})}catch(N){throw h.error({...gp(N,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),N}if(Re())throw an();if(Cp(S))throw await pa(S.response),er(),new na("PayPal checkout already settled.","api_error",{code:Wc});if(S.provider!=="paypal"||S.providerObjectType!==$)throw new Error(v);return h.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),S.providerObjectId},A=(v,u)=>{let k=u?.nonce??bn.current;if(!k)return;let x=u?.sessionId??e,S=Rp(v);new Ts(qe,{telemetry:!1}).reportSessionIntentDecline(x,k,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:S}).catch(()=>{})},O=De;E("loadScript:scheduled (deferred 1 tick)");let M=null,We=setTimeout(()=>{if(gt){E("loadScript:skipped (cancelled before defer ran)");return}E("loadScript:start");let v=zn==="live"?"production":zn,u={};$==="subscription"?u={intent:"subscription",vault:!0}:$==="order"&&(u={intent:"capture"}),M=_p({clientId:s,currency:d,...u,...v?{environment:v}:{},...v==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let k=!1;M.then(x=>{if(k=!0,E(`loadScript:resolved inactive=${Re()} ns=${!!x} buttons=${!!x?.Buttons}`),Re())return;if(!x?.Buttons){E("FAIL: namespace missing Buttons factory"),xe("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}h.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),h.performance({stage:"provider_ready",durationMs:h.elapsed($t.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),h.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let S=async(ve,Z)=>{if(Re()||Ae.current!==O)return;let b=ve.vaultSetupToken??ve.subscriptionID??ve.orderID??"",T=b?Zt.current.get(b):zt.current.get(O);if(!(!T||!An(T.generation))&&Mn(T.generation)){Zt.current.delete(b),zt.current.delete(T.surfaceKey),Ln("approved");try{if(ct(!0),Bt(()=>Ut.current?.(null)),!b)throw new na("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let L=kp({accountPatch:T.accountPatch,email:_n.current,billingName:Cn.current,session:En.current});if(Sp(L))try{L=bp(L,await Z?.order?.get?.())}catch{}if((xt.current||wt)&&!jc(L.email)){let Ce=await Ke("PayPal",L);if(!Ce)return;L=Ce}jc(L.email)&&(T.accountPatch=kr({...T.accountPatch,...L}),await xt.current?.(L));let kt=fp(b,Fn);await Bn(kt,T)}catch(L){Zn(L instanceof Error?L.message:"PayPal capture failed.")}finally{Re()||ct(!1)}}},N=ve=>{let Z=pt?()=>Qn(pt):()=>P(ve);return async()=>Un(await Z())},le=x.Buttons({style:{layout:"horizontal",height:Ci,tagline:!1},...m==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ve,Z)=>{if(Re()){await Z.reject();return}Tr();let b=In.current,T={};if(b)try{let Ce=await b("paypal");if(Re()){await Z.reject();return}if(!Ce.proceed){Kt.current=null,zt.current.delete(O),await Z.reject();return}T={sessionId:Ce.sessionId,accountPatch:Ce.accountPatch,nonce:Ce.nonce}}catch(Ce){E(`onClick:runBeforeButtonClick rejected msg=${(Ce instanceof Error?Ce.message:String(Ce)).slice(0,120)}`),Kt.current=null,zt.current.delete(O),await Z.reject();return}Bt(()=>cn.current?.("paypal"));let L=en(),kt={generation:L,surfaceKey:O,...T};Kt.current=kt,zt.current.set(O,kt),lt.current={..._,attempt:L},await Z.resolve(),h.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),h.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),ze.current=h.startTiming()},createOrder:$==="order"?N("Failed to create PayPal order."):void 0,createSubscription:$==="subscription"?N("Failed to create PayPal subscription."):void 0,createVaultSetupToken:$==="setup_token"?async()=>Un(await P("Failed to create PayPal setup token.")):void 0,onApprove:S,onCancel:()=>{if(Re())return;let ve=zt.current.get(O)??Kt.current,Z=ve&&An(ve.generation)?pp(ve.sessionId??e,Fn):null;ve&&zt.current.delete(ve.surfaceKey),Kt.current=null,Ln("cancelled"),h.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be.current=!0,Vt({generation:ve?.generation,remount:!0,focus:!1}),Z&&Bt(()=>he.current?.(Z))},onError:ve=>{if(ve instanceof na&&ve.code===Wc)return;let Z=ve instanceof Error?ve.message:"PayPal failed to render.";if(Re()||Ae.current!==O){Yt(Z)||Wn(Ao());return}if(yn){let b=zt.current.get(O)??Kt.current;if(!b||!An(b.generation)){if(Yt(Z)){!b&&!on()&&Mn();return}Wn(b||on()?"stale_attempt":"no_current_attempt");return}if(E(`onError rendered=${yn} msg=${Z.slice(0,120)}`),Yt(Z)){Mn(b.generation);return}let{errorCode:T,popupBlocked:L,providerDeclined:kt,terminalReason:Ce}=Cs(ve,{inAppBrowser:hn.inAppBrowser,handoffObserved:re.current===b.generation});if(L&&V.markBlocked(),Ln(Ce),kt){h.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ce}),A(ve,b),Bt(()=>Dn.current?.(mn("paypal",Z))),zt.current.delete(b.surfaceKey),Kt.current=null,Mn(b.generation);return}h.error({errorCode:T,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ce}),zt.current.delete(b.surfaceKey),Kt.current=null,Vt({generation:b.generation,remount:!0,showRetry:!0,focus:!0}),ir(ve,{code:"paypal_runtime_failed",popupBlocked:L,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:m,terminalReason:Ce});return}E(`onError rendered=${yn} msg=${Z.slice(0,120)}`),xe(Yt(Z)?"teardown":"pre_ready_callback",Z)}}),F=le.isEligible();if(E(`isEligible=${F}`),h.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!F){Ue(!1),xe("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}qr=!0,Jn=le,Pr=()=>{if(!Xn||hr||Re()||yn)return;hr=!0,E(`container:dims ${sr(Hn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Sn=new MutationObserver(Z=>{if(!Re()){for(let b of Z)if(b.type==="childList")b.addedNodes.forEach(T=>{if(!(T instanceof Element))return;let L=T.tagName.toLowerCase(),kt=(T.getAttribute("title")??"").slice(0,40),Ce=L==="iframe"?` ${jr(T)}`:"";E(`child+ ${L}${kt?` title="${kt}"`:""}${Ce} dims=${sr(T)}`)});else if(b.type==="attributes"&&b.target instanceof Element){let T=b.target;if(T.tagName.toLowerCase()!=="iframe")continue;let L=b.attributeName;(L==="src"||L==="srcdoc")&&E(`attr~ iframe ${L}=${L==="srcdoc"?`[${(T.getAttribute("srcdoc")??"").length}ch]`:yo(T.getAttribute("src"))} dims=${sr(T)}`)}}}),Sn.observe(Hn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ve=Z=>{if(Re()||yn)return;let b=Hn.querySelectorAll("iframe"),T=typeof document<"u"&&"hasStorageAccess"in document;E(`watchdog:${Z} container=${sr(Hn)} children=${Hn.childElementCount} iframes=${b.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${T} paypalNetRequests=${lr.value}`),b.forEach((L,kt)=>{let Ce=(L.getAttribute("title")??"").slice(0,40);E(` iframe[${kt}] ${sr(L)}${Ce?` title="${Ce}"`:""} ${jr(L)}`);let Ge=mo(L);Ge&&E(` ${Ge}`)}),$r.length===0&&E(" (no PayPal/zoid window errors captured)")};Pe.push(setTimeout(()=>ve("3s"),3e3)),Pe.push(setTimeout(()=>ve("8s"),8e3)),Pe.push(setTimeout(()=>ve("15s"),15e3))},Pr(),E("render:start");let ft=h.startTiming();wn=setTimeout(()=>{Re()||yn||(E("watchdog:11s retryable render timeout"),xe("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Ap);let _t=le.render(Hn);(async()=>{try{if(await _t,E(`render:resolved inactive=${Re()}`),Kn(),Re()){zr();return}yn=!0,Ue(!0),bt(!1),nt.current?.("ready"),h.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),h.performance({stage:"checkout_render",durationMs:h.elapsed(ft),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ve){let Z=ve instanceof Error?ve.message:"PayPal failed to render.";E(`render:rejected msg=${Z.slice(0,120)}`),Kn(),xe(Yt(Z)?"teardown":"render_rejected",Z)}})()}).catch(x=>{let S=x instanceof Error?x.message:"PayPal operation failed.";E(`provider:failed msg=${S.slice(0,120)}`);let N="script_rejected";k&&Yt(S)?N="teardown":k&&qr&&(N="render_rejected"),xe(N,S)})},0);return()=>{gt=!0,clearTimeout(We),Jr&&clearTimeout(Jr),Kn(),H.current===Ar&&(H.current=null),zr(),ze.current=null,lt.current=null}},[He,qe,s,d,c,$,m,Y,e,pt,De,te,Ke,wt,E,Ln]);let xn=ke?Ms("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:G?"#fef2f2":"#f3f4f6",border:`1px solid ${G?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Je} failed=${G})`,Se.length===0?`
|
|
1
|
+
import{a as fc}from"./chunk-D4CVZRT4.mjs";import{c as Ft,d as Ur,e as wa,f as Ps,g as vs,h as Fu,j as Bu}from"./chunk-YR36EYW2.mjs";import{a as yc}from"./chunk-BU7THP6H.mjs";import{a as Eo,b as ui,c as Ss,d as ws,e as Ra,f as lc,g as cc,h as dc,i as uc,j as pc,k as mc}from"./chunk-FGCZOMML.mjs";import{a as li,b as Cs,c as oc,d as bs,e as Ho,f as ac,g as so,h as ci,i as ic,j as ka,k as di,l as sc}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as bP}from"@flopay/shared";import{PaymentAPI as dl}from"@flopay/js";import{FloPayError as Bo,isDeclineCallbackFailure as ef,isMerchantAuthRequired as lu,resolveBillingApiUrl as tf,resolveButtonsLayoutTheme as nf,resolveTheme as rf}from"@flopay/shared";import{useCallback as $r,useEffect as ua,useMemo as Ga,useRef as ho,useState as pa}from"react";import{Fragment as Jo,jsx as ur,jsxs as gc}from"react/jsx-runtime";function Du(){return gc(Jo,{children:[gc("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[ur("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),ur("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",ur("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:ur("path",{d:"M9 18l6-6-6-6"})})]})}function Ou(){return ur(Jo,{children:"Go back"})}function Lu(){return ur(Jo,{children:"Secure card checkout"})}function Vo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Go({content:e}){return ur(Jo,{children:e===void 0?ur(Du,{}):e})}function Yo({content:e}){return ur(Jo,{children:e===void 0?ur(Ou,{}):e})}function Ia({content:e}){return ur(Jo,{children:e===void 0?ur(Lu,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as Nu,canRecoverHostedCardForm as Uu,classifyTelemetryFailure as zu,FloPayError as er,isCardHolderNamePlaceholder as qu,isMoneySettledOutcome as ju,isMountableVaultBlock as $u,isSetupIntentClientSecret as Wu,isValidEmail as Ku,resolveSetupFutureUsage as Hu,resolveWalletModeOptions as Vu}from"@flopay/shared";import{canRecoverHostedCardForm as _o,hasServerSideCardGateway as _c}from"@flopay/shared";import{splitFullName as Ta}from"@flopay/shared";import{applyFriendlyMessageOverride as Qo}from"@flopay/shared";function ks(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof er&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Gu(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function hc(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&($u(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||Uu(o))||t&&e?.data.paypal?.publishableKey)}function Pc(e,t){if(t&&(!(e instanceof er)||e.type==="authentication_error"))return ks(e);if(!(e instanceof er&&Gu(e))){if(!t&&!(e instanceof er)&&(e instanceof TypeError||e instanceof SyntaxError))return{...zu(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof er)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof er))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Xo(e,t,n,o={}){let a;return(i={})=>{if(a!==void 0)return a;let l={...o,...i,email:i.email?.trim()||o.email?.trim()},u=qu(l.firstName,l.lastName);if(!Ku(l.email))return Promise.reject(new er("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[R,C]of Object.entries(l)){if(u&&R.endsWith("Name")||typeof C!="string")continue;let g=C.trim();g&&(m[R]=g)}return a=e.claimCheckoutSession(t,n,{accountData:m}),a.catch(()=>{}),a}}function vc(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Rs(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Cc(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],o=n.reduce((i,l)=>i+(l.overrideAmount??l.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(o*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,l)=>({uuid:`synthetic-${i.type??"item"}-${l}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Is(e,t){return t?{...e,...t}:e}function gn(e,t,n){let o=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,l=typeof t=="string"?void 0:t.sessionId;return{method:e,message:o,...a?{code:a}:{},...i?{declineCode:i}:{},...l?{sessionId:l}:{}}}var bc=new WeakMap;function Sc(e,t){return typeof e=="object"&&e!==null&&bc.set(e,t?{sessionId:t}:{}),e}function wc(e){return typeof e=="object"&&e!==null?bc.get(e):void 0}function lo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Jr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Xr(e){return e?.status==="authorized"||e?.status==="complete"}function co(e,t){if(e.data.session)return e.data.session;let n=e.raw,o=n?.latestTransactionAttempt?.result,a=n?.status==="authorized"||o==="AUTHORIZED";return a||n?.status==="completed"||o==="SUCCESS"?{...t,status:a?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function kc(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function pi(e){let t=kc(e);return new er(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function yi(e){return e instanceof er||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Zo(e){return kc(e)?new er("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new er("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new er(Nu,"api_error",{code:"checkout_processing_timeout"})}function Ea(e,t){return e==="processing"||ju(e,t)}function Rc(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Ic(e,t){let n=e;if(Wu(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:l}=await n.retrieveSetupIntent(t);if(l)throw new er(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:o,error:a}=await n.retrievePaymentIntent(t);if(a)throw new er(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var Yu=["apple_pay","google_pay"];function Ec(e,t="automatic",n){let o=Hu(n,Yu,"wallet");return{...Vu(e,t),allowedPaymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Ju=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Es(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Ju.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function _a(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Bm,PaymentAPI as Oi,SESSION_CREATE_TELEMETRY as Dm}from"@flopay/js";import{applyClaimAdvertisement as Kd,buildCheckoutDisplayData as Om,classifyTelemetryFailure as ou,DEFAULT_PAYMENT_METHOD_ORDER as Lm,FloPayError as kn,isDeclineCallbackFailure as Hd,isDetachedSessionEligible as Nm,isExpectedPaymentDecline as Vd,isMerchantAuthRequired as Um,isMountableVaultBlock as zm,resolveBillingApiUrl as qm,resolveButtonsLayoutTheme as jm,resolveDirectPaypalConfig as au,resolveIdempotencyKey as Gd,resolveCheckoutLogLayout as $m,resolveTheme as iu,SDK_VERSION as su,telemetryStatusClass as Wm,toPublicCheckoutInitError as Yd}from"@flopay/shared";import Ui,{useCallback as pn,useEffect as ir,useMemo as mr,useRef as Bt,useState as Jt}from"react";import{Elements as Xu}from"@stripe/react-stripe-js";import{jsx as Zu}from"react/jsx-runtime";var Mc=new WeakMap,Tc=0;function Ac(e){return!!e&&typeof e=="object"}function xc(e,t){for(let n of e)!Ac(n)||t.includes(n)||(Tc+=1,Mc.set(n,`stripe-account-${Tc}`))}function uo(e){let t=Ac(e.stripe)?Mc.get(e.stripe):void 0;return Zu(Xu,{...e},t)}import{createContext as Fc}from"react";var pr=Fc({flopay:null,paypalFlopay:null,billingApiUrl:""}),wr=Fc({session:null,loading:!1,error:null});import{PaymentAPI as Ts}from"@flopay/js";import{buildPayPalCancelEvent as yp,buildPayPalProcessPaymentRequest as mp,buildPayPalSessionIntentRequest as fp,buildPayPalTokenizedBody as gp,classifyTelemetryFailure as hp,describePayPalProcessFailure as qc,FloPayError as ra,friendlyPayPalFailureMessage as Pp,generateIdempotencyKey as vp,isPayPalTeardownMessage as Cp,isSettledSessionIntent as bp,isValidEmail as jc,mergePayPalPayerIdentity as Sp,needsPayPalPayerDetails as wp,normalizeGatewayEnvironment as kp,paypalProviderIdentityRequired as $c,resolvePayPalApprovalIdentity as Rp,resolvePayPalDeclineReason as Ip,SDK_VERSION as Ep,usesPayPalVaultedChannel as _p}from"@flopay/shared";import{loadScript as Tp}from"@paypal/paypal-js";import{useCallback as yr,useContext as Mp,useEffect as Wt,useMemo as Fa,useRef as nt,useState as Zr}from"react";import{compactBuyerIdentity as Qu,isValidEmail as ep}from"@flopay/shared";import{useCallback as Bc,useEffect as tp,useRef as Dc,useState as Lc}from"react";import{compactBuyerIdentity as kr}from"@flopay/shared";import{jsx as Oc,jsxs as Ma}from"react/jsx-runtime";function ea(){let[e,t]=Lc(null),n=Dc(null),o=Dc(0),a=Bc((l,u)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:l,identity:u}),new Promise(m=>{n.current=m})),[]),i=Bc(l=>{let u=n.current;n.current=null,t(null),u?.(l)},[]);return tp(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function ta({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[l,u]=Lc(e.email?.trim()??""),m=ep(l.trim());return Ma("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[Ma("div",{style:{fontWeight:700},children:["Continue with ",t]}),Ma("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Oc("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:R=>u(R.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ma("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&Oc("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),Ma("button",{type:"button",disabled:!m||a,onClick:()=>{n(Qu({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as np}from"@flopay/shared";import{useContext as mi}from"react";function po(){return mi(pr).flopay}function _s(){return mi(pr).paypalFlopay??null}function rp(){return mi(wr)}function Nc(){return mi(pr).billingApiUrl||np()}import{FLO_INSTRUMENT_ONCE_NAMES as op,invokeMerchantCallback as ap,projectFloInstrument as ip}from"@flopay/shared";import{useCallback as sp,useRef as fi}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Uc}from"@flopay/shared";function na(e,t){let n=fi(e);n.current=e;let o=fi(new Set),a=fi(t),i=fi(t);return wa(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),sp(l=>{if(i.current!==t)return;let u=ip(l);if(u){if(op.has(u.name)){if(o.current.has(u.name))return;o.current.add(u.name)}ap(()=>n.current?.(u))}},[t])}import{createContext as lp}from"react";var Aa=lp(null);function gi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var hi="provider.callback.ignored";function Pi(){let e,t=0;return{take(n){return n!==e&&(e=n,t=0),t>=5?!1:(t+=1,!0)}}}var cp=Symbol.for("@flopay/js.telemetry.bridge.v1"),dp=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function up(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function pp(e){let t=up(),n=(a,i)=>a?a.bind(e):i,o=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:o,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,o()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function vi(e){let t=globalThis[dp];return pp(t?.(e)??{})}function hn(e){if(e)return e[cp]}import{useCallback as yo,useEffect as zc,useRef as To}from"react";function xa(e,t){let n=To(0),o=To(null),a=To(null),i=To(e),l=To(t?.onHandoffObserved),u=To(t?.defersMissingTerminal),m=To(t?.onMissingTerminalDeferred);zc(()=>{i.current=e,l.current=t?.onHandoffObserved,u.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let R=yo((w=a.current)=>{w?.timer&&(clearTimeout(w.timer),w.timer=null)},[]),C=yo(w=>{R();let pe=n.current+1;return n.current=pe,o.current=null,a.current={generation:pe,method:w,timer:null,yieldedControl:!1},pe},[R]),g=yo(w=>{let pe=a.current;return w!==void 0&&pe?.generation!==w?!1:(R(pe),a.current=null,(w===void 0||o.current===w)&&(o.current=null),!0)},[R]),A=yo(w=>{let pe=a.current,se=w??pe?.generation??n.current;(w===void 0||pe?.generation===w)&&(R(pe),a.current=null),o.current=se},[R]),X=yo(w=>o.current===(w??n.current),[]),te=yo(w=>a.current?.generation===w&&o.current!==w,[]),D=yo(()=>{let w=a.current;w&&(R(w),!w.yieldedControl&&(w.yieldedControl=!0,l.current?.(w.method)))},[R]),K=yo(()=>{let w=a.current;!w?.yieldedControl||document.visibilityState!=="visible"||(R(w),w.timer=setTimeout(()=>{if(w.timer=null,a.current?.generation===w.generation){if(u.current?.(w.method)){m.current?.(w.method,w.generation);return}a.current=null,o.current=w.generation,i.current(w.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},oc))},[R]);return zc(()=>{let w=()=>{document.visibilityState==="visible"?K():D()};return document.addEventListener("visibilitychange",w),window.addEventListener("blur",D),window.addEventListener("focus",K),()=>{document.removeEventListener("visibilitychange",w),window.removeEventListener("blur",D),window.removeEventListener("focus",K),R()}},[R,D,K]),{startAttempt:C,finishAttempt:g,invalidateAttempt:A,isAttemptInvalidated:X,isAttemptCurrent:te,generationRef:n}}import{jsx as Mo,jsxs as Ms}from"react/jsx-runtime";var Ci=45,Ap=1e3,xp=11e3,Wc="paypal_intent_settled",Fp={width:"100%",minHeight:Ci,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},Bp={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function Dp(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Bp[e.kind]??null}}function Kc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":ac(t)?"paypal_init_timeout":"paypal_init_failure"}function Op(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Hc({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:l,environment:u,currency:m,isSubscription:R,providerObjectType:C,approvalPresentation:g,onTokenizedBody:A,onComplete:X,onErrorChange:te,onDecline:D,onCancel:K,onTechnicalFailure:w,isProcessing:pe=!1,onLoadStateChange:se,onInitializationStateChange:I,allowAutomaticRetry:We=!0,onButtonClick:G,runBeforeButtonClick:Ue,session:rt,existingOrderId:dt,telemetry:Re,telemetryContext:Nt,onInstrument:Dt,debug:be=!1}){let He=po(),ot=na(Dt,e),at=Fa(()=>{if(He)return null;let T=vi({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ep,enabled:Re!==!1});return T.setCheckoutContext(Nt??{}),T.beginCheckout(Nt??{}),T},[n,He,Re,Nt?.checkoutMode,Nt?.layout]),Ie=Fa(()=>hn(He),[He]);Wt(()=>()=>{at&&at.flush().catch(()=>{}).finally(()=>at.destroy())},[at]);let Z=Fa(()=>({error:T=>{Ie?Ie.error(T):at?.error(T),ot({class:"technical_error",errorCode:T.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":T.errorCode,requestCategory:T.requestCategory,provider:T.provider})},log:T=>{Ie?Ie.log(T):at?.log(T),ot({class:"lifecycle",name:T.name,provider:T.provider})},performance:T=>{Ie?Ie.performance(T):at?.performance(T)},terminal:T=>{Ie?Ie.terminal(T):at?.terminal(T)},startTiming:()=>Ie?.now()??at?.now()??0,elapsed:T=>Ie?.elapsed(T)??Math.max(0,(at?.now()??T)-T)}),[ot,Ie,at]),le=nt(null),Kt=nt(0),je=nt(null),it=nt(null),Q=nt(null),Te=Mp(Aa),Xe=nt(null);Xe.current||(Xe.current=gi());let H=Te??Xe.current,ht=nt(null),Ce=nt(!1),[Ve,ze]=Zr(!1),[Ze,Pt]=Zr(!1),[De,wt]=Zr(0),Me=nt(0),[Ee,vt]=Zr(!1),Ot=nt(!1),kt=nt(!1),[V,ce]=Zr(!1),[_e,st]=Zr(!1),{request:lt,collect:Ke,finish:Ct}=ea(),_t=nt({sessionId:e,required:$c(o,rt)});_t.current.sessionId!==e&&(_t.current={sessionId:e,required:$c(o,rt)});let ct=_t.current.required,Ae=Fa(()=>n.replace(/\/+$/,""),[n]),et=rt?.gateways?.paypal?.providerObjectType??C,z=et??(R?"subscription":"order"),[Ht]=Zr(ka),k=rt?.gateways?.paypal?.approvalPresentation??g,q=di(Ht,k==="app_switch"?"app_switch":void 0,z),j=_p(et),y=Fa(()=>JSON.stringify([Ae,l,m,u??"",z,j,q,e,dt??""]),[Ae,l,m,u,dt,z,j,q,e]),oe=nt(y),h=oe.current!==y,$=nt(be),O=nt(null),[he,Se]=Zr([]),_=yr(T=>{$.current&&Se($e=>[...$e,`${new Date().toISOString().slice(11,23)} ${T}`])},[]);Wt(()=>{$.current=be,be&&_("debug:enabled"),O.current?.setEnabled(be)},[_,be]);let ut=nt(A),Mt=nt(X),At=nt(te),Fn=nt(D),Ge=nt(K),fr=nt(w),bt=nt(G),Er=nt(se),pt=nt(I),yt=nt(i),Rn=nt(Ue),Hn=nt(rt),Vn=nt(o),rn=nt(a),yn=nt(t),Xt=nt(null),Zt=nt(new Map),Nn=nt(new Map),xe=nt(!1),we=nt(e);we.current=e;let[tr]=Zr(Pi);Wt(()=>(xe.current=!0,()=>{xe.current=!1}),[]),Wt(()=>{ut.current=A},[A]),Wt(()=>{yt.current=i},[i]),Wt(()=>{Mt.current=X},[X]),Wt(()=>{At.current=te},[te]),Wt(()=>{Fn.current=D},[D]),Wt(()=>{Ge.current=K},[K]),Wt(()=>{fr.current=w},[w]),Wt(()=>{bt.current=G},[G]),Wt(()=>{Er.current=se},[se]),Wt(()=>{pt.current=I},[I]),Wt(()=>{Rn.current=Ue},[Ue]),Wt(()=>{Hn.current=rt},[rt]),Wt(()=>{Vn.current=o},[o]),Wt(()=>{rn.current=a},[a]),Wt(()=>{yn.current=t},[t]),Wt(()=>{Me.current=De},[De]),Wt(()=>{Ee&&ht.current?.focus()},[Ee,De]);let St=yr(()=>{window.setTimeout(()=>{ht.current?.focus()},0)},[]),Bn=yr(()=>{ze(!1),wt(T=>T+1)},[]),Qt=yr(()=>{vt(!1),(le.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??le.current)?.focus?.()},[]);Wt(()=>{!Ve||!Ce.current||(Ce.current=!1,Qt())},[Qt,Ve,De]);let gr=yr((T,$e)=>{let P=$e?.popupBlocked??so(T);P&&H.markBlocked();let ae=li("PayPal",P,Ht.inAppBrowser),Rt=fr.current;if(Rt){let xt=P&&Ht.inAppBrowser?new ra(ae,"api_error",{code:$e?.code??"paypal_popup_blocked"}):T;Rt("paypal",xt,$e);return}if(T instanceof ra&&T.code==="checkout_processing_timeout"){At.current?.(T.message);return}At.current?.(ae)},[H,Ht.inAppBrowser]),In=yr(T=>{let $e=je.current,P=it.current;$e===null||!P||(Z.log({...P,popupCapability:H.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:T}),Z.performance({...P,popupCapability:H.current(),stage:"overlay_return",durationMs:Z.elapsed($e),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:T}),je.current=null)},[H,Z]),_r=yr((T,$e,P)=>{let ae=it.current;In("overlay_timeout"),ae&&Z.error({...ae,popupCapability:H.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),gr($e,{...P,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:q,terminalReason:"overlay_timeout"}),vt(!0),Bn(),St()},[In,St,gr,H,q,Bn,Z]),hr=yr(()=>{H.markAvailable();let T=it.current;T&&(Q.current=T.attempt,Z.log({...T,popupCapability:H.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[H,Z]),En=yr(()=>!0,[]),mn=yr(()=>{let T=it.current;if(!T)return;let $e=je.current;Z.performance({...T,popupCapability:H.current(),stage:"overlay_return",durationMs:$e===null?0:Z.elapsed($e),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[H,Z]),{finishAttempt:_n,generationRef:Pr,invalidateAttempt:Un,isAttemptCurrent:zn,isAttemptInvalidated:qn,startAttempt:fn}=xa(_r,{onHandoffObserved:hr,defersMissingTerminal:En,onMissingTerminalDeferred:mn}),Ut=yr(()=>(vt(!1),fn("paypal")),[fn]),zt=yr(T=>{Un(T?.generation),T?.showRetry&&vt(!0),T?.remount&&Bn(),T?.focus!==!1&&St()},[St,Un,Bn]),Dn=T=>{let $e=Xt.current;return $e&&Nn.current.set(T,$e),T};Wt(()=>{oe.current!==y&&(oe.current=y,Ot.current=!1,kt.current=!1,ze(!1),Pt(!1),ce(!1),pt.current?.("loading"))},[y]),Wt(()=>{Ft(()=>Er.current?.(Ve&&!V))},[Ve,V]);let vn=kp(u);Wt(()=>{let T={attempt:Pr.current+1,inAppBrowser:Ht.inAppBrowser,appFamily:Ht.appFamily,popupCapability:H.current(),presentationMode:q},$e=()=>({...it.current??T,popupCapability:H.current()}),P={error:s=>Z.error({...s,...$e()}),log:s=>Z.log({...s,...$e()}),performance:s=>Z.performance({...s,...$e()}),terminal:s=>Z.terminal({...s,...$e()}),startTiming:Z.startTiming,elapsed:Z.elapsed},ae=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Rt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(_(`mount clientId=${ae} env=${u??"(unset)"}\u2192${vn??"live"} ccy=${m} sub=${R}`),_(`ua=${Rt.slice(0,80)}${Rt.length>80?"\u2026":""}`),!l){_("FAIL: clientId empty \u2014 gateway misconfigured"),ce(!0),P.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!le.current){_("FAIL: containerRef not attached");return}Kt.current=P.startTiming(),P.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let xt=!1,Vt=!1,ye=()=>xt||Vt,en=s=>{let c=xe.current,p=c?s:"torn_down";c&&_(`onError ignored reason=${p}`),tr.take(we.current)&&P.log({name:hi,stage:"provider_ready",reason:p,provider:"paypal",paymentMethodCategory:"paypal"})},Wr=()=>we.current===e?"stale_attempt":"session_changed",Mn=j?z:void 0,Pe,Tr=!1,Cn=()=>{Pe=vp(),Pe||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Tr=!0},sr=null,Po=!1,Gn=null,nr=!1,Mr=()=>{!Gn||nr||(nr=!0,Gn.close().catch(()=>{}))},jn=!1,Ar=!1,vr=le.current,lr=null,Yn=null,ke=[],An=null,$n=!1,ln=!1,cr=null,rr=s=>{if(!s||typeof s.getBoundingClientRect!="function")return"(no rect)";let c=s.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},Kr=s=>{if(!s)return"(empty)";try{let c=new URL(s,typeof window>"u"?"https://localhost":window.location.href),p=c.pathname.toLowerCase();return p.includes("checkcaptcha")||p.includes("captcha")?`CAPTCHA(${c.host}${p})`:p.includes("risk")||p.includes("challenge")?`RISK(${c.host}${p})`:p.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${p}`.slice(0,100)}catch{return s.slice(0,80)}},xr=s=>{let c=s.getAttribute("src"),p=s.getAttribute("srcdoc"),W=s.getAttribute("name"),qe=s.getAttribute("sandbox"),Y=[];return c&&Y.push(`src=${Kr(c)}`),p&&Y.push(`srcdoc[${p.length}ch]`),!c&&!p&&Y.push("src=(empty) srcdoc=(empty)"),W&&Y.push(`name=${W.slice(0,40)}`),qe!==null&&Y.push(`sandbox="${qe.slice(0,40)}"`),Y.join(" ")},vo=s=>{if(!(s instanceof HTMLIFrameElement))return"";try{let c=s.contentDocument;if(!c)return"cd=null";let p=c.body?.children.length??0,W=c.body?.innerHTML.length??0,qe=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${p}children,${W}ch] head[${qe}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},Fr=[],Co=s=>{if(ye())return;let c=s.message??String(s.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(_(`window:error ${c.slice(0,140)}`),Fr.push(c))},Hr=s=>{if(ye())return;let c=s.reason instanceof Error?s.reason.message:String(s.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(_(`window:rejection ${c.slice(0,140)}`),Fr.push(c))},Cr={value:0},eo=()=>{lr?.disconnect(),lr=null,Yn?.disconnect(),Yn=null;for(let s of ke.splice(0))clearTimeout(s);ln=!1,$n&&typeof window<"u"&&(window.removeEventListener("error",Co),window.removeEventListener("unhandledrejection",Hr)),$n=!1},to=()=>{if(!($n||ye()||jn)){if($n=!0,Fr.length=0,Cr.value=0,typeof window<"u"&&(window.addEventListener("error",Co),window.addEventListener("unhandledrejection",Hr)),typeof PerformanceObserver<"u")try{Yn=new PerformanceObserver(s=>{if(!ye())for(let c of s.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Cr.value+=1;let p=Math.round(c.duration);_(`net ${p}ms ${c.name.slice(0,90)}`)}}),Yn.observe({type:"resource",buffered:!0})}catch{}cr?.()}},qt=()=>{An&&(clearTimeout(An),An=null)},Jn=()=>{eo(),qt()},Vr={setEnabled:s=>{s?to():eo()}};O.current=Vr,$.current&&to();let On=Cp,Xn=s=>{if(ye()||On(s))return;let c=Qo(s)??s;Ft(()=>At.current?.(c))},Fe=(s,c)=>{if(xt||Po)return;Po=!0,Vt=!0,Jn(),Mr();let p=Dp({kind:s,generationActive:!0,automaticRetryAllowed:We,automaticRetryUsed:Ot.current});if(p.action==="retry"){Ot.current=!0,ze(!1),st(!1),Pt(!0),pt.current?.("retrying"),sr=setTimeout(()=>{xt||wt(W=>W+1)},Ap);return}if(ze(!1),st(!1),Pt(!1),ce(!0),p.action!=="ignore"){if(pt.current?.("exhausted"),p.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",c);return}if(p.report){let W=Cs({code:Kc(s,c),message:c},{inAppBrowser:Ht.inAppBrowser,handoffObserved:!1});W.popupBlocked&&H.markBlocked(),P.error({errorCode:W.popupBlocked?W.errorCode:p.report.errorCode,stage:p.report.stage,operationOutcome:p.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:W.terminalReason})}kt.current||(kt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Kc(s,c)))}};ce(!1);let Ln=async(s,c=Xt.current)=>{if(ye())return;let p=c?.sessionId??e;if(ut.current){await ut.current(s,{sessionId:p,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let W=P.startTiming();P.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let qe=()=>{P.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),P.performance({stage:"processing",durationMs:P.elapsed(W),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Y=mp({body:s,sessionId:p,nonce:c?.nonce??yn.current,accountPatch:c?.accountPatch,session:Hn.current,email:Vn.current}),U=await new Ts(Ae,{telemetry:!1}).processPayment(Y.userId,Y.params);if(U.ok){if(Vt||xt&&xe.current)return;qe(),P.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Ft(()=>Mt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ye())return;let S=await U.json().catch(()=>null),ne=qc(S),me=ne.message;qe(),U.status===400&&(typeof S?.declineCode=="string"||!Array.isArray(S?.fields))?P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):U.status===400||U.status===422?P.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):P.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Op(U.status),failureCategory:U.status>=500?"server_error":void 0}),Xn(me),Ft(()=>Fn.current?.(gn("paypal",me,{code:ne.code,declineCode:ne.declineCode})));return}catch(Y){if(ye())return;qe(),P.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let de=Pp(Y instanceof Error?Y.message:void 0);Xn(de),Ft(()=>Fn.current?.(gn("paypal",de)));return}},$t=()=>new ra("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Gr=s=>ye()?Promise.reject($t()):Promise.resolve(s),no=async s=>{if(s.ok){P.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Ft(()=>Mt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let c=await s.json().catch(()=>null),p=qc(c);P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Ft(()=>Fn.current?.(gn("paypal",p.message,{code:p.code,declineCode:p.declineCode})))},bo=()=>{let s=Xt.current;In("approved"),s&&(Zt.current.delete(s.surfaceKey),_n(s.generation)),Xt.current=null},Br=async s=>{if(ye())throw $t();Tr||Cn();let c=Xt.current,p=c?.sessionId??e,W=c?.nonce??yn.current;P.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let qe;try{qe=await new Ts(Ae,{telemetry:!1}).createSessionIntent(p,W??"",fp(Mn),{idempotencyKey:Pe})}catch(Y){throw P.error({...hp(Y,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Y}if(ye())throw $t();if(bp(qe))throw await no(qe.response),bo(),new ra("PayPal checkout already settled.","api_error",{code:Wc});if(qe.provider!=="paypal"||qe.providerObjectType!==z)throw new Error(s);return P.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),qe.providerObjectId},Dr=(s,c)=>{let p=c?.nonce??yn.current;if(!p)return;let W=c?.sessionId??e,qe=Ip(s);new Ts(Ae,{telemetry:!1}).reportSessionIntentDecline(W,p,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:qe}).catch(()=>{})},bn=De;_("loadScript:scheduled (deferred 1 tick)");let cn=null,v=setTimeout(()=>{if(xt){_("loadScript:skipped (cancelled before defer ran)");return}_("loadScript:start");let s=vn==="live"?"production":vn,c={};z==="subscription"?c={intent:"subscription",vault:!0}:z==="order"&&(c={intent:"capture"}),cn=Tp({clientId:l,currency:m,...c,...s?{environment:s}:{},...s==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let p=!1;cn.then(W=>{if(p=!0,_(`loadScript:resolved inactive=${ye()} ns=${!!W} buttons=${!!W?.Buttons}`),ye())return;if(!W?.Buttons){_("FAIL: namespace missing Buttons factory"),Fe("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}P.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),P.performance({stage:"provider_ready",durationMs:P.elapsed(Kt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),P.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let qe=async(b,M)=>{if(ye()||Me.current!==bn)return;let x=b.vaultSetupToken??b.subscriptionID??b.orderID??"",L=x?Nn.current.get(x):Zt.current.get(bn);if(!(!L||!zn(L.generation))&&_n(L.generation)){Nn.current.delete(x),Zt.current.delete(L.surfaceKey),In("approved");try{if(st(!0),Ft(()=>At.current?.(null)),!x)throw new ra("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let re=Rp({accountPatch:L.accountPatch,email:Vn.current,billingName:rn.current,session:Hn.current});if(wp(re))try{re=Sp(re,await M?.order?.get?.())}catch{}if((yt.current||ct)&&!jc(re.email)){let N=await Ke("PayPal",re);if(!N)return;re=N}jc(re.email)&&(L.accountPatch=kr({...L.accountPatch,...re}),await yt.current?.(re));let Oe=gp(x,Mn);await Ln(Oe,L)}catch(re){Xn(re instanceof Error?re.message:"PayPal capture failed.")}finally{ye()||st(!1)}}},Y=b=>{let M=dt?()=>Gr(dt):()=>Br(b);return async()=>Dn(await M())},de=W.Buttons({style:{layout:"horizontal",height:Ci,tagline:!1},...q==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(b,M)=>{if(ye()){await M.reject();return}Cn();let x=Rn.current,L={};if(x)try{let N=await x("paypal");if(ye()){await M.reject();return}if(!N.proceed){Xt.current=null,Zt.current.delete(bn),await M.reject();return}L={sessionId:N.sessionId,accountPatch:N.accountPatch,nonce:N.nonce}}catch(N){_(`onClick:runBeforeButtonClick rejected msg=${(N instanceof Error?N.message:String(N)).slice(0,120)}`),Xt.current=null,Zt.current.delete(bn),await M.reject();return}Ft(()=>bt.current?.("paypal"));let re=Ut(),Oe={generation:re,surfaceKey:bn,...L};Xt.current=Oe,Zt.current.set(bn,Oe),it.current={...T,attempt:re},await M.resolve(),P.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),P.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),je.current=P.startTiming()},createOrder:z==="order"?Y("Failed to create PayPal order."):void 0,createSubscription:z==="subscription"?Y("Failed to create PayPal subscription."):void 0,createVaultSetupToken:z==="setup_token"?async()=>Dn(await Br("Failed to create PayPal setup token.")):void 0,onApprove:qe,onCancel:()=>{if(ye())return;let b=Zt.current.get(bn)??Xt.current,M=b&&zn(b.generation)?yp(b.sessionId??e,Mn):null;b&&Zt.current.delete(b.surfaceKey),Xt.current=null,In("cancelled"),P.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ce.current=!0,zt({generation:b?.generation,remount:!0,focus:!1}),M&&Ft(()=>Ge.current?.(M))},onError:b=>{if(b instanceof ra&&b.code===Wc)return;let M=b instanceof Error?b.message:"PayPal failed to render.";if(ye()||Me.current!==bn){On(M)||en(Wr());return}if(jn){let x=Zt.current.get(bn)??Xt.current;if(!x||!zn(x.generation)){if(On(M)){!x&&!qn()&&_n();return}en(x||qn()?"stale_attempt":"no_current_attempt");return}if(_(`onError rendered=${jn} msg=${M.slice(0,120)}`),On(M)){_n(x.generation);return}let{errorCode:L,popupBlocked:re,providerDeclined:Oe,terminalReason:N}=Cs(b,{inAppBrowser:Ht.inAppBrowser,handoffObserved:Q.current===x.generation});if(re&&H.markBlocked(),In(N),Oe){P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:N}),Dr(b,x),Ft(()=>Fn.current?.(gn("paypal",M))),Zt.current.delete(x.surfaceKey),Xt.current=null,_n(x.generation);return}P.error({errorCode:L,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:N}),Zt.current.delete(x.surfaceKey),Xt.current=null,zt({generation:x.generation,remount:!0,showRetry:!0,focus:!0}),gr(b,{code:"paypal_runtime_failed",popupBlocked:re,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:q,terminalReason:N});return}_(`onError rendered=${jn} msg=${M.slice(0,120)}`),Fe(On(M)?"teardown":"pre_ready_callback",M)}}),U=de.isEligible();if(_(`isEligible=${U}`),P.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!U){ze(!1),Fe("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ar=!0,Gn=de,cr=()=>{if(!$n||ln||ye()||jn)return;ln=!0,_(`container:dims ${rr(vr)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(lr=new MutationObserver(M=>{if(!ye()){for(let x of M)if(x.type==="childList")x.addedNodes.forEach(L=>{if(!(L instanceof Element))return;let re=L.tagName.toLowerCase(),Oe=(L.getAttribute("title")??"").slice(0,40),N=re==="iframe"?` ${xr(L)}`:"";_(`child+ ${re}${Oe?` title="${Oe}"`:""}${N} dims=${rr(L)}`)});else if(x.type==="attributes"&&x.target instanceof Element){let L=x.target;if(L.tagName.toLowerCase()!=="iframe")continue;let re=x.attributeName;(re==="src"||re==="srcdoc")&&_(`attr~ iframe ${re}=${re==="srcdoc"?`[${(L.getAttribute("srcdoc")??"").length}ch]`:Kr(L.getAttribute("src"))} dims=${rr(L)}`)}}}),lr.observe(vr,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let b=M=>{if(ye()||jn)return;let x=vr.querySelectorAll("iframe"),L=typeof document<"u"&&"hasStorageAccess"in document;_(`watchdog:${M} container=${rr(vr)} children=${vr.childElementCount} iframes=${x.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${L} paypalNetRequests=${Cr.value}`),x.forEach((re,Oe)=>{let N=(re.getAttribute("title")??"").slice(0,40);_(` iframe[${Oe}] ${rr(re)}${N?` title="${N}"`:""} ${xr(re)}`);let fe=vo(re);fe&&_(` ${fe}`)}),Fr.length===0&&_(" (no PayPal/zoid window errors captured)")};ke.push(setTimeout(()=>b("3s"),3e3)),ke.push(setTimeout(()=>b("8s"),8e3)),ke.push(setTimeout(()=>b("15s"),15e3))},cr(),_("render:start");let ne=P.startTiming();An=setTimeout(()=>{ye()||jn||(_("watchdog:11s retryable render timeout"),Fe("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},xp);let me=de.render(vr);(async()=>{try{if(await me,_(`render:resolved inactive=${ye()}`),Jn(),ye()){Mr();return}jn=!0,ze(!0),Pt(!1),pt.current?.("ready"),P.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),P.performance({stage:"checkout_render",durationMs:P.elapsed(ne),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(b){let M=b instanceof Error?b.message:"PayPal failed to render.";_(`render:rejected msg=${M.slice(0,120)}`),Jn(),Fe(On(M)?"teardown":"render_rejected",M)}})()}).catch(W=>{let qe=W instanceof Error?W.message:"PayPal operation failed.";_(`provider:failed msg=${qe.slice(0,120)}`);let Y="script_rejected";p&&On(qe)?Y="teardown":p&&Ar&&(Y="render_rejected"),Fe(Y,qe)})},0);return()=>{xt=!0,clearTimeout(v),sr&&clearTimeout(sr),Jn(),O.current===Vr&&(O.current=null),Mr(),je.current=null,it.current=null}},[We,Ae,l,m,u,z,q,j,e,dt,De,Z,Ke,ct,_,In]);let Tn=be?Ms("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:V?"#fef2f2":"#f3f4f6",border:`1px solid ${V?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Ve} failed=${V})`,he.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return G&&!f?ke?Io("div",{children:xn}):null:Ms("div",{children:[xn,dt&&Io(ea,{identity:dt.identity,methodLabel:dt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:yt,onCancel:()=>yt(null)}),Ms("div",{"aria-hidden":Qe||dt?!0:void 0,style:Qe||dt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ci},children:[!Je&&!Qe&&Io("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),Io("div",{ref:ue,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ci,display:"flex",opacity:Je?1:0},"aria-busy":Te||fe},De)]},De),_e&&Io("button",{ref:Ct,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:On,style:xp,children:"Try PayPal again"})]})}function bi(e){return Io(Kc,{...e})}function Vc(e){return Io(Kc,{...e})}import{jsx as Gc,jsxs as Op}from"react/jsx-runtime";function ra({children:e,margin:t,icon:n=!0,styleOverride:o}){return Op("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...o??{}},children:[n&&Gc("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Gc("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{clearCachedInlineCheckout as Si,clearCachedInlineSession as As,hashCreateParams as Yc,legacyCachedSessionMatchesDraft as Jc,persistCachedInlineIdempotencyKey as wi,persistCachedInlineSession as ki,readCachedInlineIdempotencyKey as Xc,readCachedInlineSession as Zc,serializeCreateParams as Ba}from"@flopay/shared";var Qc=new Set;function Lp(){return globalThis.process?.env?.NODE_ENV==="production"}function ed(e,t){Qc.has(e)||Lp()||(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 Np,resolveBillingApiUrl as Up}from"@flopay/shared";import{useCallback as zp,useEffect as so,useMemo as qp,useRef as rd,useState as od}from"react";import{jsx as jp}from"react/jsx-runtime";function Ri({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=od(e instanceof Promise?null:e),[c,d]=od(t instanceof Promise||!t?null:t),R=rd(null),g=rd(null),y=ta(o),D=zp(j=>{Np(j)||y(j)},[y]);so(()=>{y({class:"lifecycle",name:"checkout.mount"})},[y]),so(()=>{i&&y({class:"lifecycle",name:"sdk.initialize.ready"})},[y,i]),so(()=>{if(i)return fn(i)?.subscribe?.(D)},[D,i]),so(()=>{if(!(!c||c===i))return fn(c)?.subscribe?.(D)},[D,i,c]),so(()=>{if(!i)return;let j=fn(i);return R.current=j?.beginCheckout()??j?.now()??0,j?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{j?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),so(()=>{let j=!1;return e instanceof Promise?e.then(K=>{j||s(K)},()=>{j||y({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{j=!0}},[y,e]),so(()=>{let j=!1;if(!t){d(null);return}return t instanceof Promise?t.then(K=>{j||d(K)},()=>{j||y({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):d(t),()=>{j=!0}},[y,t]),so(()=>{if(!i||g.current===i)return;g.current=i;let j=fn(i);j?.log({name:"checkout.rendered",stage:"checkout_render"}),y({class:"lifecycle",name:"checkout.rendered"}),j?.performance({stage:"checkout_render",durationMs:j.elapsed(R.current??0),durationMode:"machine"})},[y,i]);let ee=Up(n?.billingApiUrl),ae=qp(()=>({flopay:i,paypalFlopay:c,billingApiUrl:ee,emitInstrument:y}),[i,c,ee,y]);return jp(pr.Provider,{value:ae,children:a})}import{markSessionRecentlyCompleted as oa,wasSessionRecentlyCompleted as xs}from"@flopay/shared";async function Ii(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{beginSavedCardChallengeTelemetry as $p,completeSavedCardNextAction as Wp,loadFloPay as ad,PaymentAPI as Oa,runSavedCardChallenge as Hp}from"@flopay/js";import{classifyPaymentRejection as Kp,FloPayError as At,isAuthorizationOnlySession as Vp,isMerchantAuthRequired as Bs,isMountableVaultBlock as Gp,isSetupIntentClientSecret as Yp,MERCHANT_AUTH_REQUIRED_CODE as Jp,normalizeCheckoutFailureOutcome as id}from"@flopay/shared";var Na="card";async function Xp(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:o??null}}async function Zp(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function aa(e){return new At("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Qp(){return new At("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function La(e,t){return Object.assign(e,{checkoutMethod:t})}function Yr(e,t){let n=e instanceof At?e:new At(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 Yr(n,t)}}function ld(e){return!e?.type||!e.threeDSecureToken||Bs(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function cd(e){return Hp(e)}function Ua(e,t,n,o=!0){let a={release:()=>{}};if(!o)return a;try{let i=new Oa(e),s=$p(i,t,n);return s?{telemetry:s,release:()=>{setTimeout(()=>{try{i.destroy()}catch{}},0)}}:a}catch{return a}}async function ia(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new Oa(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,d;try{d=await Wp({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:g=>Or({type:g.declineReason??"authorization_declined",gatewayErrorCode:g.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(g){if(a.aborted||g instanceof Error&&g.name==="AbortError")throw g instanceof At&&g.code==="three_ds_aborted"?g:aa(g);if(!(g instanceof At)||g.code!=="three_ds_timeout"&&g.code!=="checkout_processing_timeout")throw g;try{d=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:c,timeoutMs:5e3,signal:a})}catch(D){if(a.aborted)throw aa(D);if(!(D instanceof At)||D.code!=="checkout_processing_timeout")throw D}let y=d&&ro(d,t.session);if(!Vr(y)&&y?.status!=="expired"){if(t.telemetry){let D=new Oa(n);try{D.reportThreeDsAbandoned(o)}finally{D.destroy()}}throw Qp()}}let R=d&&ro(d,t.session);if(!Vr(R))throw Xo(R);return{...Kr(R,o),checkoutMethod:"card"}}function dd(e){return new At("This payment needs your card details. Please complete your payment below.","authentication_error",{code:Jp,...e===void 0?{}:{statusCode:e}})}function Or(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if(Bs(e))return La(dd(),o);let a=e?.message??t,i=Zo(a)??a,s=La(new At(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&&(s.orderId=e.orderId),s}function Fs(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ei(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ud(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ei(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let c of i)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||Ei(c)))return c;let s=a.gateways;if(s&&typeof s=="object"){let c=s.stripe;if(c&&typeof c=="object"){let d=c,R=[d.stripeClientSecret,d.clientSecret];for(let g of R)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Ei(g)))return g}}}}async function ey({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 c=(await new Oa(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ei(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function sa({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:s}){let c=e.replace(/\/+$/,""),d=t??n.id,R=o??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",y=n.customer?.email??n.accountData?.email??"",D=n.customer?.firstName??n.accountData?.firstName??"",ee=n.customer?.lastName??n.accountData?.lastName??"",ae=n.customer?.country??n.accountData?.country??void 0,j=n.customer?.zip??n.accountData?.zip??void 0,C=await new Oa(c,s===!1?{telemetry:!1}:void 0).processPayment(g,{sessionId:d,nonce:R,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:g,email:y,firstName:D,lastName:ee,country:ae,zip:j},returnUrl:i??Fs(n)});if(C.ok){let de=typeof C.json=="function"?await C.json().catch(()=>null):null;if(Vp(n)||de?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof de?.paymentId=="string"?de.paymentId:n.paymentId,sessionId:typeof de?.sessionId=="string"?de.sessionId:d,authorizationExpiresAt:typeof de?.authorizationExpiresAt=="string"?de.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:_a(a),checkoutMethod:sd(a,n)}};let I=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...I?{paymentIntentId:I}:{},paymentMethodId:_a(a),checkoutMethod:sd(a,n)}}}let fe;try{fe=await C.json()}catch(de){throw new At("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:C.status,cause:de})}if(Bs(fe))throw La(dd(C.status),"card");if(fe?.type==="3ds_required"&&typeof fe.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:fe.nextActionRedirectUrl};if(fe?.type==="paypal_redirect_required"||fe?.type==="3ds_required"){let de=ud(fe);if(!de)throw new At("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:C.status});return{type:fe.type,threeDSecureToken:de,paymentMethodId:fe.paymentMethodId}}if(fe?.gatewayErrorCode==="authentication_required"){let de=await ey({billingApiUrl:c,sessionId:d,nonce:R,responseJson:fe});if(de)return de;throw La(new At("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw ty(fe,C.status)}function ty(e,t){let n=new At(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(n,{telemetryOutcome:Kp(t,e)})}async function _i(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:d,signal:R}){let g=t?.getRawProvider();if(!g)throw Yr(new At("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw La(new At("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let y=Yp(e.threeDSecureToken),D=null,ee=e.paymentMethodId,ae=await Da(()=>Xp(g,e.threeDSecureToken,y),"card");if(ae){if(ae.error)throw Yr(new At(ae.error.message??`Failed to retrieve 3DS ${y?"setup":"payment"} status.`,"api_error",{code:ae.error.code}),"card");let K=ae.intent;!ee&&K?.payment_method&&(typeof K.payment_method=="string"?ee=K.payment_method:"id"in K.payment_method&&(ee=K.payment_method.id??void 0))}let j=ee?await Da(()=>Zp(g,e.threeDSecureToken,{payment_method:ee,return_url:c??Fs(s)??window.location.href},y),"card"):null;if(j){if(j.error)throw Yr(new At(j.error.message??"3DS authentication failed.","api_error",{code:j.error.code}),"card");D=j.intent}else{let K=await Da(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(K.error)throw Yr(new At(K.error.message??"3DS authentication failed.","api_error",{code:K.error.code}),"card");D=(y?K.setupIntent:K.paymentIntent)??null}if(D&&(D.status==="requires_capture"||D.status==="succeeded"||D.status==="processing")){let K=await sa({billingApiUrl:a,sessionId:i,session:s,telemetry:d,tokenizedData:{id:D.id,type:"card",threeDSecureActionResultTokenId:D.id},returnUrl:c});return K.type==="success"?{...K.result,paymentIntentId:K.result.paymentIntentId??D.id,paymentMethodId:K.result.paymentMethodId??ee}:K.type==="next_action_required"?ia(K,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:R}):_i(K,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:d,signal:R})}throw Yr(new At("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let y=(n??t)?.getRawProvider();if(!y)throw Yr(new At("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:ee}=await Da(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(ee)throw Yr(new At(ee.message??"PayPal authorization failed.","api_error",{code:ee.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:D}=await Da(()=>y.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Fs(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(D)throw Yr(new At(D.message??"PayPal authorization failed.","api_error",{code:D.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new At("Unsupported payment redirect state.","api_error")}function za(e){if(e instanceof At){let o=Zo(e.message);return o&&o!==e.message?Object.assign(new At(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=Zo(t)??t;return new At(n,"api_error")}function Ds(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=Gp(e.data.session?.vault)||ko(e.data.session);if(!t&&!n&&!o)throw new At("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&&ko(t)?"card":void 0}async function Os({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:o,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,c]=await Promise.all([ad(e,{billingApiUrl:n,locale:o,telemetry:a}),i?ad(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(R=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",R),null)):Promise.resolve(null)]);if(!s)throw new At("The payment provider did not initialize.","authentication_error");let d=null;return i?d=c:t&&(d=s),{flopay:s,paypalFlopay:d}}import{PaymentAPI as la,PciVaultCardCapture as hy,toStripeAppearance as Py}from"@flopay/js";import{buildCardFieldLabelsPayload as vy,buildCheckoutProcessMetadata as Cy,buildProcessPaymentAvsAccount as by,buildWalletSheetWindowMessage as Sy,buyerEmailRequiredPrompt as wy,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as ky,COUNTRY_OPTIONS as Ry,cardFieldsInstrumentSource as Iy,classifyPaymentRejection as Ey,clearStripePayPalReturn as _y,computeVaultCardThemeColors as Ty,darkenHex as My,denyPaymentPermissionToNewFrames as Ay,FloPayError as Rr,filterStripeMethodsByCountryGate as xy,getPostalCodeExample as Fy,getPostalCodeLabel as Vs,getStateFromPostalCode as By,getStateLabel as Us,getStateOptions as Dy,getStripeMethodDisplayName as Wa,hasMatchingStripePayPalReturn as Oy,invokeMerchantCallback as vd,isAuthorizationOnlySession as zs,isAVSFieldVisible as Xt,isCardFormFirst as Ly,isMountableVaultBlock as Ny,isPostalCodeSupported as Uy,isSettledSessionIntent as Fi,isSetupIntentClientSecret as qs,isValidEmail as kn,isValidPostalCode as zy,isWalletSheetRefusedForWindowSize as qy,keyPaymentMethodOrder as jy,needsStripeMethodExplicitConfirm as Cd,normalizeBeforeButtonClickError as bd,normalizeCheckoutFailureOutcome as $y,partitionStripeMethods as Wy,placePaymentMethodGroups as Sd,randomUuidV4 as Hy,readMatchingStripePayPalContinuation as Ky,readStripeRedirectParams as Bd,resolveAVSConfig as Vy,resolveButtonsLayoutTheme as Gy,resolveSetupFutureUsage as Dd,resolveTheme as Yy,resolveVaultMountOptions as js,STRIPE_PAYPAL_RESUME_KEY as Jy,derivePrimaryTileStyle as Xy,shouldPreferWalletPopup as wd,stripeExpressMethodToOptionKey as Zy,stripeRedirectReturnUrl as Od,toCssWeight as Qy,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as Ld}from"@flopay/shared";import{ExpressCheckoutElement as Nd,PaymentElement as em,useElements as Xs,useStripe as Zs}from"@stripe/react-stripe-js";import ja,{useCallback as Be,useContext as ca,useEffect as Xe,useLayoutEffect as tm,useMemo as vt,useRef as q,useState as oe}from"react";function Eo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ti(e,t){if(e)return{error:n=>e.error(Eo(t,n)),log:n=>e.log(Eo(t,n)),performance:n=>e.performance(Eo(t,n)),terminal:n=>e.terminal(Eo(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}import{useEffect as ny,useId as ry,useRef as pd}from"react";import{Fragment as iy,jsx as yd,jsxs as sy}from"react/jsx-runtime";var md="More payment options",oy={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ay={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Ls({label:e,open:t,showLink:n,onOpen:o,color:a,fontFamily:i,children:s}){let c=ry(),d=pd(null),R=pd(!1);return ny(()=>{t&&R.current&&d.current?.focus()},[t]),sy(iy,{children:[!t&&n&&yd("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":c,onClick:()=>{R.current=!0,o()},style:{alignSelf:"center",margin:0,padding:"0.25rem 0",border:0,background:"none",cursor:"pointer",color:a,fontFamily:i,fontSize:"0.9rem",fontWeight:500,textDecoration:"underline",textUnderlineOffset:"0.2em"},children:e}),yd("div",{id:c,ref:d,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?ay:oy,children:s})]})}import{jsx as fd}from"react/jsx-runtime";var ly=["first","second","third","fourth"];function Ns({rows:e,borderRadius:t}){return fd("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:ly.slice(0,Math.max(1,e)).map(n=>fd("div",{style:{height:wo,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},n))})}import{PaymentAPI as cy}from"@flopay/js";import{DEFAULT_PAYMENT_METHOD_ORDER as dy,resolveDefaultPaymentMethodLayout as uy}from"@flopay/shared";import{useEffect as py,useState as yy}from"react";var my=1500,gd=new Set;function hd(e){for(let t of e)gd.has(t)||(gd.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function fy(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 gy={order:[...dy],moreOptions:[]};function Pd({rules:e,sessionId:t,nonce:n,billingApiUrl:o,waitForSession:a}){let i=fy(e),[s,c]=yy(null);return py(()=>{if(i===void 0||a)return;let d=JSON.parse(i),R=!1,g=ae=>{R||(R=!0,c(ae))},y=()=>g(uy(d));if(!t||!n||!o){y();return}let D=new AbortController,ee=setTimeout(()=>{y(),D.abort()},my);return new cy(o,{telemetry:!1}).resolvePaymentMethodLayout(t,n,d,{signal:D.signal}).then(ae=>{if(!ae){y();return}R||hd(ae.warnings),g({order:ae.order,moreOptions:ae.moreOptions})}).catch(y).finally(()=>clearTimeout(ee)),()=>{R=!0,clearTimeout(ee),D.abort()}},[i,t,n,o,a]),i===void 0?gy:s}import{darkenHex as Wd}from"@flopay/shared";import{Fragment as jn,jsx as l,jsxs as Le}from"react/jsx-runtime";var Lr="flopay_stripe_resume",kd="flopay_wallet_resume",Ud="fw1",nm="fw2",zd=300*1e3,rm=900,om="express_checkout_click_timeout",am=25e3,im=25e3,sm=1e4,Ir={provider:"paypal",paymentMethodCategory:"paypal"},lm="x-flopay-process-result-source",cm="status";async function dm(e,t,n){try{let o=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(o?.status==="complete")return null;if(o?.status==="authorized")return{status:"authorized",paymentId:o.paymentId,sessionId:o.id||t,authorizationExpiresAt:o.authorizationExpiresAt}}catch{}}var Mi={},$a=class{constructor(t){this.reason=t}};function um(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function rn(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function Qs(e){return`${nm}:${e}`}function Ai(e){return rn(Qs(e))}function xi(e,t){if(typeof window>"u")return null;let n=Qs(e);try{let o=localStorage.getItem(n);if(!o)return null;let a=JSON.parse(o);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>zd||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Ai(e),null):a}catch{return Ai(e),null}}function pm(e){return rn(Qs(e.sessionId),e)}function Rd(e,t,n){let o=xi(e,t);return!o||o.clientSecret!==n?!1:Ai(e)}function $s(e,t,n){if(typeof window>"u")return;xi(e,t)?.clientSecret===n&&Ai(e)}function ym(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ws(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let o=n?e.status==="succeeded":Ea(e.status),a=ym(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)},sm),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function mm(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function 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 la(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 Hs=Jy,qa=new Map,fm=250,Ed="Just a moment \u2014 we are finalizing your order. Please press pay again.",gm="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function el(e,t,n,o){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...o?{terminalReason:o}:{}})}async function Di({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new la(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function hm(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),s=i.firstName?i:Ta(o?.name);return kr({email:kn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Pm({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=jd({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return kn(s.email)?s:i(a,s)}var Ha=180,_d=`flopay-card-enter ${Ha}ms cubic-bezier(0, 0, 0.2, 1) both`,Td=`flopay-card-exit ${Ha}ms cubic-bezier(0.4, 0, 0.2, 1) both`,vm=`flopay-buttons-enter ${Ha}ms cubic-bezier(0, 0, 0.2, 1) both`,Cm=`flopay-buttons-exit ${Ha}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function bm(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function tl(e){return Xy(e)}var Sm={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function wm(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var Gs={width:"100%",minHeight:wo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Md(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ys(e){return e==="paypal"?"PayPal":Wa(e)}function km(e){let t=Fy(e);return`Enter a valid ${Vs(e)}${t?` (e.g. ${t})`:""}`}function Rm(e,t,n){let o=Uy(e),a=t.trim(),i=n&&o,s=i&&!a,c=i&&!!a&&!zy(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:c}}function Im(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!kn(n);return{required:t,empty:o,malformed:a,value:n}}function Em(e){return typeof e=="number"?`${e}px`:e}var _m=["number","expiry","cvv","name"];function Tm(e){if(e===null||typeof e!="object")return null;let t={};for(let n of _m){let o=e[n];typeof o=="string"&&(t[n]=o)}return JSON.stringify(t)}function nl(e){return l(xm,{...e})}function Ad({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:c,onDecline:d,onTechnicalFailure:R,runBeforeButtonClick:g,billingName:y,onBuyerIdentityReady:D,onLoadStateChange:ee,placeholderBorderRadius:ae,popupCapabilityOwner:j,externalTelemetryContext:K,presentationMode:C}){let fe=ao(),{emitInstrument:de}=ca(pr),I=Zs(),He=Xs(),X=vt(()=>Ti(fn(fe),K),[K,fe]),[Ne,at]=oe("loading");Xe(()=>{ee?.(Ne)},[Ne,ee]);let[pt,Ie]=oe(!1),Nt=q(!1),Dt=!kn(n?.trim())||!y?.trim(),{request:ke,collect:Ye,finish:it}=Qo(),st=q(!1),Ee=q(null),te=q(null),[ue,$t]=oe(0),[ze,lt]=oe(!1),re=q(!1),Me=q(new Map),{startAttempt:Ze,finishAttempt:V,invalidateAttempt:Ct,isAttemptInvalidated:be,isAttemptCurrent:Je,generationRef:Ue}=xa((pe,Te,ct)=>{R?.(pe,Te,{...ct,popupBlocked:ct?.popupBlocked??to(Te),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:C,terminalReason:"overlay_timeout"}),lt(!0),$t(dt=>dt+1)},{onHandoffObserved:()=>{j.markAvailable(),X?.log({name:"provider.popup.opened",stage:"overlay_open",...Ir,attempt:Ue.current})}});Xe(()=>{ze&&te.current?.focus()},[ze,ue]);let Qe=Be(()=>{$t(pe=>pe+1)},[]),bt=Be((pe,Te,ct)=>{Ct(ct),R?.("paypal",pe,{code:Te,popupBlocked:to(pe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:C}),lt(!0),Qe()},[Ct,R,C,Qe]),De=Be(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);Xe(()=>{re.current&&(re.current=!1,De())},[De,ue]);let Rt=Be(()=>{lt(!1),i?.(null),De()},[De,i]);Xe(()=>{if(!I||st.current)return;let[pe,Te,ct]=Bd();if(!pe||!Te)return;let dt=Ky(Te);if(!dt)return;st.current=!0;let Ke=!0,yt=qa.get(Te);yt||(yt=ct==="failed"?Promise.resolve(null):Promise.resolve().then(()=>I.retrievePaymentIntent(Te)),qa.set(Te,yt));let mt={accountPatch:dt.accountPatch,sessionId:dt.sessionId,nonce:dt.nonce},wt=()=>{X?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Ir,requestCategory:"provider_sdk"})};return X?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Ir}),(async()=>{try{Ie(!0);let je=await yt;if(!Ke)return;if(je?.error){qa.delete(Te),wt(),i?.(je.error.message??"Failed to retrieve PayPal payment status.");return}if(_y(),qa.delete(Te),ct==="failed"){let $="PayPal payment was declined. Please try again.";X?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}),i?.($),d?.(mn("paypal",$));return}let et=je?.paymentIntent;if(et&&et.id!==pe){wt(),i?.("Failed to match the returned PayPal payment.");return}if(et&&(et.status==="requires_capture"||et.status==="succeeded")){let $=typeof et.payment_method=="string"?et.payment_method:et.payment_method?.id;a({id:$??et.id,type:"card",threeDSecureActionResultTokenId:et.id,isPaypal:!0},{...mt,presentationMode:"redirect"})}else{let $="PayPal payment was not completed. Please try again.";X?.terminal({outcome:et?.status==="canceled"?"payment_cancelled":"payment_declined",...Ir,terminalReason:et?.status==="canceled"?"cancelled":"provider_declined"}),i?.($),d?.(mn("paypal",$))}}catch(je){if(!Ke)return;qa.delete(Te),wt(),i?.(je instanceof Error?je.message:"Failed to complete PayPal payment.")}finally{Ke&&Ie(!1)}})(),()=>{Ke=!1,st.current=!1}},[I,a,i,d,X]);let Ae=Be(async(pe=!1)=>{let Te=g?await g("paypal"):{proceed:!0};if(!Te.proceed)return Me.current.delete(ue),!1;let ct=Ze("paypal");return Me.current.set(ue,{generation:ct,accountPatch:Te.accountPatch,sessionId:Te.sessionId,nonce:Te.nonce}),lt(!1),X?.log({name:`provider.${pe?"redirect.started":"handoff.requested"}`,stage:pe?"redirect":"overlay_open",...Ir,attempt:ct}),c?.("paypal"),!0},[c,X,g,Ze,ue]),_e=Be(async pe=>{if(s||pt||!await Ae()){pe.reject();return}pe.resolve()},[s,Ae,pt]),St=Be(async pe=>{if(!I||!He)return;let Te=Me.current.get(ue);if(Te&&!Je(Te.generation)){Me.current.delete(ue);return}if(!Te&&be()||Te&&!V(Te.generation))return;Te||V();let ct=Te??null;if(Me.current.delete(ue),!ct&&g){let qe=await g("paypal");if(!qe.proceed){pe.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ct={accountPatch:qe.accountPatch,sessionId:qe.sessionId,nonce:qe.nonce}}let dt=ct?.sessionId??e,Ke=ct?.nonce??t,yt=await Pm({event:pe,prepared:ct,email:n,billingName:y,methodLabel:"PayPal",collect:Ye});if(!yt){pe.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let mt=yt.email,wt={...ct?.accountPatch,...kr(yt,!0)};try{if(Ie(!0),i?.(null),!dt||!kn(mt))throw new Error("Missing sessionId or email for PayPal payment");await D?.(yt);let qe=I.createPaymentMethod,{error:je,paymentMethod:et}=await qe({type:"paypal"});if(je){bt(je,"stripe_paypal_create_payment_method_failed",Te?.generation),pe.paymentFailed({reason:"fail"});return}let $=await Bi(o,de,dt,Ke??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:et?.id??null,intentKind:"payment"});if(Fi($)){pe.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:wt,paymentMethodCategory:"paypal",presentationMode:C,sessionId:dt,nonce:Ke,settledProcessResponse:$.response});return}if($.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let hn=$.clientSecret,w={return_url:Od()};if(et?.id&&(w.payment_method=et.id),!rn(Hs,{clientSecret:hn,sessionId:dt,nonce:Ke,accountPatch:wt})&&C==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:Y,paymentIntent:W}=await I.confirmPayment({clientSecret:hn,confirmParams:w,redirect:"if_required"});if(Y){if(rn(Hs),ci(Y)){let f=Y.message??"Your payment was declined.";X?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}),i?.(f),d?.(mn("paypal",f,{code:Ho(Y),declineCode:bs(Y)})),await Di({billingApiUrl:o,sessionId:dt,nonce:Ke,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ho(Y)??"provider_declined"}})}else bt(Y,"stripe_paypal_confirm_failed",Te?.generation);return}rn(Hs);let J=typeof W?.payment_method=="string"?W.payment_method:W?.payment_method?.id;a({id:J??W?.id,type:"card",threeDSecureActionResultTokenId:W?.id,isPaypal:!0},{accountPatch:wt,paymentMethodCategory:"paypal",presentationMode:C,sessionId:dt,nonce:Ke});return}catch(qe){bt(qe,"stripe_paypal_failed",Te?.generation)}finally{Ie(!1)}},[I,He,e,t,n,y,Ye,D,o,de,a,i,d,g,bt,V,Je,be,X,C,ue]),Ot=Be(async()=>{if(!(Nt.current||s||pt||!I||!He)){Nt.current=!0,Ie(!0);try{if(!await Ae(!0))return;await St({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Nt.current=!1,Ie(!1)}}},[He,St,s,Ae,I,pt]),It=C==="redirect"?l("button",{type:"button",disabled:s||pt,onClick:()=>{Ot()},style:{width:"100%",minHeight:wo,border:"1px solid #d1d5db",borderRadius:ae??8,background:"#ffc439",color:"#111827",cursor:s||pt?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):l(Nd,{onReady:pe=>at(Ss(pe,["paypal"])),onLoadError:()=>{at("load_error"),el(X,"paypal","paypal","provider_error")},onClick:_e,onConfirm:St,onCancel:()=>{let pe=Me.current.get(ue);Me.current.delete(ue),X?.terminal({outcome:"payment_cancelled",...Ir,terminalReason:"cancelled",...pe?{attempt:pe.generation}:{}}),Ct(pe?.generation),lt(!1),re.current=!0,Qe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Dt,emailRequired:Dt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ue),G=Le(jn,{children:[Le("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[ze&&l("button",{ref:te,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Rt,style:Gs,children:"Try PayPal again"}),ke&&l(ea,{identity:ke.identity,methodLabel:ke.methodLabel,onComplete:it,onCancel:()=>it(null)},ke.id),l("div",{style:{display:ke?"none":void 0},children:It})]}),pt&&!ke&&l(Dr,{status:"processing"})]});return C==="redirect"?G:l(ws,{state:Ne,placeholderTestId:"flopay-paypal-placeholder",borderRadius:ae,children:G})}function Ks(e){return e==="apple_pay"||e==="google_pay"}var Mm=200;function Am({active:e}){return tm(()=>e?Ay(document):void 0,[e]),null}function xd({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:c,onButtonClick:d,onDecline:R,onTechnicalFailure:g,runBeforeButtonClick:y,billingName:D,onBuyerIdentityReady:ee,onLoadStateChange:ae,placeholderBorderRadius:j,popupCapabilityOwner:K,externalTelemetryContext:C}){let fe=ao(),{emitInstrument:de}=ca(pr),I=Zs(),He=Xs(),X=vt(()=>Ti(fn(fe),C),[C,fe]),[Ne,at]=oe("loading");Xe(()=>{ae?.(Ne)},[Ne,ae]);let[pt,Ie]=oe(!1);Xe(()=>{lt.current=pt},[pt]);let Nt=q(!kn(n?.trim())||!D?.trim()).current,{request:Dt,collect:ke,finish:Ye}=Qo(),it=q(null),st=q(null),[Ee,te]=oe(0),[ue,$t]=oe(()=>wd()),ze=q(ue),lt=q(!1),[re,Me]=oe(!1),[Ze,V]=oe(()=>xi(e,t)?"blocked":"idle"),[Ct,be]=oe("google_pay"),Je=q(null),Ue=q(!0),Qe=q(!1),bt=q("google_pay"),De=q("google_pay"),Rt=q(null),Ae=q(null),_e=q(new Set),St=q(null),Ot=q(null);Xe(()=>(Ue.current=!0,()=>{Ue.current=!1;for(let f of _e.current)window.clearTimeout(f);_e.current.clear()}),[]);let It=q(new Map),{startAttempt:G,finishAttempt:pe,invalidateAttempt:Te,isAttemptInvalidated:ct,isAttemptCurrent:dt,generationRef:Ke}=xa((f,ie,H)=>{g?.(f,ie,{...H,popupBlocked:H?.popupBlocked??to(ie),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),be(f),Me(!0),te(Se=>Se+1)},{onHandoffObserved:f=>{Ot.current=Ke.current,K.markAvailable(),X?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ke.current,...f==="apple_pay"||f==="google_pay"?{walletType:f}:{}})},defersMissingTerminal:Ks,onMissingTerminalDeferred:(f,ie)=>{let H=X?.now()??globalThis.performance?.now()??Date.now(),Se=St.current,we=Se?.generation===ie?Se.startedAt:H;X?.performance({stage:"overlay_return",durationMs:Math.max(0,H-we),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:ie,...Ks(f)?{walletType:f}:{}}),X?.flush?.().catch(()=>{})}});Xe(()=>{re&&st.current?.focus()},[re,Ee]);let yt=q(0),mt=q(!1),wt=Be(()=>{if(yt.current>0){mt.current=!0;return}te(f=>f+1)},[]),qe=Be(()=>{yt.current-=1,!(yt.current>0||!mt.current)&&(mt.current=!1,Ue.current&&te(f=>f+1))},[]),je=Be((f,ie,H,Se,we=!1)=>{Te(Se),g?.(f,ie,{code:H,popupBlocked:to(ie),telemetryReported:we,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),be(f),Me(!0),wt()},[Te,g,wt]),et=Be(f=>{X?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...Ks(f)?{walletType:f}:{}}),g?.(f,new Error("The wallet click was not ready within the time the wallet allows."),{code:om,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),be(f),Me(!0)},[g,X]),$=Be(()=>{window.setTimeout(()=>{(it.current?.querySelector("iframe")??it.current)?.focus()},0)},[]);Xe(()=>{Qe.current&&(Qe.current=!1,$())},[$,Ee]);let hn=Be(()=>{Me(!1),c?.(null),$()},[$,c]),w=Be(()=>{Je.current?.()},[]);Xe(()=>{let f=null,ie=()=>{f=null;let Se=wd();Se!==ze.current&&(ze.current=Se,$t(Se),!lt.current&&!dt(Ke.current)&&wt())},H=()=>{f!==null&&window.clearTimeout(f),f=window.setTimeout(ie,Mm)};return window.addEventListener("resize",H),()=>{window.removeEventListener("resize",H),f!==null&&window.clearTimeout(f)}},[Ke,dt,wt]),Xe(()=>{let f=xi(e,t);if(!f)return;let ie=!1,H=!1,Se=async()=>{if(!H){H=!0,ie||V("checking");try{let we=await Id(I,f.clientSecret,_e.current);if(ie)return;let E=Ws(we,f.providerObjectId,qs(f.clientSecret));if(E.kind==="confirmed"){if(!Rd(e,t,f.clientSecret))return;Je.current=null,V("idle"),s({id:E.paymentMethodId,type:"card",threeDSecureActionResultTokenId:E.intentId},{...f.accountPatch?{accountPatch:f.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(E.kind==="terminal"){$s(e,t,f.clientSecret),Je.current=null,V("idle"),be(f.paymentMethodType),Me(!0),wt();return}V("blocked")}catch{ie||V("blocked")}finally{H=!1}}};return Je.current=Se,V("blocked"),()=>{ie=!0,Je.current===Se&&(Je.current=null)}},[t,s,wt,e,I]);let m=Be(async f=>{let ie=!1,H=!1,Se=Ve=>{ie||H||(ie=!0,f.paymentFailed({reason:"fail",...Ve?{message:Ve}:{}}))};if(!I||!He){Se();return}let we=It.current.get(Ee);if(we&&!dt(we.generation)){It.current.delete(Ee),Se();return}if(!we&&ct()){Se();return}if(we&&!pe(we.generation)){Se();return}we||(pe(),mt.current=!1);let E=f.expressPaymentType??we?.method??bt.current,tt=we??null,Ht=Md(E),Ut;E==="apple_pay"?Ut="apple_pay":E==="google_pay"&&(Ut="google_pay");let Dn=we?.generation??Ke.current,he=X,Er=he?.now()??globalThis.performance?.now()??Date.now(),cn=new AbortController,dn=!1,nt=!1,xt=null,In=e,En="processing",_n="other",Cn="provider_runtime",bn,Kt=new Promise((Ve,ye)=>{bn=ye}),zt=window.setTimeout(()=>{dn=!0,cn.abort(),bn(Mi)},am),Zt=async(Ve,ye,ar)=>{En=Ve,_n=ye,Cn=ye==="intent_create"||ye==="session_claim"?"transport_error":"provider_runtime";let Ft=he?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([ar,Kt])}finally{let Tn=he?.now()??globalThis.performance?.now()??Date.now();he?.performance({stage:Ve,durationMs:Math.max(0,Tn-Ft),durationMode:"machine",requestCategory:ye,paymentMethodCategory:"wallet",provider:"stripe",...dn?{statusClass:"timeout"}:{}})}};try{if(Ie(!0),c?.(null),!tt&&y){let se=await Zt("processing","other",y(Ht));if(!se.proceed){Se();return}tt={accountPatch:se.accountPatch,sessionId:se.sessionId,nonce:se.nonce}}let Ve=tt?.sessionId??e;In=Ve;let ye=tt?.nonce??t,ar=Rt.current??tt?.accountPatch,Ft=jd({event:f,fallbackEmail:ar?.email??n,fallbackName:[ar?.firstName,ar?.lastName].join(" ").trim()||D});if(!kn(Ft.email)){Se("Buyer details are required."),ke(Ys(E),Ft).then(se=>{se&&(Rt.current=se)});return}Rt.current=null;let Tn={...tt?.accountPatch,...kr(Ft,!0)};await Zt("processing","session_claim",Promise.resolve(ee?.(Ft)));let{error:On}=await Zt("tokenization","provider_sdk",He.submit());if(On){Se(),je(E,On,"stripe_wallet_submit_failed",we?.generation);return}if(!Ve)throw new Error("Missing sessionId or email for payment.");let ir={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:E,paymentMethodId:null,intentKind:a},Ln=JSON.stringify({sessionId:Ve,nonce:ye??"",request:ir}),_r=Ae.current,fr=_r?.retryIdentity===Ln?_r.authorizationAttemptId:Hy();Ae.current={authorizationAttemptId:fr,retryIdentity:Ln};let un=await Zt("processing","intent_create",Bi(o,de,Ve,ye??"",{...ir,authorizationAttemptId:fr},{signal:cn.signal}));if(Fi(un)){Se(),s({type:"card",paymentMethodType:E},{accountPatch:Tn,paymentMethodCategory:"wallet",sessionId:Ve,nonce:ye,settledProcessResponse:un.response});return}if(un.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let pn=un.clientSecret,Mn=pm({createdAt:Date.now(),sessionId:Ve,...ye?{nonce:ye}:{},clientSecret:pn,providerObjectId:un.providerObjectId,paymentMethodType:E,accountPatch:Tn});window.clearTimeout(zt),nt=!0,he?.performance({stage:"callback",durationMs:Math.max(0,(he?.now()??globalThis.performance?.now()??Date.now())-Er),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let $n=he?.now()??globalThis.performance?.now()??Date.now(),Nn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Ut?{walletType:Ut}:{},attempt:Dn},An=!1,on=null;he?.log({name:"payment.provider_confirmation.started",...Nn}),xt=window.setTimeout(()=>{xt!==null&&_e.current.delete(xt),An=!0;let se=he?.now()??globalThis.performance?.now()??Date.now();he?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Nn,operationOutcome:"watchdog_expired",durationMs:Math.max(0,se-$n),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),he?.flush?.().catch(()=>{}),on?.()},im),_e.current.add(xt);let Qt=(se,Et)=>{xt!==null&&(window.clearTimeout(xt),_e.current.delete(xt),xt=null);let gt=he?.now()??globalThis.performance?.now()??Date.now(),ut=Math.max(0,gt-$n),Re=se;An&&(se==="resolved"?Re="resolved_late":se==="returned_error"?Re="returned_error_late":Re="rejected_late");let Wn=Et??(se==="resolved"?"approved":"provider_error");return he?.log({name:"payment.provider_confirmation.returned",...Nn,operationOutcome:Re,terminalReason:Wn}),he?.performance({...Nn,durationMs:ut,durationMode:"buyer",operationOutcome:Re,terminalReason:Wn}),{durationMs:ut,operationOutcome:Re,terminalReason:Wn}},en=!1,Vt=!1,Un=se=>{if(!se||typeof se!="object")return null;let Et=se;if(Et.error)return null;let gt=Et.setupIntent??Et.paymentIntent,ut=Ws(gt??null,void 0,!!Et.setupIntent);return ut.kind==="confirmed"?ut:null},zn=se=>{if(en||we&&Ke.current!==we.generation)return;let Et=Un(se);if(!Et)return;if(Mn&&!Rd(Ve,ye,pn)){en=!0;return}let{intentId:gt,paymentMethodId:ut}=Et;en=!0,Vt=!0,Ae.current=null,Je.current=null,Ue.current&&(V("idle"),Ie(!1));let Re=`${Ud}:${Ve}`;rn(Re,{createdAt:Date.now(),sessionId:Ve,nonce:ye,accountPatch:Tn,paymentMethodId:ut,providerIntentId:gt,paymentMethodType:E});try{s({id:ut,type:"card",threeDSecureActionResultTokenId:gt},{accountPatch:Tn,paymentMethodCategory:"wallet",sessionId:Ve,nonce:ye})}finally{rn(Re)}},xn=!1;on=async()=>{if(!(xn||en||Vt)){xn=!0,Ue.current&&V("checking");try{let se=await Id(I,pn,_e.current);if(en||Vt)return;let Et=qs(pn),gt=Ws(se,un.providerObjectId,Et);if(gt.kind==="confirmed"){zn(Et?{setupIntent:se}:{paymentIntent:se});return}if(gt.kind==="terminal"){if(Vt=!0,$s(Ve,ye,pn),Ae.current=null,Je.current=null,!Ue.current)return;V("idle"),Se(),je(E,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",we?.generation,!0);return}Ue.current&&!Vt&&(V("blocked"),Ie(!1))}catch{Ue.current&&!Vt&&(V("blocked"),Ie(!1))}finally{xn=!1}}},Je.current=on;let _,$e;try{H=!0,yt.current+=1;let se;try{se=await(qs(pn)?I.confirmSetup({elements:He,clientSecret:pn,redirect:"if_required"}):I.confirmPayment({elements:He,clientSecret:pn,redirect:"if_required"}))}finally{qe()}if(!se||typeof se!="object")throw new $a(um(se));if(_=se,!_.error&&!Un(_))throw new $a("confirmation_result_unconfirmed");$e=Qt(_.error?"returned_error":"resolved",_.error&&ci(_.error)?"provider_declined":void 0)}catch(se){let Et=se instanceof $a?se.reason:void 0,gt=Et!==void 0,ut=Qt(gt?"returned_error":"rejected");if(he?.error({...gt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Et}:Es(se),...Nn,operationOutcome:ut.operationOutcome,durationMs:ut.durationMs,statusClass:"unknown",terminalReason:ut.terminalReason}),!Ue.current||en)return;await on?.();return}let h=_.error;if(h){if(!Ue.current||en)return;if(ci(h)){Vt=!0,$s(Ve,ye,pn),Ae.current=null,Je.current=null,V("idle"),It.current.get(Ee)===we&&It.current.delete(Ee);let se=h.message??"Your payment was declined.";c?.(se),R?.(mn(Ht,se,{code:Ho(h),declineCode:bs(h)})),Di({billingApiUrl:o,sessionId:Ve,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:E,providerDeclineReason:Ho(h)??"provider_declined",...un.intentKind==="payment"&&un.providerObjectId.startsWith("pi_")?{providerIntentId:un.providerObjectId}:{}}})}else he?.error({...Es(h),...Nn,operationOutcome:$e.operationOutcome,durationMs:$e.durationMs,statusClass:"unknown",terminalReason:$e.terminalReason}),await on?.();return}if(zn(_),!en)throw new Error("Invalid provider returned for APM intent")}catch(Ve){if(Ve===Mi){let ye=he?.now()??globalThis.performance?.now()??Date.now();he?.error({errorCode:mm(_n),stage:En,requestCategory:_n,paymentMethodCategory:"wallet",provider:"stripe",...Ut?{walletType:Ut}:{},operationOutcome:"watchdog_expired",checkoutSessionId:In,durationMs:Math.max(0,ye-Er),statusClass:"timeout",failureCategory:Cn,attempt:Dn,terminalReason:"provider_error"}),he?.flush?.().catch(()=>{})}Se(),je(E,Ve,Ve===Mi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",we?.generation,Ve===Mi)}finally{if(window.clearTimeout(zt),xt!==null&&(window.clearTimeout(xt),_e.current.delete(xt)),!nt){let Ve=he?.now()??globalThis.performance?.now()??Date.now();he?.performance({stage:"callback",durationMs:Math.max(0,Ve-Er),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...dn?{statusClass:"timeout"}:{}})}Ue.current&&Ie(!1)}},[I,He,e,t,n,D,ke,ee,o,de,a,s,c,R,y,je,qe,pe,dt,ct,Ke,X,Ee]),Y=vt(()=>cc(i),[i]),W=vt(()=>i.map(Zy),[i]),J=vt(()=>l(Nd,{onReady:f=>{at(Ss(f,W))},onLoadError:f=>{at("load_error"),el(X,"stripe","wallet","provider_error")},onClick:async f=>{let ie=X?.now()??globalThis.performance?.now()??Date.now();bt.current=f.expressPaymentType,De.current=Md(f.expressPaymentType);let H=!0,Se=window.setTimeout(()=>{H=!1,f.reject(),et(f.expressPaymentType)},rm),we=y?await y(De.current,{abandoned:()=>!H}):{proceed:!0};if(window.clearTimeout(Se),!H)return;if(!we.proceed){It.current.delete(Ee),f.reject();return}let E=G(f.expressPaymentType);mt.current=!1,St.current={generation:E,startedAt:ie},It.current.set(Ee,{generation:E,method:f.expressPaymentType,accountPatch:we.accountPatch,sessionId:we.sessionId,nonce:we.nonce}),Me(!1),X?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:E,...f.expressPaymentType==="apple_pay"||f.expressPaymentType==="google_pay"?{walletType:f.expressPaymentType}:{}}),d?.(De.current),f.resolve()},onConfirm:m,onCancel:()=>{let f=It.current.get(Ee);It.current.delete(Ee);let ie=St.current,H=X?.now()??globalThis.performance?.now()??Date.now();if(f&&ie?.generation===f.generation&&qy({method:f.method,elapsedMs:H-ie.startedAt,handoffObserved:Ot.current===f.generation})){X?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:f.generation,walletType:"google_pay"}),Ae.current=null,je(f.method,new Error("The browser window is too small for the Google Pay sheet."),Ld,f.generation,!0);return}X?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...f?{attempt:f.generation}:{}}),Te(f?.generation),Ae.current=null,Me(!1),Qe.current=!0,wt()},options:{...dc,paymentMethods:Y,emailRequired:Nt,billingAddressRequired:Nt}},Ee),[W,Y,m,Te,d,Nt,je,et,wt,y,G,Ee,X]);return Le(jn,{children:[l(ws,{state:Ne,placeholderTestId:"flopay-wallet-placeholder",borderRadius:j,children:Le("div",{ref:it,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[re&&Le("button",{ref:st,type:"button","data-testid":"flopay-wallet-retry-button",onClick:hn,style:Gs,children:["Try ",Ys(Ct)," again"]}),Ze!=="idle"&&Le("div",{role:"status","aria-live":"polite",children:[l("p",{children:"We are still confirming your payment. Check its status before trying again."}),l("button",{type:"button",onClick:w,disabled:Ze==="checking",style:Gs,children:Ze==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Dt&&l(ea,{identity:Dt.identity,methodLabel:Dt.methodLabel,onComplete:Ye,onCancel:()=>Ye(null)},Dt.id),Le("div",{style:{display:Dt||Ze!=="idle"?"none":void 0},children:[l(Am,{active:ue}),J]})]})}),pt&&l(Dr,{status:"processing"})]})}function $d(e,t,n){let o=Dd(n,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function Js({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:c,onErrorChange:d,onDecline:R,onCancel:g,runBeforeButtonClick:y,onButtonClick:D,isProcessing:ee,submitButtonColor:ae,submitButtonBorderRadius:j,submitButtonStyle:K,errorText:C}){let fe=ao(),{emitInstrument:de}=ca(pr),I=Zs(),He=Xs(),[X,Ne]=oe(!1),at=q(!1),[pt,Ie]=oe(!1),[Nt,Dt]=oe("loading"),[ke,Ye]=oe(""),it=!kn(o?.trim()),st=!it||kn(ke.trim()),Ee=Be(async()=>{if(!I||!He||ee||at.current||!pt)return;at.current=!0,Ne(!0);let te=y?await y("card"):{proceed:!0};if(!te.proceed){at.current=!1,Ne(!1);return}D?.("card");let ue=te.sessionId??t,$t=te.nonce??n,ze=Ta(a?.trim()),lt=kr({email:te.accountPatch?.email?.trim()||o?.trim()||ke.trim(),firstName:te.accountPatch?.firstName?.trim()||ze.firstName,lastName:te.accountPatch?.lastName?.trim()||ze.lastName}),re=lt.email,Me=kr({...te.accountPatch,...lt});try{if(d?.(null),!kn(re))throw new Error("A valid email address is required for payment.");await i?.(lt);let Ze=await He.submit();if(Ze.error){d?.(Ze.error.message??"Payment failed.");return}let V=[lt.firstName,lt.lastName].filter(Boolean).join(" "),Ct=await I.createPaymentMethod({elements:He,params:{billing_details:{email:re,...V?{name:V}:{}}}});if(Ct.error||!Ct.paymentMethod){d?.(Ct.error?.message??"Failed to create payment method.");return}let be=Ct.paymentMethod;if(!ue||!re)throw new Error("Missing sessionId or email for payment.");let Je=be.type||e,Ue=await Bi(s,de,ue,$t??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Je,paymentMethodId:null,intentKind:"payment"});if(Fi(Ue)){c({type:"card",gateway:"stripe",paymentMethodType:Je},{accountPatch:Me,paymentMethodCategory:"apm",sessionId:ue,nonce:$t,settledProcessResponse:Ue.response});return}if(Ue.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Qe=Ue.clientSecret;rn(Lr,{clientSecret:Qe,sessionId:ue,nonce:$t,accountPatch:Me,paymentMethodId:be.id,paymentMethodType:be.type??e,gateway:"stripe"});let{error:bt,paymentIntent:De}=await I.confirmPayment({clientSecret:Qe,confirmParams:{return_url:window.location.href,payment_method:be.id},redirect:"if_required"});if(bt){rn(Lr);let _e=bt.message??"Payment failed.";d?.(_e),R?.(mn("card",_e,{code:bt.code})),await Di({billingApiUrl:s,sessionId:ue,nonce:$t,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:bt.code??"provider_declined"}});return}let Rt=De?.status;if(!Ea(Rt)){rn(Lr);let _e=Rt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(_e),R?.(mn("card",_e,{code:Rt??"missing_payment_intent"}));return}rn(Lr);let Ae=typeof De?.payment_method=="string"?De.payment_method:De?.payment_method?.id;c({id:Ae??be.id,type:"card",threeDSecureActionResultTokenId:De?.id,gateway:"stripe",paymentMethodType:be.type??e},{accountPatch:Me,paymentMethodCategory:"apm",sessionId:ue,nonce:$t})}catch(Ze){d?.(Ze instanceof Error?Ze.message:"Payment failed. Please try again.")}finally{at.current=!1,Ne(!1)}},[I,He,ee,pt,y,D,t,n,o,a,ke,i,s,de,e,c,d,R]);return Le("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[it&&l("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:it&&Le("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",l("input",{type:"email",autoComplete:"email",required:!0,value:ke,onChange:te=>Ye(te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),l(em,{onReady:()=>Dt("ready"),onLoadError:()=>{Dt("load_error"),el(fn(fe),"stripe","apm")},onChange:te=>{Ie(!!te.complete)},options:{layout:uc,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...kn(o?.trim())?{email:o?.trim()}:{}}}}}),l(pc,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Ee()},disabled:!pt||!st||X||ee||Nt!=="ready",color:ae,borderRadius:j,style:K,children:X?"Processing\u2026":`Pay with ${Wa(e)}`}),C&&l(ra,{margin:"0.75rem 0 0",children:C})]})}function Fd({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:c,paymentElementBaseOptions:d,futureUseSession:R,onTokenizedBody:g,onErrorChange:y,onButtonClick:D,onDecline:ee,runBeforeButtonClick:ae,onLoadStateChange:j,isProcessing:K=!1,submitButtonColor:C="#4A49FF",submitButtonBorderRadius:fe=8,submitButtonStyle:de,buttonAppearance:I,themeId:He,onExpandApm:X,expandedApmMethod:Ne}){let{emitInstrument:at}=ca(pr),[pt,Ie]=oe(null),[Nt,Dt]=oe(null),ke=q(!1),{request:Ye,collect:it,finish:st}=Qo();Xe(()=>{s.length>0&&c?j?.("ready"):c||j?.("loading")},[s.length,c,j]);let Ee=Be(async re=>{if(!c||ke.current||K)return;ke.current=!0,Dt(re);let Me=ae?await ae("card"):{proceed:!0};if(!Me.proceed){ke.current=!1,Dt(null);return}D?.("card");let Ze=Me.sessionId??e,V=Me.nonce??t,Ct=Ta([Me.accountPatch?.firstName,Me.accountPatch?.lastName].filter(Boolean).join(" ")||o),be=kr({email:Me.accountPatch?.email?.trim()||n?.trim(),firstName:Me.accountPatch?.firstName?.trim()||Ct.firstName,lastName:Me.accountPatch?.lastName?.trim()||Ct.lastName});if(!kn(be.email)){Dt(null);let Qe=await it(Wa(re),be);if(!Qe){ke.current=!1;return}be=Qe,Dt(re)}let Je=be.email,Ue=kr({...Me.accountPatch,...be});try{if(y?.(null),!Ze||!kn(Je))throw new Error("Missing sessionId or email for payment.");await a?.(be);let Qe=await Bi(i,at,Ze,V??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,paymentMethodId:null,intentKind:"payment"});if(Fi(Qe)){g({type:"card",gateway:"stripe",paymentMethodType:re},{accountPatch:Ue,paymentMethodCategory:"apm",sessionId:Ze,nonce:V,settledProcessResponse:Qe.response});return}if(Qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let bt=Qe.clientSecret;rn(Lr,{clientSecret:bt,sessionId:Ze,nonce:V,accountPatch:Ue,paymentMethodType:re,gateway:"stripe"});let{error:De,paymentIntent:Rt}=await c.confirmPayment({clientSecret:bt,confirmParams:{return_url:window.location.href,payment_method_data:{type:re,billing_details:{name:[be.firstName,be.lastName].filter(Boolean).join(" "),...Je?{email:Je}:{}}}},redirect:"if_required"});if(De){rn(Lr);let St=De.message??"Payment failed.";y?.(St),ee?.(mn("card",St,{code:De.code})),await Di({billingApiUrl:i,sessionId:Ze,nonce:V,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:re,providerDeclineReason:De.code??"provider_declined"}});return}let Ae=Rt?.status;if(!Ea(Ae)){rn(Lr);let St=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(St),ee?.(mn("card",St,{code:Ae??"missing_payment_intent"}));return}rn(Lr);let _e=typeof Rt?.payment_method=="string"?Rt.payment_method:Rt?.payment_method?.id;g({id:_e??Rt?.id,type:"card",threeDSecureActionResultTokenId:Rt?.id,gateway:"stripe",paymentMethodType:re},{accountPatch:Ue,paymentMethodCategory:"apm",sessionId:Ze,nonce:V})}catch(Qe){y?.(Qe instanceof Error?Qe.message:"Payment failed. Please try again.")}finally{ke.current=!1,Dt(null)}},[c,K,ae,D,e,t,n,it,i,at,o,a,g,y,ee]),[te,ue]=oe(null),$t=X?Ne??null:te,ze=Be(re=>{ke.current||K||$t&&$t!==re||(Cd(re)?X?X(re):ue(re):Ee(re))},[$t,K,Ee,X]),lt=vt(()=>te?$d(d,te,R):null,[te,d,R]);return l("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ye?l(ea,{identity:Ye.identity,methodLabel:Ye.methodLabel,onComplete:st,onCancel:()=>st(null)},Ye.id):s.map(re=>{let Me=Ne===re,Ze=Nt===re,V=Nt!==null&&Nt!==re||Ne!=null&&Ne!==re;return Le(ja.Fragment,{children:[l(lc,{method:re,themeId:He,submitting:Ze,disabled:V,highlighted:Me,hasNextStep:Cd(re),onClick:()=>ze(re),backgroundColor:I?.backgroundColor,borderColor:I?.borderColor,textColor:I?.textColor,borderRadius:I?.borderRadius,fontFamily:I?.fontFamily}),!X&&te===re&<&&c&&l(oo,{stripe:c,options:lt,children:l(Js,{method:re,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:g,onErrorChange:y,onDecline:ee,onCancel:()=>ue(null),runBeforeButtonClick:ae,onButtonClick:D,isProcessing:K,submitButtonColor:C,submitButtonBorderRadius:fe,submitButtonStyle:de})},re)]},re)})})}function xm({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:c,onDecline:d,onCancel:R,onTokenizedBody:g,firstName:y,lastName:D,chv:ee,className:ae,submitLabel:j,isProcessing:K,error:C,onErrorChange:fe,showPayPal:de=!0,showStripe:I=!0,walletPresentation:He="auto",enabledPaymentMethods:X,enabledPaymentMethodCountries:Ne,showApplePay:at=!0,showGooglePay:pt=!0,layout:Ie="default",paymentMethodLayout:Nt,moreOptionsLabel:Dt,theme:ke,buttonsTheme:Ye,buttonsStyles:it,appearance:st,cardButtonContent:Ee,cardBackButtonContent:te,cardTitleContent:ue,showSecurityFooter:$t,onButtonClick:ze,onBeforeButtonClick:lt,onBuyerIdentityReady:re,enableAVS:Me,cardFieldOrder:Ze,showCardBrandIcons:V,showCardFieldLabels:Ct,cardFieldLabels:be,cardFieldPlaceholders:Je,cardAutoFocus:Ue,onCardFieldsReady:Qe,onCardFieldsFailed:bt,cardFieldsTimeoutMs:De,cardPreFormSlot:Rt,avsLayout:Ae="row",country:_e,zip:St,addressLine1:Ot,addressLine2:It,city:G,state:pe,onCountryChange:Te,onZipChange:ct,avsCheck:dt,checkoutType:Ke,checkoutLayout:yt,totalAmount:mt=0,currency:wt="usd",initialCardOpen:qe=!1,directPaypal:je,isSubscription:et=!1,session:$,dataAttachmentPending:hn=!1,dataAttachmentRequiresIdentity:w=!1,debug:m=!1}){let Y=ao(),W=_s(),J=ca(wr),{emitInstrument:f}=ca(pr),ie=q(null);ie.current||(ie.current=gi());let H=ie.current,[,Se]=oe(0),we=q(null);we.current||(we.current=ka());let E=we.current,tt=vt(()=>({browser:E,capability:H,presentationMode:"popup"}),[E,H]),Ht=$??J.session,Ut=vt(()=>({futureUse:Ht?.futureUse,futureUseUnsupported:Ht?.futureUseUnsupported}),[Ht?.futureUse,Ht?.futureUseUnsupported]),Dn=Ht?.gateways?.paypal?.providerObjectType??je?.providerObjectType,he=hn||J.claimPending===!0,Er=w||J.claimRequiresIdentity===!0,cn=he&&!Er,dn=Nc(),nt=n||dn,xt=Pd({rules:Nt,sessionId:e,nonce:t,billingApiUrl:nt,waitForSession:cn}),In=xt?.order??null,[En,_n]=oe(!1),Cn=vt(()=>In?jy(In):null,[In]),bn=In!==null&&Ly(In),[Kt,zt]=oe(!1),[Zt,Ve]=oe(null),[ye,ar]=oe(_e??""),[Ft,Tn]=oe(St??""),[On,ir]=oe(Ot??""),[Ln,_r]=oe(It??""),[fr,un]=oe(G??""),[pn,Mn]=oe(pe??""),[$n,Nn]=oe(""),[An,on]=oe({}),Qt=q(St??""),en=q(_e??""),Vt=q(Ot??""),Un=q(It??""),zn=q(G??""),xn=q(pe??""),_=q(""),$e=q({});Xe(()=>{let r=(p,B,Q,z,me)=>{if($e.current[p])return;let Tt=B?.trim();!Tt||Tt===Q.current||(Q.current=Tt,z(Tt),me?.(Tt))};r("country",_e,en,ar,Te),r("zip",St,Qt,Tn,ct),r("addressLine1",Ot,Vt,ir),r("addressLine2",It,Un,_r),r("city",G,zn,un),r("state",pe,xn,Mn)},[_e,St,Ot,It,G,pe,Te,ct]);let h=vt(()=>Vy(Me),[Me]),se=h!==null,Et=vt(()=>zs($),[$]),gt=Ny($?.vault),ut=!!$?.gateways?.pcivault,Re=_c($),Ao=!!($?.gateways?.stripe?.enabledPaymentMethods??X)?.includes("card")||ko($),Fn=gt||Ao||ut,ne=!!(I&&Fn&&e),[gr,Tr]=oe(()=>Ie!=="buttons"||qe?e??null:null),[Jr,po]=oe(0),Jn=Ie!=="buttons"||qe||!!e&&gr===e,Mr=$?.captureMethod,zr=q(Y);Xe(()=>{zr.current=Y},[Y]);let yn=q(De);yn.current=De;let qr=q(t);qr.current=t;let Hn=q({onCardFieldsReady:Qe,onCardFieldsFailed:bt,emitInstrument:f});Hn.current={onCardFieldsReady:Qe,onCardFieldsFailed:bt,emitInstrument:f};let[Sn,Gt]=oe(null);Xe(()=>{if(!ne||!e||!Jn){Gt(null);return}let r=zr.current?zr.current.cardCapture({sessionId:e,captureMethod:Mr,sessionToken:qr.current,cardFieldsTimeoutMs:yn.current}):new hy({sessionId:e,captureMethod:Mr,billingApiUrl:nt,telemetry:o,sessionToken:qr.current,cardFieldsTimeoutMs:yn.current}),p=r.onCardFields?.(B=>{let Q=Hn.current;Q.emitInstrument?.(Iy(B)),B.type==="card_fields_ready"?vd(()=>Q.onCardFieldsReady?.(B)):vd(()=>Q.onCardFieldsFailed?.(B))});return Gt({sessionId:e,captureMethod:Mr,billingApiUrl:nt,telemetry:o,capture:r}),()=>{p?.(),r.unmount()}},[ne,e,Jn,Mr,nt,o]);let Pe=ne&&e&&Jn&&Sn?.sessionId===e&&Sn.captureMethod===Mr&&Sn.billingApiUrl===nt&&Sn.telemetry===o?Sn.capture:null,wn=vt(()=>{let r=ye,p=h?Xt(h.postal_code,r):!1;return Rm(r,Ft,p)},[h,ye,Ft]),{avsInvalid:Xn,invalidAvsFields:hr}=vt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!ne||!h)return{avsInvalid:!1,invalidAvsFields:r};let p=ye,B=(me,Tt)=>Xt(me,p)&&!Tt.trim(),Q={line1:B(h.address_line_1,On),city:B(h.city,fr),state:B(h.state,pn),zip:wn.empty||wn.malformed};return{avsInvalid:Q.line1||Q.city||Q.state||Q.zip,invalidAvsFields:Q}},[ne,h,ye,On,fr,pn,wn]),[Pr,sr]=oe(!1),[yo,jr]=oe(!1),[mo,$r]=oe(!1),[fo,Wr]=oe({line1:!1,city:!1,state:!1}),lr=q(!1),go=q({email:!1,line1:!1,city:!1,state:!1,zip:!1}),ho=q(!1),qt=Be(r=>{go.current[r]=!0,ho.current=!0},[]),Kn=Be(r=>!lr.current&&go.current[r],[]),Ar=Be(r=>{Kn(r)&&Wr(p=>p[r]?p:{...p,[r]:!0})},[Kn]),[Yt,Zn]=oe(()=>js($?.vault,{billingApiUrl:nt,sessionId:e,nonce:t})),[xe,Bn]=oe(qe&&Fn?"card":"buttons"),[an,Qn]=oe(null),pa=xe==="expanding"||xe==="card",er=$?.gateways?.stripe&&!Re?"stripe":void 0,P=Be(()=>{f?.({class:"card_surface",provider:er})},[er,f]),A=Be(()=>{_n(!0),f?.({class:"more_options"})},[f]),O=q(null),M=Be(r=>{O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{O.current=null,r()},Ha)},[]);Xe(()=>()=>{O.current&&clearTimeout(O.current)},[]);let We=q(!1),[v,u]=oe(0),k=q(null),x=Be(()=>{P(),Tr(e??null),We.current&&(We.current=!1,u(r=>r+1)),po(r=>r+1),Bn("expanding"),M(()=>Bn("card"))},[M,P,e]),S=Be(()=>{Bn("collapsing"),M(()=>Bn("buttons"))},[M]),N=Be(r=>{Qn(r),Bn("apm-expanding"),M(()=>Bn("apm-form"))},[M]),le=Be(()=>{Bn("apm-collapsing"),M(()=>{Bn("buttons"),Qn(null)})},[M]);Xe(()=>{Ie==="buttons"&&qe&&Fn&&(Tr(e??null),Bn("card"))},[Ie,qe,Fn,e]);let[F,U]=oe(null),ft=q(null),[_t,ve]=oe(0);Xe(()=>{_t!==0&&ft.current?.focus()},[_t]);let Z=q(!1),b=q(null),T=q("idle"),[L,kt]=oe(!1),Ce=q(L);Ce.current=L;let[Ge,tr]=oe(()=>je?.existingOrderId?{orderId:je.existingOrderId,attempts:1}:null),Vn=q(Ge);Xe(()=>{Vn.current=Ge},[Ge]);let vr=q(null),xo=vt(()=>{if(re||J.claimBuyerIdentity||$?.buyerIdentified!==!1||!e||!t)return;let r=`${nt}|${e}|${t}`;vr.current?.key!==r&&(vr.current={key:r,claim:Jo(new la(nt,{telemetry:!1}),e,t,{...i?{userId:i}:{},...y?{firstName:y}:{},...D?{lastName:D}:{}})});let p=vr.current.claim;return async B=>{await p(B)}},[re,J.claimBuyerIdentity,$?.buyerIdentified,e,t,nt,i,y,D]),cr=re??J.claimBuyerIdentity??xo,Cr=C??Zt,Fo=vt(()=>Yy(ke),[ke]),Fe=vt(()=>{let r=Fo?.buttonsLayout??Gy(Ye);return it?{...r,...it,cardButton:{...r.cardButton,...it.cardButton},cardFormContainer:{...r.cardFormContainer,...it.cardFormContainer},backButton:{...r.backButton,...it.backButton},backButtonIcon:{...r.backButtonIcon,...it.backButtonIcon},submitButton:{...r.submitButton,...it.submitButton},title:{...r.title,...it.title}}:r},[Fo,Ye,it]),Bo=st??Fo?.appearance,uu=vt(()=>Ty({appearance:Bo,buttonsStyles:Fe,layout:Ie}),[Bo,Fe,Ie]),pu=J.inlineSessionPatchProcessing??!1,tn=(K??Kt)||pu,Xr=nt.replace(/\/+$/,""),ht=vt(()=>Is({userId:i,email:a,firstName:y,lastName:D,country:_e,zip:St},An),[i,a,y,D,_e,St,An]),Do=[ht.firstName,ht.lastName].filter(r=>!!r?.trim()).join(" "),ml=!kn(ht.email?.trim()),ji=q(null);ne&&ji.current===null&&(ji.current=ml);let Zr=ne&&(ji.current??ml),$i=vt(()=>Im($n,Zr),[$n,Zr]),Oo=$i.empty||$i.malformed,nr=vt(()=>Y?Y.getRawProvider():null,[Y]),fl=vt(()=>W?W.getRawProvider():null,[W]),ya=mt||100,Lo=wt.toLowerCase(),Wi=vt(()=>Bo?Py(Bo):null,[Bo]),No=Wi,gl=vt(()=>{let r=Wi??{},p=r.rules??{};return{...r,rules:{...p,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...p[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...p[".AccordionItemContents"]??{}}}}},[Wi]),hl=vt(()=>({...Ec(mt,Ht?.captureMethod,Ut),currency:Lo,...No?{appearance:No}:null}),[mt,Lo,Ht?.captureMethod,Ut,No]),Hi=Dd(Ut,"paypal","paypal"),Pl=vt(()=>({mode:"payment",amount:ya,currency:Lo,captureMethod:"manual",...Hi?{setupFutureUsage:Hi}:null,...No?{appearance:No}:null}),[ya,Lo,Hi,No]),ge=Be(r=>{Ve(r),fe?.(r)},[fe]),vl=q(0);Xe(()=>{v!==vl.current&&(vl.current=v,ge(null))},[v,ge]);let Ki=q(""),[Cl,yu]=oe(!1),Vi=Be(()=>{yu(!0)},[]);Xe(()=>{if(!ne||!Zr||!cr||!Cl||Oo||Ki.current)return;let r=kr({email:kn(ht.email?.trim())?ht.email?.trim():_.current.trim(),firstName:ht.firstName?.trim(),lastName:ht.lastName?.trim()});Ki.current=JSON.stringify(r),on(p=>({...p,...r})),Promise.resolve(cr(r)).catch(p=>{Ki.current="",ge(p instanceof Error?p.message:"Failed to attach buyer details.")})},[ne,Zr,cr,Cl,Oo,ht.email,ht.firstName,ht.lastName,ge]),Xe(()=>{if(!ne||!Pe)return;let r=Ue!==!1&&h==null&&!Zr;Pe.setCardFieldOrder?.(Ze??null,r)},[ne,Pe,Ze,Ue,h,Zr]),Xe(()=>{!ne||!Pe||Pe.setCardBrandIcons?.(V===!0)},[ne,Pe,V]);let Gi=q(null);Xe(()=>{if(!(!ne||!Pe)){if(Ct===void 0){if(Gi.current!==Pe)return;Gi.current=null,Pe.setShowCardFieldLabels?.(!1);return}Gi.current=Pe,Pe.setShowCardFieldLabels?.(Ct===!0)}},[ne,Pe,Ct]);let Yi=be===void 0?void 0:JSON.stringify(vy(be)),Ji=q(null);Xe(()=>{if(!(!ne||!Pe)){if(Yi===void 0){if(Ji.current!==Pe)return;Ji.current=null,Pe.setCardFieldLabels?.(null);return}Ji.current=Pe,Pe.setCardFieldLabels?.(JSON.parse(Yi))}},[ne,Pe,Yi]);let Xi=Tm(Je),Zi=q(null);Xe(()=>{if(!(!ne||!Pe)){if(Xi===null){if(Zi.current!==Pe)return;Zi.current=null,Pe.setCardFieldPlaceholders?.(void 0);return}Zi.current=Pe,Pe.setCardFieldPlaceholders?.(JSON.parse(Xi))}},[ne,Pe,Xi]),Xe(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&ge(null)},[xe,ge]);let xr=Be((r,p,B)=>{d?.(mn(r,p,B))},[d]),bl=q(xe);bl.current=xe;let[Sl]=oe(Pi),wl=Be(()=>{let r=bl.current;if(Ie==="buttons"&&(r==="card"||r==="expanding"))return!0;let p=T.current;return p==="validation-window"||p==="processing"||Ce.current},[Ie]),kl=Be((r,p,B)=>{Sl.take(e)&&fn(Y)?.log(Eo({...tt,presentationMode:B?.presentationMode??"popup"},{name:hi,stage:"recovery",reason:"other_method_active",provider:B?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:B?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[tt,Y,Sl,e]),Ya=Be((r,p,B)=>{B?.telemetryReported||fn(Y)?.error(Eo({...tt,presentationMode:B?.presentationMode??"popup"},{errorCode:p?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:B?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:B?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:B?.terminalReason??(p?"popup_blocked":"provider_error")}))},[tt,Y]),Uo=Be((r,p,B)=>{let Q=B?.popupBlocked??to(p);if(wl()){Ya(r,Q,B),kl(r,p,B);return}if(p instanceof Rr&&p.code==="checkout_processing_timeout"){Ya(r,!1,B),U(null),Ie==="buttons"&&(Bn("buttons"),Qn(null)),ge(p.message),c?.(p);return}Q&&H.markBlocked()&&Se(rt=>rt+1);let z=Ys(r),me=B?.code===Ld?Sy(z):li(z,Q,E.inAppBrowser),Tt=Ho(p),Mt=(Tt?.toLowerCase()==="error"?void 0:Tt)??ic(B?.code)??"external_payment_method_failed",Oe=new Rr(me,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:Mt,popupBlocked:Q,inAppBrowser:E.inAppBrowser,appFamily:E.appFamily,popupCapability:H.current(),presentationMode:B?.presentationMode??"popup"}});Ya(r,Q,B),U(null),Ie==="buttons"&&(Bn("buttons"),Qn(null)),ge(me),c?.(Oe),console.error("[FloPay] External payment method failed:",{method:r,code:Mt,popupBlocked:Q})},[E,wl,Ie,c,H,kl,Ya,ge]);Xe(()=>{if(!ne||!e){Zn(null);return}let r={billingApiUrl:Xr,sessionId:e,nonce:t},p=js($?.vault,r);if(p){Zn(p);return}if(!Jn){Zn(null);return}let B=`${Xr}\0${e}\0${t??""}`,Q=k.current;if(Q&&Q.key===B){Zn(Q.mount);return}Zn(null);let z=!0;return new la(Xr).getVaultCapture(e,t).then(me=>{if(!z)return;let Tt=js(me,r);Tt?.verificationRequired&&!me.html&&(k.current={key:B,mount:Tt}),Tt?Zn(Tt):ge("Failed to load the secure card form.")}).catch(me=>{z&&ge(me instanceof Error?me.message:"Failed to load the secure card form.")}),()=>{z=!1}},[ne,Jn,Jr,e,$?.vault,Xr,t,ge]);let br=q({onComplete:s,onError:c,updateError:ge,emitDecline:xr,resolvedAccount:ht,avsConfig:h,avsCheckProp:dt,sessionId:e,nonce:t,baseUrl:Xr,captureMethod:$?.captureMethod,paymentId:$?.paymentId,authorizationExpiresAt:$?.authorizationExpiresAt,serverSideCardGateway:Re});br.current={onComplete:s,onError:c,updateError:ge,emitDecline:xr,resolvedAccount:ht,avsConfig:h,avsCheckProp:dt,sessionId:e,nonce:t,baseUrl:Xr,captureMethod:$?.captureMethod,paymentId:$?.paymentId,authorizationExpiresAt:$?.authorizationExpiresAt,serverSideCardGateway:Re};let Qi=q(!1),Rl=Be(()=>{let r=br.current,p=r.resolvedAccount.email?.trim(),B=kn(p)?p:_.current.trim();if(!kn(B))return null;let Q=r.resolvedAccount.firstName?.trim(),z=r.resolvedAccount.lastName?.trim(),me=en.current.trim()||r.resolvedAccount.country?.trim()||"",Tt=r.avsConfig?Xt(r.avsConfig.state,me):!1,Mt=r.avsConfig?Xt(r.avsConfig.address_line_1,me):!1,Oe=r.avsConfig?Xt(r.avsConfig.postal_code,me):!1,rt=r.avsConfig?Xt(r.avsConfig.city,me):!1,Pt=r.avsConfig?Xt(r.avsConfig.address_line_2,me):!1,sn=Mt&&!Tt&&Oe?By(me,(Qt.current??"").trim()):null,rr=Tt?xn.current:sn;return{accountData:{userId:r.resolvedAccount.userId??"",email:B,...Q?{firstName:Q}:{},...z?{lastName:z}:{},...Oe&&Qt.current?{zip:Qt.current}:{},...rt&&zn.current?{city:zn.current}:{},...rr?{state:rr}:{},...Mt&&Vt.current?{addressLine1:Vt.current}:{},...Pt&&Un.current?{addressLine2:Un.current}:{},...me?{country:me}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Xt(r.avsConfig.country,me),postal_code:Oe,address_line_1:Mt,address_line_2:Pt,city:rt,state:Tt}}:{}}},[]),Il=q(he);Il.current=he,Xe(()=>{he||Cr!==Ed||br.current.updateError(null)},[he,Cr]),Xe(()=>{!ne||!Pe||Pe.setSubmitGate?.(Xn||he||Oo||L)},[ne,Pe,Xn,he,Oo,L]),Xe(()=>{if(!ne||!Pe)return;Qi.current=!1;let r=null,p=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,T.current="idle",U(null)},400)},B=Pe.on("submitting",()=>{sr(!0),b.current&&clearTimeout(b.current),T.current="validation-window",b.current=setTimeout(()=>{b.current=null,T.current==="validation-window"&&(T.current="processing")},fm),U("processing");let Oe=br.current;if(!Oe.sessionId||!Oe.nonce)return;let rt=Rl();if(!rt){Oe.updateError("Enter a valid email address."),T.current="idle",U(null);return}new la(Oe.baseUrl).patchAccountSnapshot(Oe.sessionId,Oe.nonce,rt,{telemetryMode:"best_effort"}).catch(Pt=>{if(!hm(Pt))return;let sn=Pt instanceof Error?Pt.message:"Please check your billing address and try again.";Oe.updateError(sn),T.current="idle",U(null),Oe.onError?.(Pt instanceof Rr?Pt:new Rr(sn,"api_error"))})}),Q=Pe.on("complete",Oe=>{oa(Oe.sessionId??br.current.sessionId),T.current="terminal",kt(!1),U("success"),setTimeout(()=>{if(Qi.current)return;Qi.current=!0;let rt=br.current,Pt=zs(rt)||Oe.outcome==="authorized",sn=rt.serverSideCardGateway?{}:{paymentIntentId:Oe.intentId};br.current.onComplete?.(Pt?{status:"authorized",...sn,paymentId:Oe.paymentId??rt.paymentId,sessionId:Oe.sessionId??rt.sessionId,authorizationExpiresAt:Oe.authorizationExpiresAt??rt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...sn,checkoutMethod:"card"})},600)}),z=Pe.on("decline",Oe=>{let rt=br.current,Pt=Oe.message??"Your payment was declined. Please try another card or contact your bank.";T.current="terminal",kt(!1),rt.updateError(Pt),U("error");let sn=Oe.failureOutcome??$y(Oe.declineReason)??"authorization_declined";rt.emitDecline("card",Pt,{code:sn,declineCode:sn}),p()}),me=Pe.on("error",Oe=>{let rt=br.current,Pt=wy(Oe.vaultOutcome);if(Pt!==null){r&&(clearTimeout(r),r=null),T.current="idle",kt(!1),rt.updateError(Pt),U(null),ve(rr=>rr+1),rt.onError?.(new Rr(Pt,"api_error",{code:ky}));return}let sn=Oe.message??"There was a problem processing your payment. Please try again.";T.current="terminal",kt(!1),rt.updateError(sn),U("error"),rt.onError?.(new Rr(sn,"api_error",{code:Oe.failureOutcome??"capture_failed"})),p()}),Tt=Pe.on("challenge_dismissed",()=>{b.current&&(clearTimeout(b.current),b.current=null),T.current="processing",kt(!0),U(null)}),Mt=Pe.on("blocked",()=>{if(Ce.current){br.current.updateError(gm);return}if(!Il.current){sr(!0);return}Vi(),br.current.updateError(Ed)});return()=>{r&&(clearTimeout(r),r=null),b.current&&(clearTimeout(b.current),b.current=null),T.current="idle",kt(!1),U(null),B(),Q(),z(),me(),Tt(),Mt()}},[ne,Pe,Vi,Rl]);let Fr=!!je?.clientId,ma=Array.isArray(X),Ja=ma&&X.length>0,El=ma&&X.includes("paypal"),Xa=q(null);Xa.current===null&&(Xa.current=Oy());let zo=Xa.current?"redirect":sc(E,He,H.current()),{expressMethods:Za,paymentElementMethods:es}=vt(()=>Wy(X,{excludePaypal:Fr}),[X,Fr]),_l=Fr||!!W||El&&zo==="redirect",mu=vt(()=>_l?Za.filter(r=>r!=="paypal"):Za,[Za,_l]),fu=vt(()=>{let r=[];return at&&r.push("apple_pay"),pt&&r.push("google_pay"),r},[at,pt]),qo=ma?mu:fu,gu=I&&qo.length>0,Tl=se?ye:_e,Qa=vt(()=>xy(es,Tl,Ne),[es,Tl,Ne]),ts=vt(()=>({mode:"payment",amount:ya,currency:Lo,paymentMethodCreation:"manual",appearance:gl}),[ya,Lo,gl]),[ns,Ml]=oe("loading"),[rs,Al]=oe("loading"),[os,xl]=oe("loading"),[hu,as]=oe(!1),[Fl,is]=oe("loading"),[ss,Pu]=oe();Xe(()=>{Pu(ka())},[]);let ei=ss?.inAppBrowser,ti=ss?di(ss,je?.approvalPresentation,Dn??(et?"subscription":"order")):"popup",Bl=de&&(Fr||(ma?El:ei===!1)),vu=E.inAppBrowser&&H.current()==="blocked",Dl=I&&gu&&!vu,Po=(!cn||!!J.waitForDataAttachment)&&Bl&&Fr,ls=Fl==="retrying"||Fl==="exhausted",fa=null;I&&(W?fa=fl:zo==="redirect"&&(fa=nr));let Ol=vt(()=>({...tt,presentationMode:zo}),[tt,zo]),vo=!cn&&Bl&&!!fa&&(!Fr||ls),Qr=!cn&&Dl&&!!nr,Co=!cn&&I&&Ja&&Qa.length>0&&!!nr,Cu=Po&&!ls?hu:vo&&Ra(ns),bu=Qr&&Ra(rs),Su=Co&&os!=="load_error",Ll=[Po||vo,Qr,Co,ne].filter(Boolean).length,wu={card:ne,paypal:Po&&!ls||vo&&Ra(ns),wallets:Qr&&Ra(rs),apms:Co&&os!=="load_error"},Nl=r=>wu[r],Ul=r=>r==="loading"||r==="ready",zl=Po||vo&&Ul(ns)||Qr&&Ul(rs)||Co&&os!=="load_error",ni=q(!1);Xe(()=>{if(!ni.current){if(!I&&!de){ni.current=!0;let r=new Rr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(r),ge(r.message)}else if(!I&&de&&!Fr){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");c?.(r),ge(r.message)}else if(ei!==void 0&&!cn&&!Fn&&!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"});c?.(r),ge(r.message)}}},[I,de,Fr,ei,cn,Fn,zl,c,ge]);let ql=q(!1);Xe(()=>{if(ql.current||!Ja)return;let r=[];at!==!0&&r.push("showApplePay"),pt!==!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,at,pt]);let jl=Be((r,p,B)=>J.applyInlineSessionPatch?J.applyInlineSessionPatch(r).then(Q=>({error:null,sessionId:Q.sessionId||e,nonce:Q.session?.clientSecret||t})).catch(Q=>{let z=bd(p,Q);return B?.abandoned?.()||(ge(z.message),c?.(z)),{error:z,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[J.applyInlineSessionPatch,t,c,e,ge]),Sr=Be(async(r,p)=>{if(r!=="card"&&cn&&await J.waitForDataAttachment?.(),!lt)return{proceed:!0};try{let B=await lt({method:r,sessionId:e||void 0,createSession:J.inlineSessionDraft});if(B===!1)return{proceed:!1};if(B&&typeof B=="object"){B.account&&on(z=>({...z??{},...B.account}));let Q=await jl(B,r,p);return Q.error?{proceed:!1,accountPatch:B.account}:{proceed:!0,accountPatch:B.account,sessionId:Q.sessionId,nonce:Q.nonce}}return{proceed:!0}}catch(B){if(!p?.abandoned?.()){let Q=bd(r,B);ge(Q.message),c?.(Q)}return{proceed:!1}}},[jl,J.inlineSessionDraft,J.waitForDataAttachment,cn,lt,c,e,ge]),$l=Be(async(r,p)=>{if(Z.current)return;Z.current=!0,zt(!0),U("processing"),ge(null);let B=p?.sessionId??e,Q=p?.nonce??t,z=Is(ht,p?.accountPatch),me=p?.completionPaymentMethodId??_a(r),Tt=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,Mt=bm(r),Oe=p?.presentationMode?Ti(fn(Y),{...tt,presentationMode:p.presentationMode}):void 0,rt=()=>{f?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Mt}),Oe?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Ir,requestCategory:"process_payment"})};try{let Pt=new la(Xr),rr=p?.settledProcessResponse??await Pt.processPayment(z.userId??"",{sessionId:B,nonce:Q,paymentMethodCategory:p?.paymentMethodCategory??wm(r),tokenizedData:Tt,accountData:{...p?.accountPatch,userId:z.userId??"",email:z.email??"",firstName:z.firstName||void 0,lastName:z.lastName||void 0,...by({avsConfig:h,country:en.current,zip:Qt.current,city:zn.current,state:xn.current,addressLine1:Vt.current,addressLine2:Un.current})},...Cy({chv:ee,avsCheck:dt,checkoutType:Ke,checkoutLayout:yt,avsConfig:h,country:en.current})}),si=async Pn=>{let bo=zs($)||Pn?.status==="authorized";oa(B),Oe?.terminal({outcome:"payment_succeeded",...Ir}),U("success"),tr(null),await new Promise(Sa=>setTimeout(Sa,600));let Br;typeof Pn?.paymentId=="string"?Br=Pn.paymentId:$?.paymentId&&(Br=$.paymentId);let So;typeof Pn?.authorizationExpiresAt=="string"?So=Pn.authorizationExpiresAt:$?.authorizationExpiresAt&&(So=$.authorizationExpiresAt),s?.(bo?{status:"authorized",...Br===void 0?{}:{paymentId:Br},sessionId:typeof Pn?.sessionId=="string"?Pn.sessionId:B,...So===void 0?{}:{authorizationExpiresAt:So},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:me,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:me,checkoutMethod:r.isPaypal?"paypal":"card"})};if(rr.ok){await si(rr.status===204?null:await rr.json().catch(()=>null));return}let ln=await rr.json().catch(()=>null);if(ln?.type==="paypal_redirect_required"){let Pn=ln.threeDSecureToken,bo=ln.paymentMethodId||r.id||"";if(!Y||!Pn){U("error"),ge("PayPal authorization required but no token provided.");return}try{let Br=W?.getRawProvider();if(!Br){ge("PayPal is not available.");return}let So={return_url:window.location.href};bo&&(So.payment_method=bo);let{error:Sa}=await Br.confirmPayment({clientSecret:Pn,confirmParams:So,redirect:"if_required"});if(Sa){U("error");let rc=Sa.message??"PayPal payment failed.";ge(rc),xr("paypal",rc,{code:Sa.code})}}catch(Br){U("error"),ge(Br instanceof Error?Br.message:"PayPal authorization failed.")}return}if(ln?.type==="paypal_direct_required"){let Pn=ln.orderId;if(!Pn){U("error"),ge("PayPal retry required but no order id provided.");return}let bo=Vn.current?.attempts??0;if(bo>=2){U("error"),ge("PayPal payment could not be completed after multiple attempts."),xr("paypal","paypal_direct_required retry limit exceeded");return}as(!1),is("loading"),tr({orderId:Pn,attempts:bo+1}),U(null);return}if(rr.headers.get(lm)===cm){let Pn=await dm(Pt,B,Q);if(Pn!==void 0){await si(Pn);return}}Ey(rr.status,ln)?Oe?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}):rt(),U("error");let nc=ln?.message??"Payment failed. Please try again.";ge(nc),xr(r.isPaypal?"paypal":"card",nc,{code:ln?.code??ln?.gatewayErrorCode,declineCode:ln?.declineCode??ln?.gatewayDeclineReason}),await new Promise(Pn=>setTimeout(Pn,400))}catch(Pt){qd(Pt)||rt(),U("error"),ge(Pt instanceof Error?Pt.message:"An unexpected error occurred"),await new Promise(sn=>setTimeout(sn,400))}finally{zt(!1),U(null),Z.current=!1}},[Xr,e,t,ht,h,dt,Ke,yt,ee,Y,W,$,s,ge,xr,f,tt]),Gn=Be((r,p)=>{g&&!p?.settledProcessResponse?g(r):$l(r,p)},[g,$l]),ga=`${Ud}:${e}`;Xe(()=>{if(typeof window>"u")return;let r=localStorage.getItem(ga);if(!r)return;let p;try{p=JSON.parse(r)}catch{rn(ga);return}if(!p||typeof p.createdAt!="number"||Date.now()-p.createdAt<0||Date.now()-p.createdAt>zd||typeof p.paymentMethodId!="string"||typeof p.providerIntentId!="string"||typeof p.paymentMethodType!="string"||p.sessionId!==e||!t||p.nonce!==t||!qo.includes(p.paymentMethodType)){rn(ga);return}rn(ga),Gn({id:p.paymentMethodId,type:"card",threeDSecureActionResultTokenId:p.providerIntentId,gateway:"stripe",paymentMethodType:p.paymentMethodType},{...p.accountPatch?{accountPatch:p.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Gn,t,e,ga,qo]);let Wl=q(!1);Xe(()=>{if(typeof window>"u"||Wl.current)return;let[r,p,B]=Bd();if(!r||!p||Xa.current||!Y)return;let Q=Y.getRawProvider();if(!Q)return;let z=rt=>{let Pt=localStorage.getItem(rt);if(!Pt)return null;try{return JSON.parse(Pt)}catch{return rn(rt),null}},me=z(Lr)??z(kd),Tt;if(me?.clientSecret){if(me.clientSecret!==p)return;Tt={...me.accountPatch?{accountPatch:me.accountPatch}:{},...me.sessionId?{sessionId:me.sessionId}:{},...me.nonce?{nonce:me.nonce}:{}}}else if(me?.sessionId&&me.sessionId!==e)return;Wl.current=!0,rn(Lr),rn(kd),window.history.replaceState({},"",Od());let Mt=me?.paymentMethodType??me?.tokenType??"card",Oe="card";(async()=>{if(B==="failed"){let ln="Payment was declined. Please try again.";ge(ln),xr(Oe,ln);return}let{paymentIntent:rt,error:Pt}=await Q.retrievePaymentIntent(p);if(Pt){let ln=Pt.message??"Failed to retrieve payment status.";ge(ln),xr(Oe,ln,{code:Pt.code});return}let sn=rt?.status,rr=Ea(sn);if(!rt||!rr){let ln=sn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ge(ln),xr(Oe,ln,{code:sn??"missing_payment_intent"});return}let si=typeof rt.payment_method=="string"?rt.payment_method:rt.payment_method?.id;Gn({id:si??me?.paymentMethodId??me?.tokenId??rt.id,type:"card",threeDSecureActionResultTokenId:rt.id,gateway:me?.gateway??"stripe",paymentMethodType:Mt},Tt)})()},[e,Gn,Y,ge,xr]);let cs=Be(r=>{r.preventDefault()},[]);if(!(ne||Y!==null))return l("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ha=Ie==="buttons",qn=Bo?.variables,ku=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ds=qn?.colorBackground,Ru=ds&&!ku.has(ds)?ds:void 0,Pa=Fe.cardInputBorder??(ha?"#e5e7eb":"#A4A4FF"),Hl=qn?.colorDanger??"#dc2626",Jt=r=>hr[r]&&(fo[r]||Pr),ri=Oo&&(mo||Pr),dr=r=>r?Hl:Pa,oi=(wn.malformed||wn.empty)&&(yo||Pr),Iu=dr(oi),us=Fe.cardFormContainer?.backgroundColor??Ru??(ha?"white":"#EDEDFF"),jo=Fe.cardInputBackground??qn?.colorBackground??"white",ps=Ko(te),Kl=Ko(ue),$o=Fe.nameInput,Vl=Fe.cardInputFontSize??Em($o?.fontSize)??qn?.fontSizeBase??"16px",Gl=typeof $o?.fontFamily=="string"?$o.fontFamily:qn?.fontFamily??"Poppins, sans-serif",Yl=Qy($o?.fontWeight)??400,Eu=Fe.cardInputColor??(typeof $o?.color=="string"?$o.color:void 0)??qn?.colorText??"#262833",_u=Fe.cardInputPlaceholderColor??"#9ca3af",nn=qn?.borderRadius??"8px",Hr=qn?.borderRadius??Fe.cardButton?.borderRadius??nn,eo=qn?.colorPrimary??"#4A49FF",Tu=qn?.colorPrimaryHover??My(eo,.12),ys=qn?.colorText??"#262833",ms={fontSize:Vl,fontFamily:Gl,fontWeight:Yl,color:Eu,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},va={marginTop:"0.375rem",...ms,fontSize:"0.75rem",lineHeight:1.4,color:Hl},Mu={"--flopay-input-placeholder-color":_u,"--flopay-input-font-size":Vl,"--flopay-input-font-family":Gl,"--flopay-input-font-weight":String(Yl)},Ca=Fe.cardFormContainer??{},fs=Ca.padding??(ha?"0":"1rem"),gs=Ca.borderRadius??nn,Au=Pe&&Yt?l(Ps,{capture:Pe,html:Yt.html,messageToken:Yt.messageToken,expectedOrigin:Yt.expectedOrigin,verificationRequired:Yt.verificationRequired,theme:uu,submitLabel:j,onReady:()=>{if(!Zr&&!h||typeof document>"u"||Ue===!1)return;let r=()=>{let B=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(B){lr.current=!0;try{B.focus()}finally{lr.current=!1}}};ho.current||r()},onError:r=>{r&&Yt.verificationRequired&&T.current==="idle"&&(We.current=!0),ge(r)},onValidation:r=>{let p=T.current;(p==="idle"||p==="validation-window")&&(ge(r),r&&T.current==="validation-window"&&(b.current&&(clearTimeout(b.current),b.current=null),T.current="idle",U(null)))}},v):l("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),hs=Le("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&P()},style:{backgroundColor:us,borderRadius:gs,...Ca,padding:fs,...Mu,display:"flex",flexDirection:"column"},children:[l("style",{children:`
|
|
3
|
+
${he.join(`
|
|
4
|
+
`)}`]}):null;return V&&!h?be?Mo("div",{children:Tn}):null:Ms("div",{children:[Tn,lt&&Mo(ta,{identity:lt.identity,methodLabel:lt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ct,onCancel:()=>Ct(null)}),Ms("div",{"aria-hidden":Ze||lt?!0:void 0,style:Ze||lt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ci},children:[!Ve&&!Ze&&Mo("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),Mo("div",{ref:le,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ci,display:"flex",opacity:Ve?1:0},"aria-busy":_e||pe},De)]},De),Ee&&Mo("button",{ref:ht,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Qt,style:Fp,children:"Try PayPal again"})]})}function bi(e){return Mo(Hc,{...e})}function Vc(e){return Mo(Hc,{...e})}import{jsx as Gc,jsxs as Lp}from"react/jsx-runtime";function oa({children:e,margin:t,icon:n=!0,styleOverride:o}){return Lp("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...o??{}},children:[n&&Gc("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Gc("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{clearCachedInlineCheckout as Si,clearCachedInlineSession as As,hashCreateParams as Yc,legacyCachedSessionMatchesDraft as Jc,persistCachedInlineIdempotencyKey as wi,persistCachedInlineSession as ki,readCachedInlineIdempotencyKey as Xc,readCachedInlineSession as Zc,serializeCreateParams as Ba}from"@flopay/shared";var Qc=new Set;function Np(){return globalThis.process?.env?.NODE_ENV==="production"}function ed(e,t){Qc.has(e)||Np()||(Qc.add(e),console.warn(t))}function td(){ed("automatic-payment-button-inline-create","[FloPay] FloPayAutomaticPaymentButton: creating the session from inline props is deprecated and may be downgraded to a Full checkout. Mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and pass `getSession` instead.")}function nd(){ed("checkout-keyless-create","[FloPay] FloPayCheckout: `createSession` with checkoutMode confirm/auto is deprecated and may be downgraded to a Full checkout. For one-click, mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and use FloPayAutomaticPaymentButton `getSession`.")}import{isCardFieldsInstrumentSource as Up,resolveBillingApiUrl as zp}from"@flopay/shared";import{useCallback as qp,useEffect as mo,useMemo as jp,useRef as rd,useState as od}from"react";import{jsx as $p}from"react/jsx-runtime";function Ri({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,l]=od(e instanceof Promise?null:e),[u,m]=od(t instanceof Promise||!t?null:t),R=rd(null),C=rd(null),g=na(o),A=qp(D=>{Up(D)||g(D)},[g]);mo(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),mo(()=>{i&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,i]),mo(()=>{if(i)return hn(i)?.subscribe?.(A)},[A,i]),mo(()=>{if(!(!u||u===i))return hn(u)?.subscribe?.(A)},[A,i,u]),mo(()=>{if(!i)return;let D=hn(i);return R.current=D?.beginCheckout()??D?.now()??0,D?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{D?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),mo(()=>{let D=!1;return e instanceof Promise?e.then(K=>{D||l(K)},()=>{D||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{D=!0}},[g,e]),mo(()=>{let D=!1;if(!t){m(null);return}return t instanceof Promise?t.then(K=>{D||m(K)},()=>{D||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{D=!0}},[g,t]),mo(()=>{if(!i||C.current===i)return;C.current=i;let D=hn(i);D?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),D?.performance({stage:"checkout_render",durationMs:D.elapsed(R.current??0),durationMode:"machine"})},[g,i]);let X=zp(n?.billingApiUrl),te=jp(()=>({flopay:i,paypalFlopay:u,billingApiUrl:X,emitInstrument:g}),[i,u,X,g]);return $p(pr.Provider,{value:te,children:a})}import{markSessionRecentlyCompleted as aa,wasSessionRecentlyCompleted as xs}from"@flopay/shared";async function Ii(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{beginSavedCardChallengeTelemetry as Wp,completeSavedCardNextAction as Kp,loadFloPay as ad,PaymentAPI as Oa,runSavedCardChallenge as Hp}from"@flopay/js";import{classifyPaymentRejection as Vp,FloPayError as Tt,isAuthorizationOnlySession as Gp,isMerchantAuthRequired as Bs,isMountableVaultBlock as Yp,isSetupIntentClientSecret as Jp,MERCHANT_AUTH_REQUIRED_CODE as Xp,normalizeCheckoutFailureOutcome as id}from"@flopay/shared";var Na="card";async function Zp(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:o??null}}async function Qp(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:u}=await e.confirmCardSetup(t,n);return{error:u,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function ia(e){return new Tt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function ey(){return new Tt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function La(e,t){return Object.assign(e,{checkoutMethod:t})}function Qr(e,t){let n=e instanceof Tt?e:new Tt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Da(e,t){try{return await e()}catch(n){throw Qr(n,t)}}function ld(e){return!e?.type||!e.threeDSecureToken||Bs(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function cd(e){return Hp(e)}function Ua(e,t,n,o=!0){let a={release:()=>{}};if(!o)return a;try{let i=new Oa(e),l=Wp(i,t,n);return l?{telemetry:l,release:()=>{setTimeout(()=>{try{i.destroy()}catch{}},0)}}:a}catch{return a}}async function sa(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,l=new Oa(n,{telemetry:!1}),u=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,m;try{m=await Kp({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:C=>zr({type:C.declineReason??"authorization_declined",gatewayErrorCode:C.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(C){if(a.aborted||C instanceof Error&&C.name==="AbortError")throw C instanceof Tt&&C.code==="three_ds_aborted"?C:ia(C);if(!(C instanceof Tt)||C.code!=="three_ds_timeout"&&C.code!=="checkout_processing_timeout")throw C;try{m=await l.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:u,timeoutMs:5e3,signal:a})}catch(A){if(a.aborted)throw ia(A);if(!(A instanceof Tt)||A.code!=="checkout_processing_timeout")throw A}let g=m&&co(m,t.session);if(!Xr(g)&&g?.status!=="expired"){if(t.telemetry){let A=new Oa(n);try{A.reportThreeDsAbandoned(o)}finally{A.destroy()}}throw ey()}}let R=m&&co(m,t.session);if(!Xr(R))throw Zo(R);return{...Jr(R,o),checkoutMethod:"card"}}function dd(e){return new Tt("This payment needs your card details. Please complete your payment below.","authentication_error",{code:Xp,...e===void 0?{}:{statusCode:e}})}function zr(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if(Bs(e))return La(dd(),o);let a=e?.message??t,i=Qo(a)??a,l=La(new Tt(i,"api_error",{code:e?.code??id(e?.outcome)??id(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),o);return e?.orderId&&(l.orderId=e.orderId),l}function Fs(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ei(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ud(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ei(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let u of i)if(typeof u=="string"&&u.length>0&&(!t?.requirePaymentIntentClientSecret||Ei(u)))return u;let l=a.gateways;if(l&&typeof l=="object"){let u=l.stripe;if(u&&typeof u=="object"){let m=u,R=[m.stripeClientSecret,m.clientSecret];for(let C of R)if(typeof C=="string"&&C.length>0&&(!t?.requirePaymentIntentClientSecret||Ei(C)))return C}}}}async function ty({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=ud(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let u=(await new Oa(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ei(u))return{type:"3ds_required",threeDSecureToken:u}}catch{}return null}async function la({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:l}){let u=e.replace(/\/+$/,""),m=t??n.id,R=o??n.clientSecret,C=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",A=n.customer?.firstName??n.accountData?.firstName??"",X=n.customer?.lastName??n.accountData?.lastName??"",te=n.customer?.country??n.accountData?.country??void 0,D=n.customer?.zip??n.accountData?.zip??void 0,w=await new Oa(u,l===!1?{telemetry:!1}:void 0).processPayment(C,{sessionId:m,nonce:R,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:C,email:g,firstName:A,lastName:X,country:te,zip:D},returnUrl:i??Fs(n)});if(w.ok){let se=typeof w.json=="function"?await w.json().catch(()=>null):null;if(Gp(n)||se?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof se?.paymentId=="string"?se.paymentId:n.paymentId,sessionId:typeof se?.sessionId=="string"?se.sessionId:m,authorizationExpiresAt:typeof se?.authorizationExpiresAt=="string"?se.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:_a(a),checkoutMethod:sd(a,n)}};let I=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...I?{paymentIntentId:I}:{},paymentMethodId:_a(a),checkoutMethod:sd(a,n)}}}let pe;try{pe=await w.json()}catch(se){throw new Tt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:w.status,cause:se})}if(Bs(pe))throw La(dd(w.status),"card");if(pe?.type==="3ds_required"&&typeof pe.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:pe.nextActionRedirectUrl};if(pe?.type==="paypal_redirect_required"||pe?.type==="3ds_required"){let se=ud(pe);if(!se)throw new Tt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:w.status});return{type:pe.type,threeDSecureToken:se,paymentMethodId:pe.paymentMethodId}}if(pe?.gatewayErrorCode==="authentication_required"){let se=await ty({billingApiUrl:u,sessionId:m,nonce:R,responseJson:pe});if(se)return se;throw La(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw ny(pe,w.status)}function ny(e,t){let n=new Tt(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(n,{telemetryOutcome:Vp(t,e)})}async function _i(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:l,returnUrl:u,telemetry:m,signal:R}){let C=t?.getRawProvider();if(!C)throw Qr(new Tt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw La(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Jp(e.threeDSecureToken),A=null,X=e.paymentMethodId,te=await Da(()=>Zp(C,e.threeDSecureToken,g),"card");if(te){if(te.error)throw Qr(new Tt(te.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:te.error.code}),"card");let K=te.intent;!X&&K?.payment_method&&(typeof K.payment_method=="string"?X=K.payment_method:"id"in K.payment_method&&(X=K.payment_method.id??void 0))}let D=X?await Da(()=>Qp(C,e.threeDSecureToken,{payment_method:X,return_url:u??Fs(l)??window.location.href},g),"card"):null;if(D){if(D.error)throw Qr(new Tt(D.error.message??"3DS authentication failed.","api_error",{code:D.error.code}),"card");A=D.intent}else{let K=await Da(()=>C.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(K.error)throw Qr(new Tt(K.error.message??"3DS authentication failed.","api_error",{code:K.error.code}),"card");A=(g?K.setupIntent:K.paymentIntent)??null}if(A&&(A.status==="requires_capture"||A.status==="succeeded"||A.status==="processing")){let K=await la({billingApiUrl:a,sessionId:i,session:l,telemetry:m,tokenizedData:{id:A.id,type:"card",threeDSecureActionResultTokenId:A.id},returnUrl:u});return K.type==="success"?{...K.result,paymentIntentId:K.result.paymentIntentId??A.id,paymentMethodId:K.result.paymentMethodId??X}:K.type==="next_action_required"?sa(K,{billingApiUrl:a,sessionId:i??l.id,session:l,signal:R}):_i(K,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:l,returnUrl:u,telemetry:m,signal:R})}throw Qr(new Tt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Qr(new Tt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:X}=await Da(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(X)throw Qr(new Tt(X.message??"PayPal authorization failed.","api_error",{code:X.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:A}=await Da(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:u??Fs(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(A)throw Qr(new Tt(A.message??"PayPal authorization failed.","api_error",{code:A.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Tt("Unsupported payment redirect state.","api_error")}function za(e){if(e instanceof Tt){let o=Qo(e.message);return o&&o!==e.message?Object.assign(new Tt(o,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Qo(t)??t;return new Tt(n,"api_error")}function Ds(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=Yp(e.data.session?.vault)||_o(e.data.session);if(!t&&!n&&!o)throw new Tt("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function sd(e,t){return e?e.isPaypal?"paypal":"card":t&&_o(t)?"card":void 0}async function Os({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:o,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[l,u]=await Promise.all([ad(e,{billingApiUrl:n,locale:o,telemetry:a}),i?ad(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(R=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",R),null)):Promise.resolve(null)]);if(!l)throw new Tt("The payment provider did not initialize.","authentication_error");let m=null;return i?m=u:t&&(m=l),{flopay:l,paypalFlopay:m}}import{PaymentAPI as ca,PciVaultCardCapture as Py,toStripeAppearance as vy}from"@flopay/js";import{buildCardFieldLabelsPayload as Cy,buildCheckoutProcessMetadata as by,buildProcessPaymentAvsAccount as Sy,buildWalletSheetWindowMessage as wy,buyerEmailRequiredPrompt as ky,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as Ry,COUNTRY_OPTIONS as Iy,cardFieldsInstrumentSource as Ey,classifyPaymentRejection as _y,clearStripePayPalReturn as Ty,computeVaultCardThemeColors as My,darkenHex as Ay,denyPaymentPermissionToNewFrames as xy,FloPayError as Rr,filterStripeMethodsByCountryGate as Fy,getPostalCodeExample as By,getPostalCodeLabel as Vs,getStateFromPostalCode as Dy,getStateLabel as Us,getStateOptions as Oy,getStripeMethodDisplayName as Wa,hasMatchingStripePayPalReturn as Ly,invokeMerchantCallback as vd,isAuthorizationOnlySession as zs,isAVSFieldVisible as nn,isCardFormFirst as Ny,isMountableVaultBlock as Uy,isPostalCodeSupported as zy,isSettledSessionIntent as Fi,isSetupIntentClientSecret as qs,isValidEmail as xn,isValidPostalCode as qy,isWalletSheetRefusedForWindowSize as jy,keyPaymentMethodOrder as $y,needsStripeMethodExplicitConfirm as Cd,normalizeBeforeButtonClickError as bd,normalizeCheckoutFailureOutcome as Wy,partitionStripeMethods as Ky,placePaymentMethodGroups as Sd,randomUuidV4 as Hy,readMatchingStripePayPalContinuation as Vy,readStripeRedirectParams as Bd,resolveAVSConfig as Gy,resolveButtonsLayoutTheme as Yy,resolveSetupFutureUsage as Dd,resolveTheme as Jy,resolveVaultMountOptions as js,STRIPE_PAYPAL_RESUME_KEY as Xy,derivePrimaryTileStyle as Zy,shouldPreferWalletPopup as wd,stripeExpressMethodToOptionKey as Qy,stripeRedirectReturnUrl as Od,toCssWeight as em,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as Ld}from"@flopay/shared";import{ExpressCheckoutElement as Nd,PaymentElement as tm,useElements as Xs,useStripe as Zs}from"@stripe/react-stripe-js";import ja,{useCallback as Be,useContext as da,useEffect as Je,useLayoutEffect as nm,useMemo as gt,useRef as B,useState as ee}from"react";function Ao(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ti(e,t){if(e)return{error:n=>e.error(Ao(t,n)),log:n=>e.log(Ao(t,n)),performance:n=>e.performance(Ao(t,n)),terminal:n=>e.terminal(Ao(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}import{useEffect as ry,useId as oy,useRef as pd}from"react";import{Fragment as sy,jsx as yd,jsxs as ly}from"react/jsx-runtime";var md="More payment options",ay={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},iy={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Ls({label:e,open:t,showLink:n,onOpen:o,color:a,fontFamily:i,children:l}){let u=oy(),m=pd(null),R=pd(!1);return ry(()=>{t&&R.current&&m.current?.focus()},[t]),ly(sy,{children:[!t&&n&&yd("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":u,onClick:()=>{R.current=!0,o()},style:{alignSelf:"center",margin:0,padding:"0.25rem 0",border:0,background:"none",cursor:"pointer",color:a,fontFamily:i,fontSize:"0.9rem",fontWeight:500,textDecoration:"underline",textUnderlineOffset:"0.2em"},children:e}),yd("div",{id:u,ref:m,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?iy:ay,children:l})]})}import{jsx as fd}from"react/jsx-runtime";var cy=["first","second","third","fourth"];function Ns({rows:e,borderRadius:t}){return fd("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:cy.slice(0,Math.max(1,e)).map(n=>fd("div",{style:{height:Eo,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},n))})}import{PaymentAPI as dy}from"@flopay/js";import{DEFAULT_PAYMENT_METHOD_ORDER as uy,resolveDefaultPaymentMethodLayout as py}from"@flopay/shared";import{useEffect as yy,useState as my}from"react";var fy=1500,gd=new Set;function hd(e){for(let t of e)gd.has(t)||(gd.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function gy(e){if(e!=null)try{return JSON.stringify(e)}catch{return hd(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var hy={order:[...uy],moreOptions:[]};function Pd({rules:e,sessionId:t,nonce:n,billingApiUrl:o,waitForSession:a}){let i=gy(e),[l,u]=my(null);return yy(()=>{if(i===void 0||a)return;let m=JSON.parse(i),R=!1,C=te=>{R||(R=!0,u(te))},g=()=>C(py(m));if(!t||!n||!o){g();return}let A=new AbortController,X=setTimeout(()=>{g(),A.abort()},fy);return new dy(o,{telemetry:!1}).resolvePaymentMethodLayout(t,n,m,{signal:A.signal}).then(te=>{if(!te){g();return}R||hd(te.warnings),C({order:te.order,moreOptions:te.moreOptions})}).catch(g).finally(()=>clearTimeout(X)),()=>{R=!0,clearTimeout(X),A.abort()}},[i,t,n,o,a]),i===void 0?hy:l}import{darkenHex as Wd}from"@flopay/shared";import{Fragment as Kn,jsx as d,jsxs as Ne}from"react/jsx-runtime";var qr="flopay_stripe_resume",kd="flopay_wallet_resume",Ud="fw1",rm="fw2",zd=300*1e3,om=900,am="express_checkout_click_timeout",im=25e3,sm=25e3,lm=1e4,Ir={provider:"paypal",paymentMethodCategory:"paypal"},cm="x-flopay-process-result-source",dm="status";async function um(e,t,n){try{let o=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(o?.status==="complete")return null;if(o?.status==="authorized")return{status:"authorized",paymentId:o.paymentId,sessionId:o.id||t,authorizationExpiresAt:o.authorizationExpiresAt}}catch{}}var Mi={},$a=class{constructor(t){this.reason=t}};function pm(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function sn(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function Qs(e){return`${rm}:${e}`}function Ai(e){return sn(Qs(e))}function xi(e,t){if(typeof window>"u")return null;let n=Qs(e);try{let o=localStorage.getItem(n);if(!o)return null;let a=JSON.parse(o);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>zd||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Ai(e),null):a}catch{return Ai(e),null}}function ym(e){return sn(Qs(e.sessionId),e)}function Rd(e,t,n){let o=xi(e,t);return!o||o.clientSecret!==n?!1:Ai(e)}function $s(e,t,n){if(typeof window>"u")return;xi(e,t)?.clientSecret===n&&Ai(e)}function mm(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ws(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let o=n?e.status==="succeeded":Ea(e.status),a=mm(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Id(e,t,n){let o=null;try{return await Promise.race([Ic(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},lm),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function fm(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function qd(e){return e instanceof Rr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Bi(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new ca(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw qd(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var Ks=Xy,qa=new Map,gm=250,Ed="Just a moment \u2014 we are finalizing your order. Please press pay again.",hm="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function el(e,t,n,o){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...o?{terminalReason:o}:{}})}async function Di({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new ca(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function Pm(e){return e instanceof Rr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function jd({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=Ta(n),l=i.firstName?i:Ta(o?.name);return kr({email:xn(a)?a:o?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function vm({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let l=jd({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return xn(l.email)?l:i(a,l)}var Ka=180,_d=`flopay-card-enter ${Ka}ms cubic-bezier(0, 0, 0.2, 1) both`,Td=`flopay-card-exit ${Ka}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Cm=`flopay-buttons-enter ${Ka}ms cubic-bezier(0, 0, 0.2, 1) both`,bm=`flopay-buttons-exit ${Ka}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Sm(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function tl(e){return Zy(e)}var wm={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function km(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var Gs={width:"100%",minHeight:Eo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Md(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ys(e){return e==="paypal"?"PayPal":Wa(e)}function Rm(e){let t=By(e);return`Enter a valid ${Vs(e)}${t?` (e.g. ${t})`:""}`}function Im(e,t,n){let o=zy(e),a=t.trim(),i=n&&o,l=i&&!a,u=i&&!!a&&!qy(e,a);return{visible:n,supported:o,required:i,empty:l,malformed:u}}function Em(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!xn(n);return{required:t,empty:o,malformed:a,value:n}}function _m(e){return typeof e=="number"?`${e}px`:e}var Tm=["number","expiry","cvv","name"];function Mm(e){if(e===null||typeof e!="object")return null;let t={};for(let n of Tm){let o=e[n];typeof o=="string"&&(t[n]=o)}return JSON.stringify(t)}function nl(e){return d(Fm,{...e})}function Ad({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:l=!1,onButtonClick:u,onDecline:m,onTechnicalFailure:R,runBeforeButtonClick:C,billingName:g,onBuyerIdentityReady:A,onLoadStateChange:X,placeholderBorderRadius:te,popupCapabilityOwner:D,externalTelemetryContext:K,presentationMode:w}){let pe=po(),{emitInstrument:se}=da(pr),I=Zs(),We=Xs(),G=gt(()=>Ti(hn(pe),K),[K,pe]),[Ue,rt]=ee("loading");Je(()=>{X?.(Ue)},[Ue,X]);let[dt,Re]=ee(!1),Nt=B(!1),Dt=!xn(n?.trim())||!g?.trim(),{request:be,collect:He,finish:ot}=ea(),at=B(!1),Ie=B(null),Z=B(null),[le,Kt]=ee(0),[je,it]=ee(!1),Q=B(!1),Te=B(new Map),{startAttempt:Xe,finishAttempt:H,invalidateAttempt:ht,isAttemptInvalidated:Ce,isAttemptCurrent:Ve,generationRef:ze}=xa((ce,_e,st)=>{R?.(ce,_e,{...st,popupBlocked:st?.popupBlocked??so(_e),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:w,terminalReason:"overlay_timeout"}),it(!0),Kt(lt=>lt+1)},{onHandoffObserved:()=>{D.markAvailable(),G?.log({name:"provider.popup.opened",stage:"overlay_open",...Ir,attempt:ze.current})}});Je(()=>{je&&Z.current?.focus()},[je,le]);let Ze=Be(()=>{Kt(ce=>ce+1)},[]),Pt=Be((ce,_e,st)=>{ht(st),R?.("paypal",ce,{code:_e,popupBlocked:so(ce),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:w}),it(!0),Ze()},[ht,R,w,Ze]),De=Be(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);Je(()=>{Q.current&&(Q.current=!1,De())},[De,le]);let wt=Be(()=>{it(!1),i?.(null),De()},[De,i]);Je(()=>{if(!I||at.current)return;let[ce,_e,st]=Bd();if(!ce||!_e)return;let lt=Vy(_e);if(!lt)return;at.current=!0;let Ke=!0,Ct=qa.get(_e);Ct||(Ct=st==="failed"?Promise.resolve(null):Promise.resolve().then(()=>I.retrievePaymentIntent(_e)),qa.set(_e,Ct));let _t={accountPatch:lt.accountPatch,sessionId:lt.sessionId,nonce:lt.nonce},ct=()=>{G?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Ir,requestCategory:"provider_sdk"})};return G?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Ir}),(async()=>{try{Re(!0);let Qe=await Ct;if(!Ke)return;if(Qe?.error){qa.delete(_e),ct(),i?.(Qe.error.message??"Failed to retrieve PayPal payment status.");return}if(Ty(),qa.delete(_e),st==="failed"){let z="PayPal payment was declined. Please try again.";G?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}),i?.(z),m?.(gn("paypal",z));return}let et=Qe?.paymentIntent;if(et&&et.id!==ce){ct(),i?.("Failed to match the returned PayPal payment.");return}if(et&&(et.status==="requires_capture"||et.status==="succeeded")){let z=typeof et.payment_method=="string"?et.payment_method:et.payment_method?.id;a({id:z??et.id,type:"card",threeDSecureActionResultTokenId:et.id,isPaypal:!0},{..._t,presentationMode:"redirect"})}else{let z="PayPal payment was not completed. Please try again.";G?.terminal({outcome:et?.status==="canceled"?"payment_cancelled":"payment_declined",...Ir,terminalReason:et?.status==="canceled"?"cancelled":"provider_declined"}),i?.(z),m?.(gn("paypal",z))}}catch(Qe){if(!Ke)return;qa.delete(_e),ct(),i?.(Qe instanceof Error?Qe.message:"Failed to complete PayPal payment.")}finally{Ke&&Re(!1)}})(),()=>{Ke=!1,at.current=!1}},[I,a,i,m,G]);let Me=Be(async(ce=!1)=>{let _e=C?await C("paypal"):{proceed:!0};if(!_e.proceed)return Te.current.delete(le),!1;let st=Xe("paypal");return Te.current.set(le,{generation:st,accountPatch:_e.accountPatch,sessionId:_e.sessionId,nonce:_e.nonce}),it(!1),G?.log({name:`provider.${ce?"redirect.started":"handoff.requested"}`,stage:ce?"redirect":"overlay_open",...Ir,attempt:st}),u?.("paypal"),!0},[u,G,C,Xe,le]),Ee=Be(async ce=>{if(l||dt||!await Me()){ce.reject();return}ce.resolve()},[l,Me,dt]),vt=Be(async ce=>{if(!I||!We)return;let _e=Te.current.get(le);if(_e&&!Ve(_e.generation)){Te.current.delete(le);return}if(!_e&&Ce()||_e&&!H(_e.generation))return;_e||H();let st=_e??null;if(Te.current.delete(le),!st&&C){let Ae=await C("paypal");if(!Ae.proceed){ce.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}st={accountPatch:Ae.accountPatch,sessionId:Ae.sessionId,nonce:Ae.nonce}}let lt=st?.sessionId??e,Ke=st?.nonce??t,Ct=await vm({event:ce,prepared:st,email:n,billingName:g,methodLabel:"PayPal",collect:He});if(!Ct){ce.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let _t=Ct.email,ct={...st?.accountPatch,...kr(Ct,!0)};try{if(Re(!0),i?.(null),!lt||!xn(_t))throw new Error("Missing sessionId or email for PayPal payment");await A?.(Ct);let Ae=I.createPaymentMethod,{error:Qe,paymentMethod:et}=await Ae({type:"paypal"});if(Qe){Pt(Qe,"stripe_paypal_create_payment_method_failed",_e?.generation),ce.paymentFailed({reason:"fail"});return}let z=await Bi(o,se,lt,Ke??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:et?.id??null,intentKind:"payment"});if(Fi(z)){ce.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:ct,paymentMethodCategory:"paypal",presentationMode:w,sessionId:lt,nonce:Ke,settledProcessResponse:z.response});return}if(z.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ht=z.clientSecret,k={return_url:Od()};if(et?.id&&(k.payment_method=et.id),!sn(Ks,{clientSecret:Ht,sessionId:lt,nonce:Ke,accountPatch:ct})&&w==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:j,paymentIntent:y}=await I.confirmPayment({clientSecret:Ht,confirmParams:k,redirect:"if_required"});if(j){if(sn(Ks),ci(j)){let h=j.message??"Your payment was declined.";G?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}),i?.(h),m?.(gn("paypal",h,{code:Ho(j),declineCode:bs(j)})),await Di({billingApiUrl:o,sessionId:lt,nonce:Ke,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ho(j)??"provider_declined"}})}else Pt(j,"stripe_paypal_confirm_failed",_e?.generation);return}sn(Ks);let oe=typeof y?.payment_method=="string"?y.payment_method:y?.payment_method?.id;a({id:oe??y?.id,type:"card",threeDSecureActionResultTokenId:y?.id,isPaypal:!0},{accountPatch:ct,paymentMethodCategory:"paypal",presentationMode:w,sessionId:lt,nonce:Ke});return}catch(Ae){Pt(Ae,"stripe_paypal_failed",_e?.generation)}finally{Re(!1)}},[I,We,e,t,n,g,He,A,o,se,a,i,m,C,Pt,H,Ve,Ce,G,w,le]),Ot=Be(async()=>{if(!(Nt.current||l||dt||!I||!We)){Nt.current=!0,Re(!0);try{if(!await Me(!0))return;await vt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Nt.current=!1,Re(!1)}}},[We,vt,l,Me,I,dt]),kt=w==="redirect"?d("button",{type:"button",disabled:l||dt,onClick:()=>{Ot()},style:{width:"100%",minHeight:Eo,border:"1px solid #d1d5db",borderRadius:te??8,background:"#ffc439",color:"#111827",cursor:l||dt?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):d(Nd,{onReady:ce=>rt(Ss(ce,["paypal"])),onLoadError:()=>{rt("load_error"),el(G,"paypal","paypal","provider_error")},onClick:Ee,onConfirm:vt,onCancel:()=>{let ce=Te.current.get(le);Te.current.delete(le),G?.terminal({outcome:"payment_cancelled",...Ir,terminalReason:"cancelled",...ce?{attempt:ce.generation}:{}}),ht(ce?.generation),it(!1),Q.current=!0,Ze()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Dt,emailRequired:Dt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},le),V=Ne(Kn,{children:[Ne("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[je&&d("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:wt,style:Gs,children:"Try PayPal again"}),be&&d(ta,{identity:be.identity,methodLabel:be.methodLabel,onComplete:ot,onCancel:()=>ot(null)},be.id),d("div",{style:{display:be?"none":void 0},children:kt})]}),dt&&!be&&d(Ur,{status:"processing"})]});return w==="redirect"?V:d(ws,{state:Ue,placeholderTestId:"flopay-paypal-placeholder",borderRadius:te,children:V})}function Hs(e){return e==="apple_pay"||e==="google_pay"}var Am=200;function xm({active:e}){return nm(()=>e?xy(document):void 0,[e]),null}function xd({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:l,onErrorChange:u,onButtonClick:m,onDecline:R,onTechnicalFailure:C,runBeforeButtonClick:g,billingName:A,onBuyerIdentityReady:X,onLoadStateChange:te,placeholderBorderRadius:D,popupCapabilityOwner:K,externalTelemetryContext:w}){let pe=po(),{emitInstrument:se}=da(pr),I=Zs(),We=Xs(),G=gt(()=>Ti(hn(pe),w),[w,pe]),[Ue,rt]=ee("loading");Je(()=>{te?.(Ue)},[Ue,te]);let[dt,Re]=ee(!1);Je(()=>{it.current=dt},[dt]);let Nt=B(!xn(n?.trim())||!A?.trim()).current,{request:Dt,collect:be,finish:He}=ea(),ot=B(null),at=B(null),[Ie,Z]=ee(0),[le,Kt]=ee(()=>wd()),je=B(le),it=B(!1),[Q,Te]=ee(!1),[Xe,H]=ee(()=>xi(e,t)?"blocked":"idle"),[ht,Ce]=ee("google_pay"),Ve=B(null),ze=B(!0),Ze=B(!1),Pt=B("google_pay"),De=B("google_pay"),wt=B(null),Me=B(null),Ee=B(new Set),vt=B(null),Ot=B(null);Je(()=>(ze.current=!0,()=>{ze.current=!1;for(let h of Ee.current)window.clearTimeout(h);Ee.current.clear()}),[]);let kt=B(new Map),{startAttempt:V,finishAttempt:ce,invalidateAttempt:_e,isAttemptInvalidated:st,isAttemptCurrent:lt,generationRef:Ke}=xa((h,$,O)=>{C?.(h,$,{...O,popupBlocked:O?.popupBlocked??so($),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Ce(h),Te(!0),Z(he=>he+1)},{onHandoffObserved:h=>{Ot.current=Ke.current,K.markAvailable(),G?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ke.current,...h==="apple_pay"||h==="google_pay"?{walletType:h}:{}})},defersMissingTerminal:Hs,onMissingTerminalDeferred:(h,$)=>{let O=G?.now()??globalThis.performance?.now()??Date.now(),he=vt.current,Se=he?.generation===$?he.startedAt:O;G?.performance({stage:"overlay_return",durationMs:Math.max(0,O-Se),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:$,...Hs(h)?{walletType:h}:{}}),G?.flush?.().catch(()=>{})}});Je(()=>{Q&&at.current?.focus()},[Q,Ie]);let Ct=B(0),_t=B(!1),ct=Be(()=>{if(Ct.current>0){_t.current=!0;return}Z(h=>h+1)},[]),Ae=Be(()=>{Ct.current-=1,!(Ct.current>0||!_t.current)&&(_t.current=!1,ze.current&&Z(h=>h+1))},[]),Qe=Be((h,$,O,he,Se=!1)=>{_e(he),C?.(h,$,{code:O,popupBlocked:so($),telemetryReported:Se,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Ce(h),Te(!0),ct()},[_e,C,ct]),et=Be(h=>{G?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...Hs(h)?{walletType:h}:{}}),C?.(h,new Error("The wallet click was not ready within the time the wallet allows."),{code:am,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Ce(h),Te(!0)},[C,G]),z=Be(()=>{window.setTimeout(()=>{(ot.current?.querySelector("iframe")??ot.current)?.focus()},0)},[]);Je(()=>{Ze.current&&(Ze.current=!1,z())},[z,Ie]);let Ht=Be(()=>{Te(!1),u?.(null),z()},[z,u]),k=Be(()=>{Ve.current?.()},[]);Je(()=>{let h=null,$=()=>{h=null;let he=wd();he!==je.current&&(je.current=he,Kt(he),!it.current&&!lt(Ke.current)&&ct())},O=()=>{h!==null&&window.clearTimeout(h),h=window.setTimeout($,Am)};return window.addEventListener("resize",O),()=>{window.removeEventListener("resize",O),h!==null&&window.clearTimeout(h)}},[Ke,lt,ct]),Je(()=>{let h=xi(e,t);if(!h)return;let $=!1,O=!1,he=async()=>{if(!O){O=!0,$||H("checking");try{let Se=await Id(I,h.clientSecret,Ee.current);if($)return;let _=Ws(Se,h.providerObjectId,qs(h.clientSecret));if(_.kind==="confirmed"){if(!Rd(e,t,h.clientSecret))return;Ve.current=null,H("idle"),l({id:_.paymentMethodId,type:"card",threeDSecureActionResultTokenId:_.intentId},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(_.kind==="terminal"){$s(e,t,h.clientSecret),Ve.current=null,H("idle"),Ce(h.paymentMethodType),Te(!0),ct();return}H("blocked")}catch{$||H("blocked")}finally{O=!1}}};return Ve.current=he,H("blocked"),()=>{$=!0,Ve.current===he&&(Ve.current=null)}},[t,l,ct,e,I]);let q=Be(async h=>{let $=!1,O=!1,he=xe=>{$||O||($=!0,h.paymentFailed({reason:"fail",...xe?{message:xe}:{}}))};if(!I||!We){he();return}let Se=kt.current.get(Ie);if(Se&&!lt(Se.generation)){kt.current.delete(Ie),he();return}if(!Se&&st()){he();return}if(Se&&!ce(Se.generation)){he();return}Se||(ce(),_t.current=!1);let _=h.expressPaymentType??Se?.method??Pt.current,ut=Se??null,Mt=Md(_),At;_==="apple_pay"?At="apple_pay":_==="google_pay"&&(At="google_pay");let Fn=Se?.generation??Ke.current,Ge=G,fr=Ge?.now()??globalThis.performance?.now()??Date.now(),bt=new AbortController,Er=!1,pt=!1,yt=null,Rn=e,Hn="processing",Vn="other",rn="provider_runtime",yn,Xt=new Promise((xe,we)=>{yn=we}),Zt=window.setTimeout(()=>{Er=!0,bt.abort(),yn(Mi)},im),Nn=async(xe,we,tr)=>{Hn=xe,Vn=we,rn=we==="intent_create"||we==="session_claim"?"transport_error":"provider_runtime";let St=Ge?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([tr,Xt])}finally{let Bn=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.performance({stage:xe,durationMs:Math.max(0,Bn-St),durationMode:"machine",requestCategory:we,paymentMethodCategory:"wallet",provider:"stripe",...Er?{statusClass:"timeout"}:{}})}};try{if(Re(!0),u?.(null),!ut&&g){let ae=await Nn("processing","other",g(Mt));if(!ae.proceed){he();return}ut={accountPatch:ae.accountPatch,sessionId:ae.sessionId,nonce:ae.nonce}}let xe=ut?.sessionId??e;Rn=xe;let we=ut?.nonce??t,tr=wt.current??ut?.accountPatch,St=jd({event:h,fallbackEmail:tr?.email??n,fallbackName:[tr?.firstName,tr?.lastName].join(" ").trim()||A});if(!xn(St.email)){he("Buyer details are required."),be(Ys(_),St).then(ae=>{ae&&(wt.current=ae)});return}wt.current=null;let Bn={...ut?.accountPatch,...kr(St,!0)};await Nn("processing","session_claim",Promise.resolve(X?.(St)));let{error:Qt}=await Nn("tokenization","provider_sdk",We.submit());if(Qt){he(),Qe(_,Qt,"stripe_wallet_submit_failed",Se?.generation);return}if(!xe)throw new Error("Missing sessionId or email for payment.");let gr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:_,paymentMethodId:null,intentKind:a},In=JSON.stringify({sessionId:xe,nonce:we??"",request:gr}),_r=Me.current,hr=_r?.retryIdentity===In?_r.authorizationAttemptId:Hy();Me.current={authorizationAttemptId:hr,retryIdentity:In};let En=await Nn("processing","intent_create",Bi(o,se,xe,we??"",{...gr,authorizationAttemptId:hr},{signal:bt.signal}));if(Fi(En)){he(),l({type:"card",paymentMethodType:_},{accountPatch:Bn,paymentMethodCategory:"wallet",sessionId:xe,nonce:we,settledProcessResponse:En.response});return}if(En.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let mn=En.clientSecret,_n=ym({createdAt:Date.now(),sessionId:xe,...we?{nonce:we}:{},clientSecret:mn,providerObjectId:En.providerObjectId,paymentMethodType:_,accountPatch:Bn});window.clearTimeout(Zt),pt=!0,Ge?.performance({stage:"callback",durationMs:Math.max(0,(Ge?.now()??globalThis.performance?.now()??Date.now())-fr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Pr=Ge?.now()??globalThis.performance?.now()??Date.now(),Un={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...At?{walletType:At}:{},attempt:Fn},zn=!1,qn=null;Ge?.log({name:"payment.provider_confirmation.started",...Un}),yt=window.setTimeout(()=>{yt!==null&&Ee.current.delete(yt),zn=!0;let ae=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Un,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ae-Pr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Ge?.flush?.().catch(()=>{}),qn?.()},sm),Ee.current.add(yt);let fn=(ae,Rt)=>{yt!==null&&(window.clearTimeout(yt),Ee.current.delete(yt),yt=null);let xt=Ge?.now()??globalThis.performance?.now()??Date.now(),Vt=Math.max(0,xt-Pr),ye=ae;zn&&(ae==="resolved"?ye="resolved_late":ae==="returned_error"?ye="returned_error_late":ye="rejected_late");let en=Rt??(ae==="resolved"?"approved":"provider_error");return Ge?.log({name:"payment.provider_confirmation.returned",...Un,operationOutcome:ye,terminalReason:en}),Ge?.performance({...Un,durationMs:Vt,durationMode:"buyer",operationOutcome:ye,terminalReason:en}),{durationMs:Vt,operationOutcome:ye,terminalReason:en}},Ut=!1,zt=!1,Dn=ae=>{if(!ae||typeof ae!="object")return null;let Rt=ae;if(Rt.error)return null;let xt=Rt.setupIntent??Rt.paymentIntent,Vt=Ws(xt??null,void 0,!!Rt.setupIntent);return Vt.kind==="confirmed"?Vt:null},vn=ae=>{if(Ut||Se&&Ke.current!==Se.generation)return;let Rt=Dn(ae);if(!Rt)return;if(_n&&!Rd(xe,we,mn)){Ut=!0;return}let{intentId:xt,paymentMethodId:Vt}=Rt;Ut=!0,zt=!0,Me.current=null,Ve.current=null,ze.current&&(H("idle"),Re(!1));let ye=`${Ud}:${xe}`;sn(ye,{createdAt:Date.now(),sessionId:xe,nonce:we,accountPatch:Bn,paymentMethodId:Vt,providerIntentId:xt,paymentMethodType:_});try{l({id:Vt,type:"card",threeDSecureActionResultTokenId:xt},{accountPatch:Bn,paymentMethodCategory:"wallet",sessionId:xe,nonce:we})}finally{sn(ye)}},Tn=!1;qn=async()=>{if(!(Tn||Ut||zt)){Tn=!0,ze.current&&H("checking");try{let ae=await Id(I,mn,Ee.current);if(Ut||zt)return;let Rt=qs(mn),xt=Ws(ae,En.providerObjectId,Rt);if(xt.kind==="confirmed"){vn(Rt?{setupIntent:ae}:{paymentIntent:ae});return}if(xt.kind==="terminal"){if(zt=!0,$s(xe,we,mn),Me.current=null,Ve.current=null,!ze.current)return;H("idle"),he(),Qe(_,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Se?.generation,!0);return}ze.current&&!zt&&(H("blocked"),Re(!1))}catch{ze.current&&!zt&&(H("blocked"),Re(!1))}finally{Tn=!1}}},Ve.current=qn;let T,$e;try{O=!0,Ct.current+=1;let ae;try{ae=await(qs(mn)?I.confirmSetup({elements:We,clientSecret:mn,redirect:"if_required"}):I.confirmPayment({elements:We,clientSecret:mn,redirect:"if_required"}))}finally{Ae()}if(!ae||typeof ae!="object")throw new $a(pm(ae));if(T=ae,!T.error&&!Dn(T))throw new $a("confirmation_result_unconfirmed");$e=fn(T.error?"returned_error":"resolved",T.error&&ci(T.error)?"provider_declined":void 0)}catch(ae){let Rt=ae instanceof $a?ae.reason:void 0,xt=Rt!==void 0,Vt=fn(xt?"returned_error":"rejected");if(Ge?.error({...xt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Rt}:Es(ae),...Un,operationOutcome:Vt.operationOutcome,durationMs:Vt.durationMs,statusClass:"unknown",terminalReason:Vt.terminalReason}),!ze.current||Ut)return;await qn?.();return}let P=T.error;if(P){if(!ze.current||Ut)return;if(ci(P)){zt=!0,$s(xe,we,mn),Me.current=null,Ve.current=null,H("idle"),kt.current.get(Ie)===Se&&kt.current.delete(Ie);let ae=P.message??"Your payment was declined.";u?.(ae),R?.(gn(Mt,ae,{code:Ho(P),declineCode:bs(P)})),Di({billingApiUrl:o,sessionId:xe,nonce:we,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:_,providerDeclineReason:Ho(P)??"provider_declined",...En.intentKind==="payment"&&En.providerObjectId.startsWith("pi_")?{providerIntentId:En.providerObjectId}:{}}})}else Ge?.error({...Es(P),...Un,operationOutcome:$e.operationOutcome,durationMs:$e.durationMs,statusClass:"unknown",terminalReason:$e.terminalReason}),await qn?.();return}if(vn(T),!Ut)throw new Error("Invalid provider returned for APM intent")}catch(xe){if(xe===Mi){let we=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.error({errorCode:fm(Vn),stage:Hn,requestCategory:Vn,paymentMethodCategory:"wallet",provider:"stripe",...At?{walletType:At}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Rn,durationMs:Math.max(0,we-fr),statusClass:"timeout",failureCategory:rn,attempt:Fn,terminalReason:"provider_error"}),Ge?.flush?.().catch(()=>{})}he(),Qe(_,xe,xe===Mi?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Se?.generation,xe===Mi)}finally{if(window.clearTimeout(Zt),yt!==null&&(window.clearTimeout(yt),Ee.current.delete(yt)),!pt){let xe=Ge?.now()??globalThis.performance?.now()??Date.now();Ge?.performance({stage:"callback",durationMs:Math.max(0,xe-fr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Er?{statusClass:"timeout"}:{}})}ze.current&&Re(!1)}},[I,We,e,t,n,A,be,X,o,se,a,l,u,R,g,Qe,Ae,ce,lt,st,Ke,G,Ie]),j=gt(()=>cc(i),[i]),y=gt(()=>i.map(Qy),[i]),oe=gt(()=>d(Nd,{onReady:h=>{rt(Ss(h,y))},onLoadError:h=>{rt("load_error"),el(G,"stripe","wallet","provider_error")},onClick:async h=>{let $=G?.now()??globalThis.performance?.now()??Date.now();Pt.current=h.expressPaymentType,De.current=Md(h.expressPaymentType);let O=!0,he=window.setTimeout(()=>{O=!1,h.reject(),et(h.expressPaymentType)},om),Se=g?await g(De.current,{abandoned:()=>!O}):{proceed:!0};if(window.clearTimeout(he),!O)return;if(!Se.proceed){kt.current.delete(Ie),h.reject();return}let _=V(h.expressPaymentType);_t.current=!1,vt.current={generation:_,startedAt:$},kt.current.set(Ie,{generation:_,method:h.expressPaymentType,accountPatch:Se.accountPatch,sessionId:Se.sessionId,nonce:Se.nonce}),Te(!1),G?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:_,...h.expressPaymentType==="apple_pay"||h.expressPaymentType==="google_pay"?{walletType:h.expressPaymentType}:{}}),m?.(De.current),h.resolve()},onConfirm:q,onCancel:()=>{let h=kt.current.get(Ie);kt.current.delete(Ie);let $=vt.current,O=G?.now()??globalThis.performance?.now()??Date.now();if(h&&$?.generation===h.generation&&jy({method:h.method,elapsedMs:O-$.startedAt,handoffObserved:Ot.current===h.generation})){G?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:h.generation,walletType:"google_pay"}),Me.current=null,Qe(h.method,new Error("The browser window is too small for the Google Pay sheet."),Ld,h.generation,!0);return}G?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...h?{attempt:h.generation}:{}}),_e(h?.generation),Me.current=null,Te(!1),Ze.current=!0,ct()},options:{...dc,paymentMethods:j,emailRequired:Nt,billingAddressRequired:Nt}},Ie),[y,j,q,_e,m,Nt,Qe,et,ct,g,V,Ie,G]);return Ne(Kn,{children:[d(ws,{state:Ue,placeholderTestId:"flopay-wallet-placeholder",borderRadius:D,children:Ne("div",{ref:ot,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Q&&Ne("button",{ref:at,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ht,style:Gs,children:["Try ",Ys(ht)," again"]}),Xe!=="idle"&&Ne("div",{role:"status","aria-live":"polite",children:[d("p",{children:"We are still confirming your payment. Check its status before trying again."}),d("button",{type:"button",onClick:k,disabled:Xe==="checking",style:Gs,children:Xe==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Dt&&d(ta,{identity:Dt.identity,methodLabel:Dt.methodLabel,onComplete:He,onCancel:()=>He(null)},Dt.id),Ne("div",{style:{display:Dt||Xe!=="idle"?"none":void 0},children:[d(xm,{active:le}),oe]})]})}),dt&&d(Ur,{status:"processing"})]})}function $d(e,t,n){let o=Dd(n,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function Js({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:u,onErrorChange:m,onDecline:R,onCancel:C,runBeforeButtonClick:g,onButtonClick:A,isProcessing:X,submitButtonColor:te,submitButtonBorderRadius:D,submitButtonStyle:K,errorText:w}){let pe=po(),{emitInstrument:se}=da(pr),I=Zs(),We=Xs(),[G,Ue]=ee(!1),rt=B(!1),[dt,Re]=ee(!1),[Nt,Dt]=ee("loading"),[be,He]=ee(""),ot=!xn(o?.trim()),at=!ot||xn(be.trim()),Ie=Be(async()=>{if(!I||!We||X||rt.current||!dt)return;rt.current=!0,Ue(!0);let Z=g?await g("card"):{proceed:!0};if(!Z.proceed){rt.current=!1,Ue(!1);return}A?.("card");let le=Z.sessionId??t,Kt=Z.nonce??n,je=Ta(a?.trim()),it=kr({email:Z.accountPatch?.email?.trim()||o?.trim()||be.trim(),firstName:Z.accountPatch?.firstName?.trim()||je.firstName,lastName:Z.accountPatch?.lastName?.trim()||je.lastName}),Q=it.email,Te=kr({...Z.accountPatch,...it});try{if(m?.(null),!xn(Q))throw new Error("A valid email address is required for payment.");await i?.(it);let Xe=await We.submit();if(Xe.error){m?.(Xe.error.message??"Payment failed.");return}let H=[it.firstName,it.lastName].filter(Boolean).join(" "),ht=await I.createPaymentMethod({elements:We,params:{billing_details:{email:Q,...H?{name:H}:{}}}});if(ht.error||!ht.paymentMethod){m?.(ht.error?.message??"Failed to create payment method.");return}let Ce=ht.paymentMethod;if(!le||!Q)throw new Error("Missing sessionId or email for payment.");let Ve=Ce.type||e,ze=await Bi(l,se,le,Kt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Ve,paymentMethodId:null,intentKind:"payment"});if(Fi(ze)){u({type:"card",gateway:"stripe",paymentMethodType:Ve},{accountPatch:Te,paymentMethodCategory:"apm",sessionId:le,nonce:Kt,settledProcessResponse:ze.response});return}if(ze.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ze=ze.clientSecret;sn(qr,{clientSecret:Ze,sessionId:le,nonce:Kt,accountPatch:Te,paymentMethodId:Ce.id,paymentMethodType:Ce.type??e,gateway:"stripe"});let{error:Pt,paymentIntent:De}=await I.confirmPayment({clientSecret:Ze,confirmParams:{return_url:window.location.href,payment_method:Ce.id},redirect:"if_required"});if(Pt){sn(qr);let Ee=Pt.message??"Payment failed.";m?.(Ee),R?.(gn("card",Ee,{code:Pt.code})),await Di({billingApiUrl:l,sessionId:le,nonce:Kt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Pt.code??"provider_declined"}});return}let wt=De?.status;if(!Ea(wt)){sn(qr);let Ee=wt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(Ee),R?.(gn("card",Ee,{code:wt??"missing_payment_intent"}));return}sn(qr);let Me=typeof De?.payment_method=="string"?De.payment_method:De?.payment_method?.id;u({id:Me??Ce.id,type:"card",threeDSecureActionResultTokenId:De?.id,gateway:"stripe",paymentMethodType:Ce.type??e},{accountPatch:Te,paymentMethodCategory:"apm",sessionId:le,nonce:Kt})}catch(Xe){m?.(Xe instanceof Error?Xe.message:"Payment failed. Please try again.")}finally{rt.current=!1,Ue(!1)}},[I,We,X,dt,g,A,t,n,o,a,be,i,l,se,e,u,m,R]);return Ne("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ot&&d("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ot&&Ne("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",d("input",{type:"email",autoComplete:"email",required:!0,value:be,onChange:Z=>He(Z.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),d(tm,{onReady:()=>Dt("ready"),onLoadError:()=>{Dt("load_error"),el(hn(pe),"stripe","apm")},onChange:Z=>{Re(!!Z.complete)},options:{layout:uc,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...xn(o?.trim())?{email:o?.trim()}:{}}}}}),d(pc,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Ie()},disabled:!dt||!at||G||X||Nt!=="ready",color:te,borderRadius:D,style:K,children:G?"Processing\u2026":`Pay with ${Wa(e)}`}),w&&d(oa,{margin:"0.75rem 0 0",children:w})]})}function Fd({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:l,stripeInstance:u,paymentElementBaseOptions:m,futureUseSession:R,onTokenizedBody:C,onErrorChange:g,onButtonClick:A,onDecline:X,runBeforeButtonClick:te,onLoadStateChange:D,isProcessing:K=!1,submitButtonColor:w="#4A49FF",submitButtonBorderRadius:pe=8,submitButtonStyle:se,buttonAppearance:I,themeId:We,onExpandApm:G,expandedApmMethod:Ue}){let{emitInstrument:rt}=da(pr),[dt,Re]=ee(null),[Nt,Dt]=ee(null),be=B(!1),{request:He,collect:ot,finish:at}=ea();Je(()=>{l.length>0&&u?D?.("ready"):u||D?.("loading")},[l.length,u,D]);let Ie=Be(async Q=>{if(!u||be.current||K)return;be.current=!0,Dt(Q);let Te=te?await te("card"):{proceed:!0};if(!Te.proceed){be.current=!1,Dt(null);return}A?.("card");let Xe=Te.sessionId??e,H=Te.nonce??t,ht=Ta([Te.accountPatch?.firstName,Te.accountPatch?.lastName].filter(Boolean).join(" ")||o),Ce=kr({email:Te.accountPatch?.email?.trim()||n?.trim(),firstName:Te.accountPatch?.firstName?.trim()||ht.firstName,lastName:Te.accountPatch?.lastName?.trim()||ht.lastName});if(!xn(Ce.email)){Dt(null);let Ze=await ot(Wa(Q),Ce);if(!Ze){be.current=!1;return}Ce=Ze,Dt(Q)}let Ve=Ce.email,ze=kr({...Te.accountPatch,...Ce});try{if(g?.(null),!Xe||!xn(Ve))throw new Error("Missing sessionId or email for payment.");await a?.(Ce);let Ze=await Bi(i,rt,Xe,H??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if(Fi(Ze)){C({type:"card",gateway:"stripe",paymentMethodType:Q},{accountPatch:ze,paymentMethodCategory:"apm",sessionId:Xe,nonce:H,settledProcessResponse:Ze.response});return}if(Ze.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Pt=Ze.clientSecret;sn(qr,{clientSecret:Pt,sessionId:Xe,nonce:H,accountPatch:ze,paymentMethodType:Q,gateway:"stripe"});let{error:De,paymentIntent:wt}=await u.confirmPayment({clientSecret:Pt,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:[Ce.firstName,Ce.lastName].filter(Boolean).join(" "),...Ve?{email:Ve}:{}}}},redirect:"if_required"});if(De){sn(qr);let vt=De.message??"Payment failed.";g?.(vt),X?.(gn("card",vt,{code:De.code})),await Di({billingApiUrl:i,sessionId:Xe,nonce:H,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:De.code??"provider_declined"}});return}let Me=wt?.status;if(!Ea(Me)){sn(qr);let vt=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(vt),X?.(gn("card",vt,{code:Me??"missing_payment_intent"}));return}sn(qr);let Ee=typeof wt?.payment_method=="string"?wt.payment_method:wt?.payment_method?.id;C({id:Ee??wt?.id,type:"card",threeDSecureActionResultTokenId:wt?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:ze,paymentMethodCategory:"apm",sessionId:Xe,nonce:H})}catch(Ze){g?.(Ze instanceof Error?Ze.message:"Payment failed. Please try again.")}finally{be.current=!1,Dt(null)}},[u,K,te,A,e,t,n,ot,i,rt,o,a,C,g,X]),[Z,le]=ee(null),Kt=G?Ue??null:Z,je=Be(Q=>{be.current||K||Kt&&Kt!==Q||(Cd(Q)?G?G(Q):le(Q):Ie(Q))},[Kt,K,Ie,G]),it=gt(()=>Z?$d(m,Z,R):null,[Z,m,R]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:He?d(ta,{identity:He.identity,methodLabel:He.methodLabel,onComplete:at,onCancel:()=>at(null)},He.id):l.map(Q=>{let Te=Ue===Q,Xe=Nt===Q,H=Nt!==null&&Nt!==Q||Ue!=null&&Ue!==Q;return Ne(ja.Fragment,{children:[d(lc,{method:Q,themeId:We,submitting:Xe,disabled:H,highlighted:Te,hasNextStep:Cd(Q),onClick:()=>je(Q),backgroundColor:I?.backgroundColor,borderColor:I?.borderColor,textColor:I?.textColor,borderRadius:I?.borderRadius,fontFamily:I?.fontFamily}),!G&&Z===Q&&it&&u&&d(uo,{stripe:u,options:it,children:d(Js,{method:Q,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:C,onErrorChange:g,onDecline:X,onCancel:()=>le(null),runBeforeButtonClick:te,onButtonClick:A,isProcessing:K,submitButtonColor:w,submitButtonBorderRadius:pe,submitButtonStyle:se})},Q)]},Q)})})}function Fm({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:l,onError:u,onDecline:m,onCancel:R,onTokenizedBody:C,firstName:g,lastName:A,chv:X,className:te,submitLabel:D,isProcessing:K,error:w,onErrorChange:pe,showPayPal:se=!0,showStripe:I=!0,walletPresentation:We="auto",enabledPaymentMethods:G,enabledPaymentMethodCountries:Ue,showApplePay:rt=!0,showGooglePay:dt=!0,layout:Re="default",paymentMethodLayout:Nt,moreOptionsLabel:Dt,theme:be,buttonsTheme:He,buttonsStyles:ot,appearance:at,cardButtonContent:Ie,cardBackButtonContent:Z,cardTitleContent:le,showSecurityFooter:Kt,onButtonClick:je,onBeforeButtonClick:it,onBuyerIdentityReady:Q,enableAVS:Te,cardFieldOrder:Xe,showCardBrandIcons:H,showCardFieldLabels:ht,cardFieldLabels:Ce,cardFieldPlaceholders:Ve,cardAutoFocus:ze,onCardFieldsReady:Ze,onCardFieldsFailed:Pt,cardFieldsTimeoutMs:De,cardPreFormSlot:wt,avsLayout:Me="row",country:Ee,zip:vt,addressLine1:Ot,addressLine2:kt,city:V,state:ce,onCountryChange:_e,onZipChange:st,avsCheck:lt,checkoutType:Ke,checkoutLayout:Ct,totalAmount:_t=0,currency:ct="usd",initialCardOpen:Ae=!1,directPaypal:Qe,isSubscription:et=!1,session:z,dataAttachmentPending:Ht=!1,dataAttachmentRequiresIdentity:k=!1,debug:q=!1}){let j=po(),y=_s(),oe=da(wr),{emitInstrument:h}=da(pr),$=B(null);$.current||($.current=gi());let O=$.current,[,he]=ee(0),Se=B(null);Se.current||(Se.current=ka());let _=Se.current,ut=gt(()=>({browser:_,capability:O,presentationMode:"popup"}),[_,O]),Mt=z??oe.session,At=gt(()=>({futureUse:Mt?.futureUse,futureUseUnsupported:Mt?.futureUseUnsupported}),[Mt?.futureUse,Mt?.futureUseUnsupported]),Fn=Mt?.gateways?.paypal?.providerObjectType??Qe?.providerObjectType,Ge=Ht||oe.claimPending===!0,fr=k||oe.claimRequiresIdentity===!0,bt=Ge&&!fr,Er=Nc(),pt=n||Er,yt=Pd({rules:Nt,sessionId:e,nonce:t,billingApiUrl:pt,waitForSession:bt}),Rn=yt?.order??null,[Hn,Vn]=ee(!1),rn=gt(()=>Rn?$y(Rn):null,[Rn]),yn=Rn!==null&&Ny(Rn),[Xt,Zt]=ee(!1),[Nn,xe]=ee(null),[we,tr]=ee(Ee??""),[St,Bn]=ee(vt??""),[Qt,gr]=ee(Ot??""),[In,_r]=ee(kt??""),[hr,En]=ee(V??""),[mn,_n]=ee(ce??""),[Pr,Un]=ee(""),[zn,qn]=ee({}),fn=B(vt??""),Ut=B(Ee??""),zt=B(Ot??""),Dn=B(kt??""),vn=B(V??""),Tn=B(ce??""),T=B(""),$e=B({});Je(()=>{let r=(f,E,J,F,ue)=>{if($e.current[f])return;let It=E?.trim();!It||It===J.current||(J.current=It,F(It),ue?.(It))};r("country",Ee,Ut,tr,_e),r("zip",vt,fn,Bn,st),r("addressLine1",Ot,zt,gr),r("addressLine2",kt,Dn,_r),r("city",V,vn,En),r("state",ce,Tn,_n)},[Ee,vt,Ot,kt,V,ce,_e,st]);let P=gt(()=>Gy(Te),[Te]),ae=P!==null,Rt=gt(()=>zs(z),[z]),xt=Uy(z?.vault),Vt=!!z?.gateways?.pcivault,ye=_c(z),Wr=!!(z?.gateways?.stripe?.enabledPaymentMethods??G)?.includes("card")||_o(z),Mn=xt||Wr||Vt,Pe=!!(I&&Mn&&e),[Tr,Cn]=ee(()=>Re!=="buttons"||Ae?e??null:null),[sr,Po]=ee(0),Gn=Re!=="buttons"||Ae||!!e&&Tr===e,nr=z?.captureMethod,Mr=B(j);Je(()=>{Mr.current=j},[j]);let jn=B(De);jn.current=De;let Ar=B(t);Ar.current=t;let vr=B({onCardFieldsReady:Ze,onCardFieldsFailed:Pt,emitInstrument:h});vr.current={onCardFieldsReady:Ze,onCardFieldsFailed:Pt,emitInstrument:h};let[lr,Yn]=ee(null);Je(()=>{if(!Pe||!e||!Gn){Yn(null);return}let r=Mr.current?Mr.current.cardCapture({sessionId:e,captureMethod:nr,sessionToken:Ar.current,cardFieldsTimeoutMs:jn.current}):new Py({sessionId:e,captureMethod:nr,billingApiUrl:pt,telemetry:o,sessionToken:Ar.current,cardFieldsTimeoutMs:jn.current}),f=r.onCardFields?.(E=>{let J=vr.current;J.emitInstrument?.(Ey(E)),E.type==="card_fields_ready"?vd(()=>J.onCardFieldsReady?.(E)):vd(()=>J.onCardFieldsFailed?.(E))});return Yn({sessionId:e,captureMethod:nr,billingApiUrl:pt,telemetry:o,capture:r}),()=>{f?.(),r.unmount()}},[Pe,e,Gn,nr,pt,o]);let ke=Pe&&e&&Gn&&lr?.sessionId===e&&lr.captureMethod===nr&&lr.billingApiUrl===pt&&lr.telemetry===o?lr.capture:null,An=gt(()=>{let r=we,f=P?nn(P.postal_code,r):!1;return Im(r,St,f)},[P,we,St]),{avsInvalid:$n,invalidAvsFields:ln}=gt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!Pe||!P)return{avsInvalid:!1,invalidAvsFields:r};let f=we,E=(ue,It)=>nn(ue,f)&&!It.trim(),J={line1:E(P.address_line_1,Qt),city:E(P.city,hr),state:E(P.state,mn),zip:An.empty||An.malformed};return{avsInvalid:J.line1||J.city||J.state||J.zip,invalidAvsFields:J}},[Pe,P,we,Qt,hr,mn,An]),[cr,rr]=ee(!1),[Kr,xr]=ee(!1),[vo,Fr]=ee(!1),[Co,Hr]=ee({line1:!1,city:!1,state:!1}),Cr=B(!1),eo=B({email:!1,line1:!1,city:!1,state:!1,zip:!1}),to=B(!1),qt=Be(r=>{eo.current[r]=!0,to.current=!0},[]),Jn=Be(r=>!Cr.current&&eo.current[r],[]),Vr=Be(r=>{Jn(r)&&Hr(f=>f[r]?f:{...f,[r]:!0})},[Jn]),[On,Xn]=ee(()=>js(z?.vault,{billingApiUrl:pt,sessionId:e,nonce:t})),[Fe,Ln]=ee(Ae&&Mn?"card":"buttons"),[$t,Gr]=ee(null),no=Fe==="expanding"||Fe==="card",bo=z?.gateways?.stripe&&!ye?"stripe":void 0,Br=Be(()=>{h?.({class:"card_surface",provider:bo})},[bo,h]),Dr=Be(()=>{Vn(!0),h?.({class:"more_options"})},[h]),bn=B(null),cn=Be(r=>{bn.current&&clearTimeout(bn.current),bn.current=setTimeout(()=>{bn.current=null,r()},Ka)},[]);Je(()=>()=>{bn.current&&clearTimeout(bn.current)},[]);let v=B(!1),[s,c]=ee(0),p=B(null),W=Be(()=>{Br(),Cn(e??null),v.current&&(v.current=!1,c(r=>r+1)),Po(r=>r+1),Ln("expanding"),cn(()=>Ln("card"))},[cn,Br,e]),qe=Be(()=>{Ln("collapsing"),cn(()=>Ln("buttons"))},[cn]),Y=Be(r=>{Gr(r),Ln("apm-expanding"),cn(()=>Ln("apm-form"))},[cn]),de=Be(()=>{Ln("apm-collapsing"),cn(()=>{Ln("buttons"),Gr(null)})},[cn]);Je(()=>{Re==="buttons"&&Ae&&Mn&&(Cn(e??null),Ln("card"))},[Re,Ae,Mn,e]);let[U,S]=ee(null),ne=B(null),[me,b]=ee(0);Je(()=>{me!==0&&ne.current?.focus()},[me]);let M=B(!1),x=B(null),L=B("idle"),[re,Oe]=ee(!1),N=B(re);N.current=re;let[fe,Ye]=ee(()=>Qe?.existingOrderId?{orderId:Qe.existingOrderId,attempts:1}:null),Sn=B(fe);Je(()=>{Sn.current=fe},[fe]);let jt=B(null),Lt=gt(()=>{if(Q||oe.claimBuyerIdentity||z?.buyerIdentified!==!1||!e||!t)return;let r=`${pt}|${e}|${t}`;jt.current?.key!==r&&(jt.current={key:r,claim:Xo(new ca(pt,{telemetry:!1}),e,t,{...i?{userId:i}:{},...g?{firstName:g}:{},...A?{lastName:A}:{}})});let f=jt.current.claim;return async E=>{await f(E)}},[Q,oe.claimBuyerIdentity,z?.buyerIdentified,e,t,pt,i,g,A]),Gt=Q??oe.claimBuyerIdentity??Lt,Yt=w??Nn,Zn=gt(()=>Jy(be),[be]),ve=gt(()=>{let r=Zn?.buttonsLayout??Yy(He);return ot?{...r,...ot,cardButton:{...r.cardButton,...ot.cardButton},cardFormContainer:{...r.cardFormContainer,...ot.cardFormContainer},backButton:{...r.backButton,...ot.backButton},backButtonIcon:{...r.backButtonIcon,...ot.backButtonIcon},submitButton:{...r.submitButton,...ot.submitButton},title:{...r.title,...ot.title}}:r},[Zn,He,ot]),Do=at??Zn?.appearance,pu=gt(()=>My({appearance:Do,buttonsStyles:ve,layout:Re}),[Do,ve,Re]),yu=oe.inlineSessionPatchProcessing??!1,on=(K??Xt)||yu,ro=pt.replace(/\/+$/,""),mt=gt(()=>Is({userId:i,email:a,firstName:g,lastName:A,country:Ee,zip:vt},zn),[i,a,g,A,Ee,vt,zn]),Oo=[mt.firstName,mt.lastName].filter(r=>!!r?.trim()).join(" "),ml=!xn(mt.email?.trim()),ji=B(null);Pe&&ji.current===null&&(ji.current=ml);let oo=Pe&&(ji.current??ml),$i=gt(()=>Em(Pr,oo),[Pr,oo]),Lo=$i.empty||$i.malformed,or=gt(()=>j?j.getRawProvider():null,[j]),fl=gt(()=>y?y.getRawProvider():null,[y]),ya=_t||100,No=ct.toLowerCase(),Wi=gt(()=>Do?vy(Do):null,[Do]),Uo=Wi,gl=gt(()=>{let r=Wi??{},f=r.rules??{};return{...r,rules:{...f,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...f[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...f[".AccordionItemContents"]??{}}}}},[Wi]),hl=gt(()=>({...Ec(_t,Mt?.captureMethod,At),currency:No,...Uo?{appearance:Uo}:null}),[_t,No,Mt?.captureMethod,At,Uo]),Ki=Dd(At,"paypal","paypal"),Pl=gt(()=>({mode:"payment",amount:ya,currency:No,captureMethod:"manual",...Ki?{setupFutureUsage:Ki}:null,...Uo?{appearance:Uo}:null}),[ya,No,Ki,Uo]),ge=Be(r=>{xe(r),pe?.(r)},[pe]),vl=B(0);Je(()=>{s!==vl.current&&(vl.current=s,ge(null))},[s,ge]);let Hi=B(""),[Cl,mu]=ee(!1),Vi=Be(()=>{mu(!0)},[]);Je(()=>{if(!Pe||!oo||!Gt||!Cl||Lo||Hi.current)return;let r=kr({email:xn(mt.email?.trim())?mt.email?.trim():T.current.trim(),firstName:mt.firstName?.trim(),lastName:mt.lastName?.trim()});Hi.current=JSON.stringify(r),qn(f=>({...f,...r})),Promise.resolve(Gt(r)).catch(f=>{Hi.current="",ge(f instanceof Error?f.message:"Failed to attach buyer details.")})},[Pe,oo,Gt,Cl,Lo,mt.email,mt.firstName,mt.lastName,ge]),Je(()=>{if(!Pe||!ke)return;let r=ze!==!1&&P==null&&!oo;ke.setCardFieldOrder?.(Xe??null,r)},[Pe,ke,Xe,ze,P,oo]),Je(()=>{!Pe||!ke||ke.setCardBrandIcons?.(H===!0)},[Pe,ke,H]);let Gi=B(null);Je(()=>{if(!(!Pe||!ke)){if(ht===void 0){if(Gi.current!==ke)return;Gi.current=null,ke.setShowCardFieldLabels?.(!1);return}Gi.current=ke,ke.setShowCardFieldLabels?.(ht===!0)}},[Pe,ke,ht]);let Yi=Ce===void 0?void 0:JSON.stringify(Cy(Ce)),Ji=B(null);Je(()=>{if(!(!Pe||!ke)){if(Yi===void 0){if(Ji.current!==ke)return;Ji.current=null,ke.setCardFieldLabels?.(null);return}Ji.current=ke,ke.setCardFieldLabels?.(JSON.parse(Yi))}},[Pe,ke,Yi]);let Xi=Mm(Ve),Zi=B(null);Je(()=>{if(!(!Pe||!ke)){if(Xi===null){if(Zi.current!==ke)return;Zi.current=null,ke.setCardFieldPlaceholders?.(void 0);return}Zi.current=ke,ke.setCardFieldPlaceholders?.(JSON.parse(Xi))}},[Pe,ke,Xi]),Je(()=>{(Fe==="expanding"||Fe==="collapsing"||Fe==="apm-expanding"||Fe==="apm-collapsing")&&ge(null)},[Fe,ge]);let Or=Be((r,f,E)=>{m?.(gn(r,f,E))},[m]),bl=B(Fe);bl.current=Fe;let[Sl]=ee(Pi),wl=Be(()=>{let r=bl.current;if(Re==="buttons"&&(r==="card"||r==="expanding"))return!0;let f=L.current;return f==="validation-window"||f==="processing"||N.current},[Re]),kl=Be((r,f,E)=>{Sl.take(e)&&hn(j)?.log(Ao({...ut,presentationMode:E?.presentationMode??"popup"},{name:hi,stage:"recovery",reason:"other_method_active",provider:E?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:E?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[ut,j,Sl,e]),Ya=Be((r,f,E)=>{E?.telemetryReported||hn(j)?.error(Ao({...ut,presentationMode:E?.presentationMode??"popup"},{errorCode:f?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:E?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:E?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:E?.terminalReason??(f?"popup_blocked":"provider_error")}))},[ut,j]),zo=Be((r,f,E)=>{let J=E?.popupBlocked??so(f);if(wl()){Ya(r,J,E),kl(r,f,E);return}if(f instanceof Rr&&f.code==="checkout_processing_timeout"){Ya(r,!1,E),S(null),Re==="buttons"&&(Ln("buttons"),Gr(null)),ge(f.message),u?.(f);return}J&&O.markBlocked()&&he(tt=>tt+1);let F=Ys(r),ue=E?.code===Ld?wy(F):li(F,J,_.inAppBrowser),It=Ho(f),Et=(It?.toLowerCase()==="error"?void 0:It)??ic(E?.code)??"external_payment_method_failed",Le=new Rr(ue,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:Et,popupBlocked:J,inAppBrowser:_.inAppBrowser,appFamily:_.appFamily,popupCapability:O.current(),presentationMode:E?.presentationMode??"popup"}});Ya(r,J,E),S(null),Re==="buttons"&&(Ln("buttons"),Gr(null)),ge(ue),u?.(Le),console.error("[FloPay] External payment method failed:",{method:r,code:Et,popupBlocked:J})},[_,wl,Re,u,O,kl,Ya,ge]);Je(()=>{if(!Pe||!e){Xn(null);return}let r={billingApiUrl:ro,sessionId:e,nonce:t},f=js(z?.vault,r);if(f){Xn(f);return}if(!Gn){Xn(null);return}let E=`${ro}\0${e}\0${t??""}`,J=p.current;if(J&&J.key===E){Xn(J.mount);return}Xn(null);let F=!0;return new ca(ro).getVaultCapture(e,t).then(ue=>{if(!F)return;let It=js(ue,r);It?.verificationRequired&&!ue.html&&(p.current={key:E,mount:It}),It?Xn(It):ge("Failed to load the secure card form.")}).catch(ue=>{F&&ge(ue instanceof Error?ue.message:"Failed to load the secure card form.")}),()=>{F=!1}},[Pe,Gn,sr,e,z?.vault,ro,t,ge]);let br=B({onComplete:l,onError:u,updateError:ge,emitDecline:Or,resolvedAccount:mt,avsConfig:P,avsCheckProp:lt,sessionId:e,nonce:t,baseUrl:ro,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:ye});br.current={onComplete:l,onError:u,updateError:ge,emitDecline:Or,resolvedAccount:mt,avsConfig:P,avsCheckProp:lt,sessionId:e,nonce:t,baseUrl:ro,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:ye};let Qi=B(!1),Rl=Be(()=>{let r=br.current,f=r.resolvedAccount.email?.trim(),E=xn(f)?f:T.current.trim();if(!xn(E))return null;let J=r.resolvedAccount.firstName?.trim(),F=r.resolvedAccount.lastName?.trim(),ue=Ut.current.trim()||r.resolvedAccount.country?.trim()||"",It=r.avsConfig?nn(r.avsConfig.state,ue):!1,Et=r.avsConfig?nn(r.avsConfig.address_line_1,ue):!1,Le=r.avsConfig?nn(r.avsConfig.postal_code,ue):!1,tt=r.avsConfig?nn(r.avsConfig.city,ue):!1,ft=r.avsConfig?nn(r.avsConfig.address_line_2,ue):!1,dn=Et&&!It&&Le?Dy(ue,(fn.current??"").trim()):null,ar=It?Tn.current:dn;return{accountData:{userId:r.resolvedAccount.userId??"",email:E,...J?{firstName:J}:{},...F?{lastName:F}:{},...Le&&fn.current?{zip:fn.current}:{},...tt&&vn.current?{city:vn.current}:{},...ar?{state:ar}:{},...Et&&zt.current?{addressLine1:zt.current}:{},...ft&&Dn.current?{addressLine2:Dn.current}:{},...ue?{country:ue}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:nn(r.avsConfig.country,ue),postal_code:Le,address_line_1:Et,address_line_2:ft,city:tt,state:It}}:{}}},[]),Il=B(Ge);Il.current=Ge,Je(()=>{Ge||Yt!==Ed||br.current.updateError(null)},[Ge,Yt]),Je(()=>{!Pe||!ke||ke.setSubmitGate?.($n||Ge||Lo||re)},[Pe,ke,$n,Ge,Lo,re]),Je(()=>{if(!Pe||!ke)return;Qi.current=!1;let r=null,f=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,L.current="idle",S(null)},400)},E=ke.on("submitting",()=>{rr(!0),x.current&&clearTimeout(x.current),L.current="validation-window",x.current=setTimeout(()=>{x.current=null,L.current==="validation-window"&&(L.current="processing")},gm),S("processing");let Le=br.current;if(!Le.sessionId||!Le.nonce)return;let tt=Rl();if(!tt){Le.updateError("Enter a valid email address."),L.current="idle",S(null);return}new ca(Le.baseUrl).patchAccountSnapshot(Le.sessionId,Le.nonce,tt,{telemetryMode:"best_effort"}).catch(ft=>{if(!Pm(ft))return;let dn=ft instanceof Error?ft.message:"Please check your billing address and try again.";Le.updateError(dn),L.current="idle",S(null),Le.onError?.(ft instanceof Rr?ft:new Rr(dn,"api_error"))})}),J=ke.on("complete",Le=>{aa(Le.sessionId??br.current.sessionId),L.current="terminal",Oe(!1),S("success"),setTimeout(()=>{if(Qi.current)return;Qi.current=!0;let tt=br.current,ft=zs(tt)||Le.outcome==="authorized",dn=tt.serverSideCardGateway?{}:{paymentIntentId:Le.intentId};br.current.onComplete?.(ft?{status:"authorized",...dn,paymentId:Le.paymentId??tt.paymentId,sessionId:Le.sessionId??tt.sessionId,authorizationExpiresAt:Le.authorizationExpiresAt??tt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...dn,checkoutMethod:"card"})},600)}),F=ke.on("decline",Le=>{let tt=br.current,ft=Le.message??"Your payment was declined. Please try another card or contact your bank.";L.current="terminal",Oe(!1),tt.updateError(ft),S("error");let dn=Le.failureOutcome??Wy(Le.declineReason)??"authorization_declined";tt.emitDecline("card",ft,{code:dn,declineCode:dn}),f()}),ue=ke.on("error",Le=>{let tt=br.current,ft=ky(Le.vaultOutcome);if(ft!==null){r&&(clearTimeout(r),r=null),L.current="idle",Oe(!1),tt.updateError(ft),S(null),b(ar=>ar+1),tt.onError?.(new Rr(ft,"api_error",{code:Ry}));return}let dn=Le.message??"There was a problem processing your payment. Please try again.";L.current="terminal",Oe(!1),tt.updateError(dn),S("error"),tt.onError?.(new Rr(dn,"api_error",{code:Le.failureOutcome??"capture_failed"})),f()}),It=ke.on("challenge_dismissed",()=>{x.current&&(clearTimeout(x.current),x.current=null),L.current="processing",Oe(!0),S(null)}),Et=ke.on("blocked",()=>{if(N.current){br.current.updateError(hm);return}if(!Il.current){rr(!0);return}Vi(),br.current.updateError(Ed)});return()=>{r&&(clearTimeout(r),r=null),x.current&&(clearTimeout(x.current),x.current=null),L.current="idle",Oe(!1),S(null),E(),J(),F(),ue(),It(),Et()}},[Pe,ke,Vi,Rl]);let Lr=!!Qe?.clientId,ma=Array.isArray(G),Ja=ma&&G.length>0,El=ma&&G.includes("paypal"),Xa=B(null);Xa.current===null&&(Xa.current=Ly());let qo=Xa.current?"redirect":sc(_,We,O.current()),{expressMethods:Za,paymentElementMethods:es}=gt(()=>Ky(G,{excludePaypal:Lr}),[G,Lr]),_l=Lr||!!y||El&&qo==="redirect",fu=gt(()=>_l?Za.filter(r=>r!=="paypal"):Za,[Za,_l]),gu=gt(()=>{let r=[];return rt&&r.push("apple_pay"),dt&&r.push("google_pay"),r},[rt,dt]),jo=ma?fu:gu,hu=I&&jo.length>0,Tl=ae?we:Ee,Qa=gt(()=>Fy(es,Tl,Ue),[es,Tl,Ue]),ts=gt(()=>({mode:"payment",amount:ya,currency:No,paymentMethodCreation:"manual",appearance:gl}),[ya,No,gl]),[ns,Ml]=ee("loading"),[rs,Al]=ee("loading"),[os,xl]=ee("loading"),[Pu,as]=ee(!1),[Fl,is]=ee("loading"),[ss,vu]=ee();Je(()=>{vu(ka())},[]);let ei=ss?.inAppBrowser,ti=ss?di(ss,Qe?.approvalPresentation,Fn??(et?"subscription":"order")):"popup",Bl=se&&(Lr||(ma?El:ei===!1)),Cu=_.inAppBrowser&&O.current()==="blocked",Dl=I&&hu&&!Cu,So=(!bt||!!oe.waitForDataAttachment)&&Bl&&Lr,ls=Fl==="retrying"||Fl==="exhausted",fa=null;I&&(y?fa=fl:qo==="redirect"&&(fa=or));let Ol=gt(()=>({...ut,presentationMode:qo}),[ut,qo]),wo=!bt&&Bl&&!!fa&&(!Lr||ls),ao=!bt&&Dl&&!!or,ko=!bt&&I&&Ja&&Qa.length>0&&!!or,bu=So&&!ls?Pu:wo&&Ra(ns),Su=ao&&Ra(rs),wu=ko&&os!=="load_error",Ll=[So||wo,ao,ko,Pe].filter(Boolean).length,ku={card:Pe,paypal:So&&!ls||wo&&Ra(ns),wallets:ao&&Ra(rs),apms:ko&&os!=="load_error"},Nl=r=>ku[r],Ul=r=>r==="loading"||r==="ready",zl=So||wo&&Ul(ns)||ao&&Ul(rs)||ko&&os!=="load_error",ni=B(!1);Je(()=>{if(!ni.current){if(!I&&!se){ni.current=!0;let r=new Rr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(r),ge(r.message)}else if(!I&&se&&!Lr){ni.current=!0;let r=new Rr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(r),ge(r.message)}else if(ei!==void 0&&!bt&&!Mn&&!zl){ni.current=!0;let r=new Rr("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(r),ge(r.message)}}},[I,se,Lr,ei,bt,Mn,zl,u,ge]);let ql=B(!1);Je(()=>{if(ql.current||!Ja)return;let r=[];rt!==!0&&r.push("showApplePay"),dt!==!0&&r.push("showGooglePay"),r.length!==0&&(ql.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Ja,rt,dt]);let jl=Be((r,f,E)=>oe.applyInlineSessionPatch?oe.applyInlineSessionPatch(r).then(J=>({error:null,sessionId:J.sessionId||e,nonce:J.session?.clientSecret||t})).catch(J=>{let F=bd(f,J);return E?.abandoned?.()||(ge(F.message),u?.(F)),{error:F,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[oe.applyInlineSessionPatch,t,u,e,ge]),Sr=Be(async(r,f)=>{if(r!=="card"&&bt&&await oe.waitForDataAttachment?.(),!it)return{proceed:!0};try{let E=await it({method:r,sessionId:e||void 0,createSession:oe.inlineSessionDraft});if(E===!1)return{proceed:!1};if(E&&typeof E=="object"){E.account&&qn(F=>({...F??{},...E.account}));let J=await jl(E,r,f);return J.error?{proceed:!1,accountPatch:E.account}:{proceed:!0,accountPatch:E.account,sessionId:J.sessionId,nonce:J.nonce}}return{proceed:!0}}catch(E){if(!f?.abandoned?.()){let J=bd(r,E);ge(J.message),u?.(J)}return{proceed:!1}}},[jl,oe.inlineSessionDraft,oe.waitForDataAttachment,bt,it,u,e,ge]),$l=Be(async(r,f)=>{if(M.current)return;M.current=!0,Zt(!0),S("processing"),ge(null);let E=f?.sessionId??e,J=f?.nonce??t,F=Is(mt,f?.accountPatch),ue=f?.completionPaymentMethodId??_a(r),It=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,Et=Sm(r),Le=f?.presentationMode?Ti(hn(j),{...ut,presentationMode:f.presentationMode}):void 0,tt=()=>{h?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Et}),Le?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Ir,requestCategory:"process_payment"})};try{let ft=new ca(ro),ar=f?.settledProcessResponse??await ft.processPayment(F.userId??"",{sessionId:E,nonce:J,paymentMethodCategory:f?.paymentMethodCategory??km(r),tokenizedData:It,accountData:{...f?.accountPatch,userId:F.userId??"",email:F.email??"",firstName:F.firstName||void 0,lastName:F.lastName||void 0,...Sy({avsConfig:P,country:Ut.current,zip:fn.current,city:vn.current,state:Tn.current,addressLine1:zt.current,addressLine2:Dn.current})},...by({chv:X,avsCheck:lt,checkoutType:Ke,checkoutLayout:Ct,avsConfig:P,country:Ut.current})}),si=async wn=>{let Ro=zs(z)||wn?.status==="authorized";aa(E),Le?.terminal({outcome:"payment_succeeded",...Ir}),S("success"),Ye(null),await new Promise(Sa=>setTimeout(Sa,600));let Nr;typeof wn?.paymentId=="string"?Nr=wn.paymentId:z?.paymentId&&(Nr=z.paymentId);let Io;typeof wn?.authorizationExpiresAt=="string"?Io=wn.authorizationExpiresAt:z?.authorizationExpiresAt&&(Io=z.authorizationExpiresAt),l?.(Ro?{status:"authorized",...Nr===void 0?{}:{paymentId:Nr},sessionId:typeof wn?.sessionId=="string"?wn.sessionId:E,...Io===void 0?{}:{authorizationExpiresAt:Io},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ue,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ue,checkoutMethod:r.isPaypal?"paypal":"card"})};if(ar.ok){await si(ar.status===204?null:await ar.json().catch(()=>null));return}let un=await ar.json().catch(()=>null);if(un?.type==="paypal_redirect_required"){let wn=un.threeDSecureToken,Ro=un.paymentMethodId||r.id||"";if(!j||!wn){S("error"),ge("PayPal authorization required but no token provided.");return}try{let Nr=y?.getRawProvider();if(!Nr){ge("PayPal is not available.");return}let Io={return_url:window.location.href};Ro&&(Io.payment_method=Ro);let{error:Sa}=await Nr.confirmPayment({clientSecret:wn,confirmParams:Io,redirect:"if_required"});if(Sa){S("error");let rc=Sa.message??"PayPal payment failed.";ge(rc),Or("paypal",rc,{code:Sa.code})}}catch(Nr){S("error"),ge(Nr instanceof Error?Nr.message:"PayPal authorization failed.")}return}if(un?.type==="paypal_direct_required"){let wn=un.orderId;if(!wn){S("error"),ge("PayPal retry required but no order id provided.");return}let Ro=Sn.current?.attempts??0;if(Ro>=2){S("error"),ge("PayPal payment could not be completed after multiple attempts."),Or("paypal","paypal_direct_required retry limit exceeded");return}as(!1),is("loading"),Ye({orderId:wn,attempts:Ro+1}),S(null);return}if(ar.headers.get(cm)===dm){let wn=await um(ft,E,J);if(wn!==void 0){await si(wn);return}}_y(ar.status,un)?Le?.terminal({outcome:"payment_declined",...Ir,terminalReason:"provider_declined"}):tt(),S("error");let nc=un?.message??"Payment failed. Please try again.";ge(nc),Or(r.isPaypal?"paypal":"card",nc,{code:un?.code??un?.gatewayErrorCode,declineCode:un?.declineCode??un?.gatewayDeclineReason}),await new Promise(wn=>setTimeout(wn,400))}catch(ft){qd(ft)||tt(),S("error"),ge(ft instanceof Error?ft.message:"An unexpected error occurred"),await new Promise(dn=>setTimeout(dn,400))}finally{Zt(!1),S(null),M.current=!1}},[ro,e,t,mt,P,lt,Ke,Ct,X,j,y,z,l,ge,Or,h,ut]),Qn=Be((r,f)=>{C&&!f?.settledProcessResponse?C(r):$l(r,f)},[C,$l]),ga=`${Ud}:${e}`;Je(()=>{if(typeof window>"u")return;let r=localStorage.getItem(ga);if(!r)return;let f;try{f=JSON.parse(r)}catch{sn(ga);return}if(!f||typeof f.createdAt!="number"||Date.now()-f.createdAt<0||Date.now()-f.createdAt>zd||typeof f.paymentMethodId!="string"||typeof f.providerIntentId!="string"||typeof f.paymentMethodType!="string"||f.sessionId!==e||!t||f.nonce!==t||!jo.includes(f.paymentMethodType)){sn(ga);return}sn(ga),Qn({id:f.paymentMethodId,type:"card",threeDSecureActionResultTokenId:f.providerIntentId,gateway:"stripe",paymentMethodType:f.paymentMethodType},{...f.accountPatch?{accountPatch:f.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Qn,t,e,ga,jo]);let Wl=B(!1);Je(()=>{if(typeof window>"u"||Wl.current)return;let[r,f,E]=Bd();if(!r||!f||Xa.current||!j)return;let J=j.getRawProvider();if(!J)return;let F=tt=>{let ft=localStorage.getItem(tt);if(!ft)return null;try{return JSON.parse(ft)}catch{return sn(tt),null}},ue=F(qr)??F(kd),It;if(ue?.clientSecret){if(ue.clientSecret!==f)return;It={...ue.accountPatch?{accountPatch:ue.accountPatch}:{},...ue.sessionId?{sessionId:ue.sessionId}:{},...ue.nonce?{nonce:ue.nonce}:{}}}else if(ue?.sessionId&&ue.sessionId!==e)return;Wl.current=!0,sn(qr),sn(kd),window.history.replaceState({},"",Od());let Et=ue?.paymentMethodType??ue?.tokenType??"card",Le="card";(async()=>{if(E==="failed"){let un="Payment was declined. Please try again.";ge(un),Or(Le,un);return}let{paymentIntent:tt,error:ft}=await J.retrievePaymentIntent(f);if(ft){let un=ft.message??"Failed to retrieve payment status.";ge(un),Or(Le,un,{code:ft.code});return}let dn=tt?.status,ar=Ea(dn);if(!tt||!ar){let un=dn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ge(un),Or(Le,un,{code:dn??"missing_payment_intent"});return}let si=typeof tt.payment_method=="string"?tt.payment_method:tt.payment_method?.id;Qn({id:si??ue?.paymentMethodId??ue?.tokenId??tt.id,type:"card",threeDSecureActionResultTokenId:tt.id,gateway:ue?.gateway??"stripe",paymentMethodType:Et},It)})()},[e,Qn,j,ge,Or]);let cs=Be(r=>{r.preventDefault()},[]);if(!(Pe||j!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ha=Re==="buttons",Wn=Do?.variables,Ru=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ds=Wn?.colorBackground,Iu=ds&&!Ru.has(ds)?ds:void 0,Pa=ve.cardInputBorder??(ha?"#e5e7eb":"#A4A4FF"),Kl=Wn?.colorDanger??"#dc2626",tn=r=>ln[r]&&(Co[r]||cr),ri=Lo&&(vo||cr),dr=r=>r?Kl:Pa,oi=(An.malformed||An.empty)&&(Kr||cr),Eu=dr(oi),us=ve.cardFormContainer?.backgroundColor??Iu??(ha?"white":"#EDEDFF"),$o=ve.cardInputBackground??Wn?.colorBackground??"white",ps=Vo(Z),Hl=Vo(le),Wo=ve.nameInput,Vl=ve.cardInputFontSize??_m(Wo?.fontSize)??Wn?.fontSizeBase??"16px",Gl=typeof Wo?.fontFamily=="string"?Wo.fontFamily:Wn?.fontFamily??"Poppins, sans-serif",Yl=em(Wo?.fontWeight)??400,_u=ve.cardInputColor??(typeof Wo?.color=="string"?Wo.color:void 0)??Wn?.colorText??"#262833",Tu=ve.cardInputPlaceholderColor??"#9ca3af",an=Wn?.borderRadius??"8px",Yr=Wn?.borderRadius??ve.cardButton?.borderRadius??an,io=Wn?.colorPrimary??"#4A49FF",Mu=Wn?.colorPrimaryHover??Ay(io,.12),ys=Wn?.colorText??"#262833",ms={fontSize:Vl,fontFamily:Gl,fontWeight:Yl,color:_u,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},va={marginTop:"0.375rem",...ms,fontSize:"0.75rem",lineHeight:1.4,color:Kl},Au={"--flopay-input-placeholder-color":Tu,"--flopay-input-font-size":Vl,"--flopay-input-font-family":Gl,"--flopay-input-font-weight":String(Yl)},Ca=ve.cardFormContainer??{},fs=Ca.padding??(ha?"0":"1rem"),gs=Ca.borderRadius??an,xu=ke&&On?d(Ps,{capture:ke,html:On.html,messageToken:On.messageToken,expectedOrigin:On.expectedOrigin,verificationRequired:On.verificationRequired,theme:pu,submitLabel:D,onReady:()=>{if(!oo&&!P||typeof document>"u"||ze===!1)return;let r=()=>{let E=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(E){Cr.current=!0;try{E.focus()}finally{Cr.current=!1}}};to.current||r()},onError:r=>{r&&On.verificationRequired&&L.current==="idle"&&(v.current=!0),ge(r)},onValidation:r=>{let f=L.current;(f==="idle"||f==="validation-window")&&(ge(r),r&&L.current==="validation-window"&&(x.current&&(clearTimeout(x.current),x.current=null),L.current="idle",S(null)))}},s):d("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),hs=Ne("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&Br()},style:{backgroundColor:us,borderRadius:gs,...Ca,padding:fs,...Au,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
5
5
|
.flopay-shared-input::placeholder {
|
|
6
6
|
color: var(--flopay-input-placeholder-color);
|
|
7
7
|
opacity: 1;
|
|
@@ -9,13 +9,13 @@ ${Se.join(`
|
|
|
9
9
|
font-family: var(--flopay-input-font-family);
|
|
10
10
|
font-weight: var(--flopay-input-font-weight);
|
|
11
11
|
}
|
|
12
|
-
`}),ha&&
|
|
13
|
-
`)}):null,Xl=r=>
|
|
14
|
-
`)}):null,Zl=xe==="apm-expanding"||xe==="apm-form"||xe==="apm-collapsing",Wo;xe==="apm-expanding"?Wo=_d:xe==="apm-collapsing"&&(Wo=Td);let ii=an?$d(ts,an,Ut):null,Ql={label:Dt||md,open:En,onOpen:A,color:eo,fontFamily:qn?.fontFamily};if(Ie==="buttons"){let r=xe==="buttons"||xe==="expanding"||xe==="apm-expanding",p=xe==="expanding"||xe==="card"||xe==="collapsing",B=Ee===void 0?{boxSizing:"border-box",height:wo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Q;xe==="expanding"||xe==="apm-expanding"?Q=Cm:(xe==="collapsing"||xe==="apm-collapsing")&&(Q=vm);let z;xe==="expanding"?z=_d:xe==="collapsing"&&(z=Td);let me=xt&&Sd(xt,{canHide:()=>!0,available:Nl}),Tt={paypal:Le(jn,{children:[Po&&je&&Le(jn,{children:[Ge&&l("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),l(Aa.Provider,{value:H,children:l(bi,{sessionId:e,nonce:t,billingApiUrl:nt,email:ht.email,billingName:Do||void 0,onBuyerIdentityReady:cr,clientId:je.clientId,environment:je.environment,currency:wt.toUpperCase(),isSubscription:et,providerObjectType:Dn,approvalPresentation:ti==="popup"?void 0:ti,onTokenizedBody:Gn,onComplete:s,onErrorChange:ge,onDecline:d,onCancel:R,onTechnicalFailure:Uo,onButtonClick:ze,runBeforeButtonClick:Sr,isProcessing:tn,onLoadStateChange:as,onInitializationStateChange:is,session:Ht,existingOrderId:Ge?.orderId,debug:m},Ge?.orderId??"fresh")})]}),vo&&l(oo,{stripe:fa,options:Pl,children:l(Ad,{sessionId:e,nonce:t,email:ht.email,billingName:Do||void 0,onBuyerIdentityReady:cr,billingApiUrl:nt,onTokenizedBody:Gn,onErrorChange:ge,isProcessing:tn,onButtonClick:ze,onDecline:d,onTechnicalFailure:Uo,runBeforeButtonClick:Sr,onLoadStateChange:Ml,placeholderBorderRadius:Hr,popupCapabilityOwner:H,externalTelemetryContext:Ol,presentationMode:zo})})]}),wallets:Le(jn,{children:[Qr?l(oo,{stripe:nr,options:hl,children:l(xd,{sessionId:e,nonce:t,email:ht.email,billingName:Do||void 0,onBuyerIdentityReady:cr,billingApiUrl:nt,intentKind:mt>0?"payment":"setup",expressMethods:qo,onTokenizedBody:Gn,onErrorChange:ge,onButtonClick:ze,onDecline:d,onTechnicalFailure:Uo,runBeforeButtonClick:Sr,onLoadStateChange:Al,placeholderBorderRadius:Hr,popupCapabilityOwner:H,externalTelemetryContext:tt})}):null,!Qr&&Dl?l("div",{style:{height:wo,borderRadius:Hr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:l(jn,{children:Co&&l(Fd,{sessionId:e,nonce:t,email:ht.email,billingName:[ht.firstName,ht.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:cr,billingApiUrl:nt,paymentElementMethods:Qa,stripeInstance:nr,paymentElementBaseOptions:ts,futureUseSession:Ut,onTokenizedBody:Gn,onErrorChange:ge,onButtonClick:ze,onDecline:d,runBeforeButtonClick:Sr,onLoadStateChange:xl,isProcessing:tn,submitButtonColor:eo,submitButtonBorderRadius:nn,submitButtonStyle:Fe.submitButton,onExpandApm:N,expandedApmMethod:an,themeId:ke,buttonAppearance:{backgroundColor:Fe.cardButton?.backgroundColor,borderColor:Fe.cardInputBorder,textColor:Fe.cardButton?.color,borderRadius:Hr}})}),card:l(jn,{children:ne&&l("button",{type:"button",onClick:async()=>{tn||!(await Sr("card")).proceed||(ze?.("card"),x())},disabled:tn,style:{width:"100%",...B,...Fe.cardButton,...tl({themeBundle:Fo,resolvedPrimaryColor:eo,resolvedBorderRadius:nn,submitButtonStyle:Fe.submitButton,explicitPrimaryColor:qn?.colorPrimary}),fontSize:Fe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:tn?"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:tn?.6:1},onMouseEnter:Mt=>{!tn&&(Fo||qn?.colorPrimary)&&(Mt.currentTarget.style.backgroundColor=Tu)},onMouseLeave:Mt=>{(Fo||qn?.colorPrimary)&&(Mt.currentTarget.style.backgroundColor=eo)},onMouseDown:Mt=>{Mt.currentTarget.style.transform="scale(0.985)"},onMouseUp:Mt=>{Mt.currentTarget.style.transform="scale(1)"},children:l(Vo,{content:Ee})})})};return Le("form",{onSubmit:cs,className:ae,noValidate:!0,style:{position:"relative"},children:[l(ui,{}),F&&l(Dr,{status:F,errorMessage:Cr,authorized:Et}),Le("div",{style:{display:"grid"},children:[Le("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?Sm:{},...Q?{animation:Q,pointerEvents:"none"}:{}},children:[Jl("flopay-direct-paypal-gate-debug"),Xl("flopay-stripe-gate-debug"),Cn&&me?Le(jn,{children:[Cn.filter(({group:Mt})=>me.inView.includes(Mt)).map(({group:Mt,key:Oe})=>l(ja.Fragment,{children:Tt[Mt]},Oe)),me.behindLink.length>0&&l(Ls,{...Ql,showLink:me.showLink,children:Cn.filter(({group:Mt})=>me.behindLink.includes(Mt)).map(({group:Mt,key:Oe})=>l(ja.Fragment,{children:Tt[Mt]},Oe))})]}):l(Ns,{rows:Ll,borderRadius:Hr}),Cr&&xe==="buttons"&&l(ra,{margin:"0.25rem 0",styleOverride:Fe.errorBanner,children:Cr})]}),ne&&p&&l("div",{style:{gridArea:"1 / 1",...z?{animation:z}:{},...xe==="collapsing"?{pointerEvents:"none"}:{}},children:hs}),I&&Zl&&an&&ii&&nr&&l("div",{style:{gridArea:"1 / 1",...Wo?{animation:Wo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:us,borderRadius:gs,...Ca,padding:fs},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:le,style:{display:"inline-flex",alignItems:"center",gap:ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Fe.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Fe.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Fe.backButtonIcon},children:l("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Go,{content:te})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Fe.titleFontSize??"1.05rem",color:ys,paddingRight:80,...Fe.title},children:`Pay with ${Wa(an)}`})]}),l(oo,{stripe:nr,options:ii,children:l(Js,{method:an,sessionId:e,nonce:t,email:ht.email,billingName:[ht.firstName,ht.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:cr,billingApiUrl:nt,onTokenizedBody:Gn,onErrorChange:ge,onDecline:d,onCancel:le,runBeforeButtonClick:Sr,onButtonClick:ze,isProcessing:tn,submitButtonColor:eo,submitButtonBorderRadius:nn,submitButtonStyle:Fe.submitButton,errorText:Cr})},an)]})})]})]})}if(Zl&&an&&ii&&nr&&I)return Le("form",{onSubmit:cs,className:ae,noValidate:!0,style:{position:"relative"},children:[l(ui,{}),F&&l(Dr,{status:F,errorMessage:Cr,authorized:Et}),l("div",{style:{...Wo?{animation:Wo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:us,borderRadius:gs,...Ca,padding:fs},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:le,style:{display:"inline-flex",alignItems:"center",gap:ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Fe.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Fe.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Fe.backButtonIcon},children:l("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Go,{content:te})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Fe.titleFontSize??"1.05rem",color:ys,paddingRight:80,...Fe.title},children:`Pay with ${Wa(an)}`})]}),l(oo,{stripe:nr,options:ii,children:l(Js,{method:an,sessionId:e,nonce:t,email:ht.email,billingName:[ht.firstName,ht.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:cr,billingApiUrl:nt,onTokenizedBody:Gn,onErrorChange:ge,onDecline:d,onCancel:le,runBeforeButtonClick:Sr,onButtonClick:ze,isProcessing:tn,submitButtonColor:eo,submitButtonBorderRadius:nn,submitButtonStyle:Fe.submitButton,errorText:Cr})},an)]})})]});let ec=bu||Cu||Su,ba=xt&&Sd(xt,{canHide:r=>r!=="card",available:Nl}),tc={paypal:Le(jn,{children:[Po&&je&&Le(jn,{children:[Ge&&l("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),l(Aa.Provider,{value:H,children:l(bi,{sessionId:e,nonce:t,billingApiUrl:nt,email:ht.email,billingName:Do||void 0,onBuyerIdentityReady:cr,clientId:je.clientId,environment:je.environment,currency:wt.toUpperCase(),isSubscription:et,providerObjectType:Dn,approvalPresentation:ti==="popup"?void 0:ti,onTokenizedBody:Gn,onComplete:s,onErrorChange:ge,onDecline:d,onCancel:R,onTechnicalFailure:Uo,onButtonClick:ze,runBeforeButtonClick:Sr,isProcessing:tn,onLoadStateChange:as,onInitializationStateChange:is,session:Ht,existingOrderId:Ge?.orderId,debug:m},Ge?.orderId??"fresh")})]}),vo&&l(oo,{stripe:fa,options:Pl,children:l(Ad,{sessionId:e,nonce:t,email:ht.email,billingName:Do||void 0,onBuyerIdentityReady:cr,billingApiUrl:nt,onTokenizedBody:Gn,onErrorChange:ge,isProcessing:tn,onButtonClick:ze,onDecline:d,onTechnicalFailure:Uo,runBeforeButtonClick:Sr,onLoadStateChange:Ml,placeholderBorderRadius:Hr,popupCapabilityOwner:H,externalTelemetryContext:Ol,presentationMode:zo})})]}),wallets:l(jn,{children:Qr&&l(oo,{stripe:nr,options:hl,children:l(xd,{sessionId:e,nonce:t,email:ht.email,billingName:Do||void 0,onBuyerIdentityReady:cr,billingApiUrl:nt,intentKind:mt>0?"payment":"setup",expressMethods:qo,onTokenizedBody:Gn,onErrorChange:ge,onButtonClick:ze,onDecline:d,onTechnicalFailure:Uo,runBeforeButtonClick:Sr,onLoadStateChange:Al,placeholderBorderRadius:Hr,popupCapabilityOwner:H,externalTelemetryContext:tt})})}),apms:l(jn,{children:Co&&l(Fd,{sessionId:e,nonce:t,email:ht.email,billingName:[ht.firstName,ht.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:nt,paymentElementMethods:Qa,stripeInstance:nr,paymentElementBaseOptions:ts,futureUseSession:Ut,onTokenizedBody:Gn,onErrorChange:ge,onButtonClick:ze,onDecline:d,runBeforeButtonClick:Sr,onLoadStateChange:xl,isProcessing:tn,submitButtonColor:eo,submitButtonBorderRadius:nn,submitButtonStyle:Fe.submitButton,themeId:ke,onExpandApm:N,expandedApmMethod:an,buttonAppearance:{backgroundColor:Fe.cardButton?.backgroundColor,borderColor:Fe.cardInputBorder,textColor:Fe.cardButton?.color,borderRadius:Hr}})})};return Le("form",{onSubmit:cs,className:ae,noValidate:!0,style:{position:"relative"},children:[l(ui,{}),F&&l(Dr,{status:F,errorMessage:Cr,authorized:Et}),Cn===null?l(Ns,{rows:Ll,borderRadius:Hr}):Le(jn,{children:[bn&&ne&&hs,bn&&ne&&ec&&l(vs,{label:"or pay another way"}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Jl("flopay-direct-paypal-gate-debug-default"),Xl("flopay-stripe-gate-debug-default"),Cn.map(({group:r,key:p})=>r==="card"||!ba?.inView.includes(r)?null:l(ja.Fragment,{children:tc[r]},p)),ba&&ba.behindLink.length>0&&l(Ls,{...Ql,showLink:ba.showLink,children:Cn.map(({group:r,key:p})=>ba.behindLink.includes(r)&&r!=="card"?l(ja.Fragment,{children:tc[r]},p):null)})]}),!bn&&ne&&ec&&l(vs,{label:"or pay with card"}),!bn&&ne&&hs]})]})}import{Fragment as Nr,jsx as ce,jsxs as gn}from"react/jsx-runtime";var _o=44,sl="flopay_checkout_saved_payment_resume",Wm="paypal_resume_nonce_missing",qi=new Map,Li=new Map;function Yd(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 s=()=>{Li.get(e)===i&&Li.delete(e)};return a.then(s,s),a}function Ka(e){return new Promise(t=>setTimeout(t,e))}function zi(e,t,n){let o=vi({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:iu,enabled:t!==!1});return o.beginCheckout(n),o}function Va(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function rl(e,t,n,o,a,i){let s=zi(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Va(s)}function Jd(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 Xd(e,t,n,o,a){let i=ru(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-o),durationMode:"machine",requestCategory:n,attempt:a,statusClass:i.statusClass}),t instanceof vn&&t.code==="session_auto_completed"?!1:t instanceof vn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function ol(e){return!e||e.data.stripe?.publishableKey?!1:!!ou(e.data.paypal)?.clientId}var Km={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Zd(e){return new Fm(Km,{publishableKey:"provider_unavailable",...e})}async function Ni(e,t){let{publishableKey:n,paypalPublishableKey:o}=Ds(e);return{...await Os({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function Qd(e){let t=e.data.stripe;return JSON.stringify([t?.publishableKey??null,t?.paypalPublishableKey??null])}function ll(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Vm(){if(!ll())return null;try{let e=window.sessionStorage.getItem(sl);return e?JSON.parse(e):null}catch{return null}}function eu(e){if(ll())try{window.sessionStorage.setItem(sl,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function al(){if(ll())try{window.sessionStorage.removeItem(sl)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Gm(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let o of t)e.searchParams.has(o)&&(e.searchParams.delete(o),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function tu(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function il(e,t){return jm(!!e,t)}function Ym(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function nu(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Jm(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function cl({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:c,error:d,onComplete:R,onError:g,onInstrument:y,onDecline:D,onCancel:ee,onCountryChange:ae,onZipChange:j,showPayPal:K=!0,showStripe:C=!0,walletPresentation:fe="auto",enabledPaymentMethods:de,showApplePay:I=!0,showGooglePay:He=!0,debug:X=!1,layout:Ne,paymentMethodLayout:at,moreOptionsLabel:pt,theme:Ie,buttonsTheme:Nt,buttonsStyles:Dt,cardButtonContent:ke,cardBackButtonContent:Ye,cardTitleContent:it,showSecurityFooter:st,onButtonClick:Ee,onBeforeButtonClick:te,enableAVS:ue,cardFieldOrder:$t,showCardBrandIcons:ze,showCardFieldLabels:lt,cardFieldLabels:re,cardFieldPlaceholders:Me,cardAutoFocus:Ze,onCardFieldsReady:V,onCardFieldsFailed:Ct,cardFieldsTimeoutMs:be,cardPreFormSlot:Je,avsLayout:Ue,submitLabel:Qe,className:bt,initialErrorMessage:De=null,initialPayPalOrderId:Rt,children:Ae,checkoutMode:_e,confirmLabel:St,renderConfirmButton:Ot,onSessionCompleted:It}){let G=zm(o),pe=mr(()=>au(Ie),[Ie]),Te=i??pe?.appearance,ct=n?"embedded_checkout":"standard_checkout",dt=il(Ae,Ne),[Ke,yt]=Wt(null),[mt,wt]=Wt(null),qe=Lt(null),je=Lt(null),et=Lt(0),[$,hn]=Wt(null),w=Lt(null),[m,Y]=Wt(null),W=mr(()=>n?Ba(n):"",[n]),J=n?`create:${W}`:`session:${e??""}`,f=nu(m),ie=Lt(new Set),H=Lt(J),Se=Lt(J);wa(()=>{Se.current=J,H.current!==J&&(H.current=J,ie.current.clear())},[J]);let we=Rn(P=>{if(Se.current===J){if(Uc.has(P.name)){if(ie.current.has(P.name))return;ie.current.add(P.name)}Bt(()=>y?.(P))}},[J,y]),E=ta(we,J),tt=Lt(!1),Ht=Rn(P=>{if(tt.current)return;let A=P.gateway||!f?P:{...P,gateway:f};we(A)},[we,f]);or(()=>{E({class:"lifecycle",name:"checkout.mount"})},[E]);let[Ut,Dn]=Wt(e??""),he=e??Ut,Er=n?"":he,[cn,dn]=Wt(!0),[nt,xt]=Wt(null),[In,En]=Wt(0),[_n,Cn]=Wt("full"),[bn,Kt]=Wt(!1),[zt,Zt]=Wt(De),[Ve,ye]=Wt(null),[ar,Ft]=Wt(null),[Tn,On]=Wt(!1),[ir,Ln]=Wt(void 0),[_r,fr]=Wt(""),[un,pn]=Wt(!1),[Mn,$n]=Wt(!1),[Nn,An]=Wt(!1),on=Lt(null),Qt=Lt(0),en=Lt(void 0),[Vt,Un]=Wt("loading"),[zn,xn]=Wt(0),_=Lt(!1),$e=Lt(!1),h=Lt(!1),se=Lt(null),Et=Lt({active:!0});or(()=>{let P={active:!0};return Et.current=P,()=>{P.active=!1}},[]);let gt=Lt(null),ut=mr(()=>({checkoutMode:_e??_n,layout:Ym(Ae,Ne)}),[_e,Ae,_n,Ne]),Re=Lt(R);Re.current=R;let Wn=Lt(g);Wn.current=g;let Ao=Lt(D);Ao.current=D;let Fn=Rn(P=>Ii(se,async A=>{try{return await P(A)}catch(O){throw A.aborted?aa(O):O}}),[]);or(()=>()=>{se.current?.abort(),se.current=null},[]);let ne=Rn((P,A)=>{qe.current=P,wt(P),w.current=A,hn(A)},[]),gr=Rn(()=>{let P=je.current;P&&(je.current=null,P.destroy())},[]),[Tr,Jr]=Wt(null);or(()=>{!Tr||mt!==Tr.flopay||(Jr(null),Tr.apply())},[mt,Tr]);let po=Rn(async(P,A,O)=>{let M=null;try{M=await Ni(P,{billingApiUrl:G,locale:s,telemetry:a})}catch{M=null}if(!A())return;if(gr(),M){xc([M.flopay?.getRawProvider(),M.paypalFlopay?.getRawProvider()],[qe.current?.getRawProvider(),w.current?.getRawProvider()]),ne(M.flopay,M.paypalFlopay),En(0),Jr({flopay:M.flopay,apply:O});return}let We=Zd({billingApiUrl:G,locale:s,telemetry:a});je.current=We,ne(We,null),En(1),O()},[gr,ne,s,G,a]);or(()=>{fn(mt)?.setCheckoutContext(ut),$&&$!==mt&&fn($)?.setCheckoutContext(ut)},[mt,$,ut]);let Jn=Lt(It);Jn.current=It;let Mr=Rn(P=>{Un(P),!(P!=="exhausted"||h.current)&&(h.current=!0,Wn.current?.(new vn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),zr=Rn(()=>{Un("retrying"),xn(P=>P+1)},[]);or(()=>{Un("loading"),xn(0),h.current=!1},[he]),or(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:iu,checkout_type:ct,checkout_layout:dt,billing_api_url:G})},[dt,ct,G]);let yn=mr(()=>n?Ba(n,!0):"",[n]),qr=mr(()=>_r===yn?ir:void 0,[ir,_r,yn]),Hn=mr(()=>n?Rs(n,qr):void 0,[n,qr]),Sn=_e??Hn?.checkoutMode??"full",Gt=mr(()=>Hn?{...Hn,checkoutMode:Sn}:void 0,[Hn,Sn]);or(()=>{Ln(void 0),fr(yn),en.current=void 0,on.current=null,An(!1)},[yn]),or(()=>{Zt(De)},[De]);let Pe=Rn((P,A,O)=>{Bt(()=>{Ao.current?.(mn(P,A,O))})},[]),wn=Rn(async(P,A)=>{let O=Et.current;if(!O.active)return!1;Zt(null),Ft(null),On(!1),ye("processing");let M=A?.sessionId??P.id,We=P.clientSecret||t,v=nu(P),u=qe.current??w.current,k=fn(u),x=u?null:zi(G,a,ut),S={log:b=>{k?k.log(b):x?.log(b)},error:b=>{k?k.error(b):x?.error(b)},terminal:b=>{k?k.terminal(b):x?.terminal(b)},performance:b=>{k?k.performance(b):x?.performance(b)},now:()=>k?.now()??x?.now()??0,elapsed:b=>k?.elapsed(b)??Math.max(0,(x?.now()??b)-b)},N=S.now(),le=!!(A?.initialAutoProcessingError||A?.initialAutoProcessingPending),F=!1,U,ft=()=>{F||(F=!0,le=!0,U=S.now(),S.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},_t=!1,ve=()=>{_t||(_t=!0,S.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),S.performance({stage:"processing",durationMs:S.elapsed(N),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),U!==void 0&&S.performance({stage:"recovery",durationMs:S.elapsed(U),durationMode:"machine",paymentMethodCategory:"saved"}))};S.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),tt.current=!0;try{S.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{tt.current=!1}E({class:"lifecycle",name:"payment.processing.started",provider:v}),le&&ft();let Z;try{let b=ld(A?.initialAutoProcessingError),T=A?.initialAutoProcessingError?.type==="3ds_required"&&!Nm(A.initialAutoProcessingError)&&!A.initialAutoProcessingError.threeDSecureToken&&A.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:A.initialAutoProcessingError.nextActionRedirectUrl}:null,L,kt=Ce=>{ft();let Ge=Ua(G,M,P,a!==!1);return Fn(tr=>ia(Ce,{billingApiUrl:G,sessionId:M,nonce:We,session:P,signal:tr,...Ge.telemetry?{challengeTelemetry:Ge.telemetry}:{}})).finally(Ge.release)};if(T)L=await kt(T);else if(b)ft(),b.type==="paypal_redirect_required"&>.current?.publishableKey&&eu({sessionId:M,publishableKey:gt.current.publishableKey,paypalPublishableKey:gt.current.paypalPublishableKey,nonce:We}),L=await Fn(Ce=>_i(b,{flopay:qe.current,paypalFlopay:w.current,attempt3DS:A?.attempt3DS,billingApiUrl:G,sessionId:M,session:P,telemetry:!1,signal:Ce})),b.type==="paypal_redirect_required"&&al();else if(A?.initialAutoProcessingPending){let Ce=A.initialAutoProcessingPending,Ge=new Oi(G,{telemetry:!1}),tr=await Fn(xo=>Ge.waitForCheckoutSessionCompletion(Ce.sessionId,{initialDelayMs:Ce.retryAfterMs,nonce:We,statusUrl:Ce.statusUrl,signal:xo})),Vn=ro(tr,P),vr=tr.autoProcessingError?.type==="3ds_required"&&tr.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:tr.autoProcessingError.nextActionRedirectUrl}:null;if(vr)L=await kt(vr);else{if(!Vr(Vn))throw Xo(Vn);L=Kr(Vn,M)}}else{if(A?.initialAutoProcessingError)throw Or(A.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:A.initialAutoProcessingError.checkoutMethod});if(A?.fromCreateSession)return A?.fallbackToFull&&(Cn("full"),tu("full")),!1;{let Ce=await sa({billingApiUrl:G,sessionId:M,session:P,nonce:We,telemetry:!1});if(!O.active&&Ce.type!=="success")return!1;Ce.type==="success"?L=Ce.result:Ce.type==="next_action_required"?L=await kt(Ce):(ft(),Ce.type==="paypal_redirect_required"&>.current?.publishableKey&&eu({sessionId:M,publishableKey:gt.current.publishableKey,paypalPublishableKey:gt.current.paypalPublishableKey,nonce:We}),L=await Fn(Ge=>_i(Ce,{flopay:qe.current,paypalFlopay:w.current,attempt3DS:A?.attempt3DS,billingApiUrl:G,sessionId:M,session:P,telemetry:!1,signal:Ge})),Ce.type==="paypal_redirect_required"&&al())}}if(M&&oa(M),!O.active)return!1;ve(),le&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),S.terminal({outcome:L.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),On(L.status==="authorized"),ye("success"),await Ka(600),Z=()=>Re.current?.(L)}catch(b){if(!O.active)return!1;let T=no(za(b),M);if(T.code==="three_ds_aborted")return!1;let L=T.checkoutMethod??Na;Zt(T.message),Ft(T.message),On(!1),A?.fallbackToFull&&(S.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Cn("full"),tu("full")),ve();let kt=T.statusCode===void 0?void 0:$m(T.statusCode,"unknown"),Ce=kt==="4xx"?{requestCategory:"process_payment",statusClass:kt}:{},Ge=kt===void 0||kt==="4xx";if(Kd(T))S.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ce});else if(Ge&&(T.telemetryOutcome==="validation_rejected"||T.type==="validation_error"))S.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ce});else{let vr=ru(b,le?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),xo=T.telemetryRequestCategory??"process_payment";tt.current=!0;try{S.error({...vr,...T.telemetryFailureCategory?{failureCategory:T.telemetryFailureCategory}:{},stage:le?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:xo})}finally{tt.current=!1}E({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:xo,provider:v})}return Hd(T)?Pe(L,T,{code:T.code,declineCode:T.declineCode}):Bt(()=>Wn.current?.(T)),ye("error"),await Promise.allSettled([Ka(400),A?.ensureProvidersReady?A.ensureProvidersReady():Promise.resolve()]),le&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{ve(),x&&Va(x),O.active&&(ye(null),Ft(null))}return O.active?(Bt(Z),!0):!1},[Pe,E,t,G,Fn,a,ut]);or(()=>{if(typeof window>"u"||$e.current)return;let P=new URLSearchParams(window.location.search),A=P.get("payment_intent_client_secret");if(!A)return;let O=Vm();O&&($e.current=!0,(async()=>{await Promise.resolve();let M,We=0;Zt(null),Ft(null),ye("processing"),Kt(!0);try{if(P.get("redirect_status")==="failed")throw Object.assign(new vn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:v,paypalFlopay:u}=await Os({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:G,locale:s,telemetry:a});M=fn(u??v),M?.setCheckoutContext(ut),We=M?.now()??0,M?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),M?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let k=(u??v)?.getRawProvider();if(!k)throw Object.assign(new vn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:x,error:S}=await k.retrievePaymentIntent(A);if(S)throw Object.assign(new vn(S.message??"Failed to retrieve PayPal payment status.","api_error",{code:S.code}),{checkoutMethod:"paypal"});let N=Rc(x?.status);if(!x||N==="failed")throw Object.assign(new vn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let le=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id,F=N;if(O.sessionId){let U=O.nonce||t;if(!U)throw Object.assign(new vn("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:Wm}),{checkoutMethod:"paypal"});let ve=(await new Oi(G,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId,U)).data.session;if(ve&&ve.status!=="complete"){let Z=await sa({billingApiUrl:G,sessionId:O.sessionId,session:ve,nonce:U,telemetry:!1,tokenizedData:{id:le??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0}});if(Z.type!=="success")throw Object.assign(new vn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});F=Z.result.status}}O.sessionId&&oa(O.sessionId),M?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),M?.performance({stage:"redirect_resume",durationMs:M.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),M?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ye("success"),await Ka(600),Bt(()=>Re.current?.({status:F,paymentIntentId:x.id,paymentMethodId:le,checkoutMethod:"paypal"}))}catch(v){let u=no(za(v),O.sessionId),k=u.checkoutMethod??"paypal",x=Kd(u);if(M)M.performance({stage:"redirect_resume",durationMs:M.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),x?M.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):M.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(x){let S=zi(G,a,ut);S.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Va(S)}else rl(G,a,ut,"REDIRECT_RESUME_FAILED","redirect_resume");Zt(u.message),Ft(u.message),Hd(u)?Pe(k,u,{code:u.code,declineCode:u.declineCode}):Bt(()=>Wn.current?.(u)),ye("error"),await Ka(400)}finally{al(),Gm(),ye(null),Ft(null),Kt(!1)}})())},[Pe,s,t,G,a,ut]);let Xn=Lt(null),hr=mr(()=>Gt?Ba(Gt):"",[Gt]),Pr=Lt(Gt);Pr.current=Gt,or(()=>{Dn(e??"")},[e]),or(()=>{_.current=!1,Zt(De),Ft(null),On(!1),ye(null)},[hr,De,e]);async function sr(P,A,O){let M=zi(G,a,ut),We=new Oi(G,{telemetry:!1,stripeAccountSwitch:!0}),v=!1;try{let u=P.idempotencyKey===void 0?void 0:Vd(P.idempotencyKey),k=Zc(A,O),x=Xc(A,O);k?.canonicalIdentity===O&&x&&x.canonicalIdentity===void 0&&(wi(A,O,x.idempotencyKey),x={...x,canonicalIdentity:O});let S=u??(x?.canonicalIdentity===O?x.idempotencyKey:void 0),N,le=!1;M.log({name:k?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let F=k?.sid??null,U=null,ft,_t,ve=!1;if(F)try{U=await We.getUnifiedCheckoutSession(F,k?.nonce),k&&k.canonicalIdentity===void 0&&(Jc(U.data.session,P)?(ki(A,O,F,k.nonce??U.data.session?.clientSecret),x&&x.canonicalIdentity===void 0&&(wi(A,O,x.idempotencyKey),S??(S=x.idempotencyKey))):(Si(A,O),x=null,S=u,F=null,U=null));let b=U?.data.session?.status,T=U?.data.session,L=T?.clientSecret||k?.nonce;if(F&&T?.buyerIdentified===!1&&L&&(_t=Jo(We,F,L,P.account)),F&&U&&b==="complete"){if(xs(F))return{sid:F,result:U};Si(A,O),F=null,U=null,le=!0}}catch{M.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),k?.canonicalIdentity===void 0?(Si(A,O),S=u):As(A,O),F=null}if(!F){!u&&(le||!S)&&(S=Vd(),N=S),S&&wi(A,O,S);let b=M.now(),T=0;M.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let L={...P,idempotencyKey:S,avsCheck:!!ue,avsConfig:typeof ue=="object"?ue:void 0,checkoutType:"embedded_checkout",checkoutLayout:il(Ae,Ne)};Object.defineProperty(L,Bm,{configurable:!1,enumerable:!1,value:{onAttempt:Ge=>{T=Math.max(T,Ge)}}});let kt=()=>{Jd(M,"session_create",b,T)},Ce=Ge=>{Xd(M,Ge,"session_create",b,T)&&E({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(P.checkoutMode==="confirm"||P.checkoutMode==="auto")&&nd();try{if(Lm(L)){let Ge=await We.createDetachedSession(L);Ge.claimed.catch(()=>{}),U=Ge.shell,F=Ge.sessionId,_t=Ge.claim;let tr=M.now();M.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ft=Ge.claimed.then(Vn=>{let vr=Vn.data.session?.id??Ge.sessionId;return vr&&ki(A,O,vr,Vn.data.session?.clientSecret??Ge.nonce),Jd(M,"session_claim",tr),kt(),Vn},Vn=>{throw As(A,O),Xd(M,Vn,"session_claim",tr,0)&&E({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Vn}).finally(()=>Va(M)),ft.catch(()=>{}),v=!0,M.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),M.performance({stage:"session_shell",durationMs:M.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:T,statusClass:"2xx",paymentMethodCategory:"card"})}else U=await We.createAndFetchSession(L),kt()}catch(Ge){throw Ce(Ge),Ge}F=U.data.session?.id??F??"",F&&!ft&&ki(A,O,F,U.data.session?.clientSecret)}let Z=U?.data.session;return!_t&&F&&Z?.buyerIdentified===!1&&Z.clientSecret&&(_t=Jo(We,F,Z.clientSecret,P.account)),{sid:F??"",result:U,sdkGeneratedIdempotencyKey:N,...ft?{claimed:ft}:{},..._t?{claim:_t}:{},...ve?{claimRequiresIdentity:!0}:{}}}finally{v||Va(M)}}let yo=Lt(sr);wa(()=>{yo.current=sr},[sr]);let jr=Rn(async(P,A)=>{let O=Pr.current;if(!O)throw new vn("createSession is required to bootstrap checkout.","validation_error");let M=Rs(O,P),We=Ba(M),v=Yc(M),u=qi.get(We);if(!u){let S={canonicalIdentity:We,promise:yo.current(M,v,We),consumers:0,settled:!1};u=S,qi.set(We,S);let N=()=>{S.settled=!0,Yd(We,S)};S.promise.then(N,N)}u.consumers+=1;let k=!1,x=()=>{k||(k=!0,u.consumers-=1,Yd(We,u))};A?.(x);try{let S=await u.promise;Xn.current=We,P&&(fr(yn),Ln(Z=>vc(Z,P)));let{sid:N,result:le,claimed:F,claim:U,claimRequiresIdentity:ft}=S;en.current=U,An(ft===!0),yt(le),le.data.session&&Y(le.data.session),N&&Dn(N);let _t=()=>{},ve=new Promise(Z=>{_t=Z});if(F){Qt.current+=1;let Z=Qt.current,b=()=>Qt.current===Z;on.current=F,$n(!0);let T=L=>{b()&&(on.current===F&&(on.current=null),yt(L),L.data.session&&Y(L.data.session),$n(!1),An(!1))};F.then(async L=>{if(b()){if(Qd(L)===Qd(le)){T(L);return}await ve,b()&&await po(L,b,()=>T(L))}},L=>{Qt.current===Z&&(on.current===F&&(on.current=null),$n(!1),An(!1),xt(L instanceof vn?L:new vn(L instanceof Error?L.message:"Failed to create session","api_error")))})}else Qt.current+=1,on.current=null,$n(!1),An(!1);try{let{flopay:Z,paypalFlopay:b}=await Ni(le,{billingApiUrl:G,locale:s,telemetry:a}).catch(T=>{throw Sc(T,N||le.data.session?.id)});ne(Z,b)}finally{_t()}return dn(!1),S}catch(S){throw Xn.current===We&&(Xn.current=null),S}finally{A||x()}},[yn,ne,s,G,po,a]),mo=Lt(wn);mo.current=wn;let $r=Lt(jr);$r.current=jr;let fo=Rn(async P=>{if(!Jm(P)||un)return{sessionId:Ut,session:m};pn(!0);try{let A=await jr(P);return{sessionId:A.sid,session:A.result.data.session??null}}finally{pn(!1)}},[jr,un,Ut,m]),Wr=Rn(async P=>{let A=en.current;if(!A)return;let O=Qt.current,M=await A(P);Qt.current===O&&(yt(M),M.data.session&&Y(M.data.session))},[]),lr=Rn(async()=>{await on.current},[]),go=Rn(async()=>(await lr(),{proceed:!0}),[lr]);or(()=>{let P=!1,A,O=++et.current;gr(),xt(null),En(0);let M=()=>{P=!0,et.current===O&&(et.current+=1,gr())},We=Pr.current;if(hr&&We)return Cn(Sn),dn(!1),Xn.current===hr?M:(Y(Cc(We,_e)),(async()=>{let k=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),x=Sn==="auto"&&!_.current&&!k;x&&(Zt(null),Ft(null),ye("processing"));let S=!1;try{let N=await $r.current(void 0,ft=>{A=ft});S=!0;let le=N.result.data.session??null;gt.current=Ds(N.result);let F=ol(N.result),U=xs(N.sid||le?.id);if(!P&&x&&le&&!F&&!U){_.current=!0,await Hm(hr,N.sdkGeneratedIdempotencyKey,()=>mo.current(le,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:N.result.autoProcessingError,initialAutoProcessingPending:N.result.autoProcessingPending,autoProcessingAttempted:N.result.autoProcessingAttempted,sessionId:N.sid||le.id}));return}!P&&x&&((F||U)&&(_.current=!0),ye(null),Ft(null))}catch(N){if(P)return;let le=yi(N);if(x&&le==="session_auto_completed"){_.current=!0,ye("success"),await Ka(600),P||(Bt(()=>{Re.current?.({status:"succeeded"})}),ye(null),Ft(null));return}if(x&&(ye(null),Ft(null)),!S){let U=wc(N),ft=Gd(N,U?{stage:"provider_load",provider:"stripe",...U}:{stage:"session_request"});(U||!(N instanceof vn))&&Bt(()=>Wn.current?.(ft)),xt(ft);return}let F=N instanceof vn?N:new vn(N instanceof Error?N.message:"Failed to create session","api_error");xt(F)}finally{A?.(),A=void 0}})(),()=>{M(),A?.()});dn(!0);async function v(){let k=!1,x=!1,S=null;try{let N=new Oi(G,{telemetry:!1}),le=await N.getUnifiedCheckoutSession(he,t);if(x=!0,S=le,P)return;yt(le);let F=le.data.session??null;if(Y(F),!F)throw new vn("No session data returned","api_error");let U=F.checkoutMode;if(U==="setup")throw new vn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(F.status==="authorized"){dn(!1),Bt(()=>{Re.current?.(Kr(F,he)),Jn.current?.(F.successUrl??"")});return}if(F.status==="complete"){dn(!1),Bt(()=>{Jn.current?.(F.successUrl??"")});return}if(F.status==="expired")throw pi(F);k=!0;let ft=_e??U??"full";Cn(ft),Qt.current+=1;let _t=F.clientSecret||t;en.current=F.buyerIdentified===!1&&_t?Jo(N,he,_t,{...F.customer?.id?{userId:F.customer.id}:{}}):void 0,$n(!1),An(!1);let ve=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Z=ol(le);if(ft==="auto"&&!_.current&&!ve&&!Z){_.current=!0;let b=u(le);try{if(await mo.current(F,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>b,sessionId:he||F.id}),P)return;await b,P||dn(!1);return}catch{if(P)return;await b,P||dn(!1);return}}await u(le),P||dn(!1)}catch(N){if(P)return;let le=Pc(N,k);if(k&&E({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),le){let{errorCode:_t,stage:ve,...Z}=le;rl(G,a,ut,_t,ve,Z)}if(le?.stage==="provider_load"&&(_e??S?.data.session?.checkoutMode??"full")==="full"&&hc(S,K,C)){let _t=Zd({billingApiUrl:G,locale:s,telemetry:a});je.current=_t,ne(_t,null),En(1),dn(!1);return}let F=le?.stage==="provider_load",U="session_request";F?U="provider_load":x&&(U="post_session");let ft=Gd(N,{stage:U,provider:"stripe",sessionId:he||void 0});(F||!(N instanceof vn))&&Bt(()=>Wn.current?.(ft)),xt(ft),dn(!1)}}async function u(k){let{flopay:x,paypalFlopay:S,...N}=await Ni(k,{billingApiUrl:G,locale:s,telemetry:a});gt.current={publishableKey:N.publishableKey,paypalPublishableKey:N.paypalPublishableKey},ne(x,S),En(0)}return v(),M},[_e,hr,Sn,Er,t,K,C]);let ho=Rn(async()=>{if(!Ke||In!==1)return;let P=et.current;En(2);try{let{flopay:A,paypalFlopay:O}=await Ni(Ke,{billingApiUrl:G,locale:s,telemetry:a});if(et.current!==P)return;gr(),ne(A,O),En(0)}catch(A){if(et.current!==P)return;let{errorCode:O,stage:M,...We}=ks(A);rl(G,a,ut,O,M,We)}},[gr,ne,s,In,G,a,ut,Ke]),qt=!!(he&&(m?.clientSecret||t)),Kn=bn||!qt,Ar=Rn(async()=>{let P=Et.current;if(!(!P.active||bn||!qt||!m)){Kt(!0),Zt(null);try{await wn(m,{attempt3DS:!0,fallbackToFull:!0,sessionId:he||m.id})}finally{P.active&&Kt(!1)}}},[he,bn,qt,wn,m]),Yt=ou(Ke?.data.paypal,Rt),Zn=ol(Ke),xe=mr(()=>{if(!(!Ke||!m||!Ke.data.stripe?.publishableKey))return{billingApiUrl:G}},[Ke,m,G]),Bn=!!(n&&!Ae&&Ne==="buttons"&&te&&Sn==="full"),an=!!(he&&(Um(m?.vault)||ko(m))),Qn=mr(()=>({session:m,loading:cn,error:nt,checkoutMode:_n,inlineSessionDraft:Gt,applyInlineSessionPatch:Bn?fo:void 0,inlineSessionPatchProcessing:un,claimPending:Mn,claimRequiresIdentity:Nn,claimBuyerIdentity:Wr,waitForDataAttachment:lr}),[m,cn,nt,_n,Gt,Bn,fo,un,Mn,Nn,Wr,lr]),pa=!!n&&Ne==="buttons"&&!Zn&&!an&&(!mt||!xe),er=Ve?ce(Dr,{status:Ve,errorMessage:ar,authorized:Tn}):null;if(cn&&!an){if(c)return gn(Nr,{children:[c,er]});if(Ne==="buttons"){let P=pe?.buttonsLayout?.cardButton?.borderRadius??pe?.appearance.variables?.borderRadius??8,A=O=>ce("div",{style:{height:O,borderRadius:P,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return gn(Nr,{children:[gn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[K&&A(_o),C&&(I||He)&&A(_o),C&&A(_o),ce("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),er]})}return gn(Nr,{children:[gn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ce("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ce("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),er]})}return nt?d?ce(wr.Provider,{value:Qn,children:d(nt)}):ce(wr.Provider,{value:Qn,children:ce("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:nt.message})}):pa?gn(Nr,{children:[ce(wr.Provider,{value:Qn,children:ce(Zm,{onButtonClick:Ee,paymentMethodLayout:at,showPayPal:K,showStripe:C,showApplePay:I,showGooglePay:He,theme:Ie,buttonsTheme:Nt,buttonsStyles:Dt,cardButtonContent:ke,cardBackButtonContent:Ye,cardTitleContent:it})}),er]}):Zn&&m&&Yt?gn(Nr,{children:[ce(wr.Provider,{value:Qn,children:gn("div",{className:bt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[zt&&ce(ra,{icon:!1,children:zt}),Vt==="retrying"&&ce("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Vt==="exhausted"&&gn("div",{role:"alert",children:[ce("div",{children:"PayPal is temporarily unavailable. Please try again."}),ce("button",{type:"button",onClick:zr,children:"Retry PayPal"})]}),Vt!=="exhausted"&&ce("div",{"aria-hidden":Vt==="retrying"?!0:void 0,style:Vt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ce(Vc,{sessionId:he,nonce:m.clientSecret||void 0,billingApiUrl:G,email:m.customer?.email||Gt?.account?.email,billingName:[m.customer?.firstName,m.customer?.lastName].filter(Boolean).join(" ")||[Gt?.account?.firstName,Gt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Wr,clientId:Yt.clientId,environment:Yt.environment,currency:(m.currency??"usd").toUpperCase(),isSubscription:m.mode==="subscription",providerObjectType:Yt.providerObjectType,approvalPresentation:Yt.approvalPresentation,existingOrderId:Yt.existingOrderId,onComplete:R,onErrorChange:Zt,onDecline:D,onCancel:ee,onButtonClick:Ee,runBeforeButtonClick:go,onInitializationStateChange:Mr,allowAutomaticRetry:zn===0,session:m,telemetry:a,telemetryContext:ut,onInstrument:Ht,debug:X},`${J}:paypal-init-${zn}`)})]})}),er]}):_n==="confirm"?gn(Nr,{children:[ce(wr.Provider,{value:Qn,children:ce(Ri,{flopay:mt,paypalFlopay:$,options:xe??{billingApiUrl:G},onInstrument:Ht,children:gn("div",{className:bt,children:[zt&&ce("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:zt}),Ot?Ot({onConfirm:Ar,isProcessing:Kn}):ce("button",{type:"button",onClick:Ar,disabled:Kn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Kn?"not-allowed":"pointer",opacity:Kn?.6:1},children:bn?"Processing...":St??"Confirm Purchase"})]})},J)}),er]}):(!mt||!xe)&&!(an&&_n==="full")?ce(Nr,{children:er}):gn(Nr,{children:[ce(wr.Provider,{value:Qn,children:gn(Ri,{flopay:mt,paypalFlopay:$,options:xe??{billingApiUrl:G},onInstrument:Ht,children:[In===1&&ce("button",{type:"button",onClick:ho,children:"Retry payment methods"}),Ae?gn(Nr,{children:[zt&&ce("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:zt}),ce(Xm,{sessionId:he,nonce:m?.clientSecret||void 0,billingApiUrl:G,session:m,submitLabel:Qe,walletPresentation:fe,paymentMethodLayout:at,moreOptionsLabel:pt,children:Ae})]}):ce(nl,{sessionId:he,nonce:m?.clientSecret||void 0,telemetry:a,email:m?.customer?.email||Gt?.account?.email,userId:m?.customer?.id||Gt?.account?.userId,firstName:m?.customer?.firstName||Gt?.account?.firstName,lastName:m?.customer?.lastName||Gt?.account?.lastName,totalAmount:m?Math.round(Dm(m).total*100):0,currency:m?.currency?.toLowerCase()??"usd",onComplete:R,onError:g,onDecline:D,onCancel:ee,error:zt,onErrorChange:Zt,showPayPal:K,showStripe:C,walletPresentation:fe,enabledPaymentMethods:In?[]:de??Ke?.data.stripe?.enabledPaymentMethods??m?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:He,layout:Ne,paymentMethodLayout:at,moreOptionsLabel:pt,theme:Ie,buttonsTheme:Nt,buttonsStyles:Dt,appearance:Te,cardButtonContent:ke,cardBackButtonContent:Ye,cardTitleContent:it,onButtonClick:Ee,onBeforeButtonClick:te,onBuyerIdentityReady:Wr,enableAVS:ue,...$t?{cardFieldOrder:$t}:{},...ze===void 0?{}:{showCardBrandIcons:ze},...lt===void 0?{}:{showCardFieldLabels:lt},...re===void 0?{}:{cardFieldLabels:re},...Me===void 0?{}:{cardFieldPlaceholders:Me},...Ze===void 0?{}:{cardAutoFocus:Ze},...V?{onCardFieldsReady:V}:{},...Ct?{onCardFieldsFailed:Ct}:{},...be===void 0?{}:{cardFieldsTimeoutMs:be},...Je?{cardPreFormSlot:Je}:{},avsLayout:Ue,country:m?.customer?.country,city:m?.customer?.city,state:m?.customer?.state,onCountryChange:ae,onZipChange:j,avsCheck:!!ue,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:il(Ae,Ne),className:bt,submitLabel:Qe,directPaypal:Yt,isSubscription:m?.mode==="subscription",session:m,dataAttachmentPending:Mn,dataAttachmentRequiresIdentity:Nn,debug:X})]},J)}),er]})}function Xm({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,paymentMethodLayout:s,moreOptionsLabel:c,children:d}){return ce(Nr,{children:Ui.Children.map(d,R=>{if(!Ui.isValidElement(R))return R;let g=R.props,y={};return g.sessionId||(y.sessionId=e),!g.nonce&&t&&(y.nonce=t),g.billingApiUrl||(y.billingApiUrl=n),g.submitLabel===void 0&&a!==void 0&&(y.submitLabel=a),g.walletPresentation===void 0&&(y.walletPresentation=i),g.paymentMethodLayout===void 0&&s!==void 0&&(y.paymentMethodLayout=s),g.moreOptionsLabel===void 0&&c!==void 0&&(y.moreOptionsLabel=c),o?.customer&&(g.email||(y.email=o.customer.email),g.userId||(y.userId=o.customer.id),g.firstName||(y.firstName=o.customer.firstName),g.lastName||(y.lastName=o.customer.lastName)),Object.keys(y).length===0?R:Ui.cloneElement(R,y)})})}function Zm({onButtonClick:e,paymentMethodLayout:t,showPayPal:n,showStripe:o=!0,showApplePay:a,showGooglePay:i,theme:s,buttonsTheme:c,buttonsStyles:d,cardButtonContent:R,cardBackButtonContent:g,cardTitleContent:y}){let[D,ee]=Wt(!1),ae=mr(()=>au(s),[s]),j=mr(()=>{let I=ae?.buttonsLayout??qm(c);return d?{...I,...d,cardButton:{...I.cardButton,...d.cardButton},cardFormContainer:{...I.cardFormContainer,...d.cardFormContainer},backButton:{...I.backButton,...d.backButton},backButtonIcon:{...I.backButtonIcon,...d.backButtonIcon},submitButton:{...I.submitButton,...d.submitButton},title:{...I.title,...d.title}}:I},[ae,c,d]),K=ae?.buttonsLayout?.cardButton?.borderRadius??ae?.appearance.variables?.borderRadius??8,C=I=>ce("div",{style:{height:I,borderRadius:K,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),fe=R===void 0?{boxSizing:"border-box",height:_o,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(D){let I=j.cardInputBorder??"#e5e7eb",He=j.cardInputBackground??"white",X=Ko(g),Ne=Ko(y);return gn("div",{style:{backgroundColor:j.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...j.cardFormContainer},children:[gn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[gn("button",{type:"button",onClick:()=>ee(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:X?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...j.backButton},children:[ce("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...j.backButtonIcon},children:ce("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:ce("path",{d:"M15 18l-6-6 6-6"})})}),ce(Go,{content:g})]}),Ne?ce("div",{style:{flex:1}}):ce("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...j.title},children:ce(Ia,{content:y})})]}),ce("div",{style:{backgroundColor:He,border:`1px solid ${I}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ce("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),gn("div",{style:{display:"flex"},children:[ce("div",{style:{flex:1,backgroundColor:He,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,borderBottomLeftRadius:8,padding:12,height:45},children:ce("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ce("div",{style:{flex:1,backgroundColor:He,borderTop:"none",borderRight:`1px solid ${I}`,borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,borderBottomRightRadius:8,padding:12,height:45},children:ce("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ce("div",{style:{backgroundColor:He,border:`1px solid ${I}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ce("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ce("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...j.submitButton,opacity:.5}}),ce("style",{children:`
|
|
12
|
+
`}),ha&&no&&Ne("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Pe?-2:0},children:[Ne("button",{type:"button",onClick:qe,style:{display:"inline-flex",alignItems:"center",gap:ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ve.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ve.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ve.backButtonIcon},children:d("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(Yo,{content:Z})]}),Hl?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ve.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...ve.title},children:d(Ia,{content:le})})]}),!ha&&!Hl&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ys,order:Pe?-3:0,...ve.title},children:d(Ia,{content:le})}),Pe&&wt&&d("div",{style:{order:-2,width:"100%"},children:wt}),Pe&&oo&&Ne("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[d("div",{style:{backgroundColor:$o,border:`1px solid ${dr(ri)}`,borderRadius:an,padding:"10px"},children:d("input",{ref:ne,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Pr,onChange:r=>{qt("email"),T.current=r.target.value,Un(r.target.value)},onPointerDown:()=>qt("email"),onKeyDown:()=>qt("email"),onBlur:()=>{Jn("email")&&Fr(!0),Lo||Vi()},disabled:on,required:!0,"aria-invalid":ri||void 0,"aria-describedby":ri?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...ms}})}),ri&&d("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:va,children:$i.empty?"Email address is required":"Enter a valid email address"})]}),P&&d("div",{style:{order:Pe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=we,f=(F=!1)=>({backgroundColor:$o,border:`1px solid ${dr(F)}`,borderRadius:an,marginTop:"0.5rem",padding:"10px"}),E=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ms}),J=Oy(r);return Ne(Kn,{children:[nn(P.address_line_1,r)&&Ne(Kn,{children:[d("div",{style:f(tn("line1")),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Qt,onChange:F=>{qt("line1"),$e.current.addressLine1=!0,zt.current=F.target.value,gr(F.target.value)},onPointerDown:()=>qt("line1"),onKeyDown:()=>qt("line1"),onBlur:()=>Vr("line1"),disabled:on,required:!0,"aria-invalid":tn("line1")||void 0,"aria-describedby":tn("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:E()})}),tn("line1")&&d("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:va,children:"Street address is required"})]}),nn(P.address_line_2,r)&&d("div",{style:f(),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:In,onChange:F=>{$e.current.addressLine2=!0,Dn.current=F.target.value,_r(F.target.value)},disabled:on,"data-testid":"flopay-address-line2",style:E()})}),(nn(P.city,r)||nn(P.state,r))&&Ne("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[nn(P.city,r)&&d("div",{style:{flex:1,backgroundColor:$o,borderTop:`1px solid ${dr(tn("city"))}`,borderRight:`1px solid ${dr(tn("city"))}`,borderBottom:`1px solid ${dr(tn("city"))}`,borderLeft:`1px solid ${dr(tn("city"))}`,padding:"10px",borderTopLeftRadius:an,borderBottomLeftRadius:an,...nn(P.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:an}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:hr,onChange:F=>{qt("city"),$e.current.city=!0,vn.current=F.target.value,En(F.target.value)},onPointerDown:()=>qt("city"),onKeyDown:()=>qt("city"),onBlur:()=>Vr("city"),disabled:on,required:!0,"aria-invalid":tn("city")||void 0,"aria-describedby":tn("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:E()})}),nn(P.state,r)&&d("div",{style:{flex:1,backgroundColor:$o,borderTop:`1px solid ${dr(tn("state"))}`,borderRight:`1px solid ${dr(tn("state"))}`,borderBottom:`1px solid ${dr(tn("state"))}`,borderLeft:`1px solid ${dr(tn("state"))}`,padding:"10px",borderTopRightRadius:an,borderBottomRightRadius:an,...nn(P.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${dr(tn("state")||tn("city"))}`}:{borderRadius:an}},children:J?Ne("select",{id:"flopay-billing-state",name:"billing-state",value:mn,onChange:F=>{qt("state"),$e.current.state=!0,Tn.current=F.target.value,_n(F.target.value)},onPointerDown:()=>qt("state"),onKeyDown:()=>qt("state"),onBlur:()=>Vr("state"),disabled:on,autoComplete:"billing address-level1",required:!0,"aria-invalid":tn("state")||void 0,"aria-describedby":tn("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...E(),cursor:"pointer"},children:[d("option",{value:"",children:Us(r)}),J.map(F=>d("option",{value:F.code,children:F.name},F.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Us(r),autoComplete:"billing address-level1",value:mn,onChange:F=>{qt("state"),$e.current.state=!0,Tn.current=F.target.value,_n(F.target.value)},onPointerDown:()=>qt("state"),onKeyDown:()=>qt("state"),onBlur:()=>Vr("state"),disabled:on,required:!0,"aria-invalid":tn("state")||void 0,"aria-describedby":tn("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:E()})})]}),tn("city")&&d("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:va,children:"City is required"}),tn("state")&&Ne("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:va,children:[Us(r)," is required"]}),(nn(P.country,r)||nn(P.postal_code,r))&&Ne("div",{style:{display:"flex",flexDirection:Me==="column"?"column":"row",gap:Me==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[nn(P.country,r)&&d("div",{style:{flex:Me==="row"?1:void 0,backgroundColor:$o,borderTop:`1px solid ${Pa}`,borderRight:`1px solid ${Pa}`,borderBottom:`1px solid ${Pa}`,borderLeft:`1px solid ${Pa}`,padding:"10px",...Me==="row"&&nn(P.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:an,borderBottomLeftRadius:an,borderRight:"none"}:{borderRadius:an}},children:Ne("select",{id:"flopay-billing-country",name:"billing-country",value:we,onChange:F=>{$e.current.country=!0,Ut.current=F.target.value,tr(F.target.value),_e?.(F.target.value),Tn.current="",_n("")},disabled:on,autoComplete:"billing country","data-testid":"flopay-country",style:{...E(),cursor:"pointer"},children:[we===""?d("option",{value:"",children:"Select country"}):null,Iy.map(F=>Ne("option",{value:F.code,children:[F.flag," ",F.name]},F.code))]})}),nn(P.postal_code,r)&&d("div",{style:{flex:Me==="row"?1:void 0,backgroundColor:$o,border:`1px solid ${Eu}`,padding:"10px",...Me==="row"&&nn(P.country,r)?{borderRadius:"0",borderTopRightRadius:an,borderBottomRightRadius:an}:{borderRadius:an}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Vs(we),autoComplete:"billing postal-code",value:St,onChange:F=>{qt("zip"),$e.current.zip=!0,fn.current=F.target.value,Bn(F.target.value),st?.(F.target.value)},onPointerDown:()=>qt("zip"),onKeyDown:()=>qt("zip"),onBlur:()=>{Jn("zip")&&xr(!0)},disabled:on,required:An.required,"aria-invalid":oi||void 0,"aria-describedby":oi?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:E()})})]}),oi&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:va,children:An.empty?`${Vs(r)} is required`:Rm(r)})]})})()}),Pe&&xu,Yt&&d(oa,{margin:"0.75rem 0",styleOverride:ve.errorBanner,children:Yt})]}),ai={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Jl=r=>q?!se||!Lr?d("pre",{"data-testid":r,style:ai,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":r,style:ai,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${se}`,` directPaypalConfigured=${Lr}`,` inAppBrowserDetected=${String(ei)}`,` shouldRenderDirectPayPal=${So}`,` shouldRenderStripePayPal=${wo}`,` hasPaypalStripeInstance=${!!fl}`].join(`
|
|
13
|
+
`)}):null,Xl=r=>q?!I||!or?d("pre",{"data-testid":r,style:ai,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":r,style:ai,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${I}`,` currency=${ct}`,` amountInCents=${ya}`,` enabledPaymentMethods: ${JSON.stringify(G??[])}`,` enabledPaymentMethodsProvided=${ma}`,` hasEnabledMethods=${Ja}`,` expressMethods: ${JSON.stringify(Za)}`,` walletExpressMethods: ${JSON.stringify(jo)}`,` paymentElementMethods: ${JSON.stringify(es)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Qa)}`,` hasStripeInstance=${!!or}`,` shouldRenderWallets=${ao}`,` shouldRenderPaymentElement=${ko}`].join(`
|
|
14
|
+
`)}):null,Zl=Fe==="apm-expanding"||Fe==="apm-form"||Fe==="apm-collapsing",Ko;Fe==="apm-expanding"?Ko=_d:Fe==="apm-collapsing"&&(Ko=Td);let ii=$t?$d(ts,$t,At):null,Ql={label:Dt||md,open:Hn,onOpen:Dr,color:io,fontFamily:Wn?.fontFamily};if(Re==="buttons"){let r=Fe==="buttons"||Fe==="expanding"||Fe==="apm-expanding",f=Fe==="expanding"||Fe==="card"||Fe==="collapsing",E=Ie===void 0?{boxSizing:"border-box",height:Eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},J;Fe==="expanding"||Fe==="apm-expanding"?J=bm:(Fe==="collapsing"||Fe==="apm-collapsing")&&(J=Cm);let F;Fe==="expanding"?F=_d:Fe==="collapsing"&&(F=Td);let ue=yt&&Sd(yt,{canHide:()=>!0,available:Nl}),It={paypal:Ne(Kn,{children:[So&&Qe&&Ne(Kn,{children:[fe&&d("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),d(Aa.Provider,{value:O,children:d(bi,{sessionId:e,nonce:t,billingApiUrl:pt,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,clientId:Qe.clientId,environment:Qe.environment,currency:ct.toUpperCase(),isSubscription:et,providerObjectType:Fn,approvalPresentation:ti==="popup"?void 0:ti,onTokenizedBody:Qn,onComplete:l,onErrorChange:ge,onDecline:m,onCancel:R,onTechnicalFailure:zo,onButtonClick:je,runBeforeButtonClick:Sr,isProcessing:on,onLoadStateChange:as,onInitializationStateChange:is,session:Mt,existingOrderId:fe?.orderId,debug:q},fe?.orderId??"fresh")})]}),wo&&d(uo,{stripe:fa,options:Pl,children:d(Ad,{sessionId:e,nonce:t,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,onTokenizedBody:Qn,onErrorChange:ge,isProcessing:on,onButtonClick:je,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Ml,placeholderBorderRadius:Yr,popupCapabilityOwner:O,externalTelemetryContext:Ol,presentationMode:qo})})]}),wallets:Ne(Kn,{children:[ao?d(uo,{stripe:or,options:hl,children:d(xd,{sessionId:e,nonce:t,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,intentKind:_t>0?"payment":"setup",expressMethods:jo,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:je,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Al,placeholderBorderRadius:Yr,popupCapabilityOwner:O,externalTelemetryContext:ut})}):null,!ao&&Dl?d("div",{style:{height:Eo,borderRadius:Yr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:d(Kn,{children:ko&&d(Fd,{sessionId:e,nonce:t,email:mt.email,billingName:[mt.firstName,mt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,paymentElementMethods:Qa,stripeInstance:or,paymentElementBaseOptions:ts,futureUseSession:At,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:je,onDecline:m,runBeforeButtonClick:Sr,onLoadStateChange:xl,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,onExpandApm:Y,expandedApmMethod:$t,themeId:be,buttonAppearance:{backgroundColor:ve.cardButton?.backgroundColor,borderColor:ve.cardInputBorder,textColor:ve.cardButton?.color,borderRadius:Yr}})}),card:d(Kn,{children:Pe&&d("button",{type:"button",onClick:async()=>{on||!(await Sr("card")).proceed||(je?.("card"),W())},disabled:on,style:{width:"100%",...E,...ve.cardButton,...tl({themeBundle:Zn,resolvedPrimaryColor:io,resolvedBorderRadius:an,submitButtonStyle:ve.submitButton,explicitPrimaryColor:Wn?.colorPrimary}),fontSize:ve.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:on?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:on?.6:1},onMouseEnter:Et=>{!on&&(Zn||Wn?.colorPrimary)&&(Et.currentTarget.style.backgroundColor=Mu)},onMouseLeave:Et=>{(Zn||Wn?.colorPrimary)&&(Et.currentTarget.style.backgroundColor=io)},onMouseDown:Et=>{Et.currentTarget.style.transform="scale(0.985)"},onMouseUp:Et=>{Et.currentTarget.style.transform="scale(1)"},children:d(Go,{content:Ie})})})};return Ne("form",{onSubmit:cs,className:te,noValidate:!0,style:{position:"relative"},children:[d(ui,{}),U&&d(Ur,{status:U,errorMessage:Yt,authorized:Rt}),Ne("div",{style:{display:"grid"},children:[Ne("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!J?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!J?wm:{},...J?{animation:J,pointerEvents:"none"}:{}},children:[Jl("flopay-direct-paypal-gate-debug"),Xl("flopay-stripe-gate-debug"),rn&&ue?Ne(Kn,{children:[rn.filter(({group:Et})=>ue.inView.includes(Et)).map(({group:Et,key:Le})=>d(ja.Fragment,{children:It[Et]},Le)),ue.behindLink.length>0&&d(Ls,{...Ql,showLink:ue.showLink,children:rn.filter(({group:Et})=>ue.behindLink.includes(Et)).map(({group:Et,key:Le})=>d(ja.Fragment,{children:It[Et]},Le))})]}):d(Ns,{rows:Ll,borderRadius:Yr}),Yt&&Fe==="buttons"&&d(oa,{margin:"0.25rem 0",styleOverride:ve.errorBanner,children:Yt})]}),Pe&&f&&d("div",{style:{gridArea:"1 / 1",...F?{animation:F}:{},...Fe==="collapsing"?{pointerEvents:"none"}:{}},children:hs}),I&&Zl&&$t&&ii&&or&&d("div",{style:{gridArea:"1 / 1",...Ko?{animation:Ko}:{},...Fe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ne("div",{style:{backgroundColor:us,borderRadius:gs,...Ca,padding:fs},children:[Ne("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ne("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:de,style:{display:"inline-flex",alignItems:"center",gap:ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ve.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ve.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ve.backButtonIcon},children:d("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(Yo,{content:Z})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ve.titleFontSize??"1.05rem",color:ys,paddingRight:80,...ve.title},children:`Pay with ${Wa($t)}`})]}),d(uo,{stripe:or,options:ii,children:d(Js,{method:$t,sessionId:e,nonce:t,email:mt.email,billingName:[mt.firstName,mt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,onTokenizedBody:Qn,onErrorChange:ge,onDecline:m,onCancel:de,runBeforeButtonClick:Sr,onButtonClick:je,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,errorText:Yt})},$t)]})})]})]})}if(Zl&&$t&&ii&&or&&I)return Ne("form",{onSubmit:cs,className:te,noValidate:!0,style:{position:"relative"},children:[d(ui,{}),U&&d(Ur,{status:U,errorMessage:Yt,authorized:Rt}),d("div",{style:{...Ko?{animation:Ko}:{},...Fe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ne("div",{style:{backgroundColor:us,borderRadius:gs,...Ca,padding:fs},children:[Ne("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ne("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:de,style:{display:"inline-flex",alignItems:"center",gap:ps?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:ve.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...ve.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...ve.backButtonIcon},children:d("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(Yo,{content:Z})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:ve.titleFontSize??"1.05rem",color:ys,paddingRight:80,...ve.title},children:`Pay with ${Wa($t)}`})]}),d(uo,{stripe:or,options:ii,children:d(Js,{method:$t,sessionId:e,nonce:t,email:mt.email,billingName:[mt.firstName,mt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,onTokenizedBody:Qn,onErrorChange:ge,onDecline:m,onCancel:de,runBeforeButtonClick:Sr,onButtonClick:je,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,errorText:Yt})},$t)]})})]});let ec=Su||bu||wu,ba=yt&&Sd(yt,{canHide:r=>r!=="card",available:Nl}),tc={paypal:Ne(Kn,{children:[So&&Qe&&Ne(Kn,{children:[fe&&d("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),d(Aa.Provider,{value:O,children:d(bi,{sessionId:e,nonce:t,billingApiUrl:pt,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,clientId:Qe.clientId,environment:Qe.environment,currency:ct.toUpperCase(),isSubscription:et,providerObjectType:Fn,approvalPresentation:ti==="popup"?void 0:ti,onTokenizedBody:Qn,onComplete:l,onErrorChange:ge,onDecline:m,onCancel:R,onTechnicalFailure:zo,onButtonClick:je,runBeforeButtonClick:Sr,isProcessing:on,onLoadStateChange:as,onInitializationStateChange:is,session:Mt,existingOrderId:fe?.orderId,debug:q},fe?.orderId??"fresh")})]}),wo&&d(uo,{stripe:fa,options:Pl,children:d(Ad,{sessionId:e,nonce:t,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,onTokenizedBody:Qn,onErrorChange:ge,isProcessing:on,onButtonClick:je,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Ml,placeholderBorderRadius:Yr,popupCapabilityOwner:O,externalTelemetryContext:Ol,presentationMode:qo})})]}),wallets:d(Kn,{children:ao&&d(uo,{stripe:or,options:hl,children:d(xd,{sessionId:e,nonce:t,email:mt.email,billingName:Oo||void 0,onBuyerIdentityReady:Gt,billingApiUrl:pt,intentKind:_t>0?"payment":"setup",expressMethods:jo,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:je,onDecline:m,onTechnicalFailure:zo,runBeforeButtonClick:Sr,onLoadStateChange:Al,placeholderBorderRadius:Yr,popupCapabilityOwner:O,externalTelemetryContext:ut})})}),apms:d(Kn,{children:ko&&d(Fd,{sessionId:e,nonce:t,email:mt.email,billingName:[mt.firstName,mt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,paymentElementMethods:Qa,stripeInstance:or,paymentElementBaseOptions:ts,futureUseSession:At,onTokenizedBody:Qn,onErrorChange:ge,onButtonClick:je,onDecline:m,runBeforeButtonClick:Sr,onLoadStateChange:xl,isProcessing:on,submitButtonColor:io,submitButtonBorderRadius:an,submitButtonStyle:ve.submitButton,themeId:be,onExpandApm:Y,expandedApmMethod:$t,buttonAppearance:{backgroundColor:ve.cardButton?.backgroundColor,borderColor:ve.cardInputBorder,textColor:ve.cardButton?.color,borderRadius:Yr}})})};return Ne("form",{onSubmit:cs,className:te,noValidate:!0,style:{position:"relative"},children:[d(ui,{}),U&&d(Ur,{status:U,errorMessage:Yt,authorized:Rt}),rn===null?d(Ns,{rows:Ll,borderRadius:Yr}):Ne(Kn,{children:[yn&&Pe&&hs,yn&&Pe&&ec&&d(vs,{label:"or pay another way"}),Ne("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Jl("flopay-direct-paypal-gate-debug-default"),Xl("flopay-stripe-gate-debug-default"),rn.map(({group:r,key:f})=>r==="card"||!ba?.inView.includes(r)?null:d(ja.Fragment,{children:tc[r]},f)),ba&&ba.behindLink.length>0&&d(Ls,{...Ql,showLink:ba.showLink,children:rn.map(({group:r,key:f})=>ba.behindLink.includes(r)&&r!=="card"?d(ja.Fragment,{children:tc[r]},f):null)})]}),!yn&&Pe&&ec&&d(vs,{label:"or pay with card"}),!yn&&Pe&&hs]})]})}import{Fragment as jr,jsx as ie,jsxs as Pn}from"react/jsx-runtime";var xo=44,sl="flopay_checkout_saved_payment_resume",Km="paypal_resume_nonce_missing",qi=new Map,Li=new Map;function Jd(e,t){t.settled&&t.consumers===0&&qi.get(e)===t&&qi.delete(e)}function Hm(e,t,n){let o=Li.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};Li.set(e,i);let l=()=>{Li.get(e)===i&&Li.delete(e)};return a.then(l,l),a}function Ha(e){return new Promise(t=>setTimeout(t,e))}function zi(e,t,n){let o=vi({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:su,enabled:t!==!1});return o.beginCheckout(n),o}function Va(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function rl(e,t,n,o,a,i){let l=zi(e,t,n);l.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Va(l)}function Xd(e,t,n,o){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...o===void 0?{}:{attempt:o},statusClass:"2xx"})}function Zd(e,t,n,o,a){let i=ou(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-o),durationMode:"machine",requestCategory:n,attempt:a,statusClass:i.statusClass}),t instanceof kn&&t.code==="session_auto_completed"?!1:t instanceof kn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function ol(e){return!e||e.data.stripe?.publishableKey?!1:!!au(e.data.paypal)?.clientId}var Vm={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Qd(e){return new Bm(Vm,{publishableKey:"provider_unavailable",...e})}async function Ni(e,t){let{publishableKey:n,paypalPublishableKey:o}=Ds(e);return{...await Os({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function eu(e){let t=e.data.stripe;return JSON.stringify([t?.publishableKey??null,t?.paypalPublishableKey??null])}function ll(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Gm(){if(!ll())return null;try{let e=window.sessionStorage.getItem(sl);return e?JSON.parse(e):null}catch{return null}}function tu(e){if(ll())try{window.sessionStorage.setItem(sl,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function al(){if(ll())try{window.sessionStorage.removeItem(sl)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Ym(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let o of t)e.searchParams.has(o)&&(e.searchParams.delete(o),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function nu(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function il(e,t){return $m(!!e,t)}function Jm(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function ru(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Xm(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function cl({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:l,loading:u,error:m,onComplete:R,onError:C,onInstrument:g,onDecline:A,onCancel:X,onCountryChange:te,onZipChange:D,showPayPal:K=!0,showStripe:w=!0,walletPresentation:pe="auto",enabledPaymentMethods:se,showApplePay:I=!0,showGooglePay:We=!0,debug:G=!1,layout:Ue,paymentMethodLayout:rt,moreOptionsLabel:dt,theme:Re,buttonsTheme:Nt,buttonsStyles:Dt,cardButtonContent:be,cardBackButtonContent:He,cardTitleContent:ot,showSecurityFooter:at,onButtonClick:Ie,onBeforeButtonClick:Z,enableAVS:le,cardFieldOrder:Kt,showCardBrandIcons:je,showCardFieldLabels:it,cardFieldLabels:Q,cardFieldPlaceholders:Te,cardAutoFocus:Xe,onCardFieldsReady:H,onCardFieldsFailed:ht,cardFieldsTimeoutMs:Ce,cardPreFormSlot:Ve,avsLayout:ze,submitLabel:Ze,className:Pt,initialErrorMessage:De=null,initialPayPalOrderId:wt,children:Me,checkoutMode:Ee,confirmLabel:vt,renderConfirmButton:Ot,onSessionCompleted:kt}){let V=qm(o),ce=mr(()=>iu(Re),[Re]),_e=i??ce?.appearance,st=n?"embedded_checkout":"standard_checkout",lt=il(Me,Ue),[Ke,Ct]=Jt(null),_t=Bt(null),ct=pn(v=>{_t.current=v,Ct(v)},[]),[Ae,Qe]=Jt(null),et=Bt(null),z=Bt(null),Ht=Bt(0),[k,q]=Jt(null),j=Bt(null),[y,oe]=Jt(null),h=mr(()=>n?Ba(n):"",[n]),$=n?`create:${h}`:`session:${e??""}`,O=ru(y),he=Bt(new Set),Se=Bt($),_=Bt($);wa(()=>{_.current=$,Se.current!==$&&(Se.current=$,he.current.clear())},[$]);let ut=pn(v=>{if(_.current===$){if(Uc.has(v.name)){if(he.current.has(v.name))return;he.current.add(v.name)}Ft(()=>g?.(v))}},[$,g]),Mt=na(ut,$),At=Bt(!1),Fn=pn(v=>{if(At.current)return;let s=v.gateway||!O?v:{...v,gateway:O};ut(s)},[ut,O]);ir(()=>{Mt({class:"lifecycle",name:"checkout.mount"})},[Mt]);let[Ge,fr]=Jt(e??""),bt=e??Ge,Er=n?"":bt,[pt,yt]=Jt(!0),[Rn,Hn]=Jt(null),[Vn,rn]=Jt(0),[yn,Xt]=Jt("full"),[Zt,Nn]=Jt(!1),[xe,we]=Jt(De),[tr,St]=Jt(null),[Bn,Qt]=Jt(null),[gr,In]=Jt(!1),[_r,hr]=Jt(void 0),[En,mn]=Jt(""),[_n,Pr]=Jt(!1),[Un,zn]=Jt(!1),[qn,fn]=Jt(!1),Ut=Bt(null),zt=Bt(0),Dn=Bt(void 0),[vn,Tn]=Jt("loading"),[T,$e]=Jt(0),P=Bt(!1),ae=Bt(!1),Rt=Bt(!1),xt=Bt(null),Vt=Bt({active:!0});ir(()=>{let v={active:!0};return Vt.current=v,()=>{v.active=!1}},[]);let ye=Bt(null),en=mr(()=>({checkoutMode:Ee??yn,layout:Jm(Me,Ue)}),[Ee,Me,yn,Ue]),Wr=Bt(R);Wr.current=R;let Mn=Bt(C);Mn.current=C;let Pe=Bt(A);Pe.current=A;let Tr=pn(v=>Ii(xt,async s=>{try{return await v(s)}catch(c){throw s.aborted?ia(c):c}}),[]);ir(()=>()=>{xt.current?.abort(),xt.current=null},[]);let Cn=pn((v,s)=>{et.current=v,Qe(v),j.current=s,q(s)},[]),sr=pn(()=>{let v=z.current;v&&(z.current=null,v.destroy())},[]),Po=pn(()=>{let v=et.current,s=j.current;!v&&!s||(Cn(null,null),rn(0))},[Cn]),Gn=pn(v=>{let s=_t.current,c=s?Kd(s,v):v;ct(c),c.data.session&&oe(c.data.session),c.data.stripe?.publishableKey||Po()},[Po,ct]),[nr,Mr]=Jt(null);ir(()=>{!nr||Ae!==nr.flopay||(Mr(null),nr.apply())},[Ae,nr]);let jn=pn(async(v,s,c)=>{let p=null;try{p=await Ni(v,{billingApiUrl:V,locale:l,telemetry:a})}catch{p=null}if(!s())return;if(sr(),p){xc([p.flopay?.getRawProvider(),p.paypalFlopay?.getRawProvider()],[et.current?.getRawProvider(),j.current?.getRawProvider()]),Cn(p.flopay,p.paypalFlopay),rn(0),Mr({flopay:p.flopay,apply:c});return}let W=Qd({billingApiUrl:V,locale:l,telemetry:a});z.current=W,Cn(W,null),rn(1),c()},[sr,Cn,l,V,a]);ir(()=>{hn(Ae)?.setCheckoutContext(en),k&&k!==Ae&&hn(k)?.setCheckoutContext(en)},[Ae,k,en]);let Ar=Bt(kt);Ar.current=kt;let vr=pn(v=>{Tn(v),!(v!=="exhausted"||Rt.current)&&(Rt.current=!0,Mn.current?.(new kn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),lr=pn(()=>{Tn("retrying"),$e(v=>v+1)},[]);ir(()=>{Tn("loading"),$e(0),Rt.current=!1},[bt]),ir(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:su,checkout_type:st,checkout_layout:lt,billing_api_url:V})},[lt,st,V]);let Yn=mr(()=>n?Ba(n,!0):"",[n]),ke=mr(()=>En===Yn?_r:void 0,[_r,En,Yn]),An=mr(()=>n?Rs(n,ke):void 0,[n,ke]),$n=Ee??An?.checkoutMode??"full",ln=mr(()=>An?{...An,checkoutMode:$n}:void 0,[An,$n]);ir(()=>{hr(void 0),mn(Yn),Dn.current=void 0,Ut.current=null,fn(!1)},[Yn]),ir(()=>{we(De)},[De]);let cr=pn((v,s,c)=>{Ft(()=>{Pe.current?.(gn(v,s,c))})},[]),rr=pn(async(v,s)=>{let c=Vt.current;if(!c.active)return!1;we(null),Qt(null),In(!1),St("processing");let p=s?.sessionId??v.id,W=v.clientSecret||t,qe=ru(v),Y=et.current??j.current,de=hn(Y),U=Y?null:zi(V,a,en),S={log:N=>{de?de.log(N):U?.log(N)},error:N=>{de?de.error(N):U?.error(N)},terminal:N=>{de?de.terminal(N):U?.terminal(N)},performance:N=>{de?de.performance(N):U?.performance(N)},now:()=>de?.now()??U?.now()??0,elapsed:N=>de?.elapsed(N)??Math.max(0,(U?.now()??N)-N)},ne=S.now(),me=!!(s?.initialAutoProcessingError||s?.initialAutoProcessingPending),b=!1,M,x=()=>{b||(b=!0,me=!0,M=S.now(),S.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},L=!1,re=()=>{L||(L=!0,S.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),S.performance({stage:"processing",durationMs:S.elapsed(ne),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),M!==void 0&&S.performance({stage:"recovery",durationMs:S.elapsed(M),durationMode:"machine",paymentMethodCategory:"saved"}))};S.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),At.current=!0;try{S.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{At.current=!1}Mt({class:"lifecycle",name:"payment.processing.started",provider:qe}),me&&x();let Oe;try{let N=ld(s?.initialAutoProcessingError),fe=s?.initialAutoProcessingError?.type==="3ds_required"&&!Um(s.initialAutoProcessingError)&&!s.initialAutoProcessingError.threeDSecureToken&&s.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:s.initialAutoProcessingError.nextActionRedirectUrl}:null,Ye,Sn=jt=>{x();let Lt=Ua(V,p,v,a!==!1);return Tr(Gt=>sa(jt,{billingApiUrl:V,sessionId:p,nonce:W,session:v,signal:Gt,...Lt.telemetry?{challengeTelemetry:Lt.telemetry}:{}})).finally(Lt.release)};if(fe)Ye=await Sn(fe);else if(N)x(),N.type==="paypal_redirect_required"&&ye.current?.publishableKey&&tu({sessionId:p,publishableKey:ye.current.publishableKey,paypalPublishableKey:ye.current.paypalPublishableKey,nonce:W}),Ye=await Tr(jt=>_i(N,{flopay:et.current,paypalFlopay:j.current,attempt3DS:s?.attempt3DS,billingApiUrl:V,sessionId:p,session:v,telemetry:!1,signal:jt})),N.type==="paypal_redirect_required"&&al();else if(s?.initialAutoProcessingPending){let jt=s.initialAutoProcessingPending,Lt=new Oi(V,{telemetry:!1}),Gt=await Tr(ve=>Lt.waitForCheckoutSessionCompletion(jt.sessionId,{initialDelayMs:jt.retryAfterMs,nonce:W,statusUrl:jt.statusUrl,signal:ve})),Yt=co(Gt,v),Zn=Gt.autoProcessingError?.type==="3ds_required"&&Gt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Gt.autoProcessingError.nextActionRedirectUrl}:null;if(Zn)Ye=await Sn(Zn);else{if(!Xr(Yt))throw Zo(Yt);Ye=Jr(Yt,p)}}else{if(s?.initialAutoProcessingError)throw zr(s.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:s.initialAutoProcessingError.checkoutMethod});if(s?.fromCreateSession)return s?.fallbackToFull&&(Xt("full"),nu("full")),!1;{let jt=await la({billingApiUrl:V,sessionId:p,session:v,nonce:W,telemetry:!1});if(!c.active&&jt.type!=="success")return!1;jt.type==="success"?Ye=jt.result:jt.type==="next_action_required"?Ye=await Sn(jt):(x(),jt.type==="paypal_redirect_required"&&ye.current?.publishableKey&&tu({sessionId:p,publishableKey:ye.current.publishableKey,paypalPublishableKey:ye.current.paypalPublishableKey,nonce:W}),Ye=await Tr(Lt=>_i(jt,{flopay:et.current,paypalFlopay:j.current,attempt3DS:s?.attempt3DS,billingApiUrl:V,sessionId:p,session:v,telemetry:!1,signal:Lt})),jt.type==="paypal_redirect_required"&&al())}}if(p&&aa(p),!c.active)return!1;re(),me&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),S.terminal({outcome:Ye.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),In(Ye.status==="authorized"),St("success"),await Ha(600),Oe=()=>Wr.current?.(Ye)}catch(N){if(!c.active)return!1;let fe=lo(za(N),p);if(fe.code==="three_ds_aborted")return!1;let Ye=fe.checkoutMethod??Na;we(fe.message),Qt(fe.message),In(!1),s?.fallbackToFull&&(S.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Xt("full"),nu("full")),re();let Sn=fe.statusCode===void 0?void 0:Wm(fe.statusCode,"unknown"),jt=Sn==="4xx"?{requestCategory:"process_payment",statusClass:Sn}:{},Lt=Sn===void 0||Sn==="4xx";if(Vd(fe))S.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...jt});else if(Lt&&(fe.telemetryOutcome==="validation_rejected"||fe.type==="validation_error"))S.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...jt});else{let Zn=ou(N,me?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),ve=fe.telemetryRequestCategory??"process_payment";At.current=!0;try{S.error({...Zn,...fe.telemetryFailureCategory?{failureCategory:fe.telemetryFailureCategory}:{},stage:me?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:ve})}finally{At.current=!1}Mt({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:ve,provider:qe})}return Hd(fe)?cr(Ye,fe,{code:fe.code,declineCode:fe.declineCode}):Ft(()=>Mn.current?.(fe)),St("error"),await Promise.allSettled([Ha(400),s?.ensureProvidersReady?s.ensureProvidersReady():Promise.resolve()]),me&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{re(),U&&Va(U),c.active&&(St(null),Qt(null))}return c.active?(Ft(Oe),!0):!1},[cr,Mt,t,V,Tr,a,en]);ir(()=>{if(typeof window>"u"||ae.current)return;let v=new URLSearchParams(window.location.search),s=v.get("payment_intent_client_secret");if(!s)return;let c=Gm();c&&(ae.current=!0,(async()=>{await Promise.resolve();let p,W=0;we(null),Qt(null),St("processing"),Nn(!0);try{if(v.get("redirect_status")==="failed")throw Object.assign(new kn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:qe,paypalFlopay:Y}=await Os({publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey,billingApiUrl:V,locale:l,telemetry:a});p=hn(Y??qe),p?.setCheckoutContext(en),W=p?.now()??0,p?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),p?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let de=(Y??qe)?.getRawProvider();if(!de)throw Object.assign(new kn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:U,error:S}=await de.retrievePaymentIntent(s);if(S)throw Object.assign(new kn(S.message??"Failed to retrieve PayPal payment status.","api_error",{code:S.code}),{checkoutMethod:"paypal"});let ne=Rc(U?.status);if(!U||ne==="failed")throw Object.assign(new kn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let me=typeof U.payment_method=="string"?U.payment_method:U.payment_method?.id,b=ne;if(c.sessionId){let M=c.nonce||t;if(!M)throw Object.assign(new kn("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:Km}),{checkoutMethod:"paypal"});let re=(await new Oi(V,{telemetry:!1}).getUnifiedCheckoutSession(c.sessionId,M)).data.session;if(re&&re.status!=="complete"){let Oe=await la({billingApiUrl:V,sessionId:c.sessionId,session:re,nonce:M,telemetry:!1,tokenizedData:{id:me??U.id,type:"card",threeDSecureActionResultTokenId:U.id,isPaypal:!0}});if(Oe.type!=="success")throw Object.assign(new kn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});b=Oe.result.status}}c.sessionId&&aa(c.sessionId),p?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),p?.performance({stage:"redirect_resume",durationMs:p.elapsed(W),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),p?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),St("success"),await Ha(600),Ft(()=>Wr.current?.({status:b,paymentIntentId:U.id,paymentMethodId:me,checkoutMethod:"paypal"}))}catch(qe){let Y=lo(za(qe),c.sessionId),de=Y.checkoutMethod??"paypal",U=Vd(Y);if(p)p.performance({stage:"redirect_resume",durationMs:p.elapsed(W),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),U?p.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):p.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(U){let S=zi(V,a,en);S.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Va(S)}else rl(V,a,en,"REDIRECT_RESUME_FAILED","redirect_resume");we(Y.message),Qt(Y.message),Hd(Y)?cr(de,Y,{code:Y.code,declineCode:Y.declineCode}):Ft(()=>Mn.current?.(Y)),St("error"),await Ha(400)}finally{al(),Ym(),St(null),Qt(null),Nn(!1)}})())},[cr,l,t,V,a,en]);let Kr=Bt(null),xr=mr(()=>ln?Ba(ln):"",[ln]),vo=Bt(ln);vo.current=ln,ir(()=>{fr(e??"")},[e]),ir(()=>{P.current=!1,we(De),Qt(null),In(!1),St(null)},[xr,De,e]);async function Fr(v,s,c){let p=zi(V,a,en),W=new Oi(V,{telemetry:!1,stripeAccountSwitch:!0}),qe=!1;try{let Y=v.idempotencyKey===void 0?void 0:Gd(v.idempotencyKey),de=Zc(s,c),U=Xc(s,c);de?.canonicalIdentity===c&&U&&U.canonicalIdentity===void 0&&(wi(s,c,U.idempotencyKey),U={...U,canonicalIdentity:c});let S=Y??(U?.canonicalIdentity===c?U.idempotencyKey:void 0),ne,me=!1;p.log({name:de?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let b=de?.sid??null,M=null,x,L,re=!1;if(b)try{M=await W.getUnifiedCheckoutSession(b,de?.nonce),de&&de.canonicalIdentity===void 0&&(Jc(M.data.session,v)?(ki(s,c,b,de.nonce??M.data.session?.clientSecret),U&&U.canonicalIdentity===void 0&&(wi(s,c,U.idempotencyKey),S??(S=U.idempotencyKey))):(Si(s,c),U=null,S=Y,b=null,M=null));let N=M?.data.session?.status,fe=M?.data.session,Ye=fe?.clientSecret||de?.nonce;if(b&&fe?.buyerIdentified===!1&&Ye&&(L=Xo(W,b,Ye,v.account)),b&&M&&N==="complete"){if(xs(b))return{sid:b,result:M};Si(s,c),b=null,M=null,me=!0}}catch{p.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),de?.canonicalIdentity===void 0?(Si(s,c),S=Y):As(s,c),b=null}if(!b){!Y&&(me||!S)&&(S=Gd(),ne=S),S&&wi(s,c,S);let N=p.now(),fe=0;p.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ye={...v,idempotencyKey:S,avsCheck:!!le,avsConfig:typeof le=="object"?le:void 0,checkoutType:"embedded_checkout",checkoutLayout:il(Me,Ue)};Object.defineProperty(Ye,Dm,{configurable:!1,enumerable:!1,value:{onAttempt:Lt=>{fe=Math.max(fe,Lt)}}});let Sn=()=>{Xd(p,"session_create",N,fe)},jt=Lt=>{Zd(p,Lt,"session_create",N,fe)&&Mt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(v.checkoutMode==="confirm"||v.checkoutMode==="auto")&&nd();try{if(Nm(Ye)){let Lt=await W.createDetachedSession(Ye);Lt.claimed.catch(()=>{}),M=Lt.shell,b=Lt.sessionId,L=Lt.claim;let Gt=p.now();p.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),x=Lt.claimed.then(Yt=>{let Zn=Yt.data.session?.id??Lt.sessionId;return Zn&&ki(s,c,Zn,Yt.data.session?.clientSecret??Lt.nonce),Xd(p,"session_claim",Gt),Sn(),Yt},Yt=>{throw As(s,c),Zd(p,Yt,"session_claim",Gt,0)&&Mt({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Yt}).finally(()=>Va(p)),x.catch(()=>{}),qe=!0,p.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),p.performance({stage:"session_shell",durationMs:p.now()-N,durationMode:"machine",requestCategory:"session_create",attempt:fe,statusClass:"2xx",paymentMethodCategory:"card"})}else M=await W.createAndFetchSession(Ye),Sn()}catch(Lt){throw jt(Lt),Lt}b=M.data.session?.id??b??"",b&&!x&&ki(s,c,b,M.data.session?.clientSecret)}let Oe=M?.data.session;return!L&&b&&Oe?.buyerIdentified===!1&&Oe.clientSecret&&(L=Xo(W,b,Oe.clientSecret,v.account)),{sid:b??"",result:M,sdkGeneratedIdempotencyKey:ne,...x?{claimed:x}:{},...L?{claim:L}:{},...re?{claimRequiresIdentity:!0}:{}}}finally{qe||Va(p)}}let Co=Bt(Fr);wa(()=>{Co.current=Fr},[Fr]);let Hr=pn(async(v,s)=>{let c=vo.current;if(!c)throw new kn("createSession is required to bootstrap checkout.","validation_error");let p=Rs(c,v),W=Ba(p),qe=Yc(p),Y=qi.get(W);if(!Y){let S={canonicalIdentity:W,promise:Co.current(p,qe,W),consumers:0,settled:!1};Y=S,qi.set(W,S);let ne=()=>{S.settled=!0,Jd(W,S)};S.promise.then(ne,ne)}Y.consumers+=1;let de=!1,U=()=>{de||(de=!0,Y.consumers-=1,Jd(W,Y))};s?.(U);try{let S=await Y.promise;Kr.current=W,v&&(mn(Yn),hr(Oe=>vc(Oe,v)));let{sid:ne,result:me,claimed:b,claim:M,claimRequiresIdentity:x}=S;Dn.current=M,fn(x===!0),ct(me),me.data.session&&oe(me.data.session),ne&&fr(ne);let L=()=>{},re=new Promise(Oe=>{L=Oe});if(b){zt.current+=1;let Oe=zt.current,N=()=>zt.current===Oe;Ut.current=b,zn(!0);let fe=Ye=>{N()&&(Ut.current===b&&(Ut.current=null),Gn(Ye),zn(!1),fn(!1))};b.then(async Ye=>{if(!N())return;let Sn=Kd(_t.current??me,Ye);if(!Sn.data.stripe?.publishableKey||eu(Sn)===eu(me)){fe(Ye);return}await re,N()&&await jn(Sn,N,()=>fe(Ye))},Ye=>{zt.current===Oe&&(Ut.current===b&&(Ut.current=null),zn(!1),fn(!1),Hn(Ye instanceof kn?Ye:new kn(Ye instanceof Error?Ye.message:"Failed to create session","api_error")))})}else zt.current+=1,Ut.current=null,zn(!1),fn(!1);try{let{flopay:Oe,paypalFlopay:N}=await Ni(me,{billingApiUrl:V,locale:l,telemetry:a}).catch(Ye=>{throw Sc(Ye,ne||me.data.session?.id)}),fe=_t.current;b&&fe!==me&&!fe?.data.stripe?.publishableKey?Cn(null,null):Cn(Oe,N)}finally{L()}return yt(!1),S}catch(S){throw Kr.current===W&&(Kr.current=null),S}finally{s||U()}},[Gn,Yn,Cn,l,V,ct,jn,a]),Cr=Bt(rr);Cr.current=rr;let eo=Bt(Hr);eo.current=Hr;let to=pn(async v=>{if(!Xm(v)||_n)return{sessionId:Ge,session:y};Pr(!0);try{let s=await Hr(v);return{sessionId:s.sid,session:s.result.data.session??null}}finally{Pr(!1)}},[Hr,_n,Ge,y]),qt=pn(async v=>{let s=Dn.current;if(!s)return;let c=zt.current,p=await s(v);zt.current===c&&Gn(p)},[Gn]),Jn=pn(async()=>{await Ut.current},[]),Vr=pn(async()=>(await Jn(),{proceed:!0}),[Jn]);ir(()=>{let v=!1,s,c=++Ht.current;sr(),Hn(null),rn(0);let p=()=>{v=!0,Ht.current===c&&(Ht.current+=1,sr())},W=vo.current;if(xr&&W)return Xt($n),yt(!1),Kr.current===xr?p:(oe(Cc(W,Ee)),(async()=>{let de=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),U=$n==="auto"&&!P.current&&!de;U&&(we(null),Qt(null),St("processing"));let S=!1;try{let ne=await eo.current(void 0,x=>{s=x});S=!0;let me=ne.result.data.session??null;ye.current=Ds(ne.result);let b=ol(ne.result),M=xs(ne.sid||me?.id);if(!v&&U&&me&&!b&&!M){P.current=!0,await Hm(xr,ne.sdkGeneratedIdempotencyKey,()=>Cr.current(me,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:ne.result.autoProcessingError,initialAutoProcessingPending:ne.result.autoProcessingPending,autoProcessingAttempted:ne.result.autoProcessingAttempted,sessionId:ne.sid||me.id}));return}!v&&U&&((b||M)&&(P.current=!0),St(null),Qt(null))}catch(ne){if(v)return;let me=yi(ne);if(U&&me==="session_auto_completed"){P.current=!0,St("success"),await Ha(600),v||(Ft(()=>{Wr.current?.({status:"succeeded"})}),St(null),Qt(null));return}if(U&&(St(null),Qt(null)),!S){let M=wc(ne),x=Yd(ne,M?{stage:"provider_load",provider:"stripe",...M}:{stage:"session_request"});(M||!(ne instanceof kn))&&Ft(()=>Mn.current?.(x)),Hn(x);return}let b=ne instanceof kn?ne:new kn(ne instanceof Error?ne.message:"Failed to create session","api_error");Hn(b)}finally{s?.(),s=void 0}})(),()=>{p(),s?.()});yt(!0);async function qe(){let de=!1,U=!1,S=null;try{let ne=new Oi(V,{telemetry:!1}),me=await ne.getUnifiedCheckoutSession(bt,t);if(U=!0,S=me,v)return;ct(me);let b=me.data.session??null;if(oe(b),!b)throw new kn("No session data returned","api_error");let M=b.checkoutMode;if(M==="setup")throw new kn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(b.status==="authorized"){yt(!1),Ft(()=>{Wr.current?.(Jr(b,bt)),Ar.current?.(b.successUrl??"")});return}if(b.status==="complete"){yt(!1),Ft(()=>{Ar.current?.(b.successUrl??"")});return}if(b.status==="expired")throw pi(b);de=!0;let x=Ee??M??"full";Xt(x),zt.current+=1;let L=b.clientSecret||t;Dn.current=b.buyerIdentified===!1&&L?Xo(ne,bt,L,{...b.customer?.id?{userId:b.customer.id}:{}}):void 0,zn(!1),fn(!1);let re=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Oe=ol(me);if(x==="auto"&&!P.current&&!re&&!Oe){P.current=!0;let N=Y(me);try{if(await Cr.current(b,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>N,sessionId:bt||b.id}),v)return;await N,v||yt(!1);return}catch{if(v)return;await N,v||yt(!1);return}}await Y(me),v||yt(!1)}catch(ne){if(v)return;let me=Pc(ne,de);if(de&&Mt({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),me){let{errorCode:L,stage:re,...Oe}=me;rl(V,a,en,L,re,Oe)}if(me?.stage==="provider_load"&&(Ee??S?.data.session?.checkoutMode??"full")==="full"&&hc(S,K,w)){let L=Qd({billingApiUrl:V,locale:l,telemetry:a});z.current=L,Cn(L,null),rn(1),yt(!1);return}let b=me?.stage==="provider_load",M="session_request";b?M="provider_load":U&&(M="post_session");let x=Yd(ne,{stage:M,provider:"stripe",sessionId:bt||void 0});(b||!(ne instanceof kn))&&Ft(()=>Mn.current?.(x)),Hn(x),yt(!1)}}async function Y(de){let{flopay:U,paypalFlopay:S,...ne}=await Ni(de,{billingApiUrl:V,locale:l,telemetry:a});ye.current={publishableKey:ne.publishableKey,paypalPublishableKey:ne.paypalPublishableKey},Cn(U,S),rn(0)}return qe(),p},[Ee,xr,$n,Er,t,K,w]);let On=pn(async()=>{if(!Ke||Vn!==1)return;let v=Ht.current;rn(2);try{let{flopay:s,paypalFlopay:c}=await Ni(Ke,{billingApiUrl:V,locale:l,telemetry:a});if(Ht.current!==v)return;sr(),Cn(s,c),rn(0)}catch(s){if(Ht.current!==v)return;let{errorCode:c,stage:p,...W}=ks(s);rl(V,a,en,c,p,W)}},[sr,Cn,l,Vn,V,a,en,Ke]),Xn=!!(bt&&(y?.clientSecret||t)),Fe=Zt||!Xn,Ln=pn(async()=>{let v=Vt.current;if(!(!v.active||Zt||!Xn||!y)){Nn(!0),we(null);try{await rr(y,{attempt3DS:!0,fallbackToFull:!0,sessionId:bt||y.id})}finally{v.active&&Nn(!1)}}},[bt,Zt,Xn,rr,y]),$t=au(Ke?.data.paypal,wt),Gr=ol(Ke),no=mr(()=>{if(!(!Ke||!y||!Ke.data.stripe?.publishableKey))return{billingApiUrl:V}},[Ke,y,V]),bo=!!(n&&!Me&&Ue==="buttons"&&Z&&$n==="full"),Br=!!(bt&&(zm(y?.vault)||_o(y))),Dr=mr(()=>({session:y,loading:pt,error:Rn,checkoutMode:yn,inlineSessionDraft:ln,applyInlineSessionPatch:bo?to:void 0,inlineSessionPatchProcessing:_n,claimPending:Un,claimRequiresIdentity:qn,claimBuyerIdentity:qt,waitForDataAttachment:Jn}),[y,pt,Rn,yn,ln,bo,to,_n,Un,qn,qt,Jn]),bn=!!n&&Ue==="buttons"&&!Gr&&!Br&&(!Ae||!no),cn=tr?ie(Ur,{status:tr,errorMessage:Bn,authorized:gr}):null;if(pt&&!Br){if(u)return Pn(jr,{children:[u,cn]});if(Ue==="buttons"){let v=ce?.buttonsLayout?.cardButton?.borderRadius??ce?.appearance.variables?.borderRadius??8,s=c=>ie("div",{style:{height:c,borderRadius:v,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Pn(jr,{children:[Pn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[K&&s(xo),w&&(I||We)&&s(xo),w&&s(xo),ie("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),cn]})}return Pn(jr,{children:[Pn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ie("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ie("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),cn]})}return Rn?m?ie(wr.Provider,{value:Dr,children:m(Rn)}):ie(wr.Provider,{value:Dr,children:ie("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Rn.message})}):bn?Pn(jr,{children:[ie(wr.Provider,{value:Dr,children:ie(Qm,{onButtonClick:Ie,paymentMethodLayout:rt,showPayPal:K,showStripe:w,showApplePay:I,showGooglePay:We,theme:Re,buttonsTheme:Nt,buttonsStyles:Dt,cardButtonContent:be,cardBackButtonContent:He,cardTitleContent:ot})}),cn]}):Gr&&y&&$t?Pn(jr,{children:[ie(wr.Provider,{value:Dr,children:Pn("div",{className:Pt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xe&&ie(oa,{icon:!1,children:xe}),vn==="retrying"&&ie("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),vn==="exhausted"&&Pn("div",{role:"alert",children:[ie("div",{children:"PayPal is temporarily unavailable. Please try again."}),ie("button",{type:"button",onClick:lr,children:"Retry PayPal"})]}),vn!=="exhausted"&&ie("div",{"aria-hidden":vn==="retrying"?!0:void 0,style:vn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ie(Vc,{sessionId:bt,nonce:y.clientSecret||void 0,billingApiUrl:V,email:y.customer?.email||ln?.account?.email,billingName:[y.customer?.firstName,y.customer?.lastName].filter(Boolean).join(" ")||[ln?.account?.firstName,ln?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:qt,clientId:$t.clientId,environment:$t.environment,currency:(y.currency??"usd").toUpperCase(),isSubscription:y.mode==="subscription",providerObjectType:$t.providerObjectType,approvalPresentation:$t.approvalPresentation,existingOrderId:$t.existingOrderId,onComplete:R,onErrorChange:we,onDecline:A,onCancel:X,onButtonClick:Ie,runBeforeButtonClick:Vr,onInitializationStateChange:vr,allowAutomaticRetry:T===0,session:y,telemetry:a,telemetryContext:en,onInstrument:Fn,debug:G},`${$}:paypal-init-${T}`)})]})}),cn]}):yn==="confirm"?Pn(jr,{children:[ie(wr.Provider,{value:Dr,children:ie(Ri,{flopay:Ae,paypalFlopay:k,options:no??{billingApiUrl:V},onInstrument:Fn,children:Pn("div",{className:Pt,children:[xe&&ie("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:xe}),Ot?Ot({onConfirm:Ln,isProcessing:Fe}):ie("button",{type:"button",onClick:Ln,disabled:Fe,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Fe?"not-allowed":"pointer",opacity:Fe?.6:1},children:Zt?"Processing...":vt??"Confirm Purchase"})]})},$)}),cn]}):(!Ae||!no)&&!(Br&&yn==="full")?ie(jr,{children:cn}):Pn(jr,{children:[ie(wr.Provider,{value:Dr,children:Pn(Ri,{flopay:Ae,paypalFlopay:k,options:no??{billingApiUrl:V},onInstrument:Fn,children:[Vn===1&&ie("button",{type:"button",onClick:On,children:"Retry payment methods"}),Me?Pn(jr,{children:[xe&&ie("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:xe}),ie(Zm,{sessionId:bt,nonce:y?.clientSecret||void 0,billingApiUrl:V,session:y,submitLabel:Ze,walletPresentation:pe,paymentMethodLayout:rt,moreOptionsLabel:dt,children:Me})]}):ie(nl,{sessionId:bt,nonce:y?.clientSecret||void 0,telemetry:a,email:y?.customer?.email||ln?.account?.email,userId:y?.customer?.id||ln?.account?.userId,firstName:y?.customer?.firstName||ln?.account?.firstName,lastName:y?.customer?.lastName||ln?.account?.lastName,totalAmount:y?Math.round(Om(y).total*100):0,currency:y?.currency?.toLowerCase()??"usd",onComplete:R,onError:C,onDecline:A,onCancel:X,error:xe,onErrorChange:we,showPayPal:K,showStripe:w,walletPresentation:pe,enabledPaymentMethods:Vn?[]:se??Ke?.data.stripe?.enabledPaymentMethods??y?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:We,layout:Ue,paymentMethodLayout:rt,moreOptionsLabel:dt,theme:Re,buttonsTheme:Nt,buttonsStyles:Dt,appearance:_e,cardButtonContent:be,cardBackButtonContent:He,cardTitleContent:ot,onButtonClick:Ie,onBeforeButtonClick:Z,onBuyerIdentityReady:qt,enableAVS:le,...Kt?{cardFieldOrder:Kt}:{},...je===void 0?{}:{showCardBrandIcons:je},...it===void 0?{}:{showCardFieldLabels:it},...Q===void 0?{}:{cardFieldLabels:Q},...Te===void 0?{}:{cardFieldPlaceholders:Te},...Xe===void 0?{}:{cardAutoFocus:Xe},...H?{onCardFieldsReady:H}:{},...ht?{onCardFieldsFailed:ht}:{},...Ce===void 0?{}:{cardFieldsTimeoutMs:Ce},...Ve?{cardPreFormSlot:Ve}:{},avsLayout:ze,country:y?.customer?.country,city:y?.customer?.city,state:y?.customer?.state,onCountryChange:te,onZipChange:D,avsCheck:!!le,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:il(Me,Ue),className:Pt,submitLabel:Ze,directPaypal:$t,isSubscription:y?.mode==="subscription",session:y,dataAttachmentPending:Un,dataAttachmentRequiresIdentity:qn,debug:G})]},$)}),cn]})}function Zm({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,paymentMethodLayout:l,moreOptionsLabel:u,children:m}){return ie(jr,{children:Ui.Children.map(m,R=>{if(!Ui.isValidElement(R))return R;let C=R.props,g={};return C.sessionId||(g.sessionId=e),!C.nonce&&t&&(g.nonce=t),C.billingApiUrl||(g.billingApiUrl=n),C.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),C.walletPresentation===void 0&&(g.walletPresentation=i),C.paymentMethodLayout===void 0&&l!==void 0&&(g.paymentMethodLayout=l),C.moreOptionsLabel===void 0&&u!==void 0&&(g.moreOptionsLabel=u),o?.customer&&(C.email||(g.email=o.customer.email),C.userId||(g.userId=o.customer.id),C.firstName||(g.firstName=o.customer.firstName),C.lastName||(g.lastName=o.customer.lastName)),Object.keys(g).length===0?R:Ui.cloneElement(R,g)})})}function Qm({onButtonClick:e,paymentMethodLayout:t,showPayPal:n,showStripe:o=!0,showApplePay:a,showGooglePay:i,theme:l,buttonsTheme:u,buttonsStyles:m,cardButtonContent:R,cardBackButtonContent:C,cardTitleContent:g}){let[A,X]=Jt(!1),te=mr(()=>iu(l),[l]),D=mr(()=>{let I=te?.buttonsLayout??jm(u);return m?{...I,...m,cardButton:{...I.cardButton,...m.cardButton},cardFormContainer:{...I.cardFormContainer,...m.cardFormContainer},backButton:{...I.backButton,...m.backButton},backButtonIcon:{...I.backButtonIcon,...m.backButtonIcon},submitButton:{...I.submitButton,...m.submitButton},title:{...I.title,...m.title}}:I},[te,u,m]),K=te?.buttonsLayout?.cardButton?.borderRadius??te?.appearance.variables?.borderRadius??8,w=I=>ie("div",{style:{height:I,borderRadius:K,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),pe=R===void 0?{boxSizing:"border-box",height:xo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(A){let I=D.cardInputBorder??"#e5e7eb",We=D.cardInputBackground??"white",G=Vo(C),Ue=Vo(g);return Pn("div",{style:{backgroundColor:D.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...D.cardFormContainer},children:[Pn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Pn("button",{type:"button",onClick:()=>X(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:G?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...D.backButton},children:[ie("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...D.backButtonIcon},children:ie("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ie("path",{d:"M15 18l-6-6 6-6"})})}),ie(Yo,{content:C})]}),Ue?ie("div",{style:{flex:1}}):ie("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...D.title},children:ie(Ia,{content:g})})]}),ie("div",{style:{backgroundColor:We,border:`1px solid ${I}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ie("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Pn("div",{style:{display:"flex"},children:[ie("div",{style:{flex:1,backgroundColor:We,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,borderBottomLeftRadius:8,padding:12,height:45},children:ie("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ie("div",{style:{flex:1,backgroundColor:We,borderTop:"none",borderRight:`1px solid ${I}`,borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,borderBottomRightRadius:8,padding:12,height:45},children:ie("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ie("div",{style:{backgroundColor:We,border:`1px solid ${I}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ie("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ie("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...D.submitButton,opacity:.5}}),ie("style",{children:`
|
|
15
15
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
16
16
|
@keyframes flopay-interim-expand {
|
|
17
17
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
18
18
|
40% { opacity: 1; }
|
|
19
19
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
20
20
|
}
|
|
21
|
-
`})]})}let de={paypal:n&&C(_o),wallets:o&&(a||i)&&C(_o),card:o&&(t?C(_o):ce("button",{type:"button",onClick:()=>{e?.("card"),ee(!0)},style:{width:"100%",...fe,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:j.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,...j.cardButton},onMouseDown:I=>{I.currentTarget.style.transform="scale(0.985)"},onMouseUp:I=>{I.currentTarget.style.transform="scale(1)"},children:ce(Vo,{content:R})}))};return gn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Om.map(I=>ce(Ui.Fragment,{children:de[I]},I)),ce("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as uf,jsx as To,jsxs as pf}from"react/jsx-runtime";var rf=44;function lu(e){return new Promise(t=>setTimeout(t,e))}var cu=15e3;function ul(e,t){return new Mo(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function of(e,t){return new Promise((n,o)=>{let a=()=>o(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(i=>{t.removeEventListener("abort",a),n(i)},i=>{t.removeEventListener("abort",a),o(i)})})}function af(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function sf(e,t){return e instanceof Mo?e:new Mo(e instanceof Error?e.message:t,"api_error")}function lf(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function cf(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function df({sessionId:e,nonce:t,createSession:n,getSession:o,paymentMethodId:a,checkoutMethod:i,clientId:s,products:c,items:d,subscriptions:R,account:g,successUrl:y,cancelUrl:D,couponCodes:ee,tagsData:ae,utmMetadata:j,billingApiUrl:K,locale:C,theme:fe,appearance:de,buttonsTheme:I,buttonsStyles:He,onSuccess:X,onError:Ne,onDecline:at,children:pt,disabled:Ie=!1,type:Nt="button",style:Dt,...ke}){let Ye=Ga(()=>ef(K),[K]),it=Ga(()=>cf({createSession:n,clientId:s,products:c,items:d,subscriptions:R,account:g,successUrl:y,cancelUrl:D,couponCodes:ee,tagsData:ae,utmMetadata:j}),[g,D,s,ee,n,c,d,R,y,ae,j]),[st,Ee]=ua(!1),[te,ue]=ua(null),[$t,ze]=ua(null),[lt,re]=ua(!1),[Me,Ze]=ua(null),[V,Ct]=ua(null),be=uo(!0),Je=uo(null),Ue=uo(null),Qe=uo(!1),bt=uo(V),De=uo(X),Rt=uo(Ne),Ae=uo(at),_e=Ur(w=>Ii(Je,async m=>{try{return await w(m)}catch(Y){throw m.aborted?aa(Y):Y}}),[]);da(()=>{bt.current=V},[V]),da(()=>{De.current=X},[X]),da(()=>{Rt.current=Ne},[Ne]),da(()=>{Ae.current=at},[at]),da(()=>(be.current=!0,()=>{be.current=!1,Je.current?.abort(),Ue.current?.abort()}),[]),da(()=>{if(typeof window>"u")return;let w=m=>{m.key==="Escape"&&Ct(null)};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[]);let St=Ur((w,m=Na)=>{Ae.current?.(mn(m,w,{code:w.code,declineCode:w.declineCode}))},[]),Ot=Ur(async w=>{be.current&&(ze(null),re(w.result.status==="authorized"),ue("success"),await lu(600),be.current&&Bt(()=>De.current?.(w)))},[]),It=Ur(async(w,m)=>{if(!be.current)return;!!m?.emitDecline&&Qm(w)?St(w,m?.method):Rt.current?.(w),ze(w.message),re(!1),ue("error"),await lu(400)},[St]),G=Ur(async(w,m,Y)=>{let W=w.data.session??null;if(!W)throw no(new Mo("No session data returned","api_error"),m);let J=Y?.nonce||W.clientSecret||t;if(Vr(W)){await Ot({result:Kr(W,m),session:W,sessionId:W.id||m,autoCompleted:!1});return}if(W.status==="expired")throw no(pi(W),W.id||m);try{if(w.autoProcessingPending){let ie=w.autoProcessingPending,H=new dl(Ye),Se=await _e(tt=>H.waitForCheckoutSessionCompletion(ie.sessionId,{initialDelayMs:ie.retryAfterMs,nonce:J,statusUrl:ie.statusUrl,signal:tt})),we=ro(Se,W),E=Se.autoProcessingError?.type==="3ds_required"&&!su(Se.autoProcessingError)&&Se.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Se.autoProcessingError.nextActionRedirectUrl}:null;if(E&&m&&J){let tt=Ua(Ye,m,W),Ht=await _e(Ut=>ia(E,{billingApiUrl:Ye,sessionId:m,nonce:J,session:W,signal:Ut,telemetry:!0,...tt.telemetry?{challengeTelemetry:tt.telemetry}:{}})).finally(tt.release);await Ot({result:Ht,session:W,sessionId:W.id||m,autoCompleted:!1});return}if(Se.autoProcessingError)throw Or(Se.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Se.autoProcessingError.checkoutMethod});if(!Vr(we))throw Xo(we);await Ot({result:Kr(we,m),session:we,sessionId:we.id||m,autoCompleted:!1});return}if(w.autoProcessingError){let ie=w.autoProcessingError.nextActionRedirectUrl;if(w.autoProcessingError.type==="3ds_required"&&!su(w.autoProcessingError)&&ie&&m&&J){let H=await _e(tt=>cd({billingApiUrl:Ye,sessionId:m,nonce:J,nextActionRedirectUrl:ie,signal:tt}));if(H.status==="declined")throw Or({type:H.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:H.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:w.autoProcessingError.checkoutMethod});let we=await new dl(Ye).waitForCheckoutSessionCompletion(m,{initialDelayMs:0,nonce:J}),E=ro(we,W);if(!Vr(E))throw Or({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:w.autoProcessingError.checkoutMethod});await Ot({result:Kr(E,m),session:E,sessionId:E.id||m,autoCompleted:!1});return}throw Or(w.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:w.autoProcessingError.checkoutMethod})}if(Y?.fromCreateSession&&w.autoProcessingAttempted===!0)throw Or({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let f=await sa({billingApiUrl:Ye,sessionId:m??W.id,session:W,nonce:J});if(f.type==="next_action_required"&&J){let ie=m??W.id,H=Ua(Ye,ie,W),Se=await _e(we=>ia(f,{billingApiUrl:Ye,sessionId:ie,nonce:J,session:W,signal:we,telemetry:!0,...H.telemetry?{challengeTelemetry:H.telemetry}:{}})).finally(H.release);await Ot({result:Se,session:W,sessionId:W.id||ie,autoCompleted:!1});return}if(f.type!=="success")throw Or({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ot({result:f.result,session:W,sessionId:W.id||m,autoCompleted:!1})}catch(f){let ie=W.id||m,H=no(za(f),ie);if(H.code==="three_ds_aborted")return;if(H.code==="checkout_processing_timeout"){if(!be.current)return;Ze(H.message),Bt(()=>Rt.current?.(H));return}await It(H,{emitDecline:!0,method:H.checkoutMethod??Na}),lf(H,ie)&&ie&&be.current&&Ct({sessionId:ie,errorMessage:H.message,nonce:J||void 0,payPalOrderId:H.orderId})}},[t,Ye,_e,It,Ot]),pe=Ur(async w=>{let m=new AbortController;Ue.current=m;let Y=!1,W=setTimeout(()=>{Y=!0,m.abort()},cu);try{let J=await of((async()=>w({signal:m.signal}))(),m.signal);if(!be.current)return null;if(!af(J))throw ul("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:J.sessionId,nonce:J.nonce}}catch(J){if(!be.current)return null;throw J instanceof Mo&&J.code==="session_fetch_failed"?J:Y?ul(`getSession did not resolve within ${cu/1e3} seconds.`):ul("Could not fetch the one-click session.",J)}finally{clearTimeout(W),Ue.current===m&&(Ue.current=null)}},[]),Te=Ur(async w=>{if(ke.onClick?.(w),w.defaultPrevented||Ie||st||(Ct(null),Ze(null),Qe.current))return;let m=[e,o,it].filter(Boolean).length;if(m>1){let Y=new Mo("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await It(Y),be.current&&(ue(null),ze(null));return}if(m===0){let Y=new Mo("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await It(Y),be.current&&(ue(null),ze(null));return}Qe.current=!0,Ee(!0),ze(null),re(!1),ue("processing");try{let Y=new dl(Ye);if(e){let W=await Y.getUnifiedCheckoutSession(e,t);await G(W,e);return}if(o){let W=await pe(o);if(!W)return;let J=await Y.getUnifiedCheckoutSession(W.sessionId,W.nonce);await G(J,W.sessionId,{nonce:W.nonce});return}td();try{let W=await Y.createAndFetchSession({...it});await G(W,W.data.session?.id??null,{fromCreateSession:!0})}catch(W){if(yi(W)==="session_auto_completed"){await Ot({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw W}}catch(Y){await It(no(sf(Y,"Automatic payment failed. Please try again."),e))}finally{Qe.current=!1,be.current&&(ue(null),ze(null),Ee(!1))}},[ke.onClick,it,Ie,pe,o,st,t,G,Ye,e,It,Ot]),ct=Ur(w=>{let m=bt.current;Ct(null),De.current?.({result:w,session:null,sessionId:m?.sessionId??null,autoCompleted:!1})},[]),dt=Ur(w=>{Rt.current?.(w)},[]),Ke=Ur(w=>{Ae.current?.(w)},[]),yt=Ga(()=>nf(fe),[fe]),mt=Ga(()=>{let w=yt?.buttonsLayout??tf(I);return He?{...w,...He,cardButton:{...w.cardButton,...He.cardButton}}:w},[yt,I,He]),wt=Ga(()=>{let w=yt?.appearance;return de?w?{...w,...de,variables:{...w.variables,...de.variables}}:de:w},[de,yt]),qe=wt?.variables,je=qe?.colorPrimary??"#4A49FF",et=qe?.colorPrimaryHover??Wd(je,.12),$=qe?.borderRadius??"8px";return pf(uf,{children:[To("button",{...ke,type:Nt,onClick:Te,disabled:Ie||st,"aria-busy":st,style:{width:"100%",...pt===void 0?{boxSizing:"border-box",height:rf,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...mt.cardButton,...tl({themeBundle:yt,resolvedPrimaryColor:je,resolvedBorderRadius:$,submitButtonStyle:mt.submitButton,explicitPrimaryColor:qe?.colorPrimary}),fontSize:mt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ie||st?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Ie||st?.6:1,...Dt},onMouseEnter:w=>{ke.onMouseEnter?.(w),!w.defaultPrevented&&!Ie&&!st&&(yt||qe?.colorPrimary)&&(w.currentTarget.style.backgroundColor=et)},onMouseLeave:w=>{ke.onMouseLeave?.(w),!w.defaultPrevented&&(yt||qe?.colorPrimary)&&(w.currentTarget.style.backgroundColor=je)},onMouseDown:w=>{ke.onMouseDown?.(w),w.defaultPrevented||(w.currentTarget.style.transform="scale(0.985)")},onMouseUp:w=>{ke.onMouseUp?.(w),w.defaultPrevented||(w.currentTarget.style.transform="scale(1)")},children:To(Vo,{content:pt})}),Me&&To("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Me}),te&&To(Dr,{status:te,errorMessage:$t,authorized:lt}),V&&To("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:w=>{w.target===w.currentTarget&&Ct(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:To("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:To(cl,{sessionId:V.sessionId,nonce:V.nonce,checkoutMode:"full",billingApiUrl:Ye,locale:C,theme:fe,...wt?{appearance:wt}:{},buttonsTheme:I,buttonsStyles:He,initialErrorMessage:V.errorMessage,initialPayPalOrderId:V.payPalOrderId,cardTitleContent:null,onComplete:ct,onError:dt,onDecline:Ke})})})]})}import{jsx as ff}from"react/jsx-runtime";var yf={StripeSetupMethod:mc,PayPalSetupMethod:yc};function mf(e){return ff(fc,{...e,branches:yf})}import{loadCheckoutRuntime as gf}from"@flopay/js";import{FloPayError as du}from"@flopay/shared";import{useEffect as pl,useRef as yl}from"react";import{jsx as vf}from"react/jsx-runtime";function hf(e){return e instanceof du?e:new du("The checkout runtime failed to load.","network_error",{code:"runtime_load_failed",cause:e})}function Pf(e){let{publishableKey:t,sessionId:n,nonce:o,appearance:a,strings:i,runtimeUrl:s,runtimeTimeoutMs:c}=e,d=e.createSession===void 0?void 0:JSON.stringify(e.createSession),R=yl(null),g=yl(null),y=yl(e);return y.current=e,pl(()=>{let D=!0;return gf({runtimeUrl:s,timeoutMs:c}).then(ee=>{let ae=R.current;!D||!ae||(g.current=ee.mount(ae,{publishableKey:t,sessionId:n,nonce:o,createSession:d===void 0?void 0:JSON.parse(d),appearance:y.current.appearance,strings:y.current.strings,onEvent:j=>y.current.onEvent?.(j)}))},ee=>{D&&y.current.onError?.(hf(ee))}),()=>{D=!1,g.current?.unmount(),g.current=null}},[t,n,o,d,s,c]),pl(()=>{a!==void 0&&g.current?.update({appearance:a})},[a]),pl(()=>{i!==void 0&&g.current?.update({strings:i})},[i]),vf("div",{ref:R,"data-flopay-runtime-checkout":""})}export{bi as DirectPayPalButton,df as FloPayAutomaticPaymentButton,Fu as FloPayCardSetup,xu as FloPayCardSetupError,cl as FloPayCheckout,mf as FloPayPaymentMethodSetup,Ri as FloPayProvider,Pf as FloPayRuntimeCheckout,nl as SplitCardForm,Ps as VaultCardFields,CP as dropThirdPartyOnlyError,np as useCheckout,ao as useFloPay,_s as usePayPalFloPay};
|
|
21
|
+
`})]})}let se={paypal:n&&w(xo),wallets:o&&(a||i)&&w(xo),card:o&&(t?w(xo):ie("button",{type:"button",onClick:()=>{e?.("card"),X(!0)},style:{width:"100%",...pe,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:D.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...D.cardButton},onMouseDown:I=>{I.currentTarget.style.transform="scale(0.985)"},onMouseUp:I=>{I.currentTarget.style.transform="scale(1)"},children:ie(Go,{content:R})}))};return Pn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Lm.map(I=>ie(Ui.Fragment,{children:se[I]},I)),ie("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as pf,jsx as Fo,jsxs as yf}from"react/jsx-runtime";var of=44;function cu(e){return new Promise(t=>setTimeout(t,e))}var du=15e3;function ul(e,t){return new Bo(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function af(e,t){return new Promise((n,o)=>{let a=()=>o(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(i=>{t.removeEventListener("abort",a),n(i)},i=>{t.removeEventListener("abort",a),o(i)})})}function sf(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function lf(e,t){return e instanceof Bo?e:new Bo(e instanceof Error?e.message:t,"api_error")}function cf(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function df(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function uf({sessionId:e,nonce:t,createSession:n,getSession:o,paymentMethodId:a,checkoutMethod:i,clientId:l,products:u,items:m,subscriptions:R,account:C,successUrl:g,cancelUrl:A,couponCodes:X,tagsData:te,utmMetadata:D,billingApiUrl:K,locale:w,theme:pe,appearance:se,buttonsTheme:I,buttonsStyles:We,onSuccess:G,onError:Ue,onDecline:rt,children:dt,disabled:Re=!1,type:Nt="button",style:Dt,...be}){let He=Ga(()=>tf(K),[K]),ot=Ga(()=>df({createSession:n,clientId:l,products:u,items:m,subscriptions:R,account:C,successUrl:g,cancelUrl:A,couponCodes:X,tagsData:te,utmMetadata:D}),[C,A,l,X,n,u,m,R,g,te,D]),[at,Ie]=pa(!1),[Z,le]=pa(null),[Kt,je]=pa(null),[it,Q]=pa(!1),[Te,Xe]=pa(null),[H,ht]=pa(null),Ce=ho(!0),Ve=ho(null),ze=ho(null),Ze=ho(!1),Pt=ho(H),De=ho(G),wt=ho(Ue),Me=ho(rt),Ee=$r(k=>Ii(Ve,async q=>{try{return await k(q)}catch(j){throw q.aborted?ia(j):j}}),[]);ua(()=>{Pt.current=H},[H]),ua(()=>{De.current=G},[G]),ua(()=>{wt.current=Ue},[Ue]),ua(()=>{Me.current=rt},[rt]),ua(()=>(Ce.current=!0,()=>{Ce.current=!1,Ve.current?.abort(),ze.current?.abort()}),[]),ua(()=>{if(typeof window>"u")return;let k=q=>{q.key==="Escape"&&ht(null)};return window.addEventListener("keydown",k),()=>{window.removeEventListener("keydown",k)}},[]);let vt=$r((k,q=Na)=>{Me.current?.(gn(q,k,{code:k.code,declineCode:k.declineCode}))},[]),Ot=$r(async k=>{Ce.current&&(je(null),Q(k.result.status==="authorized"),le("success"),await cu(600),Ce.current&&Ft(()=>De.current?.(k)))},[]),kt=$r(async(k,q)=>{if(!Ce.current)return;!!q?.emitDecline&&ef(k)?vt(k,q?.method):wt.current?.(k),je(k.message),Q(!1),le("error"),await cu(400)},[vt]),V=$r(async(k,q,j)=>{let y=k.data.session??null;if(!y)throw lo(new Bo("No session data returned","api_error"),q);let oe=j?.nonce||y.clientSecret||t;if(Xr(y)){await Ot({result:Jr(y,q),session:y,sessionId:y.id||q,autoCompleted:!1});return}if(y.status==="expired")throw lo(pi(y),y.id||q);try{if(k.autoProcessingPending){let $=k.autoProcessingPending,O=new dl(He),he=await Ee(ut=>O.waitForCheckoutSessionCompletion($.sessionId,{initialDelayMs:$.retryAfterMs,nonce:oe,statusUrl:$.statusUrl,signal:ut})),Se=co(he,y),_=he.autoProcessingError?.type==="3ds_required"&&!lu(he.autoProcessingError)&&he.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:he.autoProcessingError.nextActionRedirectUrl}:null;if(_&&q&&oe){let ut=Ua(He,q,y),Mt=await Ee(At=>sa(_,{billingApiUrl:He,sessionId:q,nonce:oe,session:y,signal:At,telemetry:!0,...ut.telemetry?{challengeTelemetry:ut.telemetry}:{}})).finally(ut.release);await Ot({result:Mt,session:y,sessionId:y.id||q,autoCompleted:!1});return}if(he.autoProcessingError)throw zr(he.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:he.autoProcessingError.checkoutMethod});if(!Xr(Se))throw Zo(Se);await Ot({result:Jr(Se,q),session:Se,sessionId:Se.id||q,autoCompleted:!1});return}if(k.autoProcessingError){let $=k.autoProcessingError.nextActionRedirectUrl;if(k.autoProcessingError.type==="3ds_required"&&!lu(k.autoProcessingError)&&$&&q&&oe){let O=await Ee(ut=>cd({billingApiUrl:He,sessionId:q,nonce:oe,nextActionRedirectUrl:$,signal:ut}));if(O.status==="declined")throw zr({type:O.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:O.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:k.autoProcessingError.checkoutMethod});let Se=await new dl(He).waitForCheckoutSessionCompletion(q,{initialDelayMs:0,nonce:oe}),_=co(Se,y);if(!Xr(_))throw zr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:k.autoProcessingError.checkoutMethod});await Ot({result:Jr(_,q),session:_,sessionId:_.id||q,autoCompleted:!1});return}throw zr(k.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:k.autoProcessingError.checkoutMethod})}if(j?.fromCreateSession&&k.autoProcessingAttempted===!0)throw zr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let h=await la({billingApiUrl:He,sessionId:q??y.id,session:y,nonce:oe});if(h.type==="next_action_required"&&oe){let $=q??y.id,O=Ua(He,$,y),he=await Ee(Se=>sa(h,{billingApiUrl:He,sessionId:$,nonce:oe,session:y,signal:Se,telemetry:!0,...O.telemetry?{challengeTelemetry:O.telemetry}:{}})).finally(O.release);await Ot({result:he,session:y,sessionId:y.id||$,autoCompleted:!1});return}if(h.type!=="success")throw zr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ot({result:h.result,session:y,sessionId:y.id||q,autoCompleted:!1})}catch(h){let $=y.id||q,O=lo(za(h),$);if(O.code==="three_ds_aborted")return;if(O.code==="checkout_processing_timeout"){if(!Ce.current)return;Xe(O.message),Ft(()=>wt.current?.(O));return}await kt(O,{emitDecline:!0,method:O.checkoutMethod??Na}),cf(O,$)&&$&&Ce.current&&ht({sessionId:$,errorMessage:O.message,nonce:oe||void 0,payPalOrderId:O.orderId})}},[t,He,Ee,kt,Ot]),ce=$r(async k=>{let q=new AbortController;ze.current=q;let j=!1,y=setTimeout(()=>{j=!0,q.abort()},du);try{let oe=await af((async()=>k({signal:q.signal}))(),q.signal);if(!Ce.current)return null;if(!sf(oe))throw ul("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:oe.sessionId,nonce:oe.nonce}}catch(oe){if(!Ce.current)return null;throw oe instanceof Bo&&oe.code==="session_fetch_failed"?oe:j?ul(`getSession did not resolve within ${du/1e3} seconds.`):ul("Could not fetch the one-click session.",oe)}finally{clearTimeout(y),ze.current===q&&(ze.current=null)}},[]),_e=$r(async k=>{if(be.onClick?.(k),k.defaultPrevented||Re||at||(ht(null),Xe(null),Ze.current))return;let q=[e,o,ot].filter(Boolean).length;if(q>1){let j=new Bo("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await kt(j),Ce.current&&(le(null),je(null));return}if(q===0){let j=new Bo("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await kt(j),Ce.current&&(le(null),je(null));return}Ze.current=!0,Ie(!0),je(null),Q(!1),le("processing");try{let j=new dl(He);if(e){let y=await j.getUnifiedCheckoutSession(e,t);await V(y,e);return}if(o){let y=await ce(o);if(!y)return;let oe=await j.getUnifiedCheckoutSession(y.sessionId,y.nonce);await V(oe,y.sessionId,{nonce:y.nonce});return}td();try{let y=await j.createAndFetchSession({...ot});await V(y,y.data.session?.id??null,{fromCreateSession:!0})}catch(y){if(yi(y)==="session_auto_completed"){await Ot({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw y}}catch(j){await kt(lo(lf(j,"Automatic payment failed. Please try again."),e))}finally{Ze.current=!1,Ce.current&&(le(null),je(null),Ie(!1))}},[be.onClick,ot,Re,ce,o,at,t,V,He,e,kt,Ot]),st=$r(k=>{let q=Pt.current;ht(null),De.current?.({result:k,session:null,sessionId:q?.sessionId??null,autoCompleted:!1})},[]),lt=$r(k=>{wt.current?.(k)},[]),Ke=$r(k=>{Me.current?.(k)},[]),Ct=Ga(()=>rf(pe),[pe]),_t=Ga(()=>{let k=Ct?.buttonsLayout??nf(I);return We?{...k,...We,cardButton:{...k.cardButton,...We.cardButton}}:k},[Ct,I,We]),ct=Ga(()=>{let k=Ct?.appearance;return se?k?{...k,...se,variables:{...k.variables,...se.variables}}:se:k},[se,Ct]),Ae=ct?.variables,Qe=Ae?.colorPrimary??"#4A49FF",et=Ae?.colorPrimaryHover??Wd(Qe,.12),z=Ae?.borderRadius??"8px";return yf(pf,{children:[Fo("button",{...be,type:Nt,onClick:_e,disabled:Re||at,"aria-busy":at,style:{width:"100%",...dt===void 0?{boxSizing:"border-box",height:of,padding:"0 1rem"}:{padding:"0.9rem 1rem"},..._t.cardButton,...tl({themeBundle:Ct,resolvedPrimaryColor:Qe,resolvedBorderRadius:z,submitButtonStyle:_t.submitButton,explicitPrimaryColor:Ae?.colorPrimary}),fontSize:_t.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Re||at?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Re||at?.6:1,...Dt},onMouseEnter:k=>{be.onMouseEnter?.(k),!k.defaultPrevented&&!Re&&!at&&(Ct||Ae?.colorPrimary)&&(k.currentTarget.style.backgroundColor=et)},onMouseLeave:k=>{be.onMouseLeave?.(k),!k.defaultPrevented&&(Ct||Ae?.colorPrimary)&&(k.currentTarget.style.backgroundColor=Qe)},onMouseDown:k=>{be.onMouseDown?.(k),k.defaultPrevented||(k.currentTarget.style.transform="scale(0.985)")},onMouseUp:k=>{be.onMouseUp?.(k),k.defaultPrevented||(k.currentTarget.style.transform="scale(1)")},children:Fo(Go,{content:dt})}),Te&&Fo("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Te}),Z&&Fo(Ur,{status:Z,errorMessage:Kt,authorized:it}),H&&Fo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:k=>{k.target===k.currentTarget&&ht(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:Fo("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:Fo(cl,{sessionId:H.sessionId,nonce:H.nonce,checkoutMode:"full",billingApiUrl:He,locale:w,theme:pe,...ct?{appearance:ct}:{},buttonsTheme:I,buttonsStyles:We,initialErrorMessage:H.errorMessage,initialPayPalOrderId:H.payPalOrderId,cardTitleContent:null,onComplete:st,onError:lt,onDecline:Ke})})})]})}import{jsx as gf}from"react/jsx-runtime";var mf={StripeSetupMethod:mc,PayPalSetupMethod:yc};function ff(e){return gf(fc,{...e,branches:mf})}import{loadCheckoutRuntime as hf}from"@flopay/js";import{FloPayError as uu}from"@flopay/shared";import{useEffect as pl,useRef as yl}from"react";import{jsx as Cf}from"react/jsx-runtime";function Pf(e){return e instanceof uu?e:new uu("The checkout runtime failed to load.","network_error",{code:"runtime_load_failed",cause:e})}function vf(e){let{publishableKey:t,sessionId:n,nonce:o,appearance:a,strings:i,runtimeUrl:l,runtimeTimeoutMs:u}=e,m=e.createSession===void 0?void 0:JSON.stringify(e.createSession),R=yl(null),C=yl(null),g=yl(e);return g.current=e,pl(()=>{let A=!0;return hf({runtimeUrl:l,timeoutMs:u}).then(X=>{let te=R.current;!A||!te||(C.current=X.mount(te,{publishableKey:t,sessionId:n,nonce:o,createSession:m===void 0?void 0:JSON.parse(m),appearance:g.current.appearance,strings:g.current.strings,onEvent:D=>g.current.onEvent?.(D)}))},X=>{A&&g.current.onError?.(Pf(X))}),()=>{A=!1,C.current?.unmount(),C.current=null}},[t,n,o,m,l,u]),pl(()=>{a!==void 0&&C.current?.update({appearance:a})},[a]),pl(()=>{i!==void 0&&C.current?.update({strings:i})},[i]),Cf("div",{ref:R,"data-flopay-runtime-checkout":""})}export{bi as DirectPayPalButton,uf as FloPayAutomaticPaymentButton,Bu as FloPayCardSetup,Fu as FloPayCardSetupError,cl as FloPayCheckout,ff as FloPayPaymentMethodSetup,Ri as FloPayProvider,vf as FloPayRuntimeCheckout,nl as SplitCardForm,Ps as VaultCardFields,bP as dropThirdPartyOnlyError,rp as useCheckout,po as useFloPay,_s as usePayPalFloPay};
|