@flopay/react 1.18.1 → 1.19.0

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 ic}from"./chunk-D4CVZRT4.mjs";import{c as Lt,d as Dr,e as va,f as ds,g as us,h as hu,j as Pu}from"./chunk-YR36EYW2.mjs";import{a as oc}from"./chunk-BU7THP6H.mjs";import{a as ho,b as si,c as ms,d as fs,e as ba,f as Ql,g as ec,h as tc,i as nc,j as rc,k as ac}from"./chunk-FGCZOMML.mjs";import{a as oi,b as ps,c as Yl,d as ys,e as qo,f as Jl,g as no,h as ai,i as Xl,j as Ca,k as ii,l as Zl}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as $h}from"@flopay/shared";import{PaymentAPI as rl}from"@flopay/js";import{FloPayError as Ro,isDeclineCallbackFailure as Om,isMerchantAuthRequired as Kd,resolveBillingApiUrl as Lm,resolveButtonsLayoutTheme as Nm,resolveTheme as Um}from"@flopay/shared";import{useCallback as Ur,useEffect as ia,useMemo as Wa,useRef as uo,useState as sa}from"react";import{Fragment as Ho,jsx as pr,jsxs as sc}from"react/jsx-runtime";function vu(){return sc(Ho,{children:[sc("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:[pr("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),pr("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",pr("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:pr("path",{d:"M9 18l6-6-6-6"})})]})}function Cu(){return pr(Ho,{children:"Go back"})}function bu(){return pr(Ho,{children:"Secure card checkout"})}function jo(e){return e!==void 0&&(e===""||e===null||e===!1)}function $o({content:e}){return pr(Ho,{children:e===void 0?pr(vu,{}):e})}function Wo({content:e}){return pr(Ho,{children:e===void 0?pr(Cu,{}):e})}function Sa({content:e}){return pr(Ho,{children:e===void 0?pr(bu,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as Su,canRecoverHostedCardForm as wu,classifyTelemetryFailure as ku,FloPayError as Vn,isCardHolderNamePlaceholder as Ru,isMoneySettledOutcome as Iu,isMountableVaultBlock as Eu,isSetupIntentClientSecret as _u,isValidEmail as Tu,resolveSetupFutureUsage as Mu,resolveWalletModeOptions as Au}from"@flopay/shared";import{canRecoverHostedCardForm as Po,hasServerSideCardGateway as vc}from"@flopay/shared";import{splitFullName as Ra}from"@flopay/shared";import{applyFriendlyMessageOverride as Go}from"@flopay/shared";function gs(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Vn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function xu(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 lc(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(Eu(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||wu(o))||t&&e?.data.paypal?.publishableKey)}function cc(e,t){if(t&&(!(e instanceof Vn)||e.type==="authentication_error"))return gs(e);if(!(e instanceof Vn&&xu(e))){if(!t&&!(e instanceof Vn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...ku(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Vn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Vn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Ko(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()},d=Ru(s.firstName,s.lastName);if(!Tu(s.email))return Promise.reject(new Vn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let g={};for(let[w,v]of Object.entries(s)){if(d&&w.endsWith("Name")||typeof v!="string")continue;let h=v.trim();h&&(g[w]=h)}return a=e.claimCheckoutSession(t,n,{accountData:g}),a.catch(()=>{}),a}}function dc(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 hs(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 uc(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 Ps(e,t){return t?{...e,...t}:e}function Cn(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 pc=new WeakMap;function yc(e,t){return typeof e=="object"&&e!==null&&pc.set(e,t?{sessionId:t}:{}),e}function mc(e){return typeof e=="object"&&e!==null?pc.get(e):void 0}function ro(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Wr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Hr(e){return e?.status==="authorized"||e?.status==="complete"}function oo(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 fc(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function li(e){let t=fc(e);return new Vn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ci(e){return e instanceof Vn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Vo(e){return fc(e)?new Vn("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Vn("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Vn(Su,"api_error",{code:"checkout_processing_timeout"})}function wa(e,t){return e==="processing"||Iu(e,t)}function gc(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function hc(e,t){let n=e;if(_u(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new Vn(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 Vn(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var Fu=["apple_pay","google_pay"];function Pc(e,t="automatic",n){let o=Mu(n,Fu,"wallet");return{...Au(e,t),allowedPaymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Bu=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function vs(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:Bu.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function ka(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as fm,PaymentAPI as xi,SESSION_CREATE_TELEMETRY as gm}from"@flopay/js";import{buildCheckoutDisplayData as hm,classifyTelemetryFailure as jd,DEFAULT_PAYMENT_METHOD_ORDER as Pm,FloPayError as Tn,isDeclineCallbackFailure as xd,isDetachedSessionEligible as vm,isExpectedPaymentDecline as Fd,isMerchantAuthRequired as Cm,isMountableVaultBlock as bm,resolveBillingApiUrl as Sm,resolveButtonsLayoutTheme as wm,resolveDirectPaypalConfig as $d,resolveIdempotencyKey as Bd,resolveCheckoutLogLayout as km,resolveTheme as Wd,SDK_VERSION as Hd,telemetryStatusClass as Rm,toPublicCheckoutInitError as Dd}from"@flopay/shared";import Bi,{useCallback as On,useEffect as _r,useMemo as fr,useRef as jt,useState as Zt}from"react";import{createContext as Cc}from"react";var yr=Cc({flopay:null,paypalFlopay:null,billingApiUrl:""}),kr=Cc({session:null,loading:!1,error:null});import{PaymentAPI as bs}from"@flopay/js";import{buildPayPalCancelEvent as Yu,buildPayPalProcessPaymentRequest as Ju,buildPayPalSessionIntentRequest as Xu,buildPayPalTokenizedBody as Zu,classifyTelemetryFailure as Qu,describePayPalProcessFailure as _c,FloPayError as Zo,friendlyPayPalFailureMessage as ep,generateIdempotencyKey as tp,isPayPalTeardownMessage as np,isSettledSessionIntent as rp,isValidEmail as Tc,mergePayPalPayerIdentity as op,needsPayPalPayerDetails as ap,normalizeGatewayEnvironment as ip,paypalProviderIdentityRequired as Mc,resolvePayPalApprovalIdentity as sp,resolvePayPalDeclineReason as lp,SDK_VERSION as cp,usesPayPalVaultedChannel as dp}from"@flopay/shared";import{loadScript as up}from"@paypal/paypal-js";import{useCallback as mr,useContext as pp,useEffect as Wt,useMemo as Ta,useRef as it,useState as Kr}from"react";import{compactBuyerIdentity as Du,isValidEmail as Ou}from"@flopay/shared";import{useCallback as bc,useEffect as Lu,useRef as Sc,useState as kc}from"react";import{compactBuyerIdentity as Rr}from"@flopay/shared";import{jsx as wc,jsxs as Ia}from"react/jsx-runtime";function Yo(){let[e,t]=kc(null),n=Sc(null),o=Sc(0),a=bc((s,d)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:d}),new Promise(g=>{n.current=g})),[]),i=bc(s=>{let d=n.current;n.current=null,t(null),d?.(s)},[]);return Lu(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function Jo({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,d]=kc(e.email?.trim()??""),g=Ou(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",wc("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:w=>d(w.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&&wc("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),Ia("button",{type:"button",disabled:!g||a,onClick:()=>{n(Du({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as Nu}from"@flopay/shared";import{useContext as di}from"react";function ao(){return di(yr).flopay}function Cs(){return di(yr).paypalFlopay??null}function Uu(){return di(kr)}function Rc(){return di(yr).billingApiUrl||Nu()}import{FLO_INSTRUMENT_ONCE_NAMES as zu,invokeMerchantCallback as qu,projectFloInstrument as ju}from"@flopay/shared";import{useCallback as $u,useRef as ui}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Ic}from"@flopay/shared";function Xo(e,t){let n=ui(e);n.current=e;let o=ui(new Set),a=ui(t),i=ui(t);return va(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),$u(s=>{if(i.current!==t)return;let d=ju(s);if(d){if(zu.has(d.name)){if(o.current.has(d.name))return;o.current.add(d.name)}qu(()=>n.current?.(d))}},[t])}import{createContext as Wu}from"react";var Ea=Wu(null);function pi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var yi="provider.callback.ignored";function mi(){let e,t=0;return{take(n){return n!==e&&(e=n,t=0),t>=5?!1:(t+=1,!0)}}}var Hu=Symbol.for("@flopay/js.telemetry.bridge.v1"),Ku=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Vu(){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 Gu(e){let t=Vu(),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 fi(e){let t=globalThis[Ku];return Gu(t?.(e)??{})}function bn(e){if(e)return e[Hu]}import{useCallback as io,useEffect as Ec,useRef as vo}from"react";function _a(e,t){let n=vo(0),o=vo(null),a=vo(null),i=vo(e),s=vo(t?.onHandoffObserved),d=vo(t?.defersMissingTerminal),g=vo(t?.onMissingTerminalDeferred);Ec(()=>{i.current=e,s.current=t?.onHandoffObserved,d.current=t?.defersMissingTerminal,g.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let w=io((C=a.current)=>{C?.timer&&(clearTimeout(C.timer),C.timer=null)},[]),v=io(C=>{w();let me=n.current+1;return n.current=me,o.current=null,a.current={generation:me,method:C,timer:null,yieldedControl:!1},me},[w]),h=io(C=>{let me=a.current;return C!==void 0&&me?.generation!==C?!1:(w(me),a.current=null,(C===void 0||o.current===C)&&(o.current=null),!0)},[w]),T=io(C=>{let me=a.current,de=C??me?.generation??n.current;(C===void 0||me?.generation===C)&&(w(me),a.current=null),o.current=de},[w]),ie=io(C=>o.current===(C??n.current),[]),ce=io(C=>a.current?.generation===C&&o.current!==C,[]),x=io(()=>{let C=a.current;C&&(w(C),!C.yieldedControl&&(C.yieldedControl=!0,s.current?.(C.method)))},[w]),U=io(()=>{let C=a.current;!C?.yieldedControl||document.visibilityState!=="visible"||(w(C),C.timer=setTimeout(()=>{if(C.timer=null,a.current?.generation===C.generation){if(d.current?.(C.method)){g.current?.(C.method,C.generation);return}a.current=null,o.current=C.generation,i.current(C.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},Yl))},[w]);return Ec(()=>{let C=()=>{document.visibilityState==="visible"?U():x()};return document.addEventListener("visibilitychange",C),window.addEventListener("blur",x),window.addEventListener("focus",U),()=>{document.removeEventListener("visibilitychange",C),window.removeEventListener("blur",x),window.removeEventListener("focus",U),w()}},[w,x,U]),{startAttempt:v,finishAttempt:h,invalidateAttempt:T,isAttemptInvalidated:ie,isAttemptCurrent:ce,generationRef:n}}import{jsx as Co,jsxs as Ss}from"react/jsx-runtime";var gi=45,yp=1e3,mp=11e3,Ac="paypal_intent_settled",fp={width:"100%",minHeight:gi,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"},gp={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 hp(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:gp[e.kind]??null}}function xc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Jl(t)?"paypal_init_timeout":"paypal_init_failure"}function Pp(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Fc({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:d,currency:g,isSubscription:w,providerObjectType:v,approvalPresentation:h,onTokenizedBody:T,onComplete:ie,onErrorChange:ce,onDecline:x,onCancel:U,onTechnicalFailure:C,isProcessing:me=!1,onLoadStateChange:de,onInitializationStateChange:S,allowAutomaticRetry:Ye=!0,onButtonClick:$,runBeforeButtonClick:Oe,session:st,existingOrderId:yt,telemetry:we,telemetryContext:zt,onInstrument:Nt,debug:be=!1}){let tt=ao(),lt=Xo(Nt,e),ct=Ta(()=>{if(tt)return null;let u=fi({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:cp,enabled:we!==!1});return u.setCheckoutContext(zt??{}),u.beginCheckout(zt??{}),u},[n,tt,we,zt?.checkoutMode,zt?.layout]),ke=Ta(()=>bn(tt),[tt]);Wt(()=>()=>{ct&&ct.flush().catch(()=>{}).finally(()=>ct.destroy())},[ct]);let Z=Ta(()=>({error:u=>{ke?ke.error(u):ct?.error(u),lt({class:"technical_error",errorCode:u.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":u.errorCode,requestCategory:u.requestCategory,provider:u.provider})},log:u=>{ke?ke.log(u):ct?.log(u),lt({class:"lifecycle",name:u.name,provider:u.provider})},performance:u=>{ke?ke.performance(u):ct?.performance(u)},terminal:u=>{ke?ke.terminal(u):ct?.terminal(u)},startTiming:()=>ke?.now()??ct?.now()??0,elapsed:u=>ke?.elapsed(u)??Math.max(0,(ct?.now()??u)-u)}),[lt,ke,ct]),ue=it(null),Ht=it(0),je=it(null),dt=it(null),Q=it(null),_e=pp(Ea),rt=it(null);rt.current||(rt.current=pi());let z=_e??rt.current,Mt=it(null),ve=it(!1),[Je,xe]=Kr(!1),[We,At]=Kr(!1),[fe,Le]=Kr(0),ot=it(0),[nt,Rt]=Kr(!1),H=it(!1),St=it(!1),[Kt,Pe]=Kr(!1),[Ce,Fe]=Kr(!1),{request:ut,collect:Xe,finish:ft}=Yo(),xt=it({sessionId:e,required:Mc(o,st)});xt.current.sessionId!==e&&(xt.current={sessionId:e,required:Mc(o,st)});let $e=xt.current.required,Ze=Ta(()=>n.replace(/\/+$/,""),[n]),Ft=st?.gateways?.paypal?.providerObjectType??v,He=Ft??(w?"subscription":"order"),[W]=Kr(Ca),f=st?.gateways?.paypal?.approvalPresentation??h,O=ii(W,f==="app_switch"?"app_switch":void 0,He),F=dp(Ft),_=Ta(()=>JSON.stringify([Ze,s,g,d??"",He,F,O,e,yt??""]),[Ze,s,g,d,yt,He,F,O,e]),Ke=it(_),y=Ke.current!==_,ge=it(be),G=it(null),[q,X]=Kr([]),k=mr(u=>{ge.current&&X(ht=>[...ht,`${new Date().toISOString().slice(11,23)} ${u}`])},[]);Wt(()=>{ge.current=be,be&&k("debug:enabled"),G.current?.setEnabled(be)},[k,be]);let It=it(T),Ln=it(ie),Qe=it(ce),Qn=it(x),Ve=it(U),mn=it(C),gt=it($),wn=it(de),fn=it(S),Vt=it(i),jn=it(Oe),kn=it(st),Mn=it(o),er=it(a),Rn=it(t),Bt=it(null),gn=it(new Map),mt=it(new Map),et=it(!1),Ne=it(e);Ne.current=e;let[tr]=Kr(mi);Wt(()=>(et.current=!0,()=>{et.current=!1}),[]),Wt(()=>{It.current=T},[T]),Wt(()=>{Vt.current=i},[i]),Wt(()=>{Ln.current=ie},[ie]),Wt(()=>{Qe.current=ce},[ce]),Wt(()=>{Qn.current=x},[x]),Wt(()=>{Ve.current=U},[U]),Wt(()=>{mn.current=C},[C]),Wt(()=>{gt.current=$},[$]),Wt(()=>{wn.current=de},[de]),Wt(()=>{fn.current=S},[S]),Wt(()=>{jn.current=Oe},[Oe]),Wt(()=>{kn.current=st},[st]),Wt(()=>{Mn.current=o},[o]),Wt(()=>{er.current=a},[a]),Wt(()=>{Rn.current=t},[t]),Wt(()=>{ot.current=fe},[fe]),Wt(()=>{nt&&Mt.current?.focus()},[nt,fe]);let ln=mr(()=>{window.setTimeout(()=>{Mt.current?.focus()},0)},[]),An=mr(()=>{xe(!1),Le(u=>u+1)},[]),gr=mr(()=>{Rt(!1),(ue.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ue.current)?.focus?.()},[]);Wt(()=>{!Je||!ve.current||(ve.current=!1,gr())},[gr,Je,fe]);let nr=mr((u,ht)=>{let A=ht?.popupBlocked??no(u);A&&z.markBlocked();let L=oi("PayPal",A,W.inAppBrowser),Et=mn.current;if(Et){let Pt=A&&W.inAppBrowser?new Zo(L,"api_error",{code:ht?.code??"paypal_popup_blocked"}):u;Et("paypal",Pt,ht);return}if(u instanceof Zo&&u.code==="checkout_processing_timeout"){Qe.current?.(u.message);return}Qe.current?.(L)},[z,W.inAppBrowser]),xn=mr(u=>{let ht=je.current,A=dt.current;ht===null||!A||(Z.log({...A,popupCapability:z.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:u}),Z.performance({...A,popupCapability:z.current(),stage:"overlay_return",durationMs:Z.elapsed(ht),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:u}),je.current=null)},[z,Z]),rr=mr((u,ht,A)=>{let L=dt.current;xn("overlay_timeout"),L&&Z.error({...L,popupCapability:z.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),nr(ht,{...A,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:O,terminalReason:"overlay_timeout"}),Rt(!0),An(),ln()},[xn,ln,nr,z,O,An,Z]),or=mr(()=>{z.markAvailable();let u=dt.current;u&&(Q.current=u.attempt,Z.log({...u,popupCapability:z.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[z,Z]),cn=mr(()=>!0,[]),Qt=mr(()=>{let u=dt.current;if(!u)return;let ht=je.current;Z.performance({...u,popupCapability:z.current(),stage:"overlay_return",durationMs:ht===null?0:Z.elapsed(ht),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[z,Z]),{finishAttempt:Gn,generationRef:$n,invalidateAttempt:en,isAttemptCurrent:Yt,isAttemptInvalidated:hn,startAttempt:Fn}=_a(rr,{onHandoffObserved:or,defersMissingTerminal:cn,onMissingTerminalDeferred:Qt}),dn=mr(()=>(Rt(!1),Fn("paypal")),[Fn]),Pn=mr(u=>{en(u?.generation),u?.showRetry&&Rt(!0),u?.remount&&An(),u?.focus!==!1&&ln()},[ln,en,An]),Nn=u=>{let ht=Bt.current;return ht&&mt.current.set(u,ht),u};Wt(()=>{Ke.current!==_&&(Ke.current=_,H.current=!1,St.current=!1,xe(!1),At(!1),Pe(!1),fn.current?.("loading"))},[_]),Wt(()=>{Lt(()=>wn.current?.(Je&&!Kt))},[Je,Kt]);let In=ip(d);Wt(()=>{let u={attempt:$n.current+1,inAppBrowser:W.inAppBrowser,appFamily:W.appFamily,popupCapability:z.current(),presentationMode:O},ht=()=>({...dt.current??u,popupCapability:z.current()}),A={error:p=>Z.error({...p,...ht()}),log:p=>Z.log({...p,...ht()}),performance:p=>Z.performance({...p,...ht()}),terminal:p=>Z.terminal({...p,...ht()}),startTiming:Z.startTiming,elapsed:Z.elapsed},L=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Et=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(k(`mount clientId=${L} env=${d??"(unset)"}\u2192${In??"live"} ccy=${g} sub=${w}`),k(`ua=${Et.slice(0,80)}${Et.length>80?"\u2026":""}`),!s){k("FAIL: clientId empty \u2014 gateway misconfigured"),Pe(!0),A.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!ue.current){k("FAIL: containerRef not attached");return}Ht.current=A.startTiming(),A.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Pt=!1,tn=!1,Ie=()=>Pt||tn,un=p=>{let l=et.current,P=l?p:"torn_down";l&&k(`onError ignored reason=${P}`),tr.take(Ne.current)&&A.log({name:yi,stage:"provider_ready",reason:P,provider:"paypal",paymentMethodCategory:"paypal"})},Ee=()=>Ne.current===e?"stale_attempt":"session_changed",zr=F?He:void 0,Gr,Io=!1,hr=()=>{Gr=tp(),Gr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Io=!0},ar=null,Yn=!1,Wn=null,nn=!1,Pr=()=>{!Wn||nn||(nn=!0,Wn.close().catch(()=>{}))},vn=!1,Tr=!1,Ge=ue.current,Dn=null,vr=null,qr=[],Jn=null,ir=!1,Yr=!1,Jr=null,sr=p=>{if(!p||typeof p.getBoundingClientRect!="function")return"(no rect)";let l=p.getBoundingClientRect();return`${Math.round(l.width)}\xD7${Math.round(l.height)}`},jr=p=>{if(!p)return"(empty)";try{let l=new URL(p,typeof window>"u"?"https://localhost":window.location.href),P=l.pathname.toLowerCase();return P.includes("checkcaptcha")||P.includes("captcha")?`CAPTCHA(${l.host}${P})`:P.includes("risk")||P.includes("challenge")?`RISK(${l.host}${P})`:P.includes("smart/buttons")?`smart-buttons(${l.host})`:`${l.host}${P}`.slice(0,100)}catch{return p.slice(0,80)}},Eo=p=>{let l=p.getAttribute("src"),P=p.getAttribute("srcdoc"),te=p.getAttribute("name"),oe=p.getAttribute("sandbox"),N=[];return l&&N.push(`src=${jr(l)}`),P&&N.push(`srcdoc[${P.length}ch]`),!l&&!P&&N.push("src=(empty) srcdoc=(empty)"),te&&N.push(`name=${te.slice(0,40)}`),oe!==null&&N.push(`sandbox="${oe.slice(0,40)}"`),N.join(" ")},la=p=>{if(!(p instanceof HTMLIFrameElement))return"";try{let l=p.contentDocument;if(!l)return"cd=null";let P=l.body?.children.length??0,te=l.body?.innerHTML.length??0,oe=l.head?.innerHTML.length??0;return`cd=same-origin readyState=${l.readyState} body[${P}children,${te}ch] head[${oe}ch]`}catch(l){return`cd=cross-origin(${l.message.slice(0,30)})`}},lr=[],Mr=p=>{if(Ie())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"))&&(k(`window:error ${l.slice(0,140)}`),lr.push(l))},Xr=p=>{if(Ie())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"))&&(k(`window:rejection ${l.slice(0,140)}`),lr.push(l))},wt={value:0},Ar=()=>{Dn?.disconnect(),Dn=null,vr?.disconnect(),vr=null;for(let p of qr.splice(0))clearTimeout(p);Yr=!1,ir&&typeof window<"u"&&(window.removeEventListener("error",Mr),window.removeEventListener("unhandledrejection",Xr)),ir=!1},cr=()=>{if(!(ir||Ie()||vn)){if(ir=!0,lr.length=0,wt.value=0,typeof window<"u"&&(window.addEventListener("error",Mr),window.addEventListener("unhandledrejection",Xr)),typeof PerformanceObserver<"u")try{vr=new PerformanceObserver(p=>{if(!Ie())for(let l of p.getEntries()){if(!l.name.toLowerCase().includes("paypal"))continue;wt.value+=1;let P=Math.round(l.duration);k(`net ${P}ms ${l.name.slice(0,90)}`)}}),vr.observe({type:"resource",buffered:!0})}catch{}Jr?.()}},Cr=()=>{Jn&&(clearTimeout(Jn),Jn=null)},Un=()=>{Ar(),Cr()},Ue={setEnabled:p=>{p?cr():Ar()}};G.current=Ue,ge.current&&cr();let rn=np,qt=p=>{if(Ie()||rn(p))return;let l=Go(p)??p;Lt(()=>Qe.current?.(l))},b=(p,l)=>{if(Pt||Yn)return;Yn=!0,tn=!0,Un(),Pr();let P=hp({kind:p,generationActive:!0,automaticRetryAllowed:Ye,automaticRetryUsed:H.current});if(P.action==="retry"){H.current=!0,xe(!1),Fe(!1),At(!0),fn.current?.("retrying"),ar=setTimeout(()=>{Pt||Le(te=>te+1)},yp);return}if(xe(!1),Fe(!1),At(!1),Pe(!0),P.action!=="ignore"){if(fn.current?.("exhausted"),P.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",l);return}if(P.report){let te=ps({code:xc(p,l),message:l},{inAppBrowser:W.inAppBrowser,handoffObserved:!1});te.popupBlocked&&z.markBlocked(),A.error({errorCode:te.popupBlocked?te.errorCode:P.report.errorCode,stage:P.report.stage,operationOutcome:P.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:te.terminalReason})}St.current||(St.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",xc(p,l)))}};Pe(!1);let I=async(p,l=Bt.current)=>{if(Ie())return;let P=l?.sessionId??e;if(It.current){await It.current(p,{sessionId:P,accountPatch:l?.accountPatch,nonce:l?.nonce});return}let te=A.startTiming();A.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let oe=()=>{A.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"processing",durationMs:A.elapsed(te),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let N=Ju({body:p,sessionId:P,nonce:l?.nonce??Rn.current,accountPatch:l?.accountPatch,session:kn.current,email:Mn.current}),ne=await new bs(Ze,{telemetry:!1}).processPayment(N.userId,N.params);if(ne.ok){if(tn||Pt&&et.current)return;oe(),A.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Lt(()=>Ln.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ie())return;let Dt=await ne.json().catch(()=>null),Ut=_c(Dt),qe=Ut.message;oe(),ne.status===400&&(typeof Dt?.declineCode=="string"||!Array.isArray(Dt?.fields))?A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ne.status===400||ne.status===422?A.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):A.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Pp(ne.status),failureCategory:ne.status>=500?"server_error":void 0}),qt(qe),Lt(()=>Qn.current?.(Cn("paypal",qe,{code:Ut.code,declineCode:Ut.declineCode})));return}catch(N){if(Ie())return;oe(),A.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let ae=ep(N instanceof Error?N.message:void 0);qt(ae),Lt(()=>Qn.current?.(Cn("paypal",ae)));return}},B=()=>new Zo("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Y=p=>Ie()?Promise.reject(B()):Promise.resolve(p),kt=async p=>{if(p.ok){A.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Lt(()=>Ln.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let l=await p.json().catch(()=>null),P=_c(l);A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Lt(()=>Qn.current?.(Cn("paypal",P.message,{code:P.code,declineCode:P.declineCode})))},Gt=()=>{let p=Bt.current;xn("approved"),p&&(gn.current.delete(p.surfaceKey),Gn(p.generation)),Bt.current=null},se=async p=>{if(Ie())throw B();Io||hr();let l=Bt.current,P=l?.sessionId??e,te=l?.nonce??Rn.current;A.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let oe;try{oe=await new bs(Ze,{telemetry:!1}).createSessionIntent(P,te??"",Xu(zr),{idempotencyKey:Gr})}catch(N){throw A.error({...Qu(N,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),N}if(Ie())throw B();if(rp(oe))throw await kt(oe.response),Gt(),new Zo("PayPal checkout already settled.","api_error",{code:Ac});if(oe.provider!=="paypal"||oe.providerObjectType!==He)throw new Error(p);return A.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),oe.providerObjectId},ze=(p,l)=>{let P=l?.nonce??Rn.current;if(!P)return;let te=l?.sessionId??e,oe=lp(p);new bs(Ze,{telemetry:!1}).reportSessionIntentDecline(te,P,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:oe}).catch(()=>{})},E=fe;k("loadScript:scheduled (deferred 1 tick)");let Re=null,ee=setTimeout(()=>{if(Pt){k("loadScript:skipped (cancelled before defer ran)");return}k("loadScript:start");let p=In==="live"?"production":In,l={};He==="subscription"?l={intent:"subscription",vault:!0}:He==="order"&&(l={intent:"capture"}),Re=up({clientId:s,currency:g,...l,...p?{environment:p}:{},...p==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let P=!1;Re.then(te=>{if(P=!0,k(`loadScript:resolved inactive=${Ie()} ns=${!!te} buttons=${!!te?.Buttons}`),Ie())return;if(!te?.Buttons){k("FAIL: namespace missing Buttons factory"),b("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}A.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"provider_ready",durationMs:A.elapsed(Ht.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),A.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let oe=async(j,K)=>{if(Ie()||ot.current!==E)return;let Se=j.vaultSetupToken??j.subscriptionID??j.orderID??"",Te=Se?mt.current.get(Se):gn.current.get(E);if(!(!Te||!Yt(Te.generation))&&Gn(Te.generation)){mt.current.delete(Se),gn.current.delete(Te.surfaceKey),xn("approved");try{if(Fe(!0),Lt(()=>Qe.current?.(null)),!Se)throw new Zo("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let pe=sp({accountPatch:Te.accountPatch,email:Mn.current,billingName:er.current,session:kn.current});if(ap(pe))try{pe=op(pe,await K?.order?.get?.())}catch{}if((Vt.current||$e)&&!Tc(pe.email)){let $t=await Xe("PayPal",pe);if(!$t)return;pe=$t}Tc(pe.email)&&(Te.accountPatch=Rr({...Te.accountPatch,...pe}),await Vt.current?.(pe));let Hn=Zu(Se,zr);await I(Hn,Te)}catch(pe){qt(pe instanceof Error?pe.message:"PayPal capture failed.")}finally{Ie()||Fe(!1)}}},N=j=>{let K=yt?()=>Y(yt):()=>se(j);return async()=>Nn(await K())},ae=te.Buttons({style:{layout:"horizontal",height:gi,tagline:!1},...O==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(j,K)=>{if(Ie()){await K.reject();return}hr();let Se=jn.current,Te={};if(Se)try{let $t=await Se("paypal");if(Ie()){await K.reject();return}if(!$t.proceed){Bt.current=null,gn.current.delete(E),await K.reject();return}Te={sessionId:$t.sessionId,accountPatch:$t.accountPatch,nonce:$t.nonce}}catch($t){k(`onClick:runBeforeButtonClick rejected msg=${($t instanceof Error?$t.message:String($t)).slice(0,120)}`),Bt.current=null,gn.current.delete(E),await K.reject();return}Lt(()=>gt.current?.("paypal"));let pe=dn(),Hn={generation:pe,surfaceKey:E,...Te};Bt.current=Hn,gn.current.set(E,Hn),dt.current={...u,attempt:pe},await K.resolve(),A.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),je.current=A.startTiming()},createOrder:He==="order"?N("Failed to create PayPal order."):void 0,createSubscription:He==="subscription"?N("Failed to create PayPal subscription."):void 0,createVaultSetupToken:He==="setup_token"?async()=>Nn(await se("Failed to create PayPal setup token.")):void 0,onApprove:oe,onCancel:()=>{if(Ie())return;let j=gn.current.get(E)??Bt.current,K=j&&Yt(j.generation)?Yu(j.sessionId??e,zr):null;j&&gn.current.delete(j.surfaceKey),Bt.current=null,xn("cancelled"),A.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ve.current=!0,Pn({generation:j?.generation,remount:!0,focus:!1}),K&&Lt(()=>Ve.current?.(K))},onError:j=>{if(j instanceof Zo&&j.code===Ac)return;let K=j instanceof Error?j.message:"PayPal failed to render.";if(Ie()||ot.current!==E){rn(K)||un(Ee());return}if(vn){let Se=gn.current.get(E)??Bt.current;if(!Se||!Yt(Se.generation)){if(rn(K)){!Se&&!hn()&&Gn();return}un(Se||hn()?"stale_attempt":"no_current_attempt");return}if(k(`onError rendered=${vn} msg=${K.slice(0,120)}`),rn(K)){Gn(Se.generation);return}let{errorCode:Te,popupBlocked:pe,providerDeclined:Hn,terminalReason:$t}=ps(j,{inAppBrowser:W.inAppBrowser,handoffObserved:Q.current===Se.generation});if(pe&&z.markBlocked(),xn($t),Hn){A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:$t}),ze(j,Se),Lt(()=>Qn.current?.(Cn("paypal",K))),gn.current.delete(Se.surfaceKey),Bt.current=null,Gn(Se.generation);return}A.error({errorCode:Te,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:$t}),gn.current.delete(Se.surfaceKey),Bt.current=null,Pn({generation:Se.generation,remount:!0,showRetry:!0,focus:!0}),nr(j,{code:"paypal_runtime_failed",popupBlocked:pe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:O,terminalReason:$t});return}k(`onError rendered=${vn} msg=${K.slice(0,120)}`),b(rn(K)?"teardown":"pre_ready_callback",K)}}),ne=ae.isEligible();if(k(`isEligible=${ne}`),A.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ne){xe(!1),b("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Tr=!0,Wn=ae,Jr=()=>{if(!ir||Yr||Ie()||vn)return;Yr=!0,k(`container:dims ${sr(Ge)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Dn=new MutationObserver(K=>{if(!Ie()){for(let Se of K)if(Se.type==="childList")Se.addedNodes.forEach(Te=>{if(!(Te instanceof Element))return;let pe=Te.tagName.toLowerCase(),Hn=(Te.getAttribute("title")??"").slice(0,40),$t=pe==="iframe"?` ${Eo(Te)}`:"";k(`child+ ${pe}${Hn?` title="${Hn}"`:""}${$t} dims=${sr(Te)}`)});else if(Se.type==="attributes"&&Se.target instanceof Element){let Te=Se.target;if(Te.tagName.toLowerCase()!=="iframe")continue;let pe=Se.attributeName;(pe==="src"||pe==="srcdoc")&&k(`attr~ iframe ${pe}=${pe==="srcdoc"?`[${(Te.getAttribute("srcdoc")??"").length}ch]`:jr(Te.getAttribute("src"))} dims=${sr(Te)}`)}}}),Dn.observe(Ge,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let j=K=>{if(Ie()||vn)return;let Se=Ge.querySelectorAll("iframe"),Te=typeof document<"u"&&"hasStorageAccess"in document;k(`watchdog:${K} container=${sr(Ge)} children=${Ge.childElementCount} iframes=${Se.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Te} paypalNetRequests=${wt.value}`),Se.forEach((pe,Hn)=>{let $t=(pe.getAttribute("title")??"").slice(0,40);k(` iframe[${Hn}] ${sr(pe)}${$t?` title="${$t}"`:""} ${Eo(pe)}`);let _o=la(pe);_o&&k(` ${_o}`)}),lr.length===0&&k(" (no PayPal/zoid window errors captured)")};qr.push(setTimeout(()=>j("3s"),3e3)),qr.push(setTimeout(()=>j("8s"),8e3)),qr.push(setTimeout(()=>j("15s"),15e3))},Jr(),k("render:start");let Ut=A.startTiming();Jn=setTimeout(()=>{Ie()||vn||(k("watchdog:11s retryable render timeout"),b("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},mp);let qe=ae.render(Ge);(async()=>{try{if(await qe,k(`render:resolved inactive=${Ie()}`),Un(),Ie()){Pr();return}vn=!0,xe(!0),At(!1),fn.current?.("ready"),A.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"checkout_render",durationMs:A.elapsed(Ut),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(j){let K=j instanceof Error?j.message:"PayPal failed to render.";k(`render:rejected msg=${K.slice(0,120)}`),Un(),b(rn(K)?"teardown":"render_rejected",K)}})()}).catch(te=>{let oe=te instanceof Error?te.message:"PayPal operation failed.";k(`provider:failed msg=${oe.slice(0,120)}`);let N="script_rejected";P&&rn(oe)?N="teardown":P&&Tr&&(N="render_rejected"),b(N,oe)})},0);return()=>{Pt=!0,clearTimeout(ee),ar&&clearTimeout(ar),Un(),G.current===Ue&&(G.current=null),Pr(),je.current=null,dt.current=null}},[Ye,Ze,s,g,d,He,O,F,e,yt,fe,Z,Xe,$e,k,xn]);let En=be?Ss("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Kt?"#fef2f2":"#f3f4f6",border:`1px solid ${Kt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Je} failed=${Kt})`,q.length===0?`
1
+ import{a as uc}from"./chunk-D4CVZRT4.mjs";import{c as Lt,d as Br,e as Ca,f as ms,g as fs,h as Su,j as wu}from"./chunk-YR36EYW2.mjs";import{a as cc}from"./chunk-BU7THP6H.mjs";import{a as Co,b as si,c as Ps,d as Cs,e as va,f as oc,g as ac,h as ic,i as sc,j as lc,k as dc}from"./chunk-FGCZOMML.mjs";import{a as oi,b as gs,c as ec,d as hs,e as qo,f as tc,g as to,h as ai,i as nc,j as ba,k as ii,l as rc}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as Yh}from"@flopay/shared";import{PaymentAPI as sl}from"@flopay/js";import{FloPayError as Eo,isDeclineCallbackFailure as jm,isMerchantAuthRequired as Xd,resolveBillingApiUrl as $m,resolveButtonsLayoutTheme as Wm,resolveTheme as Hm}from"@flopay/shared";import{useCallback as Nr,useEffect as ia,useMemo as Wa,useRef as co,useState as sa}from"react";import{Fragment as Ho,jsx as sr,jsxs as pc}from"react/jsx-runtime";function ku(){return pc(Ho,{children:[pc("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 Ru(){return sr(Ho,{children:"Go back"})}function Iu(){return sr(Ho,{children:"Secure card checkout"})}function jo(e){return e!==void 0&&(e===""||e===null||e===!1)}function $o({content:e}){return sr(Ho,{children:e===void 0?sr(ku,{}):e})}function Wo({content:e}){return sr(Ho,{children:e===void 0?sr(Ru,{}):e})}function Sa({content:e}){return sr(Ho,{children:e===void 0?sr(Iu,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as Eu,canRecoverHostedCardForm as _u,classifyTelemetryFailure as Tu,FloPayError as Yn,isCardHolderNamePlaceholder as Mu,isMoneySettledOutcome as Au,isMountableVaultBlock as xu,isSetupIntentClientSecret as Fu,isValidEmail as Bu,resolveSetupFutureUsage as Du,resolveWalletModeOptions as Ou}from"@flopay/shared";import{canRecoverHostedCardForm as bo,hasServerSideCardGateway as kc}from"@flopay/shared";import{splitFullName as Ra}from"@flopay/shared";import{applyFriendlyMessageOverride as Go}from"@flopay/shared";function bs(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Yn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Lu(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 yc(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(xu(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||_u(o))||t&&e?.data.paypal?.publishableKey)}function mc(e,t){if(t&&(!(e instanceof Yn)||e.type==="authentication_error"))return bs(e);if(!(e instanceof Yn&&Lu(e))){if(!t&&!(e instanceof Yn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Tu(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Yn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Yn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Ko(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()},d=Mu(s.firstName,s.lastName);if(!Bu(s.email))return Promise.reject(new Yn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[R,C]of Object.entries(s)){if(d&&R.endsWith("Name")||typeof C!="string")continue;let g=C.trim();g&&(y[R]=g)}return a=e.claimCheckoutSession(t,n,{accountData:y}),a.catch(()=>{}),a}}function fc(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 vs(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 gc(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 Ss(e,t){return t?{...e,...t}:e}function gn(e,t,n){let o=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:o,...a?{code:a}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}var hc=new WeakMap;function Pc(e,t){return typeof e=="object"&&e!==null&&hc.set(e,t?{sessionId:t}:{}),e}function Cc(e){return typeof e=="object"&&e!==null?hc.get(e):void 0}function no(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function $r(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Wr(e){return e?.status==="authorized"||e?.status==="complete"}function ro(e,t){if(e.data.session)return e.data.session;let n=e.raw,o=n?.latestTransactionAttempt?.result,a=n?.status==="authorized"||o==="AUTHORIZED";return a||n?.status==="completed"||o==="SUCCESS"?{...t,status:a?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function bc(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function li(e){let t=bc(e);return new Yn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ci(e){return e instanceof Yn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Vo(e){return bc(e)?new Yn("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Yn("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Yn(Eu,"api_error",{code:"checkout_processing_timeout"})}function wa(e,t){return e==="processing"||Au(e,t)}function vc(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Sc(e,t){let n=e;if(Fu(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new Yn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:o,error:a}=await n.retrievePaymentIntent(t);if(a)throw new Yn(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var Nu=["apple_pay","google_pay"];function wc(e,t="automatic",n){let o=Du(n,Nu,"wallet");return{...Ou(e,t),allowedPaymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Uu=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ws(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:Uu.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function ka(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as vm,PaymentAPI as xi,SESSION_CREATE_TELEMETRY as Sm}from"@flopay/js";import{buildCheckoutDisplayData as wm,classifyTelemetryFailure as Vd,DEFAULT_PAYMENT_METHOD_ORDER as km,FloPayError as Sn,isDeclineCallbackFailure as Ld,isDetachedSessionEligible as Rm,isExpectedPaymentDecline as Nd,isMerchantAuthRequired as Im,isMountableVaultBlock as Em,resolveBillingApiUrl as _m,resolveButtonsLayoutTheme as Tm,resolveDirectPaypalConfig as Gd,resolveIdempotencyKey as Ud,resolveCheckoutLogLayout as Mm,resolveTheme as Yd,SDK_VERSION as Jd,telemetryStatusClass as Am,toPublicCheckoutInitError as zd}from"@flopay/shared";import Bi,{useCallback as Dn,useEffect as Sr,useMemo as dr,useRef as Wt,useState as en}from"react";import{createContext as Rc}from"react";var lr=Rc({flopay:null,paypalFlopay:null,billingApiUrl:""}),Pr=Rc({session:null,loading:!1,error:null});import{PaymentAPI as Rs}from"@flopay/js";import{buildPayPalCancelEvent as ep,buildPayPalProcessPaymentRequest as tp,buildPayPalSessionIntentRequest as np,buildPayPalTokenizedBody as rp,classifyTelemetryFailure as op,describePayPalProcessFailure as Fc,FloPayError as Zo,friendlyPayPalFailureMessage as ap,generateIdempotencyKey as ip,isPayPalTeardownMessage as sp,isSettledSessionIntent as lp,isValidEmail as Bc,mergePayPalPayerIdentity as cp,needsPayPalPayerDetails as dp,normalizeGatewayEnvironment as up,paypalProviderIdentityRequired as Dc,resolvePayPalApprovalIdentity as pp,resolvePayPalDeclineReason as yp,SDK_VERSION as mp,usesPayPalVaultedChannel as fp}from"@flopay/shared";import{loadScript as gp}from"@paypal/paypal-js";import{useCallback as cr,useContext as hp,useEffect as Ht,useMemo as Ta,useRef as st,useState as Hr}from"react";import{compactBuyerIdentity as zu,isValidEmail as qu}from"@flopay/shared";import{useCallback as Ic,useEffect as ju,useRef as Ec,useState as Tc}from"react";import{compactBuyerIdentity as Cr}from"@flopay/shared";import{jsx as _c,jsxs as Ia}from"react/jsx-runtime";function Yo(){let[e,t]=Tc(null),n=Ec(null),o=Ec(0),a=Ic((s,d)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:d}),new Promise(y=>{n.current=y})),[]),i=Ic(s=>{let d=n.current;n.current=null,t(null),d?.(s)},[]);return ju(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function Jo({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,d]=Tc(e.email?.trim()??""),y=qu(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",_c("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:R=>d(R.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&&_c("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),Ia("button",{type:"button",disabled:!y||a,onClick:()=>{n(zu({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as $u}from"@flopay/shared";import{useContext as di}from"react";function oo(){return di(lr).flopay}function ks(){return di(lr).paypalFlopay??null}function Wu(){return di(Pr)}function Mc(){return di(lr).billingApiUrl||$u()}import{FLO_INSTRUMENT_ONCE_NAMES as Hu,invokeMerchantCallback as Ku,projectFloInstrument as Vu}from"@flopay/shared";import{useCallback as Gu,useRef as ui}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Ac}from"@flopay/shared";function Xo(e,t){let n=ui(e);n.current=e;let o=ui(new Set),a=ui(t),i=ui(t);return Ca(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),Gu(s=>{if(i.current!==t)return;let d=Vu(s);if(d){if(Hu.has(d.name)){if(o.current.has(d.name))return;o.current.add(d.name)}Ku(()=>n.current?.(d))}},[t])}import{createContext as Yu}from"react";var Ea=Yu(null);function pi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var yi="provider.callback.ignored";function mi(){let e,t=0;return{take(n){return n!==e&&(e=n,t=0),t>=5?!1:(t+=1,!0)}}}var Ju=Symbol.for("@flopay/js.telemetry.bridge.v1"),Xu=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Zu(){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 Qu(e){let t=Zu(),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 fi(e){let t=globalThis[Xu];return Qu(t?.(e)??{})}function hn(e){if(e)return e[Ju]}import{useCallback as ao,useEffect as xc,useRef as vo}from"react";function _a(e,t){let n=vo(0),o=vo(null),a=vo(null),i=vo(e),s=vo(t?.onHandoffObserved),d=vo(t?.defersMissingTerminal),y=vo(t?.onMissingTerminalDeferred);xc(()=>{i.current=e,s.current=t?.onHandoffObserved,d.current=t?.defersMissingTerminal,y.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let R=ao((b=a.current)=>{b?.timer&&(clearTimeout(b.timer),b.timer=null)},[]),C=ao(b=>{R();let ge=n.current+1;return n.current=ge,o.current=null,a.current={generation:ge,method:b,timer:null,yieldedControl:!1},ge},[R]),g=ao(b=>{let ge=a.current;return b!==void 0&&ge?.generation!==b?!1:(R(ge),a.current=null,(b===void 0||o.current===b)&&(o.current=null),!0)},[R]),M=ao(b=>{let ge=a.current,ce=b??ge?.generation??n.current;(b===void 0||ge?.generation===b)&&(R(ge),a.current=null),o.current=ce},[R]),te=ao(b=>o.current===(b??n.current),[]),le=ao(b=>a.current?.generation===b&&o.current!==b,[]),U=ao(()=>{let b=a.current;b&&(R(b),!b.yieldedControl&&(b.yieldedControl=!0,s.current?.(b.method)))},[R]),j=ao(()=>{let b=a.current;!b?.yieldedControl||document.visibilityState!=="visible"||(R(b),b.timer=setTimeout(()=>{if(b.timer=null,a.current?.generation===b.generation){if(d.current?.(b.method)){y.current?.(b.method,b.generation);return}a.current=null,o.current=b.generation,i.current(b.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},ec))},[R]);return xc(()=>{let b=()=>{document.visibilityState==="visible"?j():U()};return document.addEventListener("visibilitychange",b),window.addEventListener("blur",U),window.addEventListener("focus",j),()=>{document.removeEventListener("visibilitychange",b),window.removeEventListener("blur",U),window.removeEventListener("focus",j),R()}},[R,U,j]),{startAttempt:C,finishAttempt:g,invalidateAttempt:M,isAttemptInvalidated:te,isAttemptCurrent:le,generationRef:n}}import{jsx as So,jsxs as Is}from"react/jsx-runtime";var gi=45,Pp=1e3,Cp=11e3,Oc="paypal_intent_settled",bp={width:"100%",minHeight:gi,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"},vp={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 Sp(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:vp[e.kind]??null}}function Lc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":tc(t)?"paypal_init_timeout":"paypal_init_failure"}function wp(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:d,currency:y,isSubscription:R,providerObjectType:C,approvalPresentation:g,onTokenizedBody:M,onComplete:te,onErrorChange:le,onDecline:U,onCancel:j,onTechnicalFailure:b,isProcessing:ge=!1,onLoadStateChange:ce,onInitializationStateChange:v,allowAutomaticRetry:Ke=!0,onButtonClick:K,runBeforeButtonClick:ze,session:lt,existingOrderId:ft,telemetry:Ee,telemetryContext:zt,onInstrument:Nt,debug:Ie=!1}){let Xe=oo(),ct=Xo(Nt,e),dt=Ta(()=>{if(Xe)return null;let I=fi({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:mp,enabled:Ee!==!1});return I.setCheckoutContext(zt??{}),I.beginCheckout(zt??{}),I},[n,Xe,Ee,zt?.checkoutMode,zt?.layout]),_e=Ta(()=>hn(Xe),[Xe]);Ht(()=>()=>{dt&&dt.flush().catch(()=>{}).finally(()=>dt.destroy())},[dt]);let X=Ta(()=>({error:I=>{_e?_e.error(I):dt?.error(I),ct({class:"technical_error",errorCode:I.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":I.errorCode,requestCategory:I.requestCategory,provider:I.provider})},log:I=>{_e?_e.log(I):dt?.log(I),ct({class:"lifecycle",name:I.name,provider:I.provider})},performance:I=>{_e?_e.performance(I):dt?.performance(I)},terminal:I=>{_e?_e.terminal(I):dt?.terminal(I)},startTiming:()=>_e?.now()??dt?.now()??0,elapsed:I=>_e?.elapsed(I)??Math.max(0,(dt?.now()??I)-I)}),[ct,_e,dt]),de=st(null),Kt=st(0),je=st(null),ut=st(null),Q=st(null),Ae=hp(Ea),tt=st(null);tt.current||(tt.current=pi());let $=Ae??tt.current,St=st(null),ve=st(!1),[Ze,qe]=Hr(!1),[nt,wt]=Hr(!1),[De,It]=Hr(0),xe=st(0),[Te,kt]=Hr(!1),Ut=st(!1),Et=st(!1),[G,ue]=Hr(!1),[Me,pt]=Hr(!1),{request:yt,collect:Ve,finish:gt}=Yo(),Pt=st({sessionId:e,required:Dc(o,lt)});Pt.current.sessionId!==e&&(Pt.current={sessionId:e,required:Dc(o,lt)});let Rt=Pt.current.required,Ge=Ta(()=>n.replace(/\/+$/,""),[n]),rt=lt?.gateways?.paypal?.providerObjectType??C,F=rt??(R?"subscription":"order"),[Cn]=Hr(ba),S=lt?.gateways?.paypal?.approvalPresentation??g,m=ii(Cn,S==="app_switch"?"app_switch":void 0,F),W=fp(rt),B=Ta(()=>JSON.stringify([Ge,s,y,d??"",F,W,m,e,ft??""]),[Ge,s,y,d,ft,F,W,m,e]),H=st(B),f=H.current!==B,ne=st(Ie),L=st(null),[Se,we]=Hr([]),k=cr(I=>{ne.current&&we(We=>[...We,`${new Date().toISOString().slice(11,23)} ${I}`])},[]);Ht(()=>{ne.current=Ie,Ie&&k("debug:enabled"),L.current?.setEnabled(Ie)},[k,Ie]);let ot=st(M),Yt=st(te),qt=st(le),On=st(U),be=st(j),wr=st(b),pn=st(K),yn=st(ce),at=st(v),Ft=st(i),_n=st(ze),Wn=st(lt),Tn=st(o),wn=st(a),kn=st(t),Jt=st(null),jt=st(new Map),tn=st(new Map),Je=st(!1),pe=st(e);pe.current=e;let[Qn]=Hr(mi);Ht(()=>(Je.current=!0,()=>{Je.current=!1}),[]),Ht(()=>{ot.current=M},[M]),Ht(()=>{Ft.current=i},[i]),Ht(()=>{Yt.current=te},[te]),Ht(()=>{qt.current=le},[le]),Ht(()=>{On.current=U},[U]),Ht(()=>{be.current=j},[j]),Ht(()=>{wr.current=b},[b]),Ht(()=>{pn.current=K},[K]),Ht(()=>{yn.current=ce},[ce]),Ht(()=>{at.current=v},[v]),Ht(()=>{_n.current=ze},[ze]),Ht(()=>{Wn.current=lt},[lt]),Ht(()=>{Tn.current=o},[o]),Ht(()=>{wn.current=a},[a]),Ht(()=>{kn.current=t},[t]),Ht(()=>{xe.current=De},[De]),Ht(()=>{Te&&St.current?.focus()},[Te,De]);let Bt=cr(()=>{window.setTimeout(()=>{St.current?.focus()},0)},[]),Mn=cr(()=>{qe(!1),It(I=>I+1)},[]),Ln=cr(()=>{kt(!1),(de.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??de.current)?.focus?.()},[]);Ht(()=>{!Ze||!ve.current||(ve.current=!1,Ln())},[Ln,Ze,De]);let er=cr((I,We)=>{let h=We?.popupBlocked??to(I);h&&$.markBlocked();let re=oi("PayPal",h,Cn.inAppBrowser),mt=wr.current;if(mt){let He=h&&Cn.inAppBrowser?new Zo(re,"api_error",{code:We?.code??"paypal_popup_blocked"}):I;mt("paypal",He,We);return}if(I instanceof Zo&&I.code==="checkout_processing_timeout"){qt.current?.(I.message);return}qt.current?.(re)},[$,Cn.inAppBrowser]),Nn=cr(I=>{let We=je.current,h=ut.current;We===null||!h||(X.log({...h,popupCapability:$.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:I}),X.performance({...h,popupCapability:$.current(),stage:"overlay_return",durationMs:X.elapsed(We),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:I}),je.current=null)},[$,X]),kr=cr((I,We,h)=>{let re=ut.current;Nn("overlay_timeout"),re&&X.error({...re,popupCapability:$.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),er(We,{...h,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:m,terminalReason:"overlay_timeout"}),kt(!0),Mn(),Bt()},[Nn,Bt,er,$,m,Mn,X]),ur=cr(()=>{$.markAvailable();let I=ut.current;I&&(Q.current=I.attempt,X.log({...I,popupCapability:$.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[$,X]),mn=cr(()=>!0,[]),fn=cr(()=>{let I=ut.current;if(!I)return;let We=je.current;X.performance({...I,popupCapability:$.current(),stage:"overlay_return",durationMs:We===null?0:X.elapsed(We),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired"})},[$,X]),{finishAttempt:An,generationRef:Hn,invalidateAttempt:Un,isAttemptCurrent:xn,isAttemptInvalidated:ln,startAttempt:nn}=_a(kr,{onHandoffObserved:ur,defersMissingTerminal:mn,onMissingTerminalDeferred:fn}),rn=cr(()=>(kt(!1),nn("paypal")),[nn]),Xt=cr(I=>{Un(I?.generation),I?.showRetry&&kt(!0),I?.remount&&Mn(),I?.focus!==!1&&Bt()},[Bt,Un,Mn]),zn=I=>{let We=Jt.current;return We&&tn.current.set(I,We),I};Ht(()=>{H.current!==B&&(H.current=B,Ut.current=!1,Et.current=!1,qe(!1),wt(!1),ue(!1),at.current?.("loading"))},[B]),Ht(()=>{Lt(()=>yn.current?.(Ze&&!G))},[Ze,G]);let qn=up(d);Ht(()=>{let I={attempt:Hn.current+1,inAppBrowser:Cn.inAppBrowser,appFamily:Cn.appFamily,popupCapability:$.current(),presentationMode:m},We=()=>({...ut.current??I,popupCapability:$.current()}),h={error:u=>X.error({...u,...We()}),log:u=>X.log({...u,...We()}),performance:u=>X.performance({...u,...We()}),terminal:u=>X.terminal({...u,...We()}),startTiming:X.startTiming,elapsed:X.elapsed},re=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",mt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(k(`mount clientId=${re} env=${d??"(unset)"}\u2192${qn??"live"} ccy=${y} sub=${R}`),k(`ua=${mt.slice(0,80)}${mt.length>80?"\u2026":""}`),!s){k("FAIL: clientId empty \u2014 gateway misconfigured"),ue(!0),h.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!de.current){k("FAIL: containerRef not attached");return}Kt.current=h.startTiming(),h.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let He=!1,$t=!1,ke=()=>He||$t,Rr=u=>{let c=Je.current,E=c?u:"torn_down";c&&k(`onError ignored reason=${E}`),Qn.take(pe.current)&&h.log({name:yi,stage:"provider_ready",reason:E,provider:"paypal",paymentMethodCategory:"paypal"})},Ur=()=>pe.current===e?"stale_attempt":"session_changed",Rn=W?F:void 0,ye,Vr=!1,uo=()=>{ye=ip(),ye||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Vr=!0},po=null,pr=!1,tr=null,Jn=!1,Kn=()=>{!tr||Jn||(Jn=!0,tr.close().catch(()=>{}))},Dt=!1,Ir=!1,In=de.current,nr=null,he=null,Bn=[],yr=null,Er=!1,rr=!1,_r=null,Tr=u=>{if(!u||typeof u.getBoundingClientRect!="function")return"(no rect)";let c=u.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},yo=u=>{if(!u)return"(empty)";try{let c=new URL(u,typeof window>"u"?"https://localhost":window.location.href),E=c.pathname.toLowerCase();return E.includes("checkcaptcha")||E.includes("captcha")?`CAPTCHA(${c.host}${E})`:E.includes("risk")||E.includes("challenge")?`RISK(${c.host}${E})`:E.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${E}`.slice(0,100)}catch{return u.slice(0,80)}},zr=u=>{let c=u.getAttribute("src"),E=u.getAttribute("srcdoc"),P=u.getAttribute("name"),x=u.getAttribute("sandbox"),oe=[];return c&&oe.push(`src=${yo(c)}`),E&&oe.push(`srcdoc[${E.length}ch]`),!c&&!E&&oe.push("src=(empty) srcdoc=(empty)"),P&&oe.push(`name=${P.slice(0,40)}`),x!==null&&oe.push(`sandbox="${x.slice(0,40)}"`),oe.join(" ")},Gr=u=>{if(!(u instanceof HTMLIFrameElement))return"";try{let c=u.contentDocument;if(!c)return"cd=null";let E=c.body?.children.length??0,P=c.body?.innerHTML.length??0,x=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${E}children,${P}ch] head[${x}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},Yr=[],_o=u=>{if(ke())return;let c=u.message??String(u.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(k(`window:error ${c.slice(0,140)}`),Yr.push(c))},Mr=u=>{if(ke())return;let c=u.reason instanceof Error?u.reason.message:String(u.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(k(`window:rejection ${c.slice(0,140)}`),Yr.push(c))},mr={value:0},Jr=()=>{nr?.disconnect(),nr=null,he?.disconnect(),he=null;for(let u of Bn.splice(0))clearTimeout(u);rr=!1,Er&&typeof window<"u"&&(window.removeEventListener("error",_o),window.removeEventListener("unhandledrejection",Mr)),Er=!1},_t=()=>{if(!(Er||ke()||Dt)){if(Er=!0,Yr.length=0,mr.value=0,typeof window<"u"&&(window.addEventListener("error",_o),window.addEventListener("unhandledrejection",Mr)),typeof PerformanceObserver<"u")try{he=new PerformanceObserver(u=>{if(!ke())for(let c of u.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;mr.value+=1;let E=Math.round(c.duration);k(`net ${E}ms ${c.name.slice(0,90)}`)}}),he.observe({type:"resource",buffered:!0})}catch{}_r?.()}},qr=()=>{yr&&(clearTimeout(yr),yr=null)},Vn=()=>{Jr(),qr()},or={setEnabled:u=>{u?_t():Jr()}};L.current=or,ne.current&&_t();let bn=sp,Oe=u=>{if(ke()||bn(u))return;let c=Go(u)??u;Lt(()=>qt.current?.(c))},cn=(u,c)=>{if(He||pr)return;pr=!0,$t=!0,Vn(),Kn();let E=Sp({kind:u,generationActive:!0,automaticRetryAllowed:Ke,automaticRetryUsed:Ut.current});if(E.action==="retry"){Ut.current=!0,qe(!1),pt(!1),wt(!0),at.current?.("retrying"),po=setTimeout(()=>{He||It(P=>P+1)},Pp);return}if(qe(!1),pt(!1),wt(!1),ue(!0),E.action!=="ignore"){if(at.current?.("exhausted"),E.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",c);return}if(E.report){let P=gs({code:Lc(u,c),message:c},{inAppBrowser:Cn.inAppBrowser,handoffObserved:!1});P.popupBlocked&&$.markBlocked(),h.error({errorCode:P.popupBlocked?P.errorCode:E.report.errorCode,stage:E.report.stage,operationOutcome:E.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:P.terminalReason})}Et.current||(Et.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Lc(u,c)))}};ue(!1);let Vt=async(u,c=Jt.current)=>{if(ke())return;let E=c?.sessionId??e;if(ot.current){await ot.current(u,{sessionId:E,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let P=h.startTiming();h.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let x=()=>{h.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),h.performance({stage:"processing",durationMs:h.elapsed(P),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let oe=tp({body:u,sessionId:E,nonce:c?.nonce??kn.current,accountPatch:c?.accountPatch,session:Wn.current,email:Tn.current}),ae=await new Rs(Ge,{telemetry:!1}).processPayment(oe.userId,oe.params);if(ae.ok){if($t||He&&Je.current)return;x(),h.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Lt(()=>Yt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ke())return;let me=await ae.json().catch(()=>null),Pe=Fc(me),At=Pe.message;x(),ae.status===400&&(typeof me?.declineCode=="string"||!Array.isArray(me?.fields))?h.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ae.status===400||ae.status===422?h.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):h.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:wp(ae.status),failureCategory:ae.status>=500?"server_error":void 0}),Oe(At),Lt(()=>On.current?.(gn("paypal",At,{code:Pe.code,declineCode:Pe.declineCode})));return}catch(oe){if(ke())return;x(),h.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Qe=ap(oe instanceof Error?oe.message:void 0);Oe(Qe),Lt(()=>On.current?.(gn("paypal",Qe)));return}},w=()=>new Zo("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),T=u=>ke()?Promise.reject(w()):Promise.resolve(u),z=async u=>{if(u.ok){h.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Lt(()=>Yt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let c=await u.json().catch(()=>null),E=Fc(c);h.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Lt(()=>On.current?.(gn("paypal",E.message,{code:E.code,declineCode:E.declineCode})))},Y=()=>{let u=Jt.current;Nn("approved"),u&&(jt.current.delete(u.surfaceKey),An(u.generation)),Jt.current=null},Ct=async u=>{if(ke())throw w();Vr||uo();let c=Jt.current,E=c?.sessionId??e,P=c?.nonce??kn.current;h.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let x;try{x=await new Rs(Ge,{telemetry:!1}).createSessionIntent(E,P??"",np(Rn),{idempotencyKey:ye})}catch(oe){throw h.error({...op(oe,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),oe}if(ke())throw w();if(lp(x))throw await z(x.response),Y(),new Zo("PayPal checkout already settled.","api_error",{code:Oc});if(x.provider!=="paypal"||x.providerObjectType!==F)throw new Error(u);return h.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),x.providerObjectId},Gt=(u,c)=>{let E=c?.nonce??kn.current;if(!E)return;let P=c?.sessionId??e,x=yp(u);new Rs(Ge,{telemetry:!1}).reportSessionIntentDecline(P,E,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:x}).catch(()=>{})},V=De;k("loadScript:scheduled (deferred 1 tick)");let Le=null,D=setTimeout(()=>{if(He){k("loadScript:skipped (cancelled before defer ran)");return}k("loadScript:start");let u=qn==="live"?"production":qn,c={};F==="subscription"?c={intent:"subscription",vault:!0}:F==="order"&&(c={intent:"capture"}),Le=gp({clientId:s,currency:y,...c,...u?{environment:u}:{},...u==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let E=!1;Le.then(P=>{if(E=!0,k(`loadScript:resolved inactive=${ke()} ns=${!!P} buttons=${!!P?.Buttons}`),ke())return;if(!P?.Buttons){k("FAIL: namespace missing Buttons factory"),cn("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}h.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),h.performance({stage:"provider_ready",durationMs:h.elapsed(Kt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),h.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let x=async(ie,N)=>{if(ke()||xe.current!==V)return;let q=ie.vaultSetupToken??ie.subscriptionID??ie.orderID??"",Z=q?tn.current.get(q):jt.current.get(V);if(!(!Z||!xn(Z.generation))&&An(Z.generation)){tn.current.delete(q),jt.current.delete(Z.surfaceKey),Nn("approved");try{if(pt(!0),Lt(()=>qt.current?.(null)),!q)throw new Zo("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Re=pp({accountPatch:Z.accountPatch,email:Tn.current,billingName:wn.current,session:Wn.current});if(dp(Re))try{Re=cp(Re,await N?.order?.get?.())}catch{}if((Ft.current||Rt)&&!Bc(Re.email)){let $e=await Ve("PayPal",Re);if(!$e)return;Re=$e}Bc(Re.email)&&(Z.accountPatch=Cr({...Z.accountPatch,...Re}),await Ft.current?.(Re));let Ot=rp(q,Rn);await Vt(Ot,Z)}catch(Re){Oe(Re instanceof Error?Re.message:"PayPal capture failed.")}finally{ke()||pt(!1)}}},oe=ie=>{let N=ft?()=>T(ft):()=>Ct(ie);return async()=>zn(await N())},Qe=P.Buttons({style:{layout:"horizontal",height:gi,tagline:!1},...m==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ie,N)=>{if(ke()){await N.reject();return}uo();let q=_n.current,Z={};if(q)try{let $e=await q("paypal");if(ke()){await N.reject();return}if(!$e.proceed){Jt.current=null,jt.current.delete(V),await N.reject();return}Z={sessionId:$e.sessionId,accountPatch:$e.accountPatch,nonce:$e.nonce}}catch($e){k(`onClick:runBeforeButtonClick rejected msg=${($e instanceof Error?$e.message:String($e)).slice(0,120)}`),Jt.current=null,jt.current.delete(V),await N.reject();return}Lt(()=>pn.current?.("paypal"));let Re=rn(),Ot={generation:Re,surfaceKey:V,...Z};Jt.current=Ot,jt.current.set(V,Ot),ut.current={...I,attempt:Re},await N.resolve(),h.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),h.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),je.current=h.startTiming()},createOrder:F==="order"?oe("Failed to create PayPal order."):void 0,createSubscription:F==="subscription"?oe("Failed to create PayPal subscription."):void 0,createVaultSetupToken:F==="setup_token"?async()=>zn(await Ct("Failed to create PayPal setup token.")):void 0,onApprove:x,onCancel:()=>{if(ke())return;let ie=jt.current.get(V)??Jt.current,N=ie&&xn(ie.generation)?ep(ie.sessionId??e,Rn):null;ie&&jt.current.delete(ie.surfaceKey),Jt.current=null,Nn("cancelled"),h.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ve.current=!0,Xt({generation:ie?.generation,remount:!0,focus:!1}),N&&Lt(()=>be.current?.(N))},onError:ie=>{if(ie instanceof Zo&&ie.code===Oc)return;let N=ie instanceof Error?ie.message:"PayPal failed to render.";if(ke()||xe.current!==V){bn(N)||Rr(Ur());return}if(Dt){let q=jt.current.get(V)??Jt.current;if(!q||!xn(q.generation)){if(bn(N)){!q&&!ln()&&An();return}Rr(q||ln()?"stale_attempt":"no_current_attempt");return}if(k(`onError rendered=${Dt} msg=${N.slice(0,120)}`),bn(N)){An(q.generation);return}let{errorCode:Z,popupBlocked:Re,providerDeclined:Ot,terminalReason:$e}=gs(ie,{inAppBrowser:Cn.inAppBrowser,handoffObserved:Q.current===q.generation});if(Re&&$.markBlocked(),Nn($e),Ot){h.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:$e}),Gt(ie,q),Lt(()=>On.current?.(gn("paypal",N))),jt.current.delete(q.surfaceKey),Jt.current=null,An(q.generation);return}h.error({errorCode:Z,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:$e}),jt.current.delete(q.surfaceKey),Jt.current=null,Xt({generation:q.generation,remount:!0,showRetry:!0,focus:!0}),er(ie,{code:"paypal_runtime_failed",popupBlocked:Re,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:m,terminalReason:$e});return}k(`onError rendered=${Dt} msg=${N.slice(0,120)}`),cn(bn(N)?"teardown":"pre_ready_callback",N)}}),ae=Qe.isEligible();if(k(`isEligible=${ae}`),h.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ae){qe(!1),cn("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ir=!0,tr=Qe,_r=()=>{if(!Er||rr||ke()||Dt)return;rr=!0,k(`container:dims ${Tr(In)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(nr=new MutationObserver(N=>{if(!ke()){for(let q of N)if(q.type==="childList")q.addedNodes.forEach(Z=>{if(!(Z instanceof Element))return;let Re=Z.tagName.toLowerCase(),Ot=(Z.getAttribute("title")??"").slice(0,40),$e=Re==="iframe"?` ${zr(Z)}`:"";k(`child+ ${Re}${Ot?` title="${Ot}"`:""}${$e} dims=${Tr(Z)}`)});else if(q.type==="attributes"&&q.target instanceof Element){let Z=q.target;if(Z.tagName.toLowerCase()!=="iframe")continue;let Re=q.attributeName;(Re==="src"||Re==="srcdoc")&&k(`attr~ iframe ${Re}=${Re==="srcdoc"?`[${(Z.getAttribute("srcdoc")??"").length}ch]`:yo(Z.getAttribute("src"))} dims=${Tr(Z)}`)}}}),nr.observe(In,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ie=N=>{if(ke()||Dt)return;let q=In.querySelectorAll("iframe"),Z=typeof document<"u"&&"hasStorageAccess"in document;k(`watchdog:${N} container=${Tr(In)} children=${In.childElementCount} iframes=${q.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Z} paypalNetRequests=${mr.value}`),q.forEach((Re,Ot)=>{let $e=(Re.getAttribute("title")??"").slice(0,40);k(` iframe[${Ot}] ${Tr(Re)}${$e?` title="${$e}"`:""} ${zr(Re)}`);let la=Gr(Re);la&&k(` ${la}`)}),Yr.length===0&&k(" (no PayPal/zoid window errors captured)")};Bn.push(setTimeout(()=>ie("3s"),3e3)),Bn.push(setTimeout(()=>ie("8s"),8e3)),Bn.push(setTimeout(()=>ie("15s"),15e3))},_r(),k("render:start");let Pe=h.startTiming();yr=setTimeout(()=>{ke()||Dt||(k("watchdog:11s retryable render timeout"),cn("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Cp);let At=Qe.render(In);(async()=>{try{if(await At,k(`render:resolved inactive=${ke()}`),Vn(),ke()){Kn();return}Dt=!0,qe(!0),wt(!1),at.current?.("ready"),h.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),h.performance({stage:"checkout_render",durationMs:h.elapsed(Pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ie){let N=ie instanceof Error?ie.message:"PayPal failed to render.";k(`render:rejected msg=${N.slice(0,120)}`),Vn(),cn(bn(N)?"teardown":"render_rejected",N)}})()}).catch(P=>{let x=P instanceof Error?P.message:"PayPal operation failed.";k(`provider:failed msg=${x.slice(0,120)}`);let oe="script_rejected";E&&bn(x)?oe="teardown":E&&Ir&&(oe="render_rejected"),cn(oe,x)})},0);return()=>{He=!0,clearTimeout(D),po&&clearTimeout(po),Vn(),L.current===or&&(L.current=null),Kn(),je.current=null,ut.current=null}},[Ke,Ge,s,y,d,F,m,W,e,ft,De,X,Ve,Rt,k,Nn]);let Fn=Ie?Is("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:G?"#fef2f2":"#f3f4f6",border:`1px solid ${G?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Ze} failed=${G})`,Se.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${q.join(`
4
- `)}`]}):null;return Kt&&!y?be?Co("div",{children:En}):null:Ss("div",{children:[En,ut&&Co(Jo,{identity:ut.identity,methodLabel:ut.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:ft,onCancel:()=>ft(null)}),Ss("div",{"aria-hidden":We||ut?!0:void 0,style:We||ut?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:gi},children:[!Je&&!We&&Co("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"}}),Co("div",{ref:ue,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:gi,display:"flex",opacity:Je?1:0},"aria-busy":Ce||me},fe)]},fe),nt&&Co("button",{ref:Mt,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:gr,style:fp,children:"Try PayPal again"})]})}function hi(e){return Co(Fc,{...e})}function Bc(e){return Co(Fc,{...e})}import{jsx as Dc,jsxs as vp}from"react/jsx-runtime";function Qo({children:e,margin:t,icon:n=!0,styleOverride:o}){return vp("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&&Dc("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Dc("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 Pi,clearCachedInlineSession as ws,hashCreateParams as Oc,legacyCachedSessionMatchesDraft as Lc,persistCachedInlineIdempotencyKey as vi,persistCachedInlineSession as Ci,readCachedInlineIdempotencyKey as Nc,readCachedInlineSession as Uc,serializeCreateParams as Ma}from"@flopay/shared";var zc=new Set;function Cp(){return globalThis.process?.env?.NODE_ENV==="production"}function qc(e,t){zc.has(e)||Cp()||(zc.add(e),console.warn(t))}function jc(){qc("automatic-payment-button-inline-create","[FloPay] FloPayAutomaticPaymentButton: creating the session from inline props is deprecated and may be downgraded to a Full checkout. Mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and pass `getSession` instead.")}function $c(){qc("checkout-keyless-create","[FloPay] FloPayCheckout: `createSession` with checkoutMode confirm/auto is deprecated and may be downgraded to a Full checkout. For one-click, mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and use FloPayAutomaticPaymentButton `getSession`.")}import{isCardFieldsInstrumentSource as bp,resolveBillingApiUrl as Sp}from"@flopay/shared";import{useCallback as wp,useEffect as so,useMemo as kp,useRef as Wc,useState as Hc}from"react";import{jsx as Rp}from"react/jsx-runtime";function bi({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=Hc(e instanceof Promise?null:e),[d,g]=Hc(t instanceof Promise||!t?null:t),w=Wc(null),v=Wc(null),h=Xo(o),T=wp(x=>{bp(x)||h(x)},[h]);so(()=>{h({class:"lifecycle",name:"checkout.mount"})},[h]),so(()=>{i&&h({class:"lifecycle",name:"sdk.initialize.ready"})},[h,i]),so(()=>{if(i)return bn(i)?.subscribe?.(T)},[T,i]),so(()=>{if(!(!d||d===i))return bn(d)?.subscribe?.(T)},[T,i,d]),so(()=>{if(!i)return;let x=bn(i);return w.current=x?.beginCheckout()??x?.now()??0,x?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{x?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),so(()=>{let x=!1;return e instanceof Promise?e.then(U=>{x||s(U)},()=>{x||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{x=!0}},[h,e]),so(()=>{let x=!1;if(!t){g(null);return}return t instanceof Promise?t.then(U=>{x||g(U)},()=>{x||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):g(t),()=>{x=!0}},[h,t]),so(()=>{if(!i||v.current===i)return;v.current=i;let x=bn(i);x?.log({name:"checkout.rendered",stage:"checkout_render"}),h({class:"lifecycle",name:"checkout.rendered"}),x?.performance({stage:"checkout_render",durationMs:x.elapsed(w.current??0),durationMode:"machine"})},[h,i]);let ie=Sp(n?.billingApiUrl),ce=kp(()=>({flopay:i,paypalFlopay:d,billingApiUrl:ie,emitInstrument:h}),[i,d,ie,h]);return Rp(yr.Provider,{value:ce,children:a})}import{markSessionRecentlyCompleted as ea,wasSessionRecentlyCompleted as ks}from"@flopay/shared";async function Si(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{beginSavedCardChallengeTelemetry as Ip,completeSavedCardNextAction as Ep,loadFloPay as Kc,PaymentAPI as xa,runSavedCardChallenge as _p}from"@flopay/js";import{classifyPaymentRejection as Tp,FloPayError as Ot,isAuthorizationOnlySession as Mp,isMerchantAuthRequired as Is,isMountableVaultBlock as Ap,isSetupIntentClientSecret as xp,MERCHANT_AUTH_REQUIRED_CODE as Fp,normalizeCheckoutFailureOutcome as Vc}from"@flopay/shared";var Ba="card";async function Bp(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 Dp(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:d}=await e.confirmCardSetup(t,n);return{error:d,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 ta(e){return new Ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Op(){return new Ot("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Fa(e,t){return Object.assign(e,{checkoutMethod:t})}function Vr(e,t){let n=e instanceof Ot?e:new Ot(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 Aa(e,t){try{return await e()}catch(n){throw Vr(n,t)}}function Yc(e){return!e?.type||!e.threeDSecureToken||Is(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Jc(e){return _p(e)}function Da(e,t,n,o=!0){let a={release:()=>{}};if(!o)return a;try{let i=new xa(e),s=Ip(i,t,n);return s?{telemetry:s,release:()=>{setTimeout(()=>{try{i.destroy()}catch{}},0)}}:a}catch{return a}}async function na(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new xa(n,{telemetry:!1}),d=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,g;try{g=await Ep({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:v=>Or({type:v.declineReason??"authorization_declined",gatewayErrorCode:v.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(v){if(a.aborted||v instanceof Error&&v.name==="AbortError")throw v instanceof Ot&&v.code==="three_ds_aborted"?v:ta(v);if(!(v instanceof Ot)||v.code!=="three_ds_timeout"&&v.code!=="checkout_processing_timeout")throw v;try{g=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:d,timeoutMs:5e3,signal:a})}catch(T){if(a.aborted)throw ta(T);if(!(T instanceof Ot)||T.code!=="checkout_processing_timeout")throw T}let h=g&&oo(g,t.session);if(!Hr(h)&&h?.status!=="expired"){if(t.telemetry){let T=new xa(n);try{T.reportThreeDsAbandoned(o)}finally{T.destroy()}}throw Op()}}let w=g&&oo(g,t.session);if(!Hr(w))throw Vo(w);return{...Wr(w,o),checkoutMethod:"card"}}function Xc(e){return new Ot("This payment needs your card details. Please complete your payment below.","authentication_error",{code:Fp,...e===void 0?{}:{statusCode:e}})}function Or(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if(Is(e))return Fa(Xc(),o);let a=e?.message??t,i=Go(a)??a,s=Fa(new Ot(i,"api_error",{code:e?.code??Vc(e?.outcome)??Vc(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Rs(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function wi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Zc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||wi(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let d of i)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||wi(d)))return d;let s=a.gateways;if(s&&typeof s=="object"){let d=s.stripe;if(d&&typeof d=="object"){let g=d,w=[g.stripeClientSecret,g.clientSecret];for(let v of w)if(typeof v=="string"&&v.length>0&&(!t?.requirePaymentIntentClientSecret||wi(v)))return v}}}}async function Lp({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=Zc(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let d=(await new xa(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(wi(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function ra({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:s}){let d=e.replace(/\/+$/,""),g=t??n.id,w=o??n.clientSecret,v=n.customer?.id??n.accountData?.userId??"",h=n.customer?.email??n.accountData?.email??"",T=n.customer?.firstName??n.accountData?.firstName??"",ie=n.customer?.lastName??n.accountData?.lastName??"",ce=n.customer?.country??n.accountData?.country??void 0,x=n.customer?.zip??n.accountData?.zip??void 0,C=await new xa(d,s===!1?{telemetry:!1}:void 0).processPayment(v,{sessionId:g,nonce:w,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:v,email:h,firstName:T,lastName:ie,country:ce,zip:x},returnUrl:i??Rs(n)});if(C.ok){let de=typeof C.json=="function"?await C.json().catch(()=>null):null;if(Mp(n)||de?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof de?.paymentId=="string"?de.paymentId:n.paymentId,sessionId:typeof de?.sessionId=="string"?de.sessionId:g,authorizationExpiresAt:typeof de?.authorizationExpiresAt=="string"?de.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:ka(a),checkoutMethod:Gc(a,n)}};let S=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...S?{paymentIntentId:S}:{},paymentMethodId:ka(a),checkoutMethod:Gc(a,n)}}}let me;try{me=await C.json()}catch(de){throw new Ot("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:C.status,cause:de})}if(Is(me))throw Fa(Xc(C.status),"card");if(me?.type==="3ds_required"&&typeof me.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:me.nextActionRedirectUrl};if(me?.type==="paypal_redirect_required"||me?.type==="3ds_required"){let de=Zc(me);if(!de)throw new Ot("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:C.status});return{type:me.type,threeDSecureToken:de,paymentMethodId:me.paymentMethodId}}if(me?.gatewayErrorCode==="authentication_required"){let de=await Lp({billingApiUrl:d,sessionId:g,nonce:w,responseJson:me});if(de)return de;throw Fa(new Ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw Np(me,C.status)}function Np(e,t){let n=new Ot(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(n,{telemetryOutcome:Tp(t,e)})}async function ki(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:d,telemetry:g,signal:w}){let v=t?.getRawProvider();if(!v)throw Vr(new Ot("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Fa(new Ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=xp(e.threeDSecureToken),T=null,ie=e.paymentMethodId,ce=await Aa(()=>Bp(v,e.threeDSecureToken,h),"card");if(ce){if(ce.error)throw Vr(new Ot(ce.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:ce.error.code}),"card");let U=ce.intent;!ie&&U?.payment_method&&(typeof U.payment_method=="string"?ie=U.payment_method:"id"in U.payment_method&&(ie=U.payment_method.id??void 0))}let x=ie?await Aa(()=>Dp(v,e.threeDSecureToken,{payment_method:ie,return_url:d??Rs(s)??window.location.href},h),"card"):null;if(x){if(x.error)throw Vr(new Ot(x.error.message??"3DS authentication failed.","api_error",{code:x.error.code}),"card");T=x.intent}else{let U=await Aa(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(U.error)throw Vr(new Ot(U.error.message??"3DS authentication failed.","api_error",{code:U.error.code}),"card");T=(h?U.setupIntent:U.paymentIntent)??null}if(T&&(T.status==="requires_capture"||T.status==="succeeded"||T.status==="processing")){let U=await ra({billingApiUrl:a,sessionId:i,session:s,telemetry:g,tokenizedData:{id:T.id,type:"card",threeDSecureActionResultTokenId:T.id},returnUrl:d});return U.type==="success"?{...U.result,paymentIntentId:U.result.paymentIntentId??T.id,paymentMethodId:U.result.paymentMethodId??ie}:U.type==="next_action_required"?na(U,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:w}):ki(U,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:d,telemetry:g,signal:w})}throw Vr(new Ot("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw Vr(new Ot("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:ie}=await Aa(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(ie)throw Vr(new Ot(ie.message??"PayPal authorization failed.","api_error",{code:ie.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:T}=await Aa(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Rs(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(T)throw Vr(new Ot(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ot("Unsupported payment redirect state.","api_error")}function Oa(e){if(e instanceof Ot){let o=Go(e.message);return o&&o!==e.message?Object.assign(new Ot(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=Go(t)??t;return new Ot(n,"api_error")}function Es(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=Ap(e.data.session?.vault)||Po(e.data.session);if(!t&&!n&&!o)throw new Ot("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 Gc(e,t){return e?e.isPaypal?"paypal":"card":t&&Po(t)?"card":void 0}async function _s({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,d]=await Promise.all([Kc(e,{billingApiUrl:n,locale:o,telemetry:a}),i?Kc(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(w=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",w),null)):Promise.resolve(null)]);if(!s)throw new Ot("The payment provider did not initialize.","authentication_error");let g=null;return i?g=d:t&&(g=s),{flopay:s,paypalFlopay:g}}import{PaymentAPI as oa,PciVaultCardCapture as ey,toStripeAppearance as ty}from"@flopay/js";import{buildCheckoutProcessMetadata as ny,buildProcessPaymentAvsAccount as ry,buildWalletSheetWindowMessage as oy,buyerEmailRequiredPrompt as ay,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as iy,COUNTRY_OPTIONS as sy,cardFieldsInstrumentSource as ly,classifyPaymentRejection as cy,clearStripePayPalReturn as dy,computeVaultCardThemeColors as uy,darkenHex as py,denyPaymentPermissionToNewFrames as yy,FloPayError as Ir,filterStripeMethodsByCountryGate as my,getPostalCodeExample as fy,getPostalCodeLabel as Us,getStateFromPostalCode as gy,getStateLabel as As,getStateOptions as hy,getStripeMethodDisplayName as za,hasMatchingStripePayPalReturn as Py,invokeMerchantCallback as id,isAuthorizationOnlySession as xs,isAVSFieldVisible as Xt,isCardFormFirst as vy,isMountableVaultBlock as Cy,isPostalCodeSupported as by,isSettledSessionIntent as Ti,isSetupIntentClientSecret as Fs,isValidEmail as Bn,isValidPostalCode as Sy,isWalletSheetRefusedForWindowSize as wy,keyPaymentMethodOrder as ky,needsStripeMethodExplicitConfirm as sd,normalizeBeforeButtonClickError as ld,normalizeCheckoutFailureOutcome as Ry,partitionStripeMethods as Iy,placePaymentMethodGroups as cd,randomUuidV4 as Ey,readMatchingStripePayPalContinuation as _y,readStripeRedirectParams as bd,resolveAVSConfig as Ty,resolveButtonsLayoutTheme as My,resolveSetupFutureUsage as Sd,resolveTheme as Ay,resolveVaultMountOptions as Bs,STRIPE_PAYPAL_RESUME_KEY as xy,derivePrimaryTileStyle as Fy,shouldPreferWalletPopup as dd,stripeExpressMethodToOptionKey as By,stripeRedirectReturnUrl as wd,toCssWeight as Dy,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as kd}from"@flopay/shared";import{ExpressCheckoutElement as Rd,PaymentElement as Oy,Elements as So,useElements as $s,useStripe as Ws}from"@stripe/react-stripe-js";import Na,{useCallback as Ae,useContext as aa,useEffect as pt,useLayoutEffect as Ly,useMemo as bt,useRef as D,useState as re}from"react";function bo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ri(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{useEffect as Up,useId as zp,useRef as Qc}from"react";import{Fragment as $p,jsx as ed,jsxs as Wp}from"react/jsx-runtime";var td="More payment options",qp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},jp={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Ts({label:e,open:t,showLink:n,onOpen:o,color:a,fontFamily:i,children:s}){let d=zp(),g=Qc(null),w=Qc(!1);return Up(()=>{t&&w.current&&g.current?.focus()},[t]),Wp($p,{children:[!t&&n&&ed("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":d,onClick:()=>{w.current=!0,o()},style:{alignSelf:"center",margin:0,padding:"0.25rem 0",border:0,background:"none",cursor:"pointer",color:a,fontFamily:i,fontSize:"0.9rem",fontWeight:500,textDecoration:"underline",textUnderlineOffset:"0.2em"},children:e}),ed("div",{id:d,ref:g,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?jp:qp,children:s})]})}import{jsx as nd}from"react/jsx-runtime";var Hp=["first","second","third","fourth"];function Ms({rows:e,borderRadius:t}){return nd("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Hp.slice(0,Math.max(1,e)).map(n=>nd("div",{style:{height:ho,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},n))})}import{PaymentAPI as Kp}from"@flopay/js";import{DEFAULT_PAYMENT_METHOD_ORDER as Vp,resolveDefaultPaymentMethodLayout as Gp}from"@flopay/shared";import{useEffect as Yp,useState as Jp}from"react";var Xp=1500,rd=new Set;function od(e){for(let t of e)rd.has(t)||(rd.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function Zp(e){if(e!=null)try{return JSON.stringify(e)}catch{return od(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var Qp={order:[...Vp],moreOptions:[]};function ad({rules:e,sessionId:t,nonce:n,billingApiUrl:o,waitForSession:a}){let i=Zp(e),[s,d]=Jp(null);return Yp(()=>{if(i===void 0||a)return;let g=JSON.parse(i),w=!1,v=ce=>{w||(w=!0,d(ce))},h=()=>v(Gp(g));if(!t||!n||!o){h();return}let T=new AbortController,ie=setTimeout(()=>{h(),T.abort()},Xp);return new Kp(o,{telemetry:!1}).resolvePaymentMethodLayout(t,n,g,{signal:T.signal}).then(ce=>{if(!ce){h();return}w||od(ce.warnings),v({order:ce.order,moreOptions:ce.moreOptions})}).catch(h).finally(()=>clearTimeout(ie)),()=>{w=!0,clearTimeout(ie),T.abort()}},[i,t,n,o,a]),i===void 0?Qp:s}import{darkenHex as Ad}from"@flopay/shared";import{Fragment as qn,jsx as c,jsxs as De}from"react/jsx-runtime";var Lr="flopay_stripe_resume",ud="flopay_wallet_resume",Id="fw1",Ny="fw2",Ed=300*1e3,Uy=900,zy="express_checkout_click_timeout",qy=25e3,jy=25e3,$y=1e4,Er={provider:"paypal",paymentMethodCategory:"paypal"},Wy="x-flopay-process-result-source",Hy="status";async function Ky(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 Ii={},Ua=class{constructor(t){this.reason=t}};function Vy(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 Hs(e){return`${Ny}:${e}`}function Ei(e){return sn(Hs(e))}function _i(e,t){if(typeof window>"u")return null;let n=Hs(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>Ed||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Ei(e),null):a}catch{return Ei(e),null}}function Gy(e){return sn(Hs(e.sessionId),e)}function pd(e,t,n){let o=_i(e,t);return!o||o.clientSecret!==n?!1:Ei(e)}function Ds(e,t,n){if(typeof window>"u")return;_i(e,t)?.clientSecret===n&&Ei(e)}function Yy(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Os(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let o=n?e.status==="succeeded":wa(e.status),a=Yy(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function yd(e,t,n){let o=null;try{return await Promise.race([hc(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},$y),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function Jy(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function _d(e){return e instanceof Ir&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Mi(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new oa(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw _d(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var Ls=xy,La=new Map,Xy=250,md="Just a moment \u2014 we are finalizing your order. Please press pay again.",Zy="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Ks(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 Ai({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new oa(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function Qy(e){return e instanceof Ir&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Td({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=Ra(n),s=i.firstName?i:Ra(o?.name);return Rr({email:Bn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function em({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=Td({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return Bn(s.email)?s:i(a,s)}var qa=180,fd=`flopay-card-enter ${qa}ms cubic-bezier(0, 0, 0.2, 1) both`,gd=`flopay-card-exit ${qa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,tm=`flopay-buttons-enter ${qa}ms cubic-bezier(0, 0, 0.2, 1) both`,nm=`flopay-buttons-exit ${qa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function rm(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Vs(e){return Fy(e)}var om={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function am(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var zs={width:"100%",minHeight:ho,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 hd(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function qs(e){return e==="paypal"?"PayPal":za(e)}function im(e){let t=fy(e);return`Enter a valid ${Us(e)}${t?` (e.g. ${t})`:""}`}function sm(e,t,n){let o=by(e),a=t.trim(),i=n&&o,s=i&&!a,d=i&&!!a&&!Sy(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:d}}function lm(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!Bn(n);return{required:t,empty:o,malformed:a,value:n}}function cm(e){return typeof e=="number"?`${e}px`:e}var dm=["number","expiry","cvv","name"];function um(e){if(e===null||typeof e!="object")return null;let t={};for(let n of dm){let o=e[n];typeof o=="string"&&(t[n]=o)}return JSON.stringify(t)}function Gs(e){return c(mm,{...e})}function Pd({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:d,onDecline:g,onTechnicalFailure:w,runBeforeButtonClick:v,billingName:h,onBuyerIdentityReady:T,onLoadStateChange:ie,placeholderBorderRadius:ce,popupCapabilityOwner:x,externalTelemetryContext:U,presentationMode:C}){let me=ao(),{emitInstrument:de}=aa(yr),S=Ws(),Ye=$s(),$=bt(()=>Ri(bn(me),U),[U,me]),[Oe,st]=re("loading");pt(()=>{ie?.(Oe)},[Oe,ie]);let[yt,we]=re(!1),zt=D(!1),Nt=!Bn(n?.trim())||!h?.trim(),{request:be,collect:tt,finish:lt}=Yo(),ct=D(!1),ke=D(null),Z=D(null),[ue,Ht]=re(0),[je,dt]=re(!1),Q=D(!1),_e=D(new Map),{startAttempt:rt,finishAttempt:z,invalidateAttempt:Mt,isAttemptInvalidated:ve,isAttemptCurrent:Je,generationRef:xe}=_a((Pe,Ce,Fe)=>{w?.(Pe,Ce,{...Fe,popupBlocked:Fe?.popupBlocked??no(Ce),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:C,terminalReason:"overlay_timeout"}),dt(!0),Ht(ut=>ut+1)},{onHandoffObserved:()=>{x.markAvailable(),$?.log({name:"provider.popup.opened",stage:"overlay_open",...Er,attempt:xe.current})}});pt(()=>{je&&Z.current?.focus()},[je,ue]);let We=Ae(()=>{Ht(Pe=>Pe+1)},[]),At=Ae((Pe,Ce,Fe)=>{Mt(Fe),w?.("paypal",Pe,{code:Ce,popupBlocked:no(Pe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:C}),dt(!0),We()},[Mt,w,C,We]),fe=Ae(()=>{window.setTimeout(()=>{(ke.current?.querySelector("iframe")??ke.current)?.focus()},0)},[]);pt(()=>{Q.current&&(Q.current=!1,fe())},[fe,ue]);let Le=Ae(()=>{dt(!1),i?.(null),fe()},[fe,i]);pt(()=>{if(!S||ct.current)return;let[Pe,Ce,Fe]=bd();if(!Pe||!Ce)return;let ut=_y(Ce);if(!ut)return;ct.current=!0;let Xe=!0,ft=La.get(Ce);ft||(ft=Fe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>S.retrievePaymentIntent(Ce)),La.set(Ce,ft));let xt={accountPatch:ut.accountPatch,sessionId:ut.sessionId,nonce:ut.nonce},$e=()=>{$?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Er,requestCategory:"provider_sdk"})};return $?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Er}),(async()=>{try{we(!0);let V=await ft;if(!Xe)return;if(V?.error){La.delete(Ce),$e(),i?.(V.error.message??"Failed to retrieve PayPal payment status.");return}if(dy(),La.delete(Ce),Fe==="failed"){let He="PayPal payment was declined. Please try again.";$?.terminal({outcome:"payment_declined",...Er,terminalReason:"provider_declined"}),i?.(He),g?.(Cn("paypal",He));return}let Ft=V?.paymentIntent;if(Ft&&Ft.id!==Pe){$e(),i?.("Failed to match the returned PayPal payment.");return}if(Ft&&(Ft.status==="requires_capture"||Ft.status==="succeeded")){let He=typeof Ft.payment_method=="string"?Ft.payment_method:Ft.payment_method?.id;a({id:He??Ft.id,type:"card",threeDSecureActionResultTokenId:Ft.id,isPaypal:!0},{...xt,presentationMode:"redirect"})}else{let He="PayPal payment was not completed. Please try again.";$?.terminal({outcome:Ft?.status==="canceled"?"payment_cancelled":"payment_declined",...Er,terminalReason:Ft?.status==="canceled"?"cancelled":"provider_declined"}),i?.(He),g?.(Cn("paypal",He))}}catch(V){if(!Xe)return;La.delete(Ce),$e(),i?.(V instanceof Error?V.message:"Failed to complete PayPal payment.")}finally{Xe&&we(!1)}})(),()=>{Xe=!1,ct.current=!1}},[S,a,i,g,$]);let ot=Ae(async(Pe=!1)=>{let Ce=v?await v("paypal"):{proceed:!0};if(!Ce.proceed)return _e.current.delete(ue),!1;let Fe=rt("paypal");return _e.current.set(ue,{generation:Fe,accountPatch:Ce.accountPatch,sessionId:Ce.sessionId,nonce:Ce.nonce}),dt(!1),$?.log({name:`provider.${Pe?"redirect.started":"handoff.requested"}`,stage:Pe?"redirect":"overlay_open",...Er,attempt:Fe}),d?.("paypal"),!0},[d,$,v,rt,ue]),nt=Ae(async Pe=>{if(s||yt||!await ot()){Pe.reject();return}Pe.resolve()},[s,ot,yt]),Rt=Ae(async Pe=>{if(!S||!Ye)return;let Ce=_e.current.get(ue);if(Ce&&!Je(Ce.generation)){_e.current.delete(ue);return}if(!Ce&&ve()||Ce&&!z(Ce.generation))return;Ce||z();let Fe=Ce??null;if(_e.current.delete(ue),!Fe&&v){let Ze=await v("paypal");if(!Ze.proceed){Pe.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Fe={accountPatch:Ze.accountPatch,sessionId:Ze.sessionId,nonce:Ze.nonce}}let ut=Fe?.sessionId??e,Xe=Fe?.nonce??t,ft=await em({event:Pe,prepared:Fe,email:n,billingName:h,methodLabel:"PayPal",collect:tt});if(!ft){Pe.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let xt=ft.email,$e={...Fe?.accountPatch,...Rr(ft,!0)};try{if(we(!0),i?.(null),!ut||!Bn(xt))throw new Error("Missing sessionId or email for PayPal payment");await T?.(ft);let Ze=S.createPaymentMethod,{error:V,paymentMethod:Ft}=await Ze({type:"paypal"});if(V){At(V,"stripe_paypal_create_payment_method_failed",Ce?.generation),Pe.paymentFailed({reason:"fail"});return}let He=await Mi(o,de,ut,Xe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Ft?.id??null,intentKind:"payment"});if(Ti(He)){Pe.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:$e,paymentMethodCategory:"paypal",presentationMode:C,sessionId:ut,nonce:Xe,settledProcessResponse:He.response});return}if(He.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let W=He.clientSecret,f={return_url:wd()};if(Ft?.id&&(f.payment_method=Ft.id),!sn(Ls,{clientSecret:W,sessionId:ut,nonce:Xe,accountPatch:$e})&&C==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:F,paymentIntent:_}=await S.confirmPayment({clientSecret:W,confirmParams:f,redirect:"if_required"});if(F){if(sn(Ls),ai(F)){let y=F.message??"Your payment was declined.";$?.terminal({outcome:"payment_declined",...Er,terminalReason:"provider_declined"}),i?.(y),g?.(Cn("paypal",y,{code:qo(F),declineCode:ys(F)})),await Ai({billingApiUrl:o,sessionId:ut,nonce:Xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:qo(F)??"provider_declined"}})}else At(F,"stripe_paypal_confirm_failed",Ce?.generation);return}sn(Ls);let Ke=typeof _?.payment_method=="string"?_.payment_method:_?.payment_method?.id;a({id:Ke??_?.id,type:"card",threeDSecureActionResultTokenId:_?.id,isPaypal:!0},{accountPatch:$e,paymentMethodCategory:"paypal",presentationMode:C,sessionId:ut,nonce:Xe});return}catch(Ze){At(Ze,"stripe_paypal_failed",Ce?.generation)}finally{we(!1)}},[S,Ye,e,t,n,h,tt,T,o,de,a,i,g,v,At,z,Je,ve,$,C,ue]),H=Ae(async()=>{if(!(zt.current||s||yt||!S||!Ye)){zt.current=!0,we(!0);try{if(!await ot(!0))return;await Rt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{zt.current=!1,we(!1)}}},[Ye,Rt,s,ot,S,yt]),St=C==="redirect"?c("button",{type:"button",disabled:s||yt,onClick:()=>{H()},style:{width:"100%",minHeight:ho,border:"1px solid #d1d5db",borderRadius:ce??8,background:"#ffc439",color:"#111827",cursor:s||yt?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):c(Rd,{onReady:Pe=>st(ms(Pe,["paypal"])),onLoadError:()=>{st("load_error"),Ks($,"paypal","paypal","provider_error")},onClick:nt,onConfirm:Rt,onCancel:()=>{let Pe=_e.current.get(ue);_e.current.delete(ue),$?.terminal({outcome:"payment_cancelled",...Er,terminalReason:"cancelled",...Pe?{attempt:Pe.generation}:{}}),Mt(Pe?.generation),dt(!1),Q.current=!0,We()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Nt,emailRequired:Nt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ue),Kt=De(qn,{children:[De("div",{ref:ke,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[je&&c("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Le,style:zs,children:"Try PayPal again"}),be&&c(Jo,{identity:be.identity,methodLabel:be.methodLabel,onComplete:lt,onCancel:()=>lt(null)},be.id),c("div",{style:{display:be?"none":void 0},children:St})]}),yt&&!be&&c(Dr,{status:"processing"})]});return C==="redirect"?Kt:c(fs,{state:Oe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:ce,children:Kt})}function Ns(e){return e==="apple_pay"||e==="google_pay"}var pm=200;function ym({active:e}){return Ly(()=>e?yy(document):void 0,[e]),null}function vd({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:d,onButtonClick:g,onDecline:w,onTechnicalFailure:v,runBeforeButtonClick:h,billingName:T,onBuyerIdentityReady:ie,onLoadStateChange:ce,placeholderBorderRadius:x,popupCapabilityOwner:U,externalTelemetryContext:C}){let me=ao(),{emitInstrument:de}=aa(yr),S=Ws(),Ye=$s(),$=bt(()=>Ri(bn(me),C),[C,me]),[Oe,st]=re("loading");pt(()=>{ce?.(Oe)},[Oe,ce]);let[yt,we]=re(!1);pt(()=>{dt.current=yt},[yt]);let zt=D(!Bn(n?.trim())||!T?.trim()).current,{request:Nt,collect:be,finish:tt}=Yo(),lt=D(null),ct=D(null),[ke,Z]=re(0),[ue,Ht]=re(()=>dd()),je=D(ue),dt=D(!1),[Q,_e]=re(!1),[rt,z]=re(()=>_i(e,t)?"blocked":"idle"),[Mt,ve]=re("google_pay"),Je=D(null),xe=D(!0),We=D(!1),At=D("google_pay"),fe=D("google_pay"),Le=D(null),ot=D(null),nt=D(new Set),Rt=D(null),H=D(null);pt(()=>(xe.current=!0,()=>{xe.current=!1;for(let y of nt.current)window.clearTimeout(y);nt.current.clear()}),[]);let St=D(new Map),{startAttempt:Kt,finishAttempt:Pe,invalidateAttempt:Ce,isAttemptInvalidated:Fe,isAttemptCurrent:ut,generationRef:Xe}=_a((y,ge,G)=>{v?.(y,ge,{...G,popupBlocked:G?.popupBlocked??no(ge),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ve(y),_e(!0),Z(q=>q+1)},{onHandoffObserved:y=>{H.current=Xe.current,U.markAvailable(),$?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Xe.current,...y==="apple_pay"||y==="google_pay"?{walletType:y}:{}})},defersMissingTerminal:Ns,onMissingTerminalDeferred:(y,ge)=>{let G=$?.now()??globalThis.performance?.now()??Date.now(),q=Rt.current,X=q?.generation===ge?q.startedAt:G;$?.performance({stage:"overlay_return",durationMs:Math.max(0,G-X),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:ge,...Ns(y)?{walletType:y}:{}}),$?.flush?.().catch(()=>{})}});pt(()=>{Q&&ct.current?.focus()},[Q,ke]);let ft=D(0),xt=D(!1),$e=Ae(()=>{if(ft.current>0){xt.current=!0;return}Z(y=>y+1)},[]),Ze=Ae(()=>{ft.current-=1,!(ft.current>0||!xt.current)&&(xt.current=!1,xe.current&&Z(y=>y+1))},[]),V=Ae((y,ge,G,q,X=!1)=>{Ce(q),v?.(y,ge,{code:G,popupBlocked:no(ge),telemetryReported:X,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ve(y),_e(!0),$e()},[Ce,v,$e]),Ft=Ae(y=>{$?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...Ns(y)?{walletType:y}:{}}),v?.(y,new Error("The wallet click was not ready within the time the wallet allows."),{code:zy,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ve(y),_e(!0)},[v,$]),He=Ae(()=>{window.setTimeout(()=>{(lt.current?.querySelector("iframe")??lt.current)?.focus()},0)},[]);pt(()=>{We.current&&(We.current=!1,He())},[He,ke]);let W=Ae(()=>{_e(!1),d?.(null),He()},[He,d]),f=Ae(()=>{Je.current?.()},[]);pt(()=>{let y=null,ge=()=>{y=null;let q=dd();q!==je.current&&(je.current=q,Ht(q),!dt.current&&!ut(Xe.current)&&$e())},G=()=>{y!==null&&window.clearTimeout(y),y=window.setTimeout(ge,pm)};return window.addEventListener("resize",G),()=>{window.removeEventListener("resize",G),y!==null&&window.clearTimeout(y)}},[Xe,ut,$e]),pt(()=>{let y=_i(e,t);if(!y)return;let ge=!1,G=!1,q=async()=>{if(!G){G=!0,ge||z("checking");try{let X=await yd(S,y.clientSecret,nt.current);if(ge)return;let k=Os(X,y.providerObjectId,Fs(y.clientSecret));if(k.kind==="confirmed"){if(!pd(e,t,y.clientSecret))return;Je.current=null,z("idle"),s({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.intentId},{...y.accountPatch?{accountPatch:y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(k.kind==="terminal"){Ds(e,t,y.clientSecret),Je.current=null,z("idle"),ve(y.paymentMethodType),_e(!0),$e();return}z("blocked")}catch{ge||z("blocked")}finally{G=!1}}};return Je.current=q,z("blocked"),()=>{ge=!0,Je.current===q&&(Je.current=null)}},[t,s,$e,e,S]);let O=Ae(async y=>{let ge=!1,G=!1,q=et=>{ge||G||(ge=!0,y.paymentFailed({reason:"fail",...et?{message:et}:{}}))};if(!S||!Ye){q();return}let X=St.current.get(ke);if(X&&!ut(X.generation)){St.current.delete(ke),q();return}if(!X&&Fe()){q();return}if(X&&!Pe(X.generation)){q();return}X||(Pe(),xt.current=!1);let k=y.expressPaymentType??X?.method??At.current,It=X??null,Ln=hd(k),Qe;k==="apple_pay"?Qe="apple_pay":k==="google_pay"&&(Qe="google_pay");let Qn=X?.generation??Xe.current,Ve=$,mn=Ve?.now()??globalThis.performance?.now()??Date.now(),gt=new AbortController,wn=!1,fn=!1,Vt=null,jn=e,kn="processing",Mn="other",er="provider_runtime",Rn,Bt=new Promise((et,Ne)=>{Rn=Ne}),gn=window.setTimeout(()=>{wn=!0,gt.abort(),Rn(Ii)},qy),mt=async(et,Ne,tr)=>{kn=et,Mn=Ne,er=Ne==="intent_create"||Ne==="session_claim"?"transport_error":"provider_runtime";let ln=Ve?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([tr,Bt])}finally{let An=Ve?.now()??globalThis.performance?.now()??Date.now();Ve?.performance({stage:et,durationMs:Math.max(0,An-ln),durationMode:"machine",requestCategory:Ne,paymentMethodCategory:"wallet",provider:"stripe",...wn?{statusClass:"timeout"}:{}})}};try{if(we(!0),d?.(null),!It&&h){let L=await mt("processing","other",h(Ln));if(!L.proceed){q();return}It={accountPatch:L.accountPatch,sessionId:L.sessionId,nonce:L.nonce}}let et=It?.sessionId??e;jn=et;let Ne=It?.nonce??t,tr=Le.current??It?.accountPatch,ln=Td({event:y,fallbackEmail:tr?.email??n,fallbackName:[tr?.firstName,tr?.lastName].join(" ").trim()||T});if(!Bn(ln.email)){q("Buyer details are required."),be(qs(k),ln).then(L=>{L&&(Le.current=L)});return}Le.current=null;let An={...It?.accountPatch,...Rr(ln,!0)};await mt("processing","session_claim",Promise.resolve(ie?.(ln)));let{error:gr}=await mt("tokenization","provider_sdk",Ye.submit());if(gr){q(),V(k,gr,"stripe_wallet_submit_failed",X?.generation);return}if(!et)throw new Error("Missing sessionId or email for payment.");let nr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,paymentMethodId:null,intentKind:a},xn=JSON.stringify({sessionId:et,nonce:Ne??"",request:nr}),rr=ot.current,or=rr?.retryIdentity===xn?rr.authorizationAttemptId:Ey();ot.current={authorizationAttemptId:or,retryIdentity:xn};let cn=await mt("processing","intent_create",Mi(o,de,et,Ne??"",{...nr,authorizationAttemptId:or},{signal:gt.signal}));if(Ti(cn)){q(),s({type:"card",paymentMethodType:k},{accountPatch:An,paymentMethodCategory:"wallet",sessionId:et,nonce:Ne,settledProcessResponse:cn.response});return}if(cn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Qt=cn.clientSecret,Gn=Gy({createdAt:Date.now(),sessionId:et,...Ne?{nonce:Ne}:{},clientSecret:Qt,providerObjectId:cn.providerObjectId,paymentMethodType:k,accountPatch:An});window.clearTimeout(gn),fn=!0,Ve?.performance({stage:"callback",durationMs:Math.max(0,(Ve?.now()??globalThis.performance?.now()??Date.now())-mn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let $n=Ve?.now()??globalThis.performance?.now()??Date.now(),en={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Qe?{walletType:Qe}:{},attempt:Qn},Yt=!1,hn=null;Ve?.log({name:"payment.provider_confirmation.started",...en}),Vt=window.setTimeout(()=>{Vt!==null&&nt.current.delete(Vt),Yt=!0;let L=Ve?.now()??globalThis.performance?.now()??Date.now();Ve?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...en,operationOutcome:"watchdog_expired",durationMs:Math.max(0,L-$n),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),Ve?.flush?.().catch(()=>{}),hn?.()},jy),nt.current.add(Vt);let Fn=(L,Et)=>{Vt!==null&&(window.clearTimeout(Vt),nt.current.delete(Vt),Vt=null);let Pt=Ve?.now()??globalThis.performance?.now()??Date.now(),tn=Math.max(0,Pt-$n),Ie=L;Yt&&(L==="resolved"?Ie="resolved_late":L==="returned_error"?Ie="returned_error_late":Ie="rejected_late");let un=Et??(L==="resolved"?"approved":"provider_error");return Ve?.log({name:"payment.provider_confirmation.returned",...en,operationOutcome:Ie,terminalReason:un}),Ve?.performance({...en,durationMs:tn,durationMode:"buyer",operationOutcome:Ie,terminalReason:un}),{durationMs:tn,operationOutcome:Ie,terminalReason:un}},dn=!1,Pn=!1,Nn=L=>{if(!L||typeof L!="object")return null;let Et=L;if(Et.error)return null;let Pt=Et.setupIntent??Et.paymentIntent,tn=Os(Pt??null,void 0,!!Et.setupIntent);return tn.kind==="confirmed"?tn:null},In=L=>{if(dn||X&&Xe.current!==X.generation)return;let Et=Nn(L);if(!Et)return;if(Gn&&!pd(et,Ne,Qt)){dn=!0;return}let{intentId:Pt,paymentMethodId:tn}=Et;dn=!0,Pn=!0,ot.current=null,Je.current=null,xe.current&&(z("idle"),we(!1));let Ie=`${Id}:${et}`;sn(Ie,{createdAt:Date.now(),sessionId:et,nonce:Ne,accountPatch:An,paymentMethodId:tn,providerIntentId:Pt,paymentMethodType:k});try{s({id:tn,type:"card",threeDSecureActionResultTokenId:Pt},{accountPatch:An,paymentMethodCategory:"wallet",sessionId:et,nonce:Ne})}finally{sn(Ie)}},En=!1;hn=async()=>{if(!(En||dn||Pn)){En=!0,xe.current&&z("checking");try{let L=await yd(S,Qt,nt.current);if(dn||Pn)return;let Et=Fs(Qt),Pt=Os(L,cn.providerObjectId,Et);if(Pt.kind==="confirmed"){In(Et?{setupIntent:L}:{paymentIntent:L});return}if(Pt.kind==="terminal"){if(Pn=!0,Ds(et,Ne,Qt),ot.current=null,Je.current=null,!xe.current)return;z("idle"),q(),V(k,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",X?.generation,!0);return}xe.current&&!Pn&&(z("blocked"),we(!1))}catch{xe.current&&!Pn&&(z("blocked"),we(!1))}finally{En=!1}}},Je.current=hn;let u,ht;try{G=!0,ft.current+=1;let L;try{L=await(Fs(Qt)?S.confirmSetup({elements:Ye,clientSecret:Qt,redirect:"if_required"}):S.confirmPayment({elements:Ye,clientSecret:Qt,redirect:"if_required"}))}finally{Ze()}if(!L||typeof L!="object")throw new Ua(Vy(L));if(u=L,!u.error&&!Nn(u))throw new Ua("confirmation_result_unconfirmed");ht=Fn(u.error?"returned_error":"resolved",u.error&&ai(u.error)?"provider_declined":void 0)}catch(L){let Et=L instanceof Ua?L.reason:void 0,Pt=Et!==void 0,tn=Fn(Pt?"returned_error":"rejected");if(Ve?.error({...Pt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Et}:vs(L),...en,operationOutcome:tn.operationOutcome,durationMs:tn.durationMs,statusClass:"unknown",terminalReason:tn.terminalReason}),!xe.current||dn)return;await hn?.();return}let A=u.error;if(A){if(!xe.current||dn)return;if(ai(A)){Pn=!0,Ds(et,Ne,Qt),ot.current=null,Je.current=null,z("idle"),St.current.get(ke)===X&&St.current.delete(ke);let L=A.message??"Your payment was declined.";d?.(L),w?.(Cn(Ln,L,{code:qo(A),declineCode:ys(A)})),Ai({billingApiUrl:o,sessionId:et,nonce:Ne,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,providerDeclineReason:qo(A)??"provider_declined",...cn.intentKind==="payment"&&cn.providerObjectId.startsWith("pi_")?{providerIntentId:cn.providerObjectId}:{}}})}else Ve?.error({...vs(A),...en,operationOutcome:ht.operationOutcome,durationMs:ht.durationMs,statusClass:"unknown",terminalReason:ht.terminalReason}),await hn?.();return}if(In(u),!dn)throw new Error("Invalid provider returned for APM intent")}catch(et){if(et===Ii){let Ne=Ve?.now()??globalThis.performance?.now()??Date.now();Ve?.error({errorCode:Jy(Mn),stage:kn,requestCategory:Mn,paymentMethodCategory:"wallet",provider:"stripe",...Qe?{walletType:Qe}:{},operationOutcome:"watchdog_expired",checkoutSessionId:jn,durationMs:Math.max(0,Ne-mn),statusClass:"timeout",failureCategory:er,attempt:Qn,terminalReason:"provider_error"}),Ve?.flush?.().catch(()=>{})}q(),V(k,et,et===Ii?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",X?.generation,et===Ii)}finally{if(window.clearTimeout(gn),Vt!==null&&(window.clearTimeout(Vt),nt.current.delete(Vt)),!fn){let et=Ve?.now()??globalThis.performance?.now()??Date.now();Ve?.performance({stage:"callback",durationMs:Math.max(0,et-mn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...wn?{statusClass:"timeout"}:{}})}xe.current&&we(!1)}},[S,Ye,e,t,n,T,be,ie,o,de,a,s,d,w,h,V,Ze,Pe,ut,Fe,Xe,$,ke]),F=bt(()=>ec(i),[i]),_=bt(()=>i.map(By),[i]),Ke=bt(()=>c(Rd,{onReady:y=>{st(ms(y,_))},onLoadError:y=>{st("load_error"),Ks($,"stripe","wallet","provider_error")},onClick:async y=>{let ge=$?.now()??globalThis.performance?.now()??Date.now();At.current=y.expressPaymentType,fe.current=hd(y.expressPaymentType);let G=!0,q=window.setTimeout(()=>{G=!1,y.reject(),Ft(y.expressPaymentType)},Uy),X=h?await h(fe.current,{abandoned:()=>!G}):{proceed:!0};if(window.clearTimeout(q),!G)return;if(!X.proceed){St.current.delete(ke),y.reject();return}let k=Kt(y.expressPaymentType);xt.current=!1,Rt.current={generation:k,startedAt:ge},St.current.set(ke,{generation:k,method:y.expressPaymentType,accountPatch:X.accountPatch,sessionId:X.sessionId,nonce:X.nonce}),_e(!1),$?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:k,...y.expressPaymentType==="apple_pay"||y.expressPaymentType==="google_pay"?{walletType:y.expressPaymentType}:{}}),g?.(fe.current),y.resolve()},onConfirm:O,onCancel:()=>{let y=St.current.get(ke);St.current.delete(ke);let ge=Rt.current,G=$?.now()??globalThis.performance?.now()??Date.now();if(y&&ge?.generation===y.generation&&wy({method:y.method,elapsedMs:G-ge.startedAt,handoffObserved:H.current===y.generation})){$?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:y.generation,walletType:"google_pay"}),ot.current=null,V(y.method,new Error("The browser window is too small for the Google Pay sheet."),kd,y.generation,!0);return}$?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...y?{attempt:y.generation}:{}}),Ce(y?.generation),ot.current=null,_e(!1),We.current=!0,$e()},options:{...tc,paymentMethods:F,emailRequired:zt,billingAddressRequired:zt}},ke),[_,F,O,Ce,g,zt,V,Ft,$e,h,Kt,ke,$]);return De(qn,{children:[c(fs,{state:Oe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:x,children:De("div",{ref:lt,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Q&&De("button",{ref:ct,type:"button","data-testid":"flopay-wallet-retry-button",onClick:W,style:zs,children:["Try ",qs(Mt)," again"]}),rt!=="idle"&&De("div",{role:"status","aria-live":"polite",children:[c("p",{children:"We are still confirming your payment. Check its status before trying again."}),c("button",{type:"button",onClick:f,disabled:rt==="checking",style:zs,children:rt==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Nt&&c(Jo,{identity:Nt.identity,methodLabel:Nt.methodLabel,onComplete:tt,onCancel:()=>tt(null)},Nt.id),De("div",{style:{display:Nt||rt!=="idle"?"none":void 0},children:[c(ym,{active:ue}),Ke]})]})}),yt&&c(Dr,{status:"processing"})]})}function Md(e,t,n){let o=Sd(n,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function js({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:d,onErrorChange:g,onDecline:w,onCancel:v,runBeforeButtonClick:h,onButtonClick:T,isProcessing:ie,submitButtonColor:ce,submitButtonBorderRadius:x,submitButtonStyle:U,errorText:C}){let me=ao(),{emitInstrument:de}=aa(yr),S=Ws(),Ye=$s(),[$,Oe]=re(!1),st=D(!1),[yt,we]=re(!1),[zt,Nt]=re("loading"),[be,tt]=re(""),lt=!Bn(o?.trim()),ct=!lt||Bn(be.trim()),ke=Ae(async()=>{if(!S||!Ye||ie||st.current||!yt)return;st.current=!0,Oe(!0);let Z=h?await h("card"):{proceed:!0};if(!Z.proceed){st.current=!1,Oe(!1);return}T?.("card");let ue=Z.sessionId??t,Ht=Z.nonce??n,je=Ra(a?.trim()),dt=Rr({email:Z.accountPatch?.email?.trim()||o?.trim()||be.trim(),firstName:Z.accountPatch?.firstName?.trim()||je.firstName,lastName:Z.accountPatch?.lastName?.trim()||je.lastName}),Q=dt.email,_e=Rr({...Z.accountPatch,...dt});try{if(g?.(null),!Bn(Q))throw new Error("A valid email address is required for payment.");await i?.(dt);let rt=await Ye.submit();if(rt.error){g?.(rt.error.message??"Payment failed.");return}let z=[dt.firstName,dt.lastName].filter(Boolean).join(" "),Mt=await S.createPaymentMethod({elements:Ye,params:{billing_details:{email:Q,...z?{name:z}:{}}}});if(Mt.error||!Mt.paymentMethod){g?.(Mt.error?.message??"Failed to create payment method.");return}let ve=Mt.paymentMethod;if(!ue||!Q)throw new Error("Missing sessionId or email for payment.");let Je=ve.type||e,xe=await Mi(s,de,ue,Ht??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Je,paymentMethodId:null,intentKind:"payment"});if(Ti(xe)){d({type:"card",gateway:"stripe",paymentMethodType:Je},{accountPatch:_e,paymentMethodCategory:"apm",sessionId:ue,nonce:Ht,settledProcessResponse:xe.response});return}if(xe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let We=xe.clientSecret;sn(Lr,{clientSecret:We,sessionId:ue,nonce:Ht,accountPatch:_e,paymentMethodId:ve.id,paymentMethodType:ve.type??e,gateway:"stripe"});let{error:At,paymentIntent:fe}=await S.confirmPayment({clientSecret:We,confirmParams:{return_url:window.location.href,payment_method:ve.id},redirect:"if_required"});if(At){sn(Lr);let nt=At.message??"Payment failed.";g?.(nt),w?.(Cn("card",nt,{code:At.code})),await Ai({billingApiUrl:s,sessionId:ue,nonce:Ht,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:At.code??"provider_declined"}});return}let Le=fe?.status;if(!wa(Le)){sn(Lr);let nt=Le==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(nt),w?.(Cn("card",nt,{code:Le??"missing_payment_intent"}));return}sn(Lr);let ot=typeof fe?.payment_method=="string"?fe.payment_method:fe?.payment_method?.id;d({id:ot??ve.id,type:"card",threeDSecureActionResultTokenId:fe?.id,gateway:"stripe",paymentMethodType:ve.type??e},{accountPatch:_e,paymentMethodCategory:"apm",sessionId:ue,nonce:Ht})}catch(rt){g?.(rt instanceof Error?rt.message:"Payment failed. Please try again.")}finally{st.current=!1,Oe(!1)}},[S,Ye,ie,yt,h,T,t,n,o,a,be,i,s,de,e,d,g,w]);return De("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[lt&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:lt&&De("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:be,onChange:Z=>tt(Z.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(Oy,{onReady:()=>Nt("ready"),onLoadError:()=>{Nt("load_error"),Ks(bn(me),"stripe","apm")},onChange:Z=>{we(!!Z.complete)},options:{layout:nc,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...Bn(o?.trim())?{email:o?.trim()}:{}}}}}),c(rc,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ke()},disabled:!yt||!ct||$||ie||zt!=="ready",color:ce,borderRadius:x,style:U,children:$?"Processing\u2026":`Pay with ${za(e)}`}),C&&c(Qo,{margin:"0.75rem 0 0",children:C})]})}function Cd({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:d,paymentElementBaseOptions:g,futureUseSession:w,onTokenizedBody:v,onErrorChange:h,onButtonClick:T,onDecline:ie,runBeforeButtonClick:ce,onLoadStateChange:x,isProcessing:U=!1,submitButtonColor:C="#4A49FF",submitButtonBorderRadius:me=8,submitButtonStyle:de,buttonAppearance:S,themeId:Ye,onExpandApm:$,expandedApmMethod:Oe}){let{emitInstrument:st}=aa(yr),[yt,we]=re(null),[zt,Nt]=re(null),be=D(!1),{request:tt,collect:lt,finish:ct}=Yo();pt(()=>{s.length>0&&d?x?.("ready"):d||x?.("loading")},[s.length,d,x]);let ke=Ae(async Q=>{if(!d||be.current||U)return;be.current=!0,Nt(Q);let _e=ce?await ce("card"):{proceed:!0};if(!_e.proceed){be.current=!1,Nt(null);return}T?.("card");let rt=_e.sessionId??e,z=_e.nonce??t,Mt=Ra([_e.accountPatch?.firstName,_e.accountPatch?.lastName].filter(Boolean).join(" ")||o),ve=Rr({email:_e.accountPatch?.email?.trim()||n?.trim(),firstName:_e.accountPatch?.firstName?.trim()||Mt.firstName,lastName:_e.accountPatch?.lastName?.trim()||Mt.lastName});if(!Bn(ve.email)){Nt(null);let We=await lt(za(Q),ve);if(!We){be.current=!1;return}ve=We,Nt(Q)}let Je=ve.email,xe=Rr({..._e.accountPatch,...ve});try{if(h?.(null),!rt||!Bn(Je))throw new Error("Missing sessionId or email for payment.");await a?.(ve);let We=await Mi(i,st,rt,z??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if(Ti(We)){v({type:"card",gateway:"stripe",paymentMethodType:Q},{accountPatch:xe,paymentMethodCategory:"apm",sessionId:rt,nonce:z,settledProcessResponse:We.response});return}if(We.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let At=We.clientSecret;sn(Lr,{clientSecret:At,sessionId:rt,nonce:z,accountPatch:xe,paymentMethodType:Q,gateway:"stripe"});let{error:fe,paymentIntent:Le}=await d.confirmPayment({clientSecret:At,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:[ve.firstName,ve.lastName].filter(Boolean).join(" "),...Je?{email:Je}:{}}}},redirect:"if_required"});if(fe){sn(Lr);let Rt=fe.message??"Payment failed.";h?.(Rt),ie?.(Cn("card",Rt,{code:fe.code})),await Ai({billingApiUrl:i,sessionId:rt,nonce:z,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:fe.code??"provider_declined"}});return}let ot=Le?.status;if(!wa(ot)){sn(Lr);let Rt=ot==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(Rt),ie?.(Cn("card",Rt,{code:ot??"missing_payment_intent"}));return}sn(Lr);let nt=typeof Le?.payment_method=="string"?Le.payment_method:Le?.payment_method?.id;v({id:nt??Le?.id,type:"card",threeDSecureActionResultTokenId:Le?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:xe,paymentMethodCategory:"apm",sessionId:rt,nonce:z})}catch(We){h?.(We instanceof Error?We.message:"Payment failed. Please try again.")}finally{be.current=!1,Nt(null)}},[d,U,ce,T,e,t,n,lt,i,st,o,a,v,h,ie]),[Z,ue]=re(null),Ht=$?Oe??null:Z,je=Ae(Q=>{be.current||U||Ht&&Ht!==Q||(sd(Q)?$?$(Q):ue(Q):ke(Q))},[Ht,U,ke,$]),dt=bt(()=>Z?Md(g,Z,w):null,[Z,g,w]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:tt?c(Jo,{identity:tt.identity,methodLabel:tt.methodLabel,onComplete:ct,onCancel:()=>ct(null)},tt.id):s.map(Q=>{let _e=Oe===Q,rt=zt===Q,z=zt!==null&&zt!==Q||Oe!=null&&Oe!==Q;return De(Na.Fragment,{children:[c(Ql,{method:Q,themeId:Ye,submitting:rt,disabled:z,highlighted:_e,hasNextStep:sd(Q),onClick:()=>je(Q),backgroundColor:S?.backgroundColor,borderColor:S?.borderColor,textColor:S?.textColor,borderRadius:S?.borderRadius,fontFamily:S?.fontFamily}),!$&&Z===Q&&dt&&d&&c(So,{stripe:d,options:dt,children:c(js,{method:Q,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:v,onErrorChange:h,onDecline:ie,onCancel:()=>ue(null),runBeforeButtonClick:ce,onButtonClick:T,isProcessing:U,submitButtonColor:C,submitButtonBorderRadius:me,submitButtonStyle:de})},Q)]},Q)})})}function mm({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:d,onDecline:g,onCancel:w,onTokenizedBody:v,firstName:h,lastName:T,chv:ie,className:ce,submitLabel:x,isProcessing:U,error:C,onErrorChange:me,showPayPal:de=!0,showStripe:S=!0,walletPresentation:Ye="auto",enabledPaymentMethods:$,enabledPaymentMethodCountries:Oe,showApplePay:st=!0,showGooglePay:yt=!0,layout:we="default",paymentMethodLayout:zt,moreOptionsLabel:Nt,theme:be,buttonsTheme:tt,buttonsStyles:lt,appearance:ct,cardButtonContent:ke,cardBackButtonContent:Z,cardTitleContent:ue,showSecurityFooter:Ht,onButtonClick:je,onBeforeButtonClick:dt,onBuyerIdentityReady:Q,enableAVS:_e,cardFieldOrder:rt,showCardBrandIcons:z,cardFieldPlaceholders:Mt,cardAutoFocus:ve,onCardFieldsReady:Je,onCardFieldsFailed:xe,cardFieldsTimeoutMs:We,cardPreFormSlot:At,avsLayout:fe="row",country:Le,zip:ot,addressLine1:nt,addressLine2:Rt,city:H,state:St,onCountryChange:Kt,onZipChange:Pe,avsCheck:Ce,checkoutType:Fe,checkoutLayout:ut,totalAmount:Xe=0,currency:ft="usd",initialCardOpen:xt=!1,directPaypal:$e,isSubscription:Ze=!1,session:V,dataAttachmentPending:Ft=!1,dataAttachmentRequiresIdentity:He=!1,debug:W=!1}){let f=ao(),O=Cs(),F=aa(kr),{emitInstrument:_}=aa(yr),Ke=D(null);Ke.current||(Ke.current=pi());let y=Ke.current,[,ge]=re(0),G=D(null);G.current||(G.current=Ca());let q=G.current,X=bt(()=>({browser:q,capability:y,presentationMode:"popup"}),[q,y]),k=V??F.session,It=bt(()=>({futureUse:k?.futureUse,futureUseUnsupported:k?.futureUseUnsupported}),[k?.futureUse,k?.futureUseUnsupported]),Ln=k?.gateways?.paypal?.providerObjectType??$e?.providerObjectType,Qe=Ft||F.claimPending===!0,Qn=He||F.claimRequiresIdentity===!0,Ve=Qe&&!Qn,mn=Rc(),gt=n||mn,wn=ad({rules:zt,sessionId:e,nonce:t,billingApiUrl:gt,waitForSession:Ve}),fn=wn?.order??null,[Vt,jn]=re(!1),kn=bt(()=>fn?ky(fn):null,[fn]),Mn=fn!==null&&vy(fn),[er,Rn]=re(!1),[Bt,gn]=re(null),[mt,et]=re(Le??""),[Ne,tr]=re(ot??""),[ln,An]=re(nt??""),[gr,nr]=re(Rt??""),[xn,rr]=re(H??""),[or,cn]=re(St??""),[Qt,Gn]=re(""),[$n,en]=re({}),Yt=D(ot??""),hn=D(Le??""),Fn=D(nt??""),dn=D(Rt??""),Pn=D(H??""),Nn=D(St??""),In=D(""),En=D({});pt(()=>{let r=(m,R,J,M,ye)=>{if(En.current[m])return;let _t=R?.trim();!_t||_t===J.current||(J.current=_t,M(_t),ye?.(_t))};r("country",Le,hn,et,Kt),r("zip",ot,Yt,tr,Pe),r("addressLine1",nt,Fn,An),r("addressLine2",Rt,dn,nr),r("city",H,Pn,rr),r("state",St,Nn,cn)},[Le,ot,nt,Rt,H,St,Kt,Pe]);let u=bt(()=>Ty(_e),[_e]),ht=u!==null,A=bt(()=>xs(V),[V]),L=Cy(V?.vault),Et=!!V?.gateways?.pcivault,Pt=vc(V),Ie=!!(V?.gateways?.stripe?.enabledPaymentMethods??$)?.includes("card")||Po(V),un=L||Ie||Et,Ee=!!(S&&un&&e),[zr,Gr]=re(()=>we!=="buttons"||xt?e??null:null),[Io,hr]=re(0),ar=we!=="buttons"||xt||!!e&&zr===e,Yn=V?.captureMethod,Wn=D(f);pt(()=>{Wn.current=f},[f]);let nn=D(We);nn.current=We;let Pr=D({onCardFieldsReady:Je,onCardFieldsFailed:xe,emitInstrument:_});Pr.current={onCardFieldsReady:Je,onCardFieldsFailed:xe,emitInstrument:_};let[vn,Tr]=re(null);pt(()=>{if(!Ee||!e||!ar){Tr(null);return}let r=Wn.current?Wn.current.cardCapture({sessionId:e,captureMethod:Yn,cardFieldsTimeoutMs:nn.current}):new ey({sessionId:e,captureMethod:Yn,billingApiUrl:gt,telemetry:o,cardFieldsTimeoutMs:nn.current}),m=r.onCardFields?.(R=>{let J=Pr.current;J.emitInstrument?.(ly(R)),R.type==="card_fields_ready"?id(()=>J.onCardFieldsReady?.(R)):id(()=>J.onCardFieldsFailed?.(R))});return Tr({sessionId:e,captureMethod:Yn,billingApiUrl:gt,telemetry:o,capture:r}),()=>{m?.(),r.unmount()}},[Ee,e,ar,Yn,gt,o]);let Ge=Ee&&e&&ar&&vn?.sessionId===e&&vn.captureMethod===Yn&&vn.billingApiUrl===gt&&vn.telemetry===o?vn.capture:null,Dn=bt(()=>{let r=mt,m=u?Xt(u.postal_code,r):!1;return sm(r,Ne,m)},[u,mt,Ne]),{avsInvalid:vr,invalidAvsFields:qr}=bt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!Ee||!u)return{avsInvalid:!1,invalidAvsFields:r};let m=mt,R=(ye,_t)=>Xt(ye,m)&&!_t.trim(),J={line1:R(u.address_line_1,ln),city:R(u.city,xn),state:R(u.state,or),zip:Dn.empty||Dn.malformed};return{avsInvalid:J.line1||J.city||J.state||J.zip,invalidAvsFields:J}},[Ee,u,mt,ln,xn,or,Dn]),[Jn,ir]=re(!1),[Yr,Jr]=re(!1),[sr,jr]=re(!1),[Eo,la]=re({line1:!1,city:!1,state:!1}),lr=D(!1),Mr=D({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Xr=D(!1),wt=Ae(r=>{Mr.current[r]=!0,Xr.current=!0},[]),Ar=Ae(r=>!lr.current&&Mr.current[r],[]),cr=Ae(r=>{Ar(r)&&la(m=>m[r]?m:{...m,[r]:!0})},[Ar]),[Cr,Un]=re(()=>Bs(V?.vault,{billingApiUrl:gt,sessionId:e,nonce:t})),[Ue,rn]=re(xt&&un?"card":"buttons"),[qt,b]=re(null),I=Ue==="expanding"||Ue==="card",B=V?.gateways?.stripe&&!Pt?"stripe":void 0,Y=Ae(()=>{_?.({class:"card_surface",provider:B})},[B,_]),kt=Ae(()=>{jn(!0),_?.({class:"more_options"})},[_]),Gt=D(null),se=Ae(r=>{Gt.current&&clearTimeout(Gt.current),Gt.current=setTimeout(()=>{Gt.current=null,r()},qa)},[]);pt(()=>()=>{Gt.current&&clearTimeout(Gt.current)},[]);let ze=D(!1),[E,Re]=re(0),ee=D(null),p=Ae(()=>{Y(),Gr(e??null),ze.current&&(ze.current=!1,Re(r=>r+1)),hr(r=>r+1),rn("expanding"),se(()=>rn("card"))},[se,Y,e]),l=Ae(()=>{rn("collapsing"),se(()=>rn("buttons"))},[se]),P=Ae(r=>{b(r),rn("apm-expanding"),se(()=>rn("apm-form"))},[se]),te=Ae(()=>{rn("apm-collapsing"),se(()=>{rn("buttons"),b(null)})},[se]);pt(()=>{we==="buttons"&&xt&&un&&(Gr(e??null),rn("card"))},[we,xt,un,e]);let[oe,N]=re(null),ae=D(null),[ne,Dt]=re(0);pt(()=>{ne!==0&&ae.current?.focus()},[ne]);let Ut=D(!1),qe=D(null),j=D("idle"),[K,Se]=re(!1),Te=D(K);Te.current=K;let[pe,Hn]=re(()=>$e?.existingOrderId?{orderId:$e.existingOrderId,attempts:1}:null),$t=D(pe);pt(()=>{$t.current=pe},[pe]);let _o=D(null),Yd=bt(()=>{if(Q||F.claimBuyerIdentity||V?.buyerIdentified!==!1||!e||!t)return;let r=`${gt}|${e}|${t}`;_o.current?.key!==r&&(_o.current={key:r,claim:Ko(new oa(gt,{telemetry:!1}),e,t,{...i?{userId:i}:{},...h?{firstName:h}:{},...T?{lastName:T}:{}})});let m=_o.current.claim;return async R=>{await m(R)}},[Q,F.claimBuyerIdentity,V?.buyerIdentified,e,t,gt,i,h,T]),dr=Q??F.claimBuyerIdentity??Yd,br=C??Bt,To=bt(()=>Ay(be),[be]),Me=bt(()=>{let r=To?.buttonsLayout??My(tt);return lt?{...r,...lt,cardButton:{...r.cardButton,...lt.cardButton},cardFormContainer:{...r.cardFormContainer,...lt.cardFormContainer},backButton:{...r.backButton,...lt.backButton},backButtonIcon:{...r.backButtonIcon,...lt.backButtonIcon},submitButton:{...r.submitButton,...lt.submitButton},title:{...r.title,...lt.title}}:r},[To,tt,lt]),Mo=ct??To?.appearance,Jd=bt(()=>uy({appearance:Mo,buttonsStyles:Me,layout:we}),[Mo,Me,we]),Xd=F.inlineSessionPatchProcessing??!1,on=(U??er)||Xd,Zr=gt.replace(/\/+$/,""),vt=bt(()=>Ps({userId:i,email:a,firstName:h,lastName:T,country:Le,zip:ot},$n),[i,a,h,T,Le,ot,$n]),Ao=[vt.firstName,vt.lastName].filter(r=>!!r?.trim()).join(" "),al=!Bn(vt.email?.trim()),Li=D(null);Ee&&Li.current===null&&(Li.current=al);let Qr=Ee&&(Li.current??al),Ni=bt(()=>lm(Qt,Qr),[Qt,Qr]),xo=Ni.empty||Ni.malformed,Xn=bt(()=>f?f.getRawProvider():null,[f]),il=bt(()=>O?O.getRawProvider():null,[O]),ca=Xe||100,Fo=ft.toLowerCase(),Ui=bt(()=>Mo?ty(Mo):null,[Mo]),Bo=Ui,sl=bt(()=>{let r=Ui??{},m=r.rules??{};return{...r,rules:{...m,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...m[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...m[".AccordionItemContents"]??{}}}}},[Ui]),ll=bt(()=>({...Pc(Xe,k?.captureMethod,It),currency:Fo,...Bo?{appearance:Bo}:null}),[Xe,Fo,k?.captureMethod,It,Bo]),zi=Sd(It,"paypal","paypal"),cl=bt(()=>({mode:"payment",amount:ca,currency:Fo,captureMethod:"manual",...zi?{setupFutureUsage:zi}:null,...Bo?{appearance:Bo}:null}),[ca,Fo,zi,Bo]),he=Ae(r=>{gn(r),me?.(r)},[me]),dl=D(0);pt(()=>{E!==dl.current&&(dl.current=E,he(null))},[E,he]);let qi=D(""),[ul,Zd]=re(!1),ji=Ae(()=>{Zd(!0)},[]);pt(()=>{if(!Ee||!Qr||!dr||!ul||xo||qi.current)return;let r=Rr({email:Bn(vt.email?.trim())?vt.email?.trim():In.current.trim(),firstName:vt.firstName?.trim(),lastName:vt.lastName?.trim()});qi.current=JSON.stringify(r),en(m=>({...m,...r})),Promise.resolve(dr(r)).catch(m=>{qi.current="",he(m instanceof Error?m.message:"Failed to attach buyer details.")})},[Ee,Qr,dr,ul,xo,vt.email,vt.firstName,vt.lastName,he]),pt(()=>{if(!Ee||!Ge)return;let r=ve!==!1&&u==null&&!Qr;Ge.setCardFieldOrder?.(rt??null,r)},[Ee,Ge,rt,ve,u,Qr]),pt(()=>{!Ee||!Ge||Ge.setCardBrandIcons?.(z===!0)},[Ee,Ge,z]);let $i=um(Mt),Wi=D(null);pt(()=>{if(!(!Ee||!Ge)){if($i===null){if(Wi.current!==Ge)return;Wi.current=null,Ge.setCardFieldPlaceholders?.(void 0);return}Wi.current=Ge,Ge.setCardFieldPlaceholders?.(JSON.parse($i))}},[Ee,Ge,$i]),pt(()=>{(Ue==="expanding"||Ue==="collapsing"||Ue==="apm-expanding"||Ue==="apm-collapsing")&&he(null)},[Ue,he]);let xr=Ae((r,m,R)=>{g?.(Cn(r,m,R))},[g]),pl=D(Ue);pl.current=Ue;let[yl]=re(mi),ml=Ae(()=>{let r=pl.current;if(we==="buttons"&&(r==="card"||r==="expanding"))return!0;let m=j.current;return m==="validation-window"||m==="processing"||Te.current},[we]),fl=Ae((r,m,R)=>{yl.take(e)&&bn(f)?.log(bo({...X,presentationMode:R?.presentationMode??"popup"},{name:yi,stage:"recovery",reason:"other_method_active",provider:R?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:R?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[X,f,yl,e]),Ha=Ae((r,m,R)=>{R?.telemetryReported||bn(f)?.error(bo({...X,presentationMode:R?.presentationMode??"popup"},{errorCode:m?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:R?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:R?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:R?.terminalReason??(m?"popup_blocked":"provider_error")}))},[X,f]),Do=Ae((r,m,R)=>{let J=R?.popupBlocked??no(m);if(ml()){Ha(r,J,R),fl(r,m,R);return}if(m instanceof Ir&&m.code==="checkout_processing_timeout"){Ha(r,!1,R),N(null),we==="buttons"&&(rn("buttons"),b(null)),he(m.message),d?.(m);return}J&&y.markBlocked()&&ge(at=>at+1);let M=qs(r),ye=R?.code===kd?oy(M):oi(M,J,q.inAppBrowser),_t=qo(m),Tt=(_t?.toLowerCase()==="error"?void 0:_t)??Xl(R?.code)??"external_payment_method_failed",Be=new Ir(ye,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:Tt,popupBlocked:J,inAppBrowser:q.inAppBrowser,appFamily:q.appFamily,popupCapability:y.current(),presentationMode:R?.presentationMode??"popup"}});Ha(r,J,R),N(null),we==="buttons"&&(rn("buttons"),b(null)),he(ye),d?.(Be),console.error("[FloPay] External payment method failed:",{method:r,code:Tt,popupBlocked:J})},[q,ml,we,d,y,fl,Ha,he]);pt(()=>{if(!Ee||!e){Un(null);return}let r={billingApiUrl:Zr,sessionId:e,nonce:t},m=Bs(V?.vault,r);if(m){Un(m);return}if(!ar){Un(null);return}let R=`${Zr}\0${e}\0${t??""}`,J=ee.current;if(J&&J.key===R){Un(J.mount);return}Un(null);let M=!0;return new oa(Zr).getVaultCapture(e,t).then(ye=>{if(!M)return;let _t=Bs(ye,r);_t?.verificationRequired&&!ye.html&&(ee.current={key:R,mount:_t}),_t?Un(_t):he("Failed to load the secure card form.")}).catch(ye=>{M&&he(ye instanceof Error?ye.message:"Failed to load the secure card form.")}),()=>{M=!1}},[Ee,ar,Io,e,V?.vault,Zr,t,he]);let Sr=D({onComplete:s,onError:d,updateError:he,emitDecline:xr,resolvedAccount:vt,avsConfig:u,avsCheckProp:Ce,sessionId:e,nonce:t,baseUrl:Zr,captureMethod:V?.captureMethod,paymentId:V?.paymentId,authorizationExpiresAt:V?.authorizationExpiresAt,serverSideCardGateway:Pt});Sr.current={onComplete:s,onError:d,updateError:he,emitDecline:xr,resolvedAccount:vt,avsConfig:u,avsCheckProp:Ce,sessionId:e,nonce:t,baseUrl:Zr,captureMethod:V?.captureMethod,paymentId:V?.paymentId,authorizationExpiresAt:V?.authorizationExpiresAt,serverSideCardGateway:Pt};let Hi=D(!1),gl=Ae(()=>{let r=Sr.current,m=r.resolvedAccount.email?.trim(),R=Bn(m)?m:In.current.trim();if(!Bn(R))return null;let J=r.resolvedAccount.firstName?.trim(),M=r.resolvedAccount.lastName?.trim(),ye=hn.current.trim()||r.resolvedAccount.country?.trim()||"",_t=r.avsConfig?Xt(r.avsConfig.state,ye):!1,Tt=r.avsConfig?Xt(r.avsConfig.address_line_1,ye):!1,Be=r.avsConfig?Xt(r.avsConfig.postal_code,ye):!1,at=r.avsConfig?Xt(r.avsConfig.city,ye):!1,Ct=r.avsConfig?Xt(r.avsConfig.address_line_2,ye):!1,pn=Tt&&!_t&&Be?gy(ye,(Yt.current??"").trim()):null,Zn=_t?Nn.current:pn;return{accountData:{userId:r.resolvedAccount.userId??"",email:R,...J?{firstName:J}:{},...M?{lastName:M}:{},...Be&&Yt.current?{zip:Yt.current}:{},...at&&Pn.current?{city:Pn.current}:{},...Zn?{state:Zn}:{},...Tt&&Fn.current?{addressLine1:Fn.current}:{},...Ct&&dn.current?{addressLine2:dn.current}:{},...ye?{country:ye}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Xt(r.avsConfig.country,ye),postal_code:Be,address_line_1:Tt,address_line_2:Ct,city:at,state:_t}}:{}}},[]),hl=D(Qe);hl.current=Qe,pt(()=>{Qe||br!==md||Sr.current.updateError(null)},[Qe,br]),pt(()=>{!Ee||!Ge||Ge.setSubmitGate?.(vr||Qe||xo||K)},[Ee,Ge,vr,Qe,xo,K]),pt(()=>{if(!Ee||!Ge)return;Hi.current=!1;let r=null,m=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,j.current="idle",N(null)},400)},R=Ge.on("submitting",()=>{ir(!0),qe.current&&clearTimeout(qe.current),j.current="validation-window",qe.current=setTimeout(()=>{qe.current=null,j.current==="validation-window"&&(j.current="processing")},Xy),N("processing");let Be=Sr.current;if(!Be.sessionId||!Be.nonce)return;let at=gl();if(!at){Be.updateError("Enter a valid email address."),j.current="idle",N(null);return}new oa(Be.baseUrl).patchAccountSnapshot(Be.sessionId,Be.nonce,at,{telemetryMode:"best_effort"}).catch(Ct=>{if(!Qy(Ct))return;let pn=Ct instanceof Error?Ct.message:"Please check your billing address and try again.";Be.updateError(pn),j.current="idle",N(null),Be.onError?.(Ct instanceof Ir?Ct:new Ir(pn,"api_error"))})}),J=Ge.on("complete",Be=>{ea(Be.sessionId??Sr.current.sessionId),j.current="terminal",Se(!1),N("success"),setTimeout(()=>{if(Hi.current)return;Hi.current=!0;let at=Sr.current,Ct=xs(at)||Be.outcome==="authorized",pn=at.serverSideCardGateway?{}:{paymentIntentId:Be.intentId};Sr.current.onComplete?.(Ct?{status:"authorized",...pn,paymentId:Be.paymentId??at.paymentId,sessionId:Be.sessionId??at.sessionId,authorizationExpiresAt:Be.authorizationExpiresAt??at.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...pn,checkoutMethod:"card"})},600)}),M=Ge.on("decline",Be=>{let at=Sr.current,Ct=Be.message??"Your payment was declined. Please try another card or contact your bank.";j.current="terminal",Se(!1),at.updateError(Ct),N("error");let pn=Be.failureOutcome??Ry(Be.declineReason)??"authorization_declined";at.emitDecline("card",Ct,{code:pn,declineCode:pn}),m()}),ye=Ge.on("error",Be=>{let at=Sr.current,Ct=ay(Be.vaultOutcome);if(Ct!==null){r&&(clearTimeout(r),r=null),j.current="idle",Se(!1),at.updateError(Ct),N(null),Dt(Zn=>Zn+1),at.onError?.(new Ir(Ct,"api_error",{code:iy}));return}let pn=Be.message??"There was a problem processing your payment. Please try again.";j.current="terminal",Se(!1),at.updateError(pn),N("error"),at.onError?.(new Ir(pn,"api_error",{code:Be.failureOutcome??"capture_failed"})),m()}),_t=Ge.on("challenge_dismissed",()=>{qe.current&&(clearTimeout(qe.current),qe.current=null),j.current="processing",Se(!0),N(null)}),Tt=Ge.on("blocked",()=>{if(Te.current){Sr.current.updateError(Zy);return}if(!hl.current){ir(!0);return}ji(),Sr.current.updateError(md)});return()=>{r&&(clearTimeout(r),r=null),qe.current&&(clearTimeout(qe.current),qe.current=null),j.current="idle",Se(!1),N(null),R(),J(),M(),ye(),_t(),Tt()}},[Ee,Ge,ji,gl]);let Fr=!!$e?.clientId,da=Array.isArray($),Ka=da&&$.length>0,Pl=da&&$.includes("paypal"),Va=D(null);Va.current===null&&(Va.current=Py());let Oo=Va.current?"redirect":Zl(q,Ye,y.current()),{expressMethods:Ga,paymentElementMethods:Ki}=bt(()=>Iy($,{excludePaypal:Fr}),[$,Fr]),vl=Fr||!!O||Pl&&Oo==="redirect",Qd=bt(()=>vl?Ga.filter(r=>r!=="paypal"):Ga,[Ga,vl]),eu=bt(()=>{let r=[];return st&&r.push("apple_pay"),yt&&r.push("google_pay"),r},[st,yt]),Lo=da?Qd:eu,tu=S&&Lo.length>0,Cl=ht?mt:Le,Ya=bt(()=>my(Ki,Cl,Oe),[Ki,Cl,Oe]),Vi=bt(()=>({mode:"payment",amount:ca,currency:Fo,paymentMethodCreation:"manual",appearance:sl}),[ca,Fo,sl]),[Gi,bl]=re("loading"),[Yi,Sl]=re("loading"),[Ji,wl]=re("loading"),[nu,Xi]=re(!1),[kl,Zi]=re("loading"),[Qi,ru]=re();pt(()=>{ru(Ca())},[]);let Ja=Qi?.inAppBrowser,Xa=Qi?ii(Qi,$e?.approvalPresentation,Ln??(Ze?"subscription":"order")):"popup",Rl=de&&(Fr||(da?Pl:Ja===!1)),ou=q.inAppBrowser&&y.current()==="blocked",Il=S&&tu&&!ou,po=(!Ve||!!F.waitForDataAttachment)&&Rl&&Fr,es=kl==="retrying"||kl==="exhausted",ua=null;S&&(O?ua=il:Oo==="redirect"&&(ua=Xn));let El=bt(()=>({...X,presentationMode:Oo}),[X,Oo]),yo=!Ve&&Rl&&!!ua&&(!Fr||es),eo=!Ve&&Il&&!!Xn,mo=!Ve&&S&&Ka&&Ya.length>0&&!!Xn,au=po&&!es?nu:yo&&ba(Gi),iu=eo&&ba(Yi),su=mo&&Ji!=="load_error",_l=[po||yo,eo,mo,Ee].filter(Boolean).length,lu={card:Ee,paypal:po&&!es||yo&&ba(Gi),wallets:eo&&ba(Yi),apms:mo&&Ji!=="load_error"},Tl=r=>lu[r],Ml=r=>r==="loading"||r==="ready",Al=po||yo&&Ml(Gi)||eo&&Ml(Yi)||mo&&Ji!=="load_error",Za=D(!1);pt(()=>{if(!Za.current){if(!S&&!de){Za.current=!0;let r=new Ir("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(r),he(r.message)}else if(!S&&de&&!Fr){Za.current=!0;let r=new Ir("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(r),he(r.message)}else if(Ja!==void 0&&!Ve&&!un&&!Al){Za.current=!0;let r=new Ir("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});d?.(r),he(r.message)}}},[S,de,Fr,Ja,Ve,un,Al,d,he]);let xl=D(!1);pt(()=>{if(xl.current||!Ka)return;let r=[];st!==!0&&r.push("showApplePay"),yt!==!0&&r.push("showGooglePay"),r.length!==0&&(xl.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.`))},[Ka,st,yt]);let Fl=Ae((r,m,R)=>F.applyInlineSessionPatch?F.applyInlineSessionPatch(r).then(J=>({error:null,sessionId:J.sessionId||e,nonce:J.session?.clientSecret||t})).catch(J=>{let M=ld(m,J);return R?.abandoned?.()||(he(M.message),d?.(M)),{error:M,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[F.applyInlineSessionPatch,t,d,e,he]),wr=Ae(async(r,m)=>{if(r!=="card"&&Ve&&await F.waitForDataAttachment?.(),!dt)return{proceed:!0};try{let R=await dt({method:r,sessionId:e||void 0,createSession:F.inlineSessionDraft});if(R===!1)return{proceed:!1};if(R&&typeof R=="object"){R.account&&en(M=>({...M??{},...R.account}));let J=await Fl(R,r,m);return J.error?{proceed:!1,accountPatch:R.account}:{proceed:!0,accountPatch:R.account,sessionId:J.sessionId,nonce:J.nonce}}return{proceed:!0}}catch(R){if(!m?.abandoned?.()){let J=ld(r,R);he(J.message),d?.(J)}return{proceed:!1}}},[Fl,F.inlineSessionDraft,F.waitForDataAttachment,Ve,dt,d,e,he]),Bl=Ae(async(r,m)=>{if(Ut.current)return;Ut.current=!0,Rn(!0),N("processing"),he(null);let R=m?.sessionId??e,J=m?.nonce??t,M=Ps(vt,m?.accountPatch),ye=m?.completionPaymentMethodId??ka(r),_t=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,Tt=rm(r),Be=m?.presentationMode?Ri(bn(f),{...X,presentationMode:m.presentationMode}):void 0,at=()=>{_?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Tt}),Be?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Er,requestCategory:"process_payment"})};try{let Ct=new oa(Zr),Zn=m?.settledProcessResponse??await Ct.processPayment(M.userId??"",{sessionId:R,nonce:J,paymentMethodCategory:m?.paymentMethodCategory??am(r),tokenizedData:_t,accountData:{...m?.accountPatch,userId:M.userId??"",email:M.email??"",firstName:M.firstName||void 0,lastName:M.lastName||void 0,...ry({avsConfig:u,country:hn.current,zip:Yt.current,city:Pn.current,state:Nn.current,addressLine1:Fn.current,addressLine2:dn.current})},...ny({chv:ie,avsCheck:Ce,checkoutType:Fe,checkoutLayout:ut,avsConfig:u,country:hn.current})}),ri=async _n=>{let fo=xs(V)||_n?.status==="authorized";ea(R),Be?.terminal({outcome:"payment_succeeded",...Er}),N("success"),Hn(null),await new Promise(Pa=>setTimeout(Pa,600));let Br;typeof _n?.paymentId=="string"?Br=_n.paymentId:V?.paymentId&&(Br=V.paymentId);let go;typeof _n?.authorizationExpiresAt=="string"?go=_n.authorizationExpiresAt:V?.authorizationExpiresAt&&(go=V.authorizationExpiresAt),s?.(fo?{status:"authorized",...Br===void 0?{}:{paymentId:Br},sessionId:typeof _n?.sessionId=="string"?_n.sessionId:R,...go===void 0?{}:{authorizationExpiresAt:go},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ye,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ye,checkoutMethod:r.isPaypal?"paypal":"card"})};if(Zn.ok){await ri(Zn.status===204?null:await Zn.json().catch(()=>null));return}let yn=await Zn.json().catch(()=>null);if(yn?.type==="paypal_redirect_required"){let _n=yn.threeDSecureToken,fo=yn.paymentMethodId||r.id||"";if(!f||!_n){N("error"),he("PayPal authorization required but no token provided.");return}try{let Br=O?.getRawProvider();if(!Br){he("PayPal is not available.");return}let go={return_url:window.location.href};fo&&(go.payment_method=fo);let{error:Pa}=await Br.confirmPayment({clientSecret:_n,confirmParams:go,redirect:"if_required"});if(Pa){N("error");let Gl=Pa.message??"PayPal payment failed.";he(Gl),xr("paypal",Gl,{code:Pa.code})}}catch(Br){N("error"),he(Br instanceof Error?Br.message:"PayPal authorization failed.")}return}if(yn?.type==="paypal_direct_required"){let _n=yn.orderId;if(!_n){N("error"),he("PayPal retry required but no order id provided.");return}let fo=$t.current?.attempts??0;if(fo>=2){N("error"),he("PayPal payment could not be completed after multiple attempts."),xr("paypal","paypal_direct_required retry limit exceeded");return}Xi(!1),Zi("loading"),Hn({orderId:_n,attempts:fo+1}),N(null);return}if(Zn.headers.get(Wy)===Hy){let _n=await Ky(Ct,R,J);if(_n!==void 0){await ri(_n);return}}cy(Zn.status,yn)?Be?.terminal({outcome:"payment_declined",...Er,terminalReason:"provider_declined"}):at(),N("error");let Vl=yn?.message??"Payment failed. Please try again.";he(Vl),xr(r.isPaypal?"paypal":"card",Vl,{code:yn?.code??yn?.gatewayErrorCode,declineCode:yn?.declineCode??yn?.gatewayDeclineReason}),await new Promise(_n=>setTimeout(_n,400))}catch(Ct){_d(Ct)||at(),N("error"),he(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(pn=>setTimeout(pn,400))}finally{Rn(!1),N(null),Ut.current=!1}},[Zr,e,t,vt,u,Ce,Fe,ut,ie,f,O,V,s,he,xr,_,X]),Kn=Ae((r,m)=>{v&&!m?.settledProcessResponse?v(r):Bl(r,m)},[v,Bl]),pa=`${Id}:${e}`;pt(()=>{if(typeof window>"u")return;let r=localStorage.getItem(pa);if(!r)return;let m;try{m=JSON.parse(r)}catch{sn(pa);return}if(!m||typeof m.createdAt!="number"||Date.now()-m.createdAt<0||Date.now()-m.createdAt>Ed||typeof m.paymentMethodId!="string"||typeof m.providerIntentId!="string"||typeof m.paymentMethodType!="string"||m.sessionId!==e||!t||m.nonce!==t||!Lo.includes(m.paymentMethodType)){sn(pa);return}sn(pa),Kn({id:m.paymentMethodId,type:"card",threeDSecureActionResultTokenId:m.providerIntentId,gateway:"stripe",paymentMethodType:m.paymentMethodType},{...m.accountPatch?{accountPatch:m.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Kn,t,e,pa,Lo]);let Dl=D(!1);pt(()=>{if(typeof window>"u"||Dl.current)return;let[r,m,R]=bd();if(!r||!m||Va.current||!f)return;let J=f.getRawProvider();if(!J)return;let M=at=>{let Ct=localStorage.getItem(at);if(!Ct)return null;try{return JSON.parse(Ct)}catch{return sn(at),null}},ye=M(Lr)??M(ud),_t;if(ye?.clientSecret){if(ye.clientSecret!==m)return;_t={...ye.accountPatch?{accountPatch:ye.accountPatch}:{},...ye.sessionId?{sessionId:ye.sessionId}:{},...ye.nonce?{nonce:ye.nonce}:{}}}else if(ye?.sessionId&&ye.sessionId!==e)return;Dl.current=!0,sn(Lr),sn(ud),window.history.replaceState({},"",wd());let Tt=ye?.paymentMethodType??ye?.tokenType??"card",Be="card";(async()=>{if(R==="failed"){let yn="Payment was declined. Please try again.";he(yn),xr(Be,yn);return}let{paymentIntent:at,error:Ct}=await J.retrievePaymentIntent(m);if(Ct){let yn=Ct.message??"Failed to retrieve payment status.";he(yn),xr(Be,yn,{code:Ct.code});return}let pn=at?.status,Zn=wa(pn);if(!at||!Zn){let yn=pn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(yn),xr(Be,yn,{code:pn??"missing_payment_intent"});return}let ri=typeof at.payment_method=="string"?at.payment_method:at.payment_method?.id;Kn({id:ri??ye?.paymentMethodId??ye?.tokenId??at.id,type:"card",threeDSecureActionResultTokenId:at.id,gateway:ye?.gateway??"stripe",paymentMethodType:Tt},_t)})()},[e,Kn,f,he,xr]);let ts=Ae(r=>{r.preventDefault()},[]);if(!(Ee||f!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ya=we==="buttons",zn=Mo?.variables,cu=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ns=zn?.colorBackground,du=ns&&!cu.has(ns)?ns:void 0,ma=Me.cardInputBorder??(ya?"#e5e7eb":"#A4A4FF"),Ol=zn?.colorDanger??"#dc2626",Jt=r=>qr[r]&&(Eo[r]||Jn),Qa=xo&&(sr||Jn),ur=r=>r?Ol:ma,ei=(Dn.malformed||Dn.empty)&&(Yr||Jn),uu=ur(ei),rs=Me.cardFormContainer?.backgroundColor??du??(ya?"white":"#EDEDFF"),No=Me.cardInputBackground??zn?.colorBackground??"white",os=jo(Z),Ll=jo(ue),Uo=Me.nameInput,Nl=Me.cardInputFontSize??cm(Uo?.fontSize)??zn?.fontSizeBase??"16px",Ul=typeof Uo?.fontFamily=="string"?Uo.fontFamily:zn?.fontFamily??"Poppins, sans-serif",zl=Dy(Uo?.fontWeight)??400,pu=Me.cardInputColor??(typeof Uo?.color=="string"?Uo.color:void 0)??zn?.colorText??"#262833",yu=Me.cardInputPlaceholderColor??"#9ca3af",an=zn?.borderRadius??"8px",$r=zn?.borderRadius??Me.cardButton?.borderRadius??an,to=zn?.colorPrimary??"#4A49FF",mu=zn?.colorPrimaryHover??py(to,.12),as=zn?.colorText??"#262833",is={fontSize:Nl,fontFamily:Ul,fontWeight:zl,color:pu,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},fa={marginTop:"0.375rem",...is,fontSize:"0.75rem",lineHeight:1.4,color:Ol},fu={"--flopay-input-placeholder-color":yu,"--flopay-input-font-size":Nl,"--flopay-input-font-family":Ul,"--flopay-input-font-weight":String(zl)},ga=Me.cardFormContainer??{},ss=ga.padding??(ya?"0":"1rem"),ls=ga.borderRadius??an,gu=Ge&&Cr?c(ds,{capture:Ge,html:Cr.html,messageToken:Cr.messageToken,expectedOrigin:Cr.expectedOrigin,verificationRequired:Cr.verificationRequired,theme:Jd,submitLabel:x,onReady:()=>{if(!Qr&&!u||typeof document>"u"||ve===!1)return;let r=()=>{let R=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(R){lr.current=!0;try{R.focus()}finally{lr.current=!1}}};Xr.current||r()},onError:r=>{r&&Cr.verificationRequired&&j.current==="idle"&&(ze.current=!0),he(r)},onValidation:r=>{let m=j.current;(m==="idle"||m==="validation-window")&&(he(r),r&&j.current==="validation-window"&&(qe.current&&(clearTimeout(qe.current),qe.current=null),j.current="idle",N(null)))}},E):c("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),cs=De("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&Y()},style:{backgroundColor:rs,borderRadius:ls,...ga,padding:ss,...fu,display:"flex",flexDirection:"column"},children:[c("style",{children:`
3
+ ${Se.join(`
4
+ `)}`]}):null;return G&&!f?Ie?So("div",{children:Fn}):null:Is("div",{children:[Fn,yt&&So(Jo,{identity:yt.identity,methodLabel:yt.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:gt,onCancel:()=>gt(null)}),Is("div",{"aria-hidden":nt||yt?!0:void 0,style:nt||yt?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:gi},children:[!Ze&&!nt&&So("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"}}),So("div",{ref:de,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:gi,display:"flex",opacity:Ze?1:0},"aria-busy":Me||ge},De)]},De),Te&&So("button",{ref:St,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Ln,style:bp,children:"Try PayPal again"})]})}function hi(e){return So(Nc,{...e})}function Uc(e){return So(Nc,{...e})}import{jsx as zc,jsxs as kp}from"react/jsx-runtime";function Qo({children:e,margin:t,icon:n=!0,styleOverride:o}){return kp("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...o??{}},children:[n&&zc("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:zc("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 Pi,clearCachedInlineSession as Es,hashCreateParams as qc,legacyCachedSessionMatchesDraft as jc,persistCachedInlineIdempotencyKey as Ci,persistCachedInlineSession as bi,readCachedInlineIdempotencyKey as $c,readCachedInlineSession as Wc,serializeCreateParams as Ma}from"@flopay/shared";var Hc=new Set;function Rp(){return globalThis.process?.env?.NODE_ENV==="production"}function Kc(e,t){Hc.has(e)||Rp()||(Hc.add(e),console.warn(t))}function Vc(){Kc("automatic-payment-button-inline-create","[FloPay] FloPayAutomaticPaymentButton: creating the session from inline props is deprecated and may be downgraded to a Full checkout. Mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and pass `getSession` instead.")}function Gc(){Kc("checkout-keyless-create","[FloPay] FloPayCheckout: `createSession` with checkoutMode confirm/auto is deprecated and may be downgraded to a Full checkout. For one-click, mint the session on your server with @flopay/node `checkout.sessions.createOneClick` and use FloPayAutomaticPaymentButton `getSession`.")}import{isCardFieldsInstrumentSource as Ip,resolveBillingApiUrl as Ep}from"@flopay/shared";import{useCallback as _p,useEffect as io,useMemo as Tp,useRef as Yc,useState as Jc}from"react";import{jsx as Mp}from"react/jsx-runtime";function vi({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=Jc(e instanceof Promise?null:e),[d,y]=Jc(t instanceof Promise||!t?null:t),R=Yc(null),C=Yc(null),g=Xo(o),M=_p(U=>{Ip(U)||g(U)},[g]);io(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),io(()=>{i&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,i]),io(()=>{if(i)return hn(i)?.subscribe?.(M)},[M,i]),io(()=>{if(!(!d||d===i))return hn(d)?.subscribe?.(M)},[M,i,d]),io(()=>{if(!i)return;let U=hn(i);return R.current=U?.beginCheckout()??U?.now()??0,U?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{U?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),io(()=>{let U=!1;return e instanceof Promise?e.then(j=>{U||s(j)},()=>{U||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{U=!0}},[g,e]),io(()=>{let U=!1;if(!t){y(null);return}return t instanceof Promise?t.then(j=>{U||y(j)},()=>{U||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{U=!0}},[g,t]),io(()=>{if(!i||C.current===i)return;C.current=i;let U=hn(i);U?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),U?.performance({stage:"checkout_render",durationMs:U.elapsed(R.current??0),durationMode:"machine"})},[g,i]);let te=Ep(n?.billingApiUrl),le=Tp(()=>({flopay:i,paypalFlopay:d,billingApiUrl:te,emitInstrument:g}),[i,d,te,g]);return Mp(lr.Provider,{value:le,children:a})}import{markSessionRecentlyCompleted as ea,wasSessionRecentlyCompleted as _s}from"@flopay/shared";async function Si(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{beginSavedCardChallengeTelemetry as Ap,completeSavedCardNextAction as xp,loadFloPay as Xc,PaymentAPI as xa,runSavedCardChallenge as Fp}from"@flopay/js";import{classifyPaymentRejection as Bp,FloPayError as xt,isAuthorizationOnlySession as Dp,isMerchantAuthRequired as Ms,isMountableVaultBlock as Op,isSetupIntentClientSecret as Lp,MERCHANT_AUTH_REQUIRED_CODE as Np,normalizeCheckoutFailureOutcome as Zc}from"@flopay/shared";var Ba="card";async function Up(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:o??null}}async function zp(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:d}=await e.confirmCardSetup(t,n);return{error:d,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 ta(e){return new xt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function qp(){return new xt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Fa(e,t){return Object.assign(e,{checkoutMethod:t})}function Kr(e,t){let n=e instanceof xt?e:new xt(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 Aa(e,t){try{return await e()}catch(n){throw Kr(n,t)}}function ed(e){return!e?.type||!e.threeDSecureToken||Ms(e)||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function td(e){return Fp(e)}function Da(e,t,n,o=!0){let a={release:()=>{}};if(!o)return a;try{let i=new xa(e),s=Ap(i,t,n);return s?{telemetry:s,release:()=>{setTimeout(()=>{try{i.destroy()}catch{}},0)}}:a}catch{return a}}async function na(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new xa(n,{telemetry:!1}),d=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,y;try{y=await xp({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,...t.challengeTelemetry?{telemetry:t.challengeTelemetry}:{},createDeclineError:C=>Dr({type:C.declineReason??"authorization_declined",gatewayErrorCode:C.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(C){if(a.aborted||C instanceof Error&&C.name==="AbortError")throw C instanceof xt&&C.code==="three_ds_aborted"?C:ta(C);if(!(C instanceof xt)||C.code!=="three_ds_timeout"&&C.code!=="checkout_processing_timeout")throw C;try{y=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:d,timeoutMs:5e3,signal:a})}catch(M){if(a.aborted)throw ta(M);if(!(M instanceof xt)||M.code!=="checkout_processing_timeout")throw M}let g=y&&ro(y,t.session);if(!Wr(g)&&g?.status!=="expired"){if(t.telemetry){let M=new xa(n);try{M.reportThreeDsAbandoned(o)}finally{M.destroy()}}throw qp()}}let R=y&&ro(y,t.session);if(!Wr(R))throw Vo(R);return{...$r(R,o),checkoutMethod:"card"}}function nd(e){return new xt("This payment needs your card details. Please complete your payment below.","authentication_error",{code:Np,...e===void 0?{}:{statusCode:e}})}function Dr(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card");if(Ms(e))return Fa(nd(),o);let a=e?.message??t,i=Go(a)??a,s=Fa(new xt(i,"api_error",{code:e?.code??Zc(e?.outcome)??Zc(e?.type)??(e?.type==="paypal_direct_required"?"paypal_direct_required":void 0)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Ts(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function wi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function rd(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||wi(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let d of i)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||wi(d)))return d;let s=a.gateways;if(s&&typeof s=="object"){let d=s.stripe;if(d&&typeof d=="object"){let y=d,R=[y.stripeClientSecret,y.clientSecret];for(let C of R)if(typeof C=="string"&&C.length>0&&(!t?.requirePaymentIntentClientSecret||wi(C)))return C}}}}async function jp({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=rd(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let d=(await new xa(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(wi(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function ra({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:s}){let d=e.replace(/\/+$/,""),y=t??n.id,R=o??n.clientSecret,C=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",M=n.customer?.firstName??n.accountData?.firstName??"",te=n.customer?.lastName??n.accountData?.lastName??"",le=n.customer?.country??n.accountData?.country??void 0,U=n.customer?.zip??n.accountData?.zip??void 0,b=await new xa(d,s===!1?{telemetry:!1}:void 0).processPayment(C,{sessionId:y,nonce:R,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:C,email:g,firstName:M,lastName:te,country:le,zip:U},returnUrl:i??Ts(n)});if(b.ok){let ce=typeof b.json=="function"?await b.json().catch(()=>null):null;if(Dp(n)||ce?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof ce?.paymentId=="string"?ce.paymentId:n.paymentId,sessionId:typeof ce?.sessionId=="string"?ce.sessionId:y,authorizationExpiresAt:typeof ce?.authorizationExpiresAt=="string"?ce.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:ka(a),checkoutMethod:Qc(a,n)}};let v=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...v?{paymentIntentId:v}:{},paymentMethodId:ka(a),checkoutMethod:Qc(a,n)}}}let ge;try{ge=await b.json()}catch(ce){throw new xt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:b.status,cause:ce})}if(Ms(ge))throw Fa(nd(b.status),"card");if(ge?.type==="3ds_required"&&typeof ge.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:ge.nextActionRedirectUrl};if(ge?.type==="paypal_redirect_required"||ge?.type==="3ds_required"){let ce=rd(ge);if(!ce)throw new xt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:b.status});return{type:ge.type,threeDSecureToken:ce,paymentMethodId:ge.paymentMethodId}}if(ge?.gatewayErrorCode==="authentication_required"){let ce=await jp({billingApiUrl:d,sessionId:y,nonce:R,responseJson:ge});if(ce)return ce;throw Fa(new xt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw $p(ge,b.status)}function $p(e,t){let n=new xt(e?.message??"Payment failed. Please try again.","api_error",{code:e?.code??e?.gatewayErrorCode,declineCode:e?.declineCode??e?.gatewayDeclineReason,statusCode:t});return Object.assign(n,{telemetryOutcome:Bp(t,e)})}async function ki(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:d,telemetry:y,signal:R}){let C=t?.getRawProvider();if(!C)throw Kr(new xt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Fa(new xt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Lp(e.threeDSecureToken),M=null,te=e.paymentMethodId,le=await Aa(()=>Up(C,e.threeDSecureToken,g),"card");if(le){if(le.error)throw Kr(new xt(le.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:le.error.code}),"card");let j=le.intent;!te&&j?.payment_method&&(typeof j.payment_method=="string"?te=j.payment_method:"id"in j.payment_method&&(te=j.payment_method.id??void 0))}let U=te?await Aa(()=>zp(C,e.threeDSecureToken,{payment_method:te,return_url:d??Ts(s)??window.location.href},g),"card"):null;if(U){if(U.error)throw Kr(new xt(U.error.message??"3DS authentication failed.","api_error",{code:U.error.code}),"card");M=U.intent}else{let j=await Aa(()=>C.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(j.error)throw Kr(new xt(j.error.message??"3DS authentication failed.","api_error",{code:j.error.code}),"card");M=(g?j.setupIntent:j.paymentIntent)??null}if(M&&(M.status==="requires_capture"||M.status==="succeeded"||M.status==="processing")){let j=await ra({billingApiUrl:a,sessionId:i,session:s,telemetry:y,tokenizedData:{id:M.id,type:"card",threeDSecureActionResultTokenId:M.id},returnUrl:d});return j.type==="success"?{...j.result,paymentIntentId:j.result.paymentIntentId??M.id,paymentMethodId:j.result.paymentMethodId??te}:j.type==="next_action_required"?na(j,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:R}):ki(j,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:d,telemetry:y,signal:R})}throw Kr(new xt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Kr(new xt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:te}=await Aa(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(te)throw Kr(new xt(te.message??"PayPal authorization failed.","api_error",{code:te.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:M}=await Aa(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Ts(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(M)throw Kr(new xt(M.message??"PayPal authorization failed.","api_error",{code:M.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new xt("Unsupported payment redirect state.","api_error")}function Oa(e){if(e instanceof xt){let o=Go(e.message);return o&&o!==e.message?Object.assign(new xt(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=Go(t)??t;return new xt(n,"api_error")}function As(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=Op(e.data.session?.vault)||bo(e.data.session);if(!t&&!n&&!o)throw new xt("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 Qc(e,t){return e?e.isPaypal?"paypal":"card":t&&bo(t)?"card":void 0}async function xs({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,d]=await Promise.all([Xc(e,{billingApiUrl:n,locale:o,telemetry:a}),i?Xc(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(R=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",R),null)):Promise.resolve(null)]);if(!s)throw new xt("The payment provider did not initialize.","authentication_error");let y=null;return i?y=d:t&&(y=s),{flopay:s,paypalFlopay:y}}import{PaymentAPI as oa,PciVaultCardCapture as ay,toStripeAppearance as iy}from"@flopay/js";import{buildCardFieldLabelsPayload as sy,buildCheckoutProcessMetadata as ly,buildProcessPaymentAvsAccount as cy,buildWalletSheetWindowMessage as dy,buyerEmailRequiredPrompt as uy,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as py,COUNTRY_OPTIONS as yy,cardFieldsInstrumentSource as my,classifyPaymentRejection as fy,clearStripePayPalReturn as gy,computeVaultCardThemeColors as hy,darkenHex as Py,denyPaymentPermissionToNewFrames as Cy,FloPayError as br,filterStripeMethodsByCountryGate as by,getPostalCodeExample as vy,getPostalCodeLabel as $s,getStateFromPostalCode as Sy,getStateLabel as Ds,getStateOptions as wy,getStripeMethodDisplayName as za,hasMatchingStripePayPalReturn as ky,invokeMerchantCallback as ud,isAuthorizationOnlySession as Os,isAVSFieldVisible as Qt,isCardFormFirst as Ry,isMountableVaultBlock as Iy,isPostalCodeSupported as Ey,isSettledSessionIntent as Ti,isSetupIntentClientSecret as Ls,isValidEmail as En,isValidPostalCode as _y,isWalletSheetRefusedForWindowSize as Ty,keyPaymentMethodOrder as My,needsStripeMethodExplicitConfirm as pd,normalizeBeforeButtonClickError as yd,normalizeCheckoutFailureOutcome as Ay,partitionStripeMethods as xy,placePaymentMethodGroups as md,randomUuidV4 as Fy,readMatchingStripePayPalContinuation as By,readStripeRedirectParams as Id,resolveAVSConfig as Dy,resolveButtonsLayoutTheme as Oy,resolveSetupFutureUsage as Ed,resolveTheme as Ly,resolveVaultMountOptions as Ns,STRIPE_PAYPAL_RESUME_KEY as Ny,derivePrimaryTileStyle as Uy,shouldPreferWalletPopup as fd,stripeExpressMethodToOptionKey as zy,stripeRedirectReturnUrl as _d,toCssWeight as qy,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as Td}from"@flopay/shared";import{ExpressCheckoutElement as Md,PaymentElement as jy,Elements as ko,useElements as Vs,useStripe as Gs}from"@stripe/react-stripe-js";import Na,{useCallback as Be,useContext as aa,useEffect as et,useLayoutEffect as $y,useMemo as vt,useRef as O,useState as ee}from"react";function wo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function Ri(e,t){if(e)return{error:n=>e.error(wo(t,n)),log:n=>e.log(wo(t,n)),performance:n=>e.performance(wo(t,n)),terminal:n=>e.terminal(wo(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}import{useEffect as Wp,useId as Hp,useRef as od}from"react";import{Fragment as Gp,jsx as ad,jsxs as Yp}from"react/jsx-runtime";var id="More payment options",Kp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Vp={display:"flex",flexDirection:"column",gap:"0.5rem",outline:"none"};function Fs({label:e,open:t,showLink:n,onOpen:o,color:a,fontFamily:i,children:s}){let d=Hp(),y=od(null),R=od(!1);return Wp(()=>{t&&R.current&&y.current?.focus()},[t]),Yp(Gp,{children:[!t&&n&&ad("button",{type:"button","data-testid":"flopay-more-payment-options","aria-expanded":!1,"aria-controls":d,onClick:()=>{R.current=!0,o()},style:{alignSelf:"center",margin:0,padding:"0.25rem 0",border:0,background:"none",cursor:"pointer",color:a,fontFamily:i,fontSize:"0.9rem",fontWeight:500,textDecoration:"underline",textUnderlineOffset:"0.2em"},children:e}),ad("div",{id:d,ref:y,role:"group","aria-label":e,tabIndex:t?-1:void 0,"data-testid":"flopay-more-payment-options-section",style:t?Vp:Kp,children:s})]})}import{jsx as sd}from"react/jsx-runtime";var Jp=["first","second","third","fourth"];function Bs({rows:e,borderRadius:t}){return sd("div",{"data-testid":"flopay-payment-method-layout-pending","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Jp.slice(0,Math.max(1,e)).map(n=>sd("div",{style:{height:Co,borderRadius:t??8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}},n))})}import{PaymentAPI as Xp}from"@flopay/js";import{DEFAULT_PAYMENT_METHOD_ORDER as Zp,resolveDefaultPaymentMethodLayout as Qp}from"@flopay/shared";import{useEffect as ey,useState as ty}from"react";var ny=1500,ld=new Set;function cd(e){for(let t of e)ld.has(t)||(ld.add(t),console.warn(`[FloPay] paymentMethodLayout: ${t}`))}function ry(e){if(e!=null)try{return JSON.stringify(e)}catch{return cd(["the rules could not be sent (they are not plain data), so the default layout applies."]),"{}"}}var oy={order:[...Zp],moreOptions:[]};function dd({rules:e,sessionId:t,nonce:n,billingApiUrl:o,waitForSession:a}){let i=ry(e),[s,d]=ty(null);return ey(()=>{if(i===void 0||a)return;let y=JSON.parse(i),R=!1,C=le=>{R||(R=!0,d(le))},g=()=>C(Qp(y));if(!t||!n||!o){g();return}let M=new AbortController,te=setTimeout(()=>{g(),M.abort()},ny);return new Xp(o,{telemetry:!1}).resolvePaymentMethodLayout(t,n,y,{signal:M.signal}).then(le=>{if(!le){g();return}R||cd(le.warnings),C({order:le.order,moreOptions:le.moreOptions})}).catch(g).finally(()=>clearTimeout(te)),()=>{R=!0,clearTimeout(te),M.abort()}},[i,t,n,o,a]),i===void 0?oy:s}import{darkenHex as Od}from"@flopay/shared";import{Fragment as $n,jsx as l,jsxs as Ue}from"react/jsx-runtime";var Or="flopay_stripe_resume",gd="flopay_wallet_resume",Ad="fw1",Wy="fw2",xd=300*1e3,Hy=900,Ky="express_checkout_click_timeout",Vy=25e3,Gy=25e3,Yy=1e4,vr={provider:"paypal",paymentMethodCategory:"paypal"},Jy="x-flopay-process-result-source",Xy="status";async function Zy(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 Ii={},Ua=class{constructor(t){this.reason=t}};function Qy(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 Ys(e){return`${Wy}:${e}`}function Ei(e){return sn(Ys(e))}function _i(e,t){if(typeof window>"u")return null;let n=Ys(e);try{let o=localStorage.getItem(n);if(!o)return null;let a=JSON.parse(o);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>xd||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(Ei(e),null):a}catch{return Ei(e),null}}function em(e){return sn(Ys(e.sessionId),e)}function hd(e,t,n){let o=_i(e,t);return!o||o.clientSecret!==n?!1:Ei(e)}function Us(e,t,n){if(typeof window>"u")return;_i(e,t)?.clientSecret===n&&Ei(e)}function tm(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function zs(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":wa(e.status),a=tm(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Pd(e,t,n){let o=null;try{return await Promise.race([Sc(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},Yy),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function nm(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Fd(e){return e instanceof br&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Mi(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new oa(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw Fd(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var qs=Ny,La=new Map,rm=250,Cd="Just a moment \u2014 we are finalizing your order. Please press pay again.",om="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Js(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 Ai({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new oa(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function am(e){return e instanceof br&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Bd({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=Ra(n),s=i.firstName?i:Ra(o?.name);return Cr({email:En(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function im({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=Bd({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return En(s.email)?s:i(a,s)}var qa=180,bd=`flopay-card-enter ${qa}ms cubic-bezier(0, 0, 0.2, 1) both`,vd=`flopay-card-exit ${qa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,sm=`flopay-buttons-enter ${qa}ms cubic-bezier(0, 0, 0.2, 1) both`,lm=`flopay-buttons-exit ${qa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function cm(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Xs(e){return Uy(e)}var dm={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function um(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 Ws={width:"100%",minHeight:Co,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 Sd(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Hs(e){return e==="paypal"?"PayPal":za(e)}function pm(e){let t=vy(e);return`Enter a valid ${$s(e)}${t?` (e.g. ${t})`:""}`}function ym(e,t,n){let o=Ey(e),a=t.trim(),i=n&&o,s=i&&!a,d=i&&!!a&&!_y(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:d}}function mm(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!En(n);return{required:t,empty:o,malformed:a,value:n}}function fm(e){return typeof e=="number"?`${e}px`:e}var gm=["number","expiry","cvv","name"];function hm(e){if(e===null||typeof e!="object")return null;let t={};for(let n of gm){let o=e[n];typeof o=="string"&&(t[n]=o)}return JSON.stringify(t)}function Zs(e){return l(bm,{...e})}function wd({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:d,onDecline:y,onTechnicalFailure:R,runBeforeButtonClick:C,billingName:g,onBuyerIdentityReady:M,onLoadStateChange:te,placeholderBorderRadius:le,popupCapabilityOwner:U,externalTelemetryContext:j,presentationMode:b}){let ge=oo(),{emitInstrument:ce}=aa(lr),v=Gs(),Ke=Vs(),K=vt(()=>Ri(hn(ge),j),[j,ge]),[ze,lt]=ee("loading");et(()=>{te?.(ze)},[ze,te]);let[ft,Ee]=ee(!1),zt=O(!1),Nt=!En(n?.trim())||!g?.trim(),{request:Ie,collect:Xe,finish:ct}=Yo(),dt=O(!1),_e=O(null),X=O(null),[de,Kt]=ee(0),[je,ut]=ee(!1),Q=O(!1),Ae=O(new Map),{startAttempt:tt,finishAttempt:$,invalidateAttempt:St,isAttemptInvalidated:ve,isAttemptCurrent:Ze,generationRef:qe}=_a((ue,Me,pt)=>{R?.(ue,Me,{...pt,popupBlocked:pt?.popupBlocked??to(Me),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:b,terminalReason:"overlay_timeout"}),ut(!0),Kt(yt=>yt+1)},{onHandoffObserved:()=>{U.markAvailable(),K?.log({name:"provider.popup.opened",stage:"overlay_open",...vr,attempt:qe.current})}});et(()=>{je&&X.current?.focus()},[je,de]);let nt=Be(()=>{Kt(ue=>ue+1)},[]),wt=Be((ue,Me,pt)=>{St(pt),R?.("paypal",ue,{code:Me,popupBlocked:to(ue),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:b}),ut(!0),nt()},[St,R,b,nt]),De=Be(()=>{window.setTimeout(()=>{(_e.current?.querySelector("iframe")??_e.current)?.focus()},0)},[]);et(()=>{Q.current&&(Q.current=!1,De())},[De,de]);let It=Be(()=>{ut(!1),i?.(null),De()},[De,i]);et(()=>{if(!v||dt.current)return;let[ue,Me,pt]=Id();if(!ue||!Me)return;let yt=By(Me);if(!yt)return;dt.current=!0;let Ve=!0,gt=La.get(Me);gt||(gt=pt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>v.retrievePaymentIntent(Me)),La.set(Me,gt));let Pt={accountPatch:yt.accountPatch,sessionId:yt.sessionId,nonce:yt.nonce},Rt=()=>{K?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...vr,requestCategory:"provider_sdk"})};return K?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...vr}),(async()=>{try{Ee(!0);let Ye=await gt;if(!Ve)return;if(Ye?.error){La.delete(Me),Rt(),i?.(Ye.error.message??"Failed to retrieve PayPal payment status.");return}if(gy(),La.delete(Me),pt==="failed"){let F="PayPal payment was declined. Please try again.";K?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}),i?.(F),y?.(gn("paypal",F));return}let rt=Ye?.paymentIntent;if(rt&&rt.id!==ue){Rt(),i?.("Failed to match the returned PayPal payment.");return}if(rt&&(rt.status==="requires_capture"||rt.status==="succeeded")){let F=typeof rt.payment_method=="string"?rt.payment_method:rt.payment_method?.id;a({id:F??rt.id,type:"card",threeDSecureActionResultTokenId:rt.id,isPaypal:!0},{...Pt,presentationMode:"redirect"})}else{let F="PayPal payment was not completed. Please try again.";K?.terminal({outcome:rt?.status==="canceled"?"payment_cancelled":"payment_declined",...vr,terminalReason:rt?.status==="canceled"?"cancelled":"provider_declined"}),i?.(F),y?.(gn("paypal",F))}}catch(Ye){if(!Ve)return;La.delete(Me),Rt(),i?.(Ye instanceof Error?Ye.message:"Failed to complete PayPal payment.")}finally{Ve&&Ee(!1)}})(),()=>{Ve=!1,dt.current=!1}},[v,a,i,y,K]);let xe=Be(async(ue=!1)=>{let Me=C?await C("paypal"):{proceed:!0};if(!Me.proceed)return Ae.current.delete(de),!1;let pt=tt("paypal");return Ae.current.set(de,{generation:pt,accountPatch:Me.accountPatch,sessionId:Me.sessionId,nonce:Me.nonce}),ut(!1),K?.log({name:`provider.${ue?"redirect.started":"handoff.requested"}`,stage:ue?"redirect":"overlay_open",...vr,attempt:pt}),d?.("paypal"),!0},[d,K,C,tt,de]),Te=Be(async ue=>{if(s||ft||!await xe()){ue.reject();return}ue.resolve()},[s,xe,ft]),kt=Be(async ue=>{if(!v||!Ke)return;let Me=Ae.current.get(de);if(Me&&!Ze(Me.generation)){Ae.current.delete(de);return}if(!Me&&ve()||Me&&!$(Me.generation))return;Me||$();let pt=Me??null;if(Ae.current.delete(de),!pt&&C){let Ge=await C("paypal");if(!Ge.proceed){ue.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}pt={accountPatch:Ge.accountPatch,sessionId:Ge.sessionId,nonce:Ge.nonce}}let yt=pt?.sessionId??e,Ve=pt?.nonce??t,gt=await im({event:ue,prepared:pt,email:n,billingName:g,methodLabel:"PayPal",collect:Xe});if(!gt){ue.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Pt=gt.email,Rt={...pt?.accountPatch,...Cr(gt,!0)};try{if(Ee(!0),i?.(null),!yt||!En(Pt))throw new Error("Missing sessionId or email for PayPal payment");await M?.(gt);let Ge=v.createPaymentMethod,{error:Ye,paymentMethod:rt}=await Ge({type:"paypal"});if(Ye){wt(Ye,"stripe_paypal_create_payment_method_failed",Me?.generation),ue.paymentFailed({reason:"fail"});return}let F=await Mi(o,ce,yt,Ve??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:rt?.id??null,intentKind:"payment"});if(Ti(F)){ue.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:Rt,paymentMethodCategory:"paypal",presentationMode:b,sessionId:yt,nonce:Ve,settledProcessResponse:F.response});return}if(F.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Cn=F.clientSecret,S={return_url:_d()};if(rt?.id&&(S.payment_method=rt.id),!sn(qs,{clientSecret:Cn,sessionId:yt,nonce:Ve,accountPatch:Rt})&&b==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:W,paymentIntent:B}=await v.confirmPayment({clientSecret:Cn,confirmParams:S,redirect:"if_required"});if(W){if(sn(qs),ai(W)){let f=W.message??"Your payment was declined.";K?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}),i?.(f),y?.(gn("paypal",f,{code:qo(W),declineCode:hs(W)})),await Ai({billingApiUrl:o,sessionId:yt,nonce:Ve,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:qo(W)??"provider_declined"}})}else wt(W,"stripe_paypal_confirm_failed",Me?.generation);return}sn(qs);let H=typeof B?.payment_method=="string"?B.payment_method:B?.payment_method?.id;a({id:H??B?.id,type:"card",threeDSecureActionResultTokenId:B?.id,isPaypal:!0},{accountPatch:Rt,paymentMethodCategory:"paypal",presentationMode:b,sessionId:yt,nonce:Ve});return}catch(Ge){wt(Ge,"stripe_paypal_failed",Me?.generation)}finally{Ee(!1)}},[v,Ke,e,t,n,g,Xe,M,o,ce,a,i,y,C,wt,$,Ze,ve,K,b,de]),Ut=Be(async()=>{if(!(zt.current||s||ft||!v||!Ke)){zt.current=!0,Ee(!0);try{if(!await xe(!0))return;await kt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{zt.current=!1,Ee(!1)}}},[Ke,kt,s,xe,v,ft]),Et=b==="redirect"?l("button",{type:"button",disabled:s||ft,onClick:()=>{Ut()},style:{width:"100%",minHeight:Co,border:"1px solid #d1d5db",borderRadius:le??8,background:"#ffc439",color:"#111827",cursor:s||ft?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):l(Md,{onReady:ue=>lt(Ps(ue,["paypal"])),onLoadError:()=>{lt("load_error"),Js(K,"paypal","paypal","provider_error")},onClick:Te,onConfirm:kt,onCancel:()=>{let ue=Ae.current.get(de);Ae.current.delete(de),K?.terminal({outcome:"payment_cancelled",...vr,terminalReason:"cancelled",...ue?{attempt:ue.generation}:{}}),St(ue?.generation),ut(!1),Q.current=!0,nt()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Nt,emailRequired:Nt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},de),G=Ue($n,{children:[Ue("div",{ref:_e,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[je&&l("button",{ref:X,type:"button","data-testid":"flopay-paypal-retry-button",onClick:It,style:Ws,children:"Try PayPal again"}),Ie&&l(Jo,{identity:Ie.identity,methodLabel:Ie.methodLabel,onComplete:ct,onCancel:()=>ct(null)},Ie.id),l("div",{style:{display:Ie?"none":void 0},children:Et})]}),ft&&!Ie&&l(Br,{status:"processing"})]});return b==="redirect"?G:l(Cs,{state:ze,placeholderTestId:"flopay-paypal-placeholder",borderRadius:le,children:G})}function js(e){return e==="apple_pay"||e==="google_pay"}var Pm=200;function Cm({active:e}){return $y(()=>e?Cy(document):void 0,[e]),null}function kd({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:d,onButtonClick:y,onDecline:R,onTechnicalFailure:C,runBeforeButtonClick:g,billingName:M,onBuyerIdentityReady:te,onLoadStateChange:le,placeholderBorderRadius:U,popupCapabilityOwner:j,externalTelemetryContext:b}){let ge=oo(),{emitInstrument:ce}=aa(lr),v=Gs(),Ke=Vs(),K=vt(()=>Ri(hn(ge),b),[b,ge]),[ze,lt]=ee("loading");et(()=>{le?.(ze)},[ze,le]);let[ft,Ee]=ee(!1);et(()=>{ut.current=ft},[ft]);let zt=O(!En(n?.trim())||!M?.trim()).current,{request:Nt,collect:Ie,finish:Xe}=Yo(),ct=O(null),dt=O(null),[_e,X]=ee(0),[de,Kt]=ee(()=>fd()),je=O(de),ut=O(!1),[Q,Ae]=ee(!1),[tt,$]=ee(()=>_i(e,t)?"blocked":"idle"),[St,ve]=ee("google_pay"),Ze=O(null),qe=O(!0),nt=O(!1),wt=O("google_pay"),De=O("google_pay"),It=O(null),xe=O(null),Te=O(new Set),kt=O(null),Ut=O(null);et(()=>(qe.current=!0,()=>{qe.current=!1;for(let f of Te.current)window.clearTimeout(f);Te.current.clear()}),[]);let Et=O(new Map),{startAttempt:G,finishAttempt:ue,invalidateAttempt:Me,isAttemptInvalidated:pt,isAttemptCurrent:yt,generationRef:Ve}=_a((f,ne,L)=>{C?.(f,ne,{...L,popupBlocked:L?.popupBlocked??to(ne),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ve(f),Ae(!0),X(Se=>Se+1)},{onHandoffObserved:f=>{Ut.current=Ve.current,j.markAvailable(),K?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ve.current,...f==="apple_pay"||f==="google_pay"?{walletType:f}:{}})},defersMissingTerminal:js,onMissingTerminalDeferred:(f,ne)=>{let L=K?.now()??globalThis.performance?.now()??Date.now(),Se=kt.current,we=Se?.generation===ne?Se.startedAt:L;K?.performance({stage:"overlay_return",durationMs:Math.max(0,L-we),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:ne,...js(f)?{walletType:f}:{}}),K?.flush?.().catch(()=>{})}});et(()=>{Q&&dt.current?.focus()},[Q,_e]);let gt=O(0),Pt=O(!1),Rt=Be(()=>{if(gt.current>0){Pt.current=!0;return}X(f=>f+1)},[]),Ge=Be(()=>{gt.current-=1,!(gt.current>0||!Pt.current)&&(Pt.current=!1,qe.current&&X(f=>f+1))},[]),Ye=Be((f,ne,L,Se,we=!1)=>{Me(Se),C?.(f,ne,{code:L,popupBlocked:to(ne),telemetryReported:we,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ve(f),Ae(!0),Rt()},[Me,C,Rt]),rt=Be(f=>{K?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...js(f)?{walletType:f}:{}}),C?.(f,new Error("The wallet click was not ready within the time the wallet allows."),{code:Ky,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ve(f),Ae(!0)},[C,K]),F=Be(()=>{window.setTimeout(()=>{(ct.current?.querySelector("iframe")??ct.current)?.focus()},0)},[]);et(()=>{nt.current&&(nt.current=!1,F())},[F,_e]);let Cn=Be(()=>{Ae(!1),d?.(null),F()},[F,d]),S=Be(()=>{Ze.current?.()},[]);et(()=>{let f=null,ne=()=>{f=null;let Se=fd();Se!==je.current&&(je.current=Se,Kt(Se),!ut.current&&!yt(Ve.current)&&Rt())},L=()=>{f!==null&&window.clearTimeout(f),f=window.setTimeout(ne,Pm)};return window.addEventListener("resize",L),()=>{window.removeEventListener("resize",L),f!==null&&window.clearTimeout(f)}},[Ve,yt,Rt]),et(()=>{let f=_i(e,t);if(!f)return;let ne=!1,L=!1,Se=async()=>{if(!L){L=!0,ne||$("checking");try{let we=await Pd(v,f.clientSecret,Te.current);if(ne)return;let k=zs(we,f.providerObjectId,Ls(f.clientSecret));if(k.kind==="confirmed"){if(!hd(e,t,f.clientSecret))return;Ze.current=null,$("idle"),s({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.intentId},{...f.accountPatch?{accountPatch:f.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(k.kind==="terminal"){Us(e,t,f.clientSecret),Ze.current=null,$("idle"),ve(f.paymentMethodType),Ae(!0),Rt();return}$("blocked")}catch{ne||$("blocked")}finally{L=!1}}};return Ze.current=Se,$("blocked"),()=>{ne=!0,Ze.current===Se&&(Ze.current=null)}},[t,s,Rt,e,v]);let m=Be(async f=>{let ne=!1,L=!1,Se=Je=>{ne||L||(ne=!0,f.paymentFailed({reason:"fail",...Je?{message:Je}:{}}))};if(!v||!Ke){Se();return}let we=Et.current.get(_e);if(we&&!yt(we.generation)){Et.current.delete(_e),Se();return}if(!we&&pt()){Se();return}if(we&&!ue(we.generation)){Se();return}we||(ue(),Pt.current=!1);let k=f.expressPaymentType??we?.method??wt.current,ot=we??null,Yt=Sd(k),qt;k==="apple_pay"?qt="apple_pay":k==="google_pay"&&(qt="google_pay");let On=we?.generation??Ve.current,be=K,wr=be?.now()??globalThis.performance?.now()??Date.now(),pn=new AbortController,yn=!1,at=!1,Ft=null,_n=e,Wn="processing",Tn="other",wn="provider_runtime",kn,Jt=new Promise((Je,pe)=>{kn=pe}),jt=window.setTimeout(()=>{yn=!0,pn.abort(),kn(Ii)},Vy),tn=async(Je,pe,Qn)=>{Wn=Je,Tn=pe,wn=pe==="intent_create"||pe==="session_claim"?"transport_error":"provider_runtime";let Bt=be?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Qn,Jt])}finally{let Mn=be?.now()??globalThis.performance?.now()??Date.now();be?.performance({stage:Je,durationMs:Math.max(0,Mn-Bt),durationMode:"machine",requestCategory:pe,paymentMethodCategory:"wallet",provider:"stripe",...yn?{statusClass:"timeout"}:{}})}};try{if(Ee(!0),d?.(null),!ot&&g){let re=await tn("processing","other",g(Yt));if(!re.proceed){Se();return}ot={accountPatch:re.accountPatch,sessionId:re.sessionId,nonce:re.nonce}}let Je=ot?.sessionId??e;_n=Je;let pe=ot?.nonce??t,Qn=It.current??ot?.accountPatch,Bt=Bd({event:f,fallbackEmail:Qn?.email??n,fallbackName:[Qn?.firstName,Qn?.lastName].join(" ").trim()||M});if(!En(Bt.email)){Se("Buyer details are required."),Ie(Hs(k),Bt).then(re=>{re&&(It.current=re)});return}It.current=null;let Mn={...ot?.accountPatch,...Cr(Bt,!0)};await tn("processing","session_claim",Promise.resolve(te?.(Bt)));let{error:Ln}=await tn("tokenization","provider_sdk",Ke.submit());if(Ln){Se(),Ye(k,Ln,"stripe_wallet_submit_failed",we?.generation);return}if(!Je)throw new Error("Missing sessionId or email for payment.");let er={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,paymentMethodId:null,intentKind:a},Nn=JSON.stringify({sessionId:Je,nonce:pe??"",request:er}),kr=xe.current,ur=kr?.retryIdentity===Nn?kr.authorizationAttemptId:Fy();xe.current={authorizationAttemptId:ur,retryIdentity:Nn};let mn=await tn("processing","intent_create",Mi(o,ce,Je,pe??"",{...er,authorizationAttemptId:ur},{signal:pn.signal}));if(Ti(mn)){Se(),s({type:"card",paymentMethodType:k},{accountPatch:Mn,paymentMethodCategory:"wallet",sessionId:Je,nonce:pe,settledProcessResponse:mn.response});return}if(mn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let fn=mn.clientSecret,An=em({createdAt:Date.now(),sessionId:Je,...pe?{nonce:pe}:{},clientSecret:fn,providerObjectId:mn.providerObjectId,paymentMethodType:k,accountPatch:Mn});window.clearTimeout(jt),at=!0,be?.performance({stage:"callback",durationMs:Math.max(0,(be?.now()??globalThis.performance?.now()??Date.now())-wr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Hn=be?.now()??globalThis.performance?.now()??Date.now(),Un={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...qt?{walletType:qt}:{},attempt:On},xn=!1,ln=null;be?.log({name:"payment.provider_confirmation.started",...Un}),Ft=window.setTimeout(()=>{Ft!==null&&Te.current.delete(Ft),xn=!0;let re=be?.now()??globalThis.performance?.now()??Date.now();be?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Un,operationOutcome:"watchdog_expired",durationMs:Math.max(0,re-Hn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),be?.flush?.().catch(()=>{}),ln?.()},Gy),Te.current.add(Ft);let nn=(re,mt)=>{Ft!==null&&(window.clearTimeout(Ft),Te.current.delete(Ft),Ft=null);let He=be?.now()??globalThis.performance?.now()??Date.now(),$t=Math.max(0,He-Hn),ke=re;xn&&(re==="resolved"?ke="resolved_late":re==="returned_error"?ke="returned_error_late":ke="rejected_late");let Rr=mt??(re==="resolved"?"approved":"provider_error");return be?.log({name:"payment.provider_confirmation.returned",...Un,operationOutcome:ke,terminalReason:Rr}),be?.performance({...Un,durationMs:$t,durationMode:"buyer",operationOutcome:ke,terminalReason:Rr}),{durationMs:$t,operationOutcome:ke,terminalReason:Rr}},rn=!1,Xt=!1,zn=re=>{if(!re||typeof re!="object")return null;let mt=re;if(mt.error)return null;let He=mt.setupIntent??mt.paymentIntent,$t=zs(He??null,void 0,!!mt.setupIntent);return $t.kind==="confirmed"?$t:null},qn=re=>{if(rn||we&&Ve.current!==we.generation)return;let mt=zn(re);if(!mt)return;if(An&&!hd(Je,pe,fn)){rn=!0;return}let{intentId:He,paymentMethodId:$t}=mt;rn=!0,Xt=!0,xe.current=null,Ze.current=null,qe.current&&($("idle"),Ee(!1));let ke=`${Ad}:${Je}`;sn(ke,{createdAt:Date.now(),sessionId:Je,nonce:pe,accountPatch:Mn,paymentMethodId:$t,providerIntentId:He,paymentMethodType:k});try{s({id:$t,type:"card",threeDSecureActionResultTokenId:He},{accountPatch:Mn,paymentMethodCategory:"wallet",sessionId:Je,nonce:pe})}finally{sn(ke)}},Fn=!1;ln=async()=>{if(!(Fn||rn||Xt)){Fn=!0,qe.current&&$("checking");try{let re=await Pd(v,fn,Te.current);if(rn||Xt)return;let mt=Ls(fn),He=zs(re,mn.providerObjectId,mt);if(He.kind==="confirmed"){qn(mt?{setupIntent:re}:{paymentIntent:re});return}if(He.kind==="terminal"){if(Xt=!0,Us(Je,pe,fn),xe.current=null,Ze.current=null,!qe.current)return;$("idle"),Se(),Ye(k,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",we?.generation,!0);return}qe.current&&!Xt&&($("blocked"),Ee(!1))}catch{qe.current&&!Xt&&($("blocked"),Ee(!1))}finally{Fn=!1}}},Ze.current=ln;let I,We;try{L=!0,gt.current+=1;let re;try{re=await(Ls(fn)?v.confirmSetup({elements:Ke,clientSecret:fn,redirect:"if_required"}):v.confirmPayment({elements:Ke,clientSecret:fn,redirect:"if_required"}))}finally{Ge()}if(!re||typeof re!="object")throw new Ua(Qy(re));if(I=re,!I.error&&!zn(I))throw new Ua("confirmation_result_unconfirmed");We=nn(I.error?"returned_error":"resolved",I.error&&ai(I.error)?"provider_declined":void 0)}catch(re){let mt=re instanceof Ua?re.reason:void 0,He=mt!==void 0,$t=nn(He?"returned_error":"rejected");if(be?.error({...He?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:mt}:ws(re),...Un,operationOutcome:$t.operationOutcome,durationMs:$t.durationMs,statusClass:"unknown",terminalReason:$t.terminalReason}),!qe.current||rn)return;await ln?.();return}let h=I.error;if(h){if(!qe.current||rn)return;if(ai(h)){Xt=!0,Us(Je,pe,fn),xe.current=null,Ze.current=null,$("idle"),Et.current.get(_e)===we&&Et.current.delete(_e);let re=h.message??"Your payment was declined.";d?.(re),R?.(gn(Yt,re,{code:qo(h),declineCode:hs(h)})),Ai({billingApiUrl:o,sessionId:Je,nonce:pe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:k,providerDeclineReason:qo(h)??"provider_declined",...mn.intentKind==="payment"&&mn.providerObjectId.startsWith("pi_")?{providerIntentId:mn.providerObjectId}:{}}})}else be?.error({...ws(h),...Un,operationOutcome:We.operationOutcome,durationMs:We.durationMs,statusClass:"unknown",terminalReason:We.terminalReason}),await ln?.();return}if(qn(I),!rn)throw new Error("Invalid provider returned for APM intent")}catch(Je){if(Je===Ii){let pe=be?.now()??globalThis.performance?.now()??Date.now();be?.error({errorCode:nm(Tn),stage:Wn,requestCategory:Tn,paymentMethodCategory:"wallet",provider:"stripe",...qt?{walletType:qt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:_n,durationMs:Math.max(0,pe-wr),statusClass:"timeout",failureCategory:wn,attempt:On,terminalReason:"provider_error"}),be?.flush?.().catch(()=>{})}Se(),Ye(k,Je,Je===Ii?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",we?.generation,Je===Ii)}finally{if(window.clearTimeout(jt),Ft!==null&&(window.clearTimeout(Ft),Te.current.delete(Ft)),!at){let Je=be?.now()??globalThis.performance?.now()??Date.now();be?.performance({stage:"callback",durationMs:Math.max(0,Je-wr),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...yn?{statusClass:"timeout"}:{}})}qe.current&&Ee(!1)}},[v,Ke,e,t,n,M,Ie,te,o,ce,a,s,d,R,g,Ye,Ge,ue,yt,pt,Ve,K,_e]),W=vt(()=>ac(i),[i]),B=vt(()=>i.map(zy),[i]),H=vt(()=>l(Md,{onReady:f=>{lt(Ps(f,B))},onLoadError:f=>{lt("load_error"),Js(K,"stripe","wallet","provider_error")},onClick:async f=>{let ne=K?.now()??globalThis.performance?.now()??Date.now();wt.current=f.expressPaymentType,De.current=Sd(f.expressPaymentType);let L=!0,Se=window.setTimeout(()=>{L=!1,f.reject(),rt(f.expressPaymentType)},Hy),we=g?await g(De.current,{abandoned:()=>!L}):{proceed:!0};if(window.clearTimeout(Se),!L)return;if(!we.proceed){Et.current.delete(_e),f.reject();return}let k=G(f.expressPaymentType);Pt.current=!1,kt.current={generation:k,startedAt:ne},Et.current.set(_e,{generation:k,method:f.expressPaymentType,accountPatch:we.accountPatch,sessionId:we.sessionId,nonce:we.nonce}),Ae(!1),K?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:k,...f.expressPaymentType==="apple_pay"||f.expressPaymentType==="google_pay"?{walletType:f.expressPaymentType}:{}}),y?.(De.current),f.resolve()},onConfirm:m,onCancel:()=>{let f=Et.current.get(_e);Et.current.delete(_e);let ne=kt.current,L=K?.now()??globalThis.performance?.now()??Date.now();if(f&&ne?.generation===f.generation&&Ty({method:f.method,elapsedMs:L-ne.startedAt,handoffObserved:Ut.current===f.generation})){K?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:f.generation,walletType:"google_pay"}),xe.current=null,Ye(f.method,new Error("The browser window is too small for the Google Pay sheet."),Td,f.generation,!0);return}K?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...f?{attempt:f.generation}:{}}),Me(f?.generation),xe.current=null,Ae(!1),nt.current=!0,Rt()},options:{...ic,paymentMethods:W,emailRequired:zt,billingAddressRequired:zt}},_e),[B,W,m,Me,y,zt,Ye,rt,Rt,g,G,_e,K]);return Ue($n,{children:[l(Cs,{state:ze,placeholderTestId:"flopay-wallet-placeholder",borderRadius:U,children:Ue("div",{ref:ct,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Q&&Ue("button",{ref:dt,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Cn,style:Ws,children:["Try ",Hs(St)," again"]}),tt!=="idle"&&Ue("div",{role:"status","aria-live":"polite",children:[l("p",{children:"We are still confirming your payment. Check its status before trying again."}),l("button",{type:"button",onClick:S,disabled:tt==="checking",style:Ws,children:tt==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Nt&&l(Jo,{identity:Nt.identity,methodLabel:Nt.methodLabel,onComplete:Xe,onCancel:()=>Xe(null)},Nt.id),Ue("div",{style:{display:Nt||tt!=="idle"?"none":void 0},children:[l(Cm,{active:de}),H]})]})}),ft&&l(Br,{status:"processing"})]})}function Dd(e,t,n){let o=Ed(n,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function Ks({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:d,onErrorChange:y,onDecline:R,onCancel:C,runBeforeButtonClick:g,onButtonClick:M,isProcessing:te,submitButtonColor:le,submitButtonBorderRadius:U,submitButtonStyle:j,errorText:b}){let ge=oo(),{emitInstrument:ce}=aa(lr),v=Gs(),Ke=Vs(),[K,ze]=ee(!1),lt=O(!1),[ft,Ee]=ee(!1),[zt,Nt]=ee("loading"),[Ie,Xe]=ee(""),ct=!En(o?.trim()),dt=!ct||En(Ie.trim()),_e=Be(async()=>{if(!v||!Ke||te||lt.current||!ft)return;lt.current=!0,ze(!0);let X=g?await g("card"):{proceed:!0};if(!X.proceed){lt.current=!1,ze(!1);return}M?.("card");let de=X.sessionId??t,Kt=X.nonce??n,je=Ra(a?.trim()),ut=Cr({email:X.accountPatch?.email?.trim()||o?.trim()||Ie.trim(),firstName:X.accountPatch?.firstName?.trim()||je.firstName,lastName:X.accountPatch?.lastName?.trim()||je.lastName}),Q=ut.email,Ae=Cr({...X.accountPatch,...ut});try{if(y?.(null),!En(Q))throw new Error("A valid email address is required for payment.");await i?.(ut);let tt=await Ke.submit();if(tt.error){y?.(tt.error.message??"Payment failed.");return}let $=[ut.firstName,ut.lastName].filter(Boolean).join(" "),St=await v.createPaymentMethod({elements:Ke,params:{billing_details:{email:Q,...$?{name:$}:{}}}});if(St.error||!St.paymentMethod){y?.(St.error?.message??"Failed to create payment method.");return}let ve=St.paymentMethod;if(!de||!Q)throw new Error("Missing sessionId or email for payment.");let Ze=ve.type||e,qe=await Mi(s,ce,de,Kt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Ze,paymentMethodId:null,intentKind:"payment"});if(Ti(qe)){d({type:"card",gateway:"stripe",paymentMethodType:Ze},{accountPatch:Ae,paymentMethodCategory:"apm",sessionId:de,nonce:Kt,settledProcessResponse:qe.response});return}if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let nt=qe.clientSecret;sn(Or,{clientSecret:nt,sessionId:de,nonce:Kt,accountPatch:Ae,paymentMethodId:ve.id,paymentMethodType:ve.type??e,gateway:"stripe"});let{error:wt,paymentIntent:De}=await v.confirmPayment({clientSecret:nt,confirmParams:{return_url:window.location.href,payment_method:ve.id},redirect:"if_required"});if(wt){sn(Or);let Te=wt.message??"Payment failed.";y?.(Te),R?.(gn("card",Te,{code:wt.code})),await Ai({billingApiUrl:s,sessionId:de,nonce:Kt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:wt.code??"provider_declined"}});return}let It=De?.status;if(!wa(It)){sn(Or);let Te=It==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(Te),R?.(gn("card",Te,{code:It??"missing_payment_intent"}));return}sn(Or);let xe=typeof De?.payment_method=="string"?De.payment_method:De?.payment_method?.id;d({id:xe??ve.id,type:"card",threeDSecureActionResultTokenId:De?.id,gateway:"stripe",paymentMethodType:ve.type??e},{accountPatch:Ae,paymentMethodCategory:"apm",sessionId:de,nonce:Kt})}catch(tt){y?.(tt instanceof Error?tt.message:"Payment failed. Please try again.")}finally{lt.current=!1,ze(!1)}},[v,Ke,te,ft,g,M,t,n,o,a,Ie,i,s,ce,e,d,y,R]);return Ue("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ct&&l("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ct&&Ue("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",l("input",{type:"email",autoComplete:"email",required:!0,value:Ie,onChange:X=>Xe(X.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),l(jy,{onReady:()=>Nt("ready"),onLoadError:()=>{Nt("load_error"),Js(hn(ge),"stripe","apm")},onChange:X=>{Ee(!!X.complete)},options:{layout:sc,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...En(o?.trim())?{email:o?.trim()}:{}}}}}),l(lc,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{_e()},disabled:!ft||!dt||K||te||zt!=="ready",color:le,borderRadius:U,style:j,children:K?"Processing\u2026":`Pay with ${za(e)}`}),b&&l(Qo,{margin:"0.75rem 0 0",children:b})]})}function Rd({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:d,paymentElementBaseOptions:y,futureUseSession:R,onTokenizedBody:C,onErrorChange:g,onButtonClick:M,onDecline:te,runBeforeButtonClick:le,onLoadStateChange:U,isProcessing:j=!1,submitButtonColor:b="#4A49FF",submitButtonBorderRadius:ge=8,submitButtonStyle:ce,buttonAppearance:v,themeId:Ke,onExpandApm:K,expandedApmMethod:ze}){let{emitInstrument:lt}=aa(lr),[ft,Ee]=ee(null),[zt,Nt]=ee(null),Ie=O(!1),{request:Xe,collect:ct,finish:dt}=Yo();et(()=>{s.length>0&&d?U?.("ready"):d||U?.("loading")},[s.length,d,U]);let _e=Be(async Q=>{if(!d||Ie.current||j)return;Ie.current=!0,Nt(Q);let Ae=le?await le("card"):{proceed:!0};if(!Ae.proceed){Ie.current=!1,Nt(null);return}M?.("card");let tt=Ae.sessionId??e,$=Ae.nonce??t,St=Ra([Ae.accountPatch?.firstName,Ae.accountPatch?.lastName].filter(Boolean).join(" ")||o),ve=Cr({email:Ae.accountPatch?.email?.trim()||n?.trim(),firstName:Ae.accountPatch?.firstName?.trim()||St.firstName,lastName:Ae.accountPatch?.lastName?.trim()||St.lastName});if(!En(ve.email)){Nt(null);let nt=await ct(za(Q),ve);if(!nt){Ie.current=!1;return}ve=nt,Nt(Q)}let Ze=ve.email,qe=Cr({...Ae.accountPatch,...ve});try{if(g?.(null),!tt||!En(Ze))throw new Error("Missing sessionId or email for payment.");await a?.(ve);let nt=await Mi(i,lt,tt,$??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if(Ti(nt)){C({type:"card",gateway:"stripe",paymentMethodType:Q},{accountPatch:qe,paymentMethodCategory:"apm",sessionId:tt,nonce:$,settledProcessResponse:nt.response});return}if(nt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let wt=nt.clientSecret;sn(Or,{clientSecret:wt,sessionId:tt,nonce:$,accountPatch:qe,paymentMethodType:Q,gateway:"stripe"});let{error:De,paymentIntent:It}=await d.confirmPayment({clientSecret:wt,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:[ve.firstName,ve.lastName].filter(Boolean).join(" "),...Ze?{email:Ze}:{}}}},redirect:"if_required"});if(De){sn(Or);let kt=De.message??"Payment failed.";g?.(kt),te?.(gn("card",kt,{code:De.code})),await Ai({billingApiUrl:i,sessionId:tt,nonce:$,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:De.code??"provider_declined"}});return}let xe=It?.status;if(!wa(xe)){sn(Or);let kt=xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(kt),te?.(gn("card",kt,{code:xe??"missing_payment_intent"}));return}sn(Or);let Te=typeof It?.payment_method=="string"?It.payment_method:It?.payment_method?.id;C({id:Te??It?.id,type:"card",threeDSecureActionResultTokenId:It?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:qe,paymentMethodCategory:"apm",sessionId:tt,nonce:$})}catch(nt){g?.(nt instanceof Error?nt.message:"Payment failed. Please try again.")}finally{Ie.current=!1,Nt(null)}},[d,j,le,M,e,t,n,ct,i,lt,o,a,C,g,te]),[X,de]=ee(null),Kt=K?ze??null:X,je=Be(Q=>{Ie.current||j||Kt&&Kt!==Q||(pd(Q)?K?K(Q):de(Q):_e(Q))},[Kt,j,_e,K]),ut=vt(()=>X?Dd(y,X,R):null,[X,y,R]);return l("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Xe?l(Jo,{identity:Xe.identity,methodLabel:Xe.methodLabel,onComplete:dt,onCancel:()=>dt(null)},Xe.id):s.map(Q=>{let Ae=ze===Q,tt=zt===Q,$=zt!==null&&zt!==Q||ze!=null&&ze!==Q;return Ue(Na.Fragment,{children:[l(oc,{method:Q,themeId:Ke,submitting:tt,disabled:$,highlighted:Ae,hasNextStep:pd(Q),onClick:()=>je(Q),backgroundColor:v?.backgroundColor,borderColor:v?.borderColor,textColor:v?.textColor,borderRadius:v?.borderRadius,fontFamily:v?.fontFamily}),!K&&X===Q&&ut&&d&&l(ko,{stripe:d,options:ut,children:l(Ks,{method:Q,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:C,onErrorChange:g,onDecline:te,onCancel:()=>de(null),runBeforeButtonClick:le,onButtonClick:M,isProcessing:j,submitButtonColor:b,submitButtonBorderRadius:ge,submitButtonStyle:ce})},Q)]},Q)})})}function bm({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:d,onDecline:y,onCancel:R,onTokenizedBody:C,firstName:g,lastName:M,chv:te,className:le,submitLabel:U,isProcessing:j,error:b,onErrorChange:ge,showPayPal:ce=!0,showStripe:v=!0,walletPresentation:Ke="auto",enabledPaymentMethods:K,enabledPaymentMethodCountries:ze,showApplePay:lt=!0,showGooglePay:ft=!0,layout:Ee="default",paymentMethodLayout:zt,moreOptionsLabel:Nt,theme:Ie,buttonsTheme:Xe,buttonsStyles:ct,appearance:dt,cardButtonContent:_e,cardBackButtonContent:X,cardTitleContent:de,showSecurityFooter:Kt,onButtonClick:je,onBeforeButtonClick:ut,onBuyerIdentityReady:Q,enableAVS:Ae,cardFieldOrder:tt,showCardBrandIcons:$,showCardFieldLabels:St,cardFieldLabels:ve,cardFieldPlaceholders:Ze,cardAutoFocus:qe,onCardFieldsReady:nt,onCardFieldsFailed:wt,cardFieldsTimeoutMs:De,cardPreFormSlot:It,avsLayout:xe="row",country:Te,zip:kt,addressLine1:Ut,addressLine2:Et,city:G,state:ue,onCountryChange:Me,onZipChange:pt,avsCheck:yt,checkoutType:Ve,checkoutLayout:gt,totalAmount:Pt=0,currency:Rt="usd",initialCardOpen:Ge=!1,directPaypal:Ye,isSubscription:rt=!1,session:F,dataAttachmentPending:Cn=!1,dataAttachmentRequiresIdentity:S=!1,debug:m=!1}){let W=oo(),B=ks(),H=aa(Pr),{emitInstrument:f}=aa(lr),ne=O(null);ne.current||(ne.current=pi());let L=ne.current,[,Se]=ee(0),we=O(null);we.current||(we.current=ba());let k=we.current,ot=vt(()=>({browser:k,capability:L,presentationMode:"popup"}),[k,L]),Yt=F??H.session,qt=vt(()=>({futureUse:Yt?.futureUse,futureUseUnsupported:Yt?.futureUseUnsupported}),[Yt?.futureUse,Yt?.futureUseUnsupported]),On=Yt?.gateways?.paypal?.providerObjectType??Ye?.providerObjectType,be=Cn||H.claimPending===!0,wr=S||H.claimRequiresIdentity===!0,pn=be&&!wr,yn=Mc(),at=n||yn,Ft=dd({rules:zt,sessionId:e,nonce:t,billingApiUrl:at,waitForSession:pn}),_n=Ft?.order??null,[Wn,Tn]=ee(!1),wn=vt(()=>_n?My(_n):null,[_n]),kn=_n!==null&&Ry(_n),[Jt,jt]=ee(!1),[tn,Je]=ee(null),[pe,Qn]=ee(Te??""),[Bt,Mn]=ee(kt??""),[Ln,er]=ee(Ut??""),[Nn,kr]=ee(Et??""),[ur,mn]=ee(G??""),[fn,An]=ee(ue??""),[Hn,Un]=ee(""),[xn,ln]=ee({}),nn=O(kt??""),rn=O(Te??""),Xt=O(Ut??""),zn=O(Et??""),qn=O(G??""),Fn=O(ue??""),I=O(""),We=O({});et(()=>{let r=(p,_,J,A,fe)=>{if(We.current[p])return;let Tt=_?.trim();!Tt||Tt===J.current||(J.current=Tt,A(Tt),fe?.(Tt))};r("country",Te,rn,Qn,Me),r("zip",kt,nn,Mn,pt),r("addressLine1",Ut,Xt,er),r("addressLine2",Et,zn,kr),r("city",G,qn,mn),r("state",ue,Fn,An)},[Te,kt,Ut,Et,G,ue,Me,pt]);let h=vt(()=>Dy(Ae),[Ae]),re=h!==null,mt=vt(()=>Os(F),[F]),He=Iy(F?.vault),$t=!!F?.gateways?.pcivault,ke=kc(F),Ur=!!(F?.gateways?.stripe?.enabledPaymentMethods??K)?.includes("card")||bo(F),Rn=He||Ur||$t,ye=!!(v&&Rn&&e),[Vr,uo]=ee(()=>Ee!=="buttons"||Ge?e??null:null),[po,pr]=ee(0),tr=Ee!=="buttons"||Ge||!!e&&Vr===e,Jn=F?.captureMethod,Kn=O(W);et(()=>{Kn.current=W},[W]);let Dt=O(De);Dt.current=De;let Ir=O({onCardFieldsReady:nt,onCardFieldsFailed:wt,emitInstrument:f});Ir.current={onCardFieldsReady:nt,onCardFieldsFailed:wt,emitInstrument:f};let[In,nr]=ee(null);et(()=>{if(!ye||!e||!tr){nr(null);return}let r=Kn.current?Kn.current.cardCapture({sessionId:e,captureMethod:Jn,cardFieldsTimeoutMs:Dt.current}):new ay({sessionId:e,captureMethod:Jn,billingApiUrl:at,telemetry:o,cardFieldsTimeoutMs:Dt.current}),p=r.onCardFields?.(_=>{let J=Ir.current;J.emitInstrument?.(my(_)),_.type==="card_fields_ready"?ud(()=>J.onCardFieldsReady?.(_)):ud(()=>J.onCardFieldsFailed?.(_))});return nr({sessionId:e,captureMethod:Jn,billingApiUrl:at,telemetry:o,capture:r}),()=>{p?.(),r.unmount()}},[ye,e,tr,Jn,at,o]);let he=ye&&e&&tr&&In?.sessionId===e&&In.captureMethod===Jn&&In.billingApiUrl===at&&In.telemetry===o?In.capture:null,Bn=vt(()=>{let r=pe,p=h?Qt(h.postal_code,r):!1;return ym(r,Bt,p)},[h,pe,Bt]),{avsInvalid:yr,invalidAvsFields:Er}=vt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!ye||!h)return{avsInvalid:!1,invalidAvsFields:r};let p=pe,_=(fe,Tt)=>Qt(fe,p)&&!Tt.trim(),J={line1:_(h.address_line_1,Ln),city:_(h.city,ur),state:_(h.state,fn),zip:Bn.empty||Bn.malformed};return{avsInvalid:J.line1||J.city||J.state||J.zip,invalidAvsFields:J}},[ye,h,pe,Ln,ur,fn,Bn]),[rr,_r]=ee(!1),[Tr,yo]=ee(!1),[zr,Gr]=ee(!1),[Yr,_o]=ee({line1:!1,city:!1,state:!1}),Mr=O(!1),mr=O({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Jr=O(!1),_t=Be(r=>{mr.current[r]=!0,Jr.current=!0},[]),qr=Be(r=>!Mr.current&&mr.current[r],[]),Vn=Be(r=>{qr(r)&&_o(p=>p[r]?p:{...p,[r]:!0})},[qr]),[or,bn]=ee(()=>Ns(F?.vault,{billingApiUrl:at,sessionId:e,nonce:t})),[Oe,cn]=ee(Ge&&Rn?"card":"buttons"),[Vt,w]=ee(null),T=Oe==="expanding"||Oe==="card",z=F?.gateways?.stripe&&!ke?"stripe":void 0,Y=Be(()=>{f?.({class:"card_surface",provider:z})},[z,f]),Ct=Be(()=>{Tn(!0),f?.({class:"more_options"})},[f]),Gt=O(null),V=Be(r=>{Gt.current&&clearTimeout(Gt.current),Gt.current=setTimeout(()=>{Gt.current=null,r()},qa)},[]);et(()=>()=>{Gt.current&&clearTimeout(Gt.current)},[]);let Le=O(!1),[D,u]=ee(0),c=O(null),E=Be(()=>{Y(),uo(e??null),Le.current&&(Le.current=!1,u(r=>r+1)),pr(r=>r+1),cn("expanding"),V(()=>cn("card"))},[V,Y,e]),P=Be(()=>{cn("collapsing"),V(()=>cn("buttons"))},[V]),x=Be(r=>{w(r),cn("apm-expanding"),V(()=>cn("apm-form"))},[V]),oe=Be(()=>{cn("apm-collapsing"),V(()=>{cn("buttons"),w(null)})},[V]);et(()=>{Ee==="buttons"&&Ge&&Rn&&(uo(e??null),cn("card"))},[Ee,Ge,Rn,e]);let[Qe,ae]=ee(null),me=O(null),[Pe,At]=ee(0);et(()=>{Pe!==0&&me.current?.focus()},[Pe]);let ie=O(!1),N=O(null),q=O("idle"),[Z,Re]=ee(!1),Ot=O(Z);Ot.current=Z;let[$e,la]=ee(()=>Ye?.existingOrderId?{orderId:Ye.existingOrderId,attempts:1}:null),cl=O($e);et(()=>{cl.current=$e},[$e]);let Li=O(null),eu=vt(()=>{if(Q||H.claimBuyerIdentity||F?.buyerIdentified!==!1||!e||!t)return;let r=`${at}|${e}|${t}`;Li.current?.key!==r&&(Li.current={key:r,claim:Ko(new oa(at,{telemetry:!1}),e,t,{...i?{userId:i}:{},...g?{firstName:g}:{},...M?{lastName:M}:{}})});let p=Li.current.claim;return async _=>{await p(_)}},[Q,H.claimBuyerIdentity,F?.buyerIdentified,e,t,at,i,g,M]),ar=Q??H.claimBuyerIdentity??eu,fr=b??tn,To=vt(()=>Ly(Ie),[Ie]),Fe=vt(()=>{let r=To?.buttonsLayout??Oy(Xe);return ct?{...r,...ct,cardButton:{...r.cardButton,...ct.cardButton},cardFormContainer:{...r.cardFormContainer,...ct.cardFormContainer},backButton:{...r.backButton,...ct.backButton},backButtonIcon:{...r.backButtonIcon,...ct.backButtonIcon},submitButton:{...r.submitButton,...ct.submitButton},title:{...r.title,...ct.title}}:r},[To,Xe,ct]),Mo=dt??To?.appearance,tu=vt(()=>hy({appearance:Mo,buttonsStyles:Fe,layout:Ee}),[Mo,Fe,Ee]),nu=H.inlineSessionPatchProcessing??!1,on=(j??Jt)||nu,Xr=at.replace(/\/+$/,""),ht=vt(()=>Ss({userId:i,email:a,firstName:g,lastName:M,country:Te,zip:kt},xn),[i,a,g,M,Te,kt,xn]),Ao=[ht.firstName,ht.lastName].filter(r=>!!r?.trim()).join(" "),dl=!En(ht.email?.trim()),Ni=O(null);ye&&Ni.current===null&&(Ni.current=dl);let Zr=ye&&(Ni.current??dl),Ui=vt(()=>mm(Hn,Zr),[Hn,Zr]),xo=Ui.empty||Ui.malformed,Xn=vt(()=>W?W.getRawProvider():null,[W]),ul=vt(()=>B?B.getRawProvider():null,[B]),ca=Pt||100,Fo=Rt.toLowerCase(),zi=vt(()=>Mo?iy(Mo):null,[Mo]),Bo=zi,pl=vt(()=>{let r=zi??{},p=r.rules??{};return{...r,rules:{...p,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...p[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...p[".AccordionItemContents"]??{}}}}},[zi]),yl=vt(()=>({...wc(Pt,Yt?.captureMethod,qt),currency:Fo,...Bo?{appearance:Bo}:null}),[Pt,Fo,Yt?.captureMethod,qt,Bo]),qi=Ed(qt,"paypal","paypal"),ml=vt(()=>({mode:"payment",amount:ca,currency:Fo,captureMethod:"manual",...qi?{setupFutureUsage:qi}:null,...Bo?{appearance:Bo}:null}),[ca,Fo,qi,Bo]),Ce=Be(r=>{Je(r),ge?.(r)},[ge]),fl=O(0);et(()=>{D!==fl.current&&(fl.current=D,Ce(null))},[D,Ce]);let ji=O(""),[gl,ru]=ee(!1),$i=Be(()=>{ru(!0)},[]);et(()=>{if(!ye||!Zr||!ar||!gl||xo||ji.current)return;let r=Cr({email:En(ht.email?.trim())?ht.email?.trim():I.current.trim(),firstName:ht.firstName?.trim(),lastName:ht.lastName?.trim()});ji.current=JSON.stringify(r),ln(p=>({...p,...r})),Promise.resolve(ar(r)).catch(p=>{ji.current="",Ce(p instanceof Error?p.message:"Failed to attach buyer details.")})},[ye,Zr,ar,gl,xo,ht.email,ht.firstName,ht.lastName,Ce]),et(()=>{if(!ye||!he)return;let r=qe!==!1&&h==null&&!Zr;he.setCardFieldOrder?.(tt??null,r)},[ye,he,tt,qe,h,Zr]),et(()=>{!ye||!he||he.setCardBrandIcons?.($===!0)},[ye,he,$]);let Wi=O(null);et(()=>{if(!(!ye||!he)){if(St===void 0){if(Wi.current!==he)return;Wi.current=null,he.setShowCardFieldLabels?.(!1);return}Wi.current=he,he.setShowCardFieldLabels?.(St===!0)}},[ye,he,St]);let Hi=ve===void 0?void 0:JSON.stringify(sy(ve)),Ki=O(null);et(()=>{if(!(!ye||!he)){if(Hi===void 0){if(Ki.current!==he)return;Ki.current=null,he.setCardFieldLabels?.(null);return}Ki.current=he,he.setCardFieldLabels?.(JSON.parse(Hi))}},[ye,he,Hi]);let Vi=hm(Ze),Gi=O(null);et(()=>{if(!(!ye||!he)){if(Vi===null){if(Gi.current!==he)return;Gi.current=null,he.setCardFieldPlaceholders?.(void 0);return}Gi.current=he,he.setCardFieldPlaceholders?.(JSON.parse(Vi))}},[ye,he,Vi]),et(()=>{(Oe==="expanding"||Oe==="collapsing"||Oe==="apm-expanding"||Oe==="apm-collapsing")&&Ce(null)},[Oe,Ce]);let Ar=Be((r,p,_)=>{y?.(gn(r,p,_))},[y]),hl=O(Oe);hl.current=Oe;let[Pl]=ee(mi),Cl=Be(()=>{let r=hl.current;if(Ee==="buttons"&&(r==="card"||r==="expanding"))return!0;let p=q.current;return p==="validation-window"||p==="processing"||Ot.current},[Ee]),bl=Be((r,p,_)=>{Pl.take(e)&&hn(W)?.log(wo({...ot,presentationMode:_?.presentationMode??"popup"},{name:yi,stage:"recovery",reason:"other_method_active",provider:_?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:_?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[ot,W,Pl,e]),Ha=Be((r,p,_)=>{_?.telemetryReported||hn(W)?.error(wo({...ot,presentationMode:_?.presentationMode??"popup"},{errorCode:p?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:_?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:_?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:_?.terminalReason??(p?"popup_blocked":"provider_error")}))},[ot,W]),Do=Be((r,p,_)=>{let J=_?.popupBlocked??to(p);if(Cl()){Ha(r,J,_),bl(r,p,_);return}if(p instanceof br&&p.code==="checkout_processing_timeout"){Ha(r,!1,_),ae(null),Ee==="buttons"&&(cn("buttons"),w(null)),Ce(p.message),d?.(p);return}J&&L.markBlocked()&&Se(it=>it+1);let A=Hs(r),fe=_?.code===Td?dy(A):oi(A,J,k.inAppBrowser),Tt=qo(p),Mt=(Tt?.toLowerCase()==="error"?void 0:Tt)??nc(_?.code)??"external_payment_method_failed",Ne=new br(fe,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:Mt,popupBlocked:J,inAppBrowser:k.inAppBrowser,appFamily:k.appFamily,popupCapability:L.current(),presentationMode:_?.presentationMode??"popup"}});Ha(r,J,_),ae(null),Ee==="buttons"&&(cn("buttons"),w(null)),Ce(fe),d?.(Ne),console.error("[FloPay] External payment method failed:",{method:r,code:Mt,popupBlocked:J})},[k,Cl,Ee,d,L,bl,Ha,Ce]);et(()=>{if(!ye||!e){bn(null);return}let r={billingApiUrl:Xr,sessionId:e,nonce:t},p=Ns(F?.vault,r);if(p){bn(p);return}if(!tr){bn(null);return}let _=`${Xr}\0${e}\0${t??""}`,J=c.current;if(J&&J.key===_){bn(J.mount);return}bn(null);let A=!0;return new oa(Xr).getVaultCapture(e,t).then(fe=>{if(!A)return;let Tt=Ns(fe,r);Tt?.verificationRequired&&!fe.html&&(c.current={key:_,mount:Tt}),Tt?bn(Tt):Ce("Failed to load the secure card form.")}).catch(fe=>{A&&Ce(fe instanceof Error?fe.message:"Failed to load the secure card form.")}),()=>{A=!1}},[ye,tr,po,e,F?.vault,Xr,t,Ce]);let gr=O({onComplete:s,onError:d,updateError:Ce,emitDecline:Ar,resolvedAccount:ht,avsConfig:h,avsCheckProp:yt,sessionId:e,nonce:t,baseUrl:Xr,captureMethod:F?.captureMethod,paymentId:F?.paymentId,authorizationExpiresAt:F?.authorizationExpiresAt,serverSideCardGateway:ke});gr.current={onComplete:s,onError:d,updateError:Ce,emitDecline:Ar,resolvedAccount:ht,avsConfig:h,avsCheckProp:yt,sessionId:e,nonce:t,baseUrl:Xr,captureMethod:F?.captureMethod,paymentId:F?.paymentId,authorizationExpiresAt:F?.authorizationExpiresAt,serverSideCardGateway:ke};let Yi=O(!1),vl=Be(()=>{let r=gr.current,p=r.resolvedAccount.email?.trim(),_=En(p)?p:I.current.trim();if(!En(_))return null;let J=r.resolvedAccount.firstName?.trim(),A=r.resolvedAccount.lastName?.trim(),fe=rn.current.trim()||r.resolvedAccount.country?.trim()||"",Tt=r.avsConfig?Qt(r.avsConfig.state,fe):!1,Mt=r.avsConfig?Qt(r.avsConfig.address_line_1,fe):!1,Ne=r.avsConfig?Qt(r.avsConfig.postal_code,fe):!1,it=r.avsConfig?Qt(r.avsConfig.city,fe):!1,bt=r.avsConfig?Qt(r.avsConfig.address_line_2,fe):!1,dn=Mt&&!Tt&&Ne?Sy(fe,(nn.current??"").trim()):null,Zn=Tt?Fn.current:dn;return{accountData:{userId:r.resolvedAccount.userId??"",email:_,...J?{firstName:J}:{},...A?{lastName:A}:{},...Ne&&nn.current?{zip:nn.current}:{},...it&&qn.current?{city:qn.current}:{},...Zn?{state:Zn}:{},...Mt&&Xt.current?{addressLine1:Xt.current}:{},...bt&&zn.current?{addressLine2:zn.current}:{},...fe?{country:fe}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Qt(r.avsConfig.country,fe),postal_code:Ne,address_line_1:Mt,address_line_2:bt,city:it,state:Tt}}:{}}},[]),Sl=O(be);Sl.current=be,et(()=>{be||fr!==Cd||gr.current.updateError(null)},[be,fr]),et(()=>{!ye||!he||he.setSubmitGate?.(yr||be||xo||Z)},[ye,he,yr,be,xo,Z]),et(()=>{if(!ye||!he)return;Yi.current=!1;let r=null,p=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,q.current="idle",ae(null)},400)},_=he.on("submitting",()=>{_r(!0),N.current&&clearTimeout(N.current),q.current="validation-window",N.current=setTimeout(()=>{N.current=null,q.current==="validation-window"&&(q.current="processing")},rm),ae("processing");let Ne=gr.current;if(!Ne.sessionId||!Ne.nonce)return;let it=vl();if(!it){Ne.updateError("Enter a valid email address."),q.current="idle",ae(null);return}new oa(Ne.baseUrl).patchAccountSnapshot(Ne.sessionId,Ne.nonce,it,{telemetryMode:"best_effort"}).catch(bt=>{if(!am(bt))return;let dn=bt instanceof Error?bt.message:"Please check your billing address and try again.";Ne.updateError(dn),q.current="idle",ae(null),Ne.onError?.(bt instanceof br?bt:new br(dn,"api_error"))})}),J=he.on("complete",Ne=>{ea(Ne.sessionId??gr.current.sessionId),q.current="terminal",Re(!1),ae("success"),setTimeout(()=>{if(Yi.current)return;Yi.current=!0;let it=gr.current,bt=Os(it)||Ne.outcome==="authorized",dn=it.serverSideCardGateway?{}:{paymentIntentId:Ne.intentId};gr.current.onComplete?.(bt?{status:"authorized",...dn,paymentId:Ne.paymentId??it.paymentId,sessionId:Ne.sessionId??it.sessionId,authorizationExpiresAt:Ne.authorizationExpiresAt??it.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...dn,checkoutMethod:"card"})},600)}),A=he.on("decline",Ne=>{let it=gr.current,bt=Ne.message??"Your payment was declined. Please try another card or contact your bank.";q.current="terminal",Re(!1),it.updateError(bt),ae("error");let dn=Ne.failureOutcome??Ay(Ne.declineReason)??"authorization_declined";it.emitDecline("card",bt,{code:dn,declineCode:dn}),p()}),fe=he.on("error",Ne=>{let it=gr.current,bt=uy(Ne.vaultOutcome);if(bt!==null){r&&(clearTimeout(r),r=null),q.current="idle",Re(!1),it.updateError(bt),ae(null),At(Zn=>Zn+1),it.onError?.(new br(bt,"api_error",{code:py}));return}let dn=Ne.message??"There was a problem processing your payment. Please try again.";q.current="terminal",Re(!1),it.updateError(dn),ae("error"),it.onError?.(new br(dn,"api_error",{code:Ne.failureOutcome??"capture_failed"})),p()}),Tt=he.on("challenge_dismissed",()=>{N.current&&(clearTimeout(N.current),N.current=null),q.current="processing",Re(!0),ae(null)}),Mt=he.on("blocked",()=>{if(Ot.current){gr.current.updateError(om);return}if(!Sl.current){_r(!0);return}$i(),gr.current.updateError(Cd)});return()=>{r&&(clearTimeout(r),r=null),N.current&&(clearTimeout(N.current),N.current=null),q.current="idle",Re(!1),ae(null),_(),J(),A(),fe(),Tt(),Mt()}},[ye,he,$i,vl]);let xr=!!Ye?.clientId,da=Array.isArray(K),Ka=da&&K.length>0,wl=da&&K.includes("paypal"),Va=O(null);Va.current===null&&(Va.current=ky());let Oo=Va.current?"redirect":rc(k,Ke,L.current()),{expressMethods:Ga,paymentElementMethods:Ji}=vt(()=>xy(K,{excludePaypal:xr}),[K,xr]),kl=xr||!!B||wl&&Oo==="redirect",ou=vt(()=>kl?Ga.filter(r=>r!=="paypal"):Ga,[Ga,kl]),au=vt(()=>{let r=[];return lt&&r.push("apple_pay"),ft&&r.push("google_pay"),r},[lt,ft]),Lo=da?ou:au,iu=v&&Lo.length>0,Rl=re?pe:Te,Ya=vt(()=>by(Ji,Rl,ze),[Ji,Rl,ze]),Xi=vt(()=>({mode:"payment",amount:ca,currency:Fo,paymentMethodCreation:"manual",appearance:pl}),[ca,Fo,pl]),[Zi,Il]=ee("loading"),[Qi,El]=ee("loading"),[es,_l]=ee("loading"),[su,ts]=ee(!1),[Tl,ns]=ee("loading"),[rs,lu]=ee();et(()=>{lu(ba())},[]);let Ja=rs?.inAppBrowser,Xa=rs?ii(rs,Ye?.approvalPresentation,On??(rt?"subscription":"order")):"popup",Ml=ce&&(xr||(da?wl:Ja===!1)),cu=k.inAppBrowser&&L.current()==="blocked",Al=v&&iu&&!cu,mo=(!pn||!!H.waitForDataAttachment)&&Ml&&xr,os=Tl==="retrying"||Tl==="exhausted",ua=null;v&&(B?ua=ul:Oo==="redirect"&&(ua=Xn));let xl=vt(()=>({...ot,presentationMode:Oo}),[ot,Oo]),fo=!pn&&Ml&&!!ua&&(!xr||os),Qr=!pn&&Al&&!!Xn,go=!pn&&v&&Ka&&Ya.length>0&&!!Xn,du=mo&&!os?su:fo&&va(Zi),uu=Qr&&va(Qi),pu=go&&es!=="load_error",Fl=[mo||fo,Qr,go,ye].filter(Boolean).length,yu={card:ye,paypal:mo&&!os||fo&&va(Zi),wallets:Qr&&va(Qi),apms:go&&es!=="load_error"},Bl=r=>yu[r],Dl=r=>r==="loading"||r==="ready",Ol=mo||fo&&Dl(Zi)||Qr&&Dl(Qi)||go&&es!=="load_error",Za=O(!1);et(()=>{if(!Za.current){if(!v&&!ce){Za.current=!0;let r=new br("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(r),Ce(r.message)}else if(!v&&ce&&!xr){Za.current=!0;let r=new br("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(r),Ce(r.message)}else if(Ja!==void 0&&!pn&&!Rn&&!Ol){Za.current=!0;let r=new br("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});d?.(r),Ce(r.message)}}},[v,ce,xr,Ja,pn,Rn,Ol,d,Ce]);let Ll=O(!1);et(()=>{if(Ll.current||!Ka)return;let r=[];lt!==!0&&r.push("showApplePay"),ft!==!0&&r.push("showGooglePay"),r.length!==0&&(Ll.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.`))},[Ka,lt,ft]);let Nl=Be((r,p,_)=>H.applyInlineSessionPatch?H.applyInlineSessionPatch(r).then(J=>({error:null,sessionId:J.sessionId||e,nonce:J.session?.clientSecret||t})).catch(J=>{let A=yd(p,J);return _?.abandoned?.()||(Ce(A.message),d?.(A)),{error:A,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[H.applyInlineSessionPatch,t,d,e,Ce]),hr=Be(async(r,p)=>{if(r!=="card"&&pn&&await H.waitForDataAttachment?.(),!ut)return{proceed:!0};try{let _=await ut({method:r,sessionId:e||void 0,createSession:H.inlineSessionDraft});if(_===!1)return{proceed:!1};if(_&&typeof _=="object"){_.account&&ln(A=>({...A??{},..._.account}));let J=await Nl(_,r,p);return J.error?{proceed:!1,accountPatch:_.account}:{proceed:!0,accountPatch:_.account,sessionId:J.sessionId,nonce:J.nonce}}return{proceed:!0}}catch(_){if(!p?.abandoned?.()){let J=yd(r,_);Ce(J.message),d?.(J)}return{proceed:!1}}},[Nl,H.inlineSessionDraft,H.waitForDataAttachment,pn,ut,d,e,Ce]),Ul=Be(async(r,p)=>{if(ie.current)return;ie.current=!0,jt(!0),ae("processing"),Ce(null);let _=p?.sessionId??e,J=p?.nonce??t,A=Ss(ht,p?.accountPatch),fe=p?.completionPaymentMethodId??ka(r),Tt=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,Mt=cm(r),Ne=p?.presentationMode?Ri(hn(W),{...ot,presentationMode:p.presentationMode}):void 0,it=()=>{f?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Mt}),Ne?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...vr,requestCategory:"process_payment"})};try{let bt=new oa(Xr),Zn=p?.settledProcessResponse??await bt.processPayment(A.userId??"",{sessionId:_,nonce:J,paymentMethodCategory:p?.paymentMethodCategory??um(r),tokenizedData:Tt,accountData:{...p?.accountPatch,userId:A.userId??"",email:A.email??"",firstName:A.firstName||void 0,lastName:A.lastName||void 0,...cy({avsConfig:h,country:rn.current,zip:nn.current,city:qn.current,state:Fn.current,addressLine1:Xt.current,addressLine2:zn.current})},...ly({chv:te,avsCheck:yt,checkoutType:Ve,checkoutLayout:gt,avsConfig:h,country:rn.current})}),ri=async vn=>{let ho=Os(F)||vn?.status==="authorized";ea(_),Ne?.terminal({outcome:"payment_succeeded",...vr}),ae("success"),la(null),await new Promise(Pa=>setTimeout(Pa,600));let Fr;typeof vn?.paymentId=="string"?Fr=vn.paymentId:F?.paymentId&&(Fr=F.paymentId);let Po;typeof vn?.authorizationExpiresAt=="string"?Po=vn.authorizationExpiresAt:F?.authorizationExpiresAt&&(Po=F.authorizationExpiresAt),s?.(ho?{status:"authorized",...Fr===void 0?{}:{paymentId:Fr},sessionId:typeof vn?.sessionId=="string"?vn.sessionId:_,...Po===void 0?{}:{authorizationExpiresAt:Po},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:r.isPaypal?"paypal":"card"})};if(Zn.ok){await ri(Zn.status===204?null:await Zn.json().catch(()=>null));return}let un=await Zn.json().catch(()=>null);if(un?.type==="paypal_redirect_required"){let vn=un.threeDSecureToken,ho=un.paymentMethodId||r.id||"";if(!W||!vn){ae("error"),Ce("PayPal authorization required but no token provided.");return}try{let Fr=B?.getRawProvider();if(!Fr){Ce("PayPal is not available.");return}let Po={return_url:window.location.href};ho&&(Po.payment_method=ho);let{error:Pa}=await Fr.confirmPayment({clientSecret:vn,confirmParams:Po,redirect:"if_required"});if(Pa){ae("error");let Ql=Pa.message??"PayPal payment failed.";Ce(Ql),Ar("paypal",Ql,{code:Pa.code})}}catch(Fr){ae("error"),Ce(Fr instanceof Error?Fr.message:"PayPal authorization failed.")}return}if(un?.type==="paypal_direct_required"){let vn=un.orderId;if(!vn){ae("error"),Ce("PayPal retry required but no order id provided.");return}let ho=cl.current?.attempts??0;if(ho>=2){ae("error"),Ce("PayPal payment could not be completed after multiple attempts."),Ar("paypal","paypal_direct_required retry limit exceeded");return}ts(!1),ns("loading"),la({orderId:vn,attempts:ho+1}),ae(null);return}if(Zn.headers.get(Jy)===Xy){let vn=await Zy(bt,_,J);if(vn!==void 0){await ri(vn);return}}fy(Zn.status,un)?Ne?.terminal({outcome:"payment_declined",...vr,terminalReason:"provider_declined"}):it(),ae("error");let Zl=un?.message??"Payment failed. Please try again.";Ce(Zl),Ar(r.isPaypal?"paypal":"card",Zl,{code:un?.code??un?.gatewayErrorCode,declineCode:un?.declineCode??un?.gatewayDeclineReason}),await new Promise(vn=>setTimeout(vn,400))}catch(bt){Fd(bt)||it(),ae("error"),Ce(bt instanceof Error?bt.message:"An unexpected error occurred"),await new Promise(dn=>setTimeout(dn,400))}finally{jt(!1),ae(null),ie.current=!1}},[Xr,e,t,ht,h,yt,Ve,gt,te,W,B,F,s,Ce,Ar,f,ot]),Gn=Be((r,p)=>{C&&!p?.settledProcessResponse?C(r):Ul(r,p)},[C,Ul]),pa=`${Ad}:${e}`;et(()=>{if(typeof window>"u")return;let r=localStorage.getItem(pa);if(!r)return;let p;try{p=JSON.parse(r)}catch{sn(pa);return}if(!p||typeof p.createdAt!="number"||Date.now()-p.createdAt<0||Date.now()-p.createdAt>xd||typeof p.paymentMethodId!="string"||typeof p.providerIntentId!="string"||typeof p.paymentMethodType!="string"||p.sessionId!==e||!t||p.nonce!==t||!Lo.includes(p.paymentMethodType)){sn(pa);return}sn(pa),Gn({id:p.paymentMethodId,type:"card",threeDSecureActionResultTokenId:p.providerIntentId,gateway:"stripe",paymentMethodType:p.paymentMethodType},{...p.accountPatch?{accountPatch:p.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Gn,t,e,pa,Lo]);let zl=O(!1);et(()=>{if(typeof window>"u"||zl.current)return;let[r,p,_]=Id();if(!r||!p||Va.current||!W)return;let J=W.getRawProvider();if(!J)return;let A=it=>{let bt=localStorage.getItem(it);if(!bt)return null;try{return JSON.parse(bt)}catch{return sn(it),null}},fe=A(Or)??A(gd),Tt;if(fe?.clientSecret){if(fe.clientSecret!==p)return;Tt={...fe.accountPatch?{accountPatch:fe.accountPatch}:{},...fe.sessionId?{sessionId:fe.sessionId}:{},...fe.nonce?{nonce:fe.nonce}:{}}}else if(fe?.sessionId&&fe.sessionId!==e)return;zl.current=!0,sn(Or),sn(gd),window.history.replaceState({},"",_d());let Mt=fe?.paymentMethodType??fe?.tokenType??"card",Ne="card";(async()=>{if(_==="failed"){let un="Payment was declined. Please try again.";Ce(un),Ar(Ne,un);return}let{paymentIntent:it,error:bt}=await J.retrievePaymentIntent(p);if(bt){let un=bt.message??"Failed to retrieve payment status.";Ce(un),Ar(Ne,un,{code:bt.code});return}let dn=it?.status,Zn=wa(dn);if(!it||!Zn){let un=dn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ce(un),Ar(Ne,un,{code:dn??"missing_payment_intent"});return}let ri=typeof it.payment_method=="string"?it.payment_method:it.payment_method?.id;Gn({id:ri??fe?.paymentMethodId??fe?.tokenId??it.id,type:"card",threeDSecureActionResultTokenId:it.id,gateway:fe?.gateway??"stripe",paymentMethodType:Mt},Tt)})()},[e,Gn,W,Ce,Ar]);let as=Be(r=>{r.preventDefault()},[]);if(!(ye||W!==null))return l("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ya=Ee==="buttons",jn=Mo?.variables,mu=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),is=jn?.colorBackground,fu=is&&!mu.has(is)?is:void 0,ma=Fe.cardInputBorder??(ya?"#e5e7eb":"#A4A4FF"),ql=jn?.colorDanger??"#dc2626",Zt=r=>Er[r]&&(Yr[r]||rr),Qa=xo&&(zr||rr),ir=r=>r?ql:ma,ei=(Bn.malformed||Bn.empty)&&(Tr||rr),gu=ir(ei),ss=Fe.cardFormContainer?.backgroundColor??fu??(ya?"white":"#EDEDFF"),No=Fe.cardInputBackground??jn?.colorBackground??"white",ls=jo(X),jl=jo(de),Uo=Fe.nameInput,$l=Fe.cardInputFontSize??fm(Uo?.fontSize)??jn?.fontSizeBase??"16px",Wl=typeof Uo?.fontFamily=="string"?Uo.fontFamily:jn?.fontFamily??"Poppins, sans-serif",Hl=qy(Uo?.fontWeight)??400,hu=Fe.cardInputColor??(typeof Uo?.color=="string"?Uo.color:void 0)??jn?.colorText??"#262833",Pu=Fe.cardInputPlaceholderColor??"#9ca3af",an=jn?.borderRadius??"8px",jr=jn?.borderRadius??Fe.cardButton?.borderRadius??an,eo=jn?.colorPrimary??"#4A49FF",Cu=jn?.colorPrimaryHover??Py(eo,.12),cs=jn?.colorText??"#262833",ds={fontSize:$l,fontFamily:Wl,fontWeight:Hl,color:hu,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},fa={marginTop:"0.375rem",...ds,fontSize:"0.75rem",lineHeight:1.4,color:ql},bu={"--flopay-input-placeholder-color":Pu,"--flopay-input-font-size":$l,"--flopay-input-font-family":Wl,"--flopay-input-font-weight":String(Hl)},ga=Fe.cardFormContainer??{},us=ga.padding??(ya?"0":"1rem"),ps=ga.borderRadius??an,vu=he&&or?l(ms,{capture:he,html:or.html,messageToken:or.messageToken,expectedOrigin:or.expectedOrigin,verificationRequired:or.verificationRequired,theme:tu,submitLabel:U,onReady:()=>{if(!Zr&&!h||typeof document>"u"||qe===!1)return;let r=()=>{let _=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(_){Mr.current=!0;try{_.focus()}finally{Mr.current=!1}}};Jr.current||r()},onError:r=>{r&&or.verificationRequired&&q.current==="idle"&&(Le.current=!0),Ce(r)},onValidation:r=>{let p=q.current;(p==="idle"||p==="validation-window")&&(Ce(r),r&&q.current==="validation-window"&&(N.current&&(clearTimeout(N.current),N.current=null),q.current="idle",ae(null)))}},D):l("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ys=Ue("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&Y()},style:{backgroundColor:ss,borderRadius:ps,...ga,padding:us,...bu,display:"flex",flexDirection:"column"},children:[l("style",{children:`
5
5
  .flopay-shared-input::placeholder {
6
6
  color: var(--flopay-input-placeholder-color);
7
7
  opacity: 1;
@@ -9,13 +9,13 @@ ${q.join(`
9
9
  font-family: var(--flopay-input-font-family);
10
10
  font-weight: var(--flopay-input-font-weight);
11
11
  }
12
- `}),ya&&I&&De("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ee?-2:0},children:[De("button",{type:"button",onClick:l,style:{display:"inline-flex",alignItems:"center",gap:os?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Me.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Me.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Me.backButtonIcon},children:c("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(Wo,{content:Z})]}),Ll?c("div",{style:{flex:1}}):c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Me.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...Me.title},children:c(Sa,{content:ue})})]}),!ya&&!Ll&&c("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:as,order:Ee?-3:0,...Me.title},children:c(Sa,{content:ue})}),Ee&&At&&c("div",{style:{order:-2,width:"100%"},children:At}),Ee&&Qr&&De("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[c("div",{style:{backgroundColor:No,border:`1px solid ${ur(Qa)}`,borderRadius:an,padding:"10px"},children:c("input",{ref:ae,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Qt,onChange:r=>{wt("email"),In.current=r.target.value,Gn(r.target.value)},onPointerDown:()=>wt("email"),onKeyDown:()=>wt("email"),onBlur:()=>{Ar("email")&&jr(!0),xo||ji()},disabled:on,required:!0,"aria-invalid":Qa||void 0,"aria-describedby":Qa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...is}})}),Qa&&c("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:fa,children:Ni.empty?"Email address is required":"Enter a valid email address"})]}),u&&c("div",{style:{order:Ee?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=mt,m=(M=!1)=>({backgroundColor:No,border:`1px solid ${ur(M)}`,borderRadius:an,marginTop:"0.5rem",padding:"10px"}),R=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...is}),J=hy(r);return De(qn,{children:[Xt(u.address_line_1,r)&&De(qn,{children:[c("div",{style:m(Jt("line1")),children:c("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:ln,onChange:M=>{wt("line1"),En.current.addressLine1=!0,Fn.current=M.target.value,An(M.target.value)},onPointerDown:()=>wt("line1"),onKeyDown:()=>wt("line1"),onBlur:()=>cr("line1"),disabled:on,required:!0,"aria-invalid":Jt("line1")||void 0,"aria-describedby":Jt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:R()})}),Jt("line1")&&c("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:fa,children:"Street address is required"})]}),Xt(u.address_line_2,r)&&c("div",{style:m(),children:c("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:gr,onChange:M=>{En.current.addressLine2=!0,dn.current=M.target.value,nr(M.target.value)},disabled:on,"data-testid":"flopay-address-line2",style:R()})}),(Xt(u.city,r)||Xt(u.state,r))&&De("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Xt(u.city,r)&&c("div",{style:{flex:1,backgroundColor:No,borderTop:`1px solid ${ur(Jt("city"))}`,borderRight:`1px solid ${ur(Jt("city"))}`,borderBottom:`1px solid ${ur(Jt("city"))}`,borderLeft:`1px solid ${ur(Jt("city"))}`,padding:"10px",borderTopLeftRadius:an,borderBottomLeftRadius:an,...Xt(u.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:an}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:xn,onChange:M=>{wt("city"),En.current.city=!0,Pn.current=M.target.value,rr(M.target.value)},onPointerDown:()=>wt("city"),onKeyDown:()=>wt("city"),onBlur:()=>cr("city"),disabled:on,required:!0,"aria-invalid":Jt("city")||void 0,"aria-describedby":Jt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:R()})}),Xt(u.state,r)&&c("div",{style:{flex:1,backgroundColor:No,borderTop:`1px solid ${ur(Jt("state"))}`,borderRight:`1px solid ${ur(Jt("state"))}`,borderBottom:`1px solid ${ur(Jt("state"))}`,borderLeft:`1px solid ${ur(Jt("state"))}`,padding:"10px",borderTopRightRadius:an,borderBottomRightRadius:an,...Xt(u.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${ur(Jt("state")||Jt("city"))}`}:{borderRadius:an}},children:J?De("select",{id:"flopay-billing-state",name:"billing-state",value:or,onChange:M=>{wt("state"),En.current.state=!0,Nn.current=M.target.value,cn(M.target.value)},onPointerDown:()=>wt("state"),onKeyDown:()=>wt("state"),onBlur:()=>cr("state"),disabled:on,autoComplete:"billing address-level1",required:!0,"aria-invalid":Jt("state")||void 0,"aria-describedby":Jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...R(),cursor:"pointer"},children:[c("option",{value:"",children:As(r)}),J.map(M=>c("option",{value:M.code,children:M.name},M.code))]}):c("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:As(r),autoComplete:"billing address-level1",value:or,onChange:M=>{wt("state"),En.current.state=!0,Nn.current=M.target.value,cn(M.target.value)},onPointerDown:()=>wt("state"),onKeyDown:()=>wt("state"),onBlur:()=>cr("state"),disabled:on,required:!0,"aria-invalid":Jt("state")||void 0,"aria-describedby":Jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:R()})})]}),Jt("city")&&c("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:fa,children:"City is required"}),Jt("state")&&De("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:fa,children:[As(r)," is required"]}),(Xt(u.country,r)||Xt(u.postal_code,r))&&De("div",{style:{display:"flex",flexDirection:fe==="column"?"column":"row",gap:fe==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Xt(u.country,r)&&c("div",{style:{flex:fe==="row"?1:void 0,backgroundColor:No,borderTop:`1px solid ${ma}`,borderRight:`1px solid ${ma}`,borderBottom:`1px solid ${ma}`,borderLeft:`1px solid ${ma}`,padding:"10px",...fe==="row"&&Xt(u.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:an,borderBottomLeftRadius:an,borderRight:"none"}:{borderRadius:an}},children:De("select",{id:"flopay-billing-country",name:"billing-country",value:mt,onChange:M=>{En.current.country=!0,hn.current=M.target.value,et(M.target.value),Kt?.(M.target.value),Nn.current="",cn("")},disabled:on,autoComplete:"billing country","data-testid":"flopay-country",style:{...R(),cursor:"pointer"},children:[mt===""?c("option",{value:"",children:"Select country"}):null,sy.map(M=>De("option",{value:M.code,children:[M.flag," ",M.name]},M.code))]})}),Xt(u.postal_code,r)&&c("div",{style:{flex:fe==="row"?1:void 0,backgroundColor:No,border:`1px solid ${uu}`,padding:"10px",...fe==="row"&&Xt(u.country,r)?{borderRadius:"0",borderTopRightRadius:an,borderBottomRightRadius:an}:{borderRadius:an}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Us(mt),autoComplete:"billing postal-code",value:Ne,onChange:M=>{wt("zip"),En.current.zip=!0,Yt.current=M.target.value,tr(M.target.value),Pe?.(M.target.value)},onPointerDown:()=>wt("zip"),onKeyDown:()=>wt("zip"),onBlur:()=>{Ar("zip")&&Jr(!0)},disabled:on,required:Dn.required,"aria-invalid":ei||void 0,"aria-describedby":ei?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:R()})})]}),ei&&c("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:fa,children:Dn.empty?`${Us(r)} is required`:im(r)})]})})()}),Ee&&gu,br&&c(Qo,{margin:"0.75rem 0",styleOverride:Me.errorBanner,children:br})]}),ti={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},ql=r=>W?!de||!Fr?c("pre",{"data-testid":r,style:ti,children:"FloPay/DirectPayPal-debug - not enabled"}):c("pre",{"data-testid":r,style:ti,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${de}`,` directPaypalConfigured=${Fr}`,` inAppBrowserDetected=${String(Ja)}`,` shouldRenderDirectPayPal=${po}`,` shouldRenderStripePayPal=${yo}`,` hasPaypalStripeInstance=${!!il}`].join(`
13
- `)}):null,jl=r=>W?!S||!Xn?c("pre",{"data-testid":r,style:ti,children:"FloPay/Stripe-debug - not enabled"}):c("pre",{"data-testid":r,style:ti,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${S}`,` currency=${ft}`,` amountInCents=${ca}`,` enabledPaymentMethods: ${JSON.stringify($??[])}`,` enabledPaymentMethodsProvided=${da}`,` hasEnabledMethods=${Ka}`,` expressMethods: ${JSON.stringify(Ga)}`,` walletExpressMethods: ${JSON.stringify(Lo)}`,` paymentElementMethods: ${JSON.stringify(Ki)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ya)}`,` hasStripeInstance=${!!Xn}`,` shouldRenderWallets=${eo}`,` shouldRenderPaymentElement=${mo}`].join(`
14
- `)}):null,$l=Ue==="apm-expanding"||Ue==="apm-form"||Ue==="apm-collapsing",zo;Ue==="apm-expanding"?zo=fd:Ue==="apm-collapsing"&&(zo=gd);let ni=qt?Md(Vi,qt,It):null,Wl={label:Nt||td,open:Vt,onOpen:kt,color:to,fontFamily:zn?.fontFamily};if(we==="buttons"){let r=Ue==="buttons"||Ue==="expanding"||Ue==="apm-expanding",m=Ue==="expanding"||Ue==="card"||Ue==="collapsing",R=ke===void 0?{boxSizing:"border-box",height:ho,padding:"0 1rem"}:{padding:"0.9rem 1rem"},J;Ue==="expanding"||Ue==="apm-expanding"?J=nm:(Ue==="collapsing"||Ue==="apm-collapsing")&&(J=tm);let M;Ue==="expanding"?M=fd:Ue==="collapsing"&&(M=gd);let ye=wn&&cd(wn,{canHide:()=>!0,available:Tl}),_t={paypal:De(qn,{children:[po&&$e&&De(qn,{children:[pe&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(Ea.Provider,{value:y,children:c(hi,{sessionId:e,nonce:t,billingApiUrl:gt,email:vt.email,billingName:Ao||void 0,onBuyerIdentityReady:dr,clientId:$e.clientId,environment:$e.environment,currency:ft.toUpperCase(),isSubscription:Ze,providerObjectType:Ln,approvalPresentation:Xa==="popup"?void 0:Xa,onTokenizedBody:Kn,onComplete:s,onErrorChange:he,onDecline:g,onCancel:w,onTechnicalFailure:Do,onButtonClick:je,runBeforeButtonClick:wr,isProcessing:on,onLoadStateChange:Xi,onInitializationStateChange:Zi,session:k,existingOrderId:pe?.orderId,debug:W},pe?.orderId??"fresh")})]}),yo&&c(So,{stripe:ua,options:cl,children:c(Pd,{sessionId:e,nonce:t,email:vt.email,billingName:Ao||void 0,onBuyerIdentityReady:dr,billingApiUrl:gt,onTokenizedBody:Kn,onErrorChange:he,isProcessing:on,onButtonClick:je,onDecline:g,onTechnicalFailure:Do,runBeforeButtonClick:wr,onLoadStateChange:bl,placeholderBorderRadius:$r,popupCapabilityOwner:y,externalTelemetryContext:El,presentationMode:Oo})})]}),wallets:De(qn,{children:[eo?c(So,{stripe:Xn,options:ll,children:c(vd,{sessionId:e,nonce:t,email:vt.email,billingName:Ao||void 0,onBuyerIdentityReady:dr,billingApiUrl:gt,intentKind:Xe>0?"payment":"setup",expressMethods:Lo,onTokenizedBody:Kn,onErrorChange:he,onButtonClick:je,onDecline:g,onTechnicalFailure:Do,runBeforeButtonClick:wr,onLoadStateChange:Sl,placeholderBorderRadius:$r,popupCapabilityOwner:y,externalTelemetryContext:X})}):null,!eo&&Il?c("div",{style:{height:ho,borderRadius:$r,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:c(qn,{children:mo&&c(Cd,{sessionId:e,nonce:t,email:vt.email,billingName:[vt.firstName,vt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:dr,billingApiUrl:gt,paymentElementMethods:Ya,stripeInstance:Xn,paymentElementBaseOptions:Vi,futureUseSession:It,onTokenizedBody:Kn,onErrorChange:he,onButtonClick:je,onDecline:g,runBeforeButtonClick:wr,onLoadStateChange:wl,isProcessing:on,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:Me.submitButton,onExpandApm:P,expandedApmMethod:qt,themeId:be,buttonAppearance:{backgroundColor:Me.cardButton?.backgroundColor,borderColor:Me.cardInputBorder,textColor:Me.cardButton?.color,borderRadius:$r}})}),card:c(qn,{children:Ee&&c("button",{type:"button",onClick:async()=>{on||!(await wr("card")).proceed||(je?.("card"),p())},disabled:on,style:{width:"100%",...R,...Me.cardButton,...Vs({themeBundle:To,resolvedPrimaryColor:to,resolvedBorderRadius:an,submitButtonStyle:Me.submitButton,explicitPrimaryColor:zn?.colorPrimary}),fontSize:Me.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:on?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:on?.6:1},onMouseEnter:Tt=>{!on&&(To||zn?.colorPrimary)&&(Tt.currentTarget.style.backgroundColor=mu)},onMouseLeave:Tt=>{(To||zn?.colorPrimary)&&(Tt.currentTarget.style.backgroundColor=to)},onMouseDown:Tt=>{Tt.currentTarget.style.transform="scale(0.985)"},onMouseUp:Tt=>{Tt.currentTarget.style.transform="scale(1)"},children:c($o,{content:ke})})})};return De("form",{onSubmit:ts,className:ce,noValidate:!0,style:{position:"relative"},children:[c(si,{}),oe&&c(Dr,{status:oe,errorMessage:br,authorized:A}),De("div",{style:{display:"grid"},children:[De("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!J?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!J?om:{},...J?{animation:J,pointerEvents:"none"}:{}},children:[ql("flopay-direct-paypal-gate-debug"),jl("flopay-stripe-gate-debug"),kn&&ye?De(qn,{children:[kn.filter(({group:Tt})=>ye.inView.includes(Tt)).map(({group:Tt,key:Be})=>c(Na.Fragment,{children:_t[Tt]},Be)),ye.behindLink.length>0&&c(Ts,{...Wl,showLink:ye.showLink,children:kn.filter(({group:Tt})=>ye.behindLink.includes(Tt)).map(({group:Tt,key:Be})=>c(Na.Fragment,{children:_t[Tt]},Be))})]}):c(Ms,{rows:_l,borderRadius:$r}),br&&Ue==="buttons"&&c(Qo,{margin:"0.25rem 0",styleOverride:Me.errorBanner,children:br})]}),Ee&&m&&c("div",{style:{gridArea:"1 / 1",...M?{animation:M}:{},...Ue==="collapsing"?{pointerEvents:"none"}:{}},children:cs}),S&&$l&&qt&&ni&&Xn&&c("div",{style:{gridArea:"1 / 1",...zo?{animation:zo}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:De("div",{style:{backgroundColor:rs,borderRadius:ls,...ga,padding:ss},children:[De("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[De("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:te,style:{display:"inline-flex",alignItems:"center",gap:os?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Me.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Me.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Me.backButtonIcon},children:c("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(Wo,{content:Z})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Me.titleFontSize??"1.05rem",color:as,paddingRight:80,...Me.title},children:`Pay with ${za(qt)}`})]}),c(So,{stripe:Xn,options:ni,children:c(js,{method:qt,sessionId:e,nonce:t,email:vt.email,billingName:[vt.firstName,vt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:dr,billingApiUrl:gt,onTokenizedBody:Kn,onErrorChange:he,onDecline:g,onCancel:te,runBeforeButtonClick:wr,onButtonClick:je,isProcessing:on,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:Me.submitButton,errorText:br})},qt)]})})]})]})}if($l&&qt&&ni&&Xn&&S)return De("form",{onSubmit:ts,className:ce,noValidate:!0,style:{position:"relative"},children:[c(si,{}),oe&&c(Dr,{status:oe,errorMessage:br,authorized:A}),c("div",{style:{...zo?{animation:zo}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:De("div",{style:{backgroundColor:rs,borderRadius:ls,...ga,padding:ss},children:[De("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[De("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:te,style:{display:"inline-flex",alignItems:"center",gap:os?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Me.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Me.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Me.backButtonIcon},children:c("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(Wo,{content:Z})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Me.titleFontSize??"1.05rem",color:as,paddingRight:80,...Me.title},children:`Pay with ${za(qt)}`})]}),c(So,{stripe:Xn,options:ni,children:c(js,{method:qt,sessionId:e,nonce:t,email:vt.email,billingName:[vt.firstName,vt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:dr,billingApiUrl:gt,onTokenizedBody:Kn,onErrorChange:he,onDecline:g,onCancel:te,runBeforeButtonClick:wr,onButtonClick:je,isProcessing:on,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:Me.submitButton,errorText:br})},qt)]})})]});let Hl=iu||au||su,ha=wn&&cd(wn,{canHide:r=>r!=="card",available:Tl}),Kl={paypal:De(qn,{children:[po&&$e&&De(qn,{children:[pe&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(Ea.Provider,{value:y,children:c(hi,{sessionId:e,nonce:t,billingApiUrl:gt,email:vt.email,billingName:Ao||void 0,onBuyerIdentityReady:dr,clientId:$e.clientId,environment:$e.environment,currency:ft.toUpperCase(),isSubscription:Ze,providerObjectType:Ln,approvalPresentation:Xa==="popup"?void 0:Xa,onTokenizedBody:Kn,onComplete:s,onErrorChange:he,onDecline:g,onCancel:w,onTechnicalFailure:Do,onButtonClick:je,runBeforeButtonClick:wr,isProcessing:on,onLoadStateChange:Xi,onInitializationStateChange:Zi,session:k,existingOrderId:pe?.orderId,debug:W},pe?.orderId??"fresh")})]}),yo&&c(So,{stripe:ua,options:cl,children:c(Pd,{sessionId:e,nonce:t,email:vt.email,billingName:Ao||void 0,onBuyerIdentityReady:dr,billingApiUrl:gt,onTokenizedBody:Kn,onErrorChange:he,isProcessing:on,onButtonClick:je,onDecline:g,onTechnicalFailure:Do,runBeforeButtonClick:wr,onLoadStateChange:bl,placeholderBorderRadius:$r,popupCapabilityOwner:y,externalTelemetryContext:El,presentationMode:Oo})})]}),wallets:c(qn,{children:eo&&c(So,{stripe:Xn,options:ll,children:c(vd,{sessionId:e,nonce:t,email:vt.email,billingName:Ao||void 0,onBuyerIdentityReady:dr,billingApiUrl:gt,intentKind:Xe>0?"payment":"setup",expressMethods:Lo,onTokenizedBody:Kn,onErrorChange:he,onButtonClick:je,onDecline:g,onTechnicalFailure:Do,runBeforeButtonClick:wr,onLoadStateChange:Sl,placeholderBorderRadius:$r,popupCapabilityOwner:y,externalTelemetryContext:X})})}),apms:c(qn,{children:mo&&c(Cd,{sessionId:e,nonce:t,email:vt.email,billingName:[vt.firstName,vt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:gt,paymentElementMethods:Ya,stripeInstance:Xn,paymentElementBaseOptions:Vi,futureUseSession:It,onTokenizedBody:Kn,onErrorChange:he,onButtonClick:je,onDecline:g,runBeforeButtonClick:wr,onLoadStateChange:wl,isProcessing:on,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:Me.submitButton,themeId:be,onExpandApm:P,expandedApmMethod:qt,buttonAppearance:{backgroundColor:Me.cardButton?.backgroundColor,borderColor:Me.cardInputBorder,textColor:Me.cardButton?.color,borderRadius:$r}})})};return De("form",{onSubmit:ts,className:ce,noValidate:!0,style:{position:"relative"},children:[c(si,{}),oe&&c(Dr,{status:oe,errorMessage:br,authorized:A}),kn===null?c(Ms,{rows:_l,borderRadius:$r}):De(qn,{children:[Mn&&Ee&&cs,Mn&&Ee&&Hl&&c(us,{label:"or pay another way"}),De("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ql("flopay-direct-paypal-gate-debug-default"),jl("flopay-stripe-gate-debug-default"),kn.map(({group:r,key:m})=>r==="card"||!ha?.inView.includes(r)?null:c(Na.Fragment,{children:Kl[r]},m)),ha&&ha.behindLink.length>0&&c(Ts,{...Wl,showLink:ha.showLink,children:kn.map(({group:r,key:m})=>ha.behindLink.includes(r)&&r!=="card"?c(Na.Fragment,{children:Kl[r]},m):null)})]}),!Mn&&Ee&&Hl&&c(us,{label:"or pay with card"}),!Mn&&Ee&&cs]})]})}import{Fragment as Nr,jsx as le,jsxs as Sn}from"react/jsx-runtime";var wo=44,el="flopay_checkout_saved_payment_resume",Im="paypal_resume_nonce_missing",Oi=new Map,Fi=new Map;function Od(e,t){t.settled&&t.consumers===0&&Oi.get(e)===t&&Oi.delete(e)}function Em(e,t,n){let o=Fi.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};Fi.set(e,i);let s=()=>{Fi.get(e)===i&&Fi.delete(e)};return a.then(s,s),a}function ja(e){return new Promise(t=>setTimeout(t,e))}function Di(e,t,n){let o=fi({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Hd,enabled:t!==!1});return o.beginCheckout(n),o}function $a(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ys(e,t,n,o,a,i){let s=Di(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),$a(s)}function Ld(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 Nd(e,t,n,o,a){let i=jd(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 Js(e){return!e||e.data.stripe?.publishableKey?!1:!!$d(e.data.paypal)?.clientId}var _m={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Tm(e){return new fm(_m,{publishableKey:"provider_unavailable",...e})}async function Xs(e,t){let{publishableKey:n,paypalPublishableKey:o}=Es(e);return{...await _s({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function tl(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Mm(){if(!tl())return null;try{let e=window.sessionStorage.getItem(el);return e?JSON.parse(e):null}catch{return null}}function Ud(e){if(tl())try{window.sessionStorage.setItem(el,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Zs(){if(tl())try{window.sessionStorage.removeItem(el)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Am(){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 zd(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 Qs(e,t){return km(!!e,t)}function xm(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function qd(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Fm(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 nl({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:d,error:g,onComplete:w,onError:v,onInstrument:h,onDecline:T,onCancel:ie,onCountryChange:ce,onZipChange:x,showPayPal:U=!0,showStripe:C=!0,walletPresentation:me="auto",enabledPaymentMethods:de,showApplePay:S=!0,showGooglePay:Ye=!0,debug:$=!1,layout:Oe,paymentMethodLayout:st,moreOptionsLabel:yt,theme:we,buttonsTheme:zt,buttonsStyles:Nt,cardButtonContent:be,cardBackButtonContent:tt,cardTitleContent:lt,showSecurityFooter:ct,onButtonClick:ke,onBeforeButtonClick:Z,enableAVS:ue,cardFieldOrder:Ht,showCardBrandIcons:je,cardFieldPlaceholders:dt,cardAutoFocus:Q,onCardFieldsReady:_e,onCardFieldsFailed:rt,cardFieldsTimeoutMs:z,cardPreFormSlot:Mt,avsLayout:ve,submitLabel:Je,className:xe,initialErrorMessage:We=null,initialPayPalOrderId:At,children:fe,checkoutMode:Le,confirmLabel:ot,renderConfirmButton:nt,onSessionCompleted:Rt}){let H=Sm(o),St=fr(()=>Wd(we),[we]),Kt=i??St?.appearance,Pe=n?"embedded_checkout":"standard_checkout",Ce=Qs(fe,Oe),[Fe,ut]=Zt(null),[Xe,ft]=Zt(null),xt=jt(null),$e=jt(null),Ze=jt(0),[V,Ft]=Zt(null),He=jt(null),[W,f]=Zt(null),O=fr(()=>n?Ma(n):"",[n]),F=n?`create:${O}`:`session:${e??""}`,_=qd(W),Ke=jt(new Set),y=jt(F),ge=jt(F);va(()=>{ge.current=F,y.current!==F&&(y.current=F,Ke.current.clear())},[F]);let G=On(b=>{if(ge.current===F){if(Ic.has(b.name)){if(Ke.current.has(b.name))return;Ke.current.add(b.name)}Lt(()=>h?.(b))}},[F,h]),q=Xo(G,F),X=jt(!1),k=On(b=>{if(X.current)return;let I=b.gateway||!_?b:{...b,gateway:_};G(I)},[G,_]);_r(()=>{q({class:"lifecycle",name:"checkout.mount"})},[q]);let[It,Ln]=Zt(e??""),Qe=e??It,Qn=n?"":Qe,[Ve,mn]=Zt(!0),[gt,wn]=Zt(null),[fn,Vt]=Zt(0),[jn,kn]=Zt("full"),[Mn,er]=Zt(!1),[Rn,Bt]=Zt(We),[gn,mt]=Zt(null),[et,Ne]=Zt(null),[tr,ln]=Zt(!1),[An,gr]=Zt(void 0),[nr,xn]=Zt(""),[rr,or]=Zt(!1),[cn,Qt]=Zt(!1),[Gn,$n]=Zt(!1),en=jt(null),Yt=jt(0),hn=jt(void 0),[Fn,dn]=Zt("loading"),[Pn,Nn]=Zt(0),In=jt(!1),En=jt(!1),u=jt(!1),ht=jt(null),A=jt(null),L=fr(()=>({checkoutMode:Le??jn,layout:xm(fe,Oe)}),[Le,fe,jn,Oe]),Et=jt(w);Et.current=w;let Pt=jt(v);Pt.current=v;let tn=jt(T);tn.current=T;let Ie=On(b=>Si(ht,async I=>{try{return await b(I)}catch(B){throw I.aborted?ta(B):B}}),[]);_r(()=>()=>{ht.current?.abort(),ht.current=null},[]);let un=On((b,I)=>{xt.current=b,ft(b),He.current=I,Ft(I)},[]),Ee=On(()=>{let b=$e.current;b&&($e.current=null,b.destroy())},[]);_r(()=>{bn(Xe)?.setCheckoutContext(L),V&&V!==Xe&&bn(V)?.setCheckoutContext(L)},[Xe,V,L]);let zr=jt(Rt);zr.current=Rt;let Gr=On(b=>{dn(b),!(b!=="exhausted"||u.current)&&(u.current=!0,Pt.current?.(new Tn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Io=On(()=>{dn("retrying"),Nn(b=>b+1)},[]);_r(()=>{dn("loading"),Nn(0),u.current=!1},[Qe]),_r(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Hd,checkout_type:Pe,checkout_layout:Ce,billing_api_url:H})},[Ce,Pe,H]);let hr=fr(()=>n?Ma(n,!0):"",[n]),ar=fr(()=>nr===hr?An:void 0,[An,nr,hr]),Yn=fr(()=>n?hs(n,ar):void 0,[n,ar]),Wn=Le??Yn?.checkoutMode??"full",nn=fr(()=>Yn?{...Yn,checkoutMode:Wn}:void 0,[Yn,Wn]);_r(()=>{gr(void 0),xn(hr),hn.current=void 0,en.current=null,$n(!1)},[hr]),_r(()=>{Bt(We)},[We]);let Pr=On((b,I,B)=>{Lt(()=>{tn.current?.(Cn(b,I,B))})},[]),vn=On(async(b,I)=>{Bt(null),Ne(null),ln(!1),mt("processing");let B=I?.sessionId??b.id,Y=b.clientSecret||t,kt=qd(b),Gt=xt.current??He.current,se=bn(Gt),ze=Gt?null:Di(H,a,L),E={log:ae=>{se?se.log(ae):ze?.log(ae)},error:ae=>{se?se.error(ae):ze?.error(ae)},terminal:ae=>{se?se.terminal(ae):ze?.terminal(ae)},performance:ae=>{se?se.performance(ae):ze?.performance(ae)},now:()=>se?.now()??ze?.now()??0,elapsed:ae=>se?.elapsed(ae)??Math.max(0,(ze?.now()??ae)-ae)},Re=E.now(),ee=!!(I?.initialAutoProcessingError||I?.initialAutoProcessingPending),p=!1,l,P=()=>{p||(p=!0,ee=!0,l=E.now(),E.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},te=!1,oe=()=>{te||(te=!0,E.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),E.performance({stage:"processing",durationMs:E.elapsed(Re),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),l!==void 0&&E.performance({stage:"recovery",durationMs:E.elapsed(l),durationMode:"machine",paymentMethodCategory:"saved"}))};E.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),X.current=!0;try{E.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{X.current=!1}q({class:"lifecycle",name:"payment.processing.started",provider:kt}),ee&&P();let N;try{let ae=Yc(I?.initialAutoProcessingError),ne=I?.initialAutoProcessingError?.type==="3ds_required"&&!Cm(I.initialAutoProcessingError)&&!I.initialAutoProcessingError.threeDSecureToken&&I.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:I.initialAutoProcessingError.nextActionRedirectUrl}:null,Dt,Ut=qe=>{P();let j=Da(H,B,b,a!==!1);return Ie(K=>na(qe,{billingApiUrl:H,sessionId:B,nonce:Y,session:b,signal:K,...j.telemetry?{challengeTelemetry:j.telemetry}:{}})).finally(j.release)};if(ne)Dt=await Ut(ne);else if(ae)P(),ae.type==="paypal_redirect_required"&&A.current?.publishableKey&&Ud({sessionId:B,publishableKey:A.current.publishableKey,paypalPublishableKey:A.current.paypalPublishableKey,nonce:Y}),Dt=await Ie(qe=>ki(ae,{flopay:xt.current,paypalFlopay:He.current,attempt3DS:I?.attempt3DS,billingApiUrl:H,sessionId:B,session:b,telemetry:!1,signal:qe})),ae.type==="paypal_redirect_required"&&Zs();else if(I?.initialAutoProcessingPending){let qe=I.initialAutoProcessingPending,j=new xi(H,{telemetry:!1}),K=await Ie(pe=>j.waitForCheckoutSessionCompletion(qe.sessionId,{initialDelayMs:qe.retryAfterMs,nonce:Y,statusUrl:qe.statusUrl,signal:pe})),Se=oo(K,b),Te=K.autoProcessingError?.type==="3ds_required"&&K.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:K.autoProcessingError.nextActionRedirectUrl}:null;if(Te)Dt=await Ut(Te);else{if(!Hr(Se))throw Vo(Se);Dt=Wr(Se,B)}}else{if(I?.initialAutoProcessingError)throw Or(I.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:I.initialAutoProcessingError.checkoutMethod});if(I?.fromCreateSession)return I?.fallbackToFull&&(kn("full"),zd("full")),!1;{let qe=await ra({billingApiUrl:H,sessionId:B,session:b,nonce:Y,telemetry:!1});qe.type==="success"?Dt=qe.result:qe.type==="next_action_required"?Dt=await Ut(qe):(P(),qe.type==="paypal_redirect_required"&&A.current?.publishableKey&&Ud({sessionId:B,publishableKey:A.current.publishableKey,paypalPublishableKey:A.current.paypalPublishableKey,nonce:Y}),Dt=await Ie(j=>ki(qe,{flopay:xt.current,paypalFlopay:He.current,attempt3DS:I?.attempt3DS,billingApiUrl:H,sessionId:B,session:b,telemetry:!1,signal:j})),qe.type==="paypal_redirect_required"&&Zs())}}B&&ea(B),oe(),ee&&(E.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),E.terminal({outcome:Dt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),ln(Dt.status==="authorized"),mt("success"),await ja(600),N=()=>Et.current?.(Dt)}catch(ae){let ne=ro(Oa(ae),B);if(ne.code==="three_ds_aborted")return!1;let Dt=ne.checkoutMethod??Ba;Bt(ne.message),Ne(ne.message),ln(!1),I?.fallbackToFull&&(E.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),kn("full"),zd("full")),oe();let Ut=ne.statusCode===void 0?void 0:Rm(ne.statusCode,"unknown"),qe=Ut==="4xx"?{requestCategory:"process_payment",statusClass:Ut}:{},j=Ut===void 0||Ut==="4xx";if(Fd(ne))E.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...qe});else if(j&&(ne.telemetryOutcome==="validation_rejected"||ne.type==="validation_error"))E.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...qe});else{let Te=jd(ae,ee?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),pe=ne.telemetryRequestCategory??"process_payment";X.current=!0;try{E.error({...Te,...ne.telemetryFailureCategory?{failureCategory:ne.telemetryFailureCategory}:{},stage:ee?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:pe})}finally{X.current=!1}q({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:pe,provider:kt})}return xd(ne)?Pr(Dt,ne,{code:ne.code,declineCode:ne.declineCode}):Lt(()=>Pt.current?.(ne)),mt("error"),await Promise.allSettled([ja(400),I?.ensureProvidersReady?I.ensureProvidersReady():Promise.resolve()]),ee&&(E.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{oe(),ze&&$a(ze),mt(null),Ne(null)}return Lt(N),!0},[Pr,q,t,H,Ie,a,L]);_r(()=>{if(typeof window>"u"||En.current)return;let b=new URLSearchParams(window.location.search),I=b.get("payment_intent_client_secret");if(!I)return;let B=Mm();B&&(En.current=!0,(async()=>{await Promise.resolve();let Y,kt=0;Bt(null),Ne(null),mt("processing"),er(!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:Gt,paypalFlopay:se}=await _s({publishableKey:B.publishableKey,paypalPublishableKey:B.paypalPublishableKey,billingApiUrl:H,locale:s,telemetry:a});Y=bn(se??Gt),Y?.setCheckoutContext(L),kt=Y?.now()??0,Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let ze=(se??Gt)?.getRawProvider();if(!ze)throw Object.assign(new Tn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:E,error:Re}=await ze.retrievePaymentIntent(I);if(Re)throw Object.assign(new Tn(Re.message??"Failed to retrieve PayPal payment status.","api_error",{code:Re.code}),{checkoutMethod:"paypal"});let ee=gc(E?.status);if(!E||ee==="failed")throw Object.assign(new Tn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let p=typeof E.payment_method=="string"?E.payment_method:E.payment_method?.id,l=ee;if(B.sessionId){let P=B.nonce||t;if(!P)throw Object.assign(new Tn("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:Im}),{checkoutMethod:"paypal"});let N=(await new xi(H,{telemetry:!1}).getUnifiedCheckoutSession(B.sessionId,P)).data.session;if(N&&N.status!=="complete"){let ae=await ra({billingApiUrl:H,sessionId:B.sessionId,session:N,nonce:P,telemetry:!1,tokenizedData:{id:p??E.id,type:"card",threeDSecureActionResultTokenId:E.id,isPaypal:!0}});if(ae.type!=="success")throw Object.assign(new Tn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});l=ae.result.status}}B.sessionId&&ea(B.sessionId),Y?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.performance({stage:"redirect_resume",durationMs:Y.elapsed(kt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),mt("success"),await ja(600),Lt(()=>Et.current?.({status:l,paymentIntentId:E.id,paymentMethodId:p,checkoutMethod:"paypal"}))}catch(Gt){let se=ro(Oa(Gt),B.sessionId),ze=se.checkoutMethod??"paypal",E=Fd(se);if(Y)Y.performance({stage:"redirect_resume",durationMs:Y.elapsed(kt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),E?Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Y.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(E){let Re=Di(H,a,L);Re.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),$a(Re)}else Ys(H,a,L,"REDIRECT_RESUME_FAILED","redirect_resume");Bt(se.message),Ne(se.message),xd(se)?Pr(ze,se,{code:se.code,declineCode:se.declineCode}):Lt(()=>Pt.current?.(se)),mt("error"),await ja(400)}finally{Zs(),Am(),mt(null),Ne(null),er(!1)}})())},[Pr,s,t,H,a,L]);let Tr=jt(null),Ge=fr(()=>nn?Ma(nn):"",[nn]),Dn=jt(nn);Dn.current=nn,_r(()=>{Ln(e??"")},[e]),_r(()=>{In.current=!1,Bt(We),Ne(null),ln(!1),mt(null)},[Ge,We,e]);async function vr(b,I,B){let Y=Di(H,a,L),kt=new xi(H,{telemetry:!1}),Gt=!1;try{let se=b.idempotencyKey===void 0?void 0:Bd(b.idempotencyKey),ze=Uc(I,B),E=Nc(I,B);ze?.canonicalIdentity===B&&E&&E.canonicalIdentity===void 0&&(vi(I,B,E.idempotencyKey),E={...E,canonicalIdentity:B});let Re=se??(E?.canonicalIdentity===B?E.idempotencyKey:void 0),ee,p=!1;Y.log({name:ze?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let l=ze?.sid??null,P=null,te,oe,N=!1;if(l)try{P=await kt.getUnifiedCheckoutSession(l,ze?.nonce),ze&&ze.canonicalIdentity===void 0&&(Lc(P.data.session,b)?(Ci(I,B,l,ze.nonce??P.data.session?.clientSecret),E&&E.canonicalIdentity===void 0&&(vi(I,B,E.idempotencyKey),Re??(Re=E.idempotencyKey))):(Pi(I,B),E=null,Re=se,l=null,P=null));let ne=P?.data.session?.status,Dt=P?.data.session,Ut=Dt?.clientSecret||ze?.nonce;if(l&&Dt?.buyerIdentified===!1&&Ut&&(oe=Ko(kt,l,Ut,b.account)),l&&P&&ne==="complete"){if(ks(l))return{sid:l,result:P};Pi(I,B),l=null,P=null,p=!0}}catch{Y.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ze?.canonicalIdentity===void 0?(Pi(I,B),Re=se):ws(I,B),l=null}if(!l){!se&&(p||!Re)&&(Re=Bd(),ee=Re),Re&&vi(I,B,Re);let ne=Y.now(),Dt=0;Y.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ut={...b,idempotencyKey:Re,avsCheck:!!ue,avsConfig:typeof ue=="object"?ue:void 0,checkoutType:"embedded_checkout",checkoutLayout:Qs(fe,Oe)};Object.defineProperty(Ut,gm,{configurable:!1,enumerable:!1,value:{onAttempt:K=>{Dt=Math.max(Dt,K)}}});let qe=()=>{Ld(Y,"session_create",ne,Dt)},j=K=>{Nd(Y,K,"session_create",ne,Dt)&&q({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(b.checkoutMode==="confirm"||b.checkoutMode==="auto")&&$c();try{if(vm(Ut)){let K=await kt.createDetachedSession(Ut);K.claimed.catch(()=>{}),P=K.shell,l=K.sessionId,oe=K.claim;let Se=Y.now();Y.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),te=K.claimed.then(Te=>{let pe=Te.data.session?.id??K.sessionId;return pe&&Ci(I,B,pe,Te.data.session?.clientSecret??K.nonce),Ld(Y,"session_claim",Se),qe(),Te},Te=>{throw ws(I,B),Nd(Y,Te,"session_claim",Se,0)&&q({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Te}).finally(()=>$a(Y)),te.catch(()=>{}),Gt=!0,Y.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Y.performance({stage:"session_shell",durationMs:Y.now()-ne,durationMode:"machine",requestCategory:"session_create",attempt:Dt,statusClass:"2xx",paymentMethodCategory:"card"})}else P=await kt.createAndFetchSession(Ut),qe()}catch(K){throw j(K),K}l=P.data.session?.id??l??"",l&&!te&&Ci(I,B,l,P.data.session?.clientSecret)}let ae=P?.data.session;return!oe&&l&&ae?.buyerIdentified===!1&&ae.clientSecret&&(oe=Ko(kt,l,ae.clientSecret,b.account)),{sid:l??"",result:P,sdkGeneratedIdempotencyKey:ee,...te?{claimed:te}:{},...oe?{claim:oe}:{},...N?{claimRequiresIdentity:!0}:{}}}finally{Gt||$a(Y)}}let qr=jt(vr);va(()=>{qr.current=vr},[vr]);let Jn=On(async(b,I)=>{let B=Dn.current;if(!B)throw new Tn("createSession is required to bootstrap checkout.","validation_error");let Y=hs(B,b),kt=Ma(Y),Gt=Oc(Y),se=Oi.get(kt);if(!se){let Re={canonicalIdentity:kt,promise:qr.current(Y,Gt,kt),consumers:0,settled:!1};se=Re,Oi.set(kt,Re);let ee=()=>{Re.settled=!0,Od(kt,Re)};Re.promise.then(ee,ee)}se.consumers+=1;let ze=!1,E=()=>{ze||(ze=!0,se.consumers-=1,Od(kt,se))};I?.(E);try{let Re=await se.promise;Tr.current=kt,b&&(xn(hr),gr(ae=>dc(ae,b)));let{sid:ee,result:p,claimed:l,claim:P,claimRequiresIdentity:te}=Re;if(hn.current=P,$n(te===!0),ut(p),p.data.session&&f(p.data.session),ee&&Ln(ee),l){Yt.current+=1;let ae=Yt.current;en.current=l,Qt(!0),l.then(ne=>{Yt.current===ae&&(en.current===l&&(en.current=null),ut(ne),ne.data.session&&f(ne.data.session),Qt(!1),$n(!1))},ne=>{Yt.current===ae&&(en.current===l&&(en.current=null),Qt(!1),$n(!1),wn(ne instanceof Tn?ne:new Tn(ne instanceof Error?ne.message:"Failed to create session","api_error")))})}else Yt.current+=1,en.current=null,Qt(!1),$n(!1);let{flopay:oe,paypalFlopay:N}=await Xs(p,{billingApiUrl:H,locale:s,telemetry:a}).catch(ae=>{throw yc(ae,ee||p.data.session?.id)});return un(oe,N),mn(!1),Re}catch(Re){throw Tr.current===kt&&(Tr.current=null),Re}finally{I||E()}},[hr,un,s,H,a]),ir=jt(vn);ir.current=vn;let Yr=jt(Jn);Yr.current=Jn;let Jr=On(async b=>{if(!Fm(b)||rr)return{sessionId:It,session:W};or(!0);try{let I=await Jn(b);return{sessionId:I.sid,session:I.result.data.session??null}}finally{or(!1)}},[Jn,rr,It,W]),sr=On(async b=>{let I=hn.current;if(!I)return;let B=Yt.current,Y=await I(b);Yt.current===B&&(ut(Y),Y.data.session&&f(Y.data.session))},[]),jr=On(async()=>{await en.current},[]),Eo=On(async()=>(await jr(),{proceed:!0}),[jr]);_r(()=>{let b=!1,I,B=++Ze.current;Ee(),wn(null),Vt(0);let Y=()=>{b=!0,Ze.current===B&&(Ze.current+=1,Ee())},kt=Dn.current;if(Ge&&kt)return kn(Wn),mn(!1),Tr.current===Ge?Y:(f(uc(kt,Le)),(async()=>{let ze=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),E=Wn==="auto"&&!In.current&&!ze;E&&(Bt(null),Ne(null),mt("processing"));let Re=!1;try{let ee=await Yr.current(void 0,te=>{I=te});Re=!0;let p=ee.result.data.session??null;A.current=Es(ee.result);let l=Js(ee.result),P=ks(ee.sid||p?.id);if(!b&&E&&p&&!l&&!P){In.current=!0,await Em(Ge,ee.sdkGeneratedIdempotencyKey,()=>ir.current(p,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:ee.result.autoProcessingError,initialAutoProcessingPending:ee.result.autoProcessingPending,autoProcessingAttempted:ee.result.autoProcessingAttempted,sessionId:ee.sid||p.id}));return}!b&&E&&((l||P)&&(In.current=!0),mt(null),Ne(null))}catch(ee){if(b)return;let p=ci(ee);if(E&&p==="session_auto_completed"){In.current=!0,mt("success"),await ja(600),b||(Lt(()=>{Et.current?.({status:"succeeded"})}),mt(null),Ne(null));return}if(E&&(mt(null),Ne(null)),!Re){let P=mc(ee),te=Dd(ee,P?{stage:"provider_load",provider:"stripe",...P}:{stage:"session_request"});(P||!(ee instanceof Tn))&&Lt(()=>Pt.current?.(te)),wn(te);return}let l=ee instanceof Tn?ee:new Tn(ee instanceof Error?ee.message:"Failed to create session","api_error");wn(l)}finally{I?.(),I=void 0}})(),()=>{Y(),I?.()});mn(!0);async function Gt(){let ze=!1,E=!1,Re=null;try{let ee=new xi(H,{telemetry:!1}),p=await ee.getUnifiedCheckoutSession(Qe,t);if(E=!0,Re=p,b)return;ut(p);let l=p.data.session??null;if(f(l),!l)throw new Tn("No session data returned","api_error");let P=l.checkoutMode;if(P==="setup")throw new Tn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(l.status==="authorized"){mn(!1),Lt(()=>{Et.current?.(Wr(l,Qe)),zr.current?.(l.successUrl??"")});return}if(l.status==="complete"){mn(!1),Lt(()=>{zr.current?.(l.successUrl??"")});return}if(l.status==="expired")throw li(l);ze=!0;let te=Le??P??"full";kn(te),Yt.current+=1;let oe=l.clientSecret||t;hn.current=l.buyerIdentified===!1&&oe?Ko(ee,Qe,oe,{...l.customer?.id?{userId:l.customer.id}:{}}):void 0,Qt(!1),$n(!1);let N=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ae=Js(p);if(te==="auto"&&!In.current&&!N&&!ae){In.current=!0;let ne=se(p);try{if(await ir.current(l,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ne,sessionId:Qe||l.id}),b)return;await ne,b||mn(!1);return}catch{if(b)return;await ne,b||mn(!1);return}}await se(p),b||mn(!1)}catch(ee){if(b)return;let p=cc(ee,ze);if(ze&&q({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),p){let{errorCode:oe,stage:N,...ae}=p;Ys(H,a,L,oe,N,ae)}if(p?.stage==="provider_load"&&(Le??Re?.data.session?.checkoutMode??"full")==="full"&&lc(Re,U,C)){let oe=Tm({billingApiUrl:H,locale:s,telemetry:a});$e.current=oe,un(oe,null),Vt(1),mn(!1);return}let l=p?.stage==="provider_load",P="session_request";l?P="provider_load":E&&(P="post_session");let te=Dd(ee,{stage:P,provider:"stripe",sessionId:Qe||void 0});(l||!(ee instanceof Tn))&&Lt(()=>Pt.current?.(te)),wn(te),mn(!1)}}async function se(ze){let{flopay:E,paypalFlopay:Re,...ee}=await Xs(ze,{billingApiUrl:H,locale:s,telemetry:a});A.current={publishableKey:ee.publishableKey,paypalPublishableKey:ee.paypalPublishableKey},un(E,Re),Vt(0)}return Gt(),Y},[Le,Ge,Wn,Qn,t,U,C]);let la=On(async()=>{if(!Fe||fn!==1)return;let b=Ze.current;Vt(2);try{let{flopay:I,paypalFlopay:B}=await Xs(Fe,{billingApiUrl:H,locale:s,telemetry:a});if(Ze.current!==b)return;Ee(),un(I,B),Vt(0)}catch(I){if(Ze.current!==b)return;let{errorCode:B,stage:Y,...kt}=gs(I);Ys(H,a,L,B,Y,kt)}},[Ee,un,s,fn,H,a,L,Fe]),lr=!!(Qe&&(W?.clientSecret||t)),Mr=Mn||!lr,Xr=On(async()=>{if(!(Mn||!lr||!W)){er(!0),Bt(null);try{await vn(W,{attempt3DS:!0,fallbackToFull:!0,sessionId:Qe||W.id})}finally{er(!1)}}},[Qe,Mn,lr,vn,W]),wt=$d(Fe?.data.paypal,At),Ar=Js(Fe),cr=fr(()=>{if(!(!Fe||!W||!Fe.data.stripe?.publishableKey))return{billingApiUrl:H}},[Fe,W,H]),Cr=!!(n&&!fe&&Oe==="buttons"&&Z&&Wn==="full"),Un=!!(Qe&&(bm(W?.vault)||Po(W))),Ue=fr(()=>({session:W,loading:Ve,error:gt,checkoutMode:jn,inlineSessionDraft:nn,applyInlineSessionPatch:Cr?Jr:void 0,inlineSessionPatchProcessing:rr,claimPending:cn,claimRequiresIdentity:Gn,claimBuyerIdentity:sr,waitForDataAttachment:jr}),[W,Ve,gt,jn,nn,Cr,Jr,rr,cn,Gn,sr,jr]),rn=!!n&&Oe==="buttons"&&!Ar&&!Un&&(!Xe||!cr),qt=gn?le(Dr,{status:gn,errorMessage:et,authorized:tr}):null;if(Ve&&!Un){if(d)return Sn(Nr,{children:[d,qt]});if(Oe==="buttons"){let b=St?.buttonsLayout?.cardButton?.borderRadius??St?.appearance.variables?.borderRadius??8,I=B=>le("div",{style:{height:B,borderRadius:b,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Sn(Nr,{children:[Sn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[U&&I(wo),C&&(S||Ye)&&I(wo),C&&I(wo),le("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),qt]})}return Sn(Nr,{children:[Sn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[le("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),le("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),qt]})}return gt?g?le(kr.Provider,{value:Ue,children:g(gt)}):le(kr.Provider,{value:Ue,children:le("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:gt.message})}):rn?Sn(Nr,{children:[le(kr.Provider,{value:Ue,children:le(Dm,{onButtonClick:ke,paymentMethodLayout:st,showPayPal:U,showStripe:C,showApplePay:S,showGooglePay:Ye,theme:we,buttonsTheme:zt,buttonsStyles:Nt,cardButtonContent:be,cardBackButtonContent:tt,cardTitleContent:lt})}),qt]}):Ar&&W&&wt?Sn(Nr,{children:[le(kr.Provider,{value:Ue,children:Sn("div",{className:xe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Rn&&le(Qo,{icon:!1,children:Rn}),Fn==="retrying"&&le("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Fn==="exhausted"&&Sn("div",{role:"alert",children:[le("div",{children:"PayPal is temporarily unavailable. Please try again."}),le("button",{type:"button",onClick:Io,children:"Retry PayPal"})]}),Fn!=="exhausted"&&le("div",{"aria-hidden":Fn==="retrying"?!0:void 0,style:Fn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:le(Bc,{sessionId:Qe,nonce:W.clientSecret||void 0,billingApiUrl:H,email:W.customer?.email||nn?.account?.email,billingName:[W.customer?.firstName,W.customer?.lastName].filter(Boolean).join(" ")||[nn?.account?.firstName,nn?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:sr,clientId:wt.clientId,environment:wt.environment,currency:(W.currency??"usd").toUpperCase(),isSubscription:W.mode==="subscription",providerObjectType:wt.providerObjectType,approvalPresentation:wt.approvalPresentation,existingOrderId:wt.existingOrderId,onComplete:w,onErrorChange:Bt,onDecline:T,onCancel:ie,onButtonClick:ke,runBeforeButtonClick:Eo,onInitializationStateChange:Gr,allowAutomaticRetry:Pn===0,session:W,telemetry:a,telemetryContext:L,onInstrument:k,debug:$},`${F}:paypal-init-${Pn}`)})]})}),qt]}):jn==="confirm"?Sn(Nr,{children:[le(kr.Provider,{value:Ue,children:le(bi,{flopay:Xe,paypalFlopay:V,options:cr??{billingApiUrl:H},onInstrument:k,children:Sn("div",{className:xe,children:[Rn&&le("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Rn}),nt?nt({onConfirm:Xr,isProcessing:Mr}):le("button",{type:"button",onClick:Xr,disabled:Mr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Mr?"not-allowed":"pointer",opacity:Mr?.6:1},children:Mn?"Processing...":ot??"Confirm Purchase"})]})},F)}),qt]}):(!Xe||!cr)&&!(Un&&jn==="full")?le(Nr,{children:qt}):Sn(Nr,{children:[le(kr.Provider,{value:Ue,children:Sn(bi,{flopay:Xe,paypalFlopay:V,options:cr??{billingApiUrl:H},onInstrument:k,children:[fn===1&&le("button",{type:"button",onClick:la,children:"Retry payment methods"}),fe?Sn(Nr,{children:[Rn&&le("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Rn}),le(Bm,{sessionId:Qe,nonce:W?.clientSecret||void 0,billingApiUrl:H,session:W,submitLabel:Je,walletPresentation:me,paymentMethodLayout:st,moreOptionsLabel:yt,children:fe})]}):le(Gs,{sessionId:Qe,nonce:W?.clientSecret||void 0,telemetry:a,email:W?.customer?.email||nn?.account?.email,userId:W?.customer?.id||nn?.account?.userId,firstName:W?.customer?.firstName||nn?.account?.firstName,lastName:W?.customer?.lastName||nn?.account?.lastName,totalAmount:W?Math.round(hm(W).total*100):0,currency:W?.currency?.toLowerCase()??"usd",onComplete:w,onError:v,onDecline:T,onCancel:ie,error:Rn,onErrorChange:Bt,showPayPal:U,showStripe:C,walletPresentation:me,enabledPaymentMethods:fn?[]:de??Fe?.data.stripe?.enabledPaymentMethods??W?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Fe?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:Ye,layout:Oe,paymentMethodLayout:st,moreOptionsLabel:yt,theme:we,buttonsTheme:zt,buttonsStyles:Nt,appearance:Kt,cardButtonContent:be,cardBackButtonContent:tt,cardTitleContent:lt,onButtonClick:ke,onBeforeButtonClick:Z,onBuyerIdentityReady:sr,enableAVS:ue,...Ht?{cardFieldOrder:Ht}:{},...je===void 0?{}:{showCardBrandIcons:je},...dt===void 0?{}:{cardFieldPlaceholders:dt},...Q===void 0?{}:{cardAutoFocus:Q},..._e?{onCardFieldsReady:_e}:{},...rt?{onCardFieldsFailed:rt}:{},...z===void 0?{}:{cardFieldsTimeoutMs:z},...Mt?{cardPreFormSlot:Mt}:{},avsLayout:ve,country:W?.customer?.country,city:W?.customer?.city,state:W?.customer?.state,onCountryChange:ce,onZipChange:x,avsCheck:!!ue,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Qs(fe,Oe),className:xe,submitLabel:Je,directPaypal:wt,isSubscription:W?.mode==="subscription",session:W,dataAttachmentPending:cn,dataAttachmentRequiresIdentity:Gn,debug:$})]},F)}),qt]})}function Bm({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,paymentMethodLayout:s,moreOptionsLabel:d,children:g}){return le(Nr,{children:Bi.Children.map(g,w=>{if(!Bi.isValidElement(w))return w;let v=w.props,h={};return v.sessionId||(h.sessionId=e),!v.nonce&&t&&(h.nonce=t),v.billingApiUrl||(h.billingApiUrl=n),v.submitLabel===void 0&&a!==void 0&&(h.submitLabel=a),v.walletPresentation===void 0&&(h.walletPresentation=i),v.paymentMethodLayout===void 0&&s!==void 0&&(h.paymentMethodLayout=s),v.moreOptionsLabel===void 0&&d!==void 0&&(h.moreOptionsLabel=d),o?.customer&&(v.email||(h.email=o.customer.email),v.userId||(h.userId=o.customer.id),v.firstName||(h.firstName=o.customer.firstName),v.lastName||(h.lastName=o.customer.lastName)),Object.keys(h).length===0?w:Bi.cloneElement(w,h)})})}function Dm({onButtonClick:e,paymentMethodLayout:t,showPayPal:n,showStripe:o=!0,showApplePay:a,showGooglePay:i,theme:s,buttonsTheme:d,buttonsStyles:g,cardButtonContent:w,cardBackButtonContent:v,cardTitleContent:h}){let[T,ie]=Zt(!1),ce=fr(()=>Wd(s),[s]),x=fr(()=>{let S=ce?.buttonsLayout??wm(d);return g?{...S,...g,cardButton:{...S.cardButton,...g.cardButton},cardFormContainer:{...S.cardFormContainer,...g.cardFormContainer},backButton:{...S.backButton,...g.backButton},backButtonIcon:{...S.backButtonIcon,...g.backButtonIcon},submitButton:{...S.submitButton,...g.submitButton},title:{...S.title,...g.title}}:S},[ce,d,g]),U=ce?.buttonsLayout?.cardButton?.borderRadius??ce?.appearance.variables?.borderRadius??8,C=S=>le("div",{style:{height:S,borderRadius:U,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),me=w===void 0?{boxSizing:"border-box",height:wo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(T){let S=x.cardInputBorder??"#e5e7eb",Ye=x.cardInputBackground??"white",$=jo(v),Oe=jo(h);return Sn("div",{style:{backgroundColor:x.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...x.cardFormContainer},children:[Sn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Sn("button",{type:"button",onClick:()=>ie(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:$?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...x.backButton},children:[le("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...x.backButtonIcon},children:le("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:le("path",{d:"M15 18l-6-6 6-6"})})}),le(Wo,{content:v})]}),Oe?le("div",{style:{flex:1}}):le("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...x.title},children:le(Sa,{content:h})})]}),le("div",{style:{backgroundColor:Ye,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:le("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Sn("div",{style:{display:"flex"},children:[le("div",{style:{flex:1,backgroundColor:Ye,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:le("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),le("div",{style:{flex:1,backgroundColor:Ye,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:le("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),le("div",{style:{backgroundColor:Ye,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:le("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),le("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...x.submitButton,opacity:.5}}),le("style",{children:`
12
+ `}),ya&&T&&Ue("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ye?-2:0},children:[Ue("button",{type:"button",onClick:P,style:{display:"inline-flex",alignItems:"center",gap:ls?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Fe.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Fe.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Fe.backButtonIcon},children:l("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Wo,{content:X})]}),jl?l("div",{style:{flex:1}}):l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Fe.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...Fe.title},children:l(Sa,{content:de})})]}),!ya&&!jl&&l("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:cs,order:ye?-3:0,...Fe.title},children:l(Sa,{content:de})}),ye&&It&&l("div",{style:{order:-2,width:"100%"},children:It}),ye&&Zr&&Ue("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[l("div",{style:{backgroundColor:No,border:`1px solid ${ir(Qa)}`,borderRadius:an,padding:"10px"},children:l("input",{ref:me,className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Hn,onChange:r=>{_t("email"),I.current=r.target.value,Un(r.target.value)},onPointerDown:()=>_t("email"),onKeyDown:()=>_t("email"),onBlur:()=>{qr("email")&&Gr(!0),xo||$i()},disabled:on,required:!0,"aria-invalid":Qa||void 0,"aria-describedby":Qa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...ds}})}),Qa&&l("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:fa,children:Ui.empty?"Email address is required":"Enter a valid email address"})]}),h&&l("div",{style:{order:ye?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=pe,p=(A=!1)=>({backgroundColor:No,border:`1px solid ${ir(A)}`,borderRadius:an,marginTop:"0.5rem",padding:"10px"}),_=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ds}),J=wy(r);return Ue($n,{children:[Qt(h.address_line_1,r)&&Ue($n,{children:[l("div",{style:p(Zt("line1")),children:l("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:Ln,onChange:A=>{_t("line1"),We.current.addressLine1=!0,Xt.current=A.target.value,er(A.target.value)},onPointerDown:()=>_t("line1"),onKeyDown:()=>_t("line1"),onBlur:()=>Vn("line1"),disabled:on,required:!0,"aria-invalid":Zt("line1")||void 0,"aria-describedby":Zt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:_()})}),Zt("line1")&&l("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:fa,children:"Street address is required"})]}),Qt(h.address_line_2,r)&&l("div",{style:p(),children:l("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Nn,onChange:A=>{We.current.addressLine2=!0,zn.current=A.target.value,kr(A.target.value)},disabled:on,"data-testid":"flopay-address-line2",style:_()})}),(Qt(h.city,r)||Qt(h.state,r))&&Ue("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Qt(h.city,r)&&l("div",{style:{flex:1,backgroundColor:No,borderTop:`1px solid ${ir(Zt("city"))}`,borderRight:`1px solid ${ir(Zt("city"))}`,borderBottom:`1px solid ${ir(Zt("city"))}`,borderLeft:`1px solid ${ir(Zt("city"))}`,padding:"10px",borderTopLeftRadius:an,borderBottomLeftRadius:an,...Qt(h.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:an}},children:l("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:ur,onChange:A=>{_t("city"),We.current.city=!0,qn.current=A.target.value,mn(A.target.value)},onPointerDown:()=>_t("city"),onKeyDown:()=>_t("city"),onBlur:()=>Vn("city"),disabled:on,required:!0,"aria-invalid":Zt("city")||void 0,"aria-describedby":Zt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:_()})}),Qt(h.state,r)&&l("div",{style:{flex:1,backgroundColor:No,borderTop:`1px solid ${ir(Zt("state"))}`,borderRight:`1px solid ${ir(Zt("state"))}`,borderBottom:`1px solid ${ir(Zt("state"))}`,borderLeft:`1px solid ${ir(Zt("state"))}`,padding:"10px",borderTopRightRadius:an,borderBottomRightRadius:an,...Qt(h.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${ir(Zt("state")||Zt("city"))}`}:{borderRadius:an}},children:J?Ue("select",{id:"flopay-billing-state",name:"billing-state",value:fn,onChange:A=>{_t("state"),We.current.state=!0,Fn.current=A.target.value,An(A.target.value)},onPointerDown:()=>_t("state"),onKeyDown:()=>_t("state"),onBlur:()=>Vn("state"),disabled:on,autoComplete:"billing address-level1",required:!0,"aria-invalid":Zt("state")||void 0,"aria-describedby":Zt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{..._(),cursor:"pointer"},children:[l("option",{value:"",children:Ds(r)}),J.map(A=>l("option",{value:A.code,children:A.name},A.code))]}):l("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Ds(r),autoComplete:"billing address-level1",value:fn,onChange:A=>{_t("state"),We.current.state=!0,Fn.current=A.target.value,An(A.target.value)},onPointerDown:()=>_t("state"),onKeyDown:()=>_t("state"),onBlur:()=>Vn("state"),disabled:on,required:!0,"aria-invalid":Zt("state")||void 0,"aria-describedby":Zt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:_()})})]}),Zt("city")&&l("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:fa,children:"City is required"}),Zt("state")&&Ue("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:fa,children:[Ds(r)," is required"]}),(Qt(h.country,r)||Qt(h.postal_code,r))&&Ue("div",{style:{display:"flex",flexDirection:xe==="column"?"column":"row",gap:xe==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Qt(h.country,r)&&l("div",{style:{flex:xe==="row"?1:void 0,backgroundColor:No,borderTop:`1px solid ${ma}`,borderRight:`1px solid ${ma}`,borderBottom:`1px solid ${ma}`,borderLeft:`1px solid ${ma}`,padding:"10px",...xe==="row"&&Qt(h.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:an,borderBottomLeftRadius:an,borderRight:"none"}:{borderRadius:an}},children:Ue("select",{id:"flopay-billing-country",name:"billing-country",value:pe,onChange:A=>{We.current.country=!0,rn.current=A.target.value,Qn(A.target.value),Me?.(A.target.value),Fn.current="",An("")},disabled:on,autoComplete:"billing country","data-testid":"flopay-country",style:{..._(),cursor:"pointer"},children:[pe===""?l("option",{value:"",children:"Select country"}):null,yy.map(A=>Ue("option",{value:A.code,children:[A.flag," ",A.name]},A.code))]})}),Qt(h.postal_code,r)&&l("div",{style:{flex:xe==="row"?1:void 0,backgroundColor:No,border:`1px solid ${gu}`,padding:"10px",...xe==="row"&&Qt(h.country,r)?{borderRadius:"0",borderTopRightRadius:an,borderBottomRightRadius:an}:{borderRadius:an}},children:l("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:$s(pe),autoComplete:"billing postal-code",value:Bt,onChange:A=>{_t("zip"),We.current.zip=!0,nn.current=A.target.value,Mn(A.target.value),pt?.(A.target.value)},onPointerDown:()=>_t("zip"),onKeyDown:()=>_t("zip"),onBlur:()=>{qr("zip")&&yo(!0)},disabled:on,required:Bn.required,"aria-invalid":ei||void 0,"aria-describedby":ei?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:_()})})]}),ei&&l("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:fa,children:Bn.empty?`${$s(r)} is required`:pm(r)})]})})()}),ye&&vu,fr&&l(Qo,{margin:"0.75rem 0",styleOverride:Fe.errorBanner,children:fr})]}),ti={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"},Kl=r=>m?!ce||!xr?l("pre",{"data-testid":r,style:ti,children:"FloPay/DirectPayPal-debug - not enabled"}):l("pre",{"data-testid":r,style:ti,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ce}`,` directPaypalConfigured=${xr}`,` inAppBrowserDetected=${String(Ja)}`,` shouldRenderDirectPayPal=${mo}`,` shouldRenderStripePayPal=${fo}`,` hasPaypalStripeInstance=${!!ul}`].join(`
13
+ `)}):null,Vl=r=>m?!v||!Xn?l("pre",{"data-testid":r,style:ti,children:"FloPay/Stripe-debug - not enabled"}):l("pre",{"data-testid":r,style:ti,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${v}`,` currency=${Rt}`,` amountInCents=${ca}`,` enabledPaymentMethods: ${JSON.stringify(K??[])}`,` enabledPaymentMethodsProvided=${da}`,` hasEnabledMethods=${Ka}`,` expressMethods: ${JSON.stringify(Ga)}`,` walletExpressMethods: ${JSON.stringify(Lo)}`,` paymentElementMethods: ${JSON.stringify(Ji)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ya)}`,` hasStripeInstance=${!!Xn}`,` shouldRenderWallets=${Qr}`,` shouldRenderPaymentElement=${go}`].join(`
14
+ `)}):null,Gl=Oe==="apm-expanding"||Oe==="apm-form"||Oe==="apm-collapsing",zo;Oe==="apm-expanding"?zo=bd:Oe==="apm-collapsing"&&(zo=vd);let ni=Vt?Dd(Xi,Vt,qt):null,Yl={label:Nt||id,open:Wn,onOpen:Ct,color:eo,fontFamily:jn?.fontFamily};if(Ee==="buttons"){let r=Oe==="buttons"||Oe==="expanding"||Oe==="apm-expanding",p=Oe==="expanding"||Oe==="card"||Oe==="collapsing",_=_e===void 0?{boxSizing:"border-box",height:Co,padding:"0 1rem"}:{padding:"0.9rem 1rem"},J;Oe==="expanding"||Oe==="apm-expanding"?J=lm:(Oe==="collapsing"||Oe==="apm-collapsing")&&(J=sm);let A;Oe==="expanding"?A=bd:Oe==="collapsing"&&(A=vd);let fe=Ft&&md(Ft,{canHide:()=>!0,available:Bl}),Tt={paypal:Ue($n,{children:[mo&&Ye&&Ue($n,{children:[$e&&l("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),l(Ea.Provider,{value:L,children:l(hi,{sessionId:e,nonce:t,billingApiUrl:at,email:ht.email,billingName:Ao||void 0,onBuyerIdentityReady:ar,clientId:Ye.clientId,environment:Ye.environment,currency:Rt.toUpperCase(),isSubscription:rt,providerObjectType:On,approvalPresentation:Xa==="popup"?void 0:Xa,onTokenizedBody:Gn,onComplete:s,onErrorChange:Ce,onDecline:y,onCancel:R,onTechnicalFailure:Do,onButtonClick:je,runBeforeButtonClick:hr,isProcessing:on,onLoadStateChange:ts,onInitializationStateChange:ns,session:Yt,existingOrderId:$e?.orderId,debug:m},$e?.orderId??"fresh")})]}),fo&&l(ko,{stripe:ua,options:ml,children:l(wd,{sessionId:e,nonce:t,email:ht.email,billingName:Ao||void 0,onBuyerIdentityReady:ar,billingApiUrl:at,onTokenizedBody:Gn,onErrorChange:Ce,isProcessing:on,onButtonClick:je,onDecline:y,onTechnicalFailure:Do,runBeforeButtonClick:hr,onLoadStateChange:Il,placeholderBorderRadius:jr,popupCapabilityOwner:L,externalTelemetryContext:xl,presentationMode:Oo})})]}),wallets:Ue($n,{children:[Qr?l(ko,{stripe:Xn,options:yl,children:l(kd,{sessionId:e,nonce:t,email:ht.email,billingName:Ao||void 0,onBuyerIdentityReady:ar,billingApiUrl:at,intentKind:Pt>0?"payment":"setup",expressMethods:Lo,onTokenizedBody:Gn,onErrorChange:Ce,onButtonClick:je,onDecline:y,onTechnicalFailure:Do,runBeforeButtonClick:hr,onLoadStateChange:El,placeholderBorderRadius:jr,popupCapabilityOwner:L,externalTelemetryContext:ot})}):null,!Qr&&Al?l("div",{style:{height:Co,borderRadius:jr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null]}),apms:l($n,{children:go&&l(Rd,{sessionId:e,nonce:t,email:ht.email,billingName:[ht.firstName,ht.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ar,billingApiUrl:at,paymentElementMethods:Ya,stripeInstance:Xn,paymentElementBaseOptions:Xi,futureUseSession:qt,onTokenizedBody:Gn,onErrorChange:Ce,onButtonClick:je,onDecline:y,runBeforeButtonClick:hr,onLoadStateChange:_l,isProcessing:on,submitButtonColor:eo,submitButtonBorderRadius:an,submitButtonStyle:Fe.submitButton,onExpandApm:x,expandedApmMethod:Vt,themeId:Ie,buttonAppearance:{backgroundColor:Fe.cardButton?.backgroundColor,borderColor:Fe.cardInputBorder,textColor:Fe.cardButton?.color,borderRadius:jr}})}),card:l($n,{children:ye&&l("button",{type:"button",onClick:async()=>{on||!(await hr("card")).proceed||(je?.("card"),E())},disabled:on,style:{width:"100%",..._,...Fe.cardButton,...Xs({themeBundle:To,resolvedPrimaryColor:eo,resolvedBorderRadius:an,submitButtonStyle:Fe.submitButton,explicitPrimaryColor:jn?.colorPrimary}),fontSize:Fe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:on?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:on?.6:1},onMouseEnter:Mt=>{!on&&(To||jn?.colorPrimary)&&(Mt.currentTarget.style.backgroundColor=Cu)},onMouseLeave:Mt=>{(To||jn?.colorPrimary)&&(Mt.currentTarget.style.backgroundColor=eo)},onMouseDown:Mt=>{Mt.currentTarget.style.transform="scale(0.985)"},onMouseUp:Mt=>{Mt.currentTarget.style.transform="scale(1)"},children:l($o,{content:_e})})})};return Ue("form",{onSubmit:as,className:le,noValidate:!0,style:{position:"relative"},children:[l(si,{}),Qe&&l(Br,{status:Qe,errorMessage:fr,authorized:mt}),Ue("div",{style:{display:"grid"},children:[Ue("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!J?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!J?dm:{},...J?{animation:J,pointerEvents:"none"}:{}},children:[Kl("flopay-direct-paypal-gate-debug"),Vl("flopay-stripe-gate-debug"),wn&&fe?Ue($n,{children:[wn.filter(({group:Mt})=>fe.inView.includes(Mt)).map(({group:Mt,key:Ne})=>l(Na.Fragment,{children:Tt[Mt]},Ne)),fe.behindLink.length>0&&l(Fs,{...Yl,showLink:fe.showLink,children:wn.filter(({group:Mt})=>fe.behindLink.includes(Mt)).map(({group:Mt,key:Ne})=>l(Na.Fragment,{children:Tt[Mt]},Ne))})]}):l(Bs,{rows:Fl,borderRadius:jr}),fr&&Oe==="buttons"&&l(Qo,{margin:"0.25rem 0",styleOverride:Fe.errorBanner,children:fr})]}),ye&&p&&l("div",{style:{gridArea:"1 / 1",...A?{animation:A}:{},...Oe==="collapsing"?{pointerEvents:"none"}:{}},children:ys}),v&&Gl&&Vt&&ni&&Xn&&l("div",{style:{gridArea:"1 / 1",...zo?{animation:zo}:{},...Oe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ue("div",{style:{backgroundColor:ss,borderRadius:ps,...ga,padding:us},children:[Ue("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ue("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:oe,style:{display:"inline-flex",alignItems:"center",gap:ls?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Fe.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Fe.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Fe.backButtonIcon},children:l("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Wo,{content:X})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Fe.titleFontSize??"1.05rem",color:cs,paddingRight:80,...Fe.title},children:`Pay with ${za(Vt)}`})]}),l(ko,{stripe:Xn,options:ni,children:l(Ks,{method:Vt,sessionId:e,nonce:t,email:ht.email,billingName:[ht.firstName,ht.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ar,billingApiUrl:at,onTokenizedBody:Gn,onErrorChange:Ce,onDecline:y,onCancel:oe,runBeforeButtonClick:hr,onButtonClick:je,isProcessing:on,submitButtonColor:eo,submitButtonBorderRadius:an,submitButtonStyle:Fe.submitButton,errorText:fr})},Vt)]})})]})]})}if(Gl&&Vt&&ni&&Xn&&v)return Ue("form",{onSubmit:as,className:le,noValidate:!0,style:{position:"relative"},children:[l(si,{}),Qe&&l(Br,{status:Qe,errorMessage:fr,authorized:mt}),l("div",{style:{...zo?{animation:zo}:{},...Oe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ue("div",{style:{backgroundColor:ss,borderRadius:ps,...ga,padding:us},children:[Ue("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ue("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:oe,style:{display:"inline-flex",alignItems:"center",gap:ls?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:Fe.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...Fe.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...Fe.backButtonIcon},children:l("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Wo,{content:X})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:Fe.titleFontSize??"1.05rem",color:cs,paddingRight:80,...Fe.title},children:`Pay with ${za(Vt)}`})]}),l(ko,{stripe:Xn,options:ni,children:l(Ks,{method:Vt,sessionId:e,nonce:t,email:ht.email,billingName:[ht.firstName,ht.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ar,billingApiUrl:at,onTokenizedBody:Gn,onErrorChange:Ce,onDecline:y,onCancel:oe,runBeforeButtonClick:hr,onButtonClick:je,isProcessing:on,submitButtonColor:eo,submitButtonBorderRadius:an,submitButtonStyle:Fe.submitButton,errorText:fr})},Vt)]})})]});let Jl=uu||du||pu,ha=Ft&&md(Ft,{canHide:r=>r!=="card",available:Bl}),Xl={paypal:Ue($n,{children:[mo&&Ye&&Ue($n,{children:[$e&&l("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),l(Ea.Provider,{value:L,children:l(hi,{sessionId:e,nonce:t,billingApiUrl:at,email:ht.email,billingName:Ao||void 0,onBuyerIdentityReady:ar,clientId:Ye.clientId,environment:Ye.environment,currency:Rt.toUpperCase(),isSubscription:rt,providerObjectType:On,approvalPresentation:Xa==="popup"?void 0:Xa,onTokenizedBody:Gn,onComplete:s,onErrorChange:Ce,onDecline:y,onCancel:R,onTechnicalFailure:Do,onButtonClick:je,runBeforeButtonClick:hr,isProcessing:on,onLoadStateChange:ts,onInitializationStateChange:ns,session:Yt,existingOrderId:$e?.orderId,debug:m},$e?.orderId??"fresh")})]}),fo&&l(ko,{stripe:ua,options:ml,children:l(wd,{sessionId:e,nonce:t,email:ht.email,billingName:Ao||void 0,onBuyerIdentityReady:ar,billingApiUrl:at,onTokenizedBody:Gn,onErrorChange:Ce,isProcessing:on,onButtonClick:je,onDecline:y,onTechnicalFailure:Do,runBeforeButtonClick:hr,onLoadStateChange:Il,placeholderBorderRadius:jr,popupCapabilityOwner:L,externalTelemetryContext:xl,presentationMode:Oo})})]}),wallets:l($n,{children:Qr&&l(ko,{stripe:Xn,options:yl,children:l(kd,{sessionId:e,nonce:t,email:ht.email,billingName:Ao||void 0,onBuyerIdentityReady:ar,billingApiUrl:at,intentKind:Pt>0?"payment":"setup",expressMethods:Lo,onTokenizedBody:Gn,onErrorChange:Ce,onButtonClick:je,onDecline:y,onTechnicalFailure:Do,runBeforeButtonClick:hr,onLoadStateChange:El,placeholderBorderRadius:jr,popupCapabilityOwner:L,externalTelemetryContext:ot})})}),apms:l($n,{children:go&&l(Rd,{sessionId:e,nonce:t,email:ht.email,billingName:[ht.firstName,ht.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:at,paymentElementMethods:Ya,stripeInstance:Xn,paymentElementBaseOptions:Xi,futureUseSession:qt,onTokenizedBody:Gn,onErrorChange:Ce,onButtonClick:je,onDecline:y,runBeforeButtonClick:hr,onLoadStateChange:_l,isProcessing:on,submitButtonColor:eo,submitButtonBorderRadius:an,submitButtonStyle:Fe.submitButton,themeId:Ie,onExpandApm:x,expandedApmMethod:Vt,buttonAppearance:{backgroundColor:Fe.cardButton?.backgroundColor,borderColor:Fe.cardInputBorder,textColor:Fe.cardButton?.color,borderRadius:jr}})})};return Ue("form",{onSubmit:as,className:le,noValidate:!0,style:{position:"relative"},children:[l(si,{}),Qe&&l(Br,{status:Qe,errorMessage:fr,authorized:mt}),wn===null?l(Bs,{rows:Fl,borderRadius:jr}):Ue($n,{children:[kn&&ye&&ys,kn&&ye&&Jl&&l(fs,{label:"or pay another way"}),Ue("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Kl("flopay-direct-paypal-gate-debug-default"),Vl("flopay-stripe-gate-debug-default"),wn.map(({group:r,key:p})=>r==="card"||!ha?.inView.includes(r)?null:l(Na.Fragment,{children:Xl[r]},p)),ha&&ha.behindLink.length>0&&l(Fs,{...Yl,showLink:ha.showLink,children:wn.map(({group:r,key:p})=>ha.behindLink.includes(r)&&r!=="card"?l(Na.Fragment,{children:Xl[r]},p):null)})]}),!kn&&ye&&Jl&&l(fs,{label:"or pay with card"}),!kn&&ye&&ys]})]})}import{Fragment as Lr,jsx as se,jsxs as Pn}from"react/jsx-runtime";var Ro=44,ol="flopay_checkout_saved_payment_resume",xm="paypal_resume_nonce_missing",Oi=new Map,Fi=new Map;function qd(e,t){t.settled&&t.consumers===0&&Oi.get(e)===t&&Oi.delete(e)}function Fm(e,t,n){let o=Fi.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};Fi.set(e,i);let s=()=>{Fi.get(e)===i&&Fi.delete(e)};return a.then(s,s),a}function ja(e){return new Promise(t=>setTimeout(t,e))}function Di(e,t,n){let o=fi({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Jd,enabled:t!==!1});return o.beginCheckout(n),o}function $a(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Qs(e,t,n,o,a,i){let s=Di(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),$a(s)}function jd(e,t,n,o){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...o===void 0?{}:{attempt:o},statusClass:"2xx"})}function $d(e,t,n,o,a){let i=Vd(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 Sn&&t.code==="session_auto_completed"?!1:t instanceof Sn&&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 el(e){return!e||e.data.stripe?.publishableKey?!1:!!Gd(e.data.paypal)?.clientId}var Bm={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Dm(e){return new vm(Bm,{publishableKey:"provider_unavailable",...e})}async function tl(e,t){let{publishableKey:n,paypalPublishableKey:o}=As(e);return{...await xs({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function al(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Om(){if(!al())return null;try{let e=window.sessionStorage.getItem(ol);return e?JSON.parse(e):null}catch{return null}}function Wd(e){if(al())try{window.sessionStorage.setItem(ol,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function nl(){if(al())try{window.sessionStorage.removeItem(ol)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Lm(){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 Hd(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 rl(e,t){return Mm(!!e,t)}function Nm(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Kd(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Um(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 il({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:d,error:y,onComplete:R,onError:C,onInstrument:g,onDecline:M,onCancel:te,onCountryChange:le,onZipChange:U,showPayPal:j=!0,showStripe:b=!0,walletPresentation:ge="auto",enabledPaymentMethods:ce,showApplePay:v=!0,showGooglePay:Ke=!0,debug:K=!1,layout:ze,paymentMethodLayout:lt,moreOptionsLabel:ft,theme:Ee,buttonsTheme:zt,buttonsStyles:Nt,cardButtonContent:Ie,cardBackButtonContent:Xe,cardTitleContent:ct,showSecurityFooter:dt,onButtonClick:_e,onBeforeButtonClick:X,enableAVS:de,cardFieldOrder:Kt,showCardBrandIcons:je,showCardFieldLabels:ut,cardFieldLabels:Q,cardFieldPlaceholders:Ae,cardAutoFocus:tt,onCardFieldsReady:$,onCardFieldsFailed:St,cardFieldsTimeoutMs:ve,cardPreFormSlot:Ze,avsLayout:qe,submitLabel:nt,className:wt,initialErrorMessage:De=null,initialPayPalOrderId:It,children:xe,checkoutMode:Te,confirmLabel:kt,renderConfirmButton:Ut,onSessionCompleted:Et}){let G=_m(o),ue=dr(()=>Yd(Ee),[Ee]),Me=i??ue?.appearance,pt=n?"embedded_checkout":"standard_checkout",yt=rl(xe,ze),[Ve,gt]=en(null),[Pt,Rt]=en(null),Ge=Wt(null),Ye=Wt(null),rt=Wt(0),[F,Cn]=en(null),S=Wt(null),[m,W]=en(null),B=dr(()=>n?Ma(n):"",[n]),H=n?`create:${B}`:`session:${e??""}`,f=Kd(m),ne=Wt(new Set),L=Wt(H),Se=Wt(H);Ca(()=>{Se.current=H,L.current!==H&&(L.current=H,ne.current.clear())},[H]);let we=Dn(w=>{if(Se.current===H){if(Ac.has(w.name)){if(ne.current.has(w.name))return;ne.current.add(w.name)}Lt(()=>g?.(w))}},[H,g]),k=Xo(we,H),ot=Wt(!1),Yt=Dn(w=>{if(ot.current)return;let T=w.gateway||!f?w:{...w,gateway:f};we(T)},[we,f]);Sr(()=>{k({class:"lifecycle",name:"checkout.mount"})},[k]);let[qt,On]=en(e??""),be=e??qt,wr=n?"":be,[pn,yn]=en(!0),[at,Ft]=en(null),[_n,Wn]=en(0),[Tn,wn]=en("full"),[kn,Jt]=en(!1),[jt,tn]=en(De),[Je,pe]=en(null),[Qn,Bt]=en(null),[Mn,Ln]=en(!1),[er,Nn]=en(void 0),[kr,ur]=en(""),[mn,fn]=en(!1),[An,Hn]=en(!1),[Un,xn]=en(!1),ln=Wt(null),nn=Wt(0),rn=Wt(void 0),[Xt,zn]=en("loading"),[qn,Fn]=en(0),I=Wt(!1),We=Wt(!1),h=Wt(!1),re=Wt(null),mt=Wt(null),He=dr(()=>({checkoutMode:Te??Tn,layout:Nm(xe,ze)}),[Te,xe,Tn,ze]),$t=Wt(R);$t.current=R;let ke=Wt(C);ke.current=C;let Rr=Wt(M);Rr.current=M;let Ur=Dn(w=>Si(re,async T=>{try{return await w(T)}catch(z){throw T.aborted?ta(z):z}}),[]);Sr(()=>()=>{re.current?.abort(),re.current=null},[]);let Rn=Dn((w,T)=>{Ge.current=w,Rt(w),S.current=T,Cn(T)},[]),ye=Dn(()=>{let w=Ye.current;w&&(Ye.current=null,w.destroy())},[]);Sr(()=>{hn(Pt)?.setCheckoutContext(He),F&&F!==Pt&&hn(F)?.setCheckoutContext(He)},[Pt,F,He]);let Vr=Wt(Et);Vr.current=Et;let uo=Dn(w=>{zn(w),!(w!=="exhausted"||h.current)&&(h.current=!0,ke.current?.(new Sn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),po=Dn(()=>{zn("retrying"),Fn(w=>w+1)},[]);Sr(()=>{zn("loading"),Fn(0),h.current=!1},[be]),Sr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Jd,checkout_type:pt,checkout_layout:yt,billing_api_url:G})},[yt,pt,G]);let pr=dr(()=>n?Ma(n,!0):"",[n]),tr=dr(()=>kr===pr?er:void 0,[er,kr,pr]),Jn=dr(()=>n?vs(n,tr):void 0,[n,tr]),Kn=Te??Jn?.checkoutMode??"full",Dt=dr(()=>Jn?{...Jn,checkoutMode:Kn}:void 0,[Jn,Kn]);Sr(()=>{Nn(void 0),ur(pr),rn.current=void 0,ln.current=null,xn(!1)},[pr]),Sr(()=>{tn(De)},[De]);let Ir=Dn((w,T,z)=>{Lt(()=>{Rr.current?.(gn(w,T,z))})},[]),In=Dn(async(w,T)=>{tn(null),Bt(null),Ln(!1),pe("processing");let z=T?.sessionId??w.id,Y=w.clientSecret||t,Ct=Kd(w),Gt=Ge.current??S.current,V=hn(Gt),Le=Gt?null:Di(G,a,He),D={log:me=>{V?V.log(me):Le?.log(me)},error:me=>{V?V.error(me):Le?.error(me)},terminal:me=>{V?V.terminal(me):Le?.terminal(me)},performance:me=>{V?V.performance(me):Le?.performance(me)},now:()=>V?.now()??Le?.now()??0,elapsed:me=>V?.elapsed(me)??Math.max(0,(Le?.now()??me)-me)},u=D.now(),c=!!(T?.initialAutoProcessingError||T?.initialAutoProcessingPending),E=!1,P,x=()=>{E||(E=!0,c=!0,P=D.now(),D.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),D.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},oe=!1,Qe=()=>{oe||(oe=!0,D.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),D.performance({stage:"processing",durationMs:D.elapsed(u),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),P!==void 0&&D.performance({stage:"recovery",durationMs:D.elapsed(P),durationMode:"machine",paymentMethodCategory:"saved"}))};D.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ot.current=!0;try{D.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ot.current=!1}k({class:"lifecycle",name:"payment.processing.started",provider:Ct}),c&&x();let ae;try{let me=ed(T?.initialAutoProcessingError),Pe=T?.initialAutoProcessingError?.type==="3ds_required"&&!Im(T.initialAutoProcessingError)&&!T.initialAutoProcessingError.threeDSecureToken&&T.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:T.initialAutoProcessingError.nextActionRedirectUrl}:null,At,ie=N=>{x();let q=Da(G,z,w,a!==!1);return Ur(Z=>na(N,{billingApiUrl:G,sessionId:z,nonce:Y,session:w,signal:Z,...q.telemetry?{challengeTelemetry:q.telemetry}:{}})).finally(q.release)};if(Pe)At=await ie(Pe);else if(me)x(),me.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Wd({sessionId:z,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey,nonce:Y}),At=await Ur(N=>ki(me,{flopay:Ge.current,paypalFlopay:S.current,attempt3DS:T?.attempt3DS,billingApiUrl:G,sessionId:z,session:w,telemetry:!1,signal:N})),me.type==="paypal_redirect_required"&&nl();else if(T?.initialAutoProcessingPending){let N=T.initialAutoProcessingPending,q=new xi(G,{telemetry:!1}),Z=await Ur($e=>q.waitForCheckoutSessionCompletion(N.sessionId,{initialDelayMs:N.retryAfterMs,nonce:Y,statusUrl:N.statusUrl,signal:$e})),Re=ro(Z,w),Ot=Z.autoProcessingError?.type==="3ds_required"&&Z.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Z.autoProcessingError.nextActionRedirectUrl}:null;if(Ot)At=await ie(Ot);else{if(!Wr(Re))throw Vo(Re);At=$r(Re,z)}}else{if(T?.initialAutoProcessingError)throw Dr(T.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:T.initialAutoProcessingError.checkoutMethod});if(T?.fromCreateSession)return T?.fallbackToFull&&(wn("full"),Hd("full")),!1;{let N=await ra({billingApiUrl:G,sessionId:z,session:w,nonce:Y,telemetry:!1});N.type==="success"?At=N.result:N.type==="next_action_required"?At=await ie(N):(x(),N.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Wd({sessionId:z,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey,nonce:Y}),At=await Ur(q=>ki(N,{flopay:Ge.current,paypalFlopay:S.current,attempt3DS:T?.attempt3DS,billingApiUrl:G,sessionId:z,session:w,telemetry:!1,signal:q})),N.type==="paypal_redirect_required"&&nl())}}z&&ea(z),Qe(),c&&(D.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),D.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),D.terminal({outcome:At.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Ln(At.status==="authorized"),pe("success"),await ja(600),ae=()=>$t.current?.(At)}catch(me){let Pe=no(Oa(me),z);if(Pe.code==="three_ds_aborted")return!1;let At=Pe.checkoutMethod??Ba;tn(Pe.message),Bt(Pe.message),Ln(!1),T?.fallbackToFull&&(D.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),wn("full"),Hd("full")),Qe();let ie=Pe.statusCode===void 0?void 0:Am(Pe.statusCode,"unknown"),N=ie==="4xx"?{requestCategory:"process_payment",statusClass:ie}:{},q=ie===void 0||ie==="4xx";if(Nd(Pe))D.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...N});else if(q&&(Pe.telemetryOutcome==="validation_rejected"||Pe.type==="validation_error"))D.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...N});else{let Ot=Vd(me,c?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),$e=Pe.telemetryRequestCategory??"process_payment";ot.current=!0;try{D.error({...Ot,...Pe.telemetryFailureCategory?{failureCategory:Pe.telemetryFailureCategory}:{},stage:c?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:$e})}finally{ot.current=!1}k({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:$e,provider:Ct})}return Ld(Pe)?Ir(At,Pe,{code:Pe.code,declineCode:Pe.declineCode}):Lt(()=>ke.current?.(Pe)),pe("error"),await Promise.allSettled([ja(400),T?.ensureProvidersReady?T.ensureProvidersReady():Promise.resolve()]),c&&(D.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),D.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Qe(),Le&&$a(Le),pe(null),Bt(null)}return Lt(ae),!0},[Ir,k,t,G,Ur,a,He]);Sr(()=>{if(typeof window>"u"||We.current)return;let w=new URLSearchParams(window.location.search),T=w.get("payment_intent_client_secret");if(!T)return;let z=Om();z&&(We.current=!0,(async()=>{await Promise.resolve();let Y,Ct=0;tn(null),Bt(null),pe("processing"),Jt(!0);try{if(w.get("redirect_status")==="failed")throw Object.assign(new Sn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Gt,paypalFlopay:V}=await xs({publishableKey:z.publishableKey,paypalPublishableKey:z.paypalPublishableKey,billingApiUrl:G,locale:s,telemetry:a});Y=hn(V??Gt),Y?.setCheckoutContext(He),Ct=Y?.now()??0,Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Le=(V??Gt)?.getRawProvider();if(!Le)throw Object.assign(new Sn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:D,error:u}=await Le.retrievePaymentIntent(T);if(u)throw Object.assign(new Sn(u.message??"Failed to retrieve PayPal payment status.","api_error",{code:u.code}),{checkoutMethod:"paypal"});let c=vc(D?.status);if(!D||c==="failed")throw Object.assign(new Sn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let E=typeof D.payment_method=="string"?D.payment_method:D.payment_method?.id,P=c;if(z.sessionId){let x=z.nonce||t;if(!x)throw Object.assign(new Sn("Unable to resume the PayPal payment: the checkout session nonce is missing.","validation_error",{code:xm}),{checkoutMethod:"paypal"});let ae=(await new xi(G,{telemetry:!1}).getUnifiedCheckoutSession(z.sessionId,x)).data.session;if(ae&&ae.status!=="complete"){let me=await ra({billingApiUrl:G,sessionId:z.sessionId,session:ae,nonce:x,telemetry:!1,tokenizedData:{id:E??D.id,type:"card",threeDSecureActionResultTokenId:D.id,isPaypal:!0}});if(me.type!=="success")throw Object.assign(new Sn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});P=me.result.status}}z.sessionId&&ea(z.sessionId),Y?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.performance({stage:"redirect_resume",durationMs:Y.elapsed(Ct),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),pe("success"),await ja(600),Lt(()=>$t.current?.({status:P,paymentIntentId:D.id,paymentMethodId:E,checkoutMethod:"paypal"}))}catch(Gt){let V=no(Oa(Gt),z.sessionId),Le=V.checkoutMethod??"paypal",D=Nd(V);if(Y)Y.performance({stage:"redirect_resume",durationMs:Y.elapsed(Ct),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),D?Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Y.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(D){let u=Di(G,a,He);u.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),$a(u)}else Qs(G,a,He,"REDIRECT_RESUME_FAILED","redirect_resume");tn(V.message),Bt(V.message),Ld(V)?Ir(Le,V,{code:V.code,declineCode:V.declineCode}):Lt(()=>ke.current?.(V)),pe("error"),await ja(400)}finally{nl(),Lm(),pe(null),Bt(null),Jt(!1)}})())},[Ir,s,t,G,a,He]);let nr=Wt(null),he=dr(()=>Dt?Ma(Dt):"",[Dt]),Bn=Wt(Dt);Bn.current=Dt,Sr(()=>{On(e??"")},[e]),Sr(()=>{I.current=!1,tn(De),Bt(null),Ln(!1),pe(null)},[he,De,e]);async function yr(w,T,z){let Y=Di(G,a,He),Ct=new xi(G,{telemetry:!1}),Gt=!1;try{let V=w.idempotencyKey===void 0?void 0:Ud(w.idempotencyKey),Le=Wc(T,z),D=$c(T,z);Le?.canonicalIdentity===z&&D&&D.canonicalIdentity===void 0&&(Ci(T,z,D.idempotencyKey),D={...D,canonicalIdentity:z});let u=V??(D?.canonicalIdentity===z?D.idempotencyKey:void 0),c,E=!1;Y.log({name:Le?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let P=Le?.sid??null,x=null,oe,Qe,ae=!1;if(P)try{x=await Ct.getUnifiedCheckoutSession(P,Le?.nonce),Le&&Le.canonicalIdentity===void 0&&(jc(x.data.session,w)?(bi(T,z,P,Le.nonce??x.data.session?.clientSecret),D&&D.canonicalIdentity===void 0&&(Ci(T,z,D.idempotencyKey),u??(u=D.idempotencyKey))):(Pi(T,z),D=null,u=V,P=null,x=null));let Pe=x?.data.session?.status,At=x?.data.session,ie=At?.clientSecret||Le?.nonce;if(P&&At?.buyerIdentified===!1&&ie&&(Qe=Ko(Ct,P,ie,w.account)),P&&x&&Pe==="complete"){if(_s(P))return{sid:P,result:x};Pi(T,z),P=null,x=null,E=!0}}catch{Y.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Le?.canonicalIdentity===void 0?(Pi(T,z),u=V):Es(T,z),P=null}if(!P){!V&&(E||!u)&&(u=Ud(),c=u),u&&Ci(T,z,u);let Pe=Y.now(),At=0;Y.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ie={...w,idempotencyKey:u,avsCheck:!!de,avsConfig:typeof de=="object"?de:void 0,checkoutType:"embedded_checkout",checkoutLayout:rl(xe,ze)};Object.defineProperty(ie,Sm,{configurable:!1,enumerable:!1,value:{onAttempt:Z=>{At=Math.max(At,Z)}}});let N=()=>{jd(Y,"session_create",Pe,At)},q=Z=>{$d(Y,Z,"session_create",Pe,At)&&k({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};(w.checkoutMode==="confirm"||w.checkoutMode==="auto")&&Gc();try{if(Rm(ie)){let Z=await Ct.createDetachedSession(ie);Z.claimed.catch(()=>{}),x=Z.shell,P=Z.sessionId,Qe=Z.claim;let Re=Y.now();Y.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),oe=Z.claimed.then(Ot=>{let $e=Ot.data.session?.id??Z.sessionId;return $e&&bi(T,z,$e,Ot.data.session?.clientSecret??Z.nonce),jd(Y,"session_claim",Re),N(),Ot},Ot=>{throw Es(T,z),$d(Y,Ot,"session_claim",Re,0)&&k({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Ot}).finally(()=>$a(Y)),oe.catch(()=>{}),Gt=!0,Y.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Y.performance({stage:"session_shell",durationMs:Y.now()-Pe,durationMode:"machine",requestCategory:"session_create",attempt:At,statusClass:"2xx",paymentMethodCategory:"card"})}else x=await Ct.createAndFetchSession(ie),N()}catch(Z){throw q(Z),Z}P=x.data.session?.id??P??"",P&&!oe&&bi(T,z,P,x.data.session?.clientSecret)}let me=x?.data.session;return!Qe&&P&&me?.buyerIdentified===!1&&me.clientSecret&&(Qe=Ko(Ct,P,me.clientSecret,w.account)),{sid:P??"",result:x,sdkGeneratedIdempotencyKey:c,...oe?{claimed:oe}:{},...Qe?{claim:Qe}:{},...ae?{claimRequiresIdentity:!0}:{}}}finally{Gt||$a(Y)}}let Er=Wt(yr);Ca(()=>{Er.current=yr},[yr]);let rr=Dn(async(w,T)=>{let z=Bn.current;if(!z)throw new Sn("createSession is required to bootstrap checkout.","validation_error");let Y=vs(z,w),Ct=Ma(Y),Gt=qc(Y),V=Oi.get(Ct);if(!V){let u={canonicalIdentity:Ct,promise:Er.current(Y,Gt,Ct),consumers:0,settled:!1};V=u,Oi.set(Ct,u);let c=()=>{u.settled=!0,qd(Ct,u)};u.promise.then(c,c)}V.consumers+=1;let Le=!1,D=()=>{Le||(Le=!0,V.consumers-=1,qd(Ct,V))};T?.(D);try{let u=await V.promise;nr.current=Ct,w&&(ur(pr),Nn(me=>fc(me,w)));let{sid:c,result:E,claimed:P,claim:x,claimRequiresIdentity:oe}=u;if(rn.current=x,xn(oe===!0),gt(E),E.data.session&&W(E.data.session),c&&On(c),P){nn.current+=1;let me=nn.current;ln.current=P,Hn(!0),P.then(Pe=>{nn.current===me&&(ln.current===P&&(ln.current=null),gt(Pe),Pe.data.session&&W(Pe.data.session),Hn(!1),xn(!1))},Pe=>{nn.current===me&&(ln.current===P&&(ln.current=null),Hn(!1),xn(!1),Ft(Pe instanceof Sn?Pe:new Sn(Pe instanceof Error?Pe.message:"Failed to create session","api_error")))})}else nn.current+=1,ln.current=null,Hn(!1),xn(!1);let{flopay:Qe,paypalFlopay:ae}=await tl(E,{billingApiUrl:G,locale:s,telemetry:a}).catch(me=>{throw Pc(me,c||E.data.session?.id)});return Rn(Qe,ae),yn(!1),u}catch(u){throw nr.current===Ct&&(nr.current=null),u}finally{T||D()}},[pr,Rn,s,G,a]),_r=Wt(In);_r.current=In;let Tr=Wt(rr);Tr.current=rr;let yo=Dn(async w=>{if(!Um(w)||mn)return{sessionId:qt,session:m};fn(!0);try{let T=await rr(w);return{sessionId:T.sid,session:T.result.data.session??null}}finally{fn(!1)}},[rr,mn,qt,m]),zr=Dn(async w=>{let T=rn.current;if(!T)return;let z=nn.current,Y=await T(w);nn.current===z&&(gt(Y),Y.data.session&&W(Y.data.session))},[]),Gr=Dn(async()=>{await ln.current},[]),Yr=Dn(async()=>(await Gr(),{proceed:!0}),[Gr]);Sr(()=>{let w=!1,T,z=++rt.current;ye(),Ft(null),Wn(0);let Y=()=>{w=!0,rt.current===z&&(rt.current+=1,ye())},Ct=Bn.current;if(he&&Ct)return wn(Kn),yn(!1),nr.current===he?Y:(W(gc(Ct,Te)),(async()=>{let Le=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),D=Kn==="auto"&&!I.current&&!Le;D&&(tn(null),Bt(null),pe("processing"));let u=!1;try{let c=await Tr.current(void 0,oe=>{T=oe});u=!0;let E=c.result.data.session??null;mt.current=As(c.result);let P=el(c.result),x=_s(c.sid||E?.id);if(!w&&D&&E&&!P&&!x){I.current=!0,await Fm(he,c.sdkGeneratedIdempotencyKey,()=>_r.current(E,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:c.result.autoProcessingError,initialAutoProcessingPending:c.result.autoProcessingPending,autoProcessingAttempted:c.result.autoProcessingAttempted,sessionId:c.sid||E.id}));return}!w&&D&&((P||x)&&(I.current=!0),pe(null),Bt(null))}catch(c){if(w)return;let E=ci(c);if(D&&E==="session_auto_completed"){I.current=!0,pe("success"),await ja(600),w||(Lt(()=>{$t.current?.({status:"succeeded"})}),pe(null),Bt(null));return}if(D&&(pe(null),Bt(null)),!u){let x=Cc(c),oe=zd(c,x?{stage:"provider_load",provider:"stripe",...x}:{stage:"session_request"});(x||!(c instanceof Sn))&&Lt(()=>ke.current?.(oe)),Ft(oe);return}let P=c instanceof Sn?c:new Sn(c instanceof Error?c.message:"Failed to create session","api_error");Ft(P)}finally{T?.(),T=void 0}})(),()=>{Y(),T?.()});yn(!0);async function Gt(){let Le=!1,D=!1,u=null;try{let c=new xi(G,{telemetry:!1}),E=await c.getUnifiedCheckoutSession(be,t);if(D=!0,u=E,w)return;gt(E);let P=E.data.session??null;if(W(P),!P)throw new Sn("No session data returned","api_error");let x=P.checkoutMode;if(x==="setup")throw new Sn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(P.status==="authorized"){yn(!1),Lt(()=>{$t.current?.($r(P,be)),Vr.current?.(P.successUrl??"")});return}if(P.status==="complete"){yn(!1),Lt(()=>{Vr.current?.(P.successUrl??"")});return}if(P.status==="expired")throw li(P);Le=!0;let oe=Te??x??"full";wn(oe),nn.current+=1;let Qe=P.clientSecret||t;rn.current=P.buyerIdentified===!1&&Qe?Ko(c,be,Qe,{...P.customer?.id?{userId:P.customer.id}:{}}):void 0,Hn(!1),xn(!1);let ae=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),me=el(E);if(oe==="auto"&&!I.current&&!ae&&!me){I.current=!0;let Pe=V(E);try{if(await _r.current(P,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Pe,sessionId:be||P.id}),w)return;await Pe,w||yn(!1);return}catch{if(w)return;await Pe,w||yn(!1);return}}await V(E),w||yn(!1)}catch(c){if(w)return;let E=mc(c,Le);if(Le&&k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),E){let{errorCode:Qe,stage:ae,...me}=E;Qs(G,a,He,Qe,ae,me)}if(E?.stage==="provider_load"&&(Te??u?.data.session?.checkoutMode??"full")==="full"&&yc(u,j,b)){let Qe=Dm({billingApiUrl:G,locale:s,telemetry:a});Ye.current=Qe,Rn(Qe,null),Wn(1),yn(!1);return}let P=E?.stage==="provider_load",x="session_request";P?x="provider_load":D&&(x="post_session");let oe=zd(c,{stage:x,provider:"stripe",sessionId:be||void 0});(P||!(c instanceof Sn))&&Lt(()=>ke.current?.(oe)),Ft(oe),yn(!1)}}async function V(Le){let{flopay:D,paypalFlopay:u,...c}=await tl(Le,{billingApiUrl:G,locale:s,telemetry:a});mt.current={publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey},Rn(D,u),Wn(0)}return Gt(),Y},[Te,he,Kn,wr,t,j,b]);let _o=Dn(async()=>{if(!Ve||_n!==1)return;let w=rt.current;Wn(2);try{let{flopay:T,paypalFlopay:z}=await tl(Ve,{billingApiUrl:G,locale:s,telemetry:a});if(rt.current!==w)return;ye(),Rn(T,z),Wn(0)}catch(T){if(rt.current!==w)return;let{errorCode:z,stage:Y,...Ct}=bs(T);Qs(G,a,He,z,Y,Ct)}},[ye,Rn,s,_n,G,a,He,Ve]),Mr=!!(be&&(m?.clientSecret||t)),mr=kn||!Mr,Jr=Dn(async()=>{if(!(kn||!Mr||!m)){Jt(!0),tn(null);try{await In(m,{attempt3DS:!0,fallbackToFull:!0,sessionId:be||m.id})}finally{Jt(!1)}}},[be,kn,Mr,In,m]),_t=Gd(Ve?.data.paypal,It),qr=el(Ve),Vn=dr(()=>{if(!(!Ve||!m||!Ve.data.stripe?.publishableKey))return{billingApiUrl:G}},[Ve,m,G]),or=!!(n&&!xe&&ze==="buttons"&&X&&Kn==="full"),bn=!!(be&&(Em(m?.vault)||bo(m))),Oe=dr(()=>({session:m,loading:pn,error:at,checkoutMode:Tn,inlineSessionDraft:Dt,applyInlineSessionPatch:or?yo:void 0,inlineSessionPatchProcessing:mn,claimPending:An,claimRequiresIdentity:Un,claimBuyerIdentity:zr,waitForDataAttachment:Gr}),[m,pn,at,Tn,Dt,or,yo,mn,An,Un,zr,Gr]),cn=!!n&&ze==="buttons"&&!qr&&!bn&&(!Pt||!Vn),Vt=Je?se(Br,{status:Je,errorMessage:Qn,authorized:Mn}):null;if(pn&&!bn){if(d)return Pn(Lr,{children:[d,Vt]});if(ze==="buttons"){let w=ue?.buttonsLayout?.cardButton?.borderRadius??ue?.appearance.variables?.borderRadius??8,T=z=>se("div",{style:{height:z,borderRadius:w,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Pn(Lr,{children:[Pn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[j&&T(Ro),b&&(v||Ke)&&T(Ro),b&&T(Ro),se("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Vt]})}return Pn(Lr,{children:[Pn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[se("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),se("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Vt]})}return at?y?se(Pr.Provider,{value:Oe,children:y(at)}):se(Pr.Provider,{value:Oe,children:se("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:at.message})}):cn?Pn(Lr,{children:[se(Pr.Provider,{value:Oe,children:se(qm,{onButtonClick:_e,paymentMethodLayout:lt,showPayPal:j,showStripe:b,showApplePay:v,showGooglePay:Ke,theme:Ee,buttonsTheme:zt,buttonsStyles:Nt,cardButtonContent:Ie,cardBackButtonContent:Xe,cardTitleContent:ct})}),Vt]}):qr&&m&&_t?Pn(Lr,{children:[se(Pr.Provider,{value:Oe,children:Pn("div",{className:wt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jt&&se(Qo,{icon:!1,children:jt}),Xt==="retrying"&&se("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Xt==="exhausted"&&Pn("div",{role:"alert",children:[se("div",{children:"PayPal is temporarily unavailable. Please try again."}),se("button",{type:"button",onClick:po,children:"Retry PayPal"})]}),Xt!=="exhausted"&&se("div",{"aria-hidden":Xt==="retrying"?!0:void 0,style:Xt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:se(Uc,{sessionId:be,nonce:m.clientSecret||void 0,billingApiUrl:G,email:m.customer?.email||Dt?.account?.email,billingName:[m.customer?.firstName,m.customer?.lastName].filter(Boolean).join(" ")||[Dt?.account?.firstName,Dt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:zr,clientId:_t.clientId,environment:_t.environment,currency:(m.currency??"usd").toUpperCase(),isSubscription:m.mode==="subscription",providerObjectType:_t.providerObjectType,approvalPresentation:_t.approvalPresentation,existingOrderId:_t.existingOrderId,onComplete:R,onErrorChange:tn,onDecline:M,onCancel:te,onButtonClick:_e,runBeforeButtonClick:Yr,onInitializationStateChange:uo,allowAutomaticRetry:qn===0,session:m,telemetry:a,telemetryContext:He,onInstrument:Yt,debug:K},`${H}:paypal-init-${qn}`)})]})}),Vt]}):Tn==="confirm"?Pn(Lr,{children:[se(Pr.Provider,{value:Oe,children:se(vi,{flopay:Pt,paypalFlopay:F,options:Vn??{billingApiUrl:G},onInstrument:Yt,children:Pn("div",{className:wt,children:[jt&&se("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:jt}),Ut?Ut({onConfirm:Jr,isProcessing:mr}):se("button",{type:"button",onClick:Jr,disabled:mr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:mr?"not-allowed":"pointer",opacity:mr?.6:1},children:kn?"Processing...":kt??"Confirm Purchase"})]})},H)}),Vt]}):(!Pt||!Vn)&&!(bn&&Tn==="full")?se(Lr,{children:Vt}):Pn(Lr,{children:[se(Pr.Provider,{value:Oe,children:Pn(vi,{flopay:Pt,paypalFlopay:F,options:Vn??{billingApiUrl:G},onInstrument:Yt,children:[_n===1&&se("button",{type:"button",onClick:_o,children:"Retry payment methods"}),xe?Pn(Lr,{children:[jt&&se("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:jt}),se(zm,{sessionId:be,nonce:m?.clientSecret||void 0,billingApiUrl:G,session:m,submitLabel:nt,walletPresentation:ge,paymentMethodLayout:lt,moreOptionsLabel:ft,children:xe})]}):se(Zs,{sessionId:be,nonce:m?.clientSecret||void 0,telemetry:a,email:m?.customer?.email||Dt?.account?.email,userId:m?.customer?.id||Dt?.account?.userId,firstName:m?.customer?.firstName||Dt?.account?.firstName,lastName:m?.customer?.lastName||Dt?.account?.lastName,totalAmount:m?Math.round(wm(m).total*100):0,currency:m?.currency?.toLowerCase()??"usd",onComplete:R,onError:C,onDecline:M,onCancel:te,error:jt,onErrorChange:tn,showPayPal:j,showStripe:b,walletPresentation:ge,enabledPaymentMethods:_n?[]:ce??Ve?.data.stripe?.enabledPaymentMethods??m?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ve?.data.stripe?.enabledPaymentMethodCountries,showApplePay:v,showGooglePay:Ke,layout:ze,paymentMethodLayout:lt,moreOptionsLabel:ft,theme:Ee,buttonsTheme:zt,buttonsStyles:Nt,appearance:Me,cardButtonContent:Ie,cardBackButtonContent:Xe,cardTitleContent:ct,onButtonClick:_e,onBeforeButtonClick:X,onBuyerIdentityReady:zr,enableAVS:de,...Kt?{cardFieldOrder:Kt}:{},...je===void 0?{}:{showCardBrandIcons:je},...ut===void 0?{}:{showCardFieldLabels:ut},...Q===void 0?{}:{cardFieldLabels:Q},...Ae===void 0?{}:{cardFieldPlaceholders:Ae},...tt===void 0?{}:{cardAutoFocus:tt},...$?{onCardFieldsReady:$}:{},...St?{onCardFieldsFailed:St}:{},...ve===void 0?{}:{cardFieldsTimeoutMs:ve},...Ze?{cardPreFormSlot:Ze}:{},avsLayout:qe,country:m?.customer?.country,city:m?.customer?.city,state:m?.customer?.state,onCountryChange:le,onZipChange:U,avsCheck:!!de,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:rl(xe,ze),className:wt,submitLabel:nt,directPaypal:_t,isSubscription:m?.mode==="subscription",session:m,dataAttachmentPending:An,dataAttachmentRequiresIdentity:Un,debug:K})]},H)}),Vt]})}function zm({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,paymentMethodLayout:s,moreOptionsLabel:d,children:y}){return se(Lr,{children:Bi.Children.map(y,R=>{if(!Bi.isValidElement(R))return R;let C=R.props,g={};return C.sessionId||(g.sessionId=e),!C.nonce&&t&&(g.nonce=t),C.billingApiUrl||(g.billingApiUrl=n),C.submitLabel===void 0&&a!==void 0&&(g.submitLabel=a),C.walletPresentation===void 0&&(g.walletPresentation=i),C.paymentMethodLayout===void 0&&s!==void 0&&(g.paymentMethodLayout=s),C.moreOptionsLabel===void 0&&d!==void 0&&(g.moreOptionsLabel=d),o?.customer&&(C.email||(g.email=o.customer.email),C.userId||(g.userId=o.customer.id),C.firstName||(g.firstName=o.customer.firstName),C.lastName||(g.lastName=o.customer.lastName)),Object.keys(g).length===0?R:Bi.cloneElement(R,g)})})}function qm({onButtonClick:e,paymentMethodLayout:t,showPayPal:n,showStripe:o=!0,showApplePay:a,showGooglePay:i,theme:s,buttonsTheme:d,buttonsStyles:y,cardButtonContent:R,cardBackButtonContent:C,cardTitleContent:g}){let[M,te]=en(!1),le=dr(()=>Yd(s),[s]),U=dr(()=>{let v=le?.buttonsLayout??Tm(d);return y?{...v,...y,cardButton:{...v.cardButton,...y.cardButton},cardFormContainer:{...v.cardFormContainer,...y.cardFormContainer},backButton:{...v.backButton,...y.backButton},backButtonIcon:{...v.backButtonIcon,...y.backButtonIcon},submitButton:{...v.submitButton,...y.submitButton},title:{...v.title,...y.title}}:v},[le,d,y]),j=le?.buttonsLayout?.cardButton?.borderRadius??le?.appearance.variables?.borderRadius??8,b=v=>se("div",{style:{height:v,borderRadius:j,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),ge=R===void 0?{boxSizing:"border-box",height:Ro,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(M){let v=U.cardInputBorder??"#e5e7eb",Ke=U.cardInputBackground??"white",K=jo(C),ze=jo(g);return Pn("div",{style:{backgroundColor:U.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...U.cardFormContainer},children:[Pn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Pn("button",{type:"button",onClick:()=>te(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:K?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...U.backButton},children:[se("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...U.backButtonIcon},children:se("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:se("path",{d:"M15 18l-6-6 6-6"})})}),se(Wo,{content:C})]}),ze?se("div",{style:{flex:1}}):se("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...U.title},children:se(Sa,{content:g})})]}),se("div",{style:{backgroundColor:Ke,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:se("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Pn("div",{style:{display:"flex"},children:[se("div",{style:{flex:1,backgroundColor:Ke,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:se("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),se("div",{style:{flex:1,backgroundColor:Ke,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:se("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),se("div",{style:{backgroundColor:Ke,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:se("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),se("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...U.submitButton,opacity:.5}}),se("style",{children:`
15
15
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
16
16
  @keyframes flopay-interim-expand {
17
17
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
18
18
  40% { opacity: 1; }
19
19
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
20
20
  }
21
- `})]})}let de={paypal:n&&C(wo),wallets:o&&(a||i)&&C(wo),card:o&&(t?C(wo):le("button",{type:"button",onClick:()=>{e?.("card"),ie(!0)},style:{width:"100%",...me,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:x.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...x.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:le($o,{content:w})}))};return Sn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Pm.map(S=>le(Bi.Fragment,{children:de[S]},S)),le("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Vm,jsx as ko,jsxs as Gm}from"react/jsx-runtime";var zm=44;function Vd(e){return new Promise(t=>setTimeout(t,e))}var Gd=15e3;function ol(e,t){return new Ro(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function qm(e,t){return new Promise((n,o)=>{let a=()=>o(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(i=>{t.removeEventListener("abort",a),n(i)},i=>{t.removeEventListener("abort",a),o(i)})})}function jm(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function $m(e,t){return e instanceof Ro?e:new Ro(e instanceof Error?e.message:t,"api_error")}function Wm(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Hm(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 Km({sessionId:e,nonce:t,createSession:n,getSession:o,paymentMethodId:a,checkoutMethod:i,clientId:s,products:d,items:g,subscriptions:w,account:v,successUrl:h,cancelUrl:T,couponCodes:ie,tagsData:ce,utmMetadata:x,billingApiUrl:U,locale:C,theme:me,appearance:de,buttonsTheme:S,buttonsStyles:Ye,onSuccess:$,onError:Oe,onDecline:st,children:yt,disabled:we=!1,type:zt="button",style:Nt,...be}){let tt=Wa(()=>Lm(U),[U]),lt=Wa(()=>Hm({createSession:n,clientId:s,products:d,items:g,subscriptions:w,account:v,successUrl:h,cancelUrl:T,couponCodes:ie,tagsData:ce,utmMetadata:x}),[v,T,s,ie,n,d,g,w,h,ce,x]),[ct,ke]=sa(!1),[Z,ue]=sa(null),[Ht,je]=sa(null),[dt,Q]=sa(!1),[_e,rt]=sa(null),[z,Mt]=sa(null),ve=uo(!0),Je=uo(null),xe=uo(null),We=uo(!1),At=uo(z),fe=uo($),Le=uo(Oe),ot=uo(st),nt=Ur(f=>Si(Je,async O=>{try{return await f(O)}catch(F){throw O.aborted?ta(F):F}}),[]);ia(()=>{At.current=z},[z]),ia(()=>{fe.current=$},[$]),ia(()=>{Le.current=Oe},[Oe]),ia(()=>{ot.current=st},[st]),ia(()=>(ve.current=!0,()=>{ve.current=!1,Je.current?.abort(),xe.current?.abort()}),[]),ia(()=>{if(typeof window>"u")return;let f=O=>{O.key==="Escape"&&Mt(null)};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[]);let Rt=Ur((f,O=Ba)=>{ot.current?.(Cn(O,f,{code:f.code,declineCode:f.declineCode}))},[]),H=Ur(async f=>{ve.current&&(je(null),Q(f.result.status==="authorized"),ue("success"),await Vd(600),ve.current&&Lt(()=>fe.current?.(f)))},[]),St=Ur(async(f,O)=>{if(!ve.current)return;!!O?.emitDecline&&Om(f)?Rt(f,O?.method):Le.current?.(f),je(f.message),Q(!1),ue("error"),await Vd(400)},[Rt]),Kt=Ur(async(f,O,F)=>{let _=f.data.session??null;if(!_)throw ro(new Ro("No session data returned","api_error"),O);let Ke=F?.nonce||_.clientSecret||t;if(Hr(_)){await H({result:Wr(_,O),session:_,sessionId:_.id||O,autoCompleted:!1});return}if(_.status==="expired")throw ro(li(_),_.id||O);try{if(f.autoProcessingPending){let ge=f.autoProcessingPending,G=new rl(tt),q=await nt(It=>G.waitForCheckoutSessionCompletion(ge.sessionId,{initialDelayMs:ge.retryAfterMs,nonce:Ke,statusUrl:ge.statusUrl,signal:It})),X=oo(q,_),k=q.autoProcessingError?.type==="3ds_required"&&!Kd(q.autoProcessingError)&&q.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.autoProcessingError.nextActionRedirectUrl}:null;if(k&&O&&Ke){let It=Da(tt,O,_),Ln=await nt(Qe=>na(k,{billingApiUrl:tt,sessionId:O,nonce:Ke,session:_,signal:Qe,telemetry:!0,...It.telemetry?{challengeTelemetry:It.telemetry}:{}})).finally(It.release);await H({result:Ln,session:_,sessionId:_.id||O,autoCompleted:!1});return}if(q.autoProcessingError)throw Or(q.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.autoProcessingError.checkoutMethod});if(!Hr(X))throw Vo(X);await H({result:Wr(X,O),session:X,sessionId:X.id||O,autoCompleted:!1});return}if(f.autoProcessingError){let ge=f.autoProcessingError.nextActionRedirectUrl;if(f.autoProcessingError.type==="3ds_required"&&!Kd(f.autoProcessingError)&&ge&&O&&Ke){let G=await nt(It=>Jc({billingApiUrl:tt,sessionId:O,nonce:Ke,nextActionRedirectUrl:ge,signal:It}));if(G.status==="declined")throw Or({type:G.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:G.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:f.autoProcessingError.checkoutMethod});let X=await new rl(tt).waitForCheckoutSessionCompletion(O,{initialDelayMs:0,nonce:Ke}),k=oo(X,_);if(!Hr(k))throw Or({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:f.autoProcessingError.checkoutMethod});await H({result:Wr(k,O),session:k,sessionId:k.id||O,autoCompleted:!1});return}throw Or(f.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.autoProcessingError.checkoutMethod})}if(F?.fromCreateSession&&f.autoProcessingAttempted===!0)throw Or({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let y=await ra({billingApiUrl:tt,sessionId:O??_.id,session:_,nonce:Ke});if(y.type==="next_action_required"&&Ke){let ge=O??_.id,G=Da(tt,ge,_),q=await nt(X=>na(y,{billingApiUrl:tt,sessionId:ge,nonce:Ke,session:_,signal:X,telemetry:!0,...G.telemetry?{challengeTelemetry:G.telemetry}:{}})).finally(G.release);await H({result:q,session:_,sessionId:_.id||ge,autoCompleted:!1});return}if(y.type!=="success")throw Or({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await H({result:y.result,session:_,sessionId:_.id||O,autoCompleted:!1})}catch(y){let ge=_.id||O,G=ro(Oa(y),ge);if(G.code==="three_ds_aborted")return;if(G.code==="checkout_processing_timeout"){if(!ve.current)return;rt(G.message),Lt(()=>Le.current?.(G));return}await St(G,{emitDecline:!0,method:G.checkoutMethod??Ba}),Wm(G,ge)&&ge&&ve.current&&Mt({sessionId:ge,errorMessage:G.message,nonce:Ke||void 0,payPalOrderId:G.orderId})}},[t,tt,nt,St,H]),Pe=Ur(async f=>{let O=new AbortController;xe.current=O;let F=!1,_=setTimeout(()=>{F=!0,O.abort()},Gd);try{let Ke=await qm((async()=>f({signal:O.signal}))(),O.signal);if(!ve.current)return null;if(!jm(Ke))throw ol("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:Ke.sessionId,nonce:Ke.nonce}}catch(Ke){if(!ve.current)return null;throw Ke instanceof Ro&&Ke.code==="session_fetch_failed"?Ke:F?ol(`getSession did not resolve within ${Gd/1e3} seconds.`):ol("Could not fetch the one-click session.",Ke)}finally{clearTimeout(_),xe.current===O&&(xe.current=null)}},[]),Ce=Ur(async f=>{if(be.onClick?.(f),f.defaultPrevented||we||ct||(Mt(null),rt(null),We.current))return;let O=[e,o,lt].filter(Boolean).length;if(O>1){let F=new Ro("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await St(F),ve.current&&(ue(null),je(null));return}if(O===0){let F=new Ro("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await St(F),ve.current&&(ue(null),je(null));return}We.current=!0,ke(!0),je(null),Q(!1),ue("processing");try{let F=new rl(tt);if(e){let _=await F.getUnifiedCheckoutSession(e,t);await Kt(_,e);return}if(o){let _=await Pe(o);if(!_)return;let Ke=await F.getUnifiedCheckoutSession(_.sessionId,_.nonce);await Kt(Ke,_.sessionId,{nonce:_.nonce});return}jc();try{let _=await F.createAndFetchSession({...lt});await Kt(_,_.data.session?.id??null,{fromCreateSession:!0})}catch(_){if(ci(_)==="session_auto_completed"){await H({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw _}}catch(F){await St(ro($m(F,"Automatic payment failed. Please try again."),e))}finally{We.current=!1,ve.current&&(ue(null),je(null),ke(!1))}},[be.onClick,lt,we,Pe,o,ct,t,Kt,tt,e,St,H]),Fe=Ur(f=>{let O=At.current;Mt(null),fe.current?.({result:f,session:null,sessionId:O?.sessionId??null,autoCompleted:!1})},[]),ut=Ur(f=>{Le.current?.(f)},[]),Xe=Ur(f=>{ot.current?.(f)},[]),ft=Wa(()=>Um(me),[me]),xt=Wa(()=>{let f=ft?.buttonsLayout??Nm(S);return Ye?{...f,...Ye,cardButton:{...f.cardButton,...Ye.cardButton}}:f},[ft,S,Ye]),$e=Wa(()=>{let f=ft?.appearance;return de?f?{...f,...de,variables:{...f.variables,...de.variables}}:de:f},[de,ft]),Ze=$e?.variables,V=Ze?.colorPrimary??"#4A49FF",Ft=Ze?.colorPrimaryHover??Ad(V,.12),He=Ze?.borderRadius??"8px";return Gm(Vm,{children:[ko("button",{...be,type:zt,onClick:Ce,disabled:we||ct,"aria-busy":ct,style:{width:"100%",...yt===void 0?{boxSizing:"border-box",height:zm,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...xt.cardButton,...Vs({themeBundle:ft,resolvedPrimaryColor:V,resolvedBorderRadius:He,submitButtonStyle:xt.submitButton,explicitPrimaryColor:Ze?.colorPrimary}),fontSize:xt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:we||ct?"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:we||ct?.6:1,...Nt},onMouseEnter:f=>{be.onMouseEnter?.(f),!f.defaultPrevented&&!we&&!ct&&(ft||Ze?.colorPrimary)&&(f.currentTarget.style.backgroundColor=Ft)},onMouseLeave:f=>{be.onMouseLeave?.(f),!f.defaultPrevented&&(ft||Ze?.colorPrimary)&&(f.currentTarget.style.backgroundColor=V)},onMouseDown:f=>{be.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{be.onMouseUp?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(1)")},children:ko($o,{content:yt})}),_e&&ko("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:_e}),Z&&ko(Dr,{status:Z,errorMessage:Ht,authorized:dt}),z&&ko("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:f=>{f.target===f.currentTarget&&Mt(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:ko("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:ko(nl,{sessionId:z.sessionId,nonce:z.nonce,checkoutMode:"full",billingApiUrl:tt,locale:C,theme:me,...$e?{appearance:$e}:{},buttonsTheme:S,buttonsStyles:Ye,initialErrorMessage:z.errorMessage,initialPayPalOrderId:z.payPalOrderId,cardTitleContent:null,onComplete:Fe,onError:ut,onDecline:Xe})})})]})}import{jsx as Xm}from"react/jsx-runtime";var Ym={StripeSetupMethod:ac,PayPalSetupMethod:oc};function Jm(e){return Xm(ic,{...e,branches:Ym})}export{hi as DirectPayPalButton,Km as FloPayAutomaticPaymentButton,Pu as FloPayCardSetup,hu as FloPayCardSetupError,nl as FloPayCheckout,Jm as FloPayPaymentMethodSetup,bi as FloPayProvider,Gs as SplitCardForm,ds as VaultCardFields,$h as dropThirdPartyOnlyError,Uu as useCheckout,ao as useFloPay,Cs as usePayPalFloPay};
21
+ `})]})}let ce={paypal:n&&b(Ro),wallets:o&&(a||i)&&b(Ro),card:o&&(t?b(Ro):se("button",{type:"button",onClick:()=>{e?.("card"),te(!0)},style:{width:"100%",...ge,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:U.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,...U.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:se($o,{content:R})}))};return Pn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[km.map(v=>se(Bi.Fragment,{children:ce[v]},v)),se("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Qm,jsx as Io,jsxs as ef}from"react/jsx-runtime";var Km=44;function Zd(e){return new Promise(t=>setTimeout(t,e))}var Qd=15e3;function ll(e,t){return new Eo(e,"api_error",{code:"session_fetch_failed",...t===void 0?{}:{cause:t}})}function Vm(e,t){return new Promise((n,o)=>{let a=()=>o(t.reason);if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(i=>{t.removeEventListener("abort",a),n(i)},i=>{t.removeEventListener("abort",a),o(i)})})}function Gm(e){let t=e;return typeof t?.sessionId=="string"&&t.sessionId.length>0&&typeof t.nonce=="string"&&t.nonce.length>0}function Ym(e,t){return e instanceof Eo?e:new Eo(e instanceof Error?e.message:t,"api_error")}function Jm(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Xm(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 Zm({sessionId:e,nonce:t,createSession:n,getSession:o,paymentMethodId:a,checkoutMethod:i,clientId:s,products:d,items:y,subscriptions:R,account:C,successUrl:g,cancelUrl:M,couponCodes:te,tagsData:le,utmMetadata:U,billingApiUrl:j,locale:b,theme:ge,appearance:ce,buttonsTheme:v,buttonsStyles:Ke,onSuccess:K,onError:ze,onDecline:lt,children:ft,disabled:Ee=!1,type:zt="button",style:Nt,...Ie}){let Xe=Wa(()=>$m(j),[j]),ct=Wa(()=>Xm({createSession:n,clientId:s,products:d,items:y,subscriptions:R,account:C,successUrl:g,cancelUrl:M,couponCodes:te,tagsData:le,utmMetadata:U}),[C,M,s,te,n,d,y,R,g,le,U]),[dt,_e]=sa(!1),[X,de]=sa(null),[Kt,je]=sa(null),[ut,Q]=sa(!1),[Ae,tt]=sa(null),[$,St]=sa(null),ve=co(!0),Ze=co(null),qe=co(null),nt=co(!1),wt=co($),De=co(K),It=co(ze),xe=co(lt),Te=Nr(S=>Si(Ze,async m=>{try{return await S(m)}catch(W){throw m.aborted?ta(W):W}}),[]);ia(()=>{wt.current=$},[$]),ia(()=>{De.current=K},[K]),ia(()=>{It.current=ze},[ze]),ia(()=>{xe.current=lt},[lt]),ia(()=>(ve.current=!0,()=>{ve.current=!1,Ze.current?.abort(),qe.current?.abort()}),[]),ia(()=>{if(typeof window>"u")return;let S=m=>{m.key==="Escape"&&St(null)};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[]);let kt=Nr((S,m=Ba)=>{xe.current?.(gn(m,S,{code:S.code,declineCode:S.declineCode}))},[]),Ut=Nr(async S=>{ve.current&&(je(null),Q(S.result.status==="authorized"),de("success"),await Zd(600),ve.current&&Lt(()=>De.current?.(S)))},[]),Et=Nr(async(S,m)=>{if(!ve.current)return;!!m?.emitDecline&&jm(S)?kt(S,m?.method):It.current?.(S),je(S.message),Q(!1),de("error"),await Zd(400)},[kt]),G=Nr(async(S,m,W)=>{let B=S.data.session??null;if(!B)throw no(new Eo("No session data returned","api_error"),m);let H=W?.nonce||B.clientSecret||t;if(Wr(B)){await Ut({result:$r(B,m),session:B,sessionId:B.id||m,autoCompleted:!1});return}if(B.status==="expired")throw no(li(B),B.id||m);try{if(S.autoProcessingPending){let ne=S.autoProcessingPending,L=new sl(Xe),Se=await Te(ot=>L.waitForCheckoutSessionCompletion(ne.sessionId,{initialDelayMs:ne.retryAfterMs,nonce:H,statusUrl:ne.statusUrl,signal:ot})),we=ro(Se,B),k=Se.autoProcessingError?.type==="3ds_required"&&!Xd(Se.autoProcessingError)&&Se.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Se.autoProcessingError.nextActionRedirectUrl}:null;if(k&&m&&H){let ot=Da(Xe,m,B),Yt=await Te(qt=>na(k,{billingApiUrl:Xe,sessionId:m,nonce:H,session:B,signal:qt,telemetry:!0,...ot.telemetry?{challengeTelemetry:ot.telemetry}:{}})).finally(ot.release);await Ut({result:Yt,session:B,sessionId:B.id||m,autoCompleted:!1});return}if(Se.autoProcessingError)throw Dr(Se.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Se.autoProcessingError.checkoutMethod});if(!Wr(we))throw Vo(we);await Ut({result:$r(we,m),session:we,sessionId:we.id||m,autoCompleted:!1});return}if(S.autoProcessingError){let ne=S.autoProcessingError.nextActionRedirectUrl;if(S.autoProcessingError.type==="3ds_required"&&!Xd(S.autoProcessingError)&&ne&&m&&H){let L=await Te(ot=>td({billingApiUrl:Xe,sessionId:m,nonce:H,nextActionRedirectUrl:ne,signal:ot}));if(L.status==="declined")throw Dr({type:L.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:L.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:S.autoProcessingError.checkoutMethod});let we=await new sl(Xe).waitForCheckoutSessionCompletion(m,{initialDelayMs:0,nonce:H}),k=ro(we,B);if(!Wr(k))throw Dr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:S.autoProcessingError.checkoutMethod});await Ut({result:$r(k,m),session:k,sessionId:k.id||m,autoCompleted:!1});return}throw Dr(S.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:S.autoProcessingError.checkoutMethod})}if(W?.fromCreateSession&&S.autoProcessingAttempted===!0)throw Dr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let f=await ra({billingApiUrl:Xe,sessionId:m??B.id,session:B,nonce:H});if(f.type==="next_action_required"&&H){let ne=m??B.id,L=Da(Xe,ne,B),Se=await Te(we=>na(f,{billingApiUrl:Xe,sessionId:ne,nonce:H,session:B,signal:we,telemetry:!0,...L.telemetry?{challengeTelemetry:L.telemetry}:{}})).finally(L.release);await Ut({result:Se,session:B,sessionId:B.id||ne,autoCompleted:!1});return}if(f.type!=="success")throw Dr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Ut({result:f.result,session:B,sessionId:B.id||m,autoCompleted:!1})}catch(f){let ne=B.id||m,L=no(Oa(f),ne);if(L.code==="three_ds_aborted")return;if(L.code==="checkout_processing_timeout"){if(!ve.current)return;tt(L.message),Lt(()=>It.current?.(L));return}await Et(L,{emitDecline:!0,method:L.checkoutMethod??Ba}),Jm(L,ne)&&ne&&ve.current&&St({sessionId:ne,errorMessage:L.message,nonce:H||void 0,payPalOrderId:L.orderId})}},[t,Xe,Te,Et,Ut]),ue=Nr(async S=>{let m=new AbortController;qe.current=m;let W=!1,B=setTimeout(()=>{W=!0,m.abort()},Qd);try{let H=await Vm((async()=>S({signal:m.signal}))(),m.signal);if(!ve.current)return null;if(!Gm(H))throw ll("getSession must resolve to a server-minted { sessionId, nonce }.");return{sessionId:H.sessionId,nonce:H.nonce}}catch(H){if(!ve.current)return null;throw H instanceof Eo&&H.code==="session_fetch_failed"?H:W?ll(`getSession did not resolve within ${Qd/1e3} seconds.`):ll("Could not fetch the one-click session.",H)}finally{clearTimeout(B),qe.current===m&&(qe.current=null)}},[]),Me=Nr(async S=>{if(Ie.onClick?.(S),S.defaultPrevented||Ee||dt||(St(null),tt(null),nt.current))return;let m=[e,o,ct].filter(Boolean).length;if(m>1){let W=new Eo("Provide exactly one of sessionId, getSession or create-session props.","validation_error");await Et(W),ve.current&&(de(null),je(null));return}if(m===0){let W=new Eo("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Et(W),ve.current&&(de(null),je(null));return}nt.current=!0,_e(!0),je(null),Q(!1),de("processing");try{let W=new sl(Xe);if(e){let B=await W.getUnifiedCheckoutSession(e,t);await G(B,e);return}if(o){let B=await ue(o);if(!B)return;let H=await W.getUnifiedCheckoutSession(B.sessionId,B.nonce);await G(H,B.sessionId,{nonce:B.nonce});return}Vc();try{let B=await W.createAndFetchSession({...ct});await G(B,B.data.session?.id??null,{fromCreateSession:!0})}catch(B){if(ci(B)==="session_auto_completed"){await Ut({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw B}}catch(W){await Et(no(Ym(W,"Automatic payment failed. Please try again."),e))}finally{nt.current=!1,ve.current&&(de(null),je(null),_e(!1))}},[Ie.onClick,ct,Ee,ue,o,dt,t,G,Xe,e,Et,Ut]),pt=Nr(S=>{let m=wt.current;St(null),De.current?.({result:S,session:null,sessionId:m?.sessionId??null,autoCompleted:!1})},[]),yt=Nr(S=>{It.current?.(S)},[]),Ve=Nr(S=>{xe.current?.(S)},[]),gt=Wa(()=>Hm(ge),[ge]),Pt=Wa(()=>{let S=gt?.buttonsLayout??Wm(v);return Ke?{...S,...Ke,cardButton:{...S.cardButton,...Ke.cardButton}}:S},[gt,v,Ke]),Rt=Wa(()=>{let S=gt?.appearance;return ce?S?{...S,...ce,variables:{...S.variables,...ce.variables}}:ce:S},[ce,gt]),Ge=Rt?.variables,Ye=Ge?.colorPrimary??"#4A49FF",rt=Ge?.colorPrimaryHover??Od(Ye,.12),F=Ge?.borderRadius??"8px";return ef(Qm,{children:[Io("button",{...Ie,type:zt,onClick:Me,disabled:Ee||dt,"aria-busy":dt,style:{width:"100%",...ft===void 0?{boxSizing:"border-box",height:Km,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Pt.cardButton,...Xs({themeBundle:gt,resolvedPrimaryColor:Ye,resolvedBorderRadius:F,submitButtonStyle:Pt.submitButton,explicitPrimaryColor:Ge?.colorPrimary}),fontSize:Pt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ee||dt?"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:Ee||dt?.6:1,...Nt},onMouseEnter:S=>{Ie.onMouseEnter?.(S),!S.defaultPrevented&&!Ee&&!dt&&(gt||Ge?.colorPrimary)&&(S.currentTarget.style.backgroundColor=rt)},onMouseLeave:S=>{Ie.onMouseLeave?.(S),!S.defaultPrevented&&(gt||Ge?.colorPrimary)&&(S.currentTarget.style.backgroundColor=Ye)},onMouseDown:S=>{Ie.onMouseDown?.(S),S.defaultPrevented||(S.currentTarget.style.transform="scale(0.985)")},onMouseUp:S=>{Ie.onMouseUp?.(S),S.defaultPrevented||(S.currentTarget.style.transform="scale(1)")},children:Io($o,{content:ft})}),Ae&&Io("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Ae}),X&&Io(Br,{status:X,errorMessage:Kt,authorized:ut}),$&&Io("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:S=>{S.target===S.currentTarget&&St(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:Io("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:Io(il,{sessionId:$.sessionId,nonce:$.nonce,checkoutMode:"full",billingApiUrl:Xe,locale:b,theme:ge,...Rt?{appearance:Rt}:{},buttonsTheme:v,buttonsStyles:Ke,initialErrorMessage:$.errorMessage,initialPayPalOrderId:$.payPalOrderId,cardTitleContent:null,onComplete:pt,onError:yt,onDecline:Ve})})})]})}import{jsx as rf}from"react/jsx-runtime";var tf={StripeSetupMethod:dc,PayPalSetupMethod:cc};function nf(e){return rf(uc,{...e,branches:tf})}export{hi as DirectPayPalButton,Zm as FloPayAutomaticPaymentButton,wu as FloPayCardSetup,Su as FloPayCardSetupError,il as FloPayCheckout,nf as FloPayPaymentMethodSetup,vi as FloPayProvider,Zs as SplitCardForm,ms as VaultCardFields,Yh as dropThirdPartyOnlyError,Wu as useCheckout,oo as useFloPay,ks as usePayPalFloPay};