@flopay/react 1.14.7 → 1.14.9

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 Tl}from"./chunk-D4CVZRT4.mjs";import{c as Tt,d as Rr,e as na,f as Di,g as hl,h as Pd,j as vd}from"./chunk-YR36EYW2.mjs";import{a as _l}from"./chunk-BU7THP6H.mjs";import{a as oa,b as qa,c as Li,d as Ui,e as zi,f as Sl,g as wl,h as kl,i as Il,j as Rl,k as El}from"./chunk-FGCZOMML.mjs";import{a as La,b as Oi,c as Pl,d as Ni,e as Co,f as vl,g as Vr,h as Ua,i as Cl,j as ra,k as za,l as bl}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as Yf}from"@flopay/shared";import{PaymentAPI as _s}from"@flopay/js";import{FloPayError as ka,resolveBillingApiUrl as sy,resolveButtonsLayoutTheme as ly,resolveTheme as cy}from"@flopay/shared";import{useCallback as jr,useEffect as qo,useMemo as wa,useRef as jo,useState as $o}from"react";import{Fragment as ko,jsx as sr,jsxs as Ml}from"react/jsx-runtime";function Cd(){return Ml(ko,{children:[Ml("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[sr("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),sr("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",sr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:sr("path",{d:"M9 18l6-6-6-6"})})]})}function bd(){return sr(ko,{children:"Go back"})}function Sd(){return sr(ko,{children:"Secure card checkout"})}function bo(e){return e!==void 0&&(e===""||e===null||e===!1)}function So({content:e}){return sr(ko,{children:e===void 0?sr(Cd,{}):e})}function wo({content:e}){return sr(ko,{children:e===void 0?sr(bd,{}):e})}function aa({content:e}){return sr(ko,{children:e===void 0?sr(Sd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as wd,canRecoverHostedCardForm as kd,classifyTelemetryFailure as Id,FloPayError as Zn,isCardHolderNamePlaceholder as Rd,isMoneySettledOutcome as _d,isMountableVaultBlock as Ed,isSetupIntentClientSecret as Td,isValidEmail as Md,resolveSetupFutureUsage as Ad,resolveWalletModeOptions as xd}from"@flopay/shared";import{canRecoverHostedCardForm as oo,hasServerSideCardGateway as jl}from"@flopay/shared";import{splitFullName as la}from"@flopay/shared";import{applyFriendlyMessageOverride as _o}from"@flopay/shared";function qi(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 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 Al(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(Ed(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||kd(o))||t&&e?.data.paypal?.publishableKey)}function xl(e,t){if(t&&(!(e instanceof Zn)||e.type==="authentication_error"))return qi(e);if(!(e instanceof Zn&&Bd(e))){if(!t&&!(e instanceof Zn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Id(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 Io(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=Rd(s.firstName,s.lastName);if(!Md(s.email))return Promise.reject(new Zn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[C,T]of Object.entries(s)){if(l&&C.endsWith("Name")||typeof T!="string")continue;let I=T.trim();I&&(m[C]=I)}return a=e.claimCheckoutSession(t,n,{accountData:m}),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 ji(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 $i(e,t){return t?{...e,...t}:e}function fn(e,t,n){let o=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:o,...a?{code:a}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}var Dl=new WeakMap;function Ol(e,t){return typeof e=="object"&&e!==null&&Dl.set(e,t?{sessionId:t}:{}),e}function Nl(e){return typeof e=="object"&&e!==null?Dl.get(e):void 0}function Hr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Lr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Ur(e){return e?.status==="authorized"||e?.status==="complete"}function Kr(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 Ll(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ja(e){let t=Ll(e);return new Zn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $a(e){return e instanceof Zn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Ro(e){return Ll(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(wd,"api_error",{code:"checkout_processing_timeout"})}function ia(e,t){return e==="processing"||_d(e,t)}function Ul(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function zl(e,t){let n=e;if(Td(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 Fd=["apple_pay","google_pay"];function ql(e,t="automatic",n){let o=Ad(n,Fd,"wallet");return{...xd(e,t),allowedPaymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Dd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Wi(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:Dd.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 $p,PaymentAPI as yi,SESSION_CREATE_TELEMETRY as Wp}from"@flopay/js";import{buildCheckoutDisplayData as Vp,classifyTelemetryFailure as Yc,FloPayError as Mn,isDetachedSessionEligible as Hp,isMountableVaultBlock as Kp,resolveBillingApiUrl as Gp,resolveButtonsLayoutTheme as Yp,resolveDirectPaypalConfig as Jc,resolveIdempotencyKey as qc,resolveCheckoutLogLayout as Jp,resolveTheme as Xc,SDK_VERSION as Zc,telemetryStatusClass as Xp,toPublicCheckoutInitError as jc}from"@flopay/shared";import Ps,{useCallback as Nn,useEffect as hr,useMemo as cr,useRef as Nt,useState as Xt}from"react";import{createContext as $l}from"react";var lr=$l({flopay:null,paypalFlopay:null,billingApiUrl:""}),mr=$l({session:null,loading:!1,error:null});import{PaymentAPI as Hi}from"@flopay/js";import{buildPayPalCancelEvent as Jd,buildPayPalProcessPaymentRequest as Xd,buildPayPalSessionIntentRequest as Zd,buildPayPalTokenizedBody as Qd,classifyTelemetryFailure as eu,describePayPalProcessFailure as Xl,FloPayError as Ao,friendlyPayPalFailureMessage as tu,generateIdempotencyKey as nu,isPayPalTeardownMessage as ru,isSettledSessionIntent as ou,isValidEmail as Zl,mergePayPalPayerIdentity as au,needsPayPalPayerDetails as iu,normalizeGatewayEnvironment as su,paypalProviderIdentityRequired as Ql,resolvePayPalApprovalIdentity as lu,resolvePayPalDeclineReason as cu,SDK_VERSION as du,usesPayPalVaultedChannel as uu}from"@flopay/shared";import{loadScript as pu}from"@paypal/paypal-js";import{useCallback as _r,useContext as yu,useEffect as Ut,useMemo as pa,useRef as rt,useState as zr}from"react";import{compactBuyerIdentity as Od,isValidEmail as Nd}from"@flopay/shared";import{useCallback as Wl,useEffect as Ld,useRef as Vl,useState as Kl}from"react";import{compactBuyerIdentity as fr}from"@flopay/shared";import{jsx as Hl,jsxs as ca}from"react/jsx-runtime";function Eo(){let[e,t]=Kl(null),n=Vl(null),o=Vl(0),a=Wl((s,l)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:l}),new Promise(m=>{n.current=m})),[]),i=Wl(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Ld(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function To({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Kl(e.email?.trim()??""),m=Nd(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",Hl("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&&Hl("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),ca("button",{type:"button",disabled:!m||a,onClick:()=>{n(Od({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as Ud}from"@flopay/shared";import{useContext as Wa}from"react";function Gr(){return Wa(lr).flopay}function Vi(){return Wa(lr).paypalFlopay??null}function zd(){return Wa(mr)}function Gl(){return Wa(lr).billingApiUrl||Ud()}import{FLO_INSTRUMENT_ONCE_NAMES as qd,invokeMerchantCallback as jd,projectFloInstrument as $d}from"@flopay/shared";import{useCallback as Wd,useRef as Va}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Yl}from"@flopay/shared";function Mo(e,t){let n=Va(e);n.current=e;let o=Va(new Set),a=Va(t),i=Va(t);return na(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),Wd(s=>{if(i.current!==t)return;let l=$d(s);if(l){if(qd.has(l.name)){if(o.current.has(l.name))return;o.current.add(l.name)}jd(()=>n.current?.(l))}},[t])}import{createContext as Vd}from"react";var da=Vd(null);function Ha(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Ka="provider.callback.ignored";function Ga(){let e,t=0;return{take(n){return n!==e&&(e=n,t=0),t>=5?!1:(t+=1,!0)}}}var Hd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Kd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Gd(){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 Yd(e){let t=Gd(),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 Ya(e){let t=globalThis[Kd];return Yd(t?.(e)??{})}function gn(e){if(e)return e[Hd]}import{useCallback as Yr,useEffect as Jl,useRef as ao}from"react";function ua(e,t){let n=ao(0),o=ao(null),a=ao(null),i=ao(e),s=ao(t?.onHandoffObserved),l=ao(t?.defersMissingTerminal),m=ao(t?.onMissingTerminalDeferred);Jl(()=>{i.current=e,s.current=t?.onHandoffObserved,l.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let C=Yr((g=a.current)=>{g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),T=Yr(g=>{C();let S=n.current+1;return n.current=S,o.current=null,a.current={generation:S,method:g,timer:null,yieldedControl:!1},S},[C]),I=Yr(g=>{let S=a.current;return g!==void 0&&S?.generation!==g?!1:(C(S),a.current=null,(g===void 0||o.current===g)&&(o.current=null),!0)},[C]),N=Yr(g=>{let S=a.current,Ve=g??S?.generation??n.current;(g===void 0||S?.generation===g)&&(C(S),a.current=null),o.current=Ve},[C]),ue=Yr(g=>o.current===(g??n.current),[]),L=Yr(g=>a.current?.generation===g&&o.current!==g,[]),Be=Yr(()=>{let g=a.current;g&&(C(g),!g.yieldedControl&&(g.yieldedControl=!0,s.current?.(g.method)))},[C]),K=Yr(()=>{let g=a.current;!g?.yieldedControl||document.visibilityState!=="visible"||(C(g),g.timer=setTimeout(()=>{if(g.timer=null,a.current?.generation===g.generation){if(l.current?.(g.method)){m.current?.(g.method,g.generation);return}a.current=null,o.current=g.generation,i.current(g.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},Pl))},[C]);return Jl(()=>{let g=()=>{document.visibilityState==="visible"?K():Be()};return document.addEventListener("visibilitychange",g),window.addEventListener("blur",Be),window.addEventListener("focus",K),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("blur",Be),window.removeEventListener("focus",K),C()}},[C,Be,K]),{startAttempt:T,finishAttempt:I,invalidateAttempt:N,isAttemptInvalidated:ue,isAttemptCurrent:L,generationRef:n}}import{jsx as io,jsxs as Ki}from"react/jsx-runtime";var Ja=45,mu=1e3,fu=11e3,ec="paypal_intent_settled",gu={width:"100%",minHeight:Ja,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"},hu={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 Pu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:hu[e.kind]??null}}function tc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":vl(t)?"paypal_init_timeout":"paypal_init_failure"}function vu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function nc({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:l,currency:m,isSubscription:C,providerObjectType:T,approvalPresentation:I,onTokenizedBody:N,onComplete:ue,onErrorChange:L,onDecline:Be,onCancel:K,onTechnicalFailure:g,isProcessing:S=!1,onLoadStateChange:Ve,onInitializationStateChange:R,allowAutomaticRetry:Xe=!0,onButtonClick:H,runBeforeButtonClick:Ne,session:ot,existingOrderId:ze,telemetry:qe,telemetryContext:It,onInstrument:st,debug:ee=!1}){let Bt=Gr(),ut=Mo(st,e),at=pa(()=>{if(Bt)return null;let U=Ya({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:du,enabled:qe!==!1});return U.setCheckoutContext(It??{}),U.beginCheckout(It??{}),U},[n,Bt,qe,It?.checkoutMode,It?.layout]),fe=pa(()=>gn(Bt),[Bt]);Ut(()=>()=>{at&&at.flush().catch(()=>{}).finally(()=>at.destroy())},[at]);let ie=pa(()=>({error:U=>{fe?fe.error(U):at?.error(U),ut({class:"technical_error",errorCode:U.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":U.errorCode,requestCategory:U.requestCategory,provider:U.provider})},log:U=>{fe?fe.log(U):at?.log(U),ut({class:"lifecycle",name:U.name,provider:U.provider})},performance:U=>{fe?fe.performance(U):at?.performance(U)},terminal:U=>{fe?fe.terminal(U):at?.terminal(U)},startTiming:()=>fe?.now()??at?.now()??0,elapsed:U=>fe?.elapsed(U)??Math.max(0,(at?.now()??U)-U)}),[ut,fe,at]),pe=rt(null),ft=rt(0),Ft=rt(null),Ze=rt(null),Y=rt(null),_e=yu(da),se=rt(null);se.current||(se.current=Ha());let O=_e??se.current,je=rt(null),Le=rt(!1),[Fe,E]=zr(!1),[De,gt]=zr(!1),[Ee,ht]=zr(0),Pe=rt(0),[$e,He]=zr(!1),In=rt(!1),_t=rt(!1),[Pt,ce]=zr(!1),[h,lt]=zr(!1),{request:Qe,collect:_,finish:Ce}=Eo(),Dt=rt({sessionId:e,required:Ql(o,ot)});Dt.current.sessionId!==e&&(Dt.current={sessionId:e,required:Ql(o,ot)});let de=Dt.current.required,kt=pa(()=>n.replace(/\/+$/,""),[n]),P=ot?.gateways?.paypal?.providerObjectType??T,ge=P??(C?"subscription":"order"),[ve]=zr(ra),et=ot?.gateways?.paypal?.approvalPresentation??I,Ke=za(ve,et==="app_switch"?"app_switch":void 0,ge),be=uu(P),we=pa(()=>JSON.stringify([kt,s,m,l??"",ge,be,Ke,e,ze??""]),[kt,s,m,l,ze,ge,be,Ke,e]),Ot=rt(we),p=Ot.current!==we,Oe=rt(ee),he=rt(null),[Se,J]=zr([]),z=_r(U=>{Oe.current&&J(vt=>[...vt,`${new Date().toISOString().slice(11,23)} ${U}`])},[]);Ut(()=>{Oe.current=ee,ee&&z("debug:enabled"),he.current?.setEnabled(ee)},[z,ee]);let Pn=rt(N),Wn=rt(ue),Zt=rt(L),zt=rt(Be),pt=rt(K),Ln=rt(g),An=rt(H),Qt=rt(Ve),Vn=rt(R),yt=rt(i),Pr=rt(Ne),Vt=rt(ot),rr=rt(o),Un=rt(a),zn=rt(t),Ht=rt(null),un=rt(new Map),Hn=rt(new Map),Me=rt(!1),it=rt(e);it.current=e;let[Rn]=zr(Ga);Ut(()=>(Me.current=!0,()=>{Me.current=!1}),[]),Ut(()=>{Pn.current=N},[N]),Ut(()=>{yt.current=i},[i]),Ut(()=>{Wn.current=ue},[ue]),Ut(()=>{Zt.current=L},[L]),Ut(()=>{zt.current=Be},[Be]),Ut(()=>{pt.current=K},[K]),Ut(()=>{Ln.current=g},[g]),Ut(()=>{An.current=H},[H]),Ut(()=>{Qt.current=Ve},[Ve]),Ut(()=>{Vn.current=R},[R]),Ut(()=>{Pr.current=Ne},[Ne]),Ut(()=>{Vt.current=ot},[ot]),Ut(()=>{rr.current=o},[o]),Ut(()=>{Un.current=a},[a]),Ut(()=>{zn.current=t},[t]),Ut(()=>{Pe.current=Ee},[Ee]),Ut(()=>{$e&&je.current?.focus()},[$e,Ee]);let qt=_r(()=>{window.setTimeout(()=>{je.current?.focus()},0)},[]),en=_r(()=>{E(!1),ht(U=>U+1)},[]),pn=_r(()=>{He(!1),(pe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??pe.current)?.focus?.()},[]);Ut(()=>{!Fe||!Le.current||(Le.current=!1,pn())},[pn,Fe,Ee]);let Kt=_r((U,vt)=>{let x=vt?.popupBlocked??Vr(U);x&&O.markBlocked();let $t=La("PayPal",x,ve.inAppBrowser),rn=Ln.current;if(rn){let X=x&&ve.inAppBrowser?new Ao($t,"api_error",{code:vt?.code??"paypal_popup_blocked"}):U;rn("paypal",X,vt);return}if(U instanceof Ao&&U.code==="checkout_processing_timeout"){Zt.current?.(U.message);return}Zt.current?.($t)},[O,ve.inAppBrowser]),jt=_r(U=>{let vt=Ft.current,x=Ze.current;vt===null||!x||(ie.log({...x,popupCapability:O.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:U}),ie.performance({...x,popupCapability:O.current(),stage:"overlay_return",durationMs:ie.elapsed(vt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:U}),Ft.current=null)},[O,ie]),vn=_r((U,vt,x)=>{let $t=Ze.current;jt("overlay_timeout"),$t&&ie.error({...$t,popupCapability:O.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Kt(vt,{...x,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Ke,terminalReason:"overlay_timeout"}),He(!0),en(),qt()},[jt,qt,Kt,O,Ke,en,ie]),ke=_r(()=>{O.markAvailable();let U=Ze.current;U&&(Y.current=U.attempt,ie.log({...U,popupCapability:O.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[O,ie]),{finishAttempt:tn,generationRef:Cn,invalidateAttempt:xr,isAttemptCurrent:xn,isAttemptInvalidated:Bn,startAttempt:vr}=ua(vn,{onHandoffObserved:ke}),Qn=_r(()=>(He(!1),vr("paypal")),[vr]),nn=_r(U=>{xr(U?.generation),U?.showRetry&&He(!0),U?.remount&&en(),U?.focus!==!1&&qt()},[qt,xr,en]),G=U=>{let vt=Ht.current;return vt&&Hn.current.set(U,vt),U};Ut(()=>{Ot.current!==we&&(Ot.current=we,In.current=!1,_t.current=!1,E(!1),gt(!1),ce(!1),Vn.current?.("loading"))},[we]),Ut(()=>{Tt(()=>Qt.current?.(Fe&&!Pt))},[Fe,Pt]);let yn=su(l);Ut(()=>{let U={attempt:Cn.current+1,inAppBrowser:ve.inAppBrowser,appFamily:ve.appFamily,popupCapability:O.current(),presentationMode:Ke},vt=()=>({...Ze.current??U,popupCapability:O.current()}),x={error:d=>ie.error({...d,...vt()}),log:d=>ie.log({...d,...vt()}),performance:d=>ie.performance({...d,...vt()}),terminal:d=>ie.terminal({...d,...vt()}),startTiming:ie.startTiming,elapsed:ie.elapsed},$t=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",rn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(z(`mount clientId=${$t} env=${l??"(unset)"}\u2192${yn??"live"} ccy=${m} sub=${C}`),z(`ua=${rn.slice(0,80)}${rn.length>80?"\u2026":""}`),!s){z("FAIL: clientId empty \u2014 gateway misconfigured"),ce(!0),x.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){z("FAIL: containerRef not attached");return}ft.current=x.startTiming(),x.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let X=!1,Lt=!1,q=()=>X||Lt,Et=d=>{let c=Me.current,v=c?d:"torn_down";c&&z(`onError ignored reason=${v}`),Rn.take(it.current)&&x.log({name:Ka,stage:"provider_ready",reason:v,provider:"paypal",paymentMethodCategory:"paypal"})},mn=()=>it.current===e?"stale_attempt":"session_changed",Fn=be?ge:void 0,Gt,Cr=!1,Br=()=>{Gt=nu(),Gt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Cr=!0},br=null,Sr=!1,Fr=null,$r=!1,Wr=()=>{!Fr||$r||($r=!0,Fr.close().catch(()=>{}))},_n=!1,Dr=!1,or=pe.current,At=null,Kn=null,Gn=[],er=null,Yn=!1,Ue=!1,ln=null,on=d=>{if(!d||typeof d.getBoundingClientRect!="function")return"(no rect)";let c=d.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},jn=d=>{if(!d)return"(empty)";try{let c=new URL(d,typeof window>"u"?"https://localhost":window.location.href),v=c.pathname.toLowerCase();return v.includes("checkcaptcha")||v.includes("captcha")?`CAPTCHA(${c.host}${v})`:v.includes("risk")||v.includes("challenge")?`RISK(${c.host}${v})`:v.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${v}`.slice(0,100)}catch{return d.slice(0,80)}},Qr=d=>{let c=d.getAttribute("src"),v=d.getAttribute("srcdoc"),Q=d.getAttribute("name"),re=d.getAttribute("sandbox"),b=[];return c&&b.push(`src=${jn(c)}`),v&&b.push(`srcdoc[${v.length}ch]`),!c&&!v&&b.push("src=(empty) srcdoc=(empty)"),Q&&b.push(`name=${Q.slice(0,40)}`),re!==null&&b.push(`sandbox="${re.slice(0,40)}"`),b.join(" ")},Or=d=>{if(!(d instanceof HTMLIFrameElement))return"";try{let c=d.contentDocument;if(!c)return"cd=null";let v=c.body?.children.length??0,Q=c.body?.innerHTML.length??0,re=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${v}children,${Q}ch] head[${re}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},dr=[],tr=d=>{if(q())return;let c=d.message??String(d.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(z(`window:error ${c.slice(0,140)}`),dr.push(c))},bn=d=>{if(q())return;let c=d.reason instanceof Error?d.reason.message:String(d.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(z(`window:rejection ${c.slice(0,140)}`),dr.push(c))},Nr={value:0},Dn=()=>{At?.disconnect(),At=null,Kn?.disconnect(),Kn=null;for(let d of Gn.splice(0))clearTimeout(d);Ue=!1,Yn&&typeof window<"u"&&(window.removeEventListener("error",tr),window.removeEventListener("unhandledrejection",bn)),Yn=!1},w=()=>{if(!(Yn||q()||_n)){if(Yn=!0,dr.length=0,Nr.value=0,typeof window<"u"&&(window.addEventListener("error",tr),window.addEventListener("unhandledrejection",bn)),typeof PerformanceObserver<"u")try{Kn=new PerformanceObserver(d=>{if(!q())for(let c of d.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Nr.value+=1;let v=Math.round(c.duration);z(`net ${v}ms ${c.name.slice(0,90)}`)}}),Kn.observe({type:"resource",buffered:!0})}catch{}ln?.()}},k=()=>{er&&(clearTimeout(er),er=null)},j=()=>{Dn(),k()},te={setEnabled:d=>{d?w():Dn()}};he.current=te,Oe.current&&w();let We=ru,Wt=d=>{if(q()||We(d))return;let c=_o(d)??d;Tt(()=>Zt.current?.(c))},ne=(d,c)=>{if(X||Sr)return;Sr=!0,Lt=!0,j(),Wr();let v=Pu({kind:d,generationActive:!0,automaticRetryAllowed:Xe,automaticRetryUsed:In.current});if(v.action==="retry"){In.current=!0,E(!1),lt(!1),gt(!0),Vn.current?.("retrying"),br=setTimeout(()=>{X||ht(Q=>Q+1)},mu);return}if(E(!1),lt(!1),gt(!1),ce(!0),v.action!=="ignore"){if(Vn.current?.("exhausted"),v.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",c);return}if(v.report){let Q=Oi({code:tc(d,c),message:c},{inAppBrowser:ve.inAppBrowser,handoffObserved:!1});Q.popupBlocked&&O.markBlocked(),x.error({errorCode:Q.popupBlocked?Q.errorCode:v.report.errorCode,stage:v.report.stage,operationOutcome:v.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:Q.terminalReason})}_t.current||(_t.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",tc(d,c)))}};ce(!1);let W=async(d,c=Ht.current)=>{if(q())return;let v=c?.sessionId??e;if(Pn.current){await Pn.current(d,{sessionId:v,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let Q=x.startTiming();x.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let re=()=>{x.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),x.performance({stage:"processing",durationMs:x.elapsed(Q),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let b=Xd({body:d,sessionId:v,nonce:c?.nonce??zn.current,accountPatch:c?.accountPatch,session:Vt.current,email:rr.current}),cn=await new Hi(kt,{telemetry:!1}).processPayment(b.userId,b.params);if(cn.ok){if(Lt||X&&Me.current)return;re(),x.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Tt(()=>Wn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(q())return;let wn=await cn.json().catch(()=>null),nt=Xl(wn),nr=nt.message;re(),cn.status===400&&(typeof wn?.declineCode=="string"||!Array.isArray(wn?.fields))?x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):cn.status===400||cn.status===422?x.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):x.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:vu(cn.status),failureCategory:cn.status>=500?"server_error":void 0}),Wt(nr),Tt(()=>zt.current?.(fn("paypal",nr,{code:nt.code,declineCode:nt.declineCode})));return}catch(b){if(q())return;re(),x.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let tt=tu(b instanceof Error?b.message:void 0);Wt(tt),Tt(()=>zt.current?.(fn("paypal",tt)));return}},B=()=>new Ao("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Z=d=>q()?Promise.reject(B()):Promise.resolve(d),F=async d=>{if(d.ok){x.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Tt(()=>Wn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let c=await d.json().catch(()=>null),v=Xl(c);x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Tt(()=>zt.current?.(fn("paypal",v.message,{code:v.code,declineCode:v.declineCode})))},Ae=()=>{let d=Ht.current;jt("approved"),d&&(un.current.delete(d.surfaceKey),tn(d.generation)),Ht.current=null},D=async d=>{if(q())throw B();Cr||Br();let c=Ht.current,v=c?.sessionId??e,Q=c?.nonce??zn.current;x.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let re;try{re=await new Hi(kt,{telemetry:!1}).createSessionIntent(v,Q??"",Zd(Fn),{idempotencyKey:Gt})}catch(b){throw x.error({...eu(b,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),b}if(q())throw B();if(ou(re))throw await F(re.response),Ae(),new Ao("PayPal checkout already settled.","api_error",{code:ec});if(re.provider!=="paypal"||re.providerObjectType!==ge)throw new Error(d);return x.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),re.providerObjectId},Ie=(d,c)=>{let v=c?.nonce??zn.current;if(!v)return;let Q=c?.sessionId??e,re=cu(d);new Hi(kt,{telemetry:!1}).reportSessionIntentDecline(Q,v,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:re}).catch(()=>{})},Re=Ee;z("loadScript:scheduled (deferred 1 tick)");let Ct=null,Sn=setTimeout(()=>{if(X){z("loadScript:skipped (cancelled before defer ran)");return}z("loadScript:start");let d=yn==="live"?"production":yn,c={};ge==="subscription"?c={intent:"subscription",vault:!0}:ge==="order"&&(c={intent:"capture"}),Ct=pu({clientId:s,currency:m,...c,...d?{environment:d}:{},...d==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let v=!1;Ct.then(Q=>{if(v=!0,z(`loadScript:resolved inactive=${q()} ns=${!!Q} buttons=${!!Q?.Buttons}`),q())return;if(!Q?.Buttons){z("FAIL: namespace missing Buttons factory"),ne("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}x.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),x.performance({stage:"provider_ready",durationMs:x.elapsed(ft.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),x.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let re=async($,Ge)=>{if(q()||Pe.current!==Re)return;let ct=$.vaultSetupToken??$.subscriptionID??$.orderID??"",bt=ct?Hn.current.get(ct):un.current.get(Re);if(!(!bt||!xn(bt.generation))&&tn(bt.generation)){Hn.current.delete(ct),un.current.delete(bt.surfaceKey),jt("approved");try{if(lt(!0),Tt(()=>Zt.current?.(null)),!ct)throw new Ao("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let xe=lu({accountPatch:bt.accountPatch,email:rr.current,billingName:Un.current,session:Vt.current});if(iu(xe))try{xe=au(xe,await Ge?.order?.get?.())}catch{}if((yt.current||de)&&!Zl(xe.email)){let Rt=await _("PayPal",xe);if(!Rt)return;xe=Rt}Zl(xe.email)&&(bt.accountPatch=fr({...bt.accountPatch,...xe}),await yt.current?.(xe));let $n=Qd(ct,Fn);await W($n,bt)}catch(xe){Wt(xe instanceof Error?xe.message:"PayPal capture failed.")}finally{q()||lt(!1)}}},b=$=>{let Ge=ze?()=>Z(ze):()=>D($);return async()=>G(await Ge())},tt=Q.Buttons({style:{layout:"horizontal",height:Ja,tagline:!1},...Ke==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async($,Ge)=>{if(q()){await Ge.reject();return}Br();let ct=Pr.current,bt={};if(ct)try{let Rt=await ct("paypal");if(q()){await Ge.reject();return}if(!Rt.proceed){Ht.current=null,un.current.delete(Re),await Ge.reject();return}bt={sessionId:Rt.sessionId,accountPatch:Rt.accountPatch,nonce:Rt.nonce}}catch(Rt){z(`onClick:runBeforeButtonClick rejected msg=${(Rt instanceof Error?Rt.message:String(Rt)).slice(0,120)}`),Ht.current=null,un.current.delete(Re),await Ge.reject();return}Tt(()=>An.current?.("paypal"));let xe=Qn(),$n={generation:xe,surfaceKey:Re,...bt};Ht.current=$n,un.current.set(Re,$n),Ze.current={...U,attempt:xe},await Ge.resolve(),x.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),x.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Ft.current=x.startTiming()},createOrder:ge==="order"?b("Failed to create PayPal order."):void 0,createSubscription:ge==="subscription"?b("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ge==="setup_token"?async()=>G(await D("Failed to create PayPal setup token.")):void 0,onApprove:re,onCancel:()=>{if(q())return;let $=un.current.get(Re)??Ht.current,Ge=$&&xn($.generation)?Jd($.sessionId??e,Fn):null;$&&un.current.delete($.surfaceKey),Ht.current=null,jt("cancelled"),x.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Le.current=!0,nn({generation:$?.generation,remount:!0,focus:!1}),Ge&&Tt(()=>pt.current?.(Ge))},onError:$=>{if($ instanceof Ao&&$.code===ec)return;let Ge=$ instanceof Error?$.message:"PayPal failed to render.";if(q()||Pe.current!==Re){We(Ge)||Et(mn());return}if(_n){let ct=un.current.get(Re)??Ht.current;if(!ct||!xn(ct.generation)){if(We(Ge)){!ct&&!Bn()&&tn();return}Et(ct||Bn()?"stale_attempt":"no_current_attempt");return}if(z(`onError rendered=${_n} msg=${Ge.slice(0,120)}`),We(Ge)){tn(ct.generation);return}let{errorCode:bt,popupBlocked:xe,providerDeclined:$n,terminalReason:Rt}=Oi($,{inAppBrowser:ve.inAppBrowser,handoffObserved:Y.current===ct.generation});if(xe&&O.markBlocked(),jt(Rt),$n){x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Rt}),Ie($,ct),Tt(()=>zt.current?.(fn("paypal",Ge))),un.current.delete(ct.surfaceKey),Ht.current=null,tn(ct.generation);return}x.error({errorCode:bt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Rt}),un.current.delete(ct.surfaceKey),Ht.current=null,nn({generation:ct.generation,remount:!0,showRetry:!0,focus:!0}),Kt($,{code:"paypal_runtime_failed",popupBlocked:xe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Ke,terminalReason:Rt});return}z(`onError rendered=${_n} msg=${Ge.slice(0,120)}`),ne(We(Ge)?"teardown":"pre_ready_callback",Ge)}}),cn=tt.isEligible();if(z(`isEligible=${cn}`),x.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!cn){E(!1),ne("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Dr=!0,Fr=tt,ln=()=>{if(!Yn||Ue||q()||_n)return;Ue=!0,z(`container:dims ${on(or)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(At=new MutationObserver(Ge=>{if(!q()){for(let ct of Ge)if(ct.type==="childList")ct.addedNodes.forEach(bt=>{if(!(bt instanceof Element))return;let xe=bt.tagName.toLowerCase(),$n=(bt.getAttribute("title")??"").slice(0,40),Rt=xe==="iframe"?` ${Qr(bt)}`:"";z(`child+ ${xe}${$n?` title="${$n}"`:""}${Rt} dims=${on(bt)}`)});else if(ct.type==="attributes"&&ct.target instanceof Element){let bt=ct.target;if(bt.tagName.toLowerCase()!=="iframe")continue;let xe=ct.attributeName;(xe==="src"||xe==="srcdoc")&&z(`attr~ iframe ${xe}=${xe==="srcdoc"?`[${(bt.getAttribute("srcdoc")??"").length}ch]`:jn(bt.getAttribute("src"))} dims=${on(bt)}`)}}}),At.observe(or,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let $=Ge=>{if(q()||_n)return;let ct=or.querySelectorAll("iframe"),bt=typeof document<"u"&&"hasStorageAccess"in document;z(`watchdog:${Ge} container=${on(or)} children=${or.childElementCount} iframes=${ct.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${bt} paypalNetRequests=${Nr.value}`),ct.forEach((xe,$n)=>{let Rt=(xe.getAttribute("title")??"").slice(0,40);z(` iframe[${$n}] ${on(xe)}${Rt?` title="${Rt}"`:""} ${Qr(xe)}`);let On=Or(xe);On&&z(` ${On}`)}),dr.length===0&&z(" (no PayPal/zoid window errors captured)")};Gn.push(setTimeout(()=>$("3s"),3e3)),Gn.push(setTimeout(()=>$("8s"),8e3)),Gn.push(setTimeout(()=>$("15s"),15e3))},ln(),z("render:start");let nt=x.startTiming();er=setTimeout(()=>{q()||_n||(z("watchdog:11s retryable render timeout"),ne("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},fu);let nr=tt.render(or);(async()=>{try{if(await nr,z(`render:resolved inactive=${q()}`),j(),q()){Wr();return}_n=!0,E(!0),gt(!1),Vn.current?.("ready"),x.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),x.performance({stage:"checkout_render",durationMs:x.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch($){let Ge=$ instanceof Error?$.message:"PayPal failed to render.";z(`render:rejected msg=${Ge.slice(0,120)}`),j(),ne(We(Ge)?"teardown":"render_rejected",Ge)}})()}).catch(Q=>{let re=Q instanceof Error?Q.message:"PayPal operation failed.";z(`provider:failed msg=${re.slice(0,120)}`);let b="script_rejected";v&&We(re)?b="teardown":v&&Dr&&(b="render_rejected"),ne(b,re)})},0);return()=>{X=!0,clearTimeout(Sn),br&&clearTimeout(br),j(),he.current===te&&(he.current=null),Wr(),Ft.current=null,Ze.current=null}},[Xe,kt,s,m,l,ge,Ke,be,e,ze,Ee,ie,_,de,z,jt]);let qn=ee?Ki("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=${Fe} failed=${Pt})`,Se.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
+ ${Se.join(`
4
+ `)}`]}):null;return Pt&&!p?ee?io("div",{children:qn}):null:Ki("div",{children:[qn,Qe&&io(To,{identity:Qe.identity,methodLabel:Qe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ce,onCancel:()=>Ce(null)}),Ki("div",{"aria-hidden":De||Qe?!0:void 0,style:De||Qe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ja},children:[!Fe&&!De&&io("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),io("div",{ref:pe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ja,display:"flex",opacity:Fe?1:0},"aria-busy":h||S},Ee)]},Ee),$e&&io("button",{ref:je,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:pn,style:gu,children:"Try PayPal again"})]})}function Xa(e){return io(nc,{...e})}function rc(e){return io(nc,{...e})}import{jsx as oc,jsxs as Cu}from"react/jsx-runtime";function xo({children:e,margin:t,icon:n=!0,styleOverride:o}){return Cu("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&&oc("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:oc("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 Za,clearCachedInlineSession as Gi,hashCreateParams as ac,legacyCachedSessionMatchesDraft as ic,persistCachedInlineIdempotencyKey as Qa,persistCachedInlineSession as ei,readCachedInlineIdempotencyKey as sc,readCachedInlineSession as lc,serializeCreateParams as ya}from"@flopay/shared";import{resolveBillingApiUrl as bu}from"@flopay/shared";import{useEffect as Jr,useMemo as Su,useRef as cc,useState as dc}from"react";import{jsx as wu}from"react/jsx-runtime";function ti({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=dc(e instanceof Promise?null:e),[l,m]=dc(t instanceof Promise||!t?null:t),C=cc(null),T=cc(null),I=Mo(o);Jr(()=>{I({class:"lifecycle",name:"checkout.mount"})},[I]),Jr(()=>{i&&I({class:"lifecycle",name:"sdk.initialize.ready"})},[I,i]),Jr(()=>{if(i)return gn(i)?.subscribe?.(I)},[I,i]),Jr(()=>{if(!(!l||l===i))return gn(l)?.subscribe?.(I)},[I,i,l]),Jr(()=>{if(!i)return;let L=gn(i);return C.current=L?.beginCheckout()??L?.now()??0,L?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{L?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Jr(()=>{let L=!1;return e instanceof Promise?e.then(Be=>{L||s(Be)},()=>{L||I({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{L=!0}},[I,e]),Jr(()=>{let L=!1;if(!t){m(null);return}return t instanceof Promise?t.then(Be=>{L||m(Be)},()=>{L||I({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{L=!0}},[I,t]),Jr(()=>{if(!i||T.current===i)return;T.current=i;let L=gn(i);L?.log({name:"checkout.rendered",stage:"checkout_render"}),I({class:"lifecycle",name:"checkout.rendered"}),L?.performance({stage:"checkout_render",durationMs:L.elapsed(C.current??0),durationMode:"machine"})},[I,i]);let N=bu(n?.billingApiUrl),ue=Su(()=>({flopay:i,paypalFlopay:l,billingApiUrl:N,emitInstrument:I}),[i,l,N,I]);return wu(lr.Provider,{value:ue,children:a})}import{markSessionRecentlyCompleted as Bo,wasSessionRecentlyCompleted as Yi}from"@flopay/shared";async function ni(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 ku,loadFloPay as uc,PaymentAPI as oi,runSavedCardChallenge as Iu}from"@flopay/js";import{classifyPaymentRejection as Ru,FloPayError as Mt,isAuthorizationOnlySession as _u,isMountableVaultBlock as Eu,isSetupIntentClientSecret as Tu,normalizeCheckoutFailureOutcome as pc}from"@flopay/shared";var fa="card";async function Mu(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 Au(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 Mt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function xu(){return new Mt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Xi(e,t){return Object.assign(e,{checkoutMethod:t})}function qr(e,t){let n=e instanceof Mt?e:new Mt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function ma(e,t){try{return await e()}catch(n){throw qr(n,t)}}function mc(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 fc(e){return Iu(e)}async function Do(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new oi(n,{telemetry:!1}),l=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,m;try{m=await ku({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:T=>Er({type:T.declineReason??"authorization_declined",gatewayErrorCode:T.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(T){if(a.aborted||T instanceof Error&&T.name==="AbortError")throw T instanceof Mt&&T.code==="three_ds_aborted"?T:Fo(T);if(!(T instanceof Mt)||T.code!=="three_ds_timeout"&&T.code!=="checkout_processing_timeout")throw T;try{m=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:l,timeoutMs:5e3,signal:a})}catch(N){if(a.aborted)throw Fo(N);if(!(N instanceof Mt)||N.code!=="checkout_processing_timeout")throw N}let I=m&&Kr(m,t.session);if(!Ur(I)&&I?.status!=="expired"){if(t.telemetry){let N=new oi(n);try{N.reportThreeDsAbandoned(o)}finally{N.destroy()}}throw xu()}}let C=m&&Kr(m,t.session);if(!Ur(C))throw Ro(C);return{...Lr(C,o),checkoutMethod:"card"}}function Er(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=Xi(new Mt(i,"api_error",{code:e?.code??pc(e?.outcome)??pc(e?.type)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Ji(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ri(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function gc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ri(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||ri(l)))return l;let s=a.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let m=l,C=[m.stripeClientSecret,m.clientSecret];for(let T of C)if(typeof T=="string"&&T.length>0&&(!t?.requirePaymentIntentClientSecret||ri(T)))return T}}}}async function Bu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=gc(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 oi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ri(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(/\/+$/,""),m=t??n.id,C=o??n.clientSecret,T=n.customer?.id??n.accountData?.userId??"",I=n.customer?.email??n.accountData?.email??"",N=n.customer?.firstName??n.accountData?.firstName??"",ue=n.customer?.lastName??n.accountData?.lastName??"",L=n.customer?.country??n.accountData?.country??void 0,Be=n.customer?.zip??n.accountData?.zip??void 0,g=await new oi(l,s===!1?{telemetry:!1}:void 0).processPayment(T,{sessionId:m,nonce:C,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:T,email:I,firstName:N,lastName:ue,country:L,zip:Be},returnUrl:i??Ji(n)});if(g.ok){let R=typeof g.json=="function"?await g.json().catch(()=>null):null;if(_u(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:m,authorizationExpiresAt:typeof R?.authorizationExpiresAt=="string"?R.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:sa(a),checkoutMethod:yc(a,n)}};let Xe=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Xe?{paymentIntentId:Xe}:{},paymentMethodId:sa(a),checkoutMethod:yc(a,n)}}}let S;try{S=await g.json()}catch(R){throw new Mt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:g.status,cause:R})}if(S?.type==="3ds_required"&&typeof S.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:S.nextActionRedirectUrl};if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let R=gc(S);if(!R)throw new Mt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:g.status});return{type:S.type,threeDSecureToken:R,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let R=await Bu({billingApiUrl:l,sessionId:m,nonce:C,responseJson:S});if(R)return R;throw Xi(new Mt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let Ve=new Mt(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:g.status});throw Object.assign(Ve,{telemetryOutcome:Ru(g.status,S)})}async function ai(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:l,telemetry:m,signal:C}){let T=t?.getRawProvider();if(!T)throw qr(new Mt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Xi(new Mt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let I=Tu(e.threeDSecureToken),N=null,ue=e.paymentMethodId,L=await ma(()=>Mu(T,e.threeDSecureToken,I),"card");if(L){if(L.error)throw qr(new Mt(L.error.message??`Failed to retrieve 3DS ${I?"setup":"payment"} status.`,"api_error",{code:L.error.code}),"card");let K=L.intent;!ue&&K?.payment_method&&(typeof K.payment_method=="string"?ue=K.payment_method:"id"in K.payment_method&&(ue=K.payment_method.id??void 0))}let Be=ue?await ma(()=>Au(T,e.threeDSecureToken,{payment_method:ue,return_url:l??Ji(s)??window.location.href},I),"card"):null;if(Be){if(Be.error)throw qr(new Mt(Be.error.message??"3DS authentication failed.","api_error",{code:Be.error.code}),"card");N=Be.intent}else{let K=await ma(()=>T.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(K.error)throw qr(new Mt(K.error.message??"3DS authentication failed.","api_error",{code:K.error.code}),"card");N=(I?K.setupIntent:K.paymentIntent)??null}if(N&&(N.status==="requires_capture"||N.status==="succeeded"||N.status==="processing")){let K=await Oo({billingApiUrl:a,sessionId:i,session:s,telemetry:m,tokenizedData:{id:N.id,type:"card",threeDSecureActionResultTokenId:N.id},returnUrl:l});return K.type==="success"?{...K.result,paymentIntentId:K.result.paymentIntentId??N.id,paymentMethodId:K.result.paymentMethodId??ue}:K.type==="next_action_required"?Do(K,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:C}):ai(K,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:l,telemetry:m,signal:C})}throw qr(new Mt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let I=(n??t)?.getRawProvider();if(!I)throw qr(new Mt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:ue}=await ma(()=>I.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(ue)throw qr(new Mt(ue.message??"PayPal authorization failed.","api_error",{code:ue.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:N}=await ma(()=>I.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??Ji(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(N)throw qr(new Mt(N.message??"PayPal authorization failed.","api_error",{code:N.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Mt("Unsupported payment redirect state.","api_error")}function ga(e){if(e instanceof Mt){let o=_o(e.message);return o&&o!==e.message?Object.assign(new Mt(o,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=_o(t)??t;return new Mt(n,"api_error")}function Zi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=Eu(e.data.session?.vault)||oo(e.data.session);if(!t&&!n&&!o)throw new Mt("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function yc(e,t){return e?e.isPaypal?"paypal":"card":t&&oo(t)?"card":void 0}async function Qi({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([uc(e,{billingApiUrl:n,locale:o,telemetry:a}),i?uc(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 Mt("The payment provider did not initialize.","authentication_error");let m=null;return i?m=l:t&&(m=s),{flopay:s,paypalFlopay:m}}import{PaymentAPI as No,PciVaultCardCapture as Fu,toStripeAppearance as Du}from"@flopay/js";import{buildCheckoutProcessMetadata as Ou,buildProcessPaymentAvsAccount as Nu,buildWalletSheetWindowMessage as Lu,COUNTRY_OPTIONS as Uu,classifyPaymentRejection as zu,clearStripePayPalReturn as qu,computeVaultCardThemeColors as ju,darkenHex as $u,denyPaymentPermissionToNewFrames as Wu,FloPayError as Tr,filterStripeMethodsByCountryGate as Vu,getPostalCodeExample as Hu,getPostalCodeLabel as ls,getStateFromPostalCode as Ku,getStateLabel as es,getStateOptions as Gu,getStripeMethodDisplayName as va,hasMatchingStripePayPalReturn as Yu,isAuthorizationOnlySession as ts,isAVSFieldVisible as Jt,isMountableVaultBlock as Ju,isPostalCodeSupported as Xu,isSettledSessionIntent as di,isSetupIntentClientSecret as ns,isValidEmail as Tn,isValidPostalCode as Zu,isWalletSheetRefusedForWindowSize as Qu,needsStripeMethodExplicitConfirm as hc,normalizeBeforeButtonClickError as Pc,normalizeCheckoutFailureOutcome as ep,partitionStripeMethods as tp,randomUuidV4 as np,readMatchingStripePayPalContinuation as rp,readStripeRedirectParams as Mc,resolveAVSConfig as op,resolveButtonsLayoutTheme as ap,resolveSetupFutureUsage as Ac,resolveTheme as ip,resolveVaultMountOptions as rs,STRIPE_PAYPAL_RESUME_KEY as sp,derivePrimaryTileStyle as lp,shouldPreferWalletPopup as vc,stripeExpressMethodToOptionKey as cp,stripeRedirectReturnUrl as xc,toCssWeight as dp,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as Bc}from"@flopay/shared";import{ExpressCheckoutElement as Fc,PaymentElement as up,Elements as lo,useElements as ps,useStripe as ys}from"@stripe/react-stripe-js";import pp,{useCallback as Te,useContext as Uo,useEffect as mt,useLayoutEffect as yp,useMemo as wt,useRef as V,useState as le}from"react";function so(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ii(e,t){if(e)return{error:n=>e.error(so(t,n)),log:n=>e.log(so(t,n)),performance:n=>e.performance(so(t,n)),terminal:n=>e.terminal(so(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 zc}from"@flopay/shared";import{Fragment as Lo,jsx as u,jsxs as Je}from"react/jsx-runtime";var Mr="flopay_stripe_resume",Cc="flopay_wallet_resume",Dc="fw1",mp="fw2",Oc=300*1e3,fp=900,gp="express_checkout_click_timeout",hp=25e3,Pp=25e3,vp=1e4,gr={provider:"paypal",paymentMethodCategory:"paypal"},Cp="x-flopay-process-result-source",bp="status";async function Sp(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 si={},Pa=class{constructor(t){this.reason=t}};function wp(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function sn(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ms(e){return`${mp}:${e}`}function li(e){return sn(ms(e))}function ci(e,t){if(typeof window>"u")return null;let n=ms(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>Oc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(li(e),null):a}catch{return li(e),null}}function kp(e){return sn(ms(e.sessionId),e)}function bc(e,t,n){let o=ci(e,t);return!o||o.clientSecret!==n?!1:li(e)}function os(e,t,n){if(typeof window>"u")return;ci(e,t)?.clientSecret===n&&li(e)}function Ip(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function as(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=Ip(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Sc(e,t,n){let o=null;try{return await Promise.race([zl(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},vp),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function Rp(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Nc(e){return e instanceof Tr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ui(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 Nc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var is=sp,ha=new Map,_p=250,wc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Ep="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function fs(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 pi({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new No(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function Tp(e){return e instanceof Tr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Lc({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=la(n),s=i.firstName?i:la(o?.name);return fr({email:Tn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Mp({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=Lc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return Tn(s.email)?s:i(a,s)}var Ca=180,kc=`flopay-card-enter ${Ca}ms cubic-bezier(0, 0, 0.2, 1) both`,Ic=`flopay-card-exit ${Ca}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Ap=`flopay-buttons-enter ${Ca}ms cubic-bezier(0, 0, 0.2, 1) both`,xp=`flopay-buttons-exit ${Ca}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 gs(e){return lp(e)}var Fp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Dp(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 cs={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 Rc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ds(e){return e==="paypal"?"PayPal":va(e)}function Op(e){let t=Hu(e);return`Enter a valid ${ls(e)}${t?` (e.g. ${t})`:""}`}function Np(e,t,n){let o=Xu(e),a=t.trim(),i=n&&o,s=i&&!a,l=i&&!!a&&!Zu(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:l}}function Lp(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!Tn(n);return{required:t,empty:o,malformed:a,value:n}}function Up(e){return typeof e=="number"?`${e}px`:e}function hs(e){return u(jp,{...e})}function _c({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:m,onTechnicalFailure:C,runBeforeButtonClick:T,billingName:I,onBuyerIdentityReady:N,onLoadStateChange:ue,placeholderBorderRadius:L,popupCapabilityOwner:Be,externalTelemetryContext:K,presentationMode:g}){let S=Gr(),{emitInstrument:Ve}=Uo(lr),R=ys(),Xe=ps(),H=wt(()=>ii(gn(S),K),[K,S]),[Ne,ot]=le("loading");mt(()=>{ue?.(Ne)},[Ne,ue]);let[ze,qe]=le(!1),It=V(!1),st=!Tn(n?.trim())||!I?.trim(),{request:ee,collect:Bt,finish:ut}=Eo(),at=V(!1),fe=V(null),ie=V(null),[pe,ft]=le(0),[Ft,Ze]=le(!1),Y=V(!1),_e=V(new Map),{startAttempt:se,finishAttempt:O,invalidateAttempt:je,isAttemptInvalidated:Le,isAttemptCurrent:Fe,generationRef:E}=ua((ce,h,lt)=>{C?.(ce,h,{...lt,popupBlocked:lt?.popupBlocked??Vr(h),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:g,terminalReason:"overlay_timeout"}),Ze(!0),ft(Qe=>Qe+1)},{onHandoffObserved:()=>{Be.markAvailable(),H?.log({name:"provider.popup.opened",stage:"overlay_open",...gr,attempt:E.current})}});mt(()=>{Ft&&ie.current?.focus()},[Ft,pe]);let De=Te(()=>{ft(ce=>ce+1)},[]),gt=Te((ce,h,lt)=>{je(lt),C?.("paypal",ce,{code:h,popupBlocked:Vr(ce),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:g}),Ze(!0),De()},[je,C,g,De]),Ee=Te(()=>{window.setTimeout(()=>{(fe.current?.querySelector("iframe")??fe.current)?.focus()},0)},[]);mt(()=>{Y.current&&(Y.current=!1,Ee())},[Ee,pe]);let ht=Te(()=>{Ze(!1),i?.(null),Ee()},[Ee,i]);mt(()=>{if(!R||at.current)return;let[ce,h,lt]=Mc();if(!ce||!h)return;let Qe=rp(h);if(!Qe)return;at.current=!0;let _=!0,Ce=ha.get(h);Ce||(Ce=lt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>R.retrievePaymentIntent(h)),ha.set(h,Ce));let Dt={accountPatch:Qe.accountPatch,sessionId:Qe.sessionId,nonce:Qe.nonce},de=()=>{H?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...gr,requestCategory:"provider_sdk"})};return H?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...gr}),(async()=>{try{qe(!0);let f=await Ce;if(!_)return;if(f?.error){ha.delete(h),de(),i?.(f.error.message??"Failed to retrieve PayPal payment status.");return}if(qu(),ha.delete(h),lt==="failed"){let ge="PayPal payment was declined. Please try again.";H?.terminal({outcome:"payment_declined",...gr,terminalReason:"provider_declined"}),i?.(ge),m?.(fn("paypal",ge));return}let P=f?.paymentIntent;if(P&&P.id!==ce){de(),i?.("Failed to match the returned PayPal payment.");return}if(P&&(P.status==="requires_capture"||P.status==="succeeded")){let ge=typeof P.payment_method=="string"?P.payment_method:P.payment_method?.id;a({id:ge??P.id,type:"card",threeDSecureActionResultTokenId:P.id,isPaypal:!0},{...Dt,presentationMode:"redirect"})}else{let ge="PayPal payment was not completed. Please try again.";H?.terminal({outcome:P?.status==="canceled"?"payment_cancelled":"payment_declined",...gr,terminalReason:P?.status==="canceled"?"cancelled":"provider_declined"}),i?.(ge),m?.(fn("paypal",ge))}}catch(f){if(!_)return;ha.delete(h),de(),i?.(f instanceof Error?f.message:"Failed to complete PayPal payment.")}finally{_&&qe(!1)}})(),()=>{_=!1,at.current=!1}},[R,a,i,m,H]);let Pe=Te(async(ce=!1)=>{let h=T?await T("paypal"):{proceed:!0};if(!h.proceed)return _e.current.delete(pe),!1;let lt=se("paypal");return _e.current.set(pe,{generation:lt,accountPatch:h.accountPatch,sessionId:h.sessionId,nonce:h.nonce}),Ze(!1),H?.log({name:`provider.${ce?"redirect.started":"handoff.requested"}`,stage:ce?"redirect":"overlay_open",...gr,attempt:lt}),l?.("paypal"),!0},[l,H,T,se,pe]),$e=Te(async ce=>{if(s||ze||!await Pe()){ce.reject();return}ce.resolve()},[s,Pe,ze]),He=Te(async ce=>{if(!R||!Xe)return;let h=_e.current.get(pe);if(h&&!Fe(h.generation)){_e.current.delete(pe);return}if(!h&&Le()||h&&!O(h.generation))return;h||O();let lt=h??null;if(_e.current.delete(pe),!lt&&T){let kt=await T("paypal");if(!kt.proceed){ce.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}lt={accountPatch:kt.accountPatch,sessionId:kt.sessionId,nonce:kt.nonce}}let Qe=lt?.sessionId??e,_=lt?.nonce??t,Ce=await Mp({event:ce,prepared:lt,email:n,billingName:I,methodLabel:"PayPal",collect:Bt});if(!Ce){ce.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Dt=Ce.email,de={...lt?.accountPatch,...fr(Ce,!0)};try{if(qe(!0),i?.(null),!Qe||!Tn(Dt))throw new Error("Missing sessionId or email for PayPal payment");await N?.(Ce);let kt=R.createPaymentMethod,{error:f,paymentMethod:P}=await kt({type:"paypal"});if(f){gt(f,"stripe_paypal_create_payment_method_failed",h?.generation),ce.paymentFailed({reason:"fail"});return}let ge=await ui(o,Ve,Qe,_??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:P?.id??null,intentKind:"payment"});if(di(ge)){ce.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:de,paymentMethodCategory:"paypal",presentationMode:g,sessionId:Qe,nonce:_,settledProcessResponse:ge.response});return}if(ge.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ve=ge.clientSecret,et={return_url:xc()};if(P?.id&&(et.payment_method=P.id),!sn(is,{clientSecret:ve,sessionId:Qe,nonce:_,accountPatch:de})&&g==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:be,paymentIntent:we}=await R.confirmPayment({clientSecret:ve,confirmParams:et,redirect:"if_required"});if(be){if(sn(is),Ua(be)){let p=be.message??"Your payment was declined.";H?.terminal({outcome:"payment_declined",...gr,terminalReason:"provider_declined"}),i?.(p),m?.(fn("paypal",p,{code:Co(be),declineCode:Ni(be)})),await pi({billingApiUrl:o,sessionId:Qe,nonce:_,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Co(be)??"provider_declined"}})}else gt(be,"stripe_paypal_confirm_failed",h?.generation);return}sn(is);let Ot=typeof we?.payment_method=="string"?we.payment_method:we?.payment_method?.id;a({id:Ot??we?.id,type:"card",threeDSecureActionResultTokenId:we?.id,isPaypal:!0},{accountPatch:de,paymentMethodCategory:"paypal",presentationMode:g,sessionId:Qe,nonce:_});return}catch(kt){gt(kt,"stripe_paypal_failed",h?.generation)}finally{qe(!1)}},[R,Xe,e,t,n,I,Bt,N,o,Ve,a,i,m,T,gt,O,Fe,Le,H,g,pe]),In=Te(async()=>{if(!(It.current||s||ze||!R||!Xe)){It.current=!0,qe(!0);try{if(!await Pe(!0))return;await He({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{It.current=!1,qe(!1)}}},[Xe,He,s,Pe,R,ze]),_t=g==="redirect"?u("button",{type:"button",disabled:s||ze,onClick:()=>{In()},style:{width:"100%",minHeight:oa,border:"1px solid #d1d5db",borderRadius:L??8,background:"#ffc439",color:"#111827",cursor:s||ze?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):u(Fc,{onReady:ce=>ot(Li(ce,["paypal"])),onLoadError:()=>{ot("load_error"),fs(H,"paypal","paypal","provider_error")},onClick:$e,onConfirm:He,onCancel:()=>{let ce=_e.current.get(pe);_e.current.delete(pe),H?.terminal({outcome:"payment_cancelled",...gr,terminalReason:"cancelled",...ce?{attempt:ce.generation}:{}}),je(ce?.generation),Ze(!1),Y.current=!0,De()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:st,emailRequired:st,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},pe),Pt=Je(Lo,{children:[Je("div",{ref:fe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ft&&u("button",{ref:ie,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ht,style:cs,children:"Try PayPal again"}),ee&&u(To,{identity:ee.identity,methodLabel:ee.methodLabel,onComplete:ut,onCancel:()=>ut(null)},ee.id),u("div",{style:{display:ee?"none":void 0},children:_t})]}),ze&&!ee&&u(Rr,{status:"processing"})]});return g==="redirect"?Pt:u(Ui,{state:Ne,placeholderTestId:"flopay-paypal-placeholder",borderRadius:L,children:Pt})}function ss(e){return e==="apple_pay"||e==="google_pay"}var zp=200;function qp({active:e}){return yp(()=>e?Wu(document):void 0,[e]),null}function Ec({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:m,onDecline:C,onTechnicalFailure:T,runBeforeButtonClick:I,billingName:N,onBuyerIdentityReady:ue,onLoadStateChange:L,placeholderBorderRadius:Be,popupCapabilityOwner:K,externalTelemetryContext:g}){let S=Gr(),{emitInstrument:Ve}=Uo(lr),R=ys(),Xe=ps(),H=wt(()=>ii(gn(S),g),[g,S]),[Ne,ot]=le("loading");mt(()=>{L?.(Ne)},[Ne,L]);let[ze,qe]=le(!1);mt(()=>{Ze.current=ze},[ze]);let It=V(!Tn(n?.trim())||!N?.trim()).current,{request:st,collect:ee,finish:Bt}=Eo(),ut=V(null),at=V(null),[fe,ie]=le(0),[pe,ft]=le(()=>vc()),Ft=V(pe),Ze=V(!1),[Y,_e]=le(!1),[se,O]=le(()=>ci(e,t)?"blocked":"idle"),[je,Le]=le("google_pay"),Fe=V(null),E=V(!0),De=V(!1),gt=V("google_pay"),Ee=V("google_pay"),ht=V(null),Pe=V(null),$e=V(new Set),He=V(null),In=V(null);mt(()=>(E.current=!0,()=>{E.current=!1;for(let p of $e.current)window.clearTimeout(p);$e.current.clear()}),[]);let _t=V(new Map),{startAttempt:Pt,finishAttempt:ce,invalidateAttempt:h,isAttemptInvalidated:lt,isAttemptCurrent:Qe,generationRef:_}=ua((p,Oe,he)=>{T?.(p,Oe,{...he,popupBlocked:he?.popupBlocked??Vr(Oe),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Le(p),_e(!0),ie(Se=>Se+1)},{onHandoffObserved:p=>{In.current=_.current,K.markAvailable(),H?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:_.current,...p==="apple_pay"||p==="google_pay"?{walletType:p}:{}})},defersMissingTerminal:ss,onMissingTerminalDeferred:(p,Oe)=>{let he=H?.now()??globalThis.performance?.now()??Date.now(),Se=He.current,J=Se?.generation===Oe?Se.startedAt:he;H?.performance({stage:"overlay_return",durationMs:Math.max(0,he-J),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:Oe,...ss(p)?{walletType:p}:{}}),H?.flush?.().catch(()=>{})}});mt(()=>{Y&&at.current?.focus()},[Y,fe]);let Ce=V(0),Dt=V(!1),de=Te(()=>{if(Ce.current>0){Dt.current=!0;return}ie(p=>p+1)},[]),kt=Te(()=>{Ce.current-=1,!(Ce.current>0||!Dt.current)&&(Dt.current=!1,E.current&&ie(p=>p+1))},[]),f=Te((p,Oe,he,Se,J=!1)=>{h(Se),T?.(p,Oe,{code:he,popupBlocked:Vr(Oe),telemetryReported:J,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Le(p),_e(!0),de()},[h,T,de]),P=Te(p=>{H?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...ss(p)?{walletType:p}:{}}),T?.(p,new Error("The wallet click was not ready within the time the wallet allows."),{code:gp,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Le(p),_e(!0)},[T,H]),ge=Te(()=>{window.setTimeout(()=>{(ut.current?.querySelector("iframe")??ut.current)?.focus()},0)},[]);mt(()=>{De.current&&(De.current=!1,ge())},[ge,fe]);let ve=Te(()=>{_e(!1),l?.(null),ge()},[ge,l]),et=Te(()=>{Fe.current?.()},[]);mt(()=>{let p=null,Oe=()=>{p=null;let Se=vc();Se!==Ft.current&&(Ft.current=Se,ft(Se),!Ze.current&&!Qe(_.current)&&de())},he=()=>{p!==null&&window.clearTimeout(p),p=window.setTimeout(Oe,zp)};return window.addEventListener("resize",he),()=>{window.removeEventListener("resize",he),p!==null&&window.clearTimeout(p)}},[_,Qe,de]),mt(()=>{let p=ci(e,t);if(!p)return;let Oe=!1,he=!1,Se=async()=>{if(!he){he=!0,Oe||O("checking");try{let J=await Sc(R,p.clientSecret,$e.current);if(Oe)return;let z=as(J,p.providerObjectId,ns(p.clientSecret));if(z.kind==="confirmed"){if(!bc(e,t,p.clientSecret))return;Fe.current=null,O("idle"),s({id:z.paymentMethodId,type:"card",threeDSecureActionResultTokenId:z.intentId},{...p.accountPatch?{accountPatch:p.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(z.kind==="terminal"){os(e,t,p.clientSecret),Fe.current=null,O("idle"),Le(p.paymentMethodType),_e(!0),de();return}O("blocked")}catch{Oe||O("blocked")}finally{he=!1}}};return Fe.current=Se,O("blocked"),()=>{Oe=!0,Fe.current===Se&&(Fe.current=null)}},[t,s,de,e,R]);let Ke=Te(async p=>{let Oe=!1,he=!1,Se=Me=>{Oe||he||(Oe=!0,p.paymentFailed({reason:"fail",...Me?{message:Me}:{}}))};if(!R||!Xe){Se();return}let J=_t.current.get(fe);if(J&&!Qe(J.generation)){_t.current.delete(fe),Se();return}if(!J&&lt()){Se();return}if(J&&!ce(J.generation)){Se();return}J||(ce(),Dt.current=!1);let z=p.expressPaymentType??J?.method??gt.current,Pn=J??null,Wn=Rc(z),Zt;z==="apple_pay"?Zt="apple_pay":z==="google_pay"&&(Zt="google_pay");let zt=J?.generation??_.current,pt=H,Ln=pt?.now()??globalThis.performance?.now()??Date.now(),An=new AbortController,Qt=!1,Vn=!1,yt=null,Pr=e,Vt="processing",rr="other",Un="provider_runtime",zn,Ht=new Promise((Me,it)=>{zn=it}),un=window.setTimeout(()=>{Qt=!0,An.abort(),zn(si)},hp),Hn=async(Me,it,Rn)=>{Vt=Me,rr=it,Un=it==="intent_create"||it==="session_claim"?"transport_error":"provider_runtime";let qt=pt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Rn,Ht])}finally{let en=pt?.now()??globalThis.performance?.now()??Date.now();pt?.performance({stage:Me,durationMs:Math.max(0,en-qt),durationMode:"machine",requestCategory:it,paymentMethodCategory:"wallet",provider:"stripe",...Qt?{statusClass:"timeout"}:{}})}};try{if(qe(!0),l?.(null),!Pn&&I){let X=await Hn("processing","other",I(Wn));if(!X.proceed){Se();return}Pn={accountPatch:X.accountPatch,sessionId:X.sessionId,nonce:X.nonce}}let Me=Pn?.sessionId??e;Pr=Me;let it=Pn?.nonce??t,Rn=ht.current??Pn?.accountPatch,qt=Lc({event:p,fallbackEmail:Rn?.email??n,fallbackName:[Rn?.firstName,Rn?.lastName].join(" ").trim()||N});if(!Tn(qt.email)){Se("Buyer details are required."),ee(ds(z),qt).then(X=>{X&&(ht.current=X)});return}ht.current=null;let en={...Pn?.accountPatch,...fr(qt,!0)};await Hn("processing","session_claim",Promise.resolve(ue?.(qt)));let{error:pn}=await Hn("tokenization","provider_sdk",Xe.submit());if(pn){Se(),f(z,pn,"stripe_wallet_submit_failed",J?.generation);return}if(!Me)throw new Error("Missing sessionId or email for payment.");let Kt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:z,paymentMethodId:null,intentKind:a},jt=JSON.stringify({sessionId:Me,nonce:it??"",request:Kt}),vn=Pe.current,ke=vn?.retryIdentity===jt?vn.authorizationAttemptId:np();Pe.current={authorizationAttemptId:ke,retryIdentity:jt};let tn=await Hn("processing","intent_create",ui(o,Ve,Me,it??"",{...Kt,authorizationAttemptId:ke},{signal:An.signal}));if(di(tn)){Se(),s({type:"card",paymentMethodType:z},{accountPatch:en,paymentMethodCategory:"wallet",sessionId:Me,nonce:it,settledProcessResponse:tn.response});return}if(tn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Cn=tn.clientSecret,xr=kp({createdAt:Date.now(),sessionId:Me,...it?{nonce:it}:{},clientSecret:Cn,providerObjectId:tn.providerObjectId,paymentMethodType:z,accountPatch:en});window.clearTimeout(un),Vn=!0,pt?.performance({stage:"callback",durationMs:Math.max(0,(pt?.now()??globalThis.performance?.now()??Date.now())-Ln),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let xn=pt?.now()??globalThis.performance?.now()??Date.now(),Bn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Zt?{walletType:Zt}:{},attempt:zt},vr=!1,Qn=null;pt?.log({name:"payment.provider_confirmation.started",...Bn}),yt=window.setTimeout(()=>{yt!==null&&$e.current.delete(yt),vr=!0;let X=pt?.now()??globalThis.performance?.now()??Date.now();pt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Bn,operationOutcome:"watchdog_expired",durationMs:Math.max(0,X-xn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),pt?.flush?.().catch(()=>{}),Qn?.()},Pp),$e.current.add(yt);let nn=(X,Lt)=>{yt!==null&&(window.clearTimeout(yt),$e.current.delete(yt),yt=null);let q=pt?.now()??globalThis.performance?.now()??Date.now(),Et=Math.max(0,q-xn),mn=X;vr&&(X==="resolved"?mn="resolved_late":X==="returned_error"?mn="returned_error_late":mn="rejected_late");let Fn=Lt??(X==="resolved"?"approved":"provider_error");return pt?.log({name:"payment.provider_confirmation.returned",...Bn,operationOutcome:mn,terminalReason:Fn}),pt?.performance({...Bn,durationMs:Et,durationMode:"buyer",operationOutcome:mn,terminalReason:Fn}),{durationMs:Et,operationOutcome:mn,terminalReason:Fn}},G=!1,yn=!1,qn=X=>{if(!X||typeof X!="object")return null;let Lt=X;if(Lt.error)return null;let q=Lt.setupIntent??Lt.paymentIntent,Et=as(q??null,void 0,!!Lt.setupIntent);return Et.kind==="confirmed"?Et:null},U=X=>{if(G||J&&_.current!==J.generation)return;let Lt=qn(X);if(!Lt)return;if(xr&&!bc(Me,it,Cn)){G=!0;return}let{intentId:q,paymentMethodId:Et}=Lt;G=!0,yn=!0,Pe.current=null,Fe.current=null,E.current&&(O("idle"),qe(!1));let mn=`${Dc}:${Me}`;sn(mn,{createdAt:Date.now(),sessionId:Me,nonce:it,accountPatch:en,paymentMethodId:Et,providerIntentId:q,paymentMethodType:z});try{s({id:Et,type:"card",threeDSecureActionResultTokenId:q},{accountPatch:en,paymentMethodCategory:"wallet",sessionId:Me,nonce:it})}finally{sn(mn)}},vt=!1;Qn=async()=>{if(!(vt||G||yn)){vt=!0,E.current&&O("checking");try{let X=await Sc(R,Cn,$e.current);if(G||yn)return;let Lt=ns(Cn),q=as(X,tn.providerObjectId,Lt);if(q.kind==="confirmed"){U(Lt?{setupIntent:X}:{paymentIntent:X});return}if(q.kind==="terminal"){if(yn=!0,os(Me,it,Cn),Pe.current=null,Fe.current=null,!E.current)return;O("idle"),Se(),f(z,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",J?.generation,!0);return}E.current&&!yn&&(O("blocked"),qe(!1))}catch{E.current&&!yn&&(O("blocked"),qe(!1))}finally{vt=!1}}},Fe.current=Qn;let x,$t;try{he=!0,Ce.current+=1;let X;try{X=await(ns(Cn)?R.confirmSetup({elements:Xe,clientSecret:Cn,redirect:"if_required"}):R.confirmPayment({elements:Xe,clientSecret:Cn,redirect:"if_required"}))}finally{kt()}if(!X||typeof X!="object")throw new Pa(wp(X));if(x=X,!x.error&&!qn(x))throw new Pa("confirmation_result_unconfirmed");$t=nn(x.error?"returned_error":"resolved",x.error&&Ua(x.error)?"provider_declined":void 0)}catch(X){let Lt=X instanceof Pa?X.reason:void 0,q=Lt!==void 0,Et=nn(q?"returned_error":"rejected");if(pt?.error({...q?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Lt}:Wi(X),...Bn,operationOutcome:Et.operationOutcome,durationMs:Et.durationMs,statusClass:"unknown",terminalReason:Et.terminalReason}),!E.current||G)return;await Qn?.();return}let rn=x.error;if(rn){if(!E.current||G)return;if(Ua(rn)){yn=!0,os(Me,it,Cn),Pe.current=null,Fe.current=null,O("idle"),_t.current.get(fe)===J&&_t.current.delete(fe);let X=rn.message??"Your payment was declined.";l?.(X),C?.(fn(Wn,X,{code:Co(rn),declineCode:Ni(rn)})),pi({billingApiUrl:o,sessionId:Me,nonce:it,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:z,providerDeclineReason:Co(rn)??"provider_declined",...tn.intentKind==="payment"&&tn.providerObjectId.startsWith("pi_")?{providerIntentId:tn.providerObjectId}:{}}})}else pt?.error({...Wi(rn),...Bn,operationOutcome:$t.operationOutcome,durationMs:$t.durationMs,statusClass:"unknown",terminalReason:$t.terminalReason}),await Qn?.();return}if(U(x),!G)throw new Error("Invalid provider returned for APM intent")}catch(Me){if(Me===si){let it=pt?.now()??globalThis.performance?.now()??Date.now();pt?.error({errorCode:Rp(rr),stage:Vt,requestCategory:rr,paymentMethodCategory:"wallet",provider:"stripe",...Zt?{walletType:Zt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Pr,durationMs:Math.max(0,it-Ln),statusClass:"timeout",failureCategory:Un,attempt:zt,terminalReason:"provider_error"}),pt?.flush?.().catch(()=>{})}Se(),f(z,Me,Me===si?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",J?.generation,Me===si)}finally{if(window.clearTimeout(un),yt!==null&&(window.clearTimeout(yt),$e.current.delete(yt)),!Vn){let Me=pt?.now()??globalThis.performance?.now()??Date.now();pt?.performance({stage:"callback",durationMs:Math.max(0,Me-Ln),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Qt?{statusClass:"timeout"}:{}})}E.current&&qe(!1)}},[R,Xe,e,t,n,N,ee,ue,o,Ve,a,s,l,C,I,f,kt,ce,Qe,lt,_,H,fe]),be=wt(()=>wl(i),[i]),we=wt(()=>i.map(cp),[i]),Ot=wt(()=>u(Fc,{onReady:p=>{ot(Li(p,we))},onLoadError:p=>{ot("load_error"),fs(H,"stripe","wallet","provider_error")},onClick:async p=>{let Oe=H?.now()??globalThis.performance?.now()??Date.now();gt.current=p.expressPaymentType,Ee.current=Rc(p.expressPaymentType);let he=!0,Se=window.setTimeout(()=>{he=!1,p.reject(),P(p.expressPaymentType)},fp),J=I?await I(Ee.current,{abandoned:()=>!he}):{proceed:!0};if(window.clearTimeout(Se),!he)return;if(!J.proceed){_t.current.delete(fe),p.reject();return}let z=Pt(p.expressPaymentType);Dt.current=!1,He.current={generation:z,startedAt:Oe},_t.current.set(fe,{generation:z,method:p.expressPaymentType,accountPatch:J.accountPatch,sessionId:J.sessionId,nonce:J.nonce}),_e(!1),H?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:z,...p.expressPaymentType==="apple_pay"||p.expressPaymentType==="google_pay"?{walletType:p.expressPaymentType}:{}}),m?.(Ee.current),p.resolve()},onConfirm:Ke,onCancel:()=>{let p=_t.current.get(fe);_t.current.delete(fe);let Oe=He.current,he=H?.now()??globalThis.performance?.now()??Date.now();if(p&&Oe?.generation===p.generation&&Qu({method:p.method,elapsedMs:he-Oe.startedAt,handoffObserved:In.current===p.generation})){H?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:p.generation,walletType:"google_pay"}),Pe.current=null,f(p.method,new Error("The browser window is too small for the Google Pay sheet."),Bc,p.generation,!0);return}H?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...p?{attempt:p.generation}:{}}),h(p?.generation),Pe.current=null,_e(!1),De.current=!0,de()},options:{...kl,paymentMethods:be,emailRequired:It,billingAddressRequired:It}},fe),[we,be,Ke,h,m,It,f,P,de,I,Pt,fe,H]);return Je(Lo,{children:[u(Ui,{state:Ne,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Be,children:Je("div",{ref:ut,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Y&&Je("button",{ref:at,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ve,style:cs,children:["Try ",ds(je)," again"]}),se!=="idle"&&Je("div",{role:"status","aria-live":"polite",children:[u("p",{children:"We are still confirming your payment. Check its status before trying again."}),u("button",{type:"button",onClick:et,disabled:se==="checking",style:cs,children:se==="checking"?"Checking payment status\u2026":"Check payment status"})]}),st&&u(To,{identity:st.identity,methodLabel:st.methodLabel,onComplete:Bt,onCancel:()=>Bt(null)},st.id),Je("div",{style:{display:st||se!=="idle"?"none":void 0},children:[u(qp,{active:pe}),Ot]})]})}),ze&&u(Rr,{status:"processing"})]})}function Uc(e,t,n){let o=Ac(n,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function us({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:m,onDecline:C,onCancel:T,runBeforeButtonClick:I,onButtonClick:N,isProcessing:ue,submitButtonColor:L,submitButtonBorderRadius:Be,submitButtonStyle:K,errorText:g}){let S=Gr(),{emitInstrument:Ve}=Uo(lr),R=ys(),Xe=ps(),[H,Ne]=le(!1),ot=V(!1),[ze,qe]=le(!1),[It,st]=le("loading"),[ee,Bt]=le(""),ut=!Tn(o?.trim()),at=!ut||Tn(ee.trim()),fe=Te(async()=>{if(!R||!Xe||ue||ot.current||!ze)return;ot.current=!0,Ne(!0);let ie=I?await I("card"):{proceed:!0};if(!ie.proceed){ot.current=!1,Ne(!1);return}N?.("card");let pe=ie.sessionId??t,ft=ie.nonce??n,Ft=la(a?.trim()),Ze=fr({email:ie.accountPatch?.email?.trim()||o?.trim()||ee.trim(),firstName:ie.accountPatch?.firstName?.trim()||Ft.firstName,lastName:ie.accountPatch?.lastName?.trim()||Ft.lastName}),Y=Ze.email,_e=fr({...ie.accountPatch,...Ze});try{if(m?.(null),!Tn(Y))throw new Error("A valid email address is required for payment.");await i?.(Ze);let se=await Xe.submit();if(se.error){m?.(se.error.message??"Payment failed.");return}let O=[Ze.firstName,Ze.lastName].filter(Boolean).join(" "),je=await R.createPaymentMethod({elements:Xe,params:{billing_details:{email:Y,...O?{name:O}:{}}}});if(je.error||!je.paymentMethod){m?.(je.error?.message??"Failed to create payment method.");return}let Le=je.paymentMethod;if(!pe||!Y)throw new Error("Missing sessionId or email for payment.");let Fe=Le.type||e,E=await ui(s,Ve,pe,ft??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Fe,paymentMethodId:null,intentKind:"payment"});if(di(E)){l({type:"card",gateway:"stripe",paymentMethodType:Fe},{accountPatch:_e,paymentMethodCategory:"apm",sessionId:pe,nonce:ft,settledProcessResponse:E.response});return}if(E.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let De=E.clientSecret;sn(Mr,{clientSecret:De,sessionId:pe,nonce:ft,accountPatch:_e,paymentMethodId:Le.id,paymentMethodType:Le.type??e,gateway:"stripe"});let{error:gt,paymentIntent:Ee}=await R.confirmPayment({clientSecret:De,confirmParams:{return_url:window.location.href,payment_method:Le.id},redirect:"if_required"});if(gt){sn(Mr);let $e=gt.message??"Payment failed.";m?.($e),C?.(fn("card",$e,{code:gt.code})),await pi({billingApiUrl:s,sessionId:pe,nonce:ft,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:gt.code??"provider_declined"}});return}let ht=Ee?.status;if(!ia(ht)){sn(Mr);let $e=ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.($e),C?.(fn("card",$e,{code:ht??"missing_payment_intent"}));return}sn(Mr);let Pe=typeof Ee?.payment_method=="string"?Ee.payment_method:Ee?.payment_method?.id;l({id:Pe??Le.id,type:"card",threeDSecureActionResultTokenId:Ee?.id,gateway:"stripe",paymentMethodType:Le.type??e},{accountPatch:_e,paymentMethodCategory:"apm",sessionId:pe,nonce:ft})}catch(se){m?.(se instanceof Error?se.message:"Payment failed. Please try again.")}finally{ot.current=!1,Ne(!1)}},[R,Xe,ue,ze,I,N,t,n,o,a,ee,i,s,Ve,e,l,m,C]);return Je("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ut&&u("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ut&&Je("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",u("input",{type:"email",autoComplete:"email",required:!0,value:ee,onChange:ie=>Bt(ie.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),u(up,{onReady:()=>st("ready"),onLoadError:()=>{st("load_error"),fs(gn(S),"stripe","apm")},onChange:ie=>{qe(!!ie.complete)},options:{layout:Il,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...Tn(o?.trim())?{email:o?.trim()}:{}}}}}),u(Rl,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{fe()},disabled:!ze||!at||H||ue||It!=="ready",color:L,borderRadius:Be,style:K,children:H?"Processing\u2026":`Pay with ${va(e)}`}),g&&u(xo,{margin:"0.75rem 0 0",children:g})]})}function Tc({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:m,futureUseSession:C,onTokenizedBody:T,onErrorChange:I,onButtonClick:N,onDecline:ue,runBeforeButtonClick:L,onLoadStateChange:Be,isProcessing:K=!1,submitButtonColor:g="#4A49FF",submitButtonBorderRadius:S=8,submitButtonStyle:Ve,buttonAppearance:R,themeId:Xe,onExpandApm:H,expandedApmMethod:Ne}){let{emitInstrument:ot}=Uo(lr),[ze,qe]=le(null),[It,st]=le(null),ee=V(!1),{request:Bt,collect:ut,finish:at}=Eo();mt(()=>{s.length>0&&l?Be?.("ready"):l||Be?.("loading")},[s.length,l,Be]);let fe=Te(async Y=>{if(!l||ee.current||K)return;ee.current=!0,st(Y);let _e=L?await L("card"):{proceed:!0};if(!_e.proceed){ee.current=!1,st(null);return}N?.("card");let se=_e.sessionId??e,O=_e.nonce??t,je=la([_e.accountPatch?.firstName,_e.accountPatch?.lastName].filter(Boolean).join(" ")||o),Le=fr({email:_e.accountPatch?.email?.trim()||n?.trim(),firstName:_e.accountPatch?.firstName?.trim()||je.firstName,lastName:_e.accountPatch?.lastName?.trim()||je.lastName});if(!Tn(Le.email)){st(null);let De=await ut(va(Y),Le);if(!De){ee.current=!1;return}Le=De,st(Y)}let Fe=Le.email,E=fr({..._e.accountPatch,...Le});try{if(I?.(null),!se||!Tn(Fe))throw new Error("Missing sessionId or email for payment.");await a?.(Le);let De=await ui(i,ot,se,O??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Y,paymentMethodId:null,intentKind:"payment"});if(di(De)){T({type:"card",gateway:"stripe",paymentMethodType:Y},{accountPatch:E,paymentMethodCategory:"apm",sessionId:se,nonce:O,settledProcessResponse:De.response});return}if(De.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let gt=De.clientSecret;sn(Mr,{clientSecret:gt,sessionId:se,nonce:O,accountPatch:E,paymentMethodType:Y,gateway:"stripe"});let{error:Ee,paymentIntent:ht}=await l.confirmPayment({clientSecret:gt,confirmParams:{return_url:window.location.href,payment_method_data:{type:Y,billing_details:{name:[Le.firstName,Le.lastName].filter(Boolean).join(" "),...Fe?{email:Fe}:{}}}},redirect:"if_required"});if(Ee){sn(Mr);let He=Ee.message??"Payment failed.";I?.(He),ue?.(fn("card",He,{code:Ee.code})),await pi({billingApiUrl:i,sessionId:se,nonce:O,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Y,providerDeclineReason:Ee.code??"provider_declined"}});return}let Pe=ht?.status;if(!ia(Pe)){sn(Mr);let He=Pe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";I?.(He),ue?.(fn("card",He,{code:Pe??"missing_payment_intent"}));return}sn(Mr);let $e=typeof ht?.payment_method=="string"?ht.payment_method:ht?.payment_method?.id;T({id:$e??ht?.id,type:"card",threeDSecureActionResultTokenId:ht?.id,gateway:"stripe",paymentMethodType:Y},{accountPatch:E,paymentMethodCategory:"apm",sessionId:se,nonce:O})}catch(De){I?.(De instanceof Error?De.message:"Payment failed. Please try again.")}finally{ee.current=!1,st(null)}},[l,K,L,N,e,t,n,ut,i,ot,o,a,T,I,ue]),[ie,pe]=le(null),ft=H?Ne??null:ie,Ft=Te(Y=>{ee.current||K||ft&&ft!==Y||(hc(Y)?H?H(Y):pe(Y):fe(Y))},[ft,K,fe,H]),Ze=wt(()=>ie?Uc(m,ie,C):null,[ie,m,C]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Bt?u(To,{identity:Bt.identity,methodLabel:Bt.methodLabel,onComplete:at,onCancel:()=>at(null)},Bt.id):s.map(Y=>{let _e=Ne===Y,se=It===Y,O=It!==null&&It!==Y||Ne!=null&&Ne!==Y;return Je(pp.Fragment,{children:[u(Sl,{method:Y,themeId:Xe,submitting:se,disabled:O,highlighted:_e,hasNextStep:hc(Y),onClick:()=>Ft(Y),backgroundColor:R?.backgroundColor,borderColor:R?.borderColor,textColor:R?.textColor,borderRadius:R?.borderRadius,fontFamily:R?.fontFamily}),!H&&ie===Y&&Ze&&l&&u(lo,{stripe:l,options:Ze,children:u(us,{method:Y,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:T,onErrorChange:I,onDecline:ue,onCancel:()=>pe(null),runBeforeButtonClick:L,onButtonClick:N,isProcessing:K,submitButtonColor:g,submitButtonBorderRadius:S,submitButtonStyle:Ve})},Y)]},Y)})})}function jp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:l,onDecline:m,onCancel:C,onTokenizedBody:T,firstName:I,lastName:N,chv:ue,className:L,submitLabel:Be,isProcessing:K,error:g,onErrorChange:S,showPayPal:Ve=!0,showStripe:R=!0,walletPresentation:Xe="auto",enabledPaymentMethods:H,enabledPaymentMethodCountries:Ne,showApplePay:ot=!0,showGooglePay:ze=!0,layout:qe="default",theme:It,buttonsTheme:st,buttonsStyles:ee,appearance:Bt,cardButtonContent:ut,cardBackButtonContent:at,cardTitleContent:fe,showSecurityFooter:ie,onButtonClick:pe,onBeforeButtonClick:ft,onBuyerIdentityReady:Ft,enableAVS:Ze,cardFieldOrder:Y,cardPreFormSlot:_e,avsLayout:se="row",country:O,zip:je,addressLine1:Le,addressLine2:Fe,city:E,state:De,onCountryChange:gt,onZipChange:Ee,avsCheck:ht,checkoutType:Pe,checkoutLayout:$e,totalAmount:He=0,currency:In="usd",initialCardOpen:_t=!1,directPaypal:Pt,isSubscription:ce=!1,session:h,dataAttachmentPending:lt=!1,dataAttachmentRequiresIdentity:Qe=!1,debug:_=!1}){let Ce=Gr(),Dt=Vi(),de=Uo(mr),{emitInstrument:kt}=Uo(lr),f=V(null);f.current||(f.current=Ha());let P=f.current,[,ge]=le(0),ve=V(null);ve.current||(ve.current=ra());let et=ve.current,Ke=wt(()=>({browser:et,capability:P,presentationMode:"popup"}),[et,P]),be=h??de.session,we=wt(()=>({futureUse:be?.futureUse,futureUseUnsupported:be?.futureUseUnsupported}),[be?.futureUse,be?.futureUseUnsupported]),Ot=be?.gateways?.paypal?.providerObjectType??Pt?.providerObjectType,p=lt||de.claimPending===!0,Oe=Qe||de.claimRequiresIdentity===!0,he=p&&!Oe,Se=Gl(),J=n||Se,[z,Pn]=le(!1),[Wn,Zt]=le(null),[zt,pt]=le(O??""),[Ln,An]=le(je??""),[Qt,Vn]=le(Le??""),[yt,Pr]=le(Fe??""),[Vt,rr]=le(E??""),[Un,zn]=le(De??""),[Ht,un]=le(""),[Hn,Me]=le({}),it=V(je??""),Rn=V(O??""),qt=V(Le??""),en=V(Fe??""),pn=V(E??""),Kt=V(De??""),jt=V(""),vn=V({});mt(()=>{let r=(y,M,oe,A,ae)=>{if(vn.current[y])return;let xt=M?.trim();!xt||xt===oe.current||(oe.current=xt,A(xt),ae?.(xt))};r("country",O,Rn,pt,gt),r("zip",je,it,An,Ee),r("addressLine1",Le,qt,Vn),r("addressLine2",Fe,en,Pr),r("city",E,pn,rr),r("state",De,Kt,zn)},[O,je,Le,Fe,E,De,gt,Ee]);let ke=wt(()=>op(Ze),[Ze]),tn=ke!==null,Cn=wt(()=>ts(h),[h]),xr=Ju(h?.vault),xn=!!h?.gateways?.pcivault,Bn=jl(h),Qn=!!(h?.gateways?.stripe?.enabledPaymentMethods??H)?.includes("card")||oo(h),nn=xr||Qn||xn,G=!!(R&&nn&&e),[yn,qn]=le(()=>qe!=="buttons"||_t?e??null:null),[U,vt]=le(0),x=qe!=="buttons"||_t||!!e&&yn===e,$t=h?.captureMethod,rn=V(Ce);mt(()=>{rn.current=Ce},[Ce]);let[X,Lt]=le(null);mt(()=>{if(!G||!e||!x){Lt(null);return}let r=rn.current?rn.current.cardCapture({sessionId:e,captureMethod:$t}):new Fu({sessionId:e,captureMethod:$t,billingApiUrl:J,telemetry:o});return Lt({sessionId:e,captureMethod:$t,billingApiUrl:J,telemetry:o,capture:r}),()=>{r.unmount()}},[G,e,x,$t,J,o]);let q=G&&e&&x&&X?.sessionId===e&&X.captureMethod===$t&&X.billingApiUrl===J&&X.telemetry===o?X.capture:null,Et=wt(()=>{let r=zt,y=ke?Jt(ke.postal_code,r):!1;return Np(r,Ln,y)},[ke,zt,Ln]),{avsInvalid:mn,invalidAvsFields:Fn}=wt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!G||!ke)return{avsInvalid:!1,invalidAvsFields:r};let y=zt,M=(ae,xt)=>Jt(ae,y)&&!xt.trim(),oe={line1:M(ke.address_line_1,Qt),city:M(ke.city,Vt),state:M(ke.state,Un),zip:Et.empty||Et.malformed};return{avsInvalid:oe.line1||oe.city||oe.state||oe.zip,invalidAvsFields:oe}},[G,ke,zt,Qt,Vt,Un,Et]),[Gt,Cr]=le(!1),[Br,br]=le(!1),[Sr,Fr]=le(!1),[$r,Wr]=le({line1:!1,city:!1,state:!1}),_n=V(!1),Dr=V({email:!1,line1:!1,city:!1,state:!1,zip:!1}),or=V(!1),At=Te(r=>{Dr.current[r]=!0,or.current=!0},[]),Kn=Te(r=>!_n.current&&Dr.current[r],[]),Gn=Te(r=>{Kn(r)&&Wr(y=>y[r]?y:{...y,[r]:!0})},[Kn]),[er,Yn]=le(()=>rs(h?.vault,{billingApiUrl:J,sessionId:e,nonce:t})),[Ue,ln]=le(_t&&nn?"card":"buttons"),[on,jn]=le(null),Qr=Ue==="expanding"||Ue==="card",Or=h?.gateways?.stripe&&!Bn?"stripe":void 0,dr=Te(()=>{kt?.({class:"card_surface",provider:Or})},[Or,kt]),tr=V(null),bn=Te(r=>{tr.current&&clearTimeout(tr.current),tr.current=setTimeout(()=>{tr.current=null,r()},Ca)},[]);mt(()=>()=>{tr.current&&clearTimeout(tr.current)},[]);let Nr=V(!1),[Dn,w]=le(0),k=V(null),j=Te(()=>{dr(),qn(e??null),Nr.current&&(Nr.current=!1,w(r=>r+1)),vt(r=>r+1),ln("expanding"),bn(()=>ln("card"))},[bn,dr,e]),te=Te(()=>{ln("collapsing"),bn(()=>ln("buttons"))},[bn]),We=Te(r=>{jn(r),ln("apm-expanding"),bn(()=>ln("apm-form"))},[bn]),Wt=Te(()=>{ln("apm-collapsing"),bn(()=>{ln("buttons"),jn(null)})},[bn]);mt(()=>{qe==="buttons"&&_t&&nn&&(qn(e??null),ln("card"))},[qe,_t,nn,e]);let[ne,W]=le(null),B=V(!1),Z=V(null),F=V("idle"),[Ae,D]=le(!1),Ie=V(Ae);Ie.current=Ae;let[Re,Ct]=le(()=>Pt?.existingOrderId?{orderId:Pt.existingOrderId,attempts:1}:null),Sn=V(Re);mt(()=>{Sn.current=Re},[Re]);let d=V(null),c=wt(()=>{if(Ft||de.claimBuyerIdentity||h?.buyerIdentified!==!1||!e||!t)return;let r=`${J}|${e}|${t}`;d.current?.key!==r&&(d.current={key:r,claim:Io(new No(J,{telemetry:!1}),e,t,{...i?{userId:i}:{},...I?{firstName:I}:{},...N?{lastName:N}:{}})});let y=d.current.claim;return async M=>{await y(M)}},[Ft,de.claimBuyerIdentity,h?.buyerIdentified,e,t,J,i,I,N]),v=Ft??de.claimBuyerIdentity??c,Q=g??Wn,re=wt(()=>ip(It),[It]),b=wt(()=>{let r=re?.buttonsLayout??ap(st);return ee?{...r,...ee,cardButton:{...r.cardButton,...ee.cardButton},cardFormContainer:{...r.cardFormContainer,...ee.cardFormContainer},backButton:{...r.backButton,...ee.backButton},backButtonIcon:{...r.backButtonIcon,...ee.backButtonIcon},submitButton:{...r.submitButton,...ee.submitButton},title:{...r.title,...ee.title}}:r},[re,st,ee]),tt=Bt??re?.appearance,cn=wt(()=>ju({appearance:tt,buttonsStyles:b,layout:qe}),[tt,b,qe]),wn=de.inlineSessionPatchProcessing??!1,nt=(K??z)||wn,nr=J.replace(/\/+$/,""),$=wt(()=>$i({userId:i,email:a,firstName:I,lastName:N,country:O,zip:je},Hn),[i,a,I,N,O,je,Hn]),Ge=[$.firstName,$.lastName].filter(r=>!!r?.trim()).join(" "),ct=!Tn($.email?.trim()),bt=V(null);G&&bt.current===null&&(bt.current=ct);let xe=G&&(bt.current??ct),$n=wt(()=>Lp(Ht,xe),[Ht,xe]),Rt=$n.empty||$n.malformed,On=wt(()=>Ce?Ce.getRawProvider():null,[Ce]),Es=wt(()=>Dt?Dt.getRawProvider():null,[Dt]),Wo=He||100,uo=In.toLowerCase(),hi=wt(()=>tt?Du(tt):null,[tt]),po=hi,Ts=wt(()=>{let r=hi??{},y=r.rules??{};return{...r,rules:{...y,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...y[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...y[".AccordionItemContents"]??{}}}}},[hi]),Ms=wt(()=>({...ql(He,be?.captureMethod,we),currency:uo,...po?{appearance:po}:null}),[He,uo,be?.captureMethod,we,po]),Pi=Ac(we,"paypal","paypal"),As=wt(()=>({mode:"payment",amount:Wo,currency:uo,captureMethod:"manual",...Pi?{setupFutureUsage:Pi}:null,...po?{appearance:po}:null}),[Wo,uo,Pi,po]),me=Te(r=>{Zt(r),S?.(r)},[S]),xs=V(0);mt(()=>{Dn!==xs.current&&(xs.current=Dn,me(null))},[Dn,me]);let vi=V(""),[Bs,ed]=le(!1),Ci=Te(()=>{ed(!0)},[]);mt(()=>{if(!G||!xe||!v||!Bs||Rt||vi.current)return;let r=fr({email:Tn($.email?.trim())?$.email?.trim():jt.current.trim(),firstName:$.firstName?.trim(),lastName:$.lastName?.trim()});vi.current=JSON.stringify(r),Me(y=>({...y,...r})),Promise.resolve(v(r)).catch(y=>{vi.current="",me(y instanceof Error?y.message:"Failed to attach buyer details.")})},[G,xe,v,Bs,Rt,$.email,$.firstName,$.lastName,me]),mt(()=>{!G||!q||q.setCardFieldOrder?.(Y??null,ke==null&&!xe)},[G,q,Y,ke,xe]),mt(()=>{(Ue==="expanding"||Ue==="collapsing"||Ue==="apm-expanding"||Ue==="apm-collapsing")&&me(null)},[Ue,me]);let wr=Te((r,y,M)=>{m?.(fn(r,y,M))},[m]),Fs=V(Ue);Fs.current=Ue;let[Ds]=le(Ga),Os=Te(()=>{let r=Fs.current;if(qe==="buttons"&&(r==="card"||r==="expanding"))return!0;let y=F.current;return y==="validation-window"||y==="processing"||Ie.current},[qe]),Ns=Te((r,y,M)=>{Ds.take(e)&&gn(Ce)?.log(so({...Ke,presentationMode:M?.presentationMode??"popup"},{name:Ka,stage:"recovery",reason:"other_method_active",provider:M?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:M?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[Ke,Ce,Ds,e]),Ia=Te((r,y,M)=>{M?.telemetryReported||gn(Ce)?.error(so({...Ke,presentationMode:M?.presentationMode??"popup"},{errorCode:y?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:M?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:M?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:M?.terminalReason??(y?"popup_blocked":"provider_error")}))},[Ke,Ce]),yo=Te((r,y,M)=>{let oe=M?.popupBlocked??Vr(y);if(Os()){Ia(r,oe,M),Ns(r,y,M);return}if(y instanceof Tr&&y.code==="checkout_processing_timeout"){Ia(r,!1,M),W(null),qe==="buttons"&&(ln("buttons"),jn(null)),me(y.message),l?.(y);return}oe&&P.markBlocked()&&ge(dt=>dt+1);let A=ds(r),ae=M?.code===Bc?Lu(A):La(A,oe,et.inAppBrowser),xt=Co(y),ir=(xt?.toLowerCase()==="error"?void 0:xt)??Cl(M?.code)??"external_payment_method_failed",Ye=new Tr(ae,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:ir,popupBlocked:oe,inAppBrowser:et.inAppBrowser,appFamily:et.appFamily,popupCapability:P.current(),presentationMode:M?.presentationMode??"popup"}});Ia(r,oe,M),W(null),qe==="buttons"&&(ln("buttons"),jn(null)),me(ae),l?.(Ye),console.error("[FloPay] External payment method failed:",{method:r,code:ir,popupBlocked:oe})},[et,Os,qe,l,P,Ns,Ia,me]);mt(()=>{if(!G||!e){Yn(null);return}let r={billingApiUrl:nr,sessionId:e,nonce:t},y=rs(h?.vault,r);if(y){Yn(y);return}if(!x){Yn(null);return}let M=`${nr}\0${e}\0${t??""}`,oe=k.current;if(oe&&oe.key===M){Yn(oe.mount);return}Yn(null);let A=!0;return new No(nr).getVaultCapture(e,t).then(ae=>{if(!A)return;let xt=rs(ae,r);xt?.verificationRequired&&!ae.html&&(k.current={key:M,mount:xt}),xt?Yn(xt):me("Failed to load the secure card form.")}).catch(ae=>{A&&me(ae instanceof Error?ae.message:"Failed to load the secure card form.")}),()=>{A=!1}},[G,x,U,e,h?.vault,nr,t,me]);let ur=V({onComplete:s,onError:l,updateError:me,emitDecline:wr,resolvedAccount:$,avsConfig:ke,avsCheckProp:ht,sessionId:e,nonce:t,baseUrl:nr,captureMethod:h?.captureMethod,paymentId:h?.paymentId,authorizationExpiresAt:h?.authorizationExpiresAt,serverSideCardGateway:Bn});ur.current={onComplete:s,onError:l,updateError:me,emitDecline:wr,resolvedAccount:$,avsConfig:ke,avsCheckProp:ht,sessionId:e,nonce:t,baseUrl:nr,captureMethod:h?.captureMethod,paymentId:h?.paymentId,authorizationExpiresAt:h?.authorizationExpiresAt,serverSideCardGateway:Bn};let bi=V(!1),Ls=Te(()=>{let r=ur.current,y=r.resolvedAccount.email?.trim(),M=Tn(y)?y:jt.current.trim();if(!Tn(M))return null;let oe=r.resolvedAccount.firstName?.trim(),A=r.resolvedAccount.lastName?.trim(),ae=Rn.current.trim()||r.resolvedAccount.country?.trim()||"",xt=r.avsConfig?Jt(r.avsConfig.state,ae):!1,ir=r.avsConfig?Jt(r.avsConfig.address_line_1,ae):!1,Ye=r.avsConfig?Jt(r.avsConfig.postal_code,ae):!1,dt=r.avsConfig?Jt(r.avsConfig.city,ae):!1,St=r.avsConfig?Jt(r.avsConfig.address_line_2,ae):!1,En=ir&&!xt&&Ye?Ku(ae,(it.current??"").trim()):null,yr=xt?Kt.current:En;return{accountData:{userId:r.resolvedAccount.userId??"",email:M,...oe?{firstName:oe}:{},...A?{lastName:A}:{},...Ye&&it.current?{zip:it.current}:{},...dt&&pn.current?{city:pn.current}:{},...yr?{state:yr}:{},...ir&&qt.current?{addressLine1:qt.current}:{},...St&&en.current?{addressLine2:en.current}:{},...ae?{country:ae}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Jt(r.avsConfig.country,ae),postal_code:Ye,address_line_1:ir,address_line_2:St,city:dt,state:xt}}:{}}},[]),Us=V(p);Us.current=p,mt(()=>{p||Q!==wc||ur.current.updateError(null)},[p,Q]),mt(()=>{!G||!q||q.setSubmitGate?.(mn||p||Rt||Ae)},[G,q,mn,p,Rt,Ae]),mt(()=>{if(!G||!q)return;bi.current=!1;let r=null,y=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,F.current="idle",W(null)},400)},M=q.on("submitting",()=>{Cr(!0),Z.current&&clearTimeout(Z.current),F.current="validation-window",Z.current=setTimeout(()=>{Z.current=null,F.current==="validation-window"&&(F.current="processing")},_p),W("processing");let Ye=ur.current;if(!Ye.sessionId||!Ye.nonce)return;let dt=Ls();if(!dt){Ye.updateError("Enter a valid email address."),F.current="idle",W(null);return}new No(Ye.baseUrl).patchAccountSnapshot(Ye.sessionId,Ye.nonce,dt,{telemetryMode:"best_effort"}).catch(St=>{if(!Tp(St))return;let En=St instanceof Error?St.message:"Please check your billing address and try again.";Ye.updateError(En),F.current="idle",W(null),Ye.onError?.(St instanceof Tr?St:new Tr(En,"api_error"))})}),oe=q.on("complete",Ye=>{Bo(Ye.sessionId??ur.current.sessionId),F.current="terminal",D(!1),W("success"),setTimeout(()=>{if(bi.current)return;bi.current=!0;let dt=ur.current,St=ts(dt)||Ye.outcome==="authorized",En=dt.serverSideCardGateway?{}:{paymentIntentId:Ye.intentId};ur.current.onComplete?.(St?{status:"authorized",...En,paymentId:Ye.paymentId??dt.paymentId,sessionId:Ye.sessionId??dt.sessionId,authorizationExpiresAt:Ye.authorizationExpiresAt??dt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...En,checkoutMethod:"card"})},600)}),A=q.on("decline",Ye=>{let dt=ur.current,St=Ye.message??"Your payment was declined. Please try another card or contact your bank.";F.current="terminal",D(!1),dt.updateError(St),W("error");let En=Ye.failureOutcome??ep(Ye.declineReason)??"authorization_declined";dt.emitDecline("card",St,{code:En,declineCode:En}),y()}),ae=q.on("error",Ye=>{let dt=ur.current,St=Ye.message??"There was a problem processing your payment. Please try again.";F.current="terminal",D(!1),dt.updateError(St),W("error"),dt.onError?.(new Tr(St,"api_error",{code:Ye.failureOutcome??"capture_failed"})),y()}),xt=q.on("challenge_dismissed",()=>{Z.current&&(clearTimeout(Z.current),Z.current=null),F.current="processing",D(!0),W(null)}),ir=q.on("blocked",()=>{if(Ie.current){ur.current.updateError(Ep);return}if(!Us.current){Cr(!0);return}Ci(),ur.current.updateError(wc)});return()=>{r&&(clearTimeout(r),r=null),Z.current&&(clearTimeout(Z.current),Z.current=null),F.current="idle",D(!1),W(null),M(),oe(),A(),ae(),xt(),ir()}},[G,q,Ci,Ls]);let kr=!!Pt?.clientId,Vo=Array.isArray(H),Ra=Vo&&H.length>0,zs=Vo&&H.includes("paypal"),_a=V(null);_a.current===null&&(_a.current=Yu());let mo=_a.current?"redirect":bl(et,Xe,P.current()),{expressMethods:Ea,paymentElementMethods:Si}=wt(()=>tp(H,{excludePaypal:kr}),[H,kr]),qs=kr||!!Dt||zs&&mo==="redirect",td=wt(()=>qs?Ea.filter(r=>r!=="paypal"):Ea,[Ea,qs]),nd=wt(()=>{let r=[];return ot&&r.push("apple_pay"),ze&&r.push("google_pay"),r},[ot,ze]),fo=Vo?td:nd,rd=R&&fo.length>0,js=tn?zt:O,Ta=wt(()=>Vu(Si,js,Ne),[Si,js,Ne]),wi=wt(()=>({mode:"payment",amount:Wo,currency:uo,paymentMethodCreation:"manual",appearance:Ts}),[Wo,uo,Ts]),[$s,Ws]=le("loading"),[Vs,Hs]=le("loading"),[Ks,Gs]=le("loading"),[od,ki]=le(!1),[Ys,Ii]=le("loading"),[Ri,ad]=le();mt(()=>{ad(ra())},[]);let Ma=Ri?.inAppBrowser,Aa=Ri?za(Ri,Pt?.approvalPresentation,Ot??(ce?"subscription":"order")):"popup",Js=Ve&&(kr||(Vo?zs:Ma===!1)),id=et.inAppBrowser&&P.current()==="blocked",Xs=R&&rd&&!id,Ho=(!he||!!de.waitForDataAttachment)&&Js&&kr,Zs=Ys==="retrying"||Ys==="exhausted",Ko=null;R&&(Dt?Ko=Es:mo==="redirect"&&(Ko=On));let Qs=wt(()=>({...Ke,presentationMode:mo}),[Ke,mo]),Go=!he&&Js&&!!Ko&&(!kr||Zs),go=!he&&Xs&&!!On,Yo=!he&&R&&Ra&&Ta.length>0&&!!On,sd=Ho&&!Zs?od:Go&&zi($s),ld=go&&zi(Vs),cd=Yo&&Ks!=="load_error",el=r=>r==="loading"||r==="ready",tl=Ho||Go&&el($s)||go&&el(Vs)||Yo&&Ks!=="load_error",xa=V(!1);mt(()=>{if(!xa.current){if(!R&&!Ve){xa.current=!0;let r=new Tr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(r),me(r.message)}else if(!R&&Ve&&!kr){xa.current=!0;let r=new Tr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(r),me(r.message)}else if(Ma!==void 0&&!he&&!nn&&!tl){xa.current=!0;let r=new Tr("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),me(r.message)}}},[R,Ve,kr,Ma,he,nn,tl,l,me]);let nl=V(!1);mt(()=>{if(nl.current||!Ra)return;let r=[];ot!==!0&&r.push("showApplePay"),ze!==!0&&r.push("showGooglePay"),r.length!==0&&(nl.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.`))},[Ra,ot,ze]);let rl=Te((r,y,M)=>de.applyInlineSessionPatch?de.applyInlineSessionPatch(r).then(oe=>({error:null,sessionId:oe.sessionId||e,nonce:oe.session?.clientSecret||t})).catch(oe=>{let A=Pc(y,oe);return M?.abandoned?.()||(me(A.message),l?.(A)),{error:A,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[de.applyInlineSessionPatch,t,l,e,me]),pr=Te(async(r,y)=>{if(r!=="card"&&he&&await de.waitForDataAttachment?.(),!ft)return{proceed:!0};try{let M=await ft({method:r,sessionId:e||void 0,createSession:de.inlineSessionDraft});if(M===!1)return{proceed:!1};if(M&&typeof M=="object"){M.account&&Me(A=>({...A??{},...M.account}));let oe=await rl(M,r,y);return oe.error?{proceed:!1,accountPatch:M.account}:{proceed:!0,accountPatch:M.account,sessionId:oe.sessionId,nonce:oe.nonce}}return{proceed:!0}}catch(M){if(!y?.abandoned?.()){let oe=Pc(r,M);me(oe.message),l?.(oe)}return{proceed:!1}}},[rl,de.inlineSessionDraft,de.waitForDataAttachment,he,ft,l,e,me]),ol=Te(async(r,y)=>{if(B.current)return;B.current=!0,Pn(!0),W("processing"),me(null);let M=y?.sessionId??e,oe=y?.nonce??t,A=$i($,y?.accountPatch),ae=y?.completionPaymentMethodId??sa(r),xt=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,ir=Bp(r),Ye=y?.presentationMode?ii(gn(Ce),{...Ke,presentationMode:y.presentationMode}):void 0,dt=()=>{kt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ir}),Ye?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...gr,requestCategory:"process_payment"})};try{let St=new No(nr),yr=y?.settledProcessResponse??await St.processPayment(A.userId??"",{sessionId:M,nonce:oe,paymentMethodCategory:y?.paymentMethodCategory??Dp(r),tokenizedData:xt,accountData:{...y?.accountPatch,userId:A.userId??"",email:A.email??"",firstName:A.firstName||void 0,lastName:A.lastName||void 0,...Nu({avsConfig:ke,country:Rn.current,zip:it.current,city:pn.current,state:Kt.current,addressLine1:qt.current,addressLine2:en.current})},...Ou({chv:ue,avsCheck:ht,checkoutType:Pe,checkoutLayout:$e,avsConfig:ke,country:Rn.current})}),Na=async kn=>{let no=ts(h)||kn?.status==="authorized";Bo(M),Ye?.terminal({outcome:"payment_succeeded",...gr}),W("success"),Ct(null),await new Promise(ta=>setTimeout(ta,600));let Ir;typeof kn?.paymentId=="string"?Ir=kn.paymentId:h?.paymentId&&(Ir=h.paymentId);let ro;typeof kn?.authorizationExpiresAt=="string"?ro=kn.authorizationExpiresAt:h?.authorizationExpiresAt&&(ro=h.authorizationExpiresAt),s?.(no?{status:"authorized",...Ir===void 0?{}:{paymentId:Ir},sessionId:typeof kn?.sessionId=="string"?kn.sessionId:M,...ro===void 0?{}:{authorizationExpiresAt:ro},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ae,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ae,checkoutMethod:r.isPaypal?"paypal":"card"})};if(yr.ok){await Na(yr.status===204?null:await yr.json().catch(()=>null));return}let dn=await yr.json().catch(()=>null);if(dn?.type==="paypal_redirect_required"){let kn=dn.threeDSecureToken,no=dn.paymentMethodId||r.id||"";if(!Ce||!kn){W("error"),me("PayPal authorization required but no token provided.");return}try{let Ir=Dt?.getRawProvider();if(!Ir){me("PayPal is not available.");return}let ro={return_url:window.location.href};no&&(ro.payment_method=no);let{error:ta}=await Ir.confirmPayment({clientSecret:kn,confirmParams:ro,redirect:"if_required"});if(ta){W("error");let gl=ta.message??"PayPal payment failed.";me(gl),wr("paypal",gl,{code:ta.code})}}catch(Ir){W("error"),me(Ir instanceof Error?Ir.message:"PayPal authorization failed.")}return}if(dn?.type==="paypal_direct_required"){let kn=dn.orderId;if(!kn){W("error"),me("PayPal retry required but no order id provided.");return}let no=Sn.current?.attempts??0;if(no>=2){W("error"),me("PayPal payment could not be completed after multiple attempts."),wr("paypal","paypal_direct_required retry limit exceeded");return}ki(!1),Ii("loading"),Ct({orderId:kn,attempts:no+1}),W(null);return}if(yr.headers.get(Cp)===bp){let kn=await Sp(St,M,oe);if(kn!==void 0){await Na(kn);return}}zu(yr.status,dn)?Ye?.terminal({outcome:"payment_declined",...gr,terminalReason:"provider_declined"}):dt(),W("error");let fl=dn?.message??"Payment failed. Please try again.";me(fl),wr(r.isPaypal?"paypal":"card",fl,{code:dn?.code??dn?.gatewayErrorCode,declineCode:dn?.declineCode??dn?.gatewayDeclineReason}),await new Promise(kn=>setTimeout(kn,400))}catch(St){Nc(St)||dt(),W("error"),me(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(En=>setTimeout(En,400))}finally{Pn(!1),W(null),B.current=!1}},[nr,e,t,$,ke,ht,Pe,$e,ue,Ce,Dt,h,s,me,wr,kt,Ke]),Jn=Te((r,y)=>{T&&!y?.settledProcessResponse?T(r):ol(r,y)},[T,ol]),Jo=`${Dc}:${e}`;mt(()=>{if(typeof window>"u")return;let r=localStorage.getItem(Jo);if(!r)return;let y;try{y=JSON.parse(r)}catch{sn(Jo);return}if(!y||typeof y.createdAt!="number"||Date.now()-y.createdAt<0||Date.now()-y.createdAt>Oc||typeof y.paymentMethodId!="string"||typeof y.providerIntentId!="string"||typeof y.paymentMethodType!="string"||y.sessionId!==e||!t||y.nonce!==t||!fo.includes(y.paymentMethodType)){sn(Jo);return}sn(Jo),Jn({id:y.paymentMethodId,type:"card",threeDSecureActionResultTokenId:y.providerIntentId,gateway:"stripe",paymentMethodType:y.paymentMethodType},{...y.accountPatch?{accountPatch:y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Jn,t,e,Jo,fo]);let al=V(!1);mt(()=>{if(typeof window>"u"||al.current)return;let[r,y,M]=Mc();if(!r||!y||_a.current||!Ce)return;let oe=Ce.getRawProvider();if(!oe)return;let A=dt=>{let St=localStorage.getItem(dt);if(!St)return null;try{return JSON.parse(St)}catch{return sn(dt),null}},ae=A(Mr)??A(Cc),xt;if(ae?.clientSecret){if(ae.clientSecret!==y)return;xt={...ae.accountPatch?{accountPatch:ae.accountPatch}:{},...ae.sessionId?{sessionId:ae.sessionId}:{},...ae.nonce?{nonce:ae.nonce}:{}}}else if(ae?.sessionId&&ae.sessionId!==e)return;al.current=!0,sn(Mr),sn(Cc),window.history.replaceState({},"",xc());let ir=ae?.paymentMethodType??ae?.tokenType??"card",Ye="card";(async()=>{if(M==="failed"){let dn="Payment was declined. Please try again.";me(dn),wr(Ye,dn);return}let{paymentIntent:dt,error:St}=await oe.retrievePaymentIntent(y);if(St){let dn=St.message??"Failed to retrieve payment status.";me(dn),wr(Ye,dn,{code:St.code});return}let En=dt?.status,yr=ia(En);if(!dt||!yr){let dn=En==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(dn),wr(Ye,dn,{code:En??"missing_payment_intent"});return}let Na=typeof dt.payment_method=="string"?dt.payment_method:dt.payment_method?.id;Jn({id:Na??ae?.paymentMethodId??ae?.tokenId??dt.id,type:"card",threeDSecureActionResultTokenId:dt.id,gateway:ae?.gateway??"stripe",paymentMethodType:ir},xt)})()},[e,Jn,Ce,me,wr]);let _i=Te(r=>{r.preventDefault()},[]);if(!(G||Ce!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Xo=qe==="buttons",Xn=tt?.variables,dd=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ei=Xn?.colorBackground,ud=Ei&&!dd.has(Ei)?Ei:void 0,Zo=b.cardInputBorder??(Xo?"#e5e7eb":"#A4A4FF"),il=Xn?.colorDanger??"#dc2626",Yt=r=>Fn[r]&&($r[r]||Gt),Ba=Rt&&(Sr||Gt),ar=r=>r?il:Zo,Fa=(Et.malformed||Et.empty)&&(Br||Gt),pd=ar(Fa),Ti=b.cardFormContainer?.backgroundColor??ud??(Xo?"white":"#EDEDFF"),ho=b.cardInputBackground??Xn?.colorBackground??"white",Mi=bo(at),sl=bo(fe),Po=b.nameInput,ll=b.cardInputFontSize??Up(Po?.fontSize)??Xn?.fontSizeBase??"16px",cl=typeof Po?.fontFamily=="string"?Po.fontFamily:Xn?.fontFamily??"Poppins, sans-serif",dl=dp(Po?.fontWeight)??400,yd=b.cardInputColor??(typeof Po?.color=="string"?Po.color:void 0)??Xn?.colorText??"#262833",md=b.cardInputPlaceholderColor??"#9ca3af",an=Xn?.borderRadius??"8px",eo=Xn?.borderRadius??b.cardButton?.borderRadius??an,to=Xn?.colorPrimary??"#4A49FF",fd=Xn?.colorPrimaryHover??$u(to,.12),Ai=Xn?.colorText??"#262833",xi={fontSize:ll,fontFamily:cl,fontWeight:dl,color:yd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Qo={marginTop:"0.375rem",...xi,fontSize:"0.75rem",lineHeight:1.4,color:il},gd={"--flopay-input-placeholder-color":md,"--flopay-input-font-size":ll,"--flopay-input-font-family":cl,"--flopay-input-font-weight":String(dl)},ea=b.cardFormContainer??{},Bi=ea.padding??(Xo?"0":"1rem"),Fi=ea.borderRadius??an,hd=q&&er?u(Di,{capture:q,html:er.html,messageToken:er.messageToken,expectedOrigin:er.expectedOrigin,verificationRequired:er.verificationRequired,theme:cn,submitLabel:Be,onReady:()=>{if(!xe&&!ke||typeof document>"u")return;let r=()=>{let M=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(M){_n.current=!0;try{M.focus()}finally{_n.current=!1}}};or.current||r()},onError:r=>{r&&er.verificationRequired&&F.current==="idle"&&(Nr.current=!0),me(r)},onValidation:r=>{let y=F.current;(y==="idle"||y==="validation-window")&&(me(r),r&&F.current==="validation-window"&&(Z.current&&(clearTimeout(Z.current),Z.current=null),F.current="idle",W(null)))}},Dn):u("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ul=Je("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&dr()},style:{backgroundColor:Ti,borderRadius:Fi,...ea,padding:Bi,...gd,display:"flex",flexDirection:"column"},children:[u("style",{children:`
5
5
  .flopay-shared-input::placeholder {
6
6
  color: var(--flopay-input-placeholder-color);
7
7
  opacity: 1;
@@ -9,13 +9,13 @@ ${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
+ `}),Xo&&Qr&&Je("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:G?-2:0},children:[Je("button",{type:"button",onClick:te,style:{display:"inline-flex",alignItems:"center",gap:Mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:u("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(wo,{content:at})]}),sl?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...b.title},children:u(aa,{content:fe})})]}),!Xo&&!sl&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ai,order:G?-3:0,...b.title},children:u(aa,{content:fe})}),G&&_e&&u("div",{style:{order:-2,width:"100%"},children:_e}),G&&xe&&Je("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[u("div",{style:{backgroundColor:ho,border:`1px solid ${ar(Ba)}`,borderRadius:an,padding:"10px"},children:u("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Ht,onChange:r=>{At("email"),jt.current=r.target.value,un(r.target.value)},onPointerDown:()=>At("email"),onKeyDown:()=>At("email"),onBlur:()=>{Kn("email")&&Fr(!0),Rt||Ci()},disabled:nt,required:!0,"aria-invalid":Ba||void 0,"aria-describedby":Ba?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...xi}})}),Ba&&u("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Qo,children:$n.empty?"Email address is required":"Enter a valid email address"})]}),ke&&u("div",{style:{order:G?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=zt,y=(A=!1)=>({backgroundColor:ho,border:`1px solid ${ar(A)}`,borderRadius:an,marginTop:"0.5rem",padding:"10px"}),M=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...xi}),oe=Gu(r);return Je(Lo,{children:[Jt(ke.address_line_1,r)&&Je(Lo,{children:[u("div",{style:y(Yt("line1")),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Qt,onChange:A=>{At("line1"),vn.current.addressLine1=!0,qt.current=A.target.value,Vn(A.target.value)},onPointerDown:()=>At("line1"),onKeyDown:()=>At("line1"),onBlur:()=>Gn("line1"),disabled:nt,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:M()})}),Yt("line1")&&u("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Qo,children:"Street address is required"})]}),Jt(ke.address_line_2,r)&&u("div",{style:y(),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:yt,onChange:A=>{vn.current.addressLine2=!0,en.current=A.target.value,Pr(A.target.value)},disabled:nt,"data-testid":"flopay-address-line2",style:M()})}),(Jt(ke.city,r)||Jt(ke.state,r))&&Je("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Jt(ke.city,r)&&u("div",{style:{flex:1,backgroundColor:ho,borderTop:`1px solid ${ar(Yt("city"))}`,borderRight:`1px solid ${ar(Yt("city"))}`,borderBottom:`1px solid ${ar(Yt("city"))}`,borderLeft:`1px solid ${ar(Yt("city"))}`,padding:"10px",borderTopLeftRadius:an,borderBottomLeftRadius:an,...Jt(ke.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:an}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Vt,onChange:A=>{At("city"),vn.current.city=!0,pn.current=A.target.value,rr(A.target.value)},onPointerDown:()=>At("city"),onKeyDown:()=>At("city"),onBlur:()=>Gn("city"),disabled:nt,required:!0,"aria-invalid":Yt("city")||void 0,"aria-describedby":Yt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:M()})}),Jt(ke.state,r)&&u("div",{style:{flex:1,backgroundColor:ho,borderTop:`1px solid ${ar(Yt("state"))}`,borderRight:`1px solid ${ar(Yt("state"))}`,borderBottom:`1px solid ${ar(Yt("state"))}`,borderLeft:`1px solid ${ar(Yt("state"))}`,padding:"10px",borderTopRightRadius:an,borderBottomRightRadius:an,...Jt(ke.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${ar(Yt("state")||Yt("city"))}`}:{borderRadius:an}},children:oe?Je("select",{id:"flopay-billing-state",name:"billing-state",value:Un,onChange:A=>{At("state"),vn.current.state=!0,Kt.current=A.target.value,zn(A.target.value)},onPointerDown:()=>At("state"),onKeyDown:()=>At("state"),onBlur:()=>Gn("state"),disabled:nt,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:{...M(),cursor:"pointer"},children:[u("option",{value:"",children:es(r)}),oe.map(A=>u("option",{value:A.code,children:A.name},A.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:es(r),autoComplete:"billing address-level1",value:Un,onChange:A=>{At("state"),vn.current.state=!0,Kt.current=A.target.value,zn(A.target.value)},onPointerDown:()=>At("state"),onKeyDown:()=>At("state"),onBlur:()=>Gn("state"),disabled:nt,required:!0,"aria-invalid":Yt("state")||void 0,"aria-describedby":Yt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:M()})})]}),Yt("city")&&u("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Qo,children:"City is required"}),Yt("state")&&Je("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Qo,children:[es(r)," is required"]}),(Jt(ke.country,r)||Jt(ke.postal_code,r))&&Je("div",{style:{display:"flex",flexDirection:se==="column"?"column":"row",gap:se==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Jt(ke.country,r)&&u("div",{style:{flex:se==="row"?1:void 0,backgroundColor:ho,borderTop:`1px solid ${Zo}`,borderRight:`1px solid ${Zo}`,borderBottom:`1px solid ${Zo}`,borderLeft:`1px solid ${Zo}`,padding:"10px",...se==="row"&&Jt(ke.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:an,borderBottomLeftRadius:an,borderRight:"none"}:{borderRadius:an}},children:Je("select",{id:"flopay-billing-country",name:"billing-country",value:zt,onChange:A=>{vn.current.country=!0,Rn.current=A.target.value,pt(A.target.value),gt?.(A.target.value),Kt.current="",zn("")},disabled:nt,autoComplete:"billing country","data-testid":"flopay-country",style:{...M(),cursor:"pointer"},children:[zt===""?u("option",{value:"",children:"Select country"}):null,Uu.map(A=>Je("option",{value:A.code,children:[A.flag," ",A.name]},A.code))]})}),Jt(ke.postal_code,r)&&u("div",{style:{flex:se==="row"?1:void 0,backgroundColor:ho,border:`1px solid ${pd}`,padding:"10px",...se==="row"&&Jt(ke.country,r)?{borderRadius:"0",borderTopRightRadius:an,borderBottomRightRadius:an}:{borderRadius:an}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ls(zt),autoComplete:"billing postal-code",value:Ln,onChange:A=>{At("zip"),vn.current.zip=!0,it.current=A.target.value,An(A.target.value),Ee?.(A.target.value)},onPointerDown:()=>At("zip"),onKeyDown:()=>At("zip"),onBlur:()=>{Kn("zip")&&br(!0)},disabled:nt,required:Et.required,"aria-invalid":Fa||void 0,"aria-describedby":Fa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:M()})})]}),Fa&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Qo,children:Et.empty?`${ls(r)} is required`:Op(r)})]})})()}),G&&hd,Q&&u(xo,{margin:"0.75rem 0",styleOverride:b.errorBanner,children:Q})]}),Da={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"},pl=r=>_?!Ve||!kr?u("pre",{"data-testid":r,style:Da,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":r,style:Da,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${Ve}`,` directPaypalConfigured=${kr}`,` inAppBrowserDetected=${String(Ma)}`,` shouldRenderDirectPayPal=${Ho}`,` shouldRenderStripePayPal=${Go}`,` hasPaypalStripeInstance=${!!Es}`].join(`
13
+ `)}):null,yl=r=>_?!R||!On?u("pre",{"data-testid":r,style:Da,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":r,style:Da,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${R}`,` currency=${In}`,` amountInCents=${Wo}`,` enabledPaymentMethods: ${JSON.stringify(H??[])}`,` enabledPaymentMethodsProvided=${Vo}`,` hasEnabledMethods=${Ra}`,` expressMethods: ${JSON.stringify(Ea)}`,` walletExpressMethods: ${JSON.stringify(fo)}`,` paymentElementMethods: ${JSON.stringify(Si)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ta)}`,` hasStripeInstance=${!!On}`,` shouldRenderWallets=${go}`,` shouldRenderPaymentElement=${Yo}`].join(`
14
+ `)}):null,ml=Ue==="apm-expanding"||Ue==="apm-form"||Ue==="apm-collapsing",vo;Ue==="apm-expanding"?vo=kc:Ue==="apm-collapsing"&&(vo=Ic);let Oa=on?Uc(wi,on,we):null;if(qe==="buttons"){let r=Ue==="buttons"||Ue==="expanding"||Ue==="apm-expanding",y=Ue==="expanding"||Ue==="card"||Ue==="collapsing",M=ut===void 0?{boxSizing:"border-box",height:oa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},oe;Ue==="expanding"||Ue==="apm-expanding"?oe=xp:(Ue==="collapsing"||Ue==="apm-collapsing")&&(oe=Ap);let A;return Ue==="expanding"?A=kc:Ue==="collapsing"&&(A=Ic),Je("form",{onSubmit:_i,className:L,noValidate:!0,style:{position:"relative"},children:[u(qa,{}),ne&&u(Rr,{status:ne,errorMessage:Q,authorized:Cn}),Je("div",{style:{display:"grid"},children:[Je("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!oe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!oe?Fp:{},...oe?{animation:oe,pointerEvents:"none"}:{}},children:[pl("flopay-direct-paypal-gate-debug"),yl("flopay-stripe-gate-debug"),Ho&&Pt&&Je(Lo,{children:[Re&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(da.Provider,{value:P,children:u(Xa,{sessionId:e,nonce:t,billingApiUrl:J,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,clientId:Pt.clientId,environment:Pt.environment,currency:In.toUpperCase(),isSubscription:ce,providerObjectType:Ot,approvalPresentation:Aa==="popup"?void 0:Aa,onTokenizedBody:Jn,onComplete:s,onErrorChange:me,onDecline:m,onCancel:C,onTechnicalFailure:yo,onButtonClick:pe,runBeforeButtonClick:pr,isProcessing:nt,onLoadStateChange:ki,onInitializationStateChange:Ii,session:be,existingOrderId:Re?.orderId,debug:_},Re?.orderId??"fresh")})]}),Go&&u(lo,{stripe:Ko,options:As,children:u(_c,{sessionId:e,nonce:t,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,billingApiUrl:J,onTokenizedBody:Jn,onErrorChange:me,isProcessing:nt,onButtonClick:pe,onDecline:m,onTechnicalFailure:yo,runBeforeButtonClick:pr,onLoadStateChange:Ws,placeholderBorderRadius:eo,popupCapabilityOwner:P,externalTelemetryContext:Qs,presentationMode:mo})}),go?u(lo,{stripe:On,options:Ms,children:u(Ec,{sessionId:e,nonce:t,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,billingApiUrl:J,intentKind:He>0?"payment":"setup",expressMethods:fo,onTokenizedBody:Jn,onErrorChange:me,onButtonClick:pe,onDecline:m,onTechnicalFailure:yo,runBeforeButtonClick:pr,onLoadStateChange:Hs,placeholderBorderRadius:eo,popupCapabilityOwner:P,externalTelemetryContext:Ke})}):null,!go&&Xs?u("div",{style:{height:oa,borderRadius:eo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Yo&&u(Tc,{sessionId:e,nonce:t,email:$.email,billingName:[$.firstName,$.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:v,billingApiUrl:J,paymentElementMethods:Ta,stripeInstance:On,paymentElementBaseOptions:wi,futureUseSession:we,onTokenizedBody:Jn,onErrorChange:me,onButtonClick:pe,onDecline:m,runBeforeButtonClick:pr,onLoadStateChange:Gs,isProcessing:nt,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:b.submitButton,onExpandApm:We,expandedApmMethod:on,themeId:It,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:eo}}),G&&u("button",{type:"button",onClick:async()=>{nt||!(await pr("card")).proceed||(pe?.("card"),j())},disabled:nt,style:{width:"100%",...M,...b.cardButton,...gs({themeBundle:re,resolvedPrimaryColor:to,resolvedBorderRadius:an,submitButtonStyle:b.submitButton,explicitPrimaryColor:Xn?.colorPrimary}),fontSize:b.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:nt?"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:nt?.6:1},onMouseEnter:ae=>{!nt&&(re||Xn?.colorPrimary)&&(ae.currentTarget.style.backgroundColor=fd)},onMouseLeave:ae=>{(re||Xn?.colorPrimary)&&(ae.currentTarget.style.backgroundColor=to)},onMouseDown:ae=>{ae.currentTarget.style.transform="scale(0.985)"},onMouseUp:ae=>{ae.currentTarget.style.transform="scale(1)"},children:u(So,{content:ut})}),Q&&Ue==="buttons"&&u(xo,{margin:"0.25rem 0",styleOverride:b.errorBanner,children:Q})]}),G&&y&&u("div",{style:{gridArea:"1 / 1",...A?{animation:A}:{},...Ue==="collapsing"?{pointerEvents:"none"}:{}},children:ul}),R&&ml&&on&&Oa&&On&&u("div",{style:{gridArea:"1 / 1",...vo?{animation:vo}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Je("div",{style:{backgroundColor:Ti,borderRadius:Fi,...ea,padding:Bi},children:[Je("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Je("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:u("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(wo,{content:at})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Ai,paddingRight:80,...b.title},children:`Pay with ${va(on)}`})]}),u(lo,{stripe:On,options:Oa,children:u(us,{method:on,sessionId:e,nonce:t,email:$.email,billingName:[$.firstName,$.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:v,billingApiUrl:J,onTokenizedBody:Jn,onErrorChange:me,onDecline:m,onCancel:Wt,runBeforeButtonClick:pr,onButtonClick:pe,isProcessing:nt,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:b.submitButton,errorText:Q})},on)]})})]})]})}return ml&&on&&Oa&&On&&R?Je("form",{onSubmit:_i,className:L,noValidate:!0,style:{position:"relative"},children:[u(qa,{}),ne&&u(Rr,{status:ne,errorMessage:Q,authorized:Cn}),u("div",{style:{...vo?{animation:vo}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Je("div",{style:{backgroundColor:Ti,borderRadius:Fi,...ea,padding:Bi},children:[Je("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Je("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:u("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(wo,{content:at})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Ai,paddingRight:80,...b.title},children:`Pay with ${va(on)}`})]}),u(lo,{stripe:On,options:Oa,children:u(us,{method:on,sessionId:e,nonce:t,email:$.email,billingName:[$.firstName,$.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:v,billingApiUrl:J,onTokenizedBody:Jn,onErrorChange:me,onDecline:m,onCancel:Wt,runBeforeButtonClick:pr,onButtonClick:pe,isProcessing:nt,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:b.submitButton,errorText:Q})},on)]})})]}):Je("form",{onSubmit:_i,className:L,noValidate:!0,style:{position:"relative"},children:[u(qa,{}),ne&&u(Rr,{status:ne,errorMessage:Q,authorized:Cn}),Je("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[pl("flopay-direct-paypal-gate-debug-default"),yl("flopay-stripe-gate-debug-default"),Ho&&Pt&&Je(Lo,{children:[Re&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(da.Provider,{value:P,children:u(Xa,{sessionId:e,nonce:t,billingApiUrl:J,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,clientId:Pt.clientId,environment:Pt.environment,currency:In.toUpperCase(),isSubscription:ce,providerObjectType:Ot,approvalPresentation:Aa==="popup"?void 0:Aa,onTokenizedBody:Jn,onComplete:s,onErrorChange:me,onDecline:m,onCancel:C,onTechnicalFailure:yo,onButtonClick:pe,runBeforeButtonClick:pr,isProcessing:nt,onLoadStateChange:ki,onInitializationStateChange:Ii,session:be,existingOrderId:Re?.orderId,debug:_},Re?.orderId??"fresh")})]}),Go&&u(lo,{stripe:Ko,options:As,children:u(_c,{sessionId:e,nonce:t,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,billingApiUrl:J,onTokenizedBody:Jn,onErrorChange:me,isProcessing:nt,onButtonClick:pe,onDecline:m,onTechnicalFailure:yo,runBeforeButtonClick:pr,onLoadStateChange:Ws,placeholderBorderRadius:eo,popupCapabilityOwner:P,externalTelemetryContext:Qs,presentationMode:mo})}),go&&u(lo,{stripe:On,options:Ms,children:u(Ec,{sessionId:e,nonce:t,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,billingApiUrl:J,intentKind:He>0?"payment":"setup",expressMethods:fo,onTokenizedBody:Jn,onErrorChange:me,onButtonClick:pe,onDecline:m,onTechnicalFailure:yo,runBeforeButtonClick:pr,onLoadStateChange:Hs,placeholderBorderRadius:eo,popupCapabilityOwner:P,externalTelemetryContext:Ke})}),Yo&&u(Tc,{sessionId:e,nonce:t,email:$.email,billingName:[$.firstName,$.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:J,paymentElementMethods:Ta,stripeInstance:On,paymentElementBaseOptions:wi,futureUseSession:we,onTokenizedBody:Jn,onErrorChange:me,onButtonClick:pe,onDecline:m,runBeforeButtonClick:pr,onLoadStateChange:Gs,isProcessing:nt,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:b.submitButton,themeId:It,onExpandApm:We,expandedApmMethod:on,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:eo}})]}),G&&(ld||sd||cd)&&u(hl,{label:"or pay with card"}),G&&ul]})}import{Fragment as Ar,jsx as ye,jsxs as hn}from"react/jsx-runtime";var zo=44,ks="flopay_checkout_saved_payment_resume",gi=new Map,mi=new Map;function $c(e,t){t.settled&&t.consumers===0&&gi.get(e)===t&&gi.delete(e)}function Zp(e,t,n){let o=mi.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};mi.set(e,i);let s=()=>{mi.get(e)===i&&mi.delete(e)};return a.then(s,s),a}function ba(e){return new Promise(t=>setTimeout(t,e))}function fi(e,t,n){let o=Ya({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Zc,enabled:t!==!1});return o.beginCheckout(n),o}function Sa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function vs(e,t,n,o,a,i){let s=fi(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Sa(s)}function Wc(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 Vc(e,t,n,o,a){let i=Yc(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 Mn&&t.code==="session_auto_completed"?!1:t instanceof Mn&&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 Cs(e){return!e||e.data.stripe?.publishableKey?!1:!!Jc(e.data.paypal)?.clientId}var Qp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function ey(e){return new $p(Qp,{publishableKey:"provider_unavailable",...e})}async function bs(e,t){let{publishableKey:n,paypalPublishableKey:o}=Zi(e);return{...await Qi({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function Is(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ty(){if(!Is())return null;try{let e=window.sessionStorage.getItem(ks);return e?JSON.parse(e):null}catch{return null}}function Hc(e){if(Is())try{window.sessionStorage.setItem(ks,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ss(){if(Is())try{window.sessionStorage.removeItem(ks)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ny(){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 Kc(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 ws(e,t){return Jp(!!e,t)}function ry(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Gc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function oy(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 Rs({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:l,error:m,onComplete:C,onError:T,onInstrument:I,onDecline:N,onCancel:ue,onCountryChange:L,onZipChange:Be,showPayPal:K=!0,showStripe:g=!0,walletPresentation:S="auto",enabledPaymentMethods:Ve,showApplePay:R=!0,showGooglePay:Xe=!0,debug:H=!1,layout:Ne,theme:ot,buttonsTheme:ze,buttonsStyles:qe,cardButtonContent:It,cardBackButtonContent:st,cardTitleContent:ee,showSecurityFooter:Bt,onButtonClick:ut,onBeforeButtonClick:at,enableAVS:fe,cardFieldOrder:ie,cardPreFormSlot:pe,avsLayout:ft,submitLabel:Ft,className:Ze,initialErrorMessage:Y=null,initialPayPalOrderId:_e,children:se,checkoutMode:O,confirmLabel:je,renderConfirmButton:Le,onSessionCompleted:Fe}){let E=Gp(o),De=cr(()=>Xc(ot),[ot]),gt=i??De?.appearance,Ee=n?"embedded_checkout":"standard_checkout",ht=ws(se,Ne),[Pe,$e]=Xt(null),[He,In]=Xt(null),_t=Nt(null),Pt=Nt(null),ce=Nt(0),[h,lt]=Xt(null),Qe=Nt(null),[_,Ce]=Xt(null),Dt=cr(()=>n?ya(n):"",[n]),de=n?`create:${Dt}`:`session:${e??""}`,kt=Gc(_),f=Nt(new Set),P=Nt(de),ge=Nt(de);na(()=>{ge.current=de,P.current!==de&&(P.current=de,f.current.clear())},[de]);let ve=Nn(w=>{if(ge.current===de){if(Yl.has(w.name)){if(f.current.has(w.name))return;f.current.add(w.name)}Tt(()=>I?.(w))}},[de,I]),et=Mo(ve,de),Ke=Nt(!1),be=Nn(w=>{if(Ke.current)return;let k=w.gateway||!kt?w:{...w,gateway:kt};ve(k)},[ve,kt]);hr(()=>{et({class:"lifecycle",name:"checkout.mount"})},[et]);let[we,Ot]=Xt(e??""),p=e??we,Oe=n?"":p,[he,Se]=Xt(!0),[J,z]=Xt(null),[Pn,Wn]=Xt(0),[Zt,zt]=Xt("full"),[pt,Ln]=Xt(!1),[An,Qt]=Xt(Y),[Vn,yt]=Xt(null),[Pr,Vt]=Xt(null),[rr,Un]=Xt(!1),[zn,Ht]=Xt(void 0),[un,Hn]=Xt(""),[Me,it]=Xt(!1),[Rn,qt]=Xt(!1),[en,pn]=Xt(!1),Kt=Nt(null),jt=Nt(0),vn=Nt(void 0),[ke,tn]=Xt("loading"),[Cn,xr]=Xt(0),xn=Nt(!1),Bn=Nt(!1),vr=Nt(!1),Qn=Nt(null),nn=Nt(null),G=cr(()=>({checkoutMode:O??Zt,layout:ry(se,Ne)}),[O,se,Zt,Ne]),yn=Nt(C);yn.current=C;let qn=Nt(T);qn.current=T;let U=Nt(N);U.current=N;let vt=Nn(w=>ni(Qn,async k=>{try{return await w(k)}catch(j){throw k.aborted?Fo(j):j}}),[]);hr(()=>()=>{Qn.current?.abort(),Qn.current=null},[]);let x=Nn((w,k)=>{_t.current=w,In(w),Qe.current=k,lt(k)},[]),$t=Nn(()=>{let w=Pt.current;w&&(Pt.current=null,w.destroy())},[]);hr(()=>{gn(He)?.setCheckoutContext(G),h&&h!==He&&gn(h)?.setCheckoutContext(G)},[He,h,G]);let rn=Nt(Fe);rn.current=Fe;let X=Nn(w=>{tn(w),!(w!=="exhausted"||vr.current)&&(vr.current=!0,qn.current?.(new Mn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Lt=Nn(()=>{tn("retrying"),xr(w=>w+1)},[]);hr(()=>{tn("loading"),xr(0),vr.current=!1},[p]),hr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Zc,checkout_type:Ee,checkout_layout:ht,billing_api_url:E})},[ht,Ee,E]);let q=cr(()=>n?ya(n,!0):"",[n]),Et=cr(()=>un===q?zn:void 0,[zn,un,q]),mn=cr(()=>n?ji(n,Et):void 0,[n,Et]),Fn=O??mn?.checkoutMode??"full",Gt=cr(()=>mn?{...mn,checkoutMode:Fn}:void 0,[mn,Fn]);hr(()=>{Ht(void 0),Hn(q),vn.current=void 0,Kt.current=null,pn(!1)},[q]),hr(()=>{Qt(Y)},[Y]);let Cr=Nn((w,k,j)=>{Tt(()=>{U.current?.(fn(w,k,j))})},[]),Br=Nn(async(w,k)=>{Qt(null),Vt(null),Un(!1),yt("processing");let j=k?.sessionId??w.id,te=w.clientSecret||t,We=Gc(w),Wt=_t.current??Qe.current,ne=gn(Wt),W=Wt?null:fi(E,a,G),B={log:d=>{ne?ne.log(d):W?.log(d)},error:d=>{ne?ne.error(d):W?.error(d)},terminal:d=>{ne?ne.terminal(d):W?.terminal(d)},performance:d=>{ne?ne.performance(d):W?.performance(d)},now:()=>ne?.now()??W?.now()??0,elapsed:d=>ne?.elapsed(d)??Math.max(0,(W?.now()??d)-d)},Z=B.now(),F=!!(k?.initialAutoProcessingError||k?.initialAutoProcessingPending),Ae=!1,D,Ie=()=>{Ae||(Ae=!0,F=!0,D=B.now(),B.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Re=!1,Ct=()=>{Re||(Re=!0,B.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),B.performance({stage:"processing",durationMs:B.elapsed(Z),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),D!==void 0&&B.performance({stage:"recovery",durationMs:B.elapsed(D),durationMode:"machine",paymentMethodCategory:"saved"}))};B.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Ke.current=!0;try{B.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Ke.current=!1}et({class:"lifecycle",name:"payment.processing.started",provider:We}),F&&Ie();let Sn;try{let d=mc(k?.initialAutoProcessingError),c=k?.initialAutoProcessingError?.type==="3ds_required"&&!k.initialAutoProcessingError.threeDSecureToken&&k.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:k.initialAutoProcessingError.nextActionRedirectUrl}:null,v,Q=re=>(Ie(),vt(b=>Do(re,{billingApiUrl:E,sessionId:j,nonce:te,session:w,signal:b})));if(c)v=await Q(c);else if(d)Ie(),d.type==="paypal_redirect_required"&&nn.current?.publishableKey&&Hc({sessionId:j,publishableKey:nn.current.publishableKey,paypalPublishableKey:nn.current.paypalPublishableKey}),v=await vt(re=>ai(d,{flopay:_t.current,paypalFlopay:Qe.current,attempt3DS:k?.attempt3DS,billingApiUrl:E,sessionId:j,session:w,telemetry:!1,signal:re})),d.type==="paypal_redirect_required"&&Ss();else if(k?.initialAutoProcessingPending){let re=k.initialAutoProcessingPending,b=new yi(E,{telemetry:!1}),tt=await vt(nt=>b.waitForCheckoutSessionCompletion(re.sessionId,{initialDelayMs:re.retryAfterMs,nonce:te,statusUrl:re.statusUrl,signal:nt})),cn=Kr(tt,w),wn=tt.autoProcessingError?.type==="3ds_required"&&tt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:tt.autoProcessingError.nextActionRedirectUrl}:null;if(wn)v=await Q(wn);else{if(!Ur(cn))throw Ro(cn);v=Lr(cn,j)}}else{if(k?.initialAutoProcessingError)throw Er(k.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:k.initialAutoProcessingError.checkoutMethod});if(k?.fromCreateSession)return k?.fallbackToFull&&(zt("full"),Kc("full")),!1;{let re=await Oo({billingApiUrl:E,sessionId:j,session:w,nonce:te,telemetry:!1});re.type==="success"?v=re.result:re.type==="next_action_required"?v=await Q(re):(Ie(),re.type==="paypal_redirect_required"&&nn.current?.publishableKey&&Hc({sessionId:j,publishableKey:nn.current.publishableKey,paypalPublishableKey:nn.current.paypalPublishableKey}),v=await vt(b=>ai(re,{flopay:_t.current,paypalFlopay:Qe.current,attempt3DS:k?.attempt3DS,billingApiUrl:E,sessionId:j,session:w,telemetry:!1,signal:b})),re.type==="paypal_redirect_required"&&Ss())}}j&&Bo(j),Ct(),F&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),B.terminal({outcome:v.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Un(v.status==="authorized"),yt("success"),await ba(600),Sn=()=>yn.current?.(v)}catch(d){let c=Hr(ga(d),j);if(c.code==="three_ds_aborted")return!1;let v=c.checkoutMethod??fa;Qt(c.message),Vt(c.message),Un(!1),k?.fallbackToFull&&(B.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),zt("full"),Kc("full")),Ct();let Q=c.statusCode===void 0?void 0:Xp(c.statusCode,"unknown"),re=Q==="4xx"?{requestCategory:"process_payment",statusClass:Q}:{},b=Q===void 0||Q==="4xx";if(b&&(c.telemetryOutcome==="payment_declined"||!!(c.declineCode||c.code?.toLowerCase().includes("declin"))))B.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...re});else if(b&&(c.telemetryOutcome==="validation_rejected"||c.type==="validation_error"))B.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...re});else{let wn=Yc(d,F?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),nt=c.telemetryRequestCategory??"process_payment";Ke.current=!0;try{B.error({...wn,...c.telemetryFailureCategory?{failureCategory:c.telemetryFailureCategory}:{},stage:F?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:nt})}finally{Ke.current=!1}et({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:nt,provider:We})}return Tt(()=>qn.current?.(c)),Cr(v,c,{code:c.code,declineCode:c.declineCode}),yt("error"),await Promise.allSettled([ba(400),k?.ensureProvidersReady?k.ensureProvidersReady():Promise.resolve()]),F&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ct(),W&&Sa(W),yt(null),Vt(null)}return Tt(Sn),!0},[Cr,et,t,E,vt,a,G]);hr(()=>{if(typeof window>"u"||Bn.current)return;let w=new URLSearchParams(window.location.search),k=w.get("payment_intent_client_secret");if(!k)return;let j=ty();j&&(Bn.current=!0,(async()=>{let te,We=0;Qt(null),Vt(null),yt("processing"),Ln(!0);try{if(w.get("redirect_status")==="failed")throw Object.assign(new Mn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Wt,paypalFlopay:ne}=await Qi({publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey,billingApiUrl:E,locale:s,telemetry:a});te=gn(ne??Wt),te?.setCheckoutContext(G),We=te?.now()??0,te?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),te?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let W=(ne??Wt)?.getRawProvider();if(!W)throw Object.assign(new Mn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:Z}=await W.retrievePaymentIntent(k);if(Z)throw Object.assign(new Mn(Z.message??"Failed to retrieve PayPal payment status.","api_error",{code:Z.code}),{checkoutMethod:"paypal"});let F=Ul(B?.status);if(!B||F==="failed")throw Object.assign(new Mn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ae=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,D=F;if(j.sessionId){let Ct=(await new yi(E,{telemetry:!1}).getUnifiedCheckoutSession(j.sessionId)).data.session;if(Ct&&Ct.status!=="complete"){let Sn=await Oo({billingApiUrl:E,sessionId:j.sessionId,session:Ct,telemetry:!1,tokenizedData:{id:Ae??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(Sn.type!=="success")throw Object.assign(new Mn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});D=Sn.result.status}}j.sessionId&&Bo(j.sessionId),te?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),te?.performance({stage:"redirect_resume",durationMs:te.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),te?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),yt("success"),await ba(600),Tt(()=>yn.current?.({status:D,paymentIntentId:B.id,paymentMethodId:Ae,checkoutMethod:"paypal"}))}catch(Wt){let ne=Hr(ga(Wt),j.sessionId),W=ne.checkoutMethod??"paypal",B=!!(ne.declineCode||ne.code?.toLowerCase().includes("declin"));if(te)te.performance({stage:"redirect_resume",durationMs:te.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):te.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let Z=fi(E,a,G);Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Sa(Z)}else vs(E,a,G,"REDIRECT_RESUME_FAILED","redirect_resume");Qt(ne.message),Vt(ne.message),Tt(()=>qn.current?.(ne)),Cr(W,ne,{code:ne.code,declineCode:ne.declineCode}),yt("error"),await ba(400)}finally{Ss(),ny(),yt(null),Vt(null),Ln(!1)}})())},[Cr,s,E,a,G]);let br=Nt(null),Sr=cr(()=>Gt?ya(Gt):"",[Gt]),Fr=Nt(Gt);Fr.current=Gt,hr(()=>{Ot(e??"")},[e]),hr(()=>{xn.current=!1,Qt(Y),Vt(null),Un(!1),yt(null)},[Sr,Y,e]);async function $r(w,k,j){let te=fi(E,a,G),We=new yi(E,{telemetry:!1}),Wt=!1;try{let ne=w.idempotencyKey===void 0?void 0:qc(w.idempotencyKey),W=lc(k,j),B=sc(k,j);W?.canonicalIdentity===j&&B&&B.canonicalIdentity===void 0&&(Qa(k,j,B.idempotencyKey),B={...B,canonicalIdentity:j});let Z=ne??(B?.canonicalIdentity===j?B.idempotencyKey:void 0),F,Ae=!1;te.log({name:W?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let D=W?.sid??null,Ie=null,Re,Ct,Sn=!1;if(D)try{Ie=await We.getUnifiedCheckoutSession(D,W?.nonce),W&&W.canonicalIdentity===void 0&&(ic(Ie.data.session,w)?(ei(k,j,D,W.nonce??Ie.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(Qa(k,j,B.idempotencyKey),Z??(Z=B.idempotencyKey))):(Za(k,j),B=null,Z=ne,D=null,Ie=null));let c=Ie?.data.session?.status,v=Ie?.data.session,Q=v?.clientSecret||W?.nonce;if(D&&v?.buyerIdentified===!1&&Q&&(Ct=Io(We,D,Q,w.account)),D&&Ie&&c==="complete"){if(Yi(D))return{sid:D,result:Ie};Za(k,j),D=null,Ie=null,Ae=!0}}catch{te.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),W?.canonicalIdentity===void 0?(Za(k,j),Z=ne):Gi(k,j),D=null}if(!D){!ne&&(Ae||!Z)&&(Z=qc(),F=Z),Z&&Qa(k,j,Z);let c=te.now(),v=0;te.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Q={...w,idempotencyKey:Z,avsCheck:!!fe,avsConfig:typeof fe=="object"?fe:void 0,checkoutType:"embedded_checkout",checkoutLayout:ws(se,Ne)};Object.defineProperty(Q,Wp,{configurable:!1,enumerable:!1,value:{onAttempt:tt=>{v=Math.max(v,tt)}}});let re=()=>{Wc(te,"session_create",c,v)},b=tt=>{Vc(te,tt,"session_create",c,v)&&et({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Hp(Q)){let tt=await We.createDetachedSession(Q);tt.claimed.catch(()=>{}),Ie=tt.shell,D=tt.sessionId,Ct=tt.claim;let cn=te.now();te.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Re=tt.claimed.then(wn=>{let nt=wn.data.session?.id??tt.sessionId;return nt&&ei(k,j,nt,wn.data.session?.clientSecret??tt.nonce),Wc(te,"session_claim",cn),re(),wn},wn=>{throw Gi(k,j),Vc(te,wn,"session_claim",cn,0)&&et({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),wn}).finally(()=>Sa(te)),Re.catch(()=>{}),Wt=!0,te.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),te.performance({stage:"session_shell",durationMs:te.now()-c,durationMode:"machine",requestCategory:"session_create",attempt:v,statusClass:"2xx",paymentMethodCategory:"card"})}else Ie=await We.createAndFetchSession(Q),re()}catch(tt){throw b(tt),tt}D=Ie.data.session?.id??D??"",D&&!Re&&ei(k,j,D,Ie.data.session?.clientSecret)}let d=Ie?.data.session;return!Ct&&D&&d?.buyerIdentified===!1&&d.clientSecret&&(Ct=Io(We,D,d.clientSecret,w.account)),{sid:D??"",result:Ie,sdkGeneratedIdempotencyKey:F,...Re?{claimed:Re}:{},...Ct?{claim:Ct}:{},...Sn?{claimRequiresIdentity:!0}:{}}}finally{Wt||Sa(te)}}let Wr=Nt($r);na(()=>{Wr.current=$r},[$r]);let _n=Nn(async(w,k)=>{let j=Fr.current;if(!j)throw new Mn("createSession is required to bootstrap checkout.","validation_error");let te=ji(j,w),We=ya(te),Wt=ac(te),ne=gi.get(We);if(!ne){let Z={canonicalIdentity:We,promise:Wr.current(te,Wt,We),consumers:0,settled:!1};ne=Z,gi.set(We,Z);let F=()=>{Z.settled=!0,$c(We,Z)};Z.promise.then(F,F)}ne.consumers+=1;let W=!1,B=()=>{W||(W=!0,ne.consumers-=1,$c(We,ne))};k?.(B);try{let Z=await ne.promise;br.current=We,w&&(Hn(q),Ht(d=>Bl(d,w)));let{sid:F,result:Ae,claimed:D,claim:Ie,claimRequiresIdentity:Re}=Z;if(vn.current=Ie,pn(Re===!0),$e(Ae),Ae.data.session&&Ce(Ae.data.session),F&&Ot(F),D){jt.current+=1;let d=jt.current;Kt.current=D,qt(!0),D.then(c=>{jt.current===d&&(Kt.current===D&&(Kt.current=null),$e(c),c.data.session&&Ce(c.data.session),qt(!1),pn(!1))},c=>{jt.current===d&&(Kt.current===D&&(Kt.current=null),qt(!1),pn(!1),z(c instanceof Mn?c:new Mn(c instanceof Error?c.message:"Failed to create session","api_error")))})}else jt.current+=1,Kt.current=null,qt(!1),pn(!1);let{flopay:Ct,paypalFlopay:Sn}=await bs(Ae,{billingApiUrl:E,locale:s,telemetry:a}).catch(d=>{throw Ol(d,F||Ae.data.session?.id)});return x(Ct,Sn),Se(!1),Z}catch(Z){throw br.current===We&&(br.current=null),Z}finally{k||B()}},[q,x,s,E,a]),Dr=Nt(Br);Dr.current=Br;let or=Nt(_n);or.current=_n;let At=Nn(async w=>{if(!oy(w)||Me)return{sessionId:we,session:_};it(!0);try{let k=await _n(w);return{sessionId:k.sid,session:k.result.data.session??null}}finally{it(!1)}},[_n,Me,we,_]),Kn=Nn(async w=>{let k=vn.current;if(!k)return;let j=jt.current,te=await k(w);jt.current===j&&($e(te),te.data.session&&Ce(te.data.session))},[]),Gn=Nn(async()=>{await Kt.current},[]),er=Nn(async()=>(await Gn(),{proceed:!0}),[Gn]);hr(()=>{let w=!1,k,j=++ce.current;$t(),z(null),Wn(0);let te=()=>{w=!0,ce.current===j&&(ce.current+=1,$t())},We=Fr.current;if(Sr&&We)return zt(Fn),Se(!1),br.current===Sr?te:(Ce(Fl(We,O)),(async()=>{let W=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=Fn==="auto"&&!xn.current&&!W;B&&(Qt(null),Vt(null),yt("processing"));let Z=!1;try{let F=await or.current(void 0,Re=>{k=Re});Z=!0;let Ae=F.result.data.session??null;nn.current=Zi(F.result);let D=Cs(F.result),Ie=Yi(F.sid||Ae?.id);if(!w&&B&&Ae&&!D&&!Ie){xn.current=!0,await Zp(Sr,F.sdkGeneratedIdempotencyKey,()=>Dr.current(Ae,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:F.result.autoProcessingError,initialAutoProcessingPending:F.result.autoProcessingPending,autoProcessingAttempted:F.result.autoProcessingAttempted,sessionId:F.sid||Ae.id}));return}!w&&B&&((D||Ie)&&(xn.current=!0),yt(null),Vt(null))}catch(F){if(w)return;let Ae=$a(F);if(B&&Ae==="session_auto_completed"){xn.current=!0,yt("success"),await ba(600),w||(Tt(()=>{yn.current?.({status:"succeeded"})}),yt(null),Vt(null));return}if(B&&(yt(null),Vt(null)),!Z){let Ie=Nl(F),Re=jc(F,Ie?{stage:"provider_load",provider:"stripe",...Ie}:{stage:"session_request"});(Ie||!(F instanceof Mn))&&Tt(()=>qn.current?.(Re)),z(Re);return}let D=F instanceof Mn?F:new Mn(F instanceof Error?F.message:"Failed to create session","api_error");z(D)}finally{k?.(),k=void 0}})(),()=>{te(),k?.()});Se(!0);async function Wt(){let W=!1,B=!1,Z=null;try{let F=new yi(E,{telemetry:!1}),Ae=await F.getUnifiedCheckoutSession(p,t);if(B=!0,Z=Ae,w)return;$e(Ae);let D=Ae.data.session??null;if(Ce(D),!D)throw new Mn("No session data returned","api_error");let Ie=D.checkoutMode;if(Ie==="setup")throw new Mn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(D.status==="authorized"){Se(!1),Tt(()=>{yn.current?.(Lr(D,p)),rn.current?.(D.successUrl??"")});return}if(D.status==="complete"){Se(!1),Tt(()=>{rn.current?.(D.successUrl??"")});return}if(D.status==="expired")throw ja(D);W=!0;let Re=O??Ie??"full";zt(Re),jt.current+=1;let Ct=D.clientSecret||t;vn.current=D.buyerIdentified===!1&&Ct?Io(F,p,Ct,{...D.customer?.id?{userId:D.customer.id}:{}}):void 0,qt(!1),pn(!1);let Sn=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),d=Cs(Ae);if(Re==="auto"&&!xn.current&&!Sn&&!d){xn.current=!0;let c=ne(Ae);try{if(await Dr.current(D,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>c,sessionId:p||D.id}),w)return;await c,w||Se(!1);return}catch{if(w)return;await c,w||Se(!1);return}}await ne(Ae),w||Se(!1)}catch(F){if(w)return;let Ae=xl(F,W);if(W&&et({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),Ae){let{errorCode:Ct,stage:Sn,...d}=Ae;vs(E,a,G,Ct,Sn,d)}if(Ae?.stage==="provider_load"&&(O??Z?.data.session?.checkoutMode??"full")==="full"&&Al(Z,K,g)){let Ct=ey({billingApiUrl:E,locale:s,telemetry:a});Pt.current=Ct,x(Ct,null),Wn(1),Se(!1);return}let D=Ae?.stage==="provider_load",Ie="session_request";D?Ie="provider_load":B&&(Ie="post_session");let Re=jc(F,{stage:Ie,provider:"stripe",sessionId:p||void 0});(D||!(F instanceof Mn))&&Tt(()=>qn.current?.(Re)),z(Re),Se(!1)}}async function ne(W){let{flopay:B,paypalFlopay:Z,...F}=await bs(W,{billingApiUrl:E,locale:s,telemetry:a});nn.current={publishableKey:F.publishableKey,paypalPublishableKey:F.paypalPublishableKey},x(B,Z),Wn(0)}return Wt(),te},[O,Sr,Fn,Oe,t,K,g]);let Yn=Nn(async()=>{if(!Pe||Pn!==1)return;let w=ce.current;Wn(2);try{let{flopay:k,paypalFlopay:j}=await bs(Pe,{billingApiUrl:E,locale:s,telemetry:a});if(ce.current!==w)return;$t(),x(k,j),Wn(0)}catch(k){if(ce.current!==w)return;let{errorCode:j,stage:te,...We}=qi(k);vs(E,a,G,j,te,We)}},[$t,x,s,Pn,E,a,G,Pe]),Ue=!!(p&&(_?.clientSecret||t)),ln=pt||!Ue,on=Nn(async()=>{if(!(pt||!Ue||!_)){Ln(!0),Qt(null);try{await Br(_,{attempt3DS:!0,fallbackToFull:!0,sessionId:p||_.id})}finally{Ln(!1)}}},[p,pt,Ue,Br,_]),jn=Jc(Pe?.data.paypal,_e),Qr=Cs(Pe),Or=cr(()=>{if(!(!Pe||!_||!Pe.data.stripe?.publishableKey))return{billingApiUrl:E}},[Pe,_,E]),dr=!!(n&&!se&&Ne==="buttons"&&at&&Fn==="full"),tr=!!(p&&(Kp(_?.vault)||oo(_))),bn=cr(()=>({session:_,loading:he,error:J,checkoutMode:Zt,inlineSessionDraft:Gt,applyInlineSessionPatch:dr?At:void 0,inlineSessionPatchProcessing:Me,claimPending:Rn,claimRequiresIdentity:en,claimBuyerIdentity:Kn,waitForDataAttachment:Gn}),[_,he,J,Zt,Gt,dr,At,Me,Rn,en,Kn,Gn]),Nr=!!n&&Ne==="buttons"&&!Qr&&!tr&&(!He||!Or),Dn=Vn?ye(Rr,{status:Vn,errorMessage:Pr,authorized:rr}):null;if(he&&!tr){if(l)return hn(Ar,{children:[l,Dn]});if(Ne==="buttons"){let w=De?.buttonsLayout?.cardButton?.borderRadius??De?.appearance.variables?.borderRadius??8,k=j=>ye("div",{style:{height:j,borderRadius:w,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return hn(Ar,{children:[hn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[K&&k(zo),g&&(R||Xe)&&k(zo),g&&k(zo),ye("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Dn]})}return hn(Ar,{children:[hn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ye("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ye("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Dn]})}return J?m?ye(mr.Provider,{value:bn,children:m(J)}):ye(mr.Provider,{value:bn,children:ye("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:J.message})}):Nr?hn(Ar,{children:[ye(mr.Provider,{value:bn,children:ye(iy,{onButtonClick:ut,showPayPal:K,showStripe:g,showApplePay:R,showGooglePay:Xe,theme:ot,buttonsTheme:ze,buttonsStyles:qe,cardButtonContent:It,cardBackButtonContent:st,cardTitleContent:ee})}),Dn]}):Qr&&_&&jn?hn(Ar,{children:[ye(mr.Provider,{value:bn,children:hn("div",{className:Ze,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[An&&ye(xo,{icon:!1,children:An}),ke==="retrying"&&ye("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),ke==="exhausted"&&hn("div",{role:"alert",children:[ye("div",{children:"PayPal is temporarily unavailable. Please try again."}),ye("button",{type:"button",onClick:Lt,children:"Retry PayPal"})]}),ke!=="exhausted"&&ye("div",{"aria-hidden":ke==="retrying"?!0:void 0,style:ke==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ye(rc,{sessionId:p,nonce:_.clientSecret||void 0,billingApiUrl:E,email:_.customer?.email||Gt?.account?.email,billingName:[_.customer?.firstName,_.customer?.lastName].filter(Boolean).join(" ")||[Gt?.account?.firstName,Gt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Kn,clientId:jn.clientId,environment:jn.environment,currency:(_.currency??"usd").toUpperCase(),isSubscription:_.mode==="subscription",providerObjectType:jn.providerObjectType,approvalPresentation:jn.approvalPresentation,existingOrderId:jn.existingOrderId,onComplete:C,onErrorChange:Qt,onDecline:N,onCancel:ue,onButtonClick:ut,runBeforeButtonClick:er,onInitializationStateChange:X,allowAutomaticRetry:Cn===0,session:_,telemetry:a,telemetryContext:G,onInstrument:be,debug:H},`${de}:paypal-init-${Cn}`)})]})}),Dn]}):Zt==="confirm"?hn(Ar,{children:[ye(mr.Provider,{value:bn,children:ye(ti,{flopay:He,paypalFlopay:h,options:Or??{billingApiUrl:E},onInstrument:be,children:hn("div",{className:Ze,children:[An&&ye("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:An}),Le?Le({onConfirm:on,isProcessing:ln}):ye("button",{type:"button",onClick:on,disabled:ln,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:ln?"not-allowed":"pointer",opacity:ln?.6:1},children:pt?"Processing...":je??"Confirm Purchase"})]})},de)}),Dn]}):(!He||!Or)&&!(tr&&Zt==="full")?ye(Ar,{children:Dn}):hn(Ar,{children:[ye(mr.Provider,{value:bn,children:hn(ti,{flopay:He,paypalFlopay:h,options:Or??{billingApiUrl:E},onInstrument:be,children:[Pn===1&&ye("button",{type:"button",onClick:Yn,children:"Retry payment methods"}),se?hn(Ar,{children:[An&&ye("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:An}),ye(ay,{sessionId:p,nonce:_?.clientSecret||void 0,billingApiUrl:E,session:_,submitLabel:Ft,walletPresentation:S,children:se})]}):ye(hs,{sessionId:p,nonce:_?.clientSecret||void 0,telemetry:a,email:_?.customer?.email||Gt?.account?.email,userId:_?.customer?.id||Gt?.account?.userId,firstName:_?.customer?.firstName||Gt?.account?.firstName,lastName:_?.customer?.lastName||Gt?.account?.lastName,totalAmount:_?Math.round(Vp(_).total*100):0,currency:_?.currency?.toLowerCase()??"usd",onComplete:C,onError:T,onDecline:N,onCancel:ue,error:An,onErrorChange:Qt,showPayPal:K,showStripe:g,walletPresentation:S,enabledPaymentMethods:Pn?[]:Ve??Pe?.data.stripe?.enabledPaymentMethods??_?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Pe?.data.stripe?.enabledPaymentMethodCountries,showApplePay:R,showGooglePay:Xe,layout:Ne,theme:ot,buttonsTheme:ze,buttonsStyles:qe,appearance:gt,cardButtonContent:It,cardBackButtonContent:st,cardTitleContent:ee,onButtonClick:ut,onBeforeButtonClick:at,onBuyerIdentityReady:Kn,enableAVS:fe,...ie?{cardFieldOrder:ie}:{},...pe?{cardPreFormSlot:pe}:{},avsLayout:ft,country:_?.customer?.country,city:_?.customer?.city,state:_?.customer?.state,onCountryChange:L,onZipChange:Be,avsCheck:!!fe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ws(se,Ne),className:Ze,submitLabel:Ft,directPaypal:jn,isSubscription:_?.mode==="subscription",session:_,dataAttachmentPending:Rn,dataAttachmentRequiresIdentity:en,debug:H})]},de)}),Dn]})}function ay({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,children:s}){return ye(Ar,{children:Ps.Children.map(s,l=>{if(!Ps.isValidElement(l))return l;let m=l.props,C={};return m.sessionId||(C.sessionId=e),!m.nonce&&t&&(C.nonce=t),m.billingApiUrl||(C.billingApiUrl=n),m.submitLabel===void 0&&a!==void 0&&(C.submitLabel=a),m.walletPresentation===void 0&&(C.walletPresentation=i),o?.customer&&(m.email||(C.email=o.customer.email),m.userId||(C.userId=o.customer.id),m.firstName||(C.firstName=o.customer.firstName),m.lastName||(C.lastName=o.customer.lastName)),Object.keys(C).length===0?l:Ps.cloneElement(l,C)})})}function iy({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:o,showGooglePay:a,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:m,cardBackButtonContent:C,cardTitleContent:T}){let[I,N]=Xt(!1),ue=cr(()=>Xc(i),[i]),L=cr(()=>{let S=ue?.buttonsLayout??Yp(s);return l?{...S,...l,cardButton:{...S.cardButton,...l.cardButton},cardFormContainer:{...S.cardFormContainer,...l.cardFormContainer},backButton:{...S.backButton,...l.backButton},backButtonIcon:{...S.backButtonIcon,...l.backButtonIcon},submitButton:{...S.submitButton,...l.submitButton},title:{...S.title,...l.title}}:S},[ue,s,l]),Be=ue?.buttonsLayout?.cardButton?.borderRadius??ue?.appearance.variables?.borderRadius??8,K=S=>ye("div",{style:{height:S,borderRadius:Be,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),g=m===void 0?{boxSizing:"border-box",height:zo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(I){let S=L.cardInputBorder??"#e5e7eb",Ve=L.cardInputBackground??"white",R=bo(C),Xe=bo(T);return hn("div",{style:{backgroundColor:L.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...L.cardFormContainer},children:[hn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[hn("button",{type:"button",onClick:()=>N(!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",...L.backButton},children:[ye("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...L.backButtonIcon},children:ye("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:ye("path",{d:"M15 18l-6-6 6-6"})})}),ye(wo,{content:C})]}),Xe?ye("div",{style:{flex:1}}):ye("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...L.title},children:ye(aa,{content:T})})]}),ye("div",{style:{backgroundColor:Ve,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ye("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),hn("div",{style:{display:"flex"},children:[ye("div",{style:{flex:1,backgroundColor:Ve,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:ye("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ye("div",{style:{flex:1,backgroundColor:Ve,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:ye("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ye("div",{style:{backgroundColor:Ve,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ye("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ye("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...L.submitButton,opacity:.5}}),ye("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 hn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&K(zo),n&&(o||a)&&K(zo),n&&ye("button",{type:"button",onClick:()=>{e?.("card"),N(!0)},style:{width:"100%",...g,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:L.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,...L.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:ye(So,{content:m})}),ye("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as fy,jsx as co,jsxs as gy}from"react/jsx-runtime";var dy=44;function Qc(e){return new Promise(t=>setTimeout(t,e))}function uy(e,t){return e instanceof ka?e:new ka(e instanceof Error?e.message:t,"api_error")}function py(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function yy(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 my({sessionId:e,nonce:t,createSession:n,paymentMethodId:o,checkoutMethod:a,clientId:i,products:s,items:l,subscriptions:m,account:C,successUrl:T,cancelUrl:I,couponCodes:N,tagsData:ue,utmMetadata:L,billingApiUrl:Be,locale:K,theme:g,appearance:S,buttonsTheme:Ve,buttonsStyles:R,onSuccess:Xe,onError:H,onDecline:Ne,children:ot,disabled:ze=!1,type:qe="button",style:It,...st}){let ee=wa(()=>sy(Be),[Be]),Bt=wa(()=>yy({createSession:n,clientId:i,products:s,items:l,subscriptions:m,account:C,successUrl:T,cancelUrl:I,couponCodes:N,tagsData:ue,utmMetadata:L}),[C,I,i,N,n,s,l,m,T,ue,L]),[ut,at]=$o(!1),[fe,ie]=$o(null),[pe,ft]=$o(null),[Ft,Ze]=$o(!1),[Y,_e]=$o(null),[se,O]=$o(null),je=jo(!0),Le=jo(null),Fe=jo(se),E=jo(Xe),De=jo(H),gt=jo(Ne),Ee=jr(f=>ni(Le,async P=>{try{return await f(P)}catch(ge){throw P.aborted?Fo(ge):ge}}),[]);qo(()=>{Fe.current=se},[se]),qo(()=>{E.current=Xe},[Xe]),qo(()=>{De.current=H},[H]),qo(()=>{gt.current=Ne},[Ne]),qo(()=>(je.current=!0,()=>{je.current=!1,Le.current?.abort()}),[]),qo(()=>{if(typeof window>"u")return;let f=P=>{P.key==="Escape"&&O(null)};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[]);let ht=jr((f,P=fa)=>{gt.current?.(fn(P,f,{code:f.code,declineCode:f.declineCode}))},[]),Pe=jr(async f=>{je.current&&(ft(null),Ze(f.result.status==="authorized"),ie("success"),await Qc(600),je.current&&Tt(()=>E.current?.(f)))},[]),$e=jr(async(f,P)=>{je.current&&(De.current?.(f),P?.emitDecline&&ht(f,P.method),ft(f.message),Ze(!1),ie("error"),await Qc(400))},[ht]),He=jr(async(f,P,ge)=>{let ve=f.data.session??null;if(!ve)throw Hr(new ka("No session data returned","api_error"),P);let et=ve.clientSecret||t;if(Ur(ve)){await Pe({result:Lr(ve,P),session:ve,sessionId:ve.id||P,autoCompleted:!1});return}if(ve.status==="expired")throw Hr(ja(ve),ve.id||P);try{if(f.autoProcessingPending){let be=f.autoProcessingPending,we=new _s(ee),Ot=await Ee(he=>we.waitForCheckoutSessionCompletion(be.sessionId,{initialDelayMs:be.retryAfterMs,nonce:et,statusUrl:be.statusUrl,signal:he})),p=Kr(Ot,ve),Oe=Ot.autoProcessingError?.type==="3ds_required"&&Ot.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ot.autoProcessingError.nextActionRedirectUrl}:null;if(Oe&&P&&et){let he=await Ee(Se=>Do(Oe,{billingApiUrl:ee,sessionId:P,nonce:et,session:ve,signal:Se,telemetry:!0}));await Pe({result:he,session:ve,sessionId:ve.id||P,autoCompleted:!1});return}if(Ot.autoProcessingError)throw Er(Ot.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Ot.autoProcessingError.checkoutMethod});if(!Ur(p))throw Ro(p);await Pe({result:Lr(p,P),session:p,sessionId:p.id||P,autoCompleted:!1});return}if(f.autoProcessingError){let be=f.autoProcessingError.nextActionRedirectUrl;if(f.autoProcessingError.type==="3ds_required"&&be&&P&&et){let we=await Ee(he=>fc({billingApiUrl:ee,sessionId:P,nonce:et,nextActionRedirectUrl:be,signal:he}));if(we.status==="declined")throw Er({type:we.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:we.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:f.autoProcessingError.checkoutMethod});let p=await new _s(ee).waitForCheckoutSessionCompletion(P,{initialDelayMs:0,nonce:et}),Oe=Kr(p,ve);if(!Ur(Oe))throw Er({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:f.autoProcessingError.checkoutMethod});await Pe({result:Lr(Oe,P),session:Oe,sessionId:Oe.id||P,autoCompleted:!1});return}throw Er(f.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.autoProcessingError.checkoutMethod})}if(ge?.fromCreateSession&&f.autoProcessingAttempted===!0)throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ke=await Oo({billingApiUrl:ee,sessionId:P??ve.id,session:ve,nonce:et});if(Ke.type==="next_action_required"&&et){let be=P??ve.id,we=await Ee(Ot=>Do(Ke,{billingApiUrl:ee,sessionId:be,nonce:et,session:ve,signal:Ot,telemetry:!0}));await Pe({result:we,session:ve,sessionId:ve.id||be,autoCompleted:!1});return}if(Ke.type!=="success")throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Pe({result:Ke.result,session:ve,sessionId:ve.id||P,autoCompleted:!1})}catch(Ke){let be=ve.id||P,we=Hr(ga(Ke),be);if(we.code==="three_ds_aborted")return;if(we.code==="checkout_processing_timeout"){if(!je.current)return;_e(we.message),Tt(()=>De.current?.(we));return}await $e(we,{emitDecline:!0,method:we.checkoutMethod??fa}),py(we,be)&&be&&je.current&&O({sessionId:be,errorMessage:we.message,nonce:et||void 0,payPalOrderId:we.orderId})}},[t,ee,Ee,$e,Pe]),In=jr(async f=>{if(st.onClick?.(f),!(f.defaultPrevented||ze||ut)){if(O(null),_e(null),e&&Bt){let P=new ka("Provide either sessionId or create-session props, not both.","validation_error");await $e(P),je.current&&(ie(null),ft(null));return}if(!e&&!Bt){let P=new ka("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $e(P),je.current&&(ie(null),ft(null));return}at(!0),ft(null),Ze(!1),ie("processing");try{let P=new _s(ee);if(e){let ge=await P.getUnifiedCheckoutSession(e,t);await He(ge,e);return}try{let ge=await P.createAndFetchSession({...Bt});await He(ge,ge.data.session?.id??null,{fromCreateSession:!0})}catch(ge){if($a(ge)==="session_auto_completed"){await Pe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ge}}catch(P){await $e(Hr(uy(P,"Automatic payment failed. Please try again."),e))}finally{je.current&&(ie(null),ft(null),at(!1))}}},[st.onClick,Bt,ze,ut,t,He,ee,e,$e,Pe]),_t=jr(f=>{let P=Fe.current;O(null),E.current?.({result:f,session:null,sessionId:P?.sessionId??null,autoCompleted:!1})},[]),Pt=jr(f=>{De.current?.(f)},[]),ce=jr(f=>{gt.current?.(f)},[]),h=wa(()=>cy(g),[g]),lt=wa(()=>{let f=h?.buttonsLayout??ly(Ve);return R?{...f,...R,cardButton:{...f.cardButton,...R.cardButton}}:f},[h,Ve,R]),Qe=wa(()=>{let f=h?.appearance;return S?f?{...f,...S,variables:{...f.variables,...S.variables}}:S:f},[S,h]),_=Qe?.variables,Ce=_?.colorPrimary??"#4A49FF",Dt=_?.colorPrimaryHover??zc(Ce,.12),de=_?.borderRadius??"8px";return gy(fy,{children:[co("button",{...st,type:qe,onClick:In,disabled:ze||ut,"aria-busy":ut,style:{width:"100%",...ot===void 0?{boxSizing:"border-box",height:dy,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...lt.cardButton,...gs({themeBundle:h,resolvedPrimaryColor:Ce,resolvedBorderRadius:de,submitButtonStyle:lt.submitButton,explicitPrimaryColor:_?.colorPrimary}),fontSize:lt.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:f=>{st.onMouseEnter?.(f),!f.defaultPrevented&&!ze&&!ut&&(h||_?.colorPrimary)&&(f.currentTarget.style.backgroundColor=Dt)},onMouseLeave:f=>{st.onMouseLeave?.(f),!f.defaultPrevented&&(h||_?.colorPrimary)&&(f.currentTarget.style.backgroundColor=Ce)},onMouseDown:f=>{st.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{st.onMouseUp?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(1)")},children:co(So,{content:ot})}),Y&&co("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Y}),fe&&co(Rr,{status:fe,errorMessage:pe,authorized:Ft}),se&&co("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:f=>{f.target===f.currentTarget&&O(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:co("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:co(Rs,{sessionId:se.sessionId,nonce:se.nonce,checkoutMode:"full",billingApiUrl:ee,locale:K,theme:g,...Qe?{appearance:Qe}:{},buttonsTheme:Ve,buttonsStyles:R,initialErrorMessage:se.errorMessage,initialPayPalOrderId:se.payPalOrderId,cardTitleContent:null,onComplete:_t,onError:Pt,onDecline:ce})})})]})}import{jsx as vy}from"react/jsx-runtime";var hy={StripeSetupMethod:El,PayPalSetupMethod:_l};function Py(e){return vy(Tl,{...e,branches:hy})}export{Xa as DirectPayPalButton,my as FloPayAutomaticPaymentButton,vd as FloPayCardSetup,Pd as FloPayCardSetupError,Rs as FloPayCheckout,Py as FloPayPaymentMethodSetup,ti as FloPayProvider,hs as SplitCardForm,Di as VaultCardFields,Yf as dropThirdPartyOnlyError,zd as useCheckout,Gr as useFloPay,Vi as usePayPalFloPay};