@flopay/react 1.14.8 → 1.14.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/checkout-utils.d.ts +12 -3
- package/dist/chunk-BU7THP6H.mjs +1 -0
- package/dist/{chunk-JCJFICSM.mjs → chunk-FGCZOMML.mjs} +2 -2
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +7 -7
- package/dist/payment-method-setup-entry.cjs +3 -3
- package/dist/payment-method-setup-entry.mjs +1 -1
- package/dist/payment-method-setup-paypal-CLV7JDJH.mjs +1 -0
- package/dist/payment-method-setup-stripe-526L4P5X.mjs +1 -0
- package/package.json +5 -5
- package/dist/chunk-HSYSKQPT.mjs +0 -1
- package/dist/payment-method-setup-paypal-AGIJIZDK.mjs +0 -1
- package/dist/payment-method-setup-stripe-AAZGNGQO.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as _l}from"./chunk-D4CVZRT4.mjs";import{c as Lt,d as wr,e as na,f as Bi,g as gl,h as pd,j as yd}from"./chunk-YR36EYW2.mjs";import{a as Rl}from"./chunk-HSYSKQPT.mjs";import{a as oa,b as za,c as Oi,d as Ni,e as Li,f as bl,g as Sl,h as wl,i as kl,j as Il,k as El}from"./chunk-JCJFICSM.mjs";import{a as Oa,b as Fi,c as hl,d as Di,e as bo,f as Pl,g as $r,h as Na,i as vl,j as ra,k as La,l as Cl}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as $f}from"@flopay/shared";import{PaymentAPI as Rs}from"@flopay/js";import{FloPayError as ka,resolveBillingApiUrl as ny,resolveButtonsLayoutTheme as ry,resolveTheme as oy}from"@flopay/shared";import{useCallback as Ur,useEffect as qo,useMemo as wa,useRef as jo,useState as $o}from"react";import{Fragment as Io,jsx as ar,jsxs as Tl}from"react/jsx-runtime";function md(){return Tl(Io,{children:[Tl("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[ar("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),ar("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",ar("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:ar("path",{d:"M9 18l6-6-6-6"})})]})}function fd(){return ar(Io,{children:"Go back"})}function gd(){return ar(Io,{children:"Secure card checkout"})}function So(e){return e!==void 0&&(e===""||e===null||e===!1)}function wo({content:e}){return ar(Io,{children:e===void 0?ar(md,{}):e})}function ko({content:e}){return ar(Io,{children:e===void 0?ar(fd,{}):e})}function aa({content:e}){return ar(Io,{children:e===void 0?ar(gd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as hd,canRecoverHostedCardForm as Pd,classifyTelemetryFailure as vd,FloPayError as zn,isCardHolderNamePlaceholder as Cd,isMoneySettledOutcome as bd,isMountableVaultBlock as Sd,isSetupIntentClientSecret as wd,isValidEmail as kd,resolveSetupFutureUsage as Id,resolveWalletModeOptions as Rd}from"@flopay/shared";import{canRecoverHostedCardForm as ro,hasServerSideCardGateway as zl}from"@flopay/shared";import{splitFullName as la}from"@flopay/shared";import{applyFriendlyMessageOverride as _o}from"@flopay/shared";var Ed="Checkout is temporarily unavailable. Please try again later.";function zi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof zn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function _d(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Ml(){return new zn(Ed,"api_error",{code:"CheckoutInitializationFailed"})}function Al(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(Sd(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||Pd(o))||t&&e?.data.paypal?.publishableKey)}function xl(e,t){if(t&&(!(e instanceof zn)||e.type==="authentication_error"))return zi(e);if(!(e instanceof zn&&_d(e))){if(!t&&!(e instanceof zn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...vd(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof zn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof zn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Ro(e,t,n,o={}){let a;return(i={})=>{if(a!==void 0)return a;let s={...o,...i,email:i.email?.trim()||o.email?.trim()},l=Cd(s.firstName,s.lastName);if(!kd(s.email))return Promise.reject(new zn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let u={};for(let[C,_]of Object.entries(s)){if(l&&C.endsWith("Name")||typeof _!="string")continue;let k=_.trim();k&&(u[C]=k)}return a=e.claimCheckoutSession(t,n,{accountData:u}),a.catch(()=>{}),a}}function Bl(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Ui(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Fl(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],o=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(o*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function qi(e,t){return t?{...e,...t}:e}function Sn(e,t,n){let o=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:o,...a?{code:a}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}function Wr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Dr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Or(e){return e?.status==="authorized"||e?.status==="complete"}function Vr(e,t){if(e.data.session)return e.data.session;let n=e.raw,o=n?.latestTransactionAttempt?.result,a=n?.status==="authorized"||o==="AUTHORIZED";return a||n?.status==="completed"||o==="SUCCESS"?{...t,status:a?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Dl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ua(e){let t=Dl(e);return new zn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function qa(e){return e instanceof zn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Eo(e){return Dl(e)?new zn("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new zn("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new zn(hd,"api_error",{code:"checkout_processing_timeout"})}function ia(e,t){return e==="processing"||bd(e,t)}function Ol(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Nl(e,t){let n=e;if(wd(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new zn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:o,error:a}=await n.retrievePaymentIntent(t);if(a)throw new zn(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var Td=["apple_pay","google_pay"];function Ll(e,t="automatic",n){let o=Id(n,Td,"wallet");return{...Rd(e,t),paymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Md=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ji(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Md.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function sa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Lp,PaymentAPI as di,SESSION_CREATE_TELEMETRY as zp}from"@flopay/js";import{buildCheckoutDisplayData as Up,classifyTelemetryFailure as $c,FloPayError as Bn,isDetachedSessionEligible as qp,isMountableVaultBlock as jp,resolveBillingApiUrl as $p,resolveButtonsLayoutTheme as Wp,resolveDirectPaypalConfig as Wc,resolveIdempotencyKey as Oc,resolveCheckoutLogLayout as Vp,resolveTheme as Vc,SDK_VERSION as Hc,telemetryStatusClass as Hp}from"@flopay/shared";import hs,{useCallback as xn,useEffect as mr,useMemo as sr,useRef as Ot,useState as Zt}from"react";import{createContext as Ul}from"react";var ir=Ul({flopay:null,paypalFlopay:null,billingApiUrl:""}),ur=Ul({session:null,loading:!1,error:null});import{PaymentAPI as Wi}from"@flopay/js";import{buildPayPalCancelEvent as Vd,buildPayPalProcessPaymentRequest as Hd,buildPayPalSessionIntentRequest as Kd,buildPayPalTokenizedBody as Gd,classifyTelemetryFailure as Yd,describePayPalProcessFailure as Jd,FloPayError as Vi,friendlyPayPalFailureMessage as Zd,generateIdempotencyKey as Xd,isPayPalTeardownMessage as Qd,isValidEmail as Gl,mergePayPalPayerIdentity as eu,needsPayPalPayerDetails as tu,normalizeGatewayEnvironment as nu,paypalProviderIdentityRequired as Yl,resolvePayPalApprovalIdentity as ru,resolvePayPalDeclineReason as ou,SDK_VERSION as au,usesPayPalVaultedChannel as iu}from"@flopay/shared";import{loadScript as su}from"@paypal/paypal-js";import{useCallback as kr,useContext as lu,useEffect as zt,useMemo as pa,useRef as tt,useState as Nr}from"react";import{compactBuyerIdentity as Ad,isValidEmail as xd}from"@flopay/shared";import{useCallback as ql,useEffect as Bd,useRef as jl,useState as Wl}from"react";import{compactBuyerIdentity as pr}from"@flopay/shared";import{jsx as $l,jsxs as ca}from"react/jsx-runtime";function To(){let[e,t]=Wl(null),n=jl(null),o=jl(0),a=ql((s,l)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:l}),new Promise(u=>{n.current=u})),[]),i=ql(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Bd(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function Mo({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Wl(e.email?.trim()??""),u=xd(s.trim());return ca("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[ca("div",{style:{fontWeight:700},children:["Continue with ",t]}),ca("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",$l("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:C=>l(C.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),ca("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&$l("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),ca("button",{type:"button",disabled:!u||a,onClick:()=>{n(Ad({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as Fd}from"@flopay/shared";import{useContext as ja}from"react";function Hr(){return ja(ir).flopay}function $i(){return ja(ir).paypalFlopay??null}function Dd(){return ja(ur)}function Vl(){return ja(ir).billingApiUrl||Fd()}import{FLO_INSTRUMENT_ONCE_NAMES as Od,invokeMerchantCallback as Nd,projectFloInstrument as Ld}from"@flopay/shared";import{useCallback as zd,useRef as $a}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Hl}from"@flopay/shared";function Ao(e,t){let n=$a(e);n.current=e;let o=$a(new Set),a=$a(t),i=$a(t);return na(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),zd(s=>{if(i.current!==t)return;let l=Ld(s);if(l){if(Od.has(l.name)){if(o.current.has(l.name))return;o.current.add(l.name)}Nd(()=>n.current?.(l))}},[t])}import{createContext as Ud}from"react";var da=Ud(null);function Wa(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Va="provider.callback.ignored";function Ha(){let e,t=0;return{take(n){return n!==e&&(e=n,t=0),t>=5?!1:(t+=1,!0)}}}var qd=Symbol.for("@flopay/js.telemetry.bridge.v1"),jd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function $d(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Wd(e){let t=$d(),n=(a,i)=>a?a.bind(e):i,o=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:o,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,o()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Ka(e){let t=globalThis[jd];return Wd(t?.(e)??{})}function pn(e){if(e)return e[qd]}import{useCallback as Kr,useEffect as Kl,useRef as oo}from"react";function ua(e,t){let n=oo(0),o=oo(null),a=oo(null),i=oo(e),s=oo(t?.onHandoffObserved),l=oo(t?.defersMissingTerminal),u=oo(t?.onMissingTerminalDeferred);Kl(()=>{i.current=e,s.current=t?.onHandoffObserved,l.current=t?.defersMissingTerminal,u.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let C=Kr((m=a.current)=>{m?.timer&&(clearTimeout(m.timer),m.timer=null)},[]),_=Kr(m=>{C();let b=n.current+1;return n.current=b,o.current=null,a.current={generation:b,method:m,timer:null,yieldedControl:!1},b},[C]),k=Kr(m=>{let b=a.current;return m!==void 0&&b?.generation!==m?!1:(C(b),a.current=null,(m===void 0||o.current===m)&&(o.current=null),!0)},[C]),O=Kr(m=>{let b=a.current,Ve=m??b?.generation??n.current;(m===void 0||b?.generation===m)&&(C(b),a.current=null),o.current=Ve},[C]),ue=Kr(m=>o.current===(m??n.current),[]),N=Kr(m=>a.current?.generation===m&&o.current!==m,[]),Ae=Kr(()=>{let m=a.current;m&&(C(m),!m.yieldedControl&&(m.yieldedControl=!0,s.current?.(m.method)))},[C]),Z=Kr(()=>{let m=a.current;!m?.yieldedControl||document.visibilityState!=="visible"||(C(m),m.timer=setTimeout(()=>{if(m.timer=null,a.current?.generation===m.generation){if(l.current?.(m.method)){u.current?.(m.method,m.generation);return}a.current=null,o.current=m.generation,i.current(m.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},hl))},[C]);return Kl(()=>{let m=()=>{document.visibilityState==="visible"?Z():Ae()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",Ae),window.addEventListener("focus",Z),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",Ae),window.removeEventListener("focus",Z),C()}},[C,Ae,Z]),{startAttempt:_,finishAttempt:k,invalidateAttempt:O,isAttemptInvalidated:ue,isAttemptCurrent:N,generationRef:n}}import{jsx as ao,jsxs as Hi}from"react/jsx-runtime";var Ga=45,cu=1e3,du=11e3,uu={width:"100%",minHeight:Ga,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},pu={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function yu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:pu[e.kind]??null}}function Jl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Pl(t)?"paypal_init_timeout":"paypal_init_failure"}function mu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Zl({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:l,currency:u,isSubscription:C,providerObjectType:_,approvalPresentation:k,onTokenizedBody:O,onComplete:ue,onErrorChange:N,onDecline:Ae,onCancel:Z,onTechnicalFailure:m,isProcessing:b=!1,onLoadStateChange:Ve,onInitializationStateChange:I,allowAutomaticRetry:Xe=!0,onButtonClick:Y,runBeforeButtonClick:Fe,session:nt,existingOrderId:ze,telemetry:He,telemetryContext:It,onInstrument:it,debug:te=!1}){let xt=Hr(),ut=Ao(it,e),rt=pa(()=>{if(xt)return null;let $=Ka({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:au,enabled:He!==!1});return $.setCheckoutContext(It??{}),$.beginCheckout(It??{}),$},[n,xt,He,It?.checkoutMode,It?.layout]),ge=pa(()=>pn(xt),[xt]);zt(()=>()=>{rt&&rt.flush().catch(()=>{}).finally(()=>rt.destroy())},[rt]);let se=pa(()=>({error:$=>{ge?ge.error($):rt?.error($),ut({class:"technical_error",errorCode:$.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":$.errorCode,requestCategory:$.requestCategory,provider:$.provider})},log:$=>{ge?ge.log($):rt?.log($),ut({class:"lifecycle",name:$.name,provider:$.provider})},performance:$=>{ge?ge.performance($):rt?.performance($)},terminal:$=>{ge?ge.terminal($):rt?.terminal($)},startTiming:()=>ge?.now()??rt?.now()??0,elapsed:$=>ge?.elapsed($)??Math.max(0,(rt?.now()??$)-$)}),[ut,ge,rt]),fe=tt(null),wt=tt(0),Bt=tt(null),Qe=tt(null),ne=tt(null),Me=lu(da),de=tt(null);de.current||(de.current=Wa());let L=Me??de.current,Ue=tt(null),De=tt(!1),[Oe,M]=Nr(!1),[qe,gt]=Nr(!1),[_e,ht]=Nr(0),ve=tt(0),[je,Ke]=Nr(!1),wn=tt(!1),Et=tt(!1),[Pt,pe]=Nr(!1),[P,st]=Nr(!1),{request:ot,collect:R,finish:Se}=To(),Ft=tt({sessionId:e,required:Yl(o,nt)});Ft.current.sessionId!==e&&(Ft.current={sessionId:e,required:Yl(o,nt)});let ye=Ft.current.required,kt=pa(()=>n.replace(/\/+$/,""),[n]),v=nt?.gateways?.paypal?.providerObjectType??_,we=v??(C?"subscription":"order"),[Ce]=Nr(ra),et=nt?.gateways?.paypal?.approvalPresentation??k,Ge=La(Ce,et==="app_switch"?"app_switch":void 0,we),ke=iu(v),Ie=pa(()=>JSON.stringify([kt,s,u,l??"",we,ke,Ge,e,ze??""]),[kt,s,u,l,ze,we,ke,Ge,e]),Dt=tt(Ie),d=Dt.current!==Ie,xe=tt(te),he=tt(null),[Re,Q]=Nr([]),j=kr($=>{xe.current&&Q(vt=>[...vt,`${new Date().toISOString().slice(11,23)} ${$}`])},[]);zt(()=>{xe.current=te,te&&j("debug:enabled"),he.current?.setEnabled(te)},[j,te]);let mn=tt(O),Yn=tt(ue),on=tt(N),Wt=tt(Ae),pt=tt(Z),Fn=tt(m),En=tt(Y),Xt=tt(Ve),Un=tt(I),yt=tt(i),fr=tt(Fe),Vt=tt(nt),tr=tt(o),Dn=tt(a),On=tt(t),an=tt(null),fn=tt(new Map),qn=tt(new Map),Be=tt(!1),lt=tt(e);lt.current=e;let[kn]=Nr(Ha);zt(()=>(Be.current=!0,()=>{Be.current=!1}),[]),zt(()=>{mn.current=O},[O]),zt(()=>{yt.current=i},[i]),zt(()=>{Yn.current=ue},[ue]),zt(()=>{on.current=N},[N]),zt(()=>{Wt.current=Ae},[Ae]),zt(()=>{pt.current=Z},[Z]),zt(()=>{Fn.current=m},[m]),zt(()=>{En.current=Y},[Y]),zt(()=>{Xt.current=Ve},[Ve]),zt(()=>{Un.current=I},[I]),zt(()=>{fr.current=Fe},[Fe]),zt(()=>{Vt.current=nt},[nt]),zt(()=>{tr.current=o},[o]),zt(()=>{Dn.current=a},[a]),zt(()=>{On.current=t},[t]),zt(()=>{ve.current=_e},[_e]),zt(()=>{je&&Ue.current?.focus()},[je,_e]);let Ut=kr(()=>{window.setTimeout(()=>{Ue.current?.focus()},0)},[]),sn=kr(()=>{M(!1),ht($=>$+1)},[]),ln=kr(()=>{Ke(!1),(fe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??fe.current)?.focus?.()},[]);zt(()=>{!Oe||!De.current||(De.current=!1,ln())},[ln,Oe,_e]);let Ht=kr(($,vt)=>{let B=vt?.popupBlocked??$r($);B&&L.markBlocked();let qt=Oa("PayPal",B,Ce.inAppBrowser),en=Fn.current;if(en){let ee=B&&Ce.inAppBrowser?new Vi(qt,"api_error",{code:vt?.code??"paypal_popup_blocked"}):$;en("paypal",ee,vt);return}on.current?.(qt)},[L,Ce.inAppBrowser]),Kt=kr($=>{let vt=Bt.current,B=Qe.current;vt===null||!B||(se.log({...B,popupCapability:L.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:$}),se.performance({...B,popupCapability:L.current(),stage:"overlay_return",durationMs:se.elapsed(vt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:$}),Bt.current=null)},[L,se]),gn=kr(($,vt,B)=>{let qt=Qe.current;Kt("overlay_timeout"),qt&&se.error({...qt,popupCapability:L.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Ht(vt,{...B,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Ge,terminalReason:"overlay_timeout"}),Ke(!0),sn(),Ut()},[Kt,Ut,Ht,L,Ge,sn,se]),Ee=kr(()=>{L.markAvailable();let $=Qe.current;$&&(ne.current=$.attempt,se.log({...$,popupCapability:L.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[L,se]),{finishAttempt:hn,generationRef:Pn,invalidateAttempt:_r,isAttemptCurrent:_n,isAttemptInvalidated:Tn,startAttempt:gr}=ua(gn,{onHandoffObserved:Ee}),Jn=kr(()=>(Ke(!1),gr("paypal")),[gr]),Qt=kr($=>{_r($?.generation),$?.showRetry&&Ke(!0),$?.remount&&sn(),$?.focus!==!1&&Ut()},[Ut,_r,sn]),X=$=>{let vt=an.current;return vt&&qn.current.set($,vt),$};zt(()=>{Dt.current!==Ie&&(Dt.current=Ie,wn.current=!1,Et.current=!1,M(!1),gt(!1),pe(!1),Un.current?.("loading"))},[Ie]),zt(()=>{Lt(()=>Xt.current?.(Oe&&!Pt))},[Oe,Pt]);let cn=nu(l);zt(()=>{let $={attempt:Pn.current+1,inAppBrowser:Ce.inAppBrowser,appFamily:Ce.appFamily,popupCapability:L.current(),presentationMode:Ge},vt=()=>({...Qe.current??$,popupCapability:L.current()}),B={error:f=>se.error({...f,...vt()}),log:f=>se.log({...f,...vt()}),performance:f=>se.performance({...f,...vt()}),terminal:f=>se.terminal({...f,...vt()}),startTiming:se.startTiming,elapsed:se.elapsed},qt=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",en=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(j(`mount clientId=${qt} env=${l??"(unset)"}\u2192${cn??"live"} ccy=${u} sub=${C}`),j(`ua=${en.slice(0,80)}${en.length>80?"\u2026":""}`),!s){j("FAIL: clientId empty \u2014 gateway misconfigured"),pe(!0),B.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!fe.current){j("FAIL: containerRef not attached");return}wt.current=B.startTiming(),B.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ee=!1,Nt=!1,U=()=>ee||Nt,_t=f=>{let g=Be.current,h=g?f:"torn_down";g&&j(`onError ignored reason=${h}`),kn.take(lt.current)&&B.log({name:Va,stage:"provider_ready",reason:h,provider:"paypal",paymentMethodCategory:"paypal"})},dn=()=>lt.current===e?"stale_attempt":"session_changed",Mn=ke?we:void 0,Gt,hr=!1,Tr=()=>{Gt=Xd(),Gt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),hr=!0},Pr=null,vr=!1,Mr=null,qr=!1,jr=()=>{!Mr||qr||(qr=!0,Mr.close().catch(()=>{}))},In=!1,Ar=!1,nr=fe.current,Mt=null,$n=null,Wn=[],Zn=null,Vn=!1,Ne=!1,un=null,tn=f=>{if(!f||typeof f.getBoundingClientRect!="function")return"(no rect)";let g=f.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},Hn=f=>{if(!f)return"(empty)";try{let g=new URL(f,typeof window>"u"?"https://localhost":window.location.href),h=g.pathname.toLowerCase();return h.includes("checkcaptcha")||h.includes("captcha")?`CAPTCHA(${g.host}${h})`:h.includes("risk")||h.includes("challenge")?`RISK(${g.host}${h})`:h.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${h}`.slice(0,100)}catch{return f.slice(0,80)}},Zr=f=>{let g=f.getAttribute("src"),h=f.getAttribute("srcdoc"),F=f.getAttribute("name"),J=f.getAttribute("sandbox"),le=[];return g&&le.push(`src=${Hn(g)}`),h&&le.push(`srcdoc[${h.length}ch]`),!g&&!h&&le.push("src=(empty) srcdoc=(empty)"),F&&le.push(`name=${F.slice(0,40)}`),J!==null&&le.push(`sandbox="${J.slice(0,40)}"`),le.join(" ")},xr=f=>{if(!(f instanceof HTMLIFrameElement))return"";try{let g=f.contentDocument;if(!g)return"cd=null";let h=g.body?.children.length??0,F=g.body?.innerHTML.length??0,J=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${h}children,${F}ch] head[${J}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},lr=[],Xn=f=>{if(U())return;let g=f.message??String(f.error??"(no message)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(j(`window:error ${g.slice(0,140)}`),lr.push(g))},vn=f=>{if(U())return;let g=f.reason instanceof Error?f.reason.message:String(f.reason??"(no reason)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(j(`window:rejection ${g.slice(0,140)}`),lr.push(g))},Br={value:0},An=()=>{Mt?.disconnect(),Mt=null,$n?.disconnect(),$n=null;for(let f of Wn.splice(0))clearTimeout(f);Ne=!1,Vn&&typeof window<"u"&&(window.removeEventListener("error",Xn),window.removeEventListener("unhandledrejection",vn)),Vn=!1},S=()=>{if(!(Vn||U()||In)){if(Vn=!0,lr.length=0,Br.value=0,typeof window<"u"&&(window.addEventListener("error",Xn),window.addEventListener("unhandledrejection",vn)),typeof PerformanceObserver<"u")try{$n=new PerformanceObserver(f=>{if(!U())for(let g of f.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;Br.value+=1;let h=Math.round(g.duration);j(`net ${h}ms ${g.name.slice(0,90)}`)}}),$n.observe({type:"resource",buffered:!0})}catch{}un?.()}},w=()=>{Zn&&(clearTimeout(Zn),Zn=null)},q=()=>{An(),w()},re={setEnabled:f=>{f?S():An()}};he.current=re,xe.current&&S();let $e=Qd,jt=f=>{if(U()||$e(f))return;let g=_o(f)??f;Lt(()=>on.current?.(g))},oe=(f,g)=>{if(ee||vr)return;vr=!0,Nt=!0,q(),jr();let h=yu({kind:f,generationActive:!0,automaticRetryAllowed:Xe,automaticRetryUsed:wn.current});if(h.action==="retry"){wn.current=!0,M(!1),st(!1),gt(!0),Un.current?.("retrying"),Pr=setTimeout(()=>{ee||ht(F=>F+1)},cu);return}if(M(!1),st(!1),gt(!1),pe(!0),h.action!=="ignore"){if(Un.current?.("exhausted"),h.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(h.report){let F=Fi({code:Jl(f,g),message:g},{inAppBrowser:Ce.inAppBrowser,handoffObserved:!1});F.popupBlocked&&L.markBlocked(),B.error({errorCode:F.popupBlocked?F.errorCode:h.report.errorCode,stage:h.report.stage,operationOutcome:h.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:F.terminalReason})}Et.current||(Et.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Jl(f,g)))}};pe(!1);let K=async(f,g=an.current)=>{if(U())return;let h=g?.sessionId??e;if(mn.current){await mn.current(f,{sessionId:h,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let F=B.startTiming();B.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let J=()=>{B.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"processing",durationMs:B.elapsed(F),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let le=Hd({body:f,sessionId:h,nonce:g?.nonce??On.current,accountPatch:g?.accountPatch,session:Vt.current,email:tr.current}),D=await new Wi(kt,{telemetry:!1}).processPayment(le.userId,le.params);if(D.ok){if(Nt||ee&&Be.current)return;J(),B.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Lt(()=>Yn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(U())return;let mt=await D.json().catch(()=>null),Nn=Jd(mt),Cn=Nn.message;J(),D.status===400&&(typeof mt?.declineCode=="string"||!Array.isArray(mt?.fields))?B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):D.status===400||D.status===422?B.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):B.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:mu(D.status),failureCategory:D.status>=500?"server_error":void 0}),jt(Cn),Lt(()=>Wt.current?.(Sn("paypal",Cn,{code:Nn.code,declineCode:Nn.declineCode})));return}catch(le){if(U())return;J(),B.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ye=Zd(le instanceof Error?le.message:void 0);jt(Ye),Lt(()=>Wt.current?.(Sn("paypal",Ye)));return}},A=()=>new Vi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),E=f=>U()?Promise.reject(A()):Promise.resolve(f),W=async f=>{if(U())throw A();hr||Tr();let g=an.current,h=g?.sessionId??e,F=g?.nonce??On.current;B.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let J;try{J=await new Wi(kt,{telemetry:!1}).createSessionIntent(h,F??"",Kd(Mn),{idempotencyKey:Gt})}catch(le){throw B.error({...Yd(le,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),le}if(U())throw A();if(J.provider!=="paypal"||J.providerObjectType!==we)throw new Error(f);return B.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),J.providerObjectId},be=(f,g)=>{let h=g?.nonce??On.current;if(!h)return;let F=g?.sessionId??e,J=ou(f);new Wi(kt,{telemetry:!1}).reportSessionIntentDecline(F,h,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:J}).catch(()=>{})},V=_e;j("loadScript:scheduled (deferred 1 tick)");let We=null,Rt=setTimeout(()=>{if(ee){j("loadScript:skipped (cancelled before defer ran)");return}j("loadScript:start");let f=cn==="live"?"production":cn,g={};we==="subscription"?g={intent:"subscription",vault:!0}:we==="order"&&(g={intent:"capture"}),We=su({clientId:s,currency:u,...g,...f?{environment:f}:{},...f==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let h=!1;We.then(F=>{if(h=!0,j(`loadScript:resolved inactive=${U()} ns=${!!F} buttons=${!!F?.Buttons}`),U())return;if(!F?.Buttons){j("FAIL: namespace missing Buttons factory"),oe("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}B.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"provider_ready",durationMs:B.elapsed(wt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),B.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let J=async(G,Le)=>{if(U()||ve.current!==V)return;let z=G.vaultSetupToken??G.subscriptionID??G.orderID??"",ct=z?qn.current.get(z):fn.current.get(V);if(!(!ct||!_n(ct.generation))&&hn(ct.generation)){qn.current.delete(z),fn.current.delete(ct.surfaceKey),Kt("approved");try{if(st(!0),Lt(()=>on.current?.(null)),!z)throw new Vi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let at=ru({accountPatch:ct.accountPatch,email:tr.current,billingName:Dn.current,session:Vt.current});if(tu(at))try{at=eu(at,await Le?.order?.get?.())}catch{}if((yt.current||ye)&&!Gl(at.email)){let Ct=await R("PayPal",at);if(!Ct)return;at=Ct}Gl(at.email)&&(ct.accountPatch=pr({...ct.accountPatch,...at}),await yt.current?.(at));let Ln=Gd(z,Mn);await K(Ln,ct)}catch(at){jt(at instanceof Error?at.message:"PayPal capture failed.")}finally{U()||st(!1)}}},le=G=>{let Le=ze?()=>E(ze):()=>W(G);return async()=>X(await Le())},Ye=F.Buttons({style:{layout:"horizontal",height:Ga,tagline:!1},...Ge==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(G,Le)=>{if(U()){await Le.reject();return}Tr();let z=fr.current,ct={};if(z)try{let Ct=await z("paypal");if(U()){await Le.reject();return}if(!Ct.proceed){an.current=null,fn.current.delete(V),await Le.reject();return}ct={sessionId:Ct.sessionId,accountPatch:Ct.accountPatch,nonce:Ct.nonce}}catch(Ct){j(`onClick:runBeforeButtonClick rejected msg=${(Ct instanceof Error?Ct.message:String(Ct)).slice(0,120)}`),an.current=null,fn.current.delete(V),await Le.reject();return}Lt(()=>En.current?.("paypal"));let at=Jn(),Ln={generation:at,surfaceKey:V,...ct};an.current=Ln,fn.current.set(V,Ln),Qe.current={...$,attempt:at},await Le.resolve(),B.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Bt.current=B.startTiming()},createOrder:we==="order"?le("Failed to create PayPal order."):void 0,createSubscription:we==="subscription"?le("Failed to create PayPal subscription."):void 0,createVaultSetupToken:we==="setup_token"?async()=>X(await W("Failed to create PayPal setup token.")):void 0,onApprove:J,onCancel:()=>{if(U())return;let G=fn.current.get(V)??an.current,Le=G&&_n(G.generation)?Vd(G.sessionId??e,Mn):null;G&&fn.current.delete(G.surfaceKey),an.current=null,Kt("cancelled"),B.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),De.current=!0,Qt({generation:G?.generation,remount:!0,focus:!1}),Le&&Lt(()=>pt.current?.(Le))},onError:G=>{let Le=G instanceof Error?G.message:"PayPal failed to render.";if(U()||ve.current!==V){$e(Le)||_t(dn());return}if(In){let z=fn.current.get(V)??an.current;if(!z||!_n(z.generation)){if($e(Le)){!z&&!Tn()&&hn();return}_t(z||Tn()?"stale_attempt":"no_current_attempt");return}if(j(`onError rendered=${In} msg=${Le.slice(0,120)}`),$e(Le)){hn(z.generation);return}let{errorCode:ct,popupBlocked:at,providerDeclined:Ln,terminalReason:Ct}=Fi(G,{inAppBrowser:Ce.inAppBrowser,handoffObserved:ne.current===z.generation});if(at&&L.markBlocked(),Kt(Ct),Ln){B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ct}),be(G,z),Lt(()=>Wt.current?.(Sn("paypal",Le))),fn.current.delete(z.surfaceKey),an.current=null,hn(z.generation);return}B.error({errorCode:ct,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ct}),fn.current.delete(z.surfaceKey),an.current=null,Qt({generation:z.generation,remount:!0,showRetry:!0,focus:!0}),Ht(G,{code:"paypal_runtime_failed",popupBlocked:at,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Ge,terminalReason:Ct});return}j(`onError rendered=${In} msg=${Le.slice(0,120)}`),oe($e(Le)?"teardown":"pre_ready_callback",Le)}}),D=Ye.isEligible();if(j(`isEligible=${D}`),B.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!D){M(!1),oe("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ar=!0,Mr=Ye,un=()=>{if(!Vn||Ne||U()||In)return;Ne=!0,j(`container:dims ${tn(nr)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Mt=new MutationObserver(Le=>{if(!U()){for(let z of Le)if(z.type==="childList")z.addedNodes.forEach(ct=>{if(!(ct instanceof Element))return;let at=ct.tagName.toLowerCase(),Ln=(ct.getAttribute("title")??"").slice(0,40),Ct=at==="iframe"?` ${Zr(ct)}`:"";j(`child+ ${at}${Ln?` title="${Ln}"`:""}${Ct} dims=${tn(ct)}`)});else if(z.type==="attributes"&&z.target instanceof Element){let ct=z.target;if(ct.tagName.toLowerCase()!=="iframe")continue;let at=z.attributeName;(at==="src"||at==="srcdoc")&&j(`attr~ iframe ${at}=${at==="srcdoc"?`[${(ct.getAttribute("srcdoc")??"").length}ch]`:Hn(ct.getAttribute("src"))} dims=${tn(ct)}`)}}}),Mt.observe(nr,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let G=Le=>{if(U()||In)return;let z=nr.querySelectorAll("iframe"),ct=typeof document<"u"&&"hasStorageAccess"in document;j(`watchdog:${Le} container=${tn(nr)} children=${nr.childElementCount} iframes=${z.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ct} paypalNetRequests=${Br.value}`),z.forEach((at,Ln)=>{let Ct=(at.getAttribute("title")??"").slice(0,40);j(` iframe[${Ln}] ${tn(at)}${Ct?` title="${Ct}"`:""} ${Zr(at)}`);let co=xr(at);co&&j(` ${co}`)}),lr.length===0&&j(" (no PayPal/zoid window errors captured)")};Wn.push(setTimeout(()=>G("3s"),3e3)),Wn.push(setTimeout(()=>G("8s"),8e3)),Wn.push(setTimeout(()=>G("15s"),15e3))},un(),j("render:start");let Nn=B.startTiming();Zn=setTimeout(()=>{U()||In||(j("watchdog:11s retryable render timeout"),oe("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},du);let Cn=Ye.render(nr);(async()=>{try{if(await Cn,j(`render:resolved inactive=${U()}`),q(),U()){jr();return}In=!0,M(!0),gt(!1),Un.current?.("ready"),B.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"checkout_render",durationMs:B.elapsed(Nn),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(G){let Le=G instanceof Error?G.message:"PayPal failed to render.";j(`render:rejected msg=${Le.slice(0,120)}`),q(),oe($e(Le)?"teardown":"render_rejected",Le)}})()}).catch(F=>{let J=F instanceof Error?F.message:"PayPal operation failed.";j(`provider:failed msg=${J.slice(0,120)}`);let le="script_rejected";h&&$e(J)?le="teardown":h&&Ar&&(le="render_rejected"),oe(le,J)})},0);return()=>{ee=!0,clearTimeout(Rt),Pr&&clearTimeout(Pr),q(),he.current===re&&(he.current=null),jr(),Bt.current=null,Qe.current=null}},[Xe,kt,s,u,l,we,Ge,ke,e,ze,_e,se,R,ye,j,Kt]);let jn=te?Hi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Pt?"#fef2f2":"#f3f4f6",border:`1px solid ${Pt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Oe} failed=${Pt})`,Re.length===0?`
|
|
1
|
+
import{a as Tl}from"./chunk-D4CVZRT4.mjs";import{c as Tt,d as Rr,e as na,f as Di,g as hl,h as Pd,j as vd}from"./chunk-YR36EYW2.mjs";import{a as _l}from"./chunk-BU7THP6H.mjs";import{a as oa,b as qa,c as Li,d as Ui,e as zi,f as Sl,g as wl,h as kl,i as Il,j as Rl,k as El}from"./chunk-FGCZOMML.mjs";import{a as La,b as Oi,c as Pl,d as Ni,e as Co,f as vl,g as Vr,h as Ua,i as Cl,j as ra,k as za,l as bl}from"./chunk-VK67324N.mjs";import{dropThirdPartyOnlyError as Yf}from"@flopay/shared";import{PaymentAPI as _s}from"@flopay/js";import{FloPayError as ka,resolveBillingApiUrl as sy,resolveButtonsLayoutTheme as ly,resolveTheme as cy}from"@flopay/shared";import{useCallback as jr,useEffect as qo,useMemo as wa,useRef as jo,useState as $o}from"react";import{Fragment as ko,jsx as sr,jsxs as Ml}from"react/jsx-runtime";function Cd(){return Ml(ko,{children:[Ml("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[sr("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),sr("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",sr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:sr("path",{d:"M9 18l6-6-6-6"})})]})}function bd(){return sr(ko,{children:"Go back"})}function Sd(){return sr(ko,{children:"Secure card checkout"})}function bo(e){return e!==void 0&&(e===""||e===null||e===!1)}function So({content:e}){return sr(ko,{children:e===void 0?sr(Cd,{}):e})}function wo({content:e}){return sr(ko,{children:e===void 0?sr(bd,{}):e})}function aa({content:e}){return sr(ko,{children:e===void 0?sr(Sd,{}):e})}import{CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as wd,canRecoverHostedCardForm as kd,classifyTelemetryFailure as Id,FloPayError as Zn,isCardHolderNamePlaceholder as Rd,isMoneySettledOutcome as _d,isMountableVaultBlock as Ed,isSetupIntentClientSecret as Td,isValidEmail as Md,resolveSetupFutureUsage as Ad,resolveWalletModeOptions as xd}from"@flopay/shared";import{canRecoverHostedCardForm as oo,hasServerSideCardGateway as jl}from"@flopay/shared";import{splitFullName as la}from"@flopay/shared";import{applyFriendlyMessageOverride as _o}from"@flopay/shared";function qi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Zn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Bd(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Al(e,t,n){let o=e?.data.session,a=o?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(Ed(o?.vault)||o?.gateways?.pcivault||a?.includes("card")||kd(o))||t&&e?.data.paypal?.publishableKey)}function xl(e,t){if(t&&(!(e instanceof Zn)||e.type==="authentication_error"))return qi(e);if(!(e instanceof Zn&&Bd(e))){if(!t&&!(e instanceof Zn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Id(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Zn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Zn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Io(e,t,n,o={}){let a;return(i={})=>{if(a!==void 0)return a;let s={...o,...i,email:i.email?.trim()||o.email?.trim()},l=Rd(s.firstName,s.lastName);if(!Md(s.email))return Promise.reject(new Zn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let m={};for(let[C,T]of Object.entries(s)){if(l&&C.endsWith("Name")||typeof T!="string")continue;let I=T.trim();I&&(m[C]=I)}return a=e.claimCheckoutSession(t,n,{accountData:m}),a.catch(()=>{}),a}}function Bl(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function ji(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Fl(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],o=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(o*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function $i(e,t){return t?{...e,...t}:e}function fn(e,t,n){let o=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode,s=typeof t=="string"?void 0:t.sessionId;return{method:e,message:o,...a?{code:a}:{},...i?{declineCode:i}:{},...s?{sessionId:s}:{}}}var Dl=new WeakMap;function Ol(e,t){return typeof e=="object"&&e!==null&&Dl.set(e,t?{sessionId:t}:{}),e}function Nl(e){return typeof e=="object"&&e!==null?Dl.get(e):void 0}function Hr(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Lr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Ur(e){return e?.status==="authorized"||e?.status==="complete"}function Kr(e,t){if(e.data.session)return e.data.session;let n=e.raw,o=n?.latestTransactionAttempt?.result,a=n?.status==="authorized"||o==="AUTHORIZED";return a||n?.status==="completed"||o==="SUCCESS"?{...t,status:a?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Ll(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ja(e){let t=Ll(e);return new Zn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $a(e){return e instanceof Zn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Ro(e){return Ll(e)?new Zn("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Zn("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Zn(wd,"api_error",{code:"checkout_processing_timeout"})}function ia(e,t){return e==="processing"||_d(e,t)}function Ul(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function zl(e,t){let n=e;if(Td(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new Zn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:o,error:a}=await n.retrievePaymentIntent(t);if(a)throw new Zn(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return o??null}var Fd=["apple_pay","google_pay"];function ql(e,t="automatic",n){let o=Ad(n,Fd,"wallet");return{...xd(e,t),allowedPaymentMethodTypes:["card"],...o?{setupFutureUsage:o}:{}}}var Dd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Wi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Dd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function sa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as $p,PaymentAPI as yi,SESSION_CREATE_TELEMETRY as Wp}from"@flopay/js";import{buildCheckoutDisplayData as Vp,classifyTelemetryFailure as Yc,FloPayError as Mn,isDetachedSessionEligible as Hp,isMountableVaultBlock as Kp,resolveBillingApiUrl as Gp,resolveButtonsLayoutTheme as Yp,resolveDirectPaypalConfig as Jc,resolveIdempotencyKey as qc,resolveCheckoutLogLayout as Jp,resolveTheme as Xc,SDK_VERSION as Zc,telemetryStatusClass as Xp,toPublicCheckoutInitError as jc}from"@flopay/shared";import Ps,{useCallback as Nn,useEffect as hr,useMemo as cr,useRef as Nt,useState as Xt}from"react";import{createContext as $l}from"react";var lr=$l({flopay:null,paypalFlopay:null,billingApiUrl:""}),mr=$l({session:null,loading:!1,error:null});import{PaymentAPI as Hi}from"@flopay/js";import{buildPayPalCancelEvent as Jd,buildPayPalProcessPaymentRequest as Xd,buildPayPalSessionIntentRequest as Zd,buildPayPalTokenizedBody as Qd,classifyTelemetryFailure as eu,describePayPalProcessFailure as Xl,FloPayError as Ao,friendlyPayPalFailureMessage as tu,generateIdempotencyKey as nu,isPayPalTeardownMessage as ru,isSettledSessionIntent as ou,isValidEmail as Zl,mergePayPalPayerIdentity as au,needsPayPalPayerDetails as iu,normalizeGatewayEnvironment as su,paypalProviderIdentityRequired as Ql,resolvePayPalApprovalIdentity as lu,resolvePayPalDeclineReason as cu,SDK_VERSION as du,usesPayPalVaultedChannel as uu}from"@flopay/shared";import{loadScript as pu}from"@paypal/paypal-js";import{useCallback as _r,useContext as yu,useEffect as Ut,useMemo as pa,useRef as rt,useState as zr}from"react";import{compactBuyerIdentity as Od,isValidEmail as Nd}from"@flopay/shared";import{useCallback as Wl,useEffect as Ld,useRef as Vl,useState as Kl}from"react";import{compactBuyerIdentity as fr}from"@flopay/shared";import{jsx as Hl,jsxs as ca}from"react/jsx-runtime";function Eo(){let[e,t]=Kl(null),n=Vl(null),o=Vl(0),a=Wl((s,l)=>(n.current?.(null),o.current+=1,t({id:o.current,methodLabel:s,identity:l}),new Promise(m=>{n.current=m})),[]),i=Wl(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Ld(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function To({identity:e,methodLabel:t,onComplete:n,onCancel:o,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Kl(e.email?.trim()??""),m=Nd(s.trim());return ca("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[ca("div",{style:{fontWeight:700},children:["Continue with ",t]}),ca("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Hl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:C=>l(C.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),ca("div",{style:{display:"flex",gap:"0.5rem"},children:[o&&Hl("button",{type:"button",onClick:o,style:{flex:1,minHeight:42},children:"Cancel"}),ca("button",{type:"button",disabled:!m||a,onClick:()=>{n(Od({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}import{resolveBillingApiUrl as Ud}from"@flopay/shared";import{useContext as Wa}from"react";function Gr(){return Wa(lr).flopay}function Vi(){return Wa(lr).paypalFlopay??null}function zd(){return Wa(mr)}function Gl(){return Wa(lr).billingApiUrl||Ud()}import{FLO_INSTRUMENT_ONCE_NAMES as qd,invokeMerchantCallback as jd,projectFloInstrument as $d}from"@flopay/shared";import{useCallback as Wd,useRef as Va}from"react";import{FLO_INSTRUMENT_ONCE_NAMES as Yl}from"@flopay/shared";function Mo(e,t){let n=Va(e);n.current=e;let o=Va(new Set),a=Va(t),i=Va(t);return na(()=>{i.current=t,a.current!==t&&(a.current=t,o.current.clear())},[t]),Wd(s=>{if(i.current!==t)return;let l=$d(s);if(l){if(qd.has(l.name)){if(o.current.has(l.name))return;o.current.add(l.name)}jd(()=>n.current?.(l))}},[t])}import{createContext as Vd}from"react";var da=Vd(null);function Ha(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Ka="provider.callback.ignored";function Ga(){let e,t=0;return{take(n){return n!==e&&(e=n,t=0),t>=5?!1:(t+=1,!0)}}}var Hd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Kd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Gd(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Yd(e){let t=Gd(),n=(a,i)=>a?a.bind(e):i,o=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:o,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,o()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Ya(e){let t=globalThis[Kd];return Yd(t?.(e)??{})}function gn(e){if(e)return e[Hd]}import{useCallback as Yr,useEffect as Jl,useRef as ao}from"react";function ua(e,t){let n=ao(0),o=ao(null),a=ao(null),i=ao(e),s=ao(t?.onHandoffObserved),l=ao(t?.defersMissingTerminal),m=ao(t?.onMissingTerminalDeferred);Jl(()=>{i.current=e,s.current=t?.onHandoffObserved,l.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let C=Yr((g=a.current)=>{g?.timer&&(clearTimeout(g.timer),g.timer=null)},[]),T=Yr(g=>{C();let S=n.current+1;return n.current=S,o.current=null,a.current={generation:S,method:g,timer:null,yieldedControl:!1},S},[C]),I=Yr(g=>{let S=a.current;return g!==void 0&&S?.generation!==g?!1:(C(S),a.current=null,(g===void 0||o.current===g)&&(o.current=null),!0)},[C]),N=Yr(g=>{let S=a.current,Ve=g??S?.generation??n.current;(g===void 0||S?.generation===g)&&(C(S),a.current=null),o.current=Ve},[C]),ue=Yr(g=>o.current===(g??n.current),[]),L=Yr(g=>a.current?.generation===g&&o.current!==g,[]),Be=Yr(()=>{let g=a.current;g&&(C(g),!g.yieldedControl&&(g.yieldedControl=!0,s.current?.(g.method)))},[C]),K=Yr(()=>{let g=a.current;!g?.yieldedControl||document.visibilityState!=="visible"||(C(g),g.timer=setTimeout(()=>{if(g.timer=null,a.current?.generation===g.generation){if(l.current?.(g.method)){m.current?.(g.method,g.generation);return}a.current=null,o.current=g.generation,i.current(g.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},Pl))},[C]);return Jl(()=>{let g=()=>{document.visibilityState==="visible"?K():Be()};return document.addEventListener("visibilitychange",g),window.addEventListener("blur",Be),window.addEventListener("focus",K),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("blur",Be),window.removeEventListener("focus",K),C()}},[C,Be,K]),{startAttempt:T,finishAttempt:I,invalidateAttempt:N,isAttemptInvalidated:ue,isAttemptCurrent:L,generationRef:n}}import{jsx as io,jsxs as Ki}from"react/jsx-runtime";var Ja=45,mu=1e3,fu=11e3,ec="paypal_intent_settled",gu={width:"100%",minHeight:Ja,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},hu={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function Pu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:hu[e.kind]??null}}function tc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":vl(t)?"paypal_init_timeout":"paypal_init_failure"}function vu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function nc({sessionId:e,nonce:t,billingApiUrl:n,email:o,billingName:a,onBuyerIdentityReady:i,clientId:s,environment:l,currency:m,isSubscription:C,providerObjectType:T,approvalPresentation:I,onTokenizedBody:N,onComplete:ue,onErrorChange:L,onDecline:Be,onCancel:K,onTechnicalFailure:g,isProcessing:S=!1,onLoadStateChange:Ve,onInitializationStateChange:R,allowAutomaticRetry:Xe=!0,onButtonClick:H,runBeforeButtonClick:Ne,session:ot,existingOrderId:ze,telemetry:qe,telemetryContext:It,onInstrument:st,debug:ee=!1}){let Bt=Gr(),ut=Mo(st,e),at=pa(()=>{if(Bt)return null;let U=Ya({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:du,enabled:qe!==!1});return U.setCheckoutContext(It??{}),U.beginCheckout(It??{}),U},[n,Bt,qe,It?.checkoutMode,It?.layout]),fe=pa(()=>gn(Bt),[Bt]);Ut(()=>()=>{at&&at.flush().catch(()=>{}).finally(()=>at.destroy())},[at]);let ie=pa(()=>({error:U=>{fe?fe.error(U):at?.error(U),ut({class:"technical_error",errorCode:U.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":U.errorCode,requestCategory:U.requestCategory,provider:U.provider})},log:U=>{fe?fe.log(U):at?.log(U),ut({class:"lifecycle",name:U.name,provider:U.provider})},performance:U=>{fe?fe.performance(U):at?.performance(U)},terminal:U=>{fe?fe.terminal(U):at?.terminal(U)},startTiming:()=>fe?.now()??at?.now()??0,elapsed:U=>fe?.elapsed(U)??Math.max(0,(at?.now()??U)-U)}),[ut,fe,at]),pe=rt(null),ft=rt(0),Ft=rt(null),Ze=rt(null),Y=rt(null),_e=yu(da),se=rt(null);se.current||(se.current=Ha());let O=_e??se.current,je=rt(null),Le=rt(!1),[Fe,E]=zr(!1),[De,gt]=zr(!1),[Ee,ht]=zr(0),Pe=rt(0),[$e,He]=zr(!1),In=rt(!1),_t=rt(!1),[Pt,ce]=zr(!1),[h,lt]=zr(!1),{request:Qe,collect:_,finish:Ce}=Eo(),Dt=rt({sessionId:e,required:Ql(o,ot)});Dt.current.sessionId!==e&&(Dt.current={sessionId:e,required:Ql(o,ot)});let de=Dt.current.required,kt=pa(()=>n.replace(/\/+$/,""),[n]),P=ot?.gateways?.paypal?.providerObjectType??T,ge=P??(C?"subscription":"order"),[ve]=zr(ra),et=ot?.gateways?.paypal?.approvalPresentation??I,Ke=za(ve,et==="app_switch"?"app_switch":void 0,ge),be=uu(P),we=pa(()=>JSON.stringify([kt,s,m,l??"",ge,be,Ke,e,ze??""]),[kt,s,m,l,ze,ge,be,Ke,e]),Ot=rt(we),p=Ot.current!==we,Oe=rt(ee),he=rt(null),[Se,J]=zr([]),z=_r(U=>{Oe.current&&J(vt=>[...vt,`${new Date().toISOString().slice(11,23)} ${U}`])},[]);Ut(()=>{Oe.current=ee,ee&&z("debug:enabled"),he.current?.setEnabled(ee)},[z,ee]);let Pn=rt(N),Wn=rt(ue),Zt=rt(L),zt=rt(Be),pt=rt(K),Ln=rt(g),An=rt(H),Qt=rt(Ve),Vn=rt(R),yt=rt(i),Pr=rt(Ne),Vt=rt(ot),rr=rt(o),Un=rt(a),zn=rt(t),Ht=rt(null),un=rt(new Map),Hn=rt(new Map),Me=rt(!1),it=rt(e);it.current=e;let[Rn]=zr(Ga);Ut(()=>(Me.current=!0,()=>{Me.current=!1}),[]),Ut(()=>{Pn.current=N},[N]),Ut(()=>{yt.current=i},[i]),Ut(()=>{Wn.current=ue},[ue]),Ut(()=>{Zt.current=L},[L]),Ut(()=>{zt.current=Be},[Be]),Ut(()=>{pt.current=K},[K]),Ut(()=>{Ln.current=g},[g]),Ut(()=>{An.current=H},[H]),Ut(()=>{Qt.current=Ve},[Ve]),Ut(()=>{Vn.current=R},[R]),Ut(()=>{Pr.current=Ne},[Ne]),Ut(()=>{Vt.current=ot},[ot]),Ut(()=>{rr.current=o},[o]),Ut(()=>{Un.current=a},[a]),Ut(()=>{zn.current=t},[t]),Ut(()=>{Pe.current=Ee},[Ee]),Ut(()=>{$e&&je.current?.focus()},[$e,Ee]);let qt=_r(()=>{window.setTimeout(()=>{je.current?.focus()},0)},[]),en=_r(()=>{E(!1),ht(U=>U+1)},[]),pn=_r(()=>{He(!1),(pe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??pe.current)?.focus?.()},[]);Ut(()=>{!Fe||!Le.current||(Le.current=!1,pn())},[pn,Fe,Ee]);let Kt=_r((U,vt)=>{let x=vt?.popupBlocked??Vr(U);x&&O.markBlocked();let $t=La("PayPal",x,ve.inAppBrowser),rn=Ln.current;if(rn){let X=x&&ve.inAppBrowser?new Ao($t,"api_error",{code:vt?.code??"paypal_popup_blocked"}):U;rn("paypal",X,vt);return}if(U instanceof Ao&&U.code==="checkout_processing_timeout"){Zt.current?.(U.message);return}Zt.current?.($t)},[O,ve.inAppBrowser]),jt=_r(U=>{let vt=Ft.current,x=Ze.current;vt===null||!x||(ie.log({...x,popupCapability:O.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:U}),ie.performance({...x,popupCapability:O.current(),stage:"overlay_return",durationMs:ie.elapsed(vt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:U}),Ft.current=null)},[O,ie]),vn=_r((U,vt,x)=>{let $t=Ze.current;jt("overlay_timeout"),$t&&ie.error({...$t,popupCapability:O.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Kt(vt,{...x,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Ke,terminalReason:"overlay_timeout"}),He(!0),en(),qt()},[jt,qt,Kt,O,Ke,en,ie]),ke=_r(()=>{O.markAvailable();let U=Ze.current;U&&(Y.current=U.attempt,ie.log({...U,popupCapability:O.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[O,ie]),{finishAttempt:tn,generationRef:Cn,invalidateAttempt:xr,isAttemptCurrent:xn,isAttemptInvalidated:Bn,startAttempt:vr}=ua(vn,{onHandoffObserved:ke}),Qn=_r(()=>(He(!1),vr("paypal")),[vr]),nn=_r(U=>{xr(U?.generation),U?.showRetry&&He(!0),U?.remount&&en(),U?.focus!==!1&&qt()},[qt,xr,en]),G=U=>{let vt=Ht.current;return vt&&Hn.current.set(U,vt),U};Ut(()=>{Ot.current!==we&&(Ot.current=we,In.current=!1,_t.current=!1,E(!1),gt(!1),ce(!1),Vn.current?.("loading"))},[we]),Ut(()=>{Tt(()=>Qt.current?.(Fe&&!Pt))},[Fe,Pt]);let yn=su(l);Ut(()=>{let U={attempt:Cn.current+1,inAppBrowser:ve.inAppBrowser,appFamily:ve.appFamily,popupCapability:O.current(),presentationMode:Ke},vt=()=>({...Ze.current??U,popupCapability:O.current()}),x={error:d=>ie.error({...d,...vt()}),log:d=>ie.log({...d,...vt()}),performance:d=>ie.performance({...d,...vt()}),terminal:d=>ie.terminal({...d,...vt()}),startTiming:ie.startTiming,elapsed:ie.elapsed},$t=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",rn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(z(`mount clientId=${$t} env=${l??"(unset)"}\u2192${yn??"live"} ccy=${m} sub=${C}`),z(`ua=${rn.slice(0,80)}${rn.length>80?"\u2026":""}`),!s){z("FAIL: clientId empty \u2014 gateway misconfigured"),ce(!0),x.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!pe.current){z("FAIL: containerRef not attached");return}ft.current=x.startTiming(),x.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let X=!1,Lt=!1,q=()=>X||Lt,Et=d=>{let c=Me.current,v=c?d:"torn_down";c&&z(`onError ignored reason=${v}`),Rn.take(it.current)&&x.log({name:Ka,stage:"provider_ready",reason:v,provider:"paypal",paymentMethodCategory:"paypal"})},mn=()=>it.current===e?"stale_attempt":"session_changed",Fn=be?ge:void 0,Gt,Cr=!1,Br=()=>{Gt=nu(),Gt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Cr=!0},br=null,Sr=!1,Fr=null,$r=!1,Wr=()=>{!Fr||$r||($r=!0,Fr.close().catch(()=>{}))},_n=!1,Dr=!1,or=pe.current,At=null,Kn=null,Gn=[],er=null,Yn=!1,Ue=!1,ln=null,on=d=>{if(!d||typeof d.getBoundingClientRect!="function")return"(no rect)";let c=d.getBoundingClientRect();return`${Math.round(c.width)}\xD7${Math.round(c.height)}`},jn=d=>{if(!d)return"(empty)";try{let c=new URL(d,typeof window>"u"?"https://localhost":window.location.href),v=c.pathname.toLowerCase();return v.includes("checkcaptcha")||v.includes("captcha")?`CAPTCHA(${c.host}${v})`:v.includes("risk")||v.includes("challenge")?`RISK(${c.host}${v})`:v.includes("smart/buttons")?`smart-buttons(${c.host})`:`${c.host}${v}`.slice(0,100)}catch{return d.slice(0,80)}},Qr=d=>{let c=d.getAttribute("src"),v=d.getAttribute("srcdoc"),Q=d.getAttribute("name"),re=d.getAttribute("sandbox"),b=[];return c&&b.push(`src=${jn(c)}`),v&&b.push(`srcdoc[${v.length}ch]`),!c&&!v&&b.push("src=(empty) srcdoc=(empty)"),Q&&b.push(`name=${Q.slice(0,40)}`),re!==null&&b.push(`sandbox="${re.slice(0,40)}"`),b.join(" ")},Or=d=>{if(!(d instanceof HTMLIFrameElement))return"";try{let c=d.contentDocument;if(!c)return"cd=null";let v=c.body?.children.length??0,Q=c.body?.innerHTML.length??0,re=c.head?.innerHTML.length??0;return`cd=same-origin readyState=${c.readyState} body[${v}children,${Q}ch] head[${re}ch]`}catch(c){return`cd=cross-origin(${c.message.slice(0,30)})`}},dr=[],tr=d=>{if(q())return;let c=d.message??String(d.error??"(no message)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(z(`window:error ${c.slice(0,140)}`),dr.push(c))},bn=d=>{if(q())return;let c=d.reason instanceof Error?d.reason.message:String(d.reason??"(no reason)");c&&(c.toLowerCase().includes("paypal")||c.toLowerCase().includes("zoid")||c.toLowerCase().includes("postrobot")||c.toLowerCase().includes("storage"))&&(z(`window:rejection ${c.slice(0,140)}`),dr.push(c))},Nr={value:0},Dn=()=>{At?.disconnect(),At=null,Kn?.disconnect(),Kn=null;for(let d of Gn.splice(0))clearTimeout(d);Ue=!1,Yn&&typeof window<"u"&&(window.removeEventListener("error",tr),window.removeEventListener("unhandledrejection",bn)),Yn=!1},w=()=>{if(!(Yn||q()||_n)){if(Yn=!0,dr.length=0,Nr.value=0,typeof window<"u"&&(window.addEventListener("error",tr),window.addEventListener("unhandledrejection",bn)),typeof PerformanceObserver<"u")try{Kn=new PerformanceObserver(d=>{if(!q())for(let c of d.getEntries()){if(!c.name.toLowerCase().includes("paypal"))continue;Nr.value+=1;let v=Math.round(c.duration);z(`net ${v}ms ${c.name.slice(0,90)}`)}}),Kn.observe({type:"resource",buffered:!0})}catch{}ln?.()}},k=()=>{er&&(clearTimeout(er),er=null)},j=()=>{Dn(),k()},te={setEnabled:d=>{d?w():Dn()}};he.current=te,Oe.current&&w();let We=ru,Wt=d=>{if(q()||We(d))return;let c=_o(d)??d;Tt(()=>Zt.current?.(c))},ne=(d,c)=>{if(X||Sr)return;Sr=!0,Lt=!0,j(),Wr();let v=Pu({kind:d,generationActive:!0,automaticRetryAllowed:Xe,automaticRetryUsed:In.current});if(v.action==="retry"){In.current=!0,E(!1),lt(!1),gt(!0),Vn.current?.("retrying"),br=setTimeout(()=>{X||ht(Q=>Q+1)},mu);return}if(E(!1),lt(!1),gt(!1),ce(!0),v.action!=="ignore"){if(Vn.current?.("exhausted"),v.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",c);return}if(v.report){let Q=Oi({code:tc(d,c),message:c},{inAppBrowser:ve.inAppBrowser,handoffObserved:!1});Q.popupBlocked&&O.markBlocked(),x.error({errorCode:Q.popupBlocked?Q.errorCode:v.report.errorCode,stage:v.report.stage,operationOutcome:v.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:Q.terminalReason})}_t.current||(_t.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",tc(d,c)))}};ce(!1);let W=async(d,c=Ht.current)=>{if(q())return;let v=c?.sessionId??e;if(Pn.current){await Pn.current(d,{sessionId:v,accountPatch:c?.accountPatch,nonce:c?.nonce});return}let Q=x.startTiming();x.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let re=()=>{x.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),x.performance({stage:"processing",durationMs:x.elapsed(Q),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let b=Xd({body:d,sessionId:v,nonce:c?.nonce??zn.current,accountPatch:c?.accountPatch,session:Vt.current,email:rr.current}),cn=await new Hi(kt,{telemetry:!1}).processPayment(b.userId,b.params);if(cn.ok){if(Lt||X&&Me.current)return;re(),x.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Tt(()=>Wn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(q())return;let wn=await cn.json().catch(()=>null),nt=Xl(wn),nr=nt.message;re(),cn.status===400&&(typeof wn?.declineCode=="string"||!Array.isArray(wn?.fields))?x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):cn.status===400||cn.status===422?x.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):x.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:vu(cn.status),failureCategory:cn.status>=500?"server_error":void 0}),Wt(nr),Tt(()=>zt.current?.(fn("paypal",nr,{code:nt.code,declineCode:nt.declineCode})));return}catch(b){if(q())return;re(),x.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let tt=tu(b instanceof Error?b.message:void 0);Wt(tt),Tt(()=>zt.current?.(fn("paypal",tt)));return}},B=()=>new Ao("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Z=d=>q()?Promise.reject(B()):Promise.resolve(d),F=async d=>{if(d.ok){x.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Tt(()=>Wn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}let c=await d.json().catch(()=>null),v=Xl(c);x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Tt(()=>zt.current?.(fn("paypal",v.message,{code:v.code,declineCode:v.declineCode})))},Ae=()=>{let d=Ht.current;jt("approved"),d&&(un.current.delete(d.surfaceKey),tn(d.generation)),Ht.current=null},D=async d=>{if(q())throw B();Cr||Br();let c=Ht.current,v=c?.sessionId??e,Q=c?.nonce??zn.current;x.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let re;try{re=await new Hi(kt,{telemetry:!1}).createSessionIntent(v,Q??"",Zd(Fn),{idempotencyKey:Gt})}catch(b){throw x.error({...eu(b,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),b}if(q())throw B();if(ou(re))throw await F(re.response),Ae(),new Ao("PayPal checkout already settled.","api_error",{code:ec});if(re.provider!=="paypal"||re.providerObjectType!==ge)throw new Error(d);return x.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),re.providerObjectId},Ie=(d,c)=>{let v=c?.nonce??zn.current;if(!v)return;let Q=c?.sessionId??e,re=cu(d);new Hi(kt,{telemetry:!1}).reportSessionIntentDecline(Q,v,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:re}).catch(()=>{})},Re=Ee;z("loadScript:scheduled (deferred 1 tick)");let Ct=null,Sn=setTimeout(()=>{if(X){z("loadScript:skipped (cancelled before defer ran)");return}z("loadScript:start");let d=yn==="live"?"production":yn,c={};ge==="subscription"?c={intent:"subscription",vault:!0}:ge==="order"&&(c={intent:"capture"}),Ct=pu({clientId:s,currency:m,...c,...d?{environment:d}:{},...d==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let v=!1;Ct.then(Q=>{if(v=!0,z(`loadScript:resolved inactive=${q()} ns=${!!Q} buttons=${!!Q?.Buttons}`),q())return;if(!Q?.Buttons){z("FAIL: namespace missing Buttons factory"),ne("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}x.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),x.performance({stage:"provider_ready",durationMs:x.elapsed(ft.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),x.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let re=async($,Ge)=>{if(q()||Pe.current!==Re)return;let ct=$.vaultSetupToken??$.subscriptionID??$.orderID??"",bt=ct?Hn.current.get(ct):un.current.get(Re);if(!(!bt||!xn(bt.generation))&&tn(bt.generation)){Hn.current.delete(ct),un.current.delete(bt.surfaceKey),jt("approved");try{if(lt(!0),Tt(()=>Zt.current?.(null)),!ct)throw new Ao("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let xe=lu({accountPatch:bt.accountPatch,email:rr.current,billingName:Un.current,session:Vt.current});if(iu(xe))try{xe=au(xe,await Ge?.order?.get?.())}catch{}if((yt.current||de)&&!Zl(xe.email)){let Rt=await _("PayPal",xe);if(!Rt)return;xe=Rt}Zl(xe.email)&&(bt.accountPatch=fr({...bt.accountPatch,...xe}),await yt.current?.(xe));let $n=Qd(ct,Fn);await W($n,bt)}catch(xe){Wt(xe instanceof Error?xe.message:"PayPal capture failed.")}finally{q()||lt(!1)}}},b=$=>{let Ge=ze?()=>Z(ze):()=>D($);return async()=>G(await Ge())},tt=Q.Buttons({style:{layout:"horizontal",height:Ja,tagline:!1},...Ke==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async($,Ge)=>{if(q()){await Ge.reject();return}Br();let ct=Pr.current,bt={};if(ct)try{let Rt=await ct("paypal");if(q()){await Ge.reject();return}if(!Rt.proceed){Ht.current=null,un.current.delete(Re),await Ge.reject();return}bt={sessionId:Rt.sessionId,accountPatch:Rt.accountPatch,nonce:Rt.nonce}}catch(Rt){z(`onClick:runBeforeButtonClick rejected msg=${(Rt instanceof Error?Rt.message:String(Rt)).slice(0,120)}`),Ht.current=null,un.current.delete(Re),await Ge.reject();return}Tt(()=>An.current?.("paypal"));let xe=Qn(),$n={generation:xe,surfaceKey:Re,...bt};Ht.current=$n,un.current.set(Re,$n),Ze.current={...U,attempt:xe},await Ge.resolve(),x.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),x.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Ft.current=x.startTiming()},createOrder:ge==="order"?b("Failed to create PayPal order."):void 0,createSubscription:ge==="subscription"?b("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ge==="setup_token"?async()=>G(await D("Failed to create PayPal setup token.")):void 0,onApprove:re,onCancel:()=>{if(q())return;let $=un.current.get(Re)??Ht.current,Ge=$&&xn($.generation)?Jd($.sessionId??e,Fn):null;$&&un.current.delete($.surfaceKey),Ht.current=null,jt("cancelled"),x.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Le.current=!0,nn({generation:$?.generation,remount:!0,focus:!1}),Ge&&Tt(()=>pt.current?.(Ge))},onError:$=>{if($ instanceof Ao&&$.code===ec)return;let Ge=$ instanceof Error?$.message:"PayPal failed to render.";if(q()||Pe.current!==Re){We(Ge)||Et(mn());return}if(_n){let ct=un.current.get(Re)??Ht.current;if(!ct||!xn(ct.generation)){if(We(Ge)){!ct&&!Bn()&&tn();return}Et(ct||Bn()?"stale_attempt":"no_current_attempt");return}if(z(`onError rendered=${_n} msg=${Ge.slice(0,120)}`),We(Ge)){tn(ct.generation);return}let{errorCode:bt,popupBlocked:xe,providerDeclined:$n,terminalReason:Rt}=Oi($,{inAppBrowser:ve.inAppBrowser,handoffObserved:Y.current===ct.generation});if(xe&&O.markBlocked(),jt(Rt),$n){x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Rt}),Ie($,ct),Tt(()=>zt.current?.(fn("paypal",Ge))),un.current.delete(ct.surfaceKey),Ht.current=null,tn(ct.generation);return}x.error({errorCode:bt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Rt}),un.current.delete(ct.surfaceKey),Ht.current=null,nn({generation:ct.generation,remount:!0,showRetry:!0,focus:!0}),Kt($,{code:"paypal_runtime_failed",popupBlocked:xe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Ke,terminalReason:Rt});return}z(`onError rendered=${_n} msg=${Ge.slice(0,120)}`),ne(We(Ge)?"teardown":"pre_ready_callback",Ge)}}),cn=tt.isEligible();if(z(`isEligible=${cn}`),x.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!cn){E(!1),ne("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Dr=!0,Fr=tt,ln=()=>{if(!Yn||Ue||q()||_n)return;Ue=!0,z(`container:dims ${on(or)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(At=new MutationObserver(Ge=>{if(!q()){for(let ct of Ge)if(ct.type==="childList")ct.addedNodes.forEach(bt=>{if(!(bt instanceof Element))return;let xe=bt.tagName.toLowerCase(),$n=(bt.getAttribute("title")??"").slice(0,40),Rt=xe==="iframe"?` ${Qr(bt)}`:"";z(`child+ ${xe}${$n?` title="${$n}"`:""}${Rt} dims=${on(bt)}`)});else if(ct.type==="attributes"&&ct.target instanceof Element){let bt=ct.target;if(bt.tagName.toLowerCase()!=="iframe")continue;let xe=ct.attributeName;(xe==="src"||xe==="srcdoc")&&z(`attr~ iframe ${xe}=${xe==="srcdoc"?`[${(bt.getAttribute("srcdoc")??"").length}ch]`:jn(bt.getAttribute("src"))} dims=${on(bt)}`)}}}),At.observe(or,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let $=Ge=>{if(q()||_n)return;let ct=or.querySelectorAll("iframe"),bt=typeof document<"u"&&"hasStorageAccess"in document;z(`watchdog:${Ge} container=${on(or)} children=${or.childElementCount} iframes=${ct.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${bt} paypalNetRequests=${Nr.value}`),ct.forEach((xe,$n)=>{let Rt=(xe.getAttribute("title")??"").slice(0,40);z(` iframe[${$n}] ${on(xe)}${Rt?` title="${Rt}"`:""} ${Qr(xe)}`);let On=Or(xe);On&&z(` ${On}`)}),dr.length===0&&z(" (no PayPal/zoid window errors captured)")};Gn.push(setTimeout(()=>$("3s"),3e3)),Gn.push(setTimeout(()=>$("8s"),8e3)),Gn.push(setTimeout(()=>$("15s"),15e3))},ln(),z("render:start");let nt=x.startTiming();er=setTimeout(()=>{q()||_n||(z("watchdog:11s retryable render timeout"),ne("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},fu);let nr=tt.render(or);(async()=>{try{if(await nr,z(`render:resolved inactive=${q()}`),j(),q()){Wr();return}_n=!0,E(!0),gt(!1),Vn.current?.("ready"),x.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),x.performance({stage:"checkout_render",durationMs:x.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch($){let Ge=$ instanceof Error?$.message:"PayPal failed to render.";z(`render:rejected msg=${Ge.slice(0,120)}`),j(),ne(We(Ge)?"teardown":"render_rejected",Ge)}})()}).catch(Q=>{let re=Q instanceof Error?Q.message:"PayPal operation failed.";z(`provider:failed msg=${re.slice(0,120)}`);let b="script_rejected";v&&We(re)?b="teardown":v&&Dr&&(b="render_rejected"),ne(b,re)})},0);return()=>{X=!0,clearTimeout(Sn),br&&clearTimeout(br),j(),he.current===te&&(he.current=null),Wr(),Ft.current=null,Ze.current=null}},[Xe,kt,s,m,l,ge,Ke,be,e,ze,Ee,ie,_,de,z,jt]);let qn=ee?Ki("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Pt?"#fef2f2":"#f3f4f6",border:`1px solid ${Pt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Fe} failed=${Pt})`,Se.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return Pt&&!d?te?ao("div",{children:jn}):null:Hi("div",{children:[jn,ot&&ao(Mo,{identity:ot.identity,methodLabel:ot.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Se,onCancel:()=>Se(null)}),Hi("div",{"aria-hidden":qe||ot?!0:void 0,style:qe||ot?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ga},children:[!Oe&&!qe&&ao("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),ao("div",{ref:fe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ga,display:"flex",opacity:Oe?1:0},"aria-busy":P||b},_e)]},_e),je&&ao("button",{ref:Ue,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:ln,style:uu,children:"Try PayPal again"})]})}function Ya(e){return ao(Zl,{...e})}function Xl(e){return ao(Zl,{...e})}import{jsx as Ql,jsxs as fu}from"react/jsx-runtime";function xo({children:e,margin:t,icon:n=!0,styleOverride:o}){return fu("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...o??{}},children:[n&&Ql("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Ql("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{clearCachedInlineCheckout as Ja,clearCachedInlineSession as Ki,hashCreateParams as ec,legacyCachedSessionMatchesDraft as tc,persistCachedInlineIdempotencyKey as Za,persistCachedInlineSession as Xa,readCachedInlineIdempotencyKey as nc,readCachedInlineSession as rc,serializeCreateParams as ya}from"@flopay/shared";import{resolveBillingApiUrl as gu}from"@flopay/shared";import{useEffect as Gr,useMemo as hu,useRef as oc,useState as ac}from"react";import{jsx as Pu}from"react/jsx-runtime";function Qa({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=ac(e instanceof Promise?null:e),[l,u]=ac(t instanceof Promise||!t?null:t),C=oc(null),_=oc(null),k=Ao(o);Gr(()=>{k({class:"lifecycle",name:"checkout.mount"})},[k]),Gr(()=>{i&&k({class:"lifecycle",name:"sdk.initialize.ready"})},[k,i]),Gr(()=>{if(i)return pn(i)?.subscribe?.(k)},[k,i]),Gr(()=>{if(!(!l||l===i))return pn(l)?.subscribe?.(k)},[k,i,l]),Gr(()=>{if(!i)return;let N=pn(i);return C.current=N?.beginCheckout()??N?.now()??0,N?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{N?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Gr(()=>{let N=!1;return e instanceof Promise?e.then(Ae=>{N||s(Ae)},()=>{N||k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{N=!0}},[k,e]),Gr(()=>{let N=!1;if(!t){u(null);return}return t instanceof Promise?t.then(Ae=>{N||u(Ae)},()=>{N||k({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):u(t),()=>{N=!0}},[k,t]),Gr(()=>{if(!i||_.current===i)return;_.current=i;let N=pn(i);N?.log({name:"checkout.rendered",stage:"checkout_render"}),k({class:"lifecycle",name:"checkout.rendered"}),N?.performance({stage:"checkout_render",durationMs:N.elapsed(C.current??0),durationMode:"machine"})},[k,i]);let O=gu(n?.billingApiUrl),ue=hu(()=>({flopay:i,paypalFlopay:l,billingApiUrl:O,emitInstrument:k}),[i,l,O,k]);return Pu(ir.Provider,{value:ue,children:a})}import{markSessionRecentlyCompleted as Bo,wasSessionRecentlyCompleted as Gi}from"@flopay/shared";async function ei(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{completeSavedCardNextAction as vu,loadFloPay as ic,PaymentAPI as ni,runSavedCardChallenge as Cu}from"@flopay/js";import{classifyPaymentRejection as bu,FloPayError as Tt,isAuthorizationOnlySession as Su,isMountableVaultBlock as wu,isSetupIntentClientSecret as ku,normalizeCheckoutFailureOutcome as sc}from"@flopay/shared";var fa="card";async function Iu(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:o??null}}async function Ru(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function Fo(e){return new Tt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Eu(){return new Tt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Ji(e,t){return Object.assign(e,{checkoutMethod:t})}function Lr(e,t){let n=e instanceof Tt?e:new Tt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function ma(e,t){try{return await e()}catch(n){throw Lr(n,t)}}function cc(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function dc(e){return Cu(e)}async function Do(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new ni(n,{telemetry:!1}),l=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,u;try{u=await vu({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:_=>Ir({type:_.declineReason??"authorization_declined",gatewayErrorCode:_.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(_){if(a.aborted||_ instanceof Error&&_.name==="AbortError")throw _ instanceof Tt&&_.code==="three_ds_aborted"?_:Fo(_);if(!(_ instanceof Tt)||_.code!=="three_ds_timeout"&&_.code!=="checkout_processing_timeout")throw _;try{u=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:l,timeoutMs:5e3,signal:a})}catch(O){if(a.aborted)throw Fo(O);if(!(O instanceof Tt)||O.code!=="checkout_processing_timeout")throw O}let k=u&&Vr(u,t.session);if(!Or(k)&&k?.status!=="expired"){if(t.telemetry){let O=new ni(n);try{O.reportThreeDsAbandoned(o)}finally{O.destroy()}}throw Eu()}}let C=u&&Vr(u,t.session);if(!Or(C))throw Eo(C);return{...Dr(C,o),checkoutMethod:"card"}}function Ir(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=_o(a)??a,s=Ji(new Tt(i,"api_error",{code:e?.code??sc(e?.outcome)??sc(e?.type)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Yi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function uc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ti(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||ti(l)))return l;let s=a.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let u=l,C=[u.stripeClientSecret,u.clientSecret];for(let _ of C)if(typeof _=="string"&&_.length>0&&(!t?.requirePaymentIntentClientSecret||ti(_)))return _}}}}async function _u({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=uc(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let l=(await new ni(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ti(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Oo({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),u=t??n.id,C=o??n.clientSecret,_=n.customer?.id??n.accountData?.userId??"",k=n.customer?.email??n.accountData?.email??"",O=n.customer?.firstName??n.accountData?.firstName??"",ue=n.customer?.lastName??n.accountData?.lastName??"",N=n.customer?.country??n.accountData?.country??void 0,Ae=n.customer?.zip??n.accountData?.zip??void 0,m=await new ni(l,s===!1?{telemetry:!1}:void 0).processPayment(_,{sessionId:u,nonce:C,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:_,email:k,firstName:O,lastName:ue,country:N,zip:Ae},returnUrl:i??Yi(n)});if(m.ok){let I=typeof m.json=="function"?await m.json().catch(()=>null):null;if(Su(n)||I?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof I?.paymentId=="string"?I.paymentId:n.paymentId,sessionId:typeof I?.sessionId=="string"?I.sessionId:u,authorizationExpiresAt:typeof I?.authorizationExpiresAt=="string"?I.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:sa(a),checkoutMethod:lc(a,n)}};let Xe=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Xe?{paymentIntentId:Xe}:{},paymentMethodId:sa(a),checkoutMethod:lc(a,n)}}}let b;try{b=await m.json()}catch(I){throw new Tt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:m.status,cause:I})}if(b?.type==="3ds_required"&&typeof b.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:b.nextActionRedirectUrl};if(b?.type==="paypal_redirect_required"||b?.type==="3ds_required"){let I=uc(b);if(!I)throw new Tt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:m.status});return{type:b.type,threeDSecureToken:I,paymentMethodId:b.paymentMethodId}}if(b?.gatewayErrorCode==="authentication_required"){let I=await _u({billingApiUrl:l,sessionId:u,nonce:C,responseJson:b});if(I)return I;throw Ji(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let Ve=new Tt(b?.message??"Payment failed. Please try again.","api_error",{code:b?.code??b?.gatewayErrorCode,declineCode:b?.declineCode??b?.gatewayDeclineReason,statusCode:m.status});throw Object.assign(Ve,{telemetryOutcome:bu(m.status,b)})}async function ri(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:l,telemetry:u,signal:C}){let _=t?.getRawProvider();if(!_)throw Lr(new Tt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Ji(new Tt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let k=ku(e.threeDSecureToken),O=null,ue=e.paymentMethodId,N=await ma(()=>Iu(_,e.threeDSecureToken,k),"card");if(N){if(N.error)throw Lr(new Tt(N.error.message??`Failed to retrieve 3DS ${k?"setup":"payment"} status.`,"api_error",{code:N.error.code}),"card");let Z=N.intent;!ue&&Z?.payment_method&&(typeof Z.payment_method=="string"?ue=Z.payment_method:"id"in Z.payment_method&&(ue=Z.payment_method.id??void 0))}let Ae=ue?await ma(()=>Ru(_,e.threeDSecureToken,{payment_method:ue,return_url:l??Yi(s)??window.location.href},k),"card"):null;if(Ae){if(Ae.error)throw Lr(new Tt(Ae.error.message??"3DS authentication failed.","api_error",{code:Ae.error.code}),"card");O=Ae.intent}else{let Z=await ma(()=>_.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(Z.error)throw Lr(new Tt(Z.error.message??"3DS authentication failed.","api_error",{code:Z.error.code}),"card");O=(k?Z.setupIntent:Z.paymentIntent)??null}if(O&&(O.status==="requires_capture"||O.status==="succeeded"||O.status==="processing")){let Z=await Oo({billingApiUrl:a,sessionId:i,session:s,telemetry:u,tokenizedData:{id:O.id,type:"card",threeDSecureActionResultTokenId:O.id},returnUrl:l});return Z.type==="success"?{...Z.result,paymentIntentId:Z.result.paymentIntentId??O.id,paymentMethodId:Z.result.paymentMethodId??ue}:Z.type==="next_action_required"?Do(Z,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:C}):ri(Z,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:l,telemetry:u,signal:C})}throw Lr(new Tt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let k=(n??t)?.getRawProvider();if(!k)throw Lr(new Tt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:ue}=await ma(()=>k.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(ue)throw Lr(new Tt(ue.message??"PayPal authorization failed.","api_error",{code:ue.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:O}=await ma(()=>k.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??Yi(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(O)throw Lr(new Tt(O.message??"PayPal authorization failed.","api_error",{code:O.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Tt("Unsupported payment redirect state.","api_error")}function ga(e){if(e instanceof Tt){let o=_o(e.message);return o&&o!==e.message?Object.assign(new Tt(o,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=_o(t)??t;return new Tt(n,"api_error")}function Zi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=wu(e.data.session?.vault)||ro(e.data.session);if(!t&&!n&&!o)throw new Tt("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function lc(e,t){return e?e.isPaypal?"paypal":"card":t&&ro(t)?"card":void 0}async function Xi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:o,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,l]=await Promise.all([ic(e,{billingApiUrl:n,locale:o,telemetry:a}),i?ic(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);if(!s)throw new Tt("The payment provider did not initialize.","authentication_error");let u=null;return i?u=l:t&&(u=s),{flopay:s,paypalFlopay:u}}import{PaymentAPI as No,PciVaultCardCapture as Tu,toStripeAppearance as Mu}from"@flopay/js";import{buildCheckoutProcessMetadata as Au,buildProcessPaymentAvsAccount as xu,buildWalletSheetWindowMessage as Bu,COUNTRY_OPTIONS as Fu,classifyPaymentRejection as Du,clearStripePayPalReturn as Ou,computeVaultCardThemeColors as Nu,darkenHex as Lu,denyPaymentPermissionToNewFrames as zu,FloPayError as zr,filterStripeMethodsByCountryGate as Uu,getPostalCodeExample as qu,getPostalCodeLabel as ss,getStateFromPostalCode as ju,getStateLabel as Qi,getStateOptions as $u,getStripeMethodDisplayName as va,hasMatchingStripePayPalReturn as Wu,isAuthorizationOnlySession as es,isAVSFieldVisible as Jt,isMountableVaultBlock as Vu,isPostalCodeSupported as Hu,isSetupIntentClientSecret as ts,isValidEmail as Rn,isValidPostalCode as Ku,isWalletSheetRefusedForWindowSize as Gu,needsStripeMethodExplicitConfirm as pc,normalizeBeforeButtonClickError as yc,normalizeCheckoutFailureOutcome as Yu,partitionStripeMethods as Ju,randomUuidV4 as Zu,readMatchingStripePayPalContinuation as Xu,readStripeRedirectParams as Ic,resolveAVSConfig as Qu,resolveButtonsLayoutTheme as ep,resolveSetupFutureUsage as Rc,resolveTheme as tp,resolveVaultMountOptions as ns,STRIPE_PAYPAL_RESUME_KEY as np,derivePrimaryTileStyle as rp,shouldPreferWalletPopup as mc,stripeExpressMethodToOptionKey as op,stripeRedirectReturnUrl as Ec,toCssWeight as ap,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as _c}from"@flopay/shared";import{ExpressCheckoutElement as Tc,PaymentElement as ip,Elements as so,useElements as us,useStripe as ps}from"@stripe/react-stripe-js";import sp,{useCallback as Te,useContext as zo,useEffect as ft,useLayoutEffect as lp,useMemo as St,useRef as H,useState as ce}from"react";function io(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function oi(e,t){if(e)return{error:n=>e.error(io(t,n)),log:n=>e.log(io(t,n)),performance:n=>e.performance(io(t,n)),terminal:n=>e.terminal(io(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}import{darkenHex as Dc}from"@flopay/shared";import{Fragment as Lo,jsx as c,jsxs as Ze}from"react/jsx-runtime";var Rr="flopay_stripe_resume",fc="flopay_wallet_resume",Mc="fw1",cp="fw2",Ac=300*1e3,dp=900,up="express_checkout_click_timeout",pp=25e3,yp=25e3,mp=1e4,yr={provider:"paypal",paymentMethodCategory:"paypal"},fp="x-flopay-process-result-source",gp="status";async function hp(e,t,n){try{let o=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(o?.status==="complete")return null;if(o?.status==="authorized")return{status:"authorized",paymentId:o.paymentId,sessionId:o.id||t,authorizationExpiresAt:o.authorizationExpiresAt}}catch{}}var ai={},Pa=class{constructor(t){this.reason=t}};function Pp(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function rn(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ys(e){return`${cp}:${e}`}function ii(e){return rn(ys(e))}function si(e,t){if(typeof window>"u")return null;let n=ys(e);try{let o=localStorage.getItem(n);if(!o)return null;let a=JSON.parse(o);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>Ac||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(ii(e),null):a}catch{return ii(e),null}}function vp(e){return rn(ys(e.sessionId),e)}function gc(e,t,n){let o=si(e,t);return!o||o.clientSecret!==n?!1:ii(e)}function rs(e,t,n){if(typeof window>"u")return;si(e,t)?.clientSecret===n&&ii(e)}function Cp(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function os(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let o=n?e.status==="succeeded":ia(e.status),a=Cp(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function hc(e,t,n){let o=null;try{return await Promise.race([Nl(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},mp),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function bp(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function xc(e){return e instanceof zr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function li(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new No(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw xc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var as=np,ha=new Map,Sp=250,Pc="Just a moment \u2014 we are finalizing your order. Please press pay again.",wp="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function ms(e,t,n,o){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...o?{terminalReason:o}:{}})}async function ci({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new No(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function kp(e){return e instanceof zr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Bc({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=la(n),s=i.firstName?i:la(o?.name);return pr({email:Rn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Ip({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=Bc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return Rn(s.email)?s:i(a,s)}var Ca=180,vc=`flopay-card-enter ${Ca}ms cubic-bezier(0, 0, 0.2, 1) both`,Cc=`flopay-card-exit ${Ca}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Rp=`flopay-buttons-enter ${Ca}ms cubic-bezier(0, 0, 0.2, 1) both`,Ep=`flopay-buttons-exit ${Ca}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function _p(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function fs(e){return rp(e)}var Tp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Mp(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var ls={width:"100%",minHeight:oa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function bc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function cs(e){return e==="paypal"?"PayPal":va(e)}function Ap(e){let t=qu(e);return`Enter a valid ${ss(e)}${t?` (e.g. ${t})`:""}`}function xp(e,t,n){let o=Hu(e),a=t.trim(),i=n&&o,s=i&&!a,l=i&&!!a&&!Ku(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:l}}function Bp(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!Rn(n);return{required:t,empty:o,malformed:a,value:n}}function Fp(e){return typeof e=="number"?`${e}px`:e}function gs(e){return c(Np,{...e})}function Sc({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:u,onTechnicalFailure:C,runBeforeButtonClick:_,billingName:k,onBuyerIdentityReady:O,onLoadStateChange:ue,placeholderBorderRadius:N,popupCapabilityOwner:Ae,externalTelemetryContext:Z,presentationMode:m}){let b=Hr(),{emitInstrument:Ve}=zo(ir),I=ps(),Xe=us(),Y=St(()=>oi(pn(b),Z),[Z,b]),[Fe,nt]=ce("loading");ft(()=>{ue?.(Fe)},[Fe,ue]);let[ze,He]=ce(!1),It=H(!1),it=!Rn(n?.trim())||!k?.trim(),{request:te,collect:xt,finish:ut}=To(),rt=H(!1),ge=H(null),se=H(null),[fe,wt]=ce(0),[Bt,Qe]=ce(!1),ne=H(!1),Me=H(new Map),{startAttempt:de,finishAttempt:L,invalidateAttempt:Ue,isAttemptInvalidated:De,isAttemptCurrent:Oe,generationRef:M}=ua((pe,P,st)=>{C?.(pe,P,{...st,popupBlocked:st?.popupBlocked??$r(P),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:m,terminalReason:"overlay_timeout"}),Qe(!0),wt(ot=>ot+1)},{onHandoffObserved:()=>{Ae.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",...yr,attempt:M.current})}});ft(()=>{Bt&&se.current?.focus()},[Bt,fe]);let qe=Te(()=>{wt(pe=>pe+1)},[]),gt=Te((pe,P,st)=>{Ue(st),C?.("paypal",pe,{code:P,popupBlocked:$r(pe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:m}),Qe(!0),qe()},[Ue,C,m,qe]),_e=Te(()=>{window.setTimeout(()=>{(ge.current?.querySelector("iframe")??ge.current)?.focus()},0)},[]);ft(()=>{ne.current&&(ne.current=!1,_e())},[_e,fe]);let ht=Te(()=>{Qe(!1),i?.(null),_e()},[_e,i]);ft(()=>{if(!I||rt.current)return;let[pe,P,st]=Ic();if(!pe||!P)return;let ot=Xu(P);if(!ot)return;rt.current=!0;let R=!0,Se=ha.get(P);Se||(Se=st==="failed"?Promise.resolve(null):Promise.resolve().then(()=>I.retrievePaymentIntent(P)),ha.set(P,Se));let Ft={accountPatch:ot.accountPatch,sessionId:ot.sessionId,nonce:ot.nonce},ye=()=>{Y?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...yr,requestCategory:"provider_sdk"})};return Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...yr}),(async()=>{try{He(!0);let p=await Se;if(!R)return;if(p?.error){ha.delete(P),ye(),i?.(p.error.message??"Failed to retrieve PayPal payment status.");return}if(Ou(),ha.delete(P),st==="failed"){let we="PayPal payment was declined. Please try again.";Y?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}),i?.(we),u?.(Sn("paypal",we));return}let v=p?.paymentIntent;if(v&&v.id!==pe){ye(),i?.("Failed to match the returned PayPal payment.");return}if(v&&(v.status==="requires_capture"||v.status==="succeeded")){let we=typeof v.payment_method=="string"?v.payment_method:v.payment_method?.id;a({id:we??v.id,type:"card",threeDSecureActionResultTokenId:v.id,isPaypal:!0},{...Ft,presentationMode:"redirect"})}else{let we="PayPal payment was not completed. Please try again.";Y?.terminal({outcome:v?.status==="canceled"?"payment_cancelled":"payment_declined",...yr,terminalReason:v?.status==="canceled"?"cancelled":"provider_declined"}),i?.(we),u?.(Sn("paypal",we))}}catch(p){if(!R)return;ha.delete(P),ye(),i?.(p instanceof Error?p.message:"Failed to complete PayPal payment.")}finally{R&&He(!1)}})(),()=>{R=!1,rt.current=!1}},[I,a,i,u,Y]);let ve=Te(async(pe=!1)=>{let P=_?await _("paypal"):{proceed:!0};if(!P.proceed)return Me.current.delete(fe),!1;let st=de("paypal");return Me.current.set(fe,{generation:st,accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}),Qe(!1),Y?.log({name:`provider.${pe?"redirect.started":"handoff.requested"}`,stage:pe?"redirect":"overlay_open",...yr,attempt:st}),l?.("paypal"),!0},[l,Y,_,de,fe]),je=Te(async pe=>{if(s||ze||!await ve()){pe.reject();return}pe.resolve()},[s,ve,ze]),Ke=Te(async pe=>{if(!I||!Xe)return;let P=Me.current.get(fe);if(P&&!Oe(P.generation)){Me.current.delete(fe);return}if(!P&&De()||P&&!L(P.generation))return;P||L();let st=P??null;if(Me.current.delete(fe),!st&&_){let kt=await _("paypal");if(!kt.proceed){pe.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}st={accountPatch:kt.accountPatch,sessionId:kt.sessionId,nonce:kt.nonce}}let ot=st?.sessionId??e,R=st?.nonce??t,Se=await Ip({event:pe,prepared:st,email:n,billingName:k,methodLabel:"PayPal",collect:xt});if(!Se){pe.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ft=Se.email,ye={...st?.accountPatch,...pr(Se,!0)};try{if(He(!0),i?.(null),!ot||!Rn(Ft))throw new Error("Missing sessionId or email for PayPal payment");await O?.(Se);let kt=I.createPaymentMethod,{error:p,paymentMethod:v}=await kt({type:"paypal"});if(p){gt(p,"stripe_paypal_create_payment_method_failed",P?.generation),pe.paymentFailed({reason:"fail"});return}let we=await li(o,Ve,ot,R??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:v?.id??null,intentKind:"payment"});if(we.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ce=we.clientSecret,et={return_url:Ec()};if(v?.id&&(et.payment_method=v.id),!rn(as,{clientSecret:Ce,sessionId:ot,nonce:R,accountPatch:ye})&&m==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:ke,paymentIntent:Ie}=await I.confirmPayment({clientSecret:Ce,confirmParams:et,redirect:"if_required"});if(ke){if(rn(as),Na(ke)){let d=ke.message??"Your payment was declined.";Y?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}),i?.(d),u?.(Sn("paypal",d,{code:bo(ke),declineCode:Di(ke)})),await ci({billingApiUrl:o,sessionId:ot,nonce:R,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:bo(ke)??"provider_declined"}})}else gt(ke,"stripe_paypal_confirm_failed",P?.generation);return}rn(as);let Dt=typeof Ie?.payment_method=="string"?Ie.payment_method:Ie?.payment_method?.id;a({id:Dt??Ie?.id,type:"card",threeDSecureActionResultTokenId:Ie?.id,isPaypal:!0},{accountPatch:ye,paymentMethodCategory:"paypal",presentationMode:m,sessionId:ot,nonce:R});return}catch(kt){gt(kt,"stripe_paypal_failed",P?.generation)}finally{He(!1)}},[I,Xe,e,t,n,k,xt,O,o,Ve,a,i,u,_,gt,L,Oe,De,Y,m,fe]),wn=Te(async()=>{if(!(It.current||s||ze||!I||!Xe)){It.current=!0,He(!0);try{if(!await ve(!0))return;await Ke({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{It.current=!1,He(!1)}}},[Xe,Ke,s,ve,I,ze]),Et=m==="redirect"?c("button",{type:"button",disabled:s||ze,onClick:()=>{wn()},style:{width:"100%",minHeight:oa,border:"1px solid #d1d5db",borderRadius:N??8,background:"#ffc439",color:"#111827",cursor:s||ze?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):c(Tc,{onReady:pe=>nt(Oi(pe,["paypal"])),onLoadError:()=>{nt("load_error"),ms(Y,"paypal","paypal","provider_error")},onClick:je,onConfirm:Ke,onCancel:()=>{let pe=Me.current.get(fe);Me.current.delete(fe),Y?.terminal({outcome:"payment_cancelled",...yr,terminalReason:"cancelled",...pe?{attempt:pe.generation}:{}}),Ue(pe?.generation),Qe(!1),ne.current=!0,qe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:it,emailRequired:it,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},fe),Pt=Ze(Lo,{children:[Ze("div",{ref:ge,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Bt&&c("button",{ref:se,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ht,style:ls,children:"Try PayPal again"}),te&&c(Mo,{identity:te.identity,methodLabel:te.methodLabel,onComplete:ut,onCancel:()=>ut(null)},te.id),c("div",{style:{display:te?"none":void 0},children:Et})]}),ze&&!te&&c(wr,{status:"processing"})]});return m==="redirect"?Pt:c(Ni,{state:Fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:N,children:Pt})}function is(e){return e==="apple_pay"||e==="google_pay"}var Dp=200;function Op({active:e}){return lp(()=>e?zu(document):void 0,[e]),null}function wc({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:u,onDecline:C,onTechnicalFailure:_,runBeforeButtonClick:k,billingName:O,onBuyerIdentityReady:ue,onLoadStateChange:N,placeholderBorderRadius:Ae,popupCapabilityOwner:Z,externalTelemetryContext:m}){let b=Hr(),{emitInstrument:Ve}=zo(ir),I=ps(),Xe=us(),Y=St(()=>oi(pn(b),m),[m,b]),[Fe,nt]=ce("loading");ft(()=>{N?.(Fe)},[Fe,N]);let[ze,He]=ce(!1);ft(()=>{Qe.current=ze},[ze]);let It=H(!Rn(n?.trim())||!O?.trim()).current,{request:it,collect:te,finish:xt}=To(),ut=H(null),rt=H(null),[ge,se]=ce(0),[fe,wt]=ce(()=>mc()),Bt=H(fe),Qe=H(!1),[ne,Me]=ce(!1),[de,L]=ce(()=>si(e,t)?"blocked":"idle"),[Ue,De]=ce("google_pay"),Oe=H(null),M=H(!0),qe=H(!1),gt=H("google_pay"),_e=H("google_pay"),ht=H(null),ve=H(null),je=H(new Set),Ke=H(null),wn=H(null);ft(()=>(M.current=!0,()=>{M.current=!1;for(let d of je.current)window.clearTimeout(d);je.current.clear()}),[]);let Et=H(new Map),{startAttempt:Pt,finishAttempt:pe,invalidateAttempt:P,isAttemptInvalidated:st,isAttemptCurrent:ot,generationRef:R}=ua((d,xe,he)=>{_?.(d,xe,{...he,popupBlocked:he?.popupBlocked??$r(xe),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),De(d),Me(!0),se(Re=>Re+1)},{onHandoffObserved:d=>{wn.current=R.current,Z.markAvailable(),Y?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:R.current,...d==="apple_pay"||d==="google_pay"?{walletType:d}:{}})},defersMissingTerminal:is,onMissingTerminalDeferred:(d,xe)=>{let he=Y?.now()??globalThis.performance?.now()??Date.now(),Re=Ke.current,Q=Re?.generation===xe?Re.startedAt:he;Y?.performance({stage:"overlay_return",durationMs:Math.max(0,he-Q),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:xe,...is(d)?{walletType:d}:{}}),Y?.flush?.().catch(()=>{})}});ft(()=>{ne&&rt.current?.focus()},[ne,ge]);let Se=H(0),Ft=H(!1),ye=Te(()=>{if(Se.current>0){Ft.current=!0;return}se(d=>d+1)},[]),kt=Te(()=>{Se.current-=1,!(Se.current>0||!Ft.current)&&(Ft.current=!1,M.current&&se(d=>d+1))},[]),p=Te((d,xe,he,Re,Q=!1)=>{P(Re),_?.(d,xe,{code:he,popupBlocked:$r(xe),telemetryReported:Q,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),De(d),Me(!0),ye()},[P,_,ye]),v=Te(d=>{Y?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...is(d)?{walletType:d}:{}}),_?.(d,new Error("The wallet click was not ready within the time the wallet allows."),{code:up,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),De(d),Me(!0)},[_,Y]),we=Te(()=>{window.setTimeout(()=>{(ut.current?.querySelector("iframe")??ut.current)?.focus()},0)},[]);ft(()=>{qe.current&&(qe.current=!1,we())},[we,ge]);let Ce=Te(()=>{Me(!1),l?.(null),we()},[we,l]),et=Te(()=>{Oe.current?.()},[]);ft(()=>{let d=null,xe=()=>{d=null;let Re=mc();Re!==Bt.current&&(Bt.current=Re,wt(Re),!Qe.current&&!ot(R.current)&&ye())},he=()=>{d!==null&&window.clearTimeout(d),d=window.setTimeout(xe,Dp)};return window.addEventListener("resize",he),()=>{window.removeEventListener("resize",he),d!==null&&window.clearTimeout(d)}},[R,ot,ye]),ft(()=>{let d=si(e,t);if(!d)return;let xe=!1,he=!1,Re=async()=>{if(!he){he=!0,xe||L("checking");try{let Q=await hc(I,d.clientSecret,je.current);if(xe)return;let j=os(Q,d.providerObjectId,ts(d.clientSecret));if(j.kind==="confirmed"){if(!gc(e,t,d.clientSecret))return;Oe.current=null,L("idle"),s({id:j.paymentMethodId,type:"card",threeDSecureActionResultTokenId:j.intentId},{...d.accountPatch?{accountPatch:d.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(j.kind==="terminal"){rs(e,t,d.clientSecret),Oe.current=null,L("idle"),De(d.paymentMethodType),Me(!0),ye();return}L("blocked")}catch{xe||L("blocked")}finally{he=!1}}};return Oe.current=Re,L("blocked"),()=>{xe=!0,Oe.current===Re&&(Oe.current=null)}},[t,s,ye,e,I]);let Ge=Te(async d=>{let xe=!1,he=!1,Re=Be=>{xe||he||(xe=!0,d.paymentFailed({reason:"fail",...Be?{message:Be}:{}}))};if(!I||!Xe){Re();return}let Q=Et.current.get(ge);if(Q&&!ot(Q.generation)){Et.current.delete(ge),Re();return}if(!Q&&st()){Re();return}if(Q&&!pe(Q.generation)){Re();return}Q||(pe(),Ft.current=!1);let j=d.expressPaymentType??Q?.method??gt.current,mn=Q??null,Yn=bc(j),on;j==="apple_pay"?on="apple_pay":j==="google_pay"&&(on="google_pay");let Wt=Q?.generation??R.current,pt=Y,Fn=pt?.now()??globalThis.performance?.now()??Date.now(),En=new AbortController,Xt=!1,Un=!1,yt=null,fr=e,Vt="processing",tr="other",Dn="provider_runtime",On,an=new Promise((Be,lt)=>{On=lt}),fn=window.setTimeout(()=>{Xt=!0,En.abort(),On(ai)},pp),qn=async(Be,lt,kn)=>{Vt=Be,tr=lt,Dn=lt==="intent_create"||lt==="session_claim"?"transport_error":"provider_runtime";let Ut=pt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([kn,an])}finally{let sn=pt?.now()??globalThis.performance?.now()??Date.now();pt?.performance({stage:Be,durationMs:Math.max(0,sn-Ut),durationMode:"machine",requestCategory:lt,paymentMethodCategory:"wallet",provider:"stripe",...Xt?{statusClass:"timeout"}:{}})}};try{if(He(!0),l?.(null),!mn&&k){let ee=await qn("processing","other",k(Yn));if(!ee.proceed){Re();return}mn={accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}}let Be=mn?.sessionId??e;fr=Be;let lt=mn?.nonce??t,kn=ht.current??mn?.accountPatch,Ut=Bc({event:d,fallbackEmail:kn?.email??n,fallbackName:[kn?.firstName,kn?.lastName].join(" ").trim()||O});if(!Rn(Ut.email)){Re("Buyer details are required."),te(cs(j),Ut).then(ee=>{ee&&(ht.current=ee)});return}ht.current=null;let sn={...mn?.accountPatch,...pr(Ut,!0)};await qn("processing","session_claim",Promise.resolve(ue?.(Ut)));let{error:ln}=await qn("tokenization","provider_sdk",Xe.submit());if(ln){Re(),p(j,ln,"stripe_wallet_submit_failed",Q?.generation);return}if(!Be)throw new Error("Missing sessionId or email for payment.");let Ht={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j,paymentMethodId:null,intentKind:a},Kt=JSON.stringify({sessionId:Be,nonce:lt??"",request:Ht}),gn=ve.current,Ee=gn?.retryIdentity===Kt?gn.authorizationAttemptId:Zu();ve.current={authorizationAttemptId:Ee,retryIdentity:Kt};let hn=await qn("processing","intent_create",li(o,Ve,Be,lt??"",{...Ht,authorizationAttemptId:Ee},{signal:En.signal}));if(hn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Pn=hn.clientSecret,_r=vp({createdAt:Date.now(),sessionId:Be,...lt?{nonce:lt}:{},clientSecret:Pn,providerObjectId:hn.providerObjectId,paymentMethodType:j,accountPatch:sn});window.clearTimeout(fn),Un=!0,pt?.performance({stage:"callback",durationMs:Math.max(0,(pt?.now()??globalThis.performance?.now()??Date.now())-Fn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let _n=pt?.now()??globalThis.performance?.now()??Date.now(),Tn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...on?{walletType:on}:{},attempt:Wt},gr=!1,Jn=null;pt?.log({name:"payment.provider_confirmation.started",...Tn}),yt=window.setTimeout(()=>{yt!==null&&je.current.delete(yt),gr=!0;let ee=pt?.now()??globalThis.performance?.now()??Date.now();pt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Tn,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ee-_n),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),pt?.flush?.().catch(()=>{}),Jn?.()},yp),je.current.add(yt);let Qt=(ee,Nt)=>{yt!==null&&(window.clearTimeout(yt),je.current.delete(yt),yt=null);let U=pt?.now()??globalThis.performance?.now()??Date.now(),_t=Math.max(0,U-_n),dn=ee;gr&&(ee==="resolved"?dn="resolved_late":ee==="returned_error"?dn="returned_error_late":dn="rejected_late");let Mn=Nt??(ee==="resolved"?"approved":"provider_error");return pt?.log({name:"payment.provider_confirmation.returned",...Tn,operationOutcome:dn,terminalReason:Mn}),pt?.performance({...Tn,durationMs:_t,durationMode:"buyer",operationOutcome:dn,terminalReason:Mn}),{durationMs:_t,operationOutcome:dn,terminalReason:Mn}},X=!1,cn=!1,jn=ee=>{if(!ee||typeof ee!="object")return null;let Nt=ee;if(Nt.error)return null;let U=Nt.setupIntent??Nt.paymentIntent,_t=os(U??null,void 0,!!Nt.setupIntent);return _t.kind==="confirmed"?_t:null},$=ee=>{if(X||Q&&R.current!==Q.generation)return;let Nt=jn(ee);if(!Nt)return;if(_r&&!gc(Be,lt,Pn)){X=!0;return}let{intentId:U,paymentMethodId:_t}=Nt;X=!0,cn=!0,ve.current=null,Oe.current=null,M.current&&(L("idle"),He(!1));let dn=`${Mc}:${Be}`;rn(dn,{createdAt:Date.now(),sessionId:Be,nonce:lt,accountPatch:sn,paymentMethodId:_t,providerIntentId:U,paymentMethodType:j});try{s({id:_t,type:"card",threeDSecureActionResultTokenId:U},{accountPatch:sn,paymentMethodCategory:"wallet",sessionId:Be,nonce:lt})}finally{rn(dn)}},vt=!1;Jn=async()=>{if(!(vt||X||cn)){vt=!0,M.current&&L("checking");try{let ee=await hc(I,Pn,je.current);if(X||cn)return;let Nt=ts(Pn),U=os(ee,hn.providerObjectId,Nt);if(U.kind==="confirmed"){$(Nt?{setupIntent:ee}:{paymentIntent:ee});return}if(U.kind==="terminal"){if(cn=!0,rs(Be,lt,Pn),ve.current=null,Oe.current=null,!M.current)return;L("idle"),Re(),p(j,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Q?.generation,!0);return}M.current&&!cn&&(L("blocked"),He(!1))}catch{M.current&&!cn&&(L("blocked"),He(!1))}finally{vt=!1}}},Oe.current=Jn;let B,qt;try{he=!0,Se.current+=1;let ee;try{ee=await(ts(Pn)?I.confirmSetup({elements:Xe,clientSecret:Pn,redirect:"if_required"}):I.confirmPayment({elements:Xe,clientSecret:Pn,redirect:"if_required"}))}finally{kt()}if(!ee||typeof ee!="object")throw new Pa(Pp(ee));if(B=ee,!B.error&&!jn(B))throw new Pa("confirmation_result_unconfirmed");qt=Qt(B.error?"returned_error":"resolved",B.error&&Na(B.error)?"provider_declined":void 0)}catch(ee){let Nt=ee instanceof Pa?ee.reason:void 0,U=Nt!==void 0,_t=Qt(U?"returned_error":"rejected");if(pt?.error({...U?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Nt}:ji(ee),...Tn,operationOutcome:_t.operationOutcome,durationMs:_t.durationMs,statusClass:"unknown",terminalReason:_t.terminalReason}),!M.current||X)return;await Jn?.();return}let en=B.error;if(en){if(!M.current||X)return;if(Na(en)){cn=!0,rs(Be,lt,Pn),ve.current=null,Oe.current=null,L("idle"),Et.current.get(ge)===Q&&Et.current.delete(ge);let ee=en.message??"Your payment was declined.";l?.(ee),C?.(Sn(Yn,ee,{code:bo(en),declineCode:Di(en)})),ci({billingApiUrl:o,sessionId:Be,nonce:lt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j,providerDeclineReason:bo(en)??"provider_declined",...hn.intentKind==="payment"&&hn.providerObjectId.startsWith("pi_")?{providerIntentId:hn.providerObjectId}:{}}})}else pt?.error({...ji(en),...Tn,operationOutcome:qt.operationOutcome,durationMs:qt.durationMs,statusClass:"unknown",terminalReason:qt.terminalReason}),await Jn?.();return}if($(B),!X)throw new Error("Invalid provider returned for APM intent")}catch(Be){if(Be===ai){let lt=pt?.now()??globalThis.performance?.now()??Date.now();pt?.error({errorCode:bp(tr),stage:Vt,requestCategory:tr,paymentMethodCategory:"wallet",provider:"stripe",...on?{walletType:on}:{},operationOutcome:"watchdog_expired",checkoutSessionId:fr,durationMs:Math.max(0,lt-Fn),statusClass:"timeout",failureCategory:Dn,attempt:Wt,terminalReason:"provider_error"}),pt?.flush?.().catch(()=>{})}Re(),p(j,Be,Be===ai?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Q?.generation,Be===ai)}finally{if(window.clearTimeout(fn),yt!==null&&(window.clearTimeout(yt),je.current.delete(yt)),!Un){let Be=pt?.now()??globalThis.performance?.now()??Date.now();pt?.performance({stage:"callback",durationMs:Math.max(0,Be-Fn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Xt?{statusClass:"timeout"}:{}})}M.current&&He(!1)}},[I,Xe,e,t,n,O,te,ue,o,Ve,a,s,l,C,k,p,kt,pe,ot,st,R,Y,ge]),ke=St(()=>Sl(i),[i]),Ie=St(()=>i.map(op),[i]),Dt=St(()=>c(Tc,{onReady:d=>{nt(Oi(d,Ie))},onLoadError:d=>{nt("load_error"),ms(Y,"stripe","wallet","provider_error")},onClick:async d=>{let xe=Y?.now()??globalThis.performance?.now()??Date.now();gt.current=d.expressPaymentType,_e.current=bc(d.expressPaymentType);let he=!0,Re=window.setTimeout(()=>{he=!1,d.reject(),v(d.expressPaymentType)},dp),Q=k?await k(_e.current,{abandoned:()=>!he}):{proceed:!0};if(window.clearTimeout(Re),!he)return;if(!Q.proceed){Et.current.delete(ge),d.reject();return}let j=Pt(d.expressPaymentType);Ft.current=!1,Ke.current={generation:j,startedAt:xe},Et.current.set(ge,{generation:j,method:d.expressPaymentType,accountPatch:Q.accountPatch,sessionId:Q.sessionId,nonce:Q.nonce}),Me(!1),Y?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:j,...d.expressPaymentType==="apple_pay"||d.expressPaymentType==="google_pay"?{walletType:d.expressPaymentType}:{}}),u?.(_e.current),d.resolve()},onConfirm:Ge,onCancel:()=>{let d=Et.current.get(ge);Et.current.delete(ge);let xe=Ke.current,he=Y?.now()??globalThis.performance?.now()??Date.now();if(d&&xe?.generation===d.generation&&Gu({method:d.method,elapsedMs:he-xe.startedAt,handoffObserved:wn.current===d.generation})){Y?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:d.generation,walletType:"google_pay"}),ve.current=null,p(d.method,new Error("The browser window is too small for the Google Pay sheet."),_c,d.generation,!0);return}Y?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...d?{attempt:d.generation}:{}}),P(d?.generation),ve.current=null,Me(!1),qe.current=!0,ye()},options:{...wl,paymentMethods:ke,emailRequired:It,billingAddressRequired:It}},ge),[Ie,ke,Ge,P,u,It,p,v,ye,k,Pt,ge,Y]);return Ze(Lo,{children:[c(Ni,{state:Fe,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Ae,children:Ze("div",{ref:ut,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ne&&Ze("button",{ref:rt,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ce,style:ls,children:["Try ",cs(Ue)," again"]}),de!=="idle"&&Ze("div",{role:"status","aria-live":"polite",children:[c("p",{children:"We are still confirming your payment. Check its status before trying again."}),c("button",{type:"button",onClick:et,disabled:de==="checking",style:ls,children:de==="checking"?"Checking payment status\u2026":"Check payment status"})]}),it&&c(Mo,{identity:it.identity,methodLabel:it.methodLabel,onComplete:xt,onCancel:()=>xt(null)},it.id),Ze("div",{style:{display:it||de!=="idle"?"none":void 0},children:[c(Op,{active:fe}),Dt]})]})}),ze&&c(wr,{status:"processing"})]})}function Fc(e,t,n){let o=Rc(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function ds({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:u,onDecline:C,onCancel:_,runBeforeButtonClick:k,onButtonClick:O,isProcessing:ue,submitButtonColor:N,submitButtonBorderRadius:Ae,submitButtonStyle:Z,errorText:m}){let b=Hr(),{emitInstrument:Ve}=zo(ir),I=ps(),Xe=us(),[Y,Fe]=ce(!1),nt=H(!1),[ze,He]=ce(!1),[It,it]=ce("loading"),[te,xt]=ce(""),ut=!Rn(o?.trim()),rt=!ut||Rn(te.trim()),ge=Te(async()=>{if(!I||!Xe||ue||nt.current||!ze)return;nt.current=!0,Fe(!0);let se=k?await k("card"):{proceed:!0};if(!se.proceed){nt.current=!1,Fe(!1);return}O?.("card");let fe=se.sessionId??t,wt=se.nonce??n,Bt=la(a?.trim()),Qe=pr({email:se.accountPatch?.email?.trim()||o?.trim()||te.trim(),firstName:se.accountPatch?.firstName?.trim()||Bt.firstName,lastName:se.accountPatch?.lastName?.trim()||Bt.lastName}),ne=Qe.email,Me=pr({...se.accountPatch,...Qe});try{if(u?.(null),!Rn(ne))throw new Error("A valid email address is required for payment.");await i?.(Qe);let de=await Xe.submit();if(de.error){u?.(de.error.message??"Payment failed.");return}let L=[Qe.firstName,Qe.lastName].filter(Boolean).join(" "),Ue=await I.createPaymentMethod({elements:Xe,params:{billing_details:{email:ne,...L?{name:L}:{}}}});if(Ue.error||!Ue.paymentMethod){u?.(Ue.error?.message??"Failed to create payment method.");return}let De=Ue.paymentMethod;if(!fe||!ne)throw new Error("Missing sessionId or email for payment.");let Oe=De.type||e,M=await li(s,Ve,fe,wt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Oe,paymentMethodId:null,intentKind:"payment"});if(M.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let qe=M.clientSecret;rn(Rr,{clientSecret:qe,sessionId:fe,nonce:wt,accountPatch:Me,paymentMethodId:De.id,paymentMethodType:De.type??e,gateway:"stripe"});let{error:gt,paymentIntent:_e}=await I.confirmPayment({clientSecret:qe,confirmParams:{return_url:window.location.href,payment_method:De.id},redirect:"if_required"});if(gt){rn(Rr);let je=gt.message??"Payment failed.";u?.(je),C?.(Sn("card",je,{code:gt.code})),await ci({billingApiUrl:s,sessionId:fe,nonce:wt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:gt.code??"provider_declined"}});return}let ht=_e?.status;if(!ia(ht)){rn(Rr);let je=ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";u?.(je),C?.(Sn("card",je,{code:ht??"missing_payment_intent"}));return}rn(Rr);let ve=typeof _e?.payment_method=="string"?_e.payment_method:_e?.payment_method?.id;l({id:ve??De.id,type:"card",threeDSecureActionResultTokenId:_e?.id,gateway:"stripe",paymentMethodType:De.type??e},{accountPatch:Me,paymentMethodCategory:"apm",sessionId:fe,nonce:wt})}catch(de){u?.(de instanceof Error?de.message:"Payment failed. Please try again.")}finally{nt.current=!1,Fe(!1)}},[I,Xe,ue,ze,k,O,t,n,o,a,te,i,s,Ve,e,l,u,C]);return Ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ut&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ut&&Ze("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:te,onChange:se=>xt(se.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(ip,{onReady:()=>it("ready"),onLoadError:()=>{it("load_error"),ms(pn(b),"stripe","apm")},onChange:se=>{He(!!se.complete)},options:{layout:kl,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...Rn(o?.trim())?{email:o?.trim()}:{}}}}}),c(Il,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ge()},disabled:!ze||!rt||Y||ue||It!=="ready",color:N,borderRadius:Ae,style:Z,children:Y?"Processing\u2026":`Pay with ${va(e)}`}),m&&c(xo,{margin:"0.75rem 0 0",children:m})]})}function kc({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:u,futureUseSession:C,onTokenizedBody:_,onErrorChange:k,onButtonClick:O,onDecline:ue,runBeforeButtonClick:N,onLoadStateChange:Ae,isProcessing:Z=!1,submitButtonColor:m="#4A49FF",submitButtonBorderRadius:b=8,submitButtonStyle:Ve,buttonAppearance:I,themeId:Xe,onExpandApm:Y,expandedApmMethod:Fe}){let{emitInstrument:nt}=zo(ir),[ze,He]=ce(null),[It,it]=ce(null),te=H(!1),{request:xt,collect:ut,finish:rt}=To();ft(()=>{s.length>0&&l?Ae?.("ready"):l||Ae?.("loading")},[s.length,l,Ae]);let ge=Te(async ne=>{if(!l||te.current||Z)return;te.current=!0,it(ne);let Me=N?await N("card"):{proceed:!0};if(!Me.proceed){te.current=!1,it(null);return}O?.("card");let de=Me.sessionId??e,L=Me.nonce??t,Ue=la([Me.accountPatch?.firstName,Me.accountPatch?.lastName].filter(Boolean).join(" ")||o),De=pr({email:Me.accountPatch?.email?.trim()||n?.trim(),firstName:Me.accountPatch?.firstName?.trim()||Ue.firstName,lastName:Me.accountPatch?.lastName?.trim()||Ue.lastName});if(!Rn(De.email)){it(null);let qe=await ut(va(ne),De);if(!qe){te.current=!1;return}De=qe,it(ne)}let Oe=De.email,M=pr({...Me.accountPatch,...De});try{if(k?.(null),!de||!Rn(Oe))throw new Error("Missing sessionId or email for payment.");await a?.(De);let qe=await li(i,nt,de,L??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let gt=qe.clientSecret;rn(Rr,{clientSecret:gt,sessionId:de,nonce:L,accountPatch:M,paymentMethodType:ne,gateway:"stripe"});let{error:_e,paymentIntent:ht}=await l.confirmPayment({clientSecret:gt,confirmParams:{return_url:window.location.href,payment_method_data:{type:ne,billing_details:{name:[De.firstName,De.lastName].filter(Boolean).join(" "),...Oe?{email:Oe}:{}}}},redirect:"if_required"});if(_e){rn(Rr);let Ke=_e.message??"Payment failed.";k?.(Ke),ue?.(Sn("card",Ke,{code:_e.code})),await ci({billingApiUrl:i,sessionId:de,nonce:L,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ne,providerDeclineReason:_e.code??"provider_declined"}});return}let ve=ht?.status;if(!ia(ve)){rn(Rr);let Ke=ve==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";k?.(Ke),ue?.(Sn("card",Ke,{code:ve??"missing_payment_intent"}));return}rn(Rr);let je=typeof ht?.payment_method=="string"?ht.payment_method:ht?.payment_method?.id;_({id:je??ht?.id,type:"card",threeDSecureActionResultTokenId:ht?.id,gateway:"stripe",paymentMethodType:ne},{accountPatch:M,paymentMethodCategory:"apm",sessionId:de,nonce:L})}catch(qe){k?.(qe instanceof Error?qe.message:"Payment failed. Please try again.")}finally{te.current=!1,it(null)}},[l,Z,N,O,e,t,n,ut,i,nt,o,a,_,k,ue]),[se,fe]=ce(null),wt=Y?Fe??null:se,Bt=Te(ne=>{te.current||Z||wt&&wt!==ne||(pc(ne)?Y?Y(ne):fe(ne):ge(ne))},[wt,Z,ge,Y]),Qe=St(()=>se?Fc(u,se,C):null,[se,u,C]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:xt?c(Mo,{identity:xt.identity,methodLabel:xt.methodLabel,onComplete:rt,onCancel:()=>rt(null)},xt.id):s.map(ne=>{let Me=Fe===ne,de=It===ne,L=It!==null&&It!==ne||Fe!=null&&Fe!==ne;return Ze(sp.Fragment,{children:[c(bl,{method:ne,themeId:Xe,submitting:de,disabled:L,highlighted:Me,hasNextStep:pc(ne),onClick:()=>Bt(ne),backgroundColor:I?.backgroundColor,borderColor:I?.borderColor,textColor:I?.textColor,borderRadius:I?.borderRadius,fontFamily:I?.fontFamily}),!Y&&se===ne&&Qe&&l&&c(so,{stripe:l,options:Qe,children:c(ds,{method:ne,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:_,onErrorChange:k,onDecline:ue,onCancel:()=>fe(null),runBeforeButtonClick:N,onButtonClick:O,isProcessing:Z,submitButtonColor:m,submitButtonBorderRadius:b,submitButtonStyle:Ve})},ne)]},ne)})})}function Np({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:l,onDecline:u,onCancel:C,onTokenizedBody:_,firstName:k,lastName:O,chv:ue,className:N,submitLabel:Ae,isProcessing:Z,error:m,onErrorChange:b,showPayPal:Ve=!0,showStripe:I=!0,walletPresentation:Xe="auto",enabledPaymentMethods:Y,enabledPaymentMethodCountries:Fe,showApplePay:nt=!0,showGooglePay:ze=!0,layout:He="default",theme:It,buttonsTheme:it,buttonsStyles:te,appearance:xt,cardButtonContent:ut,cardBackButtonContent:rt,cardTitleContent:ge,showSecurityFooter:se,onButtonClick:fe,onBeforeButtonClick:wt,onBuyerIdentityReady:Bt,enableAVS:Qe,cardFieldOrder:ne,cardPreFormSlot:Me,avsLayout:de="row",country:L,zip:Ue,addressLine1:De,addressLine2:Oe,city:M,state:qe,onCountryChange:gt,onZipChange:_e,avsCheck:ht,checkoutType:ve,checkoutLayout:je,totalAmount:Ke=0,currency:wn="usd",initialCardOpen:Et=!1,directPaypal:Pt,isSubscription:pe=!1,session:P,dataAttachmentPending:st=!1,dataAttachmentRequiresIdentity:ot=!1,debug:R=!1}){let Se=Hr(),Ft=$i(),ye=zo(ur),{emitInstrument:kt}=zo(ir),p=H(null);p.current||(p.current=Wa());let v=p.current,[,we]=ce(0),Ce=H(null);Ce.current||(Ce.current=ra());let et=Ce.current,Ge=St(()=>({browser:et,capability:v,presentationMode:"popup"}),[et,v]),ke=P??ye.session,Ie=St(()=>({futureUse:ke?.futureUse,futureUseUnsupported:ke?.futureUseUnsupported}),[ke?.futureUse,ke?.futureUseUnsupported]),Dt=ke?.gateways?.paypal?.providerObjectType??Pt?.providerObjectType,d=st||ye.claimPending===!0,xe=ot||ye.claimRequiresIdentity===!0,he=d&&!xe,Re=Vl(),Q=n||Re,[j,mn]=ce(!1),[Yn,on]=ce(null),[Wt,pt]=ce(L??""),[Fn,En]=ce(Ue??""),[Xt,Un]=ce(De??""),[yt,fr]=ce(Oe??""),[Vt,tr]=ce(M??""),[Dn,On]=ce(qe??""),[an,fn]=ce(""),[qn,Be]=ce({}),lt=H(Ue??""),kn=H(L??""),Ut=H(De??""),sn=H(Oe??""),ln=H(M??""),Ht=H(qe??""),Kt=H(""),gn=H({});ft(()=>{let r=(y,T,ae,x,ie)=>{if(gn.current[y])return;let At=T?.trim();!At||At===ae.current||(ae.current=At,x(At),ie?.(At))};r("country",L,kn,pt,gt),r("zip",Ue,lt,En,_e),r("addressLine1",De,Ut,Un),r("addressLine2",Oe,sn,fr),r("city",M,ln,tr),r("state",qe,Ht,On)},[L,Ue,De,Oe,M,qe,gt,_e]);let Ee=St(()=>Qu(Qe),[Qe]),hn=Ee!==null,Pn=St(()=>es(P),[P]),_r=Vu(P?.vault),_n=!!P?.gateways?.pcivault,Tn=zl(P),Jn=!!(P?.gateways?.stripe?.enabledPaymentMethods??Y)?.includes("card")||ro(P),Qt=_r||Jn||_n,X=!!(I&&Qt&&e),[cn,jn]=ce(()=>He!=="buttons"||Et?e??null:null),[$,vt]=ce(0),B=He!=="buttons"||Et||!!e&&cn===e,qt=P?.captureMethod,en=H(Se);ft(()=>{en.current=Se},[Se]);let[ee,Nt]=ce(null);ft(()=>{if(!X||!e||!B){Nt(null);return}let r=en.current?en.current.cardCapture({sessionId:e,captureMethod:qt}):new Tu({sessionId:e,captureMethod:qt,billingApiUrl:Q,telemetry:o});return Nt({sessionId:e,captureMethod:qt,billingApiUrl:Q,telemetry:o,capture:r}),()=>{r.unmount()}},[X,e,B,qt,Q,o]);let U=X&&e&&B&&ee?.sessionId===e&&ee.captureMethod===qt&&ee.billingApiUrl===Q&&ee.telemetry===o?ee.capture:null,_t=St(()=>{let r=Wt,y=Ee?Jt(Ee.postal_code,r):!1;return xp(r,Fn,y)},[Ee,Wt,Fn]),{avsInvalid:dn,invalidAvsFields:Mn}=St(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!X||!Ee)return{avsInvalid:!1,invalidAvsFields:r};let y=Wt,T=(ie,At)=>Jt(ie,y)&&!At.trim(),ae={line1:T(Ee.address_line_1,Xt),city:T(Ee.city,Vt),state:T(Ee.state,Dn),zip:_t.empty||_t.malformed};return{avsInvalid:ae.line1||ae.city||ae.state||ae.zip,invalidAvsFields:ae}},[X,Ee,Wt,Xt,Vt,Dn,_t]),[Gt,hr]=ce(!1),[Tr,Pr]=ce(!1),[vr,Mr]=ce(!1),[qr,jr]=ce({line1:!1,city:!1,state:!1}),In=H(!1),Ar=H({email:!1,line1:!1,city:!1,state:!1,zip:!1}),nr=H(!1),Mt=Te(r=>{Ar.current[r]=!0,nr.current=!0},[]),$n=Te(r=>!In.current&&Ar.current[r],[]),Wn=Te(r=>{$n(r)&&jr(y=>y[r]?y:{...y,[r]:!0})},[$n]),[Zn,Vn]=ce(()=>ns(P?.vault,{billingApiUrl:Q,sessionId:e,nonce:t})),[Ne,un]=ce(Et&&Qt?"card":"buttons"),[tn,Hn]=ce(null),Zr=Ne==="expanding"||Ne==="card",xr=P?.gateways?.stripe&&!Tn?"stripe":void 0,lr=Te(()=>{kt?.({class:"card_surface",provider:xr})},[xr,kt]),Xn=H(null),vn=Te(r=>{Xn.current&&clearTimeout(Xn.current),Xn.current=setTimeout(()=>{Xn.current=null,r()},Ca)},[]);ft(()=>()=>{Xn.current&&clearTimeout(Xn.current)},[]);let Br=H(!1),[An,S]=ce(0),w=H(null),q=Te(()=>{lr(),jn(e??null),Br.current&&(Br.current=!1,S(r=>r+1)),vt(r=>r+1),un("expanding"),vn(()=>un("card"))},[vn,lr,e]),re=Te(()=>{un("collapsing"),vn(()=>un("buttons"))},[vn]),$e=Te(r=>{Hn(r),un("apm-expanding"),vn(()=>un("apm-form"))},[vn]),jt=Te(()=>{un("apm-collapsing"),vn(()=>{un("buttons"),Hn(null)})},[vn]);ft(()=>{He==="buttons"&&Et&&Qt&&(jn(e??null),un("card"))},[He,Et,Qt,e]);let[oe,K]=ce(null),A=H(!1),E=H(null),W=H("idle"),[be,V]=ce(!1),We=H(be);We.current=be;let[Rt,f]=ce(()=>Pt?.existingOrderId?{orderId:Pt.existingOrderId,attempts:1}:null),g=H(Rt);ft(()=>{g.current=Rt},[Rt]);let h=H(null),F=St(()=>{if(Bt||ye.claimBuyerIdentity||P?.buyerIdentified!==!1||!e||!t)return;let r=`${Q}|${e}|${t}`;h.current?.key!==r&&(h.current={key:r,claim:Ro(new No(Q,{telemetry:!1}),e,t,{...i?{userId:i}:{},...k?{firstName:k}:{},...O?{lastName:O}:{}})});let y=h.current.claim;return async T=>{await y(T)}},[Bt,ye.claimBuyerIdentity,P?.buyerIdentified,e,t,Q,i,k,O]),J=Bt??ye.claimBuyerIdentity??F,le=m??Yn,Ye=St(()=>tp(It),[It]),D=St(()=>{let r=Ye?.buttonsLayout??ep(it);return te?{...r,...te,cardButton:{...r.cardButton,...te.cardButton},cardFormContainer:{...r.cardFormContainer,...te.cardFormContainer},backButton:{...r.backButton,...te.backButton},backButtonIcon:{...r.backButtonIcon,...te.backButtonIcon},submitButton:{...r.submitButton,...te.submitButton},title:{...r.title,...te.title}}:r},[Ye,it,te]),mt=xt??Ye?.appearance,Nn=St(()=>Nu({appearance:mt,buttonsStyles:D,layout:He}),[mt,D,He]),Cn=ye.inlineSessionPatchProcessing??!1,G=(Z??j)||Cn,Le=Q.replace(/\/+$/,""),z=St(()=>qi({userId:i,email:a,firstName:k,lastName:O,country:L,zip:Ue},qn),[i,a,k,O,L,Ue,qn]),ct=[z.firstName,z.lastName].filter(r=>!!r?.trim()).join(" "),at=!Rn(z.email?.trim()),Ln=H(null);X&&Ln.current===null&&(Ln.current=at);let Ct=X&&(Ln.current??at),co=St(()=>Bp(an,Ct),[an,Ct]),uo=co.empty||co.malformed,Qn=St(()=>Se?Se.getRawProvider():null,[Se]),Es=St(()=>Ft?Ft.getRawProvider():null,[Ft]),Wo=Ke||100,po=wn.toLowerCase(),mi=St(()=>mt?Mu(mt):null,[mt]),yo=mi,_s=St(()=>{let r=mi??{},y=r.rules??{};return{...r,rules:{...y,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...y[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...y[".AccordionItemContents"]??{}}}}},[mi]),Ts=St(()=>({...Ll(Ke,ke?.captureMethod,Ie),currency:po,...yo?{appearance:yo}:null}),[Ke,po,ke?.captureMethod,Ie,yo]),fi=Rc(Ie,"paypal","paypal"),Ms=St(()=>({mode:"payment",amount:Wo,currency:po,captureMethod:"manual",...fi?{setupFutureUsage:fi}:null,...yo?{appearance:yo}:null}),[Wo,po,fi,yo]),Pe=Te(r=>{on(r),b?.(r)},[b]),As=H(0);ft(()=>{An!==As.current&&(As.current=An,Pe(null))},[An,Pe]);let gi=H(""),[xs,Gc]=ce(!1),hi=Te(()=>{Gc(!0)},[]);ft(()=>{if(!X||!Ct||!J||!xs||uo||gi.current)return;let r=pr({email:Rn(z.email?.trim())?z.email?.trim():Kt.current.trim(),firstName:z.firstName?.trim(),lastName:z.lastName?.trim()});gi.current=JSON.stringify(r),Be(y=>({...y,...r})),Promise.resolve(J(r)).catch(y=>{gi.current="",Pe(y instanceof Error?y.message:"Failed to attach buyer details.")})},[X,Ct,J,xs,uo,z.email,z.firstName,z.lastName,Pe]),ft(()=>{!X||!U||U.setCardFieldOrder?.(ne??null,Ee==null&&!Ct)},[X,U,ne,Ee,Ct]),ft(()=>{(Ne==="expanding"||Ne==="collapsing"||Ne==="apm-expanding"||Ne==="apm-collapsing")&&Pe(null)},[Ne,Pe]);let Cr=Te((r,y,T)=>{u?.(Sn(r,y,T))},[u]),Bs=H(Ne);Bs.current=Ne;let[Fs]=ce(Ha),Ds=Te(()=>{let r=Bs.current;if(He==="buttons"&&(r==="card"||r==="expanding"))return!0;let y=W.current;return y==="validation-window"||y==="processing"||We.current},[He]),Os=Te((r,y,T)=>{Fs.take(e)&&pn(Se)?.log(io({...Ge,presentationMode:T?.presentationMode??"popup"},{name:Va,stage:"recovery",reason:"other_method_active",provider:T?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:T?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[Ge,Se,Fs,e]),Pi=Te((r,y,T)=>{T?.telemetryReported||pn(Se)?.error(io({...Ge,presentationMode:T?.presentationMode??"popup"},{errorCode:y?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:T?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:T?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:T?.terminalReason??(y?"popup_blocked":"provider_error")}))},[Ge,Se]),mo=Te((r,y,T)=>{let ae=T?.popupBlocked??$r(y);if(Ds()){Pi(r,ae,T),Os(r,y,T);return}ae&&v.markBlocked()&&we(dt=>dt+1);let x=cs(r),ie=T?.code===_c?Bu(x):Oa(x,ae,et.inAppBrowser),At=bo(y),or=(At?.toLowerCase()==="error"?void 0:At)??vl(T?.code)??"external_payment_method_failed",Je=new zr(ie,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:or,popupBlocked:ae,inAppBrowser:et.inAppBrowser,appFamily:et.appFamily,popupCapability:v.current(),presentationMode:T?.presentationMode??"popup"}});Pi(r,ae,T),K(null),He==="buttons"&&(un("buttons"),Hn(null)),Pe(ie),l?.(Je),console.error("[FloPay] External payment method failed:",{method:r,code:or,popupBlocked:ae})},[et,Ds,He,l,v,Os,Pi,Pe]);ft(()=>{if(!X||!e){Vn(null);return}let r={billingApiUrl:Le,sessionId:e,nonce:t},y=ns(P?.vault,r);if(y){Vn(y);return}if(!B){Vn(null);return}let T=`${Le}\0${e}\0${t??""}`,ae=w.current;if(ae&&ae.key===T){Vn(ae.mount);return}Vn(null);let x=!0;return new No(Le).getVaultCapture(e,t).then(ie=>{if(!x)return;let At=ns(ie,r);At?.verificationRequired&&!ie.html&&(w.current={key:T,mount:At}),At?Vn(At):Pe("Failed to load the secure card form.")}).catch(ie=>{x&&Pe(ie instanceof Error?ie.message:"Failed to load the secure card form.")}),()=>{x=!1}},[X,B,$,e,P?.vault,Le,t,Pe]);let cr=H({onComplete:s,onError:l,updateError:Pe,emitDecline:Cr,resolvedAccount:z,avsConfig:Ee,avsCheckProp:ht,sessionId:e,nonce:t,baseUrl:Le,captureMethod:P?.captureMethod,paymentId:P?.paymentId,authorizationExpiresAt:P?.authorizationExpiresAt,serverSideCardGateway:Tn});cr.current={onComplete:s,onError:l,updateError:Pe,emitDecline:Cr,resolvedAccount:z,avsConfig:Ee,avsCheckProp:ht,sessionId:e,nonce:t,baseUrl:Le,captureMethod:P?.captureMethod,paymentId:P?.paymentId,authorizationExpiresAt:P?.authorizationExpiresAt,serverSideCardGateway:Tn};let vi=H(!1),Ns=Te(()=>{let r=cr.current,y=r.resolvedAccount.email?.trim(),T=Rn(y)?y:Kt.current.trim();if(!Rn(T))return null;let ae=r.resolvedAccount.firstName?.trim(),x=r.resolvedAccount.lastName?.trim(),ie=kn.current.trim()||r.resolvedAccount.country?.trim()||"",At=r.avsConfig?Jt(r.avsConfig.state,ie):!1,or=r.avsConfig?Jt(r.avsConfig.address_line_1,ie):!1,Je=r.avsConfig?Jt(r.avsConfig.postal_code,ie):!1,dt=r.avsConfig?Jt(r.avsConfig.city,ie):!1,bt=r.avsConfig?Jt(r.avsConfig.address_line_2,ie):!1,$t=or&&!At&&Je?ju(ie,(lt.current??"").trim()):null,eo=At?Ht.current:$t;return{accountData:{userId:r.resolvedAccount.userId??"",email:T,...ae?{firstName:ae}:{},...x?{lastName:x}:{},...Je&<.current?{zip:lt.current}:{},...dt&&ln.current?{city:ln.current}:{},...eo?{state:eo}:{},...or&&Ut.current?{addressLine1:Ut.current}:{},...bt&&sn.current?{addressLine2:sn.current}:{},...ie?{country:ie}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Jt(r.avsConfig.country,ie),postal_code:Je,address_line_1:or,address_line_2:bt,city:dt,state:At}}:{}}},[]),Ls=H(d);Ls.current=d,ft(()=>{d||le!==Pc||cr.current.updateError(null)},[d,le]),ft(()=>{!X||!U||U.setSubmitGate?.(dn||d||uo||be)},[X,U,dn,d,uo,be]),ft(()=>{if(!X||!U)return;vi.current=!1;let r=null,y=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,W.current="idle",K(null)},400)},T=U.on("submitting",()=>{hr(!0),E.current&&clearTimeout(E.current),W.current="validation-window",E.current=setTimeout(()=>{E.current=null,W.current==="validation-window"&&(W.current="processing")},Sp),K("processing");let Je=cr.current;if(!Je.sessionId||!Je.nonce)return;let dt=Ns();if(!dt){Je.updateError("Enter a valid email address."),W.current="idle",K(null);return}new No(Je.baseUrl).patchAccountSnapshot(Je.sessionId,Je.nonce,dt,{telemetryMode:"best_effort"}).catch(bt=>{if(!kp(bt))return;let $t=bt instanceof Error?bt.message:"Please check your billing address and try again.";Je.updateError($t),W.current="idle",K(null),Je.onError?.(bt instanceof zr?bt:new zr($t,"api_error"))})}),ae=U.on("complete",Je=>{Bo(Je.sessionId??cr.current.sessionId),W.current="terminal",V(!1),K("success"),setTimeout(()=>{if(vi.current)return;vi.current=!0;let dt=cr.current,bt=es(dt)||Je.outcome==="authorized",$t=dt.serverSideCardGateway?{}:{paymentIntentId:Je.intentId};cr.current.onComplete?.(bt?{status:"authorized",...$t,paymentId:Je.paymentId??dt.paymentId,sessionId:Je.sessionId??dt.sessionId,authorizationExpiresAt:Je.authorizationExpiresAt??dt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...$t,checkoutMethod:"card"})},600)}),x=U.on("decline",Je=>{let dt=cr.current,bt=Je.message??"Your payment was declined. Please try another card or contact your bank.";W.current="terminal",V(!1),dt.updateError(bt),K("error");let $t=Je.failureOutcome??Yu(Je.declineReason)??"authorization_declined";dt.emitDecline("card",bt,{code:$t,declineCode:$t}),y()}),ie=U.on("error",Je=>{let dt=cr.current,bt=Je.message??"There was a problem processing your payment. Please try again.";W.current="terminal",V(!1),dt.updateError(bt),K("error"),dt.onError?.(new zr(bt,"api_error",{code:Je.failureOutcome??"capture_failed"})),y()}),At=U.on("challenge_dismissed",()=>{E.current&&(clearTimeout(E.current),E.current=null),W.current="processing",V(!0),K(null)}),or=U.on("blocked",()=>{if(We.current){cr.current.updateError(wp);return}if(!Ls.current){hr(!0);return}hi(),cr.current.updateError(Pc)});return()=>{r&&(clearTimeout(r),r=null),E.current&&(clearTimeout(E.current),E.current=null),W.current="idle",V(!1),K(null),T(),ae(),x(),ie(),At(),or()}},[X,U,hi,Ns]);let br=!!Pt?.clientId,Vo=Array.isArray(Y),Ia=Vo&&Y.length>0,zs=Vo&&Y.includes("paypal"),Ra=H(null);Ra.current===null&&(Ra.current=Wu());let fo=Ra.current?"redirect":Cl(et,Xe,v.current()),{expressMethods:Ea,paymentElementMethods:Ci}=St(()=>Ju(Y,{excludePaypal:br}),[Y,br]),Us=br||!!Ft||zs&&fo==="redirect",Yc=St(()=>Us?Ea.filter(r=>r!=="paypal"):Ea,[Ea,Us]),Jc=St(()=>{let r=[];return nt&&r.push("apple_pay"),ze&&r.push("google_pay"),r},[nt,ze]),go=Vo?Yc:Jc,Zc=I&&go.length>0,qs=hn?Wt:L,_a=St(()=>Uu(Ci,qs,Fe),[Ci,qs,Fe]),bi=St(()=>({mode:"payment",amount:Wo,currency:po,paymentMethodCreation:"manual",appearance:_s}),[Wo,po,_s]),[js,$s]=ce("loading"),[Ws,Vs]=ce("loading"),[Hs,Ks]=ce("loading"),[Xc,Si]=ce(!1),[Gs,wi]=ce("loading"),[ki,Qc]=ce();ft(()=>{Qc(ra())},[]);let Ta=ki?.inAppBrowser,Ma=ki?La(ki,Pt?.approvalPresentation,Dt??(pe?"subscription":"order")):"popup",Ys=Ve&&(br||(Vo?zs:Ta===!1)),ed=et.inAppBrowser&&v.current()==="blocked",Js=I&&Zc&&!ed,Ho=(!he||!!ye.waitForDataAttachment)&&Ys&&br,Zs=Gs==="retrying"||Gs==="exhausted",Ko=null;I&&(Ft?Ko=Es:fo==="redirect"&&(Ko=Qn));let Xs=St(()=>({...Ge,presentationMode:fo}),[Ge,fo]),Go=!he&&Ys&&!!Ko&&(!br||Zs),ho=!he&&Js&&!!Qn,Yo=!he&&I&&Ia&&_a.length>0&&!!Qn,td=Ho&&!Zs?Xc:Go&&Li(js),nd=ho&&Li(Ws),rd=Yo&&Hs!=="load_error",Qs=r=>r==="loading"||r==="ready",el=Ho||Go&&Qs(js)||ho&&Qs(Ws)||Yo&&Hs!=="load_error",Aa=H(!1);ft(()=>{if(!Aa.current){if(!I&&!Ve){Aa.current=!0;let r=new zr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(r),Pe(r.message)}else if(!I&&Ve&&!br){Aa.current=!0;let r=new zr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(r),Pe(r.message)}else if(Ta!==void 0&&!he&&!Qt&&!el){Aa.current=!0;let r=new zr("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(r),Pe(r.message)}}},[I,Ve,br,Ta,he,Qt,el,l,Pe]);let tl=H(!1);ft(()=>{if(tl.current||!Ia)return;let r=[];nt!==!0&&r.push("showApplePay"),ze!==!0&&r.push("showGooglePay"),r.length!==0&&(tl.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Ia,nt,ze]);let nl=Te((r,y,T)=>ye.applyInlineSessionPatch?ye.applyInlineSessionPatch(r).then(ae=>({error:null,sessionId:ae.sessionId||e,nonce:ae.session?.clientSecret||t})).catch(ae=>{let x=yc(y,ae);return T?.abandoned?.()||(Pe(x.message),l?.(x)),{error:x,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ye.applyInlineSessionPatch,t,l,e,Pe]),dr=Te(async(r,y)=>{if(r!=="card"&&he&&await ye.waitForDataAttachment?.(),!wt)return{proceed:!0};try{let T=await wt({method:r,sessionId:e||void 0,createSession:ye.inlineSessionDraft});if(T===!1)return{proceed:!1};if(T&&typeof T=="object"){T.account&&Be(x=>({...x??{},...T.account}));let ae=await nl(T,r,y);return ae.error?{proceed:!1,accountPatch:T.account}:{proceed:!0,accountPatch:T.account,sessionId:ae.sessionId,nonce:ae.nonce}}return{proceed:!0}}catch(T){if(!y?.abandoned?.()){let ae=yc(r,T);Pe(ae.message),l?.(ae)}return{proceed:!1}}},[nl,ye.inlineSessionDraft,ye.waitForDataAttachment,he,wt,l,e,Pe]),rl=Te(async(r,y)=>{if(A.current)return;A.current=!0,mn(!0),K("processing"),Pe(null);let T=y?.sessionId??e,ae=y?.nonce??t,x=qi(z,y?.accountPatch),ie=y?.completionPaymentMethodId??sa(r),At=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,or=_p(r),Je=y?.presentationMode?oi(pn(Se),{...Ge,presentationMode:y.presentationMode}):void 0,dt=()=>{kt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:or}),Je?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...yr,requestCategory:"process_payment"})};try{let bt=new No(Le),$t=await bt.processPayment(x.userId??"",{sessionId:T,nonce:ae,paymentMethodCategory:y?.paymentMethodCategory??Mp(r),tokenizedData:At,accountData:{...y?.accountPatch,userId:x.userId??"",email:x.email??"",firstName:x.firstName||void 0,lastName:x.lastName||void 0,...xu({avsConfig:Ee,country:kn.current,zip:lt.current,city:ln.current,state:Ht.current,addressLine1:Ut.current,addressLine2:sn.current})},...Au({chv:ue,avsCheck:ht,checkoutType:ve,checkoutLayout:je,avsConfig:Ee,country:kn.current})}),eo=async bn=>{let to=es(P)||bn?.status==="authorized";Bo(T),Je?.terminal({outcome:"payment_succeeded",...yr}),K("success"),f(null),await new Promise(ta=>setTimeout(ta,600));let Sr;typeof bn?.paymentId=="string"?Sr=bn.paymentId:P?.paymentId&&(Sr=P.paymentId);let no;typeof bn?.authorizationExpiresAt=="string"?no=bn.authorizationExpiresAt:P?.authorizationExpiresAt&&(no=P.authorizationExpiresAt),s?.(to?{status:"authorized",...Sr===void 0?{}:{paymentId:Sr},sessionId:typeof bn?.sessionId=="string"?bn.sessionId:T,...no===void 0?{}:{authorizationExpiresAt:no},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ie,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ie,checkoutMethod:r.isPaypal?"paypal":"card"})};if($t.ok){await eo($t.status===204?null:await $t.json().catch(()=>null));return}let er=await $t.json().catch(()=>null);if(er?.type==="paypal_redirect_required"){let bn=er.threeDSecureToken,to=er.paymentMethodId||r.id||"";if(!Se||!bn){K("error"),Pe("PayPal authorization required but no token provided.");return}try{let Sr=Ft?.getRawProvider();if(!Sr){Pe("PayPal is not available.");return}let no={return_url:window.location.href};to&&(no.payment_method=to);let{error:ta}=await Sr.confirmPayment({clientSecret:bn,confirmParams:no,redirect:"if_required"});if(ta){K("error");let fl=ta.message??"PayPal payment failed.";Pe(fl),Cr("paypal",fl,{code:ta.code})}}catch(Sr){K("error"),Pe(Sr instanceof Error?Sr.message:"PayPal authorization failed.")}return}if(er?.type==="paypal_direct_required"){let bn=er.orderId;if(!bn){K("error"),Pe("PayPal retry required but no order id provided.");return}let to=g.current?.attempts??0;if(to>=2){K("error"),Pe("PayPal payment could not be completed after multiple attempts."),Cr("paypal","paypal_direct_required retry limit exceeded");return}Si(!1),wi("loading"),f({orderId:bn,attempts:to+1}),K(null);return}if($t.headers.get(fp)===gp){let bn=await hp(bt,T,ae);if(bn!==void 0){await eo(bn);return}}Du($t.status,er)?Je?.terminal({outcome:"payment_declined",...yr,terminalReason:"provider_declined"}):dt(),K("error");let ml=er?.message??"Payment failed. Please try again.";Pe(ml),Cr(r.isPaypal?"paypal":"card",ml,{code:er?.code??er?.gatewayErrorCode,declineCode:er?.declineCode??er?.gatewayDeclineReason}),await new Promise(bn=>setTimeout(bn,400))}catch(bt){xc(bt)||dt(),K("error"),Pe(bt instanceof Error?bt.message:"An unexpected error occurred"),await new Promise($t=>setTimeout($t,400))}finally{mn(!1),K(null),A.current=!1}},[Le,e,t,z,Ee,ht,ve,je,ue,Se,Ft,P,s,Pe,Cr,kt,Ge]),Kn=Te((r,y)=>{_?_(r):rl(r,y)},[_,rl]),Jo=`${Mc}:${e}`;ft(()=>{if(typeof window>"u")return;let r=localStorage.getItem(Jo);if(!r)return;let y;try{y=JSON.parse(r)}catch{rn(Jo);return}if(!y||typeof y.createdAt!="number"||Date.now()-y.createdAt<0||Date.now()-y.createdAt>Ac||typeof y.paymentMethodId!="string"||typeof y.providerIntentId!="string"||typeof y.paymentMethodType!="string"||y.sessionId!==e||!t||y.nonce!==t||!go.includes(y.paymentMethodType)){rn(Jo);return}rn(Jo),Kn({id:y.paymentMethodId,type:"card",threeDSecureActionResultTokenId:y.providerIntentId,gateway:"stripe",paymentMethodType:y.paymentMethodType},{...y.accountPatch?{accountPatch:y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Kn,t,e,Jo,go]);let ol=H(!1);ft(()=>{if(typeof window>"u"||ol.current)return;let[r,y,T]=Ic();if(!r||!y||Ra.current||!Se)return;let ae=Se.getRawProvider();if(!ae)return;let x=dt=>{let bt=localStorage.getItem(dt);if(!bt)return null;try{return JSON.parse(bt)}catch{return rn(dt),null}},ie=x(Rr)??x(fc),At;if(ie?.clientSecret){if(ie.clientSecret!==y)return;At={...ie.accountPatch?{accountPatch:ie.accountPatch}:{},...ie.sessionId?{sessionId:ie.sessionId}:{},...ie.nonce?{nonce:ie.nonce}:{}}}else if(ie?.sessionId&&ie.sessionId!==e)return;ol.current=!0,rn(Rr),rn(fc),window.history.replaceState({},"",Ec());let or=ie?.paymentMethodType??ie?.tokenType??"card",Je="card";(async()=>{if(T==="failed"){let Fr="Payment was declined. Please try again.";Pe(Fr),Cr(Je,Fr);return}let{paymentIntent:dt,error:bt}=await ae.retrievePaymentIntent(y);if(bt){let Fr=bt.message??"Failed to retrieve payment status.";Pe(Fr),Cr(Je,Fr,{code:bt.code});return}let $t=dt?.status,eo=ia($t);if(!dt||!eo){let Fr=$t==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Pe(Fr),Cr(Je,Fr,{code:$t??"missing_payment_intent"});return}let er=typeof dt.payment_method=="string"?dt.payment_method:dt.payment_method?.id;Kn({id:er??ie?.paymentMethodId??ie?.tokenId??dt.id,type:"card",threeDSecureActionResultTokenId:dt.id,gateway:ie?.gateway??"stripe",paymentMethodType:or},At)})()},[e,Kn,Se,Pe,Cr]);let Ii=Te(r=>{r.preventDefault()},[]);if(!(X||Se!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Zo=He==="buttons",Gn=mt?.variables,od=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ri=Gn?.colorBackground,ad=Ri&&!od.has(Ri)?Ri:void 0,Xo=D.cardInputBorder??(Zo?"#e5e7eb":"#A4A4FF"),al=Gn?.colorDanger??"#dc2626",Yt=r=>Mn[r]&&(qr[r]||Gt),xa=uo&&(vr||Gt),rr=r=>r?al:Xo,Ba=(_t.malformed||_t.empty)&&(Tr||Gt),id=rr(Ba),Ei=D.cardFormContainer?.backgroundColor??ad??(Zo?"white":"#EDEDFF"),Po=D.cardInputBackground??Gn?.colorBackground??"white",_i=So(rt),il=So(ge),vo=D.nameInput,sl=D.cardInputFontSize??Fp(vo?.fontSize)??Gn?.fontSizeBase??"16px",ll=typeof vo?.fontFamily=="string"?vo.fontFamily:Gn?.fontFamily??"Poppins, sans-serif",cl=ap(vo?.fontWeight)??400,sd=D.cardInputColor??(typeof vo?.color=="string"?vo.color:void 0)??Gn?.colorText??"#262833",ld=D.cardInputPlaceholderColor??"#9ca3af",nn=Gn?.borderRadius??"8px",Xr=Gn?.borderRadius??D.cardButton?.borderRadius??nn,Qr=Gn?.colorPrimary??"#4A49FF",cd=Gn?.colorPrimaryHover??Lu(Qr,.12),Ti=Gn?.colorText??"#262833",Mi={fontSize:sl,fontFamily:ll,fontWeight:cl,color:sd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Qo={marginTop:"0.375rem",...Mi,fontSize:"0.75rem",lineHeight:1.4,color:al},dd={"--flopay-input-placeholder-color":ld,"--flopay-input-font-size":sl,"--flopay-input-font-family":ll,"--flopay-input-font-weight":String(cl)},ea=D.cardFormContainer??{},Ai=ea.padding??(Zo?"0":"1rem"),xi=ea.borderRadius??nn,ud=U&&Zn?c(Bi,{capture:U,html:Zn.html,messageToken:Zn.messageToken,expectedOrigin:Zn.expectedOrigin,verificationRequired:Zn.verificationRequired,theme:Nn,submitLabel:Ae,onReady:()=>{if(!Ct&&!Ee||typeof document>"u")return;let r=()=>{let T=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(T){In.current=!0;try{T.focus()}finally{In.current=!1}}};nr.current||r()},onError:r=>{r&&Zn.verificationRequired&&W.current==="idle"&&(Br.current=!0),Pe(r)},onValidation:r=>{let y=W.current;(y==="idle"||y==="validation-window")&&(Pe(r),r&&W.current==="validation-window"&&(E.current&&(clearTimeout(E.current),E.current=null),W.current="idle",K(null)))}},An):c("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),dl=Ze("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&lr()},style:{backgroundColor:Ei,borderRadius:xi,...ea,padding:Ai,...dd,display:"flex",flexDirection:"column"},children:[c("style",{children:`
|
|
3
|
+
${Se.join(`
|
|
4
|
+
`)}`]}):null;return Pt&&!p?ee?io("div",{children:qn}):null:Ki("div",{children:[qn,Qe&&io(To,{identity:Qe.identity,methodLabel:Qe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ce,onCancel:()=>Ce(null)}),Ki("div",{"aria-hidden":De||Qe?!0:void 0,style:De||Qe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ja},children:[!Fe&&!De&&io("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),io("div",{ref:pe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ja,display:"flex",opacity:Fe?1:0},"aria-busy":h||S},Ee)]},Ee),$e&&io("button",{ref:je,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:pn,style:gu,children:"Try PayPal again"})]})}function Xa(e){return io(nc,{...e})}function rc(e){return io(nc,{...e})}import{jsx as oc,jsxs as Cu}from"react/jsx-runtime";function xo({children:e,margin:t,icon:n=!0,styleOverride:o}){return Cu("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...o??{}},children:[n&&oc("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:oc("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{clearCachedInlineCheckout as Za,clearCachedInlineSession as Gi,hashCreateParams as ac,legacyCachedSessionMatchesDraft as ic,persistCachedInlineIdempotencyKey as Qa,persistCachedInlineSession as ei,readCachedInlineIdempotencyKey as sc,readCachedInlineSession as lc,serializeCreateParams as ya}from"@flopay/shared";import{resolveBillingApiUrl as bu}from"@flopay/shared";import{useEffect as Jr,useMemo as Su,useRef as cc,useState as dc}from"react";import{jsx as wu}from"react/jsx-runtime";function ti({flopay:e,paypalFlopay:t,options:n,onInstrument:o,children:a}){let[i,s]=dc(e instanceof Promise?null:e),[l,m]=dc(t instanceof Promise||!t?null:t),C=cc(null),T=cc(null),I=Mo(o);Jr(()=>{I({class:"lifecycle",name:"checkout.mount"})},[I]),Jr(()=>{i&&I({class:"lifecycle",name:"sdk.initialize.ready"})},[I,i]),Jr(()=>{if(i)return gn(i)?.subscribe?.(I)},[I,i]),Jr(()=>{if(!(!l||l===i))return gn(l)?.subscribe?.(I)},[I,i,l]),Jr(()=>{if(!i)return;let L=gn(i);return C.current=L?.beginCheckout()??L?.now()??0,L?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{L?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Jr(()=>{let L=!1;return e instanceof Promise?e.then(Be=>{L||s(Be)},()=>{L||I({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{L=!0}},[I,e]),Jr(()=>{let L=!1;if(!t){m(null);return}return t instanceof Promise?t.then(Be=>{L||m(Be)},()=>{L||I({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{L=!0}},[I,t]),Jr(()=>{if(!i||T.current===i)return;T.current=i;let L=gn(i);L?.log({name:"checkout.rendered",stage:"checkout_render"}),I({class:"lifecycle",name:"checkout.rendered"}),L?.performance({stage:"checkout_render",durationMs:L.elapsed(C.current??0),durationMode:"machine"})},[I,i]);let N=bu(n?.billingApiUrl),ue=Su(()=>({flopay:i,paypalFlopay:l,billingApiUrl:N,emitInstrument:I}),[i,l,N,I]);return wu(lr.Provider,{value:ue,children:a})}import{markSessionRecentlyCompleted as Bo,wasSessionRecentlyCompleted as Yi}from"@flopay/shared";async function ni(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{completeSavedCardNextAction as ku,loadFloPay as uc,PaymentAPI as oi,runSavedCardChallenge as Iu}from"@flopay/js";import{classifyPaymentRejection as Ru,FloPayError as Mt,isAuthorizationOnlySession as _u,isMountableVaultBlock as Eu,isSetupIntentClientSecret as Tu,normalizeCheckoutFailureOutcome as pc}from"@flopay/shared";var fa="card";async function Mu(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:o,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:o??null}}async function Au(e,t,n,o){if(o){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function Fo(e){return new Mt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function xu(){return new Mt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Xi(e,t){return Object.assign(e,{checkoutMethod:t})}function qr(e,t){let n=e instanceof Mt?e:new Mt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function ma(e,t){try{return await e()}catch(n){throw qr(n,t)}}function mc(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function fc(e){return Iu(e)}async function Do(e,t){let{billingApiUrl:n,sessionId:o,signal:a}=t,i=t.nonce??t.session.clientSecret,s=new oi(n,{telemetry:!1}),l=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(o)}/status`,m;try{m=await ku({billingApiUrl:n,sessionId:o,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:T=>Er({type:T.declineReason??"authorization_declined",gatewayErrorCode:T.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},s)}catch(T){if(a.aborted||T instanceof Error&&T.name==="AbortError")throw T instanceof Mt&&T.code==="three_ds_aborted"?T:Fo(T);if(!(T instanceof Mt)||T.code!=="three_ds_timeout"&&T.code!=="checkout_processing_timeout")throw T;try{m=await s.waitForCheckoutSessionCompletion(o,{initialDelayMs:0,nonce:i,statusUrl:l,timeoutMs:5e3,signal:a})}catch(N){if(a.aborted)throw Fo(N);if(!(N instanceof Mt)||N.code!=="checkout_processing_timeout")throw N}let I=m&&Kr(m,t.session);if(!Ur(I)&&I?.status!=="expired"){if(t.telemetry){let N=new oi(n);try{N.reportThreeDsAbandoned(o)}finally{N.destroy()}}throw xu()}}let C=m&&Kr(m,t.session);if(!Ur(C))throw Ro(C);return{...Lr(C,o),checkoutMethod:"card"}}function Er(e,t="Payment failed. Please try again.",n){let o=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=_o(a)??a,s=Xi(new Mt(i,"api_error",{code:e?.code??pc(e?.outcome)??pc(e?.type)??e?.gatewayErrorCode}),o);return e?.orderId&&(s.orderId=e.orderId),s}function Ji(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ri(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function gc(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ri(a)))return a;let o=e?.data;if(o&&typeof o=="object"){let a=o,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||ri(l)))return l;let s=a.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let m=l,C=[m.stripeClientSecret,m.clientSecret];for(let T of C)if(typeof T=="string"&&T.length>0&&(!t?.requirePaymentIntentClientSecret||ri(T)))return T}}}}async function Bu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:o}){let a=gc(o,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let l=(await new oi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ri(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Oo({billingApiUrl:e,sessionId:t,session:n,nonce:o,tokenizedData:a,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),m=t??n.id,C=o??n.clientSecret,T=n.customer?.id??n.accountData?.userId??"",I=n.customer?.email??n.accountData?.email??"",N=n.customer?.firstName??n.accountData?.firstName??"",ue=n.customer?.lastName??n.accountData?.lastName??"",L=n.customer?.country??n.accountData?.country??void 0,Be=n.customer?.zip??n.accountData?.zip??void 0,g=await new oi(l,s===!1?{telemetry:!1}:void 0).processPayment(T,{sessionId:m,nonce:C,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:T,email:I,firstName:N,lastName:ue,country:L,zip:Be},returnUrl:i??Ji(n)});if(g.ok){let R=typeof g.json=="function"?await g.json().catch(()=>null):null;if(_u(n)||R?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof R?.paymentId=="string"?R.paymentId:n.paymentId,sessionId:typeof R?.sessionId=="string"?R.sessionId:m,authorizationExpiresAt:typeof R?.authorizationExpiresAt=="string"?R.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:sa(a),checkoutMethod:yc(a,n)}};let Xe=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Xe?{paymentIntentId:Xe}:{},paymentMethodId:sa(a),checkoutMethod:yc(a,n)}}}let S;try{S=await g.json()}catch(R){throw new Mt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:g.status,cause:R})}if(S?.type==="3ds_required"&&typeof S.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:S.nextActionRedirectUrl};if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let R=gc(S);if(!R)throw new Mt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:g.status});return{type:S.type,threeDSecureToken:R,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let R=await Bu({billingApiUrl:l,sessionId:m,nonce:C,responseJson:S});if(R)return R;throw Xi(new Mt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let Ve=new Mt(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:g.status});throw Object.assign(Ve,{telemetryOutcome:Ru(g.status,S)})}async function ai(e,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:l,telemetry:m,signal:C}){let T=t?.getRawProvider();if(!T)throw qr(new Mt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!o||!e.threeDSecureToken)throw Xi(new Mt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let I=Tu(e.threeDSecureToken),N=null,ue=e.paymentMethodId,L=await ma(()=>Mu(T,e.threeDSecureToken,I),"card");if(L){if(L.error)throw qr(new Mt(L.error.message??`Failed to retrieve 3DS ${I?"setup":"payment"} status.`,"api_error",{code:L.error.code}),"card");let K=L.intent;!ue&&K?.payment_method&&(typeof K.payment_method=="string"?ue=K.payment_method:"id"in K.payment_method&&(ue=K.payment_method.id??void 0))}let Be=ue?await ma(()=>Au(T,e.threeDSecureToken,{payment_method:ue,return_url:l??Ji(s)??window.location.href},I),"card"):null;if(Be){if(Be.error)throw qr(new Mt(Be.error.message??"3DS authentication failed.","api_error",{code:Be.error.code}),"card");N=Be.intent}else{let K=await ma(()=>T.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(K.error)throw qr(new Mt(K.error.message??"3DS authentication failed.","api_error",{code:K.error.code}),"card");N=(I?K.setupIntent:K.paymentIntent)??null}if(N&&(N.status==="requires_capture"||N.status==="succeeded"||N.status==="processing")){let K=await Oo({billingApiUrl:a,sessionId:i,session:s,telemetry:m,tokenizedData:{id:N.id,type:"card",threeDSecureActionResultTokenId:N.id},returnUrl:l});return K.type==="success"?{...K.result,paymentIntentId:K.result.paymentIntentId??N.id,paymentMethodId:K.result.paymentMethodId??ue}:K.type==="next_action_required"?Do(K,{billingApiUrl:a,sessionId:i??s.id,session:s,signal:C}):ai(K,{flopay:t,paypalFlopay:n,attempt3DS:o,billingApiUrl:a,sessionId:i,session:s,returnUrl:l,telemetry:m,signal:C})}throw qr(new Mt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let I=(n??t)?.getRawProvider();if(!I)throw qr(new Mt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:ue}=await ma(()=>I.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(ue)throw qr(new Mt(ue.message??"PayPal authorization failed.","api_error",{code:ue.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:N}=await ma(()=>I.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??Ji(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(N)throw qr(new Mt(N.message??"PayPal authorization failed.","api_error",{code:N.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Mt("Unsupported payment redirect state.","api_error")}function ga(e){if(e instanceof Mt){let o=_o(e.message);return o&&o!==e.message?Object.assign(new Mt(o,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=_o(t)??t;return new Mt(n,"api_error")}function Zi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,o=Eu(e.data.session?.vault)||oo(e.data.session);if(!t&&!n&&!o)throw new Mt("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function yc(e,t){return e?e.isPaypal?"paypal":"card":t&&oo(t)?"card":void 0}async function Qi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:o,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,l]=await Promise.all([uc(e,{billingApiUrl:n,locale:o,telemetry:a}),i?uc(i,{billingApiUrl:n,locale:o,telemetry:a}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);if(!s)throw new Mt("The payment provider did not initialize.","authentication_error");let m=null;return i?m=l:t&&(m=s),{flopay:s,paypalFlopay:m}}import{PaymentAPI as No,PciVaultCardCapture as Fu,toStripeAppearance as Du}from"@flopay/js";import{buildCheckoutProcessMetadata as Ou,buildProcessPaymentAvsAccount as Nu,buildWalletSheetWindowMessage as Lu,COUNTRY_OPTIONS as Uu,classifyPaymentRejection as zu,clearStripePayPalReturn as qu,computeVaultCardThemeColors as ju,darkenHex as $u,denyPaymentPermissionToNewFrames as Wu,FloPayError as Tr,filterStripeMethodsByCountryGate as Vu,getPostalCodeExample as Hu,getPostalCodeLabel as ls,getStateFromPostalCode as Ku,getStateLabel as es,getStateOptions as Gu,getStripeMethodDisplayName as va,hasMatchingStripePayPalReturn as Yu,isAuthorizationOnlySession as ts,isAVSFieldVisible as Jt,isMountableVaultBlock as Ju,isPostalCodeSupported as Xu,isSettledSessionIntent as di,isSetupIntentClientSecret as ns,isValidEmail as Tn,isValidPostalCode as Zu,isWalletSheetRefusedForWindowSize as Qu,needsStripeMethodExplicitConfirm as hc,normalizeBeforeButtonClickError as Pc,normalizeCheckoutFailureOutcome as ep,partitionStripeMethods as tp,randomUuidV4 as np,readMatchingStripePayPalContinuation as rp,readStripeRedirectParams as Mc,resolveAVSConfig as op,resolveButtonsLayoutTheme as ap,resolveSetupFutureUsage as Ac,resolveTheme as ip,resolveVaultMountOptions as rs,STRIPE_PAYPAL_RESUME_KEY as sp,derivePrimaryTileStyle as lp,shouldPreferWalletPopup as vc,stripeExpressMethodToOptionKey as cp,stripeRedirectReturnUrl as xc,toCssWeight as dp,WALLET_SHEET_WINDOW_TOO_SMALL_CODE as Bc}from"@flopay/shared";import{ExpressCheckoutElement as Fc,PaymentElement as up,Elements as lo,useElements as ps,useStripe as ys}from"@stripe/react-stripe-js";import pp,{useCallback as Te,useContext as Uo,useEffect as mt,useLayoutEffect as yp,useMemo as wt,useRef as V,useState as le}from"react";function so(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ii(e,t){if(e)return{error:n=>e.error(so(t,n)),log:n=>e.log(so(t,n)),performance:n=>e.performance(so(t,n)),terminal:n=>e.terminal(so(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}import{darkenHex as zc}from"@flopay/shared";import{Fragment as Lo,jsx as u,jsxs as Je}from"react/jsx-runtime";var Mr="flopay_stripe_resume",Cc="flopay_wallet_resume",Dc="fw1",mp="fw2",Oc=300*1e3,fp=900,gp="express_checkout_click_timeout",hp=25e3,Pp=25e3,vp=1e4,gr={provider:"paypal",paymentMethodCategory:"paypal"},Cp="x-flopay-process-result-source",bp="status";async function Sp(e,t,n){try{let o=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(o?.status==="complete")return null;if(o?.status==="authorized")return{status:"authorized",paymentId:o.paymentId,sessionId:o.id||t,authorizationExpiresAt:o.authorizationExpiresAt}}catch{}}var si={},Pa=class{constructor(t){this.reason=t}};function wp(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function sn(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function ms(e){return`${mp}:${e}`}function li(e){return sn(ms(e))}function ci(e,t){if(typeof window>"u")return null;let n=ms(e);try{let o=localStorage.getItem(n);if(!o)return null;let a=JSON.parse(o);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>Oc||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(li(e),null):a}catch{return li(e),null}}function kp(e){return sn(ms(e.sessionId),e)}function bc(e,t,n){let o=ci(e,t);return!o||o.clientSecret!==n?!1:li(e)}function os(e,t,n){if(typeof window>"u")return;ci(e,t)?.clientSecret===n&&li(e)}function Ip(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function as(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let o=n?e.status==="succeeded":ia(e.status),a=Ip(e);return!o||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Sc(e,t,n){let o=null;try{return await Promise.race([zl(e,t),new Promise(a=>{o=window.setTimeout(()=>{o!==null&&n?.delete(o),a(null)},vp),n?.add(o)})])}finally{o!==null&&(window.clearTimeout(o),n?.delete(o))}}function Rp(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Nc(e){return e instanceof Tr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ui(e,t,...n){let o=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:o});try{return await new No(e,{telemetry:!1}).createSessionIntent(...n)}catch(a){throw Nc(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:o}),a}}var is=sp,ha=new Map,_p=250,wc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Ep="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function fs(e,t,n,o){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...o?{terminalReason:o}:{}})}async function pi({billingApiUrl:e,sessionId:t,nonce:n,request:o}){if(!(!t||!n))try{await new No(e,{telemetry:!1}).reportSessionIntentDecline(t,n,o)}catch{}}function Tp(e){return e instanceof Tr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Lc({event:e,fallbackEmail:t,fallbackName:n}){let o=e.billingDetails,a=t?.trim(),i=la(n),s=i.firstName?i:la(o?.name);return fr({email:Tn(a)?a:o?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Mp({event:e,prepared:t,email:n,billingName:o,methodLabel:a,collect:i}){let s=Lc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||o});return Tn(s.email)?s:i(a,s)}var Ca=180,kc=`flopay-card-enter ${Ca}ms cubic-bezier(0, 0, 0.2, 1) both`,Ic=`flopay-card-exit ${Ca}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Ap=`flopay-buttons-enter ${Ca}ms cubic-bezier(0, 0, 0.2, 1) both`,xp=`flopay-buttons-exit ${Ca}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Bp(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function gs(e){return lp(e)}var Fp={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Dp(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var cs={width:"100%",minHeight:oa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Rc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ds(e){return e==="paypal"?"PayPal":va(e)}function Op(e){let t=Hu(e);return`Enter a valid ${ls(e)}${t?` (e.g. ${t})`:""}`}function Np(e,t,n){let o=Xu(e),a=t.trim(),i=n&&o,s=i&&!a,l=i&&!!a&&!Zu(e,a);return{visible:n,supported:o,required:i,empty:s,malformed:l}}function Lp(e,t){let n=e.trim(),o=t&&!n,a=t&&!!n&&!Tn(n);return{required:t,empty:o,malformed:a,value:n}}function Up(e){return typeof e=="number"?`${e}px`:e}function hs(e){return u(jp,{...e})}function _c({sessionId:e,nonce:t,email:n,billingApiUrl:o,onTokenizedBody:a,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:m,onTechnicalFailure:C,runBeforeButtonClick:T,billingName:I,onBuyerIdentityReady:N,onLoadStateChange:ue,placeholderBorderRadius:L,popupCapabilityOwner:Be,externalTelemetryContext:K,presentationMode:g}){let S=Gr(),{emitInstrument:Ve}=Uo(lr),R=ys(),Xe=ps(),H=wt(()=>ii(gn(S),K),[K,S]),[Ne,ot]=le("loading");mt(()=>{ue?.(Ne)},[Ne,ue]);let[ze,qe]=le(!1),It=V(!1),st=!Tn(n?.trim())||!I?.trim(),{request:ee,collect:Bt,finish:ut}=Eo(),at=V(!1),fe=V(null),ie=V(null),[pe,ft]=le(0),[Ft,Ze]=le(!1),Y=V(!1),_e=V(new Map),{startAttempt:se,finishAttempt:O,invalidateAttempt:je,isAttemptInvalidated:Le,isAttemptCurrent:Fe,generationRef:E}=ua((ce,h,lt)=>{C?.(ce,h,{...lt,popupBlocked:lt?.popupBlocked??Vr(h),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:g,terminalReason:"overlay_timeout"}),Ze(!0),ft(Qe=>Qe+1)},{onHandoffObserved:()=>{Be.markAvailable(),H?.log({name:"provider.popup.opened",stage:"overlay_open",...gr,attempt:E.current})}});mt(()=>{Ft&&ie.current?.focus()},[Ft,pe]);let De=Te(()=>{ft(ce=>ce+1)},[]),gt=Te((ce,h,lt)=>{je(lt),C?.("paypal",ce,{code:h,popupBlocked:Vr(ce),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:g}),Ze(!0),De()},[je,C,g,De]),Ee=Te(()=>{window.setTimeout(()=>{(fe.current?.querySelector("iframe")??fe.current)?.focus()},0)},[]);mt(()=>{Y.current&&(Y.current=!1,Ee())},[Ee,pe]);let ht=Te(()=>{Ze(!1),i?.(null),Ee()},[Ee,i]);mt(()=>{if(!R||at.current)return;let[ce,h,lt]=Mc();if(!ce||!h)return;let Qe=rp(h);if(!Qe)return;at.current=!0;let _=!0,Ce=ha.get(h);Ce||(Ce=lt==="failed"?Promise.resolve(null):Promise.resolve().then(()=>R.retrievePaymentIntent(h)),ha.set(h,Ce));let Dt={accountPatch:Qe.accountPatch,sessionId:Qe.sessionId,nonce:Qe.nonce},de=()=>{H?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...gr,requestCategory:"provider_sdk"})};return H?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...gr}),(async()=>{try{qe(!0);let f=await Ce;if(!_)return;if(f?.error){ha.delete(h),de(),i?.(f.error.message??"Failed to retrieve PayPal payment status.");return}if(qu(),ha.delete(h),lt==="failed"){let ge="PayPal payment was declined. Please try again.";H?.terminal({outcome:"payment_declined",...gr,terminalReason:"provider_declined"}),i?.(ge),m?.(fn("paypal",ge));return}let P=f?.paymentIntent;if(P&&P.id!==ce){de(),i?.("Failed to match the returned PayPal payment.");return}if(P&&(P.status==="requires_capture"||P.status==="succeeded")){let ge=typeof P.payment_method=="string"?P.payment_method:P.payment_method?.id;a({id:ge??P.id,type:"card",threeDSecureActionResultTokenId:P.id,isPaypal:!0},{...Dt,presentationMode:"redirect"})}else{let ge="PayPal payment was not completed. Please try again.";H?.terminal({outcome:P?.status==="canceled"?"payment_cancelled":"payment_declined",...gr,terminalReason:P?.status==="canceled"?"cancelled":"provider_declined"}),i?.(ge),m?.(fn("paypal",ge))}}catch(f){if(!_)return;ha.delete(h),de(),i?.(f instanceof Error?f.message:"Failed to complete PayPal payment.")}finally{_&&qe(!1)}})(),()=>{_=!1,at.current=!1}},[R,a,i,m,H]);let Pe=Te(async(ce=!1)=>{let h=T?await T("paypal"):{proceed:!0};if(!h.proceed)return _e.current.delete(pe),!1;let lt=se("paypal");return _e.current.set(pe,{generation:lt,accountPatch:h.accountPatch,sessionId:h.sessionId,nonce:h.nonce}),Ze(!1),H?.log({name:`provider.${ce?"redirect.started":"handoff.requested"}`,stage:ce?"redirect":"overlay_open",...gr,attempt:lt}),l?.("paypal"),!0},[l,H,T,se,pe]),$e=Te(async ce=>{if(s||ze||!await Pe()){ce.reject();return}ce.resolve()},[s,Pe,ze]),He=Te(async ce=>{if(!R||!Xe)return;let h=_e.current.get(pe);if(h&&!Fe(h.generation)){_e.current.delete(pe);return}if(!h&&Le()||h&&!O(h.generation))return;h||O();let lt=h??null;if(_e.current.delete(pe),!lt&&T){let kt=await T("paypal");if(!kt.proceed){ce.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}lt={accountPatch:kt.accountPatch,sessionId:kt.sessionId,nonce:kt.nonce}}let Qe=lt?.sessionId??e,_=lt?.nonce??t,Ce=await Mp({event:ce,prepared:lt,email:n,billingName:I,methodLabel:"PayPal",collect:Bt});if(!Ce){ce.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Dt=Ce.email,de={...lt?.accountPatch,...fr(Ce,!0)};try{if(qe(!0),i?.(null),!Qe||!Tn(Dt))throw new Error("Missing sessionId or email for PayPal payment");await N?.(Ce);let kt=R.createPaymentMethod,{error:f,paymentMethod:P}=await kt({type:"paypal"});if(f){gt(f,"stripe_paypal_create_payment_method_failed",h?.generation),ce.paymentFailed({reason:"fail"});return}let ge=await ui(o,Ve,Qe,_??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:P?.id??null,intentKind:"payment"});if(di(ge)){ce.paymentFailed({reason:"fail"}),a({type:"card",isPaypal:!0},{accountPatch:de,paymentMethodCategory:"paypal",presentationMode:g,sessionId:Qe,nonce:_,settledProcessResponse:ge.response});return}if(ge.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ve=ge.clientSecret,et={return_url:xc()};if(P?.id&&(et.payment_method=P.id),!sn(is,{clientSecret:ve,sessionId:Qe,nonce:_,accountPatch:de})&&g==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:be,paymentIntent:we}=await R.confirmPayment({clientSecret:ve,confirmParams:et,redirect:"if_required"});if(be){if(sn(is),Ua(be)){let p=be.message??"Your payment was declined.";H?.terminal({outcome:"payment_declined",...gr,terminalReason:"provider_declined"}),i?.(p),m?.(fn("paypal",p,{code:Co(be),declineCode:Ni(be)})),await pi({billingApiUrl:o,sessionId:Qe,nonce:_,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Co(be)??"provider_declined"}})}else gt(be,"stripe_paypal_confirm_failed",h?.generation);return}sn(is);let Ot=typeof we?.payment_method=="string"?we.payment_method:we?.payment_method?.id;a({id:Ot??we?.id,type:"card",threeDSecureActionResultTokenId:we?.id,isPaypal:!0},{accountPatch:de,paymentMethodCategory:"paypal",presentationMode:g,sessionId:Qe,nonce:_});return}catch(kt){gt(kt,"stripe_paypal_failed",h?.generation)}finally{qe(!1)}},[R,Xe,e,t,n,I,Bt,N,o,Ve,a,i,m,T,gt,O,Fe,Le,H,g,pe]),In=Te(async()=>{if(!(It.current||s||ze||!R||!Xe)){It.current=!0,qe(!0);try{if(!await Pe(!0))return;await He({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{It.current=!1,qe(!1)}}},[Xe,He,s,Pe,R,ze]),_t=g==="redirect"?u("button",{type:"button",disabled:s||ze,onClick:()=>{In()},style:{width:"100%",minHeight:oa,border:"1px solid #d1d5db",borderRadius:L??8,background:"#ffc439",color:"#111827",cursor:s||ze?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):u(Fc,{onReady:ce=>ot(Li(ce,["paypal"])),onLoadError:()=>{ot("load_error"),fs(H,"paypal","paypal","provider_error")},onClick:$e,onConfirm:He,onCancel:()=>{let ce=_e.current.get(pe);_e.current.delete(pe),H?.terminal({outcome:"payment_cancelled",...gr,terminalReason:"cancelled",...ce?{attempt:ce.generation}:{}}),je(ce?.generation),Ze(!1),Y.current=!0,De()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:st,emailRequired:st,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},pe),Pt=Je(Lo,{children:[Je("div",{ref:fe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ft&&u("button",{ref:ie,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ht,style:cs,children:"Try PayPal again"}),ee&&u(To,{identity:ee.identity,methodLabel:ee.methodLabel,onComplete:ut,onCancel:()=>ut(null)},ee.id),u("div",{style:{display:ee?"none":void 0},children:_t})]}),ze&&!ee&&u(Rr,{status:"processing"})]});return g==="redirect"?Pt:u(Ui,{state:Ne,placeholderTestId:"flopay-paypal-placeholder",borderRadius:L,children:Pt})}function ss(e){return e==="apple_pay"||e==="google_pay"}var zp=200;function qp({active:e}){return yp(()=>e?Wu(document):void 0,[e]),null}function Ec({sessionId:e,nonce:t,email:n,billingApiUrl:o,intentKind:a,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:m,onDecline:C,onTechnicalFailure:T,runBeforeButtonClick:I,billingName:N,onBuyerIdentityReady:ue,onLoadStateChange:L,placeholderBorderRadius:Be,popupCapabilityOwner:K,externalTelemetryContext:g}){let S=Gr(),{emitInstrument:Ve}=Uo(lr),R=ys(),Xe=ps(),H=wt(()=>ii(gn(S),g),[g,S]),[Ne,ot]=le("loading");mt(()=>{L?.(Ne)},[Ne,L]);let[ze,qe]=le(!1);mt(()=>{Ze.current=ze},[ze]);let It=V(!Tn(n?.trim())||!N?.trim()).current,{request:st,collect:ee,finish:Bt}=Eo(),ut=V(null),at=V(null),[fe,ie]=le(0),[pe,ft]=le(()=>vc()),Ft=V(pe),Ze=V(!1),[Y,_e]=le(!1),[se,O]=le(()=>ci(e,t)?"blocked":"idle"),[je,Le]=le("google_pay"),Fe=V(null),E=V(!0),De=V(!1),gt=V("google_pay"),Ee=V("google_pay"),ht=V(null),Pe=V(null),$e=V(new Set),He=V(null),In=V(null);mt(()=>(E.current=!0,()=>{E.current=!1;for(let p of $e.current)window.clearTimeout(p);$e.current.clear()}),[]);let _t=V(new Map),{startAttempt:Pt,finishAttempt:ce,invalidateAttempt:h,isAttemptInvalidated:lt,isAttemptCurrent:Qe,generationRef:_}=ua((p,Oe,he)=>{T?.(p,Oe,{...he,popupBlocked:he?.popupBlocked??Vr(Oe),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Le(p),_e(!0),ie(Se=>Se+1)},{onHandoffObserved:p=>{In.current=_.current,K.markAvailable(),H?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:_.current,...p==="apple_pay"||p==="google_pay"?{walletType:p}:{}})},defersMissingTerminal:ss,onMissingTerminalDeferred:(p,Oe)=>{let he=H?.now()??globalThis.performance?.now()??Date.now(),Se=He.current,J=Se?.generation===Oe?Se.startedAt:he;H?.performance({stage:"overlay_return",durationMs:Math.max(0,he-J),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:Oe,...ss(p)?{walletType:p}:{}}),H?.flush?.().catch(()=>{})}});mt(()=>{Y&&at.current?.focus()},[Y,fe]);let Ce=V(0),Dt=V(!1),de=Te(()=>{if(Ce.current>0){Dt.current=!0;return}ie(p=>p+1)},[]),kt=Te(()=>{Ce.current-=1,!(Ce.current>0||!Dt.current)&&(Dt.current=!1,E.current&&ie(p=>p+1))},[]),f=Te((p,Oe,he,Se,J=!1)=>{h(Se),T?.(p,Oe,{code:he,popupBlocked:Vr(Oe),telemetryReported:J,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),Le(p),_e(!0),de()},[h,T,de]),P=Te(p=>{H?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",statusClass:"timeout",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"overlay_timeout",...ss(p)?{walletType:p}:{}}),T?.(p,new Error("The wallet click was not ready within the time the wallet allows."),{code:gp,popupBlocked:!1,telemetryReported:!0,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),Le(p),_e(!0)},[T,H]),ge=Te(()=>{window.setTimeout(()=>{(ut.current?.querySelector("iframe")??ut.current)?.focus()},0)},[]);mt(()=>{De.current&&(De.current=!1,ge())},[ge,fe]);let ve=Te(()=>{_e(!1),l?.(null),ge()},[ge,l]),et=Te(()=>{Fe.current?.()},[]);mt(()=>{let p=null,Oe=()=>{p=null;let Se=vc();Se!==Ft.current&&(Ft.current=Se,ft(Se),!Ze.current&&!Qe(_.current)&&de())},he=()=>{p!==null&&window.clearTimeout(p),p=window.setTimeout(Oe,zp)};return window.addEventListener("resize",he),()=>{window.removeEventListener("resize",he),p!==null&&window.clearTimeout(p)}},[_,Qe,de]),mt(()=>{let p=ci(e,t);if(!p)return;let Oe=!1,he=!1,Se=async()=>{if(!he){he=!0,Oe||O("checking");try{let J=await Sc(R,p.clientSecret,$e.current);if(Oe)return;let z=as(J,p.providerObjectId,ns(p.clientSecret));if(z.kind==="confirmed"){if(!bc(e,t,p.clientSecret))return;Fe.current=null,O("idle"),s({id:z.paymentMethodId,type:"card",threeDSecureActionResultTokenId:z.intentId},{...p.accountPatch?{accountPatch:p.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(z.kind==="terminal"){os(e,t,p.clientSecret),Fe.current=null,O("idle"),Le(p.paymentMethodType),_e(!0),de();return}O("blocked")}catch{Oe||O("blocked")}finally{he=!1}}};return Fe.current=Se,O("blocked"),()=>{Oe=!0,Fe.current===Se&&(Fe.current=null)}},[t,s,de,e,R]);let Ke=Te(async p=>{let Oe=!1,he=!1,Se=Me=>{Oe||he||(Oe=!0,p.paymentFailed({reason:"fail",...Me?{message:Me}:{}}))};if(!R||!Xe){Se();return}let J=_t.current.get(fe);if(J&&!Qe(J.generation)){_t.current.delete(fe),Se();return}if(!J&<()){Se();return}if(J&&!ce(J.generation)){Se();return}J||(ce(),Dt.current=!1);let z=p.expressPaymentType??J?.method??gt.current,Pn=J??null,Wn=Rc(z),Zt;z==="apple_pay"?Zt="apple_pay":z==="google_pay"&&(Zt="google_pay");let zt=J?.generation??_.current,pt=H,Ln=pt?.now()??globalThis.performance?.now()??Date.now(),An=new AbortController,Qt=!1,Vn=!1,yt=null,Pr=e,Vt="processing",rr="other",Un="provider_runtime",zn,Ht=new Promise((Me,it)=>{zn=it}),un=window.setTimeout(()=>{Qt=!0,An.abort(),zn(si)},hp),Hn=async(Me,it,Rn)=>{Vt=Me,rr=it,Un=it==="intent_create"||it==="session_claim"?"transport_error":"provider_runtime";let qt=pt?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Rn,Ht])}finally{let en=pt?.now()??globalThis.performance?.now()??Date.now();pt?.performance({stage:Me,durationMs:Math.max(0,en-qt),durationMode:"machine",requestCategory:it,paymentMethodCategory:"wallet",provider:"stripe",...Qt?{statusClass:"timeout"}:{}})}};try{if(qe(!0),l?.(null),!Pn&&I){let X=await Hn("processing","other",I(Wn));if(!X.proceed){Se();return}Pn={accountPatch:X.accountPatch,sessionId:X.sessionId,nonce:X.nonce}}let Me=Pn?.sessionId??e;Pr=Me;let it=Pn?.nonce??t,Rn=ht.current??Pn?.accountPatch,qt=Lc({event:p,fallbackEmail:Rn?.email??n,fallbackName:[Rn?.firstName,Rn?.lastName].join(" ").trim()||N});if(!Tn(qt.email)){Se("Buyer details are required."),ee(ds(z),qt).then(X=>{X&&(ht.current=X)});return}ht.current=null;let en={...Pn?.accountPatch,...fr(qt,!0)};await Hn("processing","session_claim",Promise.resolve(ue?.(qt)));let{error:pn}=await Hn("tokenization","provider_sdk",Xe.submit());if(pn){Se(),f(z,pn,"stripe_wallet_submit_failed",J?.generation);return}if(!Me)throw new Error("Missing sessionId or email for payment.");let Kt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:z,paymentMethodId:null,intentKind:a},jt=JSON.stringify({sessionId:Me,nonce:it??"",request:Kt}),vn=Pe.current,ke=vn?.retryIdentity===jt?vn.authorizationAttemptId:np();Pe.current={authorizationAttemptId:ke,retryIdentity:jt};let tn=await Hn("processing","intent_create",ui(o,Ve,Me,it??"",{...Kt,authorizationAttemptId:ke},{signal:An.signal}));if(di(tn)){Se(),s({type:"card",paymentMethodType:z},{accountPatch:en,paymentMethodCategory:"wallet",sessionId:Me,nonce:it,settledProcessResponse:tn.response});return}if(tn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Cn=tn.clientSecret,xr=kp({createdAt:Date.now(),sessionId:Me,...it?{nonce:it}:{},clientSecret:Cn,providerObjectId:tn.providerObjectId,paymentMethodType:z,accountPatch:en});window.clearTimeout(un),Vn=!0,pt?.performance({stage:"callback",durationMs:Math.max(0,(pt?.now()??globalThis.performance?.now()??Date.now())-Ln),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let xn=pt?.now()??globalThis.performance?.now()??Date.now(),Bn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Zt?{walletType:Zt}:{},attempt:zt},vr=!1,Qn=null;pt?.log({name:"payment.provider_confirmation.started",...Bn}),yt=window.setTimeout(()=>{yt!==null&&$e.current.delete(yt),vr=!0;let X=pt?.now()??globalThis.performance?.now()??Date.now();pt?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Bn,operationOutcome:"watchdog_expired",durationMs:Math.max(0,X-xn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),pt?.flush?.().catch(()=>{}),Qn?.()},Pp),$e.current.add(yt);let nn=(X,Lt)=>{yt!==null&&(window.clearTimeout(yt),$e.current.delete(yt),yt=null);let q=pt?.now()??globalThis.performance?.now()??Date.now(),Et=Math.max(0,q-xn),mn=X;vr&&(X==="resolved"?mn="resolved_late":X==="returned_error"?mn="returned_error_late":mn="rejected_late");let Fn=Lt??(X==="resolved"?"approved":"provider_error");return pt?.log({name:"payment.provider_confirmation.returned",...Bn,operationOutcome:mn,terminalReason:Fn}),pt?.performance({...Bn,durationMs:Et,durationMode:"buyer",operationOutcome:mn,terminalReason:Fn}),{durationMs:Et,operationOutcome:mn,terminalReason:Fn}},G=!1,yn=!1,qn=X=>{if(!X||typeof X!="object")return null;let Lt=X;if(Lt.error)return null;let q=Lt.setupIntent??Lt.paymentIntent,Et=as(q??null,void 0,!!Lt.setupIntent);return Et.kind==="confirmed"?Et:null},U=X=>{if(G||J&&_.current!==J.generation)return;let Lt=qn(X);if(!Lt)return;if(xr&&!bc(Me,it,Cn)){G=!0;return}let{intentId:q,paymentMethodId:Et}=Lt;G=!0,yn=!0,Pe.current=null,Fe.current=null,E.current&&(O("idle"),qe(!1));let mn=`${Dc}:${Me}`;sn(mn,{createdAt:Date.now(),sessionId:Me,nonce:it,accountPatch:en,paymentMethodId:Et,providerIntentId:q,paymentMethodType:z});try{s({id:Et,type:"card",threeDSecureActionResultTokenId:q},{accountPatch:en,paymentMethodCategory:"wallet",sessionId:Me,nonce:it})}finally{sn(mn)}},vt=!1;Qn=async()=>{if(!(vt||G||yn)){vt=!0,E.current&&O("checking");try{let X=await Sc(R,Cn,$e.current);if(G||yn)return;let Lt=ns(Cn),q=as(X,tn.providerObjectId,Lt);if(q.kind==="confirmed"){U(Lt?{setupIntent:X}:{paymentIntent:X});return}if(q.kind==="terminal"){if(yn=!0,os(Me,it,Cn),Pe.current=null,Fe.current=null,!E.current)return;O("idle"),Se(),f(z,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",J?.generation,!0);return}E.current&&!yn&&(O("blocked"),qe(!1))}catch{E.current&&!yn&&(O("blocked"),qe(!1))}finally{vt=!1}}},Fe.current=Qn;let x,$t;try{he=!0,Ce.current+=1;let X;try{X=await(ns(Cn)?R.confirmSetup({elements:Xe,clientSecret:Cn,redirect:"if_required"}):R.confirmPayment({elements:Xe,clientSecret:Cn,redirect:"if_required"}))}finally{kt()}if(!X||typeof X!="object")throw new Pa(wp(X));if(x=X,!x.error&&!qn(x))throw new Pa("confirmation_result_unconfirmed");$t=nn(x.error?"returned_error":"resolved",x.error&&Ua(x.error)?"provider_declined":void 0)}catch(X){let Lt=X instanceof Pa?X.reason:void 0,q=Lt!==void 0,Et=nn(q?"returned_error":"rejected");if(pt?.error({...q?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:Lt}:Wi(X),...Bn,operationOutcome:Et.operationOutcome,durationMs:Et.durationMs,statusClass:"unknown",terminalReason:Et.terminalReason}),!E.current||G)return;await Qn?.();return}let rn=x.error;if(rn){if(!E.current||G)return;if(Ua(rn)){yn=!0,os(Me,it,Cn),Pe.current=null,Fe.current=null,O("idle"),_t.current.get(fe)===J&&_t.current.delete(fe);let X=rn.message??"Your payment was declined.";l?.(X),C?.(fn(Wn,X,{code:Co(rn),declineCode:Ni(rn)})),pi({billingApiUrl:o,sessionId:Me,nonce:it,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:z,providerDeclineReason:Co(rn)??"provider_declined",...tn.intentKind==="payment"&&tn.providerObjectId.startsWith("pi_")?{providerIntentId:tn.providerObjectId}:{}}})}else pt?.error({...Wi(rn),...Bn,operationOutcome:$t.operationOutcome,durationMs:$t.durationMs,statusClass:"unknown",terminalReason:$t.terminalReason}),await Qn?.();return}if(U(x),!G)throw new Error("Invalid provider returned for APM intent")}catch(Me){if(Me===si){let it=pt?.now()??globalThis.performance?.now()??Date.now();pt?.error({errorCode:Rp(rr),stage:Vt,requestCategory:rr,paymentMethodCategory:"wallet",provider:"stripe",...Zt?{walletType:Zt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Pr,durationMs:Math.max(0,it-Ln),statusClass:"timeout",failureCategory:Un,attempt:zt,terminalReason:"provider_error"}),pt?.flush?.().catch(()=>{})}Se(),f(z,Me,Me===si?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",J?.generation,Me===si)}finally{if(window.clearTimeout(un),yt!==null&&(window.clearTimeout(yt),$e.current.delete(yt)),!Vn){let Me=pt?.now()??globalThis.performance?.now()??Date.now();pt?.performance({stage:"callback",durationMs:Math.max(0,Me-Ln),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Qt?{statusClass:"timeout"}:{}})}E.current&&qe(!1)}},[R,Xe,e,t,n,N,ee,ue,o,Ve,a,s,l,C,I,f,kt,ce,Qe,lt,_,H,fe]),be=wt(()=>wl(i),[i]),we=wt(()=>i.map(cp),[i]),Ot=wt(()=>u(Fc,{onReady:p=>{ot(Li(p,we))},onLoadError:p=>{ot("load_error"),fs(H,"stripe","wallet","provider_error")},onClick:async p=>{let Oe=H?.now()??globalThis.performance?.now()??Date.now();gt.current=p.expressPaymentType,Ee.current=Rc(p.expressPaymentType);let he=!0,Se=window.setTimeout(()=>{he=!1,p.reject(),P(p.expressPaymentType)},fp),J=I?await I(Ee.current,{abandoned:()=>!he}):{proceed:!0};if(window.clearTimeout(Se),!he)return;if(!J.proceed){_t.current.delete(fe),p.reject();return}let z=Pt(p.expressPaymentType);Dt.current=!1,He.current={generation:z,startedAt:Oe},_t.current.set(fe,{generation:z,method:p.expressPaymentType,accountPatch:J.accountPatch,sessionId:J.sessionId,nonce:J.nonce}),_e(!1),H?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:z,...p.expressPaymentType==="apple_pay"||p.expressPaymentType==="google_pay"?{walletType:p.expressPaymentType}:{}}),m?.(Ee.current),p.resolve()},onConfirm:Ke,onCancel:()=>{let p=_t.current.get(fe);_t.current.delete(fe);let Oe=He.current,he=H?.now()??globalThis.performance?.now()??Date.now();if(p&&Oe?.generation===p.generation&&Qu({method:p.method,elapsedMs:he-Oe.startedAt,handoffObserved:In.current===p.generation})){H?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:p.generation,walletType:"google_pay"}),Pe.current=null,f(p.method,new Error("The browser window is too small for the Google Pay sheet."),Bc,p.generation,!0);return}H?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...p?{attempt:p.generation}:{}}),h(p?.generation),Pe.current=null,_e(!1),De.current=!0,de()},options:{...kl,paymentMethods:be,emailRequired:It,billingAddressRequired:It}},fe),[we,be,Ke,h,m,It,f,P,de,I,Pt,fe,H]);return Je(Lo,{children:[u(Ui,{state:Ne,placeholderTestId:"flopay-wallet-placeholder",borderRadius:Be,children:Je("div",{ref:ut,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Y&&Je("button",{ref:at,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ve,style:cs,children:["Try ",ds(je)," again"]}),se!=="idle"&&Je("div",{role:"status","aria-live":"polite",children:[u("p",{children:"We are still confirming your payment. Check its status before trying again."}),u("button",{type:"button",onClick:et,disabled:se==="checking",style:cs,children:se==="checking"?"Checking payment status\u2026":"Check payment status"})]}),st&&u(To,{identity:st.identity,methodLabel:st.methodLabel,onComplete:Bt,onCancel:()=>Bt(null)},st.id),Je("div",{style:{display:st||se!=="idle"?"none":void 0},children:[u(qp,{active:pe}),Ot]})]})}),ze&&u(Rr,{status:"processing"})]})}function Uc(e,t,n){let o=Ac(n,t,"inline_apm");return{...e,allowedPaymentMethodTypes:[t],...o?{setupFutureUsage:o}:null}}function us({method:e,sessionId:t,nonce:n,email:o,billingName:a,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:m,onDecline:C,onCancel:T,runBeforeButtonClick:I,onButtonClick:N,isProcessing:ue,submitButtonColor:L,submitButtonBorderRadius:Be,submitButtonStyle:K,errorText:g}){let S=Gr(),{emitInstrument:Ve}=Uo(lr),R=ys(),Xe=ps(),[H,Ne]=le(!1),ot=V(!1),[ze,qe]=le(!1),[It,st]=le("loading"),[ee,Bt]=le(""),ut=!Tn(o?.trim()),at=!ut||Tn(ee.trim()),fe=Te(async()=>{if(!R||!Xe||ue||ot.current||!ze)return;ot.current=!0,Ne(!0);let ie=I?await I("card"):{proceed:!0};if(!ie.proceed){ot.current=!1,Ne(!1);return}N?.("card");let pe=ie.sessionId??t,ft=ie.nonce??n,Ft=la(a?.trim()),Ze=fr({email:ie.accountPatch?.email?.trim()||o?.trim()||ee.trim(),firstName:ie.accountPatch?.firstName?.trim()||Ft.firstName,lastName:ie.accountPatch?.lastName?.trim()||Ft.lastName}),Y=Ze.email,_e=fr({...ie.accountPatch,...Ze});try{if(m?.(null),!Tn(Y))throw new Error("A valid email address is required for payment.");await i?.(Ze);let se=await Xe.submit();if(se.error){m?.(se.error.message??"Payment failed.");return}let O=[Ze.firstName,Ze.lastName].filter(Boolean).join(" "),je=await R.createPaymentMethod({elements:Xe,params:{billing_details:{email:Y,...O?{name:O}:{}}}});if(je.error||!je.paymentMethod){m?.(je.error?.message??"Failed to create payment method.");return}let Le=je.paymentMethod;if(!pe||!Y)throw new Error("Missing sessionId or email for payment.");let Fe=Le.type||e,E=await ui(s,Ve,pe,ft??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Fe,paymentMethodId:null,intentKind:"payment"});if(di(E)){l({type:"card",gateway:"stripe",paymentMethodType:Fe},{accountPatch:_e,paymentMethodCategory:"apm",sessionId:pe,nonce:ft,settledProcessResponse:E.response});return}if(E.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let De=E.clientSecret;sn(Mr,{clientSecret:De,sessionId:pe,nonce:ft,accountPatch:_e,paymentMethodId:Le.id,paymentMethodType:Le.type??e,gateway:"stripe"});let{error:gt,paymentIntent:Ee}=await R.confirmPayment({clientSecret:De,confirmParams:{return_url:window.location.href,payment_method:Le.id},redirect:"if_required"});if(gt){sn(Mr);let $e=gt.message??"Payment failed.";m?.($e),C?.(fn("card",$e,{code:gt.code})),await pi({billingApiUrl:s,sessionId:pe,nonce:ft,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:gt.code??"provider_declined"}});return}let ht=Ee?.status;if(!ia(ht)){sn(Mr);let $e=ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.($e),C?.(fn("card",$e,{code:ht??"missing_payment_intent"}));return}sn(Mr);let Pe=typeof Ee?.payment_method=="string"?Ee.payment_method:Ee?.payment_method?.id;l({id:Pe??Le.id,type:"card",threeDSecureActionResultTokenId:Ee?.id,gateway:"stripe",paymentMethodType:Le.type??e},{accountPatch:_e,paymentMethodCategory:"apm",sessionId:pe,nonce:ft})}catch(se){m?.(se instanceof Error?se.message:"Payment failed. Please try again.")}finally{ot.current=!1,Ne(!1)}},[R,Xe,ue,ze,I,N,t,n,o,a,ee,i,s,Ve,e,l,m,C]);return Je("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ut&&u("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ut&&Je("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",u("input",{type:"email",autoComplete:"email",required:!0,value:ee,onChange:ie=>Bt(ie.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),u(up,{onReady:()=>st("ready"),onLoadError:()=>{st("load_error"),fs(gn(S),"stripe","apm")},onChange:ie=>{qe(!!ie.complete)},options:{layout:Il,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...Tn(o?.trim())?{email:o?.trim()}:{}}}}}),u(Rl,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{fe()},disabled:!ze||!at||H||ue||It!=="ready",color:L,borderRadius:Be,style:K,children:H?"Processing\u2026":`Pay with ${va(e)}`}),g&&u(xo,{margin:"0.75rem 0 0",children:g})]})}function Tc({sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:m,futureUseSession:C,onTokenizedBody:T,onErrorChange:I,onButtonClick:N,onDecline:ue,runBeforeButtonClick:L,onLoadStateChange:Be,isProcessing:K=!1,submitButtonColor:g="#4A49FF",submitButtonBorderRadius:S=8,submitButtonStyle:Ve,buttonAppearance:R,themeId:Xe,onExpandApm:H,expandedApmMethod:Ne}){let{emitInstrument:ot}=Uo(lr),[ze,qe]=le(null),[It,st]=le(null),ee=V(!1),{request:Bt,collect:ut,finish:at}=Eo();mt(()=>{s.length>0&&l?Be?.("ready"):l||Be?.("loading")},[s.length,l,Be]);let fe=Te(async Y=>{if(!l||ee.current||K)return;ee.current=!0,st(Y);let _e=L?await L("card"):{proceed:!0};if(!_e.proceed){ee.current=!1,st(null);return}N?.("card");let se=_e.sessionId??e,O=_e.nonce??t,je=la([_e.accountPatch?.firstName,_e.accountPatch?.lastName].filter(Boolean).join(" ")||o),Le=fr({email:_e.accountPatch?.email?.trim()||n?.trim(),firstName:_e.accountPatch?.firstName?.trim()||je.firstName,lastName:_e.accountPatch?.lastName?.trim()||je.lastName});if(!Tn(Le.email)){st(null);let De=await ut(va(Y),Le);if(!De){ee.current=!1;return}Le=De,st(Y)}let Fe=Le.email,E=fr({..._e.accountPatch,...Le});try{if(I?.(null),!se||!Tn(Fe))throw new Error("Missing sessionId or email for payment.");await a?.(Le);let De=await ui(i,ot,se,O??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Y,paymentMethodId:null,intentKind:"payment"});if(di(De)){T({type:"card",gateway:"stripe",paymentMethodType:Y},{accountPatch:E,paymentMethodCategory:"apm",sessionId:se,nonce:O,settledProcessResponse:De.response});return}if(De.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let gt=De.clientSecret;sn(Mr,{clientSecret:gt,sessionId:se,nonce:O,accountPatch:E,paymentMethodType:Y,gateway:"stripe"});let{error:Ee,paymentIntent:ht}=await l.confirmPayment({clientSecret:gt,confirmParams:{return_url:window.location.href,payment_method_data:{type:Y,billing_details:{name:[Le.firstName,Le.lastName].filter(Boolean).join(" "),...Fe?{email:Fe}:{}}}},redirect:"if_required"});if(Ee){sn(Mr);let He=Ee.message??"Payment failed.";I?.(He),ue?.(fn("card",He,{code:Ee.code})),await pi({billingApiUrl:i,sessionId:se,nonce:O,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Y,providerDeclineReason:Ee.code??"provider_declined"}});return}let Pe=ht?.status;if(!ia(Pe)){sn(Mr);let He=Pe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";I?.(He),ue?.(fn("card",He,{code:Pe??"missing_payment_intent"}));return}sn(Mr);let $e=typeof ht?.payment_method=="string"?ht.payment_method:ht?.payment_method?.id;T({id:$e??ht?.id,type:"card",threeDSecureActionResultTokenId:ht?.id,gateway:"stripe",paymentMethodType:Y},{accountPatch:E,paymentMethodCategory:"apm",sessionId:se,nonce:O})}catch(De){I?.(De instanceof Error?De.message:"Payment failed. Please try again.")}finally{ee.current=!1,st(null)}},[l,K,L,N,e,t,n,ut,i,ot,o,a,T,I,ue]),[ie,pe]=le(null),ft=H?Ne??null:ie,Ft=Te(Y=>{ee.current||K||ft&&ft!==Y||(hc(Y)?H?H(Y):pe(Y):fe(Y))},[ft,K,fe,H]),Ze=wt(()=>ie?Uc(m,ie,C):null,[ie,m,C]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Bt?u(To,{identity:Bt.identity,methodLabel:Bt.methodLabel,onComplete:at,onCancel:()=>at(null)},Bt.id):s.map(Y=>{let _e=Ne===Y,se=It===Y,O=It!==null&&It!==Y||Ne!=null&&Ne!==Y;return Je(pp.Fragment,{children:[u(Sl,{method:Y,themeId:Xe,submitting:se,disabled:O,highlighted:_e,hasNextStep:hc(Y),onClick:()=>Ft(Y),backgroundColor:R?.backgroundColor,borderColor:R?.borderColor,textColor:R?.textColor,borderRadius:R?.borderRadius,fontFamily:R?.fontFamily}),!H&&ie===Y&&Ze&&l&&u(lo,{stripe:l,options:Ze,children:u(us,{method:Y,sessionId:e,nonce:t,email:n,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:T,onErrorChange:I,onDecline:ue,onCancel:()=>pe(null),runBeforeButtonClick:L,onButtonClick:N,isProcessing:K,submitButtonColor:g,submitButtonBorderRadius:S,submitButtonStyle:Ve})},Y)]},Y)})})}function jp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:o,email:a,userId:i,onComplete:s,onError:l,onDecline:m,onCancel:C,onTokenizedBody:T,firstName:I,lastName:N,chv:ue,className:L,submitLabel:Be,isProcessing:K,error:g,onErrorChange:S,showPayPal:Ve=!0,showStripe:R=!0,walletPresentation:Xe="auto",enabledPaymentMethods:H,enabledPaymentMethodCountries:Ne,showApplePay:ot=!0,showGooglePay:ze=!0,layout:qe="default",theme:It,buttonsTheme:st,buttonsStyles:ee,appearance:Bt,cardButtonContent:ut,cardBackButtonContent:at,cardTitleContent:fe,showSecurityFooter:ie,onButtonClick:pe,onBeforeButtonClick:ft,onBuyerIdentityReady:Ft,enableAVS:Ze,cardFieldOrder:Y,cardPreFormSlot:_e,avsLayout:se="row",country:O,zip:je,addressLine1:Le,addressLine2:Fe,city:E,state:De,onCountryChange:gt,onZipChange:Ee,avsCheck:ht,checkoutType:Pe,checkoutLayout:$e,totalAmount:He=0,currency:In="usd",initialCardOpen:_t=!1,directPaypal:Pt,isSubscription:ce=!1,session:h,dataAttachmentPending:lt=!1,dataAttachmentRequiresIdentity:Qe=!1,debug:_=!1}){let Ce=Gr(),Dt=Vi(),de=Uo(mr),{emitInstrument:kt}=Uo(lr),f=V(null);f.current||(f.current=Ha());let P=f.current,[,ge]=le(0),ve=V(null);ve.current||(ve.current=ra());let et=ve.current,Ke=wt(()=>({browser:et,capability:P,presentationMode:"popup"}),[et,P]),be=h??de.session,we=wt(()=>({futureUse:be?.futureUse,futureUseUnsupported:be?.futureUseUnsupported}),[be?.futureUse,be?.futureUseUnsupported]),Ot=be?.gateways?.paypal?.providerObjectType??Pt?.providerObjectType,p=lt||de.claimPending===!0,Oe=Qe||de.claimRequiresIdentity===!0,he=p&&!Oe,Se=Gl(),J=n||Se,[z,Pn]=le(!1),[Wn,Zt]=le(null),[zt,pt]=le(O??""),[Ln,An]=le(je??""),[Qt,Vn]=le(Le??""),[yt,Pr]=le(Fe??""),[Vt,rr]=le(E??""),[Un,zn]=le(De??""),[Ht,un]=le(""),[Hn,Me]=le({}),it=V(je??""),Rn=V(O??""),qt=V(Le??""),en=V(Fe??""),pn=V(E??""),Kt=V(De??""),jt=V(""),vn=V({});mt(()=>{let r=(y,M,oe,A,ae)=>{if(vn.current[y])return;let xt=M?.trim();!xt||xt===oe.current||(oe.current=xt,A(xt),ae?.(xt))};r("country",O,Rn,pt,gt),r("zip",je,it,An,Ee),r("addressLine1",Le,qt,Vn),r("addressLine2",Fe,en,Pr),r("city",E,pn,rr),r("state",De,Kt,zn)},[O,je,Le,Fe,E,De,gt,Ee]);let ke=wt(()=>op(Ze),[Ze]),tn=ke!==null,Cn=wt(()=>ts(h),[h]),xr=Ju(h?.vault),xn=!!h?.gateways?.pcivault,Bn=jl(h),Qn=!!(h?.gateways?.stripe?.enabledPaymentMethods??H)?.includes("card")||oo(h),nn=xr||Qn||xn,G=!!(R&&nn&&e),[yn,qn]=le(()=>qe!=="buttons"||_t?e??null:null),[U,vt]=le(0),x=qe!=="buttons"||_t||!!e&&yn===e,$t=h?.captureMethod,rn=V(Ce);mt(()=>{rn.current=Ce},[Ce]);let[X,Lt]=le(null);mt(()=>{if(!G||!e||!x){Lt(null);return}let r=rn.current?rn.current.cardCapture({sessionId:e,captureMethod:$t}):new Fu({sessionId:e,captureMethod:$t,billingApiUrl:J,telemetry:o});return Lt({sessionId:e,captureMethod:$t,billingApiUrl:J,telemetry:o,capture:r}),()=>{r.unmount()}},[G,e,x,$t,J,o]);let q=G&&e&&x&&X?.sessionId===e&&X.captureMethod===$t&&X.billingApiUrl===J&&X.telemetry===o?X.capture:null,Et=wt(()=>{let r=zt,y=ke?Jt(ke.postal_code,r):!1;return Np(r,Ln,y)},[ke,zt,Ln]),{avsInvalid:mn,invalidAvsFields:Fn}=wt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!G||!ke)return{avsInvalid:!1,invalidAvsFields:r};let y=zt,M=(ae,xt)=>Jt(ae,y)&&!xt.trim(),oe={line1:M(ke.address_line_1,Qt),city:M(ke.city,Vt),state:M(ke.state,Un),zip:Et.empty||Et.malformed};return{avsInvalid:oe.line1||oe.city||oe.state||oe.zip,invalidAvsFields:oe}},[G,ke,zt,Qt,Vt,Un,Et]),[Gt,Cr]=le(!1),[Br,br]=le(!1),[Sr,Fr]=le(!1),[$r,Wr]=le({line1:!1,city:!1,state:!1}),_n=V(!1),Dr=V({email:!1,line1:!1,city:!1,state:!1,zip:!1}),or=V(!1),At=Te(r=>{Dr.current[r]=!0,or.current=!0},[]),Kn=Te(r=>!_n.current&&Dr.current[r],[]),Gn=Te(r=>{Kn(r)&&Wr(y=>y[r]?y:{...y,[r]:!0})},[Kn]),[er,Yn]=le(()=>rs(h?.vault,{billingApiUrl:J,sessionId:e,nonce:t})),[Ue,ln]=le(_t&&nn?"card":"buttons"),[on,jn]=le(null),Qr=Ue==="expanding"||Ue==="card",Or=h?.gateways?.stripe&&!Bn?"stripe":void 0,dr=Te(()=>{kt?.({class:"card_surface",provider:Or})},[Or,kt]),tr=V(null),bn=Te(r=>{tr.current&&clearTimeout(tr.current),tr.current=setTimeout(()=>{tr.current=null,r()},Ca)},[]);mt(()=>()=>{tr.current&&clearTimeout(tr.current)},[]);let Nr=V(!1),[Dn,w]=le(0),k=V(null),j=Te(()=>{dr(),qn(e??null),Nr.current&&(Nr.current=!1,w(r=>r+1)),vt(r=>r+1),ln("expanding"),bn(()=>ln("card"))},[bn,dr,e]),te=Te(()=>{ln("collapsing"),bn(()=>ln("buttons"))},[bn]),We=Te(r=>{jn(r),ln("apm-expanding"),bn(()=>ln("apm-form"))},[bn]),Wt=Te(()=>{ln("apm-collapsing"),bn(()=>{ln("buttons"),jn(null)})},[bn]);mt(()=>{qe==="buttons"&&_t&&nn&&(qn(e??null),ln("card"))},[qe,_t,nn,e]);let[ne,W]=le(null),B=V(!1),Z=V(null),F=V("idle"),[Ae,D]=le(!1),Ie=V(Ae);Ie.current=Ae;let[Re,Ct]=le(()=>Pt?.existingOrderId?{orderId:Pt.existingOrderId,attempts:1}:null),Sn=V(Re);mt(()=>{Sn.current=Re},[Re]);let d=V(null),c=wt(()=>{if(Ft||de.claimBuyerIdentity||h?.buyerIdentified!==!1||!e||!t)return;let r=`${J}|${e}|${t}`;d.current?.key!==r&&(d.current={key:r,claim:Io(new No(J,{telemetry:!1}),e,t,{...i?{userId:i}:{},...I?{firstName:I}:{},...N?{lastName:N}:{}})});let y=d.current.claim;return async M=>{await y(M)}},[Ft,de.claimBuyerIdentity,h?.buyerIdentified,e,t,J,i,I,N]),v=Ft??de.claimBuyerIdentity??c,Q=g??Wn,re=wt(()=>ip(It),[It]),b=wt(()=>{let r=re?.buttonsLayout??ap(st);return ee?{...r,...ee,cardButton:{...r.cardButton,...ee.cardButton},cardFormContainer:{...r.cardFormContainer,...ee.cardFormContainer},backButton:{...r.backButton,...ee.backButton},backButtonIcon:{...r.backButtonIcon,...ee.backButtonIcon},submitButton:{...r.submitButton,...ee.submitButton},title:{...r.title,...ee.title}}:r},[re,st,ee]),tt=Bt??re?.appearance,cn=wt(()=>ju({appearance:tt,buttonsStyles:b,layout:qe}),[tt,b,qe]),wn=de.inlineSessionPatchProcessing??!1,nt=(K??z)||wn,nr=J.replace(/\/+$/,""),$=wt(()=>$i({userId:i,email:a,firstName:I,lastName:N,country:O,zip:je},Hn),[i,a,I,N,O,je,Hn]),Ge=[$.firstName,$.lastName].filter(r=>!!r?.trim()).join(" "),ct=!Tn($.email?.trim()),bt=V(null);G&&bt.current===null&&(bt.current=ct);let xe=G&&(bt.current??ct),$n=wt(()=>Lp(Ht,xe),[Ht,xe]),Rt=$n.empty||$n.malformed,On=wt(()=>Ce?Ce.getRawProvider():null,[Ce]),Es=wt(()=>Dt?Dt.getRawProvider():null,[Dt]),Wo=He||100,uo=In.toLowerCase(),hi=wt(()=>tt?Du(tt):null,[tt]),po=hi,Ts=wt(()=>{let r=hi??{},y=r.rules??{};return{...r,rules:{...y,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...y[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...y[".AccordionItemContents"]??{}}}}},[hi]),Ms=wt(()=>({...ql(He,be?.captureMethod,we),currency:uo,...po?{appearance:po}:null}),[He,uo,be?.captureMethod,we,po]),Pi=Ac(we,"paypal","paypal"),As=wt(()=>({mode:"payment",amount:Wo,currency:uo,captureMethod:"manual",...Pi?{setupFutureUsage:Pi}:null,...po?{appearance:po}:null}),[Wo,uo,Pi,po]),me=Te(r=>{Zt(r),S?.(r)},[S]),xs=V(0);mt(()=>{Dn!==xs.current&&(xs.current=Dn,me(null))},[Dn,me]);let vi=V(""),[Bs,ed]=le(!1),Ci=Te(()=>{ed(!0)},[]);mt(()=>{if(!G||!xe||!v||!Bs||Rt||vi.current)return;let r=fr({email:Tn($.email?.trim())?$.email?.trim():jt.current.trim(),firstName:$.firstName?.trim(),lastName:$.lastName?.trim()});vi.current=JSON.stringify(r),Me(y=>({...y,...r})),Promise.resolve(v(r)).catch(y=>{vi.current="",me(y instanceof Error?y.message:"Failed to attach buyer details.")})},[G,xe,v,Bs,Rt,$.email,$.firstName,$.lastName,me]),mt(()=>{!G||!q||q.setCardFieldOrder?.(Y??null,ke==null&&!xe)},[G,q,Y,ke,xe]),mt(()=>{(Ue==="expanding"||Ue==="collapsing"||Ue==="apm-expanding"||Ue==="apm-collapsing")&&me(null)},[Ue,me]);let wr=Te((r,y,M)=>{m?.(fn(r,y,M))},[m]),Fs=V(Ue);Fs.current=Ue;let[Ds]=le(Ga),Os=Te(()=>{let r=Fs.current;if(qe==="buttons"&&(r==="card"||r==="expanding"))return!0;let y=F.current;return y==="validation-window"||y==="processing"||Ie.current},[qe]),Ns=Te((r,y,M)=>{Ds.take(e)&&gn(Ce)?.log(so({...Ke,presentationMode:M?.presentationMode??"popup"},{name:Ka,stage:"recovery",reason:"other_method_active",provider:M?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:M?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet")}))},[Ke,Ce,Ds,e]),Ia=Te((r,y,M)=>{M?.telemetryReported||gn(Ce)?.error(so({...Ke,presentationMode:M?.presentationMode??"popup"},{errorCode:y?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:M?.provider??(r==="paypal"?"paypal":"stripe"),paymentMethodCategory:M?.paymentMethodCategory??(r==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:M?.terminalReason??(y?"popup_blocked":"provider_error")}))},[Ke,Ce]),yo=Te((r,y,M)=>{let oe=M?.popupBlocked??Vr(y);if(Os()){Ia(r,oe,M),Ns(r,y,M);return}if(y instanceof Tr&&y.code==="checkout_processing_timeout"){Ia(r,!1,M),W(null),qe==="buttons"&&(ln("buttons"),jn(null)),me(y.message),l?.(y);return}oe&&P.markBlocked()&&ge(dt=>dt+1);let A=ds(r),ae=M?.code===Bc?Lu(A):La(A,oe,et.inAppBrowser),xt=Co(y),ir=(xt?.toLowerCase()==="error"?void 0:xt)??Cl(M?.code)??"external_payment_method_failed",Ye=new Tr(ae,"api_error",{code:"external_payment_method_failed",param:r,details:{providerCode:ir,popupBlocked:oe,inAppBrowser:et.inAppBrowser,appFamily:et.appFamily,popupCapability:P.current(),presentationMode:M?.presentationMode??"popup"}});Ia(r,oe,M),W(null),qe==="buttons"&&(ln("buttons"),jn(null)),me(ae),l?.(Ye),console.error("[FloPay] External payment method failed:",{method:r,code:ir,popupBlocked:oe})},[et,Os,qe,l,P,Ns,Ia,me]);mt(()=>{if(!G||!e){Yn(null);return}let r={billingApiUrl:nr,sessionId:e,nonce:t},y=rs(h?.vault,r);if(y){Yn(y);return}if(!x){Yn(null);return}let M=`${nr}\0${e}\0${t??""}`,oe=k.current;if(oe&&oe.key===M){Yn(oe.mount);return}Yn(null);let A=!0;return new No(nr).getVaultCapture(e,t).then(ae=>{if(!A)return;let xt=rs(ae,r);xt?.verificationRequired&&!ae.html&&(k.current={key:M,mount:xt}),xt?Yn(xt):me("Failed to load the secure card form.")}).catch(ae=>{A&&me(ae instanceof Error?ae.message:"Failed to load the secure card form.")}),()=>{A=!1}},[G,x,U,e,h?.vault,nr,t,me]);let ur=V({onComplete:s,onError:l,updateError:me,emitDecline:wr,resolvedAccount:$,avsConfig:ke,avsCheckProp:ht,sessionId:e,nonce:t,baseUrl:nr,captureMethod:h?.captureMethod,paymentId:h?.paymentId,authorizationExpiresAt:h?.authorizationExpiresAt,serverSideCardGateway:Bn});ur.current={onComplete:s,onError:l,updateError:me,emitDecline:wr,resolvedAccount:$,avsConfig:ke,avsCheckProp:ht,sessionId:e,nonce:t,baseUrl:nr,captureMethod:h?.captureMethod,paymentId:h?.paymentId,authorizationExpiresAt:h?.authorizationExpiresAt,serverSideCardGateway:Bn};let bi=V(!1),Ls=Te(()=>{let r=ur.current,y=r.resolvedAccount.email?.trim(),M=Tn(y)?y:jt.current.trim();if(!Tn(M))return null;let oe=r.resolvedAccount.firstName?.trim(),A=r.resolvedAccount.lastName?.trim(),ae=Rn.current.trim()||r.resolvedAccount.country?.trim()||"",xt=r.avsConfig?Jt(r.avsConfig.state,ae):!1,ir=r.avsConfig?Jt(r.avsConfig.address_line_1,ae):!1,Ye=r.avsConfig?Jt(r.avsConfig.postal_code,ae):!1,dt=r.avsConfig?Jt(r.avsConfig.city,ae):!1,St=r.avsConfig?Jt(r.avsConfig.address_line_2,ae):!1,En=ir&&!xt&&Ye?Ku(ae,(it.current??"").trim()):null,yr=xt?Kt.current:En;return{accountData:{userId:r.resolvedAccount.userId??"",email:M,...oe?{firstName:oe}:{},...A?{lastName:A}:{},...Ye&&it.current?{zip:it.current}:{},...dt&&pn.current?{city:pn.current}:{},...yr?{state:yr}:{},...ir&&qt.current?{addressLine1:qt.current}:{},...St&&en.current?{addressLine2:en.current}:{},...ae?{country:ae}:{}},...r.avsCheckProp===void 0?{}:{avsCheck:r.avsCheckProp},...r.avsConfig?{avsConfig:{country:Jt(r.avsConfig.country,ae),postal_code:Ye,address_line_1:ir,address_line_2:St,city:dt,state:xt}}:{}}},[]),Us=V(p);Us.current=p,mt(()=>{p||Q!==wc||ur.current.updateError(null)},[p,Q]),mt(()=>{!G||!q||q.setSubmitGate?.(mn||p||Rt||Ae)},[G,q,mn,p,Rt,Ae]),mt(()=>{if(!G||!q)return;bi.current=!1;let r=null,y=()=>{r&&clearTimeout(r),r=setTimeout(()=>{r=null,F.current="idle",W(null)},400)},M=q.on("submitting",()=>{Cr(!0),Z.current&&clearTimeout(Z.current),F.current="validation-window",Z.current=setTimeout(()=>{Z.current=null,F.current==="validation-window"&&(F.current="processing")},_p),W("processing");let Ye=ur.current;if(!Ye.sessionId||!Ye.nonce)return;let dt=Ls();if(!dt){Ye.updateError("Enter a valid email address."),F.current="idle",W(null);return}new No(Ye.baseUrl).patchAccountSnapshot(Ye.sessionId,Ye.nonce,dt,{telemetryMode:"best_effort"}).catch(St=>{if(!Tp(St))return;let En=St instanceof Error?St.message:"Please check your billing address and try again.";Ye.updateError(En),F.current="idle",W(null),Ye.onError?.(St instanceof Tr?St:new Tr(En,"api_error"))})}),oe=q.on("complete",Ye=>{Bo(Ye.sessionId??ur.current.sessionId),F.current="terminal",D(!1),W("success"),setTimeout(()=>{if(bi.current)return;bi.current=!0;let dt=ur.current,St=ts(dt)||Ye.outcome==="authorized",En=dt.serverSideCardGateway?{}:{paymentIntentId:Ye.intentId};ur.current.onComplete?.(St?{status:"authorized",...En,paymentId:Ye.paymentId??dt.paymentId,sessionId:Ye.sessionId??dt.sessionId,authorizationExpiresAt:Ye.authorizationExpiresAt??dt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...En,checkoutMethod:"card"})},600)}),A=q.on("decline",Ye=>{let dt=ur.current,St=Ye.message??"Your payment was declined. Please try another card or contact your bank.";F.current="terminal",D(!1),dt.updateError(St),W("error");let En=Ye.failureOutcome??ep(Ye.declineReason)??"authorization_declined";dt.emitDecline("card",St,{code:En,declineCode:En}),y()}),ae=q.on("error",Ye=>{let dt=ur.current,St=Ye.message??"There was a problem processing your payment. Please try again.";F.current="terminal",D(!1),dt.updateError(St),W("error"),dt.onError?.(new Tr(St,"api_error",{code:Ye.failureOutcome??"capture_failed"})),y()}),xt=q.on("challenge_dismissed",()=>{Z.current&&(clearTimeout(Z.current),Z.current=null),F.current="processing",D(!0),W(null)}),ir=q.on("blocked",()=>{if(Ie.current){ur.current.updateError(Ep);return}if(!Us.current){Cr(!0);return}Ci(),ur.current.updateError(wc)});return()=>{r&&(clearTimeout(r),r=null),Z.current&&(clearTimeout(Z.current),Z.current=null),F.current="idle",D(!1),W(null),M(),oe(),A(),ae(),xt(),ir()}},[G,q,Ci,Ls]);let kr=!!Pt?.clientId,Vo=Array.isArray(H),Ra=Vo&&H.length>0,zs=Vo&&H.includes("paypal"),_a=V(null);_a.current===null&&(_a.current=Yu());let mo=_a.current?"redirect":bl(et,Xe,P.current()),{expressMethods:Ea,paymentElementMethods:Si}=wt(()=>tp(H,{excludePaypal:kr}),[H,kr]),qs=kr||!!Dt||zs&&mo==="redirect",td=wt(()=>qs?Ea.filter(r=>r!=="paypal"):Ea,[Ea,qs]),nd=wt(()=>{let r=[];return ot&&r.push("apple_pay"),ze&&r.push("google_pay"),r},[ot,ze]),fo=Vo?td:nd,rd=R&&fo.length>0,js=tn?zt:O,Ta=wt(()=>Vu(Si,js,Ne),[Si,js,Ne]),wi=wt(()=>({mode:"payment",amount:Wo,currency:uo,paymentMethodCreation:"manual",appearance:Ts}),[Wo,uo,Ts]),[$s,Ws]=le("loading"),[Vs,Hs]=le("loading"),[Ks,Gs]=le("loading"),[od,ki]=le(!1),[Ys,Ii]=le("loading"),[Ri,ad]=le();mt(()=>{ad(ra())},[]);let Ma=Ri?.inAppBrowser,Aa=Ri?za(Ri,Pt?.approvalPresentation,Ot??(ce?"subscription":"order")):"popup",Js=Ve&&(kr||(Vo?zs:Ma===!1)),id=et.inAppBrowser&&P.current()==="blocked",Xs=R&&rd&&!id,Ho=(!he||!!de.waitForDataAttachment)&&Js&&kr,Zs=Ys==="retrying"||Ys==="exhausted",Ko=null;R&&(Dt?Ko=Es:mo==="redirect"&&(Ko=On));let Qs=wt(()=>({...Ke,presentationMode:mo}),[Ke,mo]),Go=!he&&Js&&!!Ko&&(!kr||Zs),go=!he&&Xs&&!!On,Yo=!he&&R&&Ra&&Ta.length>0&&!!On,sd=Ho&&!Zs?od:Go&&zi($s),ld=go&&zi(Vs),cd=Yo&&Ks!=="load_error",el=r=>r==="loading"||r==="ready",tl=Ho||Go&&el($s)||go&&el(Vs)||Yo&&Ks!=="load_error",xa=V(!1);mt(()=>{if(!xa.current){if(!R&&!Ve){xa.current=!0;let r=new Tr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(r),me(r.message)}else if(!R&&Ve&&!kr){xa.current=!0;let r=new Tr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(r),me(r.message)}else if(Ma!==void 0&&!he&&!nn&&!tl){xa.current=!0;let r=new Tr("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(r),me(r.message)}}},[R,Ve,kr,Ma,he,nn,tl,l,me]);let nl=V(!1);mt(()=>{if(nl.current||!Ra)return;let r=[];ot!==!0&&r.push("showApplePay"),ze!==!0&&r.push("showGooglePay"),r.length!==0&&(nl.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Ra,ot,ze]);let rl=Te((r,y,M)=>de.applyInlineSessionPatch?de.applyInlineSessionPatch(r).then(oe=>({error:null,sessionId:oe.sessionId||e,nonce:oe.session?.clientSecret||t})).catch(oe=>{let A=Pc(y,oe);return M?.abandoned?.()||(me(A.message),l?.(A)),{error:A,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[de.applyInlineSessionPatch,t,l,e,me]),pr=Te(async(r,y)=>{if(r!=="card"&&he&&await de.waitForDataAttachment?.(),!ft)return{proceed:!0};try{let M=await ft({method:r,sessionId:e||void 0,createSession:de.inlineSessionDraft});if(M===!1)return{proceed:!1};if(M&&typeof M=="object"){M.account&&Me(A=>({...A??{},...M.account}));let oe=await rl(M,r,y);return oe.error?{proceed:!1,accountPatch:M.account}:{proceed:!0,accountPatch:M.account,sessionId:oe.sessionId,nonce:oe.nonce}}return{proceed:!0}}catch(M){if(!y?.abandoned?.()){let oe=Pc(r,M);me(oe.message),l?.(oe)}return{proceed:!1}}},[rl,de.inlineSessionDraft,de.waitForDataAttachment,he,ft,l,e,me]),ol=Te(async(r,y)=>{if(B.current)return;B.current=!0,Pn(!0),W("processing"),me(null);let M=y?.sessionId??e,oe=y?.nonce??t,A=$i($,y?.accountPatch),ae=y?.completionPaymentMethodId??sa(r),xt=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r,ir=Bp(r),Ye=y?.presentationMode?ii(gn(Ce),{...Ke,presentationMode:y.presentationMode}):void 0,dt=()=>{kt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ir}),Ye?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...gr,requestCategory:"process_payment"})};try{let St=new No(nr),yr=y?.settledProcessResponse??await St.processPayment(A.userId??"",{sessionId:M,nonce:oe,paymentMethodCategory:y?.paymentMethodCategory??Dp(r),tokenizedData:xt,accountData:{...y?.accountPatch,userId:A.userId??"",email:A.email??"",firstName:A.firstName||void 0,lastName:A.lastName||void 0,...Nu({avsConfig:ke,country:Rn.current,zip:it.current,city:pn.current,state:Kt.current,addressLine1:qt.current,addressLine2:en.current})},...Ou({chv:ue,avsCheck:ht,checkoutType:Pe,checkoutLayout:$e,avsConfig:ke,country:Rn.current})}),Na=async kn=>{let no=ts(h)||kn?.status==="authorized";Bo(M),Ye?.terminal({outcome:"payment_succeeded",...gr}),W("success"),Ct(null),await new Promise(ta=>setTimeout(ta,600));let Ir;typeof kn?.paymentId=="string"?Ir=kn.paymentId:h?.paymentId&&(Ir=h.paymentId);let ro;typeof kn?.authorizationExpiresAt=="string"?ro=kn.authorizationExpiresAt:h?.authorizationExpiresAt&&(ro=h.authorizationExpiresAt),s?.(no?{status:"authorized",...Ir===void 0?{}:{paymentId:Ir},sessionId:typeof kn?.sessionId=="string"?kn.sessionId:M,...ro===void 0?{}:{authorizationExpiresAt:ro},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ae,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:ae,checkoutMethod:r.isPaypal?"paypal":"card"})};if(yr.ok){await Na(yr.status===204?null:await yr.json().catch(()=>null));return}let dn=await yr.json().catch(()=>null);if(dn?.type==="paypal_redirect_required"){let kn=dn.threeDSecureToken,no=dn.paymentMethodId||r.id||"";if(!Ce||!kn){W("error"),me("PayPal authorization required but no token provided.");return}try{let Ir=Dt?.getRawProvider();if(!Ir){me("PayPal is not available.");return}let ro={return_url:window.location.href};no&&(ro.payment_method=no);let{error:ta}=await Ir.confirmPayment({clientSecret:kn,confirmParams:ro,redirect:"if_required"});if(ta){W("error");let gl=ta.message??"PayPal payment failed.";me(gl),wr("paypal",gl,{code:ta.code})}}catch(Ir){W("error"),me(Ir instanceof Error?Ir.message:"PayPal authorization failed.")}return}if(dn?.type==="paypal_direct_required"){let kn=dn.orderId;if(!kn){W("error"),me("PayPal retry required but no order id provided.");return}let no=Sn.current?.attempts??0;if(no>=2){W("error"),me("PayPal payment could not be completed after multiple attempts."),wr("paypal","paypal_direct_required retry limit exceeded");return}ki(!1),Ii("loading"),Ct({orderId:kn,attempts:no+1}),W(null);return}if(yr.headers.get(Cp)===bp){let kn=await Sp(St,M,oe);if(kn!==void 0){await Na(kn);return}}zu(yr.status,dn)?Ye?.terminal({outcome:"payment_declined",...gr,terminalReason:"provider_declined"}):dt(),W("error");let fl=dn?.message??"Payment failed. Please try again.";me(fl),wr(r.isPaypal?"paypal":"card",fl,{code:dn?.code??dn?.gatewayErrorCode,declineCode:dn?.declineCode??dn?.gatewayDeclineReason}),await new Promise(kn=>setTimeout(kn,400))}catch(St){Nc(St)||dt(),W("error"),me(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(En=>setTimeout(En,400))}finally{Pn(!1),W(null),B.current=!1}},[nr,e,t,$,ke,ht,Pe,$e,ue,Ce,Dt,h,s,me,wr,kt,Ke]),Jn=Te((r,y)=>{T&&!y?.settledProcessResponse?T(r):ol(r,y)},[T,ol]),Jo=`${Dc}:${e}`;mt(()=>{if(typeof window>"u")return;let r=localStorage.getItem(Jo);if(!r)return;let y;try{y=JSON.parse(r)}catch{sn(Jo);return}if(!y||typeof y.createdAt!="number"||Date.now()-y.createdAt<0||Date.now()-y.createdAt>Oc||typeof y.paymentMethodId!="string"||typeof y.providerIntentId!="string"||typeof y.paymentMethodType!="string"||y.sessionId!==e||!t||y.nonce!==t||!fo.includes(y.paymentMethodType)){sn(Jo);return}sn(Jo),Jn({id:y.paymentMethodId,type:"card",threeDSecureActionResultTokenId:y.providerIntentId,gateway:"stripe",paymentMethodType:y.paymentMethodType},{...y.accountPatch?{accountPatch:y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Jn,t,e,Jo,fo]);let al=V(!1);mt(()=>{if(typeof window>"u"||al.current)return;let[r,y,M]=Mc();if(!r||!y||_a.current||!Ce)return;let oe=Ce.getRawProvider();if(!oe)return;let A=dt=>{let St=localStorage.getItem(dt);if(!St)return null;try{return JSON.parse(St)}catch{return sn(dt),null}},ae=A(Mr)??A(Cc),xt;if(ae?.clientSecret){if(ae.clientSecret!==y)return;xt={...ae.accountPatch?{accountPatch:ae.accountPatch}:{},...ae.sessionId?{sessionId:ae.sessionId}:{},...ae.nonce?{nonce:ae.nonce}:{}}}else if(ae?.sessionId&&ae.sessionId!==e)return;al.current=!0,sn(Mr),sn(Cc),window.history.replaceState({},"",xc());let ir=ae?.paymentMethodType??ae?.tokenType??"card",Ye="card";(async()=>{if(M==="failed"){let dn="Payment was declined. Please try again.";me(dn),wr(Ye,dn);return}let{paymentIntent:dt,error:St}=await oe.retrievePaymentIntent(y);if(St){let dn=St.message??"Failed to retrieve payment status.";me(dn),wr(Ye,dn,{code:St.code});return}let En=dt?.status,yr=ia(En);if(!dt||!yr){let dn=En==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(dn),wr(Ye,dn,{code:En??"missing_payment_intent"});return}let Na=typeof dt.payment_method=="string"?dt.payment_method:dt.payment_method?.id;Jn({id:Na??ae?.paymentMethodId??ae?.tokenId??dt.id,type:"card",threeDSecureActionResultTokenId:dt.id,gateway:ae?.gateway??"stripe",paymentMethodType:ir},xt)})()},[e,Jn,Ce,me,wr]);let _i=Te(r=>{r.preventDefault()},[]);if(!(G||Ce!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Xo=qe==="buttons",Xn=tt?.variables,dd=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ei=Xn?.colorBackground,ud=Ei&&!dd.has(Ei)?Ei:void 0,Zo=b.cardInputBorder??(Xo?"#e5e7eb":"#A4A4FF"),il=Xn?.colorDanger??"#dc2626",Yt=r=>Fn[r]&&($r[r]||Gt),Ba=Rt&&(Sr||Gt),ar=r=>r?il:Zo,Fa=(Et.malformed||Et.empty)&&(Br||Gt),pd=ar(Fa),Ti=b.cardFormContainer?.backgroundColor??ud??(Xo?"white":"#EDEDFF"),ho=b.cardInputBackground??Xn?.colorBackground??"white",Mi=bo(at),sl=bo(fe),Po=b.nameInput,ll=b.cardInputFontSize??Up(Po?.fontSize)??Xn?.fontSizeBase??"16px",cl=typeof Po?.fontFamily=="string"?Po.fontFamily:Xn?.fontFamily??"Poppins, sans-serif",dl=dp(Po?.fontWeight)??400,yd=b.cardInputColor??(typeof Po?.color=="string"?Po.color:void 0)??Xn?.colorText??"#262833",md=b.cardInputPlaceholderColor??"#9ca3af",an=Xn?.borderRadius??"8px",eo=Xn?.borderRadius??b.cardButton?.borderRadius??an,to=Xn?.colorPrimary??"#4A49FF",fd=Xn?.colorPrimaryHover??$u(to,.12),Ai=Xn?.colorText??"#262833",xi={fontSize:ll,fontFamily:cl,fontWeight:dl,color:yd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Qo={marginTop:"0.375rem",...xi,fontSize:"0.75rem",lineHeight:1.4,color:il},gd={"--flopay-input-placeholder-color":md,"--flopay-input-font-size":ll,"--flopay-input-font-family":cl,"--flopay-input-font-weight":String(dl)},ea=b.cardFormContainer??{},Bi=ea.padding??(Xo?"0":"1rem"),Fi=ea.borderRadius??an,hd=q&&er?u(Di,{capture:q,html:er.html,messageToken:er.messageToken,expectedOrigin:er.expectedOrigin,verificationRequired:er.verificationRequired,theme:cn,submitLabel:Be,onReady:()=>{if(!xe&&!ke||typeof document>"u")return;let r=()=>{let M=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(M){_n.current=!0;try{M.focus()}finally{_n.current=!1}}};or.current||r()},onError:r=>{r&&er.verificationRequired&&F.current==="idle"&&(Nr.current=!0),me(r)},onValidation:r=>{let y=F.current;(y==="idle"||y==="validation-window")&&(me(r),r&&F.current==="validation-window"&&(Z.current&&(clearTimeout(Z.current),Z.current=null),F.current="idle",W(null)))}},Dn):u("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),ul=Je("div",{onFocusCapture:r=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(r.target.tagName)&&dr()},style:{backgroundColor:Ti,borderRadius:Fi,...ea,padding:Bi,...gd,display:"flex",flexDirection:"column"},children:[u("style",{children:`
|
|
5
5
|
.flopay-shared-input::placeholder {
|
|
6
6
|
color: var(--flopay-input-placeholder-color);
|
|
7
7
|
opacity: 1;
|
|
@@ -9,13 +9,13 @@ ${Re.join(`
|
|
|
9
9
|
font-family: var(--flopay-input-font-family);
|
|
10
10
|
font-weight: var(--flopay-input-font-weight);
|
|
11
11
|
}
|
|
12
|
-
`}),
|
|
13
|
-
`)}):null,
|
|
14
|
-
`)}):null,yl=Ne==="apm-expanding"||Ne==="apm-form"||Ne==="apm-collapsing",Co;Ne==="apm-expanding"?Co=vc:Ne==="apm-collapsing"&&(Co=Cc);let Da=tn?Fc(bi,tn,Ie):null;if(He==="buttons"){let r=Ne==="buttons"||Ne==="expanding"||Ne==="apm-expanding",y=Ne==="expanding"||Ne==="card"||Ne==="collapsing",T=ut===void 0?{boxSizing:"border-box",height:oa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ae;Ne==="expanding"||Ne==="apm-expanding"?ae=Ep:(Ne==="collapsing"||Ne==="apm-collapsing")&&(ae=Rp);let x;return Ne==="expanding"?x=vc:Ne==="collapsing"&&(x=Cc),Ze("form",{onSubmit:Ii,className:N,noValidate:!0,style:{position:"relative"},children:[c(za,{}),oe&&c(wr,{status:oe,errorMessage:le,authorized:Pn}),Ze("div",{style:{display:"grid"},children:[Ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!ae?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!ae?Tp:{},...ae?{animation:ae,pointerEvents:"none"}:{}},children:[ul("flopay-direct-paypal-gate-debug"),pl("flopay-stripe-gate-debug"),Ho&&Pt&&Ze(Lo,{children:[Rt&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(da.Provider,{value:v,children:c(Ya,{sessionId:e,nonce:t,billingApiUrl:Q,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,clientId:Pt.clientId,environment:Pt.environment,currency:wn.toUpperCase(),isSubscription:pe,providerObjectType:Dt,approvalPresentation:Ma==="popup"?void 0:Ma,onTokenizedBody:Kn,onComplete:s,onErrorChange:Pe,onDecline:u,onCancel:C,onTechnicalFailure:mo,onButtonClick:fe,runBeforeButtonClick:dr,isProcessing:G,onLoadStateChange:Si,onInitializationStateChange:wi,session:ke,existingOrderId:Rt?.orderId,debug:R},Rt?.orderId??"fresh")})]}),Go&&c(so,{stripe:Ko,options:Ms,children:c(Sc,{sessionId:e,nonce:t,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,onTokenizedBody:Kn,onErrorChange:Pe,isProcessing:G,onButtonClick:fe,onDecline:u,onTechnicalFailure:mo,runBeforeButtonClick:dr,onLoadStateChange:$s,placeholderBorderRadius:Xr,popupCapabilityOwner:v,externalTelemetryContext:Xs,presentationMode:fo})}),ho?c(so,{stripe:Qn,options:Ts,children:c(wc,{sessionId:e,nonce:t,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,intentKind:Ke>0?"payment":"setup",expressMethods:go,onTokenizedBody:Kn,onErrorChange:Pe,onButtonClick:fe,onDecline:u,onTechnicalFailure:mo,runBeforeButtonClick:dr,onLoadStateChange:Vs,placeholderBorderRadius:Xr,popupCapabilityOwner:v,externalTelemetryContext:Ge})}):null,!ho&&Js?c("div",{style:{height:oa,borderRadius:Xr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Yo&&c(kc,{sessionId:e,nonce:t,email:z.email,billingName:[z.firstName,z.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,paymentElementMethods:_a,stripeInstance:Qn,paymentElementBaseOptions:bi,futureUseSession:Ie,onTokenizedBody:Kn,onErrorChange:Pe,onButtonClick:fe,onDecline:u,runBeforeButtonClick:dr,onLoadStateChange:Ks,isProcessing:G,submitButtonColor:Qr,submitButtonBorderRadius:nn,submitButtonStyle:D.submitButton,onExpandApm:$e,expandedApmMethod:tn,themeId:It,buttonAppearance:{backgroundColor:D.cardButton?.backgroundColor,borderColor:D.cardInputBorder,textColor:D.cardButton?.color,borderRadius:Xr}}),X&&c("button",{type:"button",onClick:async()=>{G||!(await dr("card")).proceed||(fe?.("card"),q())},disabled:G,style:{width:"100%",...T,...D.cardButton,...fs({themeBundle:Ye,resolvedPrimaryColor:Qr,resolvedBorderRadius:nn,submitButtonStyle:D.submitButton,explicitPrimaryColor:Gn?.colorPrimary}),fontSize:D.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:G?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:G?.6:1},onMouseEnter:ie=>{!G&&(Ye||Gn?.colorPrimary)&&(ie.currentTarget.style.backgroundColor=cd)},onMouseLeave:ie=>{(Ye||Gn?.colorPrimary)&&(ie.currentTarget.style.backgroundColor=Qr)},onMouseDown:ie=>{ie.currentTarget.style.transform="scale(0.985)"},onMouseUp:ie=>{ie.currentTarget.style.transform="scale(1)"},children:c(wo,{content:ut})}),le&&Ne==="buttons"&&c(xo,{margin:"0.25rem 0",styleOverride:D.errorBanner,children:le})]}),X&&y&&c("div",{style:{gridArea:"1 / 1",...x?{animation:x}:{},...Ne==="collapsing"?{pointerEvents:"none"}:{}},children:dl}),I&&yl&&tn&&Da&&Qn&&c("div",{style:{gridArea:"1 / 1",...Co?{animation:Co}:{},...Ne==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ze("div",{style:{backgroundColor:Ei,borderRadius:xi,...ea,padding:Ai},children:[Ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ze("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:jt,style:{display:"inline-flex",alignItems:"center",gap:_i?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...D.backButtonIcon},children:c("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(ko,{content:rt})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:Ti,paddingRight:80,...D.title},children:`Pay with ${va(tn)}`})]}),c(so,{stripe:Qn,options:Da,children:c(ds,{method:tn,sessionId:e,nonce:t,email:z.email,billingName:[z.firstName,z.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,onTokenizedBody:Kn,onErrorChange:Pe,onDecline:u,onCancel:jt,runBeforeButtonClick:dr,onButtonClick:fe,isProcessing:G,submitButtonColor:Qr,submitButtonBorderRadius:nn,submitButtonStyle:D.submitButton,errorText:le})},tn)]})})]})]})}return yl&&tn&&Da&&Qn&&I?Ze("form",{onSubmit:Ii,className:N,noValidate:!0,style:{position:"relative"},children:[c(za,{}),oe&&c(wr,{status:oe,errorMessage:le,authorized:Pn}),c("div",{style:{...Co?{animation:Co}:{},...Ne==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ze("div",{style:{backgroundColor:Ei,borderRadius:xi,...ea,padding:Ai},children:[Ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ze("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:jt,style:{display:"inline-flex",alignItems:"center",gap:_i?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...D.backButtonIcon},children:c("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(ko,{content:rt})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:Ti,paddingRight:80,...D.title},children:`Pay with ${va(tn)}`})]}),c(so,{stripe:Qn,options:Da,children:c(ds,{method:tn,sessionId:e,nonce:t,email:z.email,billingName:[z.firstName,z.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,onTokenizedBody:Kn,onErrorChange:Pe,onDecline:u,onCancel:jt,runBeforeButtonClick:dr,onButtonClick:fe,isProcessing:G,submitButtonColor:Qr,submitButtonBorderRadius:nn,submitButtonStyle:D.submitButton,errorText:le})},tn)]})})]}):Ze("form",{onSubmit:Ii,className:N,noValidate:!0,style:{position:"relative"},children:[c(za,{}),oe&&c(wr,{status:oe,errorMessage:le,authorized:Pn}),Ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ul("flopay-direct-paypal-gate-debug-default"),pl("flopay-stripe-gate-debug-default"),Ho&&Pt&&Ze(Lo,{children:[Rt&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(da.Provider,{value:v,children:c(Ya,{sessionId:e,nonce:t,billingApiUrl:Q,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,clientId:Pt.clientId,environment:Pt.environment,currency:wn.toUpperCase(),isSubscription:pe,providerObjectType:Dt,approvalPresentation:Ma==="popup"?void 0:Ma,onTokenizedBody:Kn,onComplete:s,onErrorChange:Pe,onDecline:u,onCancel:C,onTechnicalFailure:mo,onButtonClick:fe,runBeforeButtonClick:dr,isProcessing:G,onLoadStateChange:Si,onInitializationStateChange:wi,session:ke,existingOrderId:Rt?.orderId,debug:R},Rt?.orderId??"fresh")})]}),Go&&c(so,{stripe:Ko,options:Ms,children:c(Sc,{sessionId:e,nonce:t,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,onTokenizedBody:Kn,onErrorChange:Pe,isProcessing:G,onButtonClick:fe,onDecline:u,onTechnicalFailure:mo,runBeforeButtonClick:dr,onLoadStateChange:$s,placeholderBorderRadius:Xr,popupCapabilityOwner:v,externalTelemetryContext:Xs,presentationMode:fo})}),ho&&c(so,{stripe:Qn,options:Ts,children:c(wc,{sessionId:e,nonce:t,email:z.email,billingName:ct||void 0,onBuyerIdentityReady:J,billingApiUrl:Q,intentKind:Ke>0?"payment":"setup",expressMethods:go,onTokenizedBody:Kn,onErrorChange:Pe,onButtonClick:fe,onDecline:u,onTechnicalFailure:mo,runBeforeButtonClick:dr,onLoadStateChange:Vs,placeholderBorderRadius:Xr,popupCapabilityOwner:v,externalTelemetryContext:Ge})}),Yo&&c(kc,{sessionId:e,nonce:t,email:z.email,billingName:[z.firstName,z.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Q,paymentElementMethods:_a,stripeInstance:Qn,paymentElementBaseOptions:bi,futureUseSession:Ie,onTokenizedBody:Kn,onErrorChange:Pe,onButtonClick:fe,onDecline:u,runBeforeButtonClick:dr,onLoadStateChange:Ks,isProcessing:G,submitButtonColor:Qr,submitButtonBorderRadius:nn,submitButtonStyle:D.submitButton,themeId:It,onExpandApm:$e,expandedApmMethod:tn,buttonAppearance:{backgroundColor:D.cardButton?.backgroundColor,borderColor:D.cardInputBorder,textColor:D.cardButton?.color,borderRadius:Xr}})]}),X&&(nd||td||rd)&&c(gl,{label:"or pay with card"}),X&&dl]})}import{Fragment as Er,jsx as me,jsxs as yn}from"react/jsx-runtime";var Uo=44,ws="flopay_checkout_saved_payment_resume",yi=new Map,ui=new Map;function Nc(e,t){t.settled&&t.consumers===0&&yi.get(e)===t&&yi.delete(e)}function Kp(e,t,n){let o=ui.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};ui.set(e,i);let s=()=>{ui.get(e)===i&&ui.delete(e)};return a.then(s,s),a}function ba(e){return new Promise(t=>setTimeout(t,e))}function pi(e,t,n){let o=Ka({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Hc,enabled:t!==!1});return o.beginCheckout(n),o}function Sa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ps(e,t,n,o,a,i){let s=pi(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Sa(s)}function Lc(e,t,n,o){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...o===void 0?{}:{attempt:o},statusClass:"2xx"})}function zc(e,t,n,o,a){let i=$c(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-o),durationMode:"machine",requestCategory:n,attempt:a,statusClass:i.statusClass}),t instanceof Bn&&t.code==="session_auto_completed"?!1:t instanceof Bn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function vs(e){return!e||e.data.stripe?.publishableKey?!1:!!Wc(e.data.paypal)?.clientId}var Gp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Yp(e){return new Lp(Gp,{publishableKey:"provider_unavailable",...e})}async function Cs(e,t){let{publishableKey:n,paypalPublishableKey:o}=Zi(e);return{...await Xi({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function ks(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Jp(){if(!ks())return null;try{let e=window.sessionStorage.getItem(ws);return e?JSON.parse(e):null}catch{return null}}function Uc(e){if(ks())try{window.sessionStorage.setItem(ws,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function bs(){if(ks())try{window.sessionStorage.removeItem(ws)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Zp(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let o of t)e.searchParams.has(o)&&(e.searchParams.delete(o),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function qc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Ss(e,t){return Vp(!!e,t)}function Xp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function jc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Qp(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function Is({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:l,error:u,onComplete:C,onError:_,onInstrument:k,onDecline:O,onCancel:ue,onCountryChange:N,onZipChange:Ae,showPayPal:Z=!0,showStripe:m=!0,walletPresentation:b="auto",enabledPaymentMethods:Ve,showApplePay:I=!0,showGooglePay:Xe=!0,debug:Y=!1,layout:Fe,theme:nt,buttonsTheme:ze,buttonsStyles:He,cardButtonContent:It,cardBackButtonContent:it,cardTitleContent:te,showSecurityFooter:xt,onButtonClick:ut,onBeforeButtonClick:rt,enableAVS:ge,cardFieldOrder:se,cardPreFormSlot:fe,avsLayout:wt,submitLabel:Bt,className:Qe,initialErrorMessage:ne=null,initialPayPalOrderId:Me,children:de,checkoutMode:L,confirmLabel:Ue,renderConfirmButton:De,onSessionCompleted:Oe}){let M=$p(o),qe=sr(()=>Vc(nt),[nt]),gt=i??qe?.appearance,_e=n?"embedded_checkout":"standard_checkout",ht=Ss(de,Fe),[ve,je]=Zt(null),[Ke,wn]=Zt(null),Et=Ot(null),Pt=Ot(null),pe=Ot(0),[P,st]=Zt(null),ot=Ot(null),[R,Se]=Zt(null),Ft=sr(()=>n?ya(n):"",[n]),ye=n?`create:${Ft}`:`session:${e??""}`,kt=jc(R),p=Ot(new Set),v=Ot(ye),we=Ot(ye);na(()=>{we.current=ye,v.current!==ye&&(v.current=ye,p.current.clear())},[ye]);let Ce=xn(S=>{if(we.current===ye){if(Hl.has(S.name)){if(p.current.has(S.name))return;p.current.add(S.name)}Lt(()=>k?.(S))}},[ye,k]),et=Ao(Ce,ye),Ge=Ot(!1),ke=xn(S=>{if(Ge.current)return;let w=S.gateway||!kt?S:{...S,gateway:kt};Ce(w)},[Ce,kt]);mr(()=>{et({class:"lifecycle",name:"checkout.mount"})},[et]);let[Ie,Dt]=Zt(e??""),d=e??Ie,xe=n?"":d,[he,Re]=Zt(!0),[Q,j]=Zt(null),[mn,Yn]=Zt(0),[on,Wt]=Zt("full"),[pt,Fn]=Zt(!1),[En,Xt]=Zt(ne),[Un,yt]=Zt(null),[fr,Vt]=Zt(null),[tr,Dn]=Zt(!1),[On,an]=Zt(void 0),[fn,qn]=Zt(""),[Be,lt]=Zt(!1),[kn,Ut]=Zt(!1),[sn,ln]=Zt(!1),Ht=Ot(null),Kt=Ot(0),gn=Ot(void 0),[Ee,hn]=Zt("loading"),[Pn,_r]=Zt(0),_n=Ot(!1),Tn=Ot(!1),gr=Ot(!1),Jn=Ot(null),Qt=Ot(null),X=sr(()=>({checkoutMode:L??on,layout:Xp(de,Fe)}),[L,de,on,Fe]),cn=Ot(C);cn.current=C;let jn=Ot(_);jn.current=_;let $=Ot(O);$.current=O;let vt=xn(S=>ei(Jn,async w=>{try{return await S(w)}catch(q){throw w.aborted?Fo(q):q}}),[]);mr(()=>()=>{Jn.current?.abort(),Jn.current=null},[]);let B=xn((S,w)=>{Et.current=S,wn(S),ot.current=w,st(w)},[]),qt=xn(()=>{let S=Pt.current;S&&(Pt.current=null,S.destroy())},[]);mr(()=>{pn(Ke)?.setCheckoutContext(X),P&&P!==Ke&&pn(P)?.setCheckoutContext(X)},[Ke,P,X]);let en=Ot(Oe);en.current=Oe;let ee=xn(S=>{hn(S),!(S!=="exhausted"||gr.current)&&(gr.current=!0,jn.current?.(new Bn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Nt=xn(()=>{hn("retrying"),_r(S=>S+1)},[]);mr(()=>{hn("loading"),_r(0),gr.current=!1},[d]),mr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Hc,checkout_type:_e,checkout_layout:ht,billing_api_url:M})},[ht,_e,M]);let U=sr(()=>n?ya(n,!0):"",[n]),_t=sr(()=>fn===U?On:void 0,[On,fn,U]),dn=sr(()=>n?Ui(n,_t):void 0,[n,_t]),Mn=L??dn?.checkoutMode??"full",Gt=sr(()=>dn?{...dn,checkoutMode:Mn}:void 0,[dn,Mn]);mr(()=>{an(void 0),qn(U),gn.current=void 0,Ht.current=null,ln(!1)},[U]),mr(()=>{Xt(ne)},[ne]);let hr=xn((S,w,q)=>{Lt(()=>{$.current?.(Sn(S,w,q))})},[]),Tr=xn(async(S,w)=>{Xt(null),Vt(null),Dn(!1),yt("processing");let q=w?.sessionId??S.id,re=S.clientSecret||t,$e=jc(S),jt=Et.current??ot.current,oe=pn(jt),K=jt?null:pi(M,a,X),A={log:h=>{oe?oe.log(h):K?.log(h)},error:h=>{oe?oe.error(h):K?.error(h)},terminal:h=>{oe?oe.terminal(h):K?.terminal(h)},performance:h=>{oe?oe.performance(h):K?.performance(h)},now:()=>oe?.now()??K?.now()??0,elapsed:h=>oe?.elapsed(h)??Math.max(0,(K?.now()??h)-h)},E=A.now(),W=!!(w?.initialAutoProcessingError||w?.initialAutoProcessingPending),be=!1,V,We=()=>{be||(be=!0,W=!0,V=A.now(),A.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),A.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Rt=!1,f=()=>{Rt||(Rt=!0,A.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),A.performance({stage:"processing",durationMs:A.elapsed(E),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),V!==void 0&&A.performance({stage:"recovery",durationMs:A.elapsed(V),durationMode:"machine",paymentMethodCategory:"saved"}))};A.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Ge.current=!0;try{A.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Ge.current=!1}et({class:"lifecycle",name:"payment.processing.started",provider:$e}),W&&We();let g;try{let h=cc(w?.initialAutoProcessingError),F=w?.initialAutoProcessingError?.type==="3ds_required"&&!w.initialAutoProcessingError.threeDSecureToken&&w.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:w.initialAutoProcessingError.nextActionRedirectUrl}:null,J,le=Ye=>(We(),vt(D=>Do(Ye,{billingApiUrl:M,sessionId:q,nonce:re,session:S,signal:D})));if(F)J=await le(F);else if(h)We(),h.type==="paypal_redirect_required"&&Qt.current?.publishableKey&&Uc({sessionId:q,publishableKey:Qt.current.publishableKey,paypalPublishableKey:Qt.current.paypalPublishableKey}),J=await vt(Ye=>ri(h,{flopay:Et.current,paypalFlopay:ot.current,attempt3DS:w?.attempt3DS,billingApiUrl:M,sessionId:q,session:S,telemetry:!1,signal:Ye})),h.type==="paypal_redirect_required"&&bs();else if(w?.initialAutoProcessingPending){let Ye=w.initialAutoProcessingPending,D=new di(M,{telemetry:!1}),mt=await vt(G=>D.waitForCheckoutSessionCompletion(Ye.sessionId,{initialDelayMs:Ye.retryAfterMs,nonce:re,statusUrl:Ye.statusUrl,signal:G})),Nn=Vr(mt,S),Cn=mt.autoProcessingError?.type==="3ds_required"&&mt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:mt.autoProcessingError.nextActionRedirectUrl}:null;if(Cn)J=await le(Cn);else{if(!Or(Nn))throw Eo(Nn);J=Dr(Nn,q)}}else{if(w?.initialAutoProcessingError)throw Ir(w.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:w.initialAutoProcessingError.checkoutMethod});if(w?.fromCreateSession)return w?.fallbackToFull&&(Wt("full"),qc("full")),!1;{let Ye=await Oo({billingApiUrl:M,sessionId:q,session:S,nonce:re,telemetry:!1});Ye.type==="success"?J=Ye.result:Ye.type==="next_action_required"?J=await le(Ye):(We(),Ye.type==="paypal_redirect_required"&&Qt.current?.publishableKey&&Uc({sessionId:q,publishableKey:Qt.current.publishableKey,paypalPublishableKey:Qt.current.paypalPublishableKey}),J=await vt(D=>ri(Ye,{flopay:Et.current,paypalFlopay:ot.current,attempt3DS:w?.attempt3DS,billingApiUrl:M,sessionId:q,session:S,telemetry:!1,signal:D})),Ye.type==="paypal_redirect_required"&&bs())}}q&&Bo(q),f(),W&&(A.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),A.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),A.terminal({outcome:J.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Dn(J.status==="authorized"),yt("success"),await ba(600),g=()=>cn.current?.(J)}catch(h){let F=Wr(ga(h),q);if(F.code==="three_ds_aborted")return!1;let J=F.checkoutMethod??fa;Xt(F.message),Vt(F.message),Dn(!1),w?.fallbackToFull&&(A.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Wt("full"),qc("full")),f();let le=F.statusCode===void 0?void 0:Hp(F.statusCode,"unknown"),Ye=le==="4xx"?{requestCategory:"process_payment",statusClass:le}:{},D=le===void 0||le==="4xx";if(D&&(F.telemetryOutcome==="payment_declined"||!!(F.declineCode||F.code?.toLowerCase().includes("declin"))))A.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ye});else if(D&&(F.telemetryOutcome==="validation_rejected"||F.type==="validation_error"))A.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ye});else{let Cn=$c(h,W?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),G=F.telemetryRequestCategory??"process_payment";Ge.current=!0;try{A.error({...Cn,...F.telemetryFailureCategory?{failureCategory:F.telemetryFailureCategory}:{},stage:W?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:G})}finally{Ge.current=!1}et({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:G,provider:$e})}return Lt(()=>jn.current?.(F)),hr(J,F,{code:F.code,declineCode:F.declineCode}),yt("error"),await Promise.allSettled([ba(400),w?.ensureProvidersReady?w.ensureProvidersReady():Promise.resolve()]),W&&(A.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),A.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{f(),K&&Sa(K),yt(null),Vt(null)}return Lt(g),!0},[hr,et,t,M,vt,a,X]);mr(()=>{if(typeof window>"u"||Tn.current)return;let S=new URLSearchParams(window.location.search),w=S.get("payment_intent_client_secret");if(!w)return;let q=Jp();q&&(Tn.current=!0,(async()=>{let re,$e=0;Xt(null),Vt(null),yt("processing"),Fn(!0);try{if(S.get("redirect_status")==="failed")throw Object.assign(new Bn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:jt,paypalFlopay:oe}=await Xi({publishableKey:q.publishableKey,paypalPublishableKey:q.paypalPublishableKey,billingApiUrl:M,locale:s,telemetry:a});re=pn(oe??jt),re?.setCheckoutContext(X),$e=re?.now()??0,re?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),re?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let K=(oe??jt)?.getRawProvider();if(!K)throw Object.assign(new Bn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:A,error:E}=await K.retrievePaymentIntent(w);if(E)throw Object.assign(new Bn(E.message??"Failed to retrieve PayPal payment status.","api_error",{code:E.code}),{checkoutMethod:"paypal"});let W=Ol(A?.status);if(!A||W==="failed")throw Object.assign(new Bn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let be=typeof A.payment_method=="string"?A.payment_method:A.payment_method?.id,V=W;if(q.sessionId){let f=(await new di(M,{telemetry:!1}).getUnifiedCheckoutSession(q.sessionId)).data.session;if(f&&f.status!=="complete"){let g=await Oo({billingApiUrl:M,sessionId:q.sessionId,session:f,telemetry:!1,tokenizedData:{id:be??A.id,type:"card",threeDSecureActionResultTokenId:A.id,isPaypal:!0}});if(g.type!=="success")throw Object.assign(new Bn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});V=g.result.status}}q.sessionId&&Bo(q.sessionId),re?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),re?.performance({stage:"redirect_resume",durationMs:re.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),re?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),yt("success"),await ba(600),Lt(()=>cn.current?.({status:V,paymentIntentId:A.id,paymentMethodId:be,checkoutMethod:"paypal"}))}catch(jt){let oe=Wr(ga(jt),q.sessionId),K=oe.checkoutMethod??"paypal",A=!!(oe.declineCode||oe.code?.toLowerCase().includes("declin"));if(re)re.performance({stage:"redirect_resume",durationMs:re.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),A?re.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):re.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(A){let E=pi(M,a,X);E.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Sa(E)}else Ps(M,a,X,"REDIRECT_RESUME_FAILED","redirect_resume");Xt(oe.message),Vt(oe.message),Lt(()=>jn.current?.(oe)),hr(K,oe,{code:oe.code,declineCode:oe.declineCode}),yt("error"),await ba(400)}finally{bs(),Zp(),yt(null),Vt(null),Fn(!1)}})())},[hr,s,M,a,X]);let Pr=Ot(null),vr=sr(()=>Gt?ya(Gt):"",[Gt]),Mr=Ot(Gt);Mr.current=Gt,mr(()=>{Dt(e??"")},[e]),mr(()=>{_n.current=!1,Xt(ne),Vt(null),Dn(!1),yt(null)},[vr,ne,e]);async function qr(S,w,q){let re=pi(M,a,X),$e=new di(M,{telemetry:!1}),jt=!1;try{let oe=S.idempotencyKey===void 0?void 0:Oc(S.idempotencyKey),K=rc(w,q),A=nc(w,q);K?.canonicalIdentity===q&&A&&A.canonicalIdentity===void 0&&(Za(w,q,A.idempotencyKey),A={...A,canonicalIdentity:q});let E=oe??(A?.canonicalIdentity===q?A.idempotencyKey:void 0),W,be=!1;re.log({name:K?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let V=K?.sid??null,We=null,Rt,f,g=!1;if(V)try{We=await $e.getUnifiedCheckoutSession(V,K?.nonce),K&&K.canonicalIdentity===void 0&&(tc(We.data.session,S)?(Xa(w,q,V,K.nonce??We.data.session?.clientSecret),A&&A.canonicalIdentity===void 0&&(Za(w,q,A.idempotencyKey),E??(E=A.idempotencyKey))):(Ja(w,q),A=null,E=oe,V=null,We=null));let F=We?.data.session?.status,J=We?.data.session,le=J?.clientSecret||K?.nonce;if(V&&J?.buyerIdentified===!1&&le&&(f=Ro($e,V,le,S.account)),V&&We&&F==="complete"){if(Gi(V))return{sid:V,result:We};Ja(w,q),V=null,We=null,be=!0}}catch{re.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),K?.canonicalIdentity===void 0?(Ja(w,q),E=oe):Ki(w,q),V=null}if(!V){!oe&&(be||!E)&&(E=Oc(),W=E),E&&Za(w,q,E);let F=re.now(),J=0;re.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let le={...S,idempotencyKey:E,avsCheck:!!ge,avsConfig:typeof ge=="object"?ge:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ss(de,Fe)};Object.defineProperty(le,zp,{configurable:!1,enumerable:!1,value:{onAttempt:mt=>{J=Math.max(J,mt)}}});let Ye=()=>{Lc(re,"session_create",F,J)},D=mt=>{zc(re,mt,"session_create",F,J)&&et({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(qp(le)){let mt=await $e.createDetachedSession(le);mt.claimed.catch(()=>{}),We=mt.shell,V=mt.sessionId,f=mt.claim;let Nn=re.now();re.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Rt=mt.claimed.then(Cn=>{let G=Cn.data.session?.id??mt.sessionId;return G&&Xa(w,q,G,Cn.data.session?.clientSecret??mt.nonce),Lc(re,"session_claim",Nn),Ye(),Cn},Cn=>{throw Ki(w,q),zc(re,Cn,"session_claim",Nn,0)&&et({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Cn}).finally(()=>Sa(re)),Rt.catch(()=>{}),jt=!0,re.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),re.performance({stage:"session_shell",durationMs:re.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:J,statusClass:"2xx",paymentMethodCategory:"card"})}else We=await $e.createAndFetchSession(le),Ye()}catch(mt){throw D(mt),mt}V=We.data.session?.id??V??"",V&&!Rt&&Xa(w,q,V,We.data.session?.clientSecret)}let h=We?.data.session;return!f&&V&&h?.buyerIdentified===!1&&h.clientSecret&&(f=Ro($e,V,h.clientSecret,S.account)),{sid:V??"",result:We,sdkGeneratedIdempotencyKey:W,...Rt?{claimed:Rt}:{},...f?{claim:f}:{},...g?{claimRequiresIdentity:!0}:{}}}finally{jt||Sa(re)}}let jr=Ot(qr);na(()=>{jr.current=qr},[qr]);let In=xn(async(S,w)=>{let q=Mr.current;if(!q)throw new Bn("createSession is required to bootstrap checkout.","validation_error");let re=Ui(q,S),$e=ya(re),jt=ec(re),oe=yi.get($e);if(!oe){let E={canonicalIdentity:$e,promise:jr.current(re,jt,$e),consumers:0,settled:!1};oe=E,yi.set($e,E);let W=()=>{E.settled=!0,Nc($e,E)};E.promise.then(W,W)}oe.consumers+=1;let K=!1,A=()=>{K||(K=!0,oe.consumers-=1,Nc($e,oe))};w?.(A);try{let E=await oe.promise;Pr.current=$e,S&&(qn(U),an(h=>Bl(h,S)));let{sid:W,result:be,claimed:V,claim:We,claimRequiresIdentity:Rt}=E;if(gn.current=We,ln(Rt===!0),je(be),be.data.session&&Se(be.data.session),W&&Dt(W),V){Kt.current+=1;let h=Kt.current;Ht.current=V,Ut(!0),V.then(F=>{Kt.current===h&&(Ht.current===V&&(Ht.current=null),je(F),F.data.session&&Se(F.data.session),Ut(!1),ln(!1))},F=>{Kt.current===h&&(Ht.current===V&&(Ht.current=null),Ut(!1),ln(!1),j(F instanceof Bn?F:new Bn(F instanceof Error?F.message:"Failed to create session","api_error")))})}else Kt.current+=1,Ht.current=null,Ut(!1),ln(!1);let{flopay:f,paypalFlopay:g}=await Cs(be,{billingApiUrl:M,locale:s,telemetry:a});return B(f,g),Re(!1),E}catch(E){throw Pr.current===$e&&(Pr.current=null),E}finally{w||A()}},[U,B,s,M,a]),Ar=Ot(Tr);Ar.current=Tr;let nr=Ot(In);nr.current=In;let Mt=xn(async S=>{if(!Qp(S)||Be)return{sessionId:Ie,session:R};lt(!0);try{let w=await In(S);return{sessionId:w.sid,session:w.result.data.session??null}}finally{lt(!1)}},[In,Be,Ie,R]),$n=xn(async S=>{let w=gn.current;if(!w)return;let q=Kt.current,re=await w(S);Kt.current===q&&(je(re),re.data.session&&Se(re.data.session))},[]),Wn=xn(async()=>{await Ht.current},[]),Zn=xn(async()=>(await Wn(),{proceed:!0}),[Wn]);mr(()=>{let S=!1,w,q=++pe.current;qt(),j(null),Yn(0);let re=()=>{S=!0,pe.current===q&&(pe.current+=1,qt())},$e=Mr.current;if(vr&&$e)return Wt(Mn),Re(!1),Pr.current===vr?re:(Se(Fl($e,L)),(async()=>{let K=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),A=Mn==="auto"&&!_n.current&&!K;A&&(Xt(null),Vt(null),yt("processing"));try{let E=await nr.current(void 0,We=>{w=We}),W=E.result.data.session??null;Qt.current=Zi(E.result);let be=vs(E.result),V=Gi(E.sid||W?.id);if(!S&&A&&W&&!be&&!V){_n.current=!0,await Kp(vr,E.sdkGeneratedIdempotencyKey,()=>Ar.current(W,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:E.result.autoProcessingError,initialAutoProcessingPending:E.result.autoProcessingPending,autoProcessingAttempted:E.result.autoProcessingAttempted,sessionId:E.sid||W.id}));return}!S&&A&&((be||V)&&(_n.current=!0),yt(null),Vt(null))}catch(E){if(S)return;let W=qa(E);if(A&&W==="session_auto_completed"){_n.current=!0,yt("success"),await ba(600),S||(Lt(()=>{cn.current?.({status:"succeeded"})}),yt(null),Vt(null));return}A&&(yt(null),Vt(null));let be=E instanceof Bn?E:new Bn(E instanceof Error?E.message:"Failed to create session","api_error");j(be)}finally{w?.(),w=void 0}})(),()=>{re(),w?.()});Re(!0);async function jt(){let K=!1,A=null;try{let E=new di(M,{telemetry:!1}),W=await E.getUnifiedCheckoutSession(d,t);if(A=W,S)return;je(W);let be=W.data.session??null;if(Se(be),!be)throw new Bn("No session data returned","api_error");let V=be.checkoutMode;if(V==="setup")throw new Bn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(be.status==="authorized"){Re(!1),Lt(()=>{cn.current?.(Dr(be,d)),en.current?.(be.successUrl??"")});return}if(be.status==="complete"){Re(!1),Lt(()=>{en.current?.(be.successUrl??"")});return}if(be.status==="expired")throw Ua(be);K=!0;let We=L??V??"full";Wt(We),Kt.current+=1;let Rt=be.clientSecret||t;gn.current=be.buyerIdentified===!1&&Rt?Ro(E,d,Rt,{...be.customer?.id?{userId:be.customer.id}:{}}):void 0,Ut(!1),ln(!1);let f=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),g=vs(W);if(We==="auto"&&!_n.current&&!f&&!g){_n.current=!0;let h=oe(W);try{if(await Ar.current(be,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>h,sessionId:d||be.id}),S)return;await h,S||Re(!1);return}catch{if(S)return;await h,S||Re(!1);return}}await oe(W),S||Re(!1)}catch(E){if(S)return;let W=xl(E,K);if(K&&et({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),W){let{errorCode:V,stage:We,...Rt}=W;Ps(M,a,X,V,We,Rt)}if(W?.stage==="provider_load"&&(L??A?.data.session?.checkoutMode??"full")==="full"&&Al(A,Z,m)){let V=Yp({billingApiUrl:M,locale:s,telemetry:a});Pt.current=V,B(V,null),Yn(1),Re(!1);return}let be=E instanceof Bn&&W?.stage!=="provider_load"?E:Ml();be!==E&&Lt(()=>jn.current?.(be)),j(be),Re(!1)}}async function oe(K){let{flopay:A,paypalFlopay:E,...W}=await Cs(K,{billingApiUrl:M,locale:s,telemetry:a});Qt.current={publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey},B(A,E),Yn(0)}return jt(),re},[L,vr,Mn,xe,t,Z,m]);let Vn=xn(async()=>{if(!ve||mn!==1)return;let S=pe.current;Yn(2);try{let{flopay:w,paypalFlopay:q}=await Cs(ve,{billingApiUrl:M,locale:s,telemetry:a});if(pe.current!==S)return;qt(),B(w,q),Yn(0)}catch(w){if(pe.current!==S)return;let{errorCode:q,stage:re,...$e}=zi(w);Ps(M,a,X,q,re,$e)}},[qt,B,s,mn,M,a,X,ve]),Ne=!!(d&&(R?.clientSecret||t)),un=pt||!Ne,tn=xn(async()=>{if(!(pt||!Ne||!R)){Fn(!0),Xt(null);try{await Tr(R,{attempt3DS:!0,fallbackToFull:!0,sessionId:d||R.id})}finally{Fn(!1)}}},[d,pt,Ne,Tr,R]),Hn=Wc(ve?.data.paypal,Me),Zr=vs(ve),xr=sr(()=>{if(!(!ve||!R||!ve.data.stripe?.publishableKey))return{billingApiUrl:M}},[ve,R,M]),lr=!!(n&&!de&&Fe==="buttons"&&rt&&Mn==="full"),Xn=!!(d&&(jp(R?.vault)||ro(R))),vn=sr(()=>({session:R,loading:he,error:Q,checkoutMode:on,inlineSessionDraft:Gt,applyInlineSessionPatch:lr?Mt:void 0,inlineSessionPatchProcessing:Be,claimPending:kn,claimRequiresIdentity:sn,claimBuyerIdentity:$n,waitForDataAttachment:Wn}),[R,he,Q,on,Gt,lr,Mt,Be,kn,sn,$n,Wn]),Br=!!n&&Fe==="buttons"&&!Zr&&!Xn&&(!Ke||!xr),An=Un?me(wr,{status:Un,errorMessage:fr,authorized:tr}):null;if(he&&!Xn){if(l)return yn(Er,{children:[l,An]});if(Fe==="buttons"){let S=qe?.buttonsLayout?.cardButton?.borderRadius??qe?.appearance.variables?.borderRadius??8,w=q=>me("div",{style:{height:q,borderRadius:S,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return yn(Er,{children:[yn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Z&&w(Uo),m&&(I||Xe)&&w(Uo),m&&w(Uo),me("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),An]})}return yn(Er,{children:[yn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[me("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),me("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),An]})}return Q?u?me(ur.Provider,{value:vn,children:u(Q)}):me(ur.Provider,{value:vn,children:me("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Q.message})}):Br?yn(Er,{children:[me(ur.Provider,{value:vn,children:me(ty,{onButtonClick:ut,showPayPal:Z,showStripe:m,showApplePay:I,showGooglePay:Xe,theme:nt,buttonsTheme:ze,buttonsStyles:He,cardButtonContent:It,cardBackButtonContent:it,cardTitleContent:te})}),An]}):Zr&&R&&Hn?yn(Er,{children:[me(ur.Provider,{value:vn,children:yn("div",{className:Qe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[En&&me(xo,{icon:!1,children:En}),Ee==="retrying"&&me("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ee==="exhausted"&&yn("div",{role:"alert",children:[me("div",{children:"PayPal is temporarily unavailable. Please try again."}),me("button",{type:"button",onClick:Nt,children:"Retry PayPal"})]}),Ee!=="exhausted"&&me("div",{"aria-hidden":Ee==="retrying"?!0:void 0,style:Ee==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:me(Xl,{sessionId:d,nonce:R.clientSecret||void 0,billingApiUrl:M,email:R.customer?.email||Gt?.account?.email,billingName:[R.customer?.firstName,R.customer?.lastName].filter(Boolean).join(" ")||[Gt?.account?.firstName,Gt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:$n,clientId:Hn.clientId,environment:Hn.environment,currency:(R.currency??"usd").toUpperCase(),isSubscription:R.mode==="subscription",providerObjectType:Hn.providerObjectType,approvalPresentation:Hn.approvalPresentation,existingOrderId:Hn.existingOrderId,onComplete:C,onErrorChange:Xt,onDecline:O,onCancel:ue,onButtonClick:ut,runBeforeButtonClick:Zn,onInitializationStateChange:ee,allowAutomaticRetry:Pn===0,session:R,telemetry:a,telemetryContext:X,onInstrument:ke,debug:Y},`${ye}:paypal-init-${Pn}`)})]})}),An]}):on==="confirm"?yn(Er,{children:[me(ur.Provider,{value:vn,children:me(Qa,{flopay:Ke,paypalFlopay:P,options:xr??{billingApiUrl:M},onInstrument:ke,children:yn("div",{className:Qe,children:[En&&me("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:En}),De?De({onConfirm:tn,isProcessing:un}):me("button",{type:"button",onClick:tn,disabled:un,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:un?"not-allowed":"pointer",opacity:un?.6:1},children:pt?"Processing...":Ue??"Confirm Purchase"})]})},ye)}),An]}):(!Ke||!xr)&&!(Xn&&on==="full")?me(Er,{children:An}):yn(Er,{children:[me(ur.Provider,{value:vn,children:yn(Qa,{flopay:Ke,paypalFlopay:P,options:xr??{billingApiUrl:M},onInstrument:ke,children:[mn===1&&me("button",{type:"button",onClick:Vn,children:"Retry payment methods"}),de?yn(Er,{children:[En&&me("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:En}),me(ey,{sessionId:d,nonce:R?.clientSecret||void 0,billingApiUrl:M,session:R,submitLabel:Bt,walletPresentation:b,children:de})]}):me(gs,{sessionId:d,nonce:R?.clientSecret||void 0,telemetry:a,email:R?.customer?.email||Gt?.account?.email,userId:R?.customer?.id||Gt?.account?.userId,firstName:R?.customer?.firstName||Gt?.account?.firstName,lastName:R?.customer?.lastName||Gt?.account?.lastName,totalAmount:R?Math.round(Up(R).total*100):0,currency:R?.currency?.toLowerCase()??"usd",onComplete:C,onError:_,onDecline:O,onCancel:ue,error:En,onErrorChange:Xt,showPayPal:Z,showStripe:m,walletPresentation:b,enabledPaymentMethods:mn?[]:Ve??ve?.data.stripe?.enabledPaymentMethods??R?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ve?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:Xe,layout:Fe,theme:nt,buttonsTheme:ze,buttonsStyles:He,appearance:gt,cardButtonContent:It,cardBackButtonContent:it,cardTitleContent:te,onButtonClick:ut,onBeforeButtonClick:rt,onBuyerIdentityReady:$n,enableAVS:ge,...se?{cardFieldOrder:se}:{},...fe?{cardPreFormSlot:fe}:{},avsLayout:wt,country:R?.customer?.country,city:R?.customer?.city,state:R?.customer?.state,onCountryChange:N,onZipChange:Ae,avsCheck:!!ge,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ss(de,Fe),className:Qe,submitLabel:Bt,directPaypal:Hn,isSubscription:R?.mode==="subscription",session:R,dataAttachmentPending:kn,dataAttachmentRequiresIdentity:sn,debug:Y})]},ye)}),An]})}function ey({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,children:s}){return me(Er,{children:hs.Children.map(s,l=>{if(!hs.isValidElement(l))return l;let u=l.props,C={};return u.sessionId||(C.sessionId=e),!u.nonce&&t&&(C.nonce=t),u.billingApiUrl||(C.billingApiUrl=n),u.submitLabel===void 0&&a!==void 0&&(C.submitLabel=a),u.walletPresentation===void 0&&(C.walletPresentation=i),o?.customer&&(u.email||(C.email=o.customer.email),u.userId||(C.userId=o.customer.id),u.firstName||(C.firstName=o.customer.firstName),u.lastName||(C.lastName=o.customer.lastName)),Object.keys(C).length===0?l:hs.cloneElement(l,C)})})}function ty({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:o,showGooglePay:a,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:u,cardBackButtonContent:C,cardTitleContent:_}){let[k,O]=Zt(!1),ue=sr(()=>Vc(i),[i]),N=sr(()=>{let b=ue?.buttonsLayout??Wp(s);return l?{...b,...l,cardButton:{...b.cardButton,...l.cardButton},cardFormContainer:{...b.cardFormContainer,...l.cardFormContainer},backButton:{...b.backButton,...l.backButton},backButtonIcon:{...b.backButtonIcon,...l.backButtonIcon},submitButton:{...b.submitButton,...l.submitButton},title:{...b.title,...l.title}}:b},[ue,s,l]),Ae=ue?.buttonsLayout?.cardButton?.borderRadius??ue?.appearance.variables?.borderRadius??8,Z=b=>me("div",{style:{height:b,borderRadius:Ae,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),m=u===void 0?{boxSizing:"border-box",height:Uo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(k){let b=N.cardInputBorder??"#e5e7eb",Ve=N.cardInputBackground??"white",I=So(C),Xe=So(_);return yn("div",{style:{backgroundColor:N.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...N.cardFormContainer},children:[yn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[yn("button",{type:"button",onClick:()=>O(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:I?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...N.backButton},children:[me("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...N.backButtonIcon},children:me("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:me("path",{d:"M15 18l-6-6 6-6"})})}),me(ko,{content:C})]}),Xe?me("div",{style:{flex:1}}):me("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...N.title},children:me(aa,{content:_})})]}),me("div",{style:{backgroundColor:Ve,border:`1px solid ${b}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:me("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),yn("div",{style:{display:"flex"},children:[me("div",{style:{flex:1,backgroundColor:Ve,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomLeftRadius:8,padding:12,height:45},children:me("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),me("div",{style:{flex:1,backgroundColor:Ve,borderTop:"none",borderRight:`1px solid ${b}`,borderBottom:`1px solid ${b}`,borderLeft:`1px solid ${b}`,borderBottomRightRadius:8,padding:12,height:45},children:me("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),me("div",{style:{backgroundColor:Ve,border:`1px solid ${b}`,borderRadius:8,marginTop:8,padding:12,height:45},children:me("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),me("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...N.submitButton,opacity:.5}}),me("style",{children:`
|
|
12
|
+
`}),Xo&&Qr&&Je("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:G?-2:0},children:[Je("button",{type:"button",onClick:te,style:{display:"inline-flex",alignItems:"center",gap:Mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:u("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(wo,{content:at})]}),sl?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...b.title},children:u(aa,{content:fe})})]}),!Xo&&!sl&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ai,order:G?-3:0,...b.title},children:u(aa,{content:fe})}),G&&_e&&u("div",{style:{order:-2,width:"100%"},children:_e}),G&&xe&&Je("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[u("div",{style:{backgroundColor:ho,border:`1px solid ${ar(Ba)}`,borderRadius:an,padding:"10px"},children:u("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Ht,onChange:r=>{At("email"),jt.current=r.target.value,un(r.target.value)},onPointerDown:()=>At("email"),onKeyDown:()=>At("email"),onBlur:()=>{Kn("email")&&Fr(!0),Rt||Ci()},disabled:nt,required:!0,"aria-invalid":Ba||void 0,"aria-describedby":Ba?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...xi}})}),Ba&&u("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Qo,children:$n.empty?"Email address is required":"Enter a valid email address"})]}),ke&&u("div",{style:{order:G?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=zt,y=(A=!1)=>({backgroundColor:ho,border:`1px solid ${ar(A)}`,borderRadius:an,marginTop:"0.5rem",padding:"10px"}),M=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...xi}),oe=Gu(r);return Je(Lo,{children:[Jt(ke.address_line_1,r)&&Je(Lo,{children:[u("div",{style:y(Yt("line1")),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Qt,onChange:A=>{At("line1"),vn.current.addressLine1=!0,qt.current=A.target.value,Vn(A.target.value)},onPointerDown:()=>At("line1"),onKeyDown:()=>At("line1"),onBlur:()=>Gn("line1"),disabled:nt,required:!0,"aria-invalid":Yt("line1")||void 0,"aria-describedby":Yt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:M()})}),Yt("line1")&&u("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Qo,children:"Street address is required"})]}),Jt(ke.address_line_2,r)&&u("div",{style:y(),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:yt,onChange:A=>{vn.current.addressLine2=!0,en.current=A.target.value,Pr(A.target.value)},disabled:nt,"data-testid":"flopay-address-line2",style:M()})}),(Jt(ke.city,r)||Jt(ke.state,r))&&Je("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Jt(ke.city,r)&&u("div",{style:{flex:1,backgroundColor:ho,borderTop:`1px solid ${ar(Yt("city"))}`,borderRight:`1px solid ${ar(Yt("city"))}`,borderBottom:`1px solid ${ar(Yt("city"))}`,borderLeft:`1px solid ${ar(Yt("city"))}`,padding:"10px",borderTopLeftRadius:an,borderBottomLeftRadius:an,...Jt(ke.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:an}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Vt,onChange:A=>{At("city"),vn.current.city=!0,pn.current=A.target.value,rr(A.target.value)},onPointerDown:()=>At("city"),onKeyDown:()=>At("city"),onBlur:()=>Gn("city"),disabled:nt,required:!0,"aria-invalid":Yt("city")||void 0,"aria-describedby":Yt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:M()})}),Jt(ke.state,r)&&u("div",{style:{flex:1,backgroundColor:ho,borderTop:`1px solid ${ar(Yt("state"))}`,borderRight:`1px solid ${ar(Yt("state"))}`,borderBottom:`1px solid ${ar(Yt("state"))}`,borderLeft:`1px solid ${ar(Yt("state"))}`,padding:"10px",borderTopRightRadius:an,borderBottomRightRadius:an,...Jt(ke.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${ar(Yt("state")||Yt("city"))}`}:{borderRadius:an}},children:oe?Je("select",{id:"flopay-billing-state",name:"billing-state",value:Un,onChange:A=>{At("state"),vn.current.state=!0,Kt.current=A.target.value,zn(A.target.value)},onPointerDown:()=>At("state"),onKeyDown:()=>At("state"),onBlur:()=>Gn("state"),disabled:nt,autoComplete:"billing address-level1",required:!0,"aria-invalid":Yt("state")||void 0,"aria-describedby":Yt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...M(),cursor:"pointer"},children:[u("option",{value:"",children:es(r)}),oe.map(A=>u("option",{value:A.code,children:A.name},A.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:es(r),autoComplete:"billing address-level1",value:Un,onChange:A=>{At("state"),vn.current.state=!0,Kt.current=A.target.value,zn(A.target.value)},onPointerDown:()=>At("state"),onKeyDown:()=>At("state"),onBlur:()=>Gn("state"),disabled:nt,required:!0,"aria-invalid":Yt("state")||void 0,"aria-describedby":Yt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:M()})})]}),Yt("city")&&u("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Qo,children:"City is required"}),Yt("state")&&Je("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Qo,children:[es(r)," is required"]}),(Jt(ke.country,r)||Jt(ke.postal_code,r))&&Je("div",{style:{display:"flex",flexDirection:se==="column"?"column":"row",gap:se==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Jt(ke.country,r)&&u("div",{style:{flex:se==="row"?1:void 0,backgroundColor:ho,borderTop:`1px solid ${Zo}`,borderRight:`1px solid ${Zo}`,borderBottom:`1px solid ${Zo}`,borderLeft:`1px solid ${Zo}`,padding:"10px",...se==="row"&&Jt(ke.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:an,borderBottomLeftRadius:an,borderRight:"none"}:{borderRadius:an}},children:Je("select",{id:"flopay-billing-country",name:"billing-country",value:zt,onChange:A=>{vn.current.country=!0,Rn.current=A.target.value,pt(A.target.value),gt?.(A.target.value),Kt.current="",zn("")},disabled:nt,autoComplete:"billing country","data-testid":"flopay-country",style:{...M(),cursor:"pointer"},children:[zt===""?u("option",{value:"",children:"Select country"}):null,Uu.map(A=>Je("option",{value:A.code,children:[A.flag," ",A.name]},A.code))]})}),Jt(ke.postal_code,r)&&u("div",{style:{flex:se==="row"?1:void 0,backgroundColor:ho,border:`1px solid ${pd}`,padding:"10px",...se==="row"&&Jt(ke.country,r)?{borderRadius:"0",borderTopRightRadius:an,borderBottomRightRadius:an}:{borderRadius:an}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ls(zt),autoComplete:"billing postal-code",value:Ln,onChange:A=>{At("zip"),vn.current.zip=!0,it.current=A.target.value,An(A.target.value),Ee?.(A.target.value)},onPointerDown:()=>At("zip"),onKeyDown:()=>At("zip"),onBlur:()=>{Kn("zip")&&br(!0)},disabled:nt,required:Et.required,"aria-invalid":Fa||void 0,"aria-describedby":Fa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:M()})})]}),Fa&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Qo,children:Et.empty?`${ls(r)} is required`:Op(r)})]})})()}),G&&hd,Q&&u(xo,{margin:"0.75rem 0",styleOverride:b.errorBanner,children:Q})]}),Da={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},pl=r=>_?!Ve||!kr?u("pre",{"data-testid":r,style:Da,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":r,style:Da,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${Ve}`,` directPaypalConfigured=${kr}`,` inAppBrowserDetected=${String(Ma)}`,` shouldRenderDirectPayPal=${Ho}`,` shouldRenderStripePayPal=${Go}`,` hasPaypalStripeInstance=${!!Es}`].join(`
|
|
13
|
+
`)}):null,yl=r=>_?!R||!On?u("pre",{"data-testid":r,style:Da,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":r,style:Da,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${R}`,` currency=${In}`,` amountInCents=${Wo}`,` enabledPaymentMethods: ${JSON.stringify(H??[])}`,` enabledPaymentMethodsProvided=${Vo}`,` hasEnabledMethods=${Ra}`,` expressMethods: ${JSON.stringify(Ea)}`,` walletExpressMethods: ${JSON.stringify(fo)}`,` paymentElementMethods: ${JSON.stringify(Si)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ta)}`,` hasStripeInstance=${!!On}`,` shouldRenderWallets=${go}`,` shouldRenderPaymentElement=${Yo}`].join(`
|
|
14
|
+
`)}):null,ml=Ue==="apm-expanding"||Ue==="apm-form"||Ue==="apm-collapsing",vo;Ue==="apm-expanding"?vo=kc:Ue==="apm-collapsing"&&(vo=Ic);let Oa=on?Uc(wi,on,we):null;if(qe==="buttons"){let r=Ue==="buttons"||Ue==="expanding"||Ue==="apm-expanding",y=Ue==="expanding"||Ue==="card"||Ue==="collapsing",M=ut===void 0?{boxSizing:"border-box",height:oa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},oe;Ue==="expanding"||Ue==="apm-expanding"?oe=xp:(Ue==="collapsing"||Ue==="apm-collapsing")&&(oe=Ap);let A;return Ue==="expanding"?A=kc:Ue==="collapsing"&&(A=Ic),Je("form",{onSubmit:_i,className:L,noValidate:!0,style:{position:"relative"},children:[u(qa,{}),ne&&u(Rr,{status:ne,errorMessage:Q,authorized:Cn}),Je("div",{style:{display:"grid"},children:[Je("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!oe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!oe?Fp:{},...oe?{animation:oe,pointerEvents:"none"}:{}},children:[pl("flopay-direct-paypal-gate-debug"),yl("flopay-stripe-gate-debug"),Ho&&Pt&&Je(Lo,{children:[Re&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(da.Provider,{value:P,children:u(Xa,{sessionId:e,nonce:t,billingApiUrl:J,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,clientId:Pt.clientId,environment:Pt.environment,currency:In.toUpperCase(),isSubscription:ce,providerObjectType:Ot,approvalPresentation:Aa==="popup"?void 0:Aa,onTokenizedBody:Jn,onComplete:s,onErrorChange:me,onDecline:m,onCancel:C,onTechnicalFailure:yo,onButtonClick:pe,runBeforeButtonClick:pr,isProcessing:nt,onLoadStateChange:ki,onInitializationStateChange:Ii,session:be,existingOrderId:Re?.orderId,debug:_},Re?.orderId??"fresh")})]}),Go&&u(lo,{stripe:Ko,options:As,children:u(_c,{sessionId:e,nonce:t,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,billingApiUrl:J,onTokenizedBody:Jn,onErrorChange:me,isProcessing:nt,onButtonClick:pe,onDecline:m,onTechnicalFailure:yo,runBeforeButtonClick:pr,onLoadStateChange:Ws,placeholderBorderRadius:eo,popupCapabilityOwner:P,externalTelemetryContext:Qs,presentationMode:mo})}),go?u(lo,{stripe:On,options:Ms,children:u(Ec,{sessionId:e,nonce:t,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,billingApiUrl:J,intentKind:He>0?"payment":"setup",expressMethods:fo,onTokenizedBody:Jn,onErrorChange:me,onButtonClick:pe,onDecline:m,onTechnicalFailure:yo,runBeforeButtonClick:pr,onLoadStateChange:Hs,placeholderBorderRadius:eo,popupCapabilityOwner:P,externalTelemetryContext:Ke})}):null,!go&&Xs?u("div",{style:{height:oa,borderRadius:eo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Yo&&u(Tc,{sessionId:e,nonce:t,email:$.email,billingName:[$.firstName,$.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:v,billingApiUrl:J,paymentElementMethods:Ta,stripeInstance:On,paymentElementBaseOptions:wi,futureUseSession:we,onTokenizedBody:Jn,onErrorChange:me,onButtonClick:pe,onDecline:m,runBeforeButtonClick:pr,onLoadStateChange:Gs,isProcessing:nt,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:b.submitButton,onExpandApm:We,expandedApmMethod:on,themeId:It,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:eo}}),G&&u("button",{type:"button",onClick:async()=>{nt||!(await pr("card")).proceed||(pe?.("card"),j())},disabled:nt,style:{width:"100%",...M,...b.cardButton,...gs({themeBundle:re,resolvedPrimaryColor:to,resolvedBorderRadius:an,submitButtonStyle:b.submitButton,explicitPrimaryColor:Xn?.colorPrimary}),fontSize:b.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:nt?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:nt?.6:1},onMouseEnter:ae=>{!nt&&(re||Xn?.colorPrimary)&&(ae.currentTarget.style.backgroundColor=fd)},onMouseLeave:ae=>{(re||Xn?.colorPrimary)&&(ae.currentTarget.style.backgroundColor=to)},onMouseDown:ae=>{ae.currentTarget.style.transform="scale(0.985)"},onMouseUp:ae=>{ae.currentTarget.style.transform="scale(1)"},children:u(So,{content:ut})}),Q&&Ue==="buttons"&&u(xo,{margin:"0.25rem 0",styleOverride:b.errorBanner,children:Q})]}),G&&y&&u("div",{style:{gridArea:"1 / 1",...A?{animation:A}:{},...Ue==="collapsing"?{pointerEvents:"none"}:{}},children:ul}),R&&ml&&on&&Oa&&On&&u("div",{style:{gridArea:"1 / 1",...vo?{animation:vo}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Je("div",{style:{backgroundColor:Ti,borderRadius:Fi,...ea,padding:Bi},children:[Je("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Je("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:u("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(wo,{content:at})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Ai,paddingRight:80,...b.title},children:`Pay with ${va(on)}`})]}),u(lo,{stripe:On,options:Oa,children:u(us,{method:on,sessionId:e,nonce:t,email:$.email,billingName:[$.firstName,$.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:v,billingApiUrl:J,onTokenizedBody:Jn,onErrorChange:me,onDecline:m,onCancel:Wt,runBeforeButtonClick:pr,onButtonClick:pe,isProcessing:nt,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:b.submitButton,errorText:Q})},on)]})})]})]})}return ml&&on&&Oa&&On&&R?Je("form",{onSubmit:_i,className:L,noValidate:!0,style:{position:"relative"},children:[u(qa,{}),ne&&u(Rr,{status:ne,errorMessage:Q,authorized:Cn}),u("div",{style:{...vo?{animation:vo}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Je("div",{style:{backgroundColor:Ti,borderRadius:Fi,...ea,padding:Bi},children:[Je("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Je("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:u("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(wo,{content:at})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Ai,paddingRight:80,...b.title},children:`Pay with ${va(on)}`})]}),u(lo,{stripe:On,options:Oa,children:u(us,{method:on,sessionId:e,nonce:t,email:$.email,billingName:[$.firstName,$.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:v,billingApiUrl:J,onTokenizedBody:Jn,onErrorChange:me,onDecline:m,onCancel:Wt,runBeforeButtonClick:pr,onButtonClick:pe,isProcessing:nt,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:b.submitButton,errorText:Q})},on)]})})]}):Je("form",{onSubmit:_i,className:L,noValidate:!0,style:{position:"relative"},children:[u(qa,{}),ne&&u(Rr,{status:ne,errorMessage:Q,authorized:Cn}),Je("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[pl("flopay-direct-paypal-gate-debug-default"),yl("flopay-stripe-gate-debug-default"),Ho&&Pt&&Je(Lo,{children:[Re&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(da.Provider,{value:P,children:u(Xa,{sessionId:e,nonce:t,billingApiUrl:J,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,clientId:Pt.clientId,environment:Pt.environment,currency:In.toUpperCase(),isSubscription:ce,providerObjectType:Ot,approvalPresentation:Aa==="popup"?void 0:Aa,onTokenizedBody:Jn,onComplete:s,onErrorChange:me,onDecline:m,onCancel:C,onTechnicalFailure:yo,onButtonClick:pe,runBeforeButtonClick:pr,isProcessing:nt,onLoadStateChange:ki,onInitializationStateChange:Ii,session:be,existingOrderId:Re?.orderId,debug:_},Re?.orderId??"fresh")})]}),Go&&u(lo,{stripe:Ko,options:As,children:u(_c,{sessionId:e,nonce:t,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,billingApiUrl:J,onTokenizedBody:Jn,onErrorChange:me,isProcessing:nt,onButtonClick:pe,onDecline:m,onTechnicalFailure:yo,runBeforeButtonClick:pr,onLoadStateChange:Ws,placeholderBorderRadius:eo,popupCapabilityOwner:P,externalTelemetryContext:Qs,presentationMode:mo})}),go&&u(lo,{stripe:On,options:Ms,children:u(Ec,{sessionId:e,nonce:t,email:$.email,billingName:Ge||void 0,onBuyerIdentityReady:v,billingApiUrl:J,intentKind:He>0?"payment":"setup",expressMethods:fo,onTokenizedBody:Jn,onErrorChange:me,onButtonClick:pe,onDecline:m,onTechnicalFailure:yo,runBeforeButtonClick:pr,onLoadStateChange:Hs,placeholderBorderRadius:eo,popupCapabilityOwner:P,externalTelemetryContext:Ke})}),Yo&&u(Tc,{sessionId:e,nonce:t,email:$.email,billingName:[$.firstName,$.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:J,paymentElementMethods:Ta,stripeInstance:On,paymentElementBaseOptions:wi,futureUseSession:we,onTokenizedBody:Jn,onErrorChange:me,onButtonClick:pe,onDecline:m,runBeforeButtonClick:pr,onLoadStateChange:Gs,isProcessing:nt,submitButtonColor:to,submitButtonBorderRadius:an,submitButtonStyle:b.submitButton,themeId:It,onExpandApm:We,expandedApmMethod:on,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:eo}})]}),G&&(ld||sd||cd)&&u(hl,{label:"or pay with card"}),G&&ul]})}import{Fragment as Ar,jsx as ye,jsxs as hn}from"react/jsx-runtime";var zo=44,ks="flopay_checkout_saved_payment_resume",gi=new Map,mi=new Map;function $c(e,t){t.settled&&t.consumers===0&&gi.get(e)===t&&gi.delete(e)}function Zp(e,t,n){let o=mi.get(e);if(o&&(!o.sdkGeneratedIdempotencyKey||!t||o.sdkGeneratedIdempotencyKey===t))return o.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};mi.set(e,i);let s=()=>{mi.get(e)===i&&mi.delete(e)};return a.then(s,s),a}function ba(e){return new Promise(t=>setTimeout(t,e))}function fi(e,t,n){let o=Ya({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Zc,enabled:t!==!1});return o.beginCheckout(n),o}function Sa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function vs(e,t,n,o,a,i){let s=fi(e,t,n);s.error({errorCode:o,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Sa(s)}function Wc(e,t,n,o){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...o===void 0?{}:{attempt:o},statusClass:"2xx"})}function Vc(e,t,n,o,a){let i=Yc(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-o),durationMode:"machine",requestCategory:n,attempt:a,statusClass:i.statusClass}),t instanceof Mn&&t.code==="session_auto_completed"?!1:t instanceof Mn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function Cs(e){return!e||e.data.stripe?.publishableKey?!1:!!Jc(e.data.paypal)?.clientId}var Qp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function ey(e){return new $p(Qp,{publishableKey:"provider_unavailable",...e})}async function bs(e,t){let{publishableKey:n,paypalPublishableKey:o}=Zi(e);return{...await Qi({publishableKey:n,paypalPublishableKey:o,...t}),publishableKey:n,paypalPublishableKey:o}}function Is(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ty(){if(!Is())return null;try{let e=window.sessionStorage.getItem(ks);return e?JSON.parse(e):null}catch{return null}}function Hc(e){if(Is())try{window.sessionStorage.setItem(ks,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ss(){if(Is())try{window.sessionStorage.removeItem(ks)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ny(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let o of t)e.searchParams.has(o)&&(e.searchParams.delete(o),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Kc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function ws(e,t){return Jp(!!e,t)}function ry(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Gc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function oy(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function Rs({sessionId:e,nonce:t,createSession:n,billingApiUrl:o,telemetry:a,appearance:i,locale:s,loading:l,error:m,onComplete:C,onError:T,onInstrument:I,onDecline:N,onCancel:ue,onCountryChange:L,onZipChange:Be,showPayPal:K=!0,showStripe:g=!0,walletPresentation:S="auto",enabledPaymentMethods:Ve,showApplePay:R=!0,showGooglePay:Xe=!0,debug:H=!1,layout:Ne,theme:ot,buttonsTheme:ze,buttonsStyles:qe,cardButtonContent:It,cardBackButtonContent:st,cardTitleContent:ee,showSecurityFooter:Bt,onButtonClick:ut,onBeforeButtonClick:at,enableAVS:fe,cardFieldOrder:ie,cardPreFormSlot:pe,avsLayout:ft,submitLabel:Ft,className:Ze,initialErrorMessage:Y=null,initialPayPalOrderId:_e,children:se,checkoutMode:O,confirmLabel:je,renderConfirmButton:Le,onSessionCompleted:Fe}){let E=Gp(o),De=cr(()=>Xc(ot),[ot]),gt=i??De?.appearance,Ee=n?"embedded_checkout":"standard_checkout",ht=ws(se,Ne),[Pe,$e]=Xt(null),[He,In]=Xt(null),_t=Nt(null),Pt=Nt(null),ce=Nt(0),[h,lt]=Xt(null),Qe=Nt(null),[_,Ce]=Xt(null),Dt=cr(()=>n?ya(n):"",[n]),de=n?`create:${Dt}`:`session:${e??""}`,kt=Gc(_),f=Nt(new Set),P=Nt(de),ge=Nt(de);na(()=>{ge.current=de,P.current!==de&&(P.current=de,f.current.clear())},[de]);let ve=Nn(w=>{if(ge.current===de){if(Yl.has(w.name)){if(f.current.has(w.name))return;f.current.add(w.name)}Tt(()=>I?.(w))}},[de,I]),et=Mo(ve,de),Ke=Nt(!1),be=Nn(w=>{if(Ke.current)return;let k=w.gateway||!kt?w:{...w,gateway:kt};ve(k)},[ve,kt]);hr(()=>{et({class:"lifecycle",name:"checkout.mount"})},[et]);let[we,Ot]=Xt(e??""),p=e??we,Oe=n?"":p,[he,Se]=Xt(!0),[J,z]=Xt(null),[Pn,Wn]=Xt(0),[Zt,zt]=Xt("full"),[pt,Ln]=Xt(!1),[An,Qt]=Xt(Y),[Vn,yt]=Xt(null),[Pr,Vt]=Xt(null),[rr,Un]=Xt(!1),[zn,Ht]=Xt(void 0),[un,Hn]=Xt(""),[Me,it]=Xt(!1),[Rn,qt]=Xt(!1),[en,pn]=Xt(!1),Kt=Nt(null),jt=Nt(0),vn=Nt(void 0),[ke,tn]=Xt("loading"),[Cn,xr]=Xt(0),xn=Nt(!1),Bn=Nt(!1),vr=Nt(!1),Qn=Nt(null),nn=Nt(null),G=cr(()=>({checkoutMode:O??Zt,layout:ry(se,Ne)}),[O,se,Zt,Ne]),yn=Nt(C);yn.current=C;let qn=Nt(T);qn.current=T;let U=Nt(N);U.current=N;let vt=Nn(w=>ni(Qn,async k=>{try{return await w(k)}catch(j){throw k.aborted?Fo(j):j}}),[]);hr(()=>()=>{Qn.current?.abort(),Qn.current=null},[]);let x=Nn((w,k)=>{_t.current=w,In(w),Qe.current=k,lt(k)},[]),$t=Nn(()=>{let w=Pt.current;w&&(Pt.current=null,w.destroy())},[]);hr(()=>{gn(He)?.setCheckoutContext(G),h&&h!==He&&gn(h)?.setCheckoutContext(G)},[He,h,G]);let rn=Nt(Fe);rn.current=Fe;let X=Nn(w=>{tn(w),!(w!=="exhausted"||vr.current)&&(vr.current=!0,qn.current?.(new Mn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Lt=Nn(()=>{tn("retrying"),xr(w=>w+1)},[]);hr(()=>{tn("loading"),xr(0),vr.current=!1},[p]),hr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Zc,checkout_type:Ee,checkout_layout:ht,billing_api_url:E})},[ht,Ee,E]);let q=cr(()=>n?ya(n,!0):"",[n]),Et=cr(()=>un===q?zn:void 0,[zn,un,q]),mn=cr(()=>n?ji(n,Et):void 0,[n,Et]),Fn=O??mn?.checkoutMode??"full",Gt=cr(()=>mn?{...mn,checkoutMode:Fn}:void 0,[mn,Fn]);hr(()=>{Ht(void 0),Hn(q),vn.current=void 0,Kt.current=null,pn(!1)},[q]),hr(()=>{Qt(Y)},[Y]);let Cr=Nn((w,k,j)=>{Tt(()=>{U.current?.(fn(w,k,j))})},[]),Br=Nn(async(w,k)=>{Qt(null),Vt(null),Un(!1),yt("processing");let j=k?.sessionId??w.id,te=w.clientSecret||t,We=Gc(w),Wt=_t.current??Qe.current,ne=gn(Wt),W=Wt?null:fi(E,a,G),B={log:d=>{ne?ne.log(d):W?.log(d)},error:d=>{ne?ne.error(d):W?.error(d)},terminal:d=>{ne?ne.terminal(d):W?.terminal(d)},performance:d=>{ne?ne.performance(d):W?.performance(d)},now:()=>ne?.now()??W?.now()??0,elapsed:d=>ne?.elapsed(d)??Math.max(0,(W?.now()??d)-d)},Z=B.now(),F=!!(k?.initialAutoProcessingError||k?.initialAutoProcessingPending),Ae=!1,D,Ie=()=>{Ae||(Ae=!0,F=!0,D=B.now(),B.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Re=!1,Ct=()=>{Re||(Re=!0,B.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),B.performance({stage:"processing",durationMs:B.elapsed(Z),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),D!==void 0&&B.performance({stage:"recovery",durationMs:B.elapsed(D),durationMode:"machine",paymentMethodCategory:"saved"}))};B.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Ke.current=!0;try{B.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Ke.current=!1}et({class:"lifecycle",name:"payment.processing.started",provider:We}),F&&Ie();let Sn;try{let d=mc(k?.initialAutoProcessingError),c=k?.initialAutoProcessingError?.type==="3ds_required"&&!k.initialAutoProcessingError.threeDSecureToken&&k.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:k.initialAutoProcessingError.nextActionRedirectUrl}:null,v,Q=re=>(Ie(),vt(b=>Do(re,{billingApiUrl:E,sessionId:j,nonce:te,session:w,signal:b})));if(c)v=await Q(c);else if(d)Ie(),d.type==="paypal_redirect_required"&&nn.current?.publishableKey&&Hc({sessionId:j,publishableKey:nn.current.publishableKey,paypalPublishableKey:nn.current.paypalPublishableKey}),v=await vt(re=>ai(d,{flopay:_t.current,paypalFlopay:Qe.current,attempt3DS:k?.attempt3DS,billingApiUrl:E,sessionId:j,session:w,telemetry:!1,signal:re})),d.type==="paypal_redirect_required"&&Ss();else if(k?.initialAutoProcessingPending){let re=k.initialAutoProcessingPending,b=new yi(E,{telemetry:!1}),tt=await vt(nt=>b.waitForCheckoutSessionCompletion(re.sessionId,{initialDelayMs:re.retryAfterMs,nonce:te,statusUrl:re.statusUrl,signal:nt})),cn=Kr(tt,w),wn=tt.autoProcessingError?.type==="3ds_required"&&tt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:tt.autoProcessingError.nextActionRedirectUrl}:null;if(wn)v=await Q(wn);else{if(!Ur(cn))throw Ro(cn);v=Lr(cn,j)}}else{if(k?.initialAutoProcessingError)throw Er(k.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:k.initialAutoProcessingError.checkoutMethod});if(k?.fromCreateSession)return k?.fallbackToFull&&(zt("full"),Kc("full")),!1;{let re=await Oo({billingApiUrl:E,sessionId:j,session:w,nonce:te,telemetry:!1});re.type==="success"?v=re.result:re.type==="next_action_required"?v=await Q(re):(Ie(),re.type==="paypal_redirect_required"&&nn.current?.publishableKey&&Hc({sessionId:j,publishableKey:nn.current.publishableKey,paypalPublishableKey:nn.current.paypalPublishableKey}),v=await vt(b=>ai(re,{flopay:_t.current,paypalFlopay:Qe.current,attempt3DS:k?.attempt3DS,billingApiUrl:E,sessionId:j,session:w,telemetry:!1,signal:b})),re.type==="paypal_redirect_required"&&Ss())}}j&&Bo(j),Ct(),F&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),B.terminal({outcome:v.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Un(v.status==="authorized"),yt("success"),await ba(600),Sn=()=>yn.current?.(v)}catch(d){let c=Hr(ga(d),j);if(c.code==="three_ds_aborted")return!1;let v=c.checkoutMethod??fa;Qt(c.message),Vt(c.message),Un(!1),k?.fallbackToFull&&(B.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),zt("full"),Kc("full")),Ct();let Q=c.statusCode===void 0?void 0:Xp(c.statusCode,"unknown"),re=Q==="4xx"?{requestCategory:"process_payment",statusClass:Q}:{},b=Q===void 0||Q==="4xx";if(b&&(c.telemetryOutcome==="payment_declined"||!!(c.declineCode||c.code?.toLowerCase().includes("declin"))))B.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...re});else if(b&&(c.telemetryOutcome==="validation_rejected"||c.type==="validation_error"))B.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...re});else{let wn=Yc(d,F?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),nt=c.telemetryRequestCategory??"process_payment";Ke.current=!0;try{B.error({...wn,...c.telemetryFailureCategory?{failureCategory:c.telemetryFailureCategory}:{},stage:F?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:nt})}finally{Ke.current=!1}et({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:nt,provider:We})}return Tt(()=>qn.current?.(c)),Cr(v,c,{code:c.code,declineCode:c.declineCode}),yt("error"),await Promise.allSettled([ba(400),k?.ensureProvidersReady?k.ensureProvidersReady():Promise.resolve()]),F&&(B.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),B.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ct(),W&&Sa(W),yt(null),Vt(null)}return Tt(Sn),!0},[Cr,et,t,E,vt,a,G]);hr(()=>{if(typeof window>"u"||Bn.current)return;let w=new URLSearchParams(window.location.search),k=w.get("payment_intent_client_secret");if(!k)return;let j=ty();j&&(Bn.current=!0,(async()=>{let te,We=0;Qt(null),Vt(null),yt("processing"),Ln(!0);try{if(w.get("redirect_status")==="failed")throw Object.assign(new Mn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Wt,paypalFlopay:ne}=await Qi({publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey,billingApiUrl:E,locale:s,telemetry:a});te=gn(ne??Wt),te?.setCheckoutContext(G),We=te?.now()??0,te?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),te?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let W=(ne??Wt)?.getRawProvider();if(!W)throw Object.assign(new Mn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:Z}=await W.retrievePaymentIntent(k);if(Z)throw Object.assign(new Mn(Z.message??"Failed to retrieve PayPal payment status.","api_error",{code:Z.code}),{checkoutMethod:"paypal"});let F=Ul(B?.status);if(!B||F==="failed")throw Object.assign(new Mn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ae=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,D=F;if(j.sessionId){let Ct=(await new yi(E,{telemetry:!1}).getUnifiedCheckoutSession(j.sessionId)).data.session;if(Ct&&Ct.status!=="complete"){let Sn=await Oo({billingApiUrl:E,sessionId:j.sessionId,session:Ct,telemetry:!1,tokenizedData:{id:Ae??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(Sn.type!=="success")throw Object.assign(new Mn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});D=Sn.result.status}}j.sessionId&&Bo(j.sessionId),te?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),te?.performance({stage:"redirect_resume",durationMs:te.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),te?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),yt("success"),await ba(600),Tt(()=>yn.current?.({status:D,paymentIntentId:B.id,paymentMethodId:Ae,checkoutMethod:"paypal"}))}catch(Wt){let ne=Hr(ga(Wt),j.sessionId),W=ne.checkoutMethod??"paypal",B=!!(ne.declineCode||ne.code?.toLowerCase().includes("declin"));if(te)te.performance({stage:"redirect_resume",durationMs:te.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):te.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let Z=fi(E,a,G);Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Sa(Z)}else vs(E,a,G,"REDIRECT_RESUME_FAILED","redirect_resume");Qt(ne.message),Vt(ne.message),Tt(()=>qn.current?.(ne)),Cr(W,ne,{code:ne.code,declineCode:ne.declineCode}),yt("error"),await ba(400)}finally{Ss(),ny(),yt(null),Vt(null),Ln(!1)}})())},[Cr,s,E,a,G]);let br=Nt(null),Sr=cr(()=>Gt?ya(Gt):"",[Gt]),Fr=Nt(Gt);Fr.current=Gt,hr(()=>{Ot(e??"")},[e]),hr(()=>{xn.current=!1,Qt(Y),Vt(null),Un(!1),yt(null)},[Sr,Y,e]);async function $r(w,k,j){let te=fi(E,a,G),We=new yi(E,{telemetry:!1}),Wt=!1;try{let ne=w.idempotencyKey===void 0?void 0:qc(w.idempotencyKey),W=lc(k,j),B=sc(k,j);W?.canonicalIdentity===j&&B&&B.canonicalIdentity===void 0&&(Qa(k,j,B.idempotencyKey),B={...B,canonicalIdentity:j});let Z=ne??(B?.canonicalIdentity===j?B.idempotencyKey:void 0),F,Ae=!1;te.log({name:W?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let D=W?.sid??null,Ie=null,Re,Ct,Sn=!1;if(D)try{Ie=await We.getUnifiedCheckoutSession(D,W?.nonce),W&&W.canonicalIdentity===void 0&&(ic(Ie.data.session,w)?(ei(k,j,D,W.nonce??Ie.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(Qa(k,j,B.idempotencyKey),Z??(Z=B.idempotencyKey))):(Za(k,j),B=null,Z=ne,D=null,Ie=null));let c=Ie?.data.session?.status,v=Ie?.data.session,Q=v?.clientSecret||W?.nonce;if(D&&v?.buyerIdentified===!1&&Q&&(Ct=Io(We,D,Q,w.account)),D&&Ie&&c==="complete"){if(Yi(D))return{sid:D,result:Ie};Za(k,j),D=null,Ie=null,Ae=!0}}catch{te.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),W?.canonicalIdentity===void 0?(Za(k,j),Z=ne):Gi(k,j),D=null}if(!D){!ne&&(Ae||!Z)&&(Z=qc(),F=Z),Z&&Qa(k,j,Z);let c=te.now(),v=0;te.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Q={...w,idempotencyKey:Z,avsCheck:!!fe,avsConfig:typeof fe=="object"?fe:void 0,checkoutType:"embedded_checkout",checkoutLayout:ws(se,Ne)};Object.defineProperty(Q,Wp,{configurable:!1,enumerable:!1,value:{onAttempt:tt=>{v=Math.max(v,tt)}}});let re=()=>{Wc(te,"session_create",c,v)},b=tt=>{Vc(te,tt,"session_create",c,v)&&et({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Hp(Q)){let tt=await We.createDetachedSession(Q);tt.claimed.catch(()=>{}),Ie=tt.shell,D=tt.sessionId,Ct=tt.claim;let cn=te.now();te.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Re=tt.claimed.then(wn=>{let nt=wn.data.session?.id??tt.sessionId;return nt&&ei(k,j,nt,wn.data.session?.clientSecret??tt.nonce),Wc(te,"session_claim",cn),re(),wn},wn=>{throw Gi(k,j),Vc(te,wn,"session_claim",cn,0)&&et({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),wn}).finally(()=>Sa(te)),Re.catch(()=>{}),Wt=!0,te.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),te.performance({stage:"session_shell",durationMs:te.now()-c,durationMode:"machine",requestCategory:"session_create",attempt:v,statusClass:"2xx",paymentMethodCategory:"card"})}else Ie=await We.createAndFetchSession(Q),re()}catch(tt){throw b(tt),tt}D=Ie.data.session?.id??D??"",D&&!Re&&ei(k,j,D,Ie.data.session?.clientSecret)}let d=Ie?.data.session;return!Ct&&D&&d?.buyerIdentified===!1&&d.clientSecret&&(Ct=Io(We,D,d.clientSecret,w.account)),{sid:D??"",result:Ie,sdkGeneratedIdempotencyKey:F,...Re?{claimed:Re}:{},...Ct?{claim:Ct}:{},...Sn?{claimRequiresIdentity:!0}:{}}}finally{Wt||Sa(te)}}let Wr=Nt($r);na(()=>{Wr.current=$r},[$r]);let _n=Nn(async(w,k)=>{let j=Fr.current;if(!j)throw new Mn("createSession is required to bootstrap checkout.","validation_error");let te=ji(j,w),We=ya(te),Wt=ac(te),ne=gi.get(We);if(!ne){let Z={canonicalIdentity:We,promise:Wr.current(te,Wt,We),consumers:0,settled:!1};ne=Z,gi.set(We,Z);let F=()=>{Z.settled=!0,$c(We,Z)};Z.promise.then(F,F)}ne.consumers+=1;let W=!1,B=()=>{W||(W=!0,ne.consumers-=1,$c(We,ne))};k?.(B);try{let Z=await ne.promise;br.current=We,w&&(Hn(q),Ht(d=>Bl(d,w)));let{sid:F,result:Ae,claimed:D,claim:Ie,claimRequiresIdentity:Re}=Z;if(vn.current=Ie,pn(Re===!0),$e(Ae),Ae.data.session&&Ce(Ae.data.session),F&&Ot(F),D){jt.current+=1;let d=jt.current;Kt.current=D,qt(!0),D.then(c=>{jt.current===d&&(Kt.current===D&&(Kt.current=null),$e(c),c.data.session&&Ce(c.data.session),qt(!1),pn(!1))},c=>{jt.current===d&&(Kt.current===D&&(Kt.current=null),qt(!1),pn(!1),z(c instanceof Mn?c:new Mn(c instanceof Error?c.message:"Failed to create session","api_error")))})}else jt.current+=1,Kt.current=null,qt(!1),pn(!1);let{flopay:Ct,paypalFlopay:Sn}=await bs(Ae,{billingApiUrl:E,locale:s,telemetry:a}).catch(d=>{throw Ol(d,F||Ae.data.session?.id)});return x(Ct,Sn),Se(!1),Z}catch(Z){throw br.current===We&&(br.current=null),Z}finally{k||B()}},[q,x,s,E,a]),Dr=Nt(Br);Dr.current=Br;let or=Nt(_n);or.current=_n;let At=Nn(async w=>{if(!oy(w)||Me)return{sessionId:we,session:_};it(!0);try{let k=await _n(w);return{sessionId:k.sid,session:k.result.data.session??null}}finally{it(!1)}},[_n,Me,we,_]),Kn=Nn(async w=>{let k=vn.current;if(!k)return;let j=jt.current,te=await k(w);jt.current===j&&($e(te),te.data.session&&Ce(te.data.session))},[]),Gn=Nn(async()=>{await Kt.current},[]),er=Nn(async()=>(await Gn(),{proceed:!0}),[Gn]);hr(()=>{let w=!1,k,j=++ce.current;$t(),z(null),Wn(0);let te=()=>{w=!0,ce.current===j&&(ce.current+=1,$t())},We=Fr.current;if(Sr&&We)return zt(Fn),Se(!1),br.current===Sr?te:(Ce(Fl(We,O)),(async()=>{let W=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=Fn==="auto"&&!xn.current&&!W;B&&(Qt(null),Vt(null),yt("processing"));let Z=!1;try{let F=await or.current(void 0,Re=>{k=Re});Z=!0;let Ae=F.result.data.session??null;nn.current=Zi(F.result);let D=Cs(F.result),Ie=Yi(F.sid||Ae?.id);if(!w&&B&&Ae&&!D&&!Ie){xn.current=!0,await Zp(Sr,F.sdkGeneratedIdempotencyKey,()=>Dr.current(Ae,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:F.result.autoProcessingError,initialAutoProcessingPending:F.result.autoProcessingPending,autoProcessingAttempted:F.result.autoProcessingAttempted,sessionId:F.sid||Ae.id}));return}!w&&B&&((D||Ie)&&(xn.current=!0),yt(null),Vt(null))}catch(F){if(w)return;let Ae=$a(F);if(B&&Ae==="session_auto_completed"){xn.current=!0,yt("success"),await ba(600),w||(Tt(()=>{yn.current?.({status:"succeeded"})}),yt(null),Vt(null));return}if(B&&(yt(null),Vt(null)),!Z){let Ie=Nl(F),Re=jc(F,Ie?{stage:"provider_load",provider:"stripe",...Ie}:{stage:"session_request"});(Ie||!(F instanceof Mn))&&Tt(()=>qn.current?.(Re)),z(Re);return}let D=F instanceof Mn?F:new Mn(F instanceof Error?F.message:"Failed to create session","api_error");z(D)}finally{k?.(),k=void 0}})(),()=>{te(),k?.()});Se(!0);async function Wt(){let W=!1,B=!1,Z=null;try{let F=new yi(E,{telemetry:!1}),Ae=await F.getUnifiedCheckoutSession(p,t);if(B=!0,Z=Ae,w)return;$e(Ae);let D=Ae.data.session??null;if(Ce(D),!D)throw new Mn("No session data returned","api_error");let Ie=D.checkoutMode;if(Ie==="setup")throw new Mn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(D.status==="authorized"){Se(!1),Tt(()=>{yn.current?.(Lr(D,p)),rn.current?.(D.successUrl??"")});return}if(D.status==="complete"){Se(!1),Tt(()=>{rn.current?.(D.successUrl??"")});return}if(D.status==="expired")throw ja(D);W=!0;let Re=O??Ie??"full";zt(Re),jt.current+=1;let Ct=D.clientSecret||t;vn.current=D.buyerIdentified===!1&&Ct?Io(F,p,Ct,{...D.customer?.id?{userId:D.customer.id}:{}}):void 0,qt(!1),pn(!1);let Sn=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),d=Cs(Ae);if(Re==="auto"&&!xn.current&&!Sn&&!d){xn.current=!0;let c=ne(Ae);try{if(await Dr.current(D,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>c,sessionId:p||D.id}),w)return;await c,w||Se(!1);return}catch{if(w)return;await c,w||Se(!1);return}}await ne(Ae),w||Se(!1)}catch(F){if(w)return;let Ae=xl(F,W);if(W&&et({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),Ae){let{errorCode:Ct,stage:Sn,...d}=Ae;vs(E,a,G,Ct,Sn,d)}if(Ae?.stage==="provider_load"&&(O??Z?.data.session?.checkoutMode??"full")==="full"&&Al(Z,K,g)){let Ct=ey({billingApiUrl:E,locale:s,telemetry:a});Pt.current=Ct,x(Ct,null),Wn(1),Se(!1);return}let D=Ae?.stage==="provider_load",Ie="session_request";D?Ie="provider_load":B&&(Ie="post_session");let Re=jc(F,{stage:Ie,provider:"stripe",sessionId:p||void 0});(D||!(F instanceof Mn))&&Tt(()=>qn.current?.(Re)),z(Re),Se(!1)}}async function ne(W){let{flopay:B,paypalFlopay:Z,...F}=await bs(W,{billingApiUrl:E,locale:s,telemetry:a});nn.current={publishableKey:F.publishableKey,paypalPublishableKey:F.paypalPublishableKey},x(B,Z),Wn(0)}return Wt(),te},[O,Sr,Fn,Oe,t,K,g]);let Yn=Nn(async()=>{if(!Pe||Pn!==1)return;let w=ce.current;Wn(2);try{let{flopay:k,paypalFlopay:j}=await bs(Pe,{billingApiUrl:E,locale:s,telemetry:a});if(ce.current!==w)return;$t(),x(k,j),Wn(0)}catch(k){if(ce.current!==w)return;let{errorCode:j,stage:te,...We}=qi(k);vs(E,a,G,j,te,We)}},[$t,x,s,Pn,E,a,G,Pe]),Ue=!!(p&&(_?.clientSecret||t)),ln=pt||!Ue,on=Nn(async()=>{if(!(pt||!Ue||!_)){Ln(!0),Qt(null);try{await Br(_,{attempt3DS:!0,fallbackToFull:!0,sessionId:p||_.id})}finally{Ln(!1)}}},[p,pt,Ue,Br,_]),jn=Jc(Pe?.data.paypal,_e),Qr=Cs(Pe),Or=cr(()=>{if(!(!Pe||!_||!Pe.data.stripe?.publishableKey))return{billingApiUrl:E}},[Pe,_,E]),dr=!!(n&&!se&&Ne==="buttons"&&at&&Fn==="full"),tr=!!(p&&(Kp(_?.vault)||oo(_))),bn=cr(()=>({session:_,loading:he,error:J,checkoutMode:Zt,inlineSessionDraft:Gt,applyInlineSessionPatch:dr?At:void 0,inlineSessionPatchProcessing:Me,claimPending:Rn,claimRequiresIdentity:en,claimBuyerIdentity:Kn,waitForDataAttachment:Gn}),[_,he,J,Zt,Gt,dr,At,Me,Rn,en,Kn,Gn]),Nr=!!n&&Ne==="buttons"&&!Qr&&!tr&&(!He||!Or),Dn=Vn?ye(Rr,{status:Vn,errorMessage:Pr,authorized:rr}):null;if(he&&!tr){if(l)return hn(Ar,{children:[l,Dn]});if(Ne==="buttons"){let w=De?.buttonsLayout?.cardButton?.borderRadius??De?.appearance.variables?.borderRadius??8,k=j=>ye("div",{style:{height:j,borderRadius:w,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return hn(Ar,{children:[hn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[K&&k(zo),g&&(R||Xe)&&k(zo),g&&k(zo),ye("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Dn]})}return hn(Ar,{children:[hn("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ye("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ye("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Dn]})}return J?m?ye(mr.Provider,{value:bn,children:m(J)}):ye(mr.Provider,{value:bn,children:ye("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:J.message})}):Nr?hn(Ar,{children:[ye(mr.Provider,{value:bn,children:ye(iy,{onButtonClick:ut,showPayPal:K,showStripe:g,showApplePay:R,showGooglePay:Xe,theme:ot,buttonsTheme:ze,buttonsStyles:qe,cardButtonContent:It,cardBackButtonContent:st,cardTitleContent:ee})}),Dn]}):Qr&&_&&jn?hn(Ar,{children:[ye(mr.Provider,{value:bn,children:hn("div",{className:Ze,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[An&&ye(xo,{icon:!1,children:An}),ke==="retrying"&&ye("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),ke==="exhausted"&&hn("div",{role:"alert",children:[ye("div",{children:"PayPal is temporarily unavailable. Please try again."}),ye("button",{type:"button",onClick:Lt,children:"Retry PayPal"})]}),ke!=="exhausted"&&ye("div",{"aria-hidden":ke==="retrying"?!0:void 0,style:ke==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ye(rc,{sessionId:p,nonce:_.clientSecret||void 0,billingApiUrl:E,email:_.customer?.email||Gt?.account?.email,billingName:[_.customer?.firstName,_.customer?.lastName].filter(Boolean).join(" ")||[Gt?.account?.firstName,Gt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Kn,clientId:jn.clientId,environment:jn.environment,currency:(_.currency??"usd").toUpperCase(),isSubscription:_.mode==="subscription",providerObjectType:jn.providerObjectType,approvalPresentation:jn.approvalPresentation,existingOrderId:jn.existingOrderId,onComplete:C,onErrorChange:Qt,onDecline:N,onCancel:ue,onButtonClick:ut,runBeforeButtonClick:er,onInitializationStateChange:X,allowAutomaticRetry:Cn===0,session:_,telemetry:a,telemetryContext:G,onInstrument:be,debug:H},`${de}:paypal-init-${Cn}`)})]})}),Dn]}):Zt==="confirm"?hn(Ar,{children:[ye(mr.Provider,{value:bn,children:ye(ti,{flopay:He,paypalFlopay:h,options:Or??{billingApiUrl:E},onInstrument:be,children:hn("div",{className:Ze,children:[An&&ye("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:An}),Le?Le({onConfirm:on,isProcessing:ln}):ye("button",{type:"button",onClick:on,disabled:ln,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:ln?"not-allowed":"pointer",opacity:ln?.6:1},children:pt?"Processing...":je??"Confirm Purchase"})]})},de)}),Dn]}):(!He||!Or)&&!(tr&&Zt==="full")?ye(Ar,{children:Dn}):hn(Ar,{children:[ye(mr.Provider,{value:bn,children:hn(ti,{flopay:He,paypalFlopay:h,options:Or??{billingApiUrl:E},onInstrument:be,children:[Pn===1&&ye("button",{type:"button",onClick:Yn,children:"Retry payment methods"}),se?hn(Ar,{children:[An&&ye("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:An}),ye(ay,{sessionId:p,nonce:_?.clientSecret||void 0,billingApiUrl:E,session:_,submitLabel:Ft,walletPresentation:S,children:se})]}):ye(hs,{sessionId:p,nonce:_?.clientSecret||void 0,telemetry:a,email:_?.customer?.email||Gt?.account?.email,userId:_?.customer?.id||Gt?.account?.userId,firstName:_?.customer?.firstName||Gt?.account?.firstName,lastName:_?.customer?.lastName||Gt?.account?.lastName,totalAmount:_?Math.round(Vp(_).total*100):0,currency:_?.currency?.toLowerCase()??"usd",onComplete:C,onError:T,onDecline:N,onCancel:ue,error:An,onErrorChange:Qt,showPayPal:K,showStripe:g,walletPresentation:S,enabledPaymentMethods:Pn?[]:Ve??Pe?.data.stripe?.enabledPaymentMethods??_?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Pe?.data.stripe?.enabledPaymentMethodCountries,showApplePay:R,showGooglePay:Xe,layout:Ne,theme:ot,buttonsTheme:ze,buttonsStyles:qe,appearance:gt,cardButtonContent:It,cardBackButtonContent:st,cardTitleContent:ee,onButtonClick:ut,onBeforeButtonClick:at,onBuyerIdentityReady:Kn,enableAVS:fe,...ie?{cardFieldOrder:ie}:{},...pe?{cardPreFormSlot:pe}:{},avsLayout:ft,country:_?.customer?.country,city:_?.customer?.city,state:_?.customer?.state,onCountryChange:L,onZipChange:Be,avsCheck:!!fe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ws(se,Ne),className:Ze,submitLabel:Ft,directPaypal:jn,isSubscription:_?.mode==="subscription",session:_,dataAttachmentPending:Rn,dataAttachmentRequiresIdentity:en,debug:H})]},de)}),Dn]})}function ay({sessionId:e,nonce:t,billingApiUrl:n,session:o,submitLabel:a,walletPresentation:i,children:s}){return ye(Ar,{children:Ps.Children.map(s,l=>{if(!Ps.isValidElement(l))return l;let m=l.props,C={};return m.sessionId||(C.sessionId=e),!m.nonce&&t&&(C.nonce=t),m.billingApiUrl||(C.billingApiUrl=n),m.submitLabel===void 0&&a!==void 0&&(C.submitLabel=a),m.walletPresentation===void 0&&(C.walletPresentation=i),o?.customer&&(m.email||(C.email=o.customer.email),m.userId||(C.userId=o.customer.id),m.firstName||(C.firstName=o.customer.firstName),m.lastName||(C.lastName=o.customer.lastName)),Object.keys(C).length===0?l:Ps.cloneElement(l,C)})})}function iy({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:o,showGooglePay:a,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:m,cardBackButtonContent:C,cardTitleContent:T}){let[I,N]=Xt(!1),ue=cr(()=>Xc(i),[i]),L=cr(()=>{let S=ue?.buttonsLayout??Yp(s);return l?{...S,...l,cardButton:{...S.cardButton,...l.cardButton},cardFormContainer:{...S.cardFormContainer,...l.cardFormContainer},backButton:{...S.backButton,...l.backButton},backButtonIcon:{...S.backButtonIcon,...l.backButtonIcon},submitButton:{...S.submitButton,...l.submitButton},title:{...S.title,...l.title}}:S},[ue,s,l]),Be=ue?.buttonsLayout?.cardButton?.borderRadius??ue?.appearance.variables?.borderRadius??8,K=S=>ye("div",{style:{height:S,borderRadius:Be,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),g=m===void 0?{boxSizing:"border-box",height:zo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(I){let S=L.cardInputBorder??"#e5e7eb",Ve=L.cardInputBackground??"white",R=bo(C),Xe=bo(T);return hn("div",{style:{backgroundColor:L.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...L.cardFormContainer},children:[hn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[hn("button",{type:"button",onClick:()=>N(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:R?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...L.backButton},children:[ye("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...L.backButtonIcon},children:ye("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ye("path",{d:"M15 18l-6-6 6-6"})})}),ye(wo,{content:C})]}),Xe?ye("div",{style:{flex:1}}):ye("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...L.title},children:ye(aa,{content:T})})]}),ye("div",{style:{backgroundColor:Ve,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ye("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),hn("div",{style:{display:"flex"},children:[ye("div",{style:{flex:1,backgroundColor:Ve,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:ye("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ye("div",{style:{flex:1,backgroundColor:Ve,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:ye("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ye("div",{style:{backgroundColor:Ve,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ye("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ye("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...L.submitButton,opacity:.5}}),ye("style",{children:`
|
|
15
15
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
16
16
|
@keyframes flopay-interim-expand {
|
|
17
17
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
18
18
|
40% { opacity: 1; }
|
|
19
19
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
20
20
|
}
|
|
21
|
-
`})]})}return yn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&Z(Uo),n&&(o||a)&&Z(Uo),n&&me("button",{type:"button",onClick:()=>{e?.("card"),O(!0)},style:{width:"100%",...m,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:N.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...N.cardButton},onMouseDown:b=>{b.currentTarget.style.transform="scale(0.985)"},onMouseUp:b=>{b.currentTarget.style.transform="scale(1)"},children:me(wo,{content:u})}),me("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as dy,jsx as lo,jsxs as uy}from"react/jsx-runtime";var ay=44;function Kc(e){return new Promise(t=>setTimeout(t,e))}function iy(e,t){return e instanceof ka?e:new ka(e instanceof Error?e.message:t,"api_error")}function sy(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ly(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function cy({sessionId:e,nonce:t,createSession:n,paymentMethodId:o,checkoutMethod:a,clientId:i,products:s,items:l,subscriptions:u,account:C,successUrl:_,cancelUrl:k,couponCodes:O,tagsData:ue,utmMetadata:N,billingApiUrl:Ae,locale:Z,theme:m,appearance:b,buttonsTheme:Ve,buttonsStyles:I,onSuccess:Xe,onError:Y,onDecline:Fe,children:nt,disabled:ze=!1,type:He="button",style:It,...it}){let te=wa(()=>ny(Ae),[Ae]),xt=wa(()=>ly({createSession:n,clientId:i,products:s,items:l,subscriptions:u,account:C,successUrl:_,cancelUrl:k,couponCodes:O,tagsData:ue,utmMetadata:N}),[C,k,i,O,n,s,l,u,_,ue,N]),[ut,rt]=$o(!1),[ge,se]=$o(null),[fe,wt]=$o(null),[Bt,Qe]=$o(!1),[ne,Me]=$o(null),[de,L]=$o(null),Ue=jo(!0),De=jo(null),Oe=jo(de),M=jo(Xe),qe=jo(Y),gt=jo(Fe),_e=Ur(p=>ei(De,async v=>{try{return await p(v)}catch(we){throw v.aborted?Fo(we):we}}),[]);qo(()=>{Oe.current=de},[de]),qo(()=>{M.current=Xe},[Xe]),qo(()=>{qe.current=Y},[Y]),qo(()=>{gt.current=Fe},[Fe]),qo(()=>(Ue.current=!0,()=>{Ue.current=!1,De.current?.abort()}),[]),qo(()=>{if(typeof window>"u")return;let p=v=>{v.key==="Escape"&&L(null)};return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p)}},[]);let ht=Ur((p,v=fa)=>{gt.current?.(Sn(v,p,{code:p.code,declineCode:p.declineCode}))},[]),ve=Ur(async p=>{Ue.current&&(wt(null),Qe(p.result.status==="authorized"),se("success"),await Kc(600),Ue.current&&Lt(()=>M.current?.(p)))},[]),je=Ur(async(p,v)=>{Ue.current&&(qe.current?.(p),v?.emitDecline&&ht(p,v.method),wt(p.message),Qe(!1),se("error"),await Kc(400))},[ht]),Ke=Ur(async(p,v,we)=>{let Ce=p.data.session??null;if(!Ce)throw Wr(new ka("No session data returned","api_error"),v);let et=Ce.clientSecret||t;if(Or(Ce)){await ve({result:Dr(Ce,v),session:Ce,sessionId:Ce.id||v,autoCompleted:!1});return}if(Ce.status==="expired")throw Wr(Ua(Ce),Ce.id||v);try{if(p.autoProcessingPending){let ke=p.autoProcessingPending,Ie=new Rs(te),Dt=await _e(he=>Ie.waitForCheckoutSessionCompletion(ke.sessionId,{initialDelayMs:ke.retryAfterMs,nonce:et,statusUrl:ke.statusUrl,signal:he})),d=Vr(Dt,Ce),xe=Dt.autoProcessingError?.type==="3ds_required"&&Dt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Dt.autoProcessingError.nextActionRedirectUrl}:null;if(xe&&v&&et){let he=await _e(Re=>Do(xe,{billingApiUrl:te,sessionId:v,nonce:et,session:Ce,signal:Re,telemetry:!0}));await ve({result:he,session:Ce,sessionId:Ce.id||v,autoCompleted:!1});return}if(Dt.autoProcessingError)throw Ir(Dt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Dt.autoProcessingError.checkoutMethod});if(!Or(d))throw Eo(d);await ve({result:Dr(d,v),session:d,sessionId:d.id||v,autoCompleted:!1});return}if(p.autoProcessingError){let ke=p.autoProcessingError.nextActionRedirectUrl;if(p.autoProcessingError.type==="3ds_required"&&ke&&v&&et){let Ie=await _e(he=>dc({billingApiUrl:te,sessionId:v,nonce:et,nextActionRedirectUrl:ke,signal:he}));if(Ie.status==="declined")throw Ir({type:Ie.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ie.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:p.autoProcessingError.checkoutMethod});let d=await new Rs(te).waitForCheckoutSessionCompletion(v,{initialDelayMs:0,nonce:et}),xe=Vr(d,Ce);if(!Or(xe))throw Ir({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:p.autoProcessingError.checkoutMethod});await ve({result:Dr(xe,v),session:xe,sessionId:xe.id||v,autoCompleted:!1});return}throw Ir(p.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:p.autoProcessingError.checkoutMethod})}if(we?.fromCreateSession&&p.autoProcessingAttempted===!0)throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ge=await Oo({billingApiUrl:te,sessionId:v??Ce.id,session:Ce,nonce:et});if(Ge.type==="next_action_required"&&et){let ke=v??Ce.id,Ie=await _e(Dt=>Do(Ge,{billingApiUrl:te,sessionId:ke,nonce:et,session:Ce,signal:Dt,telemetry:!0}));await ve({result:Ie,session:Ce,sessionId:Ce.id||ke,autoCompleted:!1});return}if(Ge.type!=="success")throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await ve({result:Ge.result,session:Ce,sessionId:Ce.id||v,autoCompleted:!1})}catch(Ge){let ke=Ce.id||v,Ie=Wr(ga(Ge),ke);if(Ie.code==="three_ds_aborted")return;if(Ie.code==="checkout_processing_timeout"){if(!Ue.current)return;Me(Ie.message),Lt(()=>qe.current?.(Ie));return}await je(Ie,{emitDecline:!0,method:Ie.checkoutMethod??fa}),sy(Ie,ke)&&ke&&Ue.current&&L({sessionId:ke,errorMessage:Ie.message,nonce:et||void 0,payPalOrderId:Ie.orderId})}},[t,te,_e,je,ve]),wn=Ur(async p=>{if(it.onClick?.(p),!(p.defaultPrevented||ze||ut)){if(L(null),Me(null),e&&xt){let v=new ka("Provide either sessionId or create-session props, not both.","validation_error");await je(v),Ue.current&&(se(null),wt(null));return}if(!e&&!xt){let v=new ka("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await je(v),Ue.current&&(se(null),wt(null));return}rt(!0),wt(null),Qe(!1),se("processing");try{let v=new Rs(te);if(e){let we=await v.getUnifiedCheckoutSession(e,t);await Ke(we,e);return}try{let we=await v.createAndFetchSession({...xt});await Ke(we,we.data.session?.id??null,{fromCreateSession:!0})}catch(we){if(qa(we)==="session_auto_completed"){await ve({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw we}}catch(v){await je(Wr(iy(v,"Automatic payment failed. Please try again."),e))}finally{Ue.current&&(se(null),wt(null),rt(!1))}}},[it.onClick,xt,ze,ut,t,Ke,te,e,je,ve]),Et=Ur(p=>{let v=Oe.current;L(null),M.current?.({result:p,session:null,sessionId:v?.sessionId??null,autoCompleted:!1})},[]),Pt=Ur(p=>{qe.current?.(p)},[]),pe=Ur(p=>{gt.current?.(p)},[]),P=wa(()=>oy(m),[m]),st=wa(()=>{let p=P?.buttonsLayout??ry(Ve);return I?{...p,...I,cardButton:{...p.cardButton,...I.cardButton}}:p},[P,Ve,I]),ot=wa(()=>{let p=P?.appearance;return b?p?{...p,...b,variables:{...p.variables,...b.variables}}:b:p},[b,P]),R=ot?.variables,Se=R?.colorPrimary??"#4A49FF",Ft=R?.colorPrimaryHover??Dc(Se,.12),ye=R?.borderRadius??"8px";return uy(dy,{children:[lo("button",{...it,type:He,onClick:wn,disabled:ze||ut,"aria-busy":ut,style:{width:"100%",...nt===void 0?{boxSizing:"border-box",height:ay,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...st.cardButton,...fs({themeBundle:P,resolvedPrimaryColor:Se,resolvedBorderRadius:ye,submitButtonStyle:st.submitButton,explicitPrimaryColor:R?.colorPrimary}),fontSize:st.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ze||ut?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ze||ut?.6:1,...It},onMouseEnter:p=>{it.onMouseEnter?.(p),!p.defaultPrevented&&!ze&&!ut&&(P||R?.colorPrimary)&&(p.currentTarget.style.backgroundColor=Ft)},onMouseLeave:p=>{it.onMouseLeave?.(p),!p.defaultPrevented&&(P||R?.colorPrimary)&&(p.currentTarget.style.backgroundColor=Se)},onMouseDown:p=>{it.onMouseDown?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(0.985)")},onMouseUp:p=>{it.onMouseUp?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(1)")},children:lo(wo,{content:nt})}),ne&&lo("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ne}),ge&&lo(wr,{status:ge,errorMessage:fe,authorized:Bt}),de&&lo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:p=>{p.target===p.currentTarget&&L(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:lo("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:lo(Is,{sessionId:de.sessionId,nonce:de.nonce,checkoutMode:"full",billingApiUrl:te,locale:Z,theme:m,...ot?{appearance:ot}:{},buttonsTheme:Ve,buttonsStyles:I,initialErrorMessage:de.errorMessage,initialPayPalOrderId:de.payPalOrderId,cardTitleContent:null,onComplete:Et,onError:Pt,onDecline:pe})})})]})}import{jsx as my}from"react/jsx-runtime";var py={StripeSetupMethod:El,PayPalSetupMethod:Rl};function yy(e){return my(_l,{...e,branches:py})}export{Ya as DirectPayPalButton,cy as FloPayAutomaticPaymentButton,yd as FloPayCardSetup,pd as FloPayCardSetupError,Is as FloPayCheckout,yy as FloPayPaymentMethodSetup,Qa as FloPayProvider,gs as SplitCardForm,Bi as VaultCardFields,$f as dropThirdPartyOnlyError,Dd as useCheckout,Hr as useFloPay,$i as usePayPalFloPay};
|
|
21
|
+
`})]})}return hn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&K(zo),n&&(o||a)&&K(zo),n&&ye("button",{type:"button",onClick:()=>{e?.("card"),N(!0)},style:{width:"100%",...g,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:L.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...L.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:ye(So,{content:m})}),ye("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as fy,jsx as co,jsxs as gy}from"react/jsx-runtime";var dy=44;function Qc(e){return new Promise(t=>setTimeout(t,e))}function uy(e,t){return e instanceof ka?e:new ka(e instanceof Error?e.message:t,"api_error")}function py(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function yy(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function my({sessionId:e,nonce:t,createSession:n,paymentMethodId:o,checkoutMethod:a,clientId:i,products:s,items:l,subscriptions:m,account:C,successUrl:T,cancelUrl:I,couponCodes:N,tagsData:ue,utmMetadata:L,billingApiUrl:Be,locale:K,theme:g,appearance:S,buttonsTheme:Ve,buttonsStyles:R,onSuccess:Xe,onError:H,onDecline:Ne,children:ot,disabled:ze=!1,type:qe="button",style:It,...st}){let ee=wa(()=>sy(Be),[Be]),Bt=wa(()=>yy({createSession:n,clientId:i,products:s,items:l,subscriptions:m,account:C,successUrl:T,cancelUrl:I,couponCodes:N,tagsData:ue,utmMetadata:L}),[C,I,i,N,n,s,l,m,T,ue,L]),[ut,at]=$o(!1),[fe,ie]=$o(null),[pe,ft]=$o(null),[Ft,Ze]=$o(!1),[Y,_e]=$o(null),[se,O]=$o(null),je=jo(!0),Le=jo(null),Fe=jo(se),E=jo(Xe),De=jo(H),gt=jo(Ne),Ee=jr(f=>ni(Le,async P=>{try{return await f(P)}catch(ge){throw P.aborted?Fo(ge):ge}}),[]);qo(()=>{Fe.current=se},[se]),qo(()=>{E.current=Xe},[Xe]),qo(()=>{De.current=H},[H]),qo(()=>{gt.current=Ne},[Ne]),qo(()=>(je.current=!0,()=>{je.current=!1,Le.current?.abort()}),[]),qo(()=>{if(typeof window>"u")return;let f=P=>{P.key==="Escape"&&O(null)};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[]);let ht=jr((f,P=fa)=>{gt.current?.(fn(P,f,{code:f.code,declineCode:f.declineCode}))},[]),Pe=jr(async f=>{je.current&&(ft(null),Ze(f.result.status==="authorized"),ie("success"),await Qc(600),je.current&&Tt(()=>E.current?.(f)))},[]),$e=jr(async(f,P)=>{je.current&&(De.current?.(f),P?.emitDecline&&ht(f,P.method),ft(f.message),Ze(!1),ie("error"),await Qc(400))},[ht]),He=jr(async(f,P,ge)=>{let ve=f.data.session??null;if(!ve)throw Hr(new ka("No session data returned","api_error"),P);let et=ve.clientSecret||t;if(Ur(ve)){await Pe({result:Lr(ve,P),session:ve,sessionId:ve.id||P,autoCompleted:!1});return}if(ve.status==="expired")throw Hr(ja(ve),ve.id||P);try{if(f.autoProcessingPending){let be=f.autoProcessingPending,we=new _s(ee),Ot=await Ee(he=>we.waitForCheckoutSessionCompletion(be.sessionId,{initialDelayMs:be.retryAfterMs,nonce:et,statusUrl:be.statusUrl,signal:he})),p=Kr(Ot,ve),Oe=Ot.autoProcessingError?.type==="3ds_required"&&Ot.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ot.autoProcessingError.nextActionRedirectUrl}:null;if(Oe&&P&&et){let he=await Ee(Se=>Do(Oe,{billingApiUrl:ee,sessionId:P,nonce:et,session:ve,signal:Se,telemetry:!0}));await Pe({result:he,session:ve,sessionId:ve.id||P,autoCompleted:!1});return}if(Ot.autoProcessingError)throw Er(Ot.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Ot.autoProcessingError.checkoutMethod});if(!Ur(p))throw Ro(p);await Pe({result:Lr(p,P),session:p,sessionId:p.id||P,autoCompleted:!1});return}if(f.autoProcessingError){let be=f.autoProcessingError.nextActionRedirectUrl;if(f.autoProcessingError.type==="3ds_required"&&be&&P&&et){let we=await Ee(he=>fc({billingApiUrl:ee,sessionId:P,nonce:et,nextActionRedirectUrl:be,signal:he}));if(we.status==="declined")throw Er({type:we.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:we.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:f.autoProcessingError.checkoutMethod});let p=await new _s(ee).waitForCheckoutSessionCompletion(P,{initialDelayMs:0,nonce:et}),Oe=Kr(p,ve);if(!Ur(Oe))throw Er({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:f.autoProcessingError.checkoutMethod});await Pe({result:Lr(Oe,P),session:Oe,sessionId:Oe.id||P,autoCompleted:!1});return}throw Er(f.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.autoProcessingError.checkoutMethod})}if(ge?.fromCreateSession&&f.autoProcessingAttempted===!0)throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ke=await Oo({billingApiUrl:ee,sessionId:P??ve.id,session:ve,nonce:et});if(Ke.type==="next_action_required"&&et){let be=P??ve.id,we=await Ee(Ot=>Do(Ke,{billingApiUrl:ee,sessionId:be,nonce:et,session:ve,signal:Ot,telemetry:!0}));await Pe({result:we,session:ve,sessionId:ve.id||be,autoCompleted:!1});return}if(Ke.type!=="success")throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Pe({result:Ke.result,session:ve,sessionId:ve.id||P,autoCompleted:!1})}catch(Ke){let be=ve.id||P,we=Hr(ga(Ke),be);if(we.code==="three_ds_aborted")return;if(we.code==="checkout_processing_timeout"){if(!je.current)return;_e(we.message),Tt(()=>De.current?.(we));return}await $e(we,{emitDecline:!0,method:we.checkoutMethod??fa}),py(we,be)&&be&&je.current&&O({sessionId:be,errorMessage:we.message,nonce:et||void 0,payPalOrderId:we.orderId})}},[t,ee,Ee,$e,Pe]),In=jr(async f=>{if(st.onClick?.(f),!(f.defaultPrevented||ze||ut)){if(O(null),_e(null),e&&Bt){let P=new ka("Provide either sessionId or create-session props, not both.","validation_error");await $e(P),je.current&&(ie(null),ft(null));return}if(!e&&!Bt){let P=new ka("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $e(P),je.current&&(ie(null),ft(null));return}at(!0),ft(null),Ze(!1),ie("processing");try{let P=new _s(ee);if(e){let ge=await P.getUnifiedCheckoutSession(e,t);await He(ge,e);return}try{let ge=await P.createAndFetchSession({...Bt});await He(ge,ge.data.session?.id??null,{fromCreateSession:!0})}catch(ge){if($a(ge)==="session_auto_completed"){await Pe({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ge}}catch(P){await $e(Hr(uy(P,"Automatic payment failed. Please try again."),e))}finally{je.current&&(ie(null),ft(null),at(!1))}}},[st.onClick,Bt,ze,ut,t,He,ee,e,$e,Pe]),_t=jr(f=>{let P=Fe.current;O(null),E.current?.({result:f,session:null,sessionId:P?.sessionId??null,autoCompleted:!1})},[]),Pt=jr(f=>{De.current?.(f)},[]),ce=jr(f=>{gt.current?.(f)},[]),h=wa(()=>cy(g),[g]),lt=wa(()=>{let f=h?.buttonsLayout??ly(Ve);return R?{...f,...R,cardButton:{...f.cardButton,...R.cardButton}}:f},[h,Ve,R]),Qe=wa(()=>{let f=h?.appearance;return S?f?{...f,...S,variables:{...f.variables,...S.variables}}:S:f},[S,h]),_=Qe?.variables,Ce=_?.colorPrimary??"#4A49FF",Dt=_?.colorPrimaryHover??zc(Ce,.12),de=_?.borderRadius??"8px";return gy(fy,{children:[co("button",{...st,type:qe,onClick:In,disabled:ze||ut,"aria-busy":ut,style:{width:"100%",...ot===void 0?{boxSizing:"border-box",height:dy,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...lt.cardButton,...gs({themeBundle:h,resolvedPrimaryColor:Ce,resolvedBorderRadius:de,submitButtonStyle:lt.submitButton,explicitPrimaryColor:_?.colorPrimary}),fontSize:lt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ze||ut?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ze||ut?.6:1,...It},onMouseEnter:f=>{st.onMouseEnter?.(f),!f.defaultPrevented&&!ze&&!ut&&(h||_?.colorPrimary)&&(f.currentTarget.style.backgroundColor=Dt)},onMouseLeave:f=>{st.onMouseLeave?.(f),!f.defaultPrevented&&(h||_?.colorPrimary)&&(f.currentTarget.style.backgroundColor=Ce)},onMouseDown:f=>{st.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{st.onMouseUp?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(1)")},children:co(So,{content:ot})}),Y&&co("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:Y}),fe&&co(Rr,{status:fe,errorMessage:pe,authorized:Ft}),se&&co("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:f=>{f.target===f.currentTarget&&O(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:co("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:co(Rs,{sessionId:se.sessionId,nonce:se.nonce,checkoutMode:"full",billingApiUrl:ee,locale:K,theme:g,...Qe?{appearance:Qe}:{},buttonsTheme:Ve,buttonsStyles:R,initialErrorMessage:se.errorMessage,initialPayPalOrderId:se.payPalOrderId,cardTitleContent:null,onComplete:_t,onError:Pt,onDecline:ce})})})]})}import{jsx as vy}from"react/jsx-runtime";var hy={StripeSetupMethod:El,PayPalSetupMethod:_l};function Py(e){return vy(Tl,{...e,branches:hy})}export{Xa as DirectPayPalButton,my as FloPayAutomaticPaymentButton,vd as FloPayCardSetup,Pd as FloPayCardSetupError,Rs as FloPayCheckout,Py as FloPayPaymentMethodSetup,ti as FloPayProvider,hs as SplitCardForm,Di as VaultCardFields,Yf as dropThirdPartyOnlyError,zd as useCheckout,Gr as useFloPay,Vi as usePayPalFloPay};
|