@flopay/react 1.11.6 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var Oc=Object.create;var $a=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)$a(e,r,{get:t[r],enumerable:!0})},sl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Nc(t))!zc.call(e,o)&&o!==r&&$a(e,o,{get:()=>t[o],enumerable:!(n=Lc(t,o))||n.enumerable});return e};var $i=(e,t,r)=>(r=e!=null?Oc(Uc(e)):{},sl(t||!e||!e.__esModule?$a(r,"default",{value:e,enumerable:!0}):r,e)),jc=e=>sl($a({},"__esModule",{value:!0}),e);var mu={};qc(mu,{DirectPayPalButton:()=>ha,FloPayAutomaticPaymentButton:()=>nc,FloPayCardSetup:()=>ac,FloPayCardSetupError:()=>xa,FloPayCheckout:()=>vi,FloPayPaymentMethodSetup:()=>gc,FloPayProvider:()=>va,SplitCardForm:()=>fi,VaultCardFields:()=>co,dropThirdPartyOnlyError:()=>Pc.dropThirdPartyOnlyError,useCheckout:()=>Pl,useFloPay:()=>Zn,usePayPalFloPay:()=>Ga});module.exports=jc(mu);var Pc=require("@flopay/shared");var bi=require("@flopay/js"),un=require("@flopay/shared"),pt=require("react");var Wt=require("react/jsx-runtime");function Vc(){return(0,Wt.jsxs)(Wt.Fragment,{children:[(0,Wt.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,Wt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Wt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Wt.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,Wt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function $c(){return(0,Wt.jsx)(Wt.Fragment,{children:"Go back"})}function Wc(){return(0,Wt.jsx)(Wt.Fragment,{children:"Secure card checkout"})}function Bo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Do({content:e}){return(0,Wt.jsx)(Wt.Fragment,{children:e===void 0?(0,Wt.jsx)(Vc,{}):e})}function Oo({content:e}){return(0,Wt.jsx)(Wt.Fragment,{children:e===void 0?(0,Wt.jsx)($c,{}):e})}function ua({content:e}){return(0,Wt.jsx)(Wt.Fragment,{children:e===void 0?(0,Wt.jsx)(Wc,{}):e})}var gt=require("@flopay/shared"),Rn=require("@flopay/shared"),Uo=require("@flopay/shared"),Po=require("@flopay/shared"),Hc="Checkout is temporarily unavailable. Please try again later.";function Wi(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 ll(){return new gt.FloPayError(Hc,"api_error",{code:"CheckoutInitializationFailed"})}function cl(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 dl(e,t){if(t&&(!(e instanceof gt.FloPayError)||e.type==="authentication_error"))return Wi(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 Lo(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()},d=(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[b,k]of Object.entries(l)){if(d&&b.endsWith("Name")||typeof k!="string")continue;let w=k.trim();w&&(p[b]=w)}return o=e.claimCheckoutSession(t,r,{accountData:p}),o.catch(()=>{}),o}}function ul(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 Hi(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 pl(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 Ki(e,t){return t?{...e,...t}:e}function gr(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 so(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}function Yn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Xn(e){return e?.status==="authorized"||e?.status==="complete"}function lo(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 Wa(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 Ha(e){return e instanceof gt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function No(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 pa(e,t){return e==="processing"||(0,gt.isMoneySettledOutcome)(e,t)}function yl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function fl(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 gl(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 Gi(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 ma(e){let t=[e?.id,e?.originalPaymentMethodId];for(let r of t)if(typeof r=="string"&&r.startsWith("pm_"))return r}var to=require("@flopay/js"),ze=require("@flopay/shared"),C=$i(require("react"),1);var Yi=require("react"),on=(0,Yi.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),En=(0,Yi.createContext)({session:null,loading:!1,error:null});var Za=require("@flopay/js"),at=require("@flopay/shared"),Sl=require("@paypal/paypal-js"),I=require("react");var Ka=require("@flopay/shared"),In=require("react"),an=require("@flopay/shared"),Jn=require("react/jsx-runtime");function zo(){let[e,t]=(0,In.useState)(null),r=(0,In.useRef)(null),n=(0,In.useRef)(0),o=(0,In.useCallback)((l,d)=>(r.current?.(null),n.current+=1,t({id:n.current,methodLabel:l,identity:d}),new Promise(p=>{r.current=p})),[]),i=(0,In.useCallback)(l=>{let d=r.current;r.current=null,t(null),d?.(l)},[]);return(0,In.useEffect)(()=>()=>{r.current?.(null),r.current=null},[]),{request:e,collect:o,finish:i}}function qo({identity:e,methodLabel:t,onComplete:r,onCancel:n,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[l,d]=(0,In.useState)(e.email?.trim()??""),p=(0,Ka.isValidEmail)(l.trim());return(0,Jn.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,Jn.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Jn.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Jn.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:b=>d(b.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Jn.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[n&&(0,Jn.jsx)("button",{type:"button",onClick:n,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Jn.jsxs)("button",{type:"button",disabled:!p||o,onClick:()=>{r((0,Ka.compactBuyerIdentity)({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var ke=require("@flopay/shared");var hl=require("@flopay/shared"),ya=require("react");function Zn(){return(0,ya.useContext)(on).flopay}function Ga(){return(0,ya.useContext)(on).paypalFlopay??null}function Pl(){return(0,ya.useContext)(En)}function vl(){return(0,ya.useContext)(on).billingApiUrl||(0,hl.resolveBillingApiUrl)()}var Xc=require("@flopay/shared"),zn=require("@flopay/shared"),qn=require("@flopay/shared");var jo=require("@flopay/shared"),bo=require("react");var Ya=require("react"),vo=typeof window>"u"?Ya.useEffect:Ya.useLayoutEffect;var Xi=require("@flopay/shared");function Vo(e,t){let r=(0,bo.useRef)(e);r.current=e;let n=(0,bo.useRef)(new Set),o=(0,bo.useRef)(t),i=(0,bo.useRef)(t);return vo(()=>{i.current=t,o.current!==t&&(o.current=t,n.current.clear())},[t]),(0,bo.useCallback)(l=>{if(i.current!==t)return;let d=(0,jo.projectFloInstrument)(l);if(d){if(jo.FLO_INSTRUMENT_ONCE_NAMES.has(d.name)){if(n.current.has(d.name))return;n.current.add(d.name)}(0,jo.invokeMerchantCallback)(()=>r.current?.(d))}},[t])}var tt=require("@flopay/shared");var bl=require("react"),fa=(0,bl.createContext)(null);function Xa(){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 Ja(e){let t=globalThis[Zc];return ed(t?.(e)??{})}function hr(e){if(e)return e[Jc]}var cr=require("react");function ga(e,t){let r=(0,cr.useRef)(0),n=(0,cr.useRef)(null),o=(0,cr.useRef)(null),i=(0,cr.useRef)(e),l=(0,cr.useRef)(t?.onHandoffObserved),d=(0,cr.useRef)(t?.defersMissingTerminal),p=(0,cr.useRef)(t?.onMissingTerminalDeferred);(0,cr.useEffect)(()=>{i.current=e,l.current=t?.onHandoffObserved,d.current=t?.defersMissingTerminal,p.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let b=(0,cr.useCallback)((h=o.current)=>{h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),k=(0,cr.useCallback)(h=>{b();let v=r.current+1;return r.current=v,n.current=null,o.current={generation:v,method:h,timer:null,yieldedControl:!1},v},[b]),w=(0,cr.useCallback)(h=>{let v=o.current;return h!==void 0&&v?.generation!==h?!1:(b(v),o.current=null,(h===void 0||n.current===h)&&(n.current=null),!0)},[b]),x=(0,cr.useCallback)(h=>{let v=o.current,te=h??v?.generation??r.current;(h===void 0||v?.generation===h)&&(b(v),o.current=null),n.current=te},[b]),O=(0,cr.useCallback)(h=>n.current===(h??r.current),[]),M=(0,cr.useCallback)(h=>o.current?.generation===h&&n.current!==h,[]),W=(0,cr.useCallback)(()=>{let h=o.current;h&&(b(h),!h.yieldedControl&&(h.yieldedControl=!0,l.current?.(h.method)))},[b]),_=(0,cr.useCallback)(()=>{let h=o.current;!h?.yieldedControl||document.visibilityState!=="visible"||(b(h),h.timer=setTimeout(()=>{if(h.timer=null,o.current?.generation===h.generation){if(d.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"})}},ke.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[b]);return(0,cr.useEffect)(()=>{let h=()=>{document.visibilityState==="visible"?_():W()};return document.addEventListener("visibilitychange",h),window.addEventListener("blur",W),window.addEventListener("focus",_),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("blur",W),window.removeEventListener("focus",_),b()}},[b,W,_]),{startAttempt:k,finishAttempt:w,invalidateAttempt:x,isAttemptInvalidated:O,isAttemptCurrent:M,generationRef:r}}var sn=require("react/jsx-runtime"),Qa=45,td=1e3,rd=11e3,nd={width:"100%",minHeight:Qa,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 Cl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,ke.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function id(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function wl({sessionId:e,nonce:t,billingApiUrl:r,email:n,billingName:o,onBuyerIdentityReady:i,clientId:l,environment:d,currency:p,isSubscription:b,providerObjectType:k,approvalPresentation:w,onTokenizedBody:x,onComplete:O,onErrorChange:M,onDecline:W,onTechnicalFailure:_,isProcessing:h=!1,onLoadStateChange:v,onInitializationStateChange:te,allowAutomaticRetry:S=!0,onButtonClick:Pe,runBeforeButtonClick:j,session:Q,existingOrderId:Be,telemetry:se,telemetryContext:je,onInstrument:Je,debug:me=!1}){let pe=Zn(),Ke=Vo(Je,e),Re=(0,I.useMemo)(()=>{if(pe)return null;let f=Ja({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:at.SDK_VERSION,enabled:se!==!1});return f.setCheckoutContext(je??{}),f.beginCheckout(je??{}),f},[r,pe,se,je?.checkoutMode,je?.layout]),_e=(0,I.useMemo)(()=>hr(pe),[pe]);(0,I.useEffect)(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let Ee=(0,I.useMemo)(()=>({error:f=>{_e?_e.error(f):Re?.error(f),Ke({class:"technical_error",errorCode:f.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":f.errorCode,requestCategory:f.requestCategory,provider:f.provider})},log:f=>{_e?_e.log(f):Re?.log(f),Ke({class:"lifecycle",name:f.name,provider:f.provider})},performance:f=>{_e?_e.performance(f):Re?.performance(f)},terminal:f=>{_e?_e.terminal(f):Re?.terminal(f)},startTiming:()=>_e?.now()??Re?.now()??0,elapsed:f=>_e?.elapsed(f)??Math.max(0,(Re?.now()??f)-f)}),[Ke,_e,Re]),re=(0,I.useRef)(null),ae=(0,I.useRef)(0),ge=(0,I.useRef)(null),Me=(0,I.useRef)(null),K=(0,I.useRef)(null),ee=(0,I.useContext)(fa),ye=(0,I.useRef)(null);ye.current||(ye.current=Xa());let L=ee??ye.current,ve=(0,I.useRef)(null),Y=(0,I.useRef)(!1),[be,X]=(0,I.useState)(!1),[ct,Ge]=(0,I.useState)(!1),[$e,lt]=(0,I.useState)(0),Ye=(0,I.useRef)(0),[dt,We]=(0,I.useState)(!1),Et=(0,I.useRef)(!1),Ut=(0,I.useRef)(!1),[kt,At]=(0,I.useState)(!1),[N,fe]=(0,I.useState)(!1),{request:Qe,collect:G,finish:Ne}=zo(),Rt=(0,I.useRef)({sessionId:e,required:(0,at.paypalProviderIdentityRequired)(n,Q)});Rt.current.sessionId!==e&&(Rt.current={sessionId:e,required:(0,at.paypalProviderIdentityRequired)(n,Q)});let Ze=Rt.current.required,Tt=(0,I.useMemo)(()=>r.replace(/\/+$/,""),[r]),m=Q?.gateways?.paypal?.providerObjectType??k,P=m??(b?"subscription":"order"),[H]=(0,I.useState)(zn.detectPayPalEnvironment),V=Q?.gateways?.paypal?.approvalPresentation??w,he=(0,qn.resolvePayPalPresentationMode)(H,V==="app_switch"?"app_switch":void 0,P),T=(0,at.usesPayPalVaultedChannel)(m),A=(0,I.useMemo)(()=>JSON.stringify([Tt,l,p,d??"",P,T,he,e,Be??""]),[Tt,l,p,d,Be,P,T,he,e]),ne=(0,I.useRef)(A),q=ne.current!==A,Ce=(0,I.useRef)(me),rt=(0,I.useRef)(null),[Ct,ht]=(0,I.useState)([]),xe=(0,I.useCallback)(f=>{Ce.current&&ht(nt=>[...nt,`${new Date().toISOString().slice(11,23)} ${f}`])},[]);(0,I.useEffect)(()=>{Ce.current=me,me&&xe("debug:enabled"),rt.current?.setEnabled(me)},[xe,me]);let Fr=(0,I.useRef)(x),Vr=(0,I.useRef)(O),br=(0,I.useRef)(M),Ht=(0,I.useRef)(W),$r=(0,I.useRef)(_),Wr=(0,I.useRef)(Pe),Rr=(0,I.useRef)(v),Lt=(0,I.useRef)(te),mt=(0,I.useRef)(i),it=(0,I.useRef)(j),Br=(0,I.useRef)(Q),Bt=(0,I.useRef)(n),Hr=(0,I.useRef)(o),Cr=(0,I.useRef)(t),Kt=(0,I.useRef)(null),or=(0,I.useRef)(new Map),pn=(0,I.useRef)(new Map),en=(0,I.useRef)(!1);(0,I.useEffect)(()=>(en.current=!0,()=>{en.current=!1}),[]),(0,I.useEffect)(()=>{Fr.current=x},[x]),(0,I.useEffect)(()=>{mt.current=i},[i]),(0,I.useEffect)(()=>{Vr.current=O},[O]),(0,I.useEffect)(()=>{br.current=M},[M]),(0,I.useEffect)(()=>{Ht.current=W},[W]),(0,I.useEffect)(()=>{$r.current=_},[_]),(0,I.useEffect)(()=>{Wr.current=Pe},[Pe]),(0,I.useEffect)(()=>{Rr.current=v},[v]),(0,I.useEffect)(()=>{Lt.current=te},[te]),(0,I.useEffect)(()=>{it.current=j},[j]),(0,I.useEffect)(()=>{Br.current=Q},[Q]),(0,I.useEffect)(()=>{Bt.current=n},[n]),(0,I.useEffect)(()=>{Hr.current=o},[o]),(0,I.useEffect)(()=>{Cr.current=t},[t]),(0,I.useEffect)(()=>{Ye.current=$e},[$e]),(0,I.useEffect)(()=>{dt&&ve.current?.focus()},[dt,$e]);let ar=(0,I.useCallback)(()=>{window.setTimeout(()=>{ve.current?.focus()},0)},[]),zt=(0,I.useCallback)(()=>{X(!1),lt(f=>f+1)},[]),Tr=(0,I.useCallback)(()=>{We(!1),(re.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??re.current)?.focus?.()},[]);(0,I.useEffect)(()=>{!be||!Y.current||(Y.current=!1,Tr())},[Tr,be,$e]);let mr=(0,I.useCallback)((f,nt)=>{let ie=nt?.popupBlocked??(0,ke.isPopupBlockedError)(f);ie&&L.markBlocked();let Er=(0,ke.buildExternalMethodRecoveryMessage)("PayPal",ie,H.inAppBrowser),Kr=$r.current;if(Kr){let Zt=ie&&H.inAppBrowser?new at.FloPayError(Er,"api_error",{code:nt?.code??"paypal_popup_blocked"}):f;Kr("paypal",Zt,nt);return}br.current?.(Er)},[L,H.inAppBrowser]),jt=(0,I.useCallback)(f=>{let nt=ge.current,ie=Me.current;nt===null||!ie||(Ee.log({...ie,popupCapability:L.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:f}),Ee.performance({...ie,popupCapability:L.current(),stage:"overlay_return",durationMs:Ee.elapsed(nt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:f}),ge.current=null)},[L,Ee]),Sr=(0,I.useCallback)((f,nt,ie)=>{let Er=Me.current;jt("overlay_timeout"),Er&&Ee.error({...Er,popupCapability:L.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),mr(nt,{...ie,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:he,terminalReason:"overlay_timeout"}),We(!0),zt(),ar()},[jt,ar,mr,L,he,zt,Ee]),Vt=(0,I.useCallback)(()=>{L.markAvailable();let f=Me.current;f&&(K.current=f.attempt,Ee.log({...f,popupCapability:L.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[L,Ee]),{finishAttempt:ur,generationRef:qt,invalidateAttempt:Ae,isAttemptCurrent:mn,isAttemptInvalidated:yn,startAttempt:fn}=ga(Sr,{onHandoffObserved:Vt}),ir=(0,I.useCallback)(()=>(We(!1),fn("paypal")),[fn]),Dr=(0,I.useCallback)(f=>{Ae(f?.generation),f?.showRetry&&We(!0),f?.remount&&zt(),f?.focus!==!1&&ar()},[ar,Ae,zt]),Mr=f=>{let nt=Kt.current;return nt&&pn.current.set(f,nt),f};(0,I.useEffect)(()=>{ne.current!==A&&(ne.current=A,Et.current=!1,Ut.current=!1,X(!1),Ge(!1),At(!1),Lt.current?.("loading"))},[A]),(0,I.useEffect)(()=>{(0,tt.invokeMerchantCallback)(()=>Rr.current?.(be&&!kt))},[be,kt]);let De=(0,at.normalizeGatewayEnvironment)(d);(0,I.useEffect)(()=>{let f={attempt:qt.current+1,inAppBrowser:H.inAppBrowser,appFamily:H.appFamily,popupCapability:L.current(),presentationMode:he},nt=()=>({...Me.current??f,popupCapability:L.current()}),ie={error:y=>Ee.error({...y,...nt()}),log:y=>Ee.log({...y,...nt()}),performance:y=>Ee.performance({...y,...nt()}),terminal:y=>Ee.terminal({...y,...nt()}),startTiming:Ee.startTiming,elapsed:Ee.elapsed},Er=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Kr=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(xe(`mount clientId=${Er} env=${d??"(unset)"}\u2192${De??"live"} ccy=${p} sub=${b}`),xe(`ua=${Kr.slice(0,80)}${Kr.length>80?"\u2026":""}`),!l){xe("FAIL: clientId empty \u2014 gateway misconfigured"),At(!0),ie.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(!re.current){xe("FAIL: containerRef not attached");return}ae.current=ie.startTiming(),ie.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Zt=!1,Or=!1,St=()=>Zt||Or,xn=T?P:void 0,no,Dt=!1,Gr=()=>{no=(0,at.generateIdempotencyKey)(),no||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Dt=!0},gn=null,hn=!1,Gt=null,An=!1,Fn=()=>{!Gt||An||(An=!0,Gt.close().catch(()=>{}))},Lr=!1,Bn=!1,tn=re.current,Dn=null,Hn=null,Yr=[],Pn=null,vn=!1,Nt=!1,Xr=null,xr=y=>{if(!y||typeof y.getBoundingClientRect!="function")return"(no rect)";let g=y.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},bn=y=>{if(!y)return"(empty)";try{let g=new URL(y,typeof window>"u"?"https://localhost":window.location.href),E=g.pathname.toLowerCase();return E.includes("checkcaptcha")||E.includes("captcha")?`CAPTCHA(${g.host}${E})`:E.includes("risk")||E.includes("challenge")?`RISK(${g.host}${E})`:E.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${E}`.slice(0,100)}catch{return y.slice(0,80)}},Cn=y=>{let g=y.getAttribute("src"),E=y.getAttribute("srcdoc"),de=y.getAttribute("name"),Fe=y.getAttribute("sandbox"),He=[];return g&&He.push(`src=${bn(g)}`),E&&He.push(`srcdoc[${E.length}ch]`),!g&&!E&&He.push("src=(empty) srcdoc=(empty)"),de&&He.push(`name=${de.slice(0,40)}`),Fe!==null&&He.push(`sandbox="${Fe.slice(0,40)}"`),He.join(" ")},bt=y=>{if(!(y instanceof HTMLIFrameElement))return"";try{let g=y.contentDocument;if(!g)return"cd=null";let E=g.body?.children.length??0,de=g.body?.innerHTML.length??0,Fe=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${E}children,${de}ch] head[${Fe}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},sr=[],yr=y=>{if(St())return;let g=y.message??String(y.error??"(no message)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(xe(`window:error ${g.slice(0,140)}`),sr.push(g))},Nr=y=>{if(St())return;let g=y.reason instanceof Error?y.reason.message:String(y.reason??"(no reason)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(xe(`window:rejection ${g.slice(0,140)}`),sr.push(g))},oo={value:0},On=()=>{Dn?.disconnect(),Dn=null,Hn?.disconnect(),Hn=null;for(let y of Yr.splice(0))clearTimeout(y);Nt=!1,vn&&typeof window<"u"&&(window.removeEventListener("error",yr),window.removeEventListener("unhandledrejection",Nr)),vn=!1},Kn=()=>{if(!(vn||St()||Lr)){if(vn=!0,sr.length=0,oo.value=0,typeof window<"u"&&(window.addEventListener("error",yr),window.addEventListener("unhandledrejection",Nr)),typeof PerformanceObserver<"u")try{Hn=new PerformanceObserver(y=>{if(!St())for(let g of y.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;oo.value+=1;let E=Math.round(g.duration);xe(`net ${E}ms ${g.name.slice(0,90)}`)}}),Hn.observe({type:"resource",buffered:!0})}catch{}Xr?.()}},rn=()=>{Pn&&(clearTimeout(Pn),Pn=null)},lr=()=>{On(),rn()},ao={setEnabled:y=>{y?Kn():On()}};rt.current=ao,Ce.current&&Kn();let pr=at.isPayPalTeardownMessage,z=y=>{if(St()||pr(y))return;let g=(0,Po.applyFriendlyMessageOverride)(y)??y;(0,tt.invokeMerchantCallback)(()=>br.current?.(g))},B=(y,g)=>{if(Zt||hn)return;hn=!0,Or=!0,lr(),Fn();let E=ad({kind:y,generationActive:!0,automaticRetryAllowed:S,automaticRetryUsed:Et.current});if(E.action==="retry"){Et.current=!0,X(!1),fe(!1),Ge(!0),Lt.current?.("retrying"),gn=setTimeout(()=>{Zt||lt(de=>de+1)},td);return}if(X(!1),fe(!1),Ge(!1),At(!0),E.action!=="ignore"){if(Lt.current?.("exhausted"),E.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(E.report){let de=(0,ke.classifyExternalMethodFailure)({code:Cl(y,g),message:g},{inAppBrowser:H.inAppBrowser,handoffObserved:!1});de.popupBlocked&&L.markBlocked(),ie.error({errorCode:de.popupBlocked?de.errorCode:E.report.errorCode,stage:E.report.stage,operationOutcome:E.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:de.terminalReason})}Ut.current||(Ut.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Cl(y,g)))}};At(!1);let ce=async(y,g=Kt.current)=>{if(St())return;let E=g?.sessionId??e;if(Fr.current){await Fr.current(y,{sessionId:E,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let de=ie.startTiming();ie.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Fe=()=>{ie.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"processing",durationMs:ie.elapsed(de),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let He=(0,at.buildPayPalProcessPaymentRequest)({body:y,sessionId:E,nonce:g?.nonce??Cr.current,accountPatch:g?.accountPatch,session:Br.current,email:Bt.current}),Te=await new Za.PaymentAPI(Tt,{telemetry:!1}).processPayment(He.userId,He.params);if(Te.ok){if(Or||Zt&&en.current)return;Fe(),ie.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,tt.invokeMerchantCallback)(()=>Vr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(St())return;let Xe=await Te.json().catch(()=>null),ot=(0,at.describePayPalProcessFailure)(Xe),wt=ot.message;Fe(),Te.status===400&&(typeof Xe?.declineCode=="string"||!Array.isArray(Xe?.fields))?ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Te.status===400||Te.status===422?ie.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):ie.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}),z(wt),(0,tt.invokeMerchantCallback)(()=>Ht.current?.(gr("paypal",wt,{code:ot.code,declineCode:ot.declineCode})));return}catch(He){if(St())return;Fe(),ie.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Xt=(0,at.friendlyPayPalFailureMessage)(He instanceof Error?He.message:void 0);z(Xt),(0,tt.invokeMerchantCallback)(()=>Ht.current?.(gr("paypal",Xt)));return}},Se=()=>new at.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),It=y=>St()?Promise.reject(Se()):Promise.resolve(y),Yt=async y=>{if(St())throw Se();Dt||Gr();let g=Kt.current,E=g?.sessionId??e,de=g?.nonce??Cr.current;ie.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Fe;try{Fe=await new Za.PaymentAPI(Tt,{telemetry:!1}).createSessionIntent(E,de??"",(0,at.buildPayPalSessionIntentRequest)(xn),{idempotencyKey:no})}catch(He){throw ie.error({...(0,at.classifyTelemetryFailure)(He,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),He}if(St())throw Se();if(Fe.provider!=="paypal"||Fe.providerObjectType!==P)throw new Error(y);return ie.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Fe.providerObjectId},Oe=(y,g)=>{let E=g?.nonce??Cr.current;if(!E)return;let de=g?.sessionId??e,Fe=(0,at.resolvePayPalDeclineReason)(y);new Za.PaymentAPI(Tt,{telemetry:!1}).reportSessionIntentDecline(de,E,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Fe}).catch(()=>{})},J=$e;xe("loadScript:scheduled (deferred 1 tick)");let Z=null,$=setTimeout(()=>{if(Zt){xe("loadScript:skipped (cancelled before defer ran)");return}xe("loadScript:start");let y=De==="live"?"production":De,g={};P==="subscription"?g={intent:"subscription",vault:!0}:P==="order"&&(g={intent:"capture"}),Z=(0,Sl.loadScript)({clientId:l,currency:p,...g,...y?{environment:y}:{},...y==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let E=!1;Z.then(de=>{if(E=!0,xe(`loadScript:resolved inactive=${St()} ns=${!!de} buttons=${!!de?.Buttons}`),St())return;if(!de?.Buttons){xe("FAIL: namespace missing Buttons factory"),B("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}ie.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"provider_ready",durationMs:ie.elapsed(ae.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ie.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Fe=async(we,D)=>{if(St()||Ye.current!==J)return;let le=we.vaultSetupToken??we.subscriptionID??we.orderID??"",yt=le?pn.current.get(le):or.current.get(J);if(!(!yt||!mn(yt.generation))&&ur(yt.generation)){pn.current.delete(le),or.current.delete(yt.surfaceKey),jt("approved");try{if(fe(!0),(0,tt.invokeMerchantCallback)(()=>br.current?.(null)),!le)throw new at.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ve=(0,at.resolvePayPalApprovalIdentity)({accountPatch:yt.accountPatch,email:Bt.current,billingName:Hr.current,session:Br.current});if((0,at.needsPayPalPayerDetails)(Ve))try{Ve=(0,at.mergePayPalPayerIdentity)(Ve,await D?.order?.get?.())}catch{}if((mt.current||Ze)&&!(0,at.isValidEmail)(Ve.email)){let Mt=await G("PayPal",Ve);if(!Mt)return;Ve=Mt}(0,at.isValidEmail)(Ve.email)&&(yt.accountPatch=(0,an.compactBuyerIdentity)({...yt.accountPatch,...Ve}),await mt.current?.(Ve));let et=(0,at.buildPayPalTokenizedBody)(le,xn);await ce(et,yt)}catch(Ve){z(Ve instanceof Error?Ve.message:"PayPal capture failed.")}finally{St()||fe(!1)}}},He=we=>{let D=Be?()=>It(Be):()=>Yt(we);return async()=>Mr(await D())},Xt=de.Buttons({style:{layout:"horizontal",height:Qa,tagline:!1},...he==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(we,D)=>{if(St()){await D.reject();return}Gr();let le=it.current,yt={};if(le)try{let Mt=await le("paypal");if(St()){await D.reject();return}if(!Mt.proceed){Kt.current=null,or.current.delete(J),await D.reject();return}yt={sessionId:Mt.sessionId,accountPatch:Mt.accountPatch,nonce:Mt.nonce}}catch(Mt){xe(`onClick:runBeforeButtonClick rejected msg=${(Mt instanceof Error?Mt.message:String(Mt)).slice(0,120)}`),Kt.current=null,or.current.delete(J),await D.reject();return}(0,tt.invokeMerchantCallback)(()=>Wr.current?.("paypal"));let Ve=ir(),et={generation:Ve,surfaceKey:J,...yt};Kt.current=et,or.current.set(J,et),Me.current={...f,attempt:Ve},await D.resolve(),ie.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),ie.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),ge.current=ie.startTiming()},createOrder:P==="order"?He("Failed to create PayPal order."):void 0,createSubscription:P==="subscription"?He("Failed to create PayPal subscription."):void 0,createVaultSetupToken:P==="setup_token"?async()=>Mr(await Yt("Failed to create PayPal setup token.")):void 0,onApprove:Fe,onCancel:()=>{if(St())return;let we=or.current.get(J)??Kt.current;we&&or.current.delete(we.surfaceKey),Kt.current=null,jt("cancelled"),ie.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Y.current=!0,Dr({generation:we?.generation,remount:!0,focus:!1})},onError:we=>{if(St()||Ye.current!==J)return;let D=we instanceof Error?we.message:"PayPal failed to render.";if(xe(`onError rendered=${Lr} msg=${D.slice(0,120)}`),Lr){let le=or.current.get(J)??Kt.current;if(le&&!mn(le.generation)||!le&&yn())return;if(pr(D)){ur(le?.generation);return}let{errorCode:yt,popupBlocked:Ve,providerDeclined:et,terminalReason:Mt}=(0,ke.classifyExternalMethodFailure)(we,{inAppBrowser:H.inAppBrowser,handoffObserved:le!=null&&K.current===le.generation});if(Ve&&L.markBlocked(),jt(Mt),et){ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Mt}),Oe(we,le),(0,tt.invokeMerchantCallback)(()=>Ht.current?.(gr("paypal",D))),le&&or.current.delete(le.surfaceKey),Kt.current=null,ur(le?.generation);return}ie.error({errorCode:yt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Mt}),le&&or.current.delete(le.surfaceKey),Kt.current=null,Dr({generation:le?.generation,remount:!0,showRetry:!0,focus:!0}),mr(we,{code:"paypal_runtime_failed",popupBlocked:Ve,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:he,terminalReason:Mt});return}B(pr(D)?"teardown":"pre_ready_callback",D)}}),Te=Xt.isEligible();if(xe(`isEligible=${Te}`),ie.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Te){X(!1),B("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Bn=!0,Gt=Xt,Xr=()=>{if(!vn||Nt||St()||Lr)return;Nt=!0,xe(`container:dims ${xr(tn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Dn=new MutationObserver(D=>{if(!St()){for(let le of D)if(le.type==="childList")le.addedNodes.forEach(yt=>{if(!(yt instanceof Element))return;let Ve=yt.tagName.toLowerCase(),et=(yt.getAttribute("title")??"").slice(0,40),Mt=Ve==="iframe"?` ${Cn(yt)}`:"";xe(`child+ ${Ve}${et?` title="${et}"`:""}${Mt} dims=${xr(yt)}`)});else if(le.type==="attributes"&&le.target instanceof Element){let yt=le.target;if(yt.tagName.toLowerCase()!=="iframe")continue;let Ve=le.attributeName;(Ve==="src"||Ve==="srcdoc")&&xe(`attr~ iframe ${Ve}=${Ve==="srcdoc"?`[${(yt.getAttribute("srcdoc")??"").length}ch]`:bn(yt.getAttribute("src"))} dims=${xr(yt)}`)}}}),Dn.observe(tn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let we=D=>{if(St()||Lr)return;let le=tn.querySelectorAll("iframe"),yt=typeof document<"u"&&"hasStorageAccess"in document;xe(`watchdog:${D} container=${xr(tn)} children=${tn.childElementCount} iframes=${le.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${yt} paypalNetRequests=${oo.value}`),le.forEach((Ve,et)=>{let Mt=(Ve.getAttribute("title")??"").slice(0,40);xe(` iframe[${et}] ${xr(Ve)}${Mt?` title="${Mt}"`:""} ${Cn(Ve)}`);let Pt=bt(Ve);Pt&&xe(` ${Pt}`)}),sr.length===0&&xe(" (no PayPal/zoid window errors captured)")};Yr.push(setTimeout(()=>we("3s"),3e3)),Yr.push(setTimeout(()=>we("8s"),8e3)),Yr.push(setTimeout(()=>we("15s"),15e3))},Xr(),xe("render:start");let ot=ie.startTiming();Pn=setTimeout(()=>{St()||Lr||(xe("watchdog:11s retryable render timeout"),B("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},rd);let wt=Xt.render(tn);(async()=>{try{if(await wt,xe(`render:resolved inactive=${St()}`),lr(),St()){Fn();return}Lr=!0,X(!0),Ge(!1),Lt.current?.("ready"),ie.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),ie.performance({stage:"checkout_render",durationMs:ie.elapsed(ot),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(we){let D=we instanceof Error?we.message:"PayPal failed to render.";xe(`render:rejected msg=${D.slice(0,120)}`),lr(),B(pr(D)?"teardown":"render_rejected",D)}})()}).catch(de=>{let Fe=de instanceof Error?de.message:"PayPal operation failed.";xe(`provider:failed msg=${Fe.slice(0,120)}`);let He="script_rejected";E&&pr(Fe)?He="teardown":E&&Bn&&(He="render_rejected"),B(He,Fe)})},0);return()=>{Zt=!0,clearTimeout($),gn&&clearTimeout(gn),lr(),rt.current===ao&&(rt.current=null),Fn(),ge.current=null,Me.current=null}},[S,Tt,l,p,d,P,he,T,e,Be,$e,Ee,G,Ze,xe,jt]);let vt=me?(0,sn.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=${be} failed=${kt})`,Ct.length===0?`
1
+ "use strict";var Nc=Object.create;var Va=Object.defineProperty;var Uc=Object.getOwnPropertyDescriptor;var zc=Object.getOwnPropertyNames;var qc=Object.getPrototypeOf,jc=Object.prototype.hasOwnProperty;var Vc=(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 zc(t))!jc.call(e,o)&&o!==r&&Va(e,o,{get:()=>t[o],enumerable:!(n=Uc(t,o))||n.enumerable});return e};var Vi=(e,t,r)=>(r=e!=null?Nc(qc(e)):{},ll(t||!e||!e.__esModule?Va(r,"default",{value:e,enumerable:!0}):r,e)),$c=e=>ll(Va({},"__esModule",{value:!0}),e);var gu={};Vc(gu,{DirectPayPalButton:()=>ga,FloPayAutomaticPaymentButton:()=>oc,FloPayCardSetup:()=>sc,FloPayCardSetupError:()=>Ma,FloPayCheckout:()=>Pi,FloPayPaymentMethodSetup:()=>Pc,FloPayProvider:()=>Pa,SplitCardForm:()=>yi,VaultCardFields:()=>lo,dropThirdPartyOnlyError:()=>Cc.dropThirdPartyOnlyError,useCheckout:()=>vl,useFloPay:()=>Jn,usePayPalFloPay:()=>Ka});module.exports=$c(gu);var Cc=require("@flopay/shared");var vi=require("@flopay/js"),dn=require("@flopay/shared"),pt=require("react");var Wt=require("react/jsx-runtime");function Wc(){return(0,Wt.jsxs)(Wt.Fragment,{children:[(0,Wt.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,Wt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Wt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Wt.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,Wt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Hc(){return(0,Wt.jsx)(Wt.Fragment,{children:"Go back"})}function Kc(){return(0,Wt.jsx)(Wt.Fragment,{children:"Secure card checkout"})}function Fo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Bo({content:e}){return(0,Wt.jsx)(Wt.Fragment,{children:e===void 0?(0,Wt.jsx)(Wc,{}):e})}function Do({content:e}){return(0,Wt.jsx)(Wt.Fragment,{children:e===void 0?(0,Wt.jsx)(Hc,{}):e})}function da({content:e}){return(0,Wt.jsx)(Wt.Fragment,{children:e===void 0?(0,Wt.jsx)(Kc,{}):e})}var gt=require("@flopay/shared"),kn=require("@flopay/shared"),No=require("@flopay/shared"),ho=require("@flopay/shared"),Gc="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 Yc(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(Gc,"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&&Yc(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 m={};for(let[C,w]of Object.entries(l)){if(u&&C.endsWith("Name")||typeof w!="string")continue;let S=w.trim();S&&(m[C]=S)}return o=e.claimCheckoutSession(t,r,{accountData:m}),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 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),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 gr(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 yl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function $a(e){let t=yl(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 yl(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 Xc=["apple_pay","google_pay"];function hl(e,t="automatic",r){let n=(0,gt.resolveSetupFutureUsage)(r,Xc,"wallet");return{...(0,gt.resolveWalletModeOptions)(e,t),paymentMethodTypes:["card"],...n?{setupFutureUsage:n}:{}}}var Jc=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:Jc.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"),qe=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"),it=require("@flopay/shared"),wl=require("@paypal/paypal-js"),I=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(m=>{r.current=m})),[]),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()??""),m=(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:!m||o,onClick:()=>{r((0,Ha.compactBuyerIdentity)({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var we=require("@flopay/shared");var Pl=require("@flopay/shared"),ma=require("react");function Jn(){return(0,ma.useContext)(nn).flopay}function Ka(){return(0,ma.useContext)(nn).paypalFlopay??null}function vl(){return(0,ma.useContext)(Rn)}function Cl(){return(0,ma.useContext)(nn).billingApiUrl||(0,Pl.resolveBillingApiUrl)()}var Zc=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 rt=require("@flopay/shared");var bl=require("react"),ya=(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 Qc=Symbol.for("@flopay/js.telemetry.bridge.v1"),ed=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function td(){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 rd(e){let t=td(),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[ed];return rd(t?.(e)??{})}function hr(e){if(e)return e[Qc]}var cr=require("react");function fa(e,t){let r=(0,cr.useRef)(0),n=(0,cr.useRef)(null),o=(0,cr.useRef)(null),i=(0,cr.useRef)(e),l=(0,cr.useRef)(t?.onHandoffObserved),u=(0,cr.useRef)(t?.defersMissingTerminal),m=(0,cr.useRef)(t?.onMissingTerminalDeferred);(0,cr.useEffect)(()=>{i.current=e,l.current=t?.onHandoffObserved,u.current=t?.defersMissingTerminal,m.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let C=(0,cr.useCallback)((h=o.current)=>{h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),w=(0,cr.useCallback)(h=>{C();let v=r.current+1;return r.current=v,n.current=null,o.current={generation:v,method:h,timer:null,yieldedControl:!1},v},[C]),S=(0,cr.useCallback)(h=>{let v=o.current;return h!==void 0&&v?.generation!==h?!1:(C(v),o.current=null,(h===void 0||n.current===h)&&(n.current=null),!0)},[C]),x=(0,cr.useCallback)(h=>{let v=o.current,Z=h??v?.generation??r.current;(h===void 0||v?.generation===h)&&(C(v),o.current=null),n.current=Z},[C]),H=(0,cr.useCallback)(h=>n.current===(h??r.current),[]),M=(0,cr.useCallback)(h=>o.current?.generation===h&&n.current!==h,[]),V=(0,cr.useCallback)(()=>{let h=o.current;h&&(C(h),!h.yieldedControl&&(h.yieldedControl=!0,l.current?.(h.method)))},[C]),_=(0,cr.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)){m.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"})}},we.EXTERNAL_METHOD_CALLBACK_GRACE_MS))},[C]);return(0,cr.useEffect)(()=>{let h=()=>{document.visibilityState==="visible"?_():V()};return document.addEventListener("visibilitychange",h),window.addEventListener("blur",V),window.addEventListener("focus",_),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("blur",V),window.removeEventListener("focus",_),C()}},[C,V,_]),{startAttempt:w,finishAttempt:S,invalidateAttempt:x,isAttemptInvalidated:H,isAttemptCurrent:M,generationRef:r}}var an=require("react/jsx-runtime"),Za=45,nd=1e3,od=11e3,ad={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"},id={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 sd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:id[e.kind]??null}}function Sl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":(0,we.isPayPalAcknowledgementDeadWindow)(t)?"paypal_init_timeout":"paypal_init_failure"}function ld(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:m,isSubscription:C,providerObjectType:w,approvalPresentation:S,onTokenizedBody:x,onComplete:H,onErrorChange:M,onDecline:V,onTechnicalFailure:_,isProcessing:h=!1,onLoadStateChange:v,onInitializationStateChange:Z,allowAutomaticRetry:k=!0,onButtonClick:fe,runBeforeButtonClick:O,session:ne,existingOrderId:Be,telemetry:pe,telemetryContext:De,onInstrument:Je,debug:me=!1}){let de=Jn(),Qe=jo(Je,e),ke=(0,I.useMemo)(()=>{if(de)return null;let f=Xa({billingApiUrl:r,sdkPackage:"@flopay/react",sdkVersion:it.SDK_VERSION,enabled:pe!==!1});return f.setCheckoutContext(De??{}),f.beginCheckout(De??{}),f},[r,de,pe,De?.checkoutMode,De?.layout]),Re=(0,I.useMemo)(()=>hr(de),[de]);(0,I.useEffect)(()=>()=>{ke&&ke.flush().catch(()=>{}).finally(()=>ke.destroy())},[ke]);let Ee=(0,I.useMemo)(()=>({error:f=>{Re?Re.error(f):ke?.error(f),Qe({class:"technical_error",errorCode:f.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":f.errorCode,requestCategory:f.requestCategory,provider:f.provider})},log:f=>{Re?Re.log(f):ke?.log(f),Qe({class:"lifecycle",name:f.name,provider:f.provider})},performance:f=>{Re?Re.performance(f):ke?.performance(f)},terminal:f=>{Re?Re.terminal(f):ke?.terminal(f)},startTiming:()=>Re?.now()??ke?.now()??0,elapsed:f=>Re?.elapsed(f)??Math.max(0,(ke?.now()??f)-f)}),[Qe,Re,ke]),ee=(0,I.useRef)(null),ue=(0,I.useRef)(0),Pe=(0,I.useRef)(null),Ie=(0,I.useRef)(null),ve=(0,I.useRef)(null),Q=(0,I.useContext)(ya),K=(0,I.useRef)(null);K.current||(K.current=Ya());let N=Q??K.current,_e=(0,I.useRef)(null),ae=(0,I.useRef)(!1),[ge,B]=(0,I.useState)(!1),[$e,Ge]=(0,I.useState)(!1),[We,ct]=(0,I.useState)(0),Ye=(0,I.useRef)(0),[dt,He]=(0,I.useState)(!1),Et=(0,I.useRef)(!1),Ut=(0,I.useRef)(!1),[kt,At]=(0,I.useState)(!1),[U,ye]=(0,I.useState)(!1),{request:et,collect:Y,finish:Ue}=Uo(),Rt=(0,I.useRef)({sessionId:e,required:(0,it.paypalProviderIdentityRequired)(n,ne)});Rt.current.sessionId!==e&&(Rt.current={sessionId:e,required:(0,it.paypalProviderIdentityRequired)(n,ne)});let Ze=Rt.current.required,Tt=(0,I.useMemo)(()=>r.replace(/\/+$/,""),[r]),p=ne?.gateways?.paypal?.providerObjectType??w,P=p??(C?"subscription":"order"),[G]=(0,I.useState)(Un.detectPayPalEnvironment),$=ne?.gateways?.paypal?.approvalPresentation??S,he=(0,zn.resolvePayPalPresentationMode)(G,$==="app_switch"?"app_switch":void 0,P),T=(0,it.usesPayPalVaultedChannel)(p),A=(0,I.useMemo)(()=>JSON.stringify([Tt,l,m,u??"",P,T,he,e,Be??""]),[Tt,l,m,u,Be,P,T,he,e]),te=(0,I.useRef)(A),j=te.current!==A,Ce=(0,I.useRef)(me),nt=(0,I.useRef)(null),[bt,ht]=(0,I.useState)([]),xe=(0,I.useCallback)(f=>{Ce.current&&ht(ot=>[...ot,`${new Date().toISOString().slice(11,23)} ${f}`])},[]);(0,I.useEffect)(()=>{Ce.current=me,me&&xe("debug:enabled"),nt.current?.setEnabled(me)},[xe,me]);let Ar=(0,I.useRef)(x),jr=(0,I.useRef)(H),Cr=(0,I.useRef)(M),Ht=(0,I.useRef)(V),Vr=(0,I.useRef)(_),$r=(0,I.useRef)(fe),kr=(0,I.useRef)(v),Ot=(0,I.useRef)(Z),mt=(0,I.useRef)(i),st=(0,I.useRef)(O),Fr=(0,I.useRef)(ne),Ft=(0,I.useRef)(n),Wr=(0,I.useRef)(o),br=(0,I.useRef)(t),Kt=(0,I.useRef)(null),or=(0,I.useRef)(new Map),un=(0,I.useRef)(new Map),Qr=(0,I.useRef)(!1);(0,I.useEffect)(()=>(Qr.current=!0,()=>{Qr.current=!1}),[]),(0,I.useEffect)(()=>{Ar.current=x},[x]),(0,I.useEffect)(()=>{mt.current=i},[i]),(0,I.useEffect)(()=>{jr.current=H},[H]),(0,I.useEffect)(()=>{Cr.current=M},[M]),(0,I.useEffect)(()=>{Ht.current=V},[V]),(0,I.useEffect)(()=>{Vr.current=_},[_]),(0,I.useEffect)(()=>{$r.current=fe},[fe]),(0,I.useEffect)(()=>{kr.current=v},[v]),(0,I.useEffect)(()=>{Ot.current=Z},[Z]),(0,I.useEffect)(()=>{st.current=O},[O]),(0,I.useEffect)(()=>{Fr.current=ne},[ne]),(0,I.useEffect)(()=>{Ft.current=n},[n]),(0,I.useEffect)(()=>{Wr.current=o},[o]),(0,I.useEffect)(()=>{br.current=t},[t]),(0,I.useEffect)(()=>{Ye.current=We},[We]),(0,I.useEffect)(()=>{dt&&_e.current?.focus()},[dt,We]);let ar=(0,I.useCallback)(()=>{window.setTimeout(()=>{_e.current?.focus()},0)},[]),zt=(0,I.useCallback)(()=>{B(!1),ct(f=>f+1)},[]),Ir=(0,I.useCallback)(()=>{He(!1),(ee.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ee.current)?.focus?.()},[]);(0,I.useEffect)(()=>{!ge||!ae.current||(ae.current=!1,Ir())},[Ir,ge,We]);let mr=(0,I.useCallback)((f,ot)=>{let oe=ot?.popupBlocked??(0,we.isPopupBlockedError)(f);oe&&N.markBlocked();let Rr=(0,we.buildExternalMethodRecoveryMessage)("PayPal",oe,G.inAppBrowser),Hr=Vr.current;if(Hr){let Zt=oe&&G.inAppBrowser?new it.FloPayError(Rr,"api_error",{code:ot?.code??"paypal_popup_blocked"}):f;Hr("paypal",Zt,ot);return}Cr.current?.(Rr)},[N,G.inAppBrowser]),jt=(0,I.useCallback)(f=>{let ot=Pe.current,oe=Ie.current;ot===null||!oe||(Ee.log({...oe,popupCapability:N.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:f}),Ee.performance({...oe,popupCapability:N.current(),stage:"overlay_return",durationMs:Ee.elapsed(ot),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:f}),Pe.current=null)},[N,Ee]),Sr=(0,I.useCallback)((f,ot,oe)=>{let Rr=Ie.current;jt("overlay_timeout"),Rr&&Ee.error({...Rr,popupCapability:N.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),mr(ot,{...oe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:he,terminalReason:"overlay_timeout"}),He(!0),zt(),ar()},[jt,ar,mr,N,he,zt,Ee]),Vt=(0,I.useCallback)(()=>{N.markAvailable();let f=Ie.current;f&&(ve.current=f.attempt,Ee.log({...f,popupCapability:N.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[N,Ee]),{finishAttempt:ur,generationRef:qt,invalidateAttempt:Ae,isAttemptCurrent:pn,isAttemptInvalidated:mn,startAttempt:yn}=fa(Sr,{onHandoffObserved:Vt}),ir=(0,I.useCallback)(()=>(He(!1),yn("paypal")),[yn]),Br=(0,I.useCallback)(f=>{Ae(f?.generation),f?.showRetry&&He(!0),f?.remount&&zt(),f?.focus!==!1&&ar()},[ar,Ae,zt]),_r=f=>{let ot=Kt.current;return ot&&un.current.set(f,ot),f};(0,I.useEffect)(()=>{te.current!==A&&(te.current=A,Et.current=!1,Ut.current=!1,B(!1),Ge(!1),At(!1),Ot.current?.("loading"))},[A]),(0,I.useEffect)(()=>{(0,rt.invokeMerchantCallback)(()=>kr.current?.(ge&&!kt))},[ge,kt]);let Oe=(0,it.normalizeGatewayEnvironment)(u);(0,I.useEffect)(()=>{let f={attempt:qt.current+1,inAppBrowser:G.inAppBrowser,appFamily:G.appFamily,popupCapability:N.current(),presentationMode:he},ot=()=>({...Ie.current??f,popupCapability:N.current()}),oe={error:y=>Ee.error({...y,...ot()}),log:y=>Ee.log({...y,...ot()}),performance:y=>Ee.performance({...y,...ot()}),terminal:y=>Ee.terminal({...y,...ot()}),startTiming:Ee.startTiming,elapsed:Ee.elapsed},Rr=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Hr=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(xe(`mount clientId=${Rr} env=${u??"(unset)"}\u2192${Oe??"live"} ccy=${m} sub=${C}`),xe(`ua=${Hr.slice(0,80)}${Hr.length>80?"\u2026":""}`),!l){xe("FAIL: clientId empty \u2014 gateway misconfigured"),At(!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(!ee.current){xe("FAIL: containerRef not attached");return}ue.current=oe.startTiming(),oe.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Zt=!1,Dr=!1,St=()=>Zt||Dr,Mn=T?P:void 0,ro,Bt=!1,Kr=()=>{ro=(0,it.generateIdempotencyKey)(),ro||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Bt=!0},fn=null,gn=!1,Gt=null,xn=!1,An=()=>{!Gt||xn||(xn=!0,Gt.close().catch(()=>{}))},Or=!1,Fn=!1,en=ee.current,Bn=null,Wn=null,Gr=[],hn=null,Pn=!1,Lt=!1,Yr=null,Tr=y=>{if(!y||typeof y.getBoundingClientRect!="function")return"(no rect)";let g=y.getBoundingClientRect();return`${Math.round(g.width)}\xD7${Math.round(g.height)}`},vn=y=>{if(!y)return"(empty)";try{let g=new URL(y,typeof window>"u"?"https://localhost":window.location.href),E=g.pathname.toLowerCase();return E.includes("checkcaptcha")||E.includes("captcha")?`CAPTCHA(${g.host}${E})`:E.includes("risk")||E.includes("challenge")?`RISK(${g.host}${E})`:E.includes("smart/buttons")?`smart-buttons(${g.host})`:`${g.host}${E}`.slice(0,100)}catch{return y.slice(0,80)}},Cn=y=>{let g=y.getAttribute("src"),E=y.getAttribute("srcdoc"),le=y.getAttribute("name"),Fe=y.getAttribute("sandbox"),Ke=[];return g&&Ke.push(`src=${vn(g)}`),E&&Ke.push(`srcdoc[${E.length}ch]`),!g&&!E&&Ke.push("src=(empty) srcdoc=(empty)"),le&&Ke.push(`name=${le.slice(0,40)}`),Fe!==null&&Ke.push(`sandbox="${Fe.slice(0,40)}"`),Ke.join(" ")},Ct=y=>{if(!(y instanceof HTMLIFrameElement))return"";try{let g=y.contentDocument;if(!g)return"cd=null";let E=g.body?.children.length??0,le=g.body?.innerHTML.length??0,Fe=g.head?.innerHTML.length??0;return`cd=same-origin readyState=${g.readyState} body[${E}children,${le}ch] head[${Fe}ch]`}catch(g){return`cd=cross-origin(${g.message.slice(0,30)})`}},sr=[],yr=y=>{if(St())return;let g=y.message??String(y.error??"(no message)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(xe(`window:error ${g.slice(0,140)}`),sr.push(g))},Lr=y=>{if(St())return;let g=y.reason instanceof Error?y.reason.message:String(y.reason??"(no reason)");g&&(g.toLowerCase().includes("paypal")||g.toLowerCase().includes("zoid")||g.toLowerCase().includes("postrobot")||g.toLowerCase().includes("storage"))&&(xe(`window:rejection ${g.slice(0,140)}`),sr.push(g))},no={value:0},Dn=()=>{Bn?.disconnect(),Bn=null,Wn?.disconnect(),Wn=null;for(let y of Gr.splice(0))clearTimeout(y);Lt=!1,Pn&&typeof window<"u"&&(window.removeEventListener("error",yr),window.removeEventListener("unhandledrejection",Lr)),Pn=!1},Hn=()=>{if(!(Pn||St()||Or)){if(Pn=!0,sr.length=0,no.value=0,typeof window<"u"&&(window.addEventListener("error",yr),window.addEventListener("unhandledrejection",Lr)),typeof PerformanceObserver<"u")try{Wn=new PerformanceObserver(y=>{if(!St())for(let g of y.getEntries()){if(!g.name.toLowerCase().includes("paypal"))continue;no.value+=1;let E=Math.round(g.duration);xe(`net ${E}ms ${g.name.slice(0,90)}`)}}),Wn.observe({type:"resource",buffered:!0})}catch{}Yr?.()}},tn=()=>{hn&&(clearTimeout(hn),hn=null)},lr=()=>{Dn(),tn()},oo={setEnabled:y=>{y?Hn():Dn()}};nt.current=oo,Ce.current&&Hn();let pr=it.isPayPalTeardownMessage,q=y=>{if(St()||pr(y))return;let g=(0,ho.applyFriendlyMessageOverride)(y)??y;(0,rt.invokeMerchantCallback)(()=>Cr.current?.(g))},D=(y,g)=>{if(Zt||gn)return;gn=!0,Dr=!0,lr(),An();let E=sd({kind:y,generationActive:!0,automaticRetryAllowed:k,automaticRetryUsed:Et.current});if(E.action==="retry"){Et.current=!0,B(!1),ye(!1),Ge(!0),Ot.current?.("retrying"),fn=setTimeout(()=>{Zt||ct(le=>le+1)},nd);return}if(B(!1),ye(!1),Ge(!1),At(!0),E.action!=="ignore"){if(Ot.current?.("exhausted"),E.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",g);return}if(E.report){let le=(0,we.classifyExternalMethodFailure)({code:Sl(y,g),message:g},{inAppBrowser:G.inAppBrowser,handoffObserved:!1});le.popupBlocked&&N.markBlocked(),oe.error({errorCode:le.popupBlocked?le.errorCode:E.report.errorCode,stage:E.report.stage,operationOutcome:E.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:le.terminalReason})}Ut.current||(Ut.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Sl(y,g)))}};At(!1);let se=async(y,g=Kt.current)=>{if(St())return;let E=g?.sessionId??e;if(Ar.current){await Ar.current(y,{sessionId:E,accountPatch:g?.accountPatch,nonce:g?.nonce});return}let le=oe.startTiming();oe.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Fe=()=>{oe.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),oe.performance({stage:"processing",durationMs:oe.elapsed(le),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Ke=(0,it.buildPayPalProcessPaymentRequest)({body:y,sessionId:E,nonce:g?.nonce??br.current,accountPatch:g?.accountPatch,session:Fr.current,email:Ft.current}),Me=await new Ja.PaymentAPI(Tt,{telemetry:!1}).processPayment(Ke.userId,Ke.params);if(Me.ok){if(Dr||Zt&&Qr.current)return;Fe(),oe.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),(0,rt.invokeMerchantCallback)(()=>jr.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(St())return;let Xe=await Me.json().catch(()=>null),at=(0,it.describePayPalProcessFailure)(Xe),wt=at.message;Fe(),Me.status===400&&(typeof Xe?.declineCode=="string"||!Array.isArray(Xe?.fields))?oe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Me.status===400||Me.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:ld(Me.status),failureCategory:Me.status>=500?"server_error":void 0}),q(wt),(0,rt.invokeMerchantCallback)(()=>Ht.current?.(gr("paypal",wt,{code:at.code,declineCode:at.declineCode})));return}catch(Ke){if(St())return;Fe(),oe.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Xt=(0,it.friendlyPayPalFailureMessage)(Ke instanceof Error?Ke.message:void 0);q(Xt),(0,rt.invokeMerchantCallback)(()=>Ht.current?.(gr("paypal",Xt)));return}},be=()=>new it.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),It=y=>St()?Promise.reject(be()):Promise.resolve(y),Yt=async y=>{if(St())throw be();Bt||Kr();let g=Kt.current,E=g?.sessionId??e,le=g?.nonce??br.current;oe.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Fe;try{Fe=await new Ja.PaymentAPI(Tt,{telemetry:!1}).createSessionIntent(E,le??"",(0,it.buildPayPalSessionIntentRequest)(Mn),{idempotencyKey:ro})}catch(Ke){throw oe.error({...(0,it.classifyTelemetryFailure)(Ke,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Ke}if(St())throw be();if(Fe.provider!=="paypal"||Fe.providerObjectType!==P)throw new Error(y);return oe.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Fe.providerObjectId},Le=(y,g)=>{let E=g?.nonce??br.current;if(!E)return;let le=g?.sessionId??e,Fe=(0,it.resolvePayPalDeclineReason)(y);new Ja.PaymentAPI(Tt,{telemetry:!1}).reportSessionIntentDecline(le,E,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Fe}).catch(()=>{})},X=We;xe("loadScript:scheduled (deferred 1 tick)");let J=null,W=setTimeout(()=>{if(Zt){xe("loadScript:skipped (cancelled before defer ran)");return}xe("loadScript:start");let y=Oe==="live"?"production":Oe,g={};P==="subscription"?g={intent:"subscription",vault:!0}:P==="order"&&(g={intent:"capture"}),J=(0,wl.loadScript)({clientId:l,currency:m,...g,...y?{environment:y}:{},...y==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let E=!1;J.then(le=>{if(E=!0,xe(`loadScript:resolved inactive=${St()} ns=${!!le} buttons=${!!le?.Buttons}`),St())return;if(!le?.Buttons){xe("FAIL: namespace missing Buttons factory"),D("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(ue.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),oe.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Fe=async(Se,L)=>{if(St()||Ye.current!==X)return;let ie=Se.vaultSetupToken??Se.subscriptionID??Se.orderID??"",yt=ie?un.current.get(ie):or.current.get(X);if(!(!yt||!pn(yt.generation))&&ur(yt.generation)){un.current.delete(ie),or.current.delete(yt.surfaceKey),jt("approved");try{if(ye(!0),(0,rt.invokeMerchantCallback)(()=>Cr.current?.(null)),!ie)throw new it.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ve=(0,it.resolvePayPalApprovalIdentity)({accountPatch:yt.accountPatch,email:Ft.current,billingName:Wr.current,session:Fr.current});if((0,it.needsPayPalPayerDetails)(Ve))try{Ve=(0,it.mergePayPalPayerIdentity)(Ve,await L?.order?.get?.())}catch{}if((mt.current||Ze)&&!(0,it.isValidEmail)(Ve.email)){let Mt=await Y("PayPal",Ve);if(!Mt)return;Ve=Mt}(0,it.isValidEmail)(Ve.email)&&(yt.accountPatch=(0,on.compactBuyerIdentity)({...yt.accountPatch,...Ve}),await mt.current?.(Ve));let tt=(0,it.buildPayPalTokenizedBody)(ie,Mn);await se(tt,yt)}catch(Ve){q(Ve instanceof Error?Ve.message:"PayPal capture failed.")}finally{St()||ye(!1)}}},Ke=Se=>{let L=Be?()=>It(Be):()=>Yt(Se);return async()=>_r(await L())},Xt=le.Buttons({style:{layout:"horizontal",height:Za,tagline:!1},...he==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Se,L)=>{if(St()){await L.reject();return}Kr();let ie=st.current,yt={};if(ie)try{let Mt=await ie("paypal");if(St()){await L.reject();return}if(!Mt.proceed){Kt.current=null,or.current.delete(X),await L.reject();return}yt={sessionId:Mt.sessionId,accountPatch:Mt.accountPatch,nonce:Mt.nonce}}catch(Mt){xe(`onClick:runBeforeButtonClick rejected msg=${(Mt instanceof Error?Mt.message:String(Mt)).slice(0,120)}`),Kt.current=null,or.current.delete(X),await L.reject();return}(0,rt.invokeMerchantCallback)(()=>$r.current?.("paypal"));let Ve=ir(),tt={generation:Ve,surfaceKey:X,...yt};Kt.current=tt,or.current.set(X,tt),Ie.current={...f,attempt:Ve},await L.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"}),Pe.current=oe.startTiming()},createOrder:P==="order"?Ke("Failed to create PayPal order."):void 0,createSubscription:P==="subscription"?Ke("Failed to create PayPal subscription."):void 0,createVaultSetupToken:P==="setup_token"?async()=>_r(await Yt("Failed to create PayPal setup token.")):void 0,onApprove:Fe,onCancel:()=>{if(St())return;let Se=or.current.get(X)??Kt.current;Se&&or.current.delete(Se.surfaceKey),Kt.current=null,jt("cancelled"),oe.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ae.current=!0,Br({generation:Se?.generation,remount:!0,focus:!1})},onError:Se=>{if(St()||Ye.current!==X)return;let L=Se instanceof Error?Se.message:"PayPal failed to render.";if(xe(`onError rendered=${Or} msg=${L.slice(0,120)}`),Or){let ie=or.current.get(X)??Kt.current;if(ie&&!pn(ie.generation)||!ie&&mn())return;if(pr(L)){ur(ie?.generation);return}let{errorCode:yt,popupBlocked:Ve,providerDeclined:tt,terminalReason:Mt}=(0,we.classifyExternalMethodFailure)(Se,{inAppBrowser:G.inAppBrowser,handoffObserved:ie!=null&&ve.current===ie.generation});if(Ve&&N.markBlocked(),jt(Mt),tt){oe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Mt}),Le(Se,ie),(0,rt.invokeMerchantCallback)(()=>Ht.current?.(gr("paypal",L))),ie&&or.current.delete(ie.surfaceKey),Kt.current=null,ur(ie?.generation);return}oe.error({errorCode:yt,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Mt}),ie&&or.current.delete(ie.surfaceKey),Kt.current=null,Br({generation:ie?.generation,remount:!0,showRetry:!0,focus:!0}),mr(Se,{code:"paypal_runtime_failed",popupBlocked:Ve,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:he,terminalReason:Mt});return}D(pr(L)?"teardown":"pre_ready_callback",L)}}),Me=Xt.isEligible();if(xe(`isEligible=${Me}`),oe.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Me){B(!1),D("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Fn=!0,Gt=Xt,Yr=()=>{if(!Pn||Lt||St()||Or)return;Lt=!0,xe(`container:dims ${Tr(en)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Bn=new MutationObserver(L=>{if(!St()){for(let ie of L)if(ie.type==="childList")ie.addedNodes.forEach(yt=>{if(!(yt instanceof Element))return;let Ve=yt.tagName.toLowerCase(),tt=(yt.getAttribute("title")??"").slice(0,40),Mt=Ve==="iframe"?` ${Cn(yt)}`:"";xe(`child+ ${Ve}${tt?` title="${tt}"`:""}${Mt} dims=${Tr(yt)}`)});else if(ie.type==="attributes"&&ie.target instanceof Element){let yt=ie.target;if(yt.tagName.toLowerCase()!=="iframe")continue;let Ve=ie.attributeName;(Ve==="src"||Ve==="srcdoc")&&xe(`attr~ iframe ${Ve}=${Ve==="srcdoc"?`[${(yt.getAttribute("srcdoc")??"").length}ch]`:vn(yt.getAttribute("src"))} dims=${Tr(yt)}`)}}}),Bn.observe(en,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Se=L=>{if(St()||Or)return;let ie=en.querySelectorAll("iframe"),yt=typeof document<"u"&&"hasStorageAccess"in document;xe(`watchdog:${L} container=${Tr(en)} children=${en.childElementCount} iframes=${ie.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${yt} paypalNetRequests=${no.value}`),ie.forEach((Ve,tt)=>{let Mt=(Ve.getAttribute("title")??"").slice(0,40);xe(` iframe[${tt}] ${Tr(Ve)}${Mt?` title="${Mt}"`:""} ${Cn(Ve)}`);let Pt=Ct(Ve);Pt&&xe(` ${Pt}`)}),sr.length===0&&xe(" (no PayPal/zoid window errors captured)")};Gr.push(setTimeout(()=>Se("3s"),3e3)),Gr.push(setTimeout(()=>Se("8s"),8e3)),Gr.push(setTimeout(()=>Se("15s"),15e3))},Yr(),xe("render:start");let at=oe.startTiming();hn=setTimeout(()=>{St()||Or||(xe("watchdog:11s retryable render timeout"),D("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},od);let wt=Xt.render(en);(async()=>{try{if(await wt,xe(`render:resolved inactive=${St()}`),lr(),St()){An();return}Or=!0,B(!0),Ge(!1),Ot.current?.("ready"),oe.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),oe.performance({stage:"checkout_render",durationMs:oe.elapsed(at),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Se){let L=Se instanceof Error?Se.message:"PayPal failed to render.";xe(`render:rejected msg=${L.slice(0,120)}`),lr(),D(pr(L)?"teardown":"render_rejected",L)}})()}).catch(le=>{let Fe=le instanceof Error?le.message:"PayPal operation failed.";xe(`provider:failed msg=${Fe.slice(0,120)}`);let Ke="script_rejected";E&&pr(Fe)?Ke="teardown":E&&Fn&&(Ke="render_rejected"),D(Ke,Fe)})},0);return()=>{Zt=!0,clearTimeout(W),fn&&clearTimeout(fn),lr(),nt.current===oo&&(nt.current=null),An(),Pe.current=null,Ie.current=null}},[k,Tt,l,m,u,P,he,T,e,Be,We,Ee,Y,Ze,xe,jt]);let vt=me?(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=${ge} failed=${kt})`,bt.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${Ct.join(`
4
- `)}`]}):null;return kt&&!q?me?(0,sn.jsx)("div",{children:vt}):null:(0,sn.jsxs)("div",{children:[vt,Qe&&(0,sn.jsx)(qo,{identity:Qe.identity,methodLabel:Qe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ne,onCancel:()=>Ne(null)}),(0,sn.jsxs)("div",{"aria-hidden":ct||Qe?!0:void 0,style:ct||Qe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Qa},children:[!be&&!ct&&(0,sn.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,sn.jsx)("div",{ref:re,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Qa,display:"flex",opacity:be?1:0},"aria-busy":N||h},$e)]},$e),dt&&(0,sn.jsx)("button",{ref:ve,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Tr,style:nd,children:"Try PayPal again"})]})}function ha(e){return(0,sn.jsx)(wl,{...e})}function kl(e){return(0,sn.jsx)(wl,{...e})}var Pa=require("react/jsx-runtime");function $o({children:e,margin:t,icon:r=!0,styleOverride:n}){return(0,Pa.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,Pa.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Pa.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 dr=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:d=sd}){let p={fontSize:13,color:d.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,dr.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,dr.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...d.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,dr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,dr.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,dr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:d.spinnerTrackColor,strokeWidth:"3"}),(0,dr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:d.spinnerAccentColor})]}),e==="success"&&(0,dr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,dr.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,dr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,dr.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,dr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,dr.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,dr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,dr.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,dr.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:d.labelColors[e]},children:[e==="processing"&&n,e==="success"&&(o??(r?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&l!==null&&(0,dr.jsx)("p",{style:p,children:l}),e==="error"&&t&&(0,dr.jsx)("p",{style:p,children:t}),(0,dr.jsx)("style",{children:`
3
+ ${bt.join(`
4
+ `)}`]}):null;return kt&&!j?me?(0,an.jsx)("div",{children:vt}):null:(0,an.jsxs)("div",{children:[vt,et&&(0,an.jsx)(zo,{identity:et.identity,methodLabel:et.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Ue,onCancel:()=>Ue(null)}),(0,an.jsxs)("div",{"aria-hidden":$e||et?!0:void 0,style:$e||et?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Za},children:[!ge&&!$e&&(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:ee,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Za,display:"flex",opacity:ge?1:0},"aria-busy":U||h},We)]},We),dt&&(0,an.jsx)("button",{ref:_e,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Ir,style:ad,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 dr=require("react/jsx-runtime");var cd={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function zr({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=cd}){let m={fontSize:13,color:u.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,dr.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,dr.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,dr.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,dr.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,dr.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:u.spinnerTrackColor,strokeWidth:"3"}),(0,dr.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:u.spinnerAccentColor})]}),e==="success"&&(0,dr.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,dr.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,dr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,dr.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,dr.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,dr.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,dr.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,dr.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,dr.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,dr.jsx)("p",{style:m,children:l}),e==="error"&&t&&(0,dr.jsx)("p",{style:m,children:t}),(0,dr.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 Rl=require("@flopay/shared"),wr=require("react");var El=require("react/jsx-runtime");function va({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:o}){let[i,l]=(0,wr.useState)(e instanceof Promise?null:e),[d,p]=(0,wr.useState)(t instanceof Promise||!t?null:t),b=(0,wr.useRef)(null),k=(0,wr.useRef)(null),w=Vo(n);(0,wr.useEffect)(()=>{w({class:"lifecycle",name:"checkout.mount"})},[w]),(0,wr.useEffect)(()=>{i&&w({class:"lifecycle",name:"sdk.initialize.ready"})},[w,i]),(0,wr.useEffect)(()=>{if(i)return hr(i)?.subscribe?.(w)},[w,i]),(0,wr.useEffect)(()=>{if(!(!d||d===i))return hr(d)?.subscribe?.(w)},[w,i,d]),(0,wr.useEffect)(()=>{if(!i)return;let M=hr(i);return b.current=M?.beginCheckout()??M?.now()??0,M?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{M?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,wr.useEffect)(()=>{let M=!1;return e instanceof Promise?e.then(W=>{M||l(W)},()=>{M||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{M=!0}},[w,e]),(0,wr.useEffect)(()=>{let M=!1;if(!t){p(null);return}return t instanceof Promise?t.then(W=>{M||p(W)},()=>{M||w({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{M=!0}},[w,t]),(0,wr.useEffect)(()=>{if(!i||k.current===i)return;k.current=i;let M=hr(i);M?.log({name:"checkout.rendered",stage:"checkout_render"}),w({class:"lifecycle",name:"checkout.rendered"}),M?.performance({stage:"checkout_render",durationMs:M.elapsed(b.current??0),durationMode:"machine"})},[w,i]);let x=(0,Rl.resolveBillingApiUrl)(r?.billingApiUrl),O=(0,wr.useMemo)(()=>({flopay:i,paypalFlopay:d,billingApiUrl:x,emitInstrument:w}),[i,d,x,w]);return(0,El.jsx)(on.Provider,{value:O,children:o})}var _n=require("@flopay/shared");async function ei(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 ln=require("@flopay/js"),st=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:d}=await e.confirmCardSetup(t,r);return{error:d,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 Wo(e){return new st.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function dd(){return new st.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Zi(e,t){return Object.assign(e,{checkoutMethod:t})}function Qn(e,t){let r=e instanceof st.FloPayError?e:new st.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 ba(e,t){try{return await e()}catch(r){throw Qn(r,t)}}function _l(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 Tl(e){return(0,ln.runSavedCardChallenge)(e)}async function Ho(e,t){let{billingApiUrl:r,sessionId:n,signal:o}=t,i=t.nonce??t.session.clientSecret,l=new ln.PaymentAPI(r,{telemetry:!1}),d=`${r.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(n)}/status`,p;try{p=await(0,ln.completeSavedCardNextAction)({billingApiUrl:r,sessionId:n,nonce:i,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o,createDeclineError:k=>jn({type:k.declineReason??"authorization_declined",gatewayErrorCode:k.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"})},l)}catch(k){if(o.aborted||k instanceof Error&&k.name==="AbortError")throw k instanceof st.FloPayError&&k.code==="three_ds_aborted"?k:Wo(k);if(!(k instanceof st.FloPayError)||k.code!=="three_ds_timeout"&&k.code!=="checkout_processing_timeout")throw k;try{p=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:i,statusUrl:d,timeoutMs:5e3,signal:o})}catch(x){if(o.aborted)throw Wo(x);if(!(x instanceof st.FloPayError)||x.code!=="checkout_processing_timeout")throw x}let w=p&&lo(p,t.session);if(!Xn(w)&&w?.status!=="expired"){if(t.telemetry){let x=new ln.PaymentAPI(r);try{x.reportThreeDsAbandoned(n)}finally{x.destroy()}}throw dd()}}let b=p&&lo(p,t.session);if(!Xn(b))throw No(b);return{...Yn(b,n),checkoutMethod:"card"}}function jn(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,Po.applyFriendlyMessageOverride)(o)??o,l=Zi(new st.FloPayError(i,"api_error",{code:e?.code??(0,st.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,st.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),n);return e?.orderId&&(l.orderId=e.orderId),l}function Ji(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ti(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Ml(e,t){let r=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of r)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ti(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 d of i)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||ti(d)))return d;let l=o.gateways;if(l&&typeof l=="object"){let d=l.stripe;if(d&&typeof d=="object"){let p=d,b=[p.stripeClientSecret,p.clientSecret];for(let k of b)if(typeof k=="string"&&k.length>0&&(!t?.requirePaymentIntentClientSecret||ti(k)))return k}}}}async function ud({billingApiUrl:e,sessionId:t,nonce:r,responseJson:n}){let o=Ml(n,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new ln.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,r)).data.stripe?.clientSecret;if(ti(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Ko({billingApiUrl:e,sessionId:t,session:r,nonce:n,tokenizedData:o,returnUrl:i,telemetry:l}){let d=e.replace(/\/+$/,""),p=t??r.id,b=n??r.clientSecret,k=r.customer?.id??r.accountData?.userId??"",w=r.customer?.email??r.accountData?.email??"",x=r.customer?.firstName??r.accountData?.firstName??"",O=r.customer?.lastName??r.accountData?.lastName??"",M=r.customer?.country??r.accountData?.country??void 0,W=r.customer?.zip??r.accountData?.zip??void 0,h=await new ln.PaymentAPI(d,l===!1?{telemetry:!1}:void 0).processPayment(k,{sessionId:p,nonce:b,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:k,email:w,firstName:x,lastName:O,country:M,zip:W},returnUrl:i??Ji(r)});if(h.ok){let S=typeof h.json=="function"?await h.json().catch(()=>null):null;if((0,st.isAuthorizationOnlySession)(r)||S?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof S?.paymentId=="string"?S.paymentId:r.paymentId,sessionId:typeof S?.sessionId=="string"?S.sessionId:p,authorizationExpiresAt:typeof S?.authorizationExpiresAt=="string"?S.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:ma(o),checkoutMethod:Il(o,r)}};let Pe=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...Pe?{paymentIntentId:Pe}:{},paymentMethodId:ma(o),checkoutMethod:Il(o,r)}}}let v;try{v=await h.json()}catch(S){throw new st.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status,cause:S})}if(v?.type==="3ds_required"&&typeof v.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:v.nextActionRedirectUrl};if(v?.type==="paypal_redirect_required"||v?.type==="3ds_required"){let S=Ml(v);if(!S)throw new st.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status});return{type:v.type,threeDSecureToken:S,paymentMethodId:v.paymentMethodId}}if(v?.gatewayErrorCode==="authentication_required"){let S=await ud({billingApiUrl:d,sessionId:p,nonce:b,responseJson:v});if(S)return S;throw Zi(new st.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let te=new st.FloPayError(v?.message??"Payment failed. Please try again.","api_error",{code:v?.code??v?.gatewayErrorCode,declineCode:v?.declineCode??v?.gatewayDeclineReason,statusCode:h.status});throw Object.assign(te,{telemetryOutcome:(0,st.classifyPaymentRejection)(h.status,v)})}async function ri(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:o,sessionId:i,session:l,returnUrl:d,telemetry:p,signal:b}){let k=t?.getRawProvider();if(!k)throw Qn(new st.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!n||!e.threeDSecureToken)throw Zi(new st.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let w=(0,st.isSetupIntentClientSecret)(e.threeDSecureToken),x=null,O=e.paymentMethodId,M=await ba(()=>ld(k,e.threeDSecureToken,w),"card");if(M){if(M.error)throw Qn(new st.FloPayError(M.error.message??`Failed to retrieve 3DS ${w?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let _=M.intent;!O&&_?.payment_method&&(typeof _.payment_method=="string"?O=_.payment_method:"id"in _.payment_method&&(O=_.payment_method.id??void 0))}let W=O?await ba(()=>cd(k,e.threeDSecureToken,{payment_method:O,return_url:d??Ji(l)??window.location.href},w),"card"):null;if(W){if(W.error)throw Qn(new st.FloPayError(W.error.message??"3DS authentication failed.","api_error",{code:W.error.code}),"card");x=W.intent}else{let _=await ba(()=>k.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(_.error)throw Qn(new st.FloPayError(_.error.message??"3DS authentication failed.","api_error",{code:_.error.code}),"card");x=(w?_.setupIntent:_.paymentIntent)??null}if(x&&(x.status==="requires_capture"||x.status==="succeeded"||x.status==="processing")){let _=await Ko({billingApiUrl:o,sessionId:i,session:l,telemetry:p,tokenizedData:{id:x.id,type:"card",threeDSecureActionResultTokenId:x.id},returnUrl:d});return _.type==="success"?{..._.result,paymentIntentId:_.result.paymentIntentId??x.id,paymentMethodId:_.result.paymentMethodId??O}:_.type==="next_action_required"?Ho(_,{billingApiUrl:o,sessionId:i??l.id,session:l,signal:b}):ri(_,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:o,sessionId:i,session:l,returnUrl:d,telemetry:p,signal:b})}throw Qn(new st.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let w=(r??t)?.getRawProvider();if(!w)throw Qn(new st.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:O}=await ba(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(O)throw Qn(new st.FloPayError(O.message??"PayPal authorization failed.","api_error",{code:O.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:x}=await ba(()=>w.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??Ji(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(x)throw Qn(new st.FloPayError(x.message??"PayPal authorization failed.","api_error",{code:x.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new st.FloPayError("Unsupported payment redirect state.","api_error")}function Sa(e){if(e instanceof st.FloPayError){let n=(0,Po.applyFriendlyMessageOverride)(e.message);return n&&n!==e.message?Object.assign(new st.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,Po.applyFriendlyMessageOverride)(t)??t;return new st.FloPayError(r,"api_error")}function Qi(e){let t=e.data.stripe?.publishableKey,r=!!e.data.paypal?.publishableKey,n=(0,st.isMountableVaultBlock)(e.data.session?.vault)||(0,Rn.canRecoverHostedCardForm)(e.data.session);if(!t&&!r&&!n)throw new st.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 Il(e,t){return e?e.isPaypal?"paypal":"card":t&&(0,Rn.canRecoverHostedCardForm)(t)?"card":void 0}async function es({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,d]=await Promise.all([(0,ln.loadFloPay)(e,{billingApiUrl:r,locale:n,telemetry:o}),i?(0,ln.loadFloPay)(i,{billingApiUrl:r,locale:n,telemetry:o}).catch(b=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",b),null)):Promise.resolve(null)]);if(!l)throw new st.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return i?p=d:t&&(p=l),{flopay:l,paypalFlopay:p}}var Mn=require("@flopay/js"),u=require("@flopay/shared"),er=require("@stripe/react-stripe-js"),a=$i(require("react"),1);function Go(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function ni(e,t){if(e)return{error:r=>e.error(Go(t,r)),log:r=>e.log(Go(t,r)),performance:r=>e.performance(Go(t,r)),terminal:r=>e.terminal(Go(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 eo=require("@flopay/shared"),Al=require("react");var xl={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 Pr=require("react/jsx-runtime"),pd=`
9
+ `})]})})}var El=require("@flopay/shared"),wr=require("react");var Il=require("react/jsx-runtime");function Pa({flopay:e,paypalFlopay:t,options:r,onInstrument:n,children:o}){let[i,l]=(0,wr.useState)(e instanceof Promise?null:e),[u,m]=(0,wr.useState)(t instanceof Promise||!t?null:t),C=(0,wr.useRef)(null),w=(0,wr.useRef)(null),S=jo(n);(0,wr.useEffect)(()=>{S({class:"lifecycle",name:"checkout.mount"})},[S]),(0,wr.useEffect)(()=>{i&&S({class:"lifecycle",name:"sdk.initialize.ready"})},[S,i]),(0,wr.useEffect)(()=>{if(i)return hr(i)?.subscribe?.(S)},[S,i]),(0,wr.useEffect)(()=>{if(!(!u||u===i))return hr(u)?.subscribe?.(S)},[S,i,u]),(0,wr.useEffect)(()=>{if(!i)return;let M=hr(i);return C.current=M?.beginCheckout()??M?.now()??0,M?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{M?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,wr.useEffect)(()=>{let M=!1;return e instanceof Promise?e.then(V=>{M||l(V)},()=>{M||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{M=!0}},[S,e]),(0,wr.useEffect)(()=>{let M=!1;if(!t){m(null);return}return t instanceof Promise?t.then(V=>{M||m(V)},()=>{M||S({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):m(t),()=>{M=!0}},[S,t]),(0,wr.useEffect)(()=>{if(!i||w.current===i)return;w.current=i;let M=hr(i);M?.log({name:"checkout.rendered",stage:"checkout_render"}),S({class:"lifecycle",name:"checkout.rendered"}),M?.performance({stage:"checkout_render",durationMs:M.elapsed(C.current??0),durationMode:"machine"})},[S,i]);let x=(0,El.resolveBillingApiUrl)(r?.billingApiUrl),H=(0,wr.useMemo)(()=>({flopay:i,paypalFlopay:u,billingApiUrl:x,emitInstrument:S}),[i,u,x,S]);return(0,Il.jsx)(nn.Provider,{value:H,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 dd(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 ud(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 pd(){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`,m;try{m=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{m=await l.waitForCheckoutSessionCompletion(n,{initialDelayMs:0,nonce:i,statusUrl:u,timeoutMs:5e3,signal:o})}catch(x){if(o.aborted)throw $o(x);if(!(x instanceof lt.FloPayError)||x.code!=="checkout_processing_timeout")throw x}let S=m&&so(m,t.session);if(!Yn(S)&&S?.status!=="expired"){if(t.telemetry){let x=new sn.PaymentAPI(r);try{x.reportThreeDsAbandoned(n)}finally{x.destroy()}}throw pd()}}let C=m&&so(m,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 m=u,C=[m.stripeClientSecret,m.clientSecret];for(let w of C)if(typeof w=="string"&&w.length>0&&(!t?.requirePaymentIntentClientSecret||ei(w)))return w}}}}async function md({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(/\/+$/,""),m=t??r.id,C=n??r.clientSecret,w=r.customer?.id??r.accountData?.userId??"",S=r.customer?.email??r.accountData?.email??"",x=r.customer?.firstName??r.accountData?.firstName??"",H=r.customer?.lastName??r.accountData?.lastName??"",M=r.customer?.country??r.accountData?.country??void 0,V=r.customer?.zip??r.accountData?.zip??void 0,h=await new sn.PaymentAPI(u,l===!1?{telemetry:!1}:void 0).processPayment(w,{sessionId:m,nonce:C,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:w,email:S,firstName:x,lastName:H,country:M,zip:V},returnUrl:i??Xi(r)});if(h.ok){let k=typeof h.json=="function"?await h.json().catch(()=>null):null;if((0,lt.isAuthorizationOnlySession)(r)||k?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof k?.paymentId=="string"?k.paymentId:r.paymentId,sessionId:typeof k?.sessionId=="string"?k.sessionId:m,authorizationExpiresAt:typeof k?.authorizationExpiresAt=="string"?k.authorizationExpiresAt:r.authorizationExpiresAt,paymentMethodId:pa(o),checkoutMethod:_l(o,r)}};let fe=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...fe?{paymentIntentId:fe}:{},paymentMethodId:pa(o),checkoutMethod:_l(o,r)}}}let v;try{v=await h.json()}catch(k){throw new lt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status,cause:k})}if(v?.type==="3ds_required"&&typeof v.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:v.nextActionRedirectUrl};if(v?.type==="paypal_redirect_required"||v?.type==="3ds_required"){let k=xl(v);if(!k)throw new lt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:h.status});return{type:v.type,threeDSecureToken:k,paymentMethodId:v.paymentMethodId}}if(v?.gatewayErrorCode==="authentication_required"){let k=await md({billingApiUrl:u,sessionId:m,nonce:C,responseJson:v});if(k)return k;throw Ji(new lt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let Z=new lt.FloPayError(v?.message??"Payment failed. Please try again.","api_error",{code:v?.code??v?.gatewayErrorCode,declineCode:v?.declineCode??v?.gatewayDeclineReason,statusCode:h.status});throw Object.assign(Z,{telemetryOutcome:(0,lt.classifyPaymentRejection)(h.status,v)})}async function ti(e,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:o,sessionId:i,session:l,returnUrl:u,telemetry:m,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),x=null,H=e.paymentMethodId,M=await va(()=>dd(w,e.threeDSecureToken,S),"card");if(M){if(M.error)throw Zn(new lt.FloPayError(M.error.message??`Failed to retrieve 3DS ${S?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let _=M.intent;!H&&_?.payment_method&&(typeof _.payment_method=="string"?H=_.payment_method:"id"in _.payment_method&&(H=_.payment_method.id??void 0))}let V=H?await va(()=>ud(w,e.threeDSecureToken,{payment_method:H,return_url:u??Xi(l)??window.location.href},S),"card"):null;if(V){if(V.error)throw Zn(new lt.FloPayError(V.error.message??"3DS authentication failed.","api_error",{code:V.error.code}),"card");x=V.intent}else{let _=await va(()=>w.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(_.error)throw Zn(new lt.FloPayError(_.error.message??"3DS authentication failed.","api_error",{code:_.error.code}),"card");x=(S?_.setupIntent:_.paymentIntent)??null}if(x&&(x.status==="requires_capture"||x.status==="succeeded"||x.status==="processing")){let _=await Ho({billingApiUrl:o,sessionId:i,session:l,telemetry:m,tokenizedData:{id:x.id,type:"card",threeDSecureActionResultTokenId:x.id},returnUrl:u});return _.type==="success"?{..._.result,paymentIntentId:_.result.paymentIntentId??x.id,paymentMethodId:_.result.paymentMethodId??H}:_.type==="next_action_required"?Wo(_,{billingApiUrl:o,sessionId:i??l.id,session:l,signal:C}):ti(_,{flopay:t,paypalFlopay:r,attempt3DS:n,billingApiUrl:o,sessionId:i,session:l,returnUrl:u,telemetry:m,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:H}=await va(()=>S.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(H)throw Zn(new lt.FloPayError(H.message??"PayPal authorization failed.","api_error",{code:H.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:x}=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(x)throw Zn(new lt.FloPayError(x.message??"PayPal authorization failed.","api_error",{code:x.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 m=null;return i?m=u:t&&(m=l),{flopay:l,paypalFlopay:m}}var Tn=require("@flopay/js"),d=require("@flopay/shared"),er=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 Pr=require("react/jsx-runtime"),yd=`
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 @@ ${Ct.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
- `,Yo=44;function Xo(){return(0,Pr.jsx)("style",{children:pd})}function wa(e,t){let r=e.availablePaymentMethods;return r&&t.some(n=>r[n])?"ready":"unavailable"}function ka({state:e,placeholderTestId:t,borderRadius:r=8,children:n}){return e==="unavailable"||e==="load_error"?null:(0,Pr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Pr.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,Pr.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 ts(e){return e!=="unavailable"&&e!=="load_error"}function oi({method:e,themeId:t,submitting:r=!1,disabled:n=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:l,backgroundColor:d,borderColor:p,textColor:b,borderRadius:k,fontFamily:w}){let x=(0,eo.resolveStripeMethodBrandVariant)(e,t),O=xl[e],[M,W]=(0,Al.useState)(!1),_=!!O&&!M,h=x?.backgroundColor??d??"#ffffff",v=x?.borderColor??p??"#d1d5db",te=x?.textColor??b??"#262833";return(0,Pr.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:Yo,padding:"0 1rem",backgroundColor:h,color:te,border:`1px solid ${v}`,borderRadius:k??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:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:r?(0,Pr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,eo.getStripeMethodDisplayName)(e)}\u2026`}):(0,Pr.jsxs)(Pr.Fragment,{children:[(0,Pr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,eo.hasVendoredStripeMethodLogo)(e)?8:0},children:[_?(0,Pr.jsx)("img",{src:O,alt:"","aria-hidden":"true",onError:()=>W(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!_&&x?.logoSvg?(0,Pr.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,Pr.jsx)("span",{children:(0,eo.getStripeMethodDisplayName)(e)})]}),i&&(0,Pr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:te,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,Pr.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function ai(e){let t=new Set(e.map(eo.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 ii={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},si={type:"accordion",defaultCollapsed:!1,radios:"never"};function li({testId:e,attributes:t,disabled:r,onClick:n,color:o,borderRadius:i,style:l,children:d}){return(0,Pr.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:d})}var Qr=require("react");var Ra=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 Fl(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"),rs=new WeakSet;function co({capture:e,html:t,messageToken:r,expectedOrigin:n,verificationRequired:o,theme:i,submitLabel:l,containerStyle:d,onReady:p,onError:b,onValidation:k}){let w=(0,Qr.useRef)(null),x=(0,Qr.useRef)(p),O=(0,Qr.useRef)(b),M=(0,Qr.useRef)(k);x.current=p,O.current=b,M.current=k;let W=(0,Qr.useRef)(i);W.current=i;let _=(0,Qr.useRef)(null),h=l??void 0,v=(0,Qr.useRef)(h);v.current=h;let te=(0,Qr.useRef)(void 0);return(0,Qr.useEffect)(()=>{let S=w.current;if(!S)return;let Pe=!0,j=!1,Q=()=>{!Pe||j||(j=!0,x.current?.())},Be=e.on("ready",()=>{Q()}),se=e.on("error",pe=>{O.current?.(pe.message??"There was a problem loading the secure card form.")}),je=e.on("validation",pe=>{M.current?.(pe.message??null)}),Je=v.current??(rs.has(e)?null:void 0),me={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...o?{verificationRequired:!0}:{},...W.current?{theme:W.current}:{},...Je===void 0?{}:{submitLabel:Je}};return _.current=W.current??null,te.current=v.current,v.current!==void 0&&rs.add(e),e.mount(S,me).then(()=>{Q()}).catch(pe=>{Pe&&O.current?.(pe instanceof Error?pe.message:"Failed to load the secure card form.")}),()=>{Pe=!1,Be(),se(),je(),e.unmount()}},[e,t,r,n,o]),vo(()=>{let S=w.current;S&&Fl(S,d)},[d]),(0,Qr.useEffect)(()=>{i!==void 0&&(i===null&&_.current===null||(_.current=i,e.applyTheme?.(i)))},[e,i]),(0,Qr.useEffect)(()=>{h!==te.current&&(te.current=h,h!==void 0&&rs.add(e),e.setSubmitLabel?.(h??null))},[e,h]),(0,Co.jsx)("div",{ref:w,"data-testid":"flopay-vault-card-fields"})}function ci({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 Ir=require("@flopay/shared");var c=require("react/jsx-runtime"),Vn="flopay_stripe_resume",Bl="flopay_wallet_resume",Wl="fw1",gd="fw2",Hl=300*1e3,hd=900,Pd=25e3,vd=25e3,bd=1e4,Tn={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 di={},Ia=class{constructor(t){this.reason=t}};function kd(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function tr(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function cs(e){return`${gd}:${e}`}function ui(e){return tr(cs(e))}function pi(e,t){if(typeof window>"u")return null;let r=cs(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>Hl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(ui(e),null):o}catch{return ui(e),null}}function Rd(e){return tr(cs(e.sessionId),e)}function Dl(e,t,r){let n=pi(e,t);return!n||n.clientSecret!==r?!1:ui(e)}function ns(e,t,r){if(typeof window>"u")return;pi(e,t)?.clientSecret===r&&ui(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 os(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":pa(e.status),o=Ed(e);return!n||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function Ol(e,t,r){let n=null;try{return await Promise.race([fl(e,t),new Promise(o=>{n=window.setTimeout(()=>{n!==null&&r?.delete(n),o(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 Kl(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function mi(e,t,...r){let n=r[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:n});try{return await new Mn.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...r)}catch(o){throw Kl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:n}),o}}var as=u.STRIPE_PAYPAL_RESUME_KEY,Ea=new Map,_d=250,Ll="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 ds(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 Mn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Md(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Gl({event:e,fallbackEmail:t,fallbackName:r}){let n=e.billingDetails,o=t?.trim(),i=(0,Uo.splitFullName)(r),l=i.firstName?i:(0,Uo.splitFullName)(n?.name);return(0,an.compactBuyerIdentity)({email:(0,u.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=Gl({event:e,fallbackEmail:t?.accountPatch?.email??r,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||n});return(0,u.isValidEmail)(l.email)?l:i(o,l)}var _a=180,Nl=`flopay-card-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,Ul=`flopay-card-exit ${_a}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Ad=`flopay-buttons-enter ${_a}ms cubic-bezier(0, 0, 0.2, 1) both`,Fd=`flopay-buttons-exit ${_a}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 us(e){return(0,u.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 is={width:"100%",minHeight:Yo,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 zl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ss(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function Ld(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Nd(e,t,r){let n=(0,u.isPostalCodeSupported)(e),o=t.trim(),i=r&&n,l=i&&!o,d=i&&!!o&&!(0,u.isValidPostalCode)(e,o);return{visible:r,supported:n,required:i,empty:l,malformed:d}}function Ud(e,t){let r=e.trim(),n=t&&!r,o=t&&!!r&&!(0,u.isValidEmail)(r);return{required:t,empty:n,malformed:o,value:r}}function zd(e){return typeof e=="number"?`${e}px`:e}function fi(e){return(0,c.jsx)(qd,{...e})}function ql({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:o,onErrorChange:i,isProcessing:l=!1,onButtonClick:d,onDecline:p,onTechnicalFailure:b,runBeforeButtonClick:k,billingName:w,onBuyerIdentityReady:x,onLoadStateChange:O,placeholderBorderRadius:M,popupCapabilityOwner:W,externalTelemetryContext:_,presentationMode:h}){let v=Zn(),{emitInstrument:te}=(0,a.useContext)(on),S=(0,er.useStripe)(),Pe=(0,er.useElements)(),j=(0,a.useMemo)(()=>ni(hr(v),_),[_,v]),[Q,Be]=(0,a.useState)("loading");(0,a.useEffect)(()=>{O?.(Q)},[Q,O]);let[se,je]=(0,a.useState)(!1),Je=(0,a.useRef)(!1),me=!(0,u.isValidEmail)(r?.trim())||!w?.trim(),{request:pe,collect:Ke,finish:Re}=zo(),_e=(0,a.useRef)(!1),Ee=(0,a.useRef)(null),re=(0,a.useRef)(null),[ae,ge]=(0,a.useState)(0),[Me,K]=(0,a.useState)(!1),ee=(0,a.useRef)(!1),ye=(0,a.useRef)(new Map),{startAttempt:L,finishAttempt:ve,invalidateAttempt:Y,isAttemptInvalidated:be,isAttemptCurrent:X,generationRef:ct}=ga((N,fe,Qe)=>{b?.(N,fe,{...Qe,popupBlocked:Qe?.popupBlocked??(0,ke.isPopupBlockedError)(fe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h,terminalReason:"overlay_timeout"}),K(!0),ge(G=>G+1)},{onHandoffObserved:()=>{W.markAvailable(),j?.log({name:"provider.popup.opened",stage:"overlay_open",...Tn,attempt:ct.current})}});(0,a.useEffect)(()=>{Me&&re.current?.focus()},[Me,ae]);let Ge=(0,a.useCallback)(()=>{ge(N=>N+1)},[]),$e=(0,a.useCallback)((N,fe,Qe)=>{Y(Qe),b?.("paypal",N,{code:fe,popupBlocked:(0,ke.isPopupBlockedError)(N),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h}),K(!0),Ge()},[Y,b,h,Ge]),lt=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{ee.current&&(ee.current=!1,lt())},[lt,ae]);let Ye=(0,a.useCallback)(()=>{K(!1),i?.(null),lt()},[lt,i]);(0,a.useEffect)(()=>{if(!S||_e.current)return;let[N,fe,Qe]=(0,u.readStripeRedirectParams)();if(!N||!fe)return;let G=(0,u.readMatchingStripePayPalContinuation)(fe);if(!G)return;_e.current=!0;let Ne=!0,Rt=Ea.get(fe);Rt||(Rt=Qe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>S.retrievePaymentIntent(fe)),Ea.set(fe,Rt));let Ze={accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce},Tt=()=>{j?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Tn,requestCategory:"provider_sdk"})};return j?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Tn}),(async()=>{try{je(!0);let m=await Rt;if(!Ne)return;if(m?.error){Ea.delete(fe),Tt(),i?.(m.error.message??"Failed to retrieve PayPal payment status.");return}if((0,u.clearStripePayPalReturn)(),Ea.delete(fe),Qe==="failed"){let H="PayPal payment was declined. Please try again.";j?.terminal({outcome:"payment_declined",...Tn,terminalReason:"provider_declined"}),i?.(H),p?.(gr("paypal",H));return}let P=m?.paymentIntent;if(P&&P.id!==N){Tt(),i?.("Failed to match the returned PayPal payment.");return}if(P&&(P.status==="requires_capture"||P.status==="succeeded")){let H=typeof P.payment_method=="string"?P.payment_method:P.payment_method?.id;o({id:H??P.id,type:"card",threeDSecureActionResultTokenId:P.id,isPaypal:!0},{...Ze,presentationMode:"redirect"})}else{let H="PayPal payment was not completed. Please try again.";j?.terminal({outcome:P?.status==="canceled"?"payment_cancelled":"payment_declined",...Tn,terminalReason:P?.status==="canceled"?"cancelled":"provider_declined"}),i?.(H),p?.(gr("paypal",H))}}catch(m){if(!Ne)return;Ea.delete(fe),Tt(),i?.(m instanceof Error?m.message:"Failed to complete PayPal payment.")}finally{Ne&&je(!1)}})(),()=>{Ne=!1,_e.current=!1}},[S,o,i,p,j]);let dt=(0,a.useCallback)(async(N=!1)=>{let fe=k?await k("paypal"):{proceed:!0};if(!fe.proceed)return ye.current.delete(ae),!1;let Qe=L("paypal");return ye.current.set(ae,{generation:Qe,accountPatch:fe.accountPatch,sessionId:fe.sessionId,nonce:fe.nonce}),K(!1),j?.log({name:`provider.${N?"redirect.started":"handoff.requested"}`,stage:N?"redirect":"overlay_open",...Tn,attempt:Qe}),d?.("paypal"),!0},[d,j,k,L,ae]),We=(0,a.useCallback)(async N=>{if(l||se||!await dt()){N.reject();return}N.resolve()},[l,dt,se]),Et=(0,a.useCallback)(async N=>{if(!S||!Pe)return;let fe=ye.current.get(ae);if(fe&&!X(fe.generation)){ye.current.delete(ae);return}if(!fe&&be()||fe&&!ve(fe.generation))return;fe||ve();let Qe=fe??null;if(ye.current.delete(ae),!Qe&&k){let U=await k("paypal");if(!U.proceed){N.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Qe={accountPatch:U.accountPatch,sessionId:U.sessionId,nonce:U.nonce}}let G=Qe?.sessionId??e,Ne=Qe?.nonce??t,Rt=await xd({event:N,prepared:Qe,email:r,billingName:w,methodLabel:"PayPal",collect:Ke});if(!Rt){N.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ze=Rt.email,Tt={...Qe?.accountPatch,...(0,an.compactBuyerIdentity)(Rt,!0)};try{if(je(!0),i?.(null),!G||!(0,u.isValidEmail)(Ze))throw new Error("Missing sessionId or email for PayPal payment");await x?.(Rt);let U=S.createPaymentMethod,{error:m,paymentMethod:P}=await U({type:"paypal"});if(m){$e(m,"stripe_paypal_create_payment_method_failed",fe?.generation),N.paymentFailed({reason:"fail"});return}let H=await mi(n,te,G,Ne??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:P?.id??null,intentKind:"payment"});if(H.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let V=H.clientSecret,he={return_url:(0,u.stripeRedirectReturnUrl)()};if(P?.id&&(he.payment_method=P.id),!tr(as,{clientSecret:V,sessionId:G,nonce:Ne,accountPatch:Tt})&&h==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:A,paymentIntent:ne}=await S.confirmPayment({clientSecret:V,confirmParams:he,redirect:"if_required"});if(A){if(tr(as),(0,ke.isProviderDecline)(A)){let Ce=A.message??"Your payment was declined.";j?.terminal({outcome:"payment_declined",...Tn,terminalReason:"provider_declined"}),i?.(Ce),p?.(gr("paypal",Ce,{code:(0,ke.getProviderErrorCode)(A),declineCode:(0,ke.getProviderDeclineCode)(A)})),await yi({billingApiUrl:n,sessionId:G,nonce:Ne,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,ke.getProviderErrorCode)(A)??"provider_declined"}})}else $e(A,"stripe_paypal_confirm_failed",fe?.generation);return}tr(as);let q=typeof ne?.payment_method=="string"?ne.payment_method:ne?.payment_method?.id;o({id:q??ne?.id,type:"card",threeDSecureActionResultTokenId:ne?.id,isPaypal:!0},{accountPatch:Tt,paymentMethodCategory:"paypal",presentationMode:h,sessionId:G,nonce:Ne});return}catch(U){$e(U,"stripe_paypal_failed",fe?.generation)}finally{je(!1)}},[S,Pe,e,t,r,w,Ke,x,n,te,o,i,p,k,$e,ve,X,be,j,h,ae]),Ut=(0,a.useCallback)(async()=>{if(!(Je.current||l||se||!S||!Pe)){Je.current=!0,je(!0);try{if(!await dt(!0))return;await Et({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Je.current=!1,je(!1)}}},[Pe,Et,l,dt,S,se]),kt=h==="redirect"?(0,c.jsx)("button",{type:"button",disabled:l||se,onClick:()=>{Ut()},style:{width:"100%",minHeight:Yo,border:"1px solid #d1d5db",borderRadius:M??8,background:"#ffc439",color:"#111827",cursor:l||se?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,c.jsx)(er.ExpressCheckoutElement,{onReady:N=>Be(wa(N,["paypal"])),onLoadError:()=>{Be("load_error"),ds(j,"paypal","paypal","provider_error")},onClick:We,onConfirm:Et,onCancel:()=>{let N=ye.current.get(ae);ye.current.delete(ae),j?.terminal({outcome:"payment_cancelled",...Tn,terminalReason:"cancelled",...N?{attempt:N.generation}:{}}),Y(N?.generation),K(!1),ee.current=!0,Ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:me,emailRequired:me,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ae),At=(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Me&&(0,c.jsx)("button",{ref:re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ye,style:is,children:"Try PayPal again"}),pe&&(0,c.jsx)(qo,{identity:pe.identity,methodLabel:pe.methodLabel,onComplete:Re,onCancel:()=>Re(null)},pe.id),(0,c.jsx)("div",{style:{display:pe?"none":void 0},children:kt})]}),se&&!pe&&(0,c.jsx)(qr,{status:"processing"})]});return h==="redirect"?At:(0,c.jsx)(ka,{state:Q,placeholderTestId:"flopay-paypal-placeholder",borderRadius:M,children:At})}function jl(e){return e==="apple_pay"||e==="google_pay"}function Vl({sessionId:e,nonce:t,email:r,billingApiUrl:n,intentKind:o,expressMethods:i,onTokenizedBody:l,onErrorChange:d,onButtonClick:p,onDecline:b,onTechnicalFailure:k,runBeforeButtonClick:w,billingName:x,onBuyerIdentityReady:O,onLoadStateChange:M,placeholderBorderRadius:W,popupCapabilityOwner:_,externalTelemetryContext:h}){let v=Zn(),{emitInstrument:te}=(0,a.useContext)(on),S=(0,er.useStripe)(),Pe=(0,er.useElements)(),j=(0,a.useMemo)(()=>ni(hr(v),h),[h,v]),[Q,Be]=(0,a.useState)("loading");(0,a.useEffect)(()=>{M?.(Q)},[Q,M]);let[se,je]=(0,a.useState)(!1),Je=(0,a.useRef)(!(0,u.isValidEmail)(r?.trim())||!x?.trim()).current,{request:me,collect:pe,finish:Ke}=zo(),Re=(0,a.useRef)(null),_e=(0,a.useRef)(null),[Ee,re]=(0,a.useState)(0),[ae,ge]=(0,a.useState)(!1),[Me,K]=(0,a.useState)(()=>pi(e,t)?"blocked":"idle"),[ee,ye]=(0,a.useState)("google_pay"),L=(0,a.useRef)(null),ve=(0,a.useRef)(!0),Y=(0,a.useRef)(!1),be=(0,a.useRef)("google_pay"),X=(0,a.useRef)("google_pay"),ct=(0,a.useRef)(null),Ge=(0,a.useRef)(null),$e=(0,a.useRef)(new Set),lt=(0,a.useRef)(null);(0,a.useEffect)(()=>(ve.current=!0,()=>{ve.current=!1;for(let U of $e.current)window.clearTimeout(U);$e.current.clear()}),[]);let Ye=(0,a.useRef)(new Map),{startAttempt:dt,finishAttempt:We,invalidateAttempt:Et,isAttemptInvalidated:Ut,isAttemptCurrent:kt,generationRef:At}=ga((U,m,P)=>{k?.(U,m,{...P,popupBlocked:P?.popupBlocked??(0,ke.isPopupBlockedError)(m),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ye(U),ge(!0),re(H=>H+1)},{onHandoffObserved:U=>{_.markAvailable(),j?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:At.current,...U==="apple_pay"||U==="google_pay"?{walletType:U}:{}})},defersMissingTerminal:jl,onMissingTerminalDeferred:(U,m)=>{let P=j?.now()??globalThis.performance?.now()??Date.now(),H=lt.current,V=H?.generation===m?H.startedAt:P;j?.performance({stage:"overlay_return",durationMs:Math.max(0,P-V),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:m,...jl(U)?{walletType:U}:{}}),j?.flush?.().catch(()=>{})}});(0,a.useEffect)(()=>{ae&&_e.current?.focus()},[ae,Ee]);let N=(0,a.useCallback)(()=>{re(U=>U+1)},[]),fe=(0,a.useCallback)((U,m,P,H,V=!1)=>{Et(H),k?.(U,m,{code:P,popupBlocked:(0,ke.isPopupBlockedError)(m),telemetryReported:V,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ye(U),ge(!0),N()},[Et,k,N]),Qe=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Y.current&&(Y.current=!1,Qe())},[Qe,Ee]);let G=(0,a.useCallback)(()=>{ge(!1),d?.(null),Qe()},[Qe,d]),Ne=(0,a.useCallback)(()=>{L.current?.()},[]);(0,a.useEffect)(()=>{let U=pi(e,t);if(!U)return;let m=!1,P=!1,H=async()=>{if(!P){P=!0,m||K("checking");try{let V=await Ol(S,U.clientSecret,$e.current);if(m)return;let he=os(V,U.providerObjectId,(0,u.isSetupIntentClientSecret)(U.clientSecret));if(he.kind==="confirmed"){if(!Dl(e,t,U.clientSecret))return;L.current=null,K("idle"),l({id:he.paymentMethodId,type:"card",threeDSecureActionResultTokenId:he.intentId},{...U.accountPatch?{accountPatch:U.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(he.kind==="terminal"){ns(e,t,U.clientSecret),L.current=null,K("idle"),ye(U.paymentMethodType),ge(!0),N();return}K("blocked")}catch{m||K("blocked")}finally{P=!1}}};return L.current=H,K("blocked"),()=>{m=!0,L.current===H&&(L.current=null)}},[t,l,N,e,S]);let Rt=(0,a.useCallback)(async U=>{let m=!1,P=mt=>{m||(m=!0,U.paymentFailed({reason:"fail",...mt?{message:mt}:{}}))};if(!S||!Pe){P();return}let H=Ye.current.get(Ee);if(H&&!kt(H.generation)){Ye.current.delete(Ee),P();return}if(!H&&Ut()){P();return}if(H&&!We(H.generation)){P();return}H||We();let V=U.expressPaymentType??H?.method??be.current,he=H??null,T=zl(V),A;V==="apple_pay"?A="apple_pay":V==="google_pay"&&(A="google_pay");let ne=H?.generation??At.current,q=j,Ce=q?.now()??globalThis.performance?.now()??Date.now(),rt=new AbortController,Ct=!1,ht=!1,xe=null,Fr=e,Vr="processing",br="other",Ht="provider_runtime",$r,Wr=new Promise((mt,it)=>{$r=it}),Rr=window.setTimeout(()=>{Ct=!0,rt.abort(),$r(di)},Pd),Lt=async(mt,it,Br)=>{Vr=mt,br=it,Ht=it==="intent_create"||it==="session_claim"?"transport_error":"provider_runtime";let Bt=q?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Br,Wr])}finally{let Hr=q?.now()??globalThis.performance?.now()??Date.now();q?.performance({stage:mt,durationMs:Math.max(0,Hr-Bt),durationMode:"machine",requestCategory:it,paymentMethodCategory:"wallet",provider:"stripe",...Ct?{statusClass:"timeout"}:{}})}};try{if(je(!0),d?.(null),!he&&w){let De=await Lt("processing","other",w(T));if(!De.proceed){P();return}he={accountPatch:De.accountPatch,sessionId:De.sessionId,nonce:De.nonce}}let mt=he?.sessionId??e;Fr=mt;let it=he?.nonce??t,Br=ct.current??he?.accountPatch,Bt=Gl({event:U,fallbackEmail:Br?.email??r,fallbackName:[Br?.firstName,Br?.lastName].join(" ").trim()||x});if(!(0,u.isValidEmail)(Bt.email)){P("Buyer details are required."),pe(ss(V),Bt).then(De=>{De&&(ct.current=De)});return}ct.current=null;let Hr={...he?.accountPatch,...(0,an.compactBuyerIdentity)(Bt,!0)};await Lt("processing","session_claim",Promise.resolve(O?.(Bt)));let{error:Cr}=await Lt("tokenization","provider_sdk",Pe.submit());if(Cr){P(),fe(V,Cr,"stripe_wallet_submit_failed",H?.generation);return}if(!mt)throw new Error("Missing sessionId or email for payment.");let Kt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:V,paymentMethodId:null,intentKind:o},or=JSON.stringify({sessionId:mt,nonce:it??"",request:Kt}),pn=Ge.current,en=pn?.retryIdentity===or?pn.authorizationAttemptId:(0,u.randomUuidV4)();Ge.current={authorizationAttemptId:en,retryIdentity:or};let ar=await Lt("processing","intent_create",mi(n,te,mt,it??"",{...Kt,authorizationAttemptId:en},{signal:rt.signal}));if(ar.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let zt=ar.clientSecret,Tr=Rd({createdAt:Date.now(),sessionId:mt,...it?{nonce:it}:{},clientSecret:zt,providerObjectId:ar.providerObjectId,paymentMethodType:V,accountPatch:Hr});window.clearTimeout(Rr),ht=!0,q?.performance({stage:"callback",durationMs:Math.max(0,(q?.now()??globalThis.performance?.now()??Date.now())-Ce),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let mr=q?.now()??globalThis.performance?.now()??Date.now(),jt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...A?{walletType:A}:{},attempt:ne},Sr=!1,Vt=null;q?.log({name:"payment.provider_confirmation.started",...jt}),xe=window.setTimeout(()=>{xe!==null&&$e.current.delete(xe),Sr=!0;let De=q?.now()??globalThis.performance?.now()??Date.now();q?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...jt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,De-mr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),q?.flush?.().catch(()=>{}),Vt?.()},vd),$e.current.add(xe);let ur=(De,vt)=>{xe!==null&&(window.clearTimeout(xe),$e.current.delete(xe),xe=null);let f=q?.now()??globalThis.performance?.now()??Date.now(),nt=Math.max(0,f-mr),ie=De;Sr&&(De==="resolved"?ie="resolved_late":De==="returned_error"?ie="returned_error_late":ie="rejected_late");let Er=vt??(De==="resolved"?"approved":"provider_error");return q?.log({name:"payment.provider_confirmation.returned",...jt,operationOutcome:ie,terminalReason:Er}),q?.performance({...jt,durationMs:nt,durationMode:"buyer",operationOutcome:ie,terminalReason:Er}),{durationMs:nt,operationOutcome:ie,terminalReason:Er}},qt=!1,Ae=!1,mn=De=>{if(!De||typeof De!="object")return null;let vt=De;if(vt.error)return null;let f=vt.setupIntent??vt.paymentIntent,nt=os(f??null,void 0,!!vt.setupIntent);return nt.kind==="confirmed"?nt:null},yn=De=>{if(qt||H&&At.current!==H.generation)return;let vt=mn(De);if(!vt)return;if(Tr&&!Dl(mt,it,zt)){qt=!0;return}let{intentId:f,paymentMethodId:nt}=vt;qt=!0,Ae=!0,Ge.current=null,L.current=null,ve.current&&(K("idle"),je(!1));let ie=`${Wl}:${mt}`;tr(ie,{createdAt:Date.now(),sessionId:mt,nonce:it,accountPatch:Hr,paymentMethodId:nt,providerIntentId:f,paymentMethodType:V});try{l({id:nt,type:"card",threeDSecureActionResultTokenId:f},{accountPatch:Hr,paymentMethodCategory:"wallet",sessionId:mt,nonce:it})}finally{tr(ie)}},fn=!1;Vt=async()=>{if(!(fn||qt||Ae)){fn=!0,ve.current&&K("checking");try{let De=await Ol(S,zt,$e.current);if(qt||Ae)return;let vt=(0,u.isSetupIntentClientSecret)(zt),f=os(De,ar.providerObjectId,vt);if(f.kind==="confirmed"){yn(vt?{setupIntent:De}:{paymentIntent:De});return}if(f.kind==="terminal"){if(Ae=!0,ns(mt,it,zt),Ge.current=null,L.current=null,!ve.current)return;K("idle"),P(),fe(V,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",H?.generation,!0);return}ve.current&&!Ae&&(K("blocked"),je(!1))}catch{ve.current&&!Ae&&(K("blocked"),je(!1))}finally{fn=!1}}},L.current=Vt;let ir,Dr;try{let De=await((0,u.isSetupIntentClientSecret)(zt)?S.confirmSetup({elements:Pe,clientSecret:zt,redirect:"if_required"}):S.confirmPayment({elements:Pe,clientSecret:zt,redirect:"if_required"}));if(!De||typeof De!="object")throw new Ia(kd(De));if(ir=De,!ir.error&&!mn(ir))throw new Ia("confirmation_result_unconfirmed");Dr=ur(ir.error?"returned_error":"resolved",ir.error&&(0,ke.isProviderDecline)(ir.error)?"provider_declined":void 0)}catch(De){let vt=De instanceof Ia?De.reason:void 0,f=vt!==void 0,nt=ur(f?"returned_error":"rejected");if(q?.error({...f?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:vt}:Gi(De),...jt,operationOutcome:nt.operationOutcome,durationMs:nt.durationMs,statusClass:"unknown",terminalReason:nt.terminalReason}),!ve.current||qt)return;await Vt?.();return}let Mr=ir.error;if(Mr){if(!ve.current||qt)return;if((0,ke.isProviderDecline)(Mr)){Ae=!0,ns(mt,it,zt),Ge.current=null,L.current=null,K("idle");let De=Mr.message??"Your payment was declined.";P(De),d?.(De),b?.(gr(T,De,{code:(0,ke.getProviderErrorCode)(Mr),declineCode:(0,ke.getProviderDeclineCode)(Mr)})),yi({billingApiUrl:n,sessionId:mt,nonce:it,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:V,providerDeclineReason:(0,ke.getProviderErrorCode)(Mr)??"provider_declined",...ar.intentKind==="payment"&&ar.providerObjectId.startsWith("pi_")?{providerIntentId:ar.providerObjectId}:{}}})}else q?.error({...Gi(Mr),...jt,operationOutcome:Dr.operationOutcome,durationMs:Dr.durationMs,statusClass:"unknown",terminalReason:Dr.terminalReason}),await Vt?.();return}if(yn(ir),!qt)throw new Error("Invalid provider returned for APM intent")}catch(mt){if(mt===di){let it=q?.now()??globalThis.performance?.now()??Date.now();q?.error({errorCode:Id(br),stage:Vr,requestCategory:br,paymentMethodCategory:"wallet",provider:"stripe",...A?{walletType:A}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Fr,durationMs:Math.max(0,it-Ce),statusClass:"timeout",failureCategory:Ht,attempt:ne,terminalReason:"provider_error"}),q?.flush?.().catch(()=>{})}P(),fe(V,mt,mt===di?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",H?.generation,mt===di)}finally{if(window.clearTimeout(Rr),xe!==null&&(window.clearTimeout(xe),$e.current.delete(xe)),!ht){let mt=q?.now()??globalThis.performance?.now()??Date.now();q?.performance({stage:"callback",durationMs:Math.max(0,mt-Ce),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Ct?{statusClass:"timeout"}:{}})}ve.current&&je(!1)}},[S,Pe,e,t,r,x,pe,O,n,te,o,l,d,b,w,fe,We,kt,Ut,At,j,Ee]),Ze=(0,a.useMemo)(()=>ai(i),[i]),Tt=(0,a.useMemo)(()=>i.map(u.stripeExpressMethodToOptionKey),[i]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ka,{state:Q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:W,children:(0,c.jsxs)("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ae&&(0,c.jsxs)("button",{ref:_e,type:"button","data-testid":"flopay-wallet-retry-button",onClick:G,style:is,children:["Try ",ss(ee)," again"]}),Me!=="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:Ne,disabled:Me==="checking",style:is,children:Me==="checking"?"Checking payment status\u2026":"Check payment status"})]}),me&&(0,c.jsx)(qo,{identity:me.identity,methodLabel:me.methodLabel,onComplete:Ke,onCancel:()=>Ke(null)},me.id),Me==="idle"&&(0,c.jsx)("div",{style:{display:me?"none":void 0},children:(0,c.jsx)(er.ExpressCheckoutElement,{onReady:U=>{Be(wa(U,Tt))},onLoadError:U=>{Be("load_error"),ds(j,"stripe","wallet","provider_error")},onClick:async U=>{let m=j?.now()??globalThis.performance?.now()??Date.now();be.current=U.expressPaymentType,X.current=zl(U.expressPaymentType);let P=!0,H=window.setTimeout(()=>{P=!1,U.reject()},hd),V=w?await w(X.current):{proceed:!0};if(window.clearTimeout(H),!P)return;if(!V.proceed){Ye.current.delete(Ee),U.reject();return}let he=dt(U.expressPaymentType);lt.current={generation:he,startedAt:m},Ye.current.set(Ee,{generation:he,method:U.expressPaymentType,accountPatch:V.accountPatch,sessionId:V.sessionId,nonce:V.nonce}),ge(!1),j?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:he,...U.expressPaymentType==="apple_pay"||U.expressPaymentType==="google_pay"?{walletType:U.expressPaymentType}:{}}),p?.(X.current),U.resolve()},onConfirm:Rt,onCancel:()=>{let U=Ye.current.get(Ee);Ye.current.delete(Ee),j?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...U?{attempt:U.generation}:{}}),Et(U?.generation),Ge.current=null,ge(!1),Y.current=!0,N()},options:{...ii,paymentMethods:Ze,emailRequired:Je,billingAddressRequired:Je}},Ee)})]})}),se&&(0,c.jsx)(qr,{status:"processing"})]})}function Yl(e,t,r){let n=(0,u.resolveSetupFutureUsage)(r,t,"inline_apm");return{...e,paymentMethodTypes:[t],...n?{setupFutureUsage:n}:null}}function ls({method:e,sessionId:t,nonce:r,email:n,billingName:o,onBuyerIdentityReady:i,billingApiUrl:l,onTokenizedBody:d,onErrorChange:p,onDecline:b,onCancel:k,runBeforeButtonClick:w,onButtonClick:x,isProcessing:O,submitButtonColor:M,submitButtonBorderRadius:W,submitButtonStyle:_,errorText:h}){let v=Zn(),{emitInstrument:te}=(0,a.useContext)(on),S=(0,er.useStripe)(),Pe=(0,er.useElements)(),[j,Q]=(0,a.useState)(!1),Be=(0,a.useRef)(!1),[se,je]=(0,a.useState)(!1),[Je,me]=(0,a.useState)("loading"),[pe,Ke]=(0,a.useState)(""),Re=!(0,u.isValidEmail)(n?.trim()),_e=!Re||(0,u.isValidEmail)(pe.trim()),Ee=(0,a.useCallback)(async()=>{if(!S||!Pe||O||Be.current||!se)return;Be.current=!0,Q(!0);let re=w?await w("card"):{proceed:!0};if(!re.proceed){Be.current=!1,Q(!1);return}x?.("card");let ae=re.sessionId??t,ge=re.nonce??r,Me=(0,Uo.splitFullName)(o?.trim()),K=(0,an.compactBuyerIdentity)({email:re.accountPatch?.email?.trim()||n?.trim()||pe.trim(),firstName:re.accountPatch?.firstName?.trim()||Me.firstName,lastName:re.accountPatch?.lastName?.trim()||Me.lastName}),ee=K.email,ye=(0,an.compactBuyerIdentity)({...re.accountPatch,...K});try{if(p?.(null),!(0,u.isValidEmail)(ee))throw new Error("A valid email address is required for payment.");await i?.(K);let L=await Pe.submit();if(L.error){p?.(L.error.message??"Payment failed.");return}let ve=[K.firstName,K.lastName].filter(Boolean).join(" "),Y=await S.createPaymentMethod({elements:Pe,params:{billing_details:{email:ee,...ve?{name:ve}:{}}}});if(Y.error||!Y.paymentMethod){p?.(Y.error?.message??"Failed to create payment method.");return}let be=Y.paymentMethod;if(!ae||!ee)throw new Error("Missing sessionId or email for payment.");let X=be.type||e,ct=await mi(l,te,ae,ge??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(ct.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ge=ct.clientSecret;tr(Vn,{clientSecret:Ge,sessionId:ae,nonce:ge,accountPatch:ye,paymentMethodId:be.id,paymentMethodType:be.type??e,gateway:"stripe"});let{error:$e,paymentIntent:lt}=await S.confirmPayment({clientSecret:Ge,confirmParams:{return_url:window.location.href,payment_method:be.id},redirect:"if_required"});if($e){tr(Vn);let We=$e.message??"Payment failed.";p?.(We),b?.(gr("card",We,{code:$e.code})),await yi({billingApiUrl:l,sessionId:ae,nonce:ge,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:$e.code??"provider_declined"}});return}let Ye=lt?.status;if(!pa(Ye)){tr(Vn);let We=Ye==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(We),b?.(gr("card",We,{code:Ye??"missing_payment_intent"}));return}tr(Vn);let dt=typeof lt?.payment_method=="string"?lt.payment_method:lt?.payment_method?.id;d({id:dt??be.id,type:"card",threeDSecureActionResultTokenId:lt?.id,gateway:"stripe",paymentMethodType:be.type??e},{accountPatch:ye,paymentMethodCategory:"apm",sessionId:ae,nonce:ge})}catch(L){p?.(L instanceof Error?L.message:"Payment failed. Please try again.")}finally{Be.current=!1,Q(!1)}},[S,Pe,O,se,w,x,t,r,n,o,pe,i,l,te,e,d,p,b]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Re&&(0,c.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Re&&(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:pe,onChange:re=>Ke(re.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,c.jsx)(er.PaymentElement,{onReady:()=>me("ready"),onLoadError:()=>{me("load_error"),ds(hr(v),"stripe","apm")},onChange:re=>{je(!!re.complete)},options:{layout:si,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,u.isValidEmail)(n?.trim())?{email:n?.trim()}:{}}}}}),(0,c.jsx)(li,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Ee()},disabled:!se||!_e||j||O||Je!=="ready",color:M,borderRadius:W,style:_,children:j?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),h&&(0,c.jsx)($o,{margin:"0.75rem 0 0",children:h})]})}function $l({sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:l,stripeInstance:d,paymentElementBaseOptions:p,futureUseSession:b,onTokenizedBody:k,onErrorChange:w,onButtonClick:x,onDecline:O,runBeforeButtonClick:M,onLoadStateChange:W,isProcessing:_=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:v=8,submitButtonStyle:te,buttonAppearance:S,themeId:Pe,onExpandApm:j,expandedApmMethod:Q}){let{emitInstrument:Be}=(0,a.useContext)(on),[se,je]=(0,a.useState)(null),[Je,me]=(0,a.useState)(null),pe=(0,a.useRef)(!1),{request:Ke,collect:Re,finish:_e}=zo();(0,a.useEffect)(()=>{l.length>0&&d?W?.("ready"):d||W?.("loading")},[l.length,d,W]);let Ee=(0,a.useCallback)(async ee=>{if(!d||pe.current||_)return;pe.current=!0,me(ee);let ye=M?await M("card"):{proceed:!0};if(!ye.proceed){pe.current=!1,me(null);return}x?.("card");let L=ye.sessionId??e,ve=ye.nonce??t,Y=(0,Uo.splitFullName)([ye.accountPatch?.firstName,ye.accountPatch?.lastName].filter(Boolean).join(" ")||n),be=(0,an.compactBuyerIdentity)({email:ye.accountPatch?.email?.trim()||r?.trim(),firstName:ye.accountPatch?.firstName?.trim()||Y.firstName,lastName:ye.accountPatch?.lastName?.trim()||Y.lastName});if(!(0,u.isValidEmail)(be.email)){me(null);let Ge=await Re((0,u.getStripeMethodDisplayName)(ee),be);if(!Ge){pe.current=!1;return}be=Ge,me(ee)}let X=be.email,ct=(0,an.compactBuyerIdentity)({...ye.accountPatch,...be});try{if(w?.(null),!L||!(0,u.isValidEmail)(X))throw new Error("Missing sessionId or email for payment.");await o?.(be);let Ge=await mi(i,Be,L,ve??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,paymentMethodId:null,intentKind:"payment"});if(Ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let $e=Ge.clientSecret;tr(Vn,{clientSecret:$e,sessionId:L,nonce:ve,accountPatch:ct,paymentMethodType:ee,gateway:"stripe"});let{error:lt,paymentIntent:Ye}=await d.confirmPayment({clientSecret:$e,confirmParams:{return_url:window.location.href,payment_method_data:{type:ee,billing_details:{name:[be.firstName,be.lastName].filter(Boolean).join(" "),...X?{email:X}:{}}}},redirect:"if_required"});if(lt){tr(Vn);let Et=lt.message??"Payment failed.";w?.(Et),O?.(gr("card",Et,{code:lt.code})),await yi({billingApiUrl:i,sessionId:L,nonce:ve,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,providerDeclineReason:lt.code??"provider_declined"}});return}let dt=Ye?.status;if(!pa(dt)){tr(Vn);let Et=dt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";w?.(Et),O?.(gr("card",Et,{code:dt??"missing_payment_intent"}));return}tr(Vn);let We=typeof Ye?.payment_method=="string"?Ye.payment_method:Ye?.payment_method?.id;k({id:We??Ye?.id,type:"card",threeDSecureActionResultTokenId:Ye?.id,gateway:"stripe",paymentMethodType:ee},{accountPatch:ct,paymentMethodCategory:"apm",sessionId:L,nonce:ve})}catch(Ge){w?.(Ge instanceof Error?Ge.message:"Payment failed. Please try again.")}finally{pe.current=!1,me(null)}},[d,_,M,x,e,t,r,Re,i,Be,n,o,k,w,O]),[re,ae]=(0,a.useState)(null),ge=j?Q??null:re,Me=(0,a.useCallback)(ee=>{pe.current||_||ge&&ge!==ee||((0,u.needsStripeMethodExplicitConfirm)(ee)?j?j(ee):ae(ee):Ee(ee))},[ge,_,Ee,j]),K=(0,a.useMemo)(()=>re?Yl(p,re,b):null,[re,p,b]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ke?(0,c.jsx)(qo,{identity:Ke.identity,methodLabel:Ke.methodLabel,onComplete:_e,onCancel:()=>_e(null)},Ke.id):l.map(ee=>{let ye=Q===ee,L=Je===ee,ve=Je!==null&&Je!==ee||Q!=null&&Q!==ee;return(0,c.jsxs)(a.default.Fragment,{children:[(0,c.jsx)(oi,{method:ee,themeId:Pe,submitting:L,disabled:ve,highlighted:ye,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(ee),onClick:()=>Me(ee),backgroundColor:S?.backgroundColor,borderColor:S?.borderColor,textColor:S?.textColor,borderRadius:S?.borderRadius,fontFamily:S?.fontFamily}),!j&&re===ee&&K&&d&&(0,c.jsx)(er.Elements,{stripe:d,options:K,children:(0,c.jsx)(ls,{method:ee,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:k,onErrorChange:w,onDecline:O,onCancel:()=>ae(null),runBeforeButtonClick:M,onButtonClick:x,isProcessing:_,submitButtonColor:h,submitButtonBorderRadius:v,submitButtonStyle:te})},ee)]},ee)})})}function qd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:o,userId:i,onComplete:l,onError:d,onDecline:p,onTokenizedBody:b,firstName:k,lastName:w,chv:x,className:O,submitLabel:M,isProcessing:W,error:_,onErrorChange:h,showPayPal:v=!0,showStripe:te=!0,walletPresentation:S="auto",enabledPaymentMethods:Pe,enabledPaymentMethodCountries:j,showApplePay:Q=!0,showGooglePay:Be=!0,layout:se="default",theme:je,buttonsTheme:Je,buttonsStyles:me,appearance:pe,cardButtonContent:Ke,cardBackButtonContent:Re,cardTitleContent:_e,showSecurityFooter:Ee,onButtonClick:re,onBeforeButtonClick:ae,onBuyerIdentityReady:ge,enableAVS:Me,cardFieldOrder:K,cardPreFormSlot:ee,avsLayout:ye="row",country:L,zip:ve,addressLine1:Y,addressLine2:be,city:X,state:ct,onCountryChange:Ge,onZipChange:$e,avsCheck:lt,checkoutType:Ye,checkoutLayout:dt,totalAmount:We=0,currency:Et="usd",initialCardOpen:Ut=!1,directPaypal:kt,isSubscription:At=!1,session:N,dataAttachmentPending:fe=!1,dataAttachmentRequiresIdentity:Qe=!1,debug:G=!1}){let Ne=Zn(),Rt=Ga(),Ze=(0,a.useContext)(En),{emitInstrument:Tt}=(0,a.useContext)(on),U=(0,a.useRef)(null);U.current||(U.current=Xa());let m=U.current,[,P]=(0,a.useState)(0),H=(0,a.useRef)(null);H.current||(H.current=(0,zn.detectPayPalEnvironment)());let V=H.current,he=(0,a.useMemo)(()=>({browser:V,capability:m,presentationMode:"popup"}),[V,m]),T=N??Ze.session,A=(0,a.useMemo)(()=>({futureUse:T?.futureUse,futureUseUnsupported:T?.futureUseUnsupported}),[T?.futureUse,T?.futureUseUnsupported]),ne=T?.gateways?.paypal?.providerObjectType??kt?.providerObjectType,q=fe||Ze.claimPending===!0,Ce=Qe||Ze.claimRequiresIdentity===!0,rt=q&&!Ce,Ct=vl(),ht=r||Ct,[xe,Fr]=(0,a.useState)(!1),[Vr,br]=(0,a.useState)(null),[Ht,$r]=(0,a.useState)(L??""),[Wr,Rr]=(0,a.useState)(ve??""),[Lt,mt]=(0,a.useState)(Y??""),[it,Br]=(0,a.useState)(be??""),[Bt,Hr]=(0,a.useState)(X??""),[Cr,Kt]=(0,a.useState)(ct??""),[or,pn]=(0,a.useState)(""),[en,ar]=(0,a.useState)({}),zt=(0,a.useRef)(ve??""),Tr=(0,a.useRef)(L??""),mr=(0,a.useRef)(Y??""),jt=(0,a.useRef)(be??""),Sr=(0,a.useRef)(X??""),Vt=(0,a.useRef)(ct??""),ur=(0,a.useRef)(""),qt=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(R,ue,Ue,oe,Ie)=>{if(qt.current[R])return;let Ot=ue?.trim();!Ot||Ot===Ue.current||(Ue.current=Ot,oe(Ot),Ie?.(Ot))};s("country",L,Tr,$r,Ge),s("zip",ve,zt,Rr,$e),s("addressLine1",Y,mr,mt),s("addressLine2",be,jt,Br),s("city",X,Sr,Hr),s("state",ct,Vt,Kt)},[L,ve,Y,be,X,ct,Ge,$e]);let Ae=(0,a.useMemo)(()=>(0,u.resolveAVSConfig)(Me),[Me]),mn=Ae!==null,yn=(0,a.useMemo)(()=>(0,u.isAuthorizationOnlySession)(N),[N]),fn=(0,u.isMountableVaultBlock)(N?.vault),ir=!!N?.gateways?.pcivault,Dr=(0,Rn.hasServerSideCardGateway)(N),De=!!(N?.gateways?.stripe?.enabledPaymentMethods??Pe)?.includes("card")||(0,Rn.canRecoverHostedCardForm)(N),vt=fn||De||ir,f=!!(te&&vt&&e),[nt,ie]=(0,a.useState)(()=>se!=="buttons"||Ut?e??null:null),[Er,Kr]=(0,a.useState)(0),Zt=se!=="buttons"||Ut||!!e&&nt===e,Or=N?.captureMethod,St=(0,a.useRef)(Ne);(0,a.useEffect)(()=>{St.current=Ne},[Ne]);let[xn,no]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(!f||!e||!Zt){no(null);return}let s=St.current?St.current.cardCapture({sessionId:e,captureMethod:Or}):new Mn.PciVaultCardCapture({sessionId:e,captureMethod:Or,billingApiUrl:ht,telemetry:n});return no({sessionId:e,captureMethod:Or,billingApiUrl:ht,telemetry:n,capture:s}),()=>{s.unmount()}},[f,e,Zt,Or,ht,n]);let Dt=f&&e&&Zt&&xn?.sessionId===e&&xn.captureMethod===Or&&xn.billingApiUrl===ht&&xn.telemetry===n?xn.capture:null,Gr=(0,a.useMemo)(()=>{let s=Ht,R=Ae?(0,u.isAVSFieldVisible)(Ae.postal_code,s):!1;return Nd(s,Wr,R)},[Ae,Ht,Wr]),{avsInvalid:gn,invalidAvsFields:hn}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!f||!Ae)return{avsInvalid:!1,invalidAvsFields:s};let R=Ht,ue=(Ie,Ot)=>(0,u.isAVSFieldVisible)(Ie,R)&&!Ot.trim(),Ue={line1:ue(Ae.address_line_1,Lt),city:ue(Ae.city,Bt),state:ue(Ae.state,Cr),zip:Gr.empty||Gr.malformed};return{avsInvalid:Ue.line1||Ue.city||Ue.state||Ue.zip,invalidAvsFields:Ue}},[f,Ae,Ht,Lt,Bt,Cr,Gr]),[Gt,An]=(0,a.useState)(!1),[Fn,Lr]=(0,a.useState)(!1),[Bn,tn]=(0,a.useState)(!1),[Dn,Hn]=(0,a.useState)({line1:!1,city:!1,state:!1}),Yr=(0,a.useRef)(!1),Pn=(0,a.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),vn=(0,a.useRef)(!1),Nt=(0,a.useCallback)(s=>{Pn.current[s]=!0,vn.current=!0},[]),Xr=(0,a.useCallback)(s=>!Yr.current&&Pn.current[s],[]),xr=(0,a.useCallback)(s=>{Xr(s)&&Hn(R=>R[s]?R:{...R,[s]:!0})},[Xr]),[bn,Cn]=(0,a.useState)(()=>(0,u.resolveVaultMountOptions)(N?.vault,{billingApiUrl:ht,sessionId:e,nonce:t})),[bt,sr]=(0,a.useState)(Ut&&vt?"card":"buttons"),[yr,Nr]=(0,a.useState)(null),oo=bt==="expanding"||bt==="card",On=N?.gateways?.stripe&&!Dr?"stripe":void 0,Kn=(0,a.useCallback)(()=>{Tt?.({class:"card_surface",provider:On})},[On,Tt]),rn=(0,a.useRef)(null),lr=(0,a.useCallback)(s=>{rn.current&&clearTimeout(rn.current),rn.current=setTimeout(()=>{rn.current=null,s()},_a)},[]);(0,a.useEffect)(()=>()=>{rn.current&&clearTimeout(rn.current)},[]);let ao=(0,a.useRef)(!1),[pr,z]=(0,a.useState)(0),B=(0,a.useRef)(null),ce=(0,a.useCallback)(()=>{Kn(),ie(e??null),ao.current&&(ao.current=!1,z(s=>s+1)),Kr(s=>s+1),sr("expanding"),lr(()=>sr("card"))},[lr,Kn,e]),Se=(0,a.useCallback)(()=>{sr("collapsing"),lr(()=>sr("buttons"))},[lr]),It=(0,a.useCallback)(s=>{Nr(s),sr("apm-expanding"),lr(()=>sr("apm-form"))},[lr]),Yt=(0,a.useCallback)(()=>{sr("apm-collapsing"),lr(()=>{sr("buttons"),Nr(null)})},[lr]);(0,a.useEffect)(()=>{se==="buttons"&&Ut&&vt&&(ie(e??null),sr("card"))},[se,Ut,vt,e]);let[Oe,J]=(0,a.useState)(null),Z=(0,a.useRef)(!1),$=(0,a.useRef)(null),y=(0,a.useRef)("idle"),[g,E]=(0,a.useState)(!1),de=(0,a.useRef)(g);de.current=g;let[Fe,He]=(0,a.useState)(()=>kt?.existingOrderId?{orderId:kt.existingOrderId,attempts:1}:null),Xt=(0,a.useRef)(Fe);(0,a.useEffect)(()=>{Xt.current=Fe},[Fe]);let Te=(0,a.useRef)(null),Xe=(0,a.useMemo)(()=>{if(ge||Ze.claimBuyerIdentity||N?.buyerIdentified!==!1||!e||!t)return;let s=`${ht}|${e}|${t}`;Te.current?.key!==s&&(Te.current={key:s,claim:Lo(new Mn.PaymentAPI(ht,{telemetry:!1}),e,t,{...i?{userId:i}:{},...k?{firstName:k}:{},...w?{lastName:w}:{}})});let R=Te.current.claim;return async ue=>{await R(ue)}},[ge,Ze.claimBuyerIdentity,N?.buyerIdentified,e,t,ht,i,k,w]),ot=ge??Ze.claimBuyerIdentity??Xe,wt=_??Vr,we=(0,a.useMemo)(()=>(0,u.resolveTheme)(je),[je]),D=(0,a.useMemo)(()=>{let s=we?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)(Je);return me?{...s,...me,cardButton:{...s.cardButton,...me.cardButton},cardFormContainer:{...s.cardFormContainer,...me.cardFormContainer},backButton:{...s.backButton,...me.backButton},backButtonIcon:{...s.backButtonIcon,...me.backButtonIcon},submitButton:{...s.submitButton,...me.submitButton},title:{...s.title,...me.title}}:s},[we,Je,me]),le=pe??we?.appearance,yt=(0,a.useMemo)(()=>(0,Ir.computeVaultCardThemeColors)({appearance:le,buttonsStyles:D,layout:se}),[le,D,se]),Ve=Ze.inlineSessionPatchProcessing??!1,et=(W??xe)||Ve,Mt=ht.replace(/\/+$/,""),Pt=(0,a.useMemo)(()=>Ki({userId:i,email:o,firstName:k,lastName:w,country:L,zip:ve},en),[i,o,k,w,L,ve,en]),wo=[Pt.firstName,Pt.lastName].filter(s=>!!s?.trim()).join(" "),Cs=!(0,u.isValidEmail)(Pt.email?.trim()),ki=(0,a.useRef)(null);f&&ki.current===null&&(ki.current=Cs);let io=f&&(ki.current??Cs),Ri=(0,a.useMemo)(()=>Ud(or,io),[or,io]),ko=Ri.empty||Ri.malformed,Jr=(0,a.useMemo)(()=>Ne?Ne.getRawProvider():null,[Ne]),Ss=(0,a.useMemo)(()=>Rt?Rt.getRawProvider():null,[Rt]),Qo=We||100,Ro=Et.toLowerCase(),Ei=(0,a.useMemo)(()=>le?(0,Mn.toStripeAppearance)(le):null,[le]),Eo=Ei,ws=(0,a.useMemo)(()=>{let s=Ei??{},R=s.rules??{};return{...s,rules:{...R,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...R[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...R[".AccordionItemContents"]??{}}}}},[Ei]),ks=(0,a.useMemo)(()=>({...gl(We,T?.captureMethod,A),currency:Ro,...Eo?{appearance:Eo}:null}),[We,Ro,T?.captureMethod,A,Eo]),Ii=(0,u.resolveSetupFutureUsage)(A,"paypal","paypal"),Rs=(0,a.useMemo)(()=>({mode:"payment",amount:Qo,currency:Ro,captureMethod:"manual",...Ii?{setupFutureUsage:Ii}:null,...Eo?{appearance:Eo}:null}),[Qo,Ro,Ii,Eo]),Le=(0,a.useCallback)(s=>{br(s),h?.(s)},[h]),Es=(0,a.useRef)(0);(0,a.useEffect)(()=>{pr!==Es.current&&(Es.current=pr,Le(null))},[pr,Le]);let _i=(0,a.useRef)(""),[Is,vc]=(0,a.useState)(!1),Ti=(0,a.useCallback)(()=>{vc(!0)},[]);(0,a.useEffect)(()=>{if(!f||!io||!ot||!Is||ko||_i.current)return;let s=(0,an.compactBuyerIdentity)({email:(0,u.isValidEmail)(Pt.email?.trim())?Pt.email?.trim():ur.current.trim(),firstName:Pt.firstName?.trim(),lastName:Pt.lastName?.trim()});_i.current=JSON.stringify(s),ar(R=>({...R,...s})),Promise.resolve(ot(s)).catch(R=>{_i.current="",Le(R instanceof Error?R.message:"Failed to attach buyer details.")})},[f,io,ot,Is,ko,Pt.email,Pt.firstName,Pt.lastName,Le]),(0,a.useEffect)(()=>{!f||!Dt||Dt.setCardFieldOrder?.(K??null,Ae==null&&!io)},[f,Dt,K,Ae,io]),(0,a.useEffect)(()=>{(bt==="expanding"||bt==="collapsing"||bt==="apm-expanding"||bt==="apm-collapsing")&&Le(null)},[bt,Le]);let Ln=(0,a.useCallback)((s,R,ue)=>{p?.(gr(s,R,ue))},[p]),Io=(0,a.useCallback)((s,R,ue)=>{let Ue=ue?.popupBlocked??(0,ke.isPopupBlockedError)(R);Ue&&m.markBlocked()&&P(ft=>ft+1);let oe=(0,ke.buildExternalMethodRecoveryMessage)(ss(s),Ue,V.inAppBrowser),Ie=(0,ke.getProviderErrorCode)(R),Ot=(Ie?.toLowerCase()==="error"?void 0:Ie)??(0,ke.sanitizeExternalFailureCode)(ue?.code)??"external_payment_method_failed",kn=new u.FloPayError(oe,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:Ot,popupBlocked:Ue,inAppBrowser:V.inAppBrowser,appFamily:V.appFamily,popupCapability:m.current(),presentationMode:ue?.presentationMode??"popup"}});ue?.telemetryReported||hr(Ne)?.error(Go({...he,presentationMode:ue?.presentationMode??"popup"},{errorCode:Ue?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:ue?.provider??(s==="paypal"?"paypal":"stripe"),paymentMethodCategory:ue?.paymentMethodCategory??(s==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:ue?.terminalReason??(Ue?"popup_blocked":"provider_error")})),J(null),se==="buttons"&&(sr("buttons"),Nr(null)),Le(oe),d?.(kn),console.error("[FloPay] External payment method failed:",{method:s,code:Ot,popupBlocked:Ue})},[V,he,Ne,se,d,m,Le]);(0,a.useEffect)(()=>{if(!f||!e){Cn(null);return}let s={billingApiUrl:Mt,sessionId:e,nonce:t},R=(0,u.resolveVaultMountOptions)(N?.vault,s);if(R){Cn(R);return}if(!Zt){Cn(null);return}let ue=`${Mt}\0${e}\0${t??""}`,Ue=B.current;if(Ue&&Ue.key===ue){Cn(Ue.mount);return}Cn(null);let oe=!0;return new Mn.PaymentAPI(Mt).getVaultCapture(e,t).then(Ie=>{if(!oe)return;let Ot=(0,u.resolveVaultMountOptions)(Ie,s);Ot?.verificationRequired&&!Ie.html&&(B.current={key:ue,mount:Ot}),Ot?Cn(Ot):Le("Failed to load the secure card form.")}).catch(Ie=>{oe&&Le(Ie instanceof Error?Ie.message:"Failed to load the secure card form.")}),()=>{oe=!1}},[f,Zt,Er,e,N?.vault,Mt,t,Le]);let Sn=(0,a.useRef)({onComplete:l,onError:d,updateError:Le,emitDecline:Ln,resolvedAccount:Pt,avsConfig:Ae,avsCheckProp:lt,sessionId:e,nonce:t,baseUrl:Mt,captureMethod:N?.captureMethod,paymentId:N?.paymentId,authorizationExpiresAt:N?.authorizationExpiresAt,serverSideCardGateway:Dr});Sn.current={onComplete:l,onError:d,updateError:Le,emitDecline:Ln,resolvedAccount:Pt,avsConfig:Ae,avsCheckProp:lt,sessionId:e,nonce:t,baseUrl:Mt,captureMethod:N?.captureMethod,paymentId:N?.paymentId,authorizationExpiresAt:N?.authorizationExpiresAt,serverSideCardGateway:Dr};let Mi=(0,a.useRef)(!1),_s=(0,a.useCallback)(()=>{let s=Sn.current,R=s.resolvedAccount.email?.trim(),ue=(0,u.isValidEmail)(R)?R:ur.current.trim();if(!(0,u.isValidEmail)(ue))return null;let Ue=s.resolvedAccount.firstName?.trim(),oe=s.resolvedAccount.lastName?.trim(),Ie=Tr.current.trim()||s.resolvedAccount.country?.trim()||"",Ot=s.avsConfig?(0,u.isAVSFieldVisible)(s.avsConfig.state,Ie):!1,kn=s.avsConfig?(0,u.isAVSFieldVisible)(s.avsConfig.address_line_1,Ie):!1,ft=s.avsConfig?(0,u.isAVSFieldVisible)(s.avsConfig.postal_code,Ie):!1,_t=s.avsConfig?(0,u.isAVSFieldVisible)(s.avsConfig.city,Ie):!1,xt=s.avsConfig?(0,u.isAVSFieldVisible)(s.avsConfig.address_line_2,Ie):!1,$t=kn&&!Ot&&ft?(0,u.getStateFromPostalCode)(Ie,(zt.current??"").trim()):null,fo=Ot?Vt.current:$t;return{accountData:{userId:s.resolvedAccount.userId??"",email:ue,...Ue?{firstName:Ue}:{},...oe?{lastName:oe}:{},...ft&&zt.current?{zip:zt.current}:{},..._t&&Sr.current?{city:Sr.current}:{},...fo?{state:fo}:{},...kn&&mr.current?{addressLine1:mr.current}:{},...xt&&jt.current?{addressLine2:jt.current}:{},...Ie?{country:Ie}:{}},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,u.isAVSFieldVisible)(s.avsConfig.country,Ie),postal_code:ft,address_line_1:kn,address_line_2:xt,city:_t,state:Ot}}:{}}},[]),Ts=(0,a.useRef)(q);Ts.current=q,(0,a.useEffect)(()=>{q||wt!==Ll||Sn.current.updateError(null)},[q,wt]),(0,a.useEffect)(()=>{!f||!Dt||Dt.setSubmitGate?.(gn||q||ko||g)},[f,Dt,gn,q,ko,g]),(0,a.useEffect)(()=>{if(!f||!Dt)return;Mi.current=!1;let s=null,R=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,y.current="idle",J(null)},400)},ue=Dt.on("submitting",()=>{An(!0),$.current&&clearTimeout($.current),y.current="validation-window",$.current=setTimeout(()=>{$.current=null,y.current==="validation-window"&&(y.current="processing")},_d),J("processing");let ft=Sn.current;if(!ft.sessionId||!ft.nonce)return;let _t=_s();if(!_t){ft.updateError("Enter a valid email address."),y.current="idle",J(null);return}new Mn.PaymentAPI(ft.baseUrl).patchAccountSnapshot(ft.sessionId,ft.nonce,_t,{telemetryMode:"best_effort"}).catch(xt=>{if(!Md(xt))return;let $t=xt instanceof Error?xt.message:"Please check your billing address and try again.";ft.updateError($t),y.current="idle",J(null),ft.onError?.(xt instanceof u.FloPayError?xt:new u.FloPayError($t,"api_error"))})}),Ue=Dt.on("complete",ft=>{(0,_n.markSessionRecentlyCompleted)(ft.sessionId??Sn.current.sessionId),y.current="terminal",E(!1),J("success"),setTimeout(()=>{if(Mi.current)return;Mi.current=!0;let _t=Sn.current,xt=(0,u.isAuthorizationOnlySession)(_t)||ft.outcome==="authorized",$t=_t.serverSideCardGateway?{}:{paymentIntentId:ft.intentId};Sn.current.onComplete?.(xt?{status:"authorized",...$t,paymentId:ft.paymentId??_t.paymentId,sessionId:ft.sessionId??_t.sessionId,authorizationExpiresAt:ft.authorizationExpiresAt??_t.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...$t,checkoutMethod:"card"})},600)}),oe=Dt.on("decline",ft=>{let _t=Sn.current,xt=ft.message??"Your payment was declined. Please try another card or contact your bank.";y.current="terminal",E(!1),_t.updateError(xt),J("error");let $t=ft.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(ft.declineReason)??"authorization_declined";_t.emitDecline("card",xt,{code:$t,declineCode:$t}),R()}),Ie=Dt.on("error",ft=>{let _t=Sn.current,xt=ft.message??"There was a problem processing your payment. Please try again.";y.current="terminal",E(!1),_t.updateError(xt),J("error"),_t.onError?.(new u.FloPayError(xt,"api_error",{code:ft.failureOutcome??"capture_failed"})),R()}),Ot=Dt.on("challenge_dismissed",()=>{$.current&&(clearTimeout($.current),$.current=null),y.current="processing",E(!0),J(null)}),kn=Dt.on("blocked",()=>{if(de.current){Sn.current.updateError(Td);return}if(!Ts.current){An(!0);return}Ti(),Sn.current.updateError(Ll)});return()=>{s&&(clearTimeout(s),s=null),$.current&&(clearTimeout($.current),$.current=null),y.current="idle",E(!1),J(null),ue(),Ue(),oe(),Ie(),Ot(),kn()}},[f,Dt,Ti,_s]);let Nn=!!kt?.clientId,ea=Array.isArray(Pe),Fa=ea&&Pe.length>0,Ms=ea&&Pe.includes("paypal"),Ba=(0,a.useRef)(null);Ba.current===null&&(Ba.current=(0,u.hasMatchingStripePayPalReturn)());let _o=Ba.current?"redirect":(0,qn.resolveStripePayPalPresentation)(V,S,m.current()),{expressMethods:Da,paymentElementMethods:xi}=(0,a.useMemo)(()=>(0,u.partitionStripeMethods)(Pe,{excludePaypal:Nn}),[Pe,Nn]),xs=Nn||!!Rt||Ms&&_o==="redirect",bc=(0,a.useMemo)(()=>xs?Da.filter(s=>s!=="paypal"):Da,[Da,xs]),Cc=(0,a.useMemo)(()=>{let s=[];return Q&&s.push("apple_pay"),Be&&s.push("google_pay"),s},[Q,Be]),To=ea?bc:Cc,Sc=te&&To.length>0,As=mn?Ht:L,Oa=(0,a.useMemo)(()=>(0,u.filterStripeMethodsByCountryGate)(xi,As,j),[xi,As,j]),Ai=(0,a.useMemo)(()=>({mode:"payment",amount:Qo,currency:Ro,paymentMethodCreation:"manual",appearance:ws}),[Qo,Ro,ws]),[Fs,Bs]=(0,a.useState)("loading"),[Ds,Os]=(0,a.useState)("loading"),[Ls,Ns]=(0,a.useState)("loading"),[wc,Fi]=(0,a.useState)(!1),[Us,Bi]=(0,a.useState)("loading"),[Di,kc]=(0,a.useState)();(0,a.useEffect)(()=>{kc((0,zn.detectPayPalEnvironment)())},[]);let La=Di?.inAppBrowser,Na=Di?(0,qn.resolvePayPalPresentationMode)(Di,kt?.approvalPresentation,ne??(At?"subscription":"order")):"popup",zs=v&&(Nn||(ea?Ms:La===!1)),qs=te&&Sc,ta=(!rt||!!Ze.waitForDataAttachment)&&zs&&Nn,js=Us==="retrying"||Us==="exhausted",ra=null;te&&(Rt?ra=Ss:_o==="redirect"&&(ra=Jr));let Vs=(0,a.useMemo)(()=>({...he,presentationMode:_o}),[he,_o]),na=!rt&&zs&&!!ra&&(!Nn||js),Mo=!rt&&qs&&!!Jr,oa=!rt&&te&&Fa&&Oa.length>0&&!!Jr,Rc=ta&&!js?wc:na&&ts(Fs),Ec=Mo&&ts(Ds),Ic=oa&&Ls!=="load_error",$s=s=>s==="loading"||s==="ready",Ws=ta||na&&$s(Fs)||Mo&&$s(Ds)||oa&&Ls!=="load_error",Ua=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!Ua.current){if(!te&&!v){Ua.current=!0;let s=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(s),Le(s.message)}else if(!te&&v&&!Nn){Ua.current=!0;let s=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(s),Le(s.message)}else if(La!==void 0&&!rt&&!vt&&!Ws){Ua.current=!0;let s=new u.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"});d?.(s),Le(s.message)}}},[te,v,Nn,La,rt,vt,Ws,d,Le]);let Hs=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(Hs.current||!Fa)return;let s=[];Q!==!0&&s.push("showApplePay"),Be!==!0&&s.push("showGooglePay"),s.length!==0&&(Hs.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.`))},[Fa,Q,Be]);let Ks=(0,a.useCallback)((s,R)=>Ze.applyInlineSessionPatch?Ze.applyInlineSessionPatch(s).then(ue=>({error:null,sessionId:ue.sessionId||e,nonce:ue.session?.clientSecret||t})).catch(ue=>{let Ue=(0,u.normalizeBeforeButtonClickError)(R,ue);return Le(Ue.message),d?.(Ue),{error:Ue,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ze.applyInlineSessionPatch,t,d,e,Le]),wn=(0,a.useCallback)(async s=>{if(s!=="card"&&rt&&await Ze.waitForDataAttachment?.(),!ae)return{proceed:!0};try{let R=await ae({method:s,sessionId:e||void 0,createSession:Ze.inlineSessionDraft});if(R===!1)return{proceed:!1};if(R&&typeof R=="object"){R.account&&ar(Ue=>({...Ue??{},...R.account}));let ue=await Ks(R,s);return ue.error?{proceed:!1,accountPatch:R.account}:{proceed:!0,accountPatch:R.account,sessionId:ue.sessionId,nonce:ue.nonce}}return{proceed:!0}}catch(R){let ue=(0,u.normalizeBeforeButtonClickError)(s,R);return Le(ue.message),d?.(ue),{proceed:!1}}},[Ks,Ze.inlineSessionDraft,Ze.waitForDataAttachment,rt,ae,d,e,Le]),Gs=(0,a.useCallback)(async(s,R)=>{if(Z.current)return;Z.current=!0,Fr(!0),J("processing"),Le(null);let ue=R?.sessionId??e,Ue=R?.nonce??t,oe=Ki(Pt,R?.accountPatch),Ie=R?.completionPaymentMethodId??ma(s),Ot=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,kn=Bd(s),ft=R?.presentationMode?ni(hr(Ne),{...he,presentationMode:R.presentationMode}):void 0,_t=()=>{Tt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:kn}),ft?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Tn,requestCategory:"process_payment"})};try{let xt=new Mn.PaymentAPI(Mt),$t=await xt.processPayment(oe.userId??"",{sessionId:ue,nonce:Ue,paymentMethodCategory:R?.paymentMethodCategory??Od(s),tokenizedData:Ot,accountData:{...R?.accountPatch,userId:oe.userId??"",email:oe.email??"",firstName:oe.firstName||void 0,lastName:oe.lastName||void 0,...(0,u.buildProcessPaymentAvsAccount)({avsConfig:Ae,country:Tr.current,zip:zt.current,city:Sr.current,state:Vt.current,addressLine1:mr.current,addressLine2:jt.current})},...(0,u.buildCheckoutProcessMetadata)({chv:x,avsCheck:lt,checkoutType:Ye,checkoutLayout:dt,avsConfig:Ae,country:Tr.current})}),fo=async fr=>{let go=(0,u.isAuthorizationOnlySession)(N)||fr?.status==="authorized";(0,_n.markSessionRecentlyCompleted)(ue),ft?.terminal({outcome:"payment_succeeded",...Tn}),J("success"),He(null),await new Promise(da=>setTimeout(da,600));let Un;typeof fr?.paymentId=="string"?Un=fr.paymentId:N?.paymentId&&(Un=N.paymentId);let ho;typeof fr?.authorizationExpiresAt=="string"?ho=fr.authorizationExpiresAt:N?.authorizationExpiresAt&&(ho=N.authorizationExpiresAt),l?.(go?{status:"authorized",...Un===void 0?{}:{paymentId:Un},sessionId:typeof fr?.sessionId=="string"?fr.sessionId:ue,...ho===void 0?{}:{authorizationExpiresAt:ho},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Ie,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Ie,checkoutMethod:s.isPaypal?"paypal":"card"})};if($t.ok){await fo($t.status===204?null:await $t.json().catch(()=>null));return}let Zr=await $t.json().catch(()=>null);if(Zr?.type==="paypal_redirect_required"){let fr=Zr.threeDSecureToken,go=Zr.paymentMethodId||s.id||"";if(!Ne||!fr){J("error"),Le("PayPal authorization required but no token provided.");return}try{let Un=Rt?.getRawProvider();if(!Un){Le("PayPal is not available.");return}let ho={return_url:window.location.href};go&&(ho.payment_method=go);let{error:da}=await Un.confirmPayment({clientSecret:fr,confirmParams:ho,redirect:"if_required"});if(da){J("error");let il=da.message??"PayPal payment failed.";Le(il),Ln("paypal",il,{code:da.code})}}catch(Un){J("error"),Le(Un instanceof Error?Un.message:"PayPal authorization failed.")}return}if(Zr?.type==="paypal_direct_required"){let fr=Zr.orderId;if(!fr){J("error"),Le("PayPal retry required but no order id provided.");return}let go=Xt.current?.attempts??0;if(go>=2){J("error"),Le("PayPal payment could not be completed after multiple attempts."),Ln("paypal","paypal_direct_required retry limit exceeded");return}Fi(!1),Bi("loading"),He({orderId:fr,attempts:go+1}),J(null);return}if($t.headers.get(Cd)===Sd){let fr=await wd(xt,ue,Ue);if(fr!==void 0){await fo(fr);return}}(0,u.classifyPaymentRejection)($t.status,Zr)?ft?.terminal({outcome:"payment_declined",...Tn,terminalReason:"provider_declined"}):_t(),J("error");let al=Zr?.message??"Payment failed. Please try again.";Le(al),Ln(s.isPaypal?"paypal":"card",al,{code:Zr?.code??Zr?.gatewayErrorCode,declineCode:Zr?.declineCode??Zr?.gatewayDeclineReason}),await new Promise(fr=>setTimeout(fr,400))}catch(xt){Kl(xt)||_t(),J("error"),Le(xt instanceof Error?xt.message:"An unexpected error occurred"),await new Promise($t=>setTimeout($t,400))}finally{Fr(!1),J(null),Z.current=!1}},[Mt,e,t,Pt,Ae,lt,Ye,dt,x,Ne,Rt,N,l,Le,Ln,Tt,he]),Ur=(0,a.useCallback)((s,R)=>{b?b(s):Gs(s,R)},[b,Gs]),aa=`${Wl}:${e}`;(0,a.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(aa);if(!s)return;let R;try{R=JSON.parse(s)}catch{tr(aa);return}if(!R||typeof R.createdAt!="number"||Date.now()-R.createdAt<0||Date.now()-R.createdAt>Hl||typeof R.paymentMethodId!="string"||typeof R.providerIntentId!="string"||typeof R.paymentMethodType!="string"||R.sessionId!==e||!t||R.nonce!==t||!To.includes(R.paymentMethodType)){tr(aa);return}tr(aa),Ur({id:R.paymentMethodId,type:"card",threeDSecureActionResultTokenId:R.providerIntentId,gateway:"stripe",paymentMethodType:R.paymentMethodType},{...R.accountPatch?{accountPatch:R.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Ur,t,e,aa,To]);let Ys=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||Ys.current)return;let[s,R,ue]=(0,u.readStripeRedirectParams)();if(!s||!R||Ba.current||!Ne)return;let Ue=Ne.getRawProvider();if(!Ue)return;let oe=_t=>{let xt=localStorage.getItem(_t);if(!xt)return null;try{return JSON.parse(xt)}catch{return tr(_t),null}},Ie=oe(Vn)??oe(Bl),Ot;if(Ie?.clientSecret){if(Ie.clientSecret!==R)return;Ot={...Ie.accountPatch?{accountPatch:Ie.accountPatch}:{},...Ie.sessionId?{sessionId:Ie.sessionId}:{},...Ie.nonce?{nonce:Ie.nonce}:{}}}else if(Ie?.sessionId&&Ie.sessionId!==e)return;Ys.current=!0,tr(Vn),tr(Bl),window.history.replaceState({},"",(0,u.stripeRedirectReturnUrl)());let kn=Ie?.paymentMethodType??Ie?.tokenType??"card",ft="card";(async()=>{if(ue==="failed"){let Gn="Payment was declined. Please try again.";Le(Gn),Ln(ft,Gn);return}let{paymentIntent:_t,error:xt}=await Ue.retrievePaymentIntent(R);if(xt){let Gn=xt.message??"Failed to retrieve payment status.";Le(Gn),Ln(ft,Gn,{code:xt.code});return}let $t=_t?.status,fo=pa($t);if(!_t||!fo){let Gn=$t==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Le(Gn),Ln(ft,Gn,{code:$t??"missing_payment_intent"});return}let Zr=typeof _t.payment_method=="string"?_t.payment_method:_t.payment_method?.id;Ur({id:Zr??Ie?.paymentMethodId??Ie?.tokenId??_t.id,type:"card",threeDSecureActionResultTokenId:_t.id,gateway:Ie?.gateway??"stripe",paymentMethodType:kn},Ot)})()},[e,Ur,Ne,Le,Ln]);let Oi=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!(f||Ne!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ia=se==="buttons",zr=le?.variables,_c=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Li=zr?.colorBackground,Tc=Li&&!_c.has(Li)?Li:void 0,sa=D.cardInputBorder??(ia?"#e5e7eb":"#A4A4FF"),Xs=zr?.colorDanger??"#dc2626",Jt=s=>hn[s]&&(Dn[s]||Gt),za=ko&&(Bn||Gt),nn=s=>s?Xs:sa,qa=(Gr.malformed||Gr.empty)&&(Fn||Gt),Mc=nn(qa),Ni=D.cardFormContainer?.backgroundColor??Tc??(ia?"white":"#EDEDFF"),xo=D.cardInputBackground??zr?.colorBackground??"white",Ui=Bo(Re),Js=Bo(_e),Ao=D.nameInput,Zs=D.cardInputFontSize??zd(Ao?.fontSize)??zr?.fontSizeBase??"16px",Qs=typeof Ao?.fontFamily=="string"?Ao.fontFamily:zr?.fontFamily??"Poppins, sans-serif",el=(0,Ir.toCssWeight)(Ao?.fontWeight)??400,xc=D.cardInputColor??(typeof Ao?.color=="string"?Ao.color:void 0)??zr?.colorText??"#262833",Ac=D.cardInputPlaceholderColor??"#9ca3af",Qt=zr?.borderRadius??"8px",mo=zr?.borderRadius??D.cardButton?.borderRadius??Qt,yo=zr?.colorPrimary??"#4A49FF",Fc=zr?.colorPrimaryHover??(0,Ir.darkenHex)(yo,.12),zi=zr?.colorText??"#262833",qi={fontSize:Zs,fontFamily:Qs,fontWeight:el,color:xc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},la={marginTop:"0.375rem",...qi,fontSize:"0.75rem",lineHeight:1.4,color:Xs},Bc={"--flopay-input-placeholder-color":Ac,"--flopay-input-font-size":Zs,"--flopay-input-font-family":Qs,"--flopay-input-font-weight":String(el)},ca=D.cardFormContainer??{},ji=ca.padding??(ia?"0":"1rem"),Vi=ca.borderRadius??Qt,Dc=Dt&&bn?(0,c.jsx)(co,{capture:Dt,html:bn.html,messageToken:bn.messageToken,expectedOrigin:bn.expectedOrigin,verificationRequired:bn.verificationRequired,theme:yt,submitLabel:M,onReady:()=>{if(!io&&!Ae||typeof document>"u")return;let s=()=>{let ue=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(ue){Yr.current=!0;try{ue.focus()}finally{Yr.current=!1}}};vn.current||s()},onError:s=>{s&&bn.verificationRequired&&y.current==="idle"&&(ao.current=!0),Le(s)},onValidation:s=>{let R=y.current;(R==="idle"||R==="validation-window")&&(Le(s),s&&y.current==="validation-window"&&($.current&&(clearTimeout($.current),$.current=null),y.current="idle",J(null)))}},pr):(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"}),tl=(0,c.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&Kn()},style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji,...Bc,display:"flex",flexDirection:"column"},children:[(0,c.jsx)("style",{children:`
30
+ `,Go=44;function Yo(){return(0,Pr.jsx)("style",{children:yd})}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,Pr.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,Pr.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,Pr.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:m,textColor:C,borderRadius:w,fontFamily:S}){let x=(0,Qn.resolveStripeMethodBrandVariant)(e,t),H=Al[e],[M,V]=(0,Fl.useState)(!1),_=!!H&&!M,h=x?.backgroundColor??u??"#ffffff",v=x?.borderColor??m??"#d1d5db",Z=x?.textColor??C??"#262833";return(0,Pr.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:Z,border:`1px solid ${v}`,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,Pr.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,Qn.getStripeMethodDisplayName)(e)}\u2026`}):(0,Pr.jsxs)(Pr.Fragment,{children:[(0,Pr.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,Qn.hasVendoredStripeMethodLogo)(e)?8:0},children:[_?(0,Pr.jsx)("img",{src:H,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,!_&&x?.logoSvg?(0,Pr.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,Pr.jsx)("span",{children:(0,Qn.getStripeMethodDisplayName)(e)})]}),i&&(0,Pr.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:Z,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,Pr.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,Pr.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"),fd=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 gd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return fd.has(t.charAt(0).toLowerCase()+t.slice(1))}function hd(e,t){return typeof t=="number"&&t!==0&&!gd(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]=hd(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:m,onError:C,onValidation:w}){let S=(0,Zr.useRef)(null),x=(0,Zr.useRef)(m),H=(0,Zr.useRef)(C),M=(0,Zr.useRef)(w);x.current=m,H.current=C,M.current=w;let V=(0,Zr.useRef)(i);V.current=i;let _=(0,Zr.useRef)(null),h=l??void 0,v=(0,Zr.useRef)(h);v.current=h;let Z=(0,Zr.useRef)(void 0);return(0,Zr.useEffect)(()=>{let k=S.current;if(!k)return;let fe=!0,O=!1,ne=()=>{!fe||O||(O=!0,x.current?.())},Be=e.on("ready",()=>{ne()}),pe=e.on("error",de=>{H.current?.(de.message??"There was a problem loading the secure card form.")}),De=e.on("validation",de=>{M.current?.(de.message??null)}),Je=v.current??(ts.has(e)?null:void 0),me={html:t,...r?{messageToken:r}:{},...n?{expectedOrigin:n}:{},...o?{verificationRequired:!0}:{},...V.current?{theme:V.current}:{},...Je===void 0?{}:{submitLabel:Je}};return _.current=V.current??null,Z.current=v.current,v.current!==void 0&&ts.add(e),e.mount(k,me).then(()=>{ne()}).catch(de=>{fe&&H.current?.(de instanceof Error?de.message:"Failed to load the secure card form.")}),()=>{fe=!1,Be(),pe(),De(),e.unmount()}},[e,t,r,n,o]),Po(()=>{let k=S.current;k&&Bl(k,u)},[u]),(0,Zr.useEffect)(()=>{i!==void 0&&(i===null&&_.current===null||(_.current=i,e.applyTheme?.(i)))},[e,i]),(0,Zr.useEffect)(()=>{h!==Z.current&&(Z.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",Pd="fw2",Kl=300*1e3,vd=900,Cd=25e3,bd=25e3,Sd=1e4,_n={provider:"paypal",paymentMethodCategory:"paypal"},wd="x-flopay-process-result-source",kd="status";async function Rd(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 Ed(e){return e==null?"confirmation_result_missing":"confirmation_result_not_object"}function tr(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`${Pd}:${e}`}function di(e){return tr(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 Id(e){return tr(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 _d(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=_d(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)},Sd),r?.add(n)})])}finally{n!==null&&(window.clearTimeout(n),r?.delete(n))}}function Td(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,Md=250,Nl="Just a moment \u2014 we are finalizing your order. Please press pay again.",xd="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 Tn.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,r,n)}catch{}}function Ad(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 Fd({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`,Bd=`flopay-buttons-enter ${Ia}ms cubic-bezier(0, 0, 0.2, 1) both`,Dd=`flopay-buttons-exit ${Ia}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Od(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ds(e){return(0,d.derivePrimaryTileStyle)(e)}var Ld={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Nd(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 Ud(e){let t=(0,d.getPostalCodeExample)(e);return`Enter a valid ${(0,d.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function zd(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 qd(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 jd(e){return typeof e=="number"?`${e}px`:e}function yi(e){return(0,c.jsx)(Vd,{...e})}function jl({sessionId:e,nonce:t,email:r,billingApiUrl:n,onTokenizedBody:o,onErrorChange:i,isProcessing:l=!1,onButtonClick:u,onDecline:m,onTechnicalFailure:C,runBeforeButtonClick:w,billingName:S,onBuyerIdentityReady:x,onLoadStateChange:H,placeholderBorderRadius:M,popupCapabilityOwner:V,externalTelemetryContext:_,presentationMode:h}){let v=Jn(),{emitInstrument:Z}=(0,a.useContext)(nn),k=(0,er.useStripe)(),fe=(0,er.useElements)(),O=(0,a.useMemo)(()=>ri(hr(v),_),[_,v]),[ne,Be]=(0,a.useState)("loading");(0,a.useEffect)(()=>{H?.(ne)},[ne,H]);let[pe,De]=(0,a.useState)(!1),Je=(0,a.useRef)(!1),me=!(0,d.isValidEmail)(r?.trim())||!S?.trim(),{request:de,collect:Qe,finish:ke}=Uo(),Re=(0,a.useRef)(!1),Ee=(0,a.useRef)(null),ee=(0,a.useRef)(null),[ue,Pe]=(0,a.useState)(0),[Ie,ve]=(0,a.useState)(!1),Q=(0,a.useRef)(!1),K=(0,a.useRef)(new Map),{startAttempt:N,finishAttempt:_e,invalidateAttempt:ae,isAttemptInvalidated:ge,isAttemptCurrent:B,generationRef:$e}=fa((U,ye,et)=>{C?.(U,ye,{...et,popupBlocked:et?.popupBlocked??(0,we.isPopupBlockedError)(ye),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h,terminalReason:"overlay_timeout"}),ve(!0),Pe(Y=>Y+1)},{onHandoffObserved:()=>{V.markAvailable(),O?.log({name:"provider.popup.opened",stage:"overlay_open",..._n,attempt:$e.current})}});(0,a.useEffect)(()=>{Ie&&ee.current?.focus()},[Ie,ue]);let Ge=(0,a.useCallback)(()=>{Pe(U=>U+1)},[]),We=(0,a.useCallback)((U,ye,et)=>{ae(et),C?.("paypal",U,{code:ye,popupBlocked:(0,we.isPopupBlockedError)(U),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:h}),ve(!0),Ge()},[ae,C,h,Ge]),ct=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Q.current&&(Q.current=!1,ct())},[ct,ue]);let Ye=(0,a.useCallback)(()=>{ve(!1),i?.(null),ct()},[ct,i]);(0,a.useEffect)(()=>{if(!k||Re.current)return;let[U,ye,et]=(0,d.readStripeRedirectParams)();if(!U||!ye)return;let Y=(0,d.readMatchingStripePayPalContinuation)(ye);if(!Y)return;Re.current=!0;let Ue=!0,Rt=Ra.get(ye);Rt||(Rt=et==="failed"?Promise.resolve(null):Promise.resolve().then(()=>k.retrievePaymentIntent(ye)),Ra.set(ye,Rt));let Ze={accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce},Tt=()=>{O?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",..._n,requestCategory:"provider_sdk"})};return O?.log({name:"provider.redirect.resumed",stage:"redirect_resume",..._n}),(async()=>{try{De(!0);let p=await Rt;if(!Ue)return;if(p?.error){Ra.delete(ye),Tt(),i?.(p.error.message??"Failed to retrieve PayPal payment status.");return}if((0,d.clearStripePayPalReturn)(),Ra.delete(ye),et==="failed"){let G="PayPal payment was declined. Please try again.";O?.terminal({outcome:"payment_declined",..._n,terminalReason:"provider_declined"}),i?.(G),m?.(gr("paypal",G));return}let P=p?.paymentIntent;if(P&&P.id!==U){Tt(),i?.("Failed to match the returned PayPal payment.");return}if(P&&(P.status==="requires_capture"||P.status==="succeeded")){let G=typeof P.payment_method=="string"?P.payment_method:P.payment_method?.id;o({id:G??P.id,type:"card",threeDSecureActionResultTokenId:P.id,isPaypal:!0},{...Ze,presentationMode:"redirect"})}else{let G="PayPal payment was not completed. Please try again.";O?.terminal({outcome:P?.status==="canceled"?"payment_cancelled":"payment_declined",..._n,terminalReason:P?.status==="canceled"?"cancelled":"provider_declined"}),i?.(G),m?.(gr("paypal",G))}}catch(p){if(!Ue)return;Ra.delete(ye),Tt(),i?.(p instanceof Error?p.message:"Failed to complete PayPal payment.")}finally{Ue&&De(!1)}})(),()=>{Ue=!1,Re.current=!1}},[k,o,i,m,O]);let dt=(0,a.useCallback)(async(U=!1)=>{let ye=w?await w("paypal"):{proceed:!0};if(!ye.proceed)return K.current.delete(ue),!1;let et=N("paypal");return K.current.set(ue,{generation:et,accountPatch:ye.accountPatch,sessionId:ye.sessionId,nonce:ye.nonce}),ve(!1),O?.log({name:`provider.${U?"redirect.started":"handoff.requested"}`,stage:U?"redirect":"overlay_open",..._n,attempt:et}),u?.("paypal"),!0},[u,O,w,N,ue]),He=(0,a.useCallback)(async U=>{if(l||pe||!await dt()){U.reject();return}U.resolve()},[l,dt,pe]),Et=(0,a.useCallback)(async U=>{if(!k||!fe)return;let ye=K.current.get(ue);if(ye&&!B(ye.generation)){K.current.delete(ue);return}if(!ye&&ge()||ye&&!_e(ye.generation))return;ye||_e();let et=ye??null;if(K.current.delete(ue),!et&&w){let z=await w("paypal");if(!z.proceed){U.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}et={accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}}let Y=et?.sessionId??e,Ue=et?.nonce??t,Rt=await Fd({event:U,prepared:et,email:r,billingName:S,methodLabel:"PayPal",collect:Qe});if(!Rt){U.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ze=Rt.email,Tt={...et?.accountPatch,...(0,on.compactBuyerIdentity)(Rt,!0)};try{if(De(!0),i?.(null),!Y||!(0,d.isValidEmail)(Ze))throw new Error("Missing sessionId or email for PayPal payment");await x?.(Rt);let z=k.createPaymentMethod,{error:p,paymentMethod:P}=await z({type:"paypal"});if(p){We(p,"stripe_paypal_create_payment_method_failed",ye?.generation),U.paymentFailed({reason:"fail"});return}let G=await pi(n,Z,Y,Ue??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:P?.id??null,intentKind:"payment"});if(G.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let $=G.clientSecret,he={return_url:(0,d.stripeRedirectReturnUrl)()};if(P?.id&&(he.payment_method=P.id),!tr(os,{clientSecret:$,sessionId:Y,nonce:Ue,accountPatch:Tt})&&h==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:A,paymentIntent:te}=await k.confirmPayment({clientSecret:$,confirmParams:he,redirect:"if_required"});if(A){if(tr(os),(0,we.isProviderDecline)(A)){let Ce=A.message??"Your payment was declined.";O?.terminal({outcome:"payment_declined",..._n,terminalReason:"provider_declined"}),i?.(Ce),m?.(gr("paypal",Ce,{code:(0,we.getProviderErrorCode)(A),declineCode:(0,we.getProviderDeclineCode)(A)})),await mi({billingApiUrl:n,sessionId:Y,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:(0,we.getProviderErrorCode)(A)??"provider_declined"}})}else We(A,"stripe_paypal_confirm_failed",ye?.generation);return}tr(os);let j=typeof te?.payment_method=="string"?te.payment_method:te?.payment_method?.id;o({id:j??te?.id,type:"card",threeDSecureActionResultTokenId:te?.id,isPaypal:!0},{accountPatch:Tt,paymentMethodCategory:"paypal",presentationMode:h,sessionId:Y,nonce:Ue});return}catch(z){We(z,"stripe_paypal_failed",ye?.generation)}finally{De(!1)}},[k,fe,e,t,r,S,Qe,x,n,Z,o,i,m,w,We,_e,B,ge,O,h,ue]),Ut=(0,a.useCallback)(async()=>{if(!(Je.current||l||pe||!k||!fe)){Je.current=!0,De(!0);try{if(!await dt(!0))return;await Et({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Je.current=!1,De(!1)}}},[fe,Et,l,dt,k,pe]),kt=h==="redirect"?(0,c.jsx)("button",{type:"button",disabled:l||pe,onClick:()=>{Ut()},style:{width:"100%",minHeight:Go,border:"1px solid #d1d5db",borderRadius:M??8,background:"#ffc439",color:"#111827",cursor:l||pe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,c.jsx)(er.ExpressCheckoutElement,{onReady:U=>Be(Sa(U,["paypal"])),onLoadError:()=>{Be("load_error"),cs(O,"paypal","paypal","provider_error")},onClick:He,onConfirm:Et,onCancel:()=>{let U=K.current.get(ue);K.current.delete(ue),O?.terminal({outcome:"payment_cancelled",..._n,terminalReason:"cancelled",...U?{attempt:U.generation}:{}}),ae(U?.generation),ve(!1),Q.current=!0,Ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:me,emailRequired:me,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ue),At=(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("div",{ref:Ee,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:ee,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ye,style:as,children:"Try PayPal again"}),de&&(0,c.jsx)(zo,{identity:de.identity,methodLabel:de.methodLabel,onComplete:ke,onCancel:()=>ke(null)},de.id),(0,c.jsx)("div",{style:{display:de?"none":void 0},children:kt})]}),pe&&!de&&(0,c.jsx)(zr,{status:"processing"})]});return h==="redirect"?At:(0,c.jsx)(wa,{state:ne,placeholderTestId:"flopay-paypal-placeholder",borderRadius:M,children:At})}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:m,onDecline:C,onTechnicalFailure:w,runBeforeButtonClick:S,billingName:x,onBuyerIdentityReady:H,onLoadStateChange:M,placeholderBorderRadius:V,popupCapabilityOwner:_,externalTelemetryContext:h}){let v=Jn(),{emitInstrument:Z}=(0,a.useContext)(nn),k=(0,er.useStripe)(),fe=(0,er.useElements)(),O=(0,a.useMemo)(()=>ri(hr(v),h),[h,v]),[ne,Be]=(0,a.useState)("loading");(0,a.useEffect)(()=>{M?.(ne)},[ne,M]);let[pe,De]=(0,a.useState)(!1),Je=(0,a.useRef)(!(0,d.isValidEmail)(r?.trim())||!x?.trim()).current,{request:me,collect:de,finish:Qe}=Uo(),ke=(0,a.useRef)(null),Re=(0,a.useRef)(null),[Ee,ee]=(0,a.useState)(0),[ue,Pe]=(0,a.useState)(!1),[Ie,ve]=(0,a.useState)(()=>ui(e,t)?"blocked":"idle"),[Q,K]=(0,a.useState)("google_pay"),N=(0,a.useRef)(null),_e=(0,a.useRef)(!0),ae=(0,a.useRef)(!1),ge=(0,a.useRef)("google_pay"),B=(0,a.useRef)("google_pay"),$e=(0,a.useRef)(null),Ge=(0,a.useRef)(null),We=(0,a.useRef)(new Set),ct=(0,a.useRef)(null);(0,a.useEffect)(()=>(_e.current=!0,()=>{_e.current=!1;for(let z of We.current)window.clearTimeout(z);We.current.clear()}),[]);let Ye=(0,a.useRef)(new Map),{startAttempt:dt,finishAttempt:He,invalidateAttempt:Et,isAttemptInvalidated:Ut,isAttemptCurrent:kt,generationRef:At}=fa((z,p,P)=>{w?.(z,p,{...P,popupBlocked:P?.popupBlocked??(0,we.isPopupBlockedError)(p),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),K(z),Pe(!0),ee(G=>G+1)},{onHandoffObserved:z=>{_.markAvailable(),O?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:At.current,...z==="apple_pay"||z==="google_pay"?{walletType:z}:{}})},defersMissingTerminal:Vl,onMissingTerminalDeferred:(z,p)=>{let P=O?.now()??globalThis.performance?.now()??Date.now(),G=ct.current,$=G?.generation===p?G.startedAt:P;O?.performance({stage:"overlay_return",durationMs:Math.max(0,P-$),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:p,...Vl(z)?{walletType:z}:{}}),O?.flush?.().catch(()=>{})}});(0,a.useEffect)(()=>{ue&&Re.current?.focus()},[ue,Ee]);let U=(0,a.useCallback)(()=>{ee(z=>z+1)},[]),ye=(0,a.useCallback)((z,p,P,G,$=!1)=>{Et(G),w?.(z,p,{code:P,popupBlocked:(0,we.isPopupBlockedError)(p),telemetryReported:$,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),K(z),Pe(!0),U()},[Et,w,U]),et=(0,a.useCallback)(()=>{window.setTimeout(()=>{(ke.current?.querySelector("iframe")??ke.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{ae.current&&(ae.current=!1,et())},[et,Ee]);let Y=(0,a.useCallback)(()=>{Pe(!1),u?.(null),et()},[et,u]),Ue=(0,a.useCallback)(()=>{N.current?.()},[]);(0,a.useEffect)(()=>{let z=ui(e,t);if(!z)return;let p=!1,P=!1,G=async()=>{if(!P){P=!0,p||ve("checking");try{let $=await Ll(k,z.clientSecret,We.current);if(p)return;let he=ns($,z.providerObjectId,(0,d.isSetupIntentClientSecret)(z.clientSecret));if(he.kind==="confirmed"){if(!Ol(e,t,z.clientSecret))return;N.current=null,ve("idle"),l({id:he.paymentMethodId,type:"card",threeDSecureActionResultTokenId:he.intentId},{...z.accountPatch?{accountPatch:z.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(he.kind==="terminal"){rs(e,t,z.clientSecret),N.current=null,ve("idle"),K(z.paymentMethodType),Pe(!0),U();return}ve("blocked")}catch{p||ve("blocked")}finally{P=!1}}};return N.current=G,ve("blocked"),()=>{p=!0,N.current===G&&(N.current=null)}},[t,l,U,e,k]);let Rt=(0,a.useCallback)(async z=>{let p=!1,P=mt=>{p||(p=!0,z.paymentFailed({reason:"fail",...mt?{message:mt}:{}}))};if(!k||!fe){P();return}let G=Ye.current.get(Ee);if(G&&!kt(G.generation)){Ye.current.delete(Ee),P();return}if(!G&&Ut()){P();return}if(G&&!He(G.generation)){P();return}G||He();let $=z.expressPaymentType??G?.method??ge.current,he=G??null,T=ql($),A;$==="apple_pay"?A="apple_pay":$==="google_pay"&&(A="google_pay");let te=G?.generation??At.current,j=O,Ce=j?.now()??globalThis.performance?.now()??Date.now(),nt=new AbortController,bt=!1,ht=!1,xe=null,Ar=e,jr="processing",Cr="other",Ht="provider_runtime",Vr,$r=new Promise((mt,st)=>{Vr=st}),kr=window.setTimeout(()=>{bt=!0,nt.abort(),Vr(ci)},Cd),Ot=async(mt,st,Fr)=>{jr=mt,Cr=st,Ht=st==="intent_create"||st==="session_claim"?"transport_error":"provider_runtime";let Ft=j?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Fr,$r])}finally{let Wr=j?.now()??globalThis.performance?.now()??Date.now();j?.performance({stage:mt,durationMs:Math.max(0,Wr-Ft),durationMode:"machine",requestCategory:st,paymentMethodCategory:"wallet",provider:"stripe",...bt?{statusClass:"timeout"}:{}})}};try{if(De(!0),u?.(null),!he&&S){let Oe=await Ot("processing","other",S(T));if(!Oe.proceed){P();return}he={accountPatch:Oe.accountPatch,sessionId:Oe.sessionId,nonce:Oe.nonce}}let mt=he?.sessionId??e;Ar=mt;let st=he?.nonce??t,Fr=$e.current??he?.accountPatch,Ft=Yl({event:z,fallbackEmail:Fr?.email??r,fallbackName:[Fr?.firstName,Fr?.lastName].join(" ").trim()||x});if(!(0,d.isValidEmail)(Ft.email)){P("Buyer details are required."),de(is($),Ft).then(Oe=>{Oe&&($e.current=Oe)});return}$e.current=null;let Wr={...he?.accountPatch,...(0,on.compactBuyerIdentity)(Ft,!0)};await Ot("processing","session_claim",Promise.resolve(H?.(Ft)));let{error:br}=await Ot("tokenization","provider_sdk",fe.submit());if(br){P(),ye($,br,"stripe_wallet_submit_failed",G?.generation);return}if(!mt)throw new Error("Missing sessionId or email for payment.");let Kt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$,paymentMethodId:null,intentKind:o},or=JSON.stringify({sessionId:mt,nonce:st??"",request:Kt}),un=Ge.current,Qr=un?.retryIdentity===or?un.authorizationAttemptId:(0,d.randomUuidV4)();Ge.current={authorizationAttemptId:Qr,retryIdentity:or};let ar=await Ot("processing","intent_create",pi(n,Z,mt,st??"",{...Kt,authorizationAttemptId:Qr},{signal:nt.signal}));if(ar.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let zt=ar.clientSecret,Ir=Id({createdAt:Date.now(),sessionId:mt,...st?{nonce:st}:{},clientSecret:zt,providerObjectId:ar.providerObjectId,paymentMethodType:$,accountPatch:Wr});window.clearTimeout(kr),ht=!0,j?.performance({stage:"callback",durationMs:Math.max(0,(j?.now()??globalThis.performance?.now()??Date.now())-Ce),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let mr=j?.now()??globalThis.performance?.now()??Date.now(),jt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...A?{walletType:A}:{},attempt:te},Sr=!1,Vt=null;j?.log({name:"payment.provider_confirmation.started",...jt}),xe=window.setTimeout(()=>{xe!==null&&We.current.delete(xe),Sr=!0;let Oe=j?.now()??globalThis.performance?.now()??Date.now();j?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...jt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Oe-mr),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),j?.flush?.().catch(()=>{}),Vt?.()},bd),We.current.add(xe);let ur=(Oe,vt)=>{xe!==null&&(window.clearTimeout(xe),We.current.delete(xe),xe=null);let f=j?.now()??globalThis.performance?.now()??Date.now(),ot=Math.max(0,f-mr),oe=Oe;Sr&&(Oe==="resolved"?oe="resolved_late":Oe==="returned_error"?oe="returned_error_late":oe="rejected_late");let Rr=vt??(Oe==="resolved"?"approved":"provider_error");return j?.log({name:"payment.provider_confirmation.returned",...jt,operationOutcome:oe,terminalReason:Rr}),j?.performance({...jt,durationMs:ot,durationMode:"buyer",operationOutcome:oe,terminalReason:Rr}),{durationMs:ot,operationOutcome:oe,terminalReason:Rr}},qt=!1,Ae=!1,pn=Oe=>{if(!Oe||typeof Oe!="object")return null;let vt=Oe;if(vt.error)return null;let f=vt.setupIntent??vt.paymentIntent,ot=ns(f??null,void 0,!!vt.setupIntent);return ot.kind==="confirmed"?ot:null},mn=Oe=>{if(qt||G&&At.current!==G.generation)return;let vt=pn(Oe);if(!vt)return;if(Ir&&!Ol(mt,st,zt)){qt=!0;return}let{intentId:f,paymentMethodId:ot}=vt;qt=!0,Ae=!0,Ge.current=null,N.current=null,_e.current&&(ve("idle"),De(!1));let oe=`${Hl}:${mt}`;tr(oe,{createdAt:Date.now(),sessionId:mt,nonce:st,accountPatch:Wr,paymentMethodId:ot,providerIntentId:f,paymentMethodType:$});try{l({id:ot,type:"card",threeDSecureActionResultTokenId:f},{accountPatch:Wr,paymentMethodCategory:"wallet",sessionId:mt,nonce:st})}finally{tr(oe)}},yn=!1;Vt=async()=>{if(!(yn||qt||Ae)){yn=!0,_e.current&&ve("checking");try{let Oe=await Ll(k,zt,We.current);if(qt||Ae)return;let vt=(0,d.isSetupIntentClientSecret)(zt),f=ns(Oe,ar.providerObjectId,vt);if(f.kind==="confirmed"){mn(vt?{setupIntent:Oe}:{paymentIntent:Oe});return}if(f.kind==="terminal"){if(Ae=!0,rs(mt,st,zt),Ge.current=null,N.current=null,!_e.current)return;ve("idle"),P(),ye($,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",G?.generation,!0);return}_e.current&&!Ae&&(ve("blocked"),De(!1))}catch{_e.current&&!Ae&&(ve("blocked"),De(!1))}finally{yn=!1}}},N.current=Vt;let ir,Br;try{let Oe=await((0,d.isSetupIntentClientSecret)(zt)?k.confirmSetup({elements:fe,clientSecret:zt,redirect:"if_required"}):k.confirmPayment({elements:fe,clientSecret:zt,redirect:"if_required"}));if(!Oe||typeof Oe!="object")throw new Ea(Ed(Oe));if(ir=Oe,!ir.error&&!pn(ir))throw new Ea("confirmation_result_unconfirmed");Br=ur(ir.error?"returned_error":"resolved",ir.error&&(0,we.isProviderDecline)(ir.error)?"provider_declined":void 0)}catch(Oe){let vt=Oe instanceof Ea?Oe.reason:void 0,f=vt!==void 0,ot=ur(f?"returned_error":"rejected");if(j?.error({...f?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:vt}:Ki(Oe),...jt,operationOutcome:ot.operationOutcome,durationMs:ot.durationMs,statusClass:"unknown",terminalReason:ot.terminalReason}),!_e.current||qt)return;await Vt?.();return}let _r=ir.error;if(_r){if(!_e.current||qt)return;if((0,we.isProviderDecline)(_r)){Ae=!0,rs(mt,st,zt),Ge.current=null,N.current=null,ve("idle");let Oe=_r.message??"Your payment was declined.";P(Oe),u?.(Oe),C?.(gr(T,Oe,{code:(0,we.getProviderErrorCode)(_r),declineCode:(0,we.getProviderDeclineCode)(_r)})),mi({billingApiUrl:n,sessionId:mt,nonce:st,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$,providerDeclineReason:(0,we.getProviderErrorCode)(_r)??"provider_declined",...ar.intentKind==="payment"&&ar.providerObjectId.startsWith("pi_")?{providerIntentId:ar.providerObjectId}:{}}})}else j?.error({...Ki(_r),...jt,operationOutcome:Br.operationOutcome,durationMs:Br.durationMs,statusClass:"unknown",terminalReason:Br.terminalReason}),await Vt?.();return}if(mn(ir),!qt)throw new Error("Invalid provider returned for APM intent")}catch(mt){if(mt===ci){let st=j?.now()??globalThis.performance?.now()??Date.now();j?.error({errorCode:Td(Cr),stage:jr,requestCategory:Cr,paymentMethodCategory:"wallet",provider:"stripe",...A?{walletType:A}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ar,durationMs:Math.max(0,st-Ce),statusClass:"timeout",failureCategory:Ht,attempt:te,terminalReason:"provider_error"}),j?.flush?.().catch(()=>{})}P(),ye($,mt,mt===ci?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",G?.generation,mt===ci)}finally{if(window.clearTimeout(kr),xe!==null&&(window.clearTimeout(xe),We.current.delete(xe)),!ht){let mt=j?.now()??globalThis.performance?.now()??Date.now();j?.performance({stage:"callback",durationMs:Math.max(0,mt-Ce),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...bt?{statusClass:"timeout"}:{}})}_e.current&&De(!1)}},[k,fe,e,t,r,x,de,H,n,Z,o,l,u,C,S,ye,He,kt,Ut,At,O,Ee]),Ze=(0,a.useMemo)(()=>oi(i),[i]),Tt=(0,a.useMemo)(()=>i.map(d.stripeExpressMethodToOptionKey),[i]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(wa,{state:ne,placeholderTestId:"flopay-wallet-placeholder",borderRadius:V,children:(0,c.jsxs)("div",{ref:ke,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[ue&&(0,c.jsxs)("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Y,style:as,children:["Try ",is(Q)," 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:Ue,disabled:Ie==="checking",style:as,children:Ie==="checking"?"Checking payment status\u2026":"Check payment status"})]}),me&&(0,c.jsx)(zo,{identity:me.identity,methodLabel:me.methodLabel,onComplete:Qe,onCancel:()=>Qe(null)},me.id),Ie==="idle"&&(0,c.jsx)("div",{style:{display:me?"none":void 0},children:(0,c.jsx)(er.ExpressCheckoutElement,{onReady:z=>{Be(Sa(z,Tt))},onLoadError:z=>{Be("load_error"),cs(O,"stripe","wallet","provider_error")},onClick:async z=>{let p=O?.now()??globalThis.performance?.now()??Date.now();ge.current=z.expressPaymentType,B.current=ql(z.expressPaymentType);let P=!0,G=window.setTimeout(()=>{P=!1,z.reject()},vd),$=S?await S(B.current):{proceed:!0};if(window.clearTimeout(G),!P)return;if(!$.proceed){Ye.current.delete(Ee),z.reject();return}let he=dt(z.expressPaymentType);ct.current={generation:he,startedAt:p},Ye.current.set(Ee,{generation:he,method:z.expressPaymentType,accountPatch:$.accountPatch,sessionId:$.sessionId,nonce:$.nonce}),Pe(!1),O?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:he,...z.expressPaymentType==="apple_pay"||z.expressPaymentType==="google_pay"?{walletType:z.expressPaymentType}:{}}),m?.(B.current),z.resolve()},onConfirm:Rt,onCancel:()=>{let z=Ye.current.get(Ee);Ye.current.delete(Ee),O?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...z?{attempt:z.generation}:{}}),Et(z?.generation),Ge.current=null,Pe(!1),ae.current=!0,U()},options:{...ai,paymentMethods:Ze,emailRequired:Je,billingAddressRequired:Je}},Ee)})]})}),pe&&(0,c.jsx)(zr,{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:m,onDecline:C,onCancel:w,runBeforeButtonClick:S,onButtonClick:x,isProcessing:H,submitButtonColor:M,submitButtonBorderRadius:V,submitButtonStyle:_,errorText:h}){let v=Jn(),{emitInstrument:Z}=(0,a.useContext)(nn),k=(0,er.useStripe)(),fe=(0,er.useElements)(),[O,ne]=(0,a.useState)(!1),Be=(0,a.useRef)(!1),[pe,De]=(0,a.useState)(!1),[Je,me]=(0,a.useState)("loading"),[de,Qe]=(0,a.useState)(""),ke=!(0,d.isValidEmail)(n?.trim()),Re=!ke||(0,d.isValidEmail)(de.trim()),Ee=(0,a.useCallback)(async()=>{if(!k||!fe||H||Be.current||!pe)return;Be.current=!0,ne(!0);let ee=S?await S("card"):{proceed:!0};if(!ee.proceed){Be.current=!1,ne(!1);return}x?.("card");let ue=ee.sessionId??t,Pe=ee.nonce??r,Ie=(0,No.splitFullName)(o?.trim()),ve=(0,on.compactBuyerIdentity)({email:ee.accountPatch?.email?.trim()||n?.trim()||de.trim(),firstName:ee.accountPatch?.firstName?.trim()||Ie.firstName,lastName:ee.accountPatch?.lastName?.trim()||Ie.lastName}),Q=ve.email,K=(0,on.compactBuyerIdentity)({...ee.accountPatch,...ve});try{if(m?.(null),!(0,d.isValidEmail)(Q))throw new Error("A valid email address is required for payment.");await i?.(ve);let N=await fe.submit();if(N.error){m?.(N.error.message??"Payment failed.");return}let _e=[ve.firstName,ve.lastName].filter(Boolean).join(" "),ae=await k.createPaymentMethod({elements:fe,params:{billing_details:{email:Q,..._e?{name:_e}:{}}}});if(ae.error||!ae.paymentMethod){m?.(ae.error?.message??"Failed to create payment method.");return}let ge=ae.paymentMethod;if(!ue||!Q)throw new Error("Missing sessionId or email for payment.");let B=ge.type||e,$e=await pi(l,Z,ue,Pe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:B,paymentMethodId:null,intentKind:"payment"});if($e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ge=$e.clientSecret;tr(jn,{clientSecret:Ge,sessionId:ue,nonce:Pe,accountPatch:K,paymentMethodId:ge.id,paymentMethodType:ge.type??e,gateway:"stripe"});let{error:We,paymentIntent:ct}=await k.confirmPayment({clientSecret:Ge,confirmParams:{return_url:window.location.href,payment_method:ge.id},redirect:"if_required"});if(We){tr(jn);let He=We.message??"Payment failed.";m?.(He),C?.(gr("card",He,{code:We.code})),await mi({billingApiUrl:l,sessionId:ue,nonce:Pe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:We.code??"provider_declined"}});return}let Ye=ct?.status;if(!ua(Ye)){tr(jn);let He=Ye==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(He),C?.(gr("card",He,{code:Ye??"missing_payment_intent"}));return}tr(jn);let dt=typeof ct?.payment_method=="string"?ct.payment_method:ct?.payment_method?.id;u({id:dt??ge.id,type:"card",threeDSecureActionResultTokenId:ct?.id,gateway:"stripe",paymentMethodType:ge.type??e},{accountPatch:K,paymentMethodCategory:"apm",sessionId:ue,nonce:Pe})}catch(N){m?.(N instanceof Error?N.message:"Payment failed. Please try again.")}finally{Be.current=!1,ne(!1)}},[k,fe,H,pe,S,x,t,r,n,o,de,i,l,Z,e,u,m,C]);return(0,c.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ke&&(0,c.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ke&&(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:de,onChange:ee=>Qe(ee.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,c.jsx)(er.PaymentElement,{onReady:()=>me("ready"),onLoadError:()=>{me("load_error"),cs(hr(v),"stripe","apm")},onChange:ee=>{De(!!ee.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:()=>{Ee()},disabled:!pe||!Re||O||H||Je!=="ready",color:M,borderRadius:V,style:_,children:O?"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:m,futureUseSession:C,onTokenizedBody:w,onErrorChange:S,onButtonClick:x,onDecline:H,runBeforeButtonClick:M,onLoadStateChange:V,isProcessing:_=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:v=8,submitButtonStyle:Z,buttonAppearance:k,themeId:fe,onExpandApm:O,expandedApmMethod:ne}){let{emitInstrument:Be}=(0,a.useContext)(nn),[pe,De]=(0,a.useState)(null),[Je,me]=(0,a.useState)(null),de=(0,a.useRef)(!1),{request:Qe,collect:ke,finish:Re}=Uo();(0,a.useEffect)(()=>{l.length>0&&u?V?.("ready"):u||V?.("loading")},[l.length,u,V]);let Ee=(0,a.useCallback)(async Q=>{if(!u||de.current||_)return;de.current=!0,me(Q);let K=M?await M("card"):{proceed:!0};if(!K.proceed){de.current=!1,me(null);return}x?.("card");let N=K.sessionId??e,_e=K.nonce??t,ae=(0,No.splitFullName)([K.accountPatch?.firstName,K.accountPatch?.lastName].filter(Boolean).join(" ")||n),ge=(0,on.compactBuyerIdentity)({email:K.accountPatch?.email?.trim()||r?.trim(),firstName:K.accountPatch?.firstName?.trim()||ae.firstName,lastName:K.accountPatch?.lastName?.trim()||ae.lastName});if(!(0,d.isValidEmail)(ge.email)){me(null);let Ge=await ke((0,d.getStripeMethodDisplayName)(Q),ge);if(!Ge){de.current=!1;return}ge=Ge,me(Q)}let B=ge.email,$e=(0,on.compactBuyerIdentity)({...K.accountPatch,...ge});try{if(S?.(null),!N||!(0,d.isValidEmail)(B))throw new Error("Missing sessionId or email for payment.");await o?.(ge);let Ge=await pi(i,Be,N,_e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if(Ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let We=Ge.clientSecret;tr(jn,{clientSecret:We,sessionId:N,nonce:_e,accountPatch:$e,paymentMethodType:Q,gateway:"stripe"});let{error:ct,paymentIntent:Ye}=await u.confirmPayment({clientSecret:We,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:[ge.firstName,ge.lastName].filter(Boolean).join(" "),...B?{email:B}:{}}}},redirect:"if_required"});if(ct){tr(jn);let Et=ct.message??"Payment failed.";S?.(Et),H?.(gr("card",Et,{code:ct.code})),await mi({billingApiUrl:i,sessionId:N,nonce:_e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:ct.code??"provider_declined"}});return}let dt=Ye?.status;if(!ua(dt)){tr(jn);let Et=dt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(Et),H?.(gr("card",Et,{code:dt??"missing_payment_intent"}));return}tr(jn);let He=typeof Ye?.payment_method=="string"?Ye.payment_method:Ye?.payment_method?.id;w({id:He??Ye?.id,type:"card",threeDSecureActionResultTokenId:Ye?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:$e,paymentMethodCategory:"apm",sessionId:N,nonce:_e})}catch(Ge){S?.(Ge instanceof Error?Ge.message:"Payment failed. Please try again.")}finally{de.current=!1,me(null)}},[u,_,M,x,e,t,r,ke,i,Be,n,o,w,S,H]),[ee,ue]=(0,a.useState)(null),Pe=O?ne??null:ee,Ie=(0,a.useCallback)(Q=>{de.current||_||Pe&&Pe!==Q||((0,d.needsStripeMethodExplicitConfirm)(Q)?O?O(Q):ue(Q):Ee(Q))},[Pe,_,Ee,O]),ve=(0,a.useMemo)(()=>ee?Xl(m,ee,C):null,[ee,m,C]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Qe?(0,c.jsx)(zo,{identity:Qe.identity,methodLabel:Qe.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Qe.id):l.map(Q=>{let K=ne===Q,N=Je===Q,_e=Je!==null&&Je!==Q||ne!=null&&ne!==Q;return(0,c.jsxs)(a.default.Fragment,{children:[(0,c.jsx)(ni,{method:Q,themeId:fe,submitting:N,disabled:_e,highlighted:K,hasNextStep:(0,d.needsStripeMethodExplicitConfirm)(Q),onClick:()=>Ie(Q),backgroundColor:k?.backgroundColor,borderColor:k?.borderColor,textColor:k?.textColor,borderRadius:k?.borderRadius,fontFamily:k?.fontFamily}),!O&&ee===Q&&ve&&u&&(0,c.jsx)(er.Elements,{stripe:u,options:ve,children:(0,c.jsx)(ss,{method:Q,sessionId:e,nonce:t,email:r,billingName:n,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:w,onErrorChange:S,onDecline:H,onCancel:()=>ue(null),runBeforeButtonClick:M,onButtonClick:x,isProcessing:_,submitButtonColor:h,submitButtonBorderRadius:v,submitButtonStyle:Z})},Q)]},Q)})})}function Vd({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,email:o,userId:i,onComplete:l,onError:u,onDecline:m,onTokenizedBody:C,firstName:w,lastName:S,chv:x,className:H,submitLabel:M,isProcessing:V,error:_,onErrorChange:h,showPayPal:v=!0,showStripe:Z=!0,walletPresentation:k="auto",enabledPaymentMethods:fe,enabledPaymentMethodCountries:O,showApplePay:ne=!0,showGooglePay:Be=!0,layout:pe="default",theme:De,buttonsTheme:Je,buttonsStyles:me,appearance:de,cardButtonContent:Qe,cardBackButtonContent:ke,cardTitleContent:Re,showSecurityFooter:Ee,onButtonClick:ee,onBeforeButtonClick:ue,onBuyerIdentityReady:Pe,enableAVS:Ie,cardFieldOrder:ve,cardPreFormSlot:Q,avsLayout:K="row",country:N,zip:_e,addressLine1:ae,addressLine2:ge,city:B,state:$e,onCountryChange:Ge,onZipChange:We,avsCheck:ct,checkoutType:Ye,checkoutLayout:dt,totalAmount:He=0,currency:Et="usd",initialCardOpen:Ut=!1,directPaypal:kt,isSubscription:At=!1,session:U,dataAttachmentPending:ye=!1,dataAttachmentRequiresIdentity:et=!1,debug:Y=!1}){let Ue=Jn(),Rt=Ka(),Ze=(0,a.useContext)(Rn),{emitInstrument:Tt}=(0,a.useContext)(nn),z=(0,a.useRef)(null);z.current||(z.current=Ya());let p=z.current,[,P]=(0,a.useState)(0),G=(0,a.useRef)(null);G.current||(G.current=(0,Un.detectPayPalEnvironment)());let $=G.current,he=(0,a.useMemo)(()=>({browser:$,capability:p,presentationMode:"popup"}),[$,p]),T=U??Ze.session,A=(0,a.useMemo)(()=>({futureUse:T?.futureUse,futureUseUnsupported:T?.futureUseUnsupported}),[T?.futureUse,T?.futureUseUnsupported]),te=T?.gateways?.paypal?.providerObjectType??kt?.providerObjectType,j=ye||Ze.claimPending===!0,Ce=et||Ze.claimRequiresIdentity===!0,nt=j&&!Ce,bt=Cl(),ht=r||bt,[xe,Ar]=(0,a.useState)(!1),[jr,Cr]=(0,a.useState)(null),[Ht,Vr]=(0,a.useState)(N??""),[$r,kr]=(0,a.useState)(_e??""),[Ot,mt]=(0,a.useState)(ae??""),[st,Fr]=(0,a.useState)(ge??""),[Ft,Wr]=(0,a.useState)(B??""),[br,Kt]=(0,a.useState)($e??""),[or,un]=(0,a.useState)(""),[Qr,ar]=(0,a.useState)({}),zt=(0,a.useRef)(_e??""),Ir=(0,a.useRef)(N??""),mr=(0,a.useRef)(ae??""),jt=(0,a.useRef)(ge??""),Sr=(0,a.useRef)(B??""),Vt=(0,a.useRef)($e??""),ur=(0,a.useRef)(""),qt=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(R,ce,ze,re,Te)=>{if(qt.current[R])return;let Dt=ce?.trim();!Dt||Dt===ze.current||(ze.current=Dt,re(Dt),Te?.(Dt))};s("country",N,Ir,Vr,Ge),s("zip",_e,zt,kr,We),s("addressLine1",ae,mr,mt),s("addressLine2",ge,jt,Fr),s("city",B,Sr,Wr),s("state",$e,Vt,Kt)},[N,_e,ae,ge,B,$e,Ge,We]);let Ae=(0,a.useMemo)(()=>(0,d.resolveAVSConfig)(Ie),[Ie]),pn=Ae!==null,mn=(0,a.useMemo)(()=>(0,d.isAuthorizationOnlySession)(U),[U]),yn=(0,d.isMountableVaultBlock)(U?.vault),ir=!!U?.gateways?.pcivault,Br=(0,kn.hasServerSideCardGateway)(U),Oe=!!(U?.gateways?.stripe?.enabledPaymentMethods??fe)?.includes("card")||(0,kn.canRecoverHostedCardForm)(U),vt=yn||Oe||ir,f=!!(Z&&vt&&e),[ot,oe]=(0,a.useState)(()=>pe!=="buttons"||Ut?e??null:null),[Rr,Hr]=(0,a.useState)(0),Zt=pe!=="buttons"||Ut||!!e&&ot===e,Dr=U?.captureMethod,St=(0,a.useRef)(Ue);(0,a.useEffect)(()=>{St.current=Ue},[Ue]);let[Mn,ro]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(!f||!e||!Zt){ro(null);return}let s=St.current?St.current.cardCapture({sessionId:e,captureMethod:Dr}):new Tn.PciVaultCardCapture({sessionId:e,captureMethod:Dr,billingApiUrl:ht,telemetry:n});return ro({sessionId:e,captureMethod:Dr,billingApiUrl:ht,telemetry:n,capture:s}),()=>{s.unmount()}},[f,e,Zt,Dr,ht,n]);let Bt=f&&e&&Zt&&Mn?.sessionId===e&&Mn.captureMethod===Dr&&Mn.billingApiUrl===ht&&Mn.telemetry===n?Mn.capture:null,Kr=(0,a.useMemo)(()=>{let s=Ht,R=Ae?(0,d.isAVSFieldVisible)(Ae.postal_code,s):!1;return zd(s,$r,R)},[Ae,Ht,$r]),{avsInvalid:fn,invalidAvsFields:gn}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!f||!Ae)return{avsInvalid:!1,invalidAvsFields:s};let R=Ht,ce=(Te,Dt)=>(0,d.isAVSFieldVisible)(Te,R)&&!Dt.trim(),ze={line1:ce(Ae.address_line_1,Ot),city:ce(Ae.city,Ft),state:ce(Ae.state,br),zip:Kr.empty||Kr.malformed};return{avsInvalid:ze.line1||ze.city||ze.state||ze.zip,invalidAvsFields:ze}},[f,Ae,Ht,Ot,Ft,br,Kr]),[Gt,xn]=(0,a.useState)(!1),[An,Or]=(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),Lt=(0,a.useCallback)(s=>{hn.current[s]=!0,Pn.current=!0},[]),Yr=(0,a.useCallback)(s=>!Gr.current&&hn.current[s],[]),Tr=(0,a.useCallback)(s=>{Yr(s)&&Wn(R=>R[s]?R:{...R,[s]:!0})},[Yr]),[vn,Cn]=(0,a.useState)(()=>(0,d.resolveVaultMountOptions)(U?.vault,{billingApiUrl:ht,sessionId:e,nonce:t})),[Ct,sr]=(0,a.useState)(Ut&&vt?"card":"buttons"),[yr,Lr]=(0,a.useState)(null),no=Ct==="expanding"||Ct==="card",Dn=U?.gateways?.stripe&&!Br?"stripe":void 0,Hn=(0,a.useCallback)(()=>{Tt?.({class:"card_surface",provider:Dn})},[Dn,Tt]),tn=(0,a.useRef)(null),lr=(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),[pr,q]=(0,a.useState)(0),D=(0,a.useRef)(null),se=(0,a.useCallback)(()=>{Hn(),oe(e??null),oo.current&&(oo.current=!1,q(s=>s+1)),Hr(s=>s+1),sr("expanding"),lr(()=>sr("card"))},[lr,Hn,e]),be=(0,a.useCallback)(()=>{sr("collapsing"),lr(()=>sr("buttons"))},[lr]),It=(0,a.useCallback)(s=>{Lr(s),sr("apm-expanding"),lr(()=>sr("apm-form"))},[lr]),Yt=(0,a.useCallback)(()=>{sr("apm-collapsing"),lr(()=>{sr("buttons"),Lr(null)})},[lr]);(0,a.useEffect)(()=>{pe==="buttons"&&Ut&&vt&&(oe(e??null),sr("card"))},[pe,Ut,vt,e]);let[Le,X]=(0,a.useState)(null),J=(0,a.useRef)(!1),W=(0,a.useRef)(null),y=(0,a.useRef)("idle"),[g,E]=(0,a.useState)(!1),le=(0,a.useRef)(g);le.current=g;let[Fe,Ke]=(0,a.useState)(()=>kt?.existingOrderId?{orderId:kt.existingOrderId,attempts:1}:null),Xt=(0,a.useRef)(Fe);(0,a.useEffect)(()=>{Xt.current=Fe},[Fe]);let Me=(0,a.useRef)(null),Xe=(0,a.useMemo)(()=>{if(Pe||Ze.claimBuyerIdentity||U?.buyerIdentified!==!1||!e||!t)return;let s=`${ht}|${e}|${t}`;Me.current?.key!==s&&(Me.current={key:s,claim:Oo(new Tn.PaymentAPI(ht,{telemetry:!1}),e,t,{...i?{userId:i}:{},...w?{firstName:w}:{},...S?{lastName:S}:{}})});let R=Me.current.claim;return async ce=>{await R(ce)}},[Pe,Ze.claimBuyerIdentity,U?.buyerIdentified,e,t,ht,i,w,S]),at=Pe??Ze.claimBuyerIdentity??Xe,wt=_??jr,Se=(0,a.useMemo)(()=>(0,d.resolveTheme)(De),[De]),L=(0,a.useMemo)(()=>{let s=Se?.buttonsLayout??(0,d.resolveButtonsLayoutTheme)(Je);return me?{...s,...me,cardButton:{...s.cardButton,...me.cardButton},cardFormContainer:{...s.cardFormContainer,...me.cardFormContainer},backButton:{...s.backButton,...me.backButton},backButtonIcon:{...s.backButtonIcon,...me.backButtonIcon},submitButton:{...s.submitButton,...me.submitButton},title:{...s.title,...me.title}}:s},[Se,Je,me]),ie=de??Se?.appearance,yt=(0,a.useMemo)(()=>(0,d.computeVaultCardThemeColors)({appearance:ie,buttonsStyles:L,layout:pe}),[ie,L,pe]),Ve=Ze.inlineSessionPatchProcessing??!1,tt=(V??xe)||Ve,Mt=ht.replace(/\/+$/,""),Pt=(0,a.useMemo)(()=>Hi({userId:i,email:o,firstName:w,lastName:S,country:N,zip:_e},Qr),[i,o,w,S,N,_e,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)(()=>qd(or,ao),[or,ao]),wo=ki.empty||ki.malformed,Xr=(0,a.useMemo)(()=>Ue?Ue.getRawProvider():null,[Ue]),ws=(0,a.useMemo)(()=>Rt?Rt.getRawProvider():null,[Rt]),Zo=He||100,ko=Et.toLowerCase(),Ri=(0,a.useMemo)(()=>ie?(0,Tn.toStripeAppearance)(ie):null,[ie]),Ro=Ri,ks=(0,a.useMemo)(()=>{let s=Ri??{},R=s.rules??{};return{...s,rules:{...R,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...R[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...R[".AccordionItemContents"]??{}}}}},[Ri]),Rs=(0,a.useMemo)(()=>({...hl(He,T?.captureMethod,A),currency:ko,...Ro?{appearance:Ro}:null}),[He,ko,T?.captureMethod,A,Ro]),Ei=(0,d.resolveSetupFutureUsage)(A,"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]),Ne=(0,a.useCallback)(s=>{Cr(s),h?.(s)},[h]),Is=(0,a.useRef)(0);(0,a.useEffect)(()=>{pr!==Is.current&&(Is.current=pr,Ne(null))},[pr,Ne]);let Ii=(0,a.useRef)(""),[_s,bc]=(0,a.useState)(!1),_i=(0,a.useCallback)(()=>{bc(!0)},[]);(0,a.useEffect)(()=>{if(!f||!ao||!at||!_s||wo||Ii.current)return;let s=(0,on.compactBuyerIdentity)({email:(0,d.isValidEmail)(Pt.email?.trim())?Pt.email?.trim():ur.current.trim(),firstName:Pt.firstName?.trim(),lastName:Pt.lastName?.trim()});Ii.current=JSON.stringify(s),ar(R=>({...R,...s})),Promise.resolve(at(s)).catch(R=>{Ii.current="",Ne(R instanceof Error?R.message:"Failed to attach buyer details.")})},[f,ao,at,_s,wo,Pt.email,Pt.firstName,Pt.lastName,Ne]),(0,a.useEffect)(()=>{!f||!Bt||Bt.setCardFieldOrder?.(ve??null,Ae==null&&!ao)},[f,Bt,ve,Ae,ao]),(0,a.useEffect)(()=>{(Ct==="expanding"||Ct==="collapsing"||Ct==="apm-expanding"||Ct==="apm-collapsing")&&Ne(null)},[Ct,Ne]);let On=(0,a.useCallback)((s,R,ce)=>{m?.(gr(s,R,ce))},[m]),Eo=(0,a.useCallback)((s,R,ce)=>{let ze=ce?.popupBlocked??(0,we.isPopupBlockedError)(R);ze&&p.markBlocked()&&P(ft=>ft+1);let re=(0,we.buildExternalMethodRecoveryMessage)(is(s),ze,$.inAppBrowser),Te=(0,we.getProviderErrorCode)(R),Dt=(Te?.toLowerCase()==="error"?void 0:Te)??(0,we.sanitizeExternalFailureCode)(ce?.code)??"external_payment_method_failed",wn=new d.FloPayError(re,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:Dt,popupBlocked:ze,inAppBrowser:$.inAppBrowser,appFamily:$.appFamily,popupCapability:p.current(),presentationMode:ce?.presentationMode??"popup"}});ce?.telemetryReported||hr(Ue)?.error(Ko({...he,presentationMode:ce?.presentationMode??"popup"},{errorCode:ze?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:ce?.provider??(s==="paypal"?"paypal":"stripe"),paymentMethodCategory:ce?.paymentMethodCategory??(s==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:ce?.terminalReason??(ze?"popup_blocked":"provider_error")})),X(null),pe==="buttons"&&(sr("buttons"),Lr(null)),Ne(re),u?.(wn),console.error("[FloPay] External payment method failed:",{method:s,code:Dt,popupBlocked:ze})},[$,he,Ue,pe,u,p,Ne]);(0,a.useEffect)(()=>{if(!f||!e){Cn(null);return}let s={billingApiUrl:Mt,sessionId:e,nonce:t},R=(0,d.resolveVaultMountOptions)(U?.vault,s);if(R){Cn(R);return}if(!Zt){Cn(null);return}let ce=`${Mt}\0${e}\0${t??""}`,ze=D.current;if(ze&&ze.key===ce){Cn(ze.mount);return}Cn(null);let re=!0;return new Tn.PaymentAPI(Mt).getVaultCapture(e,t).then(Te=>{if(!re)return;let Dt=(0,d.resolveVaultMountOptions)(Te,s);Dt?.verificationRequired&&!Te.html&&(D.current={key:ce,mount:Dt}),Dt?Cn(Dt):Ne("Failed to load the secure card form.")}).catch(Te=>{re&&Ne(Te instanceof Error?Te.message:"Failed to load the secure card form.")}),()=>{re=!1}},[f,Zt,Rr,e,U?.vault,Mt,t,Ne]);let bn=(0,a.useRef)({onComplete:l,onError:u,updateError:Ne,emitDecline:On,resolvedAccount:Pt,avsConfig:Ae,avsCheckProp:ct,sessionId:e,nonce:t,baseUrl:Mt,captureMethod:U?.captureMethod,paymentId:U?.paymentId,authorizationExpiresAt:U?.authorizationExpiresAt,serverSideCardGateway:Br});bn.current={onComplete:l,onError:u,updateError:Ne,emitDecline:On,resolvedAccount:Pt,avsConfig:Ae,avsCheckProp:ct,sessionId:e,nonce:t,baseUrl:Mt,captureMethod:U?.captureMethod,paymentId:U?.paymentId,authorizationExpiresAt:U?.authorizationExpiresAt,serverSideCardGateway:Br};let Ti=(0,a.useRef)(!1),Ts=(0,a.useCallback)(()=>{let s=bn.current,R=s.resolvedAccount.email?.trim(),ce=(0,d.isValidEmail)(R)?R:ur.current.trim();if(!(0,d.isValidEmail)(ce))return null;let ze=s.resolvedAccount.firstName?.trim(),re=s.resolvedAccount.lastName?.trim(),Te=Ir.current.trim()||s.resolvedAccount.country?.trim()||"",Dt=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.state,Te):!1,wn=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.address_line_1,Te):!1,ft=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.postal_code,Te):!1,_t=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.city,Te):!1,xt=s.avsConfig?(0,d.isAVSFieldVisible)(s.avsConfig.address_line_2,Te):!1,$t=wn&&!Dt&&ft?(0,d.getStateFromPostalCode)(Te,(zt.current??"").trim()):null,yo=Dt?Vt.current:$t;return{accountData:{userId:s.resolvedAccount.userId??"",email:ce,...ze?{firstName:ze}:{},...re?{lastName:re}:{},...ft&&zt.current?{zip:zt.current}:{},..._t&&Sr.current?{city:Sr.current}:{},...yo?{state:yo}:{},...wn&&mr.current?{addressLine1:mr.current}:{},...xt&&jt.current?{addressLine2:jt.current}:{},...Te?{country:Te}:{}},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,d.isAVSFieldVisible)(s.avsConfig.country,Te),postal_code:ft,address_line_1:wn,address_line_2:xt,city:_t,state:Dt}}:{}}},[]),Ms=(0,a.useRef)(j);Ms.current=j,(0,a.useEffect)(()=>{j||wt!==Nl||bn.current.updateError(null)},[j,wt]),(0,a.useEffect)(()=>{!f||!Bt||Bt.setSubmitGate?.(fn||j||wo||g)},[f,Bt,fn,j,wo,g]),(0,a.useEffect)(()=>{if(!f||!Bt)return;Ti.current=!1;let s=null,R=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,y.current="idle",X(null)},400)},ce=Bt.on("submitting",()=>{xn(!0),W.current&&clearTimeout(W.current),y.current="validation-window",W.current=setTimeout(()=>{W.current=null,y.current==="validation-window"&&(y.current="processing")},Md),X("processing");let ft=bn.current;if(!ft.sessionId||!ft.nonce)return;let _t=Ts();if(!_t){ft.updateError("Enter a valid email address."),y.current="idle",X(null);return}new Tn.PaymentAPI(ft.baseUrl).patchAccountSnapshot(ft.sessionId,ft.nonce,_t,{telemetryMode:"best_effort"}).catch(xt=>{if(!Ad(xt))return;let $t=xt instanceof Error?xt.message:"Please check your billing address and try again.";ft.updateError($t),y.current="idle",X(null),ft.onError?.(xt instanceof d.FloPayError?xt:new d.FloPayError($t,"api_error"))})}),ze=Bt.on("complete",ft=>{(0,In.markSessionRecentlyCompleted)(ft.sessionId??bn.current.sessionId),y.current="terminal",E(!1),X("success"),setTimeout(()=>{if(Ti.current)return;Ti.current=!0;let _t=bn.current,xt=(0,d.isAuthorizationOnlySession)(_t)||ft.outcome==="authorized",$t=_t.serverSideCardGateway?{}:{paymentIntentId:ft.intentId};bn.current.onComplete?.(xt?{status:"authorized",...$t,paymentId:ft.paymentId??_t.paymentId,sessionId:ft.sessionId??_t.sessionId,authorizationExpiresAt:ft.authorizationExpiresAt??_t.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...$t,checkoutMethod:"card"})},600)}),re=Bt.on("decline",ft=>{let _t=bn.current,xt=ft.message??"Your payment was declined. Please try another card or contact your bank.";y.current="terminal",E(!1),_t.updateError(xt),X("error");let $t=ft.failureOutcome??(0,d.normalizeCheckoutFailureOutcome)(ft.declineReason)??"authorization_declined";_t.emitDecline("card",xt,{code:$t,declineCode:$t}),R()}),Te=Bt.on("error",ft=>{let _t=bn.current,xt=ft.message??"There was a problem processing your payment. Please try again.";y.current="terminal",E(!1),_t.updateError(xt),X("error"),_t.onError?.(new d.FloPayError(xt,"api_error",{code:ft.failureOutcome??"capture_failed"})),R()}),Dt=Bt.on("challenge_dismissed",()=>{W.current&&(clearTimeout(W.current),W.current=null),y.current="processing",E(!0),X(null)}),wn=Bt.on("blocked",()=>{if(le.current){bn.current.updateError(xd);return}if(!Ms.current){xn(!0);return}_i(),bn.current.updateError(Nl)});return()=>{s&&(clearTimeout(s),s=null),W.current&&(clearTimeout(W.current),W.current=null),y.current="idle",E(!1),X(null),ce(),ze(),re(),Te(),Dt(),wn()}},[f,Bt,_i,Ts]);let Ln=!!kt?.clientId,Qo=Array.isArray(fe),Aa=Qo&&fe.length>0,xs=Qo&&fe.includes("paypal"),Fa=(0,a.useRef)(null);Fa.current===null&&(Fa.current=(0,d.hasMatchingStripePayPalReturn)());let Io=Fa.current?"redirect":(0,zn.resolveStripePayPalPresentation)($,k,p.current()),{expressMethods:Ba,paymentElementMethods:Mi}=(0,a.useMemo)(()=>(0,d.partitionStripeMethods)(fe,{excludePaypal:Ln}),[fe,Ln]),As=Ln||!!Rt||xs&&Io==="redirect",Sc=(0,a.useMemo)(()=>As?Ba.filter(s=>s!=="paypal"):Ba,[Ba,As]),wc=(0,a.useMemo)(()=>{let s=[];return ne&&s.push("apple_pay"),Be&&s.push("google_pay"),s},[ne,Be]),_o=Qo?Sc:wc,kc=Z&&_o.length>0,Fs=pn?Ht:N,Da=(0,a.useMemo)(()=>(0,d.filterStripeMethodsByCountryGate)(Mi,Fs,O),[Mi,Fs,O]),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"),[Rc,Ai]=(0,a.useState)(!1),[zs,Fi]=(0,a.useState)("loading"),[Bi,Ec]=(0,a.useState)();(0,a.useEffect)(()=>{Ec((0,Un.detectPayPalEnvironment)())},[]);let Oa=Bi?.inAppBrowser,La=Bi?(0,zn.resolvePayPalPresentationMode)(Bi,kt?.approvalPresentation,te??(At?"subscription":"order")):"popup",qs=v&&(Ln||(Qo?xs:Oa===!1)),js=Z&&kc,ea=(!nt||!!Ze.waitForDataAttachment)&&qs&&Ln,Vs=zs==="retrying"||zs==="exhausted",ta=null;Z&&(Rt?ta=ws:Io==="redirect"&&(ta=Xr));let $s=(0,a.useMemo)(()=>({...he,presentationMode:Io}),[he,Io]),ra=!nt&&qs&&!!ta&&(!Ln||Vs),To=!nt&&js&&!!Xr,na=!nt&&Z&&Aa&&Da.length>0&&!!Xr,Ic=ea&&!Vs?Rc:ra&&es(Bs),_c=To&&es(Os),Tc=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(!Z&&!v){Na.current=!0;let s=new d.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(s),Ne(s.message)}else if(!Z&&v&&!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),Ne(s.message)}else if(Oa!==void 0&&!nt&&!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),Ne(s.message)}}},[Z,v,Ln,Oa,nt,vt,Hs,u,Ne]);let Ks=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(Ks.current||!Aa)return;let s=[];ne!==!0&&s.push("showApplePay"),Be!==!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,Be]);let Gs=(0,a.useCallback)((s,R)=>Ze.applyInlineSessionPatch?Ze.applyInlineSessionPatch(s).then(ce=>({error:null,sessionId:ce.sessionId||e,nonce:ce.session?.clientSecret||t})).catch(ce=>{let ze=(0,d.normalizeBeforeButtonClickError)(R,ce);return Ne(ze.message),u?.(ze),{error:ze,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ze.applyInlineSessionPatch,t,u,e,Ne]),Sn=(0,a.useCallback)(async s=>{if(s!=="card"&&nt&&await Ze.waitForDataAttachment?.(),!ue)return{proceed:!0};try{let R=await ue({method:s,sessionId:e||void 0,createSession:Ze.inlineSessionDraft});if(R===!1)return{proceed:!1};if(R&&typeof R=="object"){R.account&&ar(ze=>({...ze??{},...R.account}));let ce=await Gs(R,s);return ce.error?{proceed:!1,accountPatch:R.account}:{proceed:!0,accountPatch:R.account,sessionId:ce.sessionId,nonce:ce.nonce}}return{proceed:!0}}catch(R){let ce=(0,d.normalizeBeforeButtonClickError)(s,R);return Ne(ce.message),u?.(ce),{proceed:!1}}},[Gs,Ze.inlineSessionDraft,Ze.waitForDataAttachment,nt,ue,u,e,Ne]),Ys=(0,a.useCallback)(async(s,R)=>{if(J.current)return;J.current=!0,Ar(!0),X("processing"),Ne(null);let ce=R?.sessionId??e,ze=R?.nonce??t,re=Hi(Pt,R?.accountPatch),Te=R?.completionPaymentMethodId??pa(s),Dt=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,wn=Od(s),ft=R?.presentationMode?ri(hr(Ue),{...he,presentationMode:R.presentationMode}):void 0,_t=()=>{Tt?.({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),$t=await xt.processPayment(re.userId??"",{sessionId:ce,nonce:ze,paymentMethodCategory:R?.paymentMethodCategory??Nd(s),tokenizedData:Dt,accountData:{...R?.accountPatch,userId:re.userId??"",email:re.email??"",firstName:re.firstName||void 0,lastName:re.lastName||void 0,...(0,d.buildProcessPaymentAvsAccount)({avsConfig:Ae,country:Ir.current,zip:zt.current,city:Sr.current,state:Vt.current,addressLine1:mr.current,addressLine2:jt.current})},...(0,d.buildCheckoutProcessMetadata)({chv:x,avsCheck:ct,checkoutType:Ye,checkoutLayout:dt,avsConfig:Ae,country:Ir.current})}),yo=async fr=>{let fo=(0,d.isAuthorizationOnlySession)(U)||fr?.status==="authorized";(0,In.markSessionRecentlyCompleted)(ce),ft?.terminal({outcome:"payment_succeeded",..._n}),X("success"),Ke(null),await new Promise(ca=>setTimeout(ca,600));let Nn;typeof fr?.paymentId=="string"?Nn=fr.paymentId:U?.paymentId&&(Nn=U.paymentId);let go;typeof fr?.authorizationExpiresAt=="string"?go=fr.authorizationExpiresAt:U?.authorizationExpiresAt&&(go=U.authorizationExpiresAt),l?.(fo?{status:"authorized",...Nn===void 0?{}:{paymentId:Nn},sessionId:typeof fr?.sessionId=="string"?fr.sessionId:ce,...go===void 0?{}:{authorizationExpiresAt:go},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Te,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Te,checkoutMethod:s.isPaypal?"paypal":"card"})};if($t.ok){await yo($t.status===204?null:await $t.json().catch(()=>null));return}let Jr=await $t.json().catch(()=>null);if(Jr?.type==="paypal_redirect_required"){let fr=Jr.threeDSecureToken,fo=Jr.paymentMethodId||s.id||"";if(!Ue||!fr){X("error"),Ne("PayPal authorization required but no token provided.");return}try{let Nn=Rt?.getRawProvider();if(!Nn){Ne("PayPal is not available.");return}let go={return_url:window.location.href};fo&&(go.payment_method=fo);let{error:ca}=await Nn.confirmPayment({clientSecret:fr,confirmParams:go,redirect:"if_required"});if(ca){X("error");let sl=ca.message??"PayPal payment failed.";Ne(sl),On("paypal",sl,{code:ca.code})}}catch(Nn){X("error"),Ne(Nn instanceof Error?Nn.message:"PayPal authorization failed.")}return}if(Jr?.type==="paypal_direct_required"){let fr=Jr.orderId;if(!fr){X("error"),Ne("PayPal retry required but no order id provided.");return}let fo=Xt.current?.attempts??0;if(fo>=2){X("error"),Ne("PayPal payment could not be completed after multiple attempts."),On("paypal","paypal_direct_required retry limit exceeded");return}Ai(!1),Fi("loading"),Ke({orderId:fr,attempts:fo+1}),X(null);return}if($t.headers.get(wd)===kd){let fr=await Rd(xt,ce,ze);if(fr!==void 0){await yo(fr);return}}(0,d.classifyPaymentRejection)($t.status,Jr)?ft?.terminal({outcome:"payment_declined",..._n,terminalReason:"provider_declined"}):_t(),X("error");let il=Jr?.message??"Payment failed. Please try again.";Ne(il),On(s.isPaypal?"paypal":"card",il,{code:Jr?.code??Jr?.gatewayErrorCode,declineCode:Jr?.declineCode??Jr?.gatewayDeclineReason}),await new Promise(fr=>setTimeout(fr,400))}catch(xt){Gl(xt)||_t(),X("error"),Ne(xt instanceof Error?xt.message:"An unexpected error occurred"),await new Promise($t=>setTimeout($t,400))}finally{Ar(!1),X(null),J.current=!1}},[Mt,e,t,Pt,Ae,ct,Ye,dt,x,Ue,Rt,U,l,Ne,On,Tt,he]),Nr=(0,a.useCallback)((s,R)=>{C?C(s):Ys(s,R)},[C,Ys]),oa=`${Hl}:${e}`;(0,a.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(oa);if(!s)return;let R;try{R=JSON.parse(s)}catch{tr(oa);return}if(!R||typeof R.createdAt!="number"||Date.now()-R.createdAt<0||Date.now()-R.createdAt>Kl||typeof R.paymentMethodId!="string"||typeof R.providerIntentId!="string"||typeof R.paymentMethodType!="string"||R.sessionId!==e||!t||R.nonce!==t||!_o.includes(R.paymentMethodType)){tr(oa);return}tr(oa),Nr({id:R.paymentMethodId,type:"card",threeDSecureActionResultTokenId:R.providerIntentId,gateway:"stripe",paymentMethodType:R.paymentMethodType},{...R.accountPatch?{accountPatch:R.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Nr,t,e,oa,_o]);let Xs=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||Xs.current)return;let[s,R,ce]=(0,d.readStripeRedirectParams)();if(!s||!R||Fa.current||!Ue)return;let ze=Ue.getRawProvider();if(!ze)return;let re=_t=>{let xt=localStorage.getItem(_t);if(!xt)return null;try{return JSON.parse(xt)}catch{return tr(_t),null}},Te=re(jn)??re(Dl),Dt;if(Te?.clientSecret){if(Te.clientSecret!==R)return;Dt={...Te.accountPatch?{accountPatch:Te.accountPatch}:{},...Te.sessionId?{sessionId:Te.sessionId}:{},...Te.nonce?{nonce:Te.nonce}:{}}}else if(Te?.sessionId&&Te.sessionId!==e)return;Xs.current=!0,tr(jn),tr(Dl),window.history.replaceState({},"",(0,d.stripeRedirectReturnUrl)());let wn=Te?.paymentMethodType??Te?.tokenType??"card",ft="card";(async()=>{if(ce==="failed"){let Kn="Payment was declined. Please try again.";Ne(Kn),On(ft,Kn);return}let{paymentIntent:_t,error:xt}=await ze.retrievePaymentIntent(R);if(xt){let Kn=xt.message??"Failed to retrieve payment status.";Ne(Kn),On(ft,Kn,{code:xt.code});return}let $t=_t?.status,yo=ua($t);if(!_t||!yo){let Kn=$t==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ne(Kn),On(ft,Kn,{code:$t??"missing_payment_intent"});return}let Jr=typeof _t.payment_method=="string"?_t.payment_method:_t.payment_method?.id;Nr({id:Jr??Te?.paymentMethodId??Te?.tokenId??_t.id,type:"card",threeDSecureActionResultTokenId:_t.id,gateway:Te?.gateway??"stripe",paymentMethodType:wn},Dt)})()},[e,Nr,Ue,Ne,On]);let Di=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!(f||Ue!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let aa=pe==="buttons",Ur=ie?.variables,Mc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Oi=Ur?.colorBackground,xc=Oi&&!Mc.has(Oi)?Oi:void 0,ia=L.cardInputBorder??(aa?"#e5e7eb":"#A4A4FF"),Js=Ur?.colorDanger??"#dc2626",Jt=s=>gn[s]&&(Bn[s]||Gt),Ua=wo&&(Fn||Gt),rn=s=>s?Js:ia,za=(Kr.malformed||Kr.empty)&&(An||Gt),Ac=rn(za),Li=L.cardFormContainer?.backgroundColor??xc??(aa?"white":"#EDEDFF"),Mo=L.cardInputBackground??Ur?.colorBackground??"white",Ni=Fo(ke),Zs=Fo(Re),xo=L.nameInput,Qs=L.cardInputFontSize??jd(xo?.fontSize)??Ur?.fontSizeBase??"16px",el=typeof xo?.fontFamily=="string"?xo.fontFamily:Ur?.fontFamily??"Poppins, sans-serif",tl=(0,d.toCssWeight)(xo?.fontWeight)??400,Fc=L.cardInputColor??(typeof xo?.color=="string"?xo.color:void 0)??Ur?.colorText??"#262833",Bc=L.cardInputPlaceholderColor??"#9ca3af",Qt=Ur?.borderRadius??"8px",po=Ur?.borderRadius??L.cardButton?.borderRadius??Qt,mo=Ur?.colorPrimary??"#4A49FF",Dc=Ur?.colorPrimaryHover??(0,d.darkenHex)(mo,.12),Ui=Ur?.colorText??"#262833",zi={fontSize:Qs,fontFamily:el,fontWeight:tl,color:Fc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},sa={marginTop:"0.375rem",...zi,fontSize:"0.75rem",lineHeight:1.4,color:Js},Oc={"--flopay-input-placeholder-color":Bc,"--flopay-input-font-size":Qs,"--flopay-input-font-family":el,"--flopay-input-font-weight":String(tl)},la=L.cardFormContainer??{},qi=la.padding??(aa?"0":"1rem"),ji=la.borderRadius??Qt,Lc=Bt&&vn?(0,c.jsx)(lo,{capture:Bt,html:vn.html,messageToken:vn.messageToken,expectedOrigin:vn.expectedOrigin,verificationRequired:vn.verificationRequired,theme:yt,submitLabel:M,onReady:()=>{if(!ao&&!Ae||typeof document>"u")return;let s=()=>{let ce=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(ce){Gr.current=!0;try{ce.focus()}finally{Gr.current=!1}}};Pn.current||s()},onError:s=>{s&&vn.verificationRequired&&y.current==="idle"&&(oo.current=!0),Ne(s)},onValidation:s=>{let R=y.current;(R==="idle"||R==="validation-window")&&(Ne(s),s&&y.current==="validation-window"&&(W.current&&(clearTimeout(W.current),W.current=null),y.current="idle",X(null)))}},pr):(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,...Oc,display:"flex",flexDirection:"column"},children:[(0,c.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 @@ ${Ct.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),ia&&oo&&(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:Se,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.backButton},"aria-label":"Back to payment methods",children:[(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",...D.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)(Oo,{content:Re})]}),Js?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...D.title},children:(0,c.jsx)(ua,{content:_e})})]}),!ia&&!Js&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:zi,order:f?-3:0,...D.title},children:(0,c.jsx)(ua,{content:_e})}),f&&ee&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:ee}),f&&io&&(0,c.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,c.jsx)("div",{style:{backgroundColor:xo,border:`1px solid ${nn(za)}`,borderRadius:Qt,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:or,onChange:s=>{Nt("email"),ur.current=s.target.value,pn(s.target.value)},onPointerDown:()=>Nt("email"),onKeyDown:()=>Nt("email"),onBlur:()=>{Xr("email")&&tn(!0),ko||Ti()},disabled:et,required:!0,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...qi}})}),za&&(0,c.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:la,children:Ri.empty?"Email address is required":"Enter a valid email address"})]}),Ae&&(0,c.jsx)("div",{style:{order:f?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Ht,R=(oe=!1)=>({backgroundColor:xo,border:`1px solid ${nn(oe)}`,borderRadius:Qt,marginTop:"0.5rem",padding:"10px"}),ue=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...qi}),Ue=(0,u.getStateOptions)(s);return(0,c.jsxs)(c.Fragment,{children:[(0,u.isAVSFieldVisible)(Ae.address_line_1,s)&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{style:R(Jt("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:oe=>{Nt("line1"),qt.current.addressLine1=!0,mr.current=oe.target.value,mt(oe.target.value)},onPointerDown:()=>Nt("line1"),onKeyDown:()=>Nt("line1"),onBlur:()=>xr("line1"),disabled:et,required:!0,"aria-invalid":Jt("line1")||void 0,"aria-describedby":Jt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:ue()})}),Jt("line1")&&(0,c.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:la,children:"Street address is required"})]}),(0,u.isAVSFieldVisible)(Ae.address_line_2,s)&&(0,c.jsx)("div",{style:R(),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:it,onChange:oe=>{qt.current.addressLine2=!0,jt.current=oe.target.value,Br(oe.target.value)},disabled:et,"data-testid":"flopay-address-line2",style:ue()})}),((0,u.isAVSFieldVisible)(Ae.city,s)||(0,u.isAVSFieldVisible)(Ae.state,s))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(Ae.city,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${nn(Jt("city"))}`,borderRight:`1px solid ${nn(Jt("city"))}`,borderBottom:`1px solid ${nn(Jt("city"))}`,borderLeft:`1px solid ${nn(Jt("city"))}`,padding:"10px",borderTopLeftRadius:Qt,borderBottomLeftRadius:Qt,...(0,u.isAVSFieldVisible)(Ae.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Qt}},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:oe=>{Nt("city"),qt.current.city=!0,Sr.current=oe.target.value,Hr(oe.target.value)},onPointerDown:()=>Nt("city"),onKeyDown:()=>Nt("city"),onBlur:()=>xr("city"),disabled:et,required:!0,"aria-invalid":Jt("city")||void 0,"aria-describedby":Jt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:ue()})}),(0,u.isAVSFieldVisible)(Ae.state,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${nn(Jt("state"))}`,borderRight:`1px solid ${nn(Jt("state"))}`,borderBottom:`1px solid ${nn(Jt("state"))}`,borderLeft:`1px solid ${nn(Jt("state"))}`,padding:"10px",borderTopRightRadius:Qt,borderBottomRightRadius:Qt,...(0,u.isAVSFieldVisible)(Ae.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${nn(Jt("state")||Jt("city"))}`}:{borderRadius:Qt}},children:Ue?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Cr,onChange:oe=>{Nt("state"),qt.current.state=!0,Vt.current=oe.target.value,Kt(oe.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>xr("state"),disabled:et,autoComplete:"billing address-level1",required:!0,"aria-invalid":Jt("state")||void 0,"aria-describedby":Jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...ue(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,u.getStateLabel)(s)}),Ue.map(oe=>(0,c.jsx)("option",{value:oe.code,children:oe.name},oe.code))]}):(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,u.getStateLabel)(s),autoComplete:"billing address-level1",value:Cr,onChange:oe=>{Nt("state"),qt.current.state=!0,Vt.current=oe.target.value,Kt(oe.target.value)},onPointerDown:()=>Nt("state"),onKeyDown:()=>Nt("state"),onBlur:()=>xr("state"),disabled:et,required:!0,"aria-invalid":Jt("state")||void 0,"aria-describedby":Jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:ue()})})]}),Jt("city")&&(0,c.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:la,children:"City is required"}),Jt("state")&&(0,c.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:la,children:[(0,u.getStateLabel)(s)," is required"]}),((0,u.isAVSFieldVisible)(Ae.country,s)||(0,u.isAVSFieldVisible)(Ae.postal_code,s))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:ye==="column"?"column":"row",gap:ye==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(Ae.country,s)&&(0,c.jsx)("div",{style:{flex:ye==="row"?1:void 0,backgroundColor:xo,borderTop:`1px solid ${sa}`,borderRight:`1px solid ${sa}`,borderBottom:`1px solid ${sa}`,borderLeft:`1px solid ${sa}`,padding:"10px",...ye==="row"&&(0,u.isAVSFieldVisible)(Ae.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:Qt,borderBottomLeftRadius:Qt,borderRight:"none"}:{borderRadius:Qt}},children:(0,c.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Ht,onChange:oe=>{qt.current.country=!0,Tr.current=oe.target.value,$r(oe.target.value),Ge?.(oe.target.value),Vt.current="",Kt("")},disabled:et,autoComplete:"billing country","data-testid":"flopay-country",style:{...ue(),cursor:"pointer"},children:[Ht===""?(0,c.jsx)("option",{value:"",children:"Select country"}):null,u.COUNTRY_OPTIONS.map(oe=>(0,c.jsxs)("option",{value:oe.code,children:[oe.flag," ",oe.name]},oe.code))]})}),(0,u.isAVSFieldVisible)(Ae.postal_code,s)&&(0,c.jsx)("div",{style:{flex:ye==="row"?1:void 0,backgroundColor:xo,border:`1px solid ${Mc}`,padding:"10px",...ye==="row"&&(0,u.isAVSFieldVisible)(Ae.country,s)?{borderRadius:"0",borderTopRightRadius:Qt,borderBottomRightRadius:Qt}:{borderRadius:Qt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,u.getPostalCodeLabel)(Ht),autoComplete:"billing postal-code",value:Wr,onChange:oe=>{Nt("zip"),qt.current.zip=!0,zt.current=oe.target.value,Rr(oe.target.value),$e?.(oe.target.value)},onPointerDown:()=>Nt("zip"),onKeyDown:()=>Nt("zip"),onBlur:()=>{Xr("zip")&&Lr(!0)},disabled:et,required:Gr.required,"aria-invalid":qa||void 0,"aria-describedby":qa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:ue()})})]}),qa&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:la,children:Gr.empty?`${(0,u.getPostalCodeLabel)(s)} is required`:Ld(s)})]})})()}),f&&Dc,wt&&(0,c.jsx)($o,{margin:"0.75rem 0",styleOverride:D.errorBanner,children:wt})]}),ja={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"},rl=s=>G?!v||!Nn?(0,c.jsx)("pre",{"data-testid":s,style:ja,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:ja,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${v}`,` directPaypalConfigured=${Nn}`,` inAppBrowserDetected=${String(La)}`,` shouldRenderDirectPayPal=${ta}`,` shouldRenderStripePayPal=${na}`,` hasPaypalStripeInstance=${!!Ss}`].join(`
39
- `)}):null,nl=s=>G?!te||!Jr?(0,c.jsx)("pre",{"data-testid":s,style:ja,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":s,style:ja,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${te}`,` currency=${Et}`,` amountInCents=${Qo}`,` enabledPaymentMethods: ${JSON.stringify(Pe??[])}`,` enabledPaymentMethodsProvided=${ea}`,` hasEnabledMethods=${Fa}`,` expressMethods: ${JSON.stringify(Da)}`,` walletExpressMethods: ${JSON.stringify(To)}`,` paymentElementMethods: ${JSON.stringify(xi)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Oa)}`,` hasStripeInstance=${!!Jr}`,` shouldRenderWallets=${Mo}`,` shouldRenderPaymentElement=${oa}`].join(`
40
- `)}):null,ol=bt==="apm-expanding"||bt==="apm-form"||bt==="apm-collapsing",Fo;bt==="apm-expanding"?Fo=Nl:bt==="apm-collapsing"&&(Fo=Ul);let Va=yr?Yl(Ai,yr,A):null;if(se==="buttons"){let s=bt==="buttons"||bt==="expanding"||bt==="apm-expanding",R=bt==="expanding"||bt==="card"||bt==="collapsing",ue=Ke===void 0?{boxSizing:"border-box",height:Yo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ue;bt==="expanding"||bt==="apm-expanding"?Ue=Fd:(bt==="collapsing"||bt==="apm-collapsing")&&(Ue=Ad);let oe;return bt==="expanding"?oe=Nl:bt==="collapsing"&&(oe=Ul),(0,c.jsxs)("form",{onSubmit:Oi,className:O,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Xo,{}),Oe&&(0,c.jsx)(qr,{status:Oe,errorMessage:wt,authorized:yn}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Ue?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Ue?Dd:{},...Ue?{animation:Ue,pointerEvents:"none"}:{}},children:[rl("flopay-direct-paypal-gate-debug"),nl("flopay-stripe-gate-debug"),ta&&kt&&(0,c.jsxs)(c.Fragment,{children:[Fe&&(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)(fa.Provider,{value:m,children:(0,c.jsx)(ha,{sessionId:e,nonce:t,billingApiUrl:ht,email:Pt.email,billingName:wo||void 0,onBuyerIdentityReady:ot,clientId:kt.clientId,environment:kt.environment,currency:Et.toUpperCase(),isSubscription:At,providerObjectType:ne,approvalPresentation:Na==="popup"?void 0:Na,onTokenizedBody:Ur,onComplete:l,onErrorChange:Le,onDecline:p,onTechnicalFailure:Io,onButtonClick:re,runBeforeButtonClick:wn,isProcessing:et,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:T,existingOrderId:Fe?.orderId,debug:G},Fe?.orderId??"fresh")})]}),na&&(0,c.jsx)(er.Elements,{stripe:ra,options:Rs,children:(0,c.jsx)(ql,{sessionId:e,nonce:t,email:Pt.email,billingName:wo||void 0,onBuyerIdentityReady:ot,billingApiUrl:ht,onTokenizedBody:Ur,onErrorChange:Le,isProcessing:et,onButtonClick:re,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:wn,onLoadStateChange:Bs,placeholderBorderRadius:mo,popupCapabilityOwner:m,externalTelemetryContext:Vs,presentationMode:_o})}),Mo?(0,c.jsx)(er.Elements,{stripe:Jr,options:ks,children:(0,c.jsx)(Vl,{sessionId:e,nonce:t,email:Pt.email,billingName:wo||void 0,onBuyerIdentityReady:ot,billingApiUrl:ht,intentKind:We>0?"payment":"setup",expressMethods:To,onTokenizedBody:Ur,onErrorChange:Le,onButtonClick:re,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:wn,onLoadStateChange:Os,placeholderBorderRadius:mo,popupCapabilityOwner:m,externalTelemetryContext:he})}):null,!Mo&&qs?(0,c.jsx)("div",{style:{height:Yo,borderRadius:mo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,oa&&(0,c.jsx)($l,{sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ot,billingApiUrl:ht,paymentElementMethods:Oa,stripeInstance:Jr,paymentElementBaseOptions:Ai,futureUseSession:A,onTokenizedBody:Ur,onErrorChange:Le,onButtonClick:re,onDecline:p,runBeforeButtonClick:wn,onLoadStateChange:Ns,isProcessing:et,submitButtonColor:yo,submitButtonBorderRadius:Qt,submitButtonStyle:D.submitButton,onExpandApm:It,expandedApmMethod:yr,themeId:je,buttonAppearance:{backgroundColor:D.cardButton?.backgroundColor,borderColor:D.cardInputBorder,textColor:D.cardButton?.color,borderRadius:mo}}),f&&(0,c.jsx)("button",{type:"button",onClick:async()=>{et||!(await wn("card")).proceed||(re?.("card"),ce())},disabled:et,style:{width:"100%",...ue,...D.cardButton,...us({themeBundle:we,resolvedPrimaryColor:yo,resolvedBorderRadius:Qt,submitButtonStyle:D.submitButton,explicitPrimaryColor:zr?.colorPrimary}),fontSize:D.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:Ie=>{!et&&(we||zr?.colorPrimary)&&(Ie.currentTarget.style.backgroundColor=Fc)},onMouseLeave:Ie=>{(we||zr?.colorPrimary)&&(Ie.currentTarget.style.backgroundColor=yo)},onMouseDown:Ie=>{Ie.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ie=>{Ie.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(Do,{content:Ke})}),wt&&bt==="buttons"&&(0,c.jsx)($o,{margin:"0.25rem 0",styleOverride:D.errorBanner,children:wt})]}),f&&R&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...oe?{animation:oe}:{},...bt==="collapsing"?{pointerEvents:"none"}:{}},children:tl}),te&&ol&&yr&&Va&&Jr&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...Fo?{animation:Fo}:{},...bt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji},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:Yt,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.backButton},"aria-label":"Back to payment methods",children:[(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",...D.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)(Oo,{content:Re})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:zi,paddingRight:80,...D.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(yr)}`})]}),(0,c.jsx)(er.Elements,{stripe:Jr,options:Va,children:(0,c.jsx)(ls,{method:yr,sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ot,billingApiUrl:ht,onTokenizedBody:Ur,onErrorChange:Le,onDecline:p,onCancel:Yt,runBeforeButtonClick:wn,onButtonClick:re,isProcessing:et,submitButtonColor:yo,submitButtonBorderRadius:Qt,submitButtonStyle:D.submitButton,errorText:wt})},yr)]})})]})]})}return ol&&yr&&Va&&Jr&&te?(0,c.jsxs)("form",{onSubmit:Oi,className:O,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Xo,{}),Oe&&(0,c.jsx)(qr,{status:Oe,errorMessage:wt,authorized:yn}),(0,c.jsx)("div",{style:{...Fo?{animation:Fo}:{},...bt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:Ni,borderRadius:Vi,...ca,padding:ji},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:Yt,style:{display:"inline-flex",alignItems:"center",gap:Ui?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:D.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...D.backButton},"aria-label":"Back to payment methods",children:[(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",...D.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)(Oo,{content:Re})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:D.titleFontSize??"1.05rem",color:zi,paddingRight:80,...D.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(yr)}`})]}),(0,c.jsx)(er.Elements,{stripe:Jr,options:Va,children:(0,c.jsx)(ls,{method:yr,sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ot,billingApiUrl:ht,onTokenizedBody:Ur,onErrorChange:Le,onDecline:p,onCancel:Yt,runBeforeButtonClick:wn,onButtonClick:re,isProcessing:et,submitButtonColor:yo,submitButtonBorderRadius:Qt,submitButtonStyle:D.submitButton,errorText:wt})},yr)]})})]}):(0,c.jsxs)("form",{onSubmit:Oi,className:O,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Xo,{}),Oe&&(0,c.jsx)(qr,{status:Oe,errorMessage:wt,authorized:yn}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[rl("flopay-direct-paypal-gate-debug-default"),nl("flopay-stripe-gate-debug-default"),ta&&kt&&(0,c.jsxs)(c.Fragment,{children:[Fe&&(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)(fa.Provider,{value:m,children:(0,c.jsx)(ha,{sessionId:e,nonce:t,billingApiUrl:ht,email:Pt.email,billingName:wo||void 0,onBuyerIdentityReady:ot,clientId:kt.clientId,environment:kt.environment,currency:Et.toUpperCase(),isSubscription:At,providerObjectType:ne,approvalPresentation:Na==="popup"?void 0:Na,onTokenizedBody:Ur,onComplete:l,onErrorChange:Le,onDecline:p,onTechnicalFailure:Io,onButtonClick:re,runBeforeButtonClick:wn,isProcessing:et,onLoadStateChange:Fi,onInitializationStateChange:Bi,session:T,existingOrderId:Fe?.orderId,debug:G},Fe?.orderId??"fresh")})]}),na&&(0,c.jsx)(er.Elements,{stripe:ra,options:Rs,children:(0,c.jsx)(ql,{sessionId:e,nonce:t,email:Pt.email,billingName:wo||void 0,onBuyerIdentityReady:ot,billingApiUrl:ht,onTokenizedBody:Ur,onErrorChange:Le,isProcessing:et,onButtonClick:re,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:wn,onLoadStateChange:Bs,placeholderBorderRadius:mo,popupCapabilityOwner:m,externalTelemetryContext:Vs,presentationMode:_o})}),Mo&&(0,c.jsx)(er.Elements,{stripe:Jr,options:ks,children:(0,c.jsx)(Vl,{sessionId:e,nonce:t,email:Pt.email,billingName:wo||void 0,onBuyerIdentityReady:ot,billingApiUrl:ht,intentKind:We>0?"payment":"setup",expressMethods:To,onTokenizedBody:Ur,onErrorChange:Le,onButtonClick:re,onDecline:p,onTechnicalFailure:Io,runBeforeButtonClick:wn,onLoadStateChange:Os,placeholderBorderRadius:mo,popupCapabilityOwner:m,externalTelemetryContext:he})}),oa&&(0,c.jsx)($l,{sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ht,paymentElementMethods:Oa,stripeInstance:Jr,paymentElementBaseOptions:Ai,futureUseSession:A,onTokenizedBody:Ur,onErrorChange:Le,onButtonClick:re,onDecline:p,runBeforeButtonClick:wn,onLoadStateChange:Ns,isProcessing:et,submitButtonColor:yo,submitButtonBorderRadius:Qt,submitButtonStyle:D.submitButton,themeId:je,onExpandApm:It,expandedApmMethod:yr,buttonAppearance:{backgroundColor:D.cardButton?.backgroundColor,borderColor:D.cardInputBorder,textColor:D.cardButton?.color,borderRadius:mo}})]}),f&&(Ec||Rc||Ic)&&(0,c.jsx)(ci,{label:"or pay with card"}),f&&tl]})}var F=require("react/jsx-runtime"),Jo=44,hs="flopay_checkout_saved_payment_resume",Pi=new Map,gi=new Map;function Xl(e,t){t.settled&&t.consumers===0&&Pi.get(e)===t&&Pi.delete(e)}function jd(e,t,r){let n=gi.get(e);if(n&&(!n.sdkGeneratedIdempotencyKey||!t||n.sdkGeneratedIdempotencyKey===t))return n.attempt;let o=r(),i={attempt:o,sdkGeneratedIdempotencyKey:t};gi.set(e,i);let l=()=>{gi.get(e)===i&&gi.delete(e)};return o.then(l,l),o}function Ta(e){return new Promise(t=>setTimeout(t,e))}function hi(e,t,r){let n=Ja({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ze.SDK_VERSION,enabled:t!==!1});return n.beginCheckout(r),n}function Ma(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ps(e,t,r,n,o,i){let l=hi(e,t,r);l.error({errorCode:n,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),Ma(l)}function Jl(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 Zl(e,t,r,n,o){let i=(0,ze.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 ze.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof ze.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,ze.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var Vd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function $d(e){return new to.FloPay(Vd,{publishableKey:"provider_unavailable",...e})}async function ys(e,t){let{publishableKey:r,paypalPublishableKey:n}=Qi(e);return{...await es({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 Ql(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 ec(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,ze.resolveCheckoutLogLayout)(!!e,t)}function Kd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function tc(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 vi({sessionId:e,nonce:t,createSession:r,billingApiUrl:n,telemetry:o,appearance:i,locale:l,loading:d,error:p,onComplete:b,onError:k,onInstrument:w,onDecline:x,onCountryChange:O,onZipChange:M,showPayPal:W=!0,showStripe:_=!0,walletPresentation:h="auto",enabledPaymentMethods:v,showApplePay:te=!0,showGooglePay:S=!0,debug:Pe=!1,layout:j,theme:Q,buttonsTheme:Be,buttonsStyles:se,cardButtonContent:je,cardBackButtonContent:Je,cardTitleContent:me,showSecurityFooter:pe,onButtonClick:Ke,onBeforeButtonClick:Re,enableAVS:_e,cardFieldOrder:Ee,cardPreFormSlot:re,avsLayout:ae,submitLabel:ge,className:Me,initialErrorMessage:K=null,initialPayPalOrderId:ee,children:ye,checkoutMode:L,confirmLabel:ve,renderConfirmButton:Y,onSessionCompleted:be}){let X=(0,ze.resolveBillingApiUrl)(n),ct=(0,C.useMemo)(()=>(0,ze.resolveTheme)(Q),[Q]),Ge=i??ct?.appearance,$e=r?"embedded_checkout":"standard_checkout",lt=gs(ye,j),[Ye,dt]=(0,C.useState)(null),[We,Et]=(0,C.useState)(null),Ut=(0,C.useRef)(null),kt=(0,C.useRef)(null),At=(0,C.useRef)(0),[N,fe]=(0,C.useState)(null),Qe=(0,C.useRef)(null),[G,Ne]=(0,C.useState)(null),Rt=(0,C.useMemo)(()=>r?(0,ut.serializeCreateParams)(r):"",[r]),Ze=r?`create:${Rt}`:`session:${e??""}`,Tt=tc(G),U=(0,C.useRef)(new Set),m=(0,C.useRef)(Ze),P=(0,C.useRef)(Ze);vo(()=>{P.current=Ze,m.current!==Ze&&(m.current=Ze,U.current.clear())},[Ze]);let H=(0,C.useCallback)(z=>{if(P.current===Ze){if(Xi.FLO_INSTRUMENT_ONCE_NAMES.has(z.name)){if(U.current.has(z.name))return;U.current.add(z.name)}(0,tt.invokeMerchantCallback)(()=>w?.(z))}},[Ze,w]),V=Vo(H,Ze),he=(0,C.useRef)(!1),T=(0,C.useCallback)(z=>{if(he.current)return;let B=z.gateway||!Tt?z:{...z,gateway:Tt};H(B)},[H,Tt]);(0,C.useEffect)(()=>{V({class:"lifecycle",name:"checkout.mount"})},[V]);let[A,ne]=(0,C.useState)(e??""),q=e??A,Ce=r?"":q,[rt,Ct]=(0,C.useState)(!0),[ht,xe]=(0,C.useState)(null),[Fr,Vr]=(0,C.useState)(0),[br,Ht]=(0,C.useState)("full"),[$r,Wr]=(0,C.useState)(!1),[Rr,Lt]=(0,C.useState)(K),[mt,it]=(0,C.useState)(null),[Br,Bt]=(0,C.useState)(null),[Hr,Cr]=(0,C.useState)(!1),[Kt,or]=(0,C.useState)(void 0),[pn,en]=(0,C.useState)(""),[ar,zt]=(0,C.useState)(!1),[Tr,mr]=(0,C.useState)(!1),[jt,Sr]=(0,C.useState)(!1),Vt=(0,C.useRef)(null),ur=(0,C.useRef)(0),qt=(0,C.useRef)(void 0),[Ae,mn]=(0,C.useState)("loading"),[yn,fn]=(0,C.useState)(0),ir=(0,C.useRef)(!1),Dr=(0,C.useRef)(!1),Mr=(0,C.useRef)(!1),De=(0,C.useRef)(null),vt=(0,C.useRef)(null),f=(0,C.useMemo)(()=>({checkoutMode:L??br,layout:Kd(ye,j)}),[L,ye,br,j]),nt=(0,C.useRef)(b);nt.current=b;let ie=(0,C.useRef)(k);ie.current=k;let Er=(0,C.useRef)(x);Er.current=x;let Kr=(0,C.useCallback)(z=>ei(De,async B=>{try{return await z(B)}catch(ce){throw B.aborted?Wo(ce):ce}}),[]);(0,C.useEffect)(()=>()=>{De.current?.abort(),De.current=null},[]);let Zt=(0,C.useCallback)((z,B)=>{Ut.current=z,Et(z),Qe.current=B,fe(B)},[]),Or=(0,C.useCallback)(()=>{let z=kt.current;z&&(kt.current=null,z.destroy())},[]);(0,C.useEffect)(()=>{hr(We)?.setCheckoutContext(f),N&&N!==We&&hr(N)?.setCheckoutContext(f)},[We,N,f]);let St=(0,C.useRef)(be);St.current=be;let xn=(0,C.useCallback)(z=>{mn(z),!(z!=="exhausted"||Mr.current)&&(Mr.current=!0,ie.current?.(new ze.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),no=(0,C.useCallback)(()=>{mn("retrying"),fn(z=>z+1)},[]);(0,C.useEffect)(()=>{mn("loading"),fn(0),Mr.current=!1},[q]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ze.SDK_VERSION,checkout_type:$e,checkout_layout:lt,billing_api_url:X})},[lt,$e,X]);let Dt=(0,C.useMemo)(()=>r?(0,ut.serializeCreateParams)(r,!0):"",[r]),Gr=(0,C.useMemo)(()=>pn===Dt?Kt:void 0,[Kt,pn,Dt]),gn=(0,C.useMemo)(()=>r?Hi(r,Gr):void 0,[r,Gr]),hn=L??gn?.checkoutMode??"full",Gt=(0,C.useMemo)(()=>gn?{...gn,checkoutMode:hn}:void 0,[gn,hn]);(0,C.useEffect)(()=>{or(void 0),en(Dt),qt.current=void 0,Vt.current=null,Sr(!1)},[Dt]),(0,C.useEffect)(()=>{Lt(K)},[K]);let An=(0,C.useCallback)((z,B,ce)=>{(0,tt.invokeMerchantCallback)(()=>{Er.current?.(gr(z,B,ce))})},[]),Fn=(0,C.useCallback)(async(z,B)=>{Lt(null),Bt(null),Cr(!1),it("processing");let ce=B?.sessionId??z.id,Se=z.clientSecret||t,It=tc(z),Yt=Ut.current??Qe.current,Oe=hr(Yt),J=Yt?null:hi(X,o,f),Z={log:Te=>{Oe?Oe.log(Te):J?.log(Te)},error:Te=>{Oe?Oe.error(Te):J?.error(Te)},terminal:Te=>{Oe?Oe.terminal(Te):J?.terminal(Te)},performance:Te=>{Oe?Oe.performance(Te):J?.performance(Te)},now:()=>Oe?.now()??J?.now()??0,elapsed:Te=>Oe?.elapsed(Te)??Math.max(0,(J?.now()??Te)-Te)},$=Z.now(),y=!!(B?.initialAutoProcessingError||B?.initialAutoProcessingPending),g=!1,E,de=()=>{g||(g=!0,y=!0,E=Z.now(),Z.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),Z.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Fe=!1,He=()=>{Fe||(Fe=!0,Z.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),Z.performance({stage:"processing",durationMs:Z.elapsed($),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),E!==void 0&&Z.performance({stage:"recovery",durationMs:Z.elapsed(E),durationMode:"machine",paymentMethodCategory:"saved"}))};Z.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),he.current=!0;try{Z.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{he.current=!1}V({class:"lifecycle",name:"payment.processing.started",provider:It}),y&&de();let Xt;try{let Te=_l(B?.initialAutoProcessingError),Xe=B?.initialAutoProcessingError?.type==="3ds_required"&&!B.initialAutoProcessingError.threeDSecureToken&&B.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:B.initialAutoProcessingError.nextActionRedirectUrl}:null,ot,wt=we=>(de(),Kr(D=>Ho(we,{billingApiUrl:X,sessionId:ce,nonce:Se,session:z,signal:D})));if(Xe)ot=await wt(Xe);else if(Te)de(),Te.type==="paypal_redirect_required"&&vt.current?.publishableKey&&Ql({sessionId:ce,publishableKey:vt.current.publishableKey,paypalPublishableKey:vt.current.paypalPublishableKey}),ot=await Kr(we=>ri(Te,{flopay:Ut.current,paypalFlopay:Qe.current,attempt3DS:B?.attempt3DS,billingApiUrl:X,sessionId:ce,session:z,telemetry:!1,signal:we})),Te.type==="paypal_redirect_required"&&fs();else if(B?.initialAutoProcessingPending){let we=B.initialAutoProcessingPending,D=new to.PaymentAPI(X,{telemetry:!1}),le=await Kr(et=>D.waitForCheckoutSessionCompletion(we.sessionId,{initialDelayMs:we.retryAfterMs,nonce:Se,statusUrl:we.statusUrl,signal:et})),yt=lo(le,z),Ve=le.autoProcessingError?.type==="3ds_required"&&le.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:le.autoProcessingError.nextActionRedirectUrl}:null;if(Ve)ot=await wt(Ve);else{if(!Xn(yt))throw No(yt);ot=Yn(yt,ce)}}else{if(B?.initialAutoProcessingError)throw jn(B.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:B.initialAutoProcessingError.checkoutMethod});if(B?.fromCreateSession)return B?.fallbackToFull&&(Ht("full"),ec("full")),!1;{let we=await Ko({billingApiUrl:X,sessionId:ce,session:z,nonce:Se,telemetry:!1});we.type==="success"?ot=we.result:we.type==="next_action_required"?ot=await wt(we):(de(),we.type==="paypal_redirect_required"&&vt.current?.publishableKey&&Ql({sessionId:ce,publishableKey:vt.current.publishableKey,paypalPublishableKey:vt.current.paypalPublishableKey}),ot=await Kr(D=>ri(we,{flopay:Ut.current,paypalFlopay:Qe.current,attempt3DS:B?.attempt3DS,billingApiUrl:X,sessionId:ce,session:z,telemetry:!1,signal:D})),we.type==="paypal_redirect_required"&&fs())}}ce&&(0,_n.markSessionRecentlyCompleted)(ce),He(),y&&(Z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),Z.terminal({outcome:ot.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Cr(ot.status==="authorized"),it("success"),await Ta(600),Xt=()=>nt.current?.(ot)}catch(Te){let Xe=so(Sa(Te),ce);if(Xe.code==="three_ds_aborted")return!1;let ot=Xe.checkoutMethod??Ca;Lt(Xe.message),Bt(Xe.message),Cr(!1),B?.fallbackToFull&&(Z.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Ht("full"),ec("full")),He();let wt=Xe.statusCode===void 0?void 0:(0,ze.telemetryStatusClass)(Xe.statusCode,"unknown"),we=wt==="4xx"?{requestCategory:"process_payment",statusClass:wt}:{},D=wt===void 0||wt==="4xx";if(D&&(Xe.telemetryOutcome==="payment_declined"||!!(Xe.declineCode||Xe.code?.toLowerCase().includes("declin"))))Z.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...we});else if(D&&(Xe.telemetryOutcome==="validation_rejected"||Xe.type==="validation_error"))Z.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...we});else{let Ve=(0,ze.classifyTelemetryFailure)(Te,y?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),et=Xe.telemetryRequestCategory??"process_payment";he.current=!0;try{Z.error({...Ve,...Xe.telemetryFailureCategory?{failureCategory:Xe.telemetryFailureCategory}:{},stage:y?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:et})}finally{he.current=!1}V({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:et,provider:It})}return(0,tt.invokeMerchantCallback)(()=>ie.current?.(Xe)),An(ot,Xe,{code:Xe.code,declineCode:Xe.declineCode}),it("error"),await Promise.allSettled([Ta(400),B?.ensureProvidersReady?B.ensureProvidersReady():Promise.resolve()]),y&&(Z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{He(),J&&Ma(J),it(null),Bt(null)}return(0,tt.invokeMerchantCallback)(Xt),!0},[An,V,t,X,Kr,o,f]);(0,C.useEffect)(()=>{if(typeof window>"u"||Dr.current)return;let z=new URLSearchParams(window.location.search),B=z.get("payment_intent_client_secret");if(!B)return;let ce=Wd();ce&&(Dr.current=!0,(async()=>{let Se,It=0;Lt(null),Bt(null),it("processing"),Wr(!0);try{if(z.get("redirect_status")==="failed")throw Object.assign(new ze.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Yt,paypalFlopay:Oe}=await es({publishableKey:ce.publishableKey,paypalPublishableKey:ce.paypalPublishableKey,billingApiUrl:X,locale:l,telemetry:o});Se=hr(Oe??Yt),Se?.setCheckoutContext(f),It=Se?.now()??0,Se?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Se?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let J=(Oe??Yt)?.getRawProvider();if(!J)throw Object.assign(new ze.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:Z,error:$}=await J.retrievePaymentIntent(B);if($)throw Object.assign(new ze.FloPayError($.message??"Failed to retrieve PayPal payment status.","api_error",{code:$.code}),{checkoutMethod:"paypal"});let y=yl(Z?.status);if(!Z||y==="failed")throw Object.assign(new ze.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let g=typeof Z.payment_method=="string"?Z.payment_method:Z.payment_method?.id,E=y;if(ce.sessionId){let He=(await new to.PaymentAPI(X,{telemetry:!1}).getUnifiedCheckoutSession(ce.sessionId)).data.session;if(He&&He.status!=="complete"){let Xt=await Ko({billingApiUrl:X,sessionId:ce.sessionId,session:He,telemetry:!1,tokenizedData:{id:g??Z.id,type:"card",threeDSecureActionResultTokenId:Z.id,isPaypal:!0}});if(Xt.type!=="success")throw Object.assign(new ze.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});E=Xt.result.status}}ce.sessionId&&(0,_n.markSessionRecentlyCompleted)(ce.sessionId),Se?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Se?.performance({stage:"redirect_resume",durationMs:Se.elapsed(It),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Se?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),it("success"),await Ta(600),(0,tt.invokeMerchantCallback)(()=>nt.current?.({status:E,paymentIntentId:Z.id,paymentMethodId:g,checkoutMethod:"paypal"}))}catch(Yt){let Oe=so(Sa(Yt),ce.sessionId),J=Oe.checkoutMethod??"paypal",Z=!!(Oe.declineCode||Oe.code?.toLowerCase().includes("declin"));if(Se)Se.performance({stage:"redirect_resume",durationMs:Se.elapsed(It),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Z?Se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Se.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(Z){let $=hi(X,o,f);$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ma($)}else ps(X,o,f,"REDIRECT_RESUME_FAILED","redirect_resume");Lt(Oe.message),Bt(Oe.message),(0,tt.invokeMerchantCallback)(()=>ie.current?.(Oe)),An(J,Oe,{code:Oe.code,declineCode:Oe.declineCode}),it("error"),await Ta(400)}finally{fs(),Hd(),it(null),Bt(null),Wr(!1)}})())},[An,l,X,o,f]);let Lr=(0,C.useRef)(null),Bn=(0,C.useMemo)(()=>Gt?(0,ut.serializeCreateParams)(Gt):"",[Gt]),tn=(0,C.useRef)(Gt);tn.current=Gt,(0,C.useEffect)(()=>{ne(e??"")},[e]),(0,C.useEffect)(()=>{ir.current=!1,Lt(K),Bt(null),Cr(!1),it(null)},[Bn,K,e]);async function Dn(z,B,ce){let Se=hi(X,o,f),It=new to.PaymentAPI(X,{telemetry:!1}),Yt=!1;try{let Oe=z.idempotencyKey===void 0?void 0:(0,ze.resolveIdempotencyKey)(z.idempotencyKey),J=(0,ut.readCachedInlineSession)(B,ce),Z=(0,ut.readCachedInlineIdempotencyKey)(B,ce);J?.canonicalIdentity===ce&&Z&&Z.canonicalIdentity===void 0&&((0,ut.persistCachedInlineIdempotencyKey)(B,ce,Z.idempotencyKey),Z={...Z,canonicalIdentity:ce});let $=Oe??(Z?.canonicalIdentity===ce?Z.idempotencyKey:void 0),y,g=!1;Se.log({name:J?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let E=J?.sid??null,de=null,Fe,He,Xt=!1;if(E)try{de=await It.getUnifiedCheckoutSession(E,J?.nonce),J&&J.canonicalIdentity===void 0&&((0,ut.legacyCachedSessionMatchesDraft)(de.data.session,z)?((0,ut.persistCachedInlineSession)(B,ce,E,J.nonce??de.data.session?.clientSecret),Z&&Z.canonicalIdentity===void 0&&((0,ut.persistCachedInlineIdempotencyKey)(B,ce,Z.idempotencyKey),$??($=Z.idempotencyKey))):((0,ut.clearCachedInlineCheckout)(B,ce),Z=null,$=Oe,E=null,de=null));let Xe=de?.data.session?.status,ot=de?.data.session,wt=ot?.clientSecret||J?.nonce;if(E&&ot?.buyerIdentified===!1&&wt&&(He=Lo(It,E,wt,z.account)),E&&de&&Xe==="complete"){if((0,_n.wasSessionRecentlyCompleted)(E))return{sid:E,result:de};(0,ut.clearCachedInlineCheckout)(B,ce),E=null,de=null,g=!0}}catch{Se.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),J?.canonicalIdentity===void 0?((0,ut.clearCachedInlineCheckout)(B,ce),$=Oe):(0,ut.clearCachedInlineSession)(B,ce),E=null}if(!E){!Oe&&(g||!$)&&($=(0,ze.resolveIdempotencyKey)(),y=$),$&&(0,ut.persistCachedInlineIdempotencyKey)(B,ce,$);let Xe=Se.now(),ot=0;Se.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let wt={...z,idempotencyKey:$,avsCheck:!!_e,avsConfig:typeof _e=="object"?_e:void 0,checkoutType:"embedded_checkout",checkoutLayout:gs(ye,j)};Object.defineProperty(wt,to.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:le=>{ot=Math.max(ot,le)}}});let we=()=>{Jl(Se,"session_create",Xe,ot)},D=le=>{Zl(Se,le,"session_create",Xe,ot)&&V({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,ze.isDetachedSessionEligible)(wt)){let le=await It.createDetachedSession(wt);le.claimed.catch(()=>{}),de=le.shell,E=le.sessionId,He=le.claim;let yt=Se.now();Se.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Fe=le.claimed.then(Ve=>{let et=Ve.data.session?.id??le.sessionId;return et&&(0,ut.persistCachedInlineSession)(B,ce,et,Ve.data.session?.clientSecret??le.nonce),Jl(Se,"session_claim",yt),we(),Ve},Ve=>{throw(0,ut.clearCachedInlineSession)(B,ce),Zl(Se,Ve,"session_claim",yt,0)&&V({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Ve}).finally(()=>Ma(Se)),Fe.catch(()=>{}),Yt=!0,Se.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Se.performance({stage:"session_shell",durationMs:Se.now()-Xe,durationMode:"machine",requestCategory:"session_create",attempt:ot,statusClass:"2xx",paymentMethodCategory:"card"})}else de=await It.createAndFetchSession(wt),we()}catch(le){throw D(le),le}E=de.data.session?.id??E??"",E&&!Fe&&(0,ut.persistCachedInlineSession)(B,ce,E,de.data.session?.clientSecret)}let Te=de?.data.session;return!He&&E&&Te?.buyerIdentified===!1&&Te.clientSecret&&(He=Lo(It,E,Te.clientSecret,z.account)),{sid:E??"",result:de,sdkGeneratedIdempotencyKey:y,...Fe?{claimed:Fe}:{},...He?{claim:He}:{},...Xt?{claimRequiresIdentity:!0}:{}}}finally{Yt||Ma(Se)}}let Hn=(0,C.useRef)(Dn);vo(()=>{Hn.current=Dn},[Dn]);let Yr=(0,C.useCallback)(async(z,B)=>{let ce=tn.current;if(!ce)throw new ze.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Se=Hi(ce,z),It=(0,ut.serializeCreateParams)(Se),Yt=(0,ut.hashCreateParams)(Se),Oe=Pi.get(It);if(!Oe){let $={canonicalIdentity:It,promise:Hn.current(Se,Yt,It),consumers:0,settled:!1};Oe=$,Pi.set(It,$);let y=()=>{$.settled=!0,Xl(It,$)};$.promise.then(y,y)}Oe.consumers+=1;let J=!1,Z=()=>{J||(J=!0,Oe.consumers-=1,Xl(It,Oe))};B?.(Z);try{let $=await Oe.promise;Lr.current=It,z&&(en(Dt),or(Te=>ul(Te,z)));let{sid:y,result:g,claimed:E,claim:de,claimRequiresIdentity:Fe}=$;if(qt.current=de,Sr(Fe===!0),dt(g),g.data.session&&Ne(g.data.session),y&&ne(y),E){ur.current+=1;let Te=ur.current;Vt.current=E,mr(!0),E.then(Xe=>{ur.current===Te&&(Vt.current===E&&(Vt.current=null),dt(Xe),Xe.data.session&&Ne(Xe.data.session),mr(!1),Sr(!1))},Xe=>{ur.current===Te&&(Vt.current===E&&(Vt.current=null),mr(!1),Sr(!1),xe(Xe instanceof ze.FloPayError?Xe:new ze.FloPayError(Xe instanceof Error?Xe.message:"Failed to create session","api_error")))})}else ur.current+=1,Vt.current=null,mr(!1),Sr(!1);let{flopay:He,paypalFlopay:Xt}=await ys(g,{billingApiUrl:X,locale:l,telemetry:o});return Zt(He,Xt),Ct(!1),$}catch($){throw Lr.current===It&&(Lr.current=null),$}finally{B||Z()}},[Dt,Zt,l,X,o]),Pn=(0,C.useRef)(Fn);Pn.current=Fn;let vn=(0,C.useRef)(Yr);vn.current=Yr;let Nt=(0,C.useCallback)(async z=>{if(!Gd(z)||ar)return{sessionId:A,session:G};zt(!0);try{let B=await Yr(z);return{sessionId:B.sid,session:B.result.data.session??null}}finally{zt(!1)}},[Yr,ar,A,G]),Xr=(0,C.useCallback)(async z=>{let B=qt.current;if(!B)return;let ce=ur.current,Se=await B(z);ur.current===ce&&(dt(Se),Se.data.session&&Ne(Se.data.session))},[]),xr=(0,C.useCallback)(async()=>{await Vt.current},[]),bn=(0,C.useCallback)(async()=>(await xr(),{proceed:!0}),[xr]);(0,C.useEffect)(()=>{let z=!1,B,ce=++At.current;Or(),xe(null),Vr(0);let Se=()=>{z=!0,At.current===ce&&(At.current+=1,Or())},It=tn.current;if(Bn&&It)return Ht(hn),Ct(!1),Lr.current===Bn?Se:(Ne(pl(It,L)),(async()=>{let J=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Z=hn==="auto"&&!ir.current&&!J;Z&&(Lt(null),Bt(null),it("processing"));try{let $=await vn.current(void 0,de=>{B=de}),y=$.result.data.session??null;vt.current=Qi($.result);let g=ms($.result),E=(0,_n.wasSessionRecentlyCompleted)($.sid||y?.id);if(!z&&Z&&y&&!g&&!E){ir.current=!0,await jd(Bn,$.sdkGeneratedIdempotencyKey,()=>Pn.current(y,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:$.result.autoProcessingError,initialAutoProcessingPending:$.result.autoProcessingPending,autoProcessingAttempted:$.result.autoProcessingAttempted,sessionId:$.sid||y.id}));return}!z&&Z&&((g||E)&&(ir.current=!0),it(null),Bt(null))}catch($){if(z)return;let y=Ha($);if(Z&&y==="session_auto_completed"){ir.current=!0,it("success"),await Ta(600),z||((0,tt.invokeMerchantCallback)(()=>{nt.current?.({status:"succeeded"})}),it(null),Bt(null));return}Z&&(it(null),Bt(null));let g=$ instanceof ze.FloPayError?$:new ze.FloPayError($ instanceof Error?$.message:"Failed to create session","api_error");xe(g)}finally{B?.(),B=void 0}})(),()=>{Se(),B?.()});Ct(!0);async function Yt(){let J=!1,Z=null;try{let $=new to.PaymentAPI(X,{telemetry:!1}),y=await $.getUnifiedCheckoutSession(q,t);if(Z=y,z)return;dt(y);let g=y.data.session??null;if(Ne(g),!g)throw new ze.FloPayError("No session data returned","api_error");let E=g.checkoutMode;if(E==="setup")throw new ze.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(g.status==="authorized"){Ct(!1),(0,tt.invokeMerchantCallback)(()=>{nt.current?.(Yn(g,q)),St.current?.(g.successUrl??"")});return}if(g.status==="complete"){Ct(!1),(0,tt.invokeMerchantCallback)(()=>{St.current?.(g.successUrl??"")});return}if(g.status==="expired")throw Wa(g);J=!0;let de=L??E??"full";Ht(de),ur.current+=1;let Fe=g.clientSecret||t;qt.current=g.buyerIdentified===!1&&Fe?Lo($,q,Fe,{...g.customer?.id?{userId:g.customer.id}:{}}):void 0,mr(!1),Sr(!1);let He=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Xt=ms(y);if(de==="auto"&&!ir.current&&!He&&!Xt){ir.current=!0;let Te=Oe(y);try{if(await Pn.current(g,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Te,sessionId:q||g.id}),z)return;await Te,z||Ct(!1);return}catch{if(z)return;await Te,z||Ct(!1);return}}await Oe(y),z||Ct(!1)}catch($){if(z)return;let y=dl($,J);if(J&&V({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),y){let{errorCode:E,stage:de,...Fe}=y;ps(X,o,f,E,de,Fe)}if(y?.stage==="provider_load"&&(L??Z?.data.session?.checkoutMode??"full")==="full"&&cl(Z,W,_)){let E=$d({billingApiUrl:X,locale:l,telemetry:o});kt.current=E,Zt(E,null),Vr(1),Ct(!1);return}let g=$ instanceof ze.FloPayError&&y?.stage!=="provider_load"?$:ll();g!==$&&(0,tt.invokeMerchantCallback)(()=>ie.current?.(g)),xe(g),Ct(!1)}}async function Oe(J){let{flopay:Z,paypalFlopay:$,...y}=await ys(J,{billingApiUrl:X,locale:l,telemetry:o});vt.current={publishableKey:y.publishableKey,paypalPublishableKey:y.paypalPublishableKey},Zt(Z,$),Vr(0)}return Yt(),Se},[L,Bn,hn,Ce,t,W,_]);let Cn=(0,C.useCallback)(async()=>{if(!Ye||Fr!==1)return;let z=At.current;Vr(2);try{let{flopay:B,paypalFlopay:ce}=await ys(Ye,{billingApiUrl:X,locale:l,telemetry:o});if(At.current!==z)return;Or(),Zt(B,ce),Vr(0)}catch(B){if(At.current!==z)return;let{errorCode:ce,stage:Se,...It}=Wi(B);ps(X,o,f,ce,Se,It)}},[Or,Zt,l,Fr,X,o,f,Ye]),bt=!!(q&&(G?.clientSecret||t)),sr=$r||!bt,yr=(0,C.useCallback)(async()=>{if(!($r||!bt||!G)){Wr(!0),Lt(null);try{await Fn(G,{attempt3DS:!0,fallbackToFull:!0,sessionId:q||G.id})}finally{Wr(!1)}}},[q,$r,bt,Fn,G]),Nr=(0,ze.resolveDirectPaypalConfig)(Ye?.data.paypal,ee),oo=ms(Ye),On=(0,C.useMemo)(()=>{if(!(!Ye||!G||!Ye.data.stripe?.publishableKey))return{billingApiUrl:X}},[Ye,G,X]),Kn=!!(r&&!ye&&j==="buttons"&&Re&&hn==="full"),rn=!!(q&&((0,ze.isMountableVaultBlock)(G?.vault)||(0,Rn.canRecoverHostedCardForm)(G))),lr=(0,C.useMemo)(()=>({session:G,loading:rt,error:ht,checkoutMode:br,inlineSessionDraft:Gt,applyInlineSessionPatch:Kn?Nt:void 0,inlineSessionPatchProcessing:ar,claimPending:Tr,claimRequiresIdentity:jt,claimBuyerIdentity:Xr,waitForDataAttachment:xr}),[G,rt,ht,br,Gt,Kn,Nt,ar,Tr,jt,Xr,xr]),ao=!!r&&j==="buttons"&&!oo&&!rn&&(!We||!On),pr=mt?(0,F.jsx)(qr,{status:mt,errorMessage:Br,authorized:Hr}):null;if(rt&&!rn){if(d)return(0,F.jsxs)(F.Fragment,{children:[d,pr]});if(j==="buttons"){let z=ct?.buttonsLayout?.cardButton?.borderRadius??ct?.appearance.variables?.borderRadius??8,B=ce=>(0,F.jsx)("div",{style:{height:ce,borderRadius:z,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[W&&B(Jo),_&&(te||S)&&B(Jo),_&&B(Jo),(0,F.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),pr]})}return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,F.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,F.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),pr]})}return ht?p?(0,F.jsx)(En.Provider,{value:lr,children:p(ht)}):(0,F.jsx)(En.Provider,{value:lr,children:(0,F.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ht.message})}):ao?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:lr,children:(0,F.jsx)(Xd,{onButtonClick:Ke,showPayPal:W,showStripe:_,showApplePay:te,showGooglePay:S,theme:Q,buttonsTheme:Be,buttonsStyles:se,cardButtonContent:je,cardBackButtonContent:Je,cardTitleContent:me})}),pr]}):oo&&G&&Nr?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:lr,children:(0,F.jsxs)("div",{className:Me,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Rr&&(0,F.jsx)($o,{icon:!1,children:Rr}),Ae==="retrying"&&(0,F.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ae==="exhausted"&&(0,F.jsxs)("div",{role:"alert",children:[(0,F.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,F.jsx)("button",{type:"button",onClick:no,children:"Retry PayPal"})]}),Ae!=="exhausted"&&(0,F.jsx)("div",{"aria-hidden":Ae==="retrying"?!0:void 0,style:Ae==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,F.jsx)(kl,{sessionId:q,nonce:G.clientSecret||void 0,billingApiUrl:X,email:G.customer?.email||Gt?.account?.email,billingName:[G.customer?.firstName,G.customer?.lastName].filter(Boolean).join(" ")||[Gt?.account?.firstName,Gt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Xr,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:b,onErrorChange:Lt,onDecline:x,onButtonClick:Ke,runBeforeButtonClick:bn,onInitializationStateChange:xn,allowAutomaticRetry:yn===0,session:G,telemetry:o,telemetryContext:f,onInstrument:T,debug:Pe},`${Ze}:paypal-init-${yn}`)})]})}),pr]}):br==="confirm"?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:lr,children:(0,F.jsx)(va,{flopay:We,paypalFlopay:N,options:On??{billingApiUrl:X},onInstrument:T,children:(0,F.jsxs)("div",{className:Me,children:[Rr&&(0,F.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Rr}),Y?Y({onConfirm:yr,isProcessing:sr}):(0,F.jsx)("button",{type:"button",onClick:yr,disabled:sr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:sr?"not-allowed":"pointer",opacity:sr?.6:1},children:$r?"Processing...":ve??"Confirm Purchase"})]})},Ze)}),pr]}):(!We||!On)&&!(rn&&br==="full")?(0,F.jsx)(F.Fragment,{children:pr}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(En.Provider,{value:lr,children:(0,F.jsxs)(va,{flopay:We,paypalFlopay:N,options:On??{billingApiUrl:X},onInstrument:T,children:[Fr===1&&(0,F.jsx)("button",{type:"button",onClick:Cn,children:"Retry payment methods"}),ye?(0,F.jsxs)(F.Fragment,{children:[Rr&&(0,F.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Rr}),(0,F.jsx)(Yd,{sessionId:q,nonce:G?.clientSecret||void 0,billingApiUrl:X,session:G,submitLabel:ge,walletPresentation:h,children:ye})]}):(0,F.jsx)(fi,{sessionId:q,nonce:G?.clientSecret||void 0,telemetry:o,email:G?.customer?.email||Gt?.account?.email,userId:G?.customer?.id||Gt?.account?.userId,firstName:G?.customer?.firstName||Gt?.account?.firstName,lastName:G?.customer?.lastName||Gt?.account?.lastName,totalAmount:G?Math.round((0,ze.buildCheckoutDisplayData)(G).total*100):0,currency:G?.currency?.toLowerCase()??"usd",onComplete:b,onError:k,onDecline:x,error:Rr,onErrorChange:Lt,showPayPal:W,showStripe:_,walletPresentation:h,enabledPaymentMethods:Fr?[]:v??Ye?.data.stripe?.enabledPaymentMethods??G?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ye?.data.stripe?.enabledPaymentMethodCountries,showApplePay:te,showGooglePay:S,layout:j,theme:Q,buttonsTheme:Be,buttonsStyles:se,appearance:Ge,cardButtonContent:je,cardBackButtonContent:Je,cardTitleContent:me,onButtonClick:Ke,onBeforeButtonClick:Re,onBuyerIdentityReady:Xr,enableAVS:_e,...Ee?{cardFieldOrder:Ee}:{},...re?{cardPreFormSlot:re}:{},avsLayout:ae,country:G?.customer?.country,city:G?.customer?.city,state:G?.customer?.state,onCountryChange:O,onZipChange:M,avsCheck:!!_e,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:gs(ye,j),className:Me,submitLabel:ge,directPaypal:Nr,isSubscription:G?.mode==="subscription",session:G,dataAttachmentPending:Tr,dataAttachmentRequiresIdentity:jt,debug:Pe})]},Ze)}),pr]})}function Yd({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:o,walletPresentation:i,children:l}){return(0,F.jsx)(F.Fragment,{children:C.default.Children.map(l,d=>{if(!C.default.isValidElement(d))return d;let p=d.props,b={};return p.sessionId||(b.sessionId=e),!p.nonce&&t&&(b.nonce=t),p.billingApiUrl||(b.billingApiUrl=r),p.submitLabel===void 0&&o!==void 0&&(b.submitLabel=o),p.walletPresentation===void 0&&(b.walletPresentation=i),n?.customer&&(p.email||(b.email=n.customer.email),p.userId||(b.userId=n.customer.id),p.firstName||(b.firstName=n.customer.firstName),p.lastName||(b.lastName=n.customer.lastName)),Object.keys(b).length===0?d:C.default.cloneElement(d,b)})})}function Xd({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:o,theme:i,buttonsTheme:l,buttonsStyles:d,cardButtonContent:p,cardBackButtonContent:b,cardTitleContent:k}){let[w,x]=(0,C.useState)(!1),O=(0,C.useMemo)(()=>(0,ze.resolveTheme)(i),[i]),M=(0,C.useMemo)(()=>{let v=O?.buttonsLayout??(0,ze.resolveButtonsLayoutTheme)(l);return d?{...v,...d,cardButton:{...v.cardButton,...d.cardButton},cardFormContainer:{...v.cardFormContainer,...d.cardFormContainer},backButton:{...v.backButton,...d.backButton},backButtonIcon:{...v.backButtonIcon,...d.backButtonIcon},submitButton:{...v.submitButton,...d.submitButton},title:{...v.title,...d.title}}:v},[O,l,d]),W=O?.buttonsLayout?.cardButton?.borderRadius??O?.appearance.variables?.borderRadius??8,_=v=>(0,F.jsx)("div",{style:{height:v,borderRadius:W,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),h=p===void 0?{boxSizing:"border-box",height:Jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(w){let v=M.cardInputBorder??"#e5e7eb",te=M.cardInputBackground??"white",S=Bo(b),Pe=Bo(k);return(0,F.jsxs)("div",{style:{backgroundColor:M.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...M.cardFormContainer},children:[(0,F.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,F.jsxs)("button",{type:"button",onClick:()=>x(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:S?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...M.backButton},children:[(0,F.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...M.backButtonIcon},children:(0,F.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,F.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,F.jsx)(Oo,{content:b})]}),Pe?(0,F.jsx)("div",{style:{flex:1}}):(0,F.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...M.title},children:(0,F.jsx)(ua,{content:k})})]}),(0,F.jsx)("div",{style:{backgroundColor:te,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsxs)("div",{style:{display:"flex"},children:[(0,F.jsx)("div",{style:{flex:1,backgroundColor:te,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{flex:1,backgroundColor:te,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,F.jsx)("div",{style:{backgroundColor:te,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...M.submitButton,opacity:.5}}),(0,F.jsx)("style",{children:`
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:be,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:L.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...L.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",...L.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:ke})]}),Zs?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:L.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...L.title},children:(0,c.jsx)(da,{content:Re})})]}),!aa&&!Zs&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ui,order:f?-3:0,...L.title},children:(0,c.jsx)(da,{content:Re})}),f&&Q&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:Q}),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:Qt,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:or,onChange:s=>{Lt("email"),ur.current=s.target.value,un(s.target.value)},onPointerDown:()=>Lt("email"),onKeyDown:()=>Lt("email"),onBlur:()=>{Yr("email")&&en(!0),wo||_i()},disabled:tt,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"})]}),Ae&&(0,c.jsx)("div",{style:{order:f?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Ht,R=(re=!1)=>({backgroundColor:Mo,border:`1px solid ${rn(re)}`,borderRadius:Qt,marginTop:"0.5rem",padding:"10px"}),ce=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...zi}),ze=(0,d.getStateOptions)(s);return(0,c.jsxs)(c.Fragment,{children:[(0,d.isAVSFieldVisible)(Ae.address_line_1,s)&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{style:R(Jt("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:Ot,onChange:re=>{Lt("line1"),qt.current.addressLine1=!0,mr.current=re.target.value,mt(re.target.value)},onPointerDown:()=>Lt("line1"),onKeyDown:()=>Lt("line1"),onBlur:()=>Tr("line1"),disabled:tt,required:!0,"aria-invalid":Jt("line1")||void 0,"aria-describedby":Jt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:ce()})}),Jt("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)(Ae.address_line_2,s)&&(0,c.jsx)("div",{style:R(),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:re=>{qt.current.addressLine2=!0,jt.current=re.target.value,Fr(re.target.value)},disabled:tt,"data-testid":"flopay-address-line2",style:ce()})}),((0,d.isAVSFieldVisible)(Ae.city,s)||(0,d.isAVSFieldVisible)(Ae.state,s))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Ae.city,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Mo,borderTop:`1px solid ${rn(Jt("city"))}`,borderRight:`1px solid ${rn(Jt("city"))}`,borderBottom:`1px solid ${rn(Jt("city"))}`,borderLeft:`1px solid ${rn(Jt("city"))}`,padding:"10px",borderTopLeftRadius:Qt,borderBottomLeftRadius:Qt,...(0,d.isAVSFieldVisible)(Ae.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Qt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ft,onChange:re=>{Lt("city"),qt.current.city=!0,Sr.current=re.target.value,Wr(re.target.value)},onPointerDown:()=>Lt("city"),onKeyDown:()=>Lt("city"),onBlur:()=>Tr("city"),disabled:tt,required:!0,"aria-invalid":Jt("city")||void 0,"aria-describedby":Jt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:ce()})}),(0,d.isAVSFieldVisible)(Ae.state,s)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:Mo,borderTop:`1px solid ${rn(Jt("state"))}`,borderRight:`1px solid ${rn(Jt("state"))}`,borderBottom:`1px solid ${rn(Jt("state"))}`,borderLeft:`1px solid ${rn(Jt("state"))}`,padding:"10px",borderTopRightRadius:Qt,borderBottomRightRadius:Qt,...(0,d.isAVSFieldVisible)(Ae.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${rn(Jt("state")||Jt("city"))}`}:{borderRadius:Qt}},children:ze?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:br,onChange:re=>{Lt("state"),qt.current.state=!0,Vt.current=re.target.value,Kt(re.target.value)},onPointerDown:()=>Lt("state"),onKeyDown:()=>Lt("state"),onBlur:()=>Tr("state"),disabled:tt,autoComplete:"billing address-level1",required:!0,"aria-invalid":Jt("state")||void 0,"aria-describedby":Jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...ce(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,d.getStateLabel)(s)}),ze.map(re=>(0,c.jsx)("option",{value:re.code,children:re.name},re.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:br,onChange:re=>{Lt("state"),qt.current.state=!0,Vt.current=re.target.value,Kt(re.target.value)},onPointerDown:()=>Lt("state"),onKeyDown:()=>Lt("state"),onBlur:()=>Tr("state"),disabled:tt,required:!0,"aria-invalid":Jt("state")||void 0,"aria-describedby":Jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:ce()})})]}),Jt("city")&&(0,c.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:sa,children:"City is required"}),Jt("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)(Ae.country,s)||(0,d.isAVSFieldVisible)(Ae.postal_code,s))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:K==="column"?"column":"row",gap:K==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,d.isAVSFieldVisible)(Ae.country,s)&&(0,c.jsx)("div",{style:{flex:K==="row"?1:void 0,backgroundColor:Mo,borderTop:`1px solid ${ia}`,borderRight:`1px solid ${ia}`,borderBottom:`1px solid ${ia}`,borderLeft:`1px solid ${ia}`,padding:"10px",...K==="row"&&(0,d.isAVSFieldVisible)(Ae.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:Qt,borderBottomLeftRadius:Qt,borderRight:"none"}:{borderRadius:Qt}},children:(0,c.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Ht,onChange:re=>{qt.current.country=!0,Ir.current=re.target.value,Vr(re.target.value),Ge?.(re.target.value),Vt.current="",Kt("")},disabled:tt,autoComplete:"billing country","data-testid":"flopay-country",style:{...ce(),cursor:"pointer"},children:[Ht===""?(0,c.jsx)("option",{value:"",children:"Select country"}):null,d.COUNTRY_OPTIONS.map(re=>(0,c.jsxs)("option",{value:re.code,children:[re.flag," ",re.name]},re.code))]})}),(0,d.isAVSFieldVisible)(Ae.postal_code,s)&&(0,c.jsx)("div",{style:{flex:K==="row"?1:void 0,backgroundColor:Mo,border:`1px solid ${Ac}`,padding:"10px",...K==="row"&&(0,d.isAVSFieldVisible)(Ae.country,s)?{borderRadius:"0",borderTopRightRadius:Qt,borderBottomRightRadius:Qt}:{borderRadius:Qt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,d.getPostalCodeLabel)(Ht),autoComplete:"billing postal-code",value:$r,onChange:re=>{Lt("zip"),qt.current.zip=!0,zt.current=re.target.value,kr(re.target.value),We?.(re.target.value)},onPointerDown:()=>Lt("zip"),onKeyDown:()=>Lt("zip"),onBlur:()=>{Yr("zip")&&Or(!0)},disabled:tt,required:Kr.required,"aria-invalid":za||void 0,"aria-describedby":za?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:ce()})})]}),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`:Ud(s)})]})})()}),f&&Lc,wt&&(0,c.jsx)(Vo,{margin:"0.75rem 0",styleOverride:L.errorBanner,children:wt})]}),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=>Y?!v||!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=${v}`,` directPaypalConfigured=${Ln}`,` inAppBrowserDetected=${String(Oa)}`,` shouldRenderDirectPayPal=${ea}`,` shouldRenderStripePayPal=${ra}`,` hasPaypalStripeInstance=${!!ws}`].join(`
39
+ `)}):null,ol=s=>Y?!Z||!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=${Z}`,` currency=${Et}`,` amountInCents=${Zo}`,` enabledPaymentMethods: ${JSON.stringify(fe??[])}`,` 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=yr?Xl(xi,yr,A):null;if(pe==="buttons"){let s=Ct==="buttons"||Ct==="expanding"||Ct==="apm-expanding",R=Ct==="expanding"||Ct==="card"||Ct==="collapsing",ce=Qe===void 0?{boxSizing:"border-box",height:Go,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ze;Ct==="expanding"||Ct==="apm-expanding"?ze=Dd:(Ct==="collapsing"||Ct==="apm-collapsing")&&(ze=Bd);let re;return Ct==="expanding"?re=Ul:Ct==="collapsing"&&(re=zl),(0,c.jsxs)("form",{onSubmit:Di,className:H,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Yo,{}),Le&&(0,c.jsx)(zr,{status:Le,errorMessage:wt,authorized:mn}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!ze?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!ze?Ld:{},...ze?{animation:ze,pointerEvents:"none"}:{}},children:[nl("flopay-direct-paypal-gate-debug"),ol("flopay-stripe-gate-debug"),ea&&kt&&(0,c.jsxs)(c.Fragment,{children:[Fe&&(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)(ya.Provider,{value:p,children:(0,c.jsx)(ga,{sessionId:e,nonce:t,billingApiUrl:ht,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:at,clientId:kt.clientId,environment:kt.environment,currency:Et.toUpperCase(),isSubscription:At,providerObjectType:te,approvalPresentation:La==="popup"?void 0:La,onTokenizedBody:Nr,onComplete:l,onErrorChange:Ne,onDecline:m,onTechnicalFailure:Eo,onButtonClick:ee,runBeforeButtonClick:Sn,isProcessing:tt,onLoadStateChange:Ai,onInitializationStateChange:Fi,session:T,existingOrderId:Fe?.orderId,debug:Y},Fe?.orderId??"fresh")})]}),ra&&(0,c.jsx)(er.Elements,{stripe:ta,options:Es,children:(0,c.jsx)(jl,{sessionId:e,nonce:t,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:at,billingApiUrl:ht,onTokenizedBody:Nr,onErrorChange:Ne,isProcessing:tt,onButtonClick:ee,onDecline:m,onTechnicalFailure:Eo,runBeforeButtonClick:Sn,onLoadStateChange:Ds,placeholderBorderRadius:po,popupCapabilityOwner:p,externalTelemetryContext:$s,presentationMode:Io})}),To?(0,c.jsx)(er.Elements,{stripe:Xr,options:Rs,children:(0,c.jsx)($l,{sessionId:e,nonce:t,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:at,billingApiUrl:ht,intentKind:He>0?"payment":"setup",expressMethods:_o,onTokenizedBody:Nr,onErrorChange:Ne,onButtonClick:ee,onDecline:m,onTechnicalFailure:Eo,runBeforeButtonClick:Sn,onLoadStateChange:Ls,placeholderBorderRadius:po,popupCapabilityOwner:p,externalTelemetryContext:he})}):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:at,billingApiUrl:ht,paymentElementMethods:Da,stripeInstance:Xr,paymentElementBaseOptions:xi,futureUseSession:A,onTokenizedBody:Nr,onErrorChange:Ne,onButtonClick:ee,onDecline:m,runBeforeButtonClick:Sn,onLoadStateChange:Us,isProcessing:tt,submitButtonColor:mo,submitButtonBorderRadius:Qt,submitButtonStyle:L.submitButton,onExpandApm:It,expandedApmMethod:yr,themeId:De,buttonAppearance:{backgroundColor:L.cardButton?.backgroundColor,borderColor:L.cardInputBorder,textColor:L.cardButton?.color,borderRadius:po}}),f&&(0,c.jsx)("button",{type:"button",onClick:async()=>{tt||!(await Sn("card")).proceed||(ee?.("card"),se())},disabled:tt,style:{width:"100%",...ce,...L.cardButton,...ds({themeBundle:Se,resolvedPrimaryColor:mo,resolvedBorderRadius:Qt,submitButtonStyle:L.submitButton,explicitPrimaryColor:Ur?.colorPrimary}),fontSize:L.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:tt?"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:tt?.6:1},onMouseEnter:Te=>{!tt&&(Se||Ur?.colorPrimary)&&(Te.currentTarget.style.backgroundColor=Dc)},onMouseLeave:Te=>{(Se||Ur?.colorPrimary)&&(Te.currentTarget.style.backgroundColor=mo)},onMouseDown:Te=>{Te.currentTarget.style.transform="scale(0.985)"},onMouseUp:Te=>{Te.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(Bo,{content:Qe})}),wt&&Ct==="buttons"&&(0,c.jsx)(Vo,{margin:"0.25rem 0",styleOverride:L.errorBanner,children:wt})]}),f&&R&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...re?{animation:re}:{},...Ct==="collapsing"?{pointerEvents:"none"}:{}},children:rl}),Z&&al&&yr&&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:Yt,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:L.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...L.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",...L.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:ke})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:L.titleFontSize??"1.05rem",color:Ui,paddingRight:80,...L.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(yr)}`})]}),(0,c.jsx)(er.Elements,{stripe:Xr,options:ja,children:(0,c.jsx)(ss,{method:yr,sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:at,billingApiUrl:ht,onTokenizedBody:Nr,onErrorChange:Ne,onDecline:m,onCancel:Yt,runBeforeButtonClick:Sn,onButtonClick:ee,isProcessing:tt,submitButtonColor:mo,submitButtonBorderRadius:Qt,submitButtonStyle:L.submitButton,errorText:wt})},yr)]})})]})]})}return al&&yr&&ja&&Xr&&Z?(0,c.jsxs)("form",{onSubmit:Di,className:H,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Yo,{}),Le&&(0,c.jsx)(zr,{status:Le,errorMessage:wt,authorized:mn}),(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:Yt,style:{display:"inline-flex",alignItems:"center",gap:Ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:L.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...L.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",...L.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:ke})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:L.titleFontSize??"1.05rem",color:Ui,paddingRight:80,...L.title},children:`Pay with ${(0,d.getStripeMethodDisplayName)(yr)}`})]}),(0,c.jsx)(er.Elements,{stripe:Xr,options:ja,children:(0,c.jsx)(ss,{method:yr,sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:at,billingApiUrl:ht,onTokenizedBody:Nr,onErrorChange:Ne,onDecline:m,onCancel:Yt,runBeforeButtonClick:Sn,onButtonClick:ee,isProcessing:tt,submitButtonColor:mo,submitButtonBorderRadius:Qt,submitButtonStyle:L.submitButton,errorText:wt})},yr)]})})]}):(0,c.jsxs)("form",{onSubmit:Di,className:H,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(Yo,{}),Le&&(0,c.jsx)(zr,{status:Le,errorMessage:wt,authorized:mn}),(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:[Fe&&(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)(ya.Provider,{value:p,children:(0,c.jsx)(ga,{sessionId:e,nonce:t,billingApiUrl:ht,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:at,clientId:kt.clientId,environment:kt.environment,currency:Et.toUpperCase(),isSubscription:At,providerObjectType:te,approvalPresentation:La==="popup"?void 0:La,onTokenizedBody:Nr,onComplete:l,onErrorChange:Ne,onDecline:m,onTechnicalFailure:Eo,onButtonClick:ee,runBeforeButtonClick:Sn,isProcessing:tt,onLoadStateChange:Ai,onInitializationStateChange:Fi,session:T,existingOrderId:Fe?.orderId,debug:Y},Fe?.orderId??"fresh")})]}),ra&&(0,c.jsx)(er.Elements,{stripe:ta,options:Es,children:(0,c.jsx)(jl,{sessionId:e,nonce:t,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:at,billingApiUrl:ht,onTokenizedBody:Nr,onErrorChange:Ne,isProcessing:tt,onButtonClick:ee,onDecline:m,onTechnicalFailure:Eo,runBeforeButtonClick:Sn,onLoadStateChange:Ds,placeholderBorderRadius:po,popupCapabilityOwner:p,externalTelemetryContext:$s,presentationMode:Io})}),To&&(0,c.jsx)(er.Elements,{stripe:Xr,options:Rs,children:(0,c.jsx)($l,{sessionId:e,nonce:t,email:Pt.email,billingName:So||void 0,onBuyerIdentityReady:at,billingApiUrl:ht,intentKind:He>0?"payment":"setup",expressMethods:_o,onTokenizedBody:Nr,onErrorChange:Ne,onButtonClick:ee,onDecline:m,onTechnicalFailure:Eo,runBeforeButtonClick:Sn,onLoadStateChange:Ls,placeholderBorderRadius:po,popupCapabilityOwner:p,externalTelemetryContext:he})}),na&&(0,c.jsx)(Wl,{sessionId:e,nonce:t,email:Pt.email,billingName:[Pt.firstName,Pt.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ht,paymentElementMethods:Da,stripeInstance:Xr,paymentElementBaseOptions:xi,futureUseSession:A,onTokenizedBody:Nr,onErrorChange:Ne,onButtonClick:ee,onDecline:m,runBeforeButtonClick:Sn,onLoadStateChange:Us,isProcessing:tt,submitButtonColor:mo,submitButtonBorderRadius:Qt,submitButtonStyle:L.submitButton,themeId:De,onExpandApm:It,expandedApmMethod:yr,buttonAppearance:{backgroundColor:L.cardButton?.backgroundColor,borderColor:L.cardInputBorder,textColor:L.cardButton?.color,borderRadius:po}})]}),f&&(_c||Ic||Tc)&&(0,c.jsx)(li,{label:"or pay with card"}),f&&rl]})}var F=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 $d(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:qe.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,qe.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 qe.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof qe.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,qe.resolveDirectPaypalConfig)(e.data.paypal)?.clientId}var Wd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Hd(e){return new eo.FloPay(Wd,{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,qe.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:o,appearance:i,locale:l,loading:u,error:m,onComplete:C,onError:w,onInstrument:S,onDecline:x,onCountryChange:H,onZipChange:M,showPayPal:V=!0,showStripe:_=!0,walletPresentation:h="auto",enabledPaymentMethods:v,showApplePay:Z=!0,showGooglePay:k=!0,debug:fe=!1,layout:O,theme:ne,buttonsTheme:Be,buttonsStyles:pe,cardButtonContent:De,cardBackButtonContent:Je,cardTitleContent:me,showSecurityFooter:de,onButtonClick:Qe,onBeforeButtonClick:ke,enableAVS:Re,cardFieldOrder:Ee,cardPreFormSlot:ee,avsLayout:ue,submitLabel:Pe,className:Ie,initialErrorMessage:ve=null,initialPayPalOrderId:Q,children:K,checkoutMode:N,confirmLabel:_e,renderConfirmButton:ae,onSessionCompleted:ge}){let B=(0,qe.resolveBillingApiUrl)(n),$e=(0,b.useMemo)(()=>(0,qe.resolveTheme)(ne),[ne]),Ge=i??$e?.appearance,We=r?"embedded_checkout":"standard_checkout",ct=gs(K,O),[Ye,dt]=(0,b.useState)(null),[He,Et]=(0,b.useState)(null),Ut=(0,b.useRef)(null),kt=(0,b.useRef)(null),At=(0,b.useRef)(0),[U,ye]=(0,b.useState)(null),et=(0,b.useRef)(null),[Y,Ue]=(0,b.useState)(null),Rt=(0,b.useMemo)(()=>r?(0,ut.serializeCreateParams)(r):"",[r]),Ze=r?`create:${Rt}`:`session:${e??""}`,Tt=rc(Y),z=(0,b.useRef)(new Set),p=(0,b.useRef)(Ze),P=(0,b.useRef)(Ze);Po(()=>{P.current=Ze,p.current!==Ze&&(p.current=Ze,z.current.clear())},[Ze]);let G=(0,b.useCallback)(q=>{if(P.current===Ze){if(Yi.FLO_INSTRUMENT_ONCE_NAMES.has(q.name)){if(z.current.has(q.name))return;z.current.add(q.name)}(0,rt.invokeMerchantCallback)(()=>S?.(q))}},[Ze,S]),$=jo(G,Ze),he=(0,b.useRef)(!1),T=(0,b.useCallback)(q=>{if(he.current)return;let D=q.gateway||!Tt?q:{...q,gateway:Tt};G(D)},[G,Tt]);(0,b.useEffect)(()=>{$({class:"lifecycle",name:"checkout.mount"})},[$]);let[A,te]=(0,b.useState)(e??""),j=e??A,Ce=r?"":j,[nt,bt]=(0,b.useState)(!0),[ht,xe]=(0,b.useState)(null),[Ar,jr]=(0,b.useState)(0),[Cr,Ht]=(0,b.useState)("full"),[Vr,$r]=(0,b.useState)(!1),[kr,Ot]=(0,b.useState)(ve),[mt,st]=(0,b.useState)(null),[Fr,Ft]=(0,b.useState)(null),[Wr,br]=(0,b.useState)(!1),[Kt,or]=(0,b.useState)(void 0),[un,Qr]=(0,b.useState)(""),[ar,zt]=(0,b.useState)(!1),[Ir,mr]=(0,b.useState)(!1),[jt,Sr]=(0,b.useState)(!1),Vt=(0,b.useRef)(null),ur=(0,b.useRef)(0),qt=(0,b.useRef)(void 0),[Ae,pn]=(0,b.useState)("loading"),[mn,yn]=(0,b.useState)(0),ir=(0,b.useRef)(!1),Br=(0,b.useRef)(!1),_r=(0,b.useRef)(!1),Oe=(0,b.useRef)(null),vt=(0,b.useRef)(null),f=(0,b.useMemo)(()=>({checkoutMode:N??Cr,layout:Yd(K,O)}),[N,K,Cr,O]),ot=(0,b.useRef)(C);ot.current=C;let oe=(0,b.useRef)(w);oe.current=w;let Rr=(0,b.useRef)(x);Rr.current=x;let Hr=(0,b.useCallback)(q=>Qa(Oe,async D=>{try{return await q(D)}catch(se){throw D.aborted?$o(se):se}}),[]);(0,b.useEffect)(()=>()=>{Oe.current?.abort(),Oe.current=null},[]);let Zt=(0,b.useCallback)((q,D)=>{Ut.current=q,Et(q),et.current=D,ye(D)},[]),Dr=(0,b.useCallback)(()=>{let q=kt.current;q&&(kt.current=null,q.destroy())},[]);(0,b.useEffect)(()=>{hr(He)?.setCheckoutContext(f),U&&U!==He&&hr(U)?.setCheckoutContext(f)},[He,U,f]);let St=(0,b.useRef)(ge);St.current=ge;let Mn=(0,b.useCallback)(q=>{pn(q),!(q!=="exhausted"||_r.current)&&(_r.current=!0,oe.current?.(new qe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),ro=(0,b.useCallback)(()=>{pn("retrying"),yn(q=>q+1)},[]);(0,b.useEffect)(()=>{pn("loading"),yn(0),_r.current=!1},[j]),(0,b.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:qe.SDK_VERSION,checkout_type:We,checkout_layout:ct,billing_api_url:B})},[ct,We,B]);let Bt=(0,b.useMemo)(()=>r?(0,ut.serializeCreateParams)(r,!0):"",[r]),Kr=(0,b.useMemo)(()=>un===Bt?Kt:void 0,[Kt,un,Bt]),fn=(0,b.useMemo)(()=>r?Wi(r,Kr):void 0,[r,Kr]),gn=N??fn?.checkoutMode??"full",Gt=(0,b.useMemo)(()=>fn?{...fn,checkoutMode:gn}:void 0,[fn,gn]);(0,b.useEffect)(()=>{or(void 0),Qr(Bt),qt.current=void 0,Vt.current=null,Sr(!1)},[Bt]),(0,b.useEffect)(()=>{Ot(ve)},[ve]);let xn=(0,b.useCallback)((q,D,se)=>{(0,rt.invokeMerchantCallback)(()=>{Rr.current?.(gr(q,D,se))})},[]),An=(0,b.useCallback)(async(q,D)=>{Ot(null),Ft(null),br(!1),st("processing");let se=D?.sessionId??q.id,be=q.clientSecret||t,It=rc(q),Yt=Ut.current??et.current,Le=hr(Yt),X=Yt?null:gi(B,o,f),J={log:Me=>{Le?Le.log(Me):X?.log(Me)},error:Me=>{Le?Le.error(Me):X?.error(Me)},terminal:Me=>{Le?Le.terminal(Me):X?.terminal(Me)},performance:Me=>{Le?Le.performance(Me):X?.performance(Me)},now:()=>Le?.now()??X?.now()??0,elapsed:Me=>Le?.elapsed(Me)??Math.max(0,(X?.now()??Me)-Me)},W=J.now(),y=!!(D?.initialAutoProcessingError||D?.initialAutoProcessingPending),g=!1,E,le=()=>{g||(g=!0,y=!0,E=J.now(),J.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),J.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Fe=!1,Ke=()=>{Fe||(Fe=!0,J.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),J.performance({stage:"processing",durationMs:J.elapsed(W),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),E!==void 0&&J.performance({stage:"recovery",durationMs:J.elapsed(E),durationMode:"machine",paymentMethodCategory:"saved"}))};J.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),he.current=!0;try{J.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{he.current=!1}$({class:"lifecycle",name:"payment.processing.started",provider:It}),y&&le();let Xt;try{let Me=Tl(D?.initialAutoProcessingError),Xe=D?.initialAutoProcessingError?.type==="3ds_required"&&!D.initialAutoProcessingError.threeDSecureToken&&D.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:D.initialAutoProcessingError.nextActionRedirectUrl}:null,at,wt=Se=>(le(),Hr(L=>Wo(Se,{billingApiUrl:B,sessionId:se,nonce:be,session:q,signal:L})));if(Xe)at=await wt(Xe);else if(Me)le(),Me.type==="paypal_redirect_required"&&vt.current?.publishableKey&&ec({sessionId:se,publishableKey:vt.current.publishableKey,paypalPublishableKey:vt.current.paypalPublishableKey}),at=await Hr(Se=>ti(Me,{flopay:Ut.current,paypalFlopay:et.current,attempt3DS:D?.attempt3DS,billingApiUrl:B,sessionId:se,session:q,telemetry:!1,signal:Se})),Me.type==="paypal_redirect_required"&&fs();else if(D?.initialAutoProcessingPending){let Se=D.initialAutoProcessingPending,L=new eo.PaymentAPI(B,{telemetry:!1}),ie=await Hr(tt=>L.waitForCheckoutSessionCompletion(Se.sessionId,{initialDelayMs:Se.retryAfterMs,nonce:be,statusUrl:Se.statusUrl,signal:tt})),yt=so(ie,q),Ve=ie.autoProcessingError?.type==="3ds_required"&&ie.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ie.autoProcessingError.nextActionRedirectUrl}:null;if(Ve)at=await wt(Ve);else{if(!Yn(yt))throw Lo(yt);at=Gn(yt,se)}}else{if(D?.initialAutoProcessingError)throw qn(D.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.initialAutoProcessingError.checkoutMethod});if(D?.fromCreateSession)return D?.fallbackToFull&&(Ht("full"),tc("full")),!1;{let Se=await Ho({billingApiUrl:B,sessionId:se,session:q,nonce:be,telemetry:!1});Se.type==="success"?at=Se.result:Se.type==="next_action_required"?at=await wt(Se):(le(),Se.type==="paypal_redirect_required"&&vt.current?.publishableKey&&ec({sessionId:se,publishableKey:vt.current.publishableKey,paypalPublishableKey:vt.current.paypalPublishableKey}),at=await Hr(L=>ti(Se,{flopay:Ut.current,paypalFlopay:et.current,attempt3DS:D?.attempt3DS,billingApiUrl:B,sessionId:se,session:q,telemetry:!1,signal:L})),Se.type==="paypal_redirect_required"&&fs())}}se&&(0,In.markSessionRecentlyCompleted)(se),Ke(),y&&(J.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),J.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),J.terminal({outcome:at.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),br(at.status==="authorized"),st("success"),await _a(600),Xt=()=>ot.current?.(at)}catch(Me){let Xe=io(ba(Me),se);if(Xe.code==="three_ds_aborted")return!1;let at=Xe.checkoutMethod??Ca;Ot(Xe.message),Ft(Xe.message),br(!1),D?.fallbackToFull&&(J.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Ht("full"),tc("full")),Ke();let wt=Xe.statusCode===void 0?void 0:(0,qe.telemetryStatusClass)(Xe.statusCode,"unknown"),Se=wt==="4xx"?{requestCategory:"process_payment",statusClass:wt}:{},L=wt===void 0||wt==="4xx";if(L&&(Xe.telemetryOutcome==="payment_declined"||!!(Xe.declineCode||Xe.code?.toLowerCase().includes("declin"))))J.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Se});else if(L&&(Xe.telemetryOutcome==="validation_rejected"||Xe.type==="validation_error"))J.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Se});else{let Ve=(0,qe.classifyTelemetryFailure)(Me,y?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),tt=Xe.telemetryRequestCategory??"process_payment";he.current=!0;try{J.error({...Ve,...Xe.telemetryFailureCategory?{failureCategory:Xe.telemetryFailureCategory}:{},stage:y?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:tt})}finally{he.current=!1}$({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:tt,provider:It})}return(0,rt.invokeMerchantCallback)(()=>oe.current?.(Xe)),xn(at,Xe,{code:Xe.code,declineCode:Xe.declineCode}),st("error"),await Promise.allSettled([_a(400),D?.ensureProvidersReady?D.ensureProvidersReady():Promise.resolve()]),y&&(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),Ft(null)}return(0,rt.invokeMerchantCallback)(Xt),!0},[xn,$,t,B,Hr,o,f]);(0,b.useEffect)(()=>{if(typeof window>"u"||Br.current)return;let q=new URLSearchParams(window.location.search),D=q.get("payment_intent_client_secret");if(!D)return;let se=Kd();se&&(Br.current=!0,(async()=>{let be,It=0;Ot(null),Ft(null),st("processing"),$r(!0);try{if(q.get("redirect_status")==="failed")throw Object.assign(new qe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Yt,paypalFlopay:Le}=await Qi({publishableKey:se.publishableKey,paypalPublishableKey:se.paypalPublishableKey,billingApiUrl:B,locale:l,telemetry:o});be=hr(Le??Yt),be?.setCheckoutContext(f),It=be?.now()??0,be?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),be?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let X=(Le??Yt)?.getRawProvider();if(!X)throw Object.assign(new qe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:J,error:W}=await X.retrievePaymentIntent(D);if(W)throw Object.assign(new qe.FloPayError(W.message??"Failed to retrieve PayPal payment status.","api_error",{code:W.code}),{checkoutMethod:"paypal"});let y=fl(J?.status);if(!J||y==="failed")throw Object.assign(new qe.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,E=y;if(se.sessionId){let Ke=(await new eo.PaymentAPI(B,{telemetry:!1}).getUnifiedCheckoutSession(se.sessionId)).data.session;if(Ke&&Ke.status!=="complete"){let Xt=await Ho({billingApiUrl:B,sessionId:se.sessionId,session:Ke,telemetry:!1,tokenizedData:{id:g??J.id,type:"card",threeDSecureActionResultTokenId:J.id,isPaypal:!0}});if(Xt.type!=="success")throw Object.assign(new qe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});E=Xt.result.status}}se.sessionId&&(0,In.markSessionRecentlyCompleted)(se.sessionId),be?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),be?.performance({stage:"redirect_resume",durationMs:be.elapsed(It),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),be?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),st("success"),await _a(600),(0,rt.invokeMerchantCallback)(()=>ot.current?.({status:E,paymentIntentId:J.id,paymentMethodId:g,checkoutMethod:"paypal"}))}catch(Yt){let Le=io(ba(Yt),se.sessionId),X=Le.checkoutMethod??"paypal",J=!!(Le.declineCode||Le.code?.toLowerCase().includes("declin"));if(be)be.performance({stage:"redirect_resume",durationMs:be.elapsed(It),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),J?be.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):be.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(J){let W=gi(B,o,f);W.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ta(W)}else ps(B,o,f,"REDIRECT_RESUME_FAILED","redirect_resume");Ot(Le.message),Ft(Le.message),(0,rt.invokeMerchantCallback)(()=>oe.current?.(Le)),xn(X,Le,{code:Le.code,declineCode:Le.declineCode}),st("error"),await _a(400)}finally{fs(),Gd(),st(null),Ft(null),$r(!1)}})())},[xn,l,B,o,f]);let Or=(0,b.useRef)(null),Fn=(0,b.useMemo)(()=>Gt?(0,ut.serializeCreateParams)(Gt):"",[Gt]),en=(0,b.useRef)(Gt);en.current=Gt,(0,b.useEffect)(()=>{te(e??"")},[e]),(0,b.useEffect)(()=>{ir.current=!1,Ot(ve),Ft(null),br(!1),st(null)},[Fn,ve,e]);async function Bn(q,D,se){let be=gi(B,o,f),It=new eo.PaymentAPI(B,{telemetry:!1}),Yt=!1;try{let Le=q.idempotencyKey===void 0?void 0:(0,qe.resolveIdempotencyKey)(q.idempotencyKey),X=(0,ut.readCachedInlineSession)(D,se),J=(0,ut.readCachedInlineIdempotencyKey)(D,se);X?.canonicalIdentity===se&&J&&J.canonicalIdentity===void 0&&((0,ut.persistCachedInlineIdempotencyKey)(D,se,J.idempotencyKey),J={...J,canonicalIdentity:se});let W=Le??(J?.canonicalIdentity===se?J.idempotencyKey:void 0),y,g=!1;be.log({name:X?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let E=X?.sid??null,le=null,Fe,Ke,Xt=!1;if(E)try{le=await It.getUnifiedCheckoutSession(E,X?.nonce),X&&X.canonicalIdentity===void 0&&((0,ut.legacyCachedSessionMatchesDraft)(le.data.session,q)?((0,ut.persistCachedInlineSession)(D,se,E,X.nonce??le.data.session?.clientSecret),J&&J.canonicalIdentity===void 0&&((0,ut.persistCachedInlineIdempotencyKey)(D,se,J.idempotencyKey),W??(W=J.idempotencyKey))):((0,ut.clearCachedInlineCheckout)(D,se),J=null,W=Le,E=null,le=null));let Xe=le?.data.session?.status,at=le?.data.session,wt=at?.clientSecret||X?.nonce;if(E&&at?.buyerIdentified===!1&&wt&&(Ke=Oo(It,E,wt,q.account)),E&&le&&Xe==="complete"){if((0,In.wasSessionRecentlyCompleted)(E))return{sid:E,result:le};(0,ut.clearCachedInlineCheckout)(D,se),E=null,le=null,g=!0}}catch{be.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),X?.canonicalIdentity===void 0?((0,ut.clearCachedInlineCheckout)(D,se),W=Le):(0,ut.clearCachedInlineSession)(D,se),E=null}if(!E){!Le&&(g||!W)&&(W=(0,qe.resolveIdempotencyKey)(),y=W),W&&(0,ut.persistCachedInlineIdempotencyKey)(D,se,W);let Xe=be.now(),at=0;be.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let wt={...q,idempotencyKey:W,avsCheck:!!Re,avsConfig:typeof Re=="object"?Re:void 0,checkoutType:"embedded_checkout",checkoutLayout:gs(K,O)};Object.defineProperty(wt,eo.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ie=>{at=Math.max(at,ie)}}});let Se=()=>{Zl(be,"session_create",Xe,at)},L=ie=>{Ql(be,ie,"session_create",Xe,at)&&$({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,qe.isDetachedSessionEligible)(wt)){let ie=await It.createDetachedSession(wt);ie.claimed.catch(()=>{}),le=ie.shell,E=ie.sessionId,Ke=ie.claim;let yt=be.now();be.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Fe=ie.claimed.then(Ve=>{let tt=Ve.data.session?.id??ie.sessionId;return tt&&(0,ut.persistCachedInlineSession)(D,se,tt,Ve.data.session?.clientSecret??ie.nonce),Zl(be,"session_claim",yt),Se(),Ve},Ve=>{throw(0,ut.clearCachedInlineSession)(D,se),Ql(be,Ve,"session_claim",yt,0)&&$({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Ve}).finally(()=>Ta(be)),Fe.catch(()=>{}),Yt=!0,be.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),be.performance({stage:"session_shell",durationMs:be.now()-Xe,durationMode:"machine",requestCategory:"session_create",attempt:at,statusClass:"2xx",paymentMethodCategory:"card"})}else le=await It.createAndFetchSession(wt),Se()}catch(ie){throw L(ie),ie}E=le.data.session?.id??E??"",E&&!Fe&&(0,ut.persistCachedInlineSession)(D,se,E,le.data.session?.clientSecret)}let Me=le?.data.session;return!Ke&&E&&Me?.buyerIdentified===!1&&Me.clientSecret&&(Ke=Oo(It,E,Me.clientSecret,q.account)),{sid:E??"",result:le,sdkGeneratedIdempotencyKey:y,...Fe?{claimed:Fe}:{},...Ke?{claim:Ke}:{},...Xt?{claimRequiresIdentity:!0}:{}}}finally{Yt||Ta(be)}}let Wn=(0,b.useRef)(Bn);Po(()=>{Wn.current=Bn},[Bn]);let Gr=(0,b.useCallback)(async(q,D)=>{let se=en.current;if(!se)throw new qe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let be=Wi(se,q),It=(0,ut.serializeCreateParams)(be),Yt=(0,ut.hashCreateParams)(be),Le=hi.get(It);if(!Le){let W={canonicalIdentity:It,promise:Wn.current(be,Yt,It),consumers:0,settled:!1};Le=W,hi.set(It,W);let y=()=>{W.settled=!0,Jl(It,W)};W.promise.then(y,y)}Le.consumers+=1;let X=!1,J=()=>{X||(X=!0,Le.consumers-=1,Jl(It,Le))};D?.(J);try{let W=await Le.promise;Or.current=It,q&&(Qr(Bt),or(Me=>pl(Me,q)));let{sid:y,result:g,claimed:E,claim:le,claimRequiresIdentity:Fe}=W;if(qt.current=le,Sr(Fe===!0),dt(g),g.data.session&&Ue(g.data.session),y&&te(y),E){ur.current+=1;let Me=ur.current;Vt.current=E,mr(!0),E.then(Xe=>{ur.current===Me&&(Vt.current===E&&(Vt.current=null),dt(Xe),Xe.data.session&&Ue(Xe.data.session),mr(!1),Sr(!1))},Xe=>{ur.current===Me&&(Vt.current===E&&(Vt.current=null),mr(!1),Sr(!1),xe(Xe instanceof qe.FloPayError?Xe:new qe.FloPayError(Xe instanceof Error?Xe.message:"Failed to create session","api_error")))})}else ur.current+=1,Vt.current=null,mr(!1),Sr(!1);let{flopay:Ke,paypalFlopay:Xt}=await ys(g,{billingApiUrl:B,locale:l,telemetry:o});return Zt(Ke,Xt),bt(!1),W}catch(W){throw Or.current===It&&(Or.current=null),W}finally{D||J()}},[Bt,Zt,l,B,o]),hn=(0,b.useRef)(An);hn.current=An;let Pn=(0,b.useRef)(Gr);Pn.current=Gr;let Lt=(0,b.useCallback)(async q=>{if(!Xd(q)||ar)return{sessionId:A,session:Y};zt(!0);try{let D=await Gr(q);return{sessionId:D.sid,session:D.result.data.session??null}}finally{zt(!1)}},[Gr,ar,A,Y]),Yr=(0,b.useCallback)(async q=>{let D=qt.current;if(!D)return;let se=ur.current,be=await D(q);ur.current===se&&(dt(be),be.data.session&&Ue(be.data.session))},[]),Tr=(0,b.useCallback)(async()=>{await Vt.current},[]),vn=(0,b.useCallback)(async()=>(await Tr(),{proceed:!0}),[Tr]);(0,b.useEffect)(()=>{let q=!1,D,se=++At.current;Dr(),xe(null),jr(0);let be=()=>{q=!0,At.current===se&&(At.current+=1,Dr())},It=en.current;if(Fn&&It)return Ht(gn),bt(!1),Or.current===Fn?be:(Ue(ml(It,N)),(async()=>{let X=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),J=gn==="auto"&&!ir.current&&!X;J&&(Ot(null),Ft(null),st("processing"));try{let W=await Pn.current(void 0,le=>{D=le}),y=W.result.data.session??null;vt.current=Zi(W.result);let g=ms(W.result),E=(0,In.wasSessionRecentlyCompleted)(W.sid||y?.id);if(!q&&J&&y&&!g&&!E){ir.current=!0,await $d(Fn,W.sdkGeneratedIdempotencyKey,()=>hn.current(y,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:W.result.autoProcessingError,initialAutoProcessingPending:W.result.autoProcessingPending,autoProcessingAttempted:W.result.autoProcessingAttempted,sessionId:W.sid||y.id}));return}!q&&J&&((g||E)&&(ir.current=!0),st(null),Ft(null))}catch(W){if(q)return;let y=Wa(W);if(J&&y==="session_auto_completed"){ir.current=!0,st("success"),await _a(600),q||((0,rt.invokeMerchantCallback)(()=>{ot.current?.({status:"succeeded"})}),st(null),Ft(null));return}J&&(st(null),Ft(null));let g=W instanceof qe.FloPayError?W:new qe.FloPayError(W instanceof Error?W.message:"Failed to create session","api_error");xe(g)}finally{D?.(),D=void 0}})(),()=>{be(),D?.()});bt(!0);async function Yt(){let X=!1,J=null;try{let W=new eo.PaymentAPI(B,{telemetry:!1}),y=await W.getUnifiedCheckoutSession(j,t);if(J=y,q)return;dt(y);let g=y.data.session??null;if(Ue(g),!g)throw new qe.FloPayError("No session data returned","api_error");let E=g.checkoutMode;if(E==="setup")throw new qe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(g.status==="authorized"){bt(!1),(0,rt.invokeMerchantCallback)(()=>{ot.current?.(Gn(g,j)),St.current?.(g.successUrl??"")});return}if(g.status==="complete"){bt(!1),(0,rt.invokeMerchantCallback)(()=>{St.current?.(g.successUrl??"")});return}if(g.status==="expired")throw $a(g);X=!0;let le=N??E??"full";Ht(le),ur.current+=1;let Fe=g.clientSecret||t;qt.current=g.buyerIdentified===!1&&Fe?Oo(W,j,Fe,{...g.customer?.id?{userId:g.customer.id}:{}}):void 0,mr(!1),Sr(!1);let Ke=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Xt=ms(y);if(le==="auto"&&!ir.current&&!Ke&&!Xt){ir.current=!0;let Me=Le(y);try{if(await hn.current(g,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Me,sessionId:j||g.id}),q)return;await Me,q||bt(!1);return}catch{if(q)return;await Me,q||bt(!1);return}}await Le(y),q||bt(!1)}catch(W){if(q)return;let y=ul(W,X);if(X&&$({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),y){let{errorCode:E,stage:le,...Fe}=y;ps(B,o,f,E,le,Fe)}if(y?.stage==="provider_load"&&(N??J?.data.session?.checkoutMode??"full")==="full"&&dl(J,V,_)){let E=Hd({billingApiUrl:B,locale:l,telemetry:o});kt.current=E,Zt(E,null),jr(1),bt(!1);return}let g=W instanceof qe.FloPayError&&y?.stage!=="provider_load"?W:cl();g!==W&&(0,rt.invokeMerchantCallback)(()=>oe.current?.(g)),xe(g),bt(!1)}}async function Le(X){let{flopay:J,paypalFlopay:W,...y}=await ys(X,{billingApiUrl:B,locale:l,telemetry:o});vt.current={publishableKey:y.publishableKey,paypalPublishableKey:y.paypalPublishableKey},Zt(J,W),jr(0)}return Yt(),be},[N,Fn,gn,Ce,t,V,_]);let Cn=(0,b.useCallback)(async()=>{if(!Ye||Ar!==1)return;let q=At.current;jr(2);try{let{flopay:D,paypalFlopay:se}=await ys(Ye,{billingApiUrl:B,locale:l,telemetry:o});if(At.current!==q)return;Dr(),Zt(D,se),jr(0)}catch(D){if(At.current!==q)return;let{errorCode:se,stage:be,...It}=$i(D);ps(B,o,f,se,be,It)}},[Dr,Zt,l,Ar,B,o,f,Ye]),Ct=!!(j&&(Y?.clientSecret||t)),sr=Vr||!Ct,yr=(0,b.useCallback)(async()=>{if(!(Vr||!Ct||!Y)){$r(!0),Ot(null);try{await An(Y,{attempt3DS:!0,fallbackToFull:!0,sessionId:j||Y.id})}finally{$r(!1)}}},[j,Vr,Ct,An,Y]),Lr=(0,qe.resolveDirectPaypalConfig)(Ye?.data.paypal,Q),no=ms(Ye),Dn=(0,b.useMemo)(()=>{if(!(!Ye||!Y||!Ye.data.stripe?.publishableKey))return{billingApiUrl:B}},[Ye,Y,B]),Hn=!!(r&&!K&&O==="buttons"&&ke&&gn==="full"),tn=!!(j&&((0,qe.isMountableVaultBlock)(Y?.vault)||(0,kn.canRecoverHostedCardForm)(Y))),lr=(0,b.useMemo)(()=>({session:Y,loading:nt,error:ht,checkoutMode:Cr,inlineSessionDraft:Gt,applyInlineSessionPatch:Hn?Lt:void 0,inlineSessionPatchProcessing:ar,claimPending:Ir,claimRequiresIdentity:jt,claimBuyerIdentity:Yr,waitForDataAttachment:Tr}),[Y,nt,ht,Cr,Gt,Hn,Lt,ar,Ir,jt,Yr,Tr]),oo=!!r&&O==="buttons"&&!no&&!tn&&(!He||!Dn),pr=mt?(0,F.jsx)(zr,{status:mt,errorMessage:Fr,authorized:Wr}):null;if(nt&&!tn){if(u)return(0,F.jsxs)(F.Fragment,{children:[u,pr]});if(O==="buttons"){let q=$e?.buttonsLayout?.cardButton?.borderRadius??$e?.appearance.variables?.borderRadius??8,D=se=>(0,F.jsx)("div",{style:{height:se,borderRadius:q,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[V&&D(Xo),_&&(Z||k)&&D(Xo),_&&D(Xo),(0,F.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),pr]})}return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,F.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,F.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),pr]})}return ht?m?(0,F.jsx)(Rn.Provider,{value:lr,children:m(ht)}):(0,F.jsx)(Rn.Provider,{value:lr,children:(0,F.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ht.message})}):oo?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Rn.Provider,{value:lr,children:(0,F.jsx)(Zd,{onButtonClick:Qe,showPayPal:V,showStripe:_,showApplePay:Z,showGooglePay:k,theme:ne,buttonsTheme:Be,buttonsStyles:pe,cardButtonContent:De,cardBackButtonContent:Je,cardTitleContent:me})}),pr]}):no&&Y&&Lr?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Rn.Provider,{value:lr,children:(0,F.jsxs)("div",{className:Ie,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[kr&&(0,F.jsx)(Vo,{icon:!1,children:kr}),Ae==="retrying"&&(0,F.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ae==="exhausted"&&(0,F.jsxs)("div",{role:"alert",children:[(0,F.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,F.jsx)("button",{type:"button",onClick:ro,children:"Retry PayPal"})]}),Ae!=="exhausted"&&(0,F.jsx)("div",{"aria-hidden":Ae==="retrying"?!0:void 0,style:Ae==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,F.jsx)(Rl,{sessionId:j,nonce:Y.clientSecret||void 0,billingApiUrl:B,email:Y.customer?.email||Gt?.account?.email,billingName:[Y.customer?.firstName,Y.customer?.lastName].filter(Boolean).join(" ")||[Gt?.account?.firstName,Gt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Yr,clientId:Lr.clientId,environment:Lr.environment,currency:(Y.currency??"usd").toUpperCase(),isSubscription:Y.mode==="subscription",providerObjectType:Lr.providerObjectType,approvalPresentation:Lr.approvalPresentation,existingOrderId:Lr.existingOrderId,onComplete:C,onErrorChange:Ot,onDecline:x,onButtonClick:Qe,runBeforeButtonClick:vn,onInitializationStateChange:Mn,allowAutomaticRetry:mn===0,session:Y,telemetry:o,telemetryContext:f,onInstrument:T,debug:fe},`${Ze}:paypal-init-${mn}`)})]})}),pr]}):Cr==="confirm"?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Rn.Provider,{value:lr,children:(0,F.jsx)(Pa,{flopay:He,paypalFlopay:U,options:Dn??{billingApiUrl:B},onInstrument:T,children:(0,F.jsxs)("div",{className:Ie,children:[kr&&(0,F.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:kr}),ae?ae({onConfirm:yr,isProcessing:sr}):(0,F.jsx)("button",{type:"button",onClick:yr,disabled:sr,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:sr?"not-allowed":"pointer",opacity:sr?.6:1},children:Vr?"Processing...":_e??"Confirm Purchase"})]})},Ze)}),pr]}):(!He||!Dn)&&!(tn&&Cr==="full")?(0,F.jsx)(F.Fragment,{children:pr}):(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(Rn.Provider,{value:lr,children:(0,F.jsxs)(Pa,{flopay:He,paypalFlopay:U,options:Dn??{billingApiUrl:B},onInstrument:T,children:[Ar===1&&(0,F.jsx)("button",{type:"button",onClick:Cn,children:"Retry payment methods"}),K?(0,F.jsxs)(F.Fragment,{children:[kr&&(0,F.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:kr}),(0,F.jsx)(Jd,{sessionId:j,nonce:Y?.clientSecret||void 0,billingApiUrl:B,session:Y,submitLabel:Pe,walletPresentation:h,children:K})]}):(0,F.jsx)(yi,{sessionId:j,nonce:Y?.clientSecret||void 0,telemetry:o,email:Y?.customer?.email||Gt?.account?.email,userId:Y?.customer?.id||Gt?.account?.userId,firstName:Y?.customer?.firstName||Gt?.account?.firstName,lastName:Y?.customer?.lastName||Gt?.account?.lastName,totalAmount:Y?Math.round((0,qe.buildCheckoutDisplayData)(Y).total*100):0,currency:Y?.currency?.toLowerCase()??"usd",onComplete:C,onError:w,onDecline:x,error:kr,onErrorChange:Ot,showPayPal:V,showStripe:_,walletPresentation:h,enabledPaymentMethods:Ar?[]:v??Ye?.data.stripe?.enabledPaymentMethods??Y?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ye?.data.stripe?.enabledPaymentMethodCountries,showApplePay:Z,showGooglePay:k,layout:O,theme:ne,buttonsTheme:Be,buttonsStyles:pe,appearance:Ge,cardButtonContent:De,cardBackButtonContent:Je,cardTitleContent:me,onButtonClick:Qe,onBeforeButtonClick:ke,onBuyerIdentityReady:Yr,enableAVS:Re,...Ee?{cardFieldOrder:Ee}:{},...ee?{cardPreFormSlot:ee}:{},avsLayout:ue,country:Y?.customer?.country,city:Y?.customer?.city,state:Y?.customer?.state,onCountryChange:H,onZipChange:M,avsCheck:!!Re,checkoutType:r?"embedded_checkout":"standard_checkout",checkoutLayout:gs(K,O),className:Ie,submitLabel:Pe,directPaypal:Lr,isSubscription:Y?.mode==="subscription",session:Y,dataAttachmentPending:Ir,dataAttachmentRequiresIdentity:jt,debug:fe})]},Ze)}),pr]})}function Jd({sessionId:e,nonce:t,billingApiUrl:r,session:n,submitLabel:o,walletPresentation:i,children:l}){return(0,F.jsx)(F.Fragment,{children:b.default.Children.map(l,u=>{if(!b.default.isValidElement(u))return u;let m=u.props,C={};return m.sessionId||(C.sessionId=e),!m.nonce&&t&&(C.nonce=t),m.billingApiUrl||(C.billingApiUrl=r),m.submitLabel===void 0&&o!==void 0&&(C.submitLabel=o),m.walletPresentation===void 0&&(C.walletPresentation=i),n?.customer&&(m.email||(C.email=n.customer.email),m.userId||(C.userId=n.customer.id),m.firstName||(C.firstName=n.customer.firstName),m.lastName||(C.lastName=n.customer.lastName)),Object.keys(C).length===0?u:b.default.cloneElement(u,C)})})}function Zd({onButtonClick:e,showPayPal:t,showStripe:r=!0,showApplePay:n,showGooglePay:o,theme:i,buttonsTheme:l,buttonsStyles:u,cardButtonContent:m,cardBackButtonContent:C,cardTitleContent:w}){let[S,x]=(0,b.useState)(!1),H=(0,b.useMemo)(()=>(0,qe.resolveTheme)(i),[i]),M=(0,b.useMemo)(()=>{let v=H?.buttonsLayout??(0,qe.resolveButtonsLayoutTheme)(l);return u?{...v,...u,cardButton:{...v.cardButton,...u.cardButton},cardFormContainer:{...v.cardFormContainer,...u.cardFormContainer},backButton:{...v.backButton,...u.backButton},backButtonIcon:{...v.backButtonIcon,...u.backButtonIcon},submitButton:{...v.submitButton,...u.submitButton},title:{...v.title,...u.title}}:v},[H,l,u]),V=H?.buttonsLayout?.cardButton?.borderRadius??H?.appearance.variables?.borderRadius??8,_=v=>(0,F.jsx)("div",{style:{height:v,borderRadius:V,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),h=m===void 0?{boxSizing:"border-box",height:Xo,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(S){let v=M.cardInputBorder??"#e5e7eb",Z=M.cardInputBackground??"white",k=Fo(C),fe=Fo(w);return(0,F.jsxs)("div",{style:{backgroundColor:M.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...M.cardFormContainer},children:[(0,F.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,F.jsxs)("button",{type:"button",onClick:()=>x(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:k?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...M.backButton},children:[(0,F.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...M.backButtonIcon},children:(0,F.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,F.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,F.jsx)(Do,{content:C})]}),fe?(0,F.jsx)("div",{style:{flex:1}}):(0,F.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...M.title},children:(0,F.jsx)(da,{content:w})})]}),(0,F.jsx)("div",{style:{backgroundColor:Z,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsxs)("div",{style:{display:"flex"},children:[(0,F.jsx)("div",{style:{flex:1,backgroundColor:Z,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{flex:1,backgroundColor:Z,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,F.jsx)("div",{style:{backgroundColor:Z,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,F.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,F.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...M.submitButton,opacity:.5}}),(0,F.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,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&_(Jo),r&&(n||o)&&_(Jo),r&&(0,F.jsx)("button",{type:"button",onClick:()=>{e?.("card"),x(!0)},style:{width:"100%",...h,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:M.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,...M.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:(0,F.jsx)(Do,{content:p})}),(0,F.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var dn=require("react/jsx-runtime"),Jd=44;function rc(e){return new Promise(t=>setTimeout(t,e))}function Zd(e,t){return e instanceof un.FloPayError?e:new un.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 nc({sessionId:e,nonce:t,createSession:r,paymentMethodId:n,checkoutMethod:o,clientId:i,products:l,items:d,subscriptions:p,account:b,successUrl:k,cancelUrl:w,couponCodes:x,tagsData:O,utmMetadata:M,billingApiUrl:W,locale:_,theme:h,appearance:v,buttonsTheme:te,buttonsStyles:S,onSuccess:Pe,onError:j,onDecline:Q,children:Be,disabled:se=!1,type:je="button",style:Je,...me}){let pe=(0,pt.useMemo)(()=>(0,un.resolveBillingApiUrl)(W),[W]),Ke=(0,pt.useMemo)(()=>eu({createSession:r,clientId:i,products:l,items:d,subscriptions:p,account:b,successUrl:k,cancelUrl:w,couponCodes:x,tagsData:O,utmMetadata:M}),[b,w,i,x,r,l,d,p,k,O,M]),[Re,_e]=(0,pt.useState)(!1),[Ee,re]=(0,pt.useState)(null),[ae,ge]=(0,pt.useState)(null),[Me,K]=(0,pt.useState)(!1),[ee,ye]=(0,pt.useState)(null),[L,ve]=(0,pt.useState)(null),Y=(0,pt.useRef)(!0),be=(0,pt.useRef)(null),X=(0,pt.useRef)(L),ct=(0,pt.useRef)(Pe),Ge=(0,pt.useRef)(j),$e=(0,pt.useRef)(Q),lt=(0,pt.useCallback)(m=>ei(be,async P=>{try{return await m(P)}catch(H){throw P.aborted?Wo(H):H}}),[]);(0,pt.useEffect)(()=>{X.current=L},[L]),(0,pt.useEffect)(()=>{ct.current=Pe},[Pe]),(0,pt.useEffect)(()=>{Ge.current=j},[j]),(0,pt.useEffect)(()=>{$e.current=Q},[Q]),(0,pt.useEffect)(()=>(Y.current=!0,()=>{Y.current=!1,be.current?.abort()}),[]),(0,pt.useEffect)(()=>{if(typeof window>"u")return;let m=P=>{P.key==="Escape"&&ve(null)};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[]);let Ye=(0,pt.useCallback)((m,P=Ca)=>{$e.current?.(gr(P,m,{code:m.code,declineCode:m.declineCode}))},[]),dt=(0,pt.useCallback)(async m=>{Y.current&&(ge(null),K(m.result.status==="authorized"),re("success"),await rc(600),Y.current&&(0,tt.invokeMerchantCallback)(()=>ct.current?.(m)))},[]),We=(0,pt.useCallback)(async(m,P)=>{Y.current&&(Ge.current?.(m),P?.emitDecline&&Ye(m,P.method),ge(m.message),K(!1),re("error"),await rc(400))},[Ye]),Et=(0,pt.useCallback)(async(m,P,H)=>{let V=m.data.session??null;if(!V)throw so(new un.FloPayError("No session data returned","api_error"),P);let he=V.clientSecret||t;if(Xn(V)){await dt({result:Yn(V,P),session:V,sessionId:V.id||P,autoCompleted:!1});return}if(V.status==="expired")throw so(Wa(V),V.id||P);try{if(m.autoProcessingPending){let A=m.autoProcessingPending,ne=new bi.PaymentAPI(pe),q=await lt(Ct=>ne.waitForCheckoutSessionCompletion(A.sessionId,{initialDelayMs:A.retryAfterMs,nonce:he,statusUrl:A.statusUrl,signal:Ct})),Ce=lo(q,V),rt=q.autoProcessingError?.type==="3ds_required"&&q.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.autoProcessingError.nextActionRedirectUrl}:null;if(rt&&P&&he){let Ct=await lt(ht=>Ho(rt,{billingApiUrl:pe,sessionId:P,nonce:he,session:V,signal:ht,telemetry:!0}));await dt({result:Ct,session:V,sessionId:V.id||P,autoCompleted:!1});return}if(q.autoProcessingError)throw jn(q.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.autoProcessingError.checkoutMethod});if(!Xn(Ce))throw No(Ce);await dt({result:Yn(Ce,P),session:Ce,sessionId:Ce.id||P,autoCompleted:!1});return}if(m.autoProcessingError){let A=m.autoProcessingError.nextActionRedirectUrl;if(m.autoProcessingError.type==="3ds_required"&&A&&P&&he){let ne=await lt(Ct=>Tl({billingApiUrl:pe,sessionId:P,nonce:he,nextActionRedirectUrl:A,signal:Ct}));if(ne.status==="declined")throw jn({type:ne.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ne.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:m.autoProcessingError.checkoutMethod});let Ce=await new bi.PaymentAPI(pe).waitForCheckoutSessionCompletion(P,{initialDelayMs:0,nonce:he}),rt=lo(Ce,V);if(!Xn(rt))throw jn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:m.autoProcessingError.checkoutMethod});await dt({result:Yn(rt,P),session:rt,sessionId:rt.id||P,autoCompleted:!1});return}throw jn(m.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:m.autoProcessingError.checkoutMethod})}if(H?.fromCreateSession&&m.autoProcessingAttempted===!0)throw jn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let T=await Ko({billingApiUrl:pe,sessionId:P??V.id,session:V,nonce:he});if(T.type==="next_action_required"&&he){let A=P??V.id,ne=await lt(q=>Ho(T,{billingApiUrl:pe,sessionId:A,nonce:he,session:V,signal:q,telemetry:!0}));await dt({result:ne,session:V,sessionId:V.id||A,autoCompleted:!1});return}if(T.type!=="success")throw jn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await dt({result:T.result,session:V,sessionId:V.id||P,autoCompleted:!1})}catch(T){let A=V.id||P,ne=so(Sa(T),A);if(ne.code==="three_ds_aborted")return;if(ne.code==="checkout_processing_timeout"){if(!Y.current)return;ye(ne.message),(0,tt.invokeMerchantCallback)(()=>Ge.current?.(ne));return}await We(ne,{emitDecline:!0,method:ne.checkoutMethod??Ca}),Qd(ne,A)&&A&&Y.current&&ve({sessionId:A,errorMessage:ne.message,nonce:he||void 0,payPalOrderId:ne.orderId})}},[t,pe,lt,We,dt]),Ut=(0,pt.useCallback)(async m=>{if(me.onClick?.(m),!(m.defaultPrevented||se||Re)){if(ve(null),ye(null),e&&Ke){let P=new un.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await We(P),Y.current&&(re(null),ge(null));return}if(!e&&!Ke){let P=new un.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await We(P),Y.current&&(re(null),ge(null));return}_e(!0),ge(null),K(!1),re("processing");try{let P=new bi.PaymentAPI(pe);if(e){let H=await P.getUnifiedCheckoutSession(e,t);await Et(H,e);return}try{let H=await P.createAndFetchSession({...Ke});await Et(H,H.data.session?.id??null,{fromCreateSession:!0})}catch(H){if(Ha(H)==="session_auto_completed"){await dt({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw H}}catch(P){await We(so(Zd(P,"Automatic payment failed. Please try again."),e))}finally{Y.current&&(re(null),ge(null),_e(!1))}}},[me.onClick,Ke,se,Re,t,Et,pe,e,We,dt]),kt=(0,pt.useCallback)(m=>{let P=X.current;ve(null),ct.current?.({result:m,session:null,sessionId:P?.sessionId??null,autoCompleted:!1})},[]),At=(0,pt.useCallback)(m=>{Ge.current?.(m)},[]),N=(0,pt.useCallback)(m=>{$e.current?.(m)},[]),fe=(0,pt.useMemo)(()=>(0,un.resolveTheme)(h),[h]),Qe=(0,pt.useMemo)(()=>{let m=fe?.buttonsLayout??(0,un.resolveButtonsLayoutTheme)(te);return S?{...m,...S,cardButton:{...m.cardButton,...S.cardButton}}:m},[fe,te,S]),G=(0,pt.useMemo)(()=>{let m=fe?.appearance;return v?m?{...m,...v,variables:{...m.variables,...v.variables}}:v:m},[v,fe]),Ne=G?.variables,Rt=Ne?.colorPrimary??"#4A49FF",Ze=Ne?.colorPrimaryHover??(0,Ir.darkenHex)(Rt,.12),Tt=Ne?.borderRadius??"8px";return(0,dn.jsxs)(dn.Fragment,{children:[(0,dn.jsx)("button",{...me,type:je,onClick:Ut,disabled:se||Re,"aria-busy":Re,style:{width:"100%",...Be===void 0?{boxSizing:"border-box",height:Jd,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Qe.cardButton,...us({themeBundle:fe,resolvedPrimaryColor:Rt,resolvedBorderRadius:Tt,submitButtonStyle:Qe.submitButton,explicitPrimaryColor:Ne?.colorPrimary}),fontSize:Qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:se||Re?"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:se||Re?.6:1,...Je},onMouseEnter:m=>{me.onMouseEnter?.(m),!m.defaultPrevented&&!se&&!Re&&(fe||Ne?.colorPrimary)&&(m.currentTarget.style.backgroundColor=Ze)},onMouseLeave:m=>{me.onMouseLeave?.(m),!m.defaultPrevented&&(fe||Ne?.colorPrimary)&&(m.currentTarget.style.backgroundColor=Rt)},onMouseDown:m=>{me.onMouseDown?.(m),m.defaultPrevented||(m.currentTarget.style.transform="scale(0.985)")},onMouseUp:m=>{me.onMouseUp?.(m),m.defaultPrevented||(m.currentTarget.style.transform="scale(1)")},children:(0,dn.jsx)(Do,{content:Be})}),ee&&(0,dn.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ee}),Ee&&(0,dn.jsx)(qr,{status:Ee,errorMessage:ae,authorized:Me}),L&&(0,dn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:m=>{m.target===m.currentTarget&&ve(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,dn.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,dn.jsx)(vi,{sessionId:L.sessionId,nonce:L.nonce,checkoutMode:"full",billingApiUrl:pe,locale:_,theme:h,...G?{appearance:G}:{},buttonsTheme:te,buttonsStyles:S,initialErrorMessage:L.errorMessage,initialPayPalOrderId:L.payPalOrderId,cardTitleContent:null,onComplete:kt,onError:At,onDecline:N})})})]})}var Si=require("@flopay/js/card-setup"),kr=require("@flopay/shared"),Ft=require("react");var oc=require("@flopay/shared");function Ci(e){return(0,oc.computeCardSetupOverlayTheme)(e)}var $n=require("react/jsx-runtime"),xa=class extends kr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function ro(e,t={}){let r=e instanceof kr.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 xa(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,loading:l=null,onReady:d,onComplete:p,onDecline:b,onCancel:k,onValidation:w,onError:x}){let[O,M]=(0,Ft.useState)(null),[W,_]=(0,Ft.useState)(null),[h,v]=(0,Ft.useState)(null),[te,S]=(0,Ft.useState)(null),[Pe,j]=(0,Ft.useState)(null),Q=(0,Ft.useRef)(!1),Be=(0,Ft.useRef)(!1),se=(0,Ft.useMemo)(()=>typeof o=="object"?void 0:(0,kr.resolveTheme)(o),[o]),je=(0,Ft.useMemo)(()=>typeof o=="object"?o:se?(0,Ir.computeVaultCardThemeColors)({appearance:se.appearance,buttonsStyles:se.buttonsLayout,layout:"default"}):null,[se,o]),Je=(0,Ft.useMemo)(()=>(0,Ra.mergeCardSetupSurface)(se?.buttonsLayout.cardFormContainer,i),[se,i]),me=(0,Ft.useMemo)(()=>se?Ci(se):void 0,[se]),pe=(0,Ft.useRef)(d),Ke=(0,Ft.useRef)(x),Re=(0,Ft.useRef)(p),_e=(0,Ft.useRef)(b),Ee=(0,Ft.useRef)(k),re=(0,Ft.useRef)(w),ae=(0,Ft.useRef)(!1),ge=(0,Ft.useRef)(!1),Me=(0,Ft.useRef)(0);return pe.current=d,Ke.current=x,Re.current=p,_e.current=b,Ee.current=k,re.current=w,(0,Ft.useEffect)(()=>{let K=Me.current+1;return Me.current=K,()=>{queueMicrotask(()=>{Me.current===K&&(ae.current||ge.current||(ge.current=!0,(0,tt.invokeMerchantCallback)(()=>{Ee.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Ft.useEffect)(()=>{let K=!0,ee=(0,kr.resolveBillingApiUrl)(r),ye=new Si.PaymentAPI(ee,{telemetry:n});return M(null),_(null),v(null),ae.current=!1,ge.current=!1,(async()=>{try{if(!e.trim())throw new kr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new kr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let L=await ye.getUnifiedCheckoutSession(e,t);if(!K)return;let ve=L.data.session;if(!ve||!(0,kr.isCardSetupCheckoutSession)(ve))throw new kr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Y=ve.vault;(0,kr.isMountableVaultBlock)(Y)||(Y=await ye.getVaultCapture(e,t));let be=(0,kr.resolveVaultMountOptions)(Y,{billingApiUrl:ee,sessionId:e,nonce:t});if(!be)throw new kr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!K)return;_(be),M(new Si.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(L){if(!K)return;let ve=ro(L);ae.current=!0,v(ve),(0,tt.invokeMerchantCallback)(()=>Ke.current?.(ve))}})(),()=>{K=!1,ye.destroy()}},[r,t,e,n]),(0,Ft.useEffect)(()=>{if(!O)return;let K=!1;Be.current=!1,Q.current=!1;let ee=O.on("submitting",()=>{Q.current=!0,j(null),S("processing")}),ye=O.on("complete",Y=>{ae.current=!0,Q.current=!1,S("success"),(async()=>(await new Promise(be=>setTimeout(be,600)),!Be.current&&(Be.current=!0,(0,tt.invokeMerchantCallback)(()=>{Re.current?.({status:"succeeded",sessionId:e,...Y.paymentMethod?{paymentMethod:Y.paymentMethod}:{}})}),K||S(null))))()}),L=O.on("decline",Y=>{ae.current=!0,Q.current=!1,j(Y.message??null),S("error"),(0,tt.invokeMerchantCallback)(()=>{_e.current?.({status:"declined",sessionId:e,...Y.declineReason?{reason:Y.declineReason}:{},...Y.message?{message:Y.message}:{}})}),(async()=>(await new Promise(be=>setTimeout(be,400)),K||S(null)))()}),ve=O.on("challenge_dismissed",()=>{S(null)});return()=>{K=!0,ee(),ye(),L(),ve()}},[O,e]),h?(0,$n.jsx)("div",{role:"alert",children:h.message}):!O||!W?.html?(0,$n.jsx)($n.Fragment,{children:l}):(0,$n.jsxs)($n.Fragment,{children:[te&&(0,$n.jsx)(qr,{status:te,errorMessage:Pe,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...me?{theme:me}:{}}),(0,$n.jsx)(co,{capture:O,html:W.html,messageToken:W.messageToken,expectedOrigin:W.expectedOrigin,verificationRequired:W.verificationRequired,theme:je,containerStyle:Je,onReady:()=>{(0,tt.invokeMerchantCallback)(()=>pe.current?.())},onValidation:K=>{(0,tt.invokeMerchantCallback)(()=>re.current?.(K))},onError:K=>{if(!K)return;Q.current&&(Q.current=!1,j(K),S("error"),setTimeout(()=>S(null),400));let ee=ro(new Error(K),{code:"card_setup_widget_failed",retryable:!0});(0,tt.invokeMerchantCallback)(()=>Ke.current?.(ee))}})]})}var ic=require("@flopay/js/card-setup"),uo=require("@flopay/shared"),sc=require("@paypal/paypal-js"),So=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:d,email:p},onSubmitting:b,onConfirmed:k,onFailed:w,onAbandoned:x}){let O=(0,So.useRef)(null),M=(0,So.useRef)({onSubmitting:b,onConfirmed:k,onFailed:w,onAbandoned:x});M.current={onSubmitting:b,onConfirmed:k,onFailed:w,onAbandoned:x};let[W]=(0,So.useState)(()=>(0,zn.detectPayPalEnvironment)().inAppBrowser);return(0,So.useEffect)(()=>{let _=!0,h,v=new ic.PaymentAPI(i,{telemetry:l}),te={userId:d,email:p};return(async()=>{try{let S=await(0,sc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),Pe=O.current;if(!_||!Pe)return;if(!S?.Buttons)throw new uo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let j=S.Buttons({createVaultSetupToken:async()=>{M.current.onSubmitting();let Q=await v.createSessionIntent(n,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(Q.provider!=="paypal"||Q.providerObjectType!=="setup_token")throw new uo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return Q.providerObjectId},onApprove:async Q=>{let Be=Q.vaultSetupToken;if(!Be)throw new uo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let se=await v.processPayment(te.userId,{sessionId:n,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:Be,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:te});if(!se.ok)throw new uo.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:se.status});_&&M.current.onConfirmed()},onCancel:()=>{_&&M.current.onAbandoned()},onError:Q=>{if(!_)return;let{popupBlocked:Be}=(0,ke.classifyExternalMethodFailure)(Q,{inAppBrowser:W,handoffObserved:!1});M.current.onFailed(Be?new Error((0,ke.buildExternalMethodRecoveryMessage)("PayPal",!0,W)):Q,{code:Be?"popup_blocked":"paypal_setup_failed",retryable:!0})}});h=()=>j.close(),await j.render(Pe)}catch(S){if(!_)return;M.current.onFailed(S,{code:"paypal_unavailable",retryable:!0})}})(),()=>{_=!1,h?.().catch(()=>{}),v.destroy()}},[i,e,r,p,t,W,o,n,l,d]),(0,cc.jsx)("div",{ref:O,"data-flopay-paypal-setup":""})}var uc=require("@flopay/js/card-setup"),po=require("@flopay/shared"),Wn=require("@stripe/react-stripe-js"),pc=require("@stripe/stripe-js"),Ar=require("react");var _r=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"}},vs=new Map;function tu(e){let t=vs.get(e);if(t)return t;let r=(0,pc.loadStripe)(e).catch(n=>{throw vs.delete(e),n});return vs.set(e,r),r}function ru(e){return e?(0,po.toStripeAppearance)(e):void 0}function nu(e){return(0,ke.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function dc(e){return e==="paypal"?"PayPal":(0,po.getStripeMethodDisplayName)(e)}function ou(){return typeof window>"u"?"":window.location.href}var au={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function yc(e){let{publishableKey:t,method:r,currency:n,futureUse:o,futureUseUnsupported:i,appearance:l}=e,[d]=(0,Ar.useState)(()=>tu(t)),p=(0,Ar.useMemo)(()=>{let b=ru(l),k=(0,po.resolveSetupFutureUsage)({futureUse:o,futureUseUnsupported:i},r,"setup");return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:mc[r]?.types??[r],...k?{setupFutureUsage:k}:{},...b?{appearance:b}:{}}},[l,n,o,i,r]);return(0,_r.jsx)(Wn.Elements,{stripe:d,options:p,children:(0,_r.jsx)(iu,{...e})})}function iu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,appearance:l,themeId:d,buttonsLayout:p,onSubmitting:b,onConfirmed:k,onDeclined:w,onFailed:x,onValidation:O,onUnavailable:M}){let W=(0,Wn.useStripe)(),_=(0,Wn.useElements)(),[h,v]=(0,Ar.useState)(!1),[te,S]=(0,Ar.useState)("loading"),[Pe,j]=(0,Ar.useState)(!1),[Q,Be]=(0,Ar.useState)(!1),se=(0,Ar.useRef)(!1),[je]=(0,Ar.useState)(()=>(0,zn.detectPayPalEnvironment)()),[Je,me]=(0,Ar.useState)(!1),pe=(0,Ar.useCallback)((ae,ge)=>{if((0,ke.classifyExternalMethodFailure)(ae,{inAppBrowser:je.inAppBrowser,handoffObserved:!1}).popupBlocked){me(!0),x(new Error((0,ke.buildExternalMethodRecoveryMessage)(dc(e),!0,je.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}x(ge.message===void 0?ae:new Error(ge.message),{code:ge.code,retryable:!0})},[je.inAppBrowser,e,x]),Ke=(0,Ar.useCallback)(async()=>{if(!(!W||!_||se.current)){se.current=!0,v(!0);try{let ae=await _.submit();if(ae.error){O(ae.error.message??null);return}b();let ge=await new uc.PaymentAPI(o,{telemetry:i}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(ge.provider!=="stripe"||ge.intentKind!=="setup")throw new po.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let Me=await W.confirmSetup({elements:_,clientSecret:ge.clientSecret,confirmParams:{return_url:ou()},redirect:"if_required"});if(Me.error){nu(Me.error)?w({...Me.error.decline_code||Me.error.code?{reason:Me.error.decline_code??Me.error.code}:{},...Me.error.message?{message:Me.error.message}:{}}):pe(Me.error,{code:"payment_method_setup_provider_failed",message:Me.error.message??"The payment method could not be saved."});return}k()}catch(ae){pe(ae,{code:"payment_method_setup_failed"})}finally{se.current=!1,v(!1)}}},[o,t,_,e,n,k,w,b,O,pe,r,W,i]),Re=mc[e]?.wallet,_e=Re==="paypal"&&(0,qn.resolveStripePayPalPresentation)(je,"auto",Je?"blocked":je.popupCapability)==="redirect",Ee=l?.variables?.borderRadius??p?.cardButton?.borderRadius??8;if(t==="wallet"&&Re&&!_e)return(0,_r.jsxs)(_r.Fragment,{children:[(0,_r.jsx)(Xo,{}),(0,_r.jsx)(ka,{state:te,borderRadius:Ee,children:(0,_r.jsx)(Wn.ExpressCheckoutElement,{options:{...ii,paymentMethods:ai([e])},onReady:ae=>{let ge=wa(ae,[Re]);S(ge),ge==="unavailable"&&M()},onLoadError:()=>{S("load_error"),M()},onConfirm:()=>{Ke()}})})]});let re=dc(e);return(0,_r.jsxs)(_r.Fragment,{children:[Pe?(0,_r.jsx)(oi,{method:e,themeId:d,hasNextStep:!0,highlighted:Q,disabled:h,onClick:()=>Be(ae=>!ae),backgroundColor:p?.cardButton?.backgroundColor,borderColor:p?.cardInputBorder,textColor:p?.cardButton?.color,borderRadius:Ee}):null,(0,_r.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!Q,style:Q?{display:"flex",flexDirection:"column"}:au,children:[(0,_r.jsx)(Wn.PaymentElement,{options:{layout:si},onReady:()=>j(!0),onLoadError:()=>M(),onChange:ae=>{ae.complete&&O(null)}}),(0,_r.jsx)(li,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!W||!_||h||!Q,onClick:()=>{Ke()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:p?.submitButton,children:h?"Saving\u2026":`Save ${re}`})]})]})}var Aa=require("@flopay/js/card-setup"),nr=require("@flopay/shared"),qe=$i(require("react"),1);var Zo=require("@flopay/js/card-setup"),vr=require("@flopay/shared");var rr=require("react/jsx-runtime"),su=15,lu=2e3;function cu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function bs(e){return new Promise(t=>setTimeout(t,e))}async function du(e,t,r){if(!t.trim())throw new nr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new nr.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,nr.isCardSetupCheckoutSession)(o))throw new nr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let i=(0,vr.readSetupAdvertisement)(n);if(!(0,vr.advertisesAnyMethod)(i)){let{skippedForMissingCurrency:l}=i,d=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 nr.FloPayError(d,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:o,advertisement:i}}async function uu(e,t,r,n,o){let i=t.vault??null;(0,nr.isMountableVaultBlock)(i)||(i=await e.getVaultCapture(r,n));let l=(0,nr.resolveVaultMountOptions)(i,{billingApiUrl:o,sessionId:r,nonce:n});if(!l)throw new nr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return l}var wi=class extends qe.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:d,loading:p=null,onReady:b,onComplete:k,onDecline:w,onCancel:x,onValidation:O,onError:M}){let[W]=(0,qe.useState)(Zo.readSetupRedirectReturn),[_,h]=(0,qe.useState)(null),[v,te]=(0,qe.useState)(!1),[S,Pe]=(0,qe.useState)(null),[j,Q]=(0,qe.useState)(null),[Be,se]=(0,qe.useState)(null),[je,Je]=(0,qe.useState)(null),[me,pe]=(0,qe.useState)(()=>new Set),Ke=(0,qe.useRef)(me),Re=(0,qe.useRef)(null);Re.current=_;let _e=(0,qe.useRef)(!1),Ee=(0,qe.useRef)(!1),re=(0,qe.useRef)(!1),ae=(0,qe.useRef)(!1),ge=(0,qe.useRef)(0),Me=(0,qe.useRef)(0),K=(0,qe.useRef)(!1),ee=(0,qe.useMemo)(()=>typeof l=="object"?void 0:(0,nr.resolveTheme)(l),[l]),ye=(0,qe.useMemo)(()=>typeof l=="object"?l:ee?(0,Ir.computeVaultCardThemeColors)({appearance:ee.appearance,buttonsStyles:ee.buttonsLayout,layout:"default"}):null,[ee,l]),L=(0,qe.useMemo)(()=>(0,Ra.mergeCardSetupSurface)(ee?.buttonsLayout.cardFormContainer,d),[ee,d]),ve=(0,qe.useMemo)(()=>ee?Ci(ee):void 0,[ee]),Y=(0,qe.useRef)({sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,onReady:b,onComplete:k,onDecline:w,onCancel:x,onValidation:O,onError:M});Y.current={sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,onReady:b,onComplete:k,onDecline:w,onCancel:x,onValidation:O,onError:M},(0,qe.useEffect)(()=>{K.current=!0;let T=ge.current+1;return ge.current=T,()=>{K.current=!1,Me.current+=1,queueMicrotask(()=>{ge.current===T&&(re.current||ae.current||(ae.current=!0,(0,tt.invokeMerchantCallback)(()=>{Y.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let be=(0,qe.useCallback)((T,A)=>{re.current=!0,_e.current=!1,Je({status:"success",wording:T,message:null}),(async()=>(await bs(600),!Ee.current&&(Ee.current=!0,(0,tt.invokeMerchantCallback)(()=>{Y.current.onComplete?.({status:"succeeded",sessionId:Y.current.sessionId,...A?{paymentMethod:A}:{}})}),K.current&&Je(null))))()},[]),X=(0,qe.useCallback)((T,A)=>{re.current=!0,_e.current=!1,Je({status:"error",wording:T,message:A.message??null}),(0,tt.invokeMerchantCallback)(()=>{Y.current.onDecline?.({status:"declined",sessionId:Y.current.sessionId,...A.reason?{reason:A.reason}:{},...A.message?{message:A.message}:{}})}),(async()=>(await bs(400),K.current&&Je(null)))()},[]),ct=(0,qe.useCallback)((T,A)=>{_e.current?(_e.current=!1,Je({status:"error",wording:T,message:A.message}),setTimeout(()=>{K.current&&Je(null)},400)):Je(null),(0,tt.invokeMerchantCallback)(()=>Y.current.onError?.(A))},[]),Ge=(0,qe.useCallback)(async T=>{let A=Me.current+1;Me.current=A;let ne=()=>!K.current||A!==Me.current;_e.current=!0,Je({status:"processing",wording:"payment_method",message:null});let q=new Aa.PaymentAPI((0,nr.resolveBillingApiUrl)(Y.current.billingApiUrl),{telemetry:Y.current.telemetry});try{for(let Ce=0;Ce<su;Ce+=1){if((Ce>0||T.waitFirst)&&await bs(lu),ne())return;let rt=await q.getUnifiedCheckoutSession(Y.current.sessionId,Y.current.nonce);if(ne())return;let Ct=rt.data.session?.status;if(Ct==="complete"){te(!0),be("payment_method");return}if(Ct==="expired")throw new nr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new nr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(Ce){if(ne())return;let rt=Ce instanceof nr.FloPayError&&Ce.code==="payment_method_setup_unverified";ct("payment_method",ro(Ce,rt?{retryable:!0}:{}))}finally{q.destroy()}},[ct,be]);(0,qe.useEffect)(()=>{let T=!0,A=(0,nr.resolveBillingApiUrl)(o),ne=new Aa.PaymentAPI(A,{telemetry:i});h(null),te(!1),Pe(null),Q(null),se(null);let q=new Set;return Ke.current=q,pe(q),re.current=!1,ae.current=!1,Ee.current=!1,(async()=>{try{let{session:Ce,advertisement:rt}=await du(ne,r,n);if(!T)return;let Ct={advertisement:rt,customer:cu(Ce),...Ce.futureUse?{futureUse:Ce.futureUse}:{},...Ce.futureUseUnsupported?{futureUseUnsupported:Ce.futureUseUnsupported}:{}};if(W){if((0,Zo.clearSetupRedirectParams)(),Ce.status==="complete"){te(!0),h(Ct),be("payment_method");return}W.failed?X("payment_method",{reason:"redirect_failed"}):Ge({waitFirst:!0})}let ht=rt.card?await uu(ne,Ce,r,n,A):null;if(!T)return;h(Ct),ht&&(Q(ht),Pe(new Aa.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:i})))}catch(Ce){if(!T)return;let rt=ro(Ce);re.current=!0,se(rt),(0,tt.invokeMerchantCallback)(()=>Y.current.onError?.(rt))}})(),()=>{T=!1,ne.destroy()}},[o,n,W,X,be,r,i,Ge]),(0,qe.useEffect)(()=>{if(!S)return;_e.current=!1;let T=S.on("submitting",()=>{_e.current=!0,Je({status:"processing",wording:"card",message:null})}),A=S.on("complete",Ce=>{be("card",Ce.paymentMethod)}),ne=S.on("decline",Ce=>{X("card",{...Ce.declineReason?{reason:Ce.declineReason}:{},...Ce.message?{message:Ce.message}:{}})}),q=S.on("challenge_dismissed",()=>{Je(null)});return()=>{T(),A(),ne(),q()}},[S,X,be]);let $e=(0,qe.useCallback)((T,A,ne)=>{if(ne.retryable){ct("payment_method",ro(A,ne));return}if(Ke.current.has(T))return;let q=new Set(Ke.current);q.add(T),Ke.current=q,pe(q);let Ce=Re.current?.advertisement,rt=Ce?(0,vr.advertisedMethodKeys)(Ce).some(Ct=>!q.has(Ct)):!1;ct("payment_method",ro(A,{code:ne.code,retryable:rt}))},[ct]),lt=(0,qe.useMemo)(()=>({onSubmitting:()=>{_e.current=!0,Je({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Ge({waitFirst:!1})},onDeclined:T=>X("payment_method",T),onValidation:T=>{(0,tt.invokeMerchantCallback)(()=>Y.current.onValidation?.(T))},onAbandoned:()=>{_e.current=!1,Je(null)}}),[X,Ge]),Ye=(0,qe.useRef)($e);Ye.current=$e;let dt=(0,qe.useRef)(new Map),We=T=>{let A=dt.current.get(T);if(A)return A;let ne=(q,Ce)=>Ye.current(T,q,Ce);return dt.current.set(T,ne),ne},Et=(0,qe.useCallback)(T=>{if(Ke.current.has(T))return;let A=new Set(Ke.current);A.add(T),Ke.current=A,pe(A);let ne=Re.current?.advertisement;ne&&(0,vr.advertisedMethodKeys)(ne).some(Ce=>!A.has(Ce))||ct("payment_method",ro(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ct]),Ut=(0,qe.useRef)(Et);Ut.current=Et;let kt=(0,qe.useRef)(new Map),At=T=>{let A=kt.current.get(T);if(A)return A;let ne=()=>Ut.current(T);return kt.current.set(T,ne),ne},N=je?(0,rr.jsx)(qr,{status:je.status,errorMessage:je.message,...(0,vr.setupOverlayLabels)(je.wording),successNote:null,...ve?{theme:ve}:{}}):null;if(Be)return(0,rr.jsx)("div",{role:"alert",children:Be.message});if(!_||v)return(0,rr.jsxs)(rr.Fragment,{children:[N,_?null:p]});let{advertisement:fe,customer:Qe,futureUse:G,futureUseUnsupported:Ne}=_,Rt=(0,nr.resolveBillingApiUrl)(o),Ze=i===void 0?{}:{telemetry:i},Tt=fe.stripe.filter(({method:T})=>!me.has(T)),U=me.has("paypal")?null:fe.paypal,m=!!(fe.card&&S&&j?.html),P=({method:T,publishableKey:A,currency:ne})=>(0,rr.jsx)("div",{"data-flopay-payment-method":T,style:{display:"contents"},children:(0,rr.jsx)(wi,{onFailed:We(T),children:(0,rr.jsx)(qe.Suspense,{fallback:null,children:(0,rr.jsx)(e,{method:T,category:(0,vr.stripeMethodCategory)(T),publishableKey:A,currency:ne,...G?{futureUse:G}:{},...Ne?{futureUseUnsupported:Ne}:{},sessionId:r,nonce:n,billingApiUrl:Rt,...Ze,...ee?{appearance:ee.appearance,buttonsLayout:ee.buttonsLayout}:{},...typeof l=="string"?{themeId:l}:{},...lt,onFailed:We(T),onUnavailable:At(T)})})})},T),H=Tt.filter(({method:T})=>(0,vr.stripeMethodCategory)(T)==="wallet"),V=Tt.filter(({method:T})=>(0,vr.stripeMethodCategory)(T)!=="wallet"),he=Tt.length>0||U!==null;return(0,rr.jsxs)(rr.Fragment,{children:[N,he?(0,rr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[H.map(P),U?(0,rr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,rr.jsx)(wi,{onFailed:We("paypal"),children:(0,rr.jsx)(qe.Suspense,{fallback:null,children:(0,rr.jsx)(t,{clientId:U.clientId,...U.environment?{environment:U.environment}:{},...fe.currency?{currency:fe.currency}:{},sessionId:r,nonce:n,billingApiUrl:Rt,customer:Qe,...Ze,...lt,onFailed:We("paypal"),onUnavailable:At("paypal")})})})}):null,V.map(P)]}):null,m&&he?(0,rr.jsx)(ci,{label:"or add a card"}):null,m&&S&&j?.html?(0,rr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,rr.jsx)(co,{capture:S,html:j.html,messageToken:j.messageToken,expectedOrigin:j.expectedOrigin,verificationRequired:j.verificationRequired,theme:ye,containerStyle:L,onReady:()=>{(0,tt.invokeMerchantCallback)(()=>Y.current.onReady?.())},onValidation:T=>{(0,tt.invokeMerchantCallback)(()=>Y.current.onValidation?.(T))},onError:T=>{T&&ct("card",ro(new Error(T),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var hc=require("react/jsx-runtime"),pu={StripeSetupMethod:yc,PayPalSetupMethod:lc};function gc(e){return(0,hc.jsx)(fc,{...e,branches:pu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,F.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&_(Xo),r&&(n||o)&&_(Xo),r&&(0,F.jsx)("button",{type:"button",onClick:()=>{e?.("card"),x(!0)},style:{width:"100%",...h,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:M.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,...M.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:(0,F.jsx)(Bo,{content:m})}),(0,F.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var cn=require("react/jsx-runtime"),Qd=44;function nc(e){return new Promise(t=>setTimeout(t,e))}function eu(e,t){return e instanceof dn.FloPayError?e:new dn.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:o,clientId:i,products:l,items:u,subscriptions:m,account:C,successUrl:w,cancelUrl:S,couponCodes:x,tagsData:H,utmMetadata:M,billingApiUrl:V,locale:_,theme:h,appearance:v,buttonsTheme:Z,buttonsStyles:k,onSuccess:fe,onError:O,onDecline:ne,children:Be,disabled:pe=!1,type:De="button",style:Je,...me}){let de=(0,pt.useMemo)(()=>(0,dn.resolveBillingApiUrl)(V),[V]),Qe=(0,pt.useMemo)(()=>ru({createSession:r,clientId:i,products:l,items:u,subscriptions:m,account:C,successUrl:w,cancelUrl:S,couponCodes:x,tagsData:H,utmMetadata:M}),[C,S,i,x,r,l,u,m,w,H,M]),[ke,Re]=(0,pt.useState)(!1),[Ee,ee]=(0,pt.useState)(null),[ue,Pe]=(0,pt.useState)(null),[Ie,ve]=(0,pt.useState)(!1),[Q,K]=(0,pt.useState)(null),[N,_e]=(0,pt.useState)(null),ae=(0,pt.useRef)(!0),ge=(0,pt.useRef)(null),B=(0,pt.useRef)(N),$e=(0,pt.useRef)(fe),Ge=(0,pt.useRef)(O),We=(0,pt.useRef)(ne),ct=(0,pt.useCallback)(p=>Qa(ge,async P=>{try{return await p(P)}catch(G){throw P.aborted?$o(G):G}}),[]);(0,pt.useEffect)(()=>{B.current=N},[N]),(0,pt.useEffect)(()=>{$e.current=fe},[fe]),(0,pt.useEffect)(()=>{Ge.current=O},[O]),(0,pt.useEffect)(()=>{We.current=ne},[ne]),(0,pt.useEffect)(()=>(ae.current=!0,()=>{ae.current=!1,ge.current?.abort()}),[]),(0,pt.useEffect)(()=>{if(typeof window>"u")return;let p=P=>{P.key==="Escape"&&_e(null)};return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p)}},[]);let Ye=(0,pt.useCallback)((p,P=Ca)=>{We.current?.(gr(P,p,{code:p.code,declineCode:p.declineCode}))},[]),dt=(0,pt.useCallback)(async p=>{ae.current&&(Pe(null),ve(p.result.status==="authorized"),ee("success"),await nc(600),ae.current&&(0,rt.invokeMerchantCallback)(()=>$e.current?.(p)))},[]),He=(0,pt.useCallback)(async(p,P)=>{ae.current&&(Ge.current?.(p),P?.emitDecline&&Ye(p,P.method),Pe(p.message),ve(!1),ee("error"),await nc(400))},[Ye]),Et=(0,pt.useCallback)(async(p,P,G)=>{let $=p.data.session??null;if(!$)throw io(new dn.FloPayError("No session data returned","api_error"),P);let he=$.clientSecret||t;if(Yn($)){await dt({result:Gn($,P),session:$,sessionId:$.id||P,autoCompleted:!1});return}if($.status==="expired")throw io($a($),$.id||P);try{if(p.autoProcessingPending){let A=p.autoProcessingPending,te=new vi.PaymentAPI(de),j=await ct(bt=>te.waitForCheckoutSessionCompletion(A.sessionId,{initialDelayMs:A.retryAfterMs,nonce:he,statusUrl:A.statusUrl,signal:bt})),Ce=so(j,$),nt=j.autoProcessingError?.type==="3ds_required"&&j.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:j.autoProcessingError.nextActionRedirectUrl}:null;if(nt&&P&&he){let bt=await ct(ht=>Wo(nt,{billingApiUrl:de,sessionId:P,nonce:he,session:$,signal:ht,telemetry:!0}));await dt({result:bt,session:$,sessionId:$.id||P,autoCompleted:!1});return}if(j.autoProcessingError)throw qn(j.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.autoProcessingError.checkoutMethod});if(!Yn(Ce))throw Lo(Ce);await dt({result:Gn(Ce,P),session:Ce,sessionId:Ce.id||P,autoCompleted:!1});return}if(p.autoProcessingError){let A=p.autoProcessingError.nextActionRedirectUrl;if(p.autoProcessingError.type==="3ds_required"&&A&&P&&he){let te=await ct(bt=>Ml({billingApiUrl:de,sessionId:P,nonce:he,nextActionRedirectUrl:A,signal:bt}));if(te.status==="declined")throw qn({type:te.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:te.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:p.autoProcessingError.checkoutMethod});let Ce=await new vi.PaymentAPI(de).waitForCheckoutSessionCompletion(P,{initialDelayMs:0,nonce:he}),nt=so(Ce,$);if(!Yn(nt))throw qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:p.autoProcessingError.checkoutMethod});await dt({result:Gn(nt,P),session:nt,sessionId:nt.id||P,autoCompleted:!1});return}throw qn(p.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:p.autoProcessingError.checkoutMethod})}if(G?.fromCreateSession&&p.autoProcessingAttempted===!0)throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let T=await Ho({billingApiUrl:de,sessionId:P??$.id,session:$,nonce:he});if(T.type==="next_action_required"&&he){let A=P??$.id,te=await ct(j=>Wo(T,{billingApiUrl:de,sessionId:A,nonce:he,session:$,signal:j,telemetry:!0}));await dt({result:te,session:$,sessionId:$.id||A,autoCompleted:!1});return}if(T.type!=="success")throw qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await dt({result:T.result,session:$,sessionId:$.id||P,autoCompleted:!1})}catch(T){let A=$.id||P,te=io(ba(T),A);if(te.code==="three_ds_aborted")return;if(te.code==="checkout_processing_timeout"){if(!ae.current)return;K(te.message),(0,rt.invokeMerchantCallback)(()=>Ge.current?.(te));return}await He(te,{emitDecline:!0,method:te.checkoutMethod??Ca}),tu(te,A)&&A&&ae.current&&_e({sessionId:A,errorMessage:te.message,nonce:he||void 0,payPalOrderId:te.orderId})}},[t,de,ct,He,dt]),Ut=(0,pt.useCallback)(async p=>{if(me.onClick?.(p),!(p.defaultPrevented||pe||ke)){if(_e(null),K(null),e&&Qe){let P=new dn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await He(P),ae.current&&(ee(null),Pe(null));return}if(!e&&!Qe){let P=new dn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await He(P),ae.current&&(ee(null),Pe(null));return}Re(!0),Pe(null),ve(!1),ee("processing");try{let P=new vi.PaymentAPI(de);if(e){let G=await P.getUnifiedCheckoutSession(e,t);await Et(G,e);return}try{let G=await P.createAndFetchSession({...Qe});await Et(G,G.data.session?.id??null,{fromCreateSession:!0})}catch(G){if(Wa(G)==="session_auto_completed"){await dt({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw G}}catch(P){await He(io(eu(P,"Automatic payment failed. Please try again."),e))}finally{ae.current&&(ee(null),Pe(null),Re(!1))}}},[me.onClick,Qe,pe,ke,t,Et,de,e,He,dt]),kt=(0,pt.useCallback)(p=>{let P=B.current;_e(null),$e.current?.({result:p,session:null,sessionId:P?.sessionId??null,autoCompleted:!1})},[]),At=(0,pt.useCallback)(p=>{Ge.current?.(p)},[]),U=(0,pt.useCallback)(p=>{We.current?.(p)},[]),ye=(0,pt.useMemo)(()=>(0,dn.resolveTheme)(h),[h]),et=(0,pt.useMemo)(()=>{let p=ye?.buttonsLayout??(0,dn.resolveButtonsLayoutTheme)(Z);return k?{...p,...k,cardButton:{...p.cardButton,...k.cardButton}}:p},[ye,Z,k]),Y=(0,pt.useMemo)(()=>{let p=ye?.appearance;return v?p?{...p,...v,variables:{...p.variables,...v.variables}}:v:p},[v,ye]),Ue=Y?.variables,Rt=Ue?.colorPrimary??"#4A49FF",Ze=Ue?.colorPrimaryHover??(0,us.darkenHex)(Rt,.12),Tt=Ue?.borderRadius??"8px";return(0,cn.jsxs)(cn.Fragment,{children:[(0,cn.jsx)("button",{...me,type:De,onClick:Ut,disabled:pe||ke,"aria-busy":ke,style:{width:"100%",...Be===void 0?{boxSizing:"border-box",height:Qd,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...et.cardButton,...ds({themeBundle:ye,resolvedPrimaryColor:Rt,resolvedBorderRadius:Tt,submitButtonStyle:et.submitButton,explicitPrimaryColor:Ue?.colorPrimary}),fontSize:et.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:pe||ke?"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||ke?.6:1,...Je},onMouseEnter:p=>{me.onMouseEnter?.(p),!p.defaultPrevented&&!pe&&!ke&&(ye||Ue?.colorPrimary)&&(p.currentTarget.style.backgroundColor=Ze)},onMouseLeave:p=>{me.onMouseLeave?.(p),!p.defaultPrevented&&(ye||Ue?.colorPrimary)&&(p.currentTarget.style.backgroundColor=Rt)},onMouseDown:p=>{me.onMouseDown?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(0.985)")},onMouseUp:p=>{me.onMouseUp?.(p),p.defaultPrevented||(p.currentTarget.style.transform="scale(1)")},children:(0,cn.jsx)(Bo,{content:Be})}),Q&&(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:Q}),Ee&&(0,cn.jsx)(zr,{status:Ee,errorMessage:ue,authorized:Ie}),N&&(0,cn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:p=>{p.target===p.currentTarget&&_e(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:N.sessionId,nonce:N.nonce,checkoutMode:"full",billingApiUrl:de,locale:_,theme:h,...Y?{appearance:Y}:{},buttonsTheme:Z,buttonsStyles:k,initialErrorMessage:N.errorMessage,initialPayPalOrderId:N.payPalOrderId,cardTitleContent:null,onComplete:kt,onError:At,onDecline:U})})})]})}var bi=require("@flopay/js/card-setup"),Mr=require("@flopay/shared"),Nt=require("react");var Ci=require("@flopay/shared"),nu=require("@flopay/shared");function ac(e){return(0,Ci.computeCardSetupOverlayTheme)(e)}function ic(e){let{vaultTheme:t,surface:r,overlayTheme:n}=(0,Ci.resolveCardSetupTheme)(e);return{vaultTheme:t,surface:r,overlayTheme:n}}var Vn=require("react/jsx-runtime"),Ma=class extends Mr.FloPayError{constructor(t,r,n){super(t,r,n),this.name="FloPayCardSetupError",this.retryable=n.retryable}};function to(e,t={}){let r=e instanceof Mr.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 sc({sessionId:e,nonce:t,billingApiUrl:r,telemetry:n,theme:o="modern-light",containerStyle:i,appearance:l,buttonsStyles:u,loading:m=null,onReady:C,onComplete:w,onDecline:S,onCancel:x,onValidation:H,onError:M}){let[V,_]=(0,Nt.useState)(null),[h,v]=(0,Nt.useState)(null),[Z,k]=(0,Nt.useState)(null),[fe,O]=(0,Nt.useState)(null),[ne,Be]=(0,Nt.useState)(null),pe=(0,Nt.useRef)(!1),De=(0,Nt.useRef)(!1),{vaultTheme:Je,surface:me,overlayTheme:de}=(0,Nt.useMemo)(()=>ic({theme:o,appearance:l,buttonsStyles:u}),[o,l,u]),Qe=(0,Nt.useMemo)(()=>(0,ka.mergeCardSetupSurface)(me,i),[me,i]),ke=(0,Nt.useRef)(C),Re=(0,Nt.useRef)(M),Ee=(0,Nt.useRef)(w),ee=(0,Nt.useRef)(S),ue=(0,Nt.useRef)(x),Pe=(0,Nt.useRef)(H),Ie=(0,Nt.useRef)(!1),ve=(0,Nt.useRef)(!1),Q=(0,Nt.useRef)(0);return ke.current=C,Re.current=M,Ee.current=w,ee.current=S,ue.current=x,Pe.current=H,(0,Nt.useEffect)(()=>{let K=Q.current+1;return Q.current=K,()=>{queueMicrotask(()=>{Q.current===K&&(Ie.current||ve.current||(ve.current=!0,(0,rt.invokeMerchantCallback)(()=>{ue.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Nt.useEffect)(()=>{let K=!0,N=(0,Mr.resolveBillingApiUrl)(r),_e=new bi.PaymentAPI(N,{telemetry:n});return _(null),v(null),k(null),Ie.current=!1,ve.current=!1,(async()=>{try{if(!e.trim())throw new Mr.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Mr.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ae=await _e.getUnifiedCheckoutSession(e,t);if(!K)return;let ge=ae.data.session;if(!ge||!(0,Mr.isCardSetupCheckoutSession)(ge))throw new Mr.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let B=ge.vault;(0,Mr.isMountableVaultBlock)(B)||(B=await _e.getVaultCapture(e,t));let $e=(0,Mr.resolveVaultMountOptions)(B,{billingApiUrl:N,sessionId:e,nonce:t});if(!$e)throw new Mr.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!K)return;v($e),_(new bi.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:n}))}catch(ae){if(!K)return;let ge=to(ae);Ie.current=!0,k(ge),(0,rt.invokeMerchantCallback)(()=>Re.current?.(ge))}})(),()=>{K=!1,_e.destroy()}},[r,t,e,n]),(0,Nt.useEffect)(()=>{if(!V)return;let K=!1;De.current=!1,pe.current=!1;let N=V.on("submitting",()=>{pe.current=!0,Be(null),O("processing")}),_e=V.on("complete",B=>{Ie.current=!0,pe.current=!1,O("success"),(async()=>(await new Promise($e=>setTimeout($e,600)),!De.current&&(De.current=!0,(0,rt.invokeMerchantCallback)(()=>{Ee.current?.({status:"succeeded",sessionId:e,...B.paymentMethod?{paymentMethod:B.paymentMethod}:{}})}),K||O(null))))()}),ae=V.on("decline",B=>{Ie.current=!0,pe.current=!1,Be(B.message??null),O("error"),(0,rt.invokeMerchantCallback)(()=>{ee.current?.({status:"declined",sessionId:e,...B.declineReason?{reason:B.declineReason}:{},...B.message?{message:B.message}:{}})}),(async()=>(await new Promise($e=>setTimeout($e,400)),K||O(null)))()}),ge=V.on("challenge_dismissed",()=>{O(null)});return()=>{K=!0,N(),_e(),ae(),ge()}},[V,e]),Z?(0,Vn.jsx)("div",{role:"alert",children:Z.message}):!V||!h?.html?(0,Vn.jsx)(Vn.Fragment,{children:m}):(0,Vn.jsxs)(Vn.Fragment,{children:[fe&&(0,Vn.jsx)(zr,{status:fe,errorMessage:ne,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...de?{theme:de}:{}}),(0,Vn.jsx)(lo,{capture:V,html:h.html,messageToken:h.messageToken,expectedOrigin:h.expectedOrigin,verificationRequired:h.verificationRequired,theme:Je,containerStyle:Qe,onReady:()=>{(0,rt.invokeMerchantCallback)(()=>ke.current?.())},onValidation:K=>{(0,rt.invokeMerchantCallback)(()=>Pe.current?.(K))},onError:K=>{if(!K)return;pe.current&&(pe.current=!1,Be(K),O("error"),setTimeout(()=>O(null),400));let N=to(new Error(K),{code:"card_setup_widget_failed",retryable:!0});(0,rt.invokeMerchantCallback)(()=>Re.current?.(N))}})]})}var lc=require("@flopay/js/card-setup"),co=require("@flopay/shared"),cc=require("@paypal/paypal-js"),bo=require("react");var uc=require("react/jsx-runtime");function dc({clientId:e,environment:t,currency:r,sessionId:n,nonce:o,billingApiUrl:i,telemetry:l,customer:{userId:u,email:m},onSubmitting:C,onConfirmed:w,onFailed:S,onAbandoned:x}){let H=(0,bo.useRef)(null),M=(0,bo.useRef)({onSubmitting:C,onConfirmed:w,onFailed:S,onAbandoned:x});M.current={onSubmitting:C,onConfirmed:w,onFailed:S,onAbandoned:x};let[V]=(0,bo.useState)(()=>(0,Un.detectPayPalEnvironment)().inAppBrowser);return(0,bo.useEffect)(()=>{let _=!0,h,v=new lc.PaymentAPI(i,{telemetry:l}),Z={userId:u,email:m};return(async()=>{try{let k=await(0,cc.loadScript)({clientId:e,...r?{currency:r.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),fe=H.current;if(!_||!fe)return;if(!k?.Buttons)throw new co.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let O=k.Buttons({createVaultSetupToken:async()=>{M.current.onSubmitting();let ne=await v.createSessionIntent(n,o,{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 Be=ne.vaultSetupToken;if(!Be)throw new co.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let pe=await v.processPayment(Z.userId,{sessionId:n,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:Be,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:Z});if(!pe.ok)throw new co.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:pe.status});_&&M.current.onConfirmed()},onCancel:()=>{_&&M.current.onAbandoned()},onError:ne=>{if(!_)return;let{popupBlocked:Be}=(0,we.classifyExternalMethodFailure)(ne,{inAppBrowser:V,handoffObserved:!1});M.current.onFailed(Be?new Error((0,we.buildExternalMethodRecoveryMessage)("PayPal",!0,V)):ne,{code:Be?"popup_blocked":"paypal_setup_failed",retryable:!0})}});h=()=>O.close(),await O.render(fe)}catch(k){if(!_)return;M.current.onFailed(k,{code:"paypal_unavailable",retryable:!0})}})(),()=>{_=!1,h?.().catch(()=>{}),v.destroy()}},[i,e,r,m,t,V,o,n,l,u]),(0,uc.jsx)("div",{ref:H,"data-flopay-paypal-setup":""})}var mc=require("@flopay/js/card-setup"),uo=require("@flopay/shared"),$n=require("@stripe/react-stripe-js"),yc=require("@stripe/stripe-js"),xr=require("react");var Er=require("react/jsx-runtime"),fc={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"}},vs=new Map;function ou(e){let t=vs.get(e);if(t)return t;let r=(0,yc.loadStripe)(e).catch(n=>{throw vs.delete(e),n});return vs.set(e,r),r}function au(e){return e?(0,uo.toStripeAppearance)(e):void 0}function iu(e){return(0,we.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function pc(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 gc(e){let{publishableKey:t,method:r,currency:n,futureUse:o,futureUseUnsupported:i,appearance:l}=e,[u]=(0,xr.useState)(()=>ou(t)),m=(0,xr.useMemo)(()=>{let C=au(l),w=(0,uo.resolveSetupFutureUsage)({futureUse:o,futureUseUnsupported:i},r,"setup");return{mode:"setup",currency:n.toLowerCase(),paymentMethodTypes:fc[r]?.types??[r],...w?{setupFutureUsage:w}:{},...C?{appearance:C}:{}}},[l,n,o,i,r]);return(0,Er.jsx)($n.Elements,{stripe:u,options:m,children:(0,Er.jsx)(cu,{...e})})}function cu({method:e,category:t,sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,appearance:l,themeId:u,buttonsLayout:m,onSubmitting:C,onConfirmed:w,onDeclined:S,onFailed:x,onValidation:H,onUnavailable:M}){let V=(0,$n.useStripe)(),_=(0,$n.useElements)(),[h,v]=(0,xr.useState)(!1),[Z,k]=(0,xr.useState)("loading"),[fe,O]=(0,xr.useState)(!1),[ne,Be]=(0,xr.useState)(!1),pe=(0,xr.useRef)(!1),[De]=(0,xr.useState)(()=>(0,Un.detectPayPalEnvironment)()),[Je,me]=(0,xr.useState)(!1),de=(0,xr.useCallback)((ue,Pe)=>{if((0,we.classifyExternalMethodFailure)(ue,{inAppBrowser:De.inAppBrowser,handoffObserved:!1}).popupBlocked){me(!0),x(new Error((0,we.buildExternalMethodRecoveryMessage)(pc(e),!0,De.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}x(Pe.message===void 0?ue:new Error(Pe.message),{code:Pe.code,retryable:!0})},[De.inAppBrowser,e,x]),Qe=(0,xr.useCallback)(async()=>{if(!(!V||!_||pe.current)){pe.current=!0,v(!0);try{let ue=await _.submit();if(ue.error){H(ue.error.message??null);return}C();let Pe=await new mc.PaymentAPI(o,{telemetry:i}).createSessionIntent(r,n,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(Pe.provider!=="stripe"||Pe.intentKind!=="setup")throw new uo.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let Ie=await V.confirmSetup({elements:_,clientSecret:Pe.clientSecret,confirmParams:{return_url:su()},redirect:"if_required"});if(Ie.error){iu(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}:{}}):de(Ie.error,{code:"payment_method_setup_provider_failed",message:Ie.error.message??"The payment method could not be saved."});return}w()}catch(ue){de(ue,{code:"payment_method_setup_failed"})}finally{pe.current=!1,v(!1)}}},[o,t,_,e,n,w,S,C,H,de,r,V,i]),ke=fc[e]?.wallet,Re=ke==="paypal"&&(0,zn.resolveStripePayPalPresentation)(De,"auto",Je?"blocked":De.popupCapability)==="redirect",Ee=l?.variables?.borderRadius??m?.cardButton?.borderRadius??8;if(t==="wallet"&&ke&&!Re)return(0,Er.jsxs)(Er.Fragment,{children:[(0,Er.jsx)(Yo,{}),(0,Er.jsx)(wa,{state:Z,borderRadius:Ee,children:(0,Er.jsx)($n.ExpressCheckoutElement,{options:{...ai,paymentMethods:oi([e])},onReady:ue=>{let Pe=Sa(ue,[ke]);k(Pe),Pe==="unavailable"&&M()},onLoadError:()=>{k("load_error"),M()},onConfirm:()=>{Qe()}})})]});let ee=pc(e);return(0,Er.jsxs)(Er.Fragment,{children:[fe?(0,Er.jsx)(ni,{method:e,themeId:u,hasNextStep:!0,highlighted:ne,disabled:h,onClick:()=>Be(ue=>!ue),backgroundColor:m?.cardButton?.backgroundColor,borderColor:m?.cardInputBorder,textColor:m?.cardButton?.color,borderRadius:Ee}):null,(0,Er.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!ne,style:ne?{display:"flex",flexDirection:"column"}:lu,children:[(0,Er.jsx)($n.PaymentElement,{options:{layout:ii},onReady:()=>O(!0),onLoadError:()=>M(),onChange:ue=>{ue.complete&&H(null)}}),(0,Er.jsx)(si,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!V||!_||h||!ne,onClick:()=>{Qe()},color:l?.variables?.colorPrimary??"#4A49FF",borderRadius:l?.variables?.borderRadius??"8px",style:m?.submitButton,children:h?"Saving\u2026":`Save ${ee}`})]})]})}var xa=require("@flopay/js/card-setup"),nr=require("@flopay/shared"),je=Vi(require("react"),1);var Jo=require("@flopay/js/card-setup"),vr=require("@flopay/shared");var Cs=require("@flopay/shared");var rr=require("react/jsx-runtime"),du=15,uu=2e3;function pu(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function bs(e){return new Promise(t=>setTimeout(t,e))}async function mu(e,t,r){if(!t.trim())throw new nr.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!r.trim())throw new nr.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,nr.isCardSetupCheckoutSession)(o))throw new nr.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let i=(0,vr.readSetupAdvertisement)(n);if(!(0,vr.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 nr.FloPayError(u,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:o,advertisement:i}}async function yu(e,t,r,n,o){let i=t.vault??null;(0,nr.isMountableVaultBlock)(i)||(i=await e.getVaultCapture(r,n));let l=(0,nr.resolveVaultMountOptions)(i,{billingApiUrl:o,sessionId:r,nonce:n});if(!l)throw new nr.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 hc({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,theme:l="modern-light",containerStyle:u,loading:m=null,onReady:C,onComplete:w,onDecline:S,onCancel:x,onValidation:H,onError:M}){let[V]=(0,je.useState)(Jo.readSetupRedirectReturn),[_,h]=(0,je.useState)(null),[v,Z]=(0,je.useState)(!1),[k,fe]=(0,je.useState)(null),[O,ne]=(0,je.useState)(null),[Be,pe]=(0,je.useState)(null),[De,Je]=(0,je.useState)(null),[me,de]=(0,je.useState)(()=>new Set),Qe=(0,je.useRef)(me),ke=(0,je.useRef)(null);ke.current=_;let Re=(0,je.useRef)(!1),Ee=(0,je.useRef)(!1),ee=(0,je.useRef)(!1),ue=(0,je.useRef)(!1),Pe=(0,je.useRef)(0),Ie=(0,je.useRef)(0),ve=(0,je.useRef)(!1),Q=(0,je.useMemo)(()=>typeof l=="object"?void 0:(0,nr.resolveTheme)(l),[l]),K=(0,je.useMemo)(()=>typeof l=="object"?l:Q?(0,Cs.computeVaultCardThemeColors)({appearance:Q.appearance,buttonsStyles:Q.buttonsLayout,layout:"default"}):null,[Q,l]),N=(0,je.useMemo)(()=>(0,ka.mergeCardSetupSurface)(Q?.buttonsLayout.cardFormContainer,u),[Q,u]),_e=(0,je.useMemo)(()=>Q?ac(Q):void 0,[Q]),ae=(0,je.useRef)({sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,onReady:C,onComplete:w,onDecline:S,onCancel:x,onValidation:H,onError:M});ae.current={sessionId:r,nonce:n,billingApiUrl:o,telemetry:i,onReady:C,onComplete:w,onDecline:S,onCancel:x,onValidation:H,onError:M},(0,je.useEffect)(()=>{ve.current=!0;let T=Pe.current+1;return Pe.current=T,()=>{ve.current=!1,Ie.current+=1,queueMicrotask(()=>{Pe.current===T&&(ee.current||ue.current||(ue.current=!0,(0,rt.invokeMerchantCallback)(()=>{ae.current.onCancel?.({status:"cancelled",sessionId:r})})))})}},[r]);let ge=(0,je.useCallback)((T,A)=>{ee.current=!0,Re.current=!1,Je({status:"success",wording:T,message:null}),(async()=>(await bs(600),!Ee.current&&(Ee.current=!0,(0,rt.invokeMerchantCallback)(()=>{ae.current.onComplete?.({status:"succeeded",sessionId:ae.current.sessionId,...A?{paymentMethod:A}:{}})}),ve.current&&Je(null))))()},[]),B=(0,je.useCallback)((T,A)=>{ee.current=!0,Re.current=!1,Je({status:"error",wording:T,message:A.message??null}),(0,rt.invokeMerchantCallback)(()=>{ae.current.onDecline?.({status:"declined",sessionId:ae.current.sessionId,...A.reason?{reason:A.reason}:{},...A.message?{message:A.message}:{}})}),(async()=>(await bs(400),ve.current&&Je(null)))()},[]),$e=(0,je.useCallback)((T,A)=>{Re.current?(Re.current=!1,Je({status:"error",wording:T,message:A.message}),setTimeout(()=>{ve.current&&Je(null)},400)):Je(null),(0,rt.invokeMerchantCallback)(()=>ae.current.onError?.(A))},[]),Ge=(0,je.useCallback)(async T=>{let A=Ie.current+1;Ie.current=A;let te=()=>!ve.current||A!==Ie.current;Re.current=!0,Je({status:"processing",wording:"payment_method",message:null});let j=new xa.PaymentAPI((0,nr.resolveBillingApiUrl)(ae.current.billingApiUrl),{telemetry:ae.current.telemetry});try{for(let Ce=0;Ce<du;Ce+=1){if((Ce>0||T.waitFirst)&&await bs(uu),te())return;let nt=await j.getUnifiedCheckoutSession(ae.current.sessionId,ae.current.nonce);if(te())return;let bt=nt.data.session?.status;if(bt==="complete"){Z(!0),ge("payment_method");return}if(bt==="expired")throw new nr.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new nr.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(Ce){if(te())return;let nt=Ce instanceof nr.FloPayError&&Ce.code==="payment_method_setup_unverified";$e("payment_method",to(Ce,nt?{retryable:!0}:{}))}finally{j.destroy()}},[$e,ge]);(0,je.useEffect)(()=>{let T=!0,A=(0,nr.resolveBillingApiUrl)(o),te=new xa.PaymentAPI(A,{telemetry:i});h(null),Z(!1),fe(null),ne(null),pe(null);let j=new Set;return Qe.current=j,de(j),ee.current=!1,ue.current=!1,Ee.current=!1,(async()=>{try{let{session:Ce,advertisement:nt}=await mu(te,r,n);if(!T)return;let bt={advertisement:nt,customer:pu(Ce),...Ce.futureUse?{futureUse:Ce.futureUse}:{},...Ce.futureUseUnsupported?{futureUseUnsupported:Ce.futureUseUnsupported}:{}};if(V){if((0,Jo.clearSetupRedirectParams)(),Ce.status==="complete"){Z(!0),h(bt),ge("payment_method");return}V.failed?B("payment_method",{reason:"redirect_failed"}):Ge({waitFirst:!0})}let ht=nt.card?await yu(te,Ce,r,n,A):null;if(!T)return;h(bt),ht&&(ne(ht),fe(new xa.PciVaultCardCapture({sessionId:r,operation:"card_setup",telemetry:i})))}catch(Ce){if(!T)return;let nt=to(Ce);ee.current=!0,pe(nt),(0,rt.invokeMerchantCallback)(()=>ae.current.onError?.(nt))}})(),()=>{T=!1,te.destroy()}},[o,n,V,B,ge,r,i,Ge]),(0,je.useEffect)(()=>{if(!k)return;Re.current=!1;let T=k.on("submitting",()=>{Re.current=!0,Je({status:"processing",wording:"card",message:null})}),A=k.on("complete",Ce=>{ge("card",Ce.paymentMethod)}),te=k.on("decline",Ce=>{B("card",{...Ce.declineReason?{reason:Ce.declineReason}:{},...Ce.message?{message:Ce.message}:{}})}),j=k.on("challenge_dismissed",()=>{Je(null)});return()=>{T(),A(),te(),j()}},[k,B,ge]);let We=(0,je.useCallback)((T,A,te)=>{if(te.retryable){$e("payment_method",to(A,te));return}if(Qe.current.has(T))return;let j=new Set(Qe.current);j.add(T),Qe.current=j,de(j);let Ce=ke.current?.advertisement,nt=Ce?(0,vr.advertisedMethodKeys)(Ce).some(bt=>!j.has(bt)):!1;$e("payment_method",to(A,{code:te.code,retryable:nt}))},[$e]),ct=(0,je.useMemo)(()=>({onSubmitting:()=>{Re.current=!0,Je({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Ge({waitFirst:!1})},onDeclined:T=>B("payment_method",T),onValidation:T=>{(0,rt.invokeMerchantCallback)(()=>ae.current.onValidation?.(T))},onAbandoned:()=>{Re.current=!1,Je(null)}}),[B,Ge]),Ye=(0,je.useRef)(We);Ye.current=We;let dt=(0,je.useRef)(new Map),He=T=>{let A=dt.current.get(T);if(A)return A;let te=(j,Ce)=>Ye.current(T,j,Ce);return dt.current.set(T,te),te},Et=(0,je.useCallback)(T=>{if(Qe.current.has(T))return;let A=new Set(Qe.current);A.add(T),Qe.current=A,de(A);let te=ke.current?.advertisement;te&&(0,vr.advertisedMethodKeys)(te).some(Ce=>!A.has(Ce))||$e("payment_method",to(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[$e]),Ut=(0,je.useRef)(Et);Ut.current=Et;let kt=(0,je.useRef)(new Map),At=T=>{let A=kt.current.get(T);if(A)return A;let te=()=>Ut.current(T);return kt.current.set(T,te),te},U=De?(0,rr.jsx)(zr,{status:De.status,errorMessage:De.message,...(0,vr.setupOverlayLabels)(De.wording),successNote:null,..._e?{theme:_e}:{}}):null;if(Be)return(0,rr.jsx)("div",{role:"alert",children:Be.message});if(!_||v)return(0,rr.jsxs)(rr.Fragment,{children:[U,_?null:m]});let{advertisement:ye,customer:et,futureUse:Y,futureUseUnsupported:Ue}=_,Rt=(0,nr.resolveBillingApiUrl)(o),Ze=i===void 0?{}:{telemetry:i},Tt=ye.stripe.filter(({method:T})=>!me.has(T)),z=me.has("paypal")?null:ye.paypal,p=!!(ye.card&&k&&O?.html),P=({method:T,publishableKey:A,currency:te})=>(0,rr.jsx)("div",{"data-flopay-payment-method":T,style:{display:"contents"},children:(0,rr.jsx)(Si,{onFailed:He(T),children:(0,rr.jsx)(je.Suspense,{fallback:null,children:(0,rr.jsx)(e,{method:T,category:(0,vr.stripeMethodCategory)(T),publishableKey:A,currency:te,...Y?{futureUse:Y}:{},...Ue?{futureUseUnsupported:Ue}:{},sessionId:r,nonce:n,billingApiUrl:Rt,...Ze,...Q?{appearance:Q.appearance,buttonsLayout:Q.buttonsLayout}:{},...typeof l=="string"?{themeId:l}:{},...ct,onFailed:He(T),onUnavailable:At(T)})})})},T),G=Tt.filter(({method:T})=>(0,vr.stripeMethodCategory)(T)==="wallet"),$=Tt.filter(({method:T})=>(0,vr.stripeMethodCategory)(T)!=="wallet"),he=Tt.length>0||z!==null;return(0,rr.jsxs)(rr.Fragment,{children:[U,he?(0,rr.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[G.map(P),z?(0,rr.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,rr.jsx)(Si,{onFailed:He("paypal"),children:(0,rr.jsx)(je.Suspense,{fallback:null,children:(0,rr.jsx)(t,{clientId:z.clientId,...z.environment?{environment:z.environment}:{},...ye.currency?{currency:ye.currency}:{},sessionId:r,nonce:n,billingApiUrl:Rt,customer:et,...Ze,...ct,onFailed:He("paypal"),onUnavailable:At("paypal")})})})}):null,$.map(P)]}):null,p&&he?(0,rr.jsx)(li,{label:"or add a card"}):null,p&&k&&O?.html?(0,rr.jsx)("div",{"data-flopay-payment-method":"card",children:(0,rr.jsx)(lo,{capture:k,html:O.html,messageToken:O.messageToken,expectedOrigin:O.expectedOrigin,verificationRequired:O.verificationRequired,theme:K,containerStyle:N,onReady:()=>{(0,rt.invokeMerchantCallback)(()=>ae.current.onReady?.())},onValidation:T=>{(0,rt.invokeMerchantCallback)(()=>ae.current.onValidation?.(T))},onError:T=>{T&&$e("card",to(new Error(T),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var vc=require("react/jsx-runtime"),fu={StripeSetupMethod:gc,PayPalSetupMethod:dc};function Pc(e){return(0,vc.jsx)(hc,{...e,branches:fu})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});