@flopay/react 1.14.6 → 1.14.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import{a as bl}from"./chunk-D4CVZRT4.mjs";import{c as Lt,d as Sr,e as Qo,f as Ti,g as cl,h as ad,j as id}from"./chunk-YR36EYW2.mjs";import{a as vl}from"./chunk-HSYSKQPT.mjs";import{a as ta,b as Oa,c as xi,d as Bi,e as Fi,f as ml,g as fl,h as gl,i as hl,j as Pl,k as Cl}from"./chunk-JCJFICSM.mjs";import{a as Ba,b as Mi,c as dl,d as Ai,e as ho,f as ul,g as Ur,h as Fa,i as pl,j as ea,k as Da,l as yl}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as Bf}from"@flopay/shared";import{PaymentAPI as Ss}from"@flopay/js";import{FloPayError as ba,resolveBillingApiUrl as Yp,resolveButtonsLayoutTheme as Jp,resolveTheme as Zp}from"@flopay/shared";import{useCallback as Or,useEffect as Lo,useMemo as Ca,useRef as zo,useState as Uo}from"react";import{Fragment as bo,jsx as tr,jsxs as Sl}from"react/jsx-runtime";function sd(){return Sl(bo,{children:[Sl("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:[tr("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),tr("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",tr("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:tr("path",{d:"M9 18l6-6-6-6"})})]})}function ld(){return tr(bo,{children:"Go back"})}function cd(){return tr(bo,{children:"Secure card checkout"})}function Po(e){return e!==void 0&&(e===""||e===null||e===!1)}function vo({content:e}){return tr(bo,{children:e===void 0?tr(sd,{}):e})}function Co({content:e}){return tr(bo,{children:e===void 0?tr(ld,{}):e})}function na({content:e}){return tr(bo,{children:e===void 0?tr(cd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as dd,canRecoverHostedCardForm as ud,classifyTelemetryFailure as pd,FloPayError as On,isCardHolderNamePlaceholder as yd,isMoneySettledOutcome as md,isMountableVaultBlock as fd,isSetupIntentClientSecret as gd,isValidEmail as hd,resolveSetupFutureUsage as Pd,resolveWalletModeOptions as vd}from"@flopay/shared";import{canRecoverHostedCardForm as to,hasServerSideCardGateway as xl}from"@flopay/shared";import{splitFullName as aa}from"@flopay/shared";import{applyFriendlyMessageOverride as ko}from"@flopay/shared";var Cd="Checkout is temporarily unavailable. Please try again later.";function Di(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof On&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function bd(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function wl(){return new On(Cd,"api_error",{code:"CheckoutInitializationFailed"})}function kl(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(fd(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||ud(o))||t&&e?.data.paypal?.publishableKey)}function Il(e,t){if(t&&(!(e instanceof On)||e.type==="authentication_error"))return Di(e);if(!(e instanceof On&&bd(e))){if(!t&&!(e instanceof On)&&(e instanceof TypeError||e instanceof SyntaxError))return{...pd(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof On)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof On))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function So(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=yd(s.firstName,s.lastName);if(!hd(s.email))return Promise.reject(new On("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[C,A]of Object.entries(s)){if(c&&C.endsWith("Name")||typeof A!="string")continue;let I=A.trim();I&&(y[C]=I)}return a=e.claimCheckoutSession(t,n,{accountData:y}),a.catch(()=>{}),a}}function Rl(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 Oi(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 El(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 Ni(e,t){return t?{...e,...t}:e}function hn(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}:{}}}function qr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function xr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Br(e){return e?.status==="authorized"||e?.status==="complete"}function jr(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 _l(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Na(e){let t=_l(e);return new On(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function La(e){return e instanceof On||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function wo(e){return _l(e)?new On("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new On("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new On(dd,"api_error",{code:"checkout_processing_timeout"})}function ra(e,t){return e==="processing"||md(e,t)}function Tl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Ml(e,t){let n=e;if(gd(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new On(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 On(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var Sd=["apple_pay","google_pay"];function Al(e,t="automatic",n){let o=Pd(n,Sd,"wallet");return{...vd(e,t),paymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var wd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Li(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:wd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function oa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Ap,PaymentAPI as ai,SESSION_CREATE_TELEMETRY as xp}from"@flopay/js";import{buildCheckoutDisplayData as Bp,classifyTelemetryFailure as Oc,FloPayError as Tn,isDetachedSessionEligible as Fp,isMountableVaultBlock as Dp,resolveBillingApiUrl as Op,resolveButtonsLayoutTheme as Np,resolveDirectPaypalConfig as Nc,resolveIdempotencyKey as Tc,resolveCheckoutLogLayout as Lp,resolveTheme as Lc,SDK_VERSION as zc,telemetryStatusClass as zp}from"@flopay/shared";import ys,{useCallback as _n,useEffect as yr,useMemo as rr,useRef as Dt,useState as Gt}from"react";import{createContext as Bl}from"react";var nr=Bl({flopay:null,paypalFlopay:null,billingApiUrl:""}),dr=Bl({session:null,loading:!1,error:null});import{PaymentAPI as Ui}from"@flopay/js";import{buildPayPalCancelEvent as Ld,buildPayPalProcessPaymentRequest as zd,buildPayPalSessionIntentRequest as Ud,buildPayPalTokenizedBody as qd,classifyTelemetryFailure as jd,describePayPalProcessFailure as $d,FloPayError as qi,friendlyPayPalFailureMessage as Wd,generateIdempotencyKey as Hd,isPayPalTeardownMessage as Vd,isValidEmail as ql,mergePayPalPayerIdentity as Kd,needsPayPalPayerDetails as Gd,normalizeGatewayEnvironment as Yd,paypalProviderIdentityRequired as jl,resolvePayPalApprovalIdentity as Jd,resolvePayPalDeclineReason as Zd,SDK_VERSION as Xd,usesPayPalVaultedChannel as Qd}from"@flopay/shared";import{loadScript as eu}from"@paypal/paypal-js";import{useCallback as wr,useContext as tu,useEffect as zt,useMemo as ca,useRef as it,useState as Hr}from"react";import{compactBuyerIdentity as kd,isValidEmail as Id}from"@flopay/shared";import{useCallback as Fl,useEffect as Rd,useRef as Dl,useState as Nl}from"react";import{compactBuyerIdentity as ur}from"@flopay/shared";import{jsx as Ol,jsxs as ia}from"react/jsx-runtime";function Io(){let[e,t]=Nl(null),n=Dl(null),o=Dl(0),a=Fl((s,c)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:c}),new Promise(y=>{n.current=y})),[]),i=Fl(s=>{let c=n.current;n.current=null,t(null),c?.(s)},[]);return Rd(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function Ro({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,c]=Nl(e.email?.trim()??""),y=Id(s.trim());return ia("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:[ia("div",{style:{fontWeight:700},children:["Continue with ",t]}),ia("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Ol("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:C=>c(C.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),ia("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&Ol("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),ia("button",{type:"button",disabled:!y||a,onClick:()=>{n(kd({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as Ed}from"@flopay/shared";import{useContext as za}from"react";function $r(){return za(nr).flopay}function zi(){return za(nr).paypalFlopay??null}function _d(){return za(dr)}function Ll(){return za(nr).billingApiUrl||Ed()}import{FLO_INSTRUMENT_ONCE_NAMES as Td,invokeMerchantCallback as Md,projectFloInstrument as Ad}from"@flopay/shared";import{useCallback as xd,useRef as Ua}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as zl}from"@flopay/shared";function Eo(e,t){let n=Ua(e);n.current=e;let o=Ua(new Set),a=Ua(t),i=Ua(t);return Qo(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),xd(s=>{if(i.current!==t)return;let c=Ad(s);if(c){if(Td.has(c.name)){if(o.current.has(c.name))return;o.current.add(c.name)}Md(()=>n.current?.(c))}},[t])}import{createContext as Bd}from"react";var sa=Bd(null);function qa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Fd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Dd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Od(){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 Nd(e){let t=Od(),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 ja(e){let t=globalThis[Dd];return Nd(t?.(e)??{})}function Pn(e){if(e)return e[Fd]}import{useCallback as Wr,useEffect as Ul,useRef as no}from"react";function la(e,t){let n=no(0),o=no(null),a=no(null),i=no(e),s=no(t?.onHandoffObserved),c=no(t?.defersMissingTerminal),y=no(t?.onMissingTerminalDeferred);Ul(()=>{i.current=e,s.current=t?.onHandoffObserved,c.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let C=Wr((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),A=Wr(f=>{C();let w=n.current+1;return n.current=w,o.current=null,a.current={generation:w,method:f,timer:null,yieldedControl:!1},w},[C]),I=Wr(f=>{let w=a.current;return f!==void 0&&w?.generation!==f?!1:(C(w),a.current=null,(f===void 0||o.current===f)&&(o.current=null),!0)},[C]),O=Wr(f=>{let w=a.current,He=f??w?.generation??n.current;(f===void 0||w?.generation===f)&&(C(w),a.current=null),o.current=He},[C]),se=Wr(f=>o.current===(f??n.current),[]),N=Wr(f=>a.current?.generation===f&&o.current!==f,[]),xe=Wr(()=>{let f=a.current;f&&(C(f),!f.yieldedControl&&(f.yieldedControl=!0,s.current?.(f.method)))},[C]),V=Wr(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(C(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(c.current?.(f.method)){y.current?.(f.method,f.generation);return}a.current=null,o.current=f.generation,i.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},dl))},[C]);return Ul(()=>{let f=()=>{document.visibilityState==="visible"?V():xe()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",xe),window.addEventListener("focus",V),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",xe),window.removeEventListener("focus",V),C()}},[C,xe,V]),{startAttempt:A,finishAttempt:I,invalidateAttempt:O,isAttemptInvalidated:se,isAttemptCurrent:N,generationRef:n}}import{jsx as ro,jsxs as ji}from"react/jsx-runtime";var $a=45,nu=1e3,ru=11e3,ou={width:"100%",minHeight:$a,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"},au={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 iu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:au[e.kind]??null}}function $l(e,t){return e==="watchdog_expired"?"paypal_render_timeout":ul(t)?"paypal_init_timeout":"paypal_init_failure"}function su(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Wl({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:c,currency:y,isSubscription:C,providerObjectType:A,approvalPresentation:I,onTokenizedBody:O,onComplete:se,onErrorChange:N,onDecline:xe,onCancel:V,onTechnicalFailure:f,isProcessing:w=!1,onLoadStateChange:He,onInitializationStateChange:R,allowAutomaticRetry:Ye=!0,onButtonClick:H,runBeforeButtonClick:De,session:Qe,existingOrderId:Ue,telemetry:et,telemetryContext:kt,onInstrument:st,debug:Z=!1}){let At=$r(),pt=Eo(st,e),tt=ca(()=>{if(At)return null;let B=ja({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Xd,enabled:et!==!1});return B.setCheckoutContext(kt??{}),B.beginCheckout(kt??{}),B},[n,At,et,kt?.checkoutMode,kt?.layout]),fe=ca(()=>Pn(At),[At]);zt(()=>()=>{tt&&tt.flush().catch(()=>{}).finally(()=>tt.destroy())},[tt]);let re=ca(()=>({error:B=>{fe?fe.error(B):tt?.error(B),pt({class:"technical_error",errorCode:B.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":B.errorCode,requestCategory:B.requestCategory,provider:B.provider})},log:B=>{fe?fe.log(B):tt?.log(B),pt({class:"lifecycle",name:B.name,provider:B.provider})},performance:B=>{fe?fe.performance(B):tt?.performance(B)},terminal:B=>{fe?fe.terminal(B):tt?.terminal(B)},startTiming:()=>fe?.now()??tt?.now()??0,elapsed:B=>fe?.elapsed(B)??Math.max(0,(tt?.now()??B)-B)}),[pt,fe,tt]),pe=it(null),St=it(0),xt=it(null),Je=it(null),X=it(null),Te=tu(sa),oe=it(null);oe.current||(oe.current=qa());let L=Te??oe.current,qe=it(null),Oe=it(!1),[Ne,x]=Hr(!1),[je,gt]=Hr(!1),[_e,ht]=Hr(0),Pe=it(0),[$e,Ve]=Hr(!1),vn=it(!1),It=it(!1),[Pt,le]=Hr(!1),[P,lt]=Hr(!1),{request:nt,collect:_,finish:Se}=Io(),Bt=it({sessionId:e,required:jl(o,Qe)});Bt.current.sessionId!==e&&(Bt.current={sessionId:e,required:jl(o,Qe)});let ce=Bt.current.required,wt=ca(()=>n.replace(/\/+$/,""),[n]),v=Qe?.gateways?.paypal?.providerObjectType??A,Ce=v??(C?"subscription":"order"),[ve]=Hr(ea),Ze=Qe?.gateways?.paypal?.approvalPresentation??I,rt=Da(ve,Ze==="app_switch"?"app_switch":void 0,Ce),be=Qd(v),we=ca(()=>JSON.stringify([wt,s,y,c??"",Ce,be,rt,e,Ue??""]),[wt,s,y,c,Ue,Ce,be,rt,e]),Ft=it(we),u=Ft.current!==we,Be=it(Z),ge=it(null),[ke,G]=Hr([]),$=wr(B=>{Be.current&&G(vt=>[...vt,`${new Date().toISOString().slice(11,23)} ${B}`])},[]);zt(()=>{Be.current=Z,Z&&$("debug:enabled"),ge.current?.setEnabled(Z)},[$,Z]);let mn=it(O),Wn=it(se),en=it(N),qt=it(xe),yt=it(V),Mn=it(f),kn=it(H),Yt=it(He),Nn=it(R),mt=it(i),mr=it(De),jt=it(Qe),Zn=it(o),An=it(a),xn=it(t),tn=it(null),fn=it(new Map),Ln=it(new Map),Le=it(!1);zt(()=>(Le.current=!0,()=>{Le.current=!1}),[]),zt(()=>{mn.current=O},[O]),zt(()=>{mt.current=i},[i]),zt(()=>{Wn.current=se},[se]),zt(()=>{en.current=N},[N]),zt(()=>{qt.current=xe},[xe]),zt(()=>{yt.current=V},[V]),zt(()=>{Mn.current=f},[f]),zt(()=>{kn.current=H},[H]),zt(()=>{Yt.current=He},[He]),zt(()=>{Nn.current=R},[R]),zt(()=>{mr.current=De},[De]),zt(()=>{jt.current=Qe},[Qe]),zt(()=>{Zn.current=o},[o]),zt(()=>{An.current=a},[a]),zt(()=>{xn.current=t},[t]),zt(()=>{Pe.current=_e},[_e]),zt(()=>{$e&&qe.current?.focus()},[$e,_e]);let ot=wr(()=>{window.setTimeout(()=>{qe.current?.focus()},0)},[]),nn=wr(()=>{x(!1),ht(B=>B+1)},[]),$t=wr(()=>{Ve(!1),(pe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??pe.current)?.focus?.()},[]);zt(()=>{!Ne||!Oe.current||(Oe.current=!1,$t())},[$t,Ne,_e]);let dn=wr((B,vt)=>{let ae=vt?.popupBlocked??Ur(B);ae&&L.markBlocked();let un=Ba("PayPal",ae,ve.inAppBrowser),Rt=Mn.current;if(Rt){let Ot=ae&&ve.inAppBrowser?new qi(un,"api_error",{code:vt?.code??"paypal_popup_blocked"}):B;Rt("paypal",Ot,vt);return}en.current?.(un)},[L,ve.inAppBrowser]),Wt=wr(B=>{let vt=xt.current,ae=Je.current;vt===null||!ae||(re.log({...ae,popupCapability:L.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:B}),re.performance({...ae,popupCapability:L.current(),stage:"overlay_return",durationMs:re.elapsed(vt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:B}),xt.current=null)},[L,re]),rn=wr((B,vt,ae)=>{let un=Je.current;Wt("overlay_timeout"),un&&re.error({...un,popupCapability:L.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),dn(vt,{...ae,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:rt,terminalReason:"overlay_timeout"}),Ve(!0),nn(),ot()},[Wt,ot,dn,L,rt,nn,re]),Cn=wr(()=>{L.markAvailable();let B=Je.current;B&&(X.current=B.attempt,re.log({...B,popupCapability:L.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[L,re]),{finishAttempt:on,generationRef:Ie,invalidateAttempt:In,isAttemptCurrent:an,isAttemptInvalidated:Nr,startAttempt:Bn}=la(rn,{onHandoffObserved:Cn}),Fn=wr(()=>(Ve(!1),Bn("paypal")),[Bn]),fr=wr(B=>{In(B?.generation),B?.showRetry&&Ve(!0),B?.remount&&nn(),B?.focus!==!1&&ot()},[ot,In,nn]),zn=B=>{let vt=tn.current;return vt&&Ln.current.set(B,vt),B};zt(()=>{Ft.current!==we&&(Ft.current=we,vn.current=!1,It.current=!1,x(!1),gt(!1),le(!1),Nn.current?.("loading"))},[we]),zt(()=>{Lt(()=>Yt.current?.(Ne&&!Pt))},[Ne,Pt]);let Ht=Yd(c);zt(()=>{let B={attempt:Ie.current+1,inAppBrowser:ve.inAppBrowser,appFamily:ve.appFamily,popupCapability:L.current(),presentationMode:rt},vt=()=>({...Je.current??B,popupCapability:L.current()}),ae={error:p=>re.error({...p,...vt()}),log:p=>re.log({...p,...vt()}),performance:p=>re.performance({...p,...vt()}),terminal:p=>re.terminal({...p,...vt()}),startTiming:re.startTiming,elapsed:re.elapsed},un=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Rt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if($(`mount clientId=${un} env=${c??"(unset)"}\u2192${Ht??"live"} ccy=${y} sub=${C}`),$(`ua=${Rt.slice(0,80)}${Rt.length>80?"\u2026":""}`),!s){$("FAIL: clientId empty \u2014 gateway misconfigured"),le(!0),ae.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!pe.current){$("FAIL: containerRef not attached");return}St.current=ae.startTiming(),ae.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ot=!1,pn=!1,T=()=>Ot||pn,Nt=be?Ce:void 0,Me,Et=!1,sn=()=>{Me=Hd(),Me||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Et=!0},Rn=null,Jt=!1,or=null,Er=!1,gr=()=>{!or||Er||(Er=!0,or.close().catch(()=>{}))},Dn=!1,Lr=!1,Xn=pe.current,_r=null,Hn=null,ar=[],hr=null,_t=!1,Vn=!1,Kn=null,Un=p=>{if(!p||typeof p.getBoundingClientRect!="function")return"(no rect)";let l=p.getBoundingClientRect();return`${Math.round(l.width)}\xD7${Math.round(l.height)}`},ir=p=>{if(!p)return"(empty)";try{let l=new URL(p,typeof window>"u"?"https://localhost":window.location.href),M=l.pathname.toLowerCase();return M.includes("checkcaptcha")||M.includes("captcha")?`CAPTCHA(${l.host}${M})`:M.includes("risk")||M.includes("challenge")?`RISK(${l.host}${M})`:M.includes("smart/buttons")?`smart-buttons(${l.host})`:`${l.host}${M}`.slice(0,100)}catch{return p.slice(0,80)}},Xe=p=>{let l=p.getAttribute("src"),M=p.getAttribute("srcdoc"),ee=p.getAttribute("name"),Re=p.getAttribute("sandbox"),We=[];return l&&We.push(`src=${ir(l)}`),M&&We.push(`srcdoc[${M.length}ch]`),!l&&!M&&We.push("src=(empty) srcdoc=(empty)"),ee&&We.push(`name=${ee.slice(0,40)}`),Re!==null&&We.push(`sandbox="${Re.slice(0,40)}"`),We.join(" ")},bn=p=>{if(!(p instanceof HTMLIFrameElement))return"";try{let l=p.contentDocument;if(!l)return"cd=null";let M=l.body?.children.length??0,ee=l.body?.innerHTML.length??0,Re=l.head?.innerHTML.length??0;return`cd=same-origin readyState=${l.readyState} body[${M}children,${ee}ch] head[${Re}ch]`}catch(l){return`cd=cross-origin(${l.message.slice(0,30)})`}},ln=[],qn=p=>{if(T())return;let l=p.message??String(p.error??"(no message)");l&&(l.toLowerCase().includes("paypal")||l.toLowerCase().includes("zoid")||l.toLowerCase().includes("postrobot")||l.toLowerCase().includes("storage"))&&($(`window:error ${l.slice(0,140)}`),ln.push(l))},Yr=p=>{if(T())return;let l=p.reason instanceof Error?p.reason.message:String(p.reason??"(no reason)");l&&(l.toLowerCase().includes("paypal")||l.toLowerCase().includes("zoid")||l.toLowerCase().includes("postrobot")||l.toLowerCase().includes("storage"))&&($(`window:rejection ${l.slice(0,140)}`),ln.push(l))},sr={value:0},Tr=()=>{_r?.disconnect(),_r=null,Hn?.disconnect(),Hn=null;for(let p of ar.splice(0))clearTimeout(p);Vn=!1,_t&&typeof window<"u"&&(window.removeEventListener("error",qn),window.removeEventListener("unhandledrejection",Yr)),_t=!1},Gn=()=>{if(!(_t||T()||Dn)){if(_t=!0,ln.length=0,sr.value=0,typeof window<"u"&&(window.addEventListener("error",qn),window.addEventListener("unhandledrejection",Yr)),typeof PerformanceObserver<"u")try{Hn=new PerformanceObserver(p=>{if(!T())for(let l of p.getEntries()){if(!l.name.toLowerCase().includes("paypal"))continue;sr.value+=1;let M=Math.round(l.duration);$(`net ${M}ms ${l.name.slice(0,90)}`)}}),Hn.observe({type:"resource",buffered:!0})}catch{}Kn?.()}},Sn=()=>{hr&&(clearTimeout(hr),hr=null)},Pr=()=>{Tr(),Sn()},En={setEnabled:p=>{p?Gn():Tr()}};ge.current=En,Be.current&&Gn();let b=Vd,S=p=>{if(T()||b(p))return;let l=ko(p)??p;Lt(()=>en.current?.(l))},D=(p,l)=>{if(Ot||Jt)return;Jt=!0,pn=!0,Pr(),gr();let M=iu({kind:p,generationActive:!0,automaticRetryAllowed:Ye,automaticRetryUsed:vn.current});if(M.action==="retry"){vn.current=!0,x(!1),lt(!1),gt(!0),Nn.current?.("retrying"),Rn=setTimeout(()=>{Ot||ht(ee=>ee+1)},nu);return}if(x(!1),lt(!1),gt(!1),le(!0),M.action!=="ignore"){if(Nn.current?.("exhausted"),M.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",l);return}if(M.report){let ee=Mi({code:$l(p,l),message:l},{inAppBrowser:ve.inAppBrowser,handoffObserved:!1});ee.popupBlocked&&L.markBlocked(),ae.error({errorCode:ee.popupBlocked?ee.errorCode:M.report.errorCode,stage:M.report.stage,operationOutcome:M.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:ee.terminalReason})}It.current||(It.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",$l(p,l)))}};le(!1);let Q=async(p,l=tn.current)=>{if(T())return;let M=l?.sessionId??e;if(mn.current){await mn.current(p,{sessionId:M,accountPatch:l?.accountPatch,nonce:l?.nonce});return}let ee=ae.startTiming();ae.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Re=()=>{ae.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ae.performance({stage:"processing",durationMs:ae.elapsed(ee),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let We=zd({body:p,sessionId:M,nonce:l?.nonce??xn.current,accountPatch:l?.accountPatch,session:jt.current,email:Zn.current}),de=await new Ui(wt,{telemetry:!1}).processPayment(We.userId,We.params);if(de.ok){if(pn||Ot&&Le.current)return;Re(),ae.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Lt(()=>Wn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(T())return;let Fe=await de.json().catch(()=>null),at=$d(Fe),dt=at.message;Re(),de.status===400&&(typeof Fe?.declineCode=="string"||!Array.isArray(Fe?.fields))?ae.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):de.status===400||de.status===422?ae.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):ae.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:su(de.status),failureCategory:de.status>=500?"server_error":void 0}),S(dt),Lt(()=>qt.current?.(hn("paypal",dt,{code:at.code,declineCode:at.declineCode})));return}catch(We){if(T())return;Re(),ae.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let me=Wd(We instanceof Error?We.message:void 0);S(me),Lt(()=>qt.current?.(hn("paypal",me)));return}},ct=()=>new qi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Zt=p=>T()?Promise.reject(ct()):Promise.resolve(p),ye=async p=>{if(T())throw ct();Et||sn();let l=tn.current,M=l?.sessionId??e,ee=l?.nonce??xn.current;ae.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Re;try{Re=await new Ui(wt,{telemetry:!1}).createSessionIntent(M,ee??"",Ud(Nt),{idempotencyKey:Me})}catch(We){throw ae.error({...jd(We,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),We}if(T())throw ct();if(Re.provider!=="paypal"||Re.providerObjectType!==Ce)throw new Error(p);return ae.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Re.providerObjectId},q=(p,l)=>{let M=l?.nonce??xn.current;if(!M)return;let ee=l?.sessionId??e,Re=Zd(p);new Ui(wt,{telemetry:!1}).reportSessionIntentDecline(ee,M,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Re}).catch(()=>{})},k=_e;$("loadScript:scheduled (deferred 1 tick)");let E=null,W=setTimeout(()=>{if(Ot){$("loadScript:skipped (cancelled before defer ran)");return}$("loadScript:start");let p=Ht==="live"?"production":Ht,l={};Ce==="subscription"?l={intent:"subscription",vault:!0}:Ce==="order"&&(l={intent:"capture"}),E=eu({clientId:s,currency:y,...l,...p?{environment:p}:{},...p==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let M=!1;E.then(ee=>{if(M=!0,$(`loadScript:resolved inactive=${T()} ns=${!!ee} buttons=${!!ee?.Buttons}`),T())return;if(!ee?.Buttons){$("FAIL: namespace missing Buttons factory"),D("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}ae.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),ae.performance({stage:"provider_ready",durationMs:ae.elapsed(St.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ae.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Re=async(g,Y)=>{if(T()||Pe.current!==k)return;let Ee=g.vaultSetupToken??g.subscriptionID??g.orderID??"",Ae=Ee?Ln.current.get(Ee):fn.current.get(k);if(!(!Ae||!an(Ae.generation))&&on(Ae.generation)){Ln.current.delete(Ee),fn.current.delete(Ae.surfaceKey),Wt("approved");try{if(lt(!0),Lt(()=>en.current?.(null)),!Ee)throw new qi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let z=Jd({accountPatch:Ae.accountPatch,email:Zn.current,billingName:An.current,session:jt.current});if(Gd(z))try{z=Kd(z,await Y?.order?.get?.())}catch{}if((mt.current||ce)&&!ql(z.email)){let J=await _("PayPal",z);if(!J)return;z=J}ql(z.email)&&(Ae.accountPatch=ur({...Ae.accountPatch,...z}),await mt.current?.(z));let cn=qd(Ee,Nt);await Q(cn,Ae)}catch(z){S(z instanceof Error?z.message:"PayPal capture failed.")}finally{T()||lt(!1)}}},We=g=>{let Y=Ue?()=>Zt(Ue):()=>ye(g);return async()=>zn(await Y())},me=ee.Buttons({style:{layout:"horizontal",height:$a,tagline:!1},...rt==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(g,Y)=>{if(T()){await Y.reject();return}sn();let Ee=mr.current,Ae={};if(Ee)try{let J=await Ee("paypal");if(T()){await Y.reject();return}if(!J.proceed){tn.current=null,fn.current.delete(k),await Y.reject();return}Ae={sessionId:J.sessionId,accountPatch:J.accountPatch,nonce:J.nonce}}catch(J){$(`onClick:runBeforeButtonClick rejected msg=${(J instanceof Error?J.message:String(J)).slice(0,120)}`),tn.current=null,fn.current.delete(k),await Y.reject();return}Lt(()=>kn.current?.("paypal"));let z=Fn(),cn={generation:z,surfaceKey:k,...Ae};tn.current=cn,fn.current.set(k,cn),Je.current={...B,attempt:z},await Y.resolve(),ae.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ae.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),xt.current=ae.startTiming()},createOrder:Ce==="order"?We("Failed to create PayPal order."):void 0,createSubscription:Ce==="subscription"?We("Failed to create PayPal subscription."):void 0,createVaultSetupToken:Ce==="setup_token"?async()=>zn(await ye("Failed to create PayPal setup token.")):void 0,onApprove:Re,onCancel:()=>{if(T())return;let g=fn.current.get(k)??tn.current,Y=g&&an(g.generation)?Ld(g.sessionId??e,Nt):null;g&&fn.current.delete(g.surfaceKey),tn.current=null,Wt("cancelled"),ae.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Oe.current=!0,fr({generation:g?.generation,remount:!0,focus:!1}),Y&&Lt(()=>yt.current?.(Y))},onError:g=>{if(T()||Pe.current!==k)return;let Y=g instanceof Error?g.message:"PayPal failed to render.";if($(`onError rendered=${Dn} msg=${Y.slice(0,120)}`),Dn){let Ee=fn.current.get(k)??tn.current;if(Ee&&!an(Ee.generation)||!Ee&&Nr())return;if(b(Y)){on(Ee?.generation);return}let{errorCode:Ae,popupBlocked:z,providerDeclined:cn,terminalReason:J}=Mi(g,{inAppBrowser:ve.inAppBrowser,handoffObserved:Ee!=null&&X.current===Ee.generation});if(z&&L.markBlocked(),Wt(J),cn){ae.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:J}),q(g,Ee),Lt(()=>qt.current?.(hn("paypal",Y))),Ee&&fn.current.delete(Ee.surfaceKey),tn.current=null,on(Ee?.generation);return}ae.error({errorCode:Ae,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:J}),Ee&&fn.current.delete(Ee.surfaceKey),tn.current=null,fr({generation:Ee?.generation,remount:!0,showRetry:!0,focus:!0}),dn(g,{code:"paypal_runtime_failed",popupBlocked:z,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:rt,terminalReason:J});return}D(b(Y)?"teardown":"pre_ready_callback",Y)}}),de=me.isEligible();if($(`isEligible=${de}`),ae.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!de){x(!1),D("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Lr=!0,or=me,Kn=()=>{if(!_t||Vn||T()||Dn)return;Vn=!0,$(`container:dims ${Un(Xn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(_r=new MutationObserver(Y=>{if(!T()){for(let Ee of Y)if(Ee.type==="childList")Ee.addedNodes.forEach(Ae=>{if(!(Ae instanceof Element))return;let z=Ae.tagName.toLowerCase(),cn=(Ae.getAttribute("title")??"").slice(0,40),J=z==="iframe"?` ${Xe(Ae)}`:"";$(`child+ ${z}${cn?` title="${cn}"`:""}${J} dims=${Un(Ae)}`)});else if(Ee.type==="attributes"&&Ee.target instanceof Element){let Ae=Ee.target;if(Ae.tagName.toLowerCase()!=="iframe")continue;let z=Ee.attributeName;(z==="src"||z==="srcdoc")&&$(`attr~ iframe ${z}=${z==="srcdoc"?`[${(Ae.getAttribute("srcdoc")??"").length}ch]`:ir(Ae.getAttribute("src"))} dims=${Un(Ae)}`)}}}),_r.observe(Xn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let g=Y=>{if(T()||Dn)return;let Ee=Xn.querySelectorAll("iframe"),Ae=typeof document<"u"&&"hasStorageAccess"in document;$(`watchdog:${Y} container=${Un(Xn)} children=${Xn.childElementCount} iframes=${Ee.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Ae} paypalNetRequests=${sr.value}`),Ee.forEach((z,cn)=>{let J=(z.getAttribute("title")??"").slice(0,40);$(` iframe[${cn}] ${Un(z)}${J?` title="${J}"`:""} ${Xe(z)}`);let Mr=bn(z);Mr&&$(` ${Mr}`)}),ln.length===0&&$(" (no PayPal/zoid window errors captured)")};ar.push(setTimeout(()=>g("3s"),3e3)),ar.push(setTimeout(()=>g("8s"),8e3)),ar.push(setTimeout(()=>g("15s"),15e3))},Kn(),$("render:start");let at=ae.startTiming();hr=setTimeout(()=>{T()||Dn||($("watchdog:11s retryable render timeout"),D("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},ru);let dt=me.render(Xn);(async()=>{try{if(await dt,$(`render:resolved inactive=${T()}`),Pr(),T()){gr();return}Dn=!0,x(!0),gt(!1),Nn.current?.("ready"),ae.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),ae.performance({stage:"checkout_render",durationMs:ae.elapsed(at),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(g){let Y=g instanceof Error?g.message:"PayPal failed to render.";$(`render:rejected msg=${Y.slice(0,120)}`),Pr(),D(b(Y)?"teardown":"render_rejected",Y)}})()}).catch(ee=>{let Re=ee instanceof Error?ee.message:"PayPal operation failed.";$(`provider:failed msg=${Re.slice(0,120)}`);let We="script_rejected";M&&b(Re)?We="teardown":M&&Lr&&(We="render_rejected"),D(We,Re)})},0);return()=>{Ot=!0,clearTimeout(W),Rn&&clearTimeout(Rn),Pr(),ge.current===En&&(ge.current=null),gr(),xt.current=null,Je.current=null}},[Ye,wt,s,y,c,Ce,rt,be,e,Ue,_e,re,_,ce,$,Wt]);let K=Z?ji("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Pt?"#fef2f2":"#f3f4f6",border:`1px solid ${Pt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Ne} failed=${Pt})`,ke.length===0?`
1
+ import{a as _l}from"./chunk-D4CVZRT4.mjs";import{c as Lt,d as wr,e as na,f as Bi,g as gl,h as pd,j as yd}from"./chunk-YR36EYW2.mjs";import{a as Rl}from"./chunk-HSYSKQPT.mjs";import{a as oa,b as za,c as Oi,d as Ni,e as Li,f as bl,g as Sl,h as wl,i as kl,j as Il,k as El}from"./chunk-JCJFICSM.mjs";import{a as Oa,b as Fi,c as hl,d as Di,e as bo,f as Pl,g as $r,h as Na,i as vl,j as ra,k as La,l as Cl}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as $f}from"@flopay/shared";import{PaymentAPI as Rs}from"@flopay/js";import{FloPayError as ka,resolveBillingApiUrl as ny,resolveButtonsLayoutTheme as ry,resolveTheme as oy}from"@flopay/shared";import{useCallback as Ur,useEffect as qo,useMemo as wa,useRef as jo,useState as $o}from"react";import{Fragment as Io,jsx as ar,jsxs as Tl}from"react/jsx-runtime";function md(){return Tl(Io,{children:[Tl("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:[ar("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),ar("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",ar("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:ar("path",{d:"M9 18l6-6-6-6"})})]})}function fd(){return ar(Io,{children:"Go back"})}function gd(){return ar(Io,{children:"Secure card checkout"})}function So(e){return e!==void 0&&(e===""||e===null||e===!1)}function wo({content:e}){return ar(Io,{children:e===void 0?ar(md,{}):e})}function ko({content:e}){return ar(Io,{children:e===void 0?ar(fd,{}):e})}function aa({content:e}){return ar(Io,{children:e===void 0?ar(gd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as hd,canRecoverHostedCardForm as Pd,classifyTelemetryFailure as vd,FloPayError as zn,isCardHolderNamePlaceholder as Cd,isMoneySettledOutcome as bd,isMountableVaultBlock as Sd,isSetupIntentClientSecret as wd,isValidEmail as kd,resolveSetupFutureUsage as Id,resolveWalletModeOptions as Rd}from"@flopay/shared";import{canRecoverHostedCardForm as ro,hasServerSideCardGateway as zl}from"@flopay/shared";import{splitFullName as la}from"@flopay/shared";import{applyFriendlyMessageOverride as _o}from"@flopay/shared";var Ed="Checkout is temporarily unavailable. Please try again later.";function zi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof zn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function _d(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 Ml(){return new zn(Ed,"api_error",{code:"CheckoutInitializationFailed"})}function Al(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(Sd(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||Pd(o))||t&&e?.data.paypal?.publishableKey)}function xl(e,t){if(t&&(!(e instanceof zn)||e.type==="authentication_error"))return zi(e);if(!(e instanceof zn&&_d(e))){if(!t&&!(e instanceof zn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...vd(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof zn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof zn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Ro(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()},l=Cd(s.firstName,s.lastName);if(!kd(s.email))return Promise.reject(new zn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let u={};for(let[C,_]of Object.entries(s)){if(l&&C.endsWith("Name")||typeof _!="string")continue;let k=_.trim();k&&(u[C]=k)}return a=e.claimCheckoutSession(t,n,{accountData:u}),a.catch(()=>{}),a}}function Bl(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 Ui(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 Fl(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 qi(e,t){return t?{...e,...t}:e}function Sn(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}:{}}}function Wr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Dr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Or(e){return e?.status==="authorized"||e?.status==="complete"}function Vr(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 Dl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ua(e){let t=Dl(e);return new zn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function qa(e){return e instanceof zn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Eo(e){return Dl(e)?new zn("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new zn("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new zn(hd,"api_error",{code:"checkout_processing_timeout"})}function ia(e,t){return e==="processing"||bd(e,t)}function Ol(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Nl(e,t){let n=e;if(wd(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new zn(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 zn(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var Td=["apple_pay","google_pay"];function Ll(e,t="automatic",n){let o=Id(n,Td,"wallet");return{...Rd(e,t),paymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Md=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ji(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:Md.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function sa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Lp,PaymentAPI as di,SESSION_CREATE_TELEMETRY as zp}from"@flopay/js";import{buildCheckoutDisplayData as Up,classifyTelemetryFailure as $c,FloPayError as Bn,isDetachedSessionEligible as qp,isMountableVaultBlock as jp,resolveBillingApiUrl as $p,resolveButtonsLayoutTheme as Wp,resolveDirectPaypalConfig as Wc,resolveIdempotencyKey as Oc,resolveCheckoutLogLayout as Vp,resolveTheme as Vc,SDK_VERSION as Hc,telemetryStatusClass as Hp}from"@flopay/shared";import hs,{useCallback as xn,useEffect as mr,useMemo as sr,useRef as Ot,useState as Zt}from"react";import{createContext as Ul}from"react";var ir=Ul({flopay:null,paypalFlopay:null,billingApiUrl:""}),ur=Ul({session:null,loading:!1,error:null});import{PaymentAPI as Wi}from"@flopay/js";import{buildPayPalCancelEvent as Vd,buildPayPalProcessPaymentRequest as Hd,buildPayPalSessionIntentRequest as Kd,buildPayPalTokenizedBody as Gd,classifyTelemetryFailure as Yd,describePayPalProcessFailure as Jd,FloPayError as Vi,friendlyPayPalFailureMessage as Zd,generateIdempotencyKey as Xd,isPayPalTeardownMessage as Qd,isValidEmail as Gl,mergePayPalPayerIdentity as eu,needsPayPalPayerDetails as tu,normalizeGatewayEnvironment as nu,paypalProviderIdentityRequired as Yl,resolvePayPalApprovalIdentity as ru,resolvePayPalDeclineReason as ou,SDK_VERSION as au,usesPayPalVaultedChannel as iu}from"@flopay/shared";import{loadScript as su}from"@paypal/paypal-js";import{useCallback as kr,useContext as lu,useEffect as zt,useMemo as pa,useRef as tt,useState as Nr}from"react";import{compactBuyerIdentity as Ad,isValidEmail as xd}from"@flopay/shared";import{useCallback as ql,useEffect as Bd,useRef as jl,useState as Wl}from"react";import{compactBuyerIdentity as pr}from"@flopay/shared";import{jsx as $l,jsxs as ca}from"react/jsx-runtime";function To(){let[e,t]=Wl(null),n=jl(null),o=jl(0),a=ql((s,l)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:l}),new Promise(u=>{n.current=u})),[]),i=ql(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Bd(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function Mo({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Wl(e.email?.trim()??""),u=xd(s.trim());return ca("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:[ca("div",{style:{fontWeight:700},children:["Continue with ",t]}),ca("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",$l("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:C=>l(C.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),ca("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&$l("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),ca("button",{type:"button",disabled:!u||a,onClick:()=>{n(Ad({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as Fd}from"@flopay/shared";import{useContext as ja}from"react";function Hr(){return ja(ir).flopay}function $i(){return ja(ir).paypalFlopay??null}function Dd(){return ja(ur)}function Vl(){return ja(ir).billingApiUrl||Fd()}import{FLO_INSTRUMENT_ONCE_NAMES as Od,invokeMerchantCallback as Nd,projectFloInstrument as Ld}from"@flopay/shared";import{useCallback as zd,useRef as $a}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Hl}from"@flopay/shared";function Ao(e,t){let n=$a(e);n.current=e;let o=$a(new Set),a=$a(t),i=$a(t);return na(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),zd(s=>{if(i.current!==t)return;let l=Ld(s);if(l){if(Od.has(l.name)){if(o.current.has(l.name))return;o.current.add(l.name)}Nd(()=>n.current?.(l))}},[t])}import{createContext as Ud}from"react";var da=Ud(null);function Wa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Va="provider.callback.ignored";function Ha(){let e,t=0;return{take(n){return n!==e&&(e=n,t=0),t>=5?!1:(t+=1,!0)}}}var qd=Symbol.for("@flopay/js.telemetry.bridge.v1"),jd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function $d(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Wd(e){let t=$d(),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 Ka(e){let t=globalThis[jd];return Wd(t?.(e)??{})}function pn(e){if(e)return e[qd]}import{useCallback as Kr,useEffect as Kl,useRef as oo}from"react";function ua(e,t){let n=oo(0),o=oo(null),a=oo(null),i=oo(e),s=oo(t?.onHandoffObserved),l=oo(t?.defersMissingTerminal),u=oo(t?.onMissingTerminalDeferred);Kl(()=>{i.current=e,s.current=t?.onHandoffObserved,l.current=t?.defersMissingTerminal,u.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let C=Kr((m=a.current)=>{m?.timer&&(clearTimeout(m.timer),m.timer=null)},[]),_=Kr(m=>{C();let b=n.current+1;return n.current=b,o.current=null,a.current={generation:b,method:m,timer:null,yieldedControl:!1},b},[C]),k=Kr(m=>{let b=a.current;return m!==void 0&&b?.generation!==m?!1:(C(b),a.current=null,(m===void 0||o.current===m)&&(o.current=null),!0)},[C]),O=Kr(m=>{let b=a.current,Ve=m??b?.generation??n.current;(m===void 0||b?.generation===m)&&(C(b),a.current=null),o.current=Ve},[C]),ue=Kr(m=>o.current===(m??n.current),[]),N=Kr(m=>a.current?.generation===m&&o.current!==m,[]),Ae=Kr(()=>{let m=a.current;m&&(C(m),!m.yieldedControl&&(m.yieldedControl=!0,s.current?.(m.method)))},[C]),Z=Kr(()=>{let m=a.current;!m?.yieldedControl||document.visibilityState!=="visible"||(C(m),m.timer=setTimeout(()=>{if(m.timer=null,a.current?.generation===m.generation){if(l.current?.(m.method)){u.current?.(m.method,m.generation);return}a.current=null,o.current=m.generation,i.current(m.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},hl))},[C]);return Kl(()=>{let m=()=>{document.visibilityState==="visible"?Z():Ae()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",Ae),window.addEventListener("focus",Z),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",Ae),window.removeEventListener("focus",Z),C()}},[C,Ae,Z]),{startAttempt:_,finishAttempt:k,invalidateAttempt:O,isAttemptInvalidated:ue,isAttemptCurrent:N,generationRef:n}}import{jsx as ao,jsxs as Hi}from"react/jsx-runtime";var Ga=45,cu=1e3,du=11e3,uu={width:"100%",minHeight:Ga,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"},pu={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 yu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:pu[e.kind]??null}}function Jl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Pl(t)?"paypal_init_timeout":"paypal_init_failure"}function mu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Zl({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:l,currency:u,isSubscription:C,providerObjectType:_,approvalPresentation:k,onTokenizedBody:O,onComplete:ue,onErrorChange:N,onDecline:Ae,onCancel:Z,onTechnicalFailure:m,isProcessing:b=!1,onLoadStateChange:Ve,onInitializationStateChange:I,allowAutomaticRetry:Xe=!0,onButtonClick:Y,runBeforeButtonClick:Fe,session:nt,existingOrderId:ze,telemetry:He,telemetryContext:It,onInstrument:it,debug:te=!1}){let xt=Hr(),ut=Ao(it,e),rt=pa(()=>{if(xt)return null;let $=Ka({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:au,enabled:He!==!1});return $.setCheckoutContext(It??{}),$.beginCheckout(It??{}),$},[n,xt,He,It?.checkoutMode,It?.layout]),ge=pa(()=>pn(xt),[xt]);zt(()=>()=>{rt&&rt.flush().catch(()=>{}).finally(()=>rt.destroy())},[rt]);let se=pa(()=>({error:$=>{ge?ge.error($):rt?.error($),ut({class:"technical_error",errorCode:$.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":$.errorCode,requestCategory:$.requestCategory,provider:$.provider})},log:$=>{ge?ge.log($):rt?.log($),ut({class:"lifecycle",name:$.name,provider:$.provider})},performance:$=>{ge?ge.performance($):rt?.performance($)},terminal:$=>{ge?ge.terminal($):rt?.terminal($)},startTiming:()=>ge?.now()??rt?.now()??0,elapsed:$=>ge?.elapsed($)??Math.max(0,(rt?.now()??$)-$)}),[ut,ge,rt]),fe=tt(null),wt=tt(0),Bt=tt(null),Qe=tt(null),ne=tt(null),Me=lu(da),de=tt(null);de.current||(de.current=Wa());let L=Me??de.current,Ue=tt(null),De=tt(!1),[Oe,M]=Nr(!1),[qe,gt]=Nr(!1),[_e,ht]=Nr(0),ve=tt(0),[je,Ke]=Nr(!1),wn=tt(!1),Et=tt(!1),[Pt,pe]=Nr(!1),[P,st]=Nr(!1),{request:ot,collect:R,finish:Se}=To(),Ft=tt({sessionId:e,required:Yl(o,nt)});Ft.current.sessionId!==e&&(Ft.current={sessionId:e,required:Yl(o,nt)});let ye=Ft.current.required,kt=pa(()=>n.replace(/\/+$/,""),[n]),v=nt?.gateways?.paypal?.providerObjectType??_,we=v??(C?"subscription":"order"),[Ce]=Nr(ra),et=nt?.gateways?.paypal?.approvalPresentation??k,Ge=La(Ce,et==="app_switch"?"app_switch":void 0,we),ke=iu(v),Ie=pa(()=>JSON.stringify([kt,s,u,l??"",we,ke,Ge,e,ze??""]),[kt,s,u,l,ze,we,ke,Ge,e]),Dt=tt(Ie),d=Dt.current!==Ie,xe=tt(te),he=tt(null),[Re,Q]=Nr([]),j=kr($=>{xe.current&&Q(vt=>[...vt,`${new Date().toISOString().slice(11,23)} ${$}`])},[]);zt(()=>{xe.current=te,te&&j("debug:enabled"),he.current?.setEnabled(te)},[j,te]);let mn=tt(O),Yn=tt(ue),on=tt(N),Wt=tt(Ae),pt=tt(Z),Fn=tt(m),En=tt(Y),Xt=tt(Ve),Un=tt(I),yt=tt(i),fr=tt(Fe),Vt=tt(nt),tr=tt(o),Dn=tt(a),On=tt(t),an=tt(null),fn=tt(new Map),qn=tt(new Map),Be=tt(!1),lt=tt(e);lt.current=e;let[kn]=Nr(Ha);zt(()=>(Be.current=!0,()=>{Be.current=!1}),[]),zt(()=>{mn.current=O},[O]),zt(()=>{yt.current=i},[i]),zt(()=>{Yn.current=ue},[ue]),zt(()=>{on.current=N},[N]),zt(()=>{Wt.current=Ae},[Ae]),zt(()=>{pt.current=Z},[Z]),zt(()=>{Fn.current=m},[m]),zt(()=>{En.current=Y},[Y]),zt(()=>{Xt.current=Ve},[Ve]),zt(()=>{Un.current=I},[I]),zt(()=>{fr.current=Fe},[Fe]),zt(()=>{Vt.current=nt},[nt]),zt(()=>{tr.current=o},[o]),zt(()=>{Dn.current=a},[a]),zt(()=>{On.current=t},[t]),zt(()=>{ve.current=_e},[_e]),zt(()=>{je&&Ue.current?.focus()},[je,_e]);let Ut=kr(()=>{window.setTimeout(()=>{Ue.current?.focus()},0)},[]),sn=kr(()=>{M(!1),ht($=>$+1)},[]),ln=kr(()=>{Ke(!1),(fe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??fe.current)?.focus?.()},[]);zt(()=>{!Oe||!De.current||(De.current=!1,ln())},[ln,Oe,_e]);let Ht=kr(($,vt)=>{let B=vt?.popupBlocked??$r($);B&&L.markBlocked();let qt=Oa("PayPal",B,Ce.inAppBrowser),en=Fn.current;if(en){let ee=B&&Ce.inAppBrowser?new Vi(qt,"api_error",{code:vt?.code??"paypal_popup_blocked"}):$;en("paypal",ee,vt);return}on.current?.(qt)},[L,Ce.inAppBrowser]),Kt=kr($=>{let vt=Bt.current,B=Qe.current;vt===null||!B||(se.log({...B,popupCapability:L.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:$}),se.performance({...B,popupCapability:L.current(),stage:"overlay_return",durationMs:se.elapsed(vt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:$}),Bt.current=null)},[L,se]),gn=kr(($,vt,B)=>{let qt=Qe.current;Kt("overlay_timeout"),qt&&se.error({...qt,popupCapability:L.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Ht(vt,{...B,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Ge,terminalReason:"overlay_timeout"}),Ke(!0),sn(),Ut()},[Kt,Ut,Ht,L,Ge,sn,se]),Ee=kr(()=>{L.markAvailable();let $=Qe.current;$&&(ne.current=$.attempt,se.log({...$,popupCapability:L.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[L,se]),{finishAttempt:hn,generationRef:Pn,invalidateAttempt:_r,isAttemptCurrent:_n,isAttemptInvalidated:Tn,startAttempt:gr}=ua(gn,{onHandoffObserved:Ee}),Jn=kr(()=>(Ke(!1),gr("paypal")),[gr]),Qt=kr($=>{_r($?.generation),$?.showRetry&&Ke(!0),$?.remount&&sn(),$?.focus!==!1&&Ut()},[Ut,_r,sn]),X=$=>{let vt=an.current;return vt&&qn.current.set($,vt),$};zt(()=>{Dt.current!==Ie&&(Dt.current=Ie,wn.current=!1,Et.current=!1,M(!1),gt(!1),pe(!1),Un.current?.("loading"))},[Ie]),zt(()=>{Lt(()=>Xt.current?.(Oe&&!Pt))},[Oe,Pt]);let cn=nu(l);zt(()=>{let $={attempt:Pn.current+1,inAppBrowser:Ce.inAppBrowser,appFamily:Ce.appFamily,popupCapability:L.current(),presentationMode:Ge},vt=()=>({...Qe.current??$,popupCapability:L.current()}),B={error:f=>se.error({...f,...vt()}),log:f=>se.log({...f,...vt()}),performance:f=>se.performance({...f,...vt()}),terminal:f=>se.terminal({...f,...vt()}),startTiming:se.startTiming,elapsed:se.elapsed},qt=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",en=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(j(`mount clientId=${qt} env=${l??"(unset)"}\u2192${cn??"live"} ccy=${u} sub=${C}`),j(`ua=${en.slice(0,80)}${en.length>80?"\u2026":""}`),!s){j("FAIL: clientId empty \u2014 gateway misconfigured"),pe(!0),B.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(!fe.current){j("FAIL: containerRef not attached");return}wt.current=B.startTiming(),B.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ee=!1,Nt=!1,U=()=>ee||Nt,_t=f=>{let g=Be.current,h=g?f:"torn_down";g&&j(`onError ignored reason=${h}`),kn.take(lt.current)&&B.log({name:Va,stage:"provider_ready",reason:h,provider:"paypal",paymentMethodCategory:"paypal"})},dn=()=>lt.current===e?"stale_attempt":"session_changed",Mn=ke?we:void 0,Gt,hr=!1,Tr=()=>{Gt=Xd(),Gt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),hr=!0},Pr=null,vr=!1,Mr=null,qr=!1,jr=()=>{!Mr||qr||(qr=!0,Mr.close().catch(()=>{}))},In=!1,Ar=!1,nr=fe.current,Mt=null,$n=null,Wn=[],Zn=null,Vn=!1,Ne=!1,un=null,tn=f=>{if(!f||typeof f.getBoundingClientRect!="function")return"(no rect)";let g=f.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},Hn=f=>{if(!f)return"(empty)";try{let g=new URL(f,typeof window>"u"?"https://localhost":window.location.href),h=g.pathname.toLowerCase();return h.includes("checkcaptcha")||h.includes("captcha")?`CAPTCHA(${g.host}${h})`:h.includes("risk")||h.includes("challenge")?`RISK(${g.host}${h})`:h.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${h}`.slice(0,100)}catch{return f.slice(0,80)}},Zr=f=>{let g=f.getAttribute("src"),h=f.getAttribute("srcdoc"),F=f.getAttribute("name"),J=f.getAttribute("sandbox"),le=[];return g&&le.push(`src=${Hn(g)}`),h&&le.push(`srcdoc[${h.length}ch]`),!g&&!h&&le.push("src=(empty) srcdoc=(empty)"),F&&le.push(`name=${F.slice(0,40)}`),J!==null&&le.push(`sandbox="${J.slice(0,40)}"`),le.join(" ")},xr=f=>{if(!(f instanceof HTMLIFrameElement))return"";try{let g=f.contentDocument;if(!g)return"cd=null";let h=g.body?.children.length??0,F=g.body?.innerHTML.length??0,J=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${h}children,${F}ch] head[${J}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},lr=[],Xn=f=>{if(U())return;let g=f.message??String(f.error??"(no message)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(j(`window:error ${g.slice(0,140)}`),lr.push(g))},vn=f=>{if(U())return;let g=f.reason instanceof Error?f.reason.message:String(f.reason??"(no reason)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(j(`window:rejection ${g.slice(0,140)}`),lr.push(g))},Br={value:0},An=()=>{Mt?.disconnect(),Mt=null,$n?.disconnect(),$n=null;for(let f of Wn.splice(0))clearTimeout(f);Ne=!1,Vn&&typeof window<"u"&&(window.removeEventListener("error",Xn),window.removeEventListener("unhandledrejection",vn)),Vn=!1},S=()=>{if(!(Vn||U()||In)){if(Vn=!0,lr.length=0,Br.value=0,typeof window<"u"&&(window.addEventListener("error",Xn),window.addEventListener("unhandledrejection",vn)),typeof PerformanceObserver<"u")try{$n=new PerformanceObserver(f=>{if(!U())for(let g of f.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;Br.value+=1;let h=Math.round(g.duration);j(`net ${h}ms ${g.name.slice(0,90)}`)}}),$n.observe({type:"resource",buffered:!0})}catch{}un?.()}},w=()=>{Zn&&(clearTimeout(Zn),Zn=null)},q=()=>{An(),w()},re={setEnabled:f=>{f?S():An()}};he.current=re,xe.current&&S();let $e=Qd,jt=f=>{if(U()||$e(f))return;let g=_o(f)??f;Lt(()=>on.current?.(g))},oe=(f,g)=>{if(ee||vr)return;vr=!0,Nt=!0,q(),jr();let h=yu({kind:f,generationActive:!0,automaticRetryAllowed:Xe,automaticRetryUsed:wn.current});if(h.action==="retry"){wn.current=!0,M(!1),st(!1),gt(!0),Un.current?.("retrying"),Pr=setTimeout(()=>{ee||ht(F=>F+1)},cu);return}if(M(!1),st(!1),gt(!1),pe(!0),h.action!=="ignore"){if(Un.current?.("exhausted"),h.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(h.report){let F=Fi({code:Jl(f,g),message:g},{inAppBrowser:Ce.inAppBrowser,handoffObserved:!1});F.popupBlocked&&L.markBlocked(),B.error({errorCode:F.popupBlocked?F.errorCode:h.report.errorCode,stage:h.report.stage,operationOutcome:h.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:F.terminalReason})}Et.current||(Et.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Jl(f,g)))}};pe(!1);let K=async(f,g=an.current)=>{if(U())return;let h=g?.sessionId??e;if(mn.current){await mn.current(f,{sessionId:h,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let F=B.startTiming();B.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let J=()=>{B.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"processing",durationMs:B.elapsed(F),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let le=Hd({body:f,sessionId:h,nonce:g?.nonce??On.current,accountPatch:g?.accountPatch,session:Vt.current,email:tr.current}),D=await new Wi(kt,{telemetry:!1}).processPayment(le.userId,le.params);if(D.ok){if(Nt||ee&&Be.current)return;J(),B.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Lt(()=>Yn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(U())return;let mt=await D.json().catch(()=>null),Nn=Jd(mt),Cn=Nn.message;J(),D.status===400&&(typeof mt?.declineCode=="string"||!Array.isArray(mt?.fields))?B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):D.status===400||D.status===422?B.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):B.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:mu(D.status),failureCategory:D.status>=500?"server_error":void 0}),jt(Cn),Lt(()=>Wt.current?.(Sn("paypal",Cn,{code:Nn.code,declineCode:Nn.declineCode})));return}catch(le){if(U())return;J(),B.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ye=Zd(le instanceof Error?le.message:void 0);jt(Ye),Lt(()=>Wt.current?.(Sn("paypal",Ye)));return}},A=()=>new Vi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),E=f=>U()?Promise.reject(A()):Promise.resolve(f),W=async f=>{if(U())throw A();hr||Tr();let g=an.current,h=g?.sessionId??e,F=g?.nonce??On.current;B.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let J;try{J=await new Wi(kt,{telemetry:!1}).createSessionIntent(h,F??"",Kd(Mn),{idempotencyKey:Gt})}catch(le){throw B.error({...Yd(le,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),le}if(U())throw A();if(J.provider!=="paypal"||J.providerObjectType!==we)throw new Error(f);return B.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),J.providerObjectId},be=(f,g)=>{let h=g?.nonce??On.current;if(!h)return;let F=g?.sessionId??e,J=ou(f);new Wi(kt,{telemetry:!1}).reportSessionIntentDecline(F,h,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:J}).catch(()=>{})},V=_e;j("loadScript:scheduled (deferred 1 tick)");let We=null,Rt=setTimeout(()=>{if(ee){j("loadScript:skipped (cancelled before defer ran)");return}j("loadScript:start");let f=cn==="live"?"production":cn,g={};we==="subscription"?g={intent:"subscription",vault:!0}:we==="order"&&(g={intent:"capture"}),We=su({clientId:s,currency:u,...g,...f?{environment:f}:{},...f==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let h=!1;We.then(F=>{if(h=!0,j(`loadScript:resolved inactive=${U()} ns=${!!F} buttons=${!!F?.Buttons}`),U())return;if(!F?.Buttons){j("FAIL: namespace missing Buttons factory"),oe("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}B.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"provider_ready",durationMs:B.elapsed(wt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),B.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let J=async(G,Le)=>{if(U()||ve.current!==V)return;let z=G.vaultSetupToken??G.subscriptionID??G.orderID??"",ct=z?qn.current.get(z):fn.current.get(V);if(!(!ct||!_n(ct.generation))&&hn(ct.generation)){qn.current.delete(z),fn.current.delete(ct.surfaceKey),Kt("approved");try{if(st(!0),Lt(()=>on.current?.(null)),!z)throw new Vi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let at=ru({accountPatch:ct.accountPatch,email:tr.current,billingName:Dn.current,session:Vt.current});if(tu(at))try{at=eu(at,await Le?.order?.get?.())}catch{}if((yt.current||ye)&&!Gl(at.email)){let Ct=await R("PayPal",at);if(!Ct)return;at=Ct}Gl(at.email)&&(ct.accountPatch=pr({...ct.accountPatch,...at}),await yt.current?.(at));let Ln=Gd(z,Mn);await K(Ln,ct)}catch(at){jt(at instanceof Error?at.message:"PayPal capture failed.")}finally{U()||st(!1)}}},le=G=>{let Le=ze?()=>E(ze):()=>W(G);return async()=>X(await Le())},Ye=F.Buttons({style:{layout:"horizontal",height:Ga,tagline:!1},...Ge==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(G,Le)=>{if(U()){await Le.reject();return}Tr();let z=fr.current,ct={};if(z)try{let Ct=await z("paypal");if(U()){await Le.reject();return}if(!Ct.proceed){an.current=null,fn.current.delete(V),await Le.reject();return}ct={sessionId:Ct.sessionId,accountPatch:Ct.accountPatch,nonce:Ct.nonce}}catch(Ct){j(`onClick:runBeforeButtonClick rejected msg=${(Ct instanceof Error?Ct.message:String(Ct)).slice(0,120)}`),an.current=null,fn.current.delete(V),await Le.reject();return}Lt(()=>En.current?.("paypal"));let at=Jn(),Ln={generation:at,surfaceKey:V,...ct};an.current=Ln,fn.current.set(V,Ln),Qe.current={...$,attempt:at},await Le.resolve(),B.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Bt.current=B.startTiming()},createOrder:we==="order"?le("Failed to create PayPal order."):void 0,createSubscription:we==="subscription"?le("Failed to create PayPal subscription."):void 0,createVaultSetupToken:we==="setup_token"?async()=>X(await W("Failed to create PayPal setup token.")):void 0,onApprove:J,onCancel:()=>{if(U())return;let G=fn.current.get(V)??an.current,Le=G&&_n(G.generation)?Vd(G.sessionId??e,Mn):null;G&&fn.current.delete(G.surfaceKey),an.current=null,Kt("cancelled"),B.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),De.current=!0,Qt({generation:G?.generation,remount:!0,focus:!1}),Le&&Lt(()=>pt.current?.(Le))},onError:G=>{let Le=G instanceof Error?G.message:"PayPal failed to render.";if(U()||ve.current!==V){$e(Le)||_t(dn());return}if(In){let z=fn.current.get(V)??an.current;if(!z||!_n(z.generation)){if($e(Le)){!z&&!Tn()&&hn();return}_t(z||Tn()?"stale_attempt":"no_current_attempt");return}if(j(`onError rendered=${In} msg=${Le.slice(0,120)}`),$e(Le)){hn(z.generation);return}let{errorCode:ct,popupBlocked:at,providerDeclined:Ln,terminalReason:Ct}=Fi(G,{inAppBrowser:Ce.inAppBrowser,handoffObserved:ne.current===z.generation});if(at&&L.markBlocked(),Kt(Ct),Ln){B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ct}),be(G,z),Lt(()=>Wt.current?.(Sn("paypal",Le))),fn.current.delete(z.surfaceKey),an.current=null,hn(z.generation);return}B.error({errorCode:ct,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ct}),fn.current.delete(z.surfaceKey),an.current=null,Qt({generation:z.generation,remount:!0,showRetry:!0,focus:!0}),Ht(G,{code:"paypal_runtime_failed",popupBlocked:at,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Ge,terminalReason:Ct});return}j(`onError rendered=${In} msg=${Le.slice(0,120)}`),oe($e(Le)?"teardown":"pre_ready_callback",Le)}}),D=Ye.isEligible();if(j(`isEligible=${D}`),B.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!D){M(!1),oe("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ar=!0,Mr=Ye,un=()=>{if(!Vn||Ne||U()||In)return;Ne=!0,j(`container:dims ${tn(nr)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Mt=new MutationObserver(Le=>{if(!U()){for(let z of Le)if(z.type==="childList")z.addedNodes.forEach(ct=>{if(!(ct instanceof Element))return;let at=ct.tagName.toLowerCase(),Ln=(ct.getAttribute("title")??"").slice(0,40),Ct=at==="iframe"?` ${Zr(ct)}`:"";j(`child+ ${at}${Ln?` title="${Ln}"`:""}${Ct} dims=${tn(ct)}`)});else if(z.type==="attributes"&&z.target instanceof Element){let ct=z.target;if(ct.tagName.toLowerCase()!=="iframe")continue;let at=z.attributeName;(at==="src"||at==="srcdoc")&&j(`attr~ iframe ${at}=${at==="srcdoc"?`[${(ct.getAttribute("srcdoc")??"").length}ch]`:Hn(ct.getAttribute("src"))} dims=${tn(ct)}`)}}}),Mt.observe(nr,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let G=Le=>{if(U()||In)return;let z=nr.querySelectorAll("iframe"),ct=typeof document<"u"&&"hasStorageAccess"in document;j(`watchdog:${Le} container=${tn(nr)} children=${nr.childElementCount} iframes=${z.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ct} paypalNetRequests=${Br.value}`),z.forEach((at,Ln)=>{let Ct=(at.getAttribute("title")??"").slice(0,40);j(` iframe[${Ln}] ${tn(at)}${Ct?` title="${Ct}"`:""} ${Zr(at)}`);let co=xr(at);co&&j(` ${co}`)}),lr.length===0&&j(" (no PayPal/zoid window errors captured)")};Wn.push(setTimeout(()=>G("3s"),3e3)),Wn.push(setTimeout(()=>G("8s"),8e3)),Wn.push(setTimeout(()=>G("15s"),15e3))},un(),j("render:start");let Nn=B.startTiming();Zn=setTimeout(()=>{U()||In||(j("watchdog:11s retryable render timeout"),oe("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},du);let Cn=Ye.render(nr);(async()=>{try{if(await Cn,j(`render:resolved inactive=${U()}`),q(),U()){jr();return}In=!0,M(!0),gt(!1),Un.current?.("ready"),B.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"checkout_render",durationMs:B.elapsed(Nn),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(G){let Le=G instanceof Error?G.message:"PayPal failed to render.";j(`render:rejected msg=${Le.slice(0,120)}`),q(),oe($e(Le)?"teardown":"render_rejected",Le)}})()}).catch(F=>{let J=F instanceof Error?F.message:"PayPal operation failed.";j(`provider:failed msg=${J.slice(0,120)}`);let le="script_rejected";h&&$e(J)?le="teardown":h&&Ar&&(le="render_rejected"),oe(le,J)})},0);return()=>{ee=!0,clearTimeout(Rt),Pr&&clearTimeout(Pr),q(),he.current===re&&(he.current=null),jr(),Bt.current=null,Qe.current=null}},[Xe,kt,s,u,l,we,Ge,ke,e,ze,_e,se,R,ye,j,Kt]);let jn=te?Hi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Pt?"#fef2f2":"#f3f4f6",border:`1px solid ${Pt?"#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=${Oe} failed=${Pt})`,Re.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${ke.join(`
4
- `)}`]}):null;return Pt&&!u?Z?ro("div",{children:K}):null:ji("div",{children:[K,nt&&ro(Ro,{identity:nt.identity,methodLabel:nt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Se,onCancel:()=>Se(null)}),ji("div",{"aria-hidden":je||nt?!0:void 0,style:je||nt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:$a},children:[!Ne&&!je&&ro("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"}}),ro("div",{ref:pe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:$a,display:"flex",opacity:Ne?1:0},"aria-busy":P||w},_e)]},_e),$e&&ro("button",{ref:qe,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:$t,style:ou,children:"Try PayPal again"})]})}function Wa(e){return ro(Wl,{...e})}function Hl(e){return ro(Wl,{...e})}import{jsx as Vl,jsxs as lu}from"react/jsx-runtime";function _o({children:e,margin:t,icon:n=!0,styleOverride:o}){return lu("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&&Vl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Vl("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 Ha,clearCachedInlineSession as $i,hashCreateParams as Kl,legacyCachedSessionMatchesDraft as Gl,persistCachedInlineIdempotencyKey as Va,persistCachedInlineSession as Ka,readCachedInlineIdempotencyKey as Yl,readCachedInlineSession as Jl,serializeCreateParams as da}from"@flopay/shared";import{resolveBillingApiUrl as cu}from"@flopay/shared";import{useEffect as Vr,useMemo as du,useRef as Zl,useState as Xl}from"react";import{jsx as uu}from"react/jsx-runtime";function Ga({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=Xl(e instanceof Promise?null:e),[c,y]=Xl(t instanceof Promise||!t?null:t),C=Zl(null),A=Zl(null),I=Eo(o);Vr(()=>{I({class:"lifecycle",name:"checkout.mount"})},[I]),Vr(()=>{i&&I({class:"lifecycle",name:"sdk.initialize.ready"})},[I,i]),Vr(()=>{if(i)return Pn(i)?.subscribe?.(I)},[I,i]),Vr(()=>{if(!(!c||c===i))return Pn(c)?.subscribe?.(I)},[I,i,c]),Vr(()=>{if(!i)return;let N=Pn(i);return C.current=N?.beginCheckout()??N?.now()??0,N?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{N?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Vr(()=>{let N=!1;return e instanceof Promise?e.then(xe=>{N||s(xe)},()=>{N||I({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{N=!0}},[I,e]),Vr(()=>{let N=!1;if(!t){y(null);return}return t instanceof Promise?t.then(xe=>{N||y(xe)},()=>{N||I({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{N=!0}},[I,t]),Vr(()=>{if(!i||A.current===i)return;A.current=i;let N=Pn(i);N?.log({name:"checkout.rendered",stage:"checkout_render"}),I({class:"lifecycle",name:"checkout.rendered"}),N?.performance({stage:"checkout_render",durationMs:N.elapsed(C.current??0),durationMode:"machine"})},[I,i]);let O=cu(n?.billingApiUrl),se=du(()=>({flopay:i,paypalFlopay:c,billingApiUrl:O,emitInstrument:I}),[i,c,O,I]);return uu(nr.Provider,{value:se,children:a})}import{markSessionRecentlyCompleted as To,wasSessionRecentlyCompleted as Wi}from"@flopay/shared";async function Ya(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{completeSavedCardNextAction as pu,loadFloPay as Ql,PaymentAPI as Za,runSavedCardChallenge as yu}from"@flopay/js";import{classifyPaymentRejection as mu,FloPayError as Tt,isAuthorizationOnlySession as fu,isMountableVaultBlock as gu,isSetupIntentClientSecret as hu,normalizeCheckoutFailureOutcome as ec}from"@flopay/shared";var pa="card";async function Pu(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 vu(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 Mo(e){return new Tt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Cu(){return new Tt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Vi(e,t){return Object.assign(e,{checkoutMethod:t})}function Fr(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 ua(e,t){try{return await e()}catch(n){throw Fr(n,t)}}function nc(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function rc(e){return yu(e)}async function Ao(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new Za(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,y;try{y=await pu({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:A=>kr({type:A.declineReason??"authorization_declined",gatewayErrorCode:A.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(A){if(a.aborted||A instanceof Error&&A.name==="AbortError")throw A instanceof Tt&&A.code==="three_ds_aborted"?A:Mo(A);if(!(A instanceof Tt)||A.code!=="three_ds_timeout"&&A.code!=="checkout_processing_timeout")throw A;try{y=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:c,timeoutMs:5e3,signal:a})}catch(O){if(a.aborted)throw Mo(O);if(!(O instanceof Tt)||O.code!=="checkout_processing_timeout")throw O}let I=y&&jr(y,t.session);if(!Br(I)&&I?.status!=="expired"){if(t.telemetry){let O=new Za(n);try{O.reportThreeDsAbandoned(o)}finally{O.destroy()}}throw Cu()}}let C=y&&jr(y,t.session);if(!Br(C))throw wo(C);return{...xr(C,o),checkoutMethod:"card"}}function kr(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=ko(a)??a,s=Vi(new Tt(i,"api_error",{code:e?.code??ec(e?.outcome)??ec(e?.type)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Hi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ja(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function oc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Ja(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||Ja(c)))return c;let s=a.gateways;if(s&&typeof s=="object"){let c=s.stripe;if(c&&typeof c=="object"){let y=c,C=[y.stripeClientSecret,y.clientSecret];for(let A of C)if(typeof A=="string"&&A.length>0&&(!t?.requirePaymentIntentClientSecret||Ja(A)))return A}}}}async function bu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=oc(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 Za(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ja(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function xo({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:s}){let c=e.replace(/\/+$/,""),y=t??n.id,C=o??n.clientSecret,A=n.customer?.id??n.accountData?.userId??"",I=n.customer?.email??n.accountData?.email??"",O=n.customer?.firstName??n.accountData?.firstName??"",se=n.customer?.lastName??n.accountData?.lastName??"",N=n.customer?.country??n.accountData?.country??void 0,xe=n.customer?.zip??n.accountData?.zip??void 0,f=await new Za(c,s===!1?{telemetry:!1}:void 0).processPayment(A,{sessionId:y,nonce:C,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:A,email:I,firstName:O,lastName:se,country:N,zip:xe},returnUrl:i??Hi(n)});if(f.ok){let R=typeof f.json=="function"?await f.json().catch(()=>null):null;if(fu(n)||R?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof R?.paymentId=="string"?R.paymentId:n.paymentId,sessionId:typeof R?.sessionId=="string"?R.sessionId:y,authorizationExpiresAt:typeof R?.authorizationExpiresAt=="string"?R.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:oa(a),checkoutMethod:tc(a,n)}};let Ye=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Ye?{paymentIntentId:Ye}:{},paymentMethodId:oa(a),checkoutMethod:tc(a,n)}}}let w;try{w=await f.json()}catch(R){throw new Tt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:R})}if(w?.type==="3ds_required"&&typeof w.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:w.nextActionRedirectUrl};if(w?.type==="paypal_redirect_required"||w?.type==="3ds_required"){let R=oc(w);if(!R)throw new Tt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:w.type,threeDSecureToken:R,paymentMethodId:w.paymentMethodId}}if(w?.gatewayErrorCode==="authentication_required"){let R=await bu({billingApiUrl:c,sessionId:y,nonce:C,responseJson:w});if(R)return R;throw Vi(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let He=new Tt(w?.message??"Payment failed. Please try again.","api_error",{code:w?.code??w?.gatewayErrorCode,declineCode:w?.declineCode??w?.gatewayDeclineReason,statusCode:f.status});throw Object.assign(He,{telemetryOutcome:mu(f.status,w)})}async function Xa(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:y,signal:C}){let A=t?.getRawProvider();if(!A)throw Fr(new Tt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Vi(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let I=hu(e.threeDSecureToken),O=null,se=e.paymentMethodId,N=await ua(()=>Pu(A,e.threeDSecureToken,I),"card");if(N){if(N.error)throw Fr(new Tt(N.error.message??`Failed to retrieve 3DS ${I?"setup":"payment"} status.`,"api_error",{code:N.error.code}),"card");let V=N.intent;!se&&V?.payment_method&&(typeof V.payment_method=="string"?se=V.payment_method:"id"in V.payment_method&&(se=V.payment_method.id??void 0))}let xe=se?await ua(()=>vu(A,e.threeDSecureToken,{payment_method:se,return_url:c??Hi(s)??window.location.href},I),"card"):null;if(xe){if(xe.error)throw Fr(new Tt(xe.error.message??"3DS authentication failed.","api_error",{code:xe.error.code}),"card");O=xe.intent}else{let V=await ua(()=>A.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(V.error)throw Fr(new Tt(V.error.message??"3DS authentication failed.","api_error",{code:V.error.code}),"card");O=(I?V.setupIntent:V.paymentIntent)??null}if(O&&(O.status==="requires_capture"||O.status==="succeeded"||O.status==="processing")){let V=await xo({billingApiUrl:a,sessionId:i,session:s,telemetry:y,tokenizedData:{id:O.id,type:"card",threeDSecureActionResultTokenId:O.id},returnUrl:c});return V.type==="success"?{...V.result,paymentIntentId:V.result.paymentIntentId??O.id,paymentMethodId:V.result.paymentMethodId??se}:V.type==="next_action_required"?Ao(V,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:C}):Xa(V,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:c,telemetry:y,signal:C})}throw Fr(new Tt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let I=(n??t)?.getRawProvider();if(!I)throw Fr(new Tt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:se}=await ua(()=>I.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(se)throw Fr(new Tt(se.message??"PayPal authorization failed.","api_error",{code:se.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:O}=await ua(()=>I.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Hi(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(O)throw Fr(new Tt(O.message??"PayPal authorization failed.","api_error",{code:O.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Tt("Unsupported payment redirect state.","api_error")}function ya(e){if(e instanceof Tt){let o=ko(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=ko(t)??t;return new Tt(n,"api_error")}function Ki(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=gu(e.data.session?.vault)||to(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 tc(e,t){return e?e.isPaypal?"paypal":"card":t&&to(t)?"card":void 0}async function Gi({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([Ql(e,{billingApiUrl:n,locale:o,telemetry:a}),i?Ql(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);if(!s)throw new Tt("The payment provider did not initialize.","authentication_error");let y=null;return i?y=c:t&&(y=s),{flopay:s,paypalFlopay:y}}import{PaymentAPI as Fo,PciVaultCardCapture as Su,toStripeAppearance as wu}from"@flopay/js";import{buildCheckoutProcessMetadata as ku,buildProcessPaymentAvsAccount as Iu,buildWalletSheetWindowMessage as Ru,COUNTRY_OPTIONS as Eu,classifyPaymentRejection as _u,clearStripePayPalReturn as Tu,computeVaultCardThemeColors as Mu,darkenHex as Au,denyPaymentPermissionToNewFrames as xu,FloPayError as Dr,filterStripeMethodsByCountryGate as Bu,getPostalCodeExample as Fu,getPostalCodeLabel as rs,getStateFromPostalCode as Du,getStateLabel as Yi,getStateOptions as Ou,getStripeMethodDisplayName as ga,hasMatchingStripePayPalReturn as Nu,isAuthorizationOnlySession as Ji,isAVSFieldVisible as Kt,isMountableVaultBlock as Lu,isPostalCodeSupported as zu,isSetupIntentClientSecret as Zi,isValidEmail as wn,isValidPostalCode as Uu,isWalletSheetRefusedForWindowSize as qu,needsStripeMethodExplicitConfirm as ac,normalizeBeforeButtonClickError as ic,normalizeCheckoutFailureOutcome as ju,partitionStripeMethods as $u,randomUuidV4 as Wu,readMatchingStripePayPalContinuation as Hu,readStripeRedirectParams as Pc,resolveAVSConfig as Vu,resolveButtonsLayoutTheme as Ku,resolveSetupFutureUsage as vc,resolveTheme as Gu,resolveVaultMountOptions as Xi,STRIPE_PAYPAL_RESUME_KEY as Yu,derivePrimaryTileStyle as Ju,shouldPreferWalletPopup as sc,stripeExpressMethodToOptionKey as Zu,stripeRedirectReturnUrl as Cc,toCssWeight as Xu,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as bc}from"@flopay/shared";import{ExpressCheckoutElement as Sc,PaymentElement as Qu,Elements as oo,useElements as ss,useStripe as ls}from"@stripe/react-stripe-js";import ep,{useCallback as ze,useContext as Oo,useEffect as ft,useLayoutEffect as tp,useMemo as bt,useRef as j,useState as ie}from"react";function Bo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Qa(e,t){if(e)return{error:n=>e.error(Bo(t,n)),log:n=>e.log(Bo(t,n)),performance:n=>e.performance(Bo(t,n)),terminal:n=>e.terminal(Bo(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{darkenHex as _c}from"@flopay/shared";import{Fragment as Do,jsx as d,jsxs as Ge}from"react/jsx-runtime";var Ir="flopay_stripe_resume",lc="flopay_wallet_resume",wc="fw1",np="fw2",kc=300*1e3,rp=900,op="express_checkout_click_timeout",ap=25e3,ip=25e3,sp=1e4,pr={provider:"paypal",paymentMethodCategory:"paypal"},lp="x-flopay-process-result-source",cp="status";async function dp(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 ei={},fa=class{constructor(t){this.reason=t}};function up(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function Qt(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 cs(e){return`${np}:${e}`}function ti(e){return Qt(cs(e))}function ni(e,t){if(typeof window>"u")return null;let n=cs(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>kc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ti(e),null):a}catch{return ti(e),null}}function pp(e){return Qt(cs(e.sessionId),e)}function cc(e,t,n){let o=ni(e,t);return!o||o.clientSecret!==n?!1:ti(e)}function Qi(e,t,n){if(typeof window>"u")return;ni(e,t)?.clientSecret===n&&ti(e)}function yp(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function es(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let o=n?e.status==="succeeded":ra(e.status),a=yp(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function dc(e,t,n){let o=null;try{return await Promise.race([Ml(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},sp),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function mp(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Ic(e){return e instanceof Dr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ri(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new Fo(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw Ic(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var ts=Yu,ma=new Map,fp=250,uc="Just a moment \u2014 we are finalizing your order. Please press pay again.",gp="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function ds(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 oi({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new Fo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function hp(e){return e instanceof Dr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Rc({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=aa(n),s=i.firstName?i:aa(o?.name);return ur({email:wn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Pp({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=Rc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return wn(s.email)?s:i(a,s)}var ha=180,pc=`flopay-card-enter ${ha}ms cubic-bezier(0, 0, 0.2, 1) both`,yc=`flopay-card-exit ${ha}ms cubic-bezier(0.4, 0, 0.2, 1) both`,vp=`flopay-buttons-enter ${ha}ms cubic-bezier(0, 0, 0.2, 1) both`,Cp=`flopay-buttons-exit ${ha}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function bp(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function us(e){return Ju(e)}var Sp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function wp(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var os={width:"100%",minHeight:ta,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function mc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function as(e){return e==="paypal"?"PayPal":ga(e)}function kp(e){let t=Fu(e);return`Enter a valid ${rs(e)}${t?` (e.g. ${t})`:""}`}function Ip(e,t,n){let o=zu(e),a=t.trim(),i=n&&o,s=i&&!a,c=i&&!!a&&!Uu(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:c}}function Rp(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!wn(n);return{required:t,empty:o,malformed:a,value:n}}function Ep(e){return typeof e=="number"?`${e}px`:e}function ps(e){return d(Mp,{...e})}function fc({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:c,onDecline:y,onTechnicalFailure:C,runBeforeButtonClick:A,billingName:I,onBuyerIdentityReady:O,onLoadStateChange:se,placeholderBorderRadius:N,popupCapabilityOwner:xe,externalTelemetryContext:V,presentationMode:f}){let w=$r(),{emitInstrument:He}=Oo(nr),R=ls(),Ye=ss(),H=bt(()=>Qa(Pn(w),V),[V,w]),[De,Qe]=ie("loading");ft(()=>{se?.(De)},[De,se]);let[Ue,et]=ie(!1),kt=j(!1),st=!wn(n?.trim())||!I?.trim(),{request:Z,collect:At,finish:pt}=Io(),tt=j(!1),fe=j(null),re=j(null),[pe,St]=ie(0),[xt,Je]=ie(!1),X=j(!1),Te=j(new Map),{startAttempt:oe,finishAttempt:L,invalidateAttempt:qe,isAttemptInvalidated:Oe,isAttemptCurrent:Ne,generationRef:x}=la((le,P,lt)=>{C?.(le,P,{...lt,popupBlocked:lt?.popupBlocked??Ur(P),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),Je(!0),St(nt=>nt+1)},{onHandoffObserved:()=>{xe.markAvailable(),H?.log({name:"provider.popup.opened",stage:"overlay_open",...pr,attempt:x.current})}});ft(()=>{xt&&re.current?.focus()},[xt,pe]);let je=ze(()=>{St(le=>le+1)},[]),gt=ze((le,P,lt)=>{qe(lt),C?.("paypal",le,{code:P,popupBlocked:Ur(le),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),Je(!0),je()},[qe,C,f,je]),_e=ze(()=>{window.setTimeout(()=>{(fe.current?.querySelector("iframe")??fe.current)?.focus()},0)},[]);ft(()=>{X.current&&(X.current=!1,_e())},[_e,pe]);let ht=ze(()=>{Je(!1),i?.(null),_e()},[_e,i]);ft(()=>{if(!R||tt.current)return;let[le,P,lt]=Pc();if(!le||!P)return;let nt=Hu(P);if(!nt)return;tt.current=!0;let _=!0,Se=ma.get(P);Se||(Se=lt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>R.retrievePaymentIntent(P)),ma.set(P,Se));let Bt={accountPatch:nt.accountPatch,sessionId:nt.sessionId,nonce:nt.nonce},ce=()=>{H?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...pr,requestCategory:"provider_sdk"})};return H?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...pr}),(async()=>{try{et(!0);let m=await Se;if(!_)return;if(m?.error){ma.delete(P),ce(),i?.(m.error.message??"Failed to retrieve PayPal payment status.");return}if(Tu(),ma.delete(P),lt==="failed"){let Ce="PayPal payment was declined. Please try again.";H?.terminal({outcome:"payment_declined",...pr,terminalReason:"provider_declined"}),i?.(Ce),y?.(hn("paypal",Ce));return}let v=m?.paymentIntent;if(v&&v.id!==le){ce(),i?.("Failed to match the returned PayPal payment.");return}if(v&&(v.status==="requires_capture"||v.status==="succeeded")){let Ce=typeof v.payment_method=="string"?v.payment_method:v.payment_method?.id;a({id:Ce??v.id,type:"card",threeDSecureActionResultTokenId:v.id,isPaypal:!0},{...Bt,presentationMode:"redirect"})}else{let Ce="PayPal payment was not completed. Please try again.";H?.terminal({outcome:v?.status==="canceled"?"payment_cancelled":"payment_declined",...pr,terminalReason:v?.status==="canceled"?"cancelled":"provider_declined"}),i?.(Ce),y?.(hn("paypal",Ce))}}catch(m){if(!_)return;ma.delete(P),ce(),i?.(m instanceof Error?m.message:"Failed to complete PayPal payment.")}finally{_&&et(!1)}})(),()=>{_=!1,tt.current=!1}},[R,a,i,y,H]);let Pe=ze(async(le=!1)=>{let P=A?await A("paypal"):{proceed:!0};if(!P.proceed)return Te.current.delete(pe),!1;let lt=oe("paypal");return Te.current.set(pe,{generation:lt,accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}),Je(!1),H?.log({name:`provider.${le?"redirect.started":"handoff.requested"}`,stage:le?"redirect":"overlay_open",...pr,attempt:lt}),c?.("paypal"),!0},[c,H,A,oe,pe]),$e=ze(async le=>{if(s||Ue||!await Pe()){le.reject();return}le.resolve()},[s,Pe,Ue]),Ve=ze(async le=>{if(!R||!Ye)return;let P=Te.current.get(pe);if(P&&!Ne(P.generation)){Te.current.delete(pe);return}if(!P&&Oe()||P&&!L(P.generation))return;P||L();let lt=P??null;if(Te.current.delete(pe),!lt&&A){let wt=await A("paypal");if(!wt.proceed){le.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}lt={accountPatch:wt.accountPatch,sessionId:wt.sessionId,nonce:wt.nonce}}let nt=lt?.sessionId??e,_=lt?.nonce??t,Se=await Pp({event:le,prepared:lt,email:n,billingName:I,methodLabel:"PayPal",collect:At});if(!Se){le.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Bt=Se.email,ce={...lt?.accountPatch,...ur(Se,!0)};try{if(et(!0),i?.(null),!nt||!wn(Bt))throw new Error("Missing sessionId or email for PayPal payment");await O?.(Se);let wt=R.createPaymentMethod,{error:m,paymentMethod:v}=await wt({type:"paypal"});if(m){gt(m,"stripe_paypal_create_payment_method_failed",P?.generation),le.paymentFailed({reason:"fail"});return}let Ce=await ri(o,He,nt,_??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:v?.id??null,intentKind:"payment"});if(Ce.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ve=Ce.clientSecret,Ze={return_url:Cc()};if(v?.id&&(Ze.payment_method=v.id),!Qt(ts,{clientSecret:ve,sessionId:nt,nonce:_,accountPatch:ce})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:be,paymentIntent:we}=await R.confirmPayment({clientSecret:ve,confirmParams:Ze,redirect:"if_required"});if(be){if(Qt(ts),Fa(be)){let u=be.message??"Your payment was declined.";H?.terminal({outcome:"payment_declined",...pr,terminalReason:"provider_declined"}),i?.(u),y?.(hn("paypal",u,{code:ho(be),declineCode:Ai(be)})),await oi({billingApiUrl:o,sessionId:nt,nonce:_,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ho(be)??"provider_declined"}})}else gt(be,"stripe_paypal_confirm_failed",P?.generation);return}Qt(ts);let Ft=typeof we?.payment_method=="string"?we.payment_method:we?.payment_method?.id;a({id:Ft??we?.id,type:"card",threeDSecureActionResultTokenId:we?.id,isPaypal:!0},{accountPatch:ce,paymentMethodCategory:"paypal",presentationMode:f,sessionId:nt,nonce:_});return}catch(wt){gt(wt,"stripe_paypal_failed",P?.generation)}finally{et(!1)}},[R,Ye,e,t,n,I,At,O,o,He,a,i,y,A,gt,L,Ne,Oe,H,f,pe]),vn=ze(async()=>{if(!(kt.current||s||Ue||!R||!Ye)){kt.current=!0,et(!0);try{if(!await Pe(!0))return;await Ve({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{kt.current=!1,et(!1)}}},[Ye,Ve,s,Pe,R,Ue]),It=f==="redirect"?d("button",{type:"button",disabled:s||Ue,onClick:()=>{vn()},style:{width:"100%",minHeight:ta,border:"1px solid #d1d5db",borderRadius:N??8,background:"#ffc439",color:"#111827",cursor:s||Ue?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):d(Sc,{onReady:le=>Qe(xi(le,["paypal"])),onLoadError:()=>{Qe("load_error"),ds(H,"paypal","paypal","provider_error")},onClick:$e,onConfirm:Ve,onCancel:()=>{let le=Te.current.get(pe);Te.current.delete(pe),H?.terminal({outcome:"payment_cancelled",...pr,terminalReason:"cancelled",...le?{attempt:le.generation}:{}}),qe(le?.generation),Je(!1),X.current=!0,je()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:st,emailRequired:st,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},pe),Pt=Ge(Do,{children:[Ge("div",{ref:fe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[xt&&d("button",{ref:re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ht,style:os,children:"Try PayPal again"}),Z&&d(Ro,{identity:Z.identity,methodLabel:Z.methodLabel,onComplete:pt,onCancel:()=>pt(null)},Z.id),d("div",{style:{display:Z?"none":void 0},children:It})]}),Ue&&!Z&&d(Sr,{status:"processing"})]});return f==="redirect"?Pt:d(Bi,{state:De,placeholderTestId:"flopay-paypal-placeholder",borderRadius:N,children:Pt})}function ns(e){return e==="apple_pay"||e==="google_pay"}var _p=200;function Tp({active:e}){return tp(()=>e?xu(document):void 0,[e]),null}function gc({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:c,onButtonClick:y,onDecline:C,onTechnicalFailure:A,runBeforeButtonClick:I,billingName:O,onBuyerIdentityReady:se,onLoadStateChange:N,placeholderBorderRadius:xe,popupCapabilityOwner:V,externalTelemetryContext:f}){let w=$r(),{emitInstrument:He}=Oo(nr),R=ls(),Ye=ss(),H=bt(()=>Qa(Pn(w),f),[f,w]),[De,Qe]=ie("loading");ft(()=>{N?.(De)},[De,N]);let[Ue,et]=ie(!1);ft(()=>{Je.current=Ue},[Ue]);let kt=j(!wn(n?.trim())||!O?.trim()).current,{request:st,collect:Z,finish:At}=Io(),pt=j(null),tt=j(null),[fe,re]=ie(0),[pe,St]=ie(()=>sc()),xt=j(pe),Je=j(!1),[X,Te]=ie(!1),[oe,L]=ie(()=>ni(e,t)?"blocked":"idle"),[qe,Oe]=ie("google_pay"),Ne=j(null),x=j(!0),je=j(!1),gt=j("google_pay"),_e=j("google_pay"),ht=j(null),Pe=j(null),$e=j(new Set),Ve=j(null),vn=j(null);ft(()=>(x.current=!0,()=>{x.current=!1;for(let u of $e.current)window.clearTimeout(u);$e.current.clear()}),[]);let It=j(new Map),{startAttempt:Pt,finishAttempt:le,invalidateAttempt:P,isAttemptInvalidated:lt,isAttemptCurrent:nt,generationRef:_}=la((u,Be,ge)=>{A?.(u,Be,{...ge,popupBlocked:ge?.popupBlocked??Ur(Be),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Oe(u),Te(!0),re(ke=>ke+1)},{onHandoffObserved:u=>{vn.current=_.current,V.markAvailable(),H?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:_.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})},defersMissingTerminal:ns,onMissingTerminalDeferred:(u,Be)=>{let ge=H?.now()??globalThis.performance?.now()??Date.now(),ke=Ve.current,G=ke?.generation===Be?ke.startedAt:ge;H?.performance({stage:"overlay_return",durationMs:Math.max(0,ge-G),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:Be,...ns(u)?{walletType:u}:{}}),H?.flush?.().catch(()=>{})}});ft(()=>{X&&tt.current?.focus()},[X,fe]);let Se=j(0),Bt=j(!1),ce=ze(()=>{if(Se.current>0){Bt.current=!0;return}re(u=>u+1)},[]),wt=ze(()=>{Se.current-=1,!(Se.current>0||!Bt.current)&&(Bt.current=!1,x.current&&re(u=>u+1))},[]),m=ze((u,Be,ge,ke,G=!1)=>{P(ke),A?.(u,Be,{code:ge,popupBlocked:Ur(Be),telemetryReported:G,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Oe(u),Te(!0),ce()},[P,A,ce]),v=ze(u=>{H?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...ns(u)?{walletType:u}:{}}),A?.(u,new Error("The wallet click was not ready within the time the wallet allows."),{code:op,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Oe(u),Te(!0)},[A,H]),Ce=ze(()=>{window.setTimeout(()=>{(pt.current?.querySelector("iframe")??pt.current)?.focus()},0)},[]);ft(()=>{je.current&&(je.current=!1,Ce())},[Ce,fe]);let ve=ze(()=>{Te(!1),c?.(null),Ce()},[Ce,c]),Ze=ze(()=>{Ne.current?.()},[]);ft(()=>{let u=null,Be=()=>{u=null;let ke=sc();ke!==xt.current&&(xt.current=ke,St(ke),!Je.current&&!nt(_.current)&&ce())},ge=()=>{u!==null&&window.clearTimeout(u),u=window.setTimeout(Be,_p)};return window.addEventListener("resize",ge),()=>{window.removeEventListener("resize",ge),u!==null&&window.clearTimeout(u)}},[_,nt,ce]),ft(()=>{let u=ni(e,t);if(!u)return;let Be=!1,ge=!1,ke=async()=>{if(!ge){ge=!0,Be||L("checking");try{let G=await dc(R,u.clientSecret,$e.current);if(Be)return;let $=es(G,u.providerObjectId,Zi(u.clientSecret));if($.kind==="confirmed"){if(!cc(e,t,u.clientSecret))return;Ne.current=null,L("idle"),s({id:$.paymentMethodId,type:"card",threeDSecureActionResultTokenId:$.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if($.kind==="terminal"){Qi(e,t,u.clientSecret),Ne.current=null,L("idle"),Oe(u.paymentMethodType),Te(!0),ce();return}L("blocked")}catch{Be||L("blocked")}finally{ge=!1}}};return Ne.current=ke,L("blocked"),()=>{Be=!0,Ne.current===ke&&(Ne.current=null)}},[t,s,ce,e,R]);let rt=ze(async u=>{let Be=!1,ge=!1,ke=Le=>{Be||ge||(Be=!0,u.paymentFailed({reason:"fail",...Le?{message:Le}:{}}))};if(!R||!Ye){ke();return}let G=It.current.get(fe);if(G&&!nt(G.generation)){It.current.delete(fe),ke();return}if(!G&&lt()){ke();return}if(G&&!le(G.generation)){ke();return}G||(le(),Bt.current=!1);let $=u.expressPaymentType??G?.method??gt.current,mn=G??null,Wn=mc($),en;$==="apple_pay"?en="apple_pay":$==="google_pay"&&(en="google_pay");let qt=G?.generation??_.current,yt=H,Mn=yt?.now()??globalThis.performance?.now()??Date.now(),kn=new AbortController,Yt=!1,Nn=!1,mt=null,mr=e,jt="processing",Zn="other",An="provider_runtime",xn,tn=new Promise((Le,ot)=>{xn=ot}),fn=window.setTimeout(()=>{Yt=!0,kn.abort(),xn(ei)},ap),Ln=async(Le,ot,nn)=>{jt=Le,Zn=ot,An=ot==="intent_create"||ot==="session_claim"?"transport_error":"provider_runtime";let $t=yt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([nn,tn])}finally{let dn=yt?.now()??globalThis.performance?.now()??Date.now();yt?.performance({stage:Le,durationMs:Math.max(0,dn-$t),durationMode:"machine",requestCategory:ot,paymentMethodCategory:"wallet",provider:"stripe",...Yt?{statusClass:"timeout"}:{}})}};try{if(et(!0),c?.(null),!mn&&I){let T=await Ln("processing","other",I(Wn));if(!T.proceed){ke();return}mn={accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}}let Le=mn?.sessionId??e;mr=Le;let ot=mn?.nonce??t,nn=ht.current??mn?.accountPatch,$t=Rc({event:u,fallbackEmail:nn?.email??n,fallbackName:[nn?.firstName,nn?.lastName].join(" ").trim()||O});if(!wn($t.email)){ke("Buyer details are required."),Z(as($),$t).then(T=>{T&&(ht.current=T)});return}ht.current=null;let dn={...mn?.accountPatch,...ur($t,!0)};await Ln("processing","session_claim",Promise.resolve(se?.($t)));let{error:Wt}=await Ln("tokenization","provider_sdk",Ye.submit());if(Wt){ke(),m($,Wt,"stripe_wallet_submit_failed",G?.generation);return}if(!Le)throw new Error("Missing sessionId or email for payment.");let rn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$,paymentMethodId:null,intentKind:a},Cn=JSON.stringify({sessionId:Le,nonce:ot??"",request:rn}),on=Pe.current,Ie=on?.retryIdentity===Cn?on.authorizationAttemptId:Wu();Pe.current={authorizationAttemptId:Ie,retryIdentity:Cn};let In=await Ln("processing","intent_create",ri(o,He,Le,ot??"",{...rn,authorizationAttemptId:Ie},{signal:kn.signal}));if(In.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let an=In.clientSecret,Nr=pp({createdAt:Date.now(),sessionId:Le,...ot?{nonce:ot}:{},clientSecret:an,providerObjectId:In.providerObjectId,paymentMethodType:$,accountPatch:dn});window.clearTimeout(fn),Nn=!0,yt?.performance({stage:"callback",durationMs:Math.max(0,(yt?.now()??globalThis.performance?.now()??Date.now())-Mn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Bn=yt?.now()??globalThis.performance?.now()??Date.now(),Fn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...en?{walletType:en}:{},attempt:qt},fr=!1,zn=null;yt?.log({name:"payment.provider_confirmation.started",...Fn}),mt=window.setTimeout(()=>{mt!==null&&$e.current.delete(mt),fr=!0;let T=yt?.now()??globalThis.performance?.now()??Date.now();yt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Fn,operationOutcome:"watchdog_expired",durationMs:Math.max(0,T-Bn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),yt?.flush?.().catch(()=>{}),zn?.()},ip),$e.current.add(mt);let Ht=(T,Nt)=>{mt!==null&&(window.clearTimeout(mt),$e.current.delete(mt),mt=null);let Me=yt?.now()??globalThis.performance?.now()??Date.now(),Et=Math.max(0,Me-Bn),sn=T;fr&&(T==="resolved"?sn="resolved_late":T==="returned_error"?sn="returned_error_late":sn="rejected_late");let Rn=Nt??(T==="resolved"?"approved":"provider_error");return yt?.log({name:"payment.provider_confirmation.returned",...Fn,operationOutcome:sn,terminalReason:Rn}),yt?.performance({...Fn,durationMs:Et,durationMode:"buyer",operationOutcome:sn,terminalReason:Rn}),{durationMs:Et,operationOutcome:sn,terminalReason:Rn}},K=!1,B=!1,vt=T=>{if(!T||typeof T!="object")return null;let Nt=T;if(Nt.error)return null;let Me=Nt.setupIntent??Nt.paymentIntent,Et=es(Me??null,void 0,!!Nt.setupIntent);return Et.kind==="confirmed"?Et:null},ae=T=>{if(K||G&&_.current!==G.generation)return;let Nt=vt(T);if(!Nt)return;if(Nr&&!cc(Le,ot,an)){K=!0;return}let{intentId:Me,paymentMethodId:Et}=Nt;K=!0,B=!0,Pe.current=null,Ne.current=null,x.current&&(L("idle"),et(!1));let sn=`${wc}:${Le}`;Qt(sn,{createdAt:Date.now(),sessionId:Le,nonce:ot,accountPatch:dn,paymentMethodId:Et,providerIntentId:Me,paymentMethodType:$});try{s({id:Et,type:"card",threeDSecureActionResultTokenId:Me},{accountPatch:dn,paymentMethodCategory:"wallet",sessionId:Le,nonce:ot})}finally{Qt(sn)}},un=!1;zn=async()=>{if(!(un||K||B)){un=!0,x.current&&L("checking");try{let T=await dc(R,an,$e.current);if(K||B)return;let Nt=Zi(an),Me=es(T,In.providerObjectId,Nt);if(Me.kind==="confirmed"){ae(Nt?{setupIntent:T}:{paymentIntent:T});return}if(Me.kind==="terminal"){if(B=!0,Qi(Le,ot,an),Pe.current=null,Ne.current=null,!x.current)return;L("idle"),ke(),m($,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",G?.generation,!0);return}x.current&&!B&&(L("blocked"),et(!1))}catch{x.current&&!B&&(L("blocked"),et(!1))}finally{un=!1}}},Ne.current=zn;let Rt,Ot;try{ge=!0,Se.current+=1;let T;try{T=await(Zi(an)?R.confirmSetup({elements:Ye,clientSecret:an,redirect:"if_required"}):R.confirmPayment({elements:Ye,clientSecret:an,redirect:"if_required"}))}finally{wt()}if(!T||typeof T!="object")throw new fa(up(T));if(Rt=T,!Rt.error&&!vt(Rt))throw new fa("confirmation_result_unconfirmed");Ot=Ht(Rt.error?"returned_error":"resolved",Rt.error&&Fa(Rt.error)?"provider_declined":void 0)}catch(T){let Nt=T instanceof fa?T.reason:void 0,Me=Nt!==void 0,Et=Ht(Me?"returned_error":"rejected");if(yt?.error({...Me?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Nt}:Li(T),...Fn,operationOutcome:Et.operationOutcome,durationMs:Et.durationMs,statusClass:"unknown",terminalReason:Et.terminalReason}),!x.current||K)return;await zn?.();return}let pn=Rt.error;if(pn){if(!x.current||K)return;if(Fa(pn)){B=!0,Qi(Le,ot,an),Pe.current=null,Ne.current=null,L("idle"),It.current.get(fe)===G&&It.current.delete(fe);let T=pn.message??"Your payment was declined.";c?.(T),C?.(hn(Wn,T,{code:ho(pn),declineCode:Ai(pn)})),oi({billingApiUrl:o,sessionId:Le,nonce:ot,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$,providerDeclineReason:ho(pn)??"provider_declined",...In.intentKind==="payment"&&In.providerObjectId.startsWith("pi_")?{providerIntentId:In.providerObjectId}:{}}})}else yt?.error({...Li(pn),...Fn,operationOutcome:Ot.operationOutcome,durationMs:Ot.durationMs,statusClass:"unknown",terminalReason:Ot.terminalReason}),await zn?.();return}if(ae(Rt),!K)throw new Error("Invalid provider returned for APM intent")}catch(Le){if(Le===ei){let ot=yt?.now()??globalThis.performance?.now()??Date.now();yt?.error({errorCode:mp(Zn),stage:jt,requestCategory:Zn,paymentMethodCategory:"wallet",provider:"stripe",...en?{walletType:en}:{},operationOutcome:"watchdog_expired",checkoutSessionId:mr,durationMs:Math.max(0,ot-Mn),statusClass:"timeout",failureCategory:An,attempt:qt,terminalReason:"provider_error"}),yt?.flush?.().catch(()=>{})}ke(),m($,Le,Le===ei?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",G?.generation,Le===ei)}finally{if(window.clearTimeout(fn),mt!==null&&(window.clearTimeout(mt),$e.current.delete(mt)),!Nn){let Le=yt?.now()??globalThis.performance?.now()??Date.now();yt?.performance({stage:"callback",durationMs:Math.max(0,Le-Mn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Yt?{statusClass:"timeout"}:{}})}x.current&&et(!1)}},[R,Ye,e,t,n,O,Z,se,o,He,a,s,c,C,I,m,wt,le,nt,lt,_,H,fe]),be=bt(()=>fl(i),[i]),we=bt(()=>i.map(Zu),[i]),Ft=bt(()=>d(Sc,{onReady:u=>{Qe(xi(u,we))},onLoadError:u=>{Qe("load_error"),ds(H,"stripe","wallet","provider_error")},onClick:async u=>{let Be=H?.now()??globalThis.performance?.now()??Date.now();gt.current=u.expressPaymentType,_e.current=mc(u.expressPaymentType);let ge=!0,ke=window.setTimeout(()=>{ge=!1,u.reject(),v(u.expressPaymentType)},rp),G=I?await I(_e.current,{abandoned:()=>!ge}):{proceed:!0};if(window.clearTimeout(ke),!ge)return;if(!G.proceed){It.current.delete(fe),u.reject();return}let $=Pt(u.expressPaymentType);Bt.current=!1,Ve.current={generation:$,startedAt:Be},It.current.set(fe,{generation:$,method:u.expressPaymentType,accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}),Te(!1),H?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:$,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),y?.(_e.current),u.resolve()},onConfirm:rt,onCancel:()=>{let u=It.current.get(fe);It.current.delete(fe);let Be=Ve.current,ge=H?.now()??globalThis.performance?.now()??Date.now();if(u&&Be?.generation===u.generation&&qu({method:u.method,elapsedMs:ge-Be.startedAt,handoffObserved:vn.current===u.generation})){H?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:u.generation,walletType:"google_pay"}),Pe.current=null,m(u.method,new Error("The browser window is too small for the Google Pay sheet."),bc,u.generation,!0);return}H?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),P(u?.generation),Pe.current=null,Te(!1),je.current=!0,ce()},options:{...gl,paymentMethods:be,emailRequired:kt,billingAddressRequired:kt}},fe),[we,be,rt,P,y,kt,m,v,ce,I,Pt,fe,H]);return Ge(Do,{children:[d(Bi,{state:De,placeholderTestId:"flopay-wallet-placeholder",borderRadius:xe,children:Ge("div",{ref:pt,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[X&&Ge("button",{ref:tt,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ve,style:os,children:["Try ",as(qe)," again"]}),oe!=="idle"&&Ge("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:Ze,disabled:oe==="checking",style:os,children:oe==="checking"?"Checking payment status\u2026":"Check payment status"})]}),st&&d(Ro,{identity:st.identity,methodLabel:st.methodLabel,onComplete:At,onCancel:()=>At(null)},st.id),Ge("div",{style:{display:st||oe!=="idle"?"none":void 0},children:[d(Tp,{active:pe}),Ft]})]})}),Ue&&d(Sr,{status:"processing"})]})}function Ec(e,t,n){let o=vc(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function is({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:c,onErrorChange:y,onDecline:C,onCancel:A,runBeforeButtonClick:I,onButtonClick:O,isProcessing:se,submitButtonColor:N,submitButtonBorderRadius:xe,submitButtonStyle:V,errorText:f}){let w=$r(),{emitInstrument:He}=Oo(nr),R=ls(),Ye=ss(),[H,De]=ie(!1),Qe=j(!1),[Ue,et]=ie(!1),[kt,st]=ie("loading"),[Z,At]=ie(""),pt=!wn(o?.trim()),tt=!pt||wn(Z.trim()),fe=ze(async()=>{if(!R||!Ye||se||Qe.current||!Ue)return;Qe.current=!0,De(!0);let re=I?await I("card"):{proceed:!0};if(!re.proceed){Qe.current=!1,De(!1);return}O?.("card");let pe=re.sessionId??t,St=re.nonce??n,xt=aa(a?.trim()),Je=ur({email:re.accountPatch?.email?.trim()||o?.trim()||Z.trim(),firstName:re.accountPatch?.firstName?.trim()||xt.firstName,lastName:re.accountPatch?.lastName?.trim()||xt.lastName}),X=Je.email,Te=ur({...re.accountPatch,...Je});try{if(y?.(null),!wn(X))throw new Error("A valid email address is required for payment.");await i?.(Je);let oe=await Ye.submit();if(oe.error){y?.(oe.error.message??"Payment failed.");return}let L=[Je.firstName,Je.lastName].filter(Boolean).join(" "),qe=await R.createPaymentMethod({elements:Ye,params:{billing_details:{email:X,...L?{name:L}:{}}}});if(qe.error||!qe.paymentMethod){y?.(qe.error?.message??"Failed to create payment method.");return}let Oe=qe.paymentMethod;if(!pe||!X)throw new Error("Missing sessionId or email for payment.");let Ne=Oe.type||e,x=await ri(s,He,pe,St??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Ne,paymentMethodId:null,intentKind:"payment"});if(x.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let je=x.clientSecret;Qt(Ir,{clientSecret:je,sessionId:pe,nonce:St,accountPatch:Te,paymentMethodId:Oe.id,paymentMethodType:Oe.type??e,gateway:"stripe"});let{error:gt,paymentIntent:_e}=await R.confirmPayment({clientSecret:je,confirmParams:{return_url:window.location.href,payment_method:Oe.id},redirect:"if_required"});if(gt){Qt(Ir);let $e=gt.message??"Payment failed.";y?.($e),C?.(hn("card",$e,{code:gt.code})),await oi({billingApiUrl:s,sessionId:pe,nonce:St,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:gt.code??"provider_declined"}});return}let ht=_e?.status;if(!ra(ht)){Qt(Ir);let $e=ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.($e),C?.(hn("card",$e,{code:ht??"missing_payment_intent"}));return}Qt(Ir);let Pe=typeof _e?.payment_method=="string"?_e.payment_method:_e?.payment_method?.id;c({id:Pe??Oe.id,type:"card",threeDSecureActionResultTokenId:_e?.id,gateway:"stripe",paymentMethodType:Oe.type??e},{accountPatch:Te,paymentMethodCategory:"apm",sessionId:pe,nonce:St})}catch(oe){y?.(oe instanceof Error?oe.message:"Payment failed. Please try again.")}finally{Qe.current=!1,De(!1)}},[R,Ye,se,Ue,I,O,t,n,o,a,Z,i,s,He,e,c,y,C]);return Ge("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[pt&&d("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:pt&&Ge("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",d("input",{type:"email",autoComplete:"email",required:!0,value:Z,onChange:re=>At(re.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),d(Qu,{onReady:()=>st("ready"),onLoadError:()=>{st("load_error"),ds(Pn(w),"stripe","apm")},onChange:re=>{et(!!re.complete)},options:{layout:hl,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...wn(o?.trim())?{email:o?.trim()}:{}}}}}),d(Pl,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{fe()},disabled:!Ue||!tt||H||se||kt!=="ready",color:N,borderRadius:xe,style:V,children:H?"Processing\u2026":`Pay with ${ga(e)}`}),f&&d(_o,{margin:"0.75rem 0 0",children:f})]})}function hc({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:c,paymentElementBaseOptions:y,futureUseSession:C,onTokenizedBody:A,onErrorChange:I,onButtonClick:O,onDecline:se,runBeforeButtonClick:N,onLoadStateChange:xe,isProcessing:V=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:w=8,submitButtonStyle:He,buttonAppearance:R,themeId:Ye,onExpandApm:H,expandedApmMethod:De}){let{emitInstrument:Qe}=Oo(nr),[Ue,et]=ie(null),[kt,st]=ie(null),Z=j(!1),{request:At,collect:pt,finish:tt}=Io();ft(()=>{s.length>0&&c?xe?.("ready"):c||xe?.("loading")},[s.length,c,xe]);let fe=ze(async X=>{if(!c||Z.current||V)return;Z.current=!0,st(X);let Te=N?await N("card"):{proceed:!0};if(!Te.proceed){Z.current=!1,st(null);return}O?.("card");let oe=Te.sessionId??e,L=Te.nonce??t,qe=aa([Te.accountPatch?.firstName,Te.accountPatch?.lastName].filter(Boolean).join(" ")||o),Oe=ur({email:Te.accountPatch?.email?.trim()||n?.trim(),firstName:Te.accountPatch?.firstName?.trim()||qe.firstName,lastName:Te.accountPatch?.lastName?.trim()||qe.lastName});if(!wn(Oe.email)){st(null);let je=await pt(ga(X),Oe);if(!je){Z.current=!1;return}Oe=je,st(X)}let Ne=Oe.email,x=ur({...Te.accountPatch,...Oe});try{if(I?.(null),!oe||!wn(Ne))throw new Error("Missing sessionId or email for payment.");await a?.(Oe);let je=await ri(i,Qe,oe,L??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(je.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let gt=je.clientSecret;Qt(Ir,{clientSecret:gt,sessionId:oe,nonce:L,accountPatch:x,paymentMethodType:X,gateway:"stripe"});let{error:_e,paymentIntent:ht}=await c.confirmPayment({clientSecret:gt,confirmParams:{return_url:window.location.href,payment_method_data:{type:X,billing_details:{name:[Oe.firstName,Oe.lastName].filter(Boolean).join(" "),...Ne?{email:Ne}:{}}}},redirect:"if_required"});if(_e){Qt(Ir);let Ve=_e.message??"Payment failed.";I?.(Ve),se?.(hn("card",Ve,{code:_e.code})),await oi({billingApiUrl:i,sessionId:oe,nonce:L,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:_e.code??"provider_declined"}});return}let Pe=ht?.status;if(!ra(Pe)){Qt(Ir);let Ve=Pe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";I?.(Ve),se?.(hn("card",Ve,{code:Pe??"missing_payment_intent"}));return}Qt(Ir);let $e=typeof ht?.payment_method=="string"?ht.payment_method:ht?.payment_method?.id;A({id:$e??ht?.id,type:"card",threeDSecureActionResultTokenId:ht?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:x,paymentMethodCategory:"apm",sessionId:oe,nonce:L})}catch(je){I?.(je instanceof Error?je.message:"Payment failed. Please try again.")}finally{Z.current=!1,st(null)}},[c,V,N,O,e,t,n,pt,i,Qe,o,a,A,I,se]),[re,pe]=ie(null),St=H?De??null:re,xt=ze(X=>{Z.current||V||St&&St!==X||(ac(X)?H?H(X):pe(X):fe(X))},[St,V,fe,H]),Je=bt(()=>re?Ec(y,re,C):null,[re,y,C]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:At?d(Ro,{identity:At.identity,methodLabel:At.methodLabel,onComplete:tt,onCancel:()=>tt(null)},At.id):s.map(X=>{let Te=De===X,oe=kt===X,L=kt!==null&&kt!==X||De!=null&&De!==X;return Ge(ep.Fragment,{children:[d(ml,{method:X,themeId:Ye,submitting:oe,disabled:L,highlighted:Te,hasNextStep:ac(X),onClick:()=>xt(X),backgroundColor:R?.backgroundColor,borderColor:R?.borderColor,textColor:R?.textColor,borderRadius:R?.borderRadius,fontFamily:R?.fontFamily}),!H&&re===X&&Je&&c&&d(oo,{stripe:c,options:Je,children:d(is,{method:X,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:A,onErrorChange:I,onDecline:se,onCancel:()=>pe(null),runBeforeButtonClick:N,onButtonClick:O,isProcessing:V,submitButtonColor:f,submitButtonBorderRadius:w,submitButtonStyle:He})},X)]},X)})})}function Mp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:c,onDecline:y,onCancel:C,onTokenizedBody:A,firstName:I,lastName:O,chv:se,className:N,submitLabel:xe,isProcessing:V,error:f,onErrorChange:w,showPayPal:He=!0,showStripe:R=!0,walletPresentation:Ye="auto",enabledPaymentMethods:H,enabledPaymentMethodCountries:De,showApplePay:Qe=!0,showGooglePay:Ue=!0,layout:et="default",theme:kt,buttonsTheme:st,buttonsStyles:Z,appearance:At,cardButtonContent:pt,cardBackButtonContent:tt,cardTitleContent:fe,showSecurityFooter:re,onButtonClick:pe,onBeforeButtonClick:St,onBuyerIdentityReady:xt,enableAVS:Je,cardFieldOrder:X,cardPreFormSlot:Te,avsLayout:oe="row",country:L,zip:qe,addressLine1:Oe,addressLine2:Ne,city:x,state:je,onCountryChange:gt,onZipChange:_e,avsCheck:ht,checkoutType:Pe,checkoutLayout:$e,totalAmount:Ve=0,currency:vn="usd",initialCardOpen:It=!1,directPaypal:Pt,isSubscription:le=!1,session:P,dataAttachmentPending:lt=!1,dataAttachmentRequiresIdentity:nt=!1,debug:_=!1}){let Se=$r(),Bt=zi(),ce=Oo(dr),{emitInstrument:wt}=Oo(nr),m=j(null);m.current||(m.current=qa());let v=m.current,[,Ce]=ie(0),ve=j(null);ve.current||(ve.current=ea());let Ze=ve.current,rt=bt(()=>({browser:Ze,capability:v,presentationMode:"popup"}),[Ze,v]),be=P??ce.session,we=bt(()=>({futureUse:be?.futureUse,futureUseUnsupported:be?.futureUseUnsupported}),[be?.futureUse,be?.futureUseUnsupported]),Ft=be?.gateways?.paypal?.providerObjectType??Pt?.providerObjectType,u=lt||ce.claimPending===!0,Be=nt||ce.claimRequiresIdentity===!0,ge=u&&!Be,ke=Ll(),G=n||ke,[$,mn]=ie(!1),[Wn,en]=ie(null),[qt,yt]=ie(L??""),[Mn,kn]=ie(qe??""),[Yt,Nn]=ie(Oe??""),[mt,mr]=ie(Ne??""),[jt,Zn]=ie(x??""),[An,xn]=ie(je??""),[tn,fn]=ie(""),[Ln,Le]=ie({}),ot=j(qe??""),nn=j(L??""),$t=j(Oe??""),dn=j(Ne??""),Wt=j(x??""),rn=j(je??""),Cn=j(""),on=j({});ft(()=>{let r=(h,U,te,F,ne)=>{if(on.current[h])return;let Mt=U?.trim();!Mt||Mt===te.current||(te.current=Mt,F(Mt),ne?.(Mt))};r("country",L,nn,yt,gt),r("zip",qe,ot,kn,_e),r("addressLine1",Oe,$t,Nn),r("addressLine2",Ne,dn,mr),r("city",x,Wt,Zn),r("state",je,rn,xn)},[L,qe,Oe,Ne,x,je,gt,_e]);let Ie=bt(()=>Vu(Je),[Je]),In=Ie!==null,an=bt(()=>Ji(P),[P]),Nr=Lu(P?.vault),Bn=!!P?.gateways?.pcivault,Fn=xl(P),zn=!!(P?.gateways?.stripe?.enabledPaymentMethods??H)?.includes("card")||to(P),Ht=Nr||zn||Bn,K=!!(R&&Ht&&e),[B,vt]=ie(()=>et!=="buttons"||It?e??null:null),[ae,un]=ie(0),Rt=et!=="buttons"||It||!!e&&B===e,Ot=P?.captureMethod,pn=j(Se);ft(()=>{pn.current=Se},[Se]);let[T,Nt]=ie(null);ft(()=>{if(!K||!e||!Rt){Nt(null);return}let r=pn.current?pn.current.cardCapture({sessionId:e,captureMethod:Ot}):new Su({sessionId:e,captureMethod:Ot,billingApiUrl:G,telemetry:o});return Nt({sessionId:e,captureMethod:Ot,billingApiUrl:G,telemetry:o,capture:r}),()=>{r.unmount()}},[K,e,Rt,Ot,G,o]);let Me=K&&e&&Rt&&T?.sessionId===e&&T.captureMethod===Ot&&T.billingApiUrl===G&&T.telemetry===o?T.capture:null,Et=bt(()=>{let r=qt,h=Ie?Kt(Ie.postal_code,r):!1;return Ip(r,Mn,h)},[Ie,qt,Mn]),{avsInvalid:sn,invalidAvsFields:Rn}=bt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!K||!Ie)return{avsInvalid:!1,invalidAvsFields:r};let h=qt,U=(ne,Mt)=>Kt(ne,h)&&!Mt.trim(),te={line1:U(Ie.address_line_1,Yt),city:U(Ie.city,jt),state:U(Ie.state,An),zip:Et.empty||Et.malformed};return{avsInvalid:te.line1||te.city||te.state||te.zip,invalidAvsFields:te}},[K,Ie,qt,Yt,jt,An,Et]),[Jt,or]=ie(!1),[Er,gr]=ie(!1),[Dn,Lr]=ie(!1),[Xn,_r]=ie({line1:!1,city:!1,state:!1}),Hn=j(!1),ar=j({email:!1,line1:!1,city:!1,state:!1,zip:!1}),hr=j(!1),_t=ze(r=>{ar.current[r]=!0,hr.current=!0},[]),Vn=ze(r=>!Hn.current&&ar.current[r],[]),Kn=ze(r=>{Vn(r)&&_r(h=>h[r]?h:{...h,[r]:!0})},[Vn]),[Un,ir]=ie(()=>Xi(P?.vault,{billingApiUrl:G,sessionId:e,nonce:t})),[Xe,bn]=ie(It&&Ht?"card":"buttons"),[ln,qn]=ie(null),Yr=Xe==="expanding"||Xe==="card",sr=P?.gateways?.stripe&&!Fn?"stripe":void 0,Tr=ze(()=>{wt?.({class:"card_surface",provider:sr})},[sr,wt]),Gn=j(null),Sn=ze(r=>{Gn.current&&clearTimeout(Gn.current),Gn.current=setTimeout(()=>{Gn.current=null,r()},ha)},[]);ft(()=>()=>{Gn.current&&clearTimeout(Gn.current)},[]);let Pr=j(!1),[En,b]=ie(0),S=j(null),D=ze(()=>{Tr(),vt(e??null),Pr.current&&(Pr.current=!1,b(r=>r+1)),un(r=>r+1),bn("expanding"),Sn(()=>bn("card"))},[Sn,Tr,e]),Q=ze(()=>{bn("collapsing"),Sn(()=>bn("buttons"))},[Sn]),ct=ze(r=>{qn(r),bn("apm-expanding"),Sn(()=>bn("apm-form"))},[Sn]),Zt=ze(()=>{bn("apm-collapsing"),Sn(()=>{bn("buttons"),qn(null)})},[Sn]);ft(()=>{et==="buttons"&&It&&Ht&&(vt(e??null),bn("card"))},[et,It,Ht,e]);let[ye,q]=ie(null),k=j(!1),E=j(null),W=j("idle"),[p,l]=ie(!1),M=j(p);M.current=p;let[ee,Re]=ie(()=>Pt?.existingOrderId?{orderId:Pt.existingOrderId,attempts:1}:null),We=j(ee);ft(()=>{We.current=ee},[ee]);let me=j(null),de=bt(()=>{if(xt||ce.claimBuyerIdentity||P?.buyerIdentified!==!1||!e||!t)return;let r=`${G}|${e}|${t}`;me.current?.key!==r&&(me.current={key:r,claim:So(new Fo(G,{telemetry:!1}),e,t,{...i?{userId:i}:{},...I?{firstName:I}:{},...O?{lastName:O}:{}})});let h=me.current.claim;return async U=>{await h(U)}},[xt,ce.claimBuyerIdentity,P?.buyerIdentified,e,t,G,i,I,O]),Fe=xt??ce.claimBuyerIdentity??de,at=f??Wn,dt=bt(()=>Gu(kt),[kt]),g=bt(()=>{let r=dt?.buttonsLayout??Ku(st);return Z?{...r,...Z,cardButton:{...r.cardButton,...Z.cardButton},cardFormContainer:{...r.cardFormContainer,...Z.cardFormContainer},backButton:{...r.backButton,...Z.backButton},backButtonIcon:{...r.backButtonIcon,...Z.backButtonIcon},submitButton:{...r.submitButton,...Z.submitButton},title:{...r.title,...Z.title}}:r},[dt,st,Z]),Y=At??dt?.appearance,Ee=bt(()=>Mu({appearance:Y,buttonsStyles:g,layout:et}),[Y,g,et]),Ae=ce.inlineSessionPatchProcessing??!1,z=(V??$)||Ae,cn=G.replace(/\/+$/,""),J=bt(()=>Ni({userId:i,email:a,firstName:I,lastName:O,country:L,zip:qe},Ln),[i,a,I,O,L,qe,Ln]),Mr=[J.firstName,J.lastName].filter(r=>!!r?.trim()).join(" "),ws=!wn(J.email?.trim()),ci=j(null);K&&ci.current===null&&(ci.current=ws);let zr=K&&(ci.current??ws),di=bt(()=>Rp(tn,zr),[tn,zr]),io=di.empty||di.malformed,Yn=bt(()=>Se?Se.getRawProvider():null,[Se]),ks=bt(()=>Bt?Bt.getRawProvider():null,[Bt]),qo=Ve||100,so=vn.toLowerCase(),ui=bt(()=>Y?wu(Y):null,[Y]),lo=ui,Is=bt(()=>{let r=ui??{},h=r.rules??{};return{...r,rules:{...h,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...h[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...h[".AccordionItemContents"]??{}}}}},[ui]),Rs=bt(()=>({...Al(Ve,be?.captureMethod,we),currency:so,...lo?{appearance:lo}:null}),[Ve,so,be?.captureMethod,we,lo]),pi=vc(we,"paypal","paypal"),Es=bt(()=>({mode:"payment",amount:qo,currency:so,captureMethod:"manual",...pi?{setupFutureUsage:pi}:null,...lo?{appearance:lo}:null}),[qo,so,pi,lo]),he=ze(r=>{en(r),w?.(r)},[w]),_s=j(0);ft(()=>{En!==_s.current&&(_s.current=En,he(null))},[En,he]);let yi=j(""),[Ts,qc]=ie(!1),mi=ze(()=>{qc(!0)},[]);ft(()=>{if(!K||!zr||!Fe||!Ts||io||yi.current)return;let r=ur({email:wn(J.email?.trim())?J.email?.trim():Cn.current.trim(),firstName:J.firstName?.trim(),lastName:J.lastName?.trim()});yi.current=JSON.stringify(r),Le(h=>({...h,...r})),Promise.resolve(Fe(r)).catch(h=>{yi.current="",he(h instanceof Error?h.message:"Failed to attach buyer details.")})},[K,zr,Fe,Ts,io,J.email,J.firstName,J.lastName,he]),ft(()=>{!K||!Me||Me.setCardFieldOrder?.(X??null,Ie==null&&!zr)},[K,Me,X,Ie,zr]),ft(()=>{(Xe==="expanding"||Xe==="collapsing"||Xe==="apm-expanding"||Xe==="apm-collapsing")&&he(null)},[Xe,he]);let vr=ze((r,h,U)=>{y?.(hn(r,h,U))},[y]),co=ze((r,h,U)=>{let te=U?.popupBlocked??Ur(h);te&&v.markBlocked()&&Ce(ut=>ut+1);let F=as(r),ne=U?.code===bc?Ru(F):Ba(F,te,Ze.inAppBrowser),Mt=ho(h),er=(Mt?.toLowerCase()==="error"?void 0:Mt)??pl(U?.code)??"external_payment_method_failed",Ke=new Dr(ne,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:er,popupBlocked:te,inAppBrowser:Ze.inAppBrowser,appFamily:Ze.appFamily,popupCapability:v.current(),presentationMode:U?.presentationMode??"popup"}});U?.telemetryReported||Pn(Se)?.error(Bo({...rt,presentationMode:U?.presentationMode??"popup"},{errorCode:te?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:U?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:U?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:U?.terminalReason??(te?"popup_blocked":"provider_error")})),q(null),et==="buttons"&&(bn("buttons"),qn(null)),he(ne),c?.(Ke),console.error("[FloPay] External payment method failed:",{method:r,code:er,popupBlocked:te})},[Ze,rt,Se,et,c,v,he]);ft(()=>{if(!K||!e){ir(null);return}let r={billingApiUrl:cn,sessionId:e,nonce:t},h=Xi(P?.vault,r);if(h){ir(h);return}if(!Rt){ir(null);return}let U=`${cn}\0${e}\0${t??""}`,te=S.current;if(te&&te.key===U){ir(te.mount);return}ir(null);let F=!0;return new Fo(cn).getVaultCapture(e,t).then(ne=>{if(!F)return;let Mt=Xi(ne,r);Mt?.verificationRequired&&!ne.html&&(S.current={key:U,mount:Mt}),Mt?ir(Mt):he("Failed to load the secure card form.")}).catch(ne=>{F&&he(ne instanceof Error?ne.message:"Failed to load the secure card form.")}),()=>{F=!1}},[K,Rt,ae,e,P?.vault,cn,t,he]);let lr=j({onComplete:s,onError:c,updateError:he,emitDecline:vr,resolvedAccount:J,avsConfig:Ie,avsCheckProp:ht,sessionId:e,nonce:t,baseUrl:cn,captureMethod:P?.captureMethod,paymentId:P?.paymentId,authorizationExpiresAt:P?.authorizationExpiresAt,serverSideCardGateway:Fn});lr.current={onComplete:s,onError:c,updateError:he,emitDecline:vr,resolvedAccount:J,avsConfig:Ie,avsCheckProp:ht,sessionId:e,nonce:t,baseUrl:cn,captureMethod:P?.captureMethod,paymentId:P?.paymentId,authorizationExpiresAt:P?.authorizationExpiresAt,serverSideCardGateway:Fn};let fi=j(!1),Ms=ze(()=>{let r=lr.current,h=r.resolvedAccount.email?.trim(),U=wn(h)?h:Cn.current.trim();if(!wn(U))return null;let te=r.resolvedAccount.firstName?.trim(),F=r.resolvedAccount.lastName?.trim(),ne=nn.current.trim()||r.resolvedAccount.country?.trim()||"",Mt=r.avsConfig?Kt(r.avsConfig.state,ne):!1,er=r.avsConfig?Kt(r.avsConfig.address_line_1,ne):!1,Ke=r.avsConfig?Kt(r.avsConfig.postal_code,ne):!1,ut=r.avsConfig?Kt(r.avsConfig.city,ne):!1,Ct=r.avsConfig?Kt(r.avsConfig.address_line_2,ne):!1,Ut=er&&!Mt&&Ke?Du(ne,(ot.current??"").trim()):null,Xr=Mt?rn.current:Ut;return{accountData:{userId:r.resolvedAccount.userId??"",email:U,...te?{firstName:te}:{},...F?{lastName:F}:{},...Ke&&ot.current?{zip:ot.current}:{},...ut&&Wt.current?{city:Wt.current}:{},...Xr?{state:Xr}:{},...er&&$t.current?{addressLine1:$t.current}:{},...Ct&&dn.current?{addressLine2:dn.current}:{},...ne?{country:ne}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Kt(r.avsConfig.country,ne),postal_code:Ke,address_line_1:er,address_line_2:Ct,city:ut,state:Mt}}:{}}},[]),As=j(u);As.current=u,ft(()=>{u||at!==uc||lr.current.updateError(null)},[u,at]),ft(()=>{!K||!Me||Me.setSubmitGate?.(sn||u||io||p)},[K,Me,sn,u,io,p]),ft(()=>{if(!K||!Me)return;fi.current=!1;let r=null,h=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,W.current="idle",q(null)},400)},U=Me.on("submitting",()=>{or(!0),E.current&&clearTimeout(E.current),W.current="validation-window",E.current=setTimeout(()=>{E.current=null,W.current==="validation-window"&&(W.current="processing")},fp),q("processing");let Ke=lr.current;if(!Ke.sessionId||!Ke.nonce)return;let ut=Ms();if(!ut){Ke.updateError("Enter a valid email address."),W.current="idle",q(null);return}new Fo(Ke.baseUrl).patchAccountSnapshot(Ke.sessionId,Ke.nonce,ut,{telemetryMode:"best_effort"}).catch(Ct=>{if(!hp(Ct))return;let Ut=Ct instanceof Error?Ct.message:"Please check your billing address and try again.";Ke.updateError(Ut),W.current="idle",q(null),Ke.onError?.(Ct instanceof Dr?Ct:new Dr(Ut,"api_error"))})}),te=Me.on("complete",Ke=>{To(Ke.sessionId??lr.current.sessionId),W.current="terminal",l(!1),q("success"),setTimeout(()=>{if(fi.current)return;fi.current=!0;let ut=lr.current,Ct=Ji(ut)||Ke.outcome==="authorized",Ut=ut.serverSideCardGateway?{}:{paymentIntentId:Ke.intentId};lr.current.onComplete?.(Ct?{status:"authorized",...Ut,paymentId:Ke.paymentId??ut.paymentId,sessionId:Ke.sessionId??ut.sessionId,authorizationExpiresAt:Ke.authorizationExpiresAt??ut.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Ut,checkoutMethod:"card"})},600)}),F=Me.on("decline",Ke=>{let ut=lr.current,Ct=Ke.message??"Your payment was declined. Please try another card or contact your bank.";W.current="terminal",l(!1),ut.updateError(Ct),q("error");let Ut=Ke.failureOutcome??ju(Ke.declineReason)??"authorization_declined";ut.emitDecline("card",Ct,{code:Ut,declineCode:Ut}),h()}),ne=Me.on("error",Ke=>{let ut=lr.current,Ct=Ke.message??"There was a problem processing your payment. Please try again.";W.current="terminal",l(!1),ut.updateError(Ct),q("error"),ut.onError?.(new Dr(Ct,"api_error",{code:Ke.failureOutcome??"capture_failed"})),h()}),Mt=Me.on("challenge_dismissed",()=>{E.current&&(clearTimeout(E.current),E.current=null),W.current="processing",l(!0),q(null)}),er=Me.on("blocked",()=>{if(M.current){lr.current.updateError(gp);return}if(!As.current){or(!0);return}mi(),lr.current.updateError(uc)});return()=>{r&&(clearTimeout(r),r=null),E.current&&(clearTimeout(E.current),E.current=null),W.current="idle",l(!1),q(null),U(),te(),F(),ne(),Mt(),er()}},[K,Me,mi,Ms]);let Cr=!!Pt?.clientId,jo=Array.isArray(H),Sa=jo&&H.length>0,xs=jo&&H.includes("paypal"),wa=j(null);wa.current===null&&(wa.current=Nu());let uo=wa.current?"redirect":yl(Ze,Ye,v.current()),{expressMethods:ka,paymentElementMethods:gi}=bt(()=>$u(H,{excludePaypal:Cr}),[H,Cr]),Bs=Cr||!!Bt||xs&&uo==="redirect",jc=bt(()=>Bs?ka.filter(r=>r!=="paypal"):ka,[ka,Bs]),$c=bt(()=>{let r=[];return Qe&&r.push("apple_pay"),Ue&&r.push("google_pay"),r},[Qe,Ue]),po=jo?jc:$c,Wc=R&&po.length>0,Fs=In?qt:L,Ia=bt(()=>Bu(gi,Fs,De),[gi,Fs,De]),hi=bt(()=>({mode:"payment",amount:qo,currency:so,paymentMethodCreation:"manual",appearance:Is}),[qo,so,Is]),[Ds,Os]=ie("loading"),[Ns,Ls]=ie("loading"),[zs,Us]=ie("loading"),[Hc,Pi]=ie(!1),[qs,vi]=ie("loading"),[Ci,Vc]=ie();ft(()=>{Vc(ea())},[]);let Ra=Ci?.inAppBrowser,Ea=Ci?Da(Ci,Pt?.approvalPresentation,Ft??(le?"subscription":"order")):"popup",js=He&&(Cr||(jo?xs:Ra===!1)),Kc=Ze.inAppBrowser&&v.current()==="blocked",$s=R&&Wc&&!Kc,$o=(!ge||!!ce.waitForDataAttachment)&&js&&Cr,Ws=qs==="retrying"||qs==="exhausted",Wo=null;R&&(Bt?Wo=ks:uo==="redirect"&&(Wo=Yn));let Hs=bt(()=>({...rt,presentationMode:uo}),[rt,uo]),Ho=!ge&&js&&!!Wo&&(!Cr||Ws),yo=!ge&&$s&&!!Yn,Vo=!ge&&R&&Sa&&Ia.length>0&&!!Yn,Gc=$o&&!Ws?Hc:Ho&&Fi(Ds),Yc=yo&&Fi(Ns),Jc=Vo&&zs!=="load_error",Vs=r=>r==="loading"||r==="ready",Ks=$o||Ho&&Vs(Ds)||yo&&Vs(Ns)||Vo&&zs!=="load_error",_a=j(!1);ft(()=>{if(!_a.current){if(!R&&!He){_a.current=!0;let r=new Dr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(r),he(r.message)}else if(!R&&He&&!Cr){_a.current=!0;let r=new Dr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(r),he(r.message)}else if(Ra!==void 0&&!ge&&!Ht&&!Ks){_a.current=!0;let r=new Dr("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),he(r.message)}}},[R,He,Cr,Ra,ge,Ht,Ks,c,he]);let Gs=j(!1);ft(()=>{if(Gs.current||!Sa)return;let r=[];Qe!==!0&&r.push("showApplePay"),Ue!==!0&&r.push("showGooglePay"),r.length!==0&&(Gs.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.`))},[Sa,Qe,Ue]);let Ys=ze((r,h,U)=>ce.applyInlineSessionPatch?ce.applyInlineSessionPatch(r).then(te=>({error:null,sessionId:te.sessionId||e,nonce:te.session?.clientSecret||t})).catch(te=>{let F=ic(h,te);return U?.abandoned?.()||(he(F.message),c?.(F)),{error:F,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ce.applyInlineSessionPatch,t,c,e,he]),cr=ze(async(r,h)=>{if(r!=="card"&&ge&&await ce.waitForDataAttachment?.(),!St)return{proceed:!0};try{let U=await St({method:r,sessionId:e||void 0,createSession:ce.inlineSessionDraft});if(U===!1)return{proceed:!1};if(U&&typeof U=="object"){U.account&&Le(F=>({...F??{},...U.account}));let te=await Ys(U,r,h);return te.error?{proceed:!1,accountPatch:U.account}:{proceed:!0,accountPatch:U.account,sessionId:te.sessionId,nonce:te.nonce}}return{proceed:!0}}catch(U){if(!h?.abandoned?.()){let te=ic(r,U);he(te.message),c?.(te)}return{proceed:!1}}},[Ys,ce.inlineSessionDraft,ce.waitForDataAttachment,ge,St,c,e,he]),Js=ze(async(r,h)=>{if(k.current)return;k.current=!0,mn(!0),q("processing"),he(null);let U=h?.sessionId??e,te=h?.nonce??t,F=Ni(J,h?.accountPatch),ne=h?.completionPaymentMethodId??oa(r),Mt=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,er=bp(r),Ke=h?.presentationMode?Qa(Pn(Se),{...rt,presentationMode:h.presentationMode}):void 0,ut=()=>{wt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:er}),Ke?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...pr,requestCategory:"process_payment"})};try{let Ct=new Fo(cn),Ut=await Ct.processPayment(F.userId??"",{sessionId:U,nonce:te,paymentMethodCategory:h?.paymentMethodCategory??wp(r),tokenizedData:Mt,accountData:{...h?.accountPatch,userId:F.userId??"",email:F.email??"",firstName:F.firstName||void 0,lastName:F.lastName||void 0,...Iu({avsConfig:Ie,country:nn.current,zip:ot.current,city:Wt.current,state:rn.current,addressLine1:$t.current,addressLine2:dn.current})},...ku({chv:se,avsCheck:ht,checkoutType:Pe,checkoutLayout:$e,avsConfig:Ie,country:nn.current})}),Xr=async gn=>{let Qr=Ji(P)||gn?.status==="authorized";To(U),Ke?.terminal({outcome:"payment_succeeded",...pr}),q("success"),Re(null),await new Promise(Xo=>setTimeout(Xo,600));let br;typeof gn?.paymentId=="string"?br=gn.paymentId:P?.paymentId&&(br=P.paymentId);let eo;typeof gn?.authorizationExpiresAt=="string"?eo=gn.authorizationExpiresAt:P?.authorizationExpiresAt&&(eo=P.authorizationExpiresAt),s?.(Qr?{status:"authorized",...br===void 0?{}:{paymentId:br},sessionId:typeof gn?.sessionId=="string"?gn.sessionId:U,...eo===void 0?{}:{authorizationExpiresAt:eo},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ne,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ne,checkoutMethod:r.isPaypal?"paypal":"card"})};if(Ut.ok){await Xr(Ut.status===204?null:await Ut.json().catch(()=>null));return}let Jn=await Ut.json().catch(()=>null);if(Jn?.type==="paypal_redirect_required"){let gn=Jn.threeDSecureToken,Qr=Jn.paymentMethodId||r.id||"";if(!Se||!gn){q("error"),he("PayPal authorization required but no token provided.");return}try{let br=Bt?.getRawProvider();if(!br){he("PayPal is not available.");return}let eo={return_url:window.location.href};Qr&&(eo.payment_method=Qr);let{error:Xo}=await br.confirmPayment({clientSecret:gn,confirmParams:eo,redirect:"if_required"});if(Xo){q("error");let ll=Xo.message??"PayPal payment failed.";he(ll),vr("paypal",ll,{code:Xo.code})}}catch(br){q("error"),he(br instanceof Error?br.message:"PayPal authorization failed.")}return}if(Jn?.type==="paypal_direct_required"){let gn=Jn.orderId;if(!gn){q("error"),he("PayPal retry required but no order id provided.");return}let Qr=We.current?.attempts??0;if(Qr>=2){q("error"),he("PayPal payment could not be completed after multiple attempts."),vr("paypal","paypal_direct_required retry limit exceeded");return}Pi(!1),vi("loading"),Re({orderId:gn,attempts:Qr+1}),q(null);return}if(Ut.headers.get(lp)===cp){let gn=await dp(Ct,U,te);if(gn!==void 0){await Xr(gn);return}}_u(Ut.status,Jn)?Ke?.terminal({outcome:"payment_declined",...pr,terminalReason:"provider_declined"}):ut(),q("error");let sl=Jn?.message??"Payment failed. Please try again.";he(sl),vr(r.isPaypal?"paypal":"card",sl,{code:Jn?.code??Jn?.gatewayErrorCode,declineCode:Jn?.declineCode??Jn?.gatewayDeclineReason}),await new Promise(gn=>setTimeout(gn,400))}catch(Ct){Ic(Ct)||ut(),q("error"),he(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(Ut=>setTimeout(Ut,400))}finally{mn(!1),q(null),k.current=!1}},[cn,e,t,J,Ie,ht,Pe,$e,se,Se,Bt,P,s,he,vr,wt,rt]),jn=ze((r,h)=>{A?A(r):Js(r,h)},[A,Js]),Ko=`${wc}:${e}`;ft(()=>{if(typeof window>"u")return;let r=localStorage.getItem(Ko);if(!r)return;let h;try{h=JSON.parse(r)}catch{Qt(Ko);return}if(!h||typeof h.createdAt!="number"||Date.now()-h.createdAt<0||Date.now()-h.createdAt>kc||typeof h.paymentMethodId!="string"||typeof h.providerIntentId!="string"||typeof h.paymentMethodType!="string"||h.sessionId!==e||!t||h.nonce!==t||!po.includes(h.paymentMethodType)){Qt(Ko);return}Qt(Ko),jn({id:h.paymentMethodId,type:"card",threeDSecureActionResultTokenId:h.providerIntentId,gateway:"stripe",paymentMethodType:h.paymentMethodType},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[jn,t,e,Ko,po]);let Zs=j(!1);ft(()=>{if(typeof window>"u"||Zs.current)return;let[r,h,U]=Pc();if(!r||!h||wa.current||!Se)return;let te=Se.getRawProvider();if(!te)return;let F=ut=>{let Ct=localStorage.getItem(ut);if(!Ct)return null;try{return JSON.parse(Ct)}catch{return Qt(ut),null}},ne=F(Ir)??F(lc),Mt;if(ne?.clientSecret){if(ne.clientSecret!==h)return;Mt={...ne.accountPatch?{accountPatch:ne.accountPatch}:{},...ne.sessionId?{sessionId:ne.sessionId}:{},...ne.nonce?{nonce:ne.nonce}:{}}}else if(ne?.sessionId&&ne.sessionId!==e)return;Zs.current=!0,Qt(Ir),Qt(lc),window.history.replaceState({},"",Cc());let er=ne?.paymentMethodType??ne?.tokenType??"card",Ke="card";(async()=>{if(U==="failed"){let Ar="Payment was declined. Please try again.";he(Ar),vr(Ke,Ar);return}let{paymentIntent:ut,error:Ct}=await te.retrievePaymentIntent(h);if(Ct){let Ar=Ct.message??"Failed to retrieve payment status.";he(Ar),vr(Ke,Ar,{code:Ct.code});return}let Ut=ut?.status,Xr=ra(Ut);if(!ut||!Xr){let Ar=Ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(Ar),vr(Ke,Ar,{code:Ut??"missing_payment_intent"});return}let Jn=typeof ut.payment_method=="string"?ut.payment_method:ut.payment_method?.id;jn({id:Jn??ne?.paymentMethodId??ne?.tokenId??ut.id,type:"card",threeDSecureActionResultTokenId:ut.id,gateway:ne?.gateway??"stripe",paymentMethodType:er},Mt)})()},[e,jn,Se,he,vr]);let bi=ze(r=>{r.preventDefault()},[]);if(!(K||Se!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Go=et==="buttons",$n=Y?.variables,Zc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Si=$n?.colorBackground,Xc=Si&&!Zc.has(Si)?Si:void 0,Yo=g.cardInputBorder??(Go?"#e5e7eb":"#A4A4FF"),Xs=$n?.colorDanger??"#dc2626",Vt=r=>Rn[r]&&(Xn[r]||Jt),Ta=io&&(Dn||Jt),Qn=r=>r?Xs:Yo,Ma=(Et.malformed||Et.empty)&&(Er||Jt),Qc=Qn(Ma),wi=g.cardFormContainer?.backgroundColor??Xc??(Go?"white":"#EDEDFF"),mo=g.cardInputBackground??$n?.colorBackground??"white",ki=Po(tt),Qs=Po(fe),fo=g.nameInput,el=g.cardInputFontSize??Ep(fo?.fontSize)??$n?.fontSizeBase??"16px",tl=typeof fo?.fontFamily=="string"?fo.fontFamily:$n?.fontFamily??"Poppins, sans-serif",nl=Xu(fo?.fontWeight)??400,ed=g.cardInputColor??(typeof fo?.color=="string"?fo.color:void 0)??$n?.colorText??"#262833",td=g.cardInputPlaceholderColor??"#9ca3af",Xt=$n?.borderRadius??"8px",Jr=$n?.borderRadius??g.cardButton?.borderRadius??Xt,Zr=$n?.colorPrimary??"#4A49FF",nd=$n?.colorPrimaryHover??Au(Zr,.12),Ii=$n?.colorText??"#262833",Ri={fontSize:el,fontFamily:tl,fontWeight:nl,color:ed,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Jo={marginTop:"0.375rem",...Ri,fontSize:"0.75rem",lineHeight:1.4,color:Xs},rd={"--flopay-input-placeholder-color":td,"--flopay-input-font-size":el,"--flopay-input-font-family":tl,"--flopay-input-font-weight":String(nl)},Zo=g.cardFormContainer??{},Ei=Zo.padding??(Go?"0":"1rem"),_i=Zo.borderRadius??Xt,od=Me&&Un?d(Ti,{capture:Me,html:Un.html,messageToken:Un.messageToken,expectedOrigin:Un.expectedOrigin,verificationRequired:Un.verificationRequired,theme:Ee,submitLabel:xe,onReady:()=>{if(!zr&&!Ie||typeof document>"u")return;let r=()=>{let U=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(U){Hn.current=!0;try{U.focus()}finally{Hn.current=!1}}};hr.current||r()},onError:r=>{r&&Un.verificationRequired&&W.current==="idle"&&(Pr.current=!0),he(r)},onValidation:r=>{let h=W.current;(h==="idle"||h==="validation-window")&&(he(r),r&&W.current==="validation-window"&&(E.current&&(clearTimeout(E.current),E.current=null),W.current="idle",q(null)))}},En):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"}),rl=Ge("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&Tr()},style:{backgroundColor:wi,borderRadius:_i,...Zo,padding:Ei,...rd,display:"flex",flexDirection:"column"},children:[d("style",{children:`
3
+ ${Re.join(`
4
+ `)}`]}):null;return Pt&&!d?te?ao("div",{children:jn}):null:Hi("div",{children:[jn,ot&&ao(Mo,{identity:ot.identity,methodLabel:ot.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Se,onCancel:()=>Se(null)}),Hi("div",{"aria-hidden":qe||ot?!0:void 0,style:qe||ot?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ga},children:[!Oe&&!qe&&ao("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"}}),ao("div",{ref:fe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ga,display:"flex",opacity:Oe?1:0},"aria-busy":P||b},_e)]},_e),je&&ao("button",{ref:Ue,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:ln,style:uu,children:"Try PayPal again"})]})}function Ya(e){return ao(Zl,{...e})}function Xl(e){return ao(Zl,{...e})}import{jsx as Ql,jsxs as fu}from"react/jsx-runtime";function xo({children:e,margin:t,icon:n=!0,styleOverride:o}){return fu("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&&Ql("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Ql("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 Ja,clearCachedInlineSession as Ki,hashCreateParams as ec,legacyCachedSessionMatchesDraft as tc,persistCachedInlineIdempotencyKey as Za,persistCachedInlineSession as Xa,readCachedInlineIdempotencyKey as nc,readCachedInlineSession as rc,serializeCreateParams as ya}from"@flopay/shared";import{resolveBillingApiUrl as gu}from"@flopay/shared";import{useEffect as Gr,useMemo as hu,useRef as oc,useState as ac}from"react";import{jsx as Pu}from"react/jsx-runtime";function Qa({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=ac(e instanceof Promise?null:e),[l,u]=ac(t instanceof Promise||!t?null:t),C=oc(null),_=oc(null),k=Ao(o);Gr(()=>{k({class:"lifecycle",name:"checkout.mount"})},[k]),Gr(()=>{i&&k({class:"lifecycle",name:"sdk.initialize.ready"})},[k,i]),Gr(()=>{if(i)return pn(i)?.subscribe?.(k)},[k,i]),Gr(()=>{if(!(!l||l===i))return pn(l)?.subscribe?.(k)},[k,i,l]),Gr(()=>{if(!i)return;let N=pn(i);return C.current=N?.beginCheckout()??N?.now()??0,N?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{N?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Gr(()=>{let N=!1;return e instanceof Promise?e.then(Ae=>{N||s(Ae)},()=>{N||k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{N=!0}},[k,e]),Gr(()=>{let N=!1;if(!t){u(null);return}return t instanceof Promise?t.then(Ae=>{N||u(Ae)},()=>{N||k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):u(t),()=>{N=!0}},[k,t]),Gr(()=>{if(!i||_.current===i)return;_.current=i;let N=pn(i);N?.log({name:"checkout.rendered",stage:"checkout_render"}),k({class:"lifecycle",name:"checkout.rendered"}),N?.performance({stage:"checkout_render",durationMs:N.elapsed(C.current??0),durationMode:"machine"})},[k,i]);let O=gu(n?.billingApiUrl),ue=hu(()=>({flopay:i,paypalFlopay:l,billingApiUrl:O,emitInstrument:k}),[i,l,O,k]);return Pu(ir.Provider,{value:ue,children:a})}import{markSessionRecentlyCompleted as Bo,wasSessionRecentlyCompleted as Gi}from"@flopay/shared";async function ei(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{completeSavedCardNextAction as vu,loadFloPay as ic,PaymentAPI as ni,runSavedCardChallenge as Cu}from"@flopay/js";import{classifyPaymentRejection as bu,FloPayError as Tt,isAuthorizationOnlySession as Su,isMountableVaultBlock as wu,isSetupIntentClientSecret as ku,normalizeCheckoutFailureOutcome as sc}from"@flopay/shared";var fa="card";async function Iu(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 Ru(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,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 Fo(e){return new Tt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Eu(){return new Tt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Ji(e,t){return Object.assign(e,{checkoutMethod:t})}function Lr(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 ma(e,t){try{return await e()}catch(n){throw Lr(n,t)}}function cc(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function dc(e){return Cu(e)}async function Do(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new ni(n,{telemetry:!1}),l=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,u;try{u=await vu({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:_=>Ir({type:_.declineReason??"authorization_declined",gatewayErrorCode:_.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(_){if(a.aborted||_ instanceof Error&&_.name==="AbortError")throw _ instanceof Tt&&_.code==="three_ds_aborted"?_:Fo(_);if(!(_ instanceof Tt)||_.code!=="three_ds_timeout"&&_.code!=="checkout_processing_timeout")throw _;try{u=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:l,timeoutMs:5e3,signal:a})}catch(O){if(a.aborted)throw Fo(O);if(!(O instanceof Tt)||O.code!=="checkout_processing_timeout")throw O}let k=u&&Vr(u,t.session);if(!Or(k)&&k?.status!=="expired"){if(t.telemetry){let O=new ni(n);try{O.reportThreeDsAbandoned(o)}finally{O.destroy()}}throw Eu()}}let C=u&&Vr(u,t.session);if(!Or(C))throw Eo(C);return{...Dr(C,o),checkoutMethod:"card"}}function Ir(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=_o(a)??a,s=Ji(new Tt(i,"api_error",{code:e?.code??sc(e?.outcome)??sc(e?.type)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Yi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function uc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ti(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 l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||ti(l)))return l;let s=a.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let u=l,C=[u.stripeClientSecret,u.clientSecret];for(let _ of C)if(typeof _=="string"&&_.length>0&&(!t?.requirePaymentIntentClientSecret||ti(_)))return _}}}}async function _u({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=uc(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let l=(await new ni(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ti(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Oo({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),u=t??n.id,C=o??n.clientSecret,_=n.customer?.id??n.accountData?.userId??"",k=n.customer?.email??n.accountData?.email??"",O=n.customer?.firstName??n.accountData?.firstName??"",ue=n.customer?.lastName??n.accountData?.lastName??"",N=n.customer?.country??n.accountData?.country??void 0,Ae=n.customer?.zip??n.accountData?.zip??void 0,m=await new ni(l,s===!1?{telemetry:!1}:void 0).processPayment(_,{sessionId:u,nonce:C,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:_,email:k,firstName:O,lastName:ue,country:N,zip:Ae},returnUrl:i??Yi(n)});if(m.ok){let I=typeof m.json=="function"?await m.json().catch(()=>null):null;if(Su(n)||I?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof I?.paymentId=="string"?I.paymentId:n.paymentId,sessionId:typeof I?.sessionId=="string"?I.sessionId:u,authorizationExpiresAt:typeof I?.authorizationExpiresAt=="string"?I.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:sa(a),checkoutMethod:lc(a,n)}};let Xe=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Xe?{paymentIntentId:Xe}:{},paymentMethodId:sa(a),checkoutMethod:lc(a,n)}}}let b;try{b=await m.json()}catch(I){throw new Tt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:m.status,cause:I})}if(b?.type==="3ds_required"&&typeof b.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:b.nextActionRedirectUrl};if(b?.type==="paypal_redirect_required"||b?.type==="3ds_required"){let I=uc(b);if(!I)throw new Tt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:m.status});return{type:b.type,threeDSecureToken:I,paymentMethodId:b.paymentMethodId}}if(b?.gatewayErrorCode==="authentication_required"){let I=await _u({billingApiUrl:l,sessionId:u,nonce:C,responseJson:b});if(I)return I;throw Ji(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let Ve=new Tt(b?.message??"Payment failed. Please try again.","api_error",{code:b?.code??b?.gatewayErrorCode,declineCode:b?.declineCode??b?.gatewayDeclineReason,statusCode:m.status});throw Object.assign(Ve,{telemetryOutcome:bu(m.status,b)})}async function ri(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:l,telemetry:u,signal:C}){let _=t?.getRawProvider();if(!_)throw Lr(new Tt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Ji(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let k=ku(e.threeDSecureToken),O=null,ue=e.paymentMethodId,N=await ma(()=>Iu(_,e.threeDSecureToken,k),"card");if(N){if(N.error)throw Lr(new Tt(N.error.message??`Failed to retrieve 3DS ${k?"setup":"payment"} status.`,"api_error",{code:N.error.code}),"card");let Z=N.intent;!ue&&Z?.payment_method&&(typeof Z.payment_method=="string"?ue=Z.payment_method:"id"in Z.payment_method&&(ue=Z.payment_method.id??void 0))}let Ae=ue?await ma(()=>Ru(_,e.threeDSecureToken,{payment_method:ue,return_url:l??Yi(s)??window.location.href},k),"card"):null;if(Ae){if(Ae.error)throw Lr(new Tt(Ae.error.message??"3DS authentication failed.","api_error",{code:Ae.error.code}),"card");O=Ae.intent}else{let Z=await ma(()=>_.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(Z.error)throw Lr(new Tt(Z.error.message??"3DS authentication failed.","api_error",{code:Z.error.code}),"card");O=(k?Z.setupIntent:Z.paymentIntent)??null}if(O&&(O.status==="requires_capture"||O.status==="succeeded"||O.status==="processing")){let Z=await Oo({billingApiUrl:a,sessionId:i,session:s,telemetry:u,tokenizedData:{id:O.id,type:"card",threeDSecureActionResultTokenId:O.id},returnUrl:l});return Z.type==="success"?{...Z.result,paymentIntentId:Z.result.paymentIntentId??O.id,paymentMethodId:Z.result.paymentMethodId??ue}:Z.type==="next_action_required"?Do(Z,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:C}):ri(Z,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:l,telemetry:u,signal:C})}throw Lr(new Tt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let k=(n??t)?.getRawProvider();if(!k)throw Lr(new Tt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:ue}=await ma(()=>k.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(ue)throw Lr(new Tt(ue.message??"PayPal authorization failed.","api_error",{code:ue.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:O}=await ma(()=>k.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??Yi(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(O)throw Lr(new Tt(O.message??"PayPal authorization failed.","api_error",{code:O.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Tt("Unsupported payment redirect state.","api_error")}function ga(e){if(e instanceof Tt){let o=_o(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=_o(t)??t;return new Tt(n,"api_error")}function Zi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=wu(e.data.session?.vault)||ro(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 lc(e,t){return e?e.isPaypal?"paypal":"card":t&&ro(t)?"card":void 0}async function Xi({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,l]=await Promise.all([ic(e,{billingApiUrl:n,locale:o,telemetry:a}),i?ic(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);if(!s)throw new Tt("The payment provider did not initialize.","authentication_error");let u=null;return i?u=l:t&&(u=s),{flopay:s,paypalFlopay:u}}import{PaymentAPI as No,PciVaultCardCapture as Tu,toStripeAppearance as Mu}from"@flopay/js";import{buildCheckoutProcessMetadata as Au,buildProcessPaymentAvsAccount as xu,buildWalletSheetWindowMessage as Bu,COUNTRY_OPTIONS as Fu,classifyPaymentRejection as Du,clearStripePayPalReturn as Ou,computeVaultCardThemeColors as Nu,darkenHex as Lu,denyPaymentPermissionToNewFrames as zu,FloPayError as zr,filterStripeMethodsByCountryGate as Uu,getPostalCodeExample as qu,getPostalCodeLabel as ss,getStateFromPostalCode as ju,getStateLabel as Qi,getStateOptions as $u,getStripeMethodDisplayName as va,hasMatchingStripePayPalReturn as Wu,isAuthorizationOnlySession as es,isAVSFieldVisible as Jt,isMountableVaultBlock as Vu,isPostalCodeSupported as Hu,isSetupIntentClientSecret as ts,isValidEmail as Rn,isValidPostalCode as Ku,isWalletSheetRefusedForWindowSize as Gu,needsStripeMethodExplicitConfirm as pc,normalizeBeforeButtonClickError as yc,normalizeCheckoutFailureOutcome as Yu,partitionStripeMethods as Ju,randomUuidV4 as Zu,readMatchingStripePayPalContinuation as Xu,readStripeRedirectParams as Ic,resolveAVSConfig as Qu,resolveButtonsLayoutTheme as ep,resolveSetupFutureUsage as Rc,resolveTheme as tp,resolveVaultMountOptions as ns,STRIPE_PAYPAL_RESUME_KEY as np,derivePrimaryTileStyle as rp,shouldPreferWalletPopup as mc,stripeExpressMethodToOptionKey as op,stripeRedirectReturnUrl as Ec,toCssWeight as ap,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as _c}from"@flopay/shared";import{ExpressCheckoutElement as Tc,PaymentElement as ip,Elements as so,useElements as us,useStripe as ps}from"@stripe/react-stripe-js";import sp,{useCallback as Te,useContext as zo,useEffect as ft,useLayoutEffect as lp,useMemo as St,useRef as H,useState as ce}from"react";function io(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function oi(e,t){if(e)return{error:n=>e.error(io(t,n)),log:n=>e.log(io(t,n)),performance:n=>e.performance(io(t,n)),terminal:n=>e.terminal(io(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{darkenHex as Dc}from"@flopay/shared";import{Fragment as Lo,jsx as c,jsxs as Ze}from"react/jsx-runtime";var Rr="flopay_stripe_resume",fc="flopay_wallet_resume",Mc="fw1",cp="fw2",Ac=300*1e3,dp=900,up="express_checkout_click_timeout",pp=25e3,yp=25e3,mp=1e4,yr={provider:"paypal",paymentMethodCategory:"paypal"},fp="x-flopay-process-result-source",gp="status";async function hp(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 ai={},Pa=class{constructor(t){this.reason=t}};function Pp(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 ys(e){return`${cp}:${e}`}function ii(e){return rn(ys(e))}function si(e,t){if(typeof window>"u")return null;let n=ys(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>Ac||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ii(e),null):a}catch{return ii(e),null}}function vp(e){return rn(ys(e.sessionId),e)}function gc(e,t,n){let o=si(e,t);return!o||o.clientSecret!==n?!1:ii(e)}function rs(e,t,n){if(typeof window>"u")return;si(e,t)?.clientSecret===n&&ii(e)}function Cp(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function os(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let o=n?e.status==="succeeded":ia(e.status),a=Cp(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function hc(e,t,n){let o=null;try{return await Promise.race([Nl(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},mp),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function bp(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function xc(e){return e instanceof zr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function li(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new No(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw xc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var as=np,ha=new Map,Sp=250,Pc="Just a moment \u2014 we are finalizing your order. Please press pay again.",wp="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function ms(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 ci({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new No(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function kp(e){return e instanceof zr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Bc({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=la(n),s=i.firstName?i:la(o?.name);return pr({email:Rn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Ip({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=Bc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return Rn(s.email)?s:i(a,s)}var Ca=180,vc=`flopay-card-enter ${Ca}ms cubic-bezier(0, 0, 0.2, 1) both`,Cc=`flopay-card-exit ${Ca}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Rp=`flopay-buttons-enter ${Ca}ms cubic-bezier(0, 0, 0.2, 1) both`,Ep=`flopay-buttons-exit ${Ca}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function _p(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function fs(e){return rp(e)}var Tp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Mp(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 ls={width:"100%",minHeight:oa,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 bc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function cs(e){return e==="paypal"?"PayPal":va(e)}function Ap(e){let t=qu(e);return`Enter a valid ${ss(e)}${t?` (e.g. ${t})`:""}`}function xp(e,t,n){let o=Hu(e),a=t.trim(),i=n&&o,s=i&&!a,l=i&&!!a&&!Ku(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:l}}function Bp(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!Rn(n);return{required:t,empty:o,malformed:a,value:n}}function Fp(e){return typeof e=="number"?`${e}px`:e}function gs(e){return c(Np,{...e})}function Sc({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:u,onTechnicalFailure:C,runBeforeButtonClick:_,billingName:k,onBuyerIdentityReady:O,onLoadStateChange:ue,placeholderBorderRadius:N,popupCapabilityOwner:Ae,externalTelemetryContext:Z,presentationMode:m}){let b=Hr(),{emitInstrument:Ve}=zo(ir),I=ps(),Xe=us(),Y=St(()=>oi(pn(b),Z),[Z,b]),[Fe,nt]=ce("loading");ft(()=>{ue?.(Fe)},[Fe,ue]);let[ze,He]=ce(!1),It=H(!1),it=!Rn(n?.trim())||!k?.trim(),{request:te,collect:xt,finish:ut}=To(),rt=H(!1),ge=H(null),se=H(null),[fe,wt]=ce(0),[Bt,Qe]=ce(!1),ne=H(!1),Me=H(new Map),{startAttempt:de,finishAttempt:L,invalidateAttempt:Ue,isAttemptInvalidated:De,isAttemptCurrent:Oe,generationRef:M}=ua((pe,P,st)=>{C?.(pe,P,{...st,popupBlocked:st?.popupBlocked??$r(P),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:m,terminalReason:"overlay_timeout"}),Qe(!0),wt(ot=>ot+1)},{onHandoffObserved:()=>{Ae.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",...yr,attempt:M.current})}});ft(()=>{Bt&&se.current?.focus()},[Bt,fe]);let qe=Te(()=>{wt(pe=>pe+1)},[]),gt=Te((pe,P,st)=>{Ue(st),C?.("paypal",pe,{code:P,popupBlocked:$r(pe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:m}),Qe(!0),qe()},[Ue,C,m,qe]),_e=Te(()=>{window.setTimeout(()=>{(ge.current?.querySelector("iframe")??ge.current)?.focus()},0)},[]);ft(()=>{ne.current&&(ne.current=!1,_e())},[_e,fe]);let ht=Te(()=>{Qe(!1),i?.(null),_e()},[_e,i]);ft(()=>{if(!I||rt.current)return;let[pe,P,st]=Ic();if(!pe||!P)return;let ot=Xu(P);if(!ot)return;rt.current=!0;let R=!0,Se=ha.get(P);Se||(Se=st==="failed"?Promise.resolve(null):Promise.resolve().then(()=>I.retrievePaymentIntent(P)),ha.set(P,Se));let Ft={accountPatch:ot.accountPatch,sessionId:ot.sessionId,nonce:ot.nonce},ye=()=>{Y?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...yr,requestCategory:"provider_sdk"})};return Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...yr}),(async()=>{try{He(!0);let p=await Se;if(!R)return;if(p?.error){ha.delete(P),ye(),i?.(p.error.message??"Failed to retrieve PayPal payment status.");return}if(Ou(),ha.delete(P),st==="failed"){let we="PayPal payment was declined. Please try again.";Y?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}),i?.(we),u?.(Sn("paypal",we));return}let v=p?.paymentIntent;if(v&&v.id!==pe){ye(),i?.("Failed to match the returned PayPal payment.");return}if(v&&(v.status==="requires_capture"||v.status==="succeeded")){let we=typeof v.payment_method=="string"?v.payment_method:v.payment_method?.id;a({id:we??v.id,type:"card",threeDSecureActionResultTokenId:v.id,isPaypal:!0},{...Ft,presentationMode:"redirect"})}else{let we="PayPal payment was not completed. Please try again.";Y?.terminal({outcome:v?.status==="canceled"?"payment_cancelled":"payment_declined",...yr,terminalReason:v?.status==="canceled"?"cancelled":"provider_declined"}),i?.(we),u?.(Sn("paypal",we))}}catch(p){if(!R)return;ha.delete(P),ye(),i?.(p instanceof Error?p.message:"Failed to complete PayPal payment.")}finally{R&&He(!1)}})(),()=>{R=!1,rt.current=!1}},[I,a,i,u,Y]);let ve=Te(async(pe=!1)=>{let P=_?await _("paypal"):{proceed:!0};if(!P.proceed)return Me.current.delete(fe),!1;let st=de("paypal");return Me.current.set(fe,{generation:st,accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}),Qe(!1),Y?.log({name:`provider.${pe?"redirect.started":"handoff.requested"}`,stage:pe?"redirect":"overlay_open",...yr,attempt:st}),l?.("paypal"),!0},[l,Y,_,de,fe]),je=Te(async pe=>{if(s||ze||!await ve()){pe.reject();return}pe.resolve()},[s,ve,ze]),Ke=Te(async pe=>{if(!I||!Xe)return;let P=Me.current.get(fe);if(P&&!Oe(P.generation)){Me.current.delete(fe);return}if(!P&&De()||P&&!L(P.generation))return;P||L();let st=P??null;if(Me.current.delete(fe),!st&&_){let kt=await _("paypal");if(!kt.proceed){pe.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}st={accountPatch:kt.accountPatch,sessionId:kt.sessionId,nonce:kt.nonce}}let ot=st?.sessionId??e,R=st?.nonce??t,Se=await Ip({event:pe,prepared:st,email:n,billingName:k,methodLabel:"PayPal",collect:xt});if(!Se){pe.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ft=Se.email,ye={...st?.accountPatch,...pr(Se,!0)};try{if(He(!0),i?.(null),!ot||!Rn(Ft))throw new Error("Missing sessionId or email for PayPal payment");await O?.(Se);let kt=I.createPaymentMethod,{error:p,paymentMethod:v}=await kt({type:"paypal"});if(p){gt(p,"stripe_paypal_create_payment_method_failed",P?.generation),pe.paymentFailed({reason:"fail"});return}let we=await li(o,Ve,ot,R??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:v?.id??null,intentKind:"payment"});if(we.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ce=we.clientSecret,et={return_url:Ec()};if(v?.id&&(et.payment_method=v.id),!rn(as,{clientSecret:Ce,sessionId:ot,nonce:R,accountPatch:ye})&&m==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:ke,paymentIntent:Ie}=await I.confirmPayment({clientSecret:Ce,confirmParams:et,redirect:"if_required"});if(ke){if(rn(as),Na(ke)){let d=ke.message??"Your payment was declined.";Y?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}),i?.(d),u?.(Sn("paypal",d,{code:bo(ke),declineCode:Di(ke)})),await ci({billingApiUrl:o,sessionId:ot,nonce:R,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:bo(ke)??"provider_declined"}})}else gt(ke,"stripe_paypal_confirm_failed",P?.generation);return}rn(as);let Dt=typeof Ie?.payment_method=="string"?Ie.payment_method:Ie?.payment_method?.id;a({id:Dt??Ie?.id,type:"card",threeDSecureActionResultTokenId:Ie?.id,isPaypal:!0},{accountPatch:ye,paymentMethodCategory:"paypal",presentationMode:m,sessionId:ot,nonce:R});return}catch(kt){gt(kt,"stripe_paypal_failed",P?.generation)}finally{He(!1)}},[I,Xe,e,t,n,k,xt,O,o,Ve,a,i,u,_,gt,L,Oe,De,Y,m,fe]),wn=Te(async()=>{if(!(It.current||s||ze||!I||!Xe)){It.current=!0,He(!0);try{if(!await ve(!0))return;await Ke({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{It.current=!1,He(!1)}}},[Xe,Ke,s,ve,I,ze]),Et=m==="redirect"?c("button",{type:"button",disabled:s||ze,onClick:()=>{wn()},style:{width:"100%",minHeight:oa,border:"1px solid #d1d5db",borderRadius:N??8,background:"#ffc439",color:"#111827",cursor:s||ze?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):c(Tc,{onReady:pe=>nt(Oi(pe,["paypal"])),onLoadError:()=>{nt("load_error"),ms(Y,"paypal","paypal","provider_error")},onClick:je,onConfirm:Ke,onCancel:()=>{let pe=Me.current.get(fe);Me.current.delete(fe),Y?.terminal({outcome:"payment_cancelled",...yr,terminalReason:"cancelled",...pe?{attempt:pe.generation}:{}}),Ue(pe?.generation),Qe(!1),ne.current=!0,qe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:it,emailRequired:it,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},fe),Pt=Ze(Lo,{children:[Ze("div",{ref:ge,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Bt&&c("button",{ref:se,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ht,style:ls,children:"Try PayPal again"}),te&&c(Mo,{identity:te.identity,methodLabel:te.methodLabel,onComplete:ut,onCancel:()=>ut(null)},te.id),c("div",{style:{display:te?"none":void 0},children:Et})]}),ze&&!te&&c(wr,{status:"processing"})]});return m==="redirect"?Pt:c(Ni,{state:Fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:N,children:Pt})}function is(e){return e==="apple_pay"||e==="google_pay"}var Dp=200;function Op({active:e}){return lp(()=>e?zu(document):void 0,[e]),null}function wc({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:u,onDecline:C,onTechnicalFailure:_,runBeforeButtonClick:k,billingName:O,onBuyerIdentityReady:ue,onLoadStateChange:N,placeholderBorderRadius:Ae,popupCapabilityOwner:Z,externalTelemetryContext:m}){let b=Hr(),{emitInstrument:Ve}=zo(ir),I=ps(),Xe=us(),Y=St(()=>oi(pn(b),m),[m,b]),[Fe,nt]=ce("loading");ft(()=>{N?.(Fe)},[Fe,N]);let[ze,He]=ce(!1);ft(()=>{Qe.current=ze},[ze]);let It=H(!Rn(n?.trim())||!O?.trim()).current,{request:it,collect:te,finish:xt}=To(),ut=H(null),rt=H(null),[ge,se]=ce(0),[fe,wt]=ce(()=>mc()),Bt=H(fe),Qe=H(!1),[ne,Me]=ce(!1),[de,L]=ce(()=>si(e,t)?"blocked":"idle"),[Ue,De]=ce("google_pay"),Oe=H(null),M=H(!0),qe=H(!1),gt=H("google_pay"),_e=H("google_pay"),ht=H(null),ve=H(null),je=H(new Set),Ke=H(null),wn=H(null);ft(()=>(M.current=!0,()=>{M.current=!1;for(let d of je.current)window.clearTimeout(d);je.current.clear()}),[]);let Et=H(new Map),{startAttempt:Pt,finishAttempt:pe,invalidateAttempt:P,isAttemptInvalidated:st,isAttemptCurrent:ot,generationRef:R}=ua((d,xe,he)=>{_?.(d,xe,{...he,popupBlocked:he?.popupBlocked??$r(xe),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),De(d),Me(!0),se(Re=>Re+1)},{onHandoffObserved:d=>{wn.current=R.current,Z.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:R.current,...d==="apple_pay"||d==="google_pay"?{walletType:d}:{}})},defersMissingTerminal:is,onMissingTerminalDeferred:(d,xe)=>{let he=Y?.now()??globalThis.performance?.now()??Date.now(),Re=Ke.current,Q=Re?.generation===xe?Re.startedAt:he;Y?.performance({stage:"overlay_return",durationMs:Math.max(0,he-Q),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:xe,...is(d)?{walletType:d}:{}}),Y?.flush?.().catch(()=>{})}});ft(()=>{ne&&rt.current?.focus()},[ne,ge]);let Se=H(0),Ft=H(!1),ye=Te(()=>{if(Se.current>0){Ft.current=!0;return}se(d=>d+1)},[]),kt=Te(()=>{Se.current-=1,!(Se.current>0||!Ft.current)&&(Ft.current=!1,M.current&&se(d=>d+1))},[]),p=Te((d,xe,he,Re,Q=!1)=>{P(Re),_?.(d,xe,{code:he,popupBlocked:$r(xe),telemetryReported:Q,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),De(d),Me(!0),ye()},[P,_,ye]),v=Te(d=>{Y?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...is(d)?{walletType:d}:{}}),_?.(d,new Error("The wallet click was not ready within the time the wallet allows."),{code:up,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),De(d),Me(!0)},[_,Y]),we=Te(()=>{window.setTimeout(()=>{(ut.current?.querySelector("iframe")??ut.current)?.focus()},0)},[]);ft(()=>{qe.current&&(qe.current=!1,we())},[we,ge]);let Ce=Te(()=>{Me(!1),l?.(null),we()},[we,l]),et=Te(()=>{Oe.current?.()},[]);ft(()=>{let d=null,xe=()=>{d=null;let Re=mc();Re!==Bt.current&&(Bt.current=Re,wt(Re),!Qe.current&&!ot(R.current)&&ye())},he=()=>{d!==null&&window.clearTimeout(d),d=window.setTimeout(xe,Dp)};return window.addEventListener("resize",he),()=>{window.removeEventListener("resize",he),d!==null&&window.clearTimeout(d)}},[R,ot,ye]),ft(()=>{let d=si(e,t);if(!d)return;let xe=!1,he=!1,Re=async()=>{if(!he){he=!0,xe||L("checking");try{let Q=await hc(I,d.clientSecret,je.current);if(xe)return;let j=os(Q,d.providerObjectId,ts(d.clientSecret));if(j.kind==="confirmed"){if(!gc(e,t,d.clientSecret))return;Oe.current=null,L("idle"),s({id:j.paymentMethodId,type:"card",threeDSecureActionResultTokenId:j.intentId},{...d.accountPatch?{accountPatch:d.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(j.kind==="terminal"){rs(e,t,d.clientSecret),Oe.current=null,L("idle"),De(d.paymentMethodType),Me(!0),ye();return}L("blocked")}catch{xe||L("blocked")}finally{he=!1}}};return Oe.current=Re,L("blocked"),()=>{xe=!0,Oe.current===Re&&(Oe.current=null)}},[t,s,ye,e,I]);let Ge=Te(async d=>{let xe=!1,he=!1,Re=Be=>{xe||he||(xe=!0,d.paymentFailed({reason:"fail",...Be?{message:Be}:{}}))};if(!I||!Xe){Re();return}let Q=Et.current.get(ge);if(Q&&!ot(Q.generation)){Et.current.delete(ge),Re();return}if(!Q&&st()){Re();return}if(Q&&!pe(Q.generation)){Re();return}Q||(pe(),Ft.current=!1);let j=d.expressPaymentType??Q?.method??gt.current,mn=Q??null,Yn=bc(j),on;j==="apple_pay"?on="apple_pay":j==="google_pay"&&(on="google_pay");let Wt=Q?.generation??R.current,pt=Y,Fn=pt?.now()??globalThis.performance?.now()??Date.now(),En=new AbortController,Xt=!1,Un=!1,yt=null,fr=e,Vt="processing",tr="other",Dn="provider_runtime",On,an=new Promise((Be,lt)=>{On=lt}),fn=window.setTimeout(()=>{Xt=!0,En.abort(),On(ai)},pp),qn=async(Be,lt,kn)=>{Vt=Be,tr=lt,Dn=lt==="intent_create"||lt==="session_claim"?"transport_error":"provider_runtime";let Ut=pt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([kn,an])}finally{let sn=pt?.now()??globalThis.performance?.now()??Date.now();pt?.performance({stage:Be,durationMs:Math.max(0,sn-Ut),durationMode:"machine",requestCategory:lt,paymentMethodCategory:"wallet",provider:"stripe",...Xt?{statusClass:"timeout"}:{}})}};try{if(He(!0),l?.(null),!mn&&k){let ee=await qn("processing","other",k(Yn));if(!ee.proceed){Re();return}mn={accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}}let Be=mn?.sessionId??e;fr=Be;let lt=mn?.nonce??t,kn=ht.current??mn?.accountPatch,Ut=Bc({event:d,fallbackEmail:kn?.email??n,fallbackName:[kn?.firstName,kn?.lastName].join(" ").trim()||O});if(!Rn(Ut.email)){Re("Buyer details are required."),te(cs(j),Ut).then(ee=>{ee&&(ht.current=ee)});return}ht.current=null;let sn={...mn?.accountPatch,...pr(Ut,!0)};await qn("processing","session_claim",Promise.resolve(ue?.(Ut)));let{error:ln}=await qn("tokenization","provider_sdk",Xe.submit());if(ln){Re(),p(j,ln,"stripe_wallet_submit_failed",Q?.generation);return}if(!Be)throw new Error("Missing sessionId or email for payment.");let Ht={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j,paymentMethodId:null,intentKind:a},Kt=JSON.stringify({sessionId:Be,nonce:lt??"",request:Ht}),gn=ve.current,Ee=gn?.retryIdentity===Kt?gn.authorizationAttemptId:Zu();ve.current={authorizationAttemptId:Ee,retryIdentity:Kt};let hn=await qn("processing","intent_create",li(o,Ve,Be,lt??"",{...Ht,authorizationAttemptId:Ee},{signal:En.signal}));if(hn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Pn=hn.clientSecret,_r=vp({createdAt:Date.now(),sessionId:Be,...lt?{nonce:lt}:{},clientSecret:Pn,providerObjectId:hn.providerObjectId,paymentMethodType:j,accountPatch:sn});window.clearTimeout(fn),Un=!0,pt?.performance({stage:"callback",durationMs:Math.max(0,(pt?.now()??globalThis.performance?.now()??Date.now())-Fn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let _n=pt?.now()??globalThis.performance?.now()??Date.now(),Tn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...on?{walletType:on}:{},attempt:Wt},gr=!1,Jn=null;pt?.log({name:"payment.provider_confirmation.started",...Tn}),yt=window.setTimeout(()=>{yt!==null&&je.current.delete(yt),gr=!0;let ee=pt?.now()??globalThis.performance?.now()??Date.now();pt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Tn,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ee-_n),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),pt?.flush?.().catch(()=>{}),Jn?.()},yp),je.current.add(yt);let Qt=(ee,Nt)=>{yt!==null&&(window.clearTimeout(yt),je.current.delete(yt),yt=null);let U=pt?.now()??globalThis.performance?.now()??Date.now(),_t=Math.max(0,U-_n),dn=ee;gr&&(ee==="resolved"?dn="resolved_late":ee==="returned_error"?dn="returned_error_late":dn="rejected_late");let Mn=Nt??(ee==="resolved"?"approved":"provider_error");return pt?.log({name:"payment.provider_confirmation.returned",...Tn,operationOutcome:dn,terminalReason:Mn}),pt?.performance({...Tn,durationMs:_t,durationMode:"buyer",operationOutcome:dn,terminalReason:Mn}),{durationMs:_t,operationOutcome:dn,terminalReason:Mn}},X=!1,cn=!1,jn=ee=>{if(!ee||typeof ee!="object")return null;let Nt=ee;if(Nt.error)return null;let U=Nt.setupIntent??Nt.paymentIntent,_t=os(U??null,void 0,!!Nt.setupIntent);return _t.kind==="confirmed"?_t:null},$=ee=>{if(X||Q&&R.current!==Q.generation)return;let Nt=jn(ee);if(!Nt)return;if(_r&&!gc(Be,lt,Pn)){X=!0;return}let{intentId:U,paymentMethodId:_t}=Nt;X=!0,cn=!0,ve.current=null,Oe.current=null,M.current&&(L("idle"),He(!1));let dn=`${Mc}:${Be}`;rn(dn,{createdAt:Date.now(),sessionId:Be,nonce:lt,accountPatch:sn,paymentMethodId:_t,providerIntentId:U,paymentMethodType:j});try{s({id:_t,type:"card",threeDSecureActionResultTokenId:U},{accountPatch:sn,paymentMethodCategory:"wallet",sessionId:Be,nonce:lt})}finally{rn(dn)}},vt=!1;Jn=async()=>{if(!(vt||X||cn)){vt=!0,M.current&&L("checking");try{let ee=await hc(I,Pn,je.current);if(X||cn)return;let Nt=ts(Pn),U=os(ee,hn.providerObjectId,Nt);if(U.kind==="confirmed"){$(Nt?{setupIntent:ee}:{paymentIntent:ee});return}if(U.kind==="terminal"){if(cn=!0,rs(Be,lt,Pn),ve.current=null,Oe.current=null,!M.current)return;L("idle"),Re(),p(j,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Q?.generation,!0);return}M.current&&!cn&&(L("blocked"),He(!1))}catch{M.current&&!cn&&(L("blocked"),He(!1))}finally{vt=!1}}},Oe.current=Jn;let B,qt;try{he=!0,Se.current+=1;let ee;try{ee=await(ts(Pn)?I.confirmSetup({elements:Xe,clientSecret:Pn,redirect:"if_required"}):I.confirmPayment({elements:Xe,clientSecret:Pn,redirect:"if_required"}))}finally{kt()}if(!ee||typeof ee!="object")throw new Pa(Pp(ee));if(B=ee,!B.error&&!jn(B))throw new Pa("confirmation_result_unconfirmed");qt=Qt(B.error?"returned_error":"resolved",B.error&&Na(B.error)?"provider_declined":void 0)}catch(ee){let Nt=ee instanceof Pa?ee.reason:void 0,U=Nt!==void 0,_t=Qt(U?"returned_error":"rejected");if(pt?.error({...U?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Nt}:ji(ee),...Tn,operationOutcome:_t.operationOutcome,durationMs:_t.durationMs,statusClass:"unknown",terminalReason:_t.terminalReason}),!M.current||X)return;await Jn?.();return}let en=B.error;if(en){if(!M.current||X)return;if(Na(en)){cn=!0,rs(Be,lt,Pn),ve.current=null,Oe.current=null,L("idle"),Et.current.get(ge)===Q&&Et.current.delete(ge);let ee=en.message??"Your payment was declined.";l?.(ee),C?.(Sn(Yn,ee,{code:bo(en),declineCode:Di(en)})),ci({billingApiUrl:o,sessionId:Be,nonce:lt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j,providerDeclineReason:bo(en)??"provider_declined",...hn.intentKind==="payment"&&hn.providerObjectId.startsWith("pi_")?{providerIntentId:hn.providerObjectId}:{}}})}else pt?.error({...ji(en),...Tn,operationOutcome:qt.operationOutcome,durationMs:qt.durationMs,statusClass:"unknown",terminalReason:qt.terminalReason}),await Jn?.();return}if($(B),!X)throw new Error("Invalid provider returned for APM intent")}catch(Be){if(Be===ai){let lt=pt?.now()??globalThis.performance?.now()??Date.now();pt?.error({errorCode:bp(tr),stage:Vt,requestCategory:tr,paymentMethodCategory:"wallet",provider:"stripe",...on?{walletType:on}:{},operationOutcome:"watchdog_expired",checkoutSessionId:fr,durationMs:Math.max(0,lt-Fn),statusClass:"timeout",failureCategory:Dn,attempt:Wt,terminalReason:"provider_error"}),pt?.flush?.().catch(()=>{})}Re(),p(j,Be,Be===ai?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Q?.generation,Be===ai)}finally{if(window.clearTimeout(fn),yt!==null&&(window.clearTimeout(yt),je.current.delete(yt)),!Un){let Be=pt?.now()??globalThis.performance?.now()??Date.now();pt?.performance({stage:"callback",durationMs:Math.max(0,Be-Fn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Xt?{statusClass:"timeout"}:{}})}M.current&&He(!1)}},[I,Xe,e,t,n,O,te,ue,o,Ve,a,s,l,C,k,p,kt,pe,ot,st,R,Y,ge]),ke=St(()=>Sl(i),[i]),Ie=St(()=>i.map(op),[i]),Dt=St(()=>c(Tc,{onReady:d=>{nt(Oi(d,Ie))},onLoadError:d=>{nt("load_error"),ms(Y,"stripe","wallet","provider_error")},onClick:async d=>{let xe=Y?.now()??globalThis.performance?.now()??Date.now();gt.current=d.expressPaymentType,_e.current=bc(d.expressPaymentType);let he=!0,Re=window.setTimeout(()=>{he=!1,d.reject(),v(d.expressPaymentType)},dp),Q=k?await k(_e.current,{abandoned:()=>!he}):{proceed:!0};if(window.clearTimeout(Re),!he)return;if(!Q.proceed){Et.current.delete(ge),d.reject();return}let j=Pt(d.expressPaymentType);Ft.current=!1,Ke.current={generation:j,startedAt:xe},Et.current.set(ge,{generation:j,method:d.expressPaymentType,accountPatch:Q.accountPatch,sessionId:Q.sessionId,nonce:Q.nonce}),Me(!1),Y?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:j,...d.expressPaymentType==="apple_pay"||d.expressPaymentType==="google_pay"?{walletType:d.expressPaymentType}:{}}),u?.(_e.current),d.resolve()},onConfirm:Ge,onCancel:()=>{let d=Et.current.get(ge);Et.current.delete(ge);let xe=Ke.current,he=Y?.now()??globalThis.performance?.now()??Date.now();if(d&&xe?.generation===d.generation&&Gu({method:d.method,elapsedMs:he-xe.startedAt,handoffObserved:wn.current===d.generation})){Y?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:d.generation,walletType:"google_pay"}),ve.current=null,p(d.method,new Error("The browser window is too small for the Google Pay sheet."),_c,d.generation,!0);return}Y?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...d?{attempt:d.generation}:{}}),P(d?.generation),ve.current=null,Me(!1),qe.current=!0,ye()},options:{...wl,paymentMethods:ke,emailRequired:It,billingAddressRequired:It}},ge),[Ie,ke,Ge,P,u,It,p,v,ye,k,Pt,ge,Y]);return Ze(Lo,{children:[c(Ni,{state:Fe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Ae,children:Ze("div",{ref:ut,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ne&&Ze("button",{ref:rt,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ce,style:ls,children:["Try ",cs(Ue)," again"]}),de!=="idle"&&Ze("div",{role:"status","aria-live":"polite",children:[c("p",{children:"We are still confirming your payment. Check its status before trying again."}),c("button",{type:"button",onClick:et,disabled:de==="checking",style:ls,children:de==="checking"?"Checking payment status\u2026":"Check payment status"})]}),it&&c(Mo,{identity:it.identity,methodLabel:it.methodLabel,onComplete:xt,onCancel:()=>xt(null)},it.id),Ze("div",{style:{display:it||de!=="idle"?"none":void 0},children:[c(Op,{active:fe}),Dt]})]})}),ze&&c(wr,{status:"processing"})]})}function Fc(e,t,n){let o=Rc(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function ds({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:u,onDecline:C,onCancel:_,runBeforeButtonClick:k,onButtonClick:O,isProcessing:ue,submitButtonColor:N,submitButtonBorderRadius:Ae,submitButtonStyle:Z,errorText:m}){let b=Hr(),{emitInstrument:Ve}=zo(ir),I=ps(),Xe=us(),[Y,Fe]=ce(!1),nt=H(!1),[ze,He]=ce(!1),[It,it]=ce("loading"),[te,xt]=ce(""),ut=!Rn(o?.trim()),rt=!ut||Rn(te.trim()),ge=Te(async()=>{if(!I||!Xe||ue||nt.current||!ze)return;nt.current=!0,Fe(!0);let se=k?await k("card"):{proceed:!0};if(!se.proceed){nt.current=!1,Fe(!1);return}O?.("card");let fe=se.sessionId??t,wt=se.nonce??n,Bt=la(a?.trim()),Qe=pr({email:se.accountPatch?.email?.trim()||o?.trim()||te.trim(),firstName:se.accountPatch?.firstName?.trim()||Bt.firstName,lastName:se.accountPatch?.lastName?.trim()||Bt.lastName}),ne=Qe.email,Me=pr({...se.accountPatch,...Qe});try{if(u?.(null),!Rn(ne))throw new Error("A valid email address is required for payment.");await i?.(Qe);let de=await Xe.submit();if(de.error){u?.(de.error.message??"Payment failed.");return}let L=[Qe.firstName,Qe.lastName].filter(Boolean).join(" "),Ue=await I.createPaymentMethod({elements:Xe,params:{billing_details:{email:ne,...L?{name:L}:{}}}});if(Ue.error||!Ue.paymentMethod){u?.(Ue.error?.message??"Failed to create payment method.");return}let De=Ue.paymentMethod;if(!fe||!ne)throw new Error("Missing sessionId or email for payment.");let Oe=De.type||e,M=await li(s,Ve,fe,wt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Oe,paymentMethodId:null,intentKind:"payment"});if(M.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let qe=M.clientSecret;rn(Rr,{clientSecret:qe,sessionId:fe,nonce:wt,accountPatch:Me,paymentMethodId:De.id,paymentMethodType:De.type??e,gateway:"stripe"});let{error:gt,paymentIntent:_e}=await I.confirmPayment({clientSecret:qe,confirmParams:{return_url:window.location.href,payment_method:De.id},redirect:"if_required"});if(gt){rn(Rr);let je=gt.message??"Payment failed.";u?.(je),C?.(Sn("card",je,{code:gt.code})),await ci({billingApiUrl:s,sessionId:fe,nonce:wt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:gt.code??"provider_declined"}});return}let ht=_e?.status;if(!ia(ht)){rn(Rr);let je=ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";u?.(je),C?.(Sn("card",je,{code:ht??"missing_payment_intent"}));return}rn(Rr);let ve=typeof _e?.payment_method=="string"?_e.payment_method:_e?.payment_method?.id;l({id:ve??De.id,type:"card",threeDSecureActionResultTokenId:_e?.id,gateway:"stripe",paymentMethodType:De.type??e},{accountPatch:Me,paymentMethodCategory:"apm",sessionId:fe,nonce:wt})}catch(de){u?.(de instanceof Error?de.message:"Payment failed. Please try again.")}finally{nt.current=!1,Fe(!1)}},[I,Xe,ue,ze,k,O,t,n,o,a,te,i,s,Ve,e,l,u,C]);return Ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ut&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ut&&Ze("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:te,onChange:se=>xt(se.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(ip,{onReady:()=>it("ready"),onLoadError:()=>{it("load_error"),ms(pn(b),"stripe","apm")},onChange:se=>{He(!!se.complete)},options:{layout:kl,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...Rn(o?.trim())?{email:o?.trim()}:{}}}}}),c(Il,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ge()},disabled:!ze||!rt||Y||ue||It!=="ready",color:N,borderRadius:Ae,style:Z,children:Y?"Processing\u2026":`Pay with ${va(e)}`}),m&&c(xo,{margin:"0.75rem 0 0",children:m})]})}function kc({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:u,futureUseSession:C,onTokenizedBody:_,onErrorChange:k,onButtonClick:O,onDecline:ue,runBeforeButtonClick:N,onLoadStateChange:Ae,isProcessing:Z=!1,submitButtonColor:m="#4A49FF",submitButtonBorderRadius:b=8,submitButtonStyle:Ve,buttonAppearance:I,themeId:Xe,onExpandApm:Y,expandedApmMethod:Fe}){let{emitInstrument:nt}=zo(ir),[ze,He]=ce(null),[It,it]=ce(null),te=H(!1),{request:xt,collect:ut,finish:rt}=To();ft(()=>{s.length>0&&l?Ae?.("ready"):l||Ae?.("loading")},[s.length,l,Ae]);let ge=Te(async ne=>{if(!l||te.current||Z)return;te.current=!0,it(ne);let Me=N?await N("card"):{proceed:!0};if(!Me.proceed){te.current=!1,it(null);return}O?.("card");let de=Me.sessionId??e,L=Me.nonce??t,Ue=la([Me.accountPatch?.firstName,Me.accountPatch?.lastName].filter(Boolean).join(" ")||o),De=pr({email:Me.accountPatch?.email?.trim()||n?.trim(),firstName:Me.accountPatch?.firstName?.trim()||Ue.firstName,lastName:Me.accountPatch?.lastName?.trim()||Ue.lastName});if(!Rn(De.email)){it(null);let qe=await ut(va(ne),De);if(!qe){te.current=!1;return}De=qe,it(ne)}let Oe=De.email,M=pr({...Me.accountPatch,...De});try{if(k?.(null),!de||!Rn(Oe))throw new Error("Missing sessionId or email for payment.");await a?.(De);let qe=await li(i,nt,de,L??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let gt=qe.clientSecret;rn(Rr,{clientSecret:gt,sessionId:de,nonce:L,accountPatch:M,paymentMethodType:ne,gateway:"stripe"});let{error:_e,paymentIntent:ht}=await l.confirmPayment({clientSecret:gt,confirmParams:{return_url:window.location.href,payment_method_data:{type:ne,billing_details:{name:[De.firstName,De.lastName].filter(Boolean).join(" "),...Oe?{email:Oe}:{}}}},redirect:"if_required"});if(_e){rn(Rr);let Ke=_e.message??"Payment failed.";k?.(Ke),ue?.(Sn("card",Ke,{code:_e.code})),await ci({billingApiUrl:i,sessionId:de,nonce:L,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:_e.code??"provider_declined"}});return}let ve=ht?.status;if(!ia(ve)){rn(Rr);let Ke=ve==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";k?.(Ke),ue?.(Sn("card",Ke,{code:ve??"missing_payment_intent"}));return}rn(Rr);let je=typeof ht?.payment_method=="string"?ht.payment_method:ht?.payment_method?.id;_({id:je??ht?.id,type:"card",threeDSecureActionResultTokenId:ht?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:M,paymentMethodCategory:"apm",sessionId:de,nonce:L})}catch(qe){k?.(qe instanceof Error?qe.message:"Payment failed. Please try again.")}finally{te.current=!1,it(null)}},[l,Z,N,O,e,t,n,ut,i,nt,o,a,_,k,ue]),[se,fe]=ce(null),wt=Y?Fe??null:se,Bt=Te(ne=>{te.current||Z||wt&&wt!==ne||(pc(ne)?Y?Y(ne):fe(ne):ge(ne))},[wt,Z,ge,Y]),Qe=St(()=>se?Fc(u,se,C):null,[se,u,C]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:xt?c(Mo,{identity:xt.identity,methodLabel:xt.methodLabel,onComplete:rt,onCancel:()=>rt(null)},xt.id):s.map(ne=>{let Me=Fe===ne,de=It===ne,L=It!==null&&It!==ne||Fe!=null&&Fe!==ne;return Ze(sp.Fragment,{children:[c(bl,{method:ne,themeId:Xe,submitting:de,disabled:L,highlighted:Me,hasNextStep:pc(ne),onClick:()=>Bt(ne),backgroundColor:I?.backgroundColor,borderColor:I?.borderColor,textColor:I?.textColor,borderRadius:I?.borderRadius,fontFamily:I?.fontFamily}),!Y&&se===ne&&Qe&&l&&c(so,{stripe:l,options:Qe,children:c(ds,{method:ne,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:_,onErrorChange:k,onDecline:ue,onCancel:()=>fe(null),runBeforeButtonClick:N,onButtonClick:O,isProcessing:Z,submitButtonColor:m,submitButtonBorderRadius:b,submitButtonStyle:Ve})},ne)]},ne)})})}function Np({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:l,onDecline:u,onCancel:C,onTokenizedBody:_,firstName:k,lastName:O,chv:ue,className:N,submitLabel:Ae,isProcessing:Z,error:m,onErrorChange:b,showPayPal:Ve=!0,showStripe:I=!0,walletPresentation:Xe="auto",enabledPaymentMethods:Y,enabledPaymentMethodCountries:Fe,showApplePay:nt=!0,showGooglePay:ze=!0,layout:He="default",theme:It,buttonsTheme:it,buttonsStyles:te,appearance:xt,cardButtonContent:ut,cardBackButtonContent:rt,cardTitleContent:ge,showSecurityFooter:se,onButtonClick:fe,onBeforeButtonClick:wt,onBuyerIdentityReady:Bt,enableAVS:Qe,cardFieldOrder:ne,cardPreFormSlot:Me,avsLayout:de="row",country:L,zip:Ue,addressLine1:De,addressLine2:Oe,city:M,state:qe,onCountryChange:gt,onZipChange:_e,avsCheck:ht,checkoutType:ve,checkoutLayout:je,totalAmount:Ke=0,currency:wn="usd",initialCardOpen:Et=!1,directPaypal:Pt,isSubscription:pe=!1,session:P,dataAttachmentPending:st=!1,dataAttachmentRequiresIdentity:ot=!1,debug:R=!1}){let Se=Hr(),Ft=$i(),ye=zo(ur),{emitInstrument:kt}=zo(ir),p=H(null);p.current||(p.current=Wa());let v=p.current,[,we]=ce(0),Ce=H(null);Ce.current||(Ce.current=ra());let et=Ce.current,Ge=St(()=>({browser:et,capability:v,presentationMode:"popup"}),[et,v]),ke=P??ye.session,Ie=St(()=>({futureUse:ke?.futureUse,futureUseUnsupported:ke?.futureUseUnsupported}),[ke?.futureUse,ke?.futureUseUnsupported]),Dt=ke?.gateways?.paypal?.providerObjectType??Pt?.providerObjectType,d=st||ye.claimPending===!0,xe=ot||ye.claimRequiresIdentity===!0,he=d&&!xe,Re=Vl(),Q=n||Re,[j,mn]=ce(!1),[Yn,on]=ce(null),[Wt,pt]=ce(L??""),[Fn,En]=ce(Ue??""),[Xt,Un]=ce(De??""),[yt,fr]=ce(Oe??""),[Vt,tr]=ce(M??""),[Dn,On]=ce(qe??""),[an,fn]=ce(""),[qn,Be]=ce({}),lt=H(Ue??""),kn=H(L??""),Ut=H(De??""),sn=H(Oe??""),ln=H(M??""),Ht=H(qe??""),Kt=H(""),gn=H({});ft(()=>{let r=(y,T,ae,x,ie)=>{if(gn.current[y])return;let At=T?.trim();!At||At===ae.current||(ae.current=At,x(At),ie?.(At))};r("country",L,kn,pt,gt),r("zip",Ue,lt,En,_e),r("addressLine1",De,Ut,Un),r("addressLine2",Oe,sn,fr),r("city",M,ln,tr),r("state",qe,Ht,On)},[L,Ue,De,Oe,M,qe,gt,_e]);let Ee=St(()=>Qu(Qe),[Qe]),hn=Ee!==null,Pn=St(()=>es(P),[P]),_r=Vu(P?.vault),_n=!!P?.gateways?.pcivault,Tn=zl(P),Jn=!!(P?.gateways?.stripe?.enabledPaymentMethods??Y)?.includes("card")||ro(P),Qt=_r||Jn||_n,X=!!(I&&Qt&&e),[cn,jn]=ce(()=>He!=="buttons"||Et?e??null:null),[$,vt]=ce(0),B=He!=="buttons"||Et||!!e&&cn===e,qt=P?.captureMethod,en=H(Se);ft(()=>{en.current=Se},[Se]);let[ee,Nt]=ce(null);ft(()=>{if(!X||!e||!B){Nt(null);return}let r=en.current?en.current.cardCapture({sessionId:e,captureMethod:qt}):new Tu({sessionId:e,captureMethod:qt,billingApiUrl:Q,telemetry:o});return Nt({sessionId:e,captureMethod:qt,billingApiUrl:Q,telemetry:o,capture:r}),()=>{r.unmount()}},[X,e,B,qt,Q,o]);let U=X&&e&&B&&ee?.sessionId===e&&ee.captureMethod===qt&&ee.billingApiUrl===Q&&ee.telemetry===o?ee.capture:null,_t=St(()=>{let r=Wt,y=Ee?Jt(Ee.postal_code,r):!1;return xp(r,Fn,y)},[Ee,Wt,Fn]),{avsInvalid:dn,invalidAvsFields:Mn}=St(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!X||!Ee)return{avsInvalid:!1,invalidAvsFields:r};let y=Wt,T=(ie,At)=>Jt(ie,y)&&!At.trim(),ae={line1:T(Ee.address_line_1,Xt),city:T(Ee.city,Vt),state:T(Ee.state,Dn),zip:_t.empty||_t.malformed};return{avsInvalid:ae.line1||ae.city||ae.state||ae.zip,invalidAvsFields:ae}},[X,Ee,Wt,Xt,Vt,Dn,_t]),[Gt,hr]=ce(!1),[Tr,Pr]=ce(!1),[vr,Mr]=ce(!1),[qr,jr]=ce({line1:!1,city:!1,state:!1}),In=H(!1),Ar=H({email:!1,line1:!1,city:!1,state:!1,zip:!1}),nr=H(!1),Mt=Te(r=>{Ar.current[r]=!0,nr.current=!0},[]),$n=Te(r=>!In.current&&Ar.current[r],[]),Wn=Te(r=>{$n(r)&&jr(y=>y[r]?y:{...y,[r]:!0})},[$n]),[Zn,Vn]=ce(()=>ns(P?.vault,{billingApiUrl:Q,sessionId:e,nonce:t})),[Ne,un]=ce(Et&&Qt?"card":"buttons"),[tn,Hn]=ce(null),Zr=Ne==="expanding"||Ne==="card",xr=P?.gateways?.stripe&&!Tn?"stripe":void 0,lr=Te(()=>{kt?.({class:"card_surface",provider:xr})},[xr,kt]),Xn=H(null),vn=Te(r=>{Xn.current&&clearTimeout(Xn.current),Xn.current=setTimeout(()=>{Xn.current=null,r()},Ca)},[]);ft(()=>()=>{Xn.current&&clearTimeout(Xn.current)},[]);let Br=H(!1),[An,S]=ce(0),w=H(null),q=Te(()=>{lr(),jn(e??null),Br.current&&(Br.current=!1,S(r=>r+1)),vt(r=>r+1),un("expanding"),vn(()=>un("card"))},[vn,lr,e]),re=Te(()=>{un("collapsing"),vn(()=>un("buttons"))},[vn]),$e=Te(r=>{Hn(r),un("apm-expanding"),vn(()=>un("apm-form"))},[vn]),jt=Te(()=>{un("apm-collapsing"),vn(()=>{un("buttons"),Hn(null)})},[vn]);ft(()=>{He==="buttons"&&Et&&Qt&&(jn(e??null),un("card"))},[He,Et,Qt,e]);let[oe,K]=ce(null),A=H(!1),E=H(null),W=H("idle"),[be,V]=ce(!1),We=H(be);We.current=be;let[Rt,f]=ce(()=>Pt?.existingOrderId?{orderId:Pt.existingOrderId,attempts:1}:null),g=H(Rt);ft(()=>{g.current=Rt},[Rt]);let h=H(null),F=St(()=>{if(Bt||ye.claimBuyerIdentity||P?.buyerIdentified!==!1||!e||!t)return;let r=`${Q}|${e}|${t}`;h.current?.key!==r&&(h.current={key:r,claim:Ro(new No(Q,{telemetry:!1}),e,t,{...i?{userId:i}:{},...k?{firstName:k}:{},...O?{lastName:O}:{}})});let y=h.current.claim;return async T=>{await y(T)}},[Bt,ye.claimBuyerIdentity,P?.buyerIdentified,e,t,Q,i,k,O]),J=Bt??ye.claimBuyerIdentity??F,le=m??Yn,Ye=St(()=>tp(It),[It]),D=St(()=>{let r=Ye?.buttonsLayout??ep(it);return te?{...r,...te,cardButton:{...r.cardButton,...te.cardButton},cardFormContainer:{...r.cardFormContainer,...te.cardFormContainer},backButton:{...r.backButton,...te.backButton},backButtonIcon:{...r.backButtonIcon,...te.backButtonIcon},submitButton:{...r.submitButton,...te.submitButton},title:{...r.title,...te.title}}:r},[Ye,it,te]),mt=xt??Ye?.appearance,Nn=St(()=>Nu({appearance:mt,buttonsStyles:D,layout:He}),[mt,D,He]),Cn=ye.inlineSessionPatchProcessing??!1,G=(Z??j)||Cn,Le=Q.replace(/\/+$/,""),z=St(()=>qi({userId:i,email:a,firstName:k,lastName:O,country:L,zip:Ue},qn),[i,a,k,O,L,Ue,qn]),ct=[z.firstName,z.lastName].filter(r=>!!r?.trim()).join(" "),at=!Rn(z.email?.trim()),Ln=H(null);X&&Ln.current===null&&(Ln.current=at);let Ct=X&&(Ln.current??at),co=St(()=>Bp(an,Ct),[an,Ct]),uo=co.empty||co.malformed,Qn=St(()=>Se?Se.getRawProvider():null,[Se]),Es=St(()=>Ft?Ft.getRawProvider():null,[Ft]),Wo=Ke||100,po=wn.toLowerCase(),mi=St(()=>mt?Mu(mt):null,[mt]),yo=mi,_s=St(()=>{let r=mi??{},y=r.rules??{};return{...r,rules:{...y,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...y[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...y[".AccordionItemContents"]??{}}}}},[mi]),Ts=St(()=>({...Ll(Ke,ke?.captureMethod,Ie),currency:po,...yo?{appearance:yo}:null}),[Ke,po,ke?.captureMethod,Ie,yo]),fi=Rc(Ie,"paypal","paypal"),Ms=St(()=>({mode:"payment",amount:Wo,currency:po,captureMethod:"manual",...fi?{setupFutureUsage:fi}:null,...yo?{appearance:yo}:null}),[Wo,po,fi,yo]),Pe=Te(r=>{on(r),b?.(r)},[b]),As=H(0);ft(()=>{An!==As.current&&(As.current=An,Pe(null))},[An,Pe]);let gi=H(""),[xs,Gc]=ce(!1),hi=Te(()=>{Gc(!0)},[]);ft(()=>{if(!X||!Ct||!J||!xs||uo||gi.current)return;let r=pr({email:Rn(z.email?.trim())?z.email?.trim():Kt.current.trim(),firstName:z.firstName?.trim(),lastName:z.lastName?.trim()});gi.current=JSON.stringify(r),Be(y=>({...y,...r})),Promise.resolve(J(r)).catch(y=>{gi.current="",Pe(y instanceof Error?y.message:"Failed to attach buyer details.")})},[X,Ct,J,xs,uo,z.email,z.firstName,z.lastName,Pe]),ft(()=>{!X||!U||U.setCardFieldOrder?.(ne??null,Ee==null&&!Ct)},[X,U,ne,Ee,Ct]),ft(()=>{(Ne==="expanding"||Ne==="collapsing"||Ne==="apm-expanding"||Ne==="apm-collapsing")&&Pe(null)},[Ne,Pe]);let Cr=Te((r,y,T)=>{u?.(Sn(r,y,T))},[u]),Bs=H(Ne);Bs.current=Ne;let[Fs]=ce(Ha),Ds=Te(()=>{let r=Bs.current;if(He==="buttons"&&(r==="card"||r==="expanding"))return!0;let y=W.current;return y==="validation-window"||y==="processing"||We.current},[He]),Os=Te((r,y,T)=>{Fs.take(e)&&pn(Se)?.log(io({...Ge,presentationMode:T?.presentationMode??"popup"},{name:Va,stage:"recovery",reason:"other_method_active",provider:T?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:T?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[Ge,Se,Fs,e]),Pi=Te((r,y,T)=>{T?.telemetryReported||pn(Se)?.error(io({...Ge,presentationMode:T?.presentationMode??"popup"},{errorCode:y?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:T?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:T?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:T?.terminalReason??(y?"popup_blocked":"provider_error")}))},[Ge,Se]),mo=Te((r,y,T)=>{let ae=T?.popupBlocked??$r(y);if(Ds()){Pi(r,ae,T),Os(r,y,T);return}ae&&v.markBlocked()&&we(dt=>dt+1);let x=cs(r),ie=T?.code===_c?Bu(x):Oa(x,ae,et.inAppBrowser),At=bo(y),or=(At?.toLowerCase()==="error"?void 0:At)??vl(T?.code)??"external_payment_method_failed",Je=new zr(ie,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:or,popupBlocked:ae,inAppBrowser:et.inAppBrowser,appFamily:et.appFamily,popupCapability:v.current(),presentationMode:T?.presentationMode??"popup"}});Pi(r,ae,T),K(null),He==="buttons"&&(un("buttons"),Hn(null)),Pe(ie),l?.(Je),console.error("[FloPay] External payment method failed:",{method:r,code:or,popupBlocked:ae})},[et,Ds,He,l,v,Os,Pi,Pe]);ft(()=>{if(!X||!e){Vn(null);return}let r={billingApiUrl:Le,sessionId:e,nonce:t},y=ns(P?.vault,r);if(y){Vn(y);return}if(!B){Vn(null);return}let T=`${Le}\0${e}\0${t??""}`,ae=w.current;if(ae&&ae.key===T){Vn(ae.mount);return}Vn(null);let x=!0;return new No(Le).getVaultCapture(e,t).then(ie=>{if(!x)return;let At=ns(ie,r);At?.verificationRequired&&!ie.html&&(w.current={key:T,mount:At}),At?Vn(At):Pe("Failed to load the secure card form.")}).catch(ie=>{x&&Pe(ie instanceof Error?ie.message:"Failed to load the secure card form.")}),()=>{x=!1}},[X,B,$,e,P?.vault,Le,t,Pe]);let cr=H({onComplete:s,onError:l,updateError:Pe,emitDecline:Cr,resolvedAccount:z,avsConfig:Ee,avsCheckProp:ht,sessionId:e,nonce:t,baseUrl:Le,captureMethod:P?.captureMethod,paymentId:P?.paymentId,authorizationExpiresAt:P?.authorizationExpiresAt,serverSideCardGateway:Tn});cr.current={onComplete:s,onError:l,updateError:Pe,emitDecline:Cr,resolvedAccount:z,avsConfig:Ee,avsCheckProp:ht,sessionId:e,nonce:t,baseUrl:Le,captureMethod:P?.captureMethod,paymentId:P?.paymentId,authorizationExpiresAt:P?.authorizationExpiresAt,serverSideCardGateway:Tn};let vi=H(!1),Ns=Te(()=>{let r=cr.current,y=r.resolvedAccount.email?.trim(),T=Rn(y)?y:Kt.current.trim();if(!Rn(T))return null;let ae=r.resolvedAccount.firstName?.trim(),x=r.resolvedAccount.lastName?.trim(),ie=kn.current.trim()||r.resolvedAccount.country?.trim()||"",At=r.avsConfig?Jt(r.avsConfig.state,ie):!1,or=r.avsConfig?Jt(r.avsConfig.address_line_1,ie):!1,Je=r.avsConfig?Jt(r.avsConfig.postal_code,ie):!1,dt=r.avsConfig?Jt(r.avsConfig.city,ie):!1,bt=r.avsConfig?Jt(r.avsConfig.address_line_2,ie):!1,$t=or&&!At&&Je?ju(ie,(lt.current??"").trim()):null,eo=At?Ht.current:$t;return{accountData:{userId:r.resolvedAccount.userId??"",email:T,...ae?{firstName:ae}:{},...x?{lastName:x}:{},...Je&&lt.current?{zip:lt.current}:{},...dt&&ln.current?{city:ln.current}:{},...eo?{state:eo}:{},...or&&Ut.current?{addressLine1:Ut.current}:{},...bt&&sn.current?{addressLine2:sn.current}:{},...ie?{country:ie}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Jt(r.avsConfig.country,ie),postal_code:Je,address_line_1:or,address_line_2:bt,city:dt,state:At}}:{}}},[]),Ls=H(d);Ls.current=d,ft(()=>{d||le!==Pc||cr.current.updateError(null)},[d,le]),ft(()=>{!X||!U||U.setSubmitGate?.(dn||d||uo||be)},[X,U,dn,d,uo,be]),ft(()=>{if(!X||!U)return;vi.current=!1;let r=null,y=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,W.current="idle",K(null)},400)},T=U.on("submitting",()=>{hr(!0),E.current&&clearTimeout(E.current),W.current="validation-window",E.current=setTimeout(()=>{E.current=null,W.current==="validation-window"&&(W.current="processing")},Sp),K("processing");let Je=cr.current;if(!Je.sessionId||!Je.nonce)return;let dt=Ns();if(!dt){Je.updateError("Enter a valid email address."),W.current="idle",K(null);return}new No(Je.baseUrl).patchAccountSnapshot(Je.sessionId,Je.nonce,dt,{telemetryMode:"best_effort"}).catch(bt=>{if(!kp(bt))return;let $t=bt instanceof Error?bt.message:"Please check your billing address and try again.";Je.updateError($t),W.current="idle",K(null),Je.onError?.(bt instanceof zr?bt:new zr($t,"api_error"))})}),ae=U.on("complete",Je=>{Bo(Je.sessionId??cr.current.sessionId),W.current="terminal",V(!1),K("success"),setTimeout(()=>{if(vi.current)return;vi.current=!0;let dt=cr.current,bt=es(dt)||Je.outcome==="authorized",$t=dt.serverSideCardGateway?{}:{paymentIntentId:Je.intentId};cr.current.onComplete?.(bt?{status:"authorized",...$t,paymentId:Je.paymentId??dt.paymentId,sessionId:Je.sessionId??dt.sessionId,authorizationExpiresAt:Je.authorizationExpiresAt??dt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...$t,checkoutMethod:"card"})},600)}),x=U.on("decline",Je=>{let dt=cr.current,bt=Je.message??"Your payment was declined. Please try another card or contact your bank.";W.current="terminal",V(!1),dt.updateError(bt),K("error");let $t=Je.failureOutcome??Yu(Je.declineReason)??"authorization_declined";dt.emitDecline("card",bt,{code:$t,declineCode:$t}),y()}),ie=U.on("error",Je=>{let dt=cr.current,bt=Je.message??"There was a problem processing your payment. Please try again.";W.current="terminal",V(!1),dt.updateError(bt),K("error"),dt.onError?.(new zr(bt,"api_error",{code:Je.failureOutcome??"capture_failed"})),y()}),At=U.on("challenge_dismissed",()=>{E.current&&(clearTimeout(E.current),E.current=null),W.current="processing",V(!0),K(null)}),or=U.on("blocked",()=>{if(We.current){cr.current.updateError(wp);return}if(!Ls.current){hr(!0);return}hi(),cr.current.updateError(Pc)});return()=>{r&&(clearTimeout(r),r=null),E.current&&(clearTimeout(E.current),E.current=null),W.current="idle",V(!1),K(null),T(),ae(),x(),ie(),At(),or()}},[X,U,hi,Ns]);let br=!!Pt?.clientId,Vo=Array.isArray(Y),Ia=Vo&&Y.length>0,zs=Vo&&Y.includes("paypal"),Ra=H(null);Ra.current===null&&(Ra.current=Wu());let fo=Ra.current?"redirect":Cl(et,Xe,v.current()),{expressMethods:Ea,paymentElementMethods:Ci}=St(()=>Ju(Y,{excludePaypal:br}),[Y,br]),Us=br||!!Ft||zs&&fo==="redirect",Yc=St(()=>Us?Ea.filter(r=>r!=="paypal"):Ea,[Ea,Us]),Jc=St(()=>{let r=[];return nt&&r.push("apple_pay"),ze&&r.push("google_pay"),r},[nt,ze]),go=Vo?Yc:Jc,Zc=I&&go.length>0,qs=hn?Wt:L,_a=St(()=>Uu(Ci,qs,Fe),[Ci,qs,Fe]),bi=St(()=>({mode:"payment",amount:Wo,currency:po,paymentMethodCreation:"manual",appearance:_s}),[Wo,po,_s]),[js,$s]=ce("loading"),[Ws,Vs]=ce("loading"),[Hs,Ks]=ce("loading"),[Xc,Si]=ce(!1),[Gs,wi]=ce("loading"),[ki,Qc]=ce();ft(()=>{Qc(ra())},[]);let Ta=ki?.inAppBrowser,Ma=ki?La(ki,Pt?.approvalPresentation,Dt??(pe?"subscription":"order")):"popup",Ys=Ve&&(br||(Vo?zs:Ta===!1)),ed=et.inAppBrowser&&v.current()==="blocked",Js=I&&Zc&&!ed,Ho=(!he||!!ye.waitForDataAttachment)&&Ys&&br,Zs=Gs==="retrying"||Gs==="exhausted",Ko=null;I&&(Ft?Ko=Es:fo==="redirect"&&(Ko=Qn));let Xs=St(()=>({...Ge,presentationMode:fo}),[Ge,fo]),Go=!he&&Ys&&!!Ko&&(!br||Zs),ho=!he&&Js&&!!Qn,Yo=!he&&I&&Ia&&_a.length>0&&!!Qn,td=Ho&&!Zs?Xc:Go&&Li(js),nd=ho&&Li(Ws),rd=Yo&&Hs!=="load_error",Qs=r=>r==="loading"||r==="ready",el=Ho||Go&&Qs(js)||ho&&Qs(Ws)||Yo&&Hs!=="load_error",Aa=H(!1);ft(()=>{if(!Aa.current){if(!I&&!Ve){Aa.current=!0;let r=new zr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(r),Pe(r.message)}else if(!I&&Ve&&!br){Aa.current=!0;let r=new zr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(r),Pe(r.message)}else if(Ta!==void 0&&!he&&!Qt&&!el){Aa.current=!0;let r=new zr("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"});l?.(r),Pe(r.message)}}},[I,Ve,br,Ta,he,Qt,el,l,Pe]);let tl=H(!1);ft(()=>{if(tl.current||!Ia)return;let r=[];nt!==!0&&r.push("showApplePay"),ze!==!0&&r.push("showGooglePay"),r.length!==0&&(tl.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.`))},[Ia,nt,ze]);let nl=Te((r,y,T)=>ye.applyInlineSessionPatch?ye.applyInlineSessionPatch(r).then(ae=>({error:null,sessionId:ae.sessionId||e,nonce:ae.session?.clientSecret||t})).catch(ae=>{let x=yc(y,ae);return T?.abandoned?.()||(Pe(x.message),l?.(x)),{error:x,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ye.applyInlineSessionPatch,t,l,e,Pe]),dr=Te(async(r,y)=>{if(r!=="card"&&he&&await ye.waitForDataAttachment?.(),!wt)return{proceed:!0};try{let T=await wt({method:r,sessionId:e||void 0,createSession:ye.inlineSessionDraft});if(T===!1)return{proceed:!1};if(T&&typeof T=="object"){T.account&&Be(x=>({...x??{},...T.account}));let ae=await nl(T,r,y);return ae.error?{proceed:!1,accountPatch:T.account}:{proceed:!0,accountPatch:T.account,sessionId:ae.sessionId,nonce:ae.nonce}}return{proceed:!0}}catch(T){if(!y?.abandoned?.()){let ae=yc(r,T);Pe(ae.message),l?.(ae)}return{proceed:!1}}},[nl,ye.inlineSessionDraft,ye.waitForDataAttachment,he,wt,l,e,Pe]),rl=Te(async(r,y)=>{if(A.current)return;A.current=!0,mn(!0),K("processing"),Pe(null);let T=y?.sessionId??e,ae=y?.nonce??t,x=qi(z,y?.accountPatch),ie=y?.completionPaymentMethodId??sa(r),At=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,or=_p(r),Je=y?.presentationMode?oi(pn(Se),{...Ge,presentationMode:y.presentationMode}):void 0,dt=()=>{kt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:or}),Je?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...yr,requestCategory:"process_payment"})};try{let bt=new No(Le),$t=await bt.processPayment(x.userId??"",{sessionId:T,nonce:ae,paymentMethodCategory:y?.paymentMethodCategory??Mp(r),tokenizedData:At,accountData:{...y?.accountPatch,userId:x.userId??"",email:x.email??"",firstName:x.firstName||void 0,lastName:x.lastName||void 0,...xu({avsConfig:Ee,country:kn.current,zip:lt.current,city:ln.current,state:Ht.current,addressLine1:Ut.current,addressLine2:sn.current})},...Au({chv:ue,avsCheck:ht,checkoutType:ve,checkoutLayout:je,avsConfig:Ee,country:kn.current})}),eo=async bn=>{let to=es(P)||bn?.status==="authorized";Bo(T),Je?.terminal({outcome:"payment_succeeded",...yr}),K("success"),f(null),await new Promise(ta=>setTimeout(ta,600));let Sr;typeof bn?.paymentId=="string"?Sr=bn.paymentId:P?.paymentId&&(Sr=P.paymentId);let no;typeof bn?.authorizationExpiresAt=="string"?no=bn.authorizationExpiresAt:P?.authorizationExpiresAt&&(no=P.authorizationExpiresAt),s?.(to?{status:"authorized",...Sr===void 0?{}:{paymentId:Sr},sessionId:typeof bn?.sessionId=="string"?bn.sessionId:T,...no===void 0?{}:{authorizationExpiresAt:no},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ie,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ie,checkoutMethod:r.isPaypal?"paypal":"card"})};if($t.ok){await eo($t.status===204?null:await $t.json().catch(()=>null));return}let er=await $t.json().catch(()=>null);if(er?.type==="paypal_redirect_required"){let bn=er.threeDSecureToken,to=er.paymentMethodId||r.id||"";if(!Se||!bn){K("error"),Pe("PayPal authorization required but no token provided.");return}try{let Sr=Ft?.getRawProvider();if(!Sr){Pe("PayPal is not available.");return}let no={return_url:window.location.href};to&&(no.payment_method=to);let{error:ta}=await Sr.confirmPayment({clientSecret:bn,confirmParams:no,redirect:"if_required"});if(ta){K("error");let fl=ta.message??"PayPal payment failed.";Pe(fl),Cr("paypal",fl,{code:ta.code})}}catch(Sr){K("error"),Pe(Sr instanceof Error?Sr.message:"PayPal authorization failed.")}return}if(er?.type==="paypal_direct_required"){let bn=er.orderId;if(!bn){K("error"),Pe("PayPal retry required but no order id provided.");return}let to=g.current?.attempts??0;if(to>=2){K("error"),Pe("PayPal payment could not be completed after multiple attempts."),Cr("paypal","paypal_direct_required retry limit exceeded");return}Si(!1),wi("loading"),f({orderId:bn,attempts:to+1}),K(null);return}if($t.headers.get(fp)===gp){let bn=await hp(bt,T,ae);if(bn!==void 0){await eo(bn);return}}Du($t.status,er)?Je?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}):dt(),K("error");let ml=er?.message??"Payment failed. Please try again.";Pe(ml),Cr(r.isPaypal?"paypal":"card",ml,{code:er?.code??er?.gatewayErrorCode,declineCode:er?.declineCode??er?.gatewayDeclineReason}),await new Promise(bn=>setTimeout(bn,400))}catch(bt){xc(bt)||dt(),K("error"),Pe(bt instanceof Error?bt.message:"An unexpected error occurred"),await new Promise($t=>setTimeout($t,400))}finally{mn(!1),K(null),A.current=!1}},[Le,e,t,z,Ee,ht,ve,je,ue,Se,Ft,P,s,Pe,Cr,kt,Ge]),Kn=Te((r,y)=>{_?_(r):rl(r,y)},[_,rl]),Jo=`${Mc}:${e}`;ft(()=>{if(typeof window>"u")return;let r=localStorage.getItem(Jo);if(!r)return;let y;try{y=JSON.parse(r)}catch{rn(Jo);return}if(!y||typeof y.createdAt!="number"||Date.now()-y.createdAt<0||Date.now()-y.createdAt>Ac||typeof y.paymentMethodId!="string"||typeof y.providerIntentId!="string"||typeof y.paymentMethodType!="string"||y.sessionId!==e||!t||y.nonce!==t||!go.includes(y.paymentMethodType)){rn(Jo);return}rn(Jo),Kn({id:y.paymentMethodId,type:"card",threeDSecureActionResultTokenId:y.providerIntentId,gateway:"stripe",paymentMethodType:y.paymentMethodType},{...y.accountPatch?{accountPatch:y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Kn,t,e,Jo,go]);let ol=H(!1);ft(()=>{if(typeof window>"u"||ol.current)return;let[r,y,T]=Ic();if(!r||!y||Ra.current||!Se)return;let ae=Se.getRawProvider();if(!ae)return;let x=dt=>{let bt=localStorage.getItem(dt);if(!bt)return null;try{return JSON.parse(bt)}catch{return rn(dt),null}},ie=x(Rr)??x(fc),At;if(ie?.clientSecret){if(ie.clientSecret!==y)return;At={...ie.accountPatch?{accountPatch:ie.accountPatch}:{},...ie.sessionId?{sessionId:ie.sessionId}:{},...ie.nonce?{nonce:ie.nonce}:{}}}else if(ie?.sessionId&&ie.sessionId!==e)return;ol.current=!0,rn(Rr),rn(fc),window.history.replaceState({},"",Ec());let or=ie?.paymentMethodType??ie?.tokenType??"card",Je="card";(async()=>{if(T==="failed"){let Fr="Payment was declined. Please try again.";Pe(Fr),Cr(Je,Fr);return}let{paymentIntent:dt,error:bt}=await ae.retrievePaymentIntent(y);if(bt){let Fr=bt.message??"Failed to retrieve payment status.";Pe(Fr),Cr(Je,Fr,{code:bt.code});return}let $t=dt?.status,eo=ia($t);if(!dt||!eo){let Fr=$t==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Pe(Fr),Cr(Je,Fr,{code:$t??"missing_payment_intent"});return}let er=typeof dt.payment_method=="string"?dt.payment_method:dt.payment_method?.id;Kn({id:er??ie?.paymentMethodId??ie?.tokenId??dt.id,type:"card",threeDSecureActionResultTokenId:dt.id,gateway:ie?.gateway??"stripe",paymentMethodType:or},At)})()},[e,Kn,Se,Pe,Cr]);let Ii=Te(r=>{r.preventDefault()},[]);if(!(X||Se!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Zo=He==="buttons",Gn=mt?.variables,od=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ri=Gn?.colorBackground,ad=Ri&&!od.has(Ri)?Ri:void 0,Xo=D.cardInputBorder??(Zo?"#e5e7eb":"#A4A4FF"),al=Gn?.colorDanger??"#dc2626",Yt=r=>Mn[r]&&(qr[r]||Gt),xa=uo&&(vr||Gt),rr=r=>r?al:Xo,Ba=(_t.malformed||_t.empty)&&(Tr||Gt),id=rr(Ba),Ei=D.cardFormContainer?.backgroundColor??ad??(Zo?"white":"#EDEDFF"),Po=D.cardInputBackground??Gn?.colorBackground??"white",_i=So(rt),il=So(ge),vo=D.nameInput,sl=D.cardInputFontSize??Fp(vo?.fontSize)??Gn?.fontSizeBase??"16px",ll=typeof vo?.fontFamily=="string"?vo.fontFamily:Gn?.fontFamily??"Poppins, sans-serif",cl=ap(vo?.fontWeight)??400,sd=D.cardInputColor??(typeof vo?.color=="string"?vo.color:void 0)??Gn?.colorText??"#262833",ld=D.cardInputPlaceholderColor??"#9ca3af",nn=Gn?.borderRadius??"8px",Xr=Gn?.borderRadius??D.cardButton?.borderRadius??nn,Qr=Gn?.colorPrimary??"#4A49FF",cd=Gn?.colorPrimaryHover??Lu(Qr,.12),Ti=Gn?.colorText??"#262833",Mi={fontSize:sl,fontFamily:ll,fontWeight:cl,color:sd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Qo={marginTop:"0.375rem",...Mi,fontSize:"0.75rem",lineHeight:1.4,color:al},dd={"--flopay-input-placeholder-color":ld,"--flopay-input-font-size":sl,"--flopay-input-font-family":ll,"--flopay-input-font-weight":String(cl)},ea=D.cardFormContainer??{},Ai=ea.padding??(Zo?"0":"1rem"),xi=ea.borderRadius??nn,ud=U&&Zn?c(Bi,{capture:U,html:Zn.html,messageToken:Zn.messageToken,expectedOrigin:Zn.expectedOrigin,verificationRequired:Zn.verificationRequired,theme:Nn,submitLabel:Ae,onReady:()=>{if(!Ct&&!Ee||typeof document>"u")return;let r=()=>{let T=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(T){In.current=!0;try{T.focus()}finally{In.current=!1}}};nr.current||r()},onError:r=>{r&&Zn.verificationRequired&&W.current==="idle"&&(Br.current=!0),Pe(r)},onValidation:r=>{let y=W.current;(y==="idle"||y==="validation-window")&&(Pe(r),r&&W.current==="validation-window"&&(E.current&&(clearTimeout(E.current),E.current=null),W.current="idle",K(null)))}},An):c("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"}),dl=Ze("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&lr()},style:{backgroundColor:Ei,borderRadius:xi,...ea,padding:Ai,...dd,display:"flex",flexDirection:"column"},children:[c("style",{children:`
5
5
  .flopay-shared-input::placeholder {
6
6
  color: var(--flopay-input-placeholder-color);
7
7
  opacity: 1;
@@ -9,13 +9,13 @@ ${ke.join(`
9
9
  font-family: var(--flopay-input-font-family);
10
10
  font-weight: var(--flopay-input-font-weight);
11
11
  }
12
- `}),Go&&Yr&&Ge("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:K?-2:0},children:[Ge("button",{type:"button",onClick:Q,style:{display:"inline-flex",alignItems:"center",gap:ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:g.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...g.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",...g.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(Co,{content:tt})]}),Qs?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:g.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...g.title},children:d(na,{content:fe})})]}),!Go&&!Qs&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ii,order:K?-3:0,...g.title},children:d(na,{content:fe})}),K&&Te&&d("div",{style:{order:-2,width:"100%"},children:Te}),K&&zr&&Ge("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[d("div",{style:{backgroundColor:mo,border:`1px solid ${Qn(Ta)}`,borderRadius:Xt,padding:"10px"},children:d("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:tn,onChange:r=>{_t("email"),Cn.current=r.target.value,fn(r.target.value)},onPointerDown:()=>_t("email"),onKeyDown:()=>_t("email"),onBlur:()=>{Vn("email")&&Lr(!0),io||mi()},disabled:z,required:!0,"aria-invalid":Ta||void 0,"aria-describedby":Ta?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ri}})}),Ta&&d("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Jo,children:di.empty?"Email address is required":"Enter a valid email address"})]}),Ie&&d("div",{style:{order:K?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=qt,h=(F=!1)=>({backgroundColor:mo,border:`1px solid ${Qn(F)}`,borderRadius:Xt,marginTop:"0.5rem",padding:"10px"}),U=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ri}),te=Ou(r);return Ge(Do,{children:[Kt(Ie.address_line_1,r)&&Ge(Do,{children:[d("div",{style:h(Vt("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:Yt,onChange:F=>{_t("line1"),on.current.addressLine1=!0,$t.current=F.target.value,Nn(F.target.value)},onPointerDown:()=>_t("line1"),onKeyDown:()=>_t("line1"),onBlur:()=>Kn("line1"),disabled:z,required:!0,"aria-invalid":Vt("line1")||void 0,"aria-describedby":Vt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:U()})}),Vt("line1")&&d("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Jo,children:"Street address is required"})]}),Kt(Ie.address_line_2,r)&&d("div",{style:h(),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:mt,onChange:F=>{on.current.addressLine2=!0,dn.current=F.target.value,mr(F.target.value)},disabled:z,"data-testid":"flopay-address-line2",style:U()})}),(Kt(Ie.city,r)||Kt(Ie.state,r))&&Ge("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Kt(Ie.city,r)&&d("div",{style:{flex:1,backgroundColor:mo,borderTop:`1px solid ${Qn(Vt("city"))}`,borderRight:`1px solid ${Qn(Vt("city"))}`,borderBottom:`1px solid ${Qn(Vt("city"))}`,borderLeft:`1px solid ${Qn(Vt("city"))}`,padding:"10px",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,...Kt(Ie.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Xt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:jt,onChange:F=>{_t("city"),on.current.city=!0,Wt.current=F.target.value,Zn(F.target.value)},onPointerDown:()=>_t("city"),onKeyDown:()=>_t("city"),onBlur:()=>Kn("city"),disabled:z,required:!0,"aria-invalid":Vt("city")||void 0,"aria-describedby":Vt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:U()})}),Kt(Ie.state,r)&&d("div",{style:{flex:1,backgroundColor:mo,borderTop:`1px solid ${Qn(Vt("state"))}`,borderRight:`1px solid ${Qn(Vt("state"))}`,borderBottom:`1px solid ${Qn(Vt("state"))}`,borderLeft:`1px solid ${Qn(Vt("state"))}`,padding:"10px",borderTopRightRadius:Xt,borderBottomRightRadius:Xt,...Kt(Ie.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Qn(Vt("state")||Vt("city"))}`}:{borderRadius:Xt}},children:te?Ge("select",{id:"flopay-billing-state",name:"billing-state",value:An,onChange:F=>{_t("state"),on.current.state=!0,rn.current=F.target.value,xn(F.target.value)},onPointerDown:()=>_t("state"),onKeyDown:()=>_t("state"),onBlur:()=>Kn("state"),disabled:z,autoComplete:"billing address-level1",required:!0,"aria-invalid":Vt("state")||void 0,"aria-describedby":Vt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...U(),cursor:"pointer"},children:[d("option",{value:"",children:Yi(r)}),te.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:Yi(r),autoComplete:"billing address-level1",value:An,onChange:F=>{_t("state"),on.current.state=!0,rn.current=F.target.value,xn(F.target.value)},onPointerDown:()=>_t("state"),onKeyDown:()=>_t("state"),onBlur:()=>Kn("state"),disabled:z,required:!0,"aria-invalid":Vt("state")||void 0,"aria-describedby":Vt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:U()})})]}),Vt("city")&&d("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Jo,children:"City is required"}),Vt("state")&&Ge("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Jo,children:[Yi(r)," is required"]}),(Kt(Ie.country,r)||Kt(Ie.postal_code,r))&&Ge("div",{style:{display:"flex",flexDirection:oe==="column"?"column":"row",gap:oe==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Kt(Ie.country,r)&&d("div",{style:{flex:oe==="row"?1:void 0,backgroundColor:mo,borderTop:`1px solid ${Yo}`,borderRight:`1px solid ${Yo}`,borderBottom:`1px solid ${Yo}`,borderLeft:`1px solid ${Yo}`,padding:"10px",...oe==="row"&&Kt(Ie.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,borderRight:"none"}:{borderRadius:Xt}},children:Ge("select",{id:"flopay-billing-country",name:"billing-country",value:qt,onChange:F=>{on.current.country=!0,nn.current=F.target.value,yt(F.target.value),gt?.(F.target.value),rn.current="",xn("")},disabled:z,autoComplete:"billing country","data-testid":"flopay-country",style:{...U(),cursor:"pointer"},children:[qt===""?d("option",{value:"",children:"Select country"}):null,Eu.map(F=>Ge("option",{value:F.code,children:[F.flag," ",F.name]},F.code))]})}),Kt(Ie.postal_code,r)&&d("div",{style:{flex:oe==="row"?1:void 0,backgroundColor:mo,border:`1px solid ${Qc}`,padding:"10px",...oe==="row"&&Kt(Ie.country,r)?{borderRadius:"0",borderTopRightRadius:Xt,borderBottomRightRadius:Xt}:{borderRadius:Xt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:rs(qt),autoComplete:"billing postal-code",value:Mn,onChange:F=>{_t("zip"),on.current.zip=!0,ot.current=F.target.value,kn(F.target.value),_e?.(F.target.value)},onPointerDown:()=>_t("zip"),onKeyDown:()=>_t("zip"),onBlur:()=>{Vn("zip")&&gr(!0)},disabled:z,required:Et.required,"aria-invalid":Ma||void 0,"aria-describedby":Ma?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:U()})})]}),Ma&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Jo,children:Et.empty?`${rs(r)} is required`:kp(r)})]})})()}),K&&od,at&&d(_o,{margin:"0.75rem 0",styleOverride:g.errorBanner,children:at})]}),Aa={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"},ol=r=>_?!He||!Cr?d("pre",{"data-testid":r,style:Aa,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":r,style:Aa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${He}`,` directPaypalConfigured=${Cr}`,` inAppBrowserDetected=${String(Ra)}`,` shouldRenderDirectPayPal=${$o}`,` shouldRenderStripePayPal=${Ho}`,` hasPaypalStripeInstance=${!!ks}`].join(`
13
- `)}):null,al=r=>_?!R||!Yn?d("pre",{"data-testid":r,style:Aa,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":r,style:Aa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${R}`,` currency=${vn}`,` amountInCents=${qo}`,` enabledPaymentMethods: ${JSON.stringify(H??[])}`,` enabledPaymentMethodsProvided=${jo}`,` hasEnabledMethods=${Sa}`,` expressMethods: ${JSON.stringify(ka)}`,` walletExpressMethods: ${JSON.stringify(po)}`,` paymentElementMethods: ${JSON.stringify(gi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ia)}`,` hasStripeInstance=${!!Yn}`,` shouldRenderWallets=${yo}`,` shouldRenderPaymentElement=${Vo}`].join(`
14
- `)}):null,il=Xe==="apm-expanding"||Xe==="apm-form"||Xe==="apm-collapsing",go;Xe==="apm-expanding"?go=pc:Xe==="apm-collapsing"&&(go=yc);let xa=ln?Ec(hi,ln,we):null;if(et==="buttons"){let r=Xe==="buttons"||Xe==="expanding"||Xe==="apm-expanding",h=Xe==="expanding"||Xe==="card"||Xe==="collapsing",U=pt===void 0?{boxSizing:"border-box",height:ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"},te;Xe==="expanding"||Xe==="apm-expanding"?te=Cp:(Xe==="collapsing"||Xe==="apm-collapsing")&&(te=vp);let F;return Xe==="expanding"?F=pc:Xe==="collapsing"&&(F=yc),Ge("form",{onSubmit:bi,className:N,noValidate:!0,style:{position:"relative"},children:[d(Oa,{}),ye&&d(Sr,{status:ye,errorMessage:at,authorized:an}),Ge("div",{style:{display:"grid"},children:[Ge("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!te?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!te?Sp:{},...te?{animation:te,pointerEvents:"none"}:{}},children:[ol("flopay-direct-paypal-gate-debug"),al("flopay-stripe-gate-debug"),$o&&Pt&&Ge(Do,{children:[ee&&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(sa.Provider,{value:v,children:d(Wa,{sessionId:e,nonce:t,billingApiUrl:G,email:J.email,billingName:Mr||void 0,onBuyerIdentityReady:Fe,clientId:Pt.clientId,environment:Pt.environment,currency:vn.toUpperCase(),isSubscription:le,providerObjectType:Ft,approvalPresentation:Ea==="popup"?void 0:Ea,onTokenizedBody:jn,onComplete:s,onErrorChange:he,onDecline:y,onCancel:C,onTechnicalFailure:co,onButtonClick:pe,runBeforeButtonClick:cr,isProcessing:z,onLoadStateChange:Pi,onInitializationStateChange:vi,session:be,existingOrderId:ee?.orderId,debug:_},ee?.orderId??"fresh")})]}),Ho&&d(oo,{stripe:Wo,options:Es,children:d(fc,{sessionId:e,nonce:t,email:J.email,billingName:Mr||void 0,onBuyerIdentityReady:Fe,billingApiUrl:G,onTokenizedBody:jn,onErrorChange:he,isProcessing:z,onButtonClick:pe,onDecline:y,onTechnicalFailure:co,runBeforeButtonClick:cr,onLoadStateChange:Os,placeholderBorderRadius:Jr,popupCapabilityOwner:v,externalTelemetryContext:Hs,presentationMode:uo})}),yo?d(oo,{stripe:Yn,options:Rs,children:d(gc,{sessionId:e,nonce:t,email:J.email,billingName:Mr||void 0,onBuyerIdentityReady:Fe,billingApiUrl:G,intentKind:Ve>0?"payment":"setup",expressMethods:po,onTokenizedBody:jn,onErrorChange:he,onButtonClick:pe,onDecline:y,onTechnicalFailure:co,runBeforeButtonClick:cr,onLoadStateChange:Ls,placeholderBorderRadius:Jr,popupCapabilityOwner:v,externalTelemetryContext:rt})}):null,!yo&&$s?d("div",{style:{height:ta,borderRadius:Jr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Vo&&d(hc,{sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Fe,billingApiUrl:G,paymentElementMethods:Ia,stripeInstance:Yn,paymentElementBaseOptions:hi,futureUseSession:we,onTokenizedBody:jn,onErrorChange:he,onButtonClick:pe,onDecline:y,runBeforeButtonClick:cr,onLoadStateChange:Us,isProcessing:z,submitButtonColor:Zr,submitButtonBorderRadius:Xt,submitButtonStyle:g.submitButton,onExpandApm:ct,expandedApmMethod:ln,themeId:kt,buttonAppearance:{backgroundColor:g.cardButton?.backgroundColor,borderColor:g.cardInputBorder,textColor:g.cardButton?.color,borderRadius:Jr}}),K&&d("button",{type:"button",onClick:async()=>{z||!(await cr("card")).proceed||(pe?.("card"),D())},disabled:z,style:{width:"100%",...U,...g.cardButton,...us({themeBundle:dt,resolvedPrimaryColor:Zr,resolvedBorderRadius:Xt,submitButtonStyle:g.submitButton,explicitPrimaryColor:$n?.colorPrimary}),fontSize:g.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:z?"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:z?.6:1},onMouseEnter:ne=>{!z&&(dt||$n?.colorPrimary)&&(ne.currentTarget.style.backgroundColor=nd)},onMouseLeave:ne=>{(dt||$n?.colorPrimary)&&(ne.currentTarget.style.backgroundColor=Zr)},onMouseDown:ne=>{ne.currentTarget.style.transform="scale(0.985)"},onMouseUp:ne=>{ne.currentTarget.style.transform="scale(1)"},children:d(vo,{content:pt})}),at&&Xe==="buttons"&&d(_o,{margin:"0.25rem 0",styleOverride:g.errorBanner,children:at})]}),K&&h&&d("div",{style:{gridArea:"1 / 1",...F?{animation:F}:{},...Xe==="collapsing"?{pointerEvents:"none"}:{}},children:rl}),R&&il&&ln&&xa&&Yn&&d("div",{style:{gridArea:"1 / 1",...go?{animation:go}:{},...Xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ge("div",{style:{backgroundColor:wi,borderRadius:_i,...Zo,padding:Ei},children:[Ge("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ge("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Zt,style:{display:"inline-flex",alignItems:"center",gap:ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:g.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...g.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",...g.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(Co,{content:tt})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:g.titleFontSize??"1.05rem",color:Ii,paddingRight:80,...g.title},children:`Pay with ${ga(ln)}`})]}),d(oo,{stripe:Yn,options:xa,children:d(is,{method:ln,sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Fe,billingApiUrl:G,onTokenizedBody:jn,onErrorChange:he,onDecline:y,onCancel:Zt,runBeforeButtonClick:cr,onButtonClick:pe,isProcessing:z,submitButtonColor:Zr,submitButtonBorderRadius:Xt,submitButtonStyle:g.submitButton,errorText:at})},ln)]})})]})]})}return il&&ln&&xa&&Yn&&R?Ge("form",{onSubmit:bi,className:N,noValidate:!0,style:{position:"relative"},children:[d(Oa,{}),ye&&d(Sr,{status:ye,errorMessage:at,authorized:an}),d("div",{style:{...go?{animation:go}:{},...Xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ge("div",{style:{backgroundColor:wi,borderRadius:_i,...Zo,padding:Ei},children:[Ge("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ge("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Zt,style:{display:"inline-flex",alignItems:"center",gap:ki?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:g.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...g.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",...g.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(Co,{content:tt})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:g.titleFontSize??"1.05rem",color:Ii,paddingRight:80,...g.title},children:`Pay with ${ga(ln)}`})]}),d(oo,{stripe:Yn,options:xa,children:d(is,{method:ln,sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Fe,billingApiUrl:G,onTokenizedBody:jn,onErrorChange:he,onDecline:y,onCancel:Zt,runBeforeButtonClick:cr,onButtonClick:pe,isProcessing:z,submitButtonColor:Zr,submitButtonBorderRadius:Xt,submitButtonStyle:g.submitButton,errorText:at})},ln)]})})]}):Ge("form",{onSubmit:bi,className:N,noValidate:!0,style:{position:"relative"},children:[d(Oa,{}),ye&&d(Sr,{status:ye,errorMessage:at,authorized:an}),Ge("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ol("flopay-direct-paypal-gate-debug-default"),al("flopay-stripe-gate-debug-default"),$o&&Pt&&Ge(Do,{children:[ee&&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(sa.Provider,{value:v,children:d(Wa,{sessionId:e,nonce:t,billingApiUrl:G,email:J.email,billingName:Mr||void 0,onBuyerIdentityReady:Fe,clientId:Pt.clientId,environment:Pt.environment,currency:vn.toUpperCase(),isSubscription:le,providerObjectType:Ft,approvalPresentation:Ea==="popup"?void 0:Ea,onTokenizedBody:jn,onComplete:s,onErrorChange:he,onDecline:y,onCancel:C,onTechnicalFailure:co,onButtonClick:pe,runBeforeButtonClick:cr,isProcessing:z,onLoadStateChange:Pi,onInitializationStateChange:vi,session:be,existingOrderId:ee?.orderId,debug:_},ee?.orderId??"fresh")})]}),Ho&&d(oo,{stripe:Wo,options:Es,children:d(fc,{sessionId:e,nonce:t,email:J.email,billingName:Mr||void 0,onBuyerIdentityReady:Fe,billingApiUrl:G,onTokenizedBody:jn,onErrorChange:he,isProcessing:z,onButtonClick:pe,onDecline:y,onTechnicalFailure:co,runBeforeButtonClick:cr,onLoadStateChange:Os,placeholderBorderRadius:Jr,popupCapabilityOwner:v,externalTelemetryContext:Hs,presentationMode:uo})}),yo&&d(oo,{stripe:Yn,options:Rs,children:d(gc,{sessionId:e,nonce:t,email:J.email,billingName:Mr||void 0,onBuyerIdentityReady:Fe,billingApiUrl:G,intentKind:Ve>0?"payment":"setup",expressMethods:po,onTokenizedBody:jn,onErrorChange:he,onButtonClick:pe,onDecline:y,onTechnicalFailure:co,runBeforeButtonClick:cr,onLoadStateChange:Ls,placeholderBorderRadius:Jr,popupCapabilityOwner:v,externalTelemetryContext:rt})}),Vo&&d(hc,{sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:G,paymentElementMethods:Ia,stripeInstance:Yn,paymentElementBaseOptions:hi,futureUseSession:we,onTokenizedBody:jn,onErrorChange:he,onButtonClick:pe,onDecline:y,runBeforeButtonClick:cr,onLoadStateChange:Us,isProcessing:z,submitButtonColor:Zr,submitButtonBorderRadius:Xt,submitButtonStyle:g.submitButton,themeId:kt,onExpandApm:ct,expandedApmMethod:ln,buttonAppearance:{backgroundColor:g.cardButton?.backgroundColor,borderColor:g.cardInputBorder,textColor:g.cardButton?.color,borderRadius:Jr}})]}),K&&(Yc||Gc||Jc)&&d(cl,{label:"or pay with card"}),K&&rl]})}import{Fragment as Rr,jsx as ue,jsxs as yn}from"react/jsx-runtime";var No=44,vs="flopay_checkout_saved_payment_resume",li=new Map,ii=new Map;function Mc(e,t){t.settled&&t.consumers===0&&li.get(e)===t&&li.delete(e)}function Up(e,t,n){let o=ii.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};ii.set(e,i);let s=()=>{ii.get(e)===i&&ii.delete(e)};return a.then(s,s),a}function Pa(e){return new Promise(t=>setTimeout(t,e))}function si(e,t,n){let o=ja({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:zc,enabled:t!==!1});return o.beginCheckout(n),o}function va(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ms(e,t,n,o,a,i){let s=si(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),va(s)}function Ac(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 xc(e,t,n,o,a){let i=Oc(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 Tn&&t.code==="session_auto_completed"?!1:t instanceof Tn&&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 fs(e){return!e||e.data.stripe?.publishableKey?!1:!!Nc(e.data.paypal)?.clientId}var qp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function jp(e){return new Ap(qp,{publishableKey:"provider_unavailable",...e})}async function gs(e,t){let{publishableKey:n,paypalPublishableKey:o}=Ki(e);return{...await Gi({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function Cs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function $p(){if(!Cs())return null;try{let e=window.sessionStorage.getItem(vs);return e?JSON.parse(e):null}catch{return null}}function Bc(e){if(Cs())try{window.sessionStorage.setItem(vs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function hs(){if(Cs())try{window.sessionStorage.removeItem(vs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Wp(){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 Fc(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 Ps(e,t){return Lp(!!e,t)}function Hp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Dc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Vp(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 bs({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:c,error:y,onComplete:C,onError:A,onInstrument:I,onDecline:O,onCancel:se,onCountryChange:N,onZipChange:xe,showPayPal:V=!0,showStripe:f=!0,walletPresentation:w="auto",enabledPaymentMethods:He,showApplePay:R=!0,showGooglePay:Ye=!0,debug:H=!1,layout:De,theme:Qe,buttonsTheme:Ue,buttonsStyles:et,cardButtonContent:kt,cardBackButtonContent:st,cardTitleContent:Z,showSecurityFooter:At,onButtonClick:pt,onBeforeButtonClick:tt,enableAVS:fe,cardFieldOrder:re,cardPreFormSlot:pe,avsLayout:St,submitLabel:xt,className:Je,initialErrorMessage:X=null,initialPayPalOrderId:Te,children:oe,checkoutMode:L,confirmLabel:qe,renderConfirmButton:Oe,onSessionCompleted:Ne}){let x=Op(o),je=rr(()=>Lc(Qe),[Qe]),gt=i??je?.appearance,_e=n?"embedded_checkout":"standard_checkout",ht=Ps(oe,De),[Pe,$e]=Gt(null),[Ve,vn]=Gt(null),It=Dt(null),Pt=Dt(null),le=Dt(0),[P,lt]=Gt(null),nt=Dt(null),[_,Se]=Gt(null),Bt=rr(()=>n?da(n):"",[n]),ce=n?`create:${Bt}`:`session:${e??""}`,wt=Dc(_),m=Dt(new Set),v=Dt(ce),Ce=Dt(ce);Qo(()=>{Ce.current=ce,v.current!==ce&&(v.current=ce,m.current.clear())},[ce]);let ve=_n(b=>{if(Ce.current===ce){if(zl.has(b.name)){if(m.current.has(b.name))return;m.current.add(b.name)}Lt(()=>I?.(b))}},[ce,I]),Ze=Eo(ve,ce),rt=Dt(!1),be=_n(b=>{if(rt.current)return;let S=b.gateway||!wt?b:{...b,gateway:wt};ve(S)},[ve,wt]);yr(()=>{Ze({class:"lifecycle",name:"checkout.mount"})},[Ze]);let[we,Ft]=Gt(e??""),u=e??we,Be=n?"":u,[ge,ke]=Gt(!0),[G,$]=Gt(null),[mn,Wn]=Gt(0),[en,qt]=Gt("full"),[yt,Mn]=Gt(!1),[kn,Yt]=Gt(X),[Nn,mt]=Gt(null),[mr,jt]=Gt(null),[Zn,An]=Gt(!1),[xn,tn]=Gt(void 0),[fn,Ln]=Gt(""),[Le,ot]=Gt(!1),[nn,$t]=Gt(!1),[dn,Wt]=Gt(!1),rn=Dt(null),Cn=Dt(0),on=Dt(void 0),[Ie,In]=Gt("loading"),[an,Nr]=Gt(0),Bn=Dt(!1),Fn=Dt(!1),fr=Dt(!1),zn=Dt(null),Ht=Dt(null),K=rr(()=>({checkoutMode:L??en,layout:Hp(oe,De)}),[L,oe,en,De]),B=Dt(C);B.current=C;let vt=Dt(A);vt.current=A;let ae=Dt(O);ae.current=O;let un=_n(b=>Ya(zn,async S=>{try{return await b(S)}catch(D){throw S.aborted?Mo(D):D}}),[]);yr(()=>()=>{zn.current?.abort(),zn.current=null},[]);let Rt=_n((b,S)=>{It.current=b,vn(b),nt.current=S,lt(S)},[]),Ot=_n(()=>{let b=Pt.current;b&&(Pt.current=null,b.destroy())},[]);yr(()=>{Pn(Ve)?.setCheckoutContext(K),P&&P!==Ve&&Pn(P)?.setCheckoutContext(K)},[Ve,P,K]);let pn=Dt(Ne);pn.current=Ne;let T=_n(b=>{In(b),!(b!=="exhausted"||fr.current)&&(fr.current=!0,vt.current?.(new Tn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Nt=_n(()=>{In("retrying"),Nr(b=>b+1)},[]);yr(()=>{In("loading"),Nr(0),fr.current=!1},[u]),yr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:zc,checkout_type:_e,checkout_layout:ht,billing_api_url:x})},[ht,_e,x]);let Me=rr(()=>n?da(n,!0):"",[n]),Et=rr(()=>fn===Me?xn:void 0,[xn,fn,Me]),sn=rr(()=>n?Oi(n,Et):void 0,[n,Et]),Rn=L??sn?.checkoutMode??"full",Jt=rr(()=>sn?{...sn,checkoutMode:Rn}:void 0,[sn,Rn]);yr(()=>{tn(void 0),Ln(Me),on.current=void 0,rn.current=null,Wt(!1)},[Me]),yr(()=>{Yt(X)},[X]);let or=_n((b,S,D)=>{Lt(()=>{ae.current?.(hn(b,S,D))})},[]),Er=_n(async(b,S)=>{Yt(null),jt(null),An(!1),mt("processing");let D=S?.sessionId??b.id,Q=b.clientSecret||t,ct=Dc(b),Zt=It.current??nt.current,ye=Pn(Zt),q=Zt?null:si(x,a,K),k={log:me=>{ye?ye.log(me):q?.log(me)},error:me=>{ye?ye.error(me):q?.error(me)},terminal:me=>{ye?ye.terminal(me):q?.terminal(me)},performance:me=>{ye?ye.performance(me):q?.performance(me)},now:()=>ye?.now()??q?.now()??0,elapsed:me=>ye?.elapsed(me)??Math.max(0,(q?.now()??me)-me)},E=k.now(),W=!!(S?.initialAutoProcessingError||S?.initialAutoProcessingPending),p=!1,l,M=()=>{p||(p=!0,W=!0,l=k.now(),k.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),k.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ee=!1,Re=()=>{ee||(ee=!0,k.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),k.performance({stage:"processing",durationMs:k.elapsed(E),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),l!==void 0&&k.performance({stage:"recovery",durationMs:k.elapsed(l),durationMode:"machine",paymentMethodCategory:"saved"}))};k.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),rt.current=!0;try{k.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{rt.current=!1}Ze({class:"lifecycle",name:"payment.processing.started",provider:ct}),W&&M();let We;try{let me=nc(S?.initialAutoProcessingError),de=S?.initialAutoProcessingError?.type==="3ds_required"&&!S.initialAutoProcessingError.threeDSecureToken&&S.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:S.initialAutoProcessingError.nextActionRedirectUrl}:null,Fe,at=dt=>(M(),un(g=>Ao(dt,{billingApiUrl:x,sessionId:D,nonce:Q,session:b,signal:g})));if(de)Fe=await at(de);else if(me)M(),me.type==="paypal_redirect_required"&&Ht.current?.publishableKey&&Bc({sessionId:D,publishableKey:Ht.current.publishableKey,paypalPublishableKey:Ht.current.paypalPublishableKey}),Fe=await un(dt=>Xa(me,{flopay:It.current,paypalFlopay:nt.current,attempt3DS:S?.attempt3DS,billingApiUrl:x,sessionId:D,session:b,telemetry:!1,signal:dt})),me.type==="paypal_redirect_required"&&hs();else if(S?.initialAutoProcessingPending){let dt=S.initialAutoProcessingPending,g=new ai(x,{telemetry:!1}),Y=await un(z=>g.waitForCheckoutSessionCompletion(dt.sessionId,{initialDelayMs:dt.retryAfterMs,nonce:Q,statusUrl:dt.statusUrl,signal:z})),Ee=jr(Y,b),Ae=Y.autoProcessingError?.type==="3ds_required"&&Y.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Y.autoProcessingError.nextActionRedirectUrl}:null;if(Ae)Fe=await at(Ae);else{if(!Br(Ee))throw wo(Ee);Fe=xr(Ee,D)}}else{if(S?.initialAutoProcessingError)throw kr(S.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:S.initialAutoProcessingError.checkoutMethod});if(S?.fromCreateSession)return S?.fallbackToFull&&(qt("full"),Fc("full")),!1;{let dt=await xo({billingApiUrl:x,sessionId:D,session:b,nonce:Q,telemetry:!1});dt.type==="success"?Fe=dt.result:dt.type==="next_action_required"?Fe=await at(dt):(M(),dt.type==="paypal_redirect_required"&&Ht.current?.publishableKey&&Bc({sessionId:D,publishableKey:Ht.current.publishableKey,paypalPublishableKey:Ht.current.paypalPublishableKey}),Fe=await un(g=>Xa(dt,{flopay:It.current,paypalFlopay:nt.current,attempt3DS:S?.attempt3DS,billingApiUrl:x,sessionId:D,session:b,telemetry:!1,signal:g})),dt.type==="paypal_redirect_required"&&hs())}}D&&To(D),Re(),W&&(k.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),k.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),k.terminal({outcome:Fe.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),An(Fe.status==="authorized"),mt("success"),await Pa(600),We=()=>B.current?.(Fe)}catch(me){let de=qr(ya(me),D);if(de.code==="three_ds_aborted")return!1;let Fe=de.checkoutMethod??pa;Yt(de.message),jt(de.message),An(!1),S?.fallbackToFull&&(k.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),qt("full"),Fc("full")),Re();let at=de.statusCode===void 0?void 0:zp(de.statusCode,"unknown"),dt=at==="4xx"?{requestCategory:"process_payment",statusClass:at}:{},g=at===void 0||at==="4xx";if(g&&(de.telemetryOutcome==="payment_declined"||!!(de.declineCode||de.code?.toLowerCase().includes("declin"))))k.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...dt});else if(g&&(de.telemetryOutcome==="validation_rejected"||de.type==="validation_error"))k.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...dt});else{let Ae=Oc(me,W?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),z=de.telemetryRequestCategory??"process_payment";rt.current=!0;try{k.error({...Ae,...de.telemetryFailureCategory?{failureCategory:de.telemetryFailureCategory}:{},stage:W?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:z})}finally{rt.current=!1}Ze({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:z,provider:ct})}return Lt(()=>vt.current?.(de)),or(Fe,de,{code:de.code,declineCode:de.declineCode}),mt("error"),await Promise.allSettled([Pa(400),S?.ensureProvidersReady?S.ensureProvidersReady():Promise.resolve()]),W&&(k.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),k.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Re(),q&&va(q),mt(null),jt(null)}return Lt(We),!0},[or,Ze,t,x,un,a,K]);yr(()=>{if(typeof window>"u"||Fn.current)return;let b=new URLSearchParams(window.location.search),S=b.get("payment_intent_client_secret");if(!S)return;let D=$p();D&&(Fn.current=!0,(async()=>{let Q,ct=0;Yt(null),jt(null),mt("processing"),Mn(!0);try{if(b.get("redirect_status")==="failed")throw Object.assign(new Tn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Zt,paypalFlopay:ye}=await Gi({publishableKey:D.publishableKey,paypalPublishableKey:D.paypalPublishableKey,billingApiUrl:x,locale:s,telemetry:a});Q=Pn(ye??Zt),Q?.setCheckoutContext(K),ct=Q?.now()??0,Q?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Q?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let q=(ye??Zt)?.getRawProvider();if(!q)throw Object.assign(new Tn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:k,error:E}=await q.retrievePaymentIntent(S);if(E)throw Object.assign(new Tn(E.message??"Failed to retrieve PayPal payment status.","api_error",{code:E.code}),{checkoutMethod:"paypal"});let W=Tl(k?.status);if(!k||W==="failed")throw Object.assign(new Tn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let p=typeof k.payment_method=="string"?k.payment_method:k.payment_method?.id,l=W;if(D.sessionId){let Re=(await new ai(x,{telemetry:!1}).getUnifiedCheckoutSession(D.sessionId)).data.session;if(Re&&Re.status!=="complete"){let We=await xo({billingApiUrl:x,sessionId:D.sessionId,session:Re,telemetry:!1,tokenizedData:{id:p??k.id,type:"card",threeDSecureActionResultTokenId:k.id,isPaypal:!0}});if(We.type!=="success")throw Object.assign(new Tn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});l=We.result.status}}D.sessionId&&To(D.sessionId),Q?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Q?.performance({stage:"redirect_resume",durationMs:Q.elapsed(ct),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Q?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),mt("success"),await Pa(600),Lt(()=>B.current?.({status:l,paymentIntentId:k.id,paymentMethodId:p,checkoutMethod:"paypal"}))}catch(Zt){let ye=qr(ya(Zt),D.sessionId),q=ye.checkoutMethod??"paypal",k=!!(ye.declineCode||ye.code?.toLowerCase().includes("declin"));if(Q)Q.performance({stage:"redirect_resume",durationMs:Q.elapsed(ct),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),k?Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Q.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(k){let E=si(x,a,K);E.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),va(E)}else ms(x,a,K,"REDIRECT_RESUME_FAILED","redirect_resume");Yt(ye.message),jt(ye.message),Lt(()=>vt.current?.(ye)),or(q,ye,{code:ye.code,declineCode:ye.declineCode}),mt("error"),await Pa(400)}finally{hs(),Wp(),mt(null),jt(null),Mn(!1)}})())},[or,s,x,a,K]);let gr=Dt(null),Dn=rr(()=>Jt?da(Jt):"",[Jt]),Lr=Dt(Jt);Lr.current=Jt,yr(()=>{Ft(e??"")},[e]),yr(()=>{Bn.current=!1,Yt(X),jt(null),An(!1),mt(null)},[Dn,X,e]);async function Xn(b,S,D){let Q=si(x,a,K),ct=new ai(x,{telemetry:!1}),Zt=!1;try{let ye=b.idempotencyKey===void 0?void 0:Tc(b.idempotencyKey),q=Jl(S,D),k=Yl(S,D);q?.canonicalIdentity===D&&k&&k.canonicalIdentity===void 0&&(Va(S,D,k.idempotencyKey),k={...k,canonicalIdentity:D});let E=ye??(k?.canonicalIdentity===D?k.idempotencyKey:void 0),W,p=!1;Q.log({name:q?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let l=q?.sid??null,M=null,ee,Re,We=!1;if(l)try{M=await ct.getUnifiedCheckoutSession(l,q?.nonce),q&&q.canonicalIdentity===void 0&&(Gl(M.data.session,b)?(Ka(S,D,l,q.nonce??M.data.session?.clientSecret),k&&k.canonicalIdentity===void 0&&(Va(S,D,k.idempotencyKey),E??(E=k.idempotencyKey))):(Ha(S,D),k=null,E=ye,l=null,M=null));let de=M?.data.session?.status,Fe=M?.data.session,at=Fe?.clientSecret||q?.nonce;if(l&&Fe?.buyerIdentified===!1&&at&&(Re=So(ct,l,at,b.account)),l&&M&&de==="complete"){if(Wi(l))return{sid:l,result:M};Ha(S,D),l=null,M=null,p=!0}}catch{Q.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),q?.canonicalIdentity===void 0?(Ha(S,D),E=ye):$i(S,D),l=null}if(!l){!ye&&(p||!E)&&(E=Tc(),W=E),E&&Va(S,D,E);let de=Q.now(),Fe=0;Q.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let at={...b,idempotencyKey:E,avsCheck:!!fe,avsConfig:typeof fe=="object"?fe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ps(oe,De)};Object.defineProperty(at,xp,{configurable:!1,enumerable:!1,value:{onAttempt:Y=>{Fe=Math.max(Fe,Y)}}});let dt=()=>{Ac(Q,"session_create",de,Fe)},g=Y=>{xc(Q,Y,"session_create",de,Fe)&&Ze({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Fp(at)){let Y=await ct.createDetachedSession(at);Y.claimed.catch(()=>{}),M=Y.shell,l=Y.sessionId,Re=Y.claim;let Ee=Q.now();Q.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ee=Y.claimed.then(Ae=>{let z=Ae.data.session?.id??Y.sessionId;return z&&Ka(S,D,z,Ae.data.session?.clientSecret??Y.nonce),Ac(Q,"session_claim",Ee),dt(),Ae},Ae=>{throw $i(S,D),xc(Q,Ae,"session_claim",Ee,0)&&Ze({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Ae}).finally(()=>va(Q)),ee.catch(()=>{}),Zt=!0,Q.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Q.performance({stage:"session_shell",durationMs:Q.now()-de,durationMode:"machine",requestCategory:"session_create",attempt:Fe,statusClass:"2xx",paymentMethodCategory:"card"})}else M=await ct.createAndFetchSession(at),dt()}catch(Y){throw g(Y),Y}l=M.data.session?.id??l??"",l&&!ee&&Ka(S,D,l,M.data.session?.clientSecret)}let me=M?.data.session;return!Re&&l&&me?.buyerIdentified===!1&&me.clientSecret&&(Re=So(ct,l,me.clientSecret,b.account)),{sid:l??"",result:M,sdkGeneratedIdempotencyKey:W,...ee?{claimed:ee}:{},...Re?{claim:Re}:{},...We?{claimRequiresIdentity:!0}:{}}}finally{Zt||va(Q)}}let _r=Dt(Xn);Qo(()=>{_r.current=Xn},[Xn]);let Hn=_n(async(b,S)=>{let D=Lr.current;if(!D)throw new Tn("createSession is required to bootstrap checkout.","validation_error");let Q=Oi(D,b),ct=da(Q),Zt=Kl(Q),ye=li.get(ct);if(!ye){let E={canonicalIdentity:ct,promise:_r.current(Q,Zt,ct),consumers:0,settled:!1};ye=E,li.set(ct,E);let W=()=>{E.settled=!0,Mc(ct,E)};E.promise.then(W,W)}ye.consumers+=1;let q=!1,k=()=>{q||(q=!0,ye.consumers-=1,Mc(ct,ye))};S?.(k);try{let E=await ye.promise;gr.current=ct,b&&(Ln(Me),tn(me=>Rl(me,b)));let{sid:W,result:p,claimed:l,claim:M,claimRequiresIdentity:ee}=E;if(on.current=M,Wt(ee===!0),$e(p),p.data.session&&Se(p.data.session),W&&Ft(W),l){Cn.current+=1;let me=Cn.current;rn.current=l,$t(!0),l.then(de=>{Cn.current===me&&(rn.current===l&&(rn.current=null),$e(de),de.data.session&&Se(de.data.session),$t(!1),Wt(!1))},de=>{Cn.current===me&&(rn.current===l&&(rn.current=null),$t(!1),Wt(!1),$(de instanceof Tn?de:new Tn(de instanceof Error?de.message:"Failed to create session","api_error")))})}else Cn.current+=1,rn.current=null,$t(!1),Wt(!1);let{flopay:Re,paypalFlopay:We}=await gs(p,{billingApiUrl:x,locale:s,telemetry:a});return Rt(Re,We),ke(!1),E}catch(E){throw gr.current===ct&&(gr.current=null),E}finally{S||k()}},[Me,Rt,s,x,a]),ar=Dt(Er);ar.current=Er;let hr=Dt(Hn);hr.current=Hn;let _t=_n(async b=>{if(!Vp(b)||Le)return{sessionId:we,session:_};ot(!0);try{let S=await Hn(b);return{sessionId:S.sid,session:S.result.data.session??null}}finally{ot(!1)}},[Hn,Le,we,_]),Vn=_n(async b=>{let S=on.current;if(!S)return;let D=Cn.current,Q=await S(b);Cn.current===D&&($e(Q),Q.data.session&&Se(Q.data.session))},[]),Kn=_n(async()=>{await rn.current},[]),Un=_n(async()=>(await Kn(),{proceed:!0}),[Kn]);yr(()=>{let b=!1,S,D=++le.current;Ot(),$(null),Wn(0);let Q=()=>{b=!0,le.current===D&&(le.current+=1,Ot())},ct=Lr.current;if(Dn&&ct)return qt(Rn),ke(!1),gr.current===Dn?Q:(Se(El(ct,L)),(async()=>{let q=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),k=Rn==="auto"&&!Bn.current&&!q;k&&(Yt(null),jt(null),mt("processing"));try{let E=await hr.current(void 0,M=>{S=M}),W=E.result.data.session??null;Ht.current=Ki(E.result);let p=fs(E.result),l=Wi(E.sid||W?.id);if(!b&&k&&W&&!p&&!l){Bn.current=!0,await Up(Dn,E.sdkGeneratedIdempotencyKey,()=>ar.current(W,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:E.result.autoProcessingError,initialAutoProcessingPending:E.result.autoProcessingPending,autoProcessingAttempted:E.result.autoProcessingAttempted,sessionId:E.sid||W.id}));return}!b&&k&&((p||l)&&(Bn.current=!0),mt(null),jt(null))}catch(E){if(b)return;let W=La(E);if(k&&W==="session_auto_completed"){Bn.current=!0,mt("success"),await Pa(600),b||(Lt(()=>{B.current?.({status:"succeeded"})}),mt(null),jt(null));return}k&&(mt(null),jt(null));let p=E instanceof Tn?E:new Tn(E instanceof Error?E.message:"Failed to create session","api_error");$(p)}finally{S?.(),S=void 0}})(),()=>{Q(),S?.()});ke(!0);async function Zt(){let q=!1,k=null;try{let E=new ai(x,{telemetry:!1}),W=await E.getUnifiedCheckoutSession(u,t);if(k=W,b)return;$e(W);let p=W.data.session??null;if(Se(p),!p)throw new Tn("No session data returned","api_error");let l=p.checkoutMode;if(l==="setup")throw new Tn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(p.status==="authorized"){ke(!1),Lt(()=>{B.current?.(xr(p,u)),pn.current?.(p.successUrl??"")});return}if(p.status==="complete"){ke(!1),Lt(()=>{pn.current?.(p.successUrl??"")});return}if(p.status==="expired")throw Na(p);q=!0;let M=L??l??"full";qt(M),Cn.current+=1;let ee=p.clientSecret||t;on.current=p.buyerIdentified===!1&&ee?So(E,u,ee,{...p.customer?.id?{userId:p.customer.id}:{}}):void 0,$t(!1),Wt(!1);let Re=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),We=fs(W);if(M==="auto"&&!Bn.current&&!Re&&!We){Bn.current=!0;let me=ye(W);try{if(await ar.current(p,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>me,sessionId:u||p.id}),b)return;await me,b||ke(!1);return}catch{if(b)return;await me,b||ke(!1);return}}await ye(W),b||ke(!1)}catch(E){if(b)return;let W=Il(E,q);if(q&&Ze({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),W){let{errorCode:l,stage:M,...ee}=W;ms(x,a,K,l,M,ee)}if(W?.stage==="provider_load"&&(L??k?.data.session?.checkoutMode??"full")==="full"&&kl(k,V,f)){let l=jp({billingApiUrl:x,locale:s,telemetry:a});Pt.current=l,Rt(l,null),Wn(1),ke(!1);return}let p=E instanceof Tn&&W?.stage!=="provider_load"?E:wl();p!==E&&Lt(()=>vt.current?.(p)),$(p),ke(!1)}}async function ye(q){let{flopay:k,paypalFlopay:E,...W}=await gs(q,{billingApiUrl:x,locale:s,telemetry:a});Ht.current={publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey},Rt(k,E),Wn(0)}return Zt(),Q},[L,Dn,Rn,Be,t,V,f]);let ir=_n(async()=>{if(!Pe||mn!==1)return;let b=le.current;Wn(2);try{let{flopay:S,paypalFlopay:D}=await gs(Pe,{billingApiUrl:x,locale:s,telemetry:a});if(le.current!==b)return;Ot(),Rt(S,D),Wn(0)}catch(S){if(le.current!==b)return;let{errorCode:D,stage:Q,...ct}=Di(S);ms(x,a,K,D,Q,ct)}},[Ot,Rt,s,mn,x,a,K,Pe]),Xe=!!(u&&(_?.clientSecret||t)),bn=yt||!Xe,ln=_n(async()=>{if(!(yt||!Xe||!_)){Mn(!0),Yt(null);try{await Er(_,{attempt3DS:!0,fallbackToFull:!0,sessionId:u||_.id})}finally{Mn(!1)}}},[u,yt,Xe,Er,_]),qn=Nc(Pe?.data.paypal,Te),Yr=fs(Pe),sr=rr(()=>{if(!(!Pe||!_||!Pe.data.stripe?.publishableKey))return{billingApiUrl:x}},[Pe,_,x]),Tr=!!(n&&!oe&&De==="buttons"&&tt&&Rn==="full"),Gn=!!(u&&(Dp(_?.vault)||to(_))),Sn=rr(()=>({session:_,loading:ge,error:G,checkoutMode:en,inlineSessionDraft:Jt,applyInlineSessionPatch:Tr?_t:void 0,inlineSessionPatchProcessing:Le,claimPending:nn,claimRequiresIdentity:dn,claimBuyerIdentity:Vn,waitForDataAttachment:Kn}),[_,ge,G,en,Jt,Tr,_t,Le,nn,dn,Vn,Kn]),Pr=!!n&&De==="buttons"&&!Yr&&!Gn&&(!Ve||!sr),En=Nn?ue(Sr,{status:Nn,errorMessage:mr,authorized:Zn}):null;if(ge&&!Gn){if(c)return yn(Rr,{children:[c,En]});if(De==="buttons"){let b=je?.buttonsLayout?.cardButton?.borderRadius??je?.appearance.variables?.borderRadius??8,S=D=>ue("div",{style:{height:D,borderRadius:b,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return yn(Rr,{children:[yn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[V&&S(No),f&&(R||Ye)&&S(No),f&&S(No),ue("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),En]})}return yn(Rr,{children:[yn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ue("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ue("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),En]})}return G?y?ue(dr.Provider,{value:Sn,children:y(G)}):ue(dr.Provider,{value:Sn,children:ue("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:G.message})}):Pr?yn(Rr,{children:[ue(dr.Provider,{value:Sn,children:ue(Gp,{onButtonClick:pt,showPayPal:V,showStripe:f,showApplePay:R,showGooglePay:Ye,theme:Qe,buttonsTheme:Ue,buttonsStyles:et,cardButtonContent:kt,cardBackButtonContent:st,cardTitleContent:Z})}),En]}):Yr&&_&&qn?yn(Rr,{children:[ue(dr.Provider,{value:Sn,children:yn("div",{className:Je,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[kn&&ue(_o,{icon:!1,children:kn}),Ie==="retrying"&&ue("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ie==="exhausted"&&yn("div",{role:"alert",children:[ue("div",{children:"PayPal is temporarily unavailable. Please try again."}),ue("button",{type:"button",onClick:Nt,children:"Retry PayPal"})]}),Ie!=="exhausted"&&ue("div",{"aria-hidden":Ie==="retrying"?!0:void 0,style:Ie==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ue(Hl,{sessionId:u,nonce:_.clientSecret||void 0,billingApiUrl:x,email:_.customer?.email||Jt?.account?.email,billingName:[_.customer?.firstName,_.customer?.lastName].filter(Boolean).join(" ")||[Jt?.account?.firstName,Jt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Vn,clientId:qn.clientId,environment:qn.environment,currency:(_.currency??"usd").toUpperCase(),isSubscription:_.mode==="subscription",providerObjectType:qn.providerObjectType,approvalPresentation:qn.approvalPresentation,existingOrderId:qn.existingOrderId,onComplete:C,onErrorChange:Yt,onDecline:O,onCancel:se,onButtonClick:pt,runBeforeButtonClick:Un,onInitializationStateChange:T,allowAutomaticRetry:an===0,session:_,telemetry:a,telemetryContext:K,onInstrument:be,debug:H},`${ce}:paypal-init-${an}`)})]})}),En]}):en==="confirm"?yn(Rr,{children:[ue(dr.Provider,{value:Sn,children:ue(Ga,{flopay:Ve,paypalFlopay:P,options:sr??{billingApiUrl:x},onInstrument:be,children:yn("div",{className:Je,children:[kn&&ue("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:kn}),Oe?Oe({onConfirm:ln,isProcessing:bn}):ue("button",{type:"button",onClick:ln,disabled:bn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:bn?"not-allowed":"pointer",opacity:bn?.6:1},children:yt?"Processing...":qe??"Confirm Purchase"})]})},ce)}),En]}):(!Ve||!sr)&&!(Gn&&en==="full")?ue(Rr,{children:En}):yn(Rr,{children:[ue(dr.Provider,{value:Sn,children:yn(Ga,{flopay:Ve,paypalFlopay:P,options:sr??{billingApiUrl:x},onInstrument:be,children:[mn===1&&ue("button",{type:"button",onClick:ir,children:"Retry payment methods"}),oe?yn(Rr,{children:[kn&&ue("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:kn}),ue(Kp,{sessionId:u,nonce:_?.clientSecret||void 0,billingApiUrl:x,session:_,submitLabel:xt,walletPresentation:w,children:oe})]}):ue(ps,{sessionId:u,nonce:_?.clientSecret||void 0,telemetry:a,email:_?.customer?.email||Jt?.account?.email,userId:_?.customer?.id||Jt?.account?.userId,firstName:_?.customer?.firstName||Jt?.account?.firstName,lastName:_?.customer?.lastName||Jt?.account?.lastName,totalAmount:_?Math.round(Bp(_).total*100):0,currency:_?.currency?.toLowerCase()??"usd",onComplete:C,onError:A,onDecline:O,onCancel:se,error:kn,onErrorChange:Yt,showPayPal:V,showStripe:f,walletPresentation:w,enabledPaymentMethods:mn?[]:He??Pe?.data.stripe?.enabledPaymentMethods??_?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Pe?.data.stripe?.enabledPaymentMethodCountries,showApplePay:R,showGooglePay:Ye,layout:De,theme:Qe,buttonsTheme:Ue,buttonsStyles:et,appearance:gt,cardButtonContent:kt,cardBackButtonContent:st,cardTitleContent:Z,onButtonClick:pt,onBeforeButtonClick:tt,onBuyerIdentityReady:Vn,enableAVS:fe,...re?{cardFieldOrder:re}:{},...pe?{cardPreFormSlot:pe}:{},avsLayout:St,country:_?.customer?.country,city:_?.customer?.city,state:_?.customer?.state,onCountryChange:N,onZipChange:xe,avsCheck:!!fe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ps(oe,De),className:Je,submitLabel:xt,directPaypal:qn,isSubscription:_?.mode==="subscription",session:_,dataAttachmentPending:nn,dataAttachmentRequiresIdentity:dn,debug:H})]},ce)}),En]})}function Kp({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,children:s}){return ue(Rr,{children:ys.Children.map(s,c=>{if(!ys.isValidElement(c))return c;let y=c.props,C={};return y.sessionId||(C.sessionId=e),!y.nonce&&t&&(C.nonce=t),y.billingApiUrl||(C.billingApiUrl=n),y.submitLabel===void 0&&a!==void 0&&(C.submitLabel=a),y.walletPresentation===void 0&&(C.walletPresentation=i),o?.customer&&(y.email||(C.email=o.customer.email),y.userId||(C.userId=o.customer.id),y.firstName||(C.firstName=o.customer.firstName),y.lastName||(C.lastName=o.customer.lastName)),Object.keys(C).length===0?c:ys.cloneElement(c,C)})})}function Gp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:o,showGooglePay:a,theme:i,buttonsTheme:s,buttonsStyles:c,cardButtonContent:y,cardBackButtonContent:C,cardTitleContent:A}){let[I,O]=Gt(!1),se=rr(()=>Lc(i),[i]),N=rr(()=>{let w=se?.buttonsLayout??Np(s);return c?{...w,...c,cardButton:{...w.cardButton,...c.cardButton},cardFormContainer:{...w.cardFormContainer,...c.cardFormContainer},backButton:{...w.backButton,...c.backButton},backButtonIcon:{...w.backButtonIcon,...c.backButtonIcon},submitButton:{...w.submitButton,...c.submitButton},title:{...w.title,...c.title}}:w},[se,s,c]),xe=se?.buttonsLayout?.cardButton?.borderRadius??se?.appearance.variables?.borderRadius??8,V=w=>ue("div",{style:{height:w,borderRadius:xe,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),f=y===void 0?{boxSizing:"border-box",height:No,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(I){let w=N.cardInputBorder??"#e5e7eb",He=N.cardInputBackground??"white",R=Po(C),Ye=Po(A);return yn("div",{style:{backgroundColor:N.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...N.cardFormContainer},children:[yn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[yn("button",{type:"button",onClick:()=>O(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:R?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...N.backButton},children:[ue("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...N.backButtonIcon},children:ue("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:ue("path",{d:"M15 18l-6-6 6-6"})})}),ue(Co,{content:C})]}),Ye?ue("div",{style:{flex:1}}):ue("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...N.title},children:ue(na,{content:A})})]}),ue("div",{style:{backgroundColor:He,border:`1px solid ${w}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ue("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),yn("div",{style:{display:"flex"},children:[ue("div",{style:{flex:1,backgroundColor:He,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomLeftRadius:8,padding:12,height:45},children:ue("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ue("div",{style:{flex:1,backgroundColor:He,borderTop:"none",borderRight:`1px solid ${w}`,borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomRightRadius:8,padding:12,height:45},children:ue("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ue("div",{style:{backgroundColor:He,border:`1px solid ${w}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ue("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ue("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...N.submitButton,opacity:.5}}),ue("style",{children:`
12
+ `}),Zo&&Zr&&Ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:X?-2:0},children:[Ze("button",{type:"button",onClick:re,style:{display:"inline-flex",alignItems:"center",gap:_i?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...D.backButtonIcon},children:c("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:c("path",{d:"M15 18l-6-6 6-6"})})}),c(ko,{content:rt})]}),il?c("div",{style:{flex:1}}):c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...D.title},children:c(aa,{content:ge})})]}),!Zo&&!il&&c("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ti,order:X?-3:0,...D.title},children:c(aa,{content:ge})}),X&&Me&&c("div",{style:{order:-2,width:"100%"},children:Me}),X&&Ct&&Ze("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[c("div",{style:{backgroundColor:Po,border:`1px solid ${rr(xa)}`,borderRadius:nn,padding:"10px"},children:c("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:an,onChange:r=>{Mt("email"),Kt.current=r.target.value,fn(r.target.value)},onPointerDown:()=>Mt("email"),onKeyDown:()=>Mt("email"),onBlur:()=>{$n("email")&&Mr(!0),uo||hi()},disabled:G,required:!0,"aria-invalid":xa||void 0,"aria-describedby":xa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Mi}})}),xa&&c("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Qo,children:co.empty?"Email address is required":"Enter a valid email address"})]}),Ee&&c("div",{style:{order:X?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=Wt,y=(x=!1)=>({backgroundColor:Po,border:`1px solid ${rr(x)}`,borderRadius:nn,marginTop:"0.5rem",padding:"10px"}),T=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Mi}),ae=$u(r);return Ze(Lo,{children:[Jt(Ee.address_line_1,r)&&Ze(Lo,{children:[c("div",{style:y(Yt("line1")),children:c("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:Xt,onChange:x=>{Mt("line1"),gn.current.addressLine1=!0,Ut.current=x.target.value,Un(x.target.value)},onPointerDown:()=>Mt("line1"),onKeyDown:()=>Mt("line1"),onBlur:()=>Wn("line1"),disabled:G,required:!0,"aria-invalid":Yt("line1")||void 0,"aria-describedby":Yt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:T()})}),Yt("line1")&&c("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Qo,children:"Street address is required"})]}),Jt(Ee.address_line_2,r)&&c("div",{style:y(),children:c("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:yt,onChange:x=>{gn.current.addressLine2=!0,sn.current=x.target.value,fr(x.target.value)},disabled:G,"data-testid":"flopay-address-line2",style:T()})}),(Jt(Ee.city,r)||Jt(Ee.state,r))&&Ze("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Jt(Ee.city,r)&&c("div",{style:{flex:1,backgroundColor:Po,borderTop:`1px solid ${rr(Yt("city"))}`,borderRight:`1px solid ${rr(Yt("city"))}`,borderBottom:`1px solid ${rr(Yt("city"))}`,borderLeft:`1px solid ${rr(Yt("city"))}`,padding:"10px",borderTopLeftRadius:nn,borderBottomLeftRadius:nn,...Jt(Ee.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:nn}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Vt,onChange:x=>{Mt("city"),gn.current.city=!0,ln.current=x.target.value,tr(x.target.value)},onPointerDown:()=>Mt("city"),onKeyDown:()=>Mt("city"),onBlur:()=>Wn("city"),disabled:G,required:!0,"aria-invalid":Yt("city")||void 0,"aria-describedby":Yt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:T()})}),Jt(Ee.state,r)&&c("div",{style:{flex:1,backgroundColor:Po,borderTop:`1px solid ${rr(Yt("state"))}`,borderRight:`1px solid ${rr(Yt("state"))}`,borderBottom:`1px solid ${rr(Yt("state"))}`,borderLeft:`1px solid ${rr(Yt("state"))}`,padding:"10px",borderTopRightRadius:nn,borderBottomRightRadius:nn,...Jt(Ee.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${rr(Yt("state")||Yt("city"))}`}:{borderRadius:nn}},children:ae?Ze("select",{id:"flopay-billing-state",name:"billing-state",value:Dn,onChange:x=>{Mt("state"),gn.current.state=!0,Ht.current=x.target.value,On(x.target.value)},onPointerDown:()=>Mt("state"),onKeyDown:()=>Mt("state"),onBlur:()=>Wn("state"),disabled:G,autoComplete:"billing address-level1",required:!0,"aria-invalid":Yt("state")||void 0,"aria-describedby":Yt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...T(),cursor:"pointer"},children:[c("option",{value:"",children:Qi(r)}),ae.map(x=>c("option",{value:x.code,children:x.name},x.code))]}):c("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Qi(r),autoComplete:"billing address-level1",value:Dn,onChange:x=>{Mt("state"),gn.current.state=!0,Ht.current=x.target.value,On(x.target.value)},onPointerDown:()=>Mt("state"),onKeyDown:()=>Mt("state"),onBlur:()=>Wn("state"),disabled:G,required:!0,"aria-invalid":Yt("state")||void 0,"aria-describedby":Yt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:T()})})]}),Yt("city")&&c("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Qo,children:"City is required"}),Yt("state")&&Ze("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Qo,children:[Qi(r)," is required"]}),(Jt(Ee.country,r)||Jt(Ee.postal_code,r))&&Ze("div",{style:{display:"flex",flexDirection:de==="column"?"column":"row",gap:de==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Jt(Ee.country,r)&&c("div",{style:{flex:de==="row"?1:void 0,backgroundColor:Po,borderTop:`1px solid ${Xo}`,borderRight:`1px solid ${Xo}`,borderBottom:`1px solid ${Xo}`,borderLeft:`1px solid ${Xo}`,padding:"10px",...de==="row"&&Jt(Ee.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:nn,borderBottomLeftRadius:nn,borderRight:"none"}:{borderRadius:nn}},children:Ze("select",{id:"flopay-billing-country",name:"billing-country",value:Wt,onChange:x=>{gn.current.country=!0,kn.current=x.target.value,pt(x.target.value),gt?.(x.target.value),Ht.current="",On("")},disabled:G,autoComplete:"billing country","data-testid":"flopay-country",style:{...T(),cursor:"pointer"},children:[Wt===""?c("option",{value:"",children:"Select country"}):null,Fu.map(x=>Ze("option",{value:x.code,children:[x.flag," ",x.name]},x.code))]})}),Jt(Ee.postal_code,r)&&c("div",{style:{flex:de==="row"?1:void 0,backgroundColor:Po,border:`1px solid ${id}`,padding:"10px",...de==="row"&&Jt(Ee.country,r)?{borderRadius:"0",borderTopRightRadius:nn,borderBottomRightRadius:nn}:{borderRadius:nn}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ss(Wt),autoComplete:"billing postal-code",value:Fn,onChange:x=>{Mt("zip"),gn.current.zip=!0,lt.current=x.target.value,En(x.target.value),_e?.(x.target.value)},onPointerDown:()=>Mt("zip"),onKeyDown:()=>Mt("zip"),onBlur:()=>{$n("zip")&&Pr(!0)},disabled:G,required:_t.required,"aria-invalid":Ba||void 0,"aria-describedby":Ba?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:T()})})]}),Ba&&c("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Qo,children:_t.empty?`${ss(r)} is required`:Ap(r)})]})})()}),X&&ud,le&&c(xo,{margin:"0.75rem 0",styleOverride:D.errorBanner,children:le})]}),Fa={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"},ul=r=>R?!Ve||!br?c("pre",{"data-testid":r,style:Fa,children:"FloPay/DirectPayPal-debug - not enabled"}):c("pre",{"data-testid":r,style:Fa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${Ve}`,` directPaypalConfigured=${br}`,` inAppBrowserDetected=${String(Ta)}`,` shouldRenderDirectPayPal=${Ho}`,` shouldRenderStripePayPal=${Go}`,` hasPaypalStripeInstance=${!!Es}`].join(`
13
+ `)}):null,pl=r=>R?!I||!Qn?c("pre",{"data-testid":r,style:Fa,children:"FloPay/Stripe-debug - not enabled"}):c("pre",{"data-testid":r,style:Fa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${I}`,` currency=${wn}`,` amountInCents=${Wo}`,` enabledPaymentMethods: ${JSON.stringify(Y??[])}`,` enabledPaymentMethodsProvided=${Vo}`,` hasEnabledMethods=${Ia}`,` expressMethods: ${JSON.stringify(Ea)}`,` walletExpressMethods: ${JSON.stringify(go)}`,` paymentElementMethods: ${JSON.stringify(Ci)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(_a)}`,` hasStripeInstance=${!!Qn}`,` shouldRenderWallets=${ho}`,` shouldRenderPaymentElement=${Yo}`].join(`
14
+ `)}):null,yl=Ne==="apm-expanding"||Ne==="apm-form"||Ne==="apm-collapsing",Co;Ne==="apm-expanding"?Co=vc:Ne==="apm-collapsing"&&(Co=Cc);let Da=tn?Fc(bi,tn,Ie):null;if(He==="buttons"){let r=Ne==="buttons"||Ne==="expanding"||Ne==="apm-expanding",y=Ne==="expanding"||Ne==="card"||Ne==="collapsing",T=ut===void 0?{boxSizing:"border-box",height:oa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ae;Ne==="expanding"||Ne==="apm-expanding"?ae=Ep:(Ne==="collapsing"||Ne==="apm-collapsing")&&(ae=Rp);let x;return Ne==="expanding"?x=vc:Ne==="collapsing"&&(x=Cc),Ze("form",{onSubmit:Ii,className:N,noValidate:!0,style:{position:"relative"},children:[c(za,{}),oe&&c(wr,{status:oe,errorMessage:le,authorized:Pn}),Ze("div",{style:{display:"grid"},children:[Ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!ae?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!ae?Tp:{},...ae?{animation:ae,pointerEvents:"none"}:{}},children:[ul("flopay-direct-paypal-gate-debug"),pl("flopay-stripe-gate-debug"),Ho&&Pt&&Ze(Lo,{children:[Rt&&c("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."}),c(da.Provider,{value:v,children:c(Ya,{sessionId:e,nonce:t,billingApiUrl:Q,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,clientId:Pt.clientId,environment:Pt.environment,currency:wn.toUpperCase(),isSubscription:pe,providerObjectType:Dt,approvalPresentation:Ma==="popup"?void 0:Ma,onTokenizedBody:Kn,onComplete:s,onErrorChange:Pe,onDecline:u,onCancel:C,onTechnicalFailure:mo,onButtonClick:fe,runBeforeButtonClick:dr,isProcessing:G,onLoadStateChange:Si,onInitializationStateChange:wi,session:ke,existingOrderId:Rt?.orderId,debug:R},Rt?.orderId??"fresh")})]}),Go&&c(so,{stripe:Ko,options:Ms,children:c(Sc,{sessionId:e,nonce:t,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,onTokenizedBody:Kn,onErrorChange:Pe,isProcessing:G,onButtonClick:fe,onDecline:u,onTechnicalFailure:mo,runBeforeButtonClick:dr,onLoadStateChange:$s,placeholderBorderRadius:Xr,popupCapabilityOwner:v,externalTelemetryContext:Xs,presentationMode:fo})}),ho?c(so,{stripe:Qn,options:Ts,children:c(wc,{sessionId:e,nonce:t,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,intentKind:Ke>0?"payment":"setup",expressMethods:go,onTokenizedBody:Kn,onErrorChange:Pe,onButtonClick:fe,onDecline:u,onTechnicalFailure:mo,runBeforeButtonClick:dr,onLoadStateChange:Vs,placeholderBorderRadius:Xr,popupCapabilityOwner:v,externalTelemetryContext:Ge})}):null,!ho&&Js?c("div",{style:{height:oa,borderRadius:Xr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Yo&&c(kc,{sessionId:e,nonce:t,email:z.email,billingName:[z.firstName,z.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,paymentElementMethods:_a,stripeInstance:Qn,paymentElementBaseOptions:bi,futureUseSession:Ie,onTokenizedBody:Kn,onErrorChange:Pe,onButtonClick:fe,onDecline:u,runBeforeButtonClick:dr,onLoadStateChange:Ks,isProcessing:G,submitButtonColor:Qr,submitButtonBorderRadius:nn,submitButtonStyle:D.submitButton,onExpandApm:$e,expandedApmMethod:tn,themeId:It,buttonAppearance:{backgroundColor:D.cardButton?.backgroundColor,borderColor:D.cardInputBorder,textColor:D.cardButton?.color,borderRadius:Xr}}),X&&c("button",{type:"button",onClick:async()=>{G||!(await dr("card")).proceed||(fe?.("card"),q())},disabled:G,style:{width:"100%",...T,...D.cardButton,...fs({themeBundle:Ye,resolvedPrimaryColor:Qr,resolvedBorderRadius:nn,submitButtonStyle:D.submitButton,explicitPrimaryColor:Gn?.colorPrimary}),fontSize:D.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:G?"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:G?.6:1},onMouseEnter:ie=>{!G&&(Ye||Gn?.colorPrimary)&&(ie.currentTarget.style.backgroundColor=cd)},onMouseLeave:ie=>{(Ye||Gn?.colorPrimary)&&(ie.currentTarget.style.backgroundColor=Qr)},onMouseDown:ie=>{ie.currentTarget.style.transform="scale(0.985)"},onMouseUp:ie=>{ie.currentTarget.style.transform="scale(1)"},children:c(wo,{content:ut})}),le&&Ne==="buttons"&&c(xo,{margin:"0.25rem 0",styleOverride:D.errorBanner,children:le})]}),X&&y&&c("div",{style:{gridArea:"1 / 1",...x?{animation:x}:{},...Ne==="collapsing"?{pointerEvents:"none"}:{}},children:dl}),I&&yl&&tn&&Da&&Qn&&c("div",{style:{gridArea:"1 / 1",...Co?{animation:Co}:{},...Ne==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ze("div",{style:{backgroundColor:Ei,borderRadius:xi,...ea,padding:Ai},children:[Ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ze("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:jt,style:{display:"inline-flex",alignItems:"center",gap:_i?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...D.backButtonIcon},children:c("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:c("path",{d:"M15 18l-6-6 6-6"})})}),c(ko,{content:rt})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:Ti,paddingRight:80,...D.title},children:`Pay with ${va(tn)}`})]}),c(so,{stripe:Qn,options:Da,children:c(ds,{method:tn,sessionId:e,nonce:t,email:z.email,billingName:[z.firstName,z.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,onTokenizedBody:Kn,onErrorChange:Pe,onDecline:u,onCancel:jt,runBeforeButtonClick:dr,onButtonClick:fe,isProcessing:G,submitButtonColor:Qr,submitButtonBorderRadius:nn,submitButtonStyle:D.submitButton,errorText:le})},tn)]})})]})]})}return yl&&tn&&Da&&Qn&&I?Ze("form",{onSubmit:Ii,className:N,noValidate:!0,style:{position:"relative"},children:[c(za,{}),oe&&c(wr,{status:oe,errorMessage:le,authorized:Pn}),c("div",{style:{...Co?{animation:Co}:{},...Ne==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ze("div",{style:{backgroundColor:Ei,borderRadius:xi,...ea,padding:Ai},children:[Ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ze("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:jt,style:{display:"inline-flex",alignItems:"center",gap:_i?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...D.backButtonIcon},children:c("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:c("path",{d:"M15 18l-6-6 6-6"})})}),c(ko,{content:rt})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:Ti,paddingRight:80,...D.title},children:`Pay with ${va(tn)}`})]}),c(so,{stripe:Qn,options:Da,children:c(ds,{method:tn,sessionId:e,nonce:t,email:z.email,billingName:[z.firstName,z.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,onTokenizedBody:Kn,onErrorChange:Pe,onDecline:u,onCancel:jt,runBeforeButtonClick:dr,onButtonClick:fe,isProcessing:G,submitButtonColor:Qr,submitButtonBorderRadius:nn,submitButtonStyle:D.submitButton,errorText:le})},tn)]})})]}):Ze("form",{onSubmit:Ii,className:N,noValidate:!0,style:{position:"relative"},children:[c(za,{}),oe&&c(wr,{status:oe,errorMessage:le,authorized:Pn}),Ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ul("flopay-direct-paypal-gate-debug-default"),pl("flopay-stripe-gate-debug-default"),Ho&&Pt&&Ze(Lo,{children:[Rt&&c("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."}),c(da.Provider,{value:v,children:c(Ya,{sessionId:e,nonce:t,billingApiUrl:Q,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,clientId:Pt.clientId,environment:Pt.environment,currency:wn.toUpperCase(),isSubscription:pe,providerObjectType:Dt,approvalPresentation:Ma==="popup"?void 0:Ma,onTokenizedBody:Kn,onComplete:s,onErrorChange:Pe,onDecline:u,onCancel:C,onTechnicalFailure:mo,onButtonClick:fe,runBeforeButtonClick:dr,isProcessing:G,onLoadStateChange:Si,onInitializationStateChange:wi,session:ke,existingOrderId:Rt?.orderId,debug:R},Rt?.orderId??"fresh")})]}),Go&&c(so,{stripe:Ko,options:Ms,children:c(Sc,{sessionId:e,nonce:t,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,onTokenizedBody:Kn,onErrorChange:Pe,isProcessing:G,onButtonClick:fe,onDecline:u,onTechnicalFailure:mo,runBeforeButtonClick:dr,onLoadStateChange:$s,placeholderBorderRadius:Xr,popupCapabilityOwner:v,externalTelemetryContext:Xs,presentationMode:fo})}),ho&&c(so,{stripe:Qn,options:Ts,children:c(wc,{sessionId:e,nonce:t,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,intentKind:Ke>0?"payment":"setup",expressMethods:go,onTokenizedBody:Kn,onErrorChange:Pe,onButtonClick:fe,onDecline:u,onTechnicalFailure:mo,runBeforeButtonClick:dr,onLoadStateChange:Vs,placeholderBorderRadius:Xr,popupCapabilityOwner:v,externalTelemetryContext:Ge})}),Yo&&c(kc,{sessionId:e,nonce:t,email:z.email,billingName:[z.firstName,z.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Q,paymentElementMethods:_a,stripeInstance:Qn,paymentElementBaseOptions:bi,futureUseSession:Ie,onTokenizedBody:Kn,onErrorChange:Pe,onButtonClick:fe,onDecline:u,runBeforeButtonClick:dr,onLoadStateChange:Ks,isProcessing:G,submitButtonColor:Qr,submitButtonBorderRadius:nn,submitButtonStyle:D.submitButton,themeId:It,onExpandApm:$e,expandedApmMethod:tn,buttonAppearance:{backgroundColor:D.cardButton?.backgroundColor,borderColor:D.cardInputBorder,textColor:D.cardButton?.color,borderRadius:Xr}})]}),X&&(nd||td||rd)&&c(gl,{label:"or pay with card"}),X&&dl]})}import{Fragment as Er,jsx as me,jsxs as yn}from"react/jsx-runtime";var Uo=44,ws="flopay_checkout_saved_payment_resume",yi=new Map,ui=new Map;function Nc(e,t){t.settled&&t.consumers===0&&yi.get(e)===t&&yi.delete(e)}function Kp(e,t,n){let o=ui.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};ui.set(e,i);let s=()=>{ui.get(e)===i&&ui.delete(e)};return a.then(s,s),a}function ba(e){return new Promise(t=>setTimeout(t,e))}function pi(e,t,n){let o=Ka({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Hc,enabled:t!==!1});return o.beginCheckout(n),o}function Sa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ps(e,t,n,o,a,i){let s=pi(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Sa(s)}function Lc(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 zc(e,t,n,o,a){let i=$c(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 Bn&&t.code==="session_auto_completed"?!1:t instanceof Bn&&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 vs(e){return!e||e.data.stripe?.publishableKey?!1:!!Wc(e.data.paypal)?.clientId}var Gp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Yp(e){return new Lp(Gp,{publishableKey:"provider_unavailable",...e})}async function Cs(e,t){let{publishableKey:n,paypalPublishableKey:o}=Zi(e);return{...await Xi({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function ks(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Jp(){if(!ks())return null;try{let e=window.sessionStorage.getItem(ws);return e?JSON.parse(e):null}catch{return null}}function Uc(e){if(ks())try{window.sessionStorage.setItem(ws,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function bs(){if(ks())try{window.sessionStorage.removeItem(ws)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Zp(){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 qc(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 Ss(e,t){return Vp(!!e,t)}function Xp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function jc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Qp(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 Is({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:l,error:u,onComplete:C,onError:_,onInstrument:k,onDecline:O,onCancel:ue,onCountryChange:N,onZipChange:Ae,showPayPal:Z=!0,showStripe:m=!0,walletPresentation:b="auto",enabledPaymentMethods:Ve,showApplePay:I=!0,showGooglePay:Xe=!0,debug:Y=!1,layout:Fe,theme:nt,buttonsTheme:ze,buttonsStyles:He,cardButtonContent:It,cardBackButtonContent:it,cardTitleContent:te,showSecurityFooter:xt,onButtonClick:ut,onBeforeButtonClick:rt,enableAVS:ge,cardFieldOrder:se,cardPreFormSlot:fe,avsLayout:wt,submitLabel:Bt,className:Qe,initialErrorMessage:ne=null,initialPayPalOrderId:Me,children:de,checkoutMode:L,confirmLabel:Ue,renderConfirmButton:De,onSessionCompleted:Oe}){let M=$p(o),qe=sr(()=>Vc(nt),[nt]),gt=i??qe?.appearance,_e=n?"embedded_checkout":"standard_checkout",ht=Ss(de,Fe),[ve,je]=Zt(null),[Ke,wn]=Zt(null),Et=Ot(null),Pt=Ot(null),pe=Ot(0),[P,st]=Zt(null),ot=Ot(null),[R,Se]=Zt(null),Ft=sr(()=>n?ya(n):"",[n]),ye=n?`create:${Ft}`:`session:${e??""}`,kt=jc(R),p=Ot(new Set),v=Ot(ye),we=Ot(ye);na(()=>{we.current=ye,v.current!==ye&&(v.current=ye,p.current.clear())},[ye]);let Ce=xn(S=>{if(we.current===ye){if(Hl.has(S.name)){if(p.current.has(S.name))return;p.current.add(S.name)}Lt(()=>k?.(S))}},[ye,k]),et=Ao(Ce,ye),Ge=Ot(!1),ke=xn(S=>{if(Ge.current)return;let w=S.gateway||!kt?S:{...S,gateway:kt};Ce(w)},[Ce,kt]);mr(()=>{et({class:"lifecycle",name:"checkout.mount"})},[et]);let[Ie,Dt]=Zt(e??""),d=e??Ie,xe=n?"":d,[he,Re]=Zt(!0),[Q,j]=Zt(null),[mn,Yn]=Zt(0),[on,Wt]=Zt("full"),[pt,Fn]=Zt(!1),[En,Xt]=Zt(ne),[Un,yt]=Zt(null),[fr,Vt]=Zt(null),[tr,Dn]=Zt(!1),[On,an]=Zt(void 0),[fn,qn]=Zt(""),[Be,lt]=Zt(!1),[kn,Ut]=Zt(!1),[sn,ln]=Zt(!1),Ht=Ot(null),Kt=Ot(0),gn=Ot(void 0),[Ee,hn]=Zt("loading"),[Pn,_r]=Zt(0),_n=Ot(!1),Tn=Ot(!1),gr=Ot(!1),Jn=Ot(null),Qt=Ot(null),X=sr(()=>({checkoutMode:L??on,layout:Xp(de,Fe)}),[L,de,on,Fe]),cn=Ot(C);cn.current=C;let jn=Ot(_);jn.current=_;let $=Ot(O);$.current=O;let vt=xn(S=>ei(Jn,async w=>{try{return await S(w)}catch(q){throw w.aborted?Fo(q):q}}),[]);mr(()=>()=>{Jn.current?.abort(),Jn.current=null},[]);let B=xn((S,w)=>{Et.current=S,wn(S),ot.current=w,st(w)},[]),qt=xn(()=>{let S=Pt.current;S&&(Pt.current=null,S.destroy())},[]);mr(()=>{pn(Ke)?.setCheckoutContext(X),P&&P!==Ke&&pn(P)?.setCheckoutContext(X)},[Ke,P,X]);let en=Ot(Oe);en.current=Oe;let ee=xn(S=>{hn(S),!(S!=="exhausted"||gr.current)&&(gr.current=!0,jn.current?.(new Bn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Nt=xn(()=>{hn("retrying"),_r(S=>S+1)},[]);mr(()=>{hn("loading"),_r(0),gr.current=!1},[d]),mr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Hc,checkout_type:_e,checkout_layout:ht,billing_api_url:M})},[ht,_e,M]);let U=sr(()=>n?ya(n,!0):"",[n]),_t=sr(()=>fn===U?On:void 0,[On,fn,U]),dn=sr(()=>n?Ui(n,_t):void 0,[n,_t]),Mn=L??dn?.checkoutMode??"full",Gt=sr(()=>dn?{...dn,checkoutMode:Mn}:void 0,[dn,Mn]);mr(()=>{an(void 0),qn(U),gn.current=void 0,Ht.current=null,ln(!1)},[U]),mr(()=>{Xt(ne)},[ne]);let hr=xn((S,w,q)=>{Lt(()=>{$.current?.(Sn(S,w,q))})},[]),Tr=xn(async(S,w)=>{Xt(null),Vt(null),Dn(!1),yt("processing");let q=w?.sessionId??S.id,re=S.clientSecret||t,$e=jc(S),jt=Et.current??ot.current,oe=pn(jt),K=jt?null:pi(M,a,X),A={log:h=>{oe?oe.log(h):K?.log(h)},error:h=>{oe?oe.error(h):K?.error(h)},terminal:h=>{oe?oe.terminal(h):K?.terminal(h)},performance:h=>{oe?oe.performance(h):K?.performance(h)},now:()=>oe?.now()??K?.now()??0,elapsed:h=>oe?.elapsed(h)??Math.max(0,(K?.now()??h)-h)},E=A.now(),W=!!(w?.initialAutoProcessingError||w?.initialAutoProcessingPending),be=!1,V,We=()=>{be||(be=!0,W=!0,V=A.now(),A.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),A.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Rt=!1,f=()=>{Rt||(Rt=!0,A.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),A.performance({stage:"processing",durationMs:A.elapsed(E),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),V!==void 0&&A.performance({stage:"recovery",durationMs:A.elapsed(V),durationMode:"machine",paymentMethodCategory:"saved"}))};A.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Ge.current=!0;try{A.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Ge.current=!1}et({class:"lifecycle",name:"payment.processing.started",provider:$e}),W&&We();let g;try{let h=cc(w?.initialAutoProcessingError),F=w?.initialAutoProcessingError?.type==="3ds_required"&&!w.initialAutoProcessingError.threeDSecureToken&&w.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:w.initialAutoProcessingError.nextActionRedirectUrl}:null,J,le=Ye=>(We(),vt(D=>Do(Ye,{billingApiUrl:M,sessionId:q,nonce:re,session:S,signal:D})));if(F)J=await le(F);else if(h)We(),h.type==="paypal_redirect_required"&&Qt.current?.publishableKey&&Uc({sessionId:q,publishableKey:Qt.current.publishableKey,paypalPublishableKey:Qt.current.paypalPublishableKey}),J=await vt(Ye=>ri(h,{flopay:Et.current,paypalFlopay:ot.current,attempt3DS:w?.attempt3DS,billingApiUrl:M,sessionId:q,session:S,telemetry:!1,signal:Ye})),h.type==="paypal_redirect_required"&&bs();else if(w?.initialAutoProcessingPending){let Ye=w.initialAutoProcessingPending,D=new di(M,{telemetry:!1}),mt=await vt(G=>D.waitForCheckoutSessionCompletion(Ye.sessionId,{initialDelayMs:Ye.retryAfterMs,nonce:re,statusUrl:Ye.statusUrl,signal:G})),Nn=Vr(mt,S),Cn=mt.autoProcessingError?.type==="3ds_required"&&mt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:mt.autoProcessingError.nextActionRedirectUrl}:null;if(Cn)J=await le(Cn);else{if(!Or(Nn))throw Eo(Nn);J=Dr(Nn,q)}}else{if(w?.initialAutoProcessingError)throw Ir(w.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:w.initialAutoProcessingError.checkoutMethod});if(w?.fromCreateSession)return w?.fallbackToFull&&(Wt("full"),qc("full")),!1;{let Ye=await Oo({billingApiUrl:M,sessionId:q,session:S,nonce:re,telemetry:!1});Ye.type==="success"?J=Ye.result:Ye.type==="next_action_required"?J=await le(Ye):(We(),Ye.type==="paypal_redirect_required"&&Qt.current?.publishableKey&&Uc({sessionId:q,publishableKey:Qt.current.publishableKey,paypalPublishableKey:Qt.current.paypalPublishableKey}),J=await vt(D=>ri(Ye,{flopay:Et.current,paypalFlopay:ot.current,attempt3DS:w?.attempt3DS,billingApiUrl:M,sessionId:q,session:S,telemetry:!1,signal:D})),Ye.type==="paypal_redirect_required"&&bs())}}q&&Bo(q),f(),W&&(A.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),A.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),A.terminal({outcome:J.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Dn(J.status==="authorized"),yt("success"),await ba(600),g=()=>cn.current?.(J)}catch(h){let F=Wr(ga(h),q);if(F.code==="three_ds_aborted")return!1;let J=F.checkoutMethod??fa;Xt(F.message),Vt(F.message),Dn(!1),w?.fallbackToFull&&(A.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Wt("full"),qc("full")),f();let le=F.statusCode===void 0?void 0:Hp(F.statusCode,"unknown"),Ye=le==="4xx"?{requestCategory:"process_payment",statusClass:le}:{},D=le===void 0||le==="4xx";if(D&&(F.telemetryOutcome==="payment_declined"||!!(F.declineCode||F.code?.toLowerCase().includes("declin"))))A.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ye});else if(D&&(F.telemetryOutcome==="validation_rejected"||F.type==="validation_error"))A.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ye});else{let Cn=$c(h,W?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),G=F.telemetryRequestCategory??"process_payment";Ge.current=!0;try{A.error({...Cn,...F.telemetryFailureCategory?{failureCategory:F.telemetryFailureCategory}:{},stage:W?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:G})}finally{Ge.current=!1}et({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:G,provider:$e})}return Lt(()=>jn.current?.(F)),hr(J,F,{code:F.code,declineCode:F.declineCode}),yt("error"),await Promise.allSettled([ba(400),w?.ensureProvidersReady?w.ensureProvidersReady():Promise.resolve()]),W&&(A.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),A.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{f(),K&&Sa(K),yt(null),Vt(null)}return Lt(g),!0},[hr,et,t,M,vt,a,X]);mr(()=>{if(typeof window>"u"||Tn.current)return;let S=new URLSearchParams(window.location.search),w=S.get("payment_intent_client_secret");if(!w)return;let q=Jp();q&&(Tn.current=!0,(async()=>{let re,$e=0;Xt(null),Vt(null),yt("processing"),Fn(!0);try{if(S.get("redirect_status")==="failed")throw Object.assign(new Bn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:jt,paypalFlopay:oe}=await Xi({publishableKey:q.publishableKey,paypalPublishableKey:q.paypalPublishableKey,billingApiUrl:M,locale:s,telemetry:a});re=pn(oe??jt),re?.setCheckoutContext(X),$e=re?.now()??0,re?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),re?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let K=(oe??jt)?.getRawProvider();if(!K)throw Object.assign(new Bn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:A,error:E}=await K.retrievePaymentIntent(w);if(E)throw Object.assign(new Bn(E.message??"Failed to retrieve PayPal payment status.","api_error",{code:E.code}),{checkoutMethod:"paypal"});let W=Ol(A?.status);if(!A||W==="failed")throw Object.assign(new Bn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let be=typeof A.payment_method=="string"?A.payment_method:A.payment_method?.id,V=W;if(q.sessionId){let f=(await new di(M,{telemetry:!1}).getUnifiedCheckoutSession(q.sessionId)).data.session;if(f&&f.status!=="complete"){let g=await Oo({billingApiUrl:M,sessionId:q.sessionId,session:f,telemetry:!1,tokenizedData:{id:be??A.id,type:"card",threeDSecureActionResultTokenId:A.id,isPaypal:!0}});if(g.type!=="success")throw Object.assign(new Bn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});V=g.result.status}}q.sessionId&&Bo(q.sessionId),re?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),re?.performance({stage:"redirect_resume",durationMs:re.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),re?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),yt("success"),await ba(600),Lt(()=>cn.current?.({status:V,paymentIntentId:A.id,paymentMethodId:be,checkoutMethod:"paypal"}))}catch(jt){let oe=Wr(ga(jt),q.sessionId),K=oe.checkoutMethod??"paypal",A=!!(oe.declineCode||oe.code?.toLowerCase().includes("declin"));if(re)re.performance({stage:"redirect_resume",durationMs:re.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),A?re.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):re.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(A){let E=pi(M,a,X);E.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Sa(E)}else Ps(M,a,X,"REDIRECT_RESUME_FAILED","redirect_resume");Xt(oe.message),Vt(oe.message),Lt(()=>jn.current?.(oe)),hr(K,oe,{code:oe.code,declineCode:oe.declineCode}),yt("error"),await ba(400)}finally{bs(),Zp(),yt(null),Vt(null),Fn(!1)}})())},[hr,s,M,a,X]);let Pr=Ot(null),vr=sr(()=>Gt?ya(Gt):"",[Gt]),Mr=Ot(Gt);Mr.current=Gt,mr(()=>{Dt(e??"")},[e]),mr(()=>{_n.current=!1,Xt(ne),Vt(null),Dn(!1),yt(null)},[vr,ne,e]);async function qr(S,w,q){let re=pi(M,a,X),$e=new di(M,{telemetry:!1}),jt=!1;try{let oe=S.idempotencyKey===void 0?void 0:Oc(S.idempotencyKey),K=rc(w,q),A=nc(w,q);K?.canonicalIdentity===q&&A&&A.canonicalIdentity===void 0&&(Za(w,q,A.idempotencyKey),A={...A,canonicalIdentity:q});let E=oe??(A?.canonicalIdentity===q?A.idempotencyKey:void 0),W,be=!1;re.log({name:K?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let V=K?.sid??null,We=null,Rt,f,g=!1;if(V)try{We=await $e.getUnifiedCheckoutSession(V,K?.nonce),K&&K.canonicalIdentity===void 0&&(tc(We.data.session,S)?(Xa(w,q,V,K.nonce??We.data.session?.clientSecret),A&&A.canonicalIdentity===void 0&&(Za(w,q,A.idempotencyKey),E??(E=A.idempotencyKey))):(Ja(w,q),A=null,E=oe,V=null,We=null));let F=We?.data.session?.status,J=We?.data.session,le=J?.clientSecret||K?.nonce;if(V&&J?.buyerIdentified===!1&&le&&(f=Ro($e,V,le,S.account)),V&&We&&F==="complete"){if(Gi(V))return{sid:V,result:We};Ja(w,q),V=null,We=null,be=!0}}catch{re.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),K?.canonicalIdentity===void 0?(Ja(w,q),E=oe):Ki(w,q),V=null}if(!V){!oe&&(be||!E)&&(E=Oc(),W=E),E&&Za(w,q,E);let F=re.now(),J=0;re.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let le={...S,idempotencyKey:E,avsCheck:!!ge,avsConfig:typeof ge=="object"?ge:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ss(de,Fe)};Object.defineProperty(le,zp,{configurable:!1,enumerable:!1,value:{onAttempt:mt=>{J=Math.max(J,mt)}}});let Ye=()=>{Lc(re,"session_create",F,J)},D=mt=>{zc(re,mt,"session_create",F,J)&&et({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(qp(le)){let mt=await $e.createDetachedSession(le);mt.claimed.catch(()=>{}),We=mt.shell,V=mt.sessionId,f=mt.claim;let Nn=re.now();re.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Rt=mt.claimed.then(Cn=>{let G=Cn.data.session?.id??mt.sessionId;return G&&Xa(w,q,G,Cn.data.session?.clientSecret??mt.nonce),Lc(re,"session_claim",Nn),Ye(),Cn},Cn=>{throw Ki(w,q),zc(re,Cn,"session_claim",Nn,0)&&et({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Cn}).finally(()=>Sa(re)),Rt.catch(()=>{}),jt=!0,re.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),re.performance({stage:"session_shell",durationMs:re.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:J,statusClass:"2xx",paymentMethodCategory:"card"})}else We=await $e.createAndFetchSession(le),Ye()}catch(mt){throw D(mt),mt}V=We.data.session?.id??V??"",V&&!Rt&&Xa(w,q,V,We.data.session?.clientSecret)}let h=We?.data.session;return!f&&V&&h?.buyerIdentified===!1&&h.clientSecret&&(f=Ro($e,V,h.clientSecret,S.account)),{sid:V??"",result:We,sdkGeneratedIdempotencyKey:W,...Rt?{claimed:Rt}:{},...f?{claim:f}:{},...g?{claimRequiresIdentity:!0}:{}}}finally{jt||Sa(re)}}let jr=Ot(qr);na(()=>{jr.current=qr},[qr]);let In=xn(async(S,w)=>{let q=Mr.current;if(!q)throw new Bn("createSession is required to bootstrap checkout.","validation_error");let re=Ui(q,S),$e=ya(re),jt=ec(re),oe=yi.get($e);if(!oe){let E={canonicalIdentity:$e,promise:jr.current(re,jt,$e),consumers:0,settled:!1};oe=E,yi.set($e,E);let W=()=>{E.settled=!0,Nc($e,E)};E.promise.then(W,W)}oe.consumers+=1;let K=!1,A=()=>{K||(K=!0,oe.consumers-=1,Nc($e,oe))};w?.(A);try{let E=await oe.promise;Pr.current=$e,S&&(qn(U),an(h=>Bl(h,S)));let{sid:W,result:be,claimed:V,claim:We,claimRequiresIdentity:Rt}=E;if(gn.current=We,ln(Rt===!0),je(be),be.data.session&&Se(be.data.session),W&&Dt(W),V){Kt.current+=1;let h=Kt.current;Ht.current=V,Ut(!0),V.then(F=>{Kt.current===h&&(Ht.current===V&&(Ht.current=null),je(F),F.data.session&&Se(F.data.session),Ut(!1),ln(!1))},F=>{Kt.current===h&&(Ht.current===V&&(Ht.current=null),Ut(!1),ln(!1),j(F instanceof Bn?F:new Bn(F instanceof Error?F.message:"Failed to create session","api_error")))})}else Kt.current+=1,Ht.current=null,Ut(!1),ln(!1);let{flopay:f,paypalFlopay:g}=await Cs(be,{billingApiUrl:M,locale:s,telemetry:a});return B(f,g),Re(!1),E}catch(E){throw Pr.current===$e&&(Pr.current=null),E}finally{w||A()}},[U,B,s,M,a]),Ar=Ot(Tr);Ar.current=Tr;let nr=Ot(In);nr.current=In;let Mt=xn(async S=>{if(!Qp(S)||Be)return{sessionId:Ie,session:R};lt(!0);try{let w=await In(S);return{sessionId:w.sid,session:w.result.data.session??null}}finally{lt(!1)}},[In,Be,Ie,R]),$n=xn(async S=>{let w=gn.current;if(!w)return;let q=Kt.current,re=await w(S);Kt.current===q&&(je(re),re.data.session&&Se(re.data.session))},[]),Wn=xn(async()=>{await Ht.current},[]),Zn=xn(async()=>(await Wn(),{proceed:!0}),[Wn]);mr(()=>{let S=!1,w,q=++pe.current;qt(),j(null),Yn(0);let re=()=>{S=!0,pe.current===q&&(pe.current+=1,qt())},$e=Mr.current;if(vr&&$e)return Wt(Mn),Re(!1),Pr.current===vr?re:(Se(Fl($e,L)),(async()=>{let K=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),A=Mn==="auto"&&!_n.current&&!K;A&&(Xt(null),Vt(null),yt("processing"));try{let E=await nr.current(void 0,We=>{w=We}),W=E.result.data.session??null;Qt.current=Zi(E.result);let be=vs(E.result),V=Gi(E.sid||W?.id);if(!S&&A&&W&&!be&&!V){_n.current=!0,await Kp(vr,E.sdkGeneratedIdempotencyKey,()=>Ar.current(W,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:E.result.autoProcessingError,initialAutoProcessingPending:E.result.autoProcessingPending,autoProcessingAttempted:E.result.autoProcessingAttempted,sessionId:E.sid||W.id}));return}!S&&A&&((be||V)&&(_n.current=!0),yt(null),Vt(null))}catch(E){if(S)return;let W=qa(E);if(A&&W==="session_auto_completed"){_n.current=!0,yt("success"),await ba(600),S||(Lt(()=>{cn.current?.({status:"succeeded"})}),yt(null),Vt(null));return}A&&(yt(null),Vt(null));let be=E instanceof Bn?E:new Bn(E instanceof Error?E.message:"Failed to create session","api_error");j(be)}finally{w?.(),w=void 0}})(),()=>{re(),w?.()});Re(!0);async function jt(){let K=!1,A=null;try{let E=new di(M,{telemetry:!1}),W=await E.getUnifiedCheckoutSession(d,t);if(A=W,S)return;je(W);let be=W.data.session??null;if(Se(be),!be)throw new Bn("No session data returned","api_error");let V=be.checkoutMode;if(V==="setup")throw new Bn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(be.status==="authorized"){Re(!1),Lt(()=>{cn.current?.(Dr(be,d)),en.current?.(be.successUrl??"")});return}if(be.status==="complete"){Re(!1),Lt(()=>{en.current?.(be.successUrl??"")});return}if(be.status==="expired")throw Ua(be);K=!0;let We=L??V??"full";Wt(We),Kt.current+=1;let Rt=be.clientSecret||t;gn.current=be.buyerIdentified===!1&&Rt?Ro(E,d,Rt,{...be.customer?.id?{userId:be.customer.id}:{}}):void 0,Ut(!1),ln(!1);let f=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),g=vs(W);if(We==="auto"&&!_n.current&&!f&&!g){_n.current=!0;let h=oe(W);try{if(await Ar.current(be,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>h,sessionId:d||be.id}),S)return;await h,S||Re(!1);return}catch{if(S)return;await h,S||Re(!1);return}}await oe(W),S||Re(!1)}catch(E){if(S)return;let W=xl(E,K);if(K&&et({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),W){let{errorCode:V,stage:We,...Rt}=W;Ps(M,a,X,V,We,Rt)}if(W?.stage==="provider_load"&&(L??A?.data.session?.checkoutMode??"full")==="full"&&Al(A,Z,m)){let V=Yp({billingApiUrl:M,locale:s,telemetry:a});Pt.current=V,B(V,null),Yn(1),Re(!1);return}let be=E instanceof Bn&&W?.stage!=="provider_load"?E:Ml();be!==E&&Lt(()=>jn.current?.(be)),j(be),Re(!1)}}async function oe(K){let{flopay:A,paypalFlopay:E,...W}=await Cs(K,{billingApiUrl:M,locale:s,telemetry:a});Qt.current={publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey},B(A,E),Yn(0)}return jt(),re},[L,vr,Mn,xe,t,Z,m]);let Vn=xn(async()=>{if(!ve||mn!==1)return;let S=pe.current;Yn(2);try{let{flopay:w,paypalFlopay:q}=await Cs(ve,{billingApiUrl:M,locale:s,telemetry:a});if(pe.current!==S)return;qt(),B(w,q),Yn(0)}catch(w){if(pe.current!==S)return;let{errorCode:q,stage:re,...$e}=zi(w);Ps(M,a,X,q,re,$e)}},[qt,B,s,mn,M,a,X,ve]),Ne=!!(d&&(R?.clientSecret||t)),un=pt||!Ne,tn=xn(async()=>{if(!(pt||!Ne||!R)){Fn(!0),Xt(null);try{await Tr(R,{attempt3DS:!0,fallbackToFull:!0,sessionId:d||R.id})}finally{Fn(!1)}}},[d,pt,Ne,Tr,R]),Hn=Wc(ve?.data.paypal,Me),Zr=vs(ve),xr=sr(()=>{if(!(!ve||!R||!ve.data.stripe?.publishableKey))return{billingApiUrl:M}},[ve,R,M]),lr=!!(n&&!de&&Fe==="buttons"&&rt&&Mn==="full"),Xn=!!(d&&(jp(R?.vault)||ro(R))),vn=sr(()=>({session:R,loading:he,error:Q,checkoutMode:on,inlineSessionDraft:Gt,applyInlineSessionPatch:lr?Mt:void 0,inlineSessionPatchProcessing:Be,claimPending:kn,claimRequiresIdentity:sn,claimBuyerIdentity:$n,waitForDataAttachment:Wn}),[R,he,Q,on,Gt,lr,Mt,Be,kn,sn,$n,Wn]),Br=!!n&&Fe==="buttons"&&!Zr&&!Xn&&(!Ke||!xr),An=Un?me(wr,{status:Un,errorMessage:fr,authorized:tr}):null;if(he&&!Xn){if(l)return yn(Er,{children:[l,An]});if(Fe==="buttons"){let S=qe?.buttonsLayout?.cardButton?.borderRadius??qe?.appearance.variables?.borderRadius??8,w=q=>me("div",{style:{height:q,borderRadius:S,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return yn(Er,{children:[yn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Z&&w(Uo),m&&(I||Xe)&&w(Uo),m&&w(Uo),me("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),An]})}return yn(Er,{children:[yn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[me("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),me("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),An]})}return Q?u?me(ur.Provider,{value:vn,children:u(Q)}):me(ur.Provider,{value:vn,children:me("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Q.message})}):Br?yn(Er,{children:[me(ur.Provider,{value:vn,children:me(ty,{onButtonClick:ut,showPayPal:Z,showStripe:m,showApplePay:I,showGooglePay:Xe,theme:nt,buttonsTheme:ze,buttonsStyles:He,cardButtonContent:It,cardBackButtonContent:it,cardTitleContent:te})}),An]}):Zr&&R&&Hn?yn(Er,{children:[me(ur.Provider,{value:vn,children:yn("div",{className:Qe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[En&&me(xo,{icon:!1,children:En}),Ee==="retrying"&&me("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ee==="exhausted"&&yn("div",{role:"alert",children:[me("div",{children:"PayPal is temporarily unavailable. Please try again."}),me("button",{type:"button",onClick:Nt,children:"Retry PayPal"})]}),Ee!=="exhausted"&&me("div",{"aria-hidden":Ee==="retrying"?!0:void 0,style:Ee==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:me(Xl,{sessionId:d,nonce:R.clientSecret||void 0,billingApiUrl:M,email:R.customer?.email||Gt?.account?.email,billingName:[R.customer?.firstName,R.customer?.lastName].filter(Boolean).join(" ")||[Gt?.account?.firstName,Gt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:$n,clientId:Hn.clientId,environment:Hn.environment,currency:(R.currency??"usd").toUpperCase(),isSubscription:R.mode==="subscription",providerObjectType:Hn.providerObjectType,approvalPresentation:Hn.approvalPresentation,existingOrderId:Hn.existingOrderId,onComplete:C,onErrorChange:Xt,onDecline:O,onCancel:ue,onButtonClick:ut,runBeforeButtonClick:Zn,onInitializationStateChange:ee,allowAutomaticRetry:Pn===0,session:R,telemetry:a,telemetryContext:X,onInstrument:ke,debug:Y},`${ye}:paypal-init-${Pn}`)})]})}),An]}):on==="confirm"?yn(Er,{children:[me(ur.Provider,{value:vn,children:me(Qa,{flopay:Ke,paypalFlopay:P,options:xr??{billingApiUrl:M},onInstrument:ke,children:yn("div",{className:Qe,children:[En&&me("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:En}),De?De({onConfirm:tn,isProcessing:un}):me("button",{type:"button",onClick:tn,disabled:un,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:un?"not-allowed":"pointer",opacity:un?.6:1},children:pt?"Processing...":Ue??"Confirm Purchase"})]})},ye)}),An]}):(!Ke||!xr)&&!(Xn&&on==="full")?me(Er,{children:An}):yn(Er,{children:[me(ur.Provider,{value:vn,children:yn(Qa,{flopay:Ke,paypalFlopay:P,options:xr??{billingApiUrl:M},onInstrument:ke,children:[mn===1&&me("button",{type:"button",onClick:Vn,children:"Retry payment methods"}),de?yn(Er,{children:[En&&me("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:En}),me(ey,{sessionId:d,nonce:R?.clientSecret||void 0,billingApiUrl:M,session:R,submitLabel:Bt,walletPresentation:b,children:de})]}):me(gs,{sessionId:d,nonce:R?.clientSecret||void 0,telemetry:a,email:R?.customer?.email||Gt?.account?.email,userId:R?.customer?.id||Gt?.account?.userId,firstName:R?.customer?.firstName||Gt?.account?.firstName,lastName:R?.customer?.lastName||Gt?.account?.lastName,totalAmount:R?Math.round(Up(R).total*100):0,currency:R?.currency?.toLowerCase()??"usd",onComplete:C,onError:_,onDecline:O,onCancel:ue,error:En,onErrorChange:Xt,showPayPal:Z,showStripe:m,walletPresentation:b,enabledPaymentMethods:mn?[]:Ve??ve?.data.stripe?.enabledPaymentMethods??R?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ve?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:Xe,layout:Fe,theme:nt,buttonsTheme:ze,buttonsStyles:He,appearance:gt,cardButtonContent:It,cardBackButtonContent:it,cardTitleContent:te,onButtonClick:ut,onBeforeButtonClick:rt,onBuyerIdentityReady:$n,enableAVS:ge,...se?{cardFieldOrder:se}:{},...fe?{cardPreFormSlot:fe}:{},avsLayout:wt,country:R?.customer?.country,city:R?.customer?.city,state:R?.customer?.state,onCountryChange:N,onZipChange:Ae,avsCheck:!!ge,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ss(de,Fe),className:Qe,submitLabel:Bt,directPaypal:Hn,isSubscription:R?.mode==="subscription",session:R,dataAttachmentPending:kn,dataAttachmentRequiresIdentity:sn,debug:Y})]},ye)}),An]})}function ey({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,children:s}){return me(Er,{children:hs.Children.map(s,l=>{if(!hs.isValidElement(l))return l;let u=l.props,C={};return u.sessionId||(C.sessionId=e),!u.nonce&&t&&(C.nonce=t),u.billingApiUrl||(C.billingApiUrl=n),u.submitLabel===void 0&&a!==void 0&&(C.submitLabel=a),u.walletPresentation===void 0&&(C.walletPresentation=i),o?.customer&&(u.email||(C.email=o.customer.email),u.userId||(C.userId=o.customer.id),u.firstName||(C.firstName=o.customer.firstName),u.lastName||(C.lastName=o.customer.lastName)),Object.keys(C).length===0?l:hs.cloneElement(l,C)})})}function ty({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:o,showGooglePay:a,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:u,cardBackButtonContent:C,cardTitleContent:_}){let[k,O]=Zt(!1),ue=sr(()=>Vc(i),[i]),N=sr(()=>{let b=ue?.buttonsLayout??Wp(s);return l?{...b,...l,cardButton:{...b.cardButton,...l.cardButton},cardFormContainer:{...b.cardFormContainer,...l.cardFormContainer},backButton:{...b.backButton,...l.backButton},backButtonIcon:{...b.backButtonIcon,...l.backButtonIcon},submitButton:{...b.submitButton,...l.submitButton},title:{...b.title,...l.title}}:b},[ue,s,l]),Ae=ue?.buttonsLayout?.cardButton?.borderRadius??ue?.appearance.variables?.borderRadius??8,Z=b=>me("div",{style:{height:b,borderRadius:Ae,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),m=u===void 0?{boxSizing:"border-box",height:Uo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(k){let b=N.cardInputBorder??"#e5e7eb",Ve=N.cardInputBackground??"white",I=So(C),Xe=So(_);return yn("div",{style:{backgroundColor:N.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...N.cardFormContainer},children:[yn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[yn("button",{type:"button",onClick:()=>O(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:I?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...N.backButton},children:[me("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...N.backButtonIcon},children:me("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:me("path",{d:"M15 18l-6-6 6-6"})})}),me(ko,{content:C})]}),Xe?me("div",{style:{flex:1}}):me("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...N.title},children:me(aa,{content:_})})]}),me("div",{style:{backgroundColor:Ve,border:`1px solid ${b}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:me("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),yn("div",{style:{display:"flex"},children:[me("div",{style:{flex:1,backgroundColor:Ve,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomLeftRadius:8,padding:12,height:45},children:me("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),me("div",{style:{flex:1,backgroundColor:Ve,borderTop:"none",borderRight:`1px solid ${b}`,borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomRightRadius:8,padding:12,height:45},children:me("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),me("div",{style:{backgroundColor:Ve,border:`1px solid ${b}`,borderRadius:8,marginTop:8,padding:12,height:45},children:me("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),me("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...N.submitButton,opacity:.5}}),me("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
- `})]})}return yn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&V(No),n&&(o||a)&&V(No),n&&ue("button",{type:"button",onClick:()=>{e?.("card"),O(!0)},style:{width:"100%",...f,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:N.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...N.cardButton},onMouseDown:w=>{w.currentTarget.style.transform="scale(0.985)"},onMouseUp:w=>{w.currentTarget.style.transform="scale(1)"},children:ue(vo,{content:y})}),ue("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as ry,jsx as ao,jsxs as oy}from"react/jsx-runtime";var Xp=44;function Uc(e){return new Promise(t=>setTimeout(t,e))}function Qp(e,t){return e instanceof ba?e:new ba(e instanceof Error?e.message:t,"api_error")}function ey(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ty(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 ny({sessionId:e,nonce:t,createSession:n,paymentMethodId:o,checkoutMethod:a,clientId:i,products:s,items:c,subscriptions:y,account:C,successUrl:A,cancelUrl:I,couponCodes:O,tagsData:se,utmMetadata:N,billingApiUrl:xe,locale:V,theme:f,appearance:w,buttonsTheme:He,buttonsStyles:R,onSuccess:Ye,onError:H,onDecline:De,children:Qe,disabled:Ue=!1,type:et="button",style:kt,...st}){let Z=Ca(()=>Yp(xe),[xe]),At=Ca(()=>ty({createSession:n,clientId:i,products:s,items:c,subscriptions:y,account:C,successUrl:A,cancelUrl:I,couponCodes:O,tagsData:se,utmMetadata:N}),[C,I,i,O,n,s,c,y,A,se,N]),[pt,tt]=Uo(!1),[fe,re]=Uo(null),[pe,St]=Uo(null),[xt,Je]=Uo(!1),[X,Te]=Uo(null),[oe,L]=Uo(null),qe=zo(!0),Oe=zo(null),Ne=zo(oe),x=zo(Ye),je=zo(H),gt=zo(De),_e=Or(m=>Ya(Oe,async v=>{try{return await m(v)}catch(Ce){throw v.aborted?Mo(Ce):Ce}}),[]);Lo(()=>{Ne.current=oe},[oe]),Lo(()=>{x.current=Ye},[Ye]),Lo(()=>{je.current=H},[H]),Lo(()=>{gt.current=De},[De]),Lo(()=>(qe.current=!0,()=>{qe.current=!1,Oe.current?.abort()}),[]),Lo(()=>{if(typeof window>"u")return;let m=v=>{v.key==="Escape"&&L(null)};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[]);let ht=Or((m,v=pa)=>{gt.current?.(hn(v,m,{code:m.code,declineCode:m.declineCode}))},[]),Pe=Or(async m=>{qe.current&&(St(null),Je(m.result.status==="authorized"),re("success"),await Uc(600),qe.current&&Lt(()=>x.current?.(m)))},[]),$e=Or(async(m,v)=>{qe.current&&(je.current?.(m),v?.emitDecline&&ht(m,v.method),St(m.message),Je(!1),re("error"),await Uc(400))},[ht]),Ve=Or(async(m,v,Ce)=>{let ve=m.data.session??null;if(!ve)throw qr(new ba("No session data returned","api_error"),v);let Ze=ve.clientSecret||t;if(Br(ve)){await Pe({result:xr(ve,v),session:ve,sessionId:ve.id||v,autoCompleted:!1});return}if(ve.status==="expired")throw qr(Na(ve),ve.id||v);try{if(m.autoProcessingPending){let be=m.autoProcessingPending,we=new Ss(Z),Ft=await _e(ge=>we.waitForCheckoutSessionCompletion(be.sessionId,{initialDelayMs:be.retryAfterMs,nonce:Ze,statusUrl:be.statusUrl,signal:ge})),u=jr(Ft,ve),Be=Ft.autoProcessingError?.type==="3ds_required"&&Ft.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ft.autoProcessingError.nextActionRedirectUrl}:null;if(Be&&v&&Ze){let ge=await _e(ke=>Ao(Be,{billingApiUrl:Z,sessionId:v,nonce:Ze,session:ve,signal:ke,telemetry:!0}));await Pe({result:ge,session:ve,sessionId:ve.id||v,autoCompleted:!1});return}if(Ft.autoProcessingError)throw kr(Ft.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Ft.autoProcessingError.checkoutMethod});if(!Br(u))throw wo(u);await Pe({result:xr(u,v),session:u,sessionId:u.id||v,autoCompleted:!1});return}if(m.autoProcessingError){let be=m.autoProcessingError.nextActionRedirectUrl;if(m.autoProcessingError.type==="3ds_required"&&be&&v&&Ze){let we=await _e(ge=>rc({billingApiUrl:Z,sessionId:v,nonce:Ze,nextActionRedirectUrl:be,signal:ge}));if(we.status==="declined")throw kr({type:we.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:we.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:m.autoProcessingError.checkoutMethod});let u=await new Ss(Z).waitForCheckoutSessionCompletion(v,{initialDelayMs:0,nonce:Ze}),Be=jr(u,ve);if(!Br(Be))throw kr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:m.autoProcessingError.checkoutMethod});await Pe({result:xr(Be,v),session:Be,sessionId:Be.id||v,autoCompleted:!1});return}throw kr(m.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:m.autoProcessingError.checkoutMethod})}if(Ce?.fromCreateSession&&m.autoProcessingAttempted===!0)throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let rt=await xo({billingApiUrl:Z,sessionId:v??ve.id,session:ve,nonce:Ze});if(rt.type==="next_action_required"&&Ze){let be=v??ve.id,we=await _e(Ft=>Ao(rt,{billingApiUrl:Z,sessionId:be,nonce:Ze,session:ve,signal:Ft,telemetry:!0}));await Pe({result:we,session:ve,sessionId:ve.id||be,autoCompleted:!1});return}if(rt.type!=="success")throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Pe({result:rt.result,session:ve,sessionId:ve.id||v,autoCompleted:!1})}catch(rt){let be=ve.id||v,we=qr(ya(rt),be);if(we.code==="three_ds_aborted")return;if(we.code==="checkout_processing_timeout"){if(!qe.current)return;Te(we.message),Lt(()=>je.current?.(we));return}await $e(we,{emitDecline:!0,method:we.checkoutMethod??pa}),ey(we,be)&&be&&qe.current&&L({sessionId:be,errorMessage:we.message,nonce:Ze||void 0,payPalOrderId:we.orderId})}},[t,Z,_e,$e,Pe]),vn=Or(async m=>{if(st.onClick?.(m),!(m.defaultPrevented||Ue||pt)){if(L(null),Te(null),e&&At){let v=new ba("Provide either sessionId or create-session props, not both.","validation_error");await $e(v),qe.current&&(re(null),St(null));return}if(!e&&!At){let v=new ba("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $e(v),qe.current&&(re(null),St(null));return}tt(!0),St(null),Je(!1),re("processing");try{let v=new Ss(Z);if(e){let Ce=await v.getUnifiedCheckoutSession(e,t);await Ve(Ce,e);return}try{let Ce=await v.createAndFetchSession({...At});await Ve(Ce,Ce.data.session?.id??null,{fromCreateSession:!0})}catch(Ce){if(La(Ce)==="session_auto_completed"){await Pe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ce}}catch(v){await $e(qr(Qp(v,"Automatic payment failed. Please try again."),e))}finally{qe.current&&(re(null),St(null),tt(!1))}}},[st.onClick,At,Ue,pt,t,Ve,Z,e,$e,Pe]),It=Or(m=>{let v=Ne.current;L(null),x.current?.({result:m,session:null,sessionId:v?.sessionId??null,autoCompleted:!1})},[]),Pt=Or(m=>{je.current?.(m)},[]),le=Or(m=>{gt.current?.(m)},[]),P=Ca(()=>Zp(f),[f]),lt=Ca(()=>{let m=P?.buttonsLayout??Jp(He);return R?{...m,...R,cardButton:{...m.cardButton,...R.cardButton}}:m},[P,He,R]),nt=Ca(()=>{let m=P?.appearance;return w?m?{...m,...w,variables:{...m.variables,...w.variables}}:w:m},[w,P]),_=nt?.variables,Se=_?.colorPrimary??"#4A49FF",Bt=_?.colorPrimaryHover??_c(Se,.12),ce=_?.borderRadius??"8px";return oy(ry,{children:[ao("button",{...st,type:et,onClick:vn,disabled:Ue||pt,"aria-busy":pt,style:{width:"100%",...Qe===void 0?{boxSizing:"border-box",height:Xp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...lt.cardButton,...us({themeBundle:P,resolvedPrimaryColor:Se,resolvedBorderRadius:ce,submitButtonStyle:lt.submitButton,explicitPrimaryColor:_?.colorPrimary}),fontSize:lt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ue||pt?"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:Ue||pt?.6:1,...kt},onMouseEnter:m=>{st.onMouseEnter?.(m),!m.defaultPrevented&&!Ue&&!pt&&(P||_?.colorPrimary)&&(m.currentTarget.style.backgroundColor=Bt)},onMouseLeave:m=>{st.onMouseLeave?.(m),!m.defaultPrevented&&(P||_?.colorPrimary)&&(m.currentTarget.style.backgroundColor=Se)},onMouseDown:m=>{st.onMouseDown?.(m),m.defaultPrevented||(m.currentTarget.style.transform="scale(0.985)")},onMouseUp:m=>{st.onMouseUp?.(m),m.defaultPrevented||(m.currentTarget.style.transform="scale(1)")},children:ao(vo,{content:Qe})}),X&&ao("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:X}),fe&&ao(Sr,{status:fe,errorMessage:pe,authorized:xt}),oe&&ao("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:m=>{m.target===m.currentTarget&&L(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:ao("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:ao(bs,{sessionId:oe.sessionId,nonce:oe.nonce,checkoutMode:"full",billingApiUrl:Z,locale:V,theme:f,...nt?{appearance:nt}:{},buttonsTheme:He,buttonsStyles:R,initialErrorMessage:oe.errorMessage,initialPayPalOrderId:oe.payPalOrderId,cardTitleContent:null,onComplete:It,onError:Pt,onDecline:le})})})]})}import{jsx as sy}from"react/jsx-runtime";var ay={StripeSetupMethod:Cl,PayPalSetupMethod:vl};function iy(e){return sy(bl,{...e,branches:ay})}export{Wa as DirectPayPalButton,ny as FloPayAutomaticPaymentButton,id as FloPayCardSetup,ad as FloPayCardSetupError,bs as FloPayCheckout,iy as FloPayPaymentMethodSetup,Ga as FloPayProvider,ps as SplitCardForm,Ti as VaultCardFields,Bf as dropThirdPartyOnlyError,_d as useCheckout,$r as useFloPay,zi as usePayPalFloPay};
21
+ `})]})}return yn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&Z(Uo),n&&(o||a)&&Z(Uo),n&&me("button",{type:"button",onClick:()=>{e?.("card"),O(!0)},style:{width:"100%",...m,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:N.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...N.cardButton},onMouseDown:b=>{b.currentTarget.style.transform="scale(0.985)"},onMouseUp:b=>{b.currentTarget.style.transform="scale(1)"},children:me(wo,{content:u})}),me("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as dy,jsx as lo,jsxs as uy}from"react/jsx-runtime";var ay=44;function Kc(e){return new Promise(t=>setTimeout(t,e))}function iy(e,t){return e instanceof ka?e:new ka(e instanceof Error?e.message:t,"api_error")}function sy(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ly(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 cy({sessionId:e,nonce:t,createSession:n,paymentMethodId:o,checkoutMethod:a,clientId:i,products:s,items:l,subscriptions:u,account:C,successUrl:_,cancelUrl:k,couponCodes:O,tagsData:ue,utmMetadata:N,billingApiUrl:Ae,locale:Z,theme:m,appearance:b,buttonsTheme:Ve,buttonsStyles:I,onSuccess:Xe,onError:Y,onDecline:Fe,children:nt,disabled:ze=!1,type:He="button",style:It,...it}){let te=wa(()=>ny(Ae),[Ae]),xt=wa(()=>ly({createSession:n,clientId:i,products:s,items:l,subscriptions:u,account:C,successUrl:_,cancelUrl:k,couponCodes:O,tagsData:ue,utmMetadata:N}),[C,k,i,O,n,s,l,u,_,ue,N]),[ut,rt]=$o(!1),[ge,se]=$o(null),[fe,wt]=$o(null),[Bt,Qe]=$o(!1),[ne,Me]=$o(null),[de,L]=$o(null),Ue=jo(!0),De=jo(null),Oe=jo(de),M=jo(Xe),qe=jo(Y),gt=jo(Fe),_e=Ur(p=>ei(De,async v=>{try{return await p(v)}catch(we){throw v.aborted?Fo(we):we}}),[]);qo(()=>{Oe.current=de},[de]),qo(()=>{M.current=Xe},[Xe]),qo(()=>{qe.current=Y},[Y]),qo(()=>{gt.current=Fe},[Fe]),qo(()=>(Ue.current=!0,()=>{Ue.current=!1,De.current?.abort()}),[]),qo(()=>{if(typeof window>"u")return;let p=v=>{v.key==="Escape"&&L(null)};return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p)}},[]);let ht=Ur((p,v=fa)=>{gt.current?.(Sn(v,p,{code:p.code,declineCode:p.declineCode}))},[]),ve=Ur(async p=>{Ue.current&&(wt(null),Qe(p.result.status==="authorized"),se("success"),await Kc(600),Ue.current&&Lt(()=>M.current?.(p)))},[]),je=Ur(async(p,v)=>{Ue.current&&(qe.current?.(p),v?.emitDecline&&ht(p,v.method),wt(p.message),Qe(!1),se("error"),await Kc(400))},[ht]),Ke=Ur(async(p,v,we)=>{let Ce=p.data.session??null;if(!Ce)throw Wr(new ka("No session data returned","api_error"),v);let et=Ce.clientSecret||t;if(Or(Ce)){await ve({result:Dr(Ce,v),session:Ce,sessionId:Ce.id||v,autoCompleted:!1});return}if(Ce.status==="expired")throw Wr(Ua(Ce),Ce.id||v);try{if(p.autoProcessingPending){let ke=p.autoProcessingPending,Ie=new Rs(te),Dt=await _e(he=>Ie.waitForCheckoutSessionCompletion(ke.sessionId,{initialDelayMs:ke.retryAfterMs,nonce:et,statusUrl:ke.statusUrl,signal:he})),d=Vr(Dt,Ce),xe=Dt.autoProcessingError?.type==="3ds_required"&&Dt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Dt.autoProcessingError.nextActionRedirectUrl}:null;if(xe&&v&&et){let he=await _e(Re=>Do(xe,{billingApiUrl:te,sessionId:v,nonce:et,session:Ce,signal:Re,telemetry:!0}));await ve({result:he,session:Ce,sessionId:Ce.id||v,autoCompleted:!1});return}if(Dt.autoProcessingError)throw Ir(Dt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Dt.autoProcessingError.checkoutMethod});if(!Or(d))throw Eo(d);await ve({result:Dr(d,v),session:d,sessionId:d.id||v,autoCompleted:!1});return}if(p.autoProcessingError){let ke=p.autoProcessingError.nextActionRedirectUrl;if(p.autoProcessingError.type==="3ds_required"&&ke&&v&&et){let Ie=await _e(he=>dc({billingApiUrl:te,sessionId:v,nonce:et,nextActionRedirectUrl:ke,signal:he}));if(Ie.status==="declined")throw Ir({type:Ie.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ie.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:p.autoProcessingError.checkoutMethod});let d=await new Rs(te).waitForCheckoutSessionCompletion(v,{initialDelayMs:0,nonce:et}),xe=Vr(d,Ce);if(!Or(xe))throw Ir({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:p.autoProcessingError.checkoutMethod});await ve({result:Dr(xe,v),session:xe,sessionId:xe.id||v,autoCompleted:!1});return}throw Ir(p.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:p.autoProcessingError.checkoutMethod})}if(we?.fromCreateSession&&p.autoProcessingAttempted===!0)throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ge=await Oo({billingApiUrl:te,sessionId:v??Ce.id,session:Ce,nonce:et});if(Ge.type==="next_action_required"&&et){let ke=v??Ce.id,Ie=await _e(Dt=>Do(Ge,{billingApiUrl:te,sessionId:ke,nonce:et,session:Ce,signal:Dt,telemetry:!0}));await ve({result:Ie,session:Ce,sessionId:Ce.id||ke,autoCompleted:!1});return}if(Ge.type!=="success")throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await ve({result:Ge.result,session:Ce,sessionId:Ce.id||v,autoCompleted:!1})}catch(Ge){let ke=Ce.id||v,Ie=Wr(ga(Ge),ke);if(Ie.code==="three_ds_aborted")return;if(Ie.code==="checkout_processing_timeout"){if(!Ue.current)return;Me(Ie.message),Lt(()=>qe.current?.(Ie));return}await je(Ie,{emitDecline:!0,method:Ie.checkoutMethod??fa}),sy(Ie,ke)&&ke&&Ue.current&&L({sessionId:ke,errorMessage:Ie.message,nonce:et||void 0,payPalOrderId:Ie.orderId})}},[t,te,_e,je,ve]),wn=Ur(async p=>{if(it.onClick?.(p),!(p.defaultPrevented||ze||ut)){if(L(null),Me(null),e&&xt){let v=new ka("Provide either sessionId or create-session props, not both.","validation_error");await je(v),Ue.current&&(se(null),wt(null));return}if(!e&&!xt){let v=new ka("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await je(v),Ue.current&&(se(null),wt(null));return}rt(!0),wt(null),Qe(!1),se("processing");try{let v=new Rs(te);if(e){let we=await v.getUnifiedCheckoutSession(e,t);await Ke(we,e);return}try{let we=await v.createAndFetchSession({...xt});await Ke(we,we.data.session?.id??null,{fromCreateSession:!0})}catch(we){if(qa(we)==="session_auto_completed"){await ve({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw we}}catch(v){await je(Wr(iy(v,"Automatic payment failed. Please try again."),e))}finally{Ue.current&&(se(null),wt(null),rt(!1))}}},[it.onClick,xt,ze,ut,t,Ke,te,e,je,ve]),Et=Ur(p=>{let v=Oe.current;L(null),M.current?.({result:p,session:null,sessionId:v?.sessionId??null,autoCompleted:!1})},[]),Pt=Ur(p=>{qe.current?.(p)},[]),pe=Ur(p=>{gt.current?.(p)},[]),P=wa(()=>oy(m),[m]),st=wa(()=>{let p=P?.buttonsLayout??ry(Ve);return I?{...p,...I,cardButton:{...p.cardButton,...I.cardButton}}:p},[P,Ve,I]),ot=wa(()=>{let p=P?.appearance;return b?p?{...p,...b,variables:{...p.variables,...b.variables}}:b:p},[b,P]),R=ot?.variables,Se=R?.colorPrimary??"#4A49FF",Ft=R?.colorPrimaryHover??Dc(Se,.12),ye=R?.borderRadius??"8px";return uy(dy,{children:[lo("button",{...it,type:He,onClick:wn,disabled:ze||ut,"aria-busy":ut,style:{width:"100%",...nt===void 0?{boxSizing:"border-box",height:ay,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...st.cardButton,...fs({themeBundle:P,resolvedPrimaryColor:Se,resolvedBorderRadius:ye,submitButtonStyle:st.submitButton,explicitPrimaryColor:R?.colorPrimary}),fontSize:st.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ze||ut?"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:ze||ut?.6:1,...It},onMouseEnter:p=>{it.onMouseEnter?.(p),!p.defaultPrevented&&!ze&&!ut&&(P||R?.colorPrimary)&&(p.currentTarget.style.backgroundColor=Ft)},onMouseLeave:p=>{it.onMouseLeave?.(p),!p.defaultPrevented&&(P||R?.colorPrimary)&&(p.currentTarget.style.backgroundColor=Se)},onMouseDown:p=>{it.onMouseDown?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(0.985)")},onMouseUp:p=>{it.onMouseUp?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(1)")},children:lo(wo,{content:nt})}),ne&&lo("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ne}),ge&&lo(wr,{status:ge,errorMessage:fe,authorized:Bt}),de&&lo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:p=>{p.target===p.currentTarget&&L(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:lo("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:lo(Is,{sessionId:de.sessionId,nonce:de.nonce,checkoutMode:"full",billingApiUrl:te,locale:Z,theme:m,...ot?{appearance:ot}:{},buttonsTheme:Ve,buttonsStyles:I,initialErrorMessage:de.errorMessage,initialPayPalOrderId:de.payPalOrderId,cardTitleContent:null,onComplete:Et,onError:Pt,onDecline:pe})})})]})}import{jsx as my}from"react/jsx-runtime";var py={StripeSetupMethod:El,PayPalSetupMethod:Rl};function yy(e){return my(_l,{...e,branches:py})}export{Ya as DirectPayPalButton,cy as FloPayAutomaticPaymentButton,yd as FloPayCardSetup,pd as FloPayCardSetupError,Is as FloPayCheckout,yy as FloPayPaymentMethodSetup,Qa as FloPayProvider,gs as SplitCardForm,Bi as VaultCardFields,$f as dropThirdPartyOnlyError,Dd as useCheckout,Hr as useFloPay,$i as usePayPalFloPay};