@flopay/react 1.13.0 → 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var Oc=Object.create;var Va=Object.defineProperty;var Lc=Object.getOwnPropertyDescriptor;var Nc=Object.getOwnPropertyNames;var Uc=Object.getPrototypeOf,zc=Object.prototype.hasOwnProperty;var qc=(e,t)=>{for(var r in t)Va(e,r,{get:t[r],enumerable:!0})},ll=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Nc(t))!zc.call(e,o)&&o!==r&&Va(e,o,{get:()=>t[o],enumerable:!(n=Lc(t,o))||n.enumerable});return e};var Vi=(e,t,r)=>(r=e!=null?Oc(Uc(e)):{},ll(t||!e||!e.__esModule?Va(r,"default",{value:e,enumerable:!0}):r,e)),jc=e=>ll(Va({},"__esModule",{value:!0}),e);var mu={};qc(mu,{DirectPayPalButton:()=>ga,FloPayAutomaticPaymentButton:()=>oc,FloPayCardSetup:()=>ac,FloPayCardSetupError:()=>Ma,FloPayCheckout:()=>Pi,FloPayPaymentMethodSetup:()=>gc,FloPayProvider:()=>Pa,SplitCardForm:()=>mi,VaultCardFields:()=>lo,dropThirdPartyOnlyError:()=>Pc.dropThirdPartyOnlyError,useCheckout:()=>vl,useFloPay:()=>Jn,usePayPalFloPay:()=>Ka});module.exports=jc(mu);var Pc=require("@flopay/shared");var vi=require("@flopay/js"),dn=require("@flopay/shared"),pt=require("react");var Ht=require("react/jsx-runtime");function Vc(){return(0,Ht.jsxs)(Ht.Fragment,{children:[(0,Ht.jsxs)("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:[(0,Ht.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Ht.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Ht.jsx)("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:(0,Ht.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function $c(){return(0,Ht.jsx)(Ht.Fragment,{children:"Go back"})}function Wc(){return(0,Ht.jsx)(Ht.Fragment,{children:"Secure card checkout"})}function Fo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Bo({content:e}){return(0,Ht.jsx)(Ht.Fragment,{children:e===void 0?(0,Ht.jsx)(Vc,{}):e})}function Do({content:e}){return(0,Ht.jsx)(Ht.Fragment,{children:e===void 0?(0,Ht.jsx)($c,{}):e})}function da({content:e}){return(0,Ht.jsx)(Ht.Fragment,{children:e===void 0?(0,Ht.jsx)(Wc,{}):e})}var gt=require("@flopay/shared"),kn=require("@flopay/shared"),No=require("@flopay/shared"),ho=require("@flopay/shared"),Hc="Checkout is temporarily unavailable. Please try again later.";function $i(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof gt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Kc(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 cl(){return new gt.FloPayError(Hc,"api_error",{code:"CheckoutInitializationFailed"})}function dl(e,t,r){let n=e?.data.session,o=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,gt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||o?.includes("card")||(0,gt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function ul(e,t){if(t&&(!(e instanceof gt.FloPayError)||e.type==="authentication_error"))return $i(e);if(!(e instanceof gt.FloPayError&&Kc(e))){if(!t&&!(e instanceof gt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,gt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof gt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof gt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Oo(e,t,r,n={}){let o;return(i={})=>{if(o!==void 0)return o;let l={...n,...i,email:i.email?.trim()||n.email?.trim()},u=(0,gt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,gt.isValidEmail)(l.email))return Promise.reject(new gt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[C,w]of Object.entries(l)){if(u&&C.endsWith("Name")||typeof w!="string")continue;let S=w.trim();S&&(p[C]=S)}return o=e.claimCheckoutSession(t,r,{accountData:p}),o.catch(()=>{}),o}}function pl(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Wi(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 yl(e,t){let r=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}))],n=r.reduce((i,l)=>i+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??r.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(n*100),currency:o,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:r.map((i,l)=>({uuid:`synthetic-${i.type??"item"}-${l}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function Hi(e,t){return t?{...e,...t}:e}function vr(e,t,r){let n=typeof t=="string"?t:t.message,o=typeof t=="string"?r?.code:r?.code??t.code,i=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,l=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...o?{code:o}:{},...i?{declineCode:i}:{},...l?{sessionId:l}:{}}}function io(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Gn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Yn(e){return e?.status==="authorized"||e?.status==="complete"}function so(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,o=r?.status==="authorized"||n==="AUTHORIZED";return o||r?.status==="completed"||n==="SUCCESS"?{...t,status:o?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function ml(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function $a(e){let t=ml(e);return new gt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Wa(e){return e instanceof gt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Lo(e){return ml(e)?new gt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new gt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new gt.FloPayError(gt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ua(e,t){return e==="processing"||(0,gt.isMoneySettledOutcome)(e,t)}function fl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function gl(e,t){let r=e;if((0,gt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:i,error:l}=await r.retrieveSetupIntent(t);if(l)throw new gt.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return i??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:o}=await r.retrievePaymentIntent(t);if(o)throw new gt.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return n??null}var Gc=["apple_pay","google_pay"];function hl(e,t="automatic",r){let n=(0,gt.resolveSetupFutureUsage)(r,Gc,"wallet");return{...(0,gt.resolveWalletModeOptions)(e,t),paymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Yc=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Ki(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:Yc.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function pa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var eo=require("@flopay/js"),$e=require("@flopay/shared"),b=Vi(require("react"),1);var Gi=require("react"),nn=(0,Gi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Rn=(0,Gi.createContext)({session:null,loading:!1,error:null});var Ja=require("@flopay/js"),ot=require("@flopay/shared"),wl=require("@paypal/paypal-js"),E=require("react");var Ha=require("@flopay/shared"),En=require("react"),on=require("@flopay/shared"),Xn=require("react/jsx-runtime");function Uo(){let[e,t]=(0,En.useState)(null),r=(0,En.useRef)(null),n=(0,En.useRef)(0),o=(0,En.useCallback)((l,u)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:l,identity:u}),new Promise(p=>{r.current=p})),[]),i=(0,En.useCallback)(l=>{let u=r.current;r.current=null,t(null),u?.(l)},[]);return(0,En.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:o,finish:i}}function zo({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[l,u]=(0,En.useState)(e.email?.trim()??""),p=(0,Ha.isValidEmail)(l.trim());return(0,Xn.jsxs)("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:[(0,Xn.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Xn.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Xn.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:C=>u(C.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Xn.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,Xn.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Xn.jsxs)("button",{type:"button",disabled:!p||o,onClick:()=>{r((0,Ha.compactBuyerIdentity)({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Ce=require("@flopay/shared");var Pl=require("@flopay/shared"),ya=require("react");function Jn(){return(0,ya.useContext)(nn).flopay}function Ka(){return(0,ya.useContext)(nn).paypalFlopay??null}function vl(){return(0,ya.useContext)(Rn)}function Cl(){return(0,ya.useContext)(nn).billingApiUrl||(0,Pl.resolveBillingApiUrl)()}var Xc=require("@flopay/shared"),Un=require("@flopay/shared"),zn=require("@flopay/shared");var qo=require("@flopay/shared"),vo=require("react");var Ga=require("react"),Po=typeof window>"u"?Ga.useEffect:Ga.useLayoutEffect;var Yi=require("@flopay/shared");function jo(e,t){let r=(0,vo.useRef)(e);r.current=e;let n=(0,vo.useRef)(new Set),o=(0,vo.useRef)(t),i=(0,vo.useRef)(t);return Po(()=>{i.current=t,o.current!==t&&(o.current=t,n.current.clear())},[t]),(0,vo.useCallback)(l=>{if(i.current!==t)return;let u=(0,qo.projectFloInstrument)(l);if(u){if(qo.FLO_INSTRUMENT_ONCE_NAMES.has(u.name)){if(n.current.has(u.name))return;n.current.add(u.name)}(0,qo.invokeMerchantCallback)(()=>r.current?.(u))}},[t])}var tt=require("@flopay/shared");var bl=require("react"),ma=(0,bl.createContext)(null);function Ya(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Jc=Symbol.for("@flopay/js.telemetry.bridge.v1"),Zc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Qc(){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 ed(e){let t=Qc(),r=(o,i)=>o?o.bind(e):i,n=r(e.now,t.now);return{error:r(e.error,t.error),log:r(e.log,t.log),performance:r(e.performance,t.performance),terminal:r(e.terminal,t.terminal),now:n,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,n()-o),setCheckoutContext:r(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:r(e.beginCheckout,t.beginCheckout),disable:r(e.disable,t.disable),subscribe:r(e.subscribe,t.subscribe),flush:r(e.flush,t.flush),destroy:r(e.destroy,t.destroy)}}function Xa(e){let t=globalThis[Zc];return ed(t?.(e)??{})}function Cr(e){if(e)return e[Jc]}var ur=require("react");function fa(e,t){let r=(0,ur.useRef)(0),n=(0,ur.useRef)(null),o=(0,ur.useRef)(null),i=(0,ur.useRef)(e),l=(0,ur.useRef)(t?.onHandoffObserved),u=(0,ur.useRef)(t?.defersMissingTerminal),p=(0,ur.useRef)(t?.onMissingTerminalDeferred);(0,ur.useEffect)(()=>{i.current=e,l.current=t?.onHandoffObserved,u.current=t?.defersMissingTerminal,p.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let C=(0,ur.useCallback)((h=o.current)=>{h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),w=(0,ur.useCallback)(h=>{C();let P=r.current+1;return r.current=P,n.current=null,o.current={generation:P,method:h,timer:null,yieldedControl:!1},P},[C]),S=(0,ur.useCallback)(h=>{let P=o.current;return h!==void 0&&P?.generation!==h?!1:(C(P),o.current=null,(h===void 0||n.current===h)&&(n.current=null),!0)},[C]),_=(0,ur.useCallback)(h=>{let P=o.current,ee=h??P?.generation??r.current;(h===void 0||P?.generation===h)&&(C(P),o.current=null),n.current=ee},[C]),K=(0,ur.useCallback)(h=>n.current===(h??r.current),[]),I=(0,ur.useCallback)(h=>o.current?.generation===h&&n.current!==h,[]),$=(0,ur.useCallback)(()=>{let h=o.current;h&&(C(h),!h.yieldedControl&&(h.yieldedControl=!0,l.current?.(h.method)))},[C]),T=(0,ur.useCallback)(()=>{let h=o.current;!h?.yieldedControl||document.visibilityState!=="visible"||(C(h),h.timer=setTimeout(()=>{if(h.timer=null,o.current?.generation===h.generation){if(u.current?.(h.method)){p.current?.(h.method,h.generation);return}o.current=null,n.current=h.generation,i.current(h.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},Ce.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[C]);return(0,ur.useEffect)(()=>{let h=()=>{document.visibilityState==="visible"?T():$()};return document.addEventListener("visibilitychange",h),window.addEventListener("blur",$),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("blur",$),window.removeEventListener("focus",T),C()}},[C,$,T]),{startAttempt:w,finishAttempt:S,invalidateAttempt:_,isAttemptInvalidated:K,isAttemptCurrent:I,generationRef:r}}var an=require("react/jsx-runtime"),Za=45,td=1e3,rd=11e3,nd={width:"100%",minHeight:Za,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"},od={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 ad(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:od[e.kind]??null}}function Sl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,Ce.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function id(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function kl({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:o,onBuyerIdentityReady:i,clientId:l,environment:u,currency:p,isSubscription:C,providerObjectType:w,approvalPresentation:S,onTokenizedBody:_,onComplete:K,onErrorChange:I,onDecline:$,onTechnicalFailure:T,isProcessing:h=!1,onLoadStateChange:P,onInitializationStateChange:ee,allowAutomaticRetry:A=!0,onButtonClick:ue,runBeforeButtonClick:F,session:re,existingOrderId:Ee,telemetry:pe,telemetryContext:We,onInstrument:wt,debug:ce=!1}){let Y=Jn(),ct=jo(wt,e),be=(0,E.useMemo)(()=>{if(Y)return null;let f=Xa({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:ot.SDK_VERSION,enabled:pe!==!1});return f.setCheckoutContext(We??{}),f.beginCheckout(We??{}),f},[r,Y,pe,We?.checkoutMode,We?.layout]),Me=(0,E.useMemo)(()=>Cr(Y),[Y]);(0,E.useEffect)(()=>()=>{be&&be.flush().catch(()=>{}).finally(()=>be.destroy())},[be]);let Se=(0,E.useMemo)(()=>({error:f=>{Me?Me.error(f):be?.error(f),ct({class:"technical_error",errorCode:f.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":f.errorCode,requestCategory:f.requestCategory,provider:f.provider})},log:f=>{Me?Me.log(f):be?.log(f),ct({class:"lifecycle",name:f.name,provider:f.provider})},performance:f=>{Me?Me.performance(f):be?.performance(f)},terminal:f=>{Me?Me.terminal(f):be?.terminal(f)},startTiming:()=>Me?.now()??be?.now()??0,elapsed:f=>Me?.elapsed(f)??Math.max(0,(be?.now()??f)-f)}),[ct,Me,be]),Z=(0,E.useRef)(null),de=(0,E.useRef)(0),ye=(0,E.useRef)(null),Ie=(0,E.useRef)(null),_e=(0,E.useRef)(null),fe=(0,E.useContext)(ma),j=(0,E.useRef)(null);j.current||(j.current=Ya());let L=fe??j.current,we=(0,E.useRef)(null),Ne=(0,E.useRef)(!1),[ke,N]=(0,E.useState)(!1),[dt,ge]=(0,E.useState)(!1),[Be,Xe]=(0,E.useState)(0),Ae=(0,E.useRef)(0),[at,Je]=(0,E.useState)(!1),Et=(0,E.useRef)(!1),zt=(0,E.useRef)(!1),[kt,Tt]=(0,E.useState)(!1),[U,he]=(0,E.useState)(!1),{request:Ze,collect:G,finish:je}=Uo(),ht=(0,E.useRef)({sessionId:e,required:(0,ot.paypalProviderIdentityRequired)(n,re)});ht.current.sessionId!==e&&(ht.current={sessionId:e,required:(0,ot.paypalProviderIdentityRequired)(n,re)});let Qe=ht.current.required,At=(0,E.useMemo)(()=>r.replace(/\/+$/,""),[r]),y=re?.gateways?.paypal?.providerObjectType??w,v=y??(C?"subscription":"order"),[W]=(0,E.useState)(Un.detectPayPalEnvironment),z=re?.gateways?.paypal?.approvalPresentation??S,me=(0,zn.resolvePayPalPresentationMode)(W,z==="app_switch"?"app_switch":void 0,v),Rt=(0,ot.usesPayPalVaultedChannel)(y),De=(0,E.useMemo)(()=>JSON.stringify([At,l,p,u??"",v,Rt,me,e,Ee??""]),[At,l,p,u,Ee,v,Rt,me,e]),it=(0,E.useRef)(De),ne=it.current!==De,D=(0,E.useRef)(ce),Q=(0,E.useRef)(null),[xe,Oe]=(0,E.useState)([]),M=(0,E.useCallback)(f=>{D.current&&Oe(rt=>[...rt,`${new Date().toISOString().slice(11,23)} ${f}`])},[]);(0,E.useEffect)(()=>{D.current=ce,ce&&M("debug:enabled"),Q.current?.setEnabled(ce)},[M,ce]);let Ft=(0,E.useRef)(_),Qt=(0,E.useRef)(K),ar=(0,E.useRef)(I),Kt=(0,E.useRef)($),Vr=(0,E.useRef)(T),$r=(0,E.useRef)(ue),Er=(0,E.useRef)(P),Lt=(0,E.useRef)(ee),yt=(0,E.useRef)(i),st=(0,E.useRef)(F),Br=(0,E.useRef)(re),Bt=(0,E.useRef)(n),Wr=(0,E.useRef)(o),wr=(0,E.useRef)(t),Gt=(0,E.useRef)(null),ir=(0,E.useRef)(new Map),un=(0,E.useRef)(new Map),Qr=(0,E.useRef)(!1);(0,E.useEffect)(()=>(Qr.current=!0,()=>{Qr.current=!1}),[]),(0,E.useEffect)(()=>{Ft.current=_},[_]),(0,E.useEffect)(()=>{yt.current=i},[i]),(0,E.useEffect)(()=>{Qt.current=K},[K]),(0,E.useEffect)(()=>{ar.current=I},[I]),(0,E.useEffect)(()=>{Kt.current=$},[$]),(0,E.useEffect)(()=>{Vr.current=T},[T]),(0,E.useEffect)(()=>{$r.current=ue},[ue]),(0,E.useEffect)(()=>{Er.current=P},[P]),(0,E.useEffect)(()=>{Lt.current=ee},[ee]),(0,E.useEffect)(()=>{st.current=F},[F]),(0,E.useEffect)(()=>{Br.current=re},[re]),(0,E.useEffect)(()=>{Bt.current=n},[n]),(0,E.useEffect)(()=>{Wr.current=o},[o]),(0,E.useEffect)(()=>{wr.current=t},[t]),(0,E.useEffect)(()=>{Ae.current=Be},[Be]),(0,E.useEffect)(()=>{at&&we.current?.focus()},[at,Be]);let sr=(0,E.useCallback)(()=>{window.setTimeout(()=>{we.current?.focus()},0)},[]),qt=(0,E.useCallback)(()=>{N(!1),Xe(f=>f+1)},[]),Tr=(0,E.useCallback)(()=>{Je(!1),(Z.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Z.current)?.focus?.()},[]);(0,E.useEffect)(()=>{!ke||!Ne.current||(Ne.current=!1,Tr())},[Tr,ke,Be]);let gr=(0,E.useCallback)((f,rt)=>{let oe=rt?.popupBlocked??(0,Ce.isPopupBlockedError)(f);oe&&L.markBlocked();let Ir=(0,Ce.buildExternalMethodRecoveryMessage)("PayPal",oe,W.inAppBrowser),Hr=Vr.current;if(Hr){let er=oe&&W.inAppBrowser?new ot.FloPayError(Ir,"api_error",{code:rt?.code??"paypal_popup_blocked"}):f;Hr("paypal",er,rt);return}ar.current?.(Ir)},[L,W.inAppBrowser]),Vt=(0,E.useCallback)(f=>{let rt=ye.current,oe=Ie.current;rt===null||!oe||(Se.log({...oe,popupCapability:L.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:f}),Se.performance({...oe,popupCapability:L.current(),stage:"overlay_return",durationMs:Se.elapsed(rt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:f}),ye.current=null)},[L,Se]),kr=(0,E.useCallback)((f,rt,oe)=>{let Ir=Ie.current;Vt("overlay_timeout"),Ir&&Se.error({...Ir,popupCapability:L.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),gr(rt,{...oe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:me,terminalReason:"overlay_timeout"}),Je(!0),qt(),sr()},[Vt,sr,gr,L,me,qt,Se]),$t=(0,E.useCallback)(()=>{L.markAvailable();let f=Ie.current;f&&(_e.current=f.attempt,Se.log({...f,popupCapability:L.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[L,Se]),{finishAttempt:yr,generationRef:jt,invalidateAttempt:Fe,isAttemptCurrent:pn,isAttemptInvalidated:yn,startAttempt:mn}=fa(kr,{onHandoffObserved:$t}),lr=(0,E.useCallback)(()=>(Je(!1),mn("paypal")),[mn]),Dr=(0,E.useCallback)(f=>{Fe(f?.generation),f?.showRetry&&Je(!0),f?.remount&&qt(),f?.focus!==!1&&sr()},[sr,Fe,qt]),Mr=f=>{let rt=Gt.current;return rt&&un.current.set(f,rt),f};(0,E.useEffect)(()=>{it.current!==De&&(it.current=De,Et.current=!1,zt.current=!1,N(!1),ge(!1),Tt(!1),Lt.current?.("loading"))},[De]),(0,E.useEffect)(()=>{(0,tt.invokeMerchantCallback)(()=>Er.current?.(ke&&!kt))},[ke,kt]);let Ue=(0,ot.normalizeGatewayEnvironment)(u);(0,E.useEffect)(()=>{let f={attempt:jt.current+1,inAppBrowser:W.inAppBrowser,appFamily:W.appFamily,popupCapability:L.current(),presentationMode:me},rt=()=>({...Ie.current??f,popupCapability:L.current()}),oe={error:m=>Se.error({...m,...rt()}),log:m=>Se.log({...m,...rt()}),performance:m=>Se.performance({...m,...rt()}),terminal:m=>Se.terminal({...m,...rt()}),startTiming:Se.startTiming,elapsed:Se.elapsed},Ir=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Hr=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(M(`mount clientId=${Ir} env=${u??"(unset)"}\u2192${Ue??"live"} ccy=${p} sub=${C}`),M(`ua=${Hr.slice(0,80)}${Hr.length>80?"\u2026":""}`),!l){M("FAIL: clientId empty \u2014 gateway misconfigured"),Tt(!0),oe.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(!Z.current){M("FAIL: containerRef not attached");return}de.current=oe.startTiming(),oe.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let er=!1,Or=!1,bt=()=>er||Or,Mn=Rt?v:void 0,ro,Dt=!1,Kr=()=>{ro=(0,ot.generateIdempotencyKey)(),ro||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Dt=!0},fn=null,gn=!1,Yt=null,xn=!1,An=()=>{!Yt||xn||(xn=!0,Yt.close().catch(()=>{}))},Lr=!1,Fn=!1,en=Z.current,Bn=null,Wn=null,Gr=[],hn=null,Pn=!1,Nt=!1,Yr=null,xr=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let g=m.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},vn=m=>{if(!m)return"(empty)";try{let g=new URL(m,typeof window>"u"?"https://localhost":window.location.href),R=g.pathname.toLowerCase();return R.includes("checkcaptcha")||R.includes("captcha")?`CAPTCHA(${g.host}${R})`:R.includes("risk")||R.includes("challenge")?`RISK(${g.host}${R})`:R.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${R}`.slice(0,100)}catch{return m.slice(0,80)}},Cn=m=>{let g=m.getAttribute("src"),R=m.getAttribute("srcdoc"),se=m.getAttribute("name"),Le=m.getAttribute("sandbox"),Ke=[];return g&&Ke.push(`src=${vn(g)}`),R&&Ke.push(`srcdoc[${R.length}ch]`),!g&&!R&&Ke.push("src=(empty) srcdoc=(empty)"),se&&Ke.push(`name=${se.slice(0,40)}`),Le!==null&&Ke.push(`sandbox="${Le.slice(0,40)}"`),Ke.join(" ")},Ct=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let g=m.contentDocument;if(!g)return"cd=null";let R=g.body?.children.length??0,se=g.body?.innerHTML.length??0,Le=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${R}children,${se}ch] head[${Le}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},cr=[],hr=m=>{if(bt())return;let g=m.message??String(m.error??"(no message)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(M(`window:error ${g.slice(0,140)}`),cr.push(g))},Nr=m=>{if(bt())return;let g=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(M(`window:rejection ${g.slice(0,140)}`),cr.push(g))},no={value:0},Dn=()=>{Bn?.disconnect(),Bn=null,Wn?.disconnect(),Wn=null;for(let m of Gr.splice(0))clearTimeout(m);Nt=!1,Pn&&typeof window<"u"&&(window.removeEventListener("error",hr),window.removeEventListener("unhandledrejection",Nr)),Pn=!1},Hn=()=>{if(!(Pn||bt()||Lr)){if(Pn=!0,cr.length=0,no.value=0,typeof window<"u"&&(window.addEventListener("error",hr),window.addEventListener("unhandledrejection",Nr)),typeof PerformanceObserver<"u")try{Wn=new PerformanceObserver(m=>{if(!bt())for(let g of m.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;no.value+=1;let R=Math.round(g.duration);M(`net ${R}ms ${g.name.slice(0,90)}`)}}),Wn.observe({type:"resource",buffered:!0})}catch{}Yr?.()}},tn=()=>{hn&&(clearTimeout(hn),hn=null)},dr=()=>{Dn(),tn()},oo={setEnabled:m=>{m?Hn():Dn()}};Q.current=oo,D.current&&Hn();let mr=ot.isPayPalTeardownMessage,q=m=>{if(bt()||mr(m))return;let g=(0,ho.applyFriendlyMessageOverride)(m)??m;(0,tt.invokeMerchantCallback)(()=>ar.current?.(g))},B=(m,g)=>{if(er||gn)return;gn=!0,Or=!0,dr(),An();let R=ad({kind:m,generationActive:!0,automaticRetryAllowed:A,automaticRetryUsed:Et.current});if(R.action==="retry"){Et.current=!0,N(!1),he(!1),ge(!0),Lt.current?.("retrying"),fn=setTimeout(()=>{er||Xe(se=>se+1)},td);return}if(N(!1),he(!1),ge(!1),Tt(!0),R.action!=="ignore"){if(Lt.current?.("exhausted"),R.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(R.report){let se=(0,Ce.classifyExternalMethodFailure)({code:Sl(m,g),message:g},{inAppBrowser:W.inAppBrowser,handoffObserved:!1});se.popupBlocked&&L.markBlocked(),oe.error({errorCode:se.popupBlocked?se.errorCode:R.report.errorCode,stage:R.report.stage,operationOutcome:R.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:se.terminalReason})}zt.current||(zt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Sl(m,g)))}};Tt(!1);let ie=async(m,g=Gt.current)=>{if(bt())return;let R=g?.sessionId??e;if(Ft.current){await Ft.current(m,{sessionId:R,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let se=oe.startTiming();oe.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Le=()=>{oe.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),oe.performance({stage:"processing",durationMs:oe.elapsed(se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Ke=(0,ot.buildPayPalProcessPaymentRequest)({body:m,sessionId:R,nonce:g?.nonce??wr.current,accountPatch:g?.accountPatch,session:Br.current,email:Bt.current}),Te=await new Ja.PaymentAPI(At,{telemetry:!1}).processPayment(Ke.userId,Ke.params);if(Te.ok){if(Or||er&&Qr.current)return;Le(),oe.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,tt.invokeMerchantCallback)(()=>Qt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(bt())return;let Ye=await Te.json().catch(()=>null),nt=(0,ot.describePayPalProcessFailure)(Ye),St=nt.message;Le(),Te.status===400&&(typeof Ye?.declineCode=="string"||!Array.isArray(Ye?.fields))?oe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Te.status===400||Te.status===422?oe.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):oe.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:id(Te.status),failureCategory:Te.status>=500?"server_error":void 0}),q(St),(0,tt.invokeMerchantCallback)(()=>Kt.current?.(vr("paypal",St,{code:nt.code,declineCode:nt.declineCode})));return}catch(Ke){if(bt())return;Le(),oe.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Jt=(0,ot.friendlyPayPalFailureMessage)(Ke instanceof Error?Ke.message:void 0);q(Jt),(0,tt.invokeMerchantCallback)(()=>Kt.current?.(vr("paypal",Jt)));return}},Pe=()=>new ot.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),It=m=>bt()?Promise.reject(Pe()):Promise.resolve(m),Xt=async m=>{if(bt())throw Pe();Dt||Kr();let g=Gt.current,R=g?.sessionId??e,se=g?.nonce??wr.current;oe.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Le;try{Le=await new Ja.PaymentAPI(At,{telemetry:!1}).createSessionIntent(R,se??"",(0,ot.buildPayPalSessionIntentRequest)(Mn),{idempotencyKey:ro})}catch(Ke){throw oe.error({...(0,ot.classifyTelemetryFailure)(Ke,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Ke}if(bt())throw Pe();if(Le.provider!=="paypal"||Le.providerObjectType!==v)throw new Error(m);return oe.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Le.providerObjectId},ze=(m,g)=>{let R=g?.nonce??wr.current;if(!R)return;let se=g?.sessionId??e,Le=(0,ot.resolvePayPalDeclineReason)(m);new Ja.PaymentAPI(At,{telemetry:!1}).reportSessionIntentDecline(se,R,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Le}).catch(()=>{})},X=Be;M("loadScript:scheduled (deferred 1 tick)");let J=null,H=setTimeout(()=>{if(er){M("loadScript:skipped (cancelled before defer ran)");return}M("loadScript:start");let m=Ue==="live"?"production":Ue,g={};v==="subscription"?g={intent:"subscription",vault:!0}:v==="order"&&(g={intent:"capture"}),J=(0,wl.loadScript)({clientId:l,currency:p,...g,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let R=!1;J.then(se=>{if(R=!0,M(`loadScript:resolved inactive=${bt()} ns=${!!se} buttons=${!!se?.Buttons}`),bt())return;if(!se?.Buttons){M("FAIL: namespace missing Buttons factory"),B("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}oe.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),oe.performance({stage:"provider_ready",durationMs:oe.elapsed(de.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),oe.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Le=async(ve,O)=>{if(bt()||Ae.current!==X)return;let ae=ve.vaultSetupToken??ve.subscriptionID??ve.orderID??"",mt=ae?un.current.get(ae):ir.current.get(X);if(!(!mt||!pn(mt.generation))&&yr(mt.generation)){un.current.delete(ae),ir.current.delete(mt.surfaceKey),Vt("approved");try{if(he(!0),(0,tt.invokeMerchantCallback)(()=>ar.current?.(null)),!ae)throw new ot.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let He=(0,ot.resolvePayPalApprovalIdentity)({accountPatch:mt.accountPatch,email:Bt.current,billingName:Wr.current,session:Br.current});if((0,ot.needsPayPalPayerDetails)(He))try{He=(0,ot.mergePayPalPayerIdentity)(He,await O?.order?.get?.())}catch{}if((yt.current||Qe)&&!(0,ot.isValidEmail)(He.email)){let Mt=await G("PayPal",He);if(!Mt)return;He=Mt}(0,ot.isValidEmail)(He.email)&&(mt.accountPatch=(0,on.compactBuyerIdentity)({...mt.accountPatch,...He}),await yt.current?.(He));let et=(0,ot.buildPayPalTokenizedBody)(ae,Mn);await ie(et,mt)}catch(He){q(He instanceof Error?He.message:"PayPal capture failed.")}finally{bt()||he(!1)}}},Ke=ve=>{let O=Ee?()=>It(Ee):()=>Xt(ve);return async()=>Mr(await O())},Jt=se.Buttons({style:{layout:"horizontal",height:Za,tagline:!1},...me==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ve,O)=>{if(bt()){await O.reject();return}Kr();let ae=st.current,mt={};if(ae)try{let Mt=await ae("paypal");if(bt()){await O.reject();return}if(!Mt.proceed){Gt.current=null,ir.current.delete(X),await O.reject();return}mt={sessionId:Mt.sessionId,accountPatch:Mt.accountPatch,nonce:Mt.nonce}}catch(Mt){M(`onClick:runBeforeButtonClick rejected msg=${(Mt instanceof Error?Mt.message:String(Mt)).slice(0,120)}`),Gt.current=null,ir.current.delete(X),await O.reject();return}(0,tt.invokeMerchantCallback)(()=>$r.current?.("paypal"));let He=lr(),et={generation:He,surfaceKey:X,...mt};Gt.current=et,ir.current.set(X,et),Ie.current={...f,attempt:He},await O.resolve(),oe.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),oe.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),ye.current=oe.startTiming()},createOrder:v==="order"?Ke("Failed to create PayPal order."):void 0,createSubscription:v==="subscription"?Ke("Failed to create PayPal subscription."):void 0,createVaultSetupToken:v==="setup_token"?async()=>Mr(await Xt("Failed to create PayPal setup token.")):void 0,onApprove:Le,onCancel:()=>{if(bt())return;let ve=ir.current.get(X)??Gt.current;ve&&ir.current.delete(ve.surfaceKey),Gt.current=null,Vt("cancelled"),oe.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ne.current=!0,Dr({generation:ve?.generation,remount:!0,focus:!1})},onError:ve=>{if(bt()||Ae.current!==X)return;let O=ve instanceof Error?ve.message:"PayPal failed to render.";if(M(`onError rendered=${Lr} msg=${O.slice(0,120)}`),Lr){let ae=ir.current.get(X)??Gt.current;if(ae&&!pn(ae.generation)||!ae&&yn())return;if(mr(O)){yr(ae?.generation);return}let{errorCode:mt,popupBlocked:He,providerDeclined:et,terminalReason:Mt}=(0,Ce.classifyExternalMethodFailure)(ve,{inAppBrowser:W.inAppBrowser,handoffObserved:ae!=null&&_e.current===ae.generation});if(He&&L.markBlocked(),Vt(Mt),et){oe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Mt}),ze(ve,ae),(0,tt.invokeMerchantCallback)(()=>Kt.current?.(vr("paypal",O))),ae&&ir.current.delete(ae.surfaceKey),Gt.current=null,yr(ae?.generation);return}oe.error({errorCode:mt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Mt}),ae&&ir.current.delete(ae.surfaceKey),Gt.current=null,Dr({generation:ae?.generation,remount:!0,showRetry:!0,focus:!0}),gr(ve,{code:"paypal_runtime_failed",popupBlocked:He,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:me,terminalReason:Mt});return}B(mr(O)?"teardown":"pre_ready_callback",O)}}),Te=Jt.isEligible();if(M(`isEligible=${Te}`),oe.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Te){N(!1),B("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Fn=!0,Yt=Jt,Yr=()=>{if(!Pn||Nt||bt()||Lr)return;Nt=!0,M(`container:dims ${xr(en)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Bn=new MutationObserver(O=>{if(!bt()){for(let ae of O)if(ae.type==="childList")ae.addedNodes.forEach(mt=>{if(!(mt instanceof Element))return;let He=mt.tagName.toLowerCase(),et=(mt.getAttribute("title")??"").slice(0,40),Mt=He==="iframe"?` ${Cn(mt)}`:"";M(`child+ ${He}${et?` title="${et}"`:""}${Mt} dims=${xr(mt)}`)});else if(ae.type==="attributes"&&ae.target instanceof Element){let mt=ae.target;if(mt.tagName.toLowerCase()!=="iframe")continue;let He=ae.attributeName;(He==="src"||He==="srcdoc")&&M(`attr~ iframe ${He}=${He==="srcdoc"?`[${(mt.getAttribute("srcdoc")??"").length}ch]`:vn(mt.getAttribute("src"))} dims=${xr(mt)}`)}}}),Bn.observe(en,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ve=O=>{if(bt()||Lr)return;let ae=en.querySelectorAll("iframe"),mt=typeof document<"u"&&"hasStorageAccess"in document;M(`watchdog:${O} container=${xr(en)} children=${en.childElementCount} iframes=${ae.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${mt} paypalNetRequests=${no.value}`),ae.forEach((He,et)=>{let Mt=(He.getAttribute("title")??"").slice(0,40);M(` iframe[${et}] ${xr(He)}${Mt?` title="${Mt}"`:""} ${Cn(He)}`);let Pt=Ct(He);Pt&&M(` ${Pt}`)}),cr.length===0&&M(" (no PayPal/zoid window errors captured)")};Gr.push(setTimeout(()=>ve("3s"),3e3)),Gr.push(setTimeout(()=>ve("8s"),8e3)),Gr.push(setTimeout(()=>ve("15s"),15e3))},Yr(),M("render:start");let nt=oe.startTiming();hn=setTimeout(()=>{bt()||Lr||(M("watchdog:11s retryable render timeout"),B("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},rd);let St=Jt.render(en);(async()=>{try{if(await St,M(`render:resolved inactive=${bt()}`),dr(),bt()){An();return}Lr=!0,N(!0),ge(!1),Lt.current?.("ready"),oe.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),oe.performance({stage:"checkout_render",durationMs:oe.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ve){let O=ve instanceof Error?ve.message:"PayPal failed to render.";M(`render:rejected msg=${O.slice(0,120)}`),dr(),B(mr(O)?"teardown":"render_rejected",O)}})()}).catch(se=>{let Le=se instanceof Error?se.message:"PayPal operation failed.";M(`provider:failed msg=${Le.slice(0,120)}`);let Ke="script_rejected";R&&mr(Le)?Ke="teardown":R&&Fn&&(Ke="render_rejected"),B(Ke,Le)})},0);return()=>{er=!0,clearTimeout(H),fn&&clearTimeout(fn),dr(),Q.current===oo&&(Q.current=null),An(),ye.current=null,Ie.current=null}},[A,At,l,p,u,v,me,Rt,e,Ee,Be,Se,G,Qe,M,Vt]);let vt=ce?(0,an.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:kt?"#fef2f2":"#f3f4f6",border:`1px solid ${kt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ke} failed=${kt})`,xe.length===0?`
1
+ "use strict";var Oc=Object.create;var Va=Object.defineProperty;var Lc=Object.getOwnPropertyDescriptor;var Nc=Object.getOwnPropertyNames;var Uc=Object.getPrototypeOf,zc=Object.prototype.hasOwnProperty;var qc=(e,t)=>{for(var r in t)Va(e,r,{get:t[r],enumerable:!0})},ll=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Nc(t))!zc.call(e,a)&&a!==r&&Va(e,a,{get:()=>t[a],enumerable:!(n=Lc(t,a))||n.enumerable});return e};var Vi=(e,t,r)=>(r=e!=null?Oc(Uc(e)):{},ll(t||!e||!e.__esModule?Va(r,"default",{value:e,enumerable:!0}):r,e)),jc=e=>ll(Va({},"__esModule",{value:!0}),e);var gu={};qc(gu,{DirectPayPalButton:()=>ga,FloPayAutomaticPaymentButton:()=>oc,FloPayCardSetup:()=>ac,FloPayCardSetupError:()=>Ma,FloPayCheckout:()=>Pi,FloPayPaymentMethodSetup:()=>gc,FloPayProvider:()=>Pa,SplitCardForm:()=>yi,VaultCardFields:()=>lo,dropThirdPartyOnlyError:()=>Pc.dropThirdPartyOnlyError,useCheckout:()=>vl,useFloPay:()=>Jn,usePayPalFloPay:()=>Ka});module.exports=jc(gu);var Pc=require("@flopay/shared");var vi=require("@flopay/js"),pn=require("@flopay/shared"),yt=require("react");var $t=require("react/jsx-runtime");function Vc(){return(0,$t.jsxs)($t.Fragment,{children:[(0,$t.jsxs)("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:[(0,$t.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,$t.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,$t.jsx)("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:(0,$t.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Wc(){return(0,$t.jsx)($t.Fragment,{children:"Go back"})}function $c(){return(0,$t.jsx)($t.Fragment,{children:"Secure card checkout"})}function Fo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Bo({content:e}){return(0,$t.jsx)($t.Fragment,{children:e===void 0?(0,$t.jsx)(Vc,{}):e})}function Do({content:e}){return(0,$t.jsx)($t.Fragment,{children:e===void 0?(0,$t.jsx)(Wc,{}):e})}function da({content:e}){return(0,$t.jsx)($t.Fragment,{children:e===void 0?(0,$t.jsx)($c,{}):e})}var Pt=require("@flopay/shared"),Sn=require("@flopay/shared"),No=require("@flopay/shared"),ho=require("@flopay/shared"),Hc="Checkout is temporarily unavailable. Please try again later.";function Wi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Pt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Kc(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 cl(){return new Pt.FloPayError(Hc,"api_error",{code:"CheckoutInitializationFailed"})}function dl(e,t,r){let n=e?.data.session,a=n?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(r&&((0,Pt.isMountableVaultBlock)(n?.vault)||n?.gateways?.pcivault||a?.includes("card")||(0,Pt.canRecoverHostedCardForm)(n))||t&&e?.data.paypal?.publishableKey)}function ul(e,t){if(t&&(!(e instanceof Pt.FloPayError)||e.type==="authentication_error"))return Wi(e);if(!(e instanceof Pt.FloPayError&&Kc(e))){if(!t&&!(e instanceof Pt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Pt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Pt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Pt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Oo(e,t,r,n={}){let a;return(i={})=>{if(a!==void 0)return a;let l={...n,...i,email:i.email?.trim()||n.email?.trim()},u=(0,Pt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,Pt.isValidEmail)(l.email))return Promise.reject(new Pt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[v,R]of Object.entries(l)){if(u&&v.endsWith("Name")||typeof R!="string")continue;let w=R.trim();w&&(p[v]=w)}return a=e.claimCheckoutSession(t,r,{accountData:p}),a.catch(()=>{}),a}}function pl(e,t){if(!t)return e;if(!e)return t;let r;return"checkoutMetadata"in t?r=t:"checkoutMetadata"in e&&(r=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...r?{checkoutMetadata:r.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function $i(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 ml(e,t){let r=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}))],n=r.reduce((i,l)=>i+(l.overrideAmount??l.totalAmount??0),0),a=e.currency??r.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:r.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(n*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:r.map((i,l)=>({uuid:`synthetic-${i.type??"item"}-${l}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Hi(e,t){return t?{...e,...t}:e}function Cr(e,t,r){let n=typeof t=="string"?t:t.message,a=typeof t=="string"?r?.code:r?.code??t.code,i=typeof t=="string"?r?.declineCode:r?.declineCode??t.declineCode,l=typeof t=="string"?void 0:t.sessionId;return{method:e,message:n,...a?{code:a}:{},...i?{declineCode:i}:{},...l?{sessionId:l}:{}}}function io(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Gn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Yn(e){return e?.status==="authorized"||e?.status==="complete"}function so(e,t){if(e.data.session)return e.data.session;let r=e.raw,n=r?.latestTransactionAttempt?.result,a=r?.status==="authorized"||n==="AUTHORIZED";return a||r?.status==="completed"||n==="SUCCESS"?{...t,status:a?"authorized":"complete"}:r?.status==="expired"?{...t,status:"expired"}:void 0}function yl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Wa(e){let t=yl(e);return new Pt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $a(e){return e instanceof Pt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Lo(e){return yl(e)?new Pt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Pt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Pt.FloPayError(Pt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ua(e,t){return e==="processing"||(0,Pt.isMoneySettledOutcome)(e,t)}function fl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function gl(e,t){let r=e;if((0,Pt.isSetupIntentClientSecret)(t)){if(!r?.retrieveSetupIntent)return null;let{setupIntent:i,error:l}=await r.retrieveSetupIntent(t);if(l)throw new Pt.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return i??null}if(!r?.retrievePaymentIntent)return null;let{paymentIntent:n,error:a}=await r.retrievePaymentIntent(t);if(a)throw new Pt.FloPayError(a.message??"Failed to retrieve payment intent.","api_error",{...a.code?{code:a.code}:{}});return n??null}var Gc=["apple_pay","google_pay"];function hl(e,t="automatic",r){let n=(0,Pt.resolveSetupFutureUsage)(r,Gc,"wallet");return{...(0,Pt.resolveWalletModeOptions)(e,t),paymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Yc=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function Ki(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:Yc.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function pa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var eo=require("@flopay/js"),Ve=require("@flopay/shared"),C=Vi(require("react"),1);var Gi=require("react"),an=(0,Gi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),wn=(0,Gi.createContext)({session:null,loading:!1,error:null});var Ja=require("@flopay/js"),ct=require("@flopay/shared"),wl=require("@paypal/paypal-js"),_=require("react");var Ha=require("@flopay/shared"),kn=require("react"),sn=require("@flopay/shared"),Xn=require("react/jsx-runtime");function Uo(){let[e,t]=(0,kn.useState)(null),r=(0,kn.useRef)(null),n=(0,kn.useRef)(0),a=(0,kn.useCallback)((l,u)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:l,identity:u}),new Promise(p=>{r.current=p})),[]),i=(0,kn.useCallback)(l=>{let u=r.current;r.current=null,t(null),u?.(l)},[]);return(0,kn.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:a,finish:i}}function zo({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[l,u]=(0,kn.useState)(e.email?.trim()??""),p=(0,Ha.isValidEmail)(l.trim());return(0,Xn.jsxs)("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:[(0,Xn.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Xn.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Xn.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:v=>u(v.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Xn.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,Xn.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Xn.jsxs)("button",{type:"button",disabled:!p||a,onClick:()=>{r((0,Ha.compactBuyerIdentity)({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Se=require("@flopay/shared");var Pl=require("@flopay/shared"),ma=require("react");function Jn(){return(0,ma.useContext)(an).flopay}function Ka(){return(0,ma.useContext)(an).paypalFlopay??null}function vl(){return(0,ma.useContext)(wn)}function bl(){return(0,ma.useContext)(an).billingApiUrl||(0,Pl.resolveBillingApiUrl)()}var Xc=require("@flopay/shared"),Un=require("@flopay/shared"),zn=require("@flopay/shared");var qo=require("@flopay/shared"),vo=require("react");var Ga=require("react"),Po=typeof window>"u"?Ga.useEffect:Ga.useLayoutEffect;var Yi=require("@flopay/shared");function jo(e,t){let r=(0,vo.useRef)(e);r.current=e;let n=(0,vo.useRef)(new Set),a=(0,vo.useRef)(t),i=(0,vo.useRef)(t);return Po(()=>{i.current=t,a.current!==t&&(a.current=t,n.current.clear())},[t]),(0,vo.useCallback)(l=>{if(i.current!==t)return;let u=(0,qo.projectFloInstrument)(l);if(u){if(qo.FLO_INSTRUMENT_ONCE_NAMES.has(u.name)){if(n.current.has(u.name))return;n.current.add(u.name)}(0,qo.invokeMerchantCallback)(()=>r.current?.(u))}},[t])}var it=require("@flopay/shared");var Cl=require("react"),ya=(0,Cl.createContext)(null);function Ya(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Jc=Symbol.for("@flopay/js.telemetry.bridge.v1"),Zc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Qc(){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 ed(e){let t=Qc(),r=(a,i)=>a?a.bind(e):i,n=r(e.now,t.now);return{error:r(e.error,t.error),log:r(e.log,t.log),performance:r(e.performance,t.performance),terminal:r(e.terminal,t.terminal),now:n,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,n()-a),setCheckoutContext:r(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:r(e.beginCheckout,t.beginCheckout),disable:r(e.disable,t.disable),subscribe:r(e.subscribe,t.subscribe),flush:r(e.flush,t.flush),destroy:r(e.destroy,t.destroy)}}function Xa(e){let t=globalThis[Zc];return ed(t?.(e)??{})}function Sr(e){if(e)return e[Jc]}var ur=require("react");function fa(e,t){let r=(0,ur.useRef)(0),n=(0,ur.useRef)(null),a=(0,ur.useRef)(null),i=(0,ur.useRef)(e),l=(0,ur.useRef)(t?.onHandoffObserved),u=(0,ur.useRef)(t?.defersMissingTerminal),p=(0,ur.useRef)(t?.onMissingTerminalDeferred);(0,ur.useEffect)(()=>{i.current=e,l.current=t?.onHandoffObserved,u.current=t?.defersMissingTerminal,p.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let v=(0,ur.useCallback)((f=a.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),R=(0,ur.useCallback)(f=>{v();let P=r.current+1;return r.current=P,n.current=null,a.current={generation:P,method:f,timer:null,yieldedControl:!1},P},[v]),w=(0,ur.useCallback)(f=>{let P=a.current;return f!==void 0&&P?.generation!==f?!1:(v(P),a.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[v]),x=(0,ur.useCallback)(f=>{let P=a.current,ee=f??P?.generation??r.current;(f===void 0||P?.generation===f)&&(v(P),a.current=null),n.current=ee},[v]),K=(0,ur.useCallback)(f=>n.current===(f??r.current),[]),T=(0,ur.useCallback)(f=>a.current?.generation===f&&n.current!==f,[]),V=(0,ur.useCallback)(()=>{let f=a.current;f&&(v(f),!f.yieldedControl&&(f.yieldedControl=!0,l.current?.(f.method)))},[v]),A=(0,ur.useCallback)(()=>{let f=a.current;!f?.yieldedControl||document.visibilityState!=="visible"||(v(f),f.timer=setTimeout(()=>{if(f.timer=null,a.current?.generation===f.generation){if(u.current?.(f.method)){p.current?.(f.method,f.generation);return}a.current=null,n.current=f.generation,i.current(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"})}},Se.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[v]);return(0,ur.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?A():V()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",V),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",V),window.removeEventListener("focus",A),v()}},[v,V,A]),{startAttempt:R,finishAttempt:w,invalidateAttempt:x,isAttemptInvalidated:K,isAttemptCurrent:T,generationRef:r}}var ln=require("react/jsx-runtime"),Za=45,td=1e3,rd=11e3,nd={width:"100%",minHeight:Za,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"},od={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 ad(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:od[e.kind]??null}}function Sl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,Se.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function id(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function kl({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:a,onBuyerIdentityReady:i,clientId:l,environment:u,currency:p,isSubscription:v,providerObjectType:R,approvalPresentation:w,onTokenizedBody:x,onComplete:K,onErrorChange:T,onDecline:V,onTechnicalFailure:A,isProcessing:f=!1,onLoadStateChange:P,onInitializationStateChange:ee,allowAutomaticRetry:D=!0,onButtonClick:ue,runBeforeButtonClick:F,session:ne,existingOrderId:_e,telemetry:ie,telemetryContext:We,onInstrument:kt,debug:de=!1}){let G=Jn(),pt=jo(kt,e),we=(0,_.useMemo)(()=>{if(G)return null;let g=Xa({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:ct.SDK_VERSION,enabled:ie!==!1});return g.setCheckoutContext(We??{}),g.beginCheckout(We??{}),g},[r,G,ie,We?.checkoutMode,We?.layout]),xe=(0,_.useMemo)(()=>Sr(G),[G]);(0,_.useEffect)(()=>()=>{we&&we.flush().catch(()=>{}).finally(()=>we.destroy())},[we]);let ke=(0,_.useMemo)(()=>({error:g=>{xe?xe.error(g):we?.error(g),pt({class:"technical_error",errorCode:g.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":g.errorCode,requestCategory:g.requestCategory,provider:g.provider})},log:g=>{xe?xe.log(g):we?.log(g),pt({class:"lifecycle",name:g.name,provider:g.provider})},performance:g=>{xe?xe.performance(g):we?.performance(g)},terminal:g=>{xe?xe.terminal(g):we?.terminal(g)},startTiming:()=>xe?.now()??we?.now()??0,elapsed:g=>xe?.elapsed(g)??Math.max(0,(we?.now()??g)-g)}),[pt,xe,we]),Z=(0,_.useRef)(null),pe=(0,_.useRef)(0),Re=(0,_.useRef)(null),Fe=(0,_.useRef)(null),rt=(0,_.useRef)(null),me=(0,_.useContext)(ya),N=(0,_.useRef)(null);N.current||(N.current=Ya());let H=me??N.current,ye=(0,_.useRef)(null),$e=(0,_.useRef)(!1),[he,M]=(0,_.useState)(!1),[Ye,Te]=(0,_.useState)(!1),[tt,Ze]=(0,_.useState)(0),ze=(0,_.useRef)(0),[He,Le]=(0,_.useState)(!1),Et=(0,_.useRef)(!1),zt=(0,_.useRef)(!1),[ft,Ft]=(0,_.useState)(!1),[q,Pe]=(0,_.useState)(!1),{request:st,collect:W,finish:Ee}=Uo(),nt=(0,_.useRef)({sessionId:e,required:(0,ct.paypalProviderIdentityRequired)(n,ne)});nt.current.sessionId!==e&&(nt.current={sessionId:e,required:(0,ct.paypalProviderIdentityRequired)(n,ne)});let Ke=nt.current.required,Rt=(0,_.useMemo)(()=>r.replace(/\/+$/,""),[r]),b=ne?.gateways?.paypal?.providerObjectType??R,L=b??(v?"subscription":"order"),[qe]=(0,_.useState)(Un.detectPayPalEnvironment),fe=ne?.gateways?.paypal?.approvalPresentation??w,h=(0,zn.resolvePayPalPresentationMode)(qe,fe==="app_switch"?"app_switch":void 0,L),ve=(0,ct.usesPayPalVaultedChannel)(b),j=(0,_.useMemo)(()=>JSON.stringify([Rt,l,p,u??"",L,ve,h,e,_e??""]),[Rt,l,p,u,_e,L,ve,h,e]),Y=(0,_.useRef)(j),te=Y.current!==j,k=(0,_.useRef)(de),Q=(0,_.useRef)(null),[be,Be]=(0,_.useState)([]),S=(0,_.useCallback)(g=>{k.current&&Be(It=>[...It,`${new Date().toISOString().slice(11,23)} ${g}`])},[]);(0,_.useEffect)(()=>{k.current=de,de&&S("debug:enabled"),Q.current?.setEnabled(de)},[S,de]);let Bt=(0,_.useRef)(x),rr=(0,_.useRef)(K),sr=(0,_.useRef)(T),Ht=(0,_.useRef)(V),Kt=(0,_.useRef)(A),Lr=(0,_.useRef)(ue),_r=(0,_.useRef)(P),jt=(0,_.useRef)(ee),Zr=(0,_.useRef)(i),Gt=(0,_.useRef)(F),_n=(0,_.useRef)(ne),Yt=(0,_.useRef)(n),Qr=(0,_.useRef)(a),ot=(0,_.useRef)(t),dt=(0,_.useRef)(null),Vt=(0,_.useRef)(new Map),xr=(0,_.useRef)(new Map),Ar=(0,_.useRef)(!1);(0,_.useEffect)(()=>(Ar.current=!0,()=>{Ar.current=!1}),[]),(0,_.useEffect)(()=>{Bt.current=x},[x]),(0,_.useEffect)(()=>{Zr.current=i},[i]),(0,_.useEffect)(()=>{rr.current=K},[K]),(0,_.useEffect)(()=>{sr.current=T},[T]),(0,_.useEffect)(()=>{Ht.current=V},[V]),(0,_.useEffect)(()=>{Kt.current=A},[A]),(0,_.useEffect)(()=>{Lr.current=ue},[ue]),(0,_.useEffect)(()=>{_r.current=P},[P]),(0,_.useEffect)(()=>{jt.current=ee},[ee]),(0,_.useEffect)(()=>{Gt.current=F},[F]),(0,_.useEffect)(()=>{_n.current=ne},[ne]),(0,_.useEffect)(()=>{Yt.current=n},[n]),(0,_.useEffect)(()=>{Qr.current=a},[a]),(0,_.useEffect)(()=>{ot.current=t},[t]),(0,_.useEffect)(()=>{ze.current=tt},[tt]),(0,_.useEffect)(()=>{He&&ye.current?.focus()},[He,tt]);let Fr=(0,_.useCallback)(()=>{window.setTimeout(()=>{ye.current?.focus()},0)},[]),Rr=(0,_.useCallback)(()=>{M(!1),Ze(g=>g+1)},[]),Tr=(0,_.useCallback)(()=>{Le(!1),(Z.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Z.current)?.focus?.()},[]);(0,_.useEffect)(()=>{!he||!$e.current||($e.current=!1,Tr())},[Tr,he,tt]);let gr=(0,_.useCallback)((g,It)=>{let se=It?.popupBlocked??(0,Se.isPopupBlockedError)(g);se&&H.markBlocked();let Ae=(0,Se.buildExternalMethodRecoveryMessage)("PayPal",se,qe.inAppBrowser),xt=Kt.current;if(xt){let bt=se&&qe.inAppBrowser?new ct.FloPayError(Ae,"api_error",{code:It?.code??"paypal_popup_blocked"}):g;xt("paypal",bt,It);return}sr.current?.(Ae)},[H,qe.inAppBrowser]),mr=(0,_.useCallback)(g=>{let It=Re.current,se=Fe.current;It===null||!se||(ke.log({...se,popupCapability:H.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:g}),ke.performance({...se,popupCapability:H.current(),stage:"overlay_return",durationMs:ke.elapsed(It),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:g}),Re.current=null)},[H,ke]),Xt=(0,_.useCallback)((g,It,se)=>{let Ae=Fe.current;mr("overlay_timeout"),Ae&&ke.error({...Ae,popupCapability:H.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),gr(It,{...se,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:h,terminalReason:"overlay_timeout"}),Le(!0),Rr(),Fr()},[mr,Fr,gr,H,h,Rr,ke]),Dt=(0,_.useCallback)(()=>{H.markAvailable();let g=Fe.current;g&&(rt.current=g.attempt,ke.log({...g,popupCapability:H.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[H,ke]),{finishAttempt:hr,generationRef:Pr,invalidateAttempt:De,isAttemptCurrent:mn,isAttemptInvalidated:Nr,startAttempt:Tn}=fa(Xt,{onHandoffObserved:Dt}),lr=(0,_.useCallback)(()=>(Le(!1),Tn("paypal")),[Tn]),Er=(0,_.useCallback)(g=>{De(g?.generation),g?.showRetry&&Le(!0),g?.remount&&Rr(),g?.focus!==!1&&Fr()},[Fr,De,Rr]),Mn=g=>{let It=dt.current;return It&&xr.current.set(g,It),g};(0,_.useEffect)(()=>{Y.current!==j&&(Y.current=j,Et.current=!1,zt.current=!1,M(!1),Te(!1),Ft(!1),jt.current?.("loading"))},[j]),(0,_.useEffect)(()=>{(0,it.invokeMerchantCallback)(()=>_r.current?.(he&&!ft))},[he,ft]);let en=(0,ct.normalizeGatewayEnvironment)(u);(0,_.useEffect)(()=>{let g={attempt:Pr.current+1,inAppBrowser:qe.inAppBrowser,appFamily:qe.appFamily,popupCapability:H.current(),presentationMode:h},It=()=>({...Fe.current??g,popupCapability:H.current()}),se={error:m=>ke.error({...m,...It()}),log:m=>ke.log({...m,...It()}),performance:m=>ke.performance({...m,...It()}),terminal:m=>ke.terminal({...m,...It()}),startTiming:ke.startTiming,elapsed:ke.elapsed},Ae=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",xt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(S(`mount clientId=${Ae} env=${u??"(unset)"}\u2192${en??"live"} ccy=${p} sub=${v}`),S(`ua=${xt.slice(0,80)}${xt.length>80?"\u2026":""}`),!l){S("FAIL: clientId empty \u2014 gateway misconfigured"),Ft(!0),se.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(!Z.current){S("FAIL: containerRef not attached");return}pe.current=se.startTiming(),se.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let bt=!1,At=!1,Qe=()=>bt||At,Ur=ve?L:void 0,ro,Ot=!1,Hr=()=>{ro=(0,ct.generateIdempotencyKey)(),ro||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Ot=!0},yn=null,fn=!1,Zt=null,xn=!1,An=()=>{!Zt||xn||(xn=!0,Zt.close().catch(()=>{}))},zr=!1,Fn=!1,tn=Z.current,Bn=null,$n=null,Kr=[],gn=null,hn=!1,Nt=!1,Gr=null,Br=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let y=m.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},Pn=m=>{if(!m)return"(empty)";try{let y=new URL(m,typeof window>"u"?"https://localhost":window.location.href),I=y.pathname.toLowerCase();return I.includes("checkcaptcha")||I.includes("captcha")?`CAPTCHA(${y.host}${I})`:I.includes("risk")||I.includes("challenge")?`RISK(${y.host}${I})`:I.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${I}`.slice(0,100)}catch{return m.slice(0,80)}},vn=m=>{let y=m.getAttribute("src"),I=m.getAttribute("srcdoc"),ce=m.getAttribute("name"),Oe=m.getAttribute("sandbox"),Xe=[];return y&&Xe.push(`src=${Pn(y)}`),I&&Xe.push(`srcdoc[${I.length}ch]`),!y&&!I&&Xe.push("src=(empty) srcdoc=(empty)"),ce&&Xe.push(`name=${ce.slice(0,40)}`),Oe!==null&&Xe.push(`sandbox="${Oe.slice(0,40)}"`),Xe.join(" ")},Ct=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let y=m.contentDocument;if(!y)return"cd=null";let I=y.body?.children.length??0,ce=y.body?.innerHTML.length??0,Oe=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${I}children,${ce}ch] head[${Oe}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},cr=[],vr=m=>{if(Qe())return;let y=m.message??String(m.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(S(`window:error ${y.slice(0,140)}`),cr.push(y))},qr=m=>{if(Qe())return;let y=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(S(`window:rejection ${y.slice(0,140)}`),cr.push(y))},no={value:0},Dn=()=>{Bn?.disconnect(),Bn=null,$n?.disconnect(),$n=null;for(let m of Kr.splice(0))clearTimeout(m);Nt=!1,hn&&typeof window<"u"&&(window.removeEventListener("error",vr),window.removeEventListener("unhandledrejection",qr)),hn=!1},Hn=()=>{if(!(hn||Qe()||zr)){if(hn=!0,cr.length=0,no.value=0,typeof window<"u"&&(window.addEventListener("error",vr),window.addEventListener("unhandledrejection",qr)),typeof PerformanceObserver<"u")try{$n=new PerformanceObserver(m=>{if(!Qe())for(let y of m.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;no.value+=1;let I=Math.round(y.duration);S(`net ${I}ms ${y.name.slice(0,90)}`)}}),$n.observe({type:"resource",buffered:!0})}catch{}Gr?.()}},rn=()=>{gn&&(clearTimeout(gn),gn=null)},dr=()=>{Dn(),rn()},oo={setEnabled:m=>{m?Hn():Dn()}};Q.current=oo,k.current&&Hn();let yr=ct.isPayPalTeardownMessage,z=m=>{if(Qe()||yr(m))return;let y=(0,ho.applyFriendlyMessageOverride)(m)??m;(0,it.invokeMerchantCallback)(()=>sr.current?.(y))},O=(m,y)=>{if(bt||fn)return;fn=!0,At=!0,dr(),An();let I=ad({kind:m,generationActive:!0,automaticRetryAllowed:D,automaticRetryUsed:Et.current});if(I.action==="retry"){Et.current=!0,M(!1),Pe(!1),Te(!0),jt.current?.("retrying"),yn=setTimeout(()=>{bt||Ze(ce=>ce+1)},td);return}if(M(!1),Pe(!1),Te(!1),Ft(!0),I.action!=="ignore"){if(jt.current?.("exhausted"),I.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}if(I.report){let ce=(0,Se.classifyExternalMethodFailure)({code:Sl(m,y),message:y},{inAppBrowser:qe.inAppBrowser,handoffObserved:!1});ce.popupBlocked&&H.markBlocked(),se.error({errorCode:ce.popupBlocked?ce.errorCode:I.report.errorCode,stage:I.report.stage,operationOutcome:I.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:ce.terminalReason})}zt.current||(zt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Sl(m,y)))}};Ft(!1);let le=async(m,y=dt.current)=>{if(Qe())return;let I=y?.sessionId??e;if(Bt.current){await Bt.current(m,{sessionId:I,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let ce=se.startTiming();se.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Oe=()=>{se.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),se.performance({stage:"processing",durationMs:se.elapsed(ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Xe=(0,ct.buildPayPalProcessPaymentRequest)({body:m,sessionId:I,nonce:y?.nonce??ot.current,accountPatch:y?.accountPatch,session:_n.current,email:Yt.current}),Me=await new Ja.PaymentAPI(Rt,{telemetry:!1}).processPayment(Xe.userId,Xe.params);if(Me.ok){if(At||bt&&Ar.current)return;Oe(),se.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,it.invokeMerchantCallback)(()=>rr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Qe())return;let et=await Me.json().catch(()=>null),lt=(0,ct.describePayPalProcessFailure)(et),St=lt.message;Oe(),Me.status===400&&(typeof et?.declineCode=="string"||!Array.isArray(et?.fields))?se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Me.status===400||Me.status===422?se.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):se.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:id(Me.status),failureCategory:Me.status>=500?"server_error":void 0}),z(St),(0,it.invokeMerchantCallback)(()=>Ht.current?.(Cr("paypal",St,{code:lt.code,declineCode:lt.declineCode})));return}catch(Xe){if(Qe())return;Oe(),se.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let er=(0,ct.friendlyPayPalFailureMessage)(Xe instanceof Error?Xe.message:void 0);z(er),(0,it.invokeMerchantCallback)(()=>Ht.current?.(Cr("paypal",er)));return}},ge=()=>new ct.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),_t=m=>Qe()?Promise.reject(ge()):Promise.resolve(m),Qt=async m=>{if(Qe())throw ge();Ot||Hr();let y=dt.current,I=y?.sessionId??e,ce=y?.nonce??ot.current;se.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Oe;try{Oe=await new Ja.PaymentAPI(Rt,{telemetry:!1}).createSessionIntent(I,ce??"",(0,ct.buildPayPalSessionIntentRequest)(Ur),{idempotencyKey:ro})}catch(Xe){throw se.error({...(0,ct.classifyTelemetryFailure)(Xe,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Xe}if(Qe())throw ge();if(Oe.provider!=="paypal"||Oe.providerObjectType!==L)throw new Error(m);return se.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Oe.providerObjectId},Ne=(m,y)=>{let I=y?.nonce??ot.current;if(!I)return;let ce=y?.sessionId??e,Oe=(0,ct.resolvePayPalDeclineReason)(m);new Ja.PaymentAPI(Rt,{telemetry:!1}).reportSessionIntentDecline(ce,I,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Oe}).catch(()=>{})},X=tt;S("loadScript:scheduled (deferred 1 tick)");let J=null,$=setTimeout(()=>{if(bt){S("loadScript:skipped (cancelled before defer ran)");return}S("loadScript:start");let m=en==="live"?"production":en,y={};L==="subscription"?y={intent:"subscription",vault:!0}:L==="order"&&(y={intent:"capture"}),J=(0,wl.loadScript)({clientId:l,currency:p,...y,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let I=!1;J.then(ce=>{if(I=!0,S(`loadScript:resolved inactive=${Qe()} ns=${!!ce} buttons=${!!ce?.Buttons}`),Qe())return;if(!ce?.Buttons){S("FAIL: namespace missing Buttons factory"),O("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}se.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),se.performance({stage:"provider_ready",durationMs:se.elapsed(pe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),se.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Oe=async(Ce,U)=>{if(Qe()||ze.current!==X)return;let oe=Ce.vaultSetupToken??Ce.subscriptionID??Ce.orderID??"",gt=oe?xr.current.get(oe):Vt.current.get(X);if(!(!gt||!mn(gt.generation))&&hr(gt.generation)){xr.current.delete(oe),Vt.current.delete(gt.surfaceKey),mr("approved");try{if(Pe(!0),(0,it.invokeMerchantCallback)(()=>sr.current?.(null)),!oe)throw new ct.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ge=(0,ct.resolvePayPalApprovalIdentity)({accountPatch:gt.accountPatch,email:Yt.current,billingName:Qr.current,session:_n.current});if((0,ct.needsPayPalPayerDetails)(Ge))try{Ge=(0,ct.mergePayPalPayerIdentity)(Ge,await U?.order?.get?.())}catch{}if((Zr.current||Ke)&&!(0,ct.isValidEmail)(Ge.email)){let Tt=await W("PayPal",Ge);if(!Tt)return;Ge=Tt}(0,ct.isValidEmail)(Ge.email)&&(gt.accountPatch=(0,sn.compactBuyerIdentity)({...gt.accountPatch,...Ge}),await Zr.current?.(Ge));let at=(0,ct.buildPayPalTokenizedBody)(oe,Ur);await le(at,gt)}catch(Ge){z(Ge instanceof Error?Ge.message:"PayPal capture failed.")}finally{Qe()||Pe(!1)}}},Xe=Ce=>{let U=_e?()=>_t(_e):()=>Qt(Ce);return async()=>Mn(await U())},er=ce.Buttons({style:{layout:"horizontal",height:Za,tagline:!1},...h==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Ce,U)=>{if(Qe()){await U.reject();return}Hr();let oe=Gt.current,gt={};if(oe)try{let Tt=await oe("paypal");if(Qe()){await U.reject();return}if(!Tt.proceed){dt.current=null,Vt.current.delete(X),await U.reject();return}gt={sessionId:Tt.sessionId,accountPatch:Tt.accountPatch,nonce:Tt.nonce}}catch(Tt){S(`onClick:runBeforeButtonClick rejected msg=${(Tt instanceof Error?Tt.message:String(Tt)).slice(0,120)}`),dt.current=null,Vt.current.delete(X),await U.reject();return}(0,it.invokeMerchantCallback)(()=>Lr.current?.("paypal"));let Ge=lr(),at={generation:Ge,surfaceKey:X,...gt};dt.current=at,Vt.current.set(X,at),Fe.current={...g,attempt:Ge},await U.resolve(),se.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),se.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Re.current=se.startTiming()},createOrder:L==="order"?Xe("Failed to create PayPal order."):void 0,createSubscription:L==="subscription"?Xe("Failed to create PayPal subscription."):void 0,createVaultSetupToken:L==="setup_token"?async()=>Mn(await Qt("Failed to create PayPal setup token.")):void 0,onApprove:Oe,onCancel:()=>{if(Qe())return;let Ce=Vt.current.get(X)??dt.current;Ce&&Vt.current.delete(Ce.surfaceKey),dt.current=null,mr("cancelled"),se.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),$e.current=!0,Er({generation:Ce?.generation,remount:!0,focus:!1})},onError:Ce=>{if(Qe()||ze.current!==X)return;let U=Ce instanceof Error?Ce.message:"PayPal failed to render.";if(S(`onError rendered=${zr} msg=${U.slice(0,120)}`),zr){let oe=Vt.current.get(X)??dt.current;if(oe&&!mn(oe.generation)||!oe&&Nr())return;if(yr(U)){hr(oe?.generation);return}let{errorCode:gt,popupBlocked:Ge,providerDeclined:at,terminalReason:Tt}=(0,Se.classifyExternalMethodFailure)(Ce,{inAppBrowser:qe.inAppBrowser,handoffObserved:oe!=null&&rt.current===oe.generation});if(Ge&&H.markBlocked(),mr(Tt),at){se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Tt}),Ne(Ce,oe),(0,it.invokeMerchantCallback)(()=>Ht.current?.(Cr("paypal",U))),oe&&Vt.current.delete(oe.surfaceKey),dt.current=null,hr(oe?.generation);return}se.error({errorCode:gt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Tt}),oe&&Vt.current.delete(oe.surfaceKey),dt.current=null,Er({generation:oe?.generation,remount:!0,showRetry:!0,focus:!0}),gr(Ce,{code:"paypal_runtime_failed",popupBlocked:Ge,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:h,terminalReason:Tt});return}O(yr(U)?"teardown":"pre_ready_callback",U)}}),Me=er.isEligible();if(S(`isEligible=${Me}`),se.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Me){M(!1),O("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Fn=!0,Zt=er,Gr=()=>{if(!hn||Nt||Qe()||zr)return;Nt=!0,S(`container:dims ${Br(tn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Bn=new MutationObserver(U=>{if(!Qe()){for(let oe of U)if(oe.type==="childList")oe.addedNodes.forEach(gt=>{if(!(gt instanceof Element))return;let Ge=gt.tagName.toLowerCase(),at=(gt.getAttribute("title")??"").slice(0,40),Tt=Ge==="iframe"?` ${vn(gt)}`:"";S(`child+ ${Ge}${at?` title="${at}"`:""}${Tt} dims=${Br(gt)}`)});else if(oe.type==="attributes"&&oe.target instanceof Element){let gt=oe.target;if(gt.tagName.toLowerCase()!=="iframe")continue;let Ge=oe.attributeName;(Ge==="src"||Ge==="srcdoc")&&S(`attr~ iframe ${Ge}=${Ge==="srcdoc"?`[${(gt.getAttribute("srcdoc")??"").length}ch]`:Pn(gt.getAttribute("src"))} dims=${Br(gt)}`)}}}),Bn.observe(tn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ce=U=>{if(Qe()||zr)return;let oe=tn.querySelectorAll("iframe"),gt=typeof document<"u"&&"hasStorageAccess"in document;S(`watchdog:${U} container=${Br(tn)} children=${tn.childElementCount} iframes=${oe.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${gt} paypalNetRequests=${no.value}`),oe.forEach((Ge,at)=>{let Tt=(Ge.getAttribute("title")??"").slice(0,40);S(` iframe[${at}] ${Br(Ge)}${Tt?` title="${Tt}"`:""} ${vn(Ge)}`);let vt=Ct(Ge);vt&&S(` ${vt}`)}),cr.length===0&&S(" (no PayPal/zoid window errors captured)")};Kr.push(setTimeout(()=>Ce("3s"),3e3)),Kr.push(setTimeout(()=>Ce("8s"),8e3)),Kr.push(setTimeout(()=>Ce("15s"),15e3))},Gr(),S("render:start");let lt=se.startTiming();gn=setTimeout(()=>{Qe()||zr||(S("watchdog:11s retryable render timeout"),O("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},rd);let St=er.render(tn);(async()=>{try{if(await St,S(`render:resolved inactive=${Qe()}`),dr(),Qe()){An();return}zr=!0,M(!0),Te(!1),jt.current?.("ready"),se.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),se.performance({stage:"checkout_render",durationMs:se.elapsed(lt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Ce){let U=Ce instanceof Error?Ce.message:"PayPal failed to render.";S(`render:rejected msg=${U.slice(0,120)}`),dr(),O(yr(U)?"teardown":"render_rejected",U)}})()}).catch(ce=>{let Oe=ce instanceof Error?ce.message:"PayPal operation failed.";S(`provider:failed msg=${Oe.slice(0,120)}`);let Xe="script_rejected";I&&yr(Oe)?Xe="teardown":I&&Fn&&(Xe="render_rejected"),O(Xe,Oe)})},0);return()=>{bt=!0,clearTimeout($),yn&&clearTimeout(yn),dr(),Q.current===oo&&(Q.current=null),An(),Re.current=null,Fe.current=null}},[D,Rt,l,p,u,L,h,ve,e,_e,tt,ke,W,Ke,S,mr]);let Jt=de?(0,ln.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ft?"#fef2f2":"#f3f4f6",border:`1px solid ${ft?"#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=${he} failed=${ft})`,be.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${xe.join(`
4
- `)}`]}):null;return kt&&!ne?ce?(0,an.jsx)("div",{children:vt}):null:(0,an.jsxs)("div",{children:[vt,Ze&&(0,an.jsx)(zo,{identity:Ze.identity,methodLabel:Ze.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:je,onCancel:()=>je(null)}),(0,an.jsxs)("div",{"aria-hidden":dt||Ze?!0:void 0,style:dt||Ze?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Za},children:[!ke&&!dt&&(0,an.jsx)("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"}}),(0,an.jsx)("div",{ref:Z,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Za,display:"flex",opacity:ke?1:0},"aria-busy":U||h},Be)]},Be),at&&(0,an.jsx)("button",{ref:we,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Tr,style:nd,children:"Try PayPal again"})]})}function ga(e){return(0,an.jsx)(kl,{...e})}function Rl(e){return(0,an.jsx)(kl,{...e})}var ha=require("react/jsx-runtime");function Vo({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,ha.jsxs)("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,...r?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...n??{}},children:[r&&(0,ha.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ha.jsx)("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]})}var ut=require("@flopay/shared");var pr=require("react/jsx-runtime");var sd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function qr({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:o,errorLabel:i="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:u=sd}){let p={fontSize:13,color:u.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,pr.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,pr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...u.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,pr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,pr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,pr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:u.spinnerTrackColor,strokeWidth:"3"}),(0,pr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:u.spinnerAccentColor})]}),e==="success"&&(0,pr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,pr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,pr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,pr.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,pr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,pr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,pr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,pr.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,pr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:u.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(o??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&l!==null&&(0,pr.jsx)("p",{style:p,children:l}),e==="error"&&t&&(0,pr.jsx)("p",{style:p,children:t}),(0,pr.jsx)("style",{children:`
3
+ ${be.join(`
4
+ `)}`]}):null;return ft&&!te?de?(0,ln.jsx)("div",{children:Jt}):null:(0,ln.jsxs)("div",{children:[Jt,st&&(0,ln.jsx)(zo,{identity:st.identity,methodLabel:st.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ee,onCancel:()=>Ee(null)}),(0,ln.jsxs)("div",{"aria-hidden":Ye||st?!0:void 0,style:Ye||st?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Za},children:[!he&&!Ye&&(0,ln.jsx)("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"}}),(0,ln.jsx)("div",{ref:Z,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Za,display:"flex",opacity:he?1:0},"aria-busy":q||f},tt)]},tt),He&&(0,ln.jsx)("button",{ref:ye,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Tr,style:nd,children:"Try PayPal again"})]})}function ga(e){return(0,ln.jsx)(kl,{...e})}function Rl(e){return(0,ln.jsx)(kl,{...e})}var ha=require("react/jsx-runtime");function Vo({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,ha.jsxs)("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,...r?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...n??{}},children:[r&&(0,ha.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ha.jsx)("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]})}var mt=require("@flopay/shared");var pr=require("react/jsx-runtime");var sd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function Wr({status:e,errorMessage:t,authorized:r=!1,processingLabel:n="PROCESSING...",successLabel:a,errorLabel:i="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:u=sd}){let p={fontSize:13,color:u.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,pr.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,pr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...u.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,pr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,pr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,pr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:u.spinnerTrackColor,strokeWidth:"3"}),(0,pr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:u.spinnerAccentColor})]}),e==="success"&&(0,pr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,pr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,pr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,pr.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,pr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,pr.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,pr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,pr.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,pr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:u.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(a??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&l!==null&&(0,pr.jsx)("p",{style:p,children:l}),e==="error"&&t&&(0,pr.jsx)("p",{style:p,children:t}),(0,pr.jsx)("style",{children:`
5
5
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
6
6
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
7
7
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
8
8
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
9
- `})]})})}var El=require("@flopay/shared"),Rr=require("react");var Il=require("react/jsx-runtime");function Pa({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:o}){let[i,l]=(0,Rr.useState)(e instanceof Promise?null:e),[u,p]=(0,Rr.useState)(t instanceof Promise||!t?null:t),C=(0,Rr.useRef)(null),w=(0,Rr.useRef)(null),S=jo(n);(0,Rr.useEffect)(()=>{S({class:"lifecycle",name:"checkout.mount"})},[S]),(0,Rr.useEffect)(()=>{i&&S({class:"lifecycle",name:"sdk.initialize.ready"})},[S,i]),(0,Rr.useEffect)(()=>{if(i)return Cr(i)?.subscribe?.(S)},[S,i]),(0,Rr.useEffect)(()=>{if(!(!u||u===i))return Cr(u)?.subscribe?.(S)},[S,i,u]),(0,Rr.useEffect)(()=>{if(!i)return;let I=Cr(i);return C.current=I?.beginCheckout()??I?.now()??0,I?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{I?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Rr.useEffect)(()=>{let I=!1;return e instanceof Promise?e.then($=>{I||l($)},()=>{I||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{I=!0}},[S,e]),(0,Rr.useEffect)(()=>{let I=!1;if(!t){p(null);return}return t instanceof Promise?t.then($=>{I||p($)},()=>{I||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{I=!0}},[S,t]),(0,Rr.useEffect)(()=>{if(!i||w.current===i)return;w.current=i;let I=Cr(i);I?.log({name:"checkout.rendered",stage:"checkout_render"}),S({class:"lifecycle",name:"checkout.rendered"}),I?.performance({stage:"checkout_render",durationMs:I.elapsed(C.current??0),durationMode:"machine"})},[S,i]);let _=(0,El.resolveBillingApiUrl)(r?.billingApiUrl),K=(0,Rr.useMemo)(()=>({flopay:i,paypalFlopay:u,billingApiUrl:_,emitInstrument:S}),[i,u,_,S]);return(0,Il.jsx)(nn.Provider,{value:K,children:o})}var In=require("@flopay/shared");async function Qa(e,t){e.current?.abort();let r=new AbortController;e.current=r;try{return await t(r.signal)}finally{e.current===r&&(e.current=null)}}var sn=require("@flopay/js"),lt=require("@flopay/shared");var Ca="card";async function ld(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:n??null}}async function cd(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:u}=await e.confirmCardSetup(t,r);return{error:u,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,r);return{error:i,intent:o??null}}function $o(e){return new lt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function dd(){return new lt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Ji(e,t){return Object.assign(e,{checkoutMethod:t})}function Zn(e,t){let r=e instanceof lt.FloPayError?e:new lt.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function va(e,t){try{return await e()}catch(r){throw Zn(r,t)}}function Tl(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 Ml(e){return(0,sn.runSavedCardChallenge)(e)}async function Wo(e,t){let{billingApiUrl:r,sessionId:n,signal:o}=t,i=t.nonce??t.session.clientSecret,l=new sn.PaymentAPI(r,{telemetry:!1}),u=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,p;try{p=await(0,sn.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o,createDeclineError:w=>qn({type:w.declineReason??"authorization_declined",gatewayErrorCode:w.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(w){if(o.aborted||w instanceof Error&&w.name==="AbortError")throw w instanceof lt.FloPayError&&w.code==="three_ds_aborted"?w:$o(w);if(!(w instanceof lt.FloPayError)||w.code!=="three_ds_timeout"&&w.code!=="checkout_processing_timeout")throw w;try{p=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:i,statusUrl:u,timeoutMs:5e3,signal:o})}catch(_){if(o.aborted)throw $o(_);if(!(_ instanceof lt.FloPayError)||_.code!=="checkout_processing_timeout")throw _}let S=p&&so(p,t.session);if(!Yn(S)&&S?.status!=="expired"){if(t.telemetry){let _=new sn.PaymentAPI(r);try{_.reportThreeDsAbandoned(n)}finally{_.destroy()}}throw dd()}}let C=p&&so(p,t.session);if(!Yn(C))throw Lo(C);return{...Gn(C,n),checkoutMethod:"card"}}function qn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=(0,ho.applyFriendlyMessageOverride)(o)??o,l=Ji(new lt.FloPayError(i,"api_error",{code:e?.code??(0,lt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,lt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(l.orderId=e.orderId),l}function Xi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ei(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function xl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of r)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ei(o)))return o;let n=e?.data;if(n&&typeof n=="object"){let o=n,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let u of i)if(typeof u=="string"&&u.length>0&&(!t?.requirePaymentIntentClientSecret||ei(u)))return u;let l=o.gateways;if(l&&typeof l=="object"){let u=l.stripe;if(u&&typeof u=="object"){let p=u,C=[p.stripeClientSecret,p.clientSecret];for(let w of C)if(typeof w=="string"&&w.length>0&&(!t?.requirePaymentIntentClientSecret||ei(w)))return w}}}}async function ud({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let o=xl(n,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let u=(await new sn.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(ei(u))return{type:"3ds_required",threeDSecureToken:u}}catch{}return null}async function Ho({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:o,returnUrl:i,telemetry:l}){let u=e.replace(/\/+$/,""),p=t??r.id,C=n??r.clientSecret,w=r.customer?.id??r.accountData?.userId??"",S=r.customer?.email??r.accountData?.email??"",_=r.customer?.firstName??r.accountData?.firstName??"",K=r.customer?.lastName??r.accountData?.lastName??"",I=r.customer?.country??r.accountData?.country??void 0,$=r.customer?.zip??r.accountData?.zip??void 0,h=await new sn.PaymentAPI(u,l===!1?{telemetry:!1}:void 0).processPayment(w,{sessionId:p,nonce:C,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:w,email:S,firstName:_,lastName:K,country:I,zip:$},returnUrl:i??Xi(r)});if(h.ok){let A=typeof h.json=="function"?await h.json().catch(()=>null):null;if((0,lt.isAuthorizationOnlySession)(r)||A?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof A?.paymentId=="string"?A.paymentId:r.paymentId,sessionId:typeof A?.sessionId=="string"?A.sessionId:p,authorizationExpiresAt:typeof A?.authorizationExpiresAt=="string"?A.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:pa(o),checkoutMethod:_l(o,r)}};let ue=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ue?{paymentIntentId:ue}:{},paymentMethodId:pa(o),checkoutMethod:_l(o,r)}}}let P;try{P=await h.json()}catch(A){throw new lt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status,cause:A})}if(P?.type==="3ds_required"&&typeof P.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:P.nextActionRedirectUrl};if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let A=xl(P);if(!A)throw new lt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status});return{type:P.type,threeDSecureToken:A,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let A=await ud({billingApiUrl:u,sessionId:p,nonce:C,responseJson:P});if(A)return A;throw Ji(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ee=new lt.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:h.status});throw Object.assign(ee,{telemetryOutcome:(0,lt.classifyPaymentRejection)(h.status,P)})}async function ti(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:o,sessionId:i,session:l,returnUrl:u,telemetry:p,signal:C}){let w=t?.getRawProvider();if(!w)throw Zn(new lt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw Ji(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let S=(0,lt.isSetupIntentClientSecret)(e.threeDSecureToken),_=null,K=e.paymentMethodId,I=await va(()=>ld(w,e.threeDSecureToken,S),"card");if(I){if(I.error)throw Zn(new lt.FloPayError(I.error.message??`Failed to retrieve 3DS ${S?"setup":"payment"} status.`,"api_error",{code:I.error.code}),"card");let T=I.intent;!K&&T?.payment_method&&(typeof T.payment_method=="string"?K=T.payment_method:"id"in T.payment_method&&(K=T.payment_method.id??void 0))}let $=K?await va(()=>cd(w,e.threeDSecureToken,{payment_method:K,return_url:u??Xi(l)??window.location.href},S),"card"):null;if($){if($.error)throw Zn(new lt.FloPayError($.error.message??"3DS authentication failed.","api_error",{code:$.error.code}),"card");_=$.intent}else{let T=await va(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(T.error)throw Zn(new lt.FloPayError(T.error.message??"3DS authentication failed.","api_error",{code:T.error.code}),"card");_=(S?T.setupIntent:T.paymentIntent)??null}if(_&&(_.status==="requires_capture"||_.status==="succeeded"||_.status==="processing")){let T=await Ho({billingApiUrl:o,sessionId:i,session:l,telemetry:p,tokenizedData:{id:_.id,type:"card",threeDSecureActionResultTokenId:_.id},returnUrl:u});return T.type==="success"?{...T.result,paymentIntentId:T.result.paymentIntentId??_.id,paymentMethodId:T.result.paymentMethodId??K}:T.type==="next_action_required"?Wo(T,{billingApiUrl:o,sessionId:i??l.id,session:l,signal:C}):ti(T,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:o,sessionId:i,session:l,returnUrl:u,telemetry:p,signal:C})}throw Zn(new lt.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let S=(r??t)?.getRawProvider();if(!S)throw Zn(new lt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:K}=await va(()=>S.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(K)throw Zn(new lt.FloPayError(K.message??"PayPal authorization failed.","api_error",{code:K.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:_}=await va(()=>S.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:u??Xi(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(_)throw Zn(new lt.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new lt.FloPayError("Unsupported payment redirect state.","api_error")}function ba(e){if(e instanceof lt.FloPayError){let n=(0,ho.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new lt.FloPayError(n,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.",r=(0,ho.applyFriendlyMessageOverride)(t)??t;return new lt.FloPayError(r,"api_error")}function Zi(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,lt.isMountableVaultBlock)(e.data.session?.vault)||(0,kn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new lt.FloPayError("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 _l(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,kn.canRecoverHostedCardForm)(t)?"card":void 0}async function Qi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[l,u]=await Promise.all([(0,sn.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:o}),i?(0,sn.loadFloPay)(i,{billingApiUrl:r,locale:n,telemetry:o}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);if(!l)throw new lt.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return i?p=u:t&&(p=l),{flopay:l,paypalFlopay:p}}var Tn=require("@flopay/js"),d=require("@flopay/shared"),rr=require("@stripe/react-stripe-js"),a=Vi(require("react"),1);function Ko(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ri(e,t){if(e)return{error:r=>e.error(Ko(t,r)),log:r=>e.log(Ko(t,r)),performance:r=>e.performance(Ko(t,r)),terminal:r=>e.terminal(Ko(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var Qn=require("@flopay/shared"),Fl=require("react");var Al={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var br=require("react/jsx-runtime"),pd=`
9
+ `})]})})}var El=require("@flopay/shared"),Ir=require("react");var Il=require("react/jsx-runtime");function Pa({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:a}){let[i,l]=(0,Ir.useState)(e instanceof Promise?null:e),[u,p]=(0,Ir.useState)(t instanceof Promise||!t?null:t),v=(0,Ir.useRef)(null),R=(0,Ir.useRef)(null),w=jo(n);(0,Ir.useEffect)(()=>{w({class:"lifecycle",name:"checkout.mount"})},[w]),(0,Ir.useEffect)(()=>{i&&w({class:"lifecycle",name:"sdk.initialize.ready"})},[w,i]),(0,Ir.useEffect)(()=>{if(i)return Sr(i)?.subscribe?.(w)},[w,i]),(0,Ir.useEffect)(()=>{if(!(!u||u===i))return Sr(u)?.subscribe?.(w)},[w,i,u]),(0,Ir.useEffect)(()=>{if(!i)return;let T=Sr(i);return v.current=T?.beginCheckout()??T?.now()??0,T?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{T?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Ir.useEffect)(()=>{let T=!1;return e instanceof Promise?e.then(V=>{T||l(V)},()=>{T||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{T=!0}},[w,e]),(0,Ir.useEffect)(()=>{let T=!1;if(!t){p(null);return}return t instanceof Promise?t.then(V=>{T||p(V)},()=>{T||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{T=!0}},[w,t]),(0,Ir.useEffect)(()=>{if(!i||R.current===i)return;R.current=i;let T=Sr(i);T?.log({name:"checkout.rendered",stage:"checkout_render"}),w({class:"lifecycle",name:"checkout.rendered"}),T?.performance({stage:"checkout_render",durationMs:T.elapsed(v.current??0),durationMode:"machine"})},[w,i]);let x=(0,El.resolveBillingApiUrl)(r?.billingApiUrl),K=(0,Ir.useMemo)(()=>({flopay:i,paypalFlopay:u,billingApiUrl:x,emitInstrument:w}),[i,u,x,w]);return(0,Il.jsx)(an.Provider,{value:K,children:a})}var Rn=require("@flopay/shared");async function Qa(e,t){e.current?.abort();let r=new AbortController;e.current=r;try{return await t(r.signal)}finally{e.current===r&&(e.current=null)}}var cn=require("@flopay/js"),ut=require("@flopay/shared");var ba="card";async function ld(e,t,r){if(r){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:n,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:n??null}}async function cd(e,t,r,n){if(n){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:u}=await e.confirmCardSetup(t,r);return{error:u,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,r);return{error:i,intent:a??null}}function Wo(e){return new ut.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function dd(){return new ut.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Ji(e,t){return Object.assign(e,{checkoutMethod:t})}function Zn(e,t){let r=e instanceof ut.FloPayError?e:new ut.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(r,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function va(e,t){try{return await e()}catch(r){throw Zn(r,t)}}function Tl(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 Ml(e){return(0,cn.runSavedCardChallenge)(e)}async function $o(e,t){let{billingApiUrl:r,sessionId:n,signal:a}=t,i=t.nonce??t.session.clientSecret,l=new cn.PaymentAPI(r,{telemetry:!1}),u=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,p;try{p=await(0,cn.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:a,createDeclineError:R=>qn({type:R.declineReason??"authorization_declined",gatewayErrorCode:R.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(R){if(a.aborted||R instanceof Error&&R.name==="AbortError")throw R instanceof ut.FloPayError&&R.code==="three_ds_aborted"?R:Wo(R);if(!(R instanceof ut.FloPayError)||R.code!=="three_ds_timeout"&&R.code!=="checkout_processing_timeout")throw R;try{p=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:i,statusUrl:u,timeoutMs:5e3,signal:a})}catch(x){if(a.aborted)throw Wo(x);if(!(x instanceof ut.FloPayError)||x.code!=="checkout_processing_timeout")throw x}let w=p&&so(p,t.session);if(!Yn(w)&&w?.status!=="expired"){if(t.telemetry){let x=new cn.PaymentAPI(r);try{x.reportThreeDsAbandoned(n)}finally{x.destroy()}}throw dd()}}let v=p&&so(p,t.session);if(!Yn(v))throw Lo(v);return{...Gn(v,n),checkoutMethod:"card"}}function qn(e,t="Payment failed. Please try again.",r){let n=r?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=(0,ho.applyFriendlyMessageOverride)(a)??a,l=Ji(new ut.FloPayError(i,"api_error",{code:e?.code??(0,ut.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,ut.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(l.orderId=e.orderId),l}function Xi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ei(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function xl(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of r)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||ei(a)))return a;let n=e?.data;if(n&&typeof n=="object"){let a=n,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let u of i)if(typeof u=="string"&&u.length>0&&(!t?.requirePaymentIntentClientSecret||ei(u)))return u;let l=a.gateways;if(l&&typeof l=="object"){let u=l.stripe;if(u&&typeof u=="object"){let p=u,v=[p.stripeClientSecret,p.clientSecret];for(let R of v)if(typeof R=="string"&&R.length>0&&(!t?.requirePaymentIntentClientSecret||ei(R)))return R}}}}async function ud({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let a=xl(n,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let u=(await new cn.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(ei(u))return{type:"3ds_required",threeDSecureToken:u}}catch{}return null}async function Ho({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:a,returnUrl:i,telemetry:l}){let u=e.replace(/\/+$/,""),p=t??r.id,v=n??r.clientSecret,R=r.customer?.id??r.accountData?.userId??"",w=r.customer?.email??r.accountData?.email??"",x=r.customer?.firstName??r.accountData?.firstName??"",K=r.customer?.lastName??r.accountData?.lastName??"",T=r.customer?.country??r.accountData?.country??void 0,V=r.customer?.zip??r.accountData?.zip??void 0,f=await new cn.PaymentAPI(u,l===!1?{telemetry:!1}:void 0).processPayment(R,{sessionId:p,nonce:v,paymentMethodCategory:"saved",tokenizedData:a,accountData:{userId:R,email:w,firstName:x,lastName:K,country:T,zip:V},returnUrl:i??Xi(r)});if(f.ok){let D=typeof f.json=="function"?await f.json().catch(()=>null):null;if((0,ut.isAuthorizationOnlySession)(r)||D?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof D?.paymentId=="string"?D.paymentId:r.paymentId,sessionId:typeof D?.sessionId=="string"?D.sessionId:p,authorizationExpiresAt:typeof D?.authorizationExpiresAt=="string"?D.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:pa(a),checkoutMethod:_l(a,r)}};let ue=a?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ue?{paymentIntentId:ue}:{},paymentMethodId:pa(a),checkoutMethod:_l(a,r)}}}let P;try{P=await f.json()}catch(D){throw new ut.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status,cause:D})}if(P?.type==="3ds_required"&&typeof P.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:P.nextActionRedirectUrl};if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let D=xl(P);if(!D)throw new ut.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:f.status});return{type:P.type,threeDSecureToken:D,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let D=await ud({billingApiUrl:u,sessionId:p,nonce:v,responseJson:P});if(D)return D;throw Ji(new ut.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ee=new ut.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:f.status});throw Object.assign(ee,{telemetryOutcome:(0,ut.classifyPaymentRejection)(f.status,P)})}async function ti(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:i,session:l,returnUrl:u,telemetry:p,signal:v}){let R=t?.getRawProvider();if(!R)throw Zn(new ut.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw Ji(new ut.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let w=(0,ut.isSetupIntentClientSecret)(e.threeDSecureToken),x=null,K=e.paymentMethodId,T=await va(()=>ld(R,e.threeDSecureToken,w),"card");if(T){if(T.error)throw Zn(new ut.FloPayError(T.error.message??`Failed to retrieve 3DS ${w?"setup":"payment"} status.`,"api_error",{code:T.error.code}),"card");let A=T.intent;!K&&A?.payment_method&&(typeof A.payment_method=="string"?K=A.payment_method:"id"in A.payment_method&&(K=A.payment_method.id??void 0))}let V=K?await va(()=>cd(R,e.threeDSecureToken,{payment_method:K,return_url:u??Xi(l)??window.location.href},w),"card"):null;if(V){if(V.error)throw Zn(new ut.FloPayError(V.error.message??"3DS authentication failed.","api_error",{code:V.error.code}),"card");x=V.intent}else{let A=await va(()=>R.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(A.error)throw Zn(new ut.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");x=(w?A.setupIntent:A.paymentIntent)??null}if(x&&(x.status==="requires_capture"||x.status==="succeeded"||x.status==="processing")){let A=await Ho({billingApiUrl:a,sessionId:i,session:l,telemetry:p,tokenizedData:{id:x.id,type:"card",threeDSecureActionResultTokenId:x.id},returnUrl:u});return A.type==="success"?{...A.result,paymentIntentId:A.result.paymentIntentId??x.id,paymentMethodId:A.result.paymentMethodId??K}:A.type==="next_action_required"?$o(A,{billingApiUrl:a,sessionId:i??l.id,session:l,signal:v}):ti(A,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:a,sessionId:i,session:l,returnUrl:u,telemetry:p,signal:v})}throw Zn(new ut.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let w=(r??t)?.getRawProvider();if(!w)throw Zn(new ut.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:K}=await va(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(K)throw Zn(new ut.FloPayError(K.message??"PayPal authorization failed.","api_error",{code:K.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:x}=await va(()=>w.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:u??Xi(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(x)throw Zn(new ut.FloPayError(x.message??"PayPal authorization failed.","api_error",{code:x.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new ut.FloPayError("Unsupported payment redirect state.","api_error")}function Ca(e){if(e instanceof ut.FloPayError){let n=(0,ho.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new ut.FloPayError(n,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.",r=(0,ho.applyFriendlyMessageOverride)(t)??t;return new ut.FloPayError(r,"api_error")}function Zi(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,ut.isMountableVaultBlock)(e.data.session?.vault)||(0,Sn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new ut.FloPayError("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 _l(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Sn.canRecoverHostedCardForm)(t)?"card":void 0}async function Qi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:r,locale:n,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[l,u]=await Promise.all([(0,cn.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:a}),i?(0,cn.loadFloPay)(i,{billingApiUrl:r,locale:n,telemetry:a}).catch(v=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",v),null)):Promise.resolve(null)]);if(!l)throw new ut.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return i?p=u:t&&(p=l),{flopay:l,paypalFlopay:p}}var In=require("@flopay/js"),c=require("@flopay/shared"),or=require("@stripe/react-stripe-js"),o=Vi(require("react"),1);function Ko(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ri(e,t){if(e)return{error:r=>e.error(Ko(t,r)),log:r=>e.log(Ko(t,r)),performance:r=>e.performance(Ko(t,r)),terminal:r=>e.terminal(Ko(t,r)),now:()=>e.now(),elapsed:r=>e.elapsed(r),setCheckoutContext:r=>e.setCheckoutContext(r),beginCheckout:r=>e.beginCheckout(r),disable:()=>e.disable(),subscribe:r=>e.subscribe(r),flush:()=>e.flush(),destroy:()=>e.destroy()}}var Qn=require("@flopay/shared"),Fl=require("react");var Al={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var wr=require("react/jsx-runtime"),pd=`
10
10
  .paypal-buttons { margin: 0 !important; vertical-align: top !important; }
11
11
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
12
12
  @keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
@@ -27,7 +27,7 @@ ${xe.join(`
27
27
  0% { opacity: 1; transform: translateX(0) scale(1); }
28
28
  100% { opacity: 0; transform: translateX(16px) scale(0.97); }
29
29
  }
30
- `,Go=44;function Yo(){return(0,br.jsx)("style",{children:pd})}function Sa(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function wa({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,br.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,br.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,br.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:n})]})}function es(e){return e!=="unavailable"&&e!=="load_error"}function ni({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:l,backgroundColor:u,borderColor:p,textColor:C,borderRadius:w,fontFamily:S}){let _=(0,Qn.resolveStripeMethodBrandVariant)(e,t),K=Al[e],[I,$]=(0,Fl.useState)(!1),T=!!K&&!I,h=_?.backgroundColor??u??"#ffffff",P=_?.borderColor??p??"#d1d5db",ee=_?.textColor??C??"#262833";return(0,br.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&l()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Go,padding:"0 1rem",backgroundColor:h,color:ee,border:`1px solid ${P}`,borderRadius:w??8,fontSize:"0.95rem",fontWeight:600,fontFamily:S,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,br.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,Qn.getStripeMethodDisplayName)(e)}\u2026`}):(0,br.jsxs)(br.Fragment,{children:[(0,br.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,Qn.hasVendoredStripeMethodLogo)(e)?8:0},children:[T?(0,br.jsx)("img",{src:K,alt:"","aria-hidden":"true",onError:()=>$(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!T&&_?.logoSvg?(0,br.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:_.logoSvg}}):null,(0,br.jsx)("span",{children:(0,Qn.getStripeMethodDisplayName)(e)})]}),i&&(0,br.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ee,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,br.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function oi(e){let t=new Set(e.map(Qn.stripeExpressMethodToOptionKey)),r=n=>n==="applePay"||n==="googlePay"?"always":"auto";return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(n=>[n,t.has(n)?r(n):"never"]))}var ai={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},ii={type:"accordion",defaultCollapsed:!1,radios:"never"};function si({testId:e,attributes:t,disabled:r,onClick:n,color:o,borderRadius:i,style:l,children:u}){return(0,br.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:o,color:"white",border:"none",borderRadius:i,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...l??{}},children:u})}var Zr=require("react");var ka=require("@flopay/shared"),yd=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function md(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return yd.has(t.charAt(0).toLowerCase()+t.slice(1))}function fd(e,t){return typeof t=="number"&&t!==0&&!md(e)?`${t}px`:String(t).trim()}function Bl(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=fd(r,n)}}}var Co=require("react/jsx-runtime"),ts=new WeakSet;function lo({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:o,theme:i,submitLabel:l,containerStyle:u,onReady:p,onError:C,onValidation:w}){let S=(0,Zr.useRef)(null),_=(0,Zr.useRef)(p),K=(0,Zr.useRef)(C),I=(0,Zr.useRef)(w);_.current=p,K.current=C,I.current=w;let $=(0,Zr.useRef)(i);$.current=i;let T=(0,Zr.useRef)(null),h=l??void 0,P=(0,Zr.useRef)(h);P.current=h;let ee=(0,Zr.useRef)(void 0);return(0,Zr.useEffect)(()=>{let A=S.current;if(!A)return;let ue=!0,F=!1,re=()=>{!ue||F||(F=!0,_.current?.())},Ee=e.on("ready",()=>{re()}),pe=e.on("error",Y=>{K.current?.(Y.message??"There was a problem loading the secure card form.")}),We=e.on("validation",Y=>{I.current?.(Y.message??null)}),wt=P.current??(ts.has(e)?null:void 0),ce={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...o?{verificationRequired:!0}:{},...$.current?{theme:$.current}:{},...wt===void 0?{}:{submitLabel:wt}};return T.current=$.current??null,ee.current=P.current,P.current!==void 0&&ts.add(e),e.mount(A,ce).then(()=>{re()}).catch(Y=>{ue&&K.current?.(Y instanceof Error?Y.message:"Failed to load the secure card form.")}),()=>{ue=!1,Ee(),pe(),We(),e.unmount()}},[e,t,r,n,o]),Po(()=>{let A=S.current;A&&Bl(A,u)},[u]),(0,Zr.useEffect)(()=>{i!==void 0&&(i===null&&T.current===null||(T.current=i,e.applyTheme?.(i)))},[e,i]),(0,Zr.useEffect)(()=>{h!==ee.current&&(ee.current=h,h!==void 0&&ts.add(e),e.setSubmitLabel?.(h??null))},[e,h]),(0,Co.jsx)("div",{ref:S,"data-testid":"flopay-vault-card-fields"})}function li({label:e}){return(0,Co.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,Co.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,Co.jsx)("span",{children:e}),(0,Co.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var us=require("@flopay/shared"),c=require("react/jsx-runtime"),jn="flopay_stripe_resume",Dl="flopay_wallet_resume",Hl="fw1",gd="fw2",Kl=300*1e3,hd=900,Pd=25e3,vd=25e3,Cd=1e4,_n={provider:"paypal",paymentMethodCategory:"paypal"},bd="x-flopay-process-result-source",Sd="status";async function wd(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var ci={},Ea=class{constructor(t){this.reason=t}};function kd(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function nr(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 ls(e){return`${gd}:${e}`}function di(e){return nr(ls(e))}function ui(e,t){if(typeof window>"u")return null;let r=ls(e);try{let n=localStorage.getItem(r);if(!n)return null;let o=JSON.parse(n);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>Kl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(di(e),null):o}catch{return di(e),null}}function Rd(e){return nr(ls(e.sessionId),e)}function Ol(e,t,r){let n=ui(e,t);return!n||n.clientSecret!==r?!1:di(e)}function rs(e,t,r){if(typeof window>"u")return;ui(e,t)?.clientSecret===r&&di(e)}function Ed(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ns(e,t,r){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 n=r?e.status==="succeeded":ua(e.status),o=Ed(e);return!n||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function Ll(e,t,r){let n=null;try{return await Promise.race([gl(e,t),new Promise(o=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),o(null)},Cd),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Id(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Gl(e){return e instanceof d.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function pi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Tn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(o){throw Gl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),o}}var os=d.STRIPE_PAYPAL_RESUME_KEY,Ra=new Map,_d=250,Nl="Just a moment \u2014 we are finalizing your order. Please press pay again.",Td="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function cs(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function yi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new Tn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Md(e){return e instanceof d.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Yl({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,o=t?.trim(),i=(0,No.splitFullName)(r),l=i.firstName?i:(0,No.splitFullName)(n?.name);return(0,on.compactBuyerIdentity)({email:(0,d.isValidEmail)(o)?o:n?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function xd({event:e,prepared:t,email:r,billingName:n,methodLabel:o,collect:i}){let l=Yl({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,d.isValidEmail)(l.email)?l:i(o,l)}var Ia=180,Ul=`flopay-card-enter ${Ia}ms cubic-bezier(0, 0, 0.2, 1) both`,zl=`flopay-card-exit ${Ia}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Ad=`flopay-buttons-enter ${Ia}ms cubic-bezier(0, 0, 0.2, 1) both`,Fd=`flopay-buttons-exit ${Ia}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Bd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ds(e){return(0,d.derivePrimaryTileStyle)(e)}var Dd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Od(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 as={width:"100%",minHeight:Go,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 ql(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function is(e){return e==="paypal"?"PayPal":(0,d.getStripeMethodDisplayName)(e)}function Ld(e){let t=(0,d.getPostalCodeExample)(e);return`Enter a valid ${(0,d.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Nd(e,t,r){let n=(0,d.isPostalCodeSupported)(e),o=t.trim(),i=r&&n,l=i&&!o,u=i&&!!o&&!(0,d.isValidPostalCode)(e,o);return{visible:r,supported:n,required:i,empty:l,malformed:u}}function Ud(e,t){let r=e.trim(),n=t&&!r,o=t&&!!r&&!(0,d.isValidEmail)(r);return{required:t,empty:n,malformed:o,value:r}}function zd(e){return typeof e=="number"?`${e}px`:e}function mi(e){return(0,c.jsx)(qd,{...e})}function jl({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:o,onErrorChange:i,isProcessing:l=!1,onButtonClick:u,onDecline:p,onTechnicalFailure:C,runBeforeButtonClick:w,billingName:S,onBuyerIdentityReady:_,onLoadStateChange:K,placeholderBorderRadius:I,popupCapabilityOwner:$,externalTelemetryContext:T,presentationMode:h}){let P=Jn(),{emitInstrument:ee}=(0,a.useContext)(nn),A=(0,rr.useStripe)(),ue=(0,rr.useElements)(),F=(0,a.useMemo)(()=>ri(Cr(P),T),[T,P]),[re,Ee]=(0,a.useState)("loading");(0,a.useEffect)(()=>{K?.(re)},[re,K]);let[pe,We]=(0,a.useState)(!1),wt=(0,a.useRef)(!1),ce=!(0,d.isValidEmail)(r?.trim())||!S?.trim(),{request:Y,collect:ct,finish:be}=Uo(),Me=(0,a.useRef)(!1),Se=(0,a.useRef)(null),Z=(0,a.useRef)(null),[de,ye]=(0,a.useState)(0),[Ie,_e]=(0,a.useState)(!1),fe=(0,a.useRef)(!1),j=(0,a.useRef)(new Map),{startAttempt:L,finishAttempt:we,invalidateAttempt:Ne,isAttemptInvalidated:ke,isAttemptCurrent:N,generationRef:dt}=fa((U,he,Ze)=>{C?.(U,he,{...Ze,popupBlocked:Ze?.popupBlocked??(0,Ce.isPopupBlockedError)(he),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h,terminalReason:"overlay_timeout"}),_e(!0),ye(G=>G+1)},{onHandoffObserved:()=>{$.markAvailable(),F?.log({name:"provider.popup.opened",stage:"overlay_open",..._n,attempt:dt.current})}});(0,a.useEffect)(()=>{Ie&&Z.current?.focus()},[Ie,de]);let ge=(0,a.useCallback)(()=>{ye(U=>U+1)},[]),Be=(0,a.useCallback)((U,he,Ze)=>{Ne(Ze),C?.("paypal",U,{code:he,popupBlocked:(0,Ce.isPopupBlockedError)(U),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h}),_e(!0),ge()},[Ne,C,h,ge]),Xe=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Se.current?.querySelector("iframe")??Se.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{fe.current&&(fe.current=!1,Xe())},[Xe,de]);let Ae=(0,a.useCallback)(()=>{_e(!1),i?.(null),Xe()},[Xe,i]);(0,a.useEffect)(()=>{if(!A||Me.current)return;let[U,he,Ze]=(0,d.readStripeRedirectParams)();if(!U||!he)return;let G=(0,d.readMatchingStripePayPalContinuation)(he);if(!G)return;Me.current=!0;let je=!0,ht=Ra.get(he);ht||(ht=Ze==="failed"?Promise.resolve(null):Promise.resolve().then(()=>A.retrievePaymentIntent(he)),Ra.set(he,ht));let Qe={accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce},At=()=>{F?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",..._n,requestCategory:"provider_sdk"})};return F?.log({name:"provider.redirect.resumed",stage:"redirect_resume",..._n}),(async()=>{try{We(!0);let y=await ht;if(!je)return;if(y?.error){Ra.delete(he),At(),i?.(y.error.message??"Failed to retrieve PayPal payment status.");return}if((0,d.clearStripePayPalReturn)(),Ra.delete(he),Ze==="failed"){let W="PayPal payment was declined. Please try again.";F?.terminal({outcome:"payment_declined",..._n,terminalReason:"provider_declined"}),i?.(W),p?.(vr("paypal",W));return}let v=y?.paymentIntent;if(v&&v.id!==U){At(),i?.("Failed to match the returned PayPal payment.");return}if(v&&(v.status==="requires_capture"||v.status==="succeeded")){let W=typeof v.payment_method=="string"?v.payment_method:v.payment_method?.id;o({id:W??v.id,type:"card",threeDSecureActionResultTokenId:v.id,isPaypal:!0},{...Qe,presentationMode:"redirect"})}else{let W="PayPal payment was not completed. Please try again.";F?.terminal({outcome:v?.status==="canceled"?"payment_cancelled":"payment_declined",..._n,terminalReason:v?.status==="canceled"?"cancelled":"provider_declined"}),i?.(W),p?.(vr("paypal",W))}}catch(y){if(!je)return;Ra.delete(he),At(),i?.(y instanceof Error?y.message:"Failed to complete PayPal payment.")}finally{je&&We(!1)}})(),()=>{je=!1,Me.current=!1}},[A,o,i,p,F]);let at=(0,a.useCallback)(async(U=!1)=>{let he=w?await w("paypal"):{proceed:!0};if(!he.proceed)return j.current.delete(de),!1;let Ze=L("paypal");return j.current.set(de,{generation:Ze,accountPatch:he.accountPatch,sessionId:he.sessionId,nonce:he.nonce}),_e(!1),F?.log({name:`provider.${U?"redirect.started":"handoff.requested"}`,stage:U?"redirect":"overlay_open",..._n,attempt:Ze}),u?.("paypal"),!0},[u,F,w,L,de]),Je=(0,a.useCallback)(async U=>{if(l||pe||!await at()){U.reject();return}U.resolve()},[l,at,pe]),Et=(0,a.useCallback)(async U=>{if(!A||!ue)return;let he=j.current.get(de);if(he&&!N(he.generation)){j.current.delete(de);return}if(!he&&ke()||he&&!we(he.generation))return;he||we();let Ze=he??null;if(j.current.delete(de),!Ze&&w){let V=await w("paypal");if(!V.proceed){U.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Ze={accountPatch:V.accountPatch,sessionId:V.sessionId,nonce:V.nonce}}let G=Ze?.sessionId??e,je=Ze?.nonce??t,ht=await xd({event:U,prepared:Ze,email:r,billingName:S,methodLabel:"PayPal",collect:ct});if(!ht){U.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Qe=ht.email,At={...Ze?.accountPatch,...(0,on.compactBuyerIdentity)(ht,!0)};try{if(We(!0),i?.(null),!G||!(0,d.isValidEmail)(Qe))throw new Error("Missing sessionId or email for PayPal payment");await _?.(ht);let V=A.createPaymentMethod,{error:y,paymentMethod:v}=await V({type:"paypal"});if(y){Be(y,"stripe_paypal_create_payment_method_failed",he?.generation),U.paymentFailed({reason:"fail"});return}let W=await pi(n,ee,G,je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:v?.id??null,intentKind:"payment"});if(W.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let z=W.clientSecret,me={return_url:(0,d.stripeRedirectReturnUrl)()};if(v?.id&&(me.payment_method=v.id),!nr(os,{clientSecret:z,sessionId:G,nonce:je,accountPatch:At})&&h==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:De,paymentIntent:it}=await A.confirmPayment({clientSecret:z,confirmParams:me,redirect:"if_required"});if(De){if(nr(os),(0,Ce.isProviderDecline)(De)){let D=De.message??"Your payment was declined.";F?.terminal({outcome:"payment_declined",..._n,terminalReason:"provider_declined"}),i?.(D),p?.(vr("paypal",D,{code:(0,Ce.getProviderErrorCode)(De),declineCode:(0,Ce.getProviderDeclineCode)(De)})),await yi({billingApiUrl:n,sessionId:G,nonce:je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,Ce.getProviderErrorCode)(De)??"provider_declined"}})}else Be(De,"stripe_paypal_confirm_failed",he?.generation);return}nr(os);let ne=typeof it?.payment_method=="string"?it.payment_method:it?.payment_method?.id;o({id:ne??it?.id,type:"card",threeDSecureActionResultTokenId:it?.id,isPaypal:!0},{accountPatch:At,paymentMethodCategory:"paypal",presentationMode:h,sessionId:G,nonce:je});return}catch(V){Be(V,"stripe_paypal_failed",he?.generation)}finally{We(!1)}},[A,ue,e,t,r,S,ct,_,n,ee,o,i,p,w,Be,we,N,ke,F,h,de]),zt=(0,a.useCallback)(async()=>{if(!(wt.current||l||pe||!A||!ue)){wt.current=!0,We(!0);try{if(!await at(!0))return;await Et({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{wt.current=!1,We(!1)}}},[ue,Et,l,at,A,pe]),kt=h==="redirect"?(0,c.jsx)("button",{type:"button",disabled:l||pe,onClick:()=>{zt()},style:{width:"100%",minHeight:Go,border:"1px solid #d1d5db",borderRadius:I??8,background:"#ffc439",color:"#111827",cursor:l||pe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,c.jsx)(rr.ExpressCheckoutElement,{onReady:U=>Ee(Sa(U,["paypal"])),onLoadError:()=>{Ee("load_error"),cs(F,"paypal","paypal","provider_error")},onClick:Je,onConfirm:Et,onCancel:()=>{let U=j.current.get(de);j.current.delete(de),F?.terminal({outcome:"payment_cancelled",..._n,terminalReason:"cancelled",...U?{attempt:U.generation}:{}}),Ne(U?.generation),_e(!1),fe.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ce,emailRequired:ce,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},de),Tt=(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("div",{ref:Se,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ie&&(0,c.jsx)("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ae,style:as,children:"Try PayPal again"}),Y&&(0,c.jsx)(zo,{identity:Y.identity,methodLabel:Y.methodLabel,onComplete:be,onCancel:()=>be(null)},Y.id),(0,c.jsx)("div",{style:{display:Y?"none":void 0},children:kt})]}),pe&&!Y&&(0,c.jsx)(qr,{status:"processing"})]});return h==="redirect"?Tt:(0,c.jsx)(wa,{state:re,placeholderTestId:"flopay-paypal-placeholder",borderRadius:I,children:Tt})}function Vl(e){return e==="apple_pay"||e==="google_pay"}function $l({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:o,expressMethods:i,onTokenizedBody:l,onErrorChange:u,onButtonClick:p,onDecline:C,onTechnicalFailure:w,runBeforeButtonClick:S,billingName:_,onBuyerIdentityReady:K,onLoadStateChange:I,placeholderBorderRadius:$,popupCapabilityOwner:T,externalTelemetryContext:h}){let P=Jn(),{emitInstrument:ee}=(0,a.useContext)(nn),A=(0,rr.useStripe)(),ue=(0,rr.useElements)(),F=(0,a.useMemo)(()=>ri(Cr(P),h),[h,P]),[re,Ee]=(0,a.useState)("loading");(0,a.useEffect)(()=>{I?.(re)},[re,I]);let[pe,We]=(0,a.useState)(!1),wt=(0,a.useRef)(!(0,d.isValidEmail)(r?.trim())||!_?.trim()).current,{request:ce,collect:Y,finish:ct}=Uo(),be=(0,a.useRef)(null),Me=(0,a.useRef)(null),[Se,Z]=(0,a.useState)(0),[de,ye]=(0,a.useState)(!1),[Ie,_e]=(0,a.useState)(()=>ui(e,t)?"blocked":"idle"),[fe,j]=(0,a.useState)("google_pay"),L=(0,a.useRef)(null),we=(0,a.useRef)(!0),Ne=(0,a.useRef)(!1),ke=(0,a.useRef)("google_pay"),N=(0,a.useRef)("google_pay"),dt=(0,a.useRef)(null),ge=(0,a.useRef)(null),Be=(0,a.useRef)(new Set),Xe=(0,a.useRef)(null);(0,a.useEffect)(()=>(we.current=!0,()=>{we.current=!1;for(let V of Be.current)window.clearTimeout(V);Be.current.clear()}),[]);let Ae=(0,a.useRef)(new Map),{startAttempt:at,finishAttempt:Je,invalidateAttempt:Et,isAttemptInvalidated:zt,isAttemptCurrent:kt,generationRef:Tt}=fa((V,y,v)=>{w?.(V,y,{...v,popupBlocked:v?.popupBlocked??(0,Ce.isPopupBlockedError)(y),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),j(V),ye(!0),Z(W=>W+1)},{onHandoffObserved:V=>{T.markAvailable(),F?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Tt.current,...V==="apple_pay"||V==="google_pay"?{walletType:V}:{}})},defersMissingTerminal:Vl,onMissingTerminalDeferred:(V,y)=>{let v=F?.now()??globalThis.performance?.now()??Date.now(),W=Xe.current,z=W?.generation===y?W.startedAt:v;F?.performance({stage:"overlay_return",durationMs:Math.max(0,v-z),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:y,...Vl(V)?{walletType:V}:{}}),F?.flush?.().catch(()=>{})}});(0,a.useEffect)(()=>{de&&Me.current?.focus()},[de,Se]);let U=(0,a.useCallback)(()=>{Z(V=>V+1)},[]),he=(0,a.useCallback)((V,y,v,W,z=!1)=>{Et(W),w?.(V,y,{code:v,popupBlocked:(0,Ce.isPopupBlockedError)(y),telemetryReported:z,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),j(V),ye(!0),U()},[Et,w,U]),Ze=(0,a.useCallback)(()=>{window.setTimeout(()=>{(be.current?.querySelector("iframe")??be.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Ne.current&&(Ne.current=!1,Ze())},[Ze,Se]);let G=(0,a.useCallback)(()=>{ye(!1),u?.(null),Ze()},[Ze,u]),je=(0,a.useCallback)(()=>{L.current?.()},[]);(0,a.useEffect)(()=>{let V=ui(e,t);if(!V)return;let y=!1,v=!1,W=async()=>{if(!v){v=!0,y||_e("checking");try{let z=await Ll(A,V.clientSecret,Be.current);if(y)return;let me=ns(z,V.providerObjectId,(0,d.isSetupIntentClientSecret)(V.clientSecret));if(me.kind==="confirmed"){if(!Ol(e,t,V.clientSecret))return;L.current=null,_e("idle"),l({id:me.paymentMethodId,type:"card",threeDSecureActionResultTokenId:me.intentId},{...V.accountPatch?{accountPatch:V.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(me.kind==="terminal"){rs(e,t,V.clientSecret),L.current=null,_e("idle"),j(V.paymentMethodType),ye(!0),U();return}_e("blocked")}catch{y||_e("blocked")}finally{v=!1}}};return L.current=W,_e("blocked"),()=>{y=!0,L.current===W&&(L.current=null)}},[t,l,U,e,A]);let ht=(0,a.useCallback)(async V=>{let y=!1,v=yt=>{y||(y=!0,V.paymentFailed({reason:"fail",...yt?{message:yt}:{}}))};if(!A||!ue){v();return}let W=Ae.current.get(Se);if(W&&!kt(W.generation)){Ae.current.delete(Se),v();return}if(!W&&zt()){v();return}if(W&&!Je(W.generation)){v();return}W||Je();let z=V.expressPaymentType??W?.method??ke.current,me=W??null,Rt=ql(z),De;z==="apple_pay"?De="apple_pay":z==="google_pay"&&(De="google_pay");let it=W?.generation??Tt.current,ne=F,D=ne?.now()??globalThis.performance?.now()??Date.now(),Q=new AbortController,xe=!1,Oe=!1,M=null,Ft=e,Qt="processing",ar="other",Kt="provider_runtime",Vr,$r=new Promise((yt,st)=>{Vr=st}),Er=window.setTimeout(()=>{xe=!0,Q.abort(),Vr(ci)},Pd),Lt=async(yt,st,Br)=>{Qt=yt,ar=st,Kt=st==="intent_create"||st==="session_claim"?"transport_error":"provider_runtime";let Bt=ne?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Br,$r])}finally{let Wr=ne?.now()??globalThis.performance?.now()??Date.now();ne?.performance({stage:yt,durationMs:Math.max(0,Wr-Bt),durationMode:"machine",requestCategory:st,paymentMethodCategory:"wallet",provider:"stripe",...xe?{statusClass:"timeout"}:{}})}};try{if(We(!0),u?.(null),!me&&S){let Ue=await Lt("processing","other",S(Rt));if(!Ue.proceed){v();return}me={accountPatch:Ue.accountPatch,sessionId:Ue.sessionId,nonce:Ue.nonce}}let yt=me?.sessionId??e;Ft=yt;let st=me?.nonce??t,Br=dt.current??me?.accountPatch,Bt=Yl({event:V,fallbackEmail:Br?.email??r,fallbackName:[Br?.firstName,Br?.lastName].join(" ").trim()||_});if(!(0,d.isValidEmail)(Bt.email)){v("Buyer details are required."),Y(is(z),Bt).then(Ue=>{Ue&&(dt.current=Ue)});return}dt.current=null;let Wr={...me?.accountPatch,...(0,on.compactBuyerIdentity)(Bt,!0)};await Lt("processing","session_claim",Promise.resolve(K?.(Bt)));let{error:wr}=await Lt("tokenization","provider_sdk",ue.submit());if(wr){v(),he(z,wr,"stripe_wallet_submit_failed",W?.generation);return}if(!yt)throw new Error("Missing sessionId or email for payment.");let Gt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:z,paymentMethodId:null,intentKind:o},ir=JSON.stringify({sessionId:yt,nonce:st??"",request:Gt}),un=ge.current,Qr=un?.retryIdentity===ir?un.authorizationAttemptId:(0,d.randomUuidV4)();ge.current={authorizationAttemptId:Qr,retryIdentity:ir};let sr=await Lt("processing","intent_create",pi(n,ee,yt,st??"",{...Gt,authorizationAttemptId:Qr},{signal:Q.signal}));if(sr.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let qt=sr.clientSecret,Tr=Rd({createdAt:Date.now(),sessionId:yt,...st?{nonce:st}:{},clientSecret:qt,providerObjectId:sr.providerObjectId,paymentMethodType:z,accountPatch:Wr});window.clearTimeout(Er),Oe=!0,ne?.performance({stage:"callback",durationMs:Math.max(0,(ne?.now()??globalThis.performance?.now()??Date.now())-D),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let gr=ne?.now()??globalThis.performance?.now()??Date.now(),Vt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...De?{walletType:De}:{},attempt:it},kr=!1,$t=null;ne?.log({name:"payment.provider_confirmation.started",...Vt}),M=window.setTimeout(()=>{M!==null&&Be.current.delete(M),kr=!0;let Ue=ne?.now()??globalThis.performance?.now()??Date.now();ne?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Vt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Ue-gr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),ne?.flush?.().catch(()=>{}),$t?.()},vd),Be.current.add(M);let yr=(Ue,vt)=>{M!==null&&(window.clearTimeout(M),Be.current.delete(M),M=null);let f=ne?.now()??globalThis.performance?.now()??Date.now(),rt=Math.max(0,f-gr),oe=Ue;kr&&(Ue==="resolved"?oe="resolved_late":Ue==="returned_error"?oe="returned_error_late":oe="rejected_late");let Ir=vt??(Ue==="resolved"?"approved":"provider_error");return ne?.log({name:"payment.provider_confirmation.returned",...Vt,operationOutcome:oe,terminalReason:Ir}),ne?.performance({...Vt,durationMs:rt,durationMode:"buyer",operationOutcome:oe,terminalReason:Ir}),{durationMs:rt,operationOutcome:oe,terminalReason:Ir}},jt=!1,Fe=!1,pn=Ue=>{if(!Ue||typeof Ue!="object")return null;let vt=Ue;if(vt.error)return null;let f=vt.setupIntent??vt.paymentIntent,rt=ns(f??null,void 0,!!vt.setupIntent);return rt.kind==="confirmed"?rt:null},yn=Ue=>{if(jt||W&&Tt.current!==W.generation)return;let vt=pn(Ue);if(!vt)return;if(Tr&&!Ol(yt,st,qt)){jt=!0;return}let{intentId:f,paymentMethodId:rt}=vt;jt=!0,Fe=!0,ge.current=null,L.current=null,we.current&&(_e("idle"),We(!1));let oe=`${Hl}:${yt}`;nr(oe,{createdAt:Date.now(),sessionId:yt,nonce:st,accountPatch:Wr,paymentMethodId:rt,providerIntentId:f,paymentMethodType:z});try{l({id:rt,type:"card",threeDSecureActionResultTokenId:f},{accountPatch:Wr,paymentMethodCategory:"wallet",sessionId:yt,nonce:st})}finally{nr(oe)}},mn=!1;$t=async()=>{if(!(mn||jt||Fe)){mn=!0,we.current&&_e("checking");try{let Ue=await Ll(A,qt,Be.current);if(jt||Fe)return;let vt=(0,d.isSetupIntentClientSecret)(qt),f=ns(Ue,sr.providerObjectId,vt);if(f.kind==="confirmed"){yn(vt?{setupIntent:Ue}:{paymentIntent:Ue});return}if(f.kind==="terminal"){if(Fe=!0,rs(yt,st,qt),ge.current=null,L.current=null,!we.current)return;_e("idle"),v(),he(z,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",W?.generation,!0);return}we.current&&!Fe&&(_e("blocked"),We(!1))}catch{we.current&&!Fe&&(_e("blocked"),We(!1))}finally{mn=!1}}},L.current=$t;let lr,Dr;try{let Ue=await((0,d.isSetupIntentClientSecret)(qt)?A.confirmSetup({elements:ue,clientSecret:qt,redirect:"if_required"}):A.confirmPayment({elements:ue,clientSecret:qt,redirect:"if_required"}));if(!Ue||typeof Ue!="object")throw new Ea(kd(Ue));if(lr=Ue,!lr.error&&!pn(lr))throw new Ea("confirmation_result_unconfirmed");Dr=yr(lr.error?"returned_error":"resolved",lr.error&&(0,Ce.isProviderDecline)(lr.error)?"provider_declined":void 0)}catch(Ue){let vt=Ue instanceof Ea?Ue.reason:void 0,f=vt!==void 0,rt=yr(f?"returned_error":"rejected");if(ne?.error({...f?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:vt}:Ki(Ue),...Vt,operationOutcome:rt.operationOutcome,durationMs:rt.durationMs,statusClass:"unknown",terminalReason:rt.terminalReason}),!we.current||jt)return;await $t?.();return}let Mr=lr.error;if(Mr){if(!we.current||jt)return;if((0,Ce.isProviderDecline)(Mr)){Fe=!0,rs(yt,st,qt),ge.current=null,L.current=null,_e("idle");let Ue=Mr.message??"Your payment was declined.";v(Ue),u?.(Ue),C?.(vr(Rt,Ue,{code:(0,Ce.getProviderErrorCode)(Mr),declineCode:(0,Ce.getProviderDeclineCode)(Mr)})),yi({billingApiUrl:n,sessionId:yt,nonce:st,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:z,providerDeclineReason:(0,Ce.getProviderErrorCode)(Mr)??"provider_declined",...sr.intentKind==="payment"&&sr.providerObjectId.startsWith("pi_")?{providerIntentId:sr.providerObjectId}:{}}})}else ne?.error({...Ki(Mr),...Vt,operationOutcome:Dr.operationOutcome,durationMs:Dr.durationMs,statusClass:"unknown",terminalReason:Dr.terminalReason}),await $t?.();return}if(yn(lr),!jt)throw new Error("Invalid provider returned for APM intent")}catch(yt){if(yt===ci){let st=ne?.now()??globalThis.performance?.now()??Date.now();ne?.error({errorCode:Id(ar),stage:Qt,requestCategory:ar,paymentMethodCategory:"wallet",provider:"stripe",...De?{walletType:De}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ft,durationMs:Math.max(0,st-D),statusClass:"timeout",failureCategory:Kt,attempt:it,terminalReason:"provider_error"}),ne?.flush?.().catch(()=>{})}v(),he(z,yt,yt===ci?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",W?.generation,yt===ci)}finally{if(window.clearTimeout(Er),M!==null&&(window.clearTimeout(M),Be.current.delete(M)),!Oe){let yt=ne?.now()??globalThis.performance?.now()??Date.now();ne?.performance({stage:"callback",durationMs:Math.max(0,yt-D),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...xe?{statusClass:"timeout"}:{}})}we.current&&We(!1)}},[A,ue,e,t,r,_,Y,K,n,ee,o,l,u,C,S,he,Je,kt,zt,Tt,F,Se]),Qe=(0,a.useMemo)(()=>oi(i),[i]),At=(0,a.useMemo)(()=>i.map(d.stripeExpressMethodToOptionKey),[i]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(wa,{state:re,placeholderTestId:"flopay-wallet-placeholder",borderRadius:$,children:(0,c.jsxs)("div",{ref:be,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[de&&(0,c.jsxs)("button",{ref:Me,type:"button","data-testid":"flopay-wallet-retry-button",onClick:G,style:as,children:["Try ",is(fe)," again"]}),Ie!=="idle"&&(0,c.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,c.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,c.jsx)("button",{type:"button",onClick:je,disabled:Ie==="checking",style:as,children:Ie==="checking"?"Checking payment status\u2026":"Check payment status"})]}),ce&&(0,c.jsx)(zo,{identity:ce.identity,methodLabel:ce.methodLabel,onComplete:ct,onCancel:()=>ct(null)},ce.id),Ie==="idle"&&(0,c.jsx)("div",{style:{display:ce?"none":void 0},children:(0,c.jsx)(rr.ExpressCheckoutElement,{onReady:V=>{Ee(Sa(V,At))},onLoadError:V=>{Ee("load_error"),cs(F,"stripe","wallet","provider_error")},onClick:async V=>{let y=F?.now()??globalThis.performance?.now()??Date.now();ke.current=V.expressPaymentType,N.current=ql(V.expressPaymentType);let v=!0,W=window.setTimeout(()=>{v=!1,V.reject()},hd),z=S?await S(N.current):{proceed:!0};if(window.clearTimeout(W),!v)return;if(!z.proceed){Ae.current.delete(Se),V.reject();return}let me=at(V.expressPaymentType);Xe.current={generation:me,startedAt:y},Ae.current.set(Se,{generation:me,method:V.expressPaymentType,accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}),ye(!1),F?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:me,...V.expressPaymentType==="apple_pay"||V.expressPaymentType==="google_pay"?{walletType:V.expressPaymentType}:{}}),p?.(N.current),V.resolve()},onConfirm:ht,onCancel:()=>{let V=Ae.current.get(Se);Ae.current.delete(Se),F?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...V?{attempt:V.generation}:{}}),Et(V?.generation),ge.current=null,ye(!1),Ne.current=!0,U()},options:{...ai,paymentMethods:Qe,emailRequired:wt,billingAddressRequired:wt}},Se)})]})}),pe&&(0,c.jsx)(qr,{status:"processing"})]})}function Xl(e,t,r){let n=(0,d.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,paymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function ss({method:e,sessionId:t,nonce:r,email:n,billingName:o,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:u,onErrorChange:p,onDecline:C,onCancel:w,runBeforeButtonClick:S,onButtonClick:_,isProcessing:K,submitButtonColor:I,submitButtonBorderRadius:$,submitButtonStyle:T,errorText:h}){let P=Jn(),{emitInstrument:ee}=(0,a.useContext)(nn),A=(0,rr.useStripe)(),ue=(0,rr.useElements)(),[F,re]=(0,a.useState)(!1),Ee=(0,a.useRef)(!1),[pe,We]=(0,a.useState)(!1),[wt,ce]=(0,a.useState)("loading"),[Y,ct]=(0,a.useState)(""),be=!(0,d.isValidEmail)(n?.trim()),Me=!be||(0,d.isValidEmail)(Y.trim()),Se=(0,a.useCallback)(async()=>{if(!A||!ue||K||Ee.current||!pe)return;Ee.current=!0,re(!0);let Z=S?await S("card"):{proceed:!0};if(!Z.proceed){Ee.current=!1,re(!1);return}_?.("card");let de=Z.sessionId??t,ye=Z.nonce??r,Ie=(0,No.splitFullName)(o?.trim()),_e=(0,on.compactBuyerIdentity)({email:Z.accountPatch?.email?.trim()||n?.trim()||Y.trim(),firstName:Z.accountPatch?.firstName?.trim()||Ie.firstName,lastName:Z.accountPatch?.lastName?.trim()||Ie.lastName}),fe=_e.email,j=(0,on.compactBuyerIdentity)({...Z.accountPatch,..._e});try{if(p?.(null),!(0,d.isValidEmail)(fe))throw new Error("A valid email address is required for payment.");await i?.(_e);let L=await ue.submit();if(L.error){p?.(L.error.message??"Payment failed.");return}let we=[_e.firstName,_e.lastName].filter(Boolean).join(" "),Ne=await A.createPaymentMethod({elements:ue,params:{billing_details:{email:fe,...we?{name:we}:{}}}});if(Ne.error||!Ne.paymentMethod){p?.(Ne.error?.message??"Failed to create payment method.");return}let ke=Ne.paymentMethod;if(!de||!fe)throw new Error("Missing sessionId or email for payment.");let N=ke.type||e,dt=await pi(l,ee,de,ye??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:N,paymentMethodId:null,intentKind:"payment"});if(dt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ge=dt.clientSecret;nr(jn,{clientSecret:ge,sessionId:de,nonce:ye,accountPatch:j,paymentMethodId:ke.id,paymentMethodType:ke.type??e,gateway:"stripe"});let{error:Be,paymentIntent:Xe}=await A.confirmPayment({clientSecret:ge,confirmParams:{return_url:window.location.href,payment_method:ke.id},redirect:"if_required"});if(Be){nr(jn);let Je=Be.message??"Payment failed.";p?.(Je),C?.(vr("card",Je,{code:Be.code})),await yi({billingApiUrl:l,sessionId:de,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Be.code??"provider_declined"}});return}let Ae=Xe?.status;if(!ua(Ae)){nr(jn);let Je=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(Je),C?.(vr("card",Je,{code:Ae??"missing_payment_intent"}));return}nr(jn);let at=typeof Xe?.payment_method=="string"?Xe.payment_method:Xe?.payment_method?.id;u({id:at??ke.id,type:"card",threeDSecureActionResultTokenId:Xe?.id,gateway:"stripe",paymentMethodType:ke.type??e},{accountPatch:j,paymentMethodCategory:"apm",sessionId:de,nonce:ye})}catch(L){p?.(L instanceof Error?L.message:"Payment failed. Please try again.")}finally{Ee.current=!1,re(!1)}},[A,ue,K,pe,S,_,t,r,n,o,Y,i,l,ee,e,u,p,C]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[be&&(0,c.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:be&&(0,c.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,c.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Y,onChange:Z=>ct(Z.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,c.jsx)(rr.PaymentElement,{onReady:()=>ce("ready"),onLoadError:()=>{ce("load_error"),cs(Cr(P),"stripe","apm")},onChange:Z=>{We(!!Z.complete)},options:{layout:ii,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,d.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,c.jsx)(si,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Se()},disabled:!pe||!Me||F||K||wt!=="ready",color:I,borderRadius:$,style:T,children:F?"Processing\u2026":`Pay with ${(0,d.getStripeMethodDisplayName)(e)}`}),h&&(0,c.jsx)(Vo,{margin:"0.75rem 0 0",children:h})]})}function Wl({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:l,stripeInstance:u,paymentElementBaseOptions:p,futureUseSession:C,onTokenizedBody:w,onErrorChange:S,onButtonClick:_,onDecline:K,runBeforeButtonClick:I,onLoadStateChange:$,isProcessing:T=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:ee,buttonAppearance:A,themeId:ue,onExpandApm:F,expandedApmMethod:re}){let{emitInstrument:Ee}=(0,a.useContext)(nn),[pe,We]=(0,a.useState)(null),[wt,ce]=(0,a.useState)(null),Y=(0,a.useRef)(!1),{request:ct,collect:be,finish:Me}=Uo();(0,a.useEffect)(()=>{l.length>0&&u?$?.("ready"):u||$?.("loading")},[l.length,u,$]);let Se=(0,a.useCallback)(async fe=>{if(!u||Y.current||T)return;Y.current=!0,ce(fe);let j=I?await I("card"):{proceed:!0};if(!j.proceed){Y.current=!1,ce(null);return}_?.("card");let L=j.sessionId??e,we=j.nonce??t,Ne=(0,No.splitFullName)([j.accountPatch?.firstName,j.accountPatch?.lastName].filter(Boolean).join(" ")||n),ke=(0,on.compactBuyerIdentity)({email:j.accountPatch?.email?.trim()||r?.trim(),firstName:j.accountPatch?.firstName?.trim()||Ne.firstName,lastName:j.accountPatch?.lastName?.trim()||Ne.lastName});if(!(0,d.isValidEmail)(ke.email)){ce(null);let ge=await be((0,d.getStripeMethodDisplayName)(fe),ke);if(!ge){Y.current=!1;return}ke=ge,ce(fe)}let N=ke.email,dt=(0,on.compactBuyerIdentity)({...j.accountPatch,...ke});try{if(S?.(null),!L||!(0,d.isValidEmail)(N))throw new Error("Missing sessionId or email for payment.");await o?.(ke);let ge=await pi(i,Ee,L,we??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:fe,paymentMethodId:null,intentKind:"payment"});if(ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Be=ge.clientSecret;nr(jn,{clientSecret:Be,sessionId:L,nonce:we,accountPatch:dt,paymentMethodType:fe,gateway:"stripe"});let{error:Xe,paymentIntent:Ae}=await u.confirmPayment({clientSecret:Be,confirmParams:{return_url:window.location.href,payment_method_data:{type:fe,billing_details:{name:[ke.firstName,ke.lastName].filter(Boolean).join(" "),...N?{email:N}:{}}}},redirect:"if_required"});if(Xe){nr(jn);let Et=Xe.message??"Payment failed.";S?.(Et),K?.(vr("card",Et,{code:Xe.code})),await yi({billingApiUrl:i,sessionId:L,nonce:we,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:fe,providerDeclineReason:Xe.code??"provider_declined"}});return}let at=Ae?.status;if(!ua(at)){nr(jn);let Et=at==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(Et),K?.(vr("card",Et,{code:at??"missing_payment_intent"}));return}nr(jn);let Je=typeof Ae?.payment_method=="string"?Ae.payment_method:Ae?.payment_method?.id;w({id:Je??Ae?.id,type:"card",threeDSecureActionResultTokenId:Ae?.id,gateway:"stripe",paymentMethodType:fe},{accountPatch:dt,paymentMethodCategory:"apm",sessionId:L,nonce:we})}catch(ge){S?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{Y.current=!1,ce(null)}},[u,T,I,_,e,t,r,be,i,Ee,n,o,w,S,K]),[Z,de]=(0,a.useState)(null),ye=F?re??null:Z,Ie=(0,a.useCallback)(fe=>{Y.current||T||ye&&ye!==fe||((0,d.needsStripeMethodExplicitConfirm)(fe)?F?F(fe):de(fe):Se(fe))},[ye,T,Se,F]),_e=(0,a.useMemo)(()=>Z?Xl(p,Z,C):null,[Z,p,C]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:ct?(0,c.jsx)(zo,{identity:ct.identity,methodLabel:ct.methodLabel,onComplete:Me,onCancel:()=>Me(null)},ct.id):l.map(fe=>{let j=re===fe,L=wt===fe,we=wt!==null&&wt!==fe||re!=null&&re!==fe;return(0,c.jsxs)(a.default.Fragment,{children:[(0,c.jsx)(ni,{method:fe,themeId:ue,submitting:L,disabled:we,highlighted:j,hasNextStep:(0,d.needsStripeMethodExplicitConfirm)(fe),onClick:()=>Ie(fe),backgroundColor:A?.backgroundColor,borderColor:A?.borderColor,textColor:A?.textColor,borderRadius:A?.borderRadius,fontFamily:A?.fontFamily}),!F&&Z===fe&&_e&&u&&(0,c.jsx)(rr.Elements,{stripe:u,options:_e,children:(0,c.jsx)(ss,{method:fe,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:w,onErrorChange:S,onDecline:K,onCancel:()=>de(null),runBeforeButtonClick:I,onButtonClick:_,isProcessing:T,submitButtonColor:h,submitButtonBorderRadius:P,submitButtonStyle:ee})},fe)]},fe)})})}function qd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:o,userId:i,onComplete:l,onError:u,onDecline:p,onTokenizedBody:C,firstName:w,lastName:S,chv:_,className:K,submitLabel:I,isProcessing:$,error:T,onErrorChange:h,showPayPal:P=!0,showStripe:ee=!0,walletPresentation:A="auto",enabledPaymentMethods:ue,enabledPaymentMethodCountries:F,showApplePay:re=!0,showGooglePay:Ee=!0,layout:pe="default",theme:We,buttonsTheme:wt,buttonsStyles:ce,appearance:Y,cardButtonContent:ct,cardBackButtonContent:be,cardTitleContent:Me,showSecurityFooter:Se,onButtonClick:Z,onBeforeButtonClick:de,onBuyerIdentityReady:ye,enableAVS:Ie,cardFieldOrder:_e,cardPreFormSlot:fe,avsLayout:j="row",country:L,zip:we,addressLine1:Ne,addressLine2:ke,city:N,state:dt,onCountryChange:ge,onZipChange:Be,avsCheck:Xe,checkoutType:Ae,checkoutLayout:at,totalAmount:Je=0,currency:Et="usd",initialCardOpen:zt=!1,directPaypal:kt,isSubscription:Tt=!1,session:U,dataAttachmentPending:he=!1,dataAttachmentRequiresIdentity:Ze=!1,debug:G=!1}){let je=Jn(),ht=Ka(),Qe=(0,a.useContext)(Rn),{emitInstrument:At}=(0,a.useContext)(nn),V=(0,a.useRef)(null);V.current||(V.current=Ya());let y=V.current,[,v]=(0,a.useState)(0),W=(0,a.useRef)(null);W.current||(W.current=(0,Un.detectPayPalEnvironment)());let z=W.current,me=(0,a.useMemo)(()=>({browser:z,capability:y,presentationMode:"popup"}),[z,y]),Rt=U??Qe.session,De=(0,a.useMemo)(()=>({futureUse:Rt?.futureUse,futureUseUnsupported:Rt?.futureUseUnsupported}),[Rt?.futureUse,Rt?.futureUseUnsupported]),it=Rt?.gateways?.paypal?.providerObjectType??kt?.providerObjectType,ne=he||Qe.claimPending===!0,D=Ze||Qe.claimRequiresIdentity===!0,Q=ne&&!D,xe=Cl(),Oe=r||xe,[M,Ft]=(0,a.useState)(!1),[Qt,ar]=(0,a.useState)(null),[Kt,Vr]=(0,a.useState)(L??""),[$r,Er]=(0,a.useState)(we??""),[Lt,yt]=(0,a.useState)(Ne??""),[st,Br]=(0,a.useState)(ke??""),[Bt,Wr]=(0,a.useState)(N??""),[wr,Gt]=(0,a.useState)(dt??""),[ir,un]=(0,a.useState)(""),[Qr,sr]=(0,a.useState)({}),qt=(0,a.useRef)(we??""),Tr=(0,a.useRef)(L??""),gr=(0,a.useRef)(Ne??""),Vt=(0,a.useRef)(ke??""),kr=(0,a.useRef)(N??""),$t=(0,a.useRef)(dt??""),yr=(0,a.useRef)(""),jt=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(k,le,Ve,te,Re)=>{if(jt.current[k])return;let Ot=le?.trim();!Ot||Ot===Ve.current||(Ve.current=Ot,te(Ot),Re?.(Ot))};s("country",L,Tr,Vr,ge),s("zip",we,qt,Er,Be),s("addressLine1",Ne,gr,yt),s("addressLine2",ke,Vt,Br),s("city",N,kr,Wr),s("state",dt,$t,Gt)},[L,we,Ne,ke,N,dt,ge,Be]);let Fe=(0,a.useMemo)(()=>(0,d.resolveAVSConfig)(Ie),[Ie]),pn=Fe!==null,yn=(0,a.useMemo)(()=>(0,d.isAuthorizationOnlySession)(U),[U]),mn=(0,d.isMountableVaultBlock)(U?.vault),lr=!!U?.gateways?.pcivault,Dr=(0,kn.hasServerSideCardGateway)(U),Ue=!!(U?.gateways?.stripe?.enabledPaymentMethods??ue)?.includes("card")||(0,kn.canRecoverHostedCardForm)(U),vt=mn||Ue||lr,f=!!(ee&&vt&&e),[rt,oe]=(0,a.useState)(()=>pe!=="buttons"||zt?e??null:null),[Ir,Hr]=(0,a.useState)(0),er=pe!=="buttons"||zt||!!e&&rt===e,Or=U?.captureMethod,bt=(0,a.useRef)(je);(0,a.useEffect)(()=>{bt.current=je},[je]);let[Mn,ro]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(!f||!e||!er){ro(null);return}let s=bt.current?bt.current.cardCapture({sessionId:e,captureMethod:Or}):new Tn.PciVaultCardCapture({sessionId:e,captureMethod:Or,billingApiUrl:Oe,telemetry:n});return ro({sessionId:e,captureMethod:Or,billingApiUrl:Oe,telemetry:n,capture:s}),()=>{s.unmount()}},[f,e,er,Or,Oe,n]);let Dt=f&&e&&er&&Mn?.sessionId===e&&Mn.captureMethod===Or&&Mn.billingApiUrl===Oe&&Mn.telemetry===n?Mn.capture:null,Kr=(0,a.useMemo)(()=>{let s=Kt,k=Fe?(0,d.isAVSFieldVisible)(Fe.postal_code,s):!1;return Nd(s,$r,k)},[Fe,Kt,$r]),{avsInvalid:fn,invalidAvsFields:gn}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!f||!Fe)return{avsInvalid:!1,invalidAvsFields:s};let k=Kt,le=(Re,Ot)=>(0,d.isAVSFieldVisible)(Re,k)&&!Ot.trim(),Ve={line1:le(Fe.address_line_1,Lt),city:le(Fe.city,Bt),state:le(Fe.state,wr),zip:Kr.empty||Kr.malformed};return{avsInvalid:Ve.line1||Ve.city||Ve.state||Ve.zip,invalidAvsFields:Ve}},[f,Fe,Kt,Lt,Bt,wr,Kr]),[Yt,xn]=(0,a.useState)(!1),[An,Lr]=(0,a.useState)(!1),[Fn,en]=(0,a.useState)(!1),[Bn,Wn]=(0,a.useState)({line1:!1,city:!1,state:!1}),Gr=(0,a.useRef)(!1),hn=(0,a.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Pn=(0,a.useRef)(!1),Nt=(0,a.useCallback)(s=>{hn.current[s]=!0,Pn.current=!0},[]),Yr=(0,a.useCallback)(s=>!Gr.current&&hn.current[s],[]),xr=(0,a.useCallback)(s=>{Yr(s)&&Wn(k=>k[s]?k:{...k,[s]:!0})},[Yr]),[vn,Cn]=(0,a.useState)(()=>(0,d.resolveVaultMountOptions)(U?.vault,{billingApiUrl:Oe,sessionId:e,nonce:t})),[Ct,cr]=(0,a.useState)(zt&&vt?"card":"buttons"),[hr,Nr]=(0,a.useState)(null),no=Ct==="expanding"||Ct==="card",Dn=U?.gateways?.stripe&&!Dr?"stripe":void 0,Hn=(0,a.useCallback)(()=>{At?.({class:"card_surface",provider:Dn})},[Dn,At]),tn=(0,a.useRef)(null),dr=(0,a.useCallback)(s=>{tn.current&&clearTimeout(tn.current),tn.current=setTimeout(()=>{tn.current=null,s()},Ia)},[]);(0,a.useEffect)(()=>()=>{tn.current&&clearTimeout(tn.current)},[]);let oo=(0,a.useRef)(!1),[mr,q]=(0,a.useState)(0),B=(0,a.useRef)(null),ie=(0,a.useCallback)(()=>{Hn(),oe(e??null),oo.current&&(oo.current=!1,q(s=>s+1)),Hr(s=>s+1),cr("expanding"),dr(()=>cr("card"))},[dr,Hn,e]),Pe=(0,a.useCallback)(()=>{cr("collapsing"),dr(()=>cr("buttons"))},[dr]),It=(0,a.useCallback)(s=>{Nr(s),cr("apm-expanding"),dr(()=>cr("apm-form"))},[dr]),Xt=(0,a.useCallback)(()=>{cr("apm-collapsing"),dr(()=>{cr("buttons"),Nr(null)})},[dr]);(0,a.useEffect)(()=>{pe==="buttons"&&zt&&vt&&(oe(e??null),cr("card"))},[pe,zt,vt,e]);let[ze,X]=(0,a.useState)(null),J=(0,a.useRef)(!1),H=(0,a.useRef)(null),m=(0,a.useRef)("idle"),[g,R]=(0,a.useState)(!1),se=(0,a.useRef)(g);se.current=g;let[Le,Ke]=(0,a.useState)(()=>kt?.existingOrderId?{orderId:kt.existingOrderId,attempts:1}:null),Jt=(0,a.useRef)(Le);(0,a.useEffect)(()=>{Jt.current=Le},[Le]);let Te=(0,a.useRef)(null),Ye=(0,a.useMemo)(()=>{if(ye||Qe.claimBuyerIdentity||U?.buyerIdentified!==!1||!e||!t)return;let s=`${Oe}|${e}|${t}`;Te.current?.key!==s&&(Te.current={key:s,claim:Oo(new Tn.PaymentAPI(Oe,{telemetry:!1}),e,t,{...i?{userId:i}:{},...w?{firstName:w}:{},...S?{lastName:S}:{}})});let k=Te.current.claim;return async le=>{await k(le)}},[ye,Qe.claimBuyerIdentity,U?.buyerIdentified,e,t,Oe,i,w,S]),nt=ye??Qe.claimBuyerIdentity??Ye,St=T??Qt,ve=(0,a.useMemo)(()=>(0,d.resolveTheme)(We),[We]),O=(0,a.useMemo)(()=>{let s=ve?.buttonsLayout??(0,d.resolveButtonsLayoutTheme)(wt);return ce?{...s,...ce,cardButton:{...s.cardButton,...ce.cardButton},cardFormContainer:{...s.cardFormContainer,...ce.cardFormContainer},backButton:{...s.backButton,...ce.backButton},backButtonIcon:{...s.backButtonIcon,...ce.backButtonIcon},submitButton:{...s.submitButton,...ce.submitButton},title:{...s.title,...ce.title}}:s},[ve,wt,ce]),ae=Y??ve?.appearance,mt=(0,a.useMemo)(()=>(0,d.computeVaultCardThemeColors)({appearance:ae,buttonsStyles:O,layout:pe}),[ae,O,pe]),He=Qe.inlineSessionPatchProcessing??!1,et=($??M)||He,Mt=Oe.replace(/\/+$/,""),Pt=(0,a.useMemo)(()=>Hi({userId:i,email:o,firstName:w,lastName:S,country:L,zip:we},Qr),[i,o,w,S,L,we,Qr]),So=[Pt.firstName,Pt.lastName].filter(s=>!!s?.trim()).join(" "),Ss=!(0,d.isValidEmail)(Pt.email?.trim()),wi=(0,a.useRef)(null);f&&wi.current===null&&(wi.current=Ss);let ao=f&&(wi.current??Ss),ki=(0,a.useMemo)(()=>Ud(ir,ao),[ir,ao]),wo=ki.empty||ki.malformed,Xr=(0,a.useMemo)(()=>je?je.getRawProvider():null,[je]),ws=(0,a.useMemo)(()=>ht?ht.getRawProvider():null,[ht]),Zo=Je||100,ko=Et.toLowerCase(),Ri=(0,a.useMemo)(()=>ae?(0,Tn.toStripeAppearance)(ae):null,[ae]),Ro=Ri,ks=(0,a.useMemo)(()=>{let s=Ri??{},k=s.rules??{};return{...s,rules:{...k,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...k[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...k[".AccordionItemContents"]??{}}}}},[Ri]),Rs=(0,a.useMemo)(()=>({...hl(Je,Rt?.captureMethod,De),currency:ko,...Ro?{appearance:Ro}:null}),[Je,ko,Rt?.captureMethod,De,Ro]),Ei=(0,d.resolveSetupFutureUsage)(De,"paypal","paypal"),Es=(0,a.useMemo)(()=>({mode:"payment",amount:Zo,currency:ko,captureMethod:"manual",...Ei?{setupFutureUsage:Ei}:null,...Ro?{appearance:Ro}:null}),[Zo,ko,Ei,Ro]),qe=(0,a.useCallback)(s=>{ar(s),h?.(s)},[h]),Is=(0,a.useRef)(0);(0,a.useEffect)(()=>{mr!==Is.current&&(Is.current=mr,qe(null))},[mr,qe]);let Ii=(0,a.useRef)(""),[_s,vc]=(0,a.useState)(!1),_i=(0,a.useCallback)(()=>{vc(!0)},[]);(0,a.useEffect)(()=>{if(!f||!ao||!nt||!_s||wo||Ii.current)return;let s=(0,on.compactBuyerIdentity)({email:(0,d.isValidEmail)(Pt.email?.trim())?Pt.email?.trim():yr.current.trim(),firstName:Pt.firstName?.trim(),lastName:Pt.lastName?.trim()});Ii.current=JSON.stringify(s),sr(k=>({...k,...s})),Promise.resolve(nt(s)).catch(k=>{Ii.current="",qe(k instanceof Error?k.message:"Failed to attach buyer details.")})},[f,ao,nt,_s,wo,Pt.email,Pt.firstName,Pt.lastName,qe]),(0,a.useEffect)(()=>{!f||!Dt||Dt.setCardFieldOrder?.(_e??null,Fe==null&&!ao)},[f,Dt,_e,Fe,ao]),(0,a.useEffect)(()=>{(Ct==="expanding"||Ct==="collapsing"||Ct==="apm-expanding"||Ct==="apm-collapsing")&&qe(null)},[Ct,qe]);let On=(0,a.useCallback)((s,k,le)=>{p?.(vr(s,k,le))},[p]),Eo=(0,a.useCallback)((s,k,le)=>{let Ve=le?.popupBlocked??(0,Ce.isPopupBlockedError)(k);Ve&&y.markBlocked()&&v(ft=>ft+1);let te=(0,Ce.buildExternalMethodRecoveryMessage)(is(s),Ve,z.inAppBrowser),Re=(0,Ce.getProviderErrorCode)(k),Ot=(Re?.toLowerCase()==="error"?void 0:Re)??(0,Ce.sanitizeExternalFailureCode)(le?.code)??"external_payment_method_failed",wn=new d.FloPayError(te,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:Ot,popupBlocked:Ve,inAppBrowser:z.inAppBrowser,appFamily:z.appFamily,popupCapability:y.current(),presentationMode:le?.presentationMode??"popup"}});le?.telemetryReported||Cr(je)?.error(Ko({...me,presentationMode:le?.presentationMode??"popup"},{errorCode:Ve?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:le?.provider??(s==="paypal"?"paypal":"stripe"),paymentMethodCategory:le?.paymentMethodCategory??(s==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:le?.terminalReason??(Ve?"popup_blocked":"provider_error")})),X(null),pe==="buttons"&&(cr("buttons"),Nr(null)),qe(te),u?.(wn),console.error("[FloPay] External payment method failed:",{method:s,code:Ot,popupBlocked:Ve})},[z,me,je,pe,u,y,qe]);(0,a.useEffect)(()=>{if(!f||!e){Cn(null);return}let s={billingApiUrl:Mt,sessionId:e,nonce:t},k=(0,d.resolveVaultMountOptions)(U?.vault,s);if(k){Cn(k);return}if(!er){Cn(null);return}let le=`${Mt}\0${e}\0${t??""}`,Ve=B.current;if(Ve&&Ve.key===le){Cn(Ve.mount);return}Cn(null);let te=!0;return new Tn.PaymentAPI(Mt).getVaultCapture(e,t).then(Re=>{if(!te)return;let Ot=(0,d.resolveVaultMountOptions)(Re,s);Ot?.verificationRequired&&!Re.html&&(B.current={key:le,mount:Ot}),Ot?Cn(Ot):qe("Failed to load the secure card form.")}).catch(Re=>{te&&qe(Re instanceof Error?Re.message:"Failed to load the secure card form.")}),()=>{te=!1}},[f,er,Ir,e,U?.vault,Mt,t,qe]);let bn=(0,a.useRef)({onComplete:l,onError:u,updateError:qe,emitDecline:On,resolvedAccount:Pt,avsConfig:Fe,avsCheckProp:Xe,sessionId:e,nonce:t,baseUrl:Mt,captureMethod:U?.captureMethod,paymentId:U?.paymentId,authorizationExpiresAt:U?.authorizationExpiresAt,serverSideCardGateway:Dr});bn.current={onComplete:l,onError:u,updateError:qe,emitDecline:On,resolvedAccount:Pt,avsConfig:Fe,avsCheckProp:Xe,sessionId:e,nonce:t,baseUrl:Mt,captureMethod:U?.captureMethod,paymentId:U?.paymentId,authorizationExpiresAt:U?.authorizationExpiresAt,serverSideCardGateway:Dr};let Ti=(0,a.useRef)(!1),Ts=(0,a.useCallback)(()=>{let s=bn.current,k=s.resolvedAccount.email?.trim(),le=(0,d.isValidEmail)(k)?k:yr.current.trim();if(!(0,d.isValidEmail)(le))return null;let Ve=s.resolvedAccount.firstName?.trim(),te=s.resolvedAccount.lastName?.trim(),Re=Tr.current.trim()||s.resolvedAccount.country?.trim()||"",Ot=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.state,Re):!1,wn=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.address_line_1,Re):!1,ft=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.postal_code,Re):!1,_t=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.city,Re):!1,xt=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.address_line_2,Re):!1,Wt=wn&&!Ot&&ft?(0,d.getStateFromPostalCode)(Re,(qt.current??"").trim()):null,mo=Ot?$t.current:Wt;return{accountData:{userId:s.resolvedAccount.userId??"",email:le,...Ve?{firstName:Ve}:{},...te?{lastName:te}:{},...ft&&qt.current?{zip:qt.current}:{},..._t&&kr.current?{city:kr.current}:{},...mo?{state:mo}:{},...wn&&gr.current?{addressLine1:gr.current}:{},...xt&&Vt.current?{addressLine2:Vt.current}:{},...Re?{country:Re}:{}},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,d.isAVSFieldVisible)(s.avsConfig.country,Re),postal_code:ft,address_line_1:wn,address_line_2:xt,city:_t,state:Ot}}:{}}},[]),Ms=(0,a.useRef)(ne);Ms.current=ne,(0,a.useEffect)(()=>{ne||St!==Nl||bn.current.updateError(null)},[ne,St]),(0,a.useEffect)(()=>{!f||!Dt||Dt.setSubmitGate?.(fn||ne||wo||g)},[f,Dt,fn,ne,wo,g]),(0,a.useEffect)(()=>{if(!f||!Dt)return;Ti.current=!1;let s=null,k=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,m.current="idle",X(null)},400)},le=Dt.on("submitting",()=>{xn(!0),H.current&&clearTimeout(H.current),m.current="validation-window",H.current=setTimeout(()=>{H.current=null,m.current==="validation-window"&&(m.current="processing")},_d),X("processing");let ft=bn.current;if(!ft.sessionId||!ft.nonce)return;let _t=Ts();if(!_t){ft.updateError("Enter a valid email address."),m.current="idle",X(null);return}new Tn.PaymentAPI(ft.baseUrl).patchAccountSnapshot(ft.sessionId,ft.nonce,_t,{telemetryMode:"best_effort"}).catch(xt=>{if(!Md(xt))return;let Wt=xt instanceof Error?xt.message:"Please check your billing address and try again.";ft.updateError(Wt),m.current="idle",X(null),ft.onError?.(xt instanceof d.FloPayError?xt:new d.FloPayError(Wt,"api_error"))})}),Ve=Dt.on("complete",ft=>{(0,In.markSessionRecentlyCompleted)(ft.sessionId??bn.current.sessionId),m.current="terminal",R(!1),X("success"),setTimeout(()=>{if(Ti.current)return;Ti.current=!0;let _t=bn.current,xt=(0,d.isAuthorizationOnlySession)(_t)||ft.outcome==="authorized",Wt=_t.serverSideCardGateway?{}:{paymentIntentId:ft.intentId};bn.current.onComplete?.(xt?{status:"authorized",...Wt,paymentId:ft.paymentId??_t.paymentId,sessionId:ft.sessionId??_t.sessionId,authorizationExpiresAt:ft.authorizationExpiresAt??_t.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Wt,checkoutMethod:"card"})},600)}),te=Dt.on("decline",ft=>{let _t=bn.current,xt=ft.message??"Your payment was declined. Please try another card or contact your bank.";m.current="terminal",R(!1),_t.updateError(xt),X("error");let Wt=ft.failureOutcome??(0,d.normalizeCheckoutFailureOutcome)(ft.declineReason)??"authorization_declined";_t.emitDecline("card",xt,{code:Wt,declineCode:Wt}),k()}),Re=Dt.on("error",ft=>{let _t=bn.current,xt=ft.message??"There was a problem processing your payment. Please try again.";m.current="terminal",R(!1),_t.updateError(xt),X("error"),_t.onError?.(new d.FloPayError(xt,"api_error",{code:ft.failureOutcome??"capture_failed"})),k()}),Ot=Dt.on("challenge_dismissed",()=>{H.current&&(clearTimeout(H.current),H.current=null),m.current="processing",R(!0),X(null)}),wn=Dt.on("blocked",()=>{if(se.current){bn.current.updateError(Td);return}if(!Ms.current){xn(!0);return}_i(),bn.current.updateError(Nl)});return()=>{s&&(clearTimeout(s),s=null),H.current&&(clearTimeout(H.current),H.current=null),m.current="idle",R(!1),X(null),le(),Ve(),te(),Re(),Ot(),wn()}},[f,Dt,_i,Ts]);let Ln=!!kt?.clientId,Qo=Array.isArray(ue),Aa=Qo&&ue.length>0,xs=Qo&&ue.includes("paypal"),Fa=(0,a.useRef)(null);Fa.current===null&&(Fa.current=(0,d.hasMatchingStripePayPalReturn)());let Io=Fa.current?"redirect":(0,zn.resolveStripePayPalPresentation)(z,A,y.current()),{expressMethods:Ba,paymentElementMethods:Mi}=(0,a.useMemo)(()=>(0,d.partitionStripeMethods)(ue,{excludePaypal:Ln}),[ue,Ln]),As=Ln||!!ht||xs&&Io==="redirect",Cc=(0,a.useMemo)(()=>As?Ba.filter(s=>s!=="paypal"):Ba,[Ba,As]),bc=(0,a.useMemo)(()=>{let s=[];return re&&s.push("apple_pay"),Ee&&s.push("google_pay"),s},[re,Ee]),_o=Qo?Cc:bc,Sc=ee&&_o.length>0,Fs=pn?Kt:L,Da=(0,a.useMemo)(()=>(0,d.filterStripeMethodsByCountryGate)(Mi,Fs,F),[Mi,Fs,F]),xi=(0,a.useMemo)(()=>({mode:"payment",amount:Zo,currency:ko,paymentMethodCreation:"manual",appearance:ks}),[Zo,ko,ks]),[Bs,Ds]=(0,a.useState)("loading"),[Os,Ls]=(0,a.useState)("loading"),[Ns,Us]=(0,a.useState)("loading"),[wc,Ai]=(0,a.useState)(!1),[zs,Fi]=(0,a.useState)("loading"),[Bi,kc]=(0,a.useState)();(0,a.useEffect)(()=>{kc((0,Un.detectPayPalEnvironment)())},[]);let Oa=Bi?.inAppBrowser,La=Bi?(0,zn.resolvePayPalPresentationMode)(Bi,kt?.approvalPresentation,it??(Tt?"subscription":"order")):"popup",qs=P&&(Ln||(Qo?xs:Oa===!1)),js=ee&&Sc,ea=(!Q||!!Qe.waitForDataAttachment)&&qs&&Ln,Vs=zs==="retrying"||zs==="exhausted",ta=null;ee&&(ht?ta=ws:Io==="redirect"&&(ta=Xr));let $s=(0,a.useMemo)(()=>({...me,presentationMode:Io}),[me,Io]),ra=!Q&&qs&&!!ta&&(!Ln||Vs),To=!Q&&js&&!!Xr,na=!Q&&ee&&Aa&&Da.length>0&&!!Xr,Rc=ea&&!Vs?wc:ra&&es(Bs),Ec=To&&es(Os),Ic=na&&Ns!=="load_error",Ws=s=>s==="loading"||s==="ready",Hs=ea||ra&&Ws(Bs)||To&&Ws(Os)||na&&Ns!=="load_error",Na=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!Na.current){if(!ee&&!P){Na.current=!0;let s=new d.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(s),qe(s.message)}else if(!ee&&P&&!Ln){Na.current=!0;let s=new d.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(s),qe(s.message)}else if(Oa!==void 0&&!Q&&!vt&&!Hs){Na.current=!0;let s=new d.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(s),qe(s.message)}}},[ee,P,Ln,Oa,Q,vt,Hs,u,qe]);let Ks=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(Ks.current||!Aa)return;let s=[];re!==!0&&s.push("showApplePay"),Ee!==!0&&s.push("showGooglePay"),s.length!==0&&(Ks.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.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.`))},[Aa,re,Ee]);let Gs=(0,a.useCallback)((s,k)=>Qe.applyInlineSessionPatch?Qe.applyInlineSessionPatch(s).then(le=>({error:null,sessionId:le.sessionId||e,nonce:le.session?.clientSecret||t})).catch(le=>{let Ve=(0,d.normalizeBeforeButtonClickError)(k,le);return qe(Ve.message),u?.(Ve),{error:Ve,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Qe.applyInlineSessionPatch,t,u,e,qe]),Sn=(0,a.useCallback)(async s=>{if(s!=="card"&&Q&&await Qe.waitForDataAttachment?.(),!de)return{proceed:!0};try{let k=await de({method:s,sessionId:e||void 0,createSession:Qe.inlineSessionDraft});if(k===!1)return{proceed:!1};if(k&&typeof k=="object"){k.account&&sr(Ve=>({...Ve??{},...k.account}));let le=await Gs(k,s);return le.error?{proceed:!1,accountPatch:k.account}:{proceed:!0,accountPatch:k.account,sessionId:le.sessionId,nonce:le.nonce}}return{proceed:!0}}catch(k){let le=(0,d.normalizeBeforeButtonClickError)(s,k);return qe(le.message),u?.(le),{proceed:!1}}},[Gs,Qe.inlineSessionDraft,Qe.waitForDataAttachment,Q,de,u,e,qe]),Ys=(0,a.useCallback)(async(s,k)=>{if(J.current)return;J.current=!0,Ft(!0),X("processing"),qe(null);let le=k?.sessionId??e,Ve=k?.nonce??t,te=Hi(Pt,k?.accountPatch),Re=k?.completionPaymentMethodId??pa(s),Ot=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,wn=Bd(s),ft=k?.presentationMode?ri(Cr(je),{...me,presentationMode:k.presentationMode}):void 0,_t=()=>{At?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:wn}),ft?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",..._n,requestCategory:"process_payment"})};try{let xt=new Tn.PaymentAPI(Mt),Wt=await xt.processPayment(te.userId??"",{sessionId:le,nonce:Ve,paymentMethodCategory:k?.paymentMethodCategory??Od(s),tokenizedData:Ot,accountData:{...k?.accountPatch,userId:te.userId??"",email:te.email??"",firstName:te.firstName||void 0,lastName:te.lastName||void 0,...(0,d.buildProcessPaymentAvsAccount)({avsConfig:Fe,country:Tr.current,zip:qt.current,city:kr.current,state:$t.current,addressLine1:gr.current,addressLine2:Vt.current})},...(0,d.buildCheckoutProcessMetadata)({chv:_,avsCheck:Xe,checkoutType:Ae,checkoutLayout:at,avsConfig:Fe,country:Tr.current})}),mo=async Pr=>{let fo=(0,d.isAuthorizationOnlySession)(U)||Pr?.status==="authorized";(0,In.markSessionRecentlyCompleted)(le),ft?.terminal({outcome:"payment_succeeded",..._n}),X("success"),Ke(null),await new Promise(ca=>setTimeout(ca,600));let Nn;typeof Pr?.paymentId=="string"?Nn=Pr.paymentId:U?.paymentId&&(Nn=U.paymentId);let go;typeof Pr?.authorizationExpiresAt=="string"?go=Pr.authorizationExpiresAt:U?.authorizationExpiresAt&&(go=U.authorizationExpiresAt),l?.(fo?{status:"authorized",...Nn===void 0?{}:{paymentId:Nn},sessionId:typeof Pr?.sessionId=="string"?Pr.sessionId:le,...go===void 0?{}:{authorizationExpiresAt:go},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:s.isPaypal?"paypal":"card"})};if(Wt.ok){await mo(Wt.status===204?null:await Wt.json().catch(()=>null));return}let Jr=await Wt.json().catch(()=>null);if(Jr?.type==="paypal_redirect_required"){let Pr=Jr.threeDSecureToken,fo=Jr.paymentMethodId||s.id||"";if(!je||!Pr){X("error"),qe("PayPal authorization required but no token provided.");return}try{let Nn=ht?.getRawProvider();if(!Nn){qe("PayPal is not available.");return}let go={return_url:window.location.href};fo&&(go.payment_method=fo);let{error:ca}=await Nn.confirmPayment({clientSecret:Pr,confirmParams:go,redirect:"if_required"});if(ca){X("error");let sl=ca.message??"PayPal payment failed.";qe(sl),On("paypal",sl,{code:ca.code})}}catch(Nn){X("error"),qe(Nn instanceof Error?Nn.message:"PayPal authorization failed.")}return}if(Jr?.type==="paypal_direct_required"){let Pr=Jr.orderId;if(!Pr){X("error"),qe("PayPal retry required but no order id provided.");return}let fo=Jt.current?.attempts??0;if(fo>=2){X("error"),qe("PayPal payment could not be completed after multiple attempts."),On("paypal","paypal_direct_required retry limit exceeded");return}Ai(!1),Fi("loading"),Ke({orderId:Pr,attempts:fo+1}),X(null);return}if(Wt.headers.get(bd)===Sd){let Pr=await wd(xt,le,Ve);if(Pr!==void 0){await mo(Pr);return}}(0,d.classifyPaymentRejection)(Wt.status,Jr)?ft?.terminal({outcome:"payment_declined",..._n,terminalReason:"provider_declined"}):_t(),X("error");let il=Jr?.message??"Payment failed. Please try again.";qe(il),On(s.isPaypal?"paypal":"card",il,{code:Jr?.code??Jr?.gatewayErrorCode,declineCode:Jr?.declineCode??Jr?.gatewayDeclineReason}),await new Promise(Pr=>setTimeout(Pr,400))}catch(xt){Gl(xt)||_t(),X("error"),qe(xt instanceof Error?xt.message:"An unexpected error occurred"),await new Promise(Wt=>setTimeout(Wt,400))}finally{Ft(!1),X(null),J.current=!1}},[Mt,e,t,Pt,Fe,Xe,Ae,at,_,je,ht,U,l,qe,On,At,me]),Ur=(0,a.useCallback)((s,k)=>{C?C(s):Ys(s,k)},[C,Ys]),oa=`${Hl}:${e}`;(0,a.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(oa);if(!s)return;let k;try{k=JSON.parse(s)}catch{nr(oa);return}if(!k||typeof k.createdAt!="number"||Date.now()-k.createdAt<0||Date.now()-k.createdAt>Kl||typeof k.paymentMethodId!="string"||typeof k.providerIntentId!="string"||typeof k.paymentMethodType!="string"||k.sessionId!==e||!t||k.nonce!==t||!_o.includes(k.paymentMethodType)){nr(oa);return}nr(oa),Ur({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.providerIntentId,gateway:"stripe",paymentMethodType:k.paymentMethodType},{...k.accountPatch?{accountPatch:k.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Ur,t,e,oa,_o]);let Xs=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||Xs.current)return;let[s,k,le]=(0,d.readStripeRedirectParams)();if(!s||!k||Fa.current||!je)return;let Ve=je.getRawProvider();if(!Ve)return;let te=_t=>{let xt=localStorage.getItem(_t);if(!xt)return null;try{return JSON.parse(xt)}catch{return nr(_t),null}},Re=te(jn)??te(Dl),Ot;if(Re?.clientSecret){if(Re.clientSecret!==k)return;Ot={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;Xs.current=!0,nr(jn),nr(Dl),window.history.replaceState({},"",(0,d.stripeRedirectReturnUrl)());let wn=Re?.paymentMethodType??Re?.tokenType??"card",ft="card";(async()=>{if(le==="failed"){let Kn="Payment was declined. Please try again.";qe(Kn),On(ft,Kn);return}let{paymentIntent:_t,error:xt}=await Ve.retrievePaymentIntent(k);if(xt){let Kn=xt.message??"Failed to retrieve payment status.";qe(Kn),On(ft,Kn,{code:xt.code});return}let Wt=_t?.status,mo=ua(Wt);if(!_t||!mo){let Kn=Wt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";qe(Kn),On(ft,Kn,{code:Wt??"missing_payment_intent"});return}let Jr=typeof _t.payment_method=="string"?_t.payment_method:_t.payment_method?.id;Ur({id:Jr??Re?.paymentMethodId??Re?.tokenId??_t.id,type:"card",threeDSecureActionResultTokenId:_t.id,gateway:Re?.gateway??"stripe",paymentMethodType:wn},Ot)})()},[e,Ur,je,qe,On]);let Di=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!(f||je!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let aa=pe==="buttons",zr=ae?.variables,_c=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Oi=zr?.colorBackground,Tc=Oi&&!_c.has(Oi)?Oi:void 0,ia=O.cardInputBorder??(aa?"#e5e7eb":"#A4A4FF"),Js=zr?.colorDanger??"#dc2626",Zt=s=>gn[s]&&(Bn[s]||Yt),Ua=wo&&(Fn||Yt),rn=s=>s?Js:ia,za=(Kr.malformed||Kr.empty)&&(An||Yt),Mc=rn(za),Li=O.cardFormContainer?.backgroundColor??Tc??(aa?"white":"#EDEDFF"),Mo=O.cardInputBackground??zr?.colorBackground??"white",Ni=Fo(be),Zs=Fo(Me),xo=O.nameInput,Qs=O.cardInputFontSize??zd(xo?.fontSize)??zr?.fontSizeBase??"16px",el=typeof xo?.fontFamily=="string"?xo.fontFamily:zr?.fontFamily??"Poppins, sans-serif",tl=(0,d.toCssWeight)(xo?.fontWeight)??400,xc=O.cardInputColor??(typeof xo?.color=="string"?xo.color:void 0)??zr?.colorText??"#262833",Ac=O.cardInputPlaceholderColor??"#9ca3af",tr=zr?.borderRadius??"8px",po=zr?.borderRadius??O.cardButton?.borderRadius??tr,yo=zr?.colorPrimary??"#4A49FF",Fc=zr?.colorPrimaryHover??(0,d.darkenHex)(yo,.12),Ui=zr?.colorText??"#262833",zi={fontSize:Qs,fontFamily:el,fontWeight:tl,color:xc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},sa={marginTop:"0.375rem",...zi,fontSize:"0.75rem",lineHeight:1.4,color:Js},Bc={"--flopay-input-placeholder-color":Ac,"--flopay-input-font-size":Qs,"--flopay-input-font-family":el,"--flopay-input-font-weight":String(tl)},la=O.cardFormContainer??{},qi=la.padding??(aa?"0":"1rem"),ji=la.borderRadius??tr,Dc=Dt&&vn?(0,c.jsx)(lo,{capture:Dt,html:vn.html,messageToken:vn.messageToken,expectedOrigin:vn.expectedOrigin,verificationRequired:vn.verificationRequired,theme:mt,submitLabel:I,onReady:()=>{if(!ao&&!Fe||typeof document>"u")return;let s=()=>{let le=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(le){Gr.current=!0;try{le.focus()}finally{Gr.current=!1}}};Pn.current||s()},onError:s=>{s&&vn.verificationRequired&&m.current==="idle"&&(oo.current=!0),qe(s)},onValidation:s=>{let k=m.current;(k==="idle"||k==="validation-window")&&(qe(s),s&&m.current==="validation-window"&&(H.current&&(clearTimeout(H.current),H.current=null),m.current="idle",X(null)))}},mr):(0,c.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),rl=(0,c.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&Hn()},style:{backgroundColor:Li,borderRadius:ji,...la,padding:qi,...Bc,display:"flex",flexDirection:"column"},children:[(0,c.jsx)("style",{children:`
30
+ `,Go=44;function Yo(){return(0,wr.jsx)("style",{children:pd})}function Sa(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function wa({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,wr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,wr.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:r,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,wr.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:n})]})}function es(e){return e!=="unavailable"&&e!=="load_error"}function ni({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:l,backgroundColor:u,borderColor:p,textColor:v,borderRadius:R,fontFamily:w}){let x=(0,Qn.resolveStripeMethodBrandVariant)(e,t),K=Al[e],[T,V]=(0,Fl.useState)(!1),A=!!K&&!T,f=x?.backgroundColor??u??"#ffffff",P=x?.borderColor??p??"#d1d5db",ee=x?.textColor??v??"#262833";return(0,wr.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!r&&!n&&l()},disabled:r||n,"aria-busy":r||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Go,padding:"0 1rem",backgroundColor:f,color:ee,border:`1px solid ${P}`,borderRadius:R??8,fontSize:"0.95rem",fontWeight:600,fontFamily:w,cursor:r||n?"not-allowed":"pointer",opacity:n&&!r?.55:1,animation:r?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,wr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,Qn.getStripeMethodDisplayName)(e)}\u2026`}):(0,wr.jsxs)(wr.Fragment,{children:[(0,wr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,Qn.hasVendoredStripeMethodLogo)(e)?8:0},children:[A?(0,wr.jsx)("img",{src:K,alt:"","aria-hidden":"true",onError:()=>V(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!A&&x?.logoSvg?(0,wr.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:x.logoSvg}}):null,(0,wr.jsx)("span",{children:(0,Qn.getStripeMethodDisplayName)(e)})]}),i&&(0,wr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ee,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,wr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function oi(e){let t=new Set(e.map(Qn.stripeExpressMethodToOptionKey)),r=n=>n==="applePay"||n==="googlePay"?"always":"auto";return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(n=>[n,t.has(n)?r(n):"never"]))}var ai={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},ii={type:"accordion",defaultCollapsed:!1,radios:"never"};function si({testId:e,attributes:t,disabled:r,onClick:n,color:a,borderRadius:i,style:l,children:u}){return(0,wr.jsx)("button",{type:"button","data-testid":e,...t,onClick:n,disabled:r,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:a,color:"white",border:"none",borderRadius:i,fontSize:"1rem",fontWeight:600,cursor:r?"not-allowed":"pointer",opacity:r?.5:1,transition:"opacity 120ms ease-out",...l??{}},children:u})}var Jr=require("react");var ka=require("@flopay/shared"),md=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function yd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return md.has(t.charAt(0).toLowerCase()+t.slice(1))}function fd(e,t){return typeof t=="number"&&t!==0&&!yd(e)?`${t}px`:String(t).trim()}function Bl(e,t){if(e.style.cssText="",!!t){for(let[r,n]of Object.entries(t))if(!(n==null||n==="")){if(r.startsWith("--")){e.style.setProperty(r,String(n));continue}e.style[r]=fd(r,n)}}}var bo=require("react/jsx-runtime"),ts=new WeakSet;function lo({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:a,theme:i,submitLabel:l,containerStyle:u,onReady:p,onError:v,onValidation:R}){let w=(0,Jr.useRef)(null),x=(0,Jr.useRef)(p),K=(0,Jr.useRef)(v),T=(0,Jr.useRef)(R);x.current=p,K.current=v,T.current=R;let V=(0,Jr.useRef)(i);V.current=i;let A=(0,Jr.useRef)(null),f=l??void 0,P=(0,Jr.useRef)(f);P.current=f;let ee=(0,Jr.useRef)(void 0);return(0,Jr.useEffect)(()=>{let D=w.current;if(!D)return;let ue=!0,F=!1,ne=()=>{!ue||F||(F=!0,x.current?.())},_e=e.on("ready",()=>{ne()}),ie=e.on("error",G=>{K.current?.(G.message??"There was a problem loading the secure card form.")}),We=e.on("validation",G=>{T.current?.(G.message??null)}),kt=P.current??(ts.has(e)?null:void 0),de={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...a?{verificationRequired:!0}:{},...V.current?{theme:V.current}:{},...kt===void 0?{}:{submitLabel:kt}};return A.current=V.current??null,ee.current=P.current,P.current!==void 0&&ts.add(e),e.mount(D,de).then(()=>{ne()}).catch(G=>{ue&&K.current?.(G instanceof Error?G.message:"Failed to load the secure card form.")}),()=>{ue=!1,_e(),ie(),We(),e.unmount()}},[e,t,r,n,a]),Po(()=>{let D=w.current;D&&Bl(D,u)},[u]),(0,Jr.useEffect)(()=>{i!==void 0&&(i===null&&A.current===null||(A.current=i,e.applyTheme?.(i)))},[e,i]),(0,Jr.useEffect)(()=>{f!==ee.current&&(ee.current=f,f!==void 0&&ts.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,bo.jsx)("div",{ref:w,"data-testid":"flopay-vault-card-fields"})}function li({label:e}){return(0,bo.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,bo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,bo.jsx)("span",{children:e}),(0,bo.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var us=require("@flopay/shared"),d=require("react/jsx-runtime"),jn="flopay_stripe_resume",Dl="flopay_wallet_resume",Hl="fw1",gd="fw2",Kl=300*1e3,hd=900,Pd=25e3,vd=25e3,bd=1e4,En={provider:"paypal",paymentMethodCategory:"paypal"},Cd="x-flopay-process-result-source",Sd="status";async function wd(e,t,r){try{let n=(await e.getUnifiedCheckoutSession(t,r)).data.session;if(n?.status==="complete")return null;if(n?.status==="authorized")return{status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}}catch{}}var ci={},Ea=class{constructor(t){this.reason=t}};function kd(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function ar(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 ls(e){return`${gd}:${e}`}function di(e){return ar(ls(e))}function ui(e,t){if(typeof window>"u")return null;let r=ls(e);try{let n=localStorage.getItem(r);if(!n)return null;let a=JSON.parse(n);return typeof a.createdAt!="number"||Date.now()-a.createdAt<0||Date.now()-a.createdAt>Kl||a.sessionId!==e||a.nonce!==t||typeof a.clientSecret!="string"||typeof a.providerObjectId!="string"||typeof a.paymentMethodType!="string"?(di(e),null):a}catch{return di(e),null}}function Rd(e){return ar(ls(e.sessionId),e)}function Ol(e,t,r){let n=ui(e,t);return!n||n.clientSecret!==r?!1:di(e)}function rs(e,t,r){if(typeof window>"u")return;ui(e,t)?.clientSecret===r&&di(e)}function Ed(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function ns(e,t,r){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 n=r?e.status==="succeeded":ua(e.status),a=Ed(e);return!n||!a?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:a}}async function Ll(e,t,r){let n=null;try{return await Promise.race([gl(e,t),new Promise(a=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),a(null)},bd),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Id(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Gl(e){return e instanceof c.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function pi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new In.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(a){throw Gl(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),a}}var os=c.STRIPE_PAYPAL_RESUME_KEY,Ra=new Map,_d=250,Nl="Just a moment \u2014 we are finalizing your order. Please press pay again.",Td="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function cs(e,t,r,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:r,requestCategory:"provider_sdk",...n?{terminalReason:n}:{}})}async function mi({billingApiUrl:e,sessionId:t,nonce:r,request:n}){if(!(!t||!r))try{await new In.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Md(e){return e instanceof c.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Yl({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,a=t?.trim(),i=(0,No.splitFullName)(r),l=i.firstName?i:(0,No.splitFullName)(n?.name);return(0,sn.compactBuyerIdentity)({email:(0,c.isValidEmail)(a)?a:n?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function xd({event:e,prepared:t,email:r,billingName:n,methodLabel:a,collect:i}){let l=Yl({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,c.isValidEmail)(l.email)?l:i(a,l)}var Ia=180,Ul=`flopay-card-enter ${Ia}ms cubic-bezier(0, 0, 0.2, 1) both`,zl=`flopay-card-exit ${Ia}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Ad=`flopay-buttons-enter ${Ia}ms cubic-bezier(0, 0, 0.2, 1) both`,Fd=`flopay-buttons-exit ${Ia}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Bd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ds(e){return(0,c.derivePrimaryTileStyle)(e)}var Dd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Od(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 as={width:"100%",minHeight:Go,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 ql(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function is(e){return e==="paypal"?"PayPal":(0,c.getStripeMethodDisplayName)(e)}function Ld(e){let t=(0,c.getPostalCodeExample)(e);return`Enter a valid ${(0,c.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Nd(e,t,r){let n=(0,c.isPostalCodeSupported)(e),a=t.trim(),i=r&&n,l=i&&!a,u=i&&!!a&&!(0,c.isValidPostalCode)(e,a);return{visible:r,supported:n,required:i,empty:l,malformed:u}}function Ud(e,t){let r=e.trim(),n=t&&!r,a=t&&!!r&&!(0,c.isValidEmail)(r);return{required:t,empty:n,malformed:a,value:r}}function zd(e){return typeof e=="number"?`${e}px`:e}function yi(e){return(0,d.jsx)(Vd,{...e})}function jl({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:a,onErrorChange:i,isProcessing:l=!1,onButtonClick:u,onDecline:p,onTechnicalFailure:v,runBeforeButtonClick:R,billingName:w,onBuyerIdentityReady:x,onLoadStateChange:K,placeholderBorderRadius:T,popupCapabilityOwner:V,externalTelemetryContext:A,presentationMode:f}){let P=Jn(),{emitInstrument:ee}=(0,o.useContext)(an),D=(0,or.useStripe)(),ue=(0,or.useElements)(),F=(0,o.useMemo)(()=>ri(Sr(P),A),[A,P]),[ne,_e]=(0,o.useState)("loading");(0,o.useEffect)(()=>{K?.(ne)},[ne,K]);let[ie,We]=(0,o.useState)(!1),kt=(0,o.useRef)(!1),de=!(0,c.isValidEmail)(r?.trim())||!w?.trim(),{request:G,collect:pt,finish:we}=Uo(),xe=(0,o.useRef)(!1),ke=(0,o.useRef)(null),Z=(0,o.useRef)(null),[pe,Re]=(0,o.useState)(0),[Fe,rt]=(0,o.useState)(!1),me=(0,o.useRef)(!1),N=(0,o.useRef)(new Map),{startAttempt:H,finishAttempt:ye,invalidateAttempt:$e,isAttemptInvalidated:he,isAttemptCurrent:M,generationRef:Ye}=fa((q,Pe,st)=>{v?.(q,Pe,{...st,popupBlocked:st?.popupBlocked??(0,Se.isPopupBlockedError)(Pe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f,terminalReason:"overlay_timeout"}),rt(!0),Re(W=>W+1)},{onHandoffObserved:()=>{V.markAvailable(),F?.log({name:"provider.popup.opened",stage:"overlay_open",...En,attempt:Ye.current})}});(0,o.useEffect)(()=>{Fe&&Z.current?.focus()},[Fe,pe]);let Te=(0,o.useCallback)(()=>{Re(q=>q+1)},[]),tt=(0,o.useCallback)((q,Pe,st)=>{$e(st),v?.("paypal",q,{code:Pe,popupBlocked:(0,Se.isPopupBlockedError)(q),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:f}),rt(!0),Te()},[$e,v,f,Te]),Ze=(0,o.useCallback)(()=>{window.setTimeout(()=>{(ke.current?.querySelector("iframe")??ke.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{me.current&&(me.current=!1,Ze())},[Ze,pe]);let ze=(0,o.useCallback)(()=>{rt(!1),i?.(null),Ze()},[Ze,i]);(0,o.useEffect)(()=>{if(!D||xe.current)return;let[q,Pe,st]=(0,c.readStripeRedirectParams)();if(!q||!Pe)return;let W=(0,c.readMatchingStripePayPalContinuation)(Pe);if(!W)return;xe.current=!0;let Ee=!0,nt=Ra.get(Pe);nt||(nt=st==="failed"?Promise.resolve(null):Promise.resolve().then(()=>D.retrievePaymentIntent(Pe)),Ra.set(Pe,nt));let Ke={accountPatch:W.accountPatch,sessionId:W.sessionId,nonce:W.nonce},Rt=()=>{F?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...En,requestCategory:"provider_sdk"})};return F?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...En}),(async()=>{try{We(!0);let b=await nt;if(!Ee)return;if(b?.error){Ra.delete(Pe),Rt(),i?.(b.error.message??"Failed to retrieve PayPal payment status.");return}if((0,c.clearStripePayPalReturn)(),Ra.delete(Pe),st==="failed"){let qe="PayPal payment was declined. Please try again.";F?.terminal({outcome:"payment_declined",...En,terminalReason:"provider_declined"}),i?.(qe),p?.(Cr("paypal",qe));return}let L=b?.paymentIntent;if(L&&L.id!==q){Rt(),i?.("Failed to match the returned PayPal payment.");return}if(L&&(L.status==="requires_capture"||L.status==="succeeded")){let qe=typeof L.payment_method=="string"?L.payment_method:L.payment_method?.id;a({id:qe??L.id,type:"card",threeDSecureActionResultTokenId:L.id,isPaypal:!0},{...Ke,presentationMode:"redirect"})}else{let qe="PayPal payment was not completed. Please try again.";F?.terminal({outcome:L?.status==="canceled"?"payment_cancelled":"payment_declined",...En,terminalReason:L?.status==="canceled"?"cancelled":"provider_declined"}),i?.(qe),p?.(Cr("paypal",qe))}}catch(b){if(!Ee)return;Ra.delete(Pe),Rt(),i?.(b instanceof Error?b.message:"Failed to complete PayPal payment.")}finally{Ee&&We(!1)}})(),()=>{Ee=!1,xe.current=!1}},[D,a,i,p,F]);let He=(0,o.useCallback)(async(q=!1)=>{let Pe=R?await R("paypal"):{proceed:!0};if(!Pe.proceed)return N.current.delete(pe),!1;let st=H("paypal");return N.current.set(pe,{generation:st,accountPatch:Pe.accountPatch,sessionId:Pe.sessionId,nonce:Pe.nonce}),rt(!1),F?.log({name:`provider.${q?"redirect.started":"handoff.requested"}`,stage:q?"redirect":"overlay_open",...En,attempt:st}),u?.("paypal"),!0},[u,F,R,H,pe]),Le=(0,o.useCallback)(async q=>{if(l||ie||!await He()){q.reject();return}q.resolve()},[l,He,ie]),Et=(0,o.useCallback)(async q=>{if(!D||!ue)return;let Pe=N.current.get(pe);if(Pe&&!M(Pe.generation)){N.current.delete(pe);return}if(!Pe&&he()||Pe&&!ye(Pe.generation))return;Pe||ye();let st=Pe??null;if(N.current.delete(pe),!st&&R){let qt=await R("paypal");if(!qt.proceed){q.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}st={accountPatch:qt.accountPatch,sessionId:qt.sessionId,nonce:qt.nonce}}let W=st?.sessionId??e,Ee=st?.nonce??t,nt=await xd({event:q,prepared:st,email:r,billingName:w,methodLabel:"PayPal",collect:pt});if(!nt){q.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ke=nt.email,Rt={...st?.accountPatch,...(0,sn.compactBuyerIdentity)(nt,!0)};try{if(We(!0),i?.(null),!W||!(0,c.isValidEmail)(Ke))throw new Error("Missing sessionId or email for PayPal payment");await x?.(nt);let qt=D.createPaymentMethod,{error:b,paymentMethod:L}=await qt({type:"paypal"});if(b){tt(b,"stripe_paypal_create_payment_method_failed",Pe?.generation),q.paymentFailed({reason:"fail"});return}let qe=await pi(n,ee,W,Ee??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:L?.id??null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let fe=qe.clientSecret,h={return_url:(0,c.stripeRedirectReturnUrl)()};if(L?.id&&(h.payment_method=L.id),!ar(os,{clientSecret:fe,sessionId:W,nonce:Ee,accountPatch:Rt})&&f==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:j,paymentIntent:Y}=await D.confirmPayment({clientSecret:fe,confirmParams:h,redirect:"if_required"});if(j){if(ar(os),(0,Se.isProviderDecline)(j)){let k=j.message??"Your payment was declined.";F?.terminal({outcome:"payment_declined",...En,terminalReason:"provider_declined"}),i?.(k),p?.(Cr("paypal",k,{code:(0,Se.getProviderErrorCode)(j),declineCode:(0,Se.getProviderDeclineCode)(j)})),await mi({billingApiUrl:n,sessionId:W,nonce:Ee,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,Se.getProviderErrorCode)(j)??"provider_declined"}})}else tt(j,"stripe_paypal_confirm_failed",Pe?.generation);return}ar(os);let te=typeof Y?.payment_method=="string"?Y.payment_method:Y?.payment_method?.id;a({id:te??Y?.id,type:"card",threeDSecureActionResultTokenId:Y?.id,isPaypal:!0},{accountPatch:Rt,paymentMethodCategory:"paypal",presentationMode:f,sessionId:W,nonce:Ee});return}catch(qt){tt(qt,"stripe_paypal_failed",Pe?.generation)}finally{We(!1)}},[D,ue,e,t,r,w,pt,x,n,ee,a,i,p,R,tt,ye,M,he,F,f,pe]),zt=(0,o.useCallback)(async()=>{if(!(kt.current||l||ie||!D||!ue)){kt.current=!0,We(!0);try{if(!await He(!0))return;await Et({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{kt.current=!1,We(!1)}}},[ue,Et,l,He,D,ie]),ft=f==="redirect"?(0,d.jsx)("button",{type:"button",disabled:l||ie,onClick:()=>{zt()},style:{width:"100%",minHeight:Go,border:"1px solid #d1d5db",borderRadius:T??8,background:"#ffc439",color:"#111827",cursor:l||ie?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,d.jsx)(or.ExpressCheckoutElement,{onReady:q=>_e(Sa(q,["paypal"])),onLoadError:()=>{_e("load_error"),cs(F,"paypal","paypal","provider_error")},onClick:Le,onConfirm:Et,onCancel:()=>{let q=N.current.get(pe);N.current.delete(pe),F?.terminal({outcome:"payment_cancelled",...En,terminalReason:"cancelled",...q?{attempt:q.generation}:{}}),$e(q?.generation),rt(!1),me.current=!0,Te()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:de,emailRequired:de,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},pe),Ft=(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{ref:ke,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Fe&&(0,d.jsx)("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ze,style:as,children:"Try PayPal again"}),G&&(0,d.jsx)(zo,{identity:G.identity,methodLabel:G.methodLabel,onComplete:we,onCancel:()=>we(null)},G.id),(0,d.jsx)("div",{style:{display:G?"none":void 0},children:ft})]}),ie&&!G&&(0,d.jsx)(Wr,{status:"processing"})]});return f==="redirect"?Ft:(0,d.jsx)(wa,{state:ne,placeholderTestId:"flopay-paypal-placeholder",borderRadius:T,children:Ft})}function Vl(e){return e==="apple_pay"||e==="google_pay"}var qd=200;function jd({active:e}){return(0,o.useLayoutEffect)(()=>e?(0,c.denyPaymentPermissionToNewFrames)(document):void 0,[e]),null}function Wl({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:a,expressMethods:i,onTokenizedBody:l,onErrorChange:u,onButtonClick:p,onDecline:v,onTechnicalFailure:R,runBeforeButtonClick:w,billingName:x,onBuyerIdentityReady:K,onLoadStateChange:T,placeholderBorderRadius:V,popupCapabilityOwner:A,externalTelemetryContext:f}){let P=Jn(),{emitInstrument:ee}=(0,o.useContext)(an),D=(0,or.useStripe)(),ue=(0,or.useElements)(),F=(0,o.useMemo)(()=>ri(Sr(P),f),[f,P]),[ne,_e]=(0,o.useState)("loading");(0,o.useEffect)(()=>{T?.(ne)},[ne,T]);let[ie,We]=(0,o.useState)(!1);(0,o.useEffect)(()=>{rt.current=ie},[ie]);let kt=(0,o.useRef)(!(0,c.isValidEmail)(r?.trim())||!x?.trim()).current,{request:de,collect:G,finish:pt}=Uo(),we=(0,o.useRef)(null),xe=(0,o.useRef)(null),[ke,Z]=(0,o.useState)(0),[pe,Re]=(0,o.useState)(()=>(0,c.shouldPreferWalletPopup)()),Fe=(0,o.useRef)(pe),rt=(0,o.useRef)(!1),[me,N]=(0,o.useState)(!1),[H,ye]=(0,o.useState)(()=>ui(e,t)?"blocked":"idle"),[$e,he]=(0,o.useState)("google_pay"),M=(0,o.useRef)(null),Ye=(0,o.useRef)(!0),Te=(0,o.useRef)(!1),tt=(0,o.useRef)("google_pay"),Ze=(0,o.useRef)("google_pay"),ze=(0,o.useRef)(null),He=(0,o.useRef)(null),Le=(0,o.useRef)(new Set),Et=(0,o.useRef)(null),zt=(0,o.useRef)(null);(0,o.useEffect)(()=>(Ye.current=!0,()=>{Ye.current=!1;for(let h of Le.current)window.clearTimeout(h);Le.current.clear()}),[]);let ft=(0,o.useRef)(new Map),{startAttempt:Ft,finishAttempt:q,invalidateAttempt:Pe,isAttemptInvalidated:st,isAttemptCurrent:W,generationRef:Ee}=fa((h,ve,j)=>{R?.(h,ve,{...j,popupBlocked:j?.popupBlocked??(0,Se.isPopupBlockedError)(ve),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),he(h),N(!0),Z(Y=>Y+1)},{onHandoffObserved:h=>{zt.current=Ee.current,A.markAvailable(),F?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Ee.current,...h==="apple_pay"||h==="google_pay"?{walletType:h}:{}})},defersMissingTerminal:Vl,onMissingTerminalDeferred:(h,ve)=>{let j=F?.now()??globalThis.performance?.now()??Date.now(),Y=Et.current,te=Y?.generation===ve?Y.startedAt:j;F?.performance({stage:"overlay_return",durationMs:Math.max(0,j-te),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:ve,...Vl(h)?{walletType:h}:{}}),F?.flush?.().catch(()=>{})}});(0,o.useEffect)(()=>{me&&xe.current?.focus()},[me,ke]);let nt=(0,o.useCallback)(()=>{Z(h=>h+1)},[]),Ke=(0,o.useCallback)((h,ve,j,Y,te=!1)=>{Pe(Y),R?.(h,ve,{code:j,popupBlocked:(0,Se.isPopupBlockedError)(ve),telemetryReported:te,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),he(h),N(!0),nt()},[Pe,R,nt]),Rt=(0,o.useCallback)(()=>{window.setTimeout(()=>{(we.current?.querySelector("iframe")??we.current)?.focus()},0)},[]);(0,o.useEffect)(()=>{Te.current&&(Te.current=!1,Rt())},[Rt,ke]);let qt=(0,o.useCallback)(()=>{N(!1),u?.(null),Rt()},[Rt,u]),b=(0,o.useCallback)(()=>{M.current?.()},[]);(0,o.useEffect)(()=>{let h=null,ve=()=>{h=null;let Y=(0,c.shouldPreferWalletPopup)();Y!==Fe.current&&(Fe.current=Y,Re(Y),!rt.current&&!W(Ee.current)&&nt())},j=()=>{h!==null&&window.clearTimeout(h),h=window.setTimeout(ve,qd)};return window.addEventListener("resize",j),()=>{window.removeEventListener("resize",j),h!==null&&window.clearTimeout(h)}},[Ee,W,nt]),(0,o.useEffect)(()=>{let h=ui(e,t);if(!h)return;let ve=!1,j=!1,Y=async()=>{if(!j){j=!0,ve||ye("checking");try{let te=await Ll(D,h.clientSecret,Le.current);if(ve)return;let k=ns(te,h.providerObjectId,(0,c.isSetupIntentClientSecret)(h.clientSecret));if(k.kind==="confirmed"){if(!Ol(e,t,h.clientSecret))return;M.current=null,ye("idle"),l({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.intentId},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(k.kind==="terminal"){rs(e,t,h.clientSecret),M.current=null,ye("idle"),he(h.paymentMethodType),N(!0),nt();return}ye("blocked")}catch{ve||ye("blocked")}finally{j=!1}}};return M.current=Y,ye("blocked"),()=>{ve=!0,M.current===Y&&(M.current=null)}},[t,l,nt,e,D]);let L=(0,o.useCallback)(async h=>{let ve=!1,j=ot=>{ve||(ve=!0,h.paymentFailed({reason:"fail",...ot?{message:ot}:{}}))};if(!D||!ue){j();return}let Y=ft.current.get(ke);if(Y&&!W(Y.generation)){ft.current.delete(ke),j();return}if(!Y&&st()){j();return}if(Y&&!q(Y.generation)){j();return}Y||q();let te=h.expressPaymentType??Y?.method??tt.current,k=Y??null,Q=ql(te),be;te==="apple_pay"?be="apple_pay":te==="google_pay"&&(be="google_pay");let Be=Y?.generation??Ee.current,S=F,Bt=S?.now()??globalThis.performance?.now()??Date.now(),rr=new AbortController,sr=!1,Ht=!1,Kt=null,Lr=e,_r="processing",jt="other",Zr="provider_runtime",Gt,_n=new Promise((ot,dt)=>{Gt=dt}),Yt=window.setTimeout(()=>{sr=!0,rr.abort(),Gt(ci)},Pd),Qr=async(ot,dt,Vt)=>{_r=ot,jt=dt,Zr=dt==="intent_create"||dt==="session_claim"?"transport_error":"provider_runtime";let xr=S?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Vt,_n])}finally{let Ar=S?.now()??globalThis.performance?.now()??Date.now();S?.performance({stage:ot,durationMs:Math.max(0,Ar-xr),durationMode:"machine",requestCategory:dt,paymentMethodCategory:"wallet",provider:"stripe",...sr?{statusClass:"timeout"}:{}})}};try{if(We(!0),u?.(null),!k&&w){let Ae=await Qr("processing","other",w(Q));if(!Ae.proceed){j();return}k={accountPatch:Ae.accountPatch,sessionId:Ae.sessionId,nonce:Ae.nonce}}let ot=k?.sessionId??e;Lr=ot;let dt=k?.nonce??t,Vt=ze.current??k?.accountPatch,xr=Yl({event:h,fallbackEmail:Vt?.email??r,fallbackName:[Vt?.firstName,Vt?.lastName].join(" ").trim()||x});if(!(0,c.isValidEmail)(xr.email)){j("Buyer details are required."),G(is(te),xr).then(Ae=>{Ae&&(ze.current=Ae)});return}ze.current=null;let Ar={...k?.accountPatch,...(0,sn.compactBuyerIdentity)(xr,!0)};await Qr("processing","session_claim",Promise.resolve(K?.(xr)));let{error:Fr}=await Qr("tokenization","provider_sdk",ue.submit());if(Fr){j(),Ke(te,Fr,"stripe_wallet_submit_failed",Y?.generation);return}if(!ot)throw new Error("Missing sessionId or email for payment.");let Rr={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:te,paymentMethodId:null,intentKind:a},Tr=JSON.stringify({sessionId:ot,nonce:dt??"",request:Rr}),gr=He.current,mr=gr?.retryIdentity===Tr?gr.authorizationAttemptId:(0,c.randomUuidV4)();He.current={authorizationAttemptId:mr,retryIdentity:Tr};let Xt=await Qr("processing","intent_create",pi(n,ee,ot,dt??"",{...Rr,authorizationAttemptId:mr},{signal:rr.signal}));if(Xt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Dt=Xt.clientSecret,hr=Rd({createdAt:Date.now(),sessionId:ot,...dt?{nonce:dt}:{},clientSecret:Dt,providerObjectId:Xt.providerObjectId,paymentMethodType:te,accountPatch:Ar});window.clearTimeout(Yt),Ht=!0,S?.performance({stage:"callback",durationMs:Math.max(0,(S?.now()??globalThis.performance?.now()??Date.now())-Bt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Pr=S?.now()??globalThis.performance?.now()??Date.now(),De={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...be?{walletType:be}:{},attempt:Be},mn=!1,Nr=null;S?.log({name:"payment.provider_confirmation.started",...De}),Kt=window.setTimeout(()=>{Kt!==null&&Le.current.delete(Kt),mn=!0;let Ae=S?.now()??globalThis.performance?.now()??Date.now();S?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...De,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Ae-Pr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),S?.flush?.().catch(()=>{}),Nr?.()},vd),Le.current.add(Kt);let Tn=(Ae,xt)=>{Kt!==null&&(window.clearTimeout(Kt),Le.current.delete(Kt),Kt=null);let bt=S?.now()??globalThis.performance?.now()??Date.now(),At=Math.max(0,bt-Pr),Qe=Ae;mn&&(Ae==="resolved"?Qe="resolved_late":Ae==="returned_error"?Qe="returned_error_late":Qe="rejected_late");let Ur=xt??(Ae==="resolved"?"approved":"provider_error");return S?.log({name:"payment.provider_confirmation.returned",...De,operationOutcome:Qe,terminalReason:Ur}),S?.performance({...De,durationMs:At,durationMode:"buyer",operationOutcome:Qe,terminalReason:Ur}),{durationMs:At,operationOutcome:Qe,terminalReason:Ur}},lr=!1,Er=!1,Mn=Ae=>{if(!Ae||typeof Ae!="object")return null;let xt=Ae;if(xt.error)return null;let bt=xt.setupIntent??xt.paymentIntent,At=ns(bt??null,void 0,!!xt.setupIntent);return At.kind==="confirmed"?At:null},en=Ae=>{if(lr||Y&&Ee.current!==Y.generation)return;let xt=Mn(Ae);if(!xt)return;if(hr&&!Ol(ot,dt,Dt)){lr=!0;return}let{intentId:bt,paymentMethodId:At}=xt;lr=!0,Er=!0,He.current=null,M.current=null,Ye.current&&(ye("idle"),We(!1));let Qe=`${Hl}:${ot}`;ar(Qe,{createdAt:Date.now(),sessionId:ot,nonce:dt,accountPatch:Ar,paymentMethodId:At,providerIntentId:bt,paymentMethodType:te});try{l({id:At,type:"card",threeDSecureActionResultTokenId:bt},{accountPatch:Ar,paymentMethodCategory:"wallet",sessionId:ot,nonce:dt})}finally{ar(Qe)}},Jt=!1;Nr=async()=>{if(!(Jt||lr||Er)){Jt=!0,Ye.current&&ye("checking");try{let Ae=await Ll(D,Dt,Le.current);if(lr||Er)return;let xt=(0,c.isSetupIntentClientSecret)(Dt),bt=ns(Ae,Xt.providerObjectId,xt);if(bt.kind==="confirmed"){en(xt?{setupIntent:Ae}:{paymentIntent:Ae});return}if(bt.kind==="terminal"){if(Er=!0,rs(ot,dt,Dt),He.current=null,M.current=null,!Ye.current)return;ye("idle"),j(),Ke(te,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Y?.generation,!0);return}Ye.current&&!Er&&(ye("blocked"),We(!1))}catch{Ye.current&&!Er&&(ye("blocked"),We(!1))}finally{Jt=!1}}},M.current=Nr;let g,It;try{let Ae=await((0,c.isSetupIntentClientSecret)(Dt)?D.confirmSetup({elements:ue,clientSecret:Dt,redirect:"if_required"}):D.confirmPayment({elements:ue,clientSecret:Dt,redirect:"if_required"}));if(!Ae||typeof Ae!="object")throw new Ea(kd(Ae));if(g=Ae,!g.error&&!Mn(g))throw new Ea("confirmation_result_unconfirmed");It=Tn(g.error?"returned_error":"resolved",g.error&&(0,Se.isProviderDecline)(g.error)?"provider_declined":void 0)}catch(Ae){let xt=Ae instanceof Ea?Ae.reason:void 0,bt=xt!==void 0,At=Tn(bt?"returned_error":"rejected");if(S?.error({...bt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:xt}:Ki(Ae),...De,operationOutcome:At.operationOutcome,durationMs:At.durationMs,statusClass:"unknown",terminalReason:At.terminalReason}),!Ye.current||lr)return;await Nr?.();return}let se=g.error;if(se){if(!Ye.current||lr)return;if((0,Se.isProviderDecline)(se)){Er=!0,rs(ot,dt,Dt),He.current=null,M.current=null,ye("idle");let Ae=se.message??"Your payment was declined.";j(Ae),u?.(Ae),v?.(Cr(Q,Ae,{code:(0,Se.getProviderErrorCode)(se),declineCode:(0,Se.getProviderDeclineCode)(se)})),mi({billingApiUrl:n,sessionId:ot,nonce:dt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:te,providerDeclineReason:(0,Se.getProviderErrorCode)(se)??"provider_declined",...Xt.intentKind==="payment"&&Xt.providerObjectId.startsWith("pi_")?{providerIntentId:Xt.providerObjectId}:{}}})}else S?.error({...Ki(se),...De,operationOutcome:It.operationOutcome,durationMs:It.durationMs,statusClass:"unknown",terminalReason:It.terminalReason}),await Nr?.();return}if(en(g),!lr)throw new Error("Invalid provider returned for APM intent")}catch(ot){if(ot===ci){let dt=S?.now()??globalThis.performance?.now()??Date.now();S?.error({errorCode:Id(jt),stage:_r,requestCategory:jt,paymentMethodCategory:"wallet",provider:"stripe",...be?{walletType:be}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Lr,durationMs:Math.max(0,dt-Bt),statusClass:"timeout",failureCategory:Zr,attempt:Be,terminalReason:"provider_error"}),S?.flush?.().catch(()=>{})}j(),Ke(te,ot,ot===ci?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Y?.generation,ot===ci)}finally{if(window.clearTimeout(Yt),Kt!==null&&(window.clearTimeout(Kt),Le.current.delete(Kt)),!Ht){let ot=S?.now()??globalThis.performance?.now()??Date.now();S?.performance({stage:"callback",durationMs:Math.max(0,ot-Bt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...sr?{statusClass:"timeout"}:{}})}Ye.current&&We(!1)}},[D,ue,e,t,r,x,G,K,n,ee,a,l,u,v,w,Ke,q,W,st,Ee,F,ke]),qe=(0,o.useMemo)(()=>oi(i),[i]),fe=(0,o.useMemo)(()=>i.map(c.stripeExpressMethodToOptionKey),[i]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(wa,{state:ne,placeholderTestId:"flopay-wallet-placeholder",borderRadius:V,children:(0,d.jsxs)("div",{ref:we,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[me&&(0,d.jsxs)("button",{ref:xe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:qt,style:as,children:["Try ",is($e)," again"]}),H!=="idle"&&(0,d.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,d.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,d.jsx)("button",{type:"button",onClick:b,disabled:H==="checking",style:as,children:H==="checking"?"Checking payment status\u2026":"Check payment status"})]}),de&&(0,d.jsx)(zo,{identity:de.identity,methodLabel:de.methodLabel,onComplete:pt,onCancel:()=>pt(null)},de.id),H==="idle"&&(0,d.jsxs)("div",{style:{display:de?"none":void 0},children:[(0,d.jsx)(jd,{active:pe}),(0,d.jsx)(or.ExpressCheckoutElement,{onReady:h=>{_e(Sa(h,fe))},onLoadError:h=>{_e("load_error"),cs(F,"stripe","wallet","provider_error")},onClick:async h=>{let ve=F?.now()??globalThis.performance?.now()??Date.now();tt.current=h.expressPaymentType,Ze.current=ql(h.expressPaymentType);let j=!0,Y=window.setTimeout(()=>{j=!1,h.reject()},hd),te=w?await w(Ze.current):{proceed:!0};if(window.clearTimeout(Y),!j)return;if(!te.proceed){ft.current.delete(ke),h.reject();return}let k=Ft(h.expressPaymentType);Et.current={generation:k,startedAt:ve},ft.current.set(ke,{generation:k,method:h.expressPaymentType,accountPatch:te.accountPatch,sessionId:te.sessionId,nonce:te.nonce}),N(!1),F?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:k,...h.expressPaymentType==="apple_pay"||h.expressPaymentType==="google_pay"?{walletType:h.expressPaymentType}:{}}),p?.(Ze.current),h.resolve()},onConfirm:L,onCancel:()=>{let h=ft.current.get(ke);ft.current.delete(ke);let ve=Et.current,j=F?.now()??globalThis.performance?.now()??Date.now();if(h&&ve?.generation===h.generation&&(0,c.isWalletSheetRefusedForWindowSize)({method:h.method,elapsedMs:j-ve.startedAt,handoffObserved:zt.current===h.generation})){F?.error({errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",terminalReason:"provider_error",attempt:h.generation,walletType:"google_pay"}),He.current=null,Ke(h.method,new Error("The browser window is too small for the Google Pay sheet."),c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE,h.generation,!0);return}F?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...h?{attempt:h.generation}:{}}),Pe(h?.generation),He.current=null,N(!1),Te.current=!0,nt()},options:{...ai,paymentMethods:qe,emailRequired:kt,billingAddressRequired:kt}},ke)]})]})}),ie&&(0,d.jsx)(Wr,{status:"processing"})]})}function Xl(e,t,r){let n=(0,c.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,paymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function ss({method:e,sessionId:t,nonce:r,email:n,billingName:a,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:u,onErrorChange:p,onDecline:v,onCancel:R,runBeforeButtonClick:w,onButtonClick:x,isProcessing:K,submitButtonColor:T,submitButtonBorderRadius:V,submitButtonStyle:A,errorText:f}){let P=Jn(),{emitInstrument:ee}=(0,o.useContext)(an),D=(0,or.useStripe)(),ue=(0,or.useElements)(),[F,ne]=(0,o.useState)(!1),_e=(0,o.useRef)(!1),[ie,We]=(0,o.useState)(!1),[kt,de]=(0,o.useState)("loading"),[G,pt]=(0,o.useState)(""),we=!(0,c.isValidEmail)(n?.trim()),xe=!we||(0,c.isValidEmail)(G.trim()),ke=(0,o.useCallback)(async()=>{if(!D||!ue||K||_e.current||!ie)return;_e.current=!0,ne(!0);let Z=w?await w("card"):{proceed:!0};if(!Z.proceed){_e.current=!1,ne(!1);return}x?.("card");let pe=Z.sessionId??t,Re=Z.nonce??r,Fe=(0,No.splitFullName)(a?.trim()),rt=(0,sn.compactBuyerIdentity)({email:Z.accountPatch?.email?.trim()||n?.trim()||G.trim(),firstName:Z.accountPatch?.firstName?.trim()||Fe.firstName,lastName:Z.accountPatch?.lastName?.trim()||Fe.lastName}),me=rt.email,N=(0,sn.compactBuyerIdentity)({...Z.accountPatch,...rt});try{if(p?.(null),!(0,c.isValidEmail)(me))throw new Error("A valid email address is required for payment.");await i?.(rt);let H=await ue.submit();if(H.error){p?.(H.error.message??"Payment failed.");return}let ye=[rt.firstName,rt.lastName].filter(Boolean).join(" "),$e=await D.createPaymentMethod({elements:ue,params:{billing_details:{email:me,...ye?{name:ye}:{}}}});if($e.error||!$e.paymentMethod){p?.($e.error?.message??"Failed to create payment method.");return}let he=$e.paymentMethod;if(!pe||!me)throw new Error("Missing sessionId or email for payment.");let M=he.type||e,Ye=await pi(l,ee,pe,Re??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:M,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Te=Ye.clientSecret;ar(jn,{clientSecret:Te,sessionId:pe,nonce:Re,accountPatch:N,paymentMethodId:he.id,paymentMethodType:he.type??e,gateway:"stripe"});let{error:tt,paymentIntent:Ze}=await D.confirmPayment({clientSecret:Te,confirmParams:{return_url:window.location.href,payment_method:he.id},redirect:"if_required"});if(tt){ar(jn);let Le=tt.message??"Payment failed.";p?.(Le),v?.(Cr("card",Le,{code:tt.code})),await mi({billingApiUrl:l,sessionId:pe,nonce:Re,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:tt.code??"provider_declined"}});return}let ze=Ze?.status;if(!ua(ze)){ar(jn);let Le=ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(Le),v?.(Cr("card",Le,{code:ze??"missing_payment_intent"}));return}ar(jn);let He=typeof Ze?.payment_method=="string"?Ze.payment_method:Ze?.payment_method?.id;u({id:He??he.id,type:"card",threeDSecureActionResultTokenId:Ze?.id,gateway:"stripe",paymentMethodType:he.type??e},{accountPatch:N,paymentMethodCategory:"apm",sessionId:pe,nonce:Re})}catch(H){p?.(H instanceof Error?H.message:"Payment failed. Please try again.")}finally{_e.current=!1,ne(!1)}},[D,ue,K,ie,w,x,t,r,n,a,G,i,l,ee,e,u,p,v]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[we&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:we&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:G,onChange:Z=>pt(Z.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(or.PaymentElement,{onReady:()=>de("ready"),onLoadError:()=>{de("load_error"),cs(Sr(P),"stripe","apm")},onChange:Z=>{We(!!Z.complete)},options:{layout:ii,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...(0,c.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,d.jsx)(si,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{ke()},disabled:!ie||!xe||F||K||kt!=="ready",color:T,borderRadius:V,style:A,children:F?"Processing\u2026":`Pay with ${(0,c.getStripeMethodDisplayName)(e)}`}),f&&(0,d.jsx)(Vo,{margin:"0.75rem 0 0",children:f})]})}function $l({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:l,stripeInstance:u,paymentElementBaseOptions:p,futureUseSession:v,onTokenizedBody:R,onErrorChange:w,onButtonClick:x,onDecline:K,runBeforeButtonClick:T,onLoadStateChange:V,isProcessing:A=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:P=8,submitButtonStyle:ee,buttonAppearance:D,themeId:ue,onExpandApm:F,expandedApmMethod:ne}){let{emitInstrument:_e}=(0,o.useContext)(an),[ie,We]=(0,o.useState)(null),[kt,de]=(0,o.useState)(null),G=(0,o.useRef)(!1),{request:pt,collect:we,finish:xe}=Uo();(0,o.useEffect)(()=>{l.length>0&&u?V?.("ready"):u||V?.("loading")},[l.length,u,V]);let ke=(0,o.useCallback)(async me=>{if(!u||G.current||A)return;G.current=!0,de(me);let N=T?await T("card"):{proceed:!0};if(!N.proceed){G.current=!1,de(null);return}x?.("card");let H=N.sessionId??e,ye=N.nonce??t,$e=(0,No.splitFullName)([N.accountPatch?.firstName,N.accountPatch?.lastName].filter(Boolean).join(" ")||n),he=(0,sn.compactBuyerIdentity)({email:N.accountPatch?.email?.trim()||r?.trim(),firstName:N.accountPatch?.firstName?.trim()||$e.firstName,lastName:N.accountPatch?.lastName?.trim()||$e.lastName});if(!(0,c.isValidEmail)(he.email)){de(null);let Te=await we((0,c.getStripeMethodDisplayName)(me),he);if(!Te){G.current=!1;return}he=Te,de(me)}let M=he.email,Ye=(0,sn.compactBuyerIdentity)({...N.accountPatch,...he});try{if(w?.(null),!H||!(0,c.isValidEmail)(M))throw new Error("Missing sessionId or email for payment.");await a?.(he);let Te=await pi(i,_e,H,ye??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:me,paymentMethodId:null,intentKind:"payment"});if(Te.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let tt=Te.clientSecret;ar(jn,{clientSecret:tt,sessionId:H,nonce:ye,accountPatch:Ye,paymentMethodType:me,gateway:"stripe"});let{error:Ze,paymentIntent:ze}=await u.confirmPayment({clientSecret:tt,confirmParams:{return_url:window.location.href,payment_method_data:{type:me,billing_details:{name:[he.firstName,he.lastName].filter(Boolean).join(" "),...M?{email:M}:{}}}},redirect:"if_required"});if(Ze){ar(jn);let Et=Ze.message??"Payment failed.";w?.(Et),K?.(Cr("card",Et,{code:Ze.code})),await mi({billingApiUrl:i,sessionId:H,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:me,providerDeclineReason:Ze.code??"provider_declined"}});return}let He=ze?.status;if(!ua(He)){ar(jn);let Et=He==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";w?.(Et),K?.(Cr("card",Et,{code:He??"missing_payment_intent"}));return}ar(jn);let Le=typeof ze?.payment_method=="string"?ze.payment_method:ze?.payment_method?.id;R({id:Le??ze?.id,type:"card",threeDSecureActionResultTokenId:ze?.id,gateway:"stripe",paymentMethodType:me},{accountPatch:Ye,paymentMethodCategory:"apm",sessionId:H,nonce:ye})}catch(Te){w?.(Te instanceof Error?Te.message:"Payment failed. Please try again.")}finally{G.current=!1,de(null)}},[u,A,T,x,e,t,r,we,i,_e,n,a,R,w,K]),[Z,pe]=(0,o.useState)(null),Re=F?ne??null:Z,Fe=(0,o.useCallback)(me=>{G.current||A||Re&&Re!==me||((0,c.needsStripeMethodExplicitConfirm)(me)?F?F(me):pe(me):ke(me))},[Re,A,ke,F]),rt=(0,o.useMemo)(()=>Z?Xl(p,Z,v):null,[Z,p,v]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:pt?(0,d.jsx)(zo,{identity:pt.identity,methodLabel:pt.methodLabel,onComplete:xe,onCancel:()=>xe(null)},pt.id):l.map(me=>{let N=ne===me,H=kt===me,ye=kt!==null&&kt!==me||ne!=null&&ne!==me;return(0,d.jsxs)(o.default.Fragment,{children:[(0,d.jsx)(ni,{method:me,themeId:ue,submitting:H,disabled:ye,highlighted:N,hasNextStep:(0,c.needsStripeMethodExplicitConfirm)(me),onClick:()=>Fe(me),backgroundColor:D?.backgroundColor,borderColor:D?.borderColor,textColor:D?.textColor,borderRadius:D?.borderRadius,fontFamily:D?.fontFamily}),!F&&Z===me&&rt&&u&&(0,d.jsx)(or.Elements,{stripe:u,options:rt,children:(0,d.jsx)(ss,{method:me,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:R,onErrorChange:w,onDecline:K,onCancel:()=>pe(null),runBeforeButtonClick:T,onButtonClick:x,isProcessing:A,submitButtonColor:f,submitButtonBorderRadius:P,submitButtonStyle:ee})},me)]},me)})})}function Vd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:a,userId:i,onComplete:l,onError:u,onDecline:p,onTokenizedBody:v,firstName:R,lastName:w,chv:x,className:K,submitLabel:T,isProcessing:V,error:A,onErrorChange:f,showPayPal:P=!0,showStripe:ee=!0,walletPresentation:D="auto",enabledPaymentMethods:ue,enabledPaymentMethodCountries:F,showApplePay:ne=!0,showGooglePay:_e=!0,layout:ie="default",theme:We,buttonsTheme:kt,buttonsStyles:de,appearance:G,cardButtonContent:pt,cardBackButtonContent:we,cardTitleContent:xe,showSecurityFooter:ke,onButtonClick:Z,onBeforeButtonClick:pe,onBuyerIdentityReady:Re,enableAVS:Fe,cardFieldOrder:rt,cardPreFormSlot:me,avsLayout:N="row",country:H,zip:ye,addressLine1:$e,addressLine2:he,city:M,state:Ye,onCountryChange:Te,onZipChange:tt,avsCheck:Ze,checkoutType:ze,checkoutLayout:He,totalAmount:Le=0,currency:Et="usd",initialCardOpen:zt=!1,directPaypal:ft,isSubscription:Ft=!1,session:q,dataAttachmentPending:Pe=!1,dataAttachmentRequiresIdentity:st=!1,debug:W=!1}){let Ee=Jn(),nt=Ka(),Ke=(0,o.useContext)(wn),{emitInstrument:Rt}=(0,o.useContext)(an),qt=(0,o.useRef)(null);qt.current||(qt.current=Ya());let b=qt.current,[,L]=(0,o.useState)(0),qe=(0,o.useRef)(null);qe.current||(qe.current=(0,Un.detectPayPalEnvironment)());let fe=qe.current,h=(0,o.useMemo)(()=>({browser:fe,capability:b,presentationMode:"popup"}),[fe,b]),ve=q??Ke.session,j=(0,o.useMemo)(()=>({futureUse:ve?.futureUse,futureUseUnsupported:ve?.futureUseUnsupported}),[ve?.futureUse,ve?.futureUseUnsupported]),Y=ve?.gateways?.paypal?.providerObjectType??ft?.providerObjectType,te=Pe||Ke.claimPending===!0,k=st||Ke.claimRequiresIdentity===!0,Q=te&&!k,be=bl(),Be=r||be,[S,Bt]=(0,o.useState)(!1),[rr,sr]=(0,o.useState)(null),[Ht,Kt]=(0,o.useState)(H??""),[Lr,_r]=(0,o.useState)(ye??""),[jt,Zr]=(0,o.useState)($e??""),[Gt,_n]=(0,o.useState)(he??""),[Yt,Qr]=(0,o.useState)(M??""),[ot,dt]=(0,o.useState)(Ye??""),[Vt,xr]=(0,o.useState)(""),[Ar,Fr]=(0,o.useState)({}),Rr=(0,o.useRef)(ye??""),Tr=(0,o.useRef)(H??""),gr=(0,o.useRef)($e??""),mr=(0,o.useRef)(he??""),Xt=(0,o.useRef)(M??""),Dt=(0,o.useRef)(Ye??""),hr=(0,o.useRef)(""),Pr=(0,o.useRef)({});(0,o.useEffect)(()=>{let s=(E,ae,je,re,Ie)=>{if(Pr.current[E])return;let Lt=ae?.trim();!Lt||Lt===je.current||(je.current=Lt,re(Lt),Ie?.(Lt))};s("country",H,Tr,Kt,Te),s("zip",ye,Rr,_r,tt),s("addressLine1",$e,gr,Zr),s("addressLine2",he,mr,_n),s("city",M,Xt,Qr),s("state",Ye,Dt,dt)},[H,ye,$e,he,M,Ye,Te,tt]);let De=(0,o.useMemo)(()=>(0,c.resolveAVSConfig)(Fe),[Fe]),mn=De!==null,Nr=(0,o.useMemo)(()=>(0,c.isAuthorizationOnlySession)(q),[q]),Tn=(0,c.isMountableVaultBlock)(q?.vault),lr=!!q?.gateways?.pcivault,Er=(0,Sn.hasServerSideCardGateway)(q),en=!!(q?.gateways?.stripe?.enabledPaymentMethods??ue)?.includes("card")||(0,Sn.canRecoverHostedCardForm)(q),Jt=Tn||en||lr,g=!!(ee&&Jt&&e),[It,se]=(0,o.useState)(()=>ie!=="buttons"||zt?e??null:null),[Ae,xt]=(0,o.useState)(0),bt=ie!=="buttons"||zt||!!e&&It===e,At=q?.captureMethod,Qe=(0,o.useRef)(Ee);(0,o.useEffect)(()=>{Qe.current=Ee},[Ee]);let[Ur,ro]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!g||!e||!bt){ro(null);return}let s=Qe.current?Qe.current.cardCapture({sessionId:e,captureMethod:At}):new In.PciVaultCardCapture({sessionId:e,captureMethod:At,billingApiUrl:Be,telemetry:n});return ro({sessionId:e,captureMethod:At,billingApiUrl:Be,telemetry:n,capture:s}),()=>{s.unmount()}},[g,e,bt,At,Be,n]);let Ot=g&&e&&bt&&Ur?.sessionId===e&&Ur.captureMethod===At&&Ur.billingApiUrl===Be&&Ur.telemetry===n?Ur.capture:null,Hr=(0,o.useMemo)(()=>{let s=Ht,E=De?(0,c.isAVSFieldVisible)(De.postal_code,s):!1;return Nd(s,Lr,E)},[De,Ht,Lr]),{avsInvalid:yn,invalidAvsFields:fn}=(0,o.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!g||!De)return{avsInvalid:!1,invalidAvsFields:s};let E=Ht,ae=(Ie,Lt)=>(0,c.isAVSFieldVisible)(Ie,E)&&!Lt.trim(),je={line1:ae(De.address_line_1,jt),city:ae(De.city,Yt),state:ae(De.state,ot),zip:Hr.empty||Hr.malformed};return{avsInvalid:je.line1||je.city||je.state||je.zip,invalidAvsFields:je}},[g,De,Ht,jt,Yt,ot,Hr]),[Zt,xn]=(0,o.useState)(!1),[An,zr]=(0,o.useState)(!1),[Fn,tn]=(0,o.useState)(!1),[Bn,$n]=(0,o.useState)({line1:!1,city:!1,state:!1}),Kr=(0,o.useRef)(!1),gn=(0,o.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),hn=(0,o.useRef)(!1),Nt=(0,o.useCallback)(s=>{gn.current[s]=!0,hn.current=!0},[]),Gr=(0,o.useCallback)(s=>!Kr.current&&gn.current[s],[]),Br=(0,o.useCallback)(s=>{Gr(s)&&$n(E=>E[s]?E:{...E,[s]:!0})},[Gr]),[Pn,vn]=(0,o.useState)(()=>(0,c.resolveVaultMountOptions)(q?.vault,{billingApiUrl:Be,sessionId:e,nonce:t})),[Ct,cr]=(0,o.useState)(zt&&Jt?"card":"buttons"),[vr,qr]=(0,o.useState)(null),no=Ct==="expanding"||Ct==="card",Dn=q?.gateways?.stripe&&!Er?"stripe":void 0,Hn=(0,o.useCallback)(()=>{Rt?.({class:"card_surface",provider:Dn})},[Dn,Rt]),rn=(0,o.useRef)(null),dr=(0,o.useCallback)(s=>{rn.current&&clearTimeout(rn.current),rn.current=setTimeout(()=>{rn.current=null,s()},Ia)},[]);(0,o.useEffect)(()=>()=>{rn.current&&clearTimeout(rn.current)},[]);let oo=(0,o.useRef)(!1),[yr,z]=(0,o.useState)(0),O=(0,o.useRef)(null),le=(0,o.useCallback)(()=>{Hn(),se(e??null),oo.current&&(oo.current=!1,z(s=>s+1)),xt(s=>s+1),cr("expanding"),dr(()=>cr("card"))},[dr,Hn,e]),ge=(0,o.useCallback)(()=>{cr("collapsing"),dr(()=>cr("buttons"))},[dr]),_t=(0,o.useCallback)(s=>{qr(s),cr("apm-expanding"),dr(()=>cr("apm-form"))},[dr]),Qt=(0,o.useCallback)(()=>{cr("apm-collapsing"),dr(()=>{cr("buttons"),qr(null)})},[dr]);(0,o.useEffect)(()=>{ie==="buttons"&&zt&&Jt&&(se(e??null),cr("card"))},[ie,zt,Jt,e]);let[Ne,X]=(0,o.useState)(null),J=(0,o.useRef)(!1),$=(0,o.useRef)(null),m=(0,o.useRef)("idle"),[y,I]=(0,o.useState)(!1),ce=(0,o.useRef)(y);ce.current=y;let[Oe,Xe]=(0,o.useState)(()=>ft?.existingOrderId?{orderId:ft.existingOrderId,attempts:1}:null),er=(0,o.useRef)(Oe);(0,o.useEffect)(()=>{er.current=Oe},[Oe]);let Me=(0,o.useRef)(null),et=(0,o.useMemo)(()=>{if(Re||Ke.claimBuyerIdentity||q?.buyerIdentified!==!1||!e||!t)return;let s=`${Be}|${e}|${t}`;Me.current?.key!==s&&(Me.current={key:s,claim:Oo(new In.PaymentAPI(Be,{telemetry:!1}),e,t,{...i?{userId:i}:{},...R?{firstName:R}:{},...w?{lastName:w}:{}})});let E=Me.current.claim;return async ae=>{await E(ae)}},[Re,Ke.claimBuyerIdentity,q?.buyerIdentified,e,t,Be,i,R,w]),lt=Re??Ke.claimBuyerIdentity??et,St=A??rr,Ce=(0,o.useMemo)(()=>(0,c.resolveTheme)(We),[We]),U=(0,o.useMemo)(()=>{let s=Ce?.buttonsLayout??(0,c.resolveButtonsLayoutTheme)(kt);return de?{...s,...de,cardButton:{...s.cardButton,...de.cardButton},cardFormContainer:{...s.cardFormContainer,...de.cardFormContainer},backButton:{...s.backButton,...de.backButton},backButtonIcon:{...s.backButtonIcon,...de.backButtonIcon},submitButton:{...s.submitButton,...de.submitButton},title:{...s.title,...de.title}}:s},[Ce,kt,de]),oe=G??Ce?.appearance,gt=(0,o.useMemo)(()=>(0,c.computeVaultCardThemeColors)({appearance:oe,buttonsStyles:U,layout:ie}),[oe,U,ie]),Ge=Ke.inlineSessionPatchProcessing??!1,at=(V??S)||Ge,Tt=Be.replace(/\/+$/,""),vt=(0,o.useMemo)(()=>Hi({userId:i,email:a,firstName:R,lastName:w,country:H,zip:ye},Ar),[i,a,R,w,H,ye,Ar]),So=[vt.firstName,vt.lastName].filter(s=>!!s?.trim()).join(" "),Ss=!(0,c.isValidEmail)(vt.email?.trim()),wi=(0,o.useRef)(null);g&&wi.current===null&&(wi.current=Ss);let ao=g&&(wi.current??Ss),ki=(0,o.useMemo)(()=>Ud(Vt,ao),[Vt,ao]),wo=ki.empty||ki.malformed,Yr=(0,o.useMemo)(()=>Ee?Ee.getRawProvider():null,[Ee]),ws=(0,o.useMemo)(()=>nt?nt.getRawProvider():null,[nt]),Zo=Le||100,ko=Et.toLowerCase(),Ri=(0,o.useMemo)(()=>oe?(0,In.toStripeAppearance)(oe):null,[oe]),Ro=Ri,ks=(0,o.useMemo)(()=>{let s=Ri??{},E=s.rules??{};return{...s,rules:{...E,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...E[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...E[".AccordionItemContents"]??{}}}}},[Ri]),Rs=(0,o.useMemo)(()=>({...hl(Le,ve?.captureMethod,j),currency:ko,...Ro?{appearance:Ro}:null}),[Le,ko,ve?.captureMethod,j,Ro]),Ei=(0,c.resolveSetupFutureUsage)(j,"paypal","paypal"),Es=(0,o.useMemo)(()=>({mode:"payment",amount:Zo,currency:ko,captureMethod:"manual",...Ei?{setupFutureUsage:Ei}:null,...Ro?{appearance:Ro}:null}),[Zo,ko,Ei,Ro]),Ue=(0,o.useCallback)(s=>{sr(s),f?.(s)},[f]),Is=(0,o.useRef)(0);(0,o.useEffect)(()=>{yr!==Is.current&&(Is.current=yr,Ue(null))},[yr,Ue]);let Ii=(0,o.useRef)(""),[_s,vc]=(0,o.useState)(!1),_i=(0,o.useCallback)(()=>{vc(!0)},[]);(0,o.useEffect)(()=>{if(!g||!ao||!lt||!_s||wo||Ii.current)return;let s=(0,sn.compactBuyerIdentity)({email:(0,c.isValidEmail)(vt.email?.trim())?vt.email?.trim():hr.current.trim(),firstName:vt.firstName?.trim(),lastName:vt.lastName?.trim()});Ii.current=JSON.stringify(s),Fr(E=>({...E,...s})),Promise.resolve(lt(s)).catch(E=>{Ii.current="",Ue(E instanceof Error?E.message:"Failed to attach buyer details.")})},[g,ao,lt,_s,wo,vt.email,vt.firstName,vt.lastName,Ue]),(0,o.useEffect)(()=>{!g||!Ot||Ot.setCardFieldOrder?.(rt??null,De==null&&!ao)},[g,Ot,rt,De,ao]),(0,o.useEffect)(()=>{(Ct==="expanding"||Ct==="collapsing"||Ct==="apm-expanding"||Ct==="apm-collapsing")&&Ue(null)},[Ct,Ue]);let On=(0,o.useCallback)((s,E,ae)=>{p?.(Cr(s,E,ae))},[p]),Eo=(0,o.useCallback)((s,E,ae)=>{let je=ae?.popupBlocked??(0,Se.isPopupBlockedError)(E);je&&b.markBlocked()&&L(wt=>wt+1);let re=is(s),Ie=ae?.code===c.WALLET_SHEET_WINDOW_TOO_SMALL_CODE?(0,c.buildWalletSheetWindowMessage)(re):(0,Se.buildExternalMethodRecoveryMessage)(re,je,fe.inAppBrowser),Lt=(0,Se.getProviderErrorCode)(E),on=(Lt?.toLowerCase()==="error"?void 0:Lt)??(0,Se.sanitizeExternalFailureCode)(ae?.code)??"external_payment_method_failed",ht=new c.FloPayError(Ie,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:on,popupBlocked:je,inAppBrowser:fe.inAppBrowser,appFamily:fe.appFamily,popupCapability:b.current(),presentationMode:ae?.presentationMode??"popup"}});ae?.telemetryReported||Sr(Ee)?.error(Ko({...h,presentationMode:ae?.presentationMode??"popup"},{errorCode:je?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:ae?.provider??(s==="paypal"?"paypal":"stripe"),paymentMethodCategory:ae?.paymentMethodCategory??(s==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:ae?.terminalReason??(je?"popup_blocked":"provider_error")})),X(null),ie==="buttons"&&(cr("buttons"),qr(null)),Ue(Ie),u?.(ht),console.error("[FloPay] External payment method failed:",{method:s,code:on,popupBlocked:je})},[fe,h,Ee,ie,u,b,Ue]);(0,o.useEffect)(()=>{if(!g||!e){vn(null);return}let s={billingApiUrl:Tt,sessionId:e,nonce:t},E=(0,c.resolveVaultMountOptions)(q?.vault,s);if(E){vn(E);return}if(!bt){vn(null);return}let ae=`${Tt}\0${e}\0${t??""}`,je=O.current;if(je&&je.key===ae){vn(je.mount);return}vn(null);let re=!0;return new In.PaymentAPI(Tt).getVaultCapture(e,t).then(Ie=>{if(!re)return;let Lt=(0,c.resolveVaultMountOptions)(Ie,s);Lt?.verificationRequired&&!Ie.html&&(O.current={key:ae,mount:Lt}),Lt?vn(Lt):Ue("Failed to load the secure card form.")}).catch(Ie=>{re&&Ue(Ie instanceof Error?Ie.message:"Failed to load the secure card form.")}),()=>{re=!1}},[g,bt,Ae,e,q?.vault,Tt,t,Ue]);let bn=(0,o.useRef)({onComplete:l,onError:u,updateError:Ue,emitDecline:On,resolvedAccount:vt,avsConfig:De,avsCheckProp:Ze,sessionId:e,nonce:t,baseUrl:Tt,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:Er});bn.current={onComplete:l,onError:u,updateError:Ue,emitDecline:On,resolvedAccount:vt,avsConfig:De,avsCheckProp:Ze,sessionId:e,nonce:t,baseUrl:Tt,captureMethod:q?.captureMethod,paymentId:q?.paymentId,authorizationExpiresAt:q?.authorizationExpiresAt,serverSideCardGateway:Er};let Ti=(0,o.useRef)(!1),Ts=(0,o.useCallback)(()=>{let s=bn.current,E=s.resolvedAccount.email?.trim(),ae=(0,c.isValidEmail)(E)?E:hr.current.trim();if(!(0,c.isValidEmail)(ae))return null;let je=s.resolvedAccount.firstName?.trim(),re=s.resolvedAccount.lastName?.trim(),Ie=Tr.current.trim()||s.resolvedAccount.country?.trim()||"",Lt=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.state,Ie):!1,on=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.address_line_1,Ie):!1,ht=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.postal_code,Ie):!1,wt=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.city,Ie):!1,Mt=s.avsConfig?(0,c.isAVSFieldVisible)(s.avsConfig.address_line_2,Ie):!1,Wt=on&&!Lt&&ht?(0,c.getStateFromPostalCode)(Ie,(Rr.current??"").trim()):null,yo=Lt?Dt.current:Wt;return{accountData:{userId:s.resolvedAccount.userId??"",email:ae,...je?{firstName:je}:{},...re?{lastName:re}:{},...ht&&Rr.current?{zip:Rr.current}:{},...wt&&Xt.current?{city:Xt.current}:{},...yo?{state:yo}:{},...on&&gr.current?{addressLine1:gr.current}:{},...Mt&&mr.current?{addressLine2:mr.current}:{},...Ie?{country:Ie}:{}},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,c.isAVSFieldVisible)(s.avsConfig.country,Ie),postal_code:ht,address_line_1:on,address_line_2:Mt,city:wt,state:Lt}}:{}}},[]),Ms=(0,o.useRef)(te);Ms.current=te,(0,o.useEffect)(()=>{te||St!==Nl||bn.current.updateError(null)},[te,St]),(0,o.useEffect)(()=>{!g||!Ot||Ot.setSubmitGate?.(yn||te||wo||y)},[g,Ot,yn,te,wo,y]),(0,o.useEffect)(()=>{if(!g||!Ot)return;Ti.current=!1;let s=null,E=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,m.current="idle",X(null)},400)},ae=Ot.on("submitting",()=>{xn(!0),$.current&&clearTimeout($.current),m.current="validation-window",$.current=setTimeout(()=>{$.current=null,m.current==="validation-window"&&(m.current="processing")},_d),X("processing");let ht=bn.current;if(!ht.sessionId||!ht.nonce)return;let wt=Ts();if(!wt){ht.updateError("Enter a valid email address."),m.current="idle",X(null);return}new In.PaymentAPI(ht.baseUrl).patchAccountSnapshot(ht.sessionId,ht.nonce,wt,{telemetryMode:"best_effort"}).catch(Mt=>{if(!Md(Mt))return;let Wt=Mt instanceof Error?Mt.message:"Please check your billing address and try again.";ht.updateError(Wt),m.current="idle",X(null),ht.onError?.(Mt instanceof c.FloPayError?Mt:new c.FloPayError(Wt,"api_error"))})}),je=Ot.on("complete",ht=>{(0,Rn.markSessionRecentlyCompleted)(ht.sessionId??bn.current.sessionId),m.current="terminal",I(!1),X("success"),setTimeout(()=>{if(Ti.current)return;Ti.current=!0;let wt=bn.current,Mt=(0,c.isAuthorizationOnlySession)(wt)||ht.outcome==="authorized",Wt=wt.serverSideCardGateway?{}:{paymentIntentId:ht.intentId};bn.current.onComplete?.(Mt?{status:"authorized",...Wt,paymentId:ht.paymentId??wt.paymentId,sessionId:ht.sessionId??wt.sessionId,authorizationExpiresAt:ht.authorizationExpiresAt??wt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Wt,checkoutMethod:"card"})},600)}),re=Ot.on("decline",ht=>{let wt=bn.current,Mt=ht.message??"Your payment was declined. Please try another card or contact your bank.";m.current="terminal",I(!1),wt.updateError(Mt),X("error");let Wt=ht.failureOutcome??(0,c.normalizeCheckoutFailureOutcome)(ht.declineReason)??"authorization_declined";wt.emitDecline("card",Mt,{code:Wt,declineCode:Wt}),E()}),Ie=Ot.on("error",ht=>{let wt=bn.current,Mt=ht.message??"There was a problem processing your payment. Please try again.";m.current="terminal",I(!1),wt.updateError(Mt),X("error"),wt.onError?.(new c.FloPayError(Mt,"api_error",{code:ht.failureOutcome??"capture_failed"})),E()}),Lt=Ot.on("challenge_dismissed",()=>{$.current&&(clearTimeout($.current),$.current=null),m.current="processing",I(!0),X(null)}),on=Ot.on("blocked",()=>{if(ce.current){bn.current.updateError(Td);return}if(!Ms.current){xn(!0);return}_i(),bn.current.updateError(Nl)});return()=>{s&&(clearTimeout(s),s=null),$.current&&(clearTimeout($.current),$.current=null),m.current="idle",I(!1),X(null),ae(),je(),re(),Ie(),Lt(),on()}},[g,Ot,_i,Ts]);let Ln=!!ft?.clientId,Qo=Array.isArray(ue),Aa=Qo&&ue.length>0,xs=Qo&&ue.includes("paypal"),Fa=(0,o.useRef)(null);Fa.current===null&&(Fa.current=(0,c.hasMatchingStripePayPalReturn)());let Io=Fa.current?"redirect":(0,zn.resolveStripePayPalPresentation)(fe,D,b.current()),{expressMethods:Ba,paymentElementMethods:Mi}=(0,o.useMemo)(()=>(0,c.partitionStripeMethods)(ue,{excludePaypal:Ln}),[ue,Ln]),As=Ln||!!nt||xs&&Io==="redirect",bc=(0,o.useMemo)(()=>As?Ba.filter(s=>s!=="paypal"):Ba,[Ba,As]),Cc=(0,o.useMemo)(()=>{let s=[];return ne&&s.push("apple_pay"),_e&&s.push("google_pay"),s},[ne,_e]),_o=Qo?bc:Cc,Sc=ee&&_o.length>0,Fs=mn?Ht:H,Da=(0,o.useMemo)(()=>(0,c.filterStripeMethodsByCountryGate)(Mi,Fs,F),[Mi,Fs,F]),xi=(0,o.useMemo)(()=>({mode:"payment",amount:Zo,currency:ko,paymentMethodCreation:"manual",appearance:ks}),[Zo,ko,ks]),[Bs,Ds]=(0,o.useState)("loading"),[Os,Ls]=(0,o.useState)("loading"),[Ns,Us]=(0,o.useState)("loading"),[wc,Ai]=(0,o.useState)(!1),[zs,Fi]=(0,o.useState)("loading"),[Bi,kc]=(0,o.useState)();(0,o.useEffect)(()=>{kc((0,Un.detectPayPalEnvironment)())},[]);let Oa=Bi?.inAppBrowser,La=Bi?(0,zn.resolvePayPalPresentationMode)(Bi,ft?.approvalPresentation,Y??(Ft?"subscription":"order")):"popup",qs=P&&(Ln||(Qo?xs:Oa===!1)),js=ee&&Sc,ea=(!Q||!!Ke.waitForDataAttachment)&&qs&&Ln,Vs=zs==="retrying"||zs==="exhausted",ta=null;ee&&(nt?ta=ws:Io==="redirect"&&(ta=Yr));let Ws=(0,o.useMemo)(()=>({...h,presentationMode:Io}),[h,Io]),ra=!Q&&qs&&!!ta&&(!Ln||Vs),To=!Q&&js&&!!Yr,na=!Q&&ee&&Aa&&Da.length>0&&!!Yr,Rc=ea&&!Vs?wc:ra&&es(Bs),Ec=To&&es(Os),Ic=na&&Ns!=="load_error",$s=s=>s==="loading"||s==="ready",Hs=ea||ra&&$s(Bs)||To&&$s(Os)||na&&Ns!=="load_error",Na=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(!Na.current){if(!ee&&!P){Na.current=!0;let s=new c.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(s),Ue(s.message)}else if(!ee&&P&&!Ln){Na.current=!0;let s=new c.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(s),Ue(s.message)}else if(Oa!==void 0&&!Q&&!Jt&&!Hs){Na.current=!0;let s=new c.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(s),Ue(s.message)}}},[ee,P,Ln,Oa,Q,Jt,Hs,u,Ue]);let Ks=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(Ks.current||!Aa)return;let s=[];ne!==!0&&s.push("showApplePay"),_e!==!0&&s.push("showGooglePay"),s.length!==0&&(Ks.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.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.`))},[Aa,ne,_e]);let Gs=(0,o.useCallback)((s,E)=>Ke.applyInlineSessionPatch?Ke.applyInlineSessionPatch(s).then(ae=>({error:null,sessionId:ae.sessionId||e,nonce:ae.session?.clientSecret||t})).catch(ae=>{let je=(0,c.normalizeBeforeButtonClickError)(E,ae);return Ue(je.message),u?.(je),{error:je,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ke.applyInlineSessionPatch,t,u,e,Ue]),Cn=(0,o.useCallback)(async s=>{if(s!=="card"&&Q&&await Ke.waitForDataAttachment?.(),!pe)return{proceed:!0};try{let E=await pe({method:s,sessionId:e||void 0,createSession:Ke.inlineSessionDraft});if(E===!1)return{proceed:!1};if(E&&typeof E=="object"){E.account&&Fr(je=>({...je??{},...E.account}));let ae=await Gs(E,s);return ae.error?{proceed:!1,accountPatch:E.account}:{proceed:!0,accountPatch:E.account,sessionId:ae.sessionId,nonce:ae.nonce}}return{proceed:!0}}catch(E){let ae=(0,c.normalizeBeforeButtonClickError)(s,E);return Ue(ae.message),u?.(ae),{proceed:!1}}},[Gs,Ke.inlineSessionDraft,Ke.waitForDataAttachment,Q,pe,u,e,Ue]),Ys=(0,o.useCallback)(async(s,E)=>{if(J.current)return;J.current=!0,Bt(!0),X("processing"),Ue(null);let ae=E?.sessionId??e,je=E?.nonce??t,re=Hi(vt,E?.accountPatch),Ie=E?.completionPaymentMethodId??pa(s),Lt=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,on=Bd(s),ht=E?.presentationMode?ri(Sr(Ee),{...h,presentationMode:E.presentationMode}):void 0,wt=()=>{Rt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:on}),ht?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...En,requestCategory:"process_payment"})};try{let Mt=new In.PaymentAPI(Tt),Wt=await Mt.processPayment(re.userId??"",{sessionId:ae,nonce:je,paymentMethodCategory:E?.paymentMethodCategory??Od(s),tokenizedData:Lt,accountData:{...E?.accountPatch,userId:re.userId??"",email:re.email??"",firstName:re.firstName||void 0,lastName:re.lastName||void 0,...(0,c.buildProcessPaymentAvsAccount)({avsConfig:De,country:Tr.current,zip:Rr.current,city:Xt.current,state:Dt.current,addressLine1:gr.current,addressLine2:mr.current})},...(0,c.buildCheckoutProcessMetadata)({chv:x,avsCheck:Ze,checkoutType:ze,checkoutLayout:He,avsConfig:De,country:Tr.current})}),yo=async br=>{let fo=(0,c.isAuthorizationOnlySession)(q)||br?.status==="authorized";(0,Rn.markSessionRecentlyCompleted)(ae),ht?.terminal({outcome:"payment_succeeded",...En}),X("success"),Xe(null),await new Promise(ca=>setTimeout(ca,600));let Nn;typeof br?.paymentId=="string"?Nn=br.paymentId:q?.paymentId&&(Nn=q.paymentId);let go;typeof br?.authorizationExpiresAt=="string"?go=br.authorizationExpiresAt:q?.authorizationExpiresAt&&(go=q.authorizationExpiresAt),l?.(fo?{status:"authorized",...Nn===void 0?{}:{paymentId:Nn},sessionId:typeof br?.sessionId=="string"?br.sessionId:ae,...go===void 0?{}:{authorizationExpiresAt:go},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Ie,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Ie,checkoutMethod:s.isPaypal?"paypal":"card"})};if(Wt.ok){await yo(Wt.status===204?null:await Wt.json().catch(()=>null));return}let Xr=await Wt.json().catch(()=>null);if(Xr?.type==="paypal_redirect_required"){let br=Xr.threeDSecureToken,fo=Xr.paymentMethodId||s.id||"";if(!Ee||!br){X("error"),Ue("PayPal authorization required but no token provided.");return}try{let Nn=nt?.getRawProvider();if(!Nn){Ue("PayPal is not available.");return}let go={return_url:window.location.href};fo&&(go.payment_method=fo);let{error:ca}=await Nn.confirmPayment({clientSecret:br,confirmParams:go,redirect:"if_required"});if(ca){X("error");let sl=ca.message??"PayPal payment failed.";Ue(sl),On("paypal",sl,{code:ca.code})}}catch(Nn){X("error"),Ue(Nn instanceof Error?Nn.message:"PayPal authorization failed.")}return}if(Xr?.type==="paypal_direct_required"){let br=Xr.orderId;if(!br){X("error"),Ue("PayPal retry required but no order id provided.");return}let fo=er.current?.attempts??0;if(fo>=2){X("error"),Ue("PayPal payment could not be completed after multiple attempts."),On("paypal","paypal_direct_required retry limit exceeded");return}Ai(!1),Fi("loading"),Xe({orderId:br,attempts:fo+1}),X(null);return}if(Wt.headers.get(Cd)===Sd){let br=await wd(Mt,ae,je);if(br!==void 0){await yo(br);return}}(0,c.classifyPaymentRejection)(Wt.status,Xr)?ht?.terminal({outcome:"payment_declined",...En,terminalReason:"provider_declined"}):wt(),X("error");let il=Xr?.message??"Payment failed. Please try again.";Ue(il),On(s.isPaypal?"paypal":"card",il,{code:Xr?.code??Xr?.gatewayErrorCode,declineCode:Xr?.declineCode??Xr?.gatewayDeclineReason}),await new Promise(br=>setTimeout(br,400))}catch(Mt){Gl(Mt)||wt(),X("error"),Ue(Mt instanceof Error?Mt.message:"An unexpected error occurred"),await new Promise(Wt=>setTimeout(Wt,400))}finally{Bt(!1),X(null),J.current=!1}},[Tt,e,t,vt,De,Ze,ze,He,x,Ee,nt,q,l,Ue,On,Rt,h]),jr=(0,o.useCallback)((s,E)=>{v?v(s):Ys(s,E)},[v,Ys]),oa=`${Hl}:${e}`;(0,o.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(oa);if(!s)return;let E;try{E=JSON.parse(s)}catch{ar(oa);return}if(!E||typeof E.createdAt!="number"||Date.now()-E.createdAt<0||Date.now()-E.createdAt>Kl||typeof E.paymentMethodId!="string"||typeof E.providerIntentId!="string"||typeof E.paymentMethodType!="string"||E.sessionId!==e||!t||E.nonce!==t||!_o.includes(E.paymentMethodType)){ar(oa);return}ar(oa),jr({id:E.paymentMethodId,type:"card",threeDSecureActionResultTokenId:E.providerIntentId,gateway:"stripe",paymentMethodType:E.paymentMethodType},{...E.accountPatch?{accountPatch:E.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[jr,t,e,oa,_o]);let Xs=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(typeof window>"u"||Xs.current)return;let[s,E,ae]=(0,c.readStripeRedirectParams)();if(!s||!E||Fa.current||!Ee)return;let je=Ee.getRawProvider();if(!je)return;let re=wt=>{let Mt=localStorage.getItem(wt);if(!Mt)return null;try{return JSON.parse(Mt)}catch{return ar(wt),null}},Ie=re(jn)??re(Dl),Lt;if(Ie?.clientSecret){if(Ie.clientSecret!==E)return;Lt={...Ie.accountPatch?{accountPatch:Ie.accountPatch}:{},...Ie.sessionId?{sessionId:Ie.sessionId}:{},...Ie.nonce?{nonce:Ie.nonce}:{}}}else if(Ie?.sessionId&&Ie.sessionId!==e)return;Xs.current=!0,ar(jn),ar(Dl),window.history.replaceState({},"",(0,c.stripeRedirectReturnUrl)());let on=Ie?.paymentMethodType??Ie?.tokenType??"card",ht="card";(async()=>{if(ae==="failed"){let Kn="Payment was declined. Please try again.";Ue(Kn),On(ht,Kn);return}let{paymentIntent:wt,error:Mt}=await je.retrievePaymentIntent(E);if(Mt){let Kn=Mt.message??"Failed to retrieve payment status.";Ue(Kn),On(ht,Kn,{code:Mt.code});return}let Wt=wt?.status,yo=ua(Wt);if(!wt||!yo){let Kn=Wt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ue(Kn),On(ht,Kn,{code:Wt??"missing_payment_intent"});return}let Xr=typeof wt.payment_method=="string"?wt.payment_method:wt.payment_method?.id;jr({id:Xr??Ie?.paymentMethodId??Ie?.tokenId??wt.id,type:"card",threeDSecureActionResultTokenId:wt.id,gateway:Ie?.gateway??"stripe",paymentMethodType:on},Lt)})()},[e,jr,Ee,Ue,On]);let Di=(0,o.useCallback)(s=>{s.preventDefault()},[]);if(!(g||Ee!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let aa=ie==="buttons",Vr=oe?.variables,_c=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Oi=Vr?.colorBackground,Tc=Oi&&!_c.has(Oi)?Oi:void 0,ia=U.cardInputBorder??(aa?"#e5e7eb":"#A4A4FF"),Js=Vr?.colorDanger??"#dc2626",tr=s=>fn[s]&&(Bn[s]||Zt),Ua=wo&&(Fn||Zt),nn=s=>s?Js:ia,za=(Hr.malformed||Hr.empty)&&(An||Zt),Mc=nn(za),Li=U.cardFormContainer?.backgroundColor??Tc??(aa?"white":"#EDEDFF"),Mo=U.cardInputBackground??Vr?.colorBackground??"white",Ni=Fo(we),Zs=Fo(xe),xo=U.nameInput,Qs=U.cardInputFontSize??zd(xo?.fontSize)??Vr?.fontSizeBase??"16px",el=typeof xo?.fontFamily=="string"?xo.fontFamily:Vr?.fontFamily??"Poppins, sans-serif",tl=(0,c.toCssWeight)(xo?.fontWeight)??400,xc=U.cardInputColor??(typeof xo?.color=="string"?xo.color:void 0)??Vr?.colorText??"#262833",Ac=U.cardInputPlaceholderColor??"#9ca3af",nr=Vr?.borderRadius??"8px",po=Vr?.borderRadius??U.cardButton?.borderRadius??nr,mo=Vr?.colorPrimary??"#4A49FF",Fc=Vr?.colorPrimaryHover??(0,c.darkenHex)(mo,.12),Ui=Vr?.colorText??"#262833",zi={fontSize:Qs,fontFamily:el,fontWeight:tl,color:xc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},sa={marginTop:"0.375rem",...zi,fontSize:"0.75rem",lineHeight:1.4,color:Js},Bc={"--flopay-input-placeholder-color":Ac,"--flopay-input-font-size":Qs,"--flopay-input-font-family":el,"--flopay-input-font-weight":String(tl)},la=U.cardFormContainer??{},qi=la.padding??(aa?"0":"1rem"),ji=la.borderRadius??nr,Dc=Ot&&Pn?(0,d.jsx)(lo,{capture:Ot,html:Pn.html,messageToken:Pn.messageToken,expectedOrigin:Pn.expectedOrigin,verificationRequired:Pn.verificationRequired,theme:gt,submitLabel:T,onReady:()=>{if(!ao&&!De||typeof document>"u")return;let s=()=>{let ae=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(ae){Kr.current=!0;try{ae.focus()}finally{Kr.current=!1}}};hn.current||s()},onError:s=>{s&&Pn.verificationRequired&&m.current==="idle"&&(oo.current=!0),Ue(s)},onValidation:s=>{let E=m.current;(E==="idle"||E==="validation-window")&&(Ue(s),s&&m.current==="validation-window"&&($.current&&(clearTimeout($.current),$.current=null),m.current="idle",X(null)))}},yr):(0,d.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),rl=(0,d.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&Hn()},style:{backgroundColor:Li,borderRadius:ji,...la,padding:qi,...Bc,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${xe.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),aa&&no&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:f?-2:0},children:[(0,c.jsxs)("button",{type:"button",onClick:Pe,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:O.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...O.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...O.backButtonIcon},children:(0,c.jsx)("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:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(Do,{content:be})]}),Zs?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:O.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...O.title},children:(0,c.jsx)(da,{content:Me})})]}),!aa&&!Zs&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ui,order:f?-3:0,...O.title},children:(0,c.jsx)(da,{content:Me})}),f&&fe&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:fe}),f&&ao&&(0,c.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,c.jsx)("div",{style:{backgroundColor:Mo,border:`1px solid ${rn(Ua)}`,borderRadius:tr,padding:"10px"},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:ir,onChange:s=>{Nt("email"),yr.current=s.target.value,un(s.target.value)},onPointerDown:()=>Nt("email"),onKeyDown:()=>Nt("email"),onBlur:()=>{Yr("email")&&en(!0),wo||_i()},disabled:et,required:!0,"aria-invalid":Ua||void 0,"aria-describedby":Ua?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...zi}})}),Ua&&(0,c.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:sa,children:ki.empty?"Email address is required":"Enter a valid email address"})]}),Fe&&(0,c.jsx)("div",{style:{order:f?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Kt,k=(te=!1)=>({backgroundColor:Mo,border:`1px solid ${rn(te)}`,borderRadius:tr,marginTop:"0.5rem",padding:"10px"}),le=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...zi}),Ve=(0,d.getStateOptions)(s);return(0,c.jsxs)(c.Fragment,{children:[(0,d.isAVSFieldVisible)(Fe.address_line_1,s)&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{style:k(Zt("line1")),children:(0,c.jsx)("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:Lt,onChange:te=>{Nt("line1"),jt.current.addressLine1=!0,gr.current=te.target.value,yt(te.target.value)},onPointerDown:()=>Nt("line1"),onKeyDown:()=>Nt("line1"),onBlur:()=>xr("line1"),disabled:et,required:!0,"aria-invalid":Zt("line1")||void 0,"aria-describedby":Zt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:le()})}),Zt("line1")&&(0,c.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:sa,children:"Street address is required"})]}),(0,d.isAVSFieldVisible)(Fe.address_line_2,s)&&(0,c.jsx)("div",{style:k(),children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:st,onChange:te=>{jt.current.addressLine2=!0,Vt.current=te.target.value,Br(te.target.value)},disabled:et,"data-testid":"flopay-address-line2",style:le()})}),((0,d.isAVSFieldVisible)(Fe.city,s)||(0,d.isAVSFieldVisible)(Fe.state,s))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Fe.city,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Mo,borderTop:`1px solid ${rn(Zt("city"))}`,borderRight:`1px solid ${rn(Zt("city"))}`,borderBottom:`1px solid ${rn(Zt("city"))}`,borderLeft:`1px solid ${rn(Zt("city"))}`,padding:"10px",borderTopLeftRadius:tr,borderBottomLeftRadius:tr,...(0,d.isAVSFieldVisible)(Fe.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:tr}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Bt,onChange:te=>{Nt("city"),jt.current.city=!0,kr.current=te.target.value,Wr(te.target.value)},onPointerDown:()=>Nt("city"),onKeyDown:()=>Nt("city"),onBlur:()=>xr("city"),disabled:et,required:!0,"aria-invalid":Zt("city")||void 0,"aria-describedby":Zt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:le()})}),(0,d.isAVSFieldVisible)(Fe.state,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Mo,borderTop:`1px solid ${rn(Zt("state"))}`,borderRight:`1px solid ${rn(Zt("state"))}`,borderBottom:`1px solid ${rn(Zt("state"))}`,borderLeft:`1px solid ${rn(Zt("state"))}`,padding:"10px",borderTopRightRadius:tr,borderBottomRightRadius:tr,...(0,d.isAVSFieldVisible)(Fe.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${rn(Zt("state")||Zt("city"))}`}:{borderRadius:tr}},children:Ve?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:wr,onChange:te=>{Nt("state"),jt.current.state=!0,$t.current=te.target.value,Gt(te.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>xr("state"),disabled:et,autoComplete:"billing address-level1",required:!0,"aria-invalid":Zt("state")||void 0,"aria-describedby":Zt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...le(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,d.getStateLabel)(s)}),Ve.map(te=>(0,c.jsx)("option",{value:te.code,children:te.name},te.code))]}):(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,d.getStateLabel)(s),autoComplete:"billing address-level1",value:wr,onChange:te=>{Nt("state"),jt.current.state=!0,$t.current=te.target.value,Gt(te.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>xr("state"),disabled:et,required:!0,"aria-invalid":Zt("state")||void 0,"aria-describedby":Zt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:le()})})]}),Zt("city")&&(0,c.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:sa,children:"City is required"}),Zt("state")&&(0,c.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:sa,children:[(0,d.getStateLabel)(s)," is required"]}),((0,d.isAVSFieldVisible)(Fe.country,s)||(0,d.isAVSFieldVisible)(Fe.postal_code,s))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:j==="column"?"column":"row",gap:j==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Fe.country,s)&&(0,c.jsx)("div",{style:{flex:j==="row"?1:void 0,backgroundColor:Mo,borderTop:`1px solid ${ia}`,borderRight:`1px solid ${ia}`,borderBottom:`1px solid ${ia}`,borderLeft:`1px solid ${ia}`,padding:"10px",...j==="row"&&(0,d.isAVSFieldVisible)(Fe.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:tr,borderBottomLeftRadius:tr,borderRight:"none"}:{borderRadius:tr}},children:(0,c.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Kt,onChange:te=>{jt.current.country=!0,Tr.current=te.target.value,Vr(te.target.value),ge?.(te.target.value),$t.current="",Gt("")},disabled:et,autoComplete:"billing country","data-testid":"flopay-country",style:{...le(),cursor:"pointer"},children:[Kt===""?(0,c.jsx)("option",{value:"",children:"Select country"}):null,d.COUNTRY_OPTIONS.map(te=>(0,c.jsxs)("option",{value:te.code,children:[te.flag," ",te.name]},te.code))]})}),(0,d.isAVSFieldVisible)(Fe.postal_code,s)&&(0,c.jsx)("div",{style:{flex:j==="row"?1:void 0,backgroundColor:Mo,border:`1px solid ${Mc}`,padding:"10px",...j==="row"&&(0,d.isAVSFieldVisible)(Fe.country,s)?{borderRadius:"0",borderTopRightRadius:tr,borderBottomRightRadius:tr}:{borderRadius:tr}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,d.getPostalCodeLabel)(Kt),autoComplete:"billing postal-code",value:$r,onChange:te=>{Nt("zip"),jt.current.zip=!0,qt.current=te.target.value,Er(te.target.value),Be?.(te.target.value)},onPointerDown:()=>Nt("zip"),onKeyDown:()=>Nt("zip"),onBlur:()=>{Yr("zip")&&Lr(!0)},disabled:et,required:Kr.required,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:le()})})]}),za&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:sa,children:Kr.empty?`${(0,d.getPostalCodeLabel)(s)} is required`:Ld(s)})]})})()}),f&&Dc,St&&(0,c.jsx)(Vo,{margin:"0.75rem 0",styleOverride:O.errorBanner,children:St})]}),qa={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"},nl=s=>G?!P||!Ln?(0,c.jsx)("pre",{"data-testid":s,style:qa,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:qa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${P}`,` directPaypalConfigured=${Ln}`,` inAppBrowserDetected=${String(Oa)}`,` shouldRenderDirectPayPal=${ea}`,` shouldRenderStripePayPal=${ra}`,` hasPaypalStripeInstance=${!!ws}`].join(`
39
- `)}):null,ol=s=>G?!ee||!Xr?(0,c.jsx)("pre",{"data-testid":s,style:qa,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:qa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${ee}`,` currency=${Et}`,` amountInCents=${Zo}`,` enabledPaymentMethods: ${JSON.stringify(ue??[])}`,` enabledPaymentMethodsProvided=${Qo}`,` hasEnabledMethods=${Aa}`,` expressMethods: ${JSON.stringify(Ba)}`,` walletExpressMethods: ${JSON.stringify(_o)}`,` paymentElementMethods: ${JSON.stringify(Mi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Da)}`,` hasStripeInstance=${!!Xr}`,` shouldRenderWallets=${To}`,` shouldRenderPaymentElement=${na}`].join(`
40
- `)}):null,al=Ct==="apm-expanding"||Ct==="apm-form"||Ct==="apm-collapsing",Ao;Ct==="apm-expanding"?Ao=Ul:Ct==="apm-collapsing"&&(Ao=zl);let ja=hr?Xl(xi,hr,De):null;if(pe==="buttons"){let s=Ct==="buttons"||Ct==="expanding"||Ct==="apm-expanding",k=Ct==="expanding"||Ct==="card"||Ct==="collapsing",le=ct===void 0?{boxSizing:"border-box",height:Go,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ve;Ct==="expanding"||Ct==="apm-expanding"?Ve=Fd:(Ct==="collapsing"||Ct==="apm-collapsing")&&(Ve=Ad);let te;return Ct==="expanding"?te=Ul:Ct==="collapsing"&&(te=zl),(0,c.jsxs)("form",{onSubmit:Di,className:K,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Yo,{}),ze&&(0,c.jsx)(qr,{status:ze,errorMessage:St,authorized:yn}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Ve?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Ve?Dd:{},...Ve?{animation:Ve,pointerEvents:"none"}:{}},children:[nl("flopay-direct-paypal-gate-debug"),ol("flopay-stripe-gate-debug"),ea&&kt&&(0,c.jsxs)(c.Fragment,{children:[Le&&(0,c.jsx)("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."}),(0,c.jsx)(ma.Provider,{value:y,children:(0,c.jsx)(ga,{sessionId:e,nonce:t,billingApiUrl:Oe,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:nt,clientId:kt.clientId,environment:kt.environment,currency:Et.toUpperCase(),isSubscription:Tt,providerObjectType:it,approvalPresentation:La==="popup"?void 0:La,onTokenizedBody:Ur,onComplete:l,onErrorChange:qe,onDecline:p,onTechnicalFailure:Eo,onButtonClick:Z,runBeforeButtonClick:Sn,isProcessing:et,onLoadStateChange:Ai,onInitializationStateChange:Fi,session:Rt,existingOrderId:Le?.orderId,debug:G},Le?.orderId??"fresh")})]}),ra&&(0,c.jsx)(rr.Elements,{stripe:ta,options:Es,children:(0,c.jsx)(jl,{sessionId:e,nonce:t,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:nt,billingApiUrl:Oe,onTokenizedBody:Ur,onErrorChange:qe,isProcessing:et,onButtonClick:Z,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:Sn,onLoadStateChange:Ds,placeholderBorderRadius:po,popupCapabilityOwner:y,externalTelemetryContext:$s,presentationMode:Io})}),To?(0,c.jsx)(rr.Elements,{stripe:Xr,options:Rs,children:(0,c.jsx)($l,{sessionId:e,nonce:t,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:nt,billingApiUrl:Oe,intentKind:Je>0?"payment":"setup",expressMethods:_o,onTokenizedBody:Ur,onErrorChange:qe,onButtonClick:Z,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:Sn,onLoadStateChange:Ls,placeholderBorderRadius:po,popupCapabilityOwner:y,externalTelemetryContext:me})}):null,!To&&js?(0,c.jsx)("div",{style:{height:Go,borderRadius:po,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,na&&(0,c.jsx)(Wl,{sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:nt,billingApiUrl:Oe,paymentElementMethods:Da,stripeInstance:Xr,paymentElementBaseOptions:xi,futureUseSession:De,onTokenizedBody:Ur,onErrorChange:qe,onButtonClick:Z,onDecline:p,runBeforeButtonClick:Sn,onLoadStateChange:Us,isProcessing:et,submitButtonColor:yo,submitButtonBorderRadius:tr,submitButtonStyle:O.submitButton,onExpandApm:It,expandedApmMethod:hr,themeId:We,buttonAppearance:{backgroundColor:O.cardButton?.backgroundColor,borderColor:O.cardInputBorder,textColor:O.cardButton?.color,borderRadius:po}}),f&&(0,c.jsx)("button",{type:"button",onClick:async()=>{et||!(await Sn("card")).proceed||(Z?.("card"),ie())},disabled:et,style:{width:"100%",...le,...O.cardButton,...ds({themeBundle:ve,resolvedPrimaryColor:yo,resolvedBorderRadius:tr,submitButtonStyle:O.submitButton,explicitPrimaryColor:zr?.colorPrimary}),fontSize:O.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:et?"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:et?.6:1},onMouseEnter:Re=>{!et&&(ve||zr?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=Fc)},onMouseLeave:Re=>{(ve||zr?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=yo)},onMouseDown:Re=>{Re.currentTarget.style.transform="scale(0.985)"},onMouseUp:Re=>{Re.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(Bo,{content:ct})}),St&&Ct==="buttons"&&(0,c.jsx)(Vo,{margin:"0.25rem 0",styleOverride:O.errorBanner,children:St})]}),f&&k&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...te?{animation:te}:{},...Ct==="collapsing"?{pointerEvents:"none"}:{}},children:rl}),ee&&al&&hr&&ja&&Xr&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Ao?{animation:Ao}:{},...Ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Li,borderRadius:ji,...la,padding:qi},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Xt,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:O.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...O.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...O.backButtonIcon},children:(0,c.jsx)("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:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(Do,{content:be})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:O.titleFontSize??"1.05rem",color:Ui,paddingRight:80,...O.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(hr)}`})]}),(0,c.jsx)(rr.Elements,{stripe:Xr,options:ja,children:(0,c.jsx)(ss,{method:hr,sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:nt,billingApiUrl:Oe,onTokenizedBody:Ur,onErrorChange:qe,onDecline:p,onCancel:Xt,runBeforeButtonClick:Sn,onButtonClick:Z,isProcessing:et,submitButtonColor:yo,submitButtonBorderRadius:tr,submitButtonStyle:O.submitButton,errorText:St})},hr)]})})]})]})}return al&&hr&&ja&&Xr&&ee?(0,c.jsxs)("form",{onSubmit:Di,className:K,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Yo,{}),ze&&(0,c.jsx)(qr,{status:ze,errorMessage:St,authorized:yn}),(0,c.jsx)("div",{style:{...Ao?{animation:Ao}:{},...Ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Li,borderRadius:ji,...la,padding:qi},children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,c.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Xt,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:O.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...O.backButton},"aria-label":"Back to payment methods",children:[(0,c.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...O.backButtonIcon},children:(0,c.jsx)("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:(0,c.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,c.jsx)(Do,{content:be})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:O.titleFontSize??"1.05rem",color:Ui,paddingRight:80,...O.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(hr)}`})]}),(0,c.jsx)(rr.Elements,{stripe:Xr,options:ja,children:(0,c.jsx)(ss,{method:hr,sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:nt,billingApiUrl:Oe,onTokenizedBody:Ur,onErrorChange:qe,onDecline:p,onCancel:Xt,runBeforeButtonClick:Sn,onButtonClick:Z,isProcessing:et,submitButtonColor:yo,submitButtonBorderRadius:tr,submitButtonStyle:O.submitButton,errorText:St})},hr)]})})]}):(0,c.jsxs)("form",{onSubmit:Di,className:K,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Yo,{}),ze&&(0,c.jsx)(qr,{status:ze,errorMessage:St,authorized:yn}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[nl("flopay-direct-paypal-gate-debug-default"),ol("flopay-stripe-gate-debug-default"),ea&&kt&&(0,c.jsxs)(c.Fragment,{children:[Le&&(0,c.jsx)("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."}),(0,c.jsx)(ma.Provider,{value:y,children:(0,c.jsx)(ga,{sessionId:e,nonce:t,billingApiUrl:Oe,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:nt,clientId:kt.clientId,environment:kt.environment,currency:Et.toUpperCase(),isSubscription:Tt,providerObjectType:it,approvalPresentation:La==="popup"?void 0:La,onTokenizedBody:Ur,onComplete:l,onErrorChange:qe,onDecline:p,onTechnicalFailure:Eo,onButtonClick:Z,runBeforeButtonClick:Sn,isProcessing:et,onLoadStateChange:Ai,onInitializationStateChange:Fi,session:Rt,existingOrderId:Le?.orderId,debug:G},Le?.orderId??"fresh")})]}),ra&&(0,c.jsx)(rr.Elements,{stripe:ta,options:Es,children:(0,c.jsx)(jl,{sessionId:e,nonce:t,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:nt,billingApiUrl:Oe,onTokenizedBody:Ur,onErrorChange:qe,isProcessing:et,onButtonClick:Z,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:Sn,onLoadStateChange:Ds,placeholderBorderRadius:po,popupCapabilityOwner:y,externalTelemetryContext:$s,presentationMode:Io})}),To&&(0,c.jsx)(rr.Elements,{stripe:Xr,options:Rs,children:(0,c.jsx)($l,{sessionId:e,nonce:t,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:nt,billingApiUrl:Oe,intentKind:Je>0?"payment":"setup",expressMethods:_o,onTokenizedBody:Ur,onErrorChange:qe,onButtonClick:Z,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:Sn,onLoadStateChange:Ls,placeholderBorderRadius:po,popupCapabilityOwner:y,externalTelemetryContext:me})}),na&&(0,c.jsx)(Wl,{sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Oe,paymentElementMethods:Da,stripeInstance:Xr,paymentElementBaseOptions:xi,futureUseSession:De,onTokenizedBody:Ur,onErrorChange:qe,onButtonClick:Z,onDecline:p,runBeforeButtonClick:Sn,onLoadStateChange:Us,isProcessing:et,submitButtonColor:yo,submitButtonBorderRadius:tr,submitButtonStyle:O.submitButton,themeId:We,onExpandApm:It,expandedApmMethod:hr,buttonAppearance:{backgroundColor:O.cardButton?.backgroundColor,borderColor:O.cardInputBorder,textColor:O.cardButton?.color,borderRadius:po}})]}),f&&(Ec||Rc||Ic)&&(0,c.jsx)(li,{label:"or pay with card"}),f&&rl]})}var x=require("react/jsx-runtime"),Xo=44,hs="flopay_checkout_saved_payment_resume",hi=new Map,fi=new Map;function Jl(e,t){t.settled&&t.consumers===0&&hi.get(e)===t&&hi.delete(e)}function jd(e,t,r){let n=fi.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let o=r(),i={attempt:o,sdkGeneratedIdempotencyKey:t};fi.set(e,i);let l=()=>{fi.get(e)===i&&fi.delete(e)};return o.then(l,l),o}function _a(e){return new Promise(t=>setTimeout(t,e))}function gi(e,t,r){let n=Xa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:$e.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Ta(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ps(e,t,r,n,o,i){let l=gi(e,t,r);l.error({errorCode:n,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),Ta(l)}function Zl(e,t,r,n){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()-r),durationMode:"machine",requestCategory:t,...n===void 0?{}:{attempt:n},statusClass:"2xx"})}function Ql(e,t,r,n,o){let i=(0,$e.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:o,statusClass:i.statusClass}),t instanceof $e.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof $e.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...i,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function ys(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,$e.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var Vd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function $d(e){return new eo.FloPay(Vd,{publishableKey:"provider_unavailable",...e})}async function ms(e,t){let{publishableKey:r,paypalPublishableKey:n}=Zi(e);return{...await Qi({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Ps(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Wd(){if(!Ps())return null;try{let e=window.sessionStorage.getItem(hs);return e?JSON.parse(e):null}catch{return null}}function ec(e){if(Ps())try{window.sessionStorage.setItem(hs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function fs(){if(Ps())try{window.sessionStorage.removeItem(hs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Hd(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],r=!1;for(let n of t)e.searchParams.has(n)&&(e.searchParams.delete(n),r=!0);r&&window.history.replaceState(window.history.state,"",e.toString())}function tc(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 gs(e,t){return(0,$e.resolveCheckoutLogLayout)(!!e,t)}function Kd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function rc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Gd(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 Pi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:o,appearance:i,locale:l,loading:u,error:p,onComplete:C,onError:w,onInstrument:S,onDecline:_,onCountryChange:K,onZipChange:I,showPayPal:$=!0,showStripe:T=!0,walletPresentation:h="auto",enabledPaymentMethods:P,showApplePay:ee=!0,showGooglePay:A=!0,debug:ue=!1,layout:F,theme:re,buttonsTheme:Ee,buttonsStyles:pe,cardButtonContent:We,cardBackButtonContent:wt,cardTitleContent:ce,showSecurityFooter:Y,onButtonClick:ct,onBeforeButtonClick:be,enableAVS:Me,cardFieldOrder:Se,cardPreFormSlot:Z,avsLayout:de,submitLabel:ye,className:Ie,initialErrorMessage:_e=null,initialPayPalOrderId:fe,children:j,checkoutMode:L,confirmLabel:we,renderConfirmButton:Ne,onSessionCompleted:ke}){let N=(0,$e.resolveBillingApiUrl)(n),dt=(0,b.useMemo)(()=>(0,$e.resolveTheme)(re),[re]),ge=i??dt?.appearance,Be=r?"embedded_checkout":"standard_checkout",Xe=gs(j,F),[Ae,at]=(0,b.useState)(null),[Je,Et]=(0,b.useState)(null),zt=(0,b.useRef)(null),kt=(0,b.useRef)(null),Tt=(0,b.useRef)(0),[U,he]=(0,b.useState)(null),Ze=(0,b.useRef)(null),[G,je]=(0,b.useState)(null),ht=(0,b.useMemo)(()=>r?(0,ut.serializeCreateParams)(r):"",[r]),Qe=r?`create:${ht}`:`session:${e??""}`,At=rc(G),V=(0,b.useRef)(new Set),y=(0,b.useRef)(Qe),v=(0,b.useRef)(Qe);Po(()=>{v.current=Qe,y.current!==Qe&&(y.current=Qe,V.current.clear())},[Qe]);let W=(0,b.useCallback)(q=>{if(v.current===Qe){if(Yi.FLO_INSTRUMENT_ONCE_NAMES.has(q.name)){if(V.current.has(q.name))return;V.current.add(q.name)}(0,tt.invokeMerchantCallback)(()=>S?.(q))}},[Qe,S]),z=jo(W,Qe),me=(0,b.useRef)(!1),Rt=(0,b.useCallback)(q=>{if(me.current)return;let B=q.gateway||!At?q:{...q,gateway:At};W(B)},[W,At]);(0,b.useEffect)(()=>{z({class:"lifecycle",name:"checkout.mount"})},[z]);let[De,it]=(0,b.useState)(e??""),ne=e??De,D=r?"":ne,[Q,xe]=(0,b.useState)(!0),[Oe,M]=(0,b.useState)(null),[Ft,Qt]=(0,b.useState)(0),[ar,Kt]=(0,b.useState)("full"),[Vr,$r]=(0,b.useState)(!1),[Er,Lt]=(0,b.useState)(_e),[yt,st]=(0,b.useState)(null),[Br,Bt]=(0,b.useState)(null),[Wr,wr]=(0,b.useState)(!1),[Gt,ir]=(0,b.useState)(void 0),[un,Qr]=(0,b.useState)(""),[sr,qt]=(0,b.useState)(!1),[Tr,gr]=(0,b.useState)(!1),[Vt,kr]=(0,b.useState)(!1),$t=(0,b.useRef)(null),yr=(0,b.useRef)(0),jt=(0,b.useRef)(void 0),[Fe,pn]=(0,b.useState)("loading"),[yn,mn]=(0,b.useState)(0),lr=(0,b.useRef)(!1),Dr=(0,b.useRef)(!1),Mr=(0,b.useRef)(!1),Ue=(0,b.useRef)(null),vt=(0,b.useRef)(null),f=(0,b.useMemo)(()=>({checkoutMode:L??ar,layout:Kd(j,F)}),[L,j,ar,F]),rt=(0,b.useRef)(C);rt.current=C;let oe=(0,b.useRef)(w);oe.current=w;let Ir=(0,b.useRef)(_);Ir.current=_;let Hr=(0,b.useCallback)(q=>Qa(Ue,async B=>{try{return await q(B)}catch(ie){throw B.aborted?$o(ie):ie}}),[]);(0,b.useEffect)(()=>()=>{Ue.current?.abort(),Ue.current=null},[]);let er=(0,b.useCallback)((q,B)=>{zt.current=q,Et(q),Ze.current=B,he(B)},[]),Or=(0,b.useCallback)(()=>{let q=kt.current;q&&(kt.current=null,q.destroy())},[]);(0,b.useEffect)(()=>{Cr(Je)?.setCheckoutContext(f),U&&U!==Je&&Cr(U)?.setCheckoutContext(f)},[Je,U,f]);let bt=(0,b.useRef)(ke);bt.current=ke;let Mn=(0,b.useCallback)(q=>{pn(q),!(q!=="exhausted"||Mr.current)&&(Mr.current=!0,oe.current?.(new $e.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),ro=(0,b.useCallback)(()=>{pn("retrying"),mn(q=>q+1)},[]);(0,b.useEffect)(()=>{pn("loading"),mn(0),Mr.current=!1},[ne]),(0,b.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:$e.SDK_VERSION,checkout_type:Be,checkout_layout:Xe,billing_api_url:N})},[Xe,Be,N]);let Dt=(0,b.useMemo)(()=>r?(0,ut.serializeCreateParams)(r,!0):"",[r]),Kr=(0,b.useMemo)(()=>un===Dt?Gt:void 0,[Gt,un,Dt]),fn=(0,b.useMemo)(()=>r?Wi(r,Kr):void 0,[r,Kr]),gn=L??fn?.checkoutMode??"full",Yt=(0,b.useMemo)(()=>fn?{...fn,checkoutMode:gn}:void 0,[fn,gn]);(0,b.useEffect)(()=>{ir(void 0),Qr(Dt),jt.current=void 0,$t.current=null,kr(!1)},[Dt]),(0,b.useEffect)(()=>{Lt(_e)},[_e]);let xn=(0,b.useCallback)((q,B,ie)=>{(0,tt.invokeMerchantCallback)(()=>{Ir.current?.(vr(q,B,ie))})},[]),An=(0,b.useCallback)(async(q,B)=>{Lt(null),Bt(null),wr(!1),st("processing");let ie=B?.sessionId??q.id,Pe=q.clientSecret||t,It=rc(q),Xt=zt.current??Ze.current,ze=Cr(Xt),X=Xt?null:gi(N,o,f),J={log:Te=>{ze?ze.log(Te):X?.log(Te)},error:Te=>{ze?ze.error(Te):X?.error(Te)},terminal:Te=>{ze?ze.terminal(Te):X?.terminal(Te)},performance:Te=>{ze?ze.performance(Te):X?.performance(Te)},now:()=>ze?.now()??X?.now()??0,elapsed:Te=>ze?.elapsed(Te)??Math.max(0,(X?.now()??Te)-Te)},H=J.now(),m=!!(B?.initialAutoProcessingError||B?.initialAutoProcessingPending),g=!1,R,se=()=>{g||(g=!0,m=!0,R=J.now(),J.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),J.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Le=!1,Ke=()=>{Le||(Le=!0,J.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),J.performance({stage:"processing",durationMs:J.elapsed(H),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),R!==void 0&&J.performance({stage:"recovery",durationMs:J.elapsed(R),durationMode:"machine",paymentMethodCategory:"saved"}))};J.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),me.current=!0;try{J.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{me.current=!1}z({class:"lifecycle",name:"payment.processing.started",provider:It}),m&&se();let Jt;try{let Te=Tl(B?.initialAutoProcessingError),Ye=B?.initialAutoProcessingError?.type==="3ds_required"&&!B.initialAutoProcessingError.threeDSecureToken&&B.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:B.initialAutoProcessingError.nextActionRedirectUrl}:null,nt,St=ve=>(se(),Hr(O=>Wo(ve,{billingApiUrl:N,sessionId:ie,nonce:Pe,session:q,signal:O})));if(Ye)nt=await St(Ye);else if(Te)se(),Te.type==="paypal_redirect_required"&&vt.current?.publishableKey&&ec({sessionId:ie,publishableKey:vt.current.publishableKey,paypalPublishableKey:vt.current.paypalPublishableKey}),nt=await Hr(ve=>ti(Te,{flopay:zt.current,paypalFlopay:Ze.current,attempt3DS:B?.attempt3DS,billingApiUrl:N,sessionId:ie,session:q,telemetry:!1,signal:ve})),Te.type==="paypal_redirect_required"&&fs();else if(B?.initialAutoProcessingPending){let ve=B.initialAutoProcessingPending,O=new eo.PaymentAPI(N,{telemetry:!1}),ae=await Hr(et=>O.waitForCheckoutSessionCompletion(ve.sessionId,{initialDelayMs:ve.retryAfterMs,nonce:Pe,statusUrl:ve.statusUrl,signal:et})),mt=so(ae,q),He=ae.autoProcessingError?.type==="3ds_required"&&ae.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ae.autoProcessingError.nextActionRedirectUrl}:null;if(He)nt=await St(He);else{if(!Yn(mt))throw Lo(mt);nt=Gn(mt,ie)}}else{if(B?.initialAutoProcessingError)throw qn(B.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:B.initialAutoProcessingError.checkoutMethod});if(B?.fromCreateSession)return B?.fallbackToFull&&(Kt("full"),tc("full")),!1;{let ve=await Ho({billingApiUrl:N,sessionId:ie,session:q,nonce:Pe,telemetry:!1});ve.type==="success"?nt=ve.result:ve.type==="next_action_required"?nt=await St(ve):(se(),ve.type==="paypal_redirect_required"&&vt.current?.publishableKey&&ec({sessionId:ie,publishableKey:vt.current.publishableKey,paypalPublishableKey:vt.current.paypalPublishableKey}),nt=await Hr(O=>ti(ve,{flopay:zt.current,paypalFlopay:Ze.current,attempt3DS:B?.attempt3DS,billingApiUrl:N,sessionId:ie,session:q,telemetry:!1,signal:O})),ve.type==="paypal_redirect_required"&&fs())}}ie&&(0,In.markSessionRecentlyCompleted)(ie),Ke(),m&&(J.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),J.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),J.terminal({outcome:nt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),wr(nt.status==="authorized"),st("success"),await _a(600),Jt=()=>rt.current?.(nt)}catch(Te){let Ye=io(ba(Te),ie);if(Ye.code==="three_ds_aborted")return!1;let nt=Ye.checkoutMethod??Ca;Lt(Ye.message),Bt(Ye.message),wr(!1),B?.fallbackToFull&&(J.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Kt("full"),tc("full")),Ke();let St=Ye.statusCode===void 0?void 0:(0,$e.telemetryStatusClass)(Ye.statusCode,"unknown"),ve=St==="4xx"?{requestCategory:"process_payment",statusClass:St}:{},O=St===void 0||St==="4xx";if(O&&(Ye.telemetryOutcome==="payment_declined"||!!(Ye.declineCode||Ye.code?.toLowerCase().includes("declin"))))J.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ve});else if(O&&(Ye.telemetryOutcome==="validation_rejected"||Ye.type==="validation_error"))J.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ve});else{let He=(0,$e.classifyTelemetryFailure)(Te,m?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),et=Ye.telemetryRequestCategory??"process_payment";me.current=!0;try{J.error({...He,...Ye.telemetryFailureCategory?{failureCategory:Ye.telemetryFailureCategory}:{},stage:m?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:et})}finally{me.current=!1}z({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:et,provider:It})}return(0,tt.invokeMerchantCallback)(()=>oe.current?.(Ye)),xn(nt,Ye,{code:Ye.code,declineCode:Ye.declineCode}),st("error"),await Promise.allSettled([_a(400),B?.ensureProvidersReady?B.ensureProvidersReady():Promise.resolve()]),m&&(J.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),J.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ke(),X&&Ta(X),st(null),Bt(null)}return(0,tt.invokeMerchantCallback)(Jt),!0},[xn,z,t,N,Hr,o,f]);(0,b.useEffect)(()=>{if(typeof window>"u"||Dr.current)return;let q=new URLSearchParams(window.location.search),B=q.get("payment_intent_client_secret");if(!B)return;let ie=Wd();ie&&(Dr.current=!0,(async()=>{let Pe,It=0;Lt(null),Bt(null),st("processing"),$r(!0);try{if(q.get("redirect_status")==="failed")throw Object.assign(new $e.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Xt,paypalFlopay:ze}=await Qi({publishableKey:ie.publishableKey,paypalPublishableKey:ie.paypalPublishableKey,billingApiUrl:N,locale:l,telemetry:o});Pe=Cr(ze??Xt),Pe?.setCheckoutContext(f),It=Pe?.now()??0,Pe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let X=(ze??Xt)?.getRawProvider();if(!X)throw Object.assign(new $e.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:J,error:H}=await X.retrievePaymentIntent(B);if(H)throw Object.assign(new $e.FloPayError(H.message??"Failed to retrieve PayPal payment status.","api_error",{code:H.code}),{checkoutMethod:"paypal"});let m=fl(J?.status);if(!J||m==="failed")throw Object.assign(new $e.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let g=typeof J.payment_method=="string"?J.payment_method:J.payment_method?.id,R=m;if(ie.sessionId){let Ke=(await new eo.PaymentAPI(N,{telemetry:!1}).getUnifiedCheckoutSession(ie.sessionId)).data.session;if(Ke&&Ke.status!=="complete"){let Jt=await Ho({billingApiUrl:N,sessionId:ie.sessionId,session:Ke,telemetry:!1,tokenizedData:{id:g??J.id,type:"card",threeDSecureActionResultTokenId:J.id,isPaypal:!0}});if(Jt.type!=="success")throw Object.assign(new $e.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});R=Jt.result.status}}ie.sessionId&&(0,In.markSessionRecentlyCompleted)(ie.sessionId),Pe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.performance({stage:"redirect_resume",durationMs:Pe.elapsed(It),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Pe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),st("success"),await _a(600),(0,tt.invokeMerchantCallback)(()=>rt.current?.({status:R,paymentIntentId:J.id,paymentMethodId:g,checkoutMethod:"paypal"}))}catch(Xt){let ze=io(ba(Xt),ie.sessionId),X=ze.checkoutMethod??"paypal",J=!!(ze.declineCode||ze.code?.toLowerCase().includes("declin"));if(Pe)Pe.performance({stage:"redirect_resume",durationMs:Pe.elapsed(It),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),J?Pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Pe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(J){let H=gi(N,o,f);H.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ta(H)}else ps(N,o,f,"REDIRECT_RESUME_FAILED","redirect_resume");Lt(ze.message),Bt(ze.message),(0,tt.invokeMerchantCallback)(()=>oe.current?.(ze)),xn(X,ze,{code:ze.code,declineCode:ze.declineCode}),st("error"),await _a(400)}finally{fs(),Hd(),st(null),Bt(null),$r(!1)}})())},[xn,l,N,o,f]);let Lr=(0,b.useRef)(null),Fn=(0,b.useMemo)(()=>Yt?(0,ut.serializeCreateParams)(Yt):"",[Yt]),en=(0,b.useRef)(Yt);en.current=Yt,(0,b.useEffect)(()=>{it(e??"")},[e]),(0,b.useEffect)(()=>{lr.current=!1,Lt(_e),Bt(null),wr(!1),st(null)},[Fn,_e,e]);async function Bn(q,B,ie){let Pe=gi(N,o,f),It=new eo.PaymentAPI(N,{telemetry:!1}),Xt=!1;try{let ze=q.idempotencyKey===void 0?void 0:(0,$e.resolveIdempotencyKey)(q.idempotencyKey),X=(0,ut.readCachedInlineSession)(B,ie),J=(0,ut.readCachedInlineIdempotencyKey)(B,ie);X?.canonicalIdentity===ie&&J&&J.canonicalIdentity===void 0&&((0,ut.persistCachedInlineIdempotencyKey)(B,ie,J.idempotencyKey),J={...J,canonicalIdentity:ie});let H=ze??(J?.canonicalIdentity===ie?J.idempotencyKey:void 0),m,g=!1;Pe.log({name:X?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let R=X?.sid??null,se=null,Le,Ke,Jt=!1;if(R)try{se=await It.getUnifiedCheckoutSession(R,X?.nonce),X&&X.canonicalIdentity===void 0&&((0,ut.legacyCachedSessionMatchesDraft)(se.data.session,q)?((0,ut.persistCachedInlineSession)(B,ie,R,X.nonce??se.data.session?.clientSecret),J&&J.canonicalIdentity===void 0&&((0,ut.persistCachedInlineIdempotencyKey)(B,ie,J.idempotencyKey),H??(H=J.idempotencyKey))):((0,ut.clearCachedInlineCheckout)(B,ie),J=null,H=ze,R=null,se=null));let Ye=se?.data.session?.status,nt=se?.data.session,St=nt?.clientSecret||X?.nonce;if(R&&nt?.buyerIdentified===!1&&St&&(Ke=Oo(It,R,St,q.account)),R&&se&&Ye==="complete"){if((0,In.wasSessionRecentlyCompleted)(R))return{sid:R,result:se};(0,ut.clearCachedInlineCheckout)(B,ie),R=null,se=null,g=!0}}catch{Pe.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),X?.canonicalIdentity===void 0?((0,ut.clearCachedInlineCheckout)(B,ie),H=ze):(0,ut.clearCachedInlineSession)(B,ie),R=null}if(!R){!ze&&(g||!H)&&(H=(0,$e.resolveIdempotencyKey)(),m=H),H&&(0,ut.persistCachedInlineIdempotencyKey)(B,ie,H);let Ye=Pe.now(),nt=0;Pe.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let St={...q,idempotencyKey:H,avsCheck:!!Me,avsConfig:typeof Me=="object"?Me:void 0,checkoutType:"embedded_checkout",checkoutLayout:gs(j,F)};Object.defineProperty(St,eo.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ae=>{nt=Math.max(nt,ae)}}});let ve=()=>{Zl(Pe,"session_create",Ye,nt)},O=ae=>{Ql(Pe,ae,"session_create",Ye,nt)&&z({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,$e.isDetachedSessionEligible)(St)){let ae=await It.createDetachedSession(St);ae.claimed.catch(()=>{}),se=ae.shell,R=ae.sessionId,Ke=ae.claim;let mt=Pe.now();Pe.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Le=ae.claimed.then(He=>{let et=He.data.session?.id??ae.sessionId;return et&&(0,ut.persistCachedInlineSession)(B,ie,et,He.data.session?.clientSecret??ae.nonce),Zl(Pe,"session_claim",mt),ve(),He},He=>{throw(0,ut.clearCachedInlineSession)(B,ie),Ql(Pe,He,"session_claim",mt,0)&&z({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),He}).finally(()=>Ta(Pe)),Le.catch(()=>{}),Xt=!0,Pe.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Pe.performance({stage:"session_shell",durationMs:Pe.now()-Ye,durationMode:"machine",requestCategory:"session_create",attempt:nt,statusClass:"2xx",paymentMethodCategory:"card"})}else se=await It.createAndFetchSession(St),ve()}catch(ae){throw O(ae),ae}R=se.data.session?.id??R??"",R&&!Le&&(0,ut.persistCachedInlineSession)(B,ie,R,se.data.session?.clientSecret)}let Te=se?.data.session;return!Ke&&R&&Te?.buyerIdentified===!1&&Te.clientSecret&&(Ke=Oo(It,R,Te.clientSecret,q.account)),{sid:R??"",result:se,sdkGeneratedIdempotencyKey:m,...Le?{claimed:Le}:{},...Ke?{claim:Ke}:{},...Jt?{claimRequiresIdentity:!0}:{}}}finally{Xt||Ta(Pe)}}let Wn=(0,b.useRef)(Bn);Po(()=>{Wn.current=Bn},[Bn]);let Gr=(0,b.useCallback)(async(q,B)=>{let ie=en.current;if(!ie)throw new $e.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Pe=Wi(ie,q),It=(0,ut.serializeCreateParams)(Pe),Xt=(0,ut.hashCreateParams)(Pe),ze=hi.get(It);if(!ze){let H={canonicalIdentity:It,promise:Wn.current(Pe,Xt,It),consumers:0,settled:!1};ze=H,hi.set(It,H);let m=()=>{H.settled=!0,Jl(It,H)};H.promise.then(m,m)}ze.consumers+=1;let X=!1,J=()=>{X||(X=!0,ze.consumers-=1,Jl(It,ze))};B?.(J);try{let H=await ze.promise;Lr.current=It,q&&(Qr(Dt),ir(Te=>pl(Te,q)));let{sid:m,result:g,claimed:R,claim:se,claimRequiresIdentity:Le}=H;if(jt.current=se,kr(Le===!0),at(g),g.data.session&&je(g.data.session),m&&it(m),R){yr.current+=1;let Te=yr.current;$t.current=R,gr(!0),R.then(Ye=>{yr.current===Te&&($t.current===R&&($t.current=null),at(Ye),Ye.data.session&&je(Ye.data.session),gr(!1),kr(!1))},Ye=>{yr.current===Te&&($t.current===R&&($t.current=null),gr(!1),kr(!1),M(Ye instanceof $e.FloPayError?Ye:new $e.FloPayError(Ye instanceof Error?Ye.message:"Failed to create session","api_error")))})}else yr.current+=1,$t.current=null,gr(!1),kr(!1);let{flopay:Ke,paypalFlopay:Jt}=await ms(g,{billingApiUrl:N,locale:l,telemetry:o});return er(Ke,Jt),xe(!1),H}catch(H){throw Lr.current===It&&(Lr.current=null),H}finally{B||J()}},[Dt,er,l,N,o]),hn=(0,b.useRef)(An);hn.current=An;let Pn=(0,b.useRef)(Gr);Pn.current=Gr;let Nt=(0,b.useCallback)(async q=>{if(!Gd(q)||sr)return{sessionId:De,session:G};qt(!0);try{let B=await Gr(q);return{sessionId:B.sid,session:B.result.data.session??null}}finally{qt(!1)}},[Gr,sr,De,G]),Yr=(0,b.useCallback)(async q=>{let B=jt.current;if(!B)return;let ie=yr.current,Pe=await B(q);yr.current===ie&&(at(Pe),Pe.data.session&&je(Pe.data.session))},[]),xr=(0,b.useCallback)(async()=>{await $t.current},[]),vn=(0,b.useCallback)(async()=>(await xr(),{proceed:!0}),[xr]);(0,b.useEffect)(()=>{let q=!1,B,ie=++Tt.current;Or(),M(null),Qt(0);let Pe=()=>{q=!0,Tt.current===ie&&(Tt.current+=1,Or())},It=en.current;if(Fn&&It)return Kt(gn),xe(!1),Lr.current===Fn?Pe:(je(yl(It,L)),(async()=>{let X=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),J=gn==="auto"&&!lr.current&&!X;J&&(Lt(null),Bt(null),st("processing"));try{let H=await Pn.current(void 0,se=>{B=se}),m=H.result.data.session??null;vt.current=Zi(H.result);let g=ys(H.result),R=(0,In.wasSessionRecentlyCompleted)(H.sid||m?.id);if(!q&&J&&m&&!g&&!R){lr.current=!0,await jd(Fn,H.sdkGeneratedIdempotencyKey,()=>hn.current(m,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:H.result.autoProcessingError,initialAutoProcessingPending:H.result.autoProcessingPending,autoProcessingAttempted:H.result.autoProcessingAttempted,sessionId:H.sid||m.id}));return}!q&&J&&((g||R)&&(lr.current=!0),st(null),Bt(null))}catch(H){if(q)return;let m=Wa(H);if(J&&m==="session_auto_completed"){lr.current=!0,st("success"),await _a(600),q||((0,tt.invokeMerchantCallback)(()=>{rt.current?.({status:"succeeded"})}),st(null),Bt(null));return}J&&(st(null),Bt(null));let g=H instanceof $e.FloPayError?H:new $e.FloPayError(H instanceof Error?H.message:"Failed to create session","api_error");M(g)}finally{B?.(),B=void 0}})(),()=>{Pe(),B?.()});xe(!0);async function Xt(){let X=!1,J=null;try{let H=new eo.PaymentAPI(N,{telemetry:!1}),m=await H.getUnifiedCheckoutSession(ne,t);if(J=m,q)return;at(m);let g=m.data.session??null;if(je(g),!g)throw new $e.FloPayError("No session data returned","api_error");let R=g.checkoutMode;if(R==="setup")throw new $e.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(g.status==="authorized"){xe(!1),(0,tt.invokeMerchantCallback)(()=>{rt.current?.(Gn(g,ne)),bt.current?.(g.successUrl??"")});return}if(g.status==="complete"){xe(!1),(0,tt.invokeMerchantCallback)(()=>{bt.current?.(g.successUrl??"")});return}if(g.status==="expired")throw $a(g);X=!0;let se=L??R??"full";Kt(se),yr.current+=1;let Le=g.clientSecret||t;jt.current=g.buyerIdentified===!1&&Le?Oo(H,ne,Le,{...g.customer?.id?{userId:g.customer.id}:{}}):void 0,gr(!1),kr(!1);let Ke=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Jt=ys(m);if(se==="auto"&&!lr.current&&!Ke&&!Jt){lr.current=!0;let Te=ze(m);try{if(await hn.current(g,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Te,sessionId:ne||g.id}),q)return;await Te,q||xe(!1);return}catch{if(q)return;await Te,q||xe(!1);return}}await ze(m),q||xe(!1)}catch(H){if(q)return;let m=ul(H,X);if(X&&z({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),m){let{errorCode:R,stage:se,...Le}=m;ps(N,o,f,R,se,Le)}if(m?.stage==="provider_load"&&(L??J?.data.session?.checkoutMode??"full")==="full"&&dl(J,$,T)){let R=$d({billingApiUrl:N,locale:l,telemetry:o});kt.current=R,er(R,null),Qt(1),xe(!1);return}let g=H instanceof $e.FloPayError&&m?.stage!=="provider_load"?H:cl();g!==H&&(0,tt.invokeMerchantCallback)(()=>oe.current?.(g)),M(g),xe(!1)}}async function ze(X){let{flopay:J,paypalFlopay:H,...m}=await ms(X,{billingApiUrl:N,locale:l,telemetry:o});vt.current={publishableKey:m.publishableKey,paypalPublishableKey:m.paypalPublishableKey},er(J,H),Qt(0)}return Xt(),Pe},[L,Fn,gn,D,t,$,T]);let Cn=(0,b.useCallback)(async()=>{if(!Ae||Ft!==1)return;let q=Tt.current;Qt(2);try{let{flopay:B,paypalFlopay:ie}=await ms(Ae,{billingApiUrl:N,locale:l,telemetry:o});if(Tt.current!==q)return;Or(),er(B,ie),Qt(0)}catch(B){if(Tt.current!==q)return;let{errorCode:ie,stage:Pe,...It}=$i(B);ps(N,o,f,ie,Pe,It)}},[Or,er,l,Ft,N,o,f,Ae]),Ct=!!(ne&&(G?.clientSecret||t)),cr=Vr||!Ct,hr=(0,b.useCallback)(async()=>{if(!(Vr||!Ct||!G)){$r(!0),Lt(null);try{await An(G,{attempt3DS:!0,fallbackToFull:!0,sessionId:ne||G.id})}finally{$r(!1)}}},[ne,Vr,Ct,An,G]),Nr=(0,$e.resolveDirectPaypalConfig)(Ae?.data.paypal,fe),no=ys(Ae),Dn=(0,b.useMemo)(()=>{if(!(!Ae||!G||!Ae.data.stripe?.publishableKey))return{billingApiUrl:N}},[Ae,G,N]),Hn=!!(r&&!j&&F==="buttons"&&be&&gn==="full"),tn=!!(ne&&((0,$e.isMountableVaultBlock)(G?.vault)||(0,kn.canRecoverHostedCardForm)(G))),dr=(0,b.useMemo)(()=>({session:G,loading:Q,error:Oe,checkoutMode:ar,inlineSessionDraft:Yt,applyInlineSessionPatch:Hn?Nt:void 0,inlineSessionPatchProcessing:sr,claimPending:Tr,claimRequiresIdentity:Vt,claimBuyerIdentity:Yr,waitForDataAttachment:xr}),[G,Q,Oe,ar,Yt,Hn,Nt,sr,Tr,Vt,Yr,xr]),oo=!!r&&F==="buttons"&&!no&&!tn&&(!Je||!Dn),mr=yt?(0,x.jsx)(qr,{status:yt,errorMessage:Br,authorized:Wr}):null;if(Q&&!tn){if(u)return(0,x.jsxs)(x.Fragment,{children:[u,mr]});if(F==="buttons"){let q=dt?.buttonsLayout?.cardButton?.borderRadius??dt?.appearance.variables?.borderRadius??8,B=ie=>(0,x.jsx)("div",{style:{height:ie,borderRadius:q,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[$&&B(Xo),T&&(ee||A)&&B(Xo),T&&B(Xo),(0,x.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),mr]})}return(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,x.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,x.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),mr]})}return Oe?p?(0,x.jsx)(Rn.Provider,{value:dr,children:p(Oe)}):(0,x.jsx)(Rn.Provider,{value:dr,children:(0,x.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Oe.message})}):oo?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Rn.Provider,{value:dr,children:(0,x.jsx)(Xd,{onButtonClick:ct,showPayPal:$,showStripe:T,showApplePay:ee,showGooglePay:A,theme:re,buttonsTheme:Ee,buttonsStyles:pe,cardButtonContent:We,cardBackButtonContent:wt,cardTitleContent:ce})}),mr]}):no&&G&&Nr?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Rn.Provider,{value:dr,children:(0,x.jsxs)("div",{className:Ie,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Er&&(0,x.jsx)(Vo,{icon:!1,children:Er}),Fe==="retrying"&&(0,x.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Fe==="exhausted"&&(0,x.jsxs)("div",{role:"alert",children:[(0,x.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,x.jsx)("button",{type:"button",onClick:ro,children:"Retry PayPal"})]}),Fe!=="exhausted"&&(0,x.jsx)("div",{"aria-hidden":Fe==="retrying"?!0:void 0,style:Fe==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,x.jsx)(Rl,{sessionId:ne,nonce:G.clientSecret||void 0,billingApiUrl:N,email:G.customer?.email||Yt?.account?.email,billingName:[G.customer?.firstName,G.customer?.lastName].filter(Boolean).join(" ")||[Yt?.account?.firstName,Yt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Yr,clientId:Nr.clientId,environment:Nr.environment,currency:(G.currency??"usd").toUpperCase(),isSubscription:G.mode==="subscription",providerObjectType:Nr.providerObjectType,approvalPresentation:Nr.approvalPresentation,existingOrderId:Nr.existingOrderId,onComplete:C,onErrorChange:Lt,onDecline:_,onButtonClick:ct,runBeforeButtonClick:vn,onInitializationStateChange:Mn,allowAutomaticRetry:yn===0,session:G,telemetry:o,telemetryContext:f,onInstrument:Rt,debug:ue},`${Qe}:paypal-init-${yn}`)})]})}),mr]}):ar==="confirm"?(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Rn.Provider,{value:dr,children:(0,x.jsx)(Pa,{flopay:Je,paypalFlopay:U,options:Dn??{billingApiUrl:N},onInstrument:Rt,children:(0,x.jsxs)("div",{className:Ie,children:[Er&&(0,x.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Er}),Ne?Ne({onConfirm:hr,isProcessing:cr}):(0,x.jsx)("button",{type:"button",onClick:hr,disabled:cr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:cr?"not-allowed":"pointer",opacity:cr?.6:1},children:Vr?"Processing...":we??"Confirm Purchase"})]})},Qe)}),mr]}):(!Je||!Dn)&&!(tn&&ar==="full")?(0,x.jsx)(x.Fragment,{children:mr}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(Rn.Provider,{value:dr,children:(0,x.jsxs)(Pa,{flopay:Je,paypalFlopay:U,options:Dn??{billingApiUrl:N},onInstrument:Rt,children:[Ft===1&&(0,x.jsx)("button",{type:"button",onClick:Cn,children:"Retry payment methods"}),j?(0,x.jsxs)(x.Fragment,{children:[Er&&(0,x.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Er}),(0,x.jsx)(Yd,{sessionId:ne,nonce:G?.clientSecret||void 0,billingApiUrl:N,session:G,submitLabel:ye,walletPresentation:h,children:j})]}):(0,x.jsx)(mi,{sessionId:ne,nonce:G?.clientSecret||void 0,telemetry:o,email:G?.customer?.email||Yt?.account?.email,userId:G?.customer?.id||Yt?.account?.userId,firstName:G?.customer?.firstName||Yt?.account?.firstName,lastName:G?.customer?.lastName||Yt?.account?.lastName,totalAmount:G?Math.round((0,$e.buildCheckoutDisplayData)(G).total*100):0,currency:G?.currency?.toLowerCase()??"usd",onComplete:C,onError:w,onDecline:_,error:Er,onErrorChange:Lt,showPayPal:$,showStripe:T,walletPresentation:h,enabledPaymentMethods:Ft?[]:P??Ae?.data.stripe?.enabledPaymentMethods??G?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ae?.data.stripe?.enabledPaymentMethodCountries,showApplePay:ee,showGooglePay:A,layout:F,theme:re,buttonsTheme:Ee,buttonsStyles:pe,appearance:ge,cardButtonContent:We,cardBackButtonContent:wt,cardTitleContent:ce,onButtonClick:ct,onBeforeButtonClick:be,onBuyerIdentityReady:Yr,enableAVS:Me,...Se?{cardFieldOrder:Se}:{},...Z?{cardPreFormSlot:Z}:{},avsLayout:de,country:G?.customer?.country,city:G?.customer?.city,state:G?.customer?.state,onCountryChange:K,onZipChange:I,avsCheck:!!Me,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:gs(j,F),className:Ie,submitLabel:ye,directPaypal:Nr,isSubscription:G?.mode==="subscription",session:G,dataAttachmentPending:Tr,dataAttachmentRequiresIdentity:Vt,debug:ue})]},Qe)}),mr]})}function Yd({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:o,walletPresentation:i,children:l}){return(0,x.jsx)(x.Fragment,{children:b.default.Children.map(l,u=>{if(!b.default.isValidElement(u))return u;let p=u.props,C={};return p.sessionId||(C.sessionId=e),!p.nonce&&t&&(C.nonce=t),p.billingApiUrl||(C.billingApiUrl=r),p.submitLabel===void 0&&o!==void 0&&(C.submitLabel=o),p.walletPresentation===void 0&&(C.walletPresentation=i),n?.customer&&(p.email||(C.email=n.customer.email),p.userId||(C.userId=n.customer.id),p.firstName||(C.firstName=n.customer.firstName),p.lastName||(C.lastName=n.customer.lastName)),Object.keys(C).length===0?u:b.default.cloneElement(u,C)})})}function Xd({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:o,theme:i,buttonsTheme:l,buttonsStyles:u,cardButtonContent:p,cardBackButtonContent:C,cardTitleContent:w}){let[S,_]=(0,b.useState)(!1),K=(0,b.useMemo)(()=>(0,$e.resolveTheme)(i),[i]),I=(0,b.useMemo)(()=>{let P=K?.buttonsLayout??(0,$e.resolveButtonsLayoutTheme)(l);return u?{...P,...u,cardButton:{...P.cardButton,...u.cardButton},cardFormContainer:{...P.cardFormContainer,...u.cardFormContainer},backButton:{...P.backButton,...u.backButton},backButtonIcon:{...P.backButtonIcon,...u.backButtonIcon},submitButton:{...P.submitButton,...u.submitButton},title:{...P.title,...u.title}}:P},[K,l,u]),$=K?.buttonsLayout?.cardButton?.borderRadius??K?.appearance.variables?.borderRadius??8,T=P=>(0,x.jsx)("div",{style:{height:P,borderRadius:$,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),h=p===void 0?{boxSizing:"border-box",height:Xo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(S){let P=I.cardInputBorder??"#e5e7eb",ee=I.cardInputBackground??"white",A=Fo(C),ue=Fo(w);return(0,x.jsxs)("div",{style:{backgroundColor:I.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...I.cardFormContainer},children:[(0,x.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,x.jsxs)("button",{type:"button",onClick:()=>_(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:A?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...I.backButton},children:[(0,x.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...I.backButtonIcon},children:(0,x.jsx)("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:(0,x.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,x.jsx)(Do,{content:C})]}),ue?(0,x.jsx)("div",{style:{flex:1}}):(0,x.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...I.title},children:(0,x.jsx)(da,{content:w})})]}),(0,x.jsx)("div",{style:{backgroundColor:ee,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsxs)("div",{style:{display:"flex"},children:[(0,x.jsx)("div",{style:{flex:1,backgroundColor:ee,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsx)("div",{style:{flex:1,backgroundColor:ee,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,x.jsx)("div",{style:{backgroundColor:ee,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,x.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,x.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...I.submitButton,opacity:.5}}),(0,x.jsx)("style",{children:`
38
+ `}),aa&&no&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:g?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:ge,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:U.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...U.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...U.backButtonIcon},children:(0,d.jsx)("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:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Do,{content:we})]}),Zs?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:U.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...U.title},children:(0,d.jsx)(da,{content:xe})})]}),!aa&&!Zs&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ui,order:g?-3:0,...U.title},children:(0,d.jsx)(da,{content:xe})}),g&&me&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:me}),g&&ao&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:Mo,border:`1px solid ${nn(Ua)}`,borderRadius:nr,padding:"10px"},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Vt,onChange:s=>{Nt("email"),hr.current=s.target.value,xr(s.target.value)},onPointerDown:()=>Nt("email"),onKeyDown:()=>Nt("email"),onBlur:()=>{Gr("email")&&tn(!0),wo||_i()},disabled:at,required:!0,"aria-invalid":Ua||void 0,"aria-describedby":Ua?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...zi}})}),Ua&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:sa,children:ki.empty?"Email address is required":"Enter a valid email address"})]}),De&&(0,d.jsx)("div",{style:{order:g?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Ht,E=(re=!1)=>({backgroundColor:Mo,border:`1px solid ${nn(re)}`,borderRadius:nr,marginTop:"0.5rem",padding:"10px"}),ae=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...zi}),je=(0,c.getStateOptions)(s);return(0,d.jsxs)(d.Fragment,{children:[(0,c.isAVSFieldVisible)(De.address_line_1,s)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:E(tr("line1")),children:(0,d.jsx)("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:jt,onChange:re=>{Nt("line1"),Pr.current.addressLine1=!0,gr.current=re.target.value,Zr(re.target.value)},onPointerDown:()=>Nt("line1"),onKeyDown:()=>Nt("line1"),onBlur:()=>Br("line1"),disabled:at,required:!0,"aria-invalid":tr("line1")||void 0,"aria-describedby":tr("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:ae()})}),tr("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:sa,children:"Street address is required"})]}),(0,c.isAVSFieldVisible)(De.address_line_2,s)&&(0,d.jsx)("div",{style:E(),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Gt,onChange:re=>{Pr.current.addressLine2=!0,mr.current=re.target.value,_n(re.target.value)},disabled:at,"data-testid":"flopay-address-line2",style:ae()})}),((0,c.isAVSFieldVisible)(De.city,s)||(0,c.isAVSFieldVisible)(De.state,s))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(De.city,s)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Mo,borderTop:`1px solid ${nn(tr("city"))}`,borderRight:`1px solid ${nn(tr("city"))}`,borderBottom:`1px solid ${nn(tr("city"))}`,borderLeft:`1px solid ${nn(tr("city"))}`,padding:"10px",borderTopLeftRadius:nr,borderBottomLeftRadius:nr,...(0,c.isAVSFieldVisible)(De.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:nr}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Yt,onChange:re=>{Nt("city"),Pr.current.city=!0,Xt.current=re.target.value,Qr(re.target.value)},onPointerDown:()=>Nt("city"),onKeyDown:()=>Nt("city"),onBlur:()=>Br("city"),disabled:at,required:!0,"aria-invalid":tr("city")||void 0,"aria-describedby":tr("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:ae()})}),(0,c.isAVSFieldVisible)(De.state,s)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Mo,borderTop:`1px solid ${nn(tr("state"))}`,borderRight:`1px solid ${nn(tr("state"))}`,borderBottom:`1px solid ${nn(tr("state"))}`,borderLeft:`1px solid ${nn(tr("state"))}`,padding:"10px",borderTopRightRadius:nr,borderBottomRightRadius:nr,...(0,c.isAVSFieldVisible)(De.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${nn(tr("state")||tr("city"))}`}:{borderRadius:nr}},children:je?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:ot,onChange:re=>{Nt("state"),Pr.current.state=!0,Dt.current=re.target.value,dt(re.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>Br("state"),disabled:at,autoComplete:"billing address-level1",required:!0,"aria-invalid":tr("state")||void 0,"aria-describedby":tr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...ae(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,c.getStateLabel)(s)}),je.map(re=>(0,d.jsx)("option",{value:re.code,children:re.name},re.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,c.getStateLabel)(s),autoComplete:"billing address-level1",value:ot,onChange:re=>{Nt("state"),Pr.current.state=!0,Dt.current=re.target.value,dt(re.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>Br("state"),disabled:at,required:!0,"aria-invalid":tr("state")||void 0,"aria-describedby":tr("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:ae()})})]}),tr("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:sa,children:"City is required"}),tr("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:sa,children:[(0,c.getStateLabel)(s)," is required"]}),((0,c.isAVSFieldVisible)(De.country,s)||(0,c.isAVSFieldVisible)(De.postal_code,s))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:N==="column"?"column":"row",gap:N==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,c.isAVSFieldVisible)(De.country,s)&&(0,d.jsx)("div",{style:{flex:N==="row"?1:void 0,backgroundColor:Mo,borderTop:`1px solid ${ia}`,borderRight:`1px solid ${ia}`,borderBottom:`1px solid ${ia}`,borderLeft:`1px solid ${ia}`,padding:"10px",...N==="row"&&(0,c.isAVSFieldVisible)(De.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:nr,borderBottomLeftRadius:nr,borderRight:"none"}:{borderRadius:nr}},children:(0,d.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Ht,onChange:re=>{Pr.current.country=!0,Tr.current=re.target.value,Kt(re.target.value),Te?.(re.target.value),Dt.current="",dt("")},disabled:at,autoComplete:"billing country","data-testid":"flopay-country",style:{...ae(),cursor:"pointer"},children:[Ht===""?(0,d.jsx)("option",{value:"",children:"Select country"}):null,c.COUNTRY_OPTIONS.map(re=>(0,d.jsxs)("option",{value:re.code,children:[re.flag," ",re.name]},re.code))]})}),(0,c.isAVSFieldVisible)(De.postal_code,s)&&(0,d.jsx)("div",{style:{flex:N==="row"?1:void 0,backgroundColor:Mo,border:`1px solid ${Mc}`,padding:"10px",...N==="row"&&(0,c.isAVSFieldVisible)(De.country,s)?{borderRadius:"0",borderTopRightRadius:nr,borderBottomRightRadius:nr}:{borderRadius:nr}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,c.getPostalCodeLabel)(Ht),autoComplete:"billing postal-code",value:Lr,onChange:re=>{Nt("zip"),Pr.current.zip=!0,Rr.current=re.target.value,_r(re.target.value),tt?.(re.target.value)},onPointerDown:()=>Nt("zip"),onKeyDown:()=>Nt("zip"),onBlur:()=>{Gr("zip")&&zr(!0)},disabled:at,required:Hr.required,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:ae()})})]}),za&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:sa,children:Hr.empty?`${(0,c.getPostalCodeLabel)(s)} is required`:Ld(s)})]})})()}),g&&Dc,St&&(0,d.jsx)(Vo,{margin:"0.75rem 0",styleOverride:U.errorBanner,children:St})]}),qa={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"},nl=s=>W?!P||!Ln?(0,d.jsx)("pre",{"data-testid":s,style:qa,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":s,style:qa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${P}`,` directPaypalConfigured=${Ln}`,` inAppBrowserDetected=${String(Oa)}`,` shouldRenderDirectPayPal=${ea}`,` shouldRenderStripePayPal=${ra}`,` hasPaypalStripeInstance=${!!ws}`].join(`
39
+ `)}):null,ol=s=>W?!ee||!Yr?(0,d.jsx)("pre",{"data-testid":s,style:qa,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":s,style:qa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${ee}`,` currency=${Et}`,` amountInCents=${Zo}`,` enabledPaymentMethods: ${JSON.stringify(ue??[])}`,` enabledPaymentMethodsProvided=${Qo}`,` hasEnabledMethods=${Aa}`,` expressMethods: ${JSON.stringify(Ba)}`,` walletExpressMethods: ${JSON.stringify(_o)}`,` paymentElementMethods: ${JSON.stringify(Mi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Da)}`,` hasStripeInstance=${!!Yr}`,` shouldRenderWallets=${To}`,` shouldRenderPaymentElement=${na}`].join(`
40
+ `)}):null,al=Ct==="apm-expanding"||Ct==="apm-form"||Ct==="apm-collapsing",Ao;Ct==="apm-expanding"?Ao=Ul:Ct==="apm-collapsing"&&(Ao=zl);let ja=vr?Xl(xi,vr,j):null;if(ie==="buttons"){let s=Ct==="buttons"||Ct==="expanding"||Ct==="apm-expanding",E=Ct==="expanding"||Ct==="card"||Ct==="collapsing",ae=pt===void 0?{boxSizing:"border-box",height:Go,padding:"0 1rem"}:{padding:"0.9rem 1rem"},je;Ct==="expanding"||Ct==="apm-expanding"?je=Fd:(Ct==="collapsing"||Ct==="apm-collapsing")&&(je=Ad);let re;return Ct==="expanding"?re=Ul:Ct==="collapsing"&&(re=zl),(0,d.jsxs)("form",{onSubmit:Di,className:K,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Yo,{}),Ne&&(0,d.jsx)(Wr,{status:Ne,errorMessage:St,authorized:Nr}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!je?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!je?Dd:{},...je?{animation:je,pointerEvents:"none"}:{}},children:[nl("flopay-direct-paypal-gate-debug"),ol("flopay-stripe-gate-debug"),ea&&ft&&(0,d.jsxs)(d.Fragment,{children:[Oe&&(0,d.jsx)("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."}),(0,d.jsx)(ya.Provider,{value:b,children:(0,d.jsx)(ga,{sessionId:e,nonce:t,billingApiUrl:Be,email:vt.email,billingName:So||void 0,onBuyerIdentityReady:lt,clientId:ft.clientId,environment:ft.environment,currency:Et.toUpperCase(),isSubscription:Ft,providerObjectType:Y,approvalPresentation:La==="popup"?void 0:La,onTokenizedBody:jr,onComplete:l,onErrorChange:Ue,onDecline:p,onTechnicalFailure:Eo,onButtonClick:Z,runBeforeButtonClick:Cn,isProcessing:at,onLoadStateChange:Ai,onInitializationStateChange:Fi,session:ve,existingOrderId:Oe?.orderId,debug:W},Oe?.orderId??"fresh")})]}),ra&&(0,d.jsx)(or.Elements,{stripe:ta,options:Es,children:(0,d.jsx)(jl,{sessionId:e,nonce:t,email:vt.email,billingName:So||void 0,onBuyerIdentityReady:lt,billingApiUrl:Be,onTokenizedBody:jr,onErrorChange:Ue,isProcessing:at,onButtonClick:Z,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:Cn,onLoadStateChange:Ds,placeholderBorderRadius:po,popupCapabilityOwner:b,externalTelemetryContext:Ws,presentationMode:Io})}),To?(0,d.jsx)(or.Elements,{stripe:Yr,options:Rs,children:(0,d.jsx)(Wl,{sessionId:e,nonce:t,email:vt.email,billingName:So||void 0,onBuyerIdentityReady:lt,billingApiUrl:Be,intentKind:Le>0?"payment":"setup",expressMethods:_o,onTokenizedBody:jr,onErrorChange:Ue,onButtonClick:Z,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:Cn,onLoadStateChange:Ls,placeholderBorderRadius:po,popupCapabilityOwner:b,externalTelemetryContext:h})}):null,!To&&js?(0,d.jsx)("div",{style:{height:Go,borderRadius:po,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,na&&(0,d.jsx)($l,{sessionId:e,nonce:t,email:vt.email,billingName:[vt.firstName,vt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:lt,billingApiUrl:Be,paymentElementMethods:Da,stripeInstance:Yr,paymentElementBaseOptions:xi,futureUseSession:j,onTokenizedBody:jr,onErrorChange:Ue,onButtonClick:Z,onDecline:p,runBeforeButtonClick:Cn,onLoadStateChange:Us,isProcessing:at,submitButtonColor:mo,submitButtonBorderRadius:nr,submitButtonStyle:U.submitButton,onExpandApm:_t,expandedApmMethod:vr,themeId:We,buttonAppearance:{backgroundColor:U.cardButton?.backgroundColor,borderColor:U.cardInputBorder,textColor:U.cardButton?.color,borderRadius:po}}),g&&(0,d.jsx)("button",{type:"button",onClick:async()=>{at||!(await Cn("card")).proceed||(Z?.("card"),le())},disabled:at,style:{width:"100%",...ae,...U.cardButton,...ds({themeBundle:Ce,resolvedPrimaryColor:mo,resolvedBorderRadius:nr,submitButtonStyle:U.submitButton,explicitPrimaryColor:Vr?.colorPrimary}),fontSize:U.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:at?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:at?.6:1},onMouseEnter:Ie=>{!at&&(Ce||Vr?.colorPrimary)&&(Ie.currentTarget.style.backgroundColor=Fc)},onMouseLeave:Ie=>{(Ce||Vr?.colorPrimary)&&(Ie.currentTarget.style.backgroundColor=mo)},onMouseDown:Ie=>{Ie.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ie=>{Ie.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(Bo,{content:pt})}),St&&Ct==="buttons"&&(0,d.jsx)(Vo,{margin:"0.25rem 0",styleOverride:U.errorBanner,children:St})]}),g&&E&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...re?{animation:re}:{},...Ct==="collapsing"?{pointerEvents:"none"}:{}},children:rl}),ee&&al&&vr&&ja&&Yr&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Ao?{animation:Ao}:{},...Ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Li,borderRadius:ji,...la,padding:qi},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Qt,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:U.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...U.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...U.backButtonIcon},children:(0,d.jsx)("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:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Do,{content:we})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:U.titleFontSize??"1.05rem",color:Ui,paddingRight:80,...U.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(vr)}`})]}),(0,d.jsx)(or.Elements,{stripe:Yr,options:ja,children:(0,d.jsx)(ss,{method:vr,sessionId:e,nonce:t,email:vt.email,billingName:[vt.firstName,vt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:lt,billingApiUrl:Be,onTokenizedBody:jr,onErrorChange:Ue,onDecline:p,onCancel:Qt,runBeforeButtonClick:Cn,onButtonClick:Z,isProcessing:at,submitButtonColor:mo,submitButtonBorderRadius:nr,submitButtonStyle:U.submitButton,errorText:St})},vr)]})})]})]})}return al&&vr&&ja&&Yr&&ee?(0,d.jsxs)("form",{onSubmit:Di,className:K,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Yo,{}),Ne&&(0,d.jsx)(Wr,{status:Ne,errorMessage:St,authorized:Nr}),(0,d.jsx)("div",{style:{...Ao?{animation:Ao}:{},...Ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Li,borderRadius:ji,...la,padding:qi},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Qt,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:U.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...U.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...U.backButtonIcon},children:(0,d.jsx)("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:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Do,{content:we})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:U.titleFontSize??"1.05rem",color:Ui,paddingRight:80,...U.title},children:`Pay with ${(0,c.getStripeMethodDisplayName)(vr)}`})]}),(0,d.jsx)(or.Elements,{stripe:Yr,options:ja,children:(0,d.jsx)(ss,{method:vr,sessionId:e,nonce:t,email:vt.email,billingName:[vt.firstName,vt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:lt,billingApiUrl:Be,onTokenizedBody:jr,onErrorChange:Ue,onDecline:p,onCancel:Qt,runBeforeButtonClick:Cn,onButtonClick:Z,isProcessing:at,submitButtonColor:mo,submitButtonBorderRadius:nr,submitButtonStyle:U.submitButton,errorText:St})},vr)]})})]}):(0,d.jsxs)("form",{onSubmit:Di,className:K,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(Yo,{}),Ne&&(0,d.jsx)(Wr,{status:Ne,errorMessage:St,authorized:Nr}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[nl("flopay-direct-paypal-gate-debug-default"),ol("flopay-stripe-gate-debug-default"),ea&&ft&&(0,d.jsxs)(d.Fragment,{children:[Oe&&(0,d.jsx)("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."}),(0,d.jsx)(ya.Provider,{value:b,children:(0,d.jsx)(ga,{sessionId:e,nonce:t,billingApiUrl:Be,email:vt.email,billingName:So||void 0,onBuyerIdentityReady:lt,clientId:ft.clientId,environment:ft.environment,currency:Et.toUpperCase(),isSubscription:Ft,providerObjectType:Y,approvalPresentation:La==="popup"?void 0:La,onTokenizedBody:jr,onComplete:l,onErrorChange:Ue,onDecline:p,onTechnicalFailure:Eo,onButtonClick:Z,runBeforeButtonClick:Cn,isProcessing:at,onLoadStateChange:Ai,onInitializationStateChange:Fi,session:ve,existingOrderId:Oe?.orderId,debug:W},Oe?.orderId??"fresh")})]}),ra&&(0,d.jsx)(or.Elements,{stripe:ta,options:Es,children:(0,d.jsx)(jl,{sessionId:e,nonce:t,email:vt.email,billingName:So||void 0,onBuyerIdentityReady:lt,billingApiUrl:Be,onTokenizedBody:jr,onErrorChange:Ue,isProcessing:at,onButtonClick:Z,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:Cn,onLoadStateChange:Ds,placeholderBorderRadius:po,popupCapabilityOwner:b,externalTelemetryContext:Ws,presentationMode:Io})}),To&&(0,d.jsx)(or.Elements,{stripe:Yr,options:Rs,children:(0,d.jsx)(Wl,{sessionId:e,nonce:t,email:vt.email,billingName:So||void 0,onBuyerIdentityReady:lt,billingApiUrl:Be,intentKind:Le>0?"payment":"setup",expressMethods:_o,onTokenizedBody:jr,onErrorChange:Ue,onButtonClick:Z,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:Cn,onLoadStateChange:Ls,placeholderBorderRadius:po,popupCapabilityOwner:b,externalTelemetryContext:h})}),na&&(0,d.jsx)($l,{sessionId:e,nonce:t,email:vt.email,billingName:[vt.firstName,vt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Be,paymentElementMethods:Da,stripeInstance:Yr,paymentElementBaseOptions:xi,futureUseSession:j,onTokenizedBody:jr,onErrorChange:Ue,onButtonClick:Z,onDecline:p,runBeforeButtonClick:Cn,onLoadStateChange:Us,isProcessing:at,submitButtonColor:mo,submitButtonBorderRadius:nr,submitButtonStyle:U.submitButton,themeId:We,onExpandApm:_t,expandedApmMethod:vr,buttonAppearance:{backgroundColor:U.cardButton?.backgroundColor,borderColor:U.cardInputBorder,textColor:U.cardButton?.color,borderRadius:po}})]}),g&&(Ec||Rc||Ic)&&(0,d.jsx)(li,{label:"or pay with card"}),g&&rl]})}var B=require("react/jsx-runtime"),Xo=44,hs="flopay_checkout_saved_payment_resume",hi=new Map,fi=new Map;function Jl(e,t){t.settled&&t.consumers===0&&hi.get(e)===t&&hi.delete(e)}function Wd(e,t,r){let n=fi.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let a=r(),i={attempt:a,sdkGeneratedIdempotencyKey:t};fi.set(e,i);let l=()=>{fi.get(e)===i&&fi.delete(e)};return a.then(l,l),a}function _a(e){return new Promise(t=>setTimeout(t,e))}function gi(e,t,r){let n=Xa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ve.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Ta(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ps(e,t,r,n,a,i){let l=gi(e,t,r);l.error({errorCode:n,stage:a,paymentMethodCategory:"unknown",...i,...a==="session_read"?{requestCategory:"session_read"}:{}}),Ta(l)}function Zl(e,t,r,n){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()-r),durationMode:"machine",requestCategory:t,...n===void 0?{}:{attempt:n},statusClass:"2xx"})}function Ql(e,t,r,n,a){let i=(0,Ve.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:r,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:r,attempt:a,statusClass:i.statusClass}),t instanceof Ve.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Ve.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:r,paymentMethodCategory:"unknown",requestCategory:r,statusClass:"4xx"}),!1):(e.error({...i,stage:r,paymentMethodCategory:"unknown",requestCategory:r}),!0)}function ms(e){return!e||e.data.stripe?.publishableKey?!1:!!(0,Ve.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var $d={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Hd(e){return new eo.FloPay($d,{publishableKey:"provider_unavailable",...e})}async function ys(e,t){let{publishableKey:r,paypalPublishableKey:n}=Zi(e);return{...await Qi({publishableKey:r,paypalPublishableKey:n,...t}),publishableKey:r,paypalPublishableKey:n}}function Ps(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Kd(){if(!Ps())return null;try{let e=window.sessionStorage.getItem(hs);return e?JSON.parse(e):null}catch{return null}}function ec(e){if(Ps())try{window.sessionStorage.setItem(hs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function fs(){if(Ps())try{window.sessionStorage.removeItem(hs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Gd(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],r=!1;for(let n of t)e.searchParams.has(n)&&(e.searchParams.delete(n),r=!0);r&&window.history.replaceState(window.history.state,"",e.toString())}function tc(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 gs(e,t){return(0,Ve.resolveCheckoutLogLayout)(!!e,t)}function Yd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function rc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Xd(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 Pi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:a,appearance:i,locale:l,loading:u,error:p,onComplete:v,onError:R,onInstrument:w,onDecline:x,onCountryChange:K,onZipChange:T,showPayPal:V=!0,showStripe:A=!0,walletPresentation:f="auto",enabledPaymentMethods:P,showApplePay:ee=!0,showGooglePay:D=!0,debug:ue=!1,layout:F,theme:ne,buttonsTheme:_e,buttonsStyles:ie,cardButtonContent:We,cardBackButtonContent:kt,cardTitleContent:de,showSecurityFooter:G,onButtonClick:pt,onBeforeButtonClick:we,enableAVS:xe,cardFieldOrder:ke,cardPreFormSlot:Z,avsLayout:pe,submitLabel:Re,className:Fe,initialErrorMessage:rt=null,initialPayPalOrderId:me,children:N,checkoutMode:H,confirmLabel:ye,renderConfirmButton:$e,onSessionCompleted:he}){let M=(0,Ve.resolveBillingApiUrl)(n),Ye=(0,C.useMemo)(()=>(0,Ve.resolveTheme)(ne),[ne]),Te=i??Ye?.appearance,tt=r?"embedded_checkout":"standard_checkout",Ze=gs(N,F),[ze,He]=(0,C.useState)(null),[Le,Et]=(0,C.useState)(null),zt=(0,C.useRef)(null),ft=(0,C.useRef)(null),Ft=(0,C.useRef)(0),[q,Pe]=(0,C.useState)(null),st=(0,C.useRef)(null),[W,Ee]=(0,C.useState)(null),nt=(0,C.useMemo)(()=>r?(0,mt.serializeCreateParams)(r):"",[r]),Ke=r?`create:${nt}`:`session:${e??""}`,Rt=rc(W),qt=(0,C.useRef)(new Set),b=(0,C.useRef)(Ke),L=(0,C.useRef)(Ke);Po(()=>{L.current=Ke,b.current!==Ke&&(b.current=Ke,qt.current.clear())},[Ke]);let qe=(0,C.useCallback)(z=>{if(L.current===Ke){if(Yi.FLO_INSTRUMENT_ONCE_NAMES.has(z.name)){if(qt.current.has(z.name))return;qt.current.add(z.name)}(0,it.invokeMerchantCallback)(()=>w?.(z))}},[Ke,w]),fe=jo(qe,Ke),h=(0,C.useRef)(!1),ve=(0,C.useCallback)(z=>{if(h.current)return;let O=z.gateway||!Rt?z:{...z,gateway:Rt};qe(O)},[qe,Rt]);(0,C.useEffect)(()=>{fe({class:"lifecycle",name:"checkout.mount"})},[fe]);let[j,Y]=(0,C.useState)(e??""),te=e??j,k=r?"":te,[Q,be]=(0,C.useState)(!0),[Be,S]=(0,C.useState)(null),[Bt,rr]=(0,C.useState)(0),[sr,Ht]=(0,C.useState)("full"),[Kt,Lr]=(0,C.useState)(!1),[_r,jt]=(0,C.useState)(rt),[Zr,Gt]=(0,C.useState)(null),[_n,Yt]=(0,C.useState)(null),[Qr,ot]=(0,C.useState)(!1),[dt,Vt]=(0,C.useState)(void 0),[xr,Ar]=(0,C.useState)(""),[Fr,Rr]=(0,C.useState)(!1),[Tr,gr]=(0,C.useState)(!1),[mr,Xt]=(0,C.useState)(!1),Dt=(0,C.useRef)(null),hr=(0,C.useRef)(0),Pr=(0,C.useRef)(void 0),[De,mn]=(0,C.useState)("loading"),[Nr,Tn]=(0,C.useState)(0),lr=(0,C.useRef)(!1),Er=(0,C.useRef)(!1),Mn=(0,C.useRef)(!1),en=(0,C.useRef)(null),Jt=(0,C.useRef)(null),g=(0,C.useMemo)(()=>({checkoutMode:H??sr,layout:Yd(N,F)}),[H,N,sr,F]),It=(0,C.useRef)(v);It.current=v;let se=(0,C.useRef)(R);se.current=R;let Ae=(0,C.useRef)(x);Ae.current=x;let xt=(0,C.useCallback)(z=>Qa(en,async O=>{try{return await z(O)}catch(le){throw O.aborted?Wo(le):le}}),[]);(0,C.useEffect)(()=>()=>{en.current?.abort(),en.current=null},[]);let bt=(0,C.useCallback)((z,O)=>{zt.current=z,Et(z),st.current=O,Pe(O)},[]),At=(0,C.useCallback)(()=>{let z=ft.current;z&&(ft.current=null,z.destroy())},[]);(0,C.useEffect)(()=>{Sr(Le)?.setCheckoutContext(g),q&&q!==Le&&Sr(q)?.setCheckoutContext(g)},[Le,q,g]);let Qe=(0,C.useRef)(he);Qe.current=he;let Ur=(0,C.useCallback)(z=>{mn(z),!(z!=="exhausted"||Mn.current)&&(Mn.current=!0,se.current?.(new Ve.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),ro=(0,C.useCallback)(()=>{mn("retrying"),Tn(z=>z+1)},[]);(0,C.useEffect)(()=>{mn("loading"),Tn(0),Mn.current=!1},[te]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ve.SDK_VERSION,checkout_type:tt,checkout_layout:Ze,billing_api_url:M})},[Ze,tt,M]);let Ot=(0,C.useMemo)(()=>r?(0,mt.serializeCreateParams)(r,!0):"",[r]),Hr=(0,C.useMemo)(()=>xr===Ot?dt:void 0,[dt,xr,Ot]),yn=(0,C.useMemo)(()=>r?$i(r,Hr):void 0,[r,Hr]),fn=H??yn?.checkoutMode??"full",Zt=(0,C.useMemo)(()=>yn?{...yn,checkoutMode:fn}:void 0,[yn,fn]);(0,C.useEffect)(()=>{Vt(void 0),Ar(Ot),Pr.current=void 0,Dt.current=null,Xt(!1)},[Ot]),(0,C.useEffect)(()=>{jt(rt)},[rt]);let xn=(0,C.useCallback)((z,O,le)=>{(0,it.invokeMerchantCallback)(()=>{Ae.current?.(Cr(z,O,le))})},[]),An=(0,C.useCallback)(async(z,O)=>{jt(null),Yt(null),ot(!1),Gt("processing");let le=O?.sessionId??z.id,ge=z.clientSecret||t,_t=rc(z),Qt=zt.current??st.current,Ne=Sr(Qt),X=Qt?null:gi(M,a,g),J={log:Me=>{Ne?Ne.log(Me):X?.log(Me)},error:Me=>{Ne?Ne.error(Me):X?.error(Me)},terminal:Me=>{Ne?Ne.terminal(Me):X?.terminal(Me)},performance:Me=>{Ne?Ne.performance(Me):X?.performance(Me)},now:()=>Ne?.now()??X?.now()??0,elapsed:Me=>Ne?.elapsed(Me)??Math.max(0,(X?.now()??Me)-Me)},$=J.now(),m=!!(O?.initialAutoProcessingError||O?.initialAutoProcessingPending),y=!1,I,ce=()=>{y||(y=!0,m=!0,I=J.now(),J.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),J.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Oe=!1,Xe=()=>{Oe||(Oe=!0,J.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),J.performance({stage:"processing",durationMs:J.elapsed($),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),I!==void 0&&J.performance({stage:"recovery",durationMs:J.elapsed(I),durationMode:"machine",paymentMethodCategory:"saved"}))};J.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),h.current=!0;try{J.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{h.current=!1}fe({class:"lifecycle",name:"payment.processing.started",provider:_t}),m&&ce();let er;try{let Me=Tl(O?.initialAutoProcessingError),et=O?.initialAutoProcessingError?.type==="3ds_required"&&!O.initialAutoProcessingError.threeDSecureToken&&O.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:O.initialAutoProcessingError.nextActionRedirectUrl}:null,lt,St=Ce=>(ce(),xt(U=>$o(Ce,{billingApiUrl:M,sessionId:le,nonce:ge,session:z,signal:U})));if(et)lt=await St(et);else if(Me)ce(),Me.type==="paypal_redirect_required"&&Jt.current?.publishableKey&&ec({sessionId:le,publishableKey:Jt.current.publishableKey,paypalPublishableKey:Jt.current.paypalPublishableKey}),lt=await xt(Ce=>ti(Me,{flopay:zt.current,paypalFlopay:st.current,attempt3DS:O?.attempt3DS,billingApiUrl:M,sessionId:le,session:z,telemetry:!1,signal:Ce})),Me.type==="paypal_redirect_required"&&fs();else if(O?.initialAutoProcessingPending){let Ce=O.initialAutoProcessingPending,U=new eo.PaymentAPI(M,{telemetry:!1}),oe=await xt(at=>U.waitForCheckoutSessionCompletion(Ce.sessionId,{initialDelayMs:Ce.retryAfterMs,nonce:ge,statusUrl:Ce.statusUrl,signal:at})),gt=so(oe,z),Ge=oe.autoProcessingError?.type==="3ds_required"&&oe.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:oe.autoProcessingError.nextActionRedirectUrl}:null;if(Ge)lt=await St(Ge);else{if(!Yn(gt))throw Lo(gt);lt=Gn(gt,le)}}else{if(O?.initialAutoProcessingError)throw qn(O.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:O.initialAutoProcessingError.checkoutMethod});if(O?.fromCreateSession)return O?.fallbackToFull&&(Ht("full"),tc("full")),!1;{let Ce=await Ho({billingApiUrl:M,sessionId:le,session:z,nonce:ge,telemetry:!1});Ce.type==="success"?lt=Ce.result:Ce.type==="next_action_required"?lt=await St(Ce):(ce(),Ce.type==="paypal_redirect_required"&&Jt.current?.publishableKey&&ec({sessionId:le,publishableKey:Jt.current.publishableKey,paypalPublishableKey:Jt.current.paypalPublishableKey}),lt=await xt(U=>ti(Ce,{flopay:zt.current,paypalFlopay:st.current,attempt3DS:O?.attempt3DS,billingApiUrl:M,sessionId:le,session:z,telemetry:!1,signal:U})),Ce.type==="paypal_redirect_required"&&fs())}}le&&(0,Rn.markSessionRecentlyCompleted)(le),Xe(),m&&(J.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),J.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),J.terminal({outcome:lt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),ot(lt.status==="authorized"),Gt("success"),await _a(600),er=()=>It.current?.(lt)}catch(Me){let et=io(Ca(Me),le);if(et.code==="three_ds_aborted")return!1;let lt=et.checkoutMethod??ba;jt(et.message),Yt(et.message),ot(!1),O?.fallbackToFull&&(J.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Ht("full"),tc("full")),Xe();let St=et.statusCode===void 0?void 0:(0,Ve.telemetryStatusClass)(et.statusCode,"unknown"),Ce=St==="4xx"?{requestCategory:"process_payment",statusClass:St}:{},U=St===void 0||St==="4xx";if(U&&(et.telemetryOutcome==="payment_declined"||!!(et.declineCode||et.code?.toLowerCase().includes("declin"))))J.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ce});else if(U&&(et.telemetryOutcome==="validation_rejected"||et.type==="validation_error"))J.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ce});else{let Ge=(0,Ve.classifyTelemetryFailure)(Me,m?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),at=et.telemetryRequestCategory??"process_payment";h.current=!0;try{J.error({...Ge,...et.telemetryFailureCategory?{failureCategory:et.telemetryFailureCategory}:{},stage:m?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:at})}finally{h.current=!1}fe({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:at,provider:_t})}return(0,it.invokeMerchantCallback)(()=>se.current?.(et)),xn(lt,et,{code:et.code,declineCode:et.declineCode}),Gt("error"),await Promise.allSettled([_a(400),O?.ensureProvidersReady?O.ensureProvidersReady():Promise.resolve()]),m&&(J.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),J.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Xe(),X&&Ta(X),Gt(null),Yt(null)}return(0,it.invokeMerchantCallback)(er),!0},[xn,fe,t,M,xt,a,g]);(0,C.useEffect)(()=>{if(typeof window>"u"||Er.current)return;let z=new URLSearchParams(window.location.search),O=z.get("payment_intent_client_secret");if(!O)return;let le=Kd();le&&(Er.current=!0,(async()=>{let ge,_t=0;jt(null),Yt(null),Gt("processing"),Lr(!0);try{if(z.get("redirect_status")==="failed")throw Object.assign(new Ve.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Qt,paypalFlopay:Ne}=await Qi({publishableKey:le.publishableKey,paypalPublishableKey:le.paypalPublishableKey,billingApiUrl:M,locale:l,telemetry:a});ge=Sr(Ne??Qt),ge?.setCheckoutContext(g),_t=ge?.now()??0,ge?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let X=(Ne??Qt)?.getRawProvider();if(!X)throw Object.assign(new Ve.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:J,error:$}=await X.retrievePaymentIntent(O);if($)throw Object.assign(new Ve.FloPayError($.message??"Failed to retrieve PayPal payment status.","api_error",{code:$.code}),{checkoutMethod:"paypal"});let m=fl(J?.status);if(!J||m==="failed")throw Object.assign(new Ve.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let y=typeof J.payment_method=="string"?J.payment_method:J.payment_method?.id,I=m;if(le.sessionId){let Xe=(await new eo.PaymentAPI(M,{telemetry:!1}).getUnifiedCheckoutSession(le.sessionId)).data.session;if(Xe&&Xe.status!=="complete"){let er=await Ho({billingApiUrl:M,sessionId:le.sessionId,session:Xe,telemetry:!1,tokenizedData:{id:y??J.id,type:"card",threeDSecureActionResultTokenId:J.id,isPaypal:!0}});if(er.type!=="success")throw Object.assign(new Ve.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});I=er.result.status}}le.sessionId&&(0,Rn.markSessionRecentlyCompleted)(le.sessionId),ge?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.performance({stage:"redirect_resume",durationMs:ge.elapsed(_t),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Gt("success"),await _a(600),(0,it.invokeMerchantCallback)(()=>It.current?.({status:I,paymentIntentId:J.id,paymentMethodId:y,checkoutMethod:"paypal"}))}catch(Qt){let Ne=io(Ca(Qt),le.sessionId),X=Ne.checkoutMethod??"paypal",J=!!(Ne.declineCode||Ne.code?.toLowerCase().includes("declin"));if(ge)ge.performance({stage:"redirect_resume",durationMs:ge.elapsed(_t),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),J?ge.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ge.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(J){let $=gi(M,a,g);$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ta($)}else ps(M,a,g,"REDIRECT_RESUME_FAILED","redirect_resume");jt(Ne.message),Yt(Ne.message),(0,it.invokeMerchantCallback)(()=>se.current?.(Ne)),xn(X,Ne,{code:Ne.code,declineCode:Ne.declineCode}),Gt("error"),await _a(400)}finally{fs(),Gd(),Gt(null),Yt(null),Lr(!1)}})())},[xn,l,M,a,g]);let zr=(0,C.useRef)(null),Fn=(0,C.useMemo)(()=>Zt?(0,mt.serializeCreateParams)(Zt):"",[Zt]),tn=(0,C.useRef)(Zt);tn.current=Zt,(0,C.useEffect)(()=>{Y(e??"")},[e]),(0,C.useEffect)(()=>{lr.current=!1,jt(rt),Yt(null),ot(!1),Gt(null)},[Fn,rt,e]);async function Bn(z,O,le){let ge=gi(M,a,g),_t=new eo.PaymentAPI(M,{telemetry:!1}),Qt=!1;try{let Ne=z.idempotencyKey===void 0?void 0:(0,Ve.resolveIdempotencyKey)(z.idempotencyKey),X=(0,mt.readCachedInlineSession)(O,le),J=(0,mt.readCachedInlineIdempotencyKey)(O,le);X?.canonicalIdentity===le&&J&&J.canonicalIdentity===void 0&&((0,mt.persistCachedInlineIdempotencyKey)(O,le,J.idempotencyKey),J={...J,canonicalIdentity:le});let $=Ne??(J?.canonicalIdentity===le?J.idempotencyKey:void 0),m,y=!1;ge.log({name:X?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let I=X?.sid??null,ce=null,Oe,Xe,er=!1;if(I)try{ce=await _t.getUnifiedCheckoutSession(I,X?.nonce),X&&X.canonicalIdentity===void 0&&((0,mt.legacyCachedSessionMatchesDraft)(ce.data.session,z)?((0,mt.persistCachedInlineSession)(O,le,I,X.nonce??ce.data.session?.clientSecret),J&&J.canonicalIdentity===void 0&&((0,mt.persistCachedInlineIdempotencyKey)(O,le,J.idempotencyKey),$??($=J.idempotencyKey))):((0,mt.clearCachedInlineCheckout)(O,le),J=null,$=Ne,I=null,ce=null));let et=ce?.data.session?.status,lt=ce?.data.session,St=lt?.clientSecret||X?.nonce;if(I&&lt?.buyerIdentified===!1&&St&&(Xe=Oo(_t,I,St,z.account)),I&&ce&&et==="complete"){if((0,Rn.wasSessionRecentlyCompleted)(I))return{sid:I,result:ce};(0,mt.clearCachedInlineCheckout)(O,le),I=null,ce=null,y=!0}}catch{ge.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),X?.canonicalIdentity===void 0?((0,mt.clearCachedInlineCheckout)(O,le),$=Ne):(0,mt.clearCachedInlineSession)(O,le),I=null}if(!I){!Ne&&(y||!$)&&($=(0,Ve.resolveIdempotencyKey)(),m=$),$&&(0,mt.persistCachedInlineIdempotencyKey)(O,le,$);let et=ge.now(),lt=0;ge.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let St={...z,idempotencyKey:$,avsCheck:!!xe,avsConfig:typeof xe=="object"?xe:void 0,checkoutType:"embedded_checkout",checkoutLayout:gs(N,F)};Object.defineProperty(St,eo.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:oe=>{lt=Math.max(lt,oe)}}});let Ce=()=>{Zl(ge,"session_create",et,lt)},U=oe=>{Ql(ge,oe,"session_create",et,lt)&&fe({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Ve.isDetachedSessionEligible)(St)){let oe=await _t.createDetachedSession(St);oe.claimed.catch(()=>{}),ce=oe.shell,I=oe.sessionId,Xe=oe.claim;let gt=ge.now();ge.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Oe=oe.claimed.then(Ge=>{let at=Ge.data.session?.id??oe.sessionId;return at&&(0,mt.persistCachedInlineSession)(O,le,at,Ge.data.session?.clientSecret??oe.nonce),Zl(ge,"session_claim",gt),Ce(),Ge},Ge=>{throw(0,mt.clearCachedInlineSession)(O,le),Ql(ge,Ge,"session_claim",gt,0)&&fe({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Ge}).finally(()=>Ta(ge)),Oe.catch(()=>{}),Qt=!0,ge.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ge.performance({stage:"session_shell",durationMs:ge.now()-et,durationMode:"machine",requestCategory:"session_create",attempt:lt,statusClass:"2xx",paymentMethodCategory:"card"})}else ce=await _t.createAndFetchSession(St),Ce()}catch(oe){throw U(oe),oe}I=ce.data.session?.id??I??"",I&&!Oe&&(0,mt.persistCachedInlineSession)(O,le,I,ce.data.session?.clientSecret)}let Me=ce?.data.session;return!Xe&&I&&Me?.buyerIdentified===!1&&Me.clientSecret&&(Xe=Oo(_t,I,Me.clientSecret,z.account)),{sid:I??"",result:ce,sdkGeneratedIdempotencyKey:m,...Oe?{claimed:Oe}:{},...Xe?{claim:Xe}:{},...er?{claimRequiresIdentity:!0}:{}}}finally{Qt||Ta(ge)}}let $n=(0,C.useRef)(Bn);Po(()=>{$n.current=Bn},[Bn]);let Kr=(0,C.useCallback)(async(z,O)=>{let le=tn.current;if(!le)throw new Ve.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ge=$i(le,z),_t=(0,mt.serializeCreateParams)(ge),Qt=(0,mt.hashCreateParams)(ge),Ne=hi.get(_t);if(!Ne){let $={canonicalIdentity:_t,promise:$n.current(ge,Qt,_t),consumers:0,settled:!1};Ne=$,hi.set(_t,$);let m=()=>{$.settled=!0,Jl(_t,$)};$.promise.then(m,m)}Ne.consumers+=1;let X=!1,J=()=>{X||(X=!0,Ne.consumers-=1,Jl(_t,Ne))};O?.(J);try{let $=await Ne.promise;zr.current=_t,z&&(Ar(Ot),Vt(Me=>pl(Me,z)));let{sid:m,result:y,claimed:I,claim:ce,claimRequiresIdentity:Oe}=$;if(Pr.current=ce,Xt(Oe===!0),He(y),y.data.session&&Ee(y.data.session),m&&Y(m),I){hr.current+=1;let Me=hr.current;Dt.current=I,gr(!0),I.then(et=>{hr.current===Me&&(Dt.current===I&&(Dt.current=null),He(et),et.data.session&&Ee(et.data.session),gr(!1),Xt(!1))},et=>{hr.current===Me&&(Dt.current===I&&(Dt.current=null),gr(!1),Xt(!1),S(et instanceof Ve.FloPayError?et:new Ve.FloPayError(et instanceof Error?et.message:"Failed to create session","api_error")))})}else hr.current+=1,Dt.current=null,gr(!1),Xt(!1);let{flopay:Xe,paypalFlopay:er}=await ys(y,{billingApiUrl:M,locale:l,telemetry:a});return bt(Xe,er),be(!1),$}catch($){throw zr.current===_t&&(zr.current=null),$}finally{O||J()}},[Ot,bt,l,M,a]),gn=(0,C.useRef)(An);gn.current=An;let hn=(0,C.useRef)(Kr);hn.current=Kr;let Nt=(0,C.useCallback)(async z=>{if(!Xd(z)||Fr)return{sessionId:j,session:W};Rr(!0);try{let O=await Kr(z);return{sessionId:O.sid,session:O.result.data.session??null}}finally{Rr(!1)}},[Kr,Fr,j,W]),Gr=(0,C.useCallback)(async z=>{let O=Pr.current;if(!O)return;let le=hr.current,ge=await O(z);hr.current===le&&(He(ge),ge.data.session&&Ee(ge.data.session))},[]),Br=(0,C.useCallback)(async()=>{await Dt.current},[]),Pn=(0,C.useCallback)(async()=>(await Br(),{proceed:!0}),[Br]);(0,C.useEffect)(()=>{let z=!1,O,le=++Ft.current;At(),S(null),rr(0);let ge=()=>{z=!0,Ft.current===le&&(Ft.current+=1,At())},_t=tn.current;if(Fn&&_t)return Ht(fn),be(!1),zr.current===Fn?ge:(Ee(ml(_t,H)),(async()=>{let X=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),J=fn==="auto"&&!lr.current&&!X;J&&(jt(null),Yt(null),Gt("processing"));try{let $=await hn.current(void 0,ce=>{O=ce}),m=$.result.data.session??null;Jt.current=Zi($.result);let y=ms($.result),I=(0,Rn.wasSessionRecentlyCompleted)($.sid||m?.id);if(!z&&J&&m&&!y&&!I){lr.current=!0,await Wd(Fn,$.sdkGeneratedIdempotencyKey,()=>gn.current(m,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:$.result.autoProcessingError,initialAutoProcessingPending:$.result.autoProcessingPending,autoProcessingAttempted:$.result.autoProcessingAttempted,sessionId:$.sid||m.id}));return}!z&&J&&((y||I)&&(lr.current=!0),Gt(null),Yt(null))}catch($){if(z)return;let m=$a($);if(J&&m==="session_auto_completed"){lr.current=!0,Gt("success"),await _a(600),z||((0,it.invokeMerchantCallback)(()=>{It.current?.({status:"succeeded"})}),Gt(null),Yt(null));return}J&&(Gt(null),Yt(null));let y=$ instanceof Ve.FloPayError?$:new Ve.FloPayError($ instanceof Error?$.message:"Failed to create session","api_error");S(y)}finally{O?.(),O=void 0}})(),()=>{ge(),O?.()});be(!0);async function Qt(){let X=!1,J=null;try{let $=new eo.PaymentAPI(M,{telemetry:!1}),m=await $.getUnifiedCheckoutSession(te,t);if(J=m,z)return;He(m);let y=m.data.session??null;if(Ee(y),!y)throw new Ve.FloPayError("No session data returned","api_error");let I=y.checkoutMode;if(I==="setup")throw new Ve.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){be(!1),(0,it.invokeMerchantCallback)(()=>{It.current?.(Gn(y,te)),Qe.current?.(y.successUrl??"")});return}if(y.status==="complete"){be(!1),(0,it.invokeMerchantCallback)(()=>{Qe.current?.(y.successUrl??"")});return}if(y.status==="expired")throw Wa(y);X=!0;let ce=H??I??"full";Ht(ce),hr.current+=1;let Oe=y.clientSecret||t;Pr.current=y.buyerIdentified===!1&&Oe?Oo($,te,Oe,{...y.customer?.id?{userId:y.customer.id}:{}}):void 0,gr(!1),Xt(!1);let Xe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),er=ms(m);if(ce==="auto"&&!lr.current&&!Xe&&!er){lr.current=!0;let Me=Ne(m);try{if(await gn.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Me,sessionId:te||y.id}),z)return;await Me,z||be(!1);return}catch{if(z)return;await Me,z||be(!1);return}}await Ne(m),z||be(!1)}catch($){if(z)return;let m=ul($,X);if(X&&fe({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),m){let{errorCode:I,stage:ce,...Oe}=m;ps(M,a,g,I,ce,Oe)}if(m?.stage==="provider_load"&&(H??J?.data.session?.checkoutMode??"full")==="full"&&dl(J,V,A)){let I=Hd({billingApiUrl:M,locale:l,telemetry:a});ft.current=I,bt(I,null),rr(1),be(!1);return}let y=$ instanceof Ve.FloPayError&&m?.stage!=="provider_load"?$:cl();y!==$&&(0,it.invokeMerchantCallback)(()=>se.current?.(y)),S(y),be(!1)}}async function Ne(X){let{flopay:J,paypalFlopay:$,...m}=await ys(X,{billingApiUrl:M,locale:l,telemetry:a});Jt.current={publishableKey:m.publishableKey,paypalPublishableKey:m.paypalPublishableKey},bt(J,$),rr(0)}return Qt(),ge},[H,Fn,fn,k,t,V,A]);let vn=(0,C.useCallback)(async()=>{if(!ze||Bt!==1)return;let z=Ft.current;rr(2);try{let{flopay:O,paypalFlopay:le}=await ys(ze,{billingApiUrl:M,locale:l,telemetry:a});if(Ft.current!==z)return;At(),bt(O,le),rr(0)}catch(O){if(Ft.current!==z)return;let{errorCode:le,stage:ge,..._t}=Wi(O);ps(M,a,g,le,ge,_t)}},[At,bt,l,Bt,M,a,g,ze]),Ct=!!(te&&(W?.clientSecret||t)),cr=Kt||!Ct,vr=(0,C.useCallback)(async()=>{if(!(Kt||!Ct||!W)){Lr(!0),jt(null);try{await An(W,{attempt3DS:!0,fallbackToFull:!0,sessionId:te||W.id})}finally{Lr(!1)}}},[te,Kt,Ct,An,W]),qr=(0,Ve.resolveDirectPaypalConfig)(ze?.data.paypal,me),no=ms(ze),Dn=(0,C.useMemo)(()=>{if(!(!ze||!W||!ze.data.stripe?.publishableKey))return{billingApiUrl:M}},[ze,W,M]),Hn=!!(r&&!N&&F==="buttons"&&we&&fn==="full"),rn=!!(te&&((0,Ve.isMountableVaultBlock)(W?.vault)||(0,Sn.canRecoverHostedCardForm)(W))),dr=(0,C.useMemo)(()=>({session:W,loading:Q,error:Be,checkoutMode:sr,inlineSessionDraft:Zt,applyInlineSessionPatch:Hn?Nt:void 0,inlineSessionPatchProcessing:Fr,claimPending:Tr,claimRequiresIdentity:mr,claimBuyerIdentity:Gr,waitForDataAttachment:Br}),[W,Q,Be,sr,Zt,Hn,Nt,Fr,Tr,mr,Gr,Br]),oo=!!r&&F==="buttons"&&!no&&!rn&&(!Le||!Dn),yr=Zr?(0,B.jsx)(Wr,{status:Zr,errorMessage:_n,authorized:Qr}):null;if(Q&&!rn){if(u)return(0,B.jsxs)(B.Fragment,{children:[u,yr]});if(F==="buttons"){let z=Ye?.buttonsLayout?.cardButton?.borderRadius??Ye?.appearance.variables?.borderRadius??8,O=le=>(0,B.jsx)("div",{style:{height:le,borderRadius:z,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[V&&O(Xo),A&&(ee||D)&&O(Xo),A&&O(Xo),(0,B.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),yr]})}return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,B.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,B.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),yr]})}return Be?p?(0,B.jsx)(wn.Provider,{value:dr,children:p(Be)}):(0,B.jsx)(wn.Provider,{value:dr,children:(0,B.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Be.message})}):oo?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(wn.Provider,{value:dr,children:(0,B.jsx)(Zd,{onButtonClick:pt,showPayPal:V,showStripe:A,showApplePay:ee,showGooglePay:D,theme:ne,buttonsTheme:_e,buttonsStyles:ie,cardButtonContent:We,cardBackButtonContent:kt,cardTitleContent:de})}),yr]}):no&&W&&qr?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(wn.Provider,{value:dr,children:(0,B.jsxs)("div",{className:Fe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[_r&&(0,B.jsx)(Vo,{icon:!1,children:_r}),De==="retrying"&&(0,B.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),De==="exhausted"&&(0,B.jsxs)("div",{role:"alert",children:[(0,B.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,B.jsx)("button",{type:"button",onClick:ro,children:"Retry PayPal"})]}),De!=="exhausted"&&(0,B.jsx)("div",{"aria-hidden":De==="retrying"?!0:void 0,style:De==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,B.jsx)(Rl,{sessionId:te,nonce:W.clientSecret||void 0,billingApiUrl:M,email:W.customer?.email||Zt?.account?.email,billingName:[W.customer?.firstName,W.customer?.lastName].filter(Boolean).join(" ")||[Zt?.account?.firstName,Zt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Gr,clientId:qr.clientId,environment:qr.environment,currency:(W.currency??"usd").toUpperCase(),isSubscription:W.mode==="subscription",providerObjectType:qr.providerObjectType,approvalPresentation:qr.approvalPresentation,existingOrderId:qr.existingOrderId,onComplete:v,onErrorChange:jt,onDecline:x,onButtonClick:pt,runBeforeButtonClick:Pn,onInitializationStateChange:Ur,allowAutomaticRetry:Nr===0,session:W,telemetry:a,telemetryContext:g,onInstrument:ve,debug:ue},`${Ke}:paypal-init-${Nr}`)})]})}),yr]}):sr==="confirm"?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(wn.Provider,{value:dr,children:(0,B.jsx)(Pa,{flopay:Le,paypalFlopay:q,options:Dn??{billingApiUrl:M},onInstrument:ve,children:(0,B.jsxs)("div",{className:Fe,children:[_r&&(0,B.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:_r}),$e?$e({onConfirm:vr,isProcessing:cr}):(0,B.jsx)("button",{type:"button",onClick:vr,disabled:cr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:cr?"not-allowed":"pointer",opacity:cr?.6:1},children:Kt?"Processing...":ye??"Confirm Purchase"})]})},Ke)}),yr]}):(!Le||!Dn)&&!(rn&&sr==="full")?(0,B.jsx)(B.Fragment,{children:yr}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(wn.Provider,{value:dr,children:(0,B.jsxs)(Pa,{flopay:Le,paypalFlopay:q,options:Dn??{billingApiUrl:M},onInstrument:ve,children:[Bt===1&&(0,B.jsx)("button",{type:"button",onClick:vn,children:"Retry payment methods"}),N?(0,B.jsxs)(B.Fragment,{children:[_r&&(0,B.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:_r}),(0,B.jsx)(Jd,{sessionId:te,nonce:W?.clientSecret||void 0,billingApiUrl:M,session:W,submitLabel:Re,walletPresentation:f,children:N})]}):(0,B.jsx)(yi,{sessionId:te,nonce:W?.clientSecret||void 0,telemetry:a,email:W?.customer?.email||Zt?.account?.email,userId:W?.customer?.id||Zt?.account?.userId,firstName:W?.customer?.firstName||Zt?.account?.firstName,lastName:W?.customer?.lastName||Zt?.account?.lastName,totalAmount:W?Math.round((0,Ve.buildCheckoutDisplayData)(W).total*100):0,currency:W?.currency?.toLowerCase()??"usd",onComplete:v,onError:R,onDecline:x,error:_r,onErrorChange:jt,showPayPal:V,showStripe:A,walletPresentation:f,enabledPaymentMethods:Bt?[]:P??ze?.data.stripe?.enabledPaymentMethods??W?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ze?.data.stripe?.enabledPaymentMethodCountries,showApplePay:ee,showGooglePay:D,layout:F,theme:ne,buttonsTheme:_e,buttonsStyles:ie,appearance:Te,cardButtonContent:We,cardBackButtonContent:kt,cardTitleContent:de,onButtonClick:pt,onBeforeButtonClick:we,onBuyerIdentityReady:Gr,enableAVS:xe,...ke?{cardFieldOrder:ke}:{},...Z?{cardPreFormSlot:Z}:{},avsLayout:pe,country:W?.customer?.country,city:W?.customer?.city,state:W?.customer?.state,onCountryChange:K,onZipChange:T,avsCheck:!!xe,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:gs(N,F),className:Fe,submitLabel:Re,directPaypal:qr,isSubscription:W?.mode==="subscription",session:W,dataAttachmentPending:Tr,dataAttachmentRequiresIdentity:mr,debug:ue})]},Ke)}),yr]})}function Jd({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:a,walletPresentation:i,children:l}){return(0,B.jsx)(B.Fragment,{children:C.default.Children.map(l,u=>{if(!C.default.isValidElement(u))return u;let p=u.props,v={};return p.sessionId||(v.sessionId=e),!p.nonce&&t&&(v.nonce=t),p.billingApiUrl||(v.billingApiUrl=r),p.submitLabel===void 0&&a!==void 0&&(v.submitLabel=a),p.walletPresentation===void 0&&(v.walletPresentation=i),n?.customer&&(p.email||(v.email=n.customer.email),p.userId||(v.userId=n.customer.id),p.firstName||(v.firstName=n.customer.firstName),p.lastName||(v.lastName=n.customer.lastName)),Object.keys(v).length===0?u:C.default.cloneElement(u,v)})})}function Zd({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:a,theme:i,buttonsTheme:l,buttonsStyles:u,cardButtonContent:p,cardBackButtonContent:v,cardTitleContent:R}){let[w,x]=(0,C.useState)(!1),K=(0,C.useMemo)(()=>(0,Ve.resolveTheme)(i),[i]),T=(0,C.useMemo)(()=>{let P=K?.buttonsLayout??(0,Ve.resolveButtonsLayoutTheme)(l);return u?{...P,...u,cardButton:{...P.cardButton,...u.cardButton},cardFormContainer:{...P.cardFormContainer,...u.cardFormContainer},backButton:{...P.backButton,...u.backButton},backButtonIcon:{...P.backButtonIcon,...u.backButtonIcon},submitButton:{...P.submitButton,...u.submitButton},title:{...P.title,...u.title}}:P},[K,l,u]),V=K?.buttonsLayout?.cardButton?.borderRadius??K?.appearance.variables?.borderRadius??8,A=P=>(0,B.jsx)("div",{style:{height:P,borderRadius:V,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),f=p===void 0?{boxSizing:"border-box",height:Xo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(w){let P=T.cardInputBorder??"#e5e7eb",ee=T.cardInputBackground??"white",D=Fo(v),ue=Fo(R);return(0,B.jsxs)("div",{style:{backgroundColor:T.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...T.cardFormContainer},children:[(0,B.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,B.jsxs)("button",{type:"button",onClick:()=>x(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:D?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...T.backButton},children:[(0,B.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...T.backButtonIcon},children:(0,B.jsx)("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:(0,B.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,B.jsx)(Do,{content:v})]}),ue?(0,B.jsx)("div",{style:{flex:1}}):(0,B.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...T.title},children:(0,B.jsx)(da,{content:R})})]}),(0,B.jsx)("div",{style:{backgroundColor:ee,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsxs)("div",{style:{display:"flex"},children:[(0,B.jsx)("div",{style:{flex:1,backgroundColor:ee,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsx)("div",{style:{flex:1,backgroundColor:ee,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,B.jsx)("div",{style:{backgroundColor:ee,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,B.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,B.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...T.submitButton,opacity:.5}}),(0,B.jsx)("style",{children:`
41
41
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
42
42
  @keyframes flopay-interim-expand {
43
43
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
44
44
  40% { opacity: 1; }
45
45
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
46
46
  }
47
- `})]})}return(0,x.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&T(Xo),r&&(n||o)&&T(Xo),r&&(0,x.jsx)("button",{type:"button",onClick:()=>{e?.("card"),_(!0)},style:{width:"100%",...h,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:I.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,...I.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,x.jsx)(Bo,{content:p})}),(0,x.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var cn=require("react/jsx-runtime"),Jd=44;function nc(e){return new Promise(t=>setTimeout(t,e))}function Zd(e,t){return e instanceof dn.FloPayError?e:new dn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Qd(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function eu(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 oc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:o,clientId:i,products:l,items:u,subscriptions:p,account:C,successUrl:w,cancelUrl:S,couponCodes:_,tagsData:K,utmMetadata:I,billingApiUrl:$,locale:T,theme:h,appearance:P,buttonsTheme:ee,buttonsStyles:A,onSuccess:ue,onError:F,onDecline:re,children:Ee,disabled:pe=!1,type:We="button",style:wt,...ce}){let Y=(0,pt.useMemo)(()=>(0,dn.resolveBillingApiUrl)($),[$]),ct=(0,pt.useMemo)(()=>eu({createSession:r,clientId:i,products:l,items:u,subscriptions:p,account:C,successUrl:w,cancelUrl:S,couponCodes:_,tagsData:K,utmMetadata:I}),[C,S,i,_,r,l,u,p,w,K,I]),[be,Me]=(0,pt.useState)(!1),[Se,Z]=(0,pt.useState)(null),[de,ye]=(0,pt.useState)(null),[Ie,_e]=(0,pt.useState)(!1),[fe,j]=(0,pt.useState)(null),[L,we]=(0,pt.useState)(null),Ne=(0,pt.useRef)(!0),ke=(0,pt.useRef)(null),N=(0,pt.useRef)(L),dt=(0,pt.useRef)(ue),ge=(0,pt.useRef)(F),Be=(0,pt.useRef)(re),Xe=(0,pt.useCallback)(y=>Qa(ke,async v=>{try{return await y(v)}catch(W){throw v.aborted?$o(W):W}}),[]);(0,pt.useEffect)(()=>{N.current=L},[L]),(0,pt.useEffect)(()=>{dt.current=ue},[ue]),(0,pt.useEffect)(()=>{ge.current=F},[F]),(0,pt.useEffect)(()=>{Be.current=re},[re]),(0,pt.useEffect)(()=>(Ne.current=!0,()=>{Ne.current=!1,ke.current?.abort()}),[]),(0,pt.useEffect)(()=>{if(typeof window>"u")return;let y=v=>{v.key==="Escape"&&we(null)};return window.addEventListener("keydown",y),()=>{window.removeEventListener("keydown",y)}},[]);let Ae=(0,pt.useCallback)((y,v=Ca)=>{Be.current?.(vr(v,y,{code:y.code,declineCode:y.declineCode}))},[]),at=(0,pt.useCallback)(async y=>{Ne.current&&(ye(null),_e(y.result.status==="authorized"),Z("success"),await nc(600),Ne.current&&(0,tt.invokeMerchantCallback)(()=>dt.current?.(y)))},[]),Je=(0,pt.useCallback)(async(y,v)=>{Ne.current&&(ge.current?.(y),v?.emitDecline&&Ae(y,v.method),ye(y.message),_e(!1),Z("error"),await nc(400))},[Ae]),Et=(0,pt.useCallback)(async(y,v,W)=>{let z=y.data.session??null;if(!z)throw io(new dn.FloPayError("No session data returned","api_error"),v);let me=z.clientSecret||t;if(Yn(z)){await at({result:Gn(z,v),session:z,sessionId:z.id||v,autoCompleted:!1});return}if(z.status==="expired")throw io($a(z),z.id||v);try{if(y.autoProcessingPending){let De=y.autoProcessingPending,it=new vi.PaymentAPI(Y),ne=await Xe(xe=>it.waitForCheckoutSessionCompletion(De.sessionId,{initialDelayMs:De.retryAfterMs,nonce:me,statusUrl:De.statusUrl,signal:xe})),D=so(ne,z),Q=ne.autoProcessingError?.type==="3ds_required"&&ne.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ne.autoProcessingError.nextActionRedirectUrl}:null;if(Q&&v&&me){let xe=await Xe(Oe=>Wo(Q,{billingApiUrl:Y,sessionId:v,nonce:me,session:z,signal:Oe,telemetry:!0}));await at({result:xe,session:z,sessionId:z.id||v,autoCompleted:!1});return}if(ne.autoProcessingError)throw qn(ne.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:ne.autoProcessingError.checkoutMethod});if(!Yn(D))throw Lo(D);await at({result:Gn(D,v),session:D,sessionId:D.id||v,autoCompleted:!1});return}if(y.autoProcessingError){let De=y.autoProcessingError.nextActionRedirectUrl;if(y.autoProcessingError.type==="3ds_required"&&De&&v&&me){let it=await Xe(xe=>Ml({billingApiUrl:Y,sessionId:v,nonce:me,nextActionRedirectUrl:De,signal:xe}));if(it.status==="declined")throw qn({type:it.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:it.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:y.autoProcessingError.checkoutMethod});let D=await new vi.PaymentAPI(Y).waitForCheckoutSessionCompletion(v,{initialDelayMs:0,nonce:me}),Q=so(D,z);if(!Yn(Q))throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:y.autoProcessingError.checkoutMethod});await at({result:Gn(Q,v),session:Q,sessionId:Q.id||v,autoCompleted:!1});return}throw qn(y.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:y.autoProcessingError.checkoutMethod})}if(W?.fromCreateSession&&y.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Rt=await Ho({billingApiUrl:Y,sessionId:v??z.id,session:z,nonce:me});if(Rt.type==="next_action_required"&&me){let De=v??z.id,it=await Xe(ne=>Wo(Rt,{billingApiUrl:Y,sessionId:De,nonce:me,session:z,signal:ne,telemetry:!0}));await at({result:it,session:z,sessionId:z.id||De,autoCompleted:!1});return}if(Rt.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await at({result:Rt.result,session:z,sessionId:z.id||v,autoCompleted:!1})}catch(Rt){let De=z.id||v,it=io(ba(Rt),De);if(it.code==="three_ds_aborted")return;if(it.code==="checkout_processing_timeout"){if(!Ne.current)return;j(it.message),(0,tt.invokeMerchantCallback)(()=>ge.current?.(it));return}await Je(it,{emitDecline:!0,method:it.checkoutMethod??Ca}),Qd(it,De)&&De&&Ne.current&&we({sessionId:De,errorMessage:it.message,nonce:me||void 0,payPalOrderId:it.orderId})}},[t,Y,Xe,Je,at]),zt=(0,pt.useCallback)(async y=>{if(ce.onClick?.(y),!(y.defaultPrevented||pe||be)){if(we(null),j(null),e&&ct){let v=new dn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Je(v),Ne.current&&(Z(null),ye(null));return}if(!e&&!ct){let v=new dn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Je(v),Ne.current&&(Z(null),ye(null));return}Me(!0),ye(null),_e(!1),Z("processing");try{let v=new vi.PaymentAPI(Y);if(e){let W=await v.getUnifiedCheckoutSession(e,t);await Et(W,e);return}try{let W=await v.createAndFetchSession({...ct});await Et(W,W.data.session?.id??null,{fromCreateSession:!0})}catch(W){if(Wa(W)==="session_auto_completed"){await at({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw W}}catch(v){await Je(io(Zd(v,"Automatic payment failed. Please try again."),e))}finally{Ne.current&&(Z(null),ye(null),Me(!1))}}},[ce.onClick,ct,pe,be,t,Et,Y,e,Je,at]),kt=(0,pt.useCallback)(y=>{let v=N.current;we(null),dt.current?.({result:y,session:null,sessionId:v?.sessionId??null,autoCompleted:!1})},[]),Tt=(0,pt.useCallback)(y=>{ge.current?.(y)},[]),U=(0,pt.useCallback)(y=>{Be.current?.(y)},[]),he=(0,pt.useMemo)(()=>(0,dn.resolveTheme)(h),[h]),Ze=(0,pt.useMemo)(()=>{let y=he?.buttonsLayout??(0,dn.resolveButtonsLayoutTheme)(ee);return A?{...y,...A,cardButton:{...y.cardButton,...A.cardButton}}:y},[he,ee,A]),G=(0,pt.useMemo)(()=>{let y=he?.appearance;return P?y?{...y,...P,variables:{...y.variables,...P.variables}}:P:y},[P,he]),je=G?.variables,ht=je?.colorPrimary??"#4A49FF",Qe=je?.colorPrimaryHover??(0,us.darkenHex)(ht,.12),At=je?.borderRadius??"8px";return(0,cn.jsxs)(cn.Fragment,{children:[(0,cn.jsx)("button",{...ce,type:We,onClick:zt,disabled:pe||be,"aria-busy":be,style:{width:"100%",...Ee===void 0?{boxSizing:"border-box",height:Jd,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ze.cardButton,...ds({themeBundle:he,resolvedPrimaryColor:ht,resolvedBorderRadius:At,submitButtonStyle:Ze.submitButton,explicitPrimaryColor:je?.colorPrimary}),fontSize:Ze.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:pe||be?"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:pe||be?.6:1,...wt},onMouseEnter:y=>{ce.onMouseEnter?.(y),!y.defaultPrevented&&!pe&&!be&&(he||je?.colorPrimary)&&(y.currentTarget.style.backgroundColor=Qe)},onMouseLeave:y=>{ce.onMouseLeave?.(y),!y.defaultPrevented&&(he||je?.colorPrimary)&&(y.currentTarget.style.backgroundColor=ht)},onMouseDown:y=>{ce.onMouseDown?.(y),y.defaultPrevented||(y.currentTarget.style.transform="scale(0.985)")},onMouseUp:y=>{ce.onMouseUp?.(y),y.defaultPrevented||(y.currentTarget.style.transform="scale(1)")},children:(0,cn.jsx)(Bo,{content:Ee})}),fe&&(0,cn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:fe}),Se&&(0,cn.jsx)(qr,{status:Se,errorMessage:de,authorized:Ie}),L&&(0,cn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:y=>{y.target===y.currentTarget&&we(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:(0,cn.jsx)("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:(0,cn.jsx)(Pi,{sessionId:L.sessionId,nonce:L.nonce,checkoutMode:"full",billingApiUrl:Y,locale:T,theme:h,...G?{appearance:G}:{},buttonsTheme:ee,buttonsStyles:A,initialErrorMessage:L.errorMessage,initialPayPalOrderId:L.payPalOrderId,cardTitleContent:null,onComplete:kt,onError:Tt,onDecline:U})})})]})}var bi=require("@flopay/js/card-setup"),Ar=require("@flopay/shared"),Ut=require("react");var vs=require("@flopay/shared"),tu=require("@flopay/shared");function Ci(e){let t=(0,vs.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Vn=require("react/jsx-runtime"),Ma=class extends Ar.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function to(e,t={}){let r=e instanceof Ar.FloPayError?e:void 0,n=r?.statusCode,o=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new Ma(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:o,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}function ac({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:o="modern-light",containerStyle:i,appearance:l,buttonsStyles:u,loading:p=null,onReady:C,onComplete:w,onDecline:S,onCancel:_,onValidation:K,onError:I}){let[$,T]=(0,Ut.useState)(null),[h,P]=(0,Ut.useState)(null),[ee,A]=(0,Ut.useState)(null),[ue,F]=(0,Ut.useState)(null),[re,Ee]=(0,Ut.useState)(null),pe=(0,Ut.useRef)(!1),We=(0,Ut.useRef)(!1),{vaultTheme:wt,surface:ce,overlayTheme:Y}=(0,Ut.useMemo)(()=>Ci({theme:o,appearance:l,buttonsStyles:u}),[o,l,u]),ct=(0,Ut.useMemo)(()=>(0,ka.mergeCardSetupSurface)(ce,i),[ce,i]),be=(0,Ut.useRef)(C),Me=(0,Ut.useRef)(I),Se=(0,Ut.useRef)(w),Z=(0,Ut.useRef)(S),de=(0,Ut.useRef)(_),ye=(0,Ut.useRef)(K),Ie=(0,Ut.useRef)(!1),_e=(0,Ut.useRef)(!1),fe=(0,Ut.useRef)(0);return be.current=C,Me.current=I,Se.current=w,Z.current=S,de.current=_,ye.current=K,(0,Ut.useEffect)(()=>{let j=fe.current+1;return fe.current=j,()=>{queueMicrotask(()=>{fe.current===j&&(Ie.current||_e.current||(_e.current=!0,(0,tt.invokeMerchantCallback)(()=>{de.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Ut.useEffect)(()=>{let j=!0,L=(0,Ar.resolveBillingApiUrl)(r),we=new bi.PaymentAPI(L,{telemetry:n});return T(null),P(null),A(null),Ie.current=!1,_e.current=!1,(async()=>{try{if(!e.trim())throw new Ar.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Ar.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Ne=await we.getUnifiedCheckoutSession(e,t);if(!j)return;let ke=Ne.data.session;if(!ke||!(0,Ar.isCardSetupCheckoutSession)(ke))throw new Ar.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let N=ke.vault;(0,Ar.isMountableVaultBlock)(N)||(N=await we.getVaultCapture(e,t));let dt=(0,Ar.resolveVaultMountOptions)(N,{billingApiUrl:L,sessionId:e,nonce:t});if(!dt)throw new Ar.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!j)return;P(dt),T(new bi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(Ne){if(!j)return;let ke=to(Ne);Ie.current=!0,A(ke),(0,tt.invokeMerchantCallback)(()=>Me.current?.(ke))}})(),()=>{j=!1,we.destroy()}},[r,t,e,n]),(0,Ut.useEffect)(()=>{if(!$)return;let j=!1;We.current=!1,pe.current=!1;let L=$.on("submitting",()=>{pe.current=!0,Ee(null),F("processing")}),we=$.on("complete",N=>{Ie.current=!0,pe.current=!1,F("success"),(async()=>(await new Promise(dt=>setTimeout(dt,600)),!We.current&&(We.current=!0,(0,tt.invokeMerchantCallback)(()=>{Se.current?.({status:"succeeded",sessionId:e,...N.paymentMethod?{paymentMethod:N.paymentMethod}:{}})}),j||F(null))))()}),Ne=$.on("decline",N=>{Ie.current=!0,pe.current=!1,Ee(N.message??null),F("error"),(0,tt.invokeMerchantCallback)(()=>{Z.current?.({status:"declined",sessionId:e,...N.declineReason?{reason:N.declineReason}:{},...N.message?{message:N.message}:{}})}),(async()=>(await new Promise(dt=>setTimeout(dt,400)),j||F(null)))()}),ke=$.on("challenge_dismissed",()=>{F(null)});return()=>{j=!0,L(),we(),Ne(),ke()}},[$,e]),ee?(0,Vn.jsx)("div",{role:"alert",children:ee.message}):!$||!h?.html?(0,Vn.jsx)(Vn.Fragment,{children:p}):(0,Vn.jsxs)(Vn.Fragment,{children:[ue&&(0,Vn.jsx)(qr,{status:ue,errorMessage:re,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...Y?{theme:Y}:{}}),(0,Vn.jsx)(lo,{capture:$,html:h.html,messageToken:h.messageToken,expectedOrigin:h.expectedOrigin,verificationRequired:h.verificationRequired,theme:wt,containerStyle:ct,onReady:()=>{(0,tt.invokeMerchantCallback)(()=>be.current?.())},onValidation:j=>{(0,tt.invokeMerchantCallback)(()=>ye.current?.(j))},onError:j=>{if(!j)return;pe.current&&(pe.current=!1,Ee(j),F("error"),setTimeout(()=>F(null),400));let L=to(new Error(j),{code:"card_setup_widget_failed",retryable:!0});(0,tt.invokeMerchantCallback)(()=>Me.current?.(L))}})]})}var ic=require("@flopay/js/card-setup"),co=require("@flopay/shared"),sc=require("@paypal/paypal-js"),bo=require("react");var cc=require("react/jsx-runtime");function lc({clientId:e,environment:t,currency:r,sessionId:n,nonce:o,billingApiUrl:i,telemetry:l,customer:{userId:u,email:p},onSubmitting:C,onConfirmed:w,onFailed:S,onAbandoned:_}){let K=(0,bo.useRef)(null),I=(0,bo.useRef)({onSubmitting:C,onConfirmed:w,onFailed:S,onAbandoned:_});I.current={onSubmitting:C,onConfirmed:w,onFailed:S,onAbandoned:_};let[$]=(0,bo.useState)(()=>(0,Un.detectPayPalEnvironment)().inAppBrowser);return(0,bo.useEffect)(()=>{let T=!0,h,P=new ic.PaymentAPI(i,{telemetry:l}),ee={userId:u,email:p};return(async()=>{try{let A=await(0,sc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),ue=K.current;if(!T||!ue)return;if(!A?.Buttons)throw new co.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let F=A.Buttons({createVaultSetupToken:async()=>{I.current.onSubmitting();let re=await P.createSessionIntent(n,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(re.provider!=="paypal"||re.providerObjectType!=="setup_token")throw new co.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return re.providerObjectId},onApprove:async re=>{let Ee=re.vaultSetupToken;if(!Ee)throw new co.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let pe=await P.processPayment(ee.userId,{sessionId:n,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:Ee,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:ee});if(!pe.ok)throw new co.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:pe.status});T&&I.current.onConfirmed()},onCancel:()=>{T&&I.current.onAbandoned()},onError:re=>{if(!T)return;let{popupBlocked:Ee}=(0,Ce.classifyExternalMethodFailure)(re,{inAppBrowser:$,handoffObserved:!1});I.current.onFailed(Ee?new Error((0,Ce.buildExternalMethodRecoveryMessage)("PayPal",!0,$)):re,{code:Ee?"popup_blocked":"paypal_setup_failed",retryable:!0})}});h=()=>F.close(),await F.render(ue)}catch(A){if(!T)return;I.current.onFailed(A,{code:"paypal_unavailable",retryable:!0})}})(),()=>{T=!1,h?.().catch(()=>{}),P.destroy()}},[i,e,r,p,t,$,o,n,l,u]),(0,cc.jsx)("div",{ref:K,"data-flopay-paypal-setup":""})}var uc=require("@flopay/js/card-setup"),uo=require("@flopay/shared"),$n=require("@stripe/react-stripe-js"),pc=require("@stripe/stripe-js"),Fr=require("react");var _r=require("react/jsx-runtime"),yc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Cs=new Map;function ru(e){let t=Cs.get(e);if(t)return t;let r=(0,pc.loadStripe)(e).catch(n=>{throw Cs.delete(e),n});return Cs.set(e,r),r}function nu(e){return e?(0,uo.toStripeAppearance)(e):void 0}function ou(e){return(0,Ce.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function dc(e){return e==="paypal"?"PayPal":(0,uo.getStripeMethodDisplayName)(e)}function au(){return typeof window>"u"?"":window.location.href}var iu={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function mc(e){let{publishableKey:t,method:r,currency:n,futureUse:o,futureUseUnsupported:i,appearance:l}=e,[u]=(0,Fr.useState)(()=>ru(t)),p=(0,Fr.useMemo)(()=>{let C=nu(l),w=(0,uo.resolveSetupFutureUsage)({futureUse:o,futureUseUnsupported:i},r,"setup");return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:yc[r]?.types??[r],...w?{setupFutureUsage:w}:{},...C?{appearance:C}:{}}},[l,n,o,i,r]);return(0,_r.jsx)($n.Elements,{stripe:u,options:p,children:(0,_r.jsx)(su,{...e})})}function su({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,appearance:l,themeId:u,buttonsLayout:p,onSubmitting:C,onConfirmed:w,onDeclined:S,onFailed:_,onValidation:K,onUnavailable:I}){let $=(0,$n.useStripe)(),T=(0,$n.useElements)(),[h,P]=(0,Fr.useState)(!1),[ee,A]=(0,Fr.useState)("loading"),[ue,F]=(0,Fr.useState)(!1),[re,Ee]=(0,Fr.useState)(!1),pe=(0,Fr.useRef)(!1),[We]=(0,Fr.useState)(()=>(0,Un.detectPayPalEnvironment)()),[wt,ce]=(0,Fr.useState)(!1),Y=(0,Fr.useCallback)((de,ye)=>{if((0,Ce.classifyExternalMethodFailure)(de,{inAppBrowser:We.inAppBrowser,handoffObserved:!1}).popupBlocked){ce(!0),_(new Error((0,Ce.buildExternalMethodRecoveryMessage)(dc(e),!0,We.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}_(ye.message===void 0?de:new Error(ye.message),{code:ye.code,retryable:!0})},[We.inAppBrowser,e,_]),ct=(0,Fr.useCallback)(async()=>{if(!(!$||!T||pe.current)){pe.current=!0,P(!0);try{let de=await T.submit();if(de.error){K(de.error.message??null);return}C();let ye=await new uc.PaymentAPI(o,{telemetry:i}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(ye.provider!=="stripe"||ye.intentKind!=="setup")throw new uo.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let Ie=await $.confirmSetup({elements:T,clientSecret:ye.clientSecret,confirmParams:{return_url:au()},redirect:"if_required"});if(Ie.error){ou(Ie.error)?S({...Ie.error.decline_code||Ie.error.code?{reason:Ie.error.decline_code??Ie.error.code}:{},...Ie.error.message?{message:Ie.error.message}:{}}):Y(Ie.error,{code:"payment_method_setup_provider_failed",message:Ie.error.message??"The payment method could not be saved."});return}w()}catch(de){Y(de,{code:"payment_method_setup_failed"})}finally{pe.current=!1,P(!1)}}},[o,t,T,e,n,w,S,C,K,Y,r,$,i]),be=yc[e]?.wallet,Me=be==="paypal"&&(0,zn.resolveStripePayPalPresentation)(We,"auto",wt?"blocked":We.popupCapability)==="redirect",Se=l?.variables?.borderRadius??p?.cardButton?.borderRadius??8;if(t==="wallet"&&be&&!Me)return(0,_r.jsxs)(_r.Fragment,{children:[(0,_r.jsx)(Yo,{}),(0,_r.jsx)(wa,{state:ee,borderRadius:Se,children:(0,_r.jsx)($n.ExpressCheckoutElement,{options:{...ai,paymentMethods:oi([e])},onReady:de=>{let ye=Sa(de,[be]);A(ye),ye==="unavailable"&&I()},onLoadError:()=>{A("load_error"),I()},onConfirm:()=>{ct()}})})]});let Z=dc(e);return(0,_r.jsxs)(_r.Fragment,{children:[ue?(0,_r.jsx)(ni,{method:e,themeId:u,hasNextStep:!0,highlighted:re,disabled:h,onClick:()=>Ee(de=>!de),backgroundColor:p?.cardButton?.backgroundColor,borderColor:p?.cardInputBorder,textColor:p?.cardButton?.color,borderRadius:Se}):null,(0,_r.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!re,style:re?{display:"flex",flexDirection:"column"}:iu,children:[(0,_r.jsx)($n.PaymentElement,{options:{layout:ii},onReady:()=>F(!0),onLoadError:()=>I(),onChange:de=>{de.complete&&K(null)}}),(0,_r.jsx)(si,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!$||!T||h||!re,onClick:()=>{ct()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:p?.submitButton,children:h?"Saving\u2026":`Save ${Z}`})]})]})}var xa=require("@flopay/js/card-setup"),fr=require("@flopay/shared"),Ge=Vi(require("react"),1);var Jo=require("@flopay/js/card-setup"),Sr=require("@flopay/shared");var or=require("react/jsx-runtime"),lu=15,cu=2e3;function du(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function bs(e){return new Promise(t=>setTimeout(t,e))}async function uu(e,t,r){if(!t.trim())throw new fr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new fr.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),o=n.data.session;if(!o||!(0,fr.isCardSetupCheckoutSession)(o))throw new fr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let i=(0,Sr.readSetupAdvertisement)(n);if(!(0,Sr.advertisesAnyMethod)(i)){let{skippedForMissingCurrency:l}=i,u=l.length>0?`FloPay: this setup session advertises only Stripe methods (${l.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new fr.FloPayError(u,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:o,advertisement:i}}async function pu(e,t,r,n,o){let i=t.vault??null;(0,fr.isMountableVaultBlock)(i)||(i=await e.getVaultCapture(r,n));let l=(0,fr.resolveVaultMountOptions)(i,{billingApiUrl:o,sessionId:r,nonce:n});if(!l)throw new fr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return l}var Si=class extends Ge.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function fc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,theme:l="modern-light",containerStyle:u,appearance:p,buttonsStyles:C,loading:w=null,onReady:S,onComplete:_,onDecline:K,onCancel:I,onValidation:$,onError:T}){let[h]=(0,Ge.useState)(Jo.readSetupRedirectReturn),[P,ee]=(0,Ge.useState)(null),[A,ue]=(0,Ge.useState)(!1),[F,re]=(0,Ge.useState)(null),[Ee,pe]=(0,Ge.useState)(null),[We,wt]=(0,Ge.useState)(null),[ce,Y]=(0,Ge.useState)(null),[ct,be]=(0,Ge.useState)(()=>new Set),Me=(0,Ge.useRef)(ct),Se=(0,Ge.useRef)(null);Se.current=P;let Z=(0,Ge.useRef)(!1),de=(0,Ge.useRef)(!1),ye=(0,Ge.useRef)(!1),Ie=(0,Ge.useRef)(!1),_e=(0,Ge.useRef)(0),fe=(0,Ge.useRef)(0),j=(0,Ge.useRef)(!1),{vaultTheme:L,surface:we,overlayTheme:Ne,appearance:ke,buttonsLayout:N}=(0,Ge.useMemo)(()=>Ci({theme:l,appearance:p,buttonsStyles:C}),[l,p,C]),dt=(0,Ge.useMemo)(()=>(0,ka.mergeCardSetupSurface)(we,u),[we,u]),ge=(0,Ge.useRef)({sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,onReady:S,onComplete:_,onDecline:K,onCancel:I,onValidation:$,onError:T});ge.current={sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,onReady:S,onComplete:_,onDecline:K,onCancel:I,onValidation:$,onError:T},(0,Ge.useEffect)(()=>{j.current=!0;let D=_e.current+1;return _e.current=D,()=>{j.current=!1,fe.current+=1,queueMicrotask(()=>{_e.current===D&&(ye.current||Ie.current||(Ie.current=!0,(0,tt.invokeMerchantCallback)(()=>{ge.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let Be=(0,Ge.useCallback)((D,Q)=>{ye.current=!0,Z.current=!1,Y({status:"success",wording:D,message:null}),(async()=>(await bs(600),!de.current&&(de.current=!0,(0,tt.invokeMerchantCallback)(()=>{ge.current.onComplete?.({status:"succeeded",sessionId:ge.current.sessionId,...Q?{paymentMethod:Q}:{}})}),j.current&&Y(null))))()},[]),Xe=(0,Ge.useCallback)((D,Q)=>{ye.current=!0,Z.current=!1,Y({status:"error",wording:D,message:Q.message??null}),(0,tt.invokeMerchantCallback)(()=>{ge.current.onDecline?.({status:"declined",sessionId:ge.current.sessionId,...Q.reason?{reason:Q.reason}:{},...Q.message?{message:Q.message}:{}})}),(async()=>(await bs(400),j.current&&Y(null)))()},[]),Ae=(0,Ge.useCallback)((D,Q)=>{Z.current?(Z.current=!1,Y({status:"error",wording:D,message:Q.message}),setTimeout(()=>{j.current&&Y(null)},400)):Y(null),(0,tt.invokeMerchantCallback)(()=>ge.current.onError?.(Q))},[]),at=(0,Ge.useCallback)(async D=>{let Q=fe.current+1;fe.current=Q;let xe=()=>!j.current||Q!==fe.current;Z.current=!0,Y({status:"processing",wording:"payment_method",message:null});let Oe=new xa.PaymentAPI((0,fr.resolveBillingApiUrl)(ge.current.billingApiUrl),{telemetry:ge.current.telemetry});try{for(let M=0;M<lu;M+=1){if((M>0||D.waitFirst)&&await bs(cu),xe())return;let Ft=await Oe.getUnifiedCheckoutSession(ge.current.sessionId,ge.current.nonce);if(xe())return;let Qt=Ft.data.session?.status;if(Qt==="complete"){ue(!0),Be("payment_method");return}if(Qt==="expired")throw new fr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new fr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(M){if(xe())return;let Ft=M instanceof fr.FloPayError&&M.code==="payment_method_setup_unverified";Ae("payment_method",to(M,Ft?{retryable:!0}:{}))}finally{Oe.destroy()}},[Ae,Be]);(0,Ge.useEffect)(()=>{let D=!0,Q=(0,fr.resolveBillingApiUrl)(o),xe=new xa.PaymentAPI(Q,{telemetry:i});ee(null),ue(!1),re(null),pe(null),wt(null);let Oe=new Set;return Me.current=Oe,be(Oe),ye.current=!1,Ie.current=!1,de.current=!1,(async()=>{try{let{session:M,advertisement:Ft}=await uu(xe,r,n);if(!D)return;let Qt={advertisement:Ft,customer:du(M),...M.futureUse?{futureUse:M.futureUse}:{},...M.futureUseUnsupported?{futureUseUnsupported:M.futureUseUnsupported}:{}};if(h){if((0,Jo.clearSetupRedirectParams)(),M.status==="complete"){ue(!0),ee(Qt),Be("payment_method");return}h.failed?Xe("payment_method",{reason:"redirect_failed"}):at({waitFirst:!0})}let ar=Ft.card?await pu(xe,M,r,n,Q):null;if(!D)return;ee(Qt),ar&&(pe(ar),re(new xa.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:i})))}catch(M){if(!D)return;let Ft=to(M);ye.current=!0,wt(Ft),(0,tt.invokeMerchantCallback)(()=>ge.current.onError?.(Ft))}})(),()=>{D=!1,xe.destroy()}},[o,n,h,Xe,Be,r,i,at]),(0,Ge.useEffect)(()=>{if(!F)return;Z.current=!1;let D=F.on("submitting",()=>{Z.current=!0,Y({status:"processing",wording:"card",message:null})}),Q=F.on("complete",M=>{Be("card",M.paymentMethod)}),xe=F.on("decline",M=>{Xe("card",{...M.declineReason?{reason:M.declineReason}:{},...M.message?{message:M.message}:{}})}),Oe=F.on("challenge_dismissed",()=>{Y(null)});return()=>{D(),Q(),xe(),Oe()}},[F,Xe,Be]);let Je=(0,Ge.useCallback)((D,Q,xe)=>{if(xe.retryable){Ae("payment_method",to(Q,xe));return}if(Me.current.has(D))return;let Oe=new Set(Me.current);Oe.add(D),Me.current=Oe,be(Oe);let M=Se.current?.advertisement,Ft=M?(0,Sr.advertisedMethodKeys)(M).some(Qt=>!Oe.has(Qt)):!1;Ae("payment_method",to(Q,{code:xe.code,retryable:Ft}))},[Ae]),Et=(0,Ge.useMemo)(()=>({onSubmitting:()=>{Z.current=!0,Y({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{at({waitFirst:!1})},onDeclined:D=>Xe("payment_method",D),onValidation:D=>{(0,tt.invokeMerchantCallback)(()=>ge.current.onValidation?.(D))},onAbandoned:()=>{Z.current=!1,Y(null)}}),[Xe,at]),zt=(0,Ge.useRef)(Je);zt.current=Je;let kt=(0,Ge.useRef)(new Map),Tt=D=>{let Q=kt.current.get(D);if(Q)return Q;let xe=(Oe,M)=>zt.current(D,Oe,M);return kt.current.set(D,xe),xe},U=(0,Ge.useCallback)(D=>{if(Me.current.has(D))return;let Q=new Set(Me.current);Q.add(D),Me.current=Q,be(Q);let xe=Se.current?.advertisement;xe&&(0,Sr.advertisedMethodKeys)(xe).some(M=>!Q.has(M))||Ae("payment_method",to(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[Ae]),he=(0,Ge.useRef)(U);he.current=U;let Ze=(0,Ge.useRef)(new Map),G=D=>{let Q=Ze.current.get(D);if(Q)return Q;let xe=()=>he.current(D);return Ze.current.set(D,xe),xe},je=ce?(0,or.jsx)(qr,{status:ce.status,errorMessage:ce.message,...(0,Sr.setupOverlayLabels)(ce.wording),successNote:null,...Ne?{theme:Ne}:{}}):null;if(We)return(0,or.jsx)("div",{role:"alert",children:We.message});if(!P||A)return(0,or.jsxs)(or.Fragment,{children:[je,P?null:w]});let{advertisement:ht,customer:Qe,futureUse:At,futureUseUnsupported:V}=P,y=(0,fr.resolveBillingApiUrl)(o),v=i===void 0?{}:{telemetry:i},W=ht.stripe.filter(({method:D})=>!ct.has(D)),z=ct.has("paypal")?null:ht.paypal,me=!!(ht.card&&F&&Ee?.html),Rt=({method:D,publishableKey:Q,currency:xe})=>(0,or.jsx)("div",{"data-flopay-payment-method":D,style:{display:"contents"},children:(0,or.jsx)(Si,{onFailed:Tt(D),children:(0,or.jsx)(Ge.Suspense,{fallback:null,children:(0,or.jsx)(e,{method:D,category:(0,Sr.stripeMethodCategory)(D),publishableKey:Q,currency:xe,...At?{futureUse:At}:{},...V?{futureUseUnsupported:V}:{},sessionId:r,nonce:n,billingApiUrl:y,...v,...ke?{appearance:ke}:{},...N?{buttonsLayout:N}:{},...typeof l=="string"?{themeId:l}:{},...Et,onFailed:Tt(D),onUnavailable:G(D)})})})},D),De=W.filter(({method:D})=>(0,Sr.stripeMethodCategory)(D)==="wallet"),it=W.filter(({method:D})=>(0,Sr.stripeMethodCategory)(D)!=="wallet"),ne=W.length>0||z!==null;return(0,or.jsxs)(or.Fragment,{children:[je,ne?(0,or.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[De.map(Rt),z?(0,or.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,or.jsx)(Si,{onFailed:Tt("paypal"),children:(0,or.jsx)(Ge.Suspense,{fallback:null,children:(0,or.jsx)(t,{clientId:z.clientId,...z.environment?{environment:z.environment}:{},...ht.currency?{currency:ht.currency}:{},sessionId:r,nonce:n,billingApiUrl:y,customer:Qe,...v,...Et,onFailed:Tt("paypal"),onUnavailable:G("paypal")})})})}):null,it.map(Rt)]}):null,me&&ne?(0,or.jsx)(li,{label:"or add a card"}):null,me&&F&&Ee?.html?(0,or.jsx)("div",{"data-flopay-payment-method":"card",children:(0,or.jsx)(lo,{capture:F,html:Ee.html,messageToken:Ee.messageToken,expectedOrigin:Ee.expectedOrigin,verificationRequired:Ee.verificationRequired,theme:L,containerStyle:dt,onReady:()=>{(0,tt.invokeMerchantCallback)(()=>ge.current.onReady?.())},onValidation:D=>{(0,tt.invokeMerchantCallback)(()=>ge.current.onValidation?.(D))},onError:D=>{D&&Ae("card",to(new Error(D),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var hc=require("react/jsx-runtime"),yu={StripeSetupMethod:mc,PayPalSetupMethod:lc};function gc(e){return(0,hc.jsx)(fc,{...e,branches:yu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,B.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&A(Xo),r&&(n||a)&&A(Xo),r&&(0,B.jsx)("button",{type:"button",onClick:()=>{e?.("card"),x(!0)},style:{width:"100%",...f,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:T.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,...T.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,B.jsx)(Bo,{content:p})}),(0,B.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var un=require("react/jsx-runtime"),Qd=44;function nc(e){return new Promise(t=>setTimeout(t,e))}function eu(e,t){return e instanceof pn.FloPayError?e:new pn.FloPayError(e instanceof Error?e.message:t,"api_error")}function tu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ru(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 oc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:a,clientId:i,products:l,items:u,subscriptions:p,account:v,successUrl:R,cancelUrl:w,couponCodes:x,tagsData:K,utmMetadata:T,billingApiUrl:V,locale:A,theme:f,appearance:P,buttonsTheme:ee,buttonsStyles:D,onSuccess:ue,onError:F,onDecline:ne,children:_e,disabled:ie=!1,type:We="button",style:kt,...de}){let G=(0,yt.useMemo)(()=>(0,pn.resolveBillingApiUrl)(V),[V]),pt=(0,yt.useMemo)(()=>ru({createSession:r,clientId:i,products:l,items:u,subscriptions:p,account:v,successUrl:R,cancelUrl:w,couponCodes:x,tagsData:K,utmMetadata:T}),[v,w,i,x,r,l,u,p,R,K,T]),[we,xe]=(0,yt.useState)(!1),[ke,Z]=(0,yt.useState)(null),[pe,Re]=(0,yt.useState)(null),[Fe,rt]=(0,yt.useState)(!1),[me,N]=(0,yt.useState)(null),[H,ye]=(0,yt.useState)(null),$e=(0,yt.useRef)(!0),he=(0,yt.useRef)(null),M=(0,yt.useRef)(H),Ye=(0,yt.useRef)(ue),Te=(0,yt.useRef)(F),tt=(0,yt.useRef)(ne),Ze=(0,yt.useCallback)(b=>Qa(he,async L=>{try{return await b(L)}catch(qe){throw L.aborted?Wo(qe):qe}}),[]);(0,yt.useEffect)(()=>{M.current=H},[H]),(0,yt.useEffect)(()=>{Ye.current=ue},[ue]),(0,yt.useEffect)(()=>{Te.current=F},[F]),(0,yt.useEffect)(()=>{tt.current=ne},[ne]),(0,yt.useEffect)(()=>($e.current=!0,()=>{$e.current=!1,he.current?.abort()}),[]),(0,yt.useEffect)(()=>{if(typeof window>"u")return;let b=L=>{L.key==="Escape"&&ye(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let ze=(0,yt.useCallback)((b,L=ba)=>{tt.current?.(Cr(L,b,{code:b.code,declineCode:b.declineCode}))},[]),He=(0,yt.useCallback)(async b=>{$e.current&&(Re(null),rt(b.result.status==="authorized"),Z("success"),await nc(600),$e.current&&(0,it.invokeMerchantCallback)(()=>Ye.current?.(b)))},[]),Le=(0,yt.useCallback)(async(b,L)=>{$e.current&&(Te.current?.(b),L?.emitDecline&&ze(b,L.method),Re(b.message),rt(!1),Z("error"),await nc(400))},[ze]),Et=(0,yt.useCallback)(async(b,L,qe)=>{let fe=b.data.session??null;if(!fe)throw io(new pn.FloPayError("No session data returned","api_error"),L);let h=fe.clientSecret||t;if(Yn(fe)){await He({result:Gn(fe,L),session:fe,sessionId:fe.id||L,autoCompleted:!1});return}if(fe.status==="expired")throw io(Wa(fe),fe.id||L);try{if(b.autoProcessingPending){let j=b.autoProcessingPending,Y=new vi.PaymentAPI(G),te=await Ze(be=>Y.waitForCheckoutSessionCompletion(j.sessionId,{initialDelayMs:j.retryAfterMs,nonce:h,statusUrl:j.statusUrl,signal:be})),k=so(te,fe),Q=te.autoProcessingError?.type==="3ds_required"&&te.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:te.autoProcessingError.nextActionRedirectUrl}:null;if(Q&&L&&h){let be=await Ze(Be=>$o(Q,{billingApiUrl:G,sessionId:L,nonce:h,session:fe,signal:Be,telemetry:!0}));await He({result:be,session:fe,sessionId:fe.id||L,autoCompleted:!1});return}if(te.autoProcessingError)throw qn(te.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:te.autoProcessingError.checkoutMethod});if(!Yn(k))throw Lo(k);await He({result:Gn(k,L),session:k,sessionId:k.id||L,autoCompleted:!1});return}if(b.autoProcessingError){let j=b.autoProcessingError.nextActionRedirectUrl;if(b.autoProcessingError.type==="3ds_required"&&j&&L&&h){let Y=await Ze(be=>Ml({billingApiUrl:G,sessionId:L,nonce:h,nextActionRedirectUrl:j,signal:be}));if(Y.status==="declined")throw qn({type:Y.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Y.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let k=await new vi.PaymentAPI(G).waitForCheckoutSessionCompletion(L,{initialDelayMs:0,nonce:h}),Q=so(k,fe);if(!Yn(Q))throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await He({result:Gn(Q,L),session:Q,sessionId:Q.id||L,autoCompleted:!1});return}throw qn(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(qe?.fromCreateSession&&b.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ve=await Ho({billingApiUrl:G,sessionId:L??fe.id,session:fe,nonce:h});if(ve.type==="next_action_required"&&h){let j=L??fe.id,Y=await Ze(te=>$o(ve,{billingApiUrl:G,sessionId:j,nonce:h,session:fe,signal:te,telemetry:!0}));await He({result:Y,session:fe,sessionId:fe.id||j,autoCompleted:!1});return}if(ve.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await He({result:ve.result,session:fe,sessionId:fe.id||L,autoCompleted:!1})}catch(ve){let j=fe.id||L,Y=io(Ca(ve),j);if(Y.code==="three_ds_aborted")return;if(Y.code==="checkout_processing_timeout"){if(!$e.current)return;N(Y.message),(0,it.invokeMerchantCallback)(()=>Te.current?.(Y));return}await Le(Y,{emitDecline:!0,method:Y.checkoutMethod??ba}),tu(Y,j)&&j&&$e.current&&ye({sessionId:j,errorMessage:Y.message,nonce:h||void 0,payPalOrderId:Y.orderId})}},[t,G,Ze,Le,He]),zt=(0,yt.useCallback)(async b=>{if(de.onClick?.(b),!(b.defaultPrevented||ie||we)){if(ye(null),N(null),e&&pt){let L=new pn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Le(L),$e.current&&(Z(null),Re(null));return}if(!e&&!pt){let L=new pn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Le(L),$e.current&&(Z(null),Re(null));return}xe(!0),Re(null),rt(!1),Z("processing");try{let L=new vi.PaymentAPI(G);if(e){let qe=await L.getUnifiedCheckoutSession(e,t);await Et(qe,e);return}try{let qe=await L.createAndFetchSession({...pt});await Et(qe,qe.data.session?.id??null,{fromCreateSession:!0})}catch(qe){if($a(qe)==="session_auto_completed"){await He({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw qe}}catch(L){await Le(io(eu(L,"Automatic payment failed. Please try again."),e))}finally{$e.current&&(Z(null),Re(null),xe(!1))}}},[de.onClick,pt,ie,we,t,Et,G,e,Le,He]),ft=(0,yt.useCallback)(b=>{let L=M.current;ye(null),Ye.current?.({result:b,session:null,sessionId:L?.sessionId??null,autoCompleted:!1})},[]),Ft=(0,yt.useCallback)(b=>{Te.current?.(b)},[]),q=(0,yt.useCallback)(b=>{tt.current?.(b)},[]),Pe=(0,yt.useMemo)(()=>(0,pn.resolveTheme)(f),[f]),st=(0,yt.useMemo)(()=>{let b=Pe?.buttonsLayout??(0,pn.resolveButtonsLayoutTheme)(ee);return D?{...b,...D,cardButton:{...b.cardButton,...D.cardButton}}:b},[Pe,ee,D]),W=(0,yt.useMemo)(()=>{let b=Pe?.appearance;return P?b?{...b,...P,variables:{...b.variables,...P.variables}}:P:b},[P,Pe]),Ee=W?.variables,nt=Ee?.colorPrimary??"#4A49FF",Ke=Ee?.colorPrimaryHover??(0,us.darkenHex)(nt,.12),Rt=Ee?.borderRadius??"8px";return(0,un.jsxs)(un.Fragment,{children:[(0,un.jsx)("button",{...de,type:We,onClick:zt,disabled:ie||we,"aria-busy":we,style:{width:"100%",..._e===void 0?{boxSizing:"border-box",height:Qd,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...st.cardButton,...ds({themeBundle:Pe,resolvedPrimaryColor:nt,resolvedBorderRadius:Rt,submitButtonStyle:st.submitButton,explicitPrimaryColor:Ee?.colorPrimary}),fontSize:st.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ie||we?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:ie||we?.6:1,...kt},onMouseEnter:b=>{de.onMouseEnter?.(b),!b.defaultPrevented&&!ie&&!we&&(Pe||Ee?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Ke)},onMouseLeave:b=>{de.onMouseLeave?.(b),!b.defaultPrevented&&(Pe||Ee?.colorPrimary)&&(b.currentTarget.style.backgroundColor=nt)},onMouseDown:b=>{de.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{de.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:(0,un.jsx)(Bo,{content:_e})}),me&&(0,un.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:me}),ke&&(0,un.jsx)(Wr,{status:ke,errorMessage:pe,authorized:Fe}),H&&(0,un.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:b=>{b.target===b.currentTarget&&ye(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:(0,un.jsx)("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:(0,un.jsx)(Pi,{sessionId:H.sessionId,nonce:H.nonce,checkoutMode:"full",billingApiUrl:G,locale:A,theme:f,...W?{appearance:W}:{},buttonsTheme:ee,buttonsStyles:D,initialErrorMessage:H.errorMessage,initialPayPalOrderId:H.payPalOrderId,cardTitleContent:null,onComplete:ft,onError:Ft,onDecline:q})})})]})}var Ci=require("@flopay/js/card-setup"),Dr=require("@flopay/shared"),Ut=require("react");var vs=require("@flopay/shared"),nu=require("@flopay/shared");function bi(e){let t=(0,vs.resolveCardSetupTheme)(e);return{...t,surface:t.surface,overlayTheme:t.overlayTheme}}var Vn=require("react/jsx-runtime"),Ma=class extends Dr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function to(e,t={}){let r=e instanceof Dr.FloPayError?e:void 0,n=r?.statusCode,a=t.retryable??(r?.type==="network_error"||r?.type==="rate_limit_error"||typeof n=="number"&&n>=500||r?.code==="vault_capture_timeout"||!r);return new Ma(r?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),r?.type??"api_error",{code:t.code??r?.code??"card_setup_load_failed",retryable:a,...r?.param?{param:r.param}:{},...n===void 0?{}:{statusCode:n}})}function ac({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:a="modern-light",containerStyle:i,appearance:l,buttonsStyles:u,loading:p=null,onReady:v,onComplete:R,onDecline:w,onCancel:x,onValidation:K,onError:T}){let[V,A]=(0,Ut.useState)(null),[f,P]=(0,Ut.useState)(null),[ee,D]=(0,Ut.useState)(null),[ue,F]=(0,Ut.useState)(null),[ne,_e]=(0,Ut.useState)(null),ie=(0,Ut.useRef)(!1),We=(0,Ut.useRef)(!1),{vaultTheme:kt,surface:de,overlayTheme:G}=(0,Ut.useMemo)(()=>bi({theme:a,appearance:l,buttonsStyles:u}),[a,l,u]),pt=(0,Ut.useMemo)(()=>(0,ka.mergeCardSetupSurface)(de,i),[de,i]),we=(0,Ut.useRef)(v),xe=(0,Ut.useRef)(T),ke=(0,Ut.useRef)(R),Z=(0,Ut.useRef)(w),pe=(0,Ut.useRef)(x),Re=(0,Ut.useRef)(K),Fe=(0,Ut.useRef)(!1),rt=(0,Ut.useRef)(!1),me=(0,Ut.useRef)(0);return we.current=v,xe.current=T,ke.current=R,Z.current=w,pe.current=x,Re.current=K,(0,Ut.useEffect)(()=>{let N=me.current+1;return me.current=N,()=>{queueMicrotask(()=>{me.current===N&&(Fe.current||rt.current||(rt.current=!0,(0,it.invokeMerchantCallback)(()=>{pe.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Ut.useEffect)(()=>{let N=!0,H=(0,Dr.resolveBillingApiUrl)(r),ye=new Ci.PaymentAPI(H,{telemetry:n});return A(null),P(null),D(null),Fe.current=!1,rt.current=!1,(async()=>{try{if(!e.trim())throw new Dr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Dr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let $e=await ye.getUnifiedCheckoutSession(e,t);if(!N)return;let he=$e.data.session;if(!he||!(0,Dr.isCardSetupCheckoutSession)(he))throw new Dr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let M=he.vault;(0,Dr.isMountableVaultBlock)(M)||(M=await ye.getVaultCapture(e,t));let Ye=(0,Dr.resolveVaultMountOptions)(M,{billingApiUrl:H,sessionId:e,nonce:t});if(!Ye)throw new Dr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!N)return;P(Ye),A(new Ci.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch($e){if(!N)return;let he=to($e);Fe.current=!0,D(he),(0,it.invokeMerchantCallback)(()=>xe.current?.(he))}})(),()=>{N=!1,ye.destroy()}},[r,t,e,n]),(0,Ut.useEffect)(()=>{if(!V)return;let N=!1;We.current=!1,ie.current=!1;let H=V.on("submitting",()=>{ie.current=!0,_e(null),F("processing")}),ye=V.on("complete",M=>{Fe.current=!0,ie.current=!1,F("success"),(async()=>(await new Promise(Ye=>setTimeout(Ye,600)),!We.current&&(We.current=!0,(0,it.invokeMerchantCallback)(()=>{ke.current?.({status:"succeeded",sessionId:e,...M.paymentMethod?{paymentMethod:M.paymentMethod}:{}})}),N||F(null))))()}),$e=V.on("decline",M=>{Fe.current=!0,ie.current=!1,_e(M.message??null),F("error"),(0,it.invokeMerchantCallback)(()=>{Z.current?.({status:"declined",sessionId:e,...M.declineReason?{reason:M.declineReason}:{},...M.message?{message:M.message}:{}})}),(async()=>(await new Promise(Ye=>setTimeout(Ye,400)),N||F(null)))()}),he=V.on("challenge_dismissed",()=>{F(null)});return()=>{N=!0,H(),ye(),$e(),he()}},[V,e]),ee?(0,Vn.jsx)("div",{role:"alert",children:ee.message}):!V||!f?.html?(0,Vn.jsx)(Vn.Fragment,{children:p}):(0,Vn.jsxs)(Vn.Fragment,{children:[ue&&(0,Vn.jsx)(Wr,{status:ue,errorMessage:ne,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...G?{theme:G}:{}}),(0,Vn.jsx)(lo,{capture:V,html:f.html,messageToken:f.messageToken,expectedOrigin:f.expectedOrigin,verificationRequired:f.verificationRequired,theme:kt,containerStyle:pt,onReady:()=>{(0,it.invokeMerchantCallback)(()=>we.current?.())},onValidation:N=>{(0,it.invokeMerchantCallback)(()=>Re.current?.(N))},onError:N=>{if(!N)return;ie.current&&(ie.current=!1,_e(N),F("error"),setTimeout(()=>F(null),400));let H=to(new Error(N),{code:"card_setup_widget_failed",retryable:!0});(0,it.invokeMerchantCallback)(()=>xe.current?.(H))}})]})}var ic=require("@flopay/js/card-setup"),co=require("@flopay/shared"),sc=require("@paypal/paypal-js"),Co=require("react");var cc=require("react/jsx-runtime");function lc({clientId:e,environment:t,currency:r,sessionId:n,nonce:a,billingApiUrl:i,telemetry:l,customer:{userId:u,email:p},onSubmitting:v,onConfirmed:R,onFailed:w,onAbandoned:x}){let K=(0,Co.useRef)(null),T=(0,Co.useRef)({onSubmitting:v,onConfirmed:R,onFailed:w,onAbandoned:x});T.current={onSubmitting:v,onConfirmed:R,onFailed:w,onAbandoned:x};let[V]=(0,Co.useState)(()=>(0,Un.detectPayPalEnvironment)().inAppBrowser);return(0,Co.useEffect)(()=>{let A=!0,f,P=new ic.PaymentAPI(i,{telemetry:l}),ee={userId:u,email:p};return(async()=>{try{let D=await(0,sc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),ue=K.current;if(!A||!ue)return;if(!D?.Buttons)throw new co.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let F=D.Buttons({createVaultSetupToken:async()=>{T.current.onSubmitting();let ne=await P.createSessionIntent(n,a,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(ne.provider!=="paypal"||ne.providerObjectType!=="setup_token")throw new co.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return ne.providerObjectId},onApprove:async ne=>{let _e=ne.vaultSetupToken;if(!_e)throw new co.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let ie=await P.processPayment(ee.userId,{sessionId:n,nonce:a,paymentMethodCategory:"paypal",tokenizedData:{id:_e,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:ee});if(!ie.ok)throw new co.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:ie.status});A&&T.current.onConfirmed()},onCancel:()=>{A&&T.current.onAbandoned()},onError:ne=>{if(!A)return;let{popupBlocked:_e}=(0,Se.classifyExternalMethodFailure)(ne,{inAppBrowser:V,handoffObserved:!1});T.current.onFailed(_e?new Error((0,Se.buildExternalMethodRecoveryMessage)("PayPal",!0,V)):ne,{code:_e?"popup_blocked":"paypal_setup_failed",retryable:!0})}});f=()=>F.close(),await F.render(ue)}catch(D){if(!A)return;T.current.onFailed(D,{code:"paypal_unavailable",retryable:!0})}})(),()=>{A=!1,f?.().catch(()=>{}),P.destroy()}},[i,e,r,p,t,V,a,n,l,u]),(0,cc.jsx)("div",{ref:K,"data-flopay-paypal-setup":""})}var uc=require("@flopay/js/card-setup"),uo=require("@flopay/shared"),Wn=require("@stripe/react-stripe-js"),pc=require("@stripe/stripe-js"),Or=require("react");var Mr=require("react/jsx-runtime"),mc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},bs=new Map;function ou(e){let t=bs.get(e);if(t)return t;let r=(0,pc.loadStripe)(e).catch(n=>{throw bs.delete(e),n});return bs.set(e,r),r}function au(e){return e?(0,uo.toStripeAppearance)(e):void 0}function iu(e){return(0,Se.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function dc(e){return e==="paypal"?"PayPal":(0,uo.getStripeMethodDisplayName)(e)}function su(){return typeof window>"u"?"":window.location.href}var lu={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function yc(e){let{publishableKey:t,method:r,currency:n,futureUse:a,futureUseUnsupported:i,appearance:l}=e,[u]=(0,Or.useState)(()=>ou(t)),p=(0,Or.useMemo)(()=>{let v=au(l),R=(0,uo.resolveSetupFutureUsage)({futureUse:a,futureUseUnsupported:i},r,"setup");return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:mc[r]?.types??[r],...R?{setupFutureUsage:R}:{},...v?{appearance:v}:{}}},[l,n,a,i,r]);return(0,Mr.jsx)(Wn.Elements,{stripe:u,options:p,children:(0,Mr.jsx)(cu,{...e})})}function cu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,appearance:l,themeId:u,buttonsLayout:p,onSubmitting:v,onConfirmed:R,onDeclined:w,onFailed:x,onValidation:K,onUnavailable:T}){let V=(0,Wn.useStripe)(),A=(0,Wn.useElements)(),[f,P]=(0,Or.useState)(!1),[ee,D]=(0,Or.useState)("loading"),[ue,F]=(0,Or.useState)(!1),[ne,_e]=(0,Or.useState)(!1),ie=(0,Or.useRef)(!1),[We]=(0,Or.useState)(()=>(0,Un.detectPayPalEnvironment)()),[kt,de]=(0,Or.useState)(!1),G=(0,Or.useCallback)((pe,Re)=>{if((0,Se.classifyExternalMethodFailure)(pe,{inAppBrowser:We.inAppBrowser,handoffObserved:!1}).popupBlocked){de(!0),x(new Error((0,Se.buildExternalMethodRecoveryMessage)(dc(e),!0,We.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}x(Re.message===void 0?pe:new Error(Re.message),{code:Re.code,retryable:!0})},[We.inAppBrowser,e,x]),pt=(0,Or.useCallback)(async()=>{if(!(!V||!A||ie.current)){ie.current=!0,P(!0);try{let pe=await A.submit();if(pe.error){K(pe.error.message??null);return}v();let Re=await new uc.PaymentAPI(a,{telemetry:i}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(Re.provider!=="stripe"||Re.intentKind!=="setup")throw new uo.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let Fe=await V.confirmSetup({elements:A,clientSecret:Re.clientSecret,confirmParams:{return_url:su()},redirect:"if_required"});if(Fe.error){iu(Fe.error)?w({...Fe.error.decline_code||Fe.error.code?{reason:Fe.error.decline_code??Fe.error.code}:{},...Fe.error.message?{message:Fe.error.message}:{}}):G(Fe.error,{code:"payment_method_setup_provider_failed",message:Fe.error.message??"The payment method could not be saved."});return}R()}catch(pe){G(pe,{code:"payment_method_setup_failed"})}finally{ie.current=!1,P(!1)}}},[a,t,A,e,n,R,w,v,K,G,r,V,i]),we=mc[e]?.wallet,xe=we==="paypal"&&(0,zn.resolveStripePayPalPresentation)(We,"auto",kt?"blocked":We.popupCapability)==="redirect",ke=l?.variables?.borderRadius??p?.cardButton?.borderRadius??8;if(t==="wallet"&&we&&!xe)return(0,Mr.jsxs)(Mr.Fragment,{children:[(0,Mr.jsx)(Yo,{}),(0,Mr.jsx)(wa,{state:ee,borderRadius:ke,children:(0,Mr.jsx)(Wn.ExpressCheckoutElement,{options:{...ai,paymentMethods:oi([e])},onReady:pe=>{let Re=Sa(pe,[we]);D(Re),Re==="unavailable"&&T()},onLoadError:()=>{D("load_error"),T()},onConfirm:()=>{pt()}})})]});let Z=dc(e);return(0,Mr.jsxs)(Mr.Fragment,{children:[ue?(0,Mr.jsx)(ni,{method:e,themeId:u,hasNextStep:!0,highlighted:ne,disabled:f,onClick:()=>_e(pe=>!pe),backgroundColor:p?.cardButton?.backgroundColor,borderColor:p?.cardInputBorder,textColor:p?.cardButton?.color,borderRadius:ke}):null,(0,Mr.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ne,style:ne?{display:"flex",flexDirection:"column"}:lu,children:[(0,Mr.jsx)(Wn.PaymentElement,{options:{layout:ii},onReady:()=>F(!0),onLoadError:()=>T(),onChange:pe=>{pe.complete&&K(null)}}),(0,Mr.jsx)(si,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!V||!A||f||!ne,onClick:()=>{pt()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:p?.submitButton,children:f?"Saving\u2026":`Save ${Z}`})]})]})}var xa=require("@flopay/js/card-setup"),fr=require("@flopay/shared"),Je=Vi(require("react"),1);var Jo=require("@flopay/js/card-setup"),kr=require("@flopay/shared");var ir=require("react/jsx-runtime"),du=15,uu=2e3;function pu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Cs(e){return new Promise(t=>setTimeout(t,e))}async function mu(e,t,r){if(!t.trim())throw new fr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new fr.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let n=await e.getUnifiedCheckoutSession(t,r),a=n.data.session;if(!a||!(0,fr.isCardSetupCheckoutSession)(a))throw new fr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let i=(0,kr.readSetupAdvertisement)(n);if(!(0,kr.advertisesAnyMethod)(i)){let{skippedForMissingCurrency:l}=i,u=l.length>0?`FloPay: this setup session advertises only Stripe methods (${l.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new fr.FloPayError(u,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:a,advertisement:i}}async function yu(e,t,r,n,a){let i=t.vault??null;(0,fr.isMountableVaultBlock)(i)||(i=await e.getVaultCapture(r,n));let l=(0,fr.resolveVaultMountOptions)(i,{billingApiUrl:a,sessionId:r,nonce:n});if(!l)throw new fr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return l}var Si=class extends Je.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(r){this.props.onFailed(r,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function fc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,theme:l="modern-light",containerStyle:u,appearance:p,buttonsStyles:v,loading:R=null,onReady:w,onComplete:x,onDecline:K,onCancel:T,onValidation:V,onError:A}){let[f]=(0,Je.useState)(Jo.readSetupRedirectReturn),[P,ee]=(0,Je.useState)(null),[D,ue]=(0,Je.useState)(!1),[F,ne]=(0,Je.useState)(null),[_e,ie]=(0,Je.useState)(null),[We,kt]=(0,Je.useState)(null),[de,G]=(0,Je.useState)(null),[pt,we]=(0,Je.useState)(()=>new Set),xe=(0,Je.useRef)(pt),ke=(0,Je.useRef)(null);ke.current=P;let Z=(0,Je.useRef)(!1),pe=(0,Je.useRef)(!1),Re=(0,Je.useRef)(!1),Fe=(0,Je.useRef)(!1),rt=(0,Je.useRef)(0),me=(0,Je.useRef)(0),N=(0,Je.useRef)(!1),{vaultTheme:H,surface:ye,overlayTheme:$e,appearance:he,buttonsLayout:M}=(0,Je.useMemo)(()=>bi({theme:l,appearance:p,buttonsStyles:v}),[l,p,v]),Ye=(0,Je.useMemo)(()=>(0,ka.mergeCardSetupSurface)(ye,u),[ye,u]),Te=(0,Je.useRef)({sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,onReady:w,onComplete:x,onDecline:K,onCancel:T,onValidation:V,onError:A});Te.current={sessionId:r,nonce:n,billingApiUrl:a,telemetry:i,onReady:w,onComplete:x,onDecline:K,onCancel:T,onValidation:V,onError:A},(0,Je.useEffect)(()=>{N.current=!0;let k=rt.current+1;return rt.current=k,()=>{N.current=!1,me.current+=1,queueMicrotask(()=>{rt.current===k&&(Re.current||Fe.current||(Fe.current=!0,(0,it.invokeMerchantCallback)(()=>{Te.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let tt=(0,Je.useCallback)((k,Q)=>{Re.current=!0,Z.current=!1,G({status:"success",wording:k,message:null}),(async()=>(await Cs(600),!pe.current&&(pe.current=!0,(0,it.invokeMerchantCallback)(()=>{Te.current.onComplete?.({status:"succeeded",sessionId:Te.current.sessionId,...Q?{paymentMethod:Q}:{}})}),N.current&&G(null))))()},[]),Ze=(0,Je.useCallback)((k,Q)=>{Re.current=!0,Z.current=!1,G({status:"error",wording:k,message:Q.message??null}),(0,it.invokeMerchantCallback)(()=>{Te.current.onDecline?.({status:"declined",sessionId:Te.current.sessionId,...Q.reason?{reason:Q.reason}:{},...Q.message?{message:Q.message}:{}})}),(async()=>(await Cs(400),N.current&&G(null)))()},[]),ze=(0,Je.useCallback)((k,Q)=>{Z.current?(Z.current=!1,G({status:"error",wording:k,message:Q.message}),setTimeout(()=>{N.current&&G(null)},400)):G(null),(0,it.invokeMerchantCallback)(()=>Te.current.onError?.(Q))},[]),He=(0,Je.useCallback)(async k=>{let Q=me.current+1;me.current=Q;let be=()=>!N.current||Q!==me.current;Z.current=!0,G({status:"processing",wording:"payment_method",message:null});let Be=new xa.PaymentAPI((0,fr.resolveBillingApiUrl)(Te.current.billingApiUrl),{telemetry:Te.current.telemetry});try{for(let S=0;S<du;S+=1){if((S>0||k.waitFirst)&&await Cs(uu),be())return;let Bt=await Be.getUnifiedCheckoutSession(Te.current.sessionId,Te.current.nonce);if(be())return;let rr=Bt.data.session?.status;if(rr==="complete"){ue(!0),tt("payment_method");return}if(rr==="expired")throw new fr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new fr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(S){if(be())return;let Bt=S instanceof fr.FloPayError&&S.code==="payment_method_setup_unverified";ze("payment_method",to(S,Bt?{retryable:!0}:{}))}finally{Be.destroy()}},[ze,tt]);(0,Je.useEffect)(()=>{let k=!0,Q=(0,fr.resolveBillingApiUrl)(a),be=new xa.PaymentAPI(Q,{telemetry:i});ee(null),ue(!1),ne(null),ie(null),kt(null);let Be=new Set;return xe.current=Be,we(Be),Re.current=!1,Fe.current=!1,pe.current=!1,(async()=>{try{let{session:S,advertisement:Bt}=await mu(be,r,n);if(!k)return;let rr={advertisement:Bt,customer:pu(S),...S.futureUse?{futureUse:S.futureUse}:{},...S.futureUseUnsupported?{futureUseUnsupported:S.futureUseUnsupported}:{}};if(f){if((0,Jo.clearSetupRedirectParams)(),S.status==="complete"){ue(!0),ee(rr),tt("payment_method");return}f.failed?Ze("payment_method",{reason:"redirect_failed"}):He({waitFirst:!0})}let sr=Bt.card?await yu(be,S,r,n,Q):null;if(!k)return;ee(rr),sr&&(ie(sr),ne(new xa.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:i})))}catch(S){if(!k)return;let Bt=to(S);Re.current=!0,kt(Bt),(0,it.invokeMerchantCallback)(()=>Te.current.onError?.(Bt))}})(),()=>{k=!1,be.destroy()}},[a,n,f,Ze,tt,r,i,He]),(0,Je.useEffect)(()=>{if(!F)return;Z.current=!1;let k=F.on("submitting",()=>{Z.current=!0,G({status:"processing",wording:"card",message:null})}),Q=F.on("complete",S=>{tt("card",S.paymentMethod)}),be=F.on("decline",S=>{Ze("card",{...S.declineReason?{reason:S.declineReason}:{},...S.message?{message:S.message}:{}})}),Be=F.on("challenge_dismissed",()=>{G(null)});return()=>{k(),Q(),be(),Be()}},[F,Ze,tt]);let Le=(0,Je.useCallback)((k,Q,be)=>{if(be.retryable){ze("payment_method",to(Q,be));return}if(xe.current.has(k))return;let Be=new Set(xe.current);Be.add(k),xe.current=Be,we(Be);let S=ke.current?.advertisement,Bt=S?(0,kr.advertisedMethodKeys)(S).some(rr=>!Be.has(rr)):!1;ze("payment_method",to(Q,{code:be.code,retryable:Bt}))},[ze]),Et=(0,Je.useMemo)(()=>({onSubmitting:()=>{Z.current=!0,G({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{He({waitFirst:!1})},onDeclined:k=>Ze("payment_method",k),onValidation:k=>{(0,it.invokeMerchantCallback)(()=>Te.current.onValidation?.(k))},onAbandoned:()=>{Z.current=!1,G(null)}}),[Ze,He]),zt=(0,Je.useRef)(Le);zt.current=Le;let ft=(0,Je.useRef)(new Map),Ft=k=>{let Q=ft.current.get(k);if(Q)return Q;let be=(Be,S)=>zt.current(k,Be,S);return ft.current.set(k,be),be},q=(0,Je.useCallback)(k=>{if(xe.current.has(k))return;let Q=new Set(xe.current);Q.add(k),xe.current=Q,we(Q);let be=ke.current?.advertisement;be&&(0,kr.advertisedMethodKeys)(be).some(S=>!Q.has(S))||ze("payment_method",to(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ze]),Pe=(0,Je.useRef)(q);Pe.current=q;let st=(0,Je.useRef)(new Map),W=k=>{let Q=st.current.get(k);if(Q)return Q;let be=()=>Pe.current(k);return st.current.set(k,be),be},Ee=de?(0,ir.jsx)(Wr,{status:de.status,errorMessage:de.message,...(0,kr.setupOverlayLabels)(de.wording),successNote:null,...$e?{theme:$e}:{}}):null;if(We)return(0,ir.jsx)("div",{role:"alert",children:We.message});if(!P||D)return(0,ir.jsxs)(ir.Fragment,{children:[Ee,P?null:R]});let{advertisement:nt,customer:Ke,futureUse:Rt,futureUseUnsupported:qt}=P,b=(0,fr.resolveBillingApiUrl)(a),L=i===void 0?{}:{telemetry:i},qe=nt.stripe.filter(({method:k})=>!pt.has(k)),fe=pt.has("paypal")?null:nt.paypal,h=!!(nt.card&&F&&_e?.html),ve=({method:k,publishableKey:Q,currency:be})=>(0,ir.jsx)("div",{"data-flopay-payment-method":k,style:{display:"contents"},children:(0,ir.jsx)(Si,{onFailed:Ft(k),children:(0,ir.jsx)(Je.Suspense,{fallback:null,children:(0,ir.jsx)(e,{method:k,category:(0,kr.stripeMethodCategory)(k),publishableKey:Q,currency:be,...Rt?{futureUse:Rt}:{},...qt?{futureUseUnsupported:qt}:{},sessionId:r,nonce:n,billingApiUrl:b,...L,...he?{appearance:he}:{},...M?{buttonsLayout:M}:{},...typeof l=="string"?{themeId:l}:{},...Et,onFailed:Ft(k),onUnavailable:W(k)})})})},k),j=qe.filter(({method:k})=>(0,kr.stripeMethodCategory)(k)==="wallet"),Y=qe.filter(({method:k})=>(0,kr.stripeMethodCategory)(k)!=="wallet"),te=qe.length>0||fe!==null;return(0,ir.jsxs)(ir.Fragment,{children:[Ee,te?(0,ir.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[j.map(ve),fe?(0,ir.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,ir.jsx)(Si,{onFailed:Ft("paypal"),children:(0,ir.jsx)(Je.Suspense,{fallback:null,children:(0,ir.jsx)(t,{clientId:fe.clientId,...fe.environment?{environment:fe.environment}:{},...nt.currency?{currency:nt.currency}:{},sessionId:r,nonce:n,billingApiUrl:b,customer:Ke,...L,...Et,onFailed:Ft("paypal"),onUnavailable:W("paypal")})})})}):null,Y.map(ve)]}):null,h&&te?(0,ir.jsx)(li,{label:"or add a card"}):null,h&&F&&_e?.html?(0,ir.jsx)("div",{"data-flopay-payment-method":"card",children:(0,ir.jsx)(lo,{capture:F,html:_e.html,messageToken:_e.messageToken,expectedOrigin:_e.expectedOrigin,verificationRequired:_e.verificationRequired,theme:H,containerStyle:Ye,onReady:()=>{(0,it.invokeMerchantCallback)(()=>Te.current.onReady?.())},onValidation:k=>{(0,it.invokeMerchantCallback)(()=>Te.current.onValidation?.(k))},onError:k=>{k&&ze("card",to(new Error(k),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var hc=require("react/jsx-runtime"),fu={StripeSetupMethod:yc,PayPalSetupMethod:lc};function gc(e){return(0,hc.jsx)(fc,{...e,branches:fu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});