@flopay/react 1.9.21 → 1.9.22

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 da=Object.defineProperty;var ac=Object.getOwnPropertyDescriptor;var ic=Object.getOwnPropertyNames;var sc=Object.getPrototypeOf,lc=Object.prototype.hasOwnProperty;var cc=(e,t)=>{for(var n in t)da(e,n,{get:t[n],enumerable:!0})},ws=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ic(t))!lc.call(e,o)&&o!==n&&da(e,o,{get:()=>t[o],enumerable:!(r=ac(t,o))||r.enumerable});return e};var ks=(e,t,n)=>(n=e!=null?oc(sc(e)):{},ws(t||!e||!e.__esModule?da(n,"default",{value:e,enumerable:!0}):n,e)),dc=e=>ws(da({},"__esModule",{value:!0}),e);var Gd={};cc(Gd,{DirectPayPalButton:()=>Uo,FloPayAutomaticPaymentButton:()=>Fl,FloPayCardSetup:()=>Ol,FloPayCardSetupError:()=>Qo,FloPayCheckout:()=>Ua,FloPayProvider:()=>$o,SplitCardForm:()=>Na,VaultCardFields:()=>Po,dropThirdPartyOnlyError:()=>zl.dropThirdPartyOnlyError,useCheckout:()=>Ns,useFloPay:()=>Tr,usePayPalFloPay:()=>ma});module.exports=dc(Gd);var zl=require("@flopay/shared");var qa=require("@flopay/js"),nr=require("@flopay/shared"),Ze=require("react");var Nt=require("react/jsx-runtime");function uc(){return(0,Nt.jsxs)(Nt.Fragment,{children:[(0,Nt.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,Nt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Nt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Nt.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,Nt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function pc(){return(0,Nt.jsx)(Nt.Fragment,{children:"Go back"})}function mc(){return(0,Nt.jsx)(Nt.Fragment,{children:"Secure card checkout"})}function oo(e){return e!==void 0&&(e===""||e===null||e===!1)}function ao({content:e}){return(0,Nt.jsx)(Nt.Fragment,{children:e===void 0?(0,Nt.jsx)(uc,{}):e})}function io({content:e}){return(0,Nt.jsx)(Nt.Fragment,{children:e===void 0?(0,Nt.jsx)(pc,{}):e})}function Fo({content:e}){return(0,Nt.jsx)(Nt.Fragment,{children:e===void 0?(0,Nt.jsx)(mc,{}):e})}var Et=require("@flopay/shared"),yc="Checkout is temporarily unavailable. Please try again later.";function ii(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Et.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function fc(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 Is(){return new Et.FloPayError(yc,"api_error",{code:"CheckoutInitializationFailed"})}function si(e){return!!e?.gateways?.worldpayCorporateGateway}function Fr(e){return e?.status==="open"&&si(e)}function Rs(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card")||Fr(r))||t&&e?.data.paypal?.publishableKey)}function _s(e,t){if(t&&(!(e instanceof Et.FloPayError)||e.type==="authentication_error"))return ii(e);if(!(e instanceof Et.FloPayError&&fc(e))){if(!t&&!(e instanceof Et.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Et.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Et.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Et.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function so(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()},d=(0,Et.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,Et.isValidEmail)(l.email))return Promise.reject(new Et.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let u={};for(let[m,h]of Object.entries(l)){if(d&&m.endsWith("Name")||typeof h!="string")continue;let b=h.trim();b&&(u[m]=b)}return o=e.claimCheckoutSession(t,n,{accountData:u}),o.catch(()=>{}),o}}function Es(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function li(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 Ts(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*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:n.map((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function Vr(e){if((0,Et.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ci(e,t){return t?{...e,...t}:e}function nn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var gc=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Dr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of gc)if(n.test(t))return r;return e}function Ir(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Nr(e){return e?.status==="authorized"||e?.status==="complete"}function As(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ua(e){let t=As(e);return new Et.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function pa(e){return e instanceof Et.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function lo(e){let t=As(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new Et.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function Do(e,t){return e==="processing"||(0,Et.isMoneySettledOutcome)(e,t)}function xs(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Ms(e,t){let n=e;if((0,Et.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:l}=await n.retrieveSetupIntent(t);if(l)throw new Et.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new Et.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Bs(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function di(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function No(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var xr=require("@flopay/js"),qe=require("@flopay/shared"),P=ks(require("react"),1);var ui=require("react"),Qn=(0,ui.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),dr=(0,ui.createContext)({session:null,loading:!1,error:null});var ba=require("@flopay/js"),qt=require("@flopay/shared"),zs=require("@paypal/paypal-js"),E=require("react");var Fs=require("@flopay/shared"),ur=require("react"),Rr=require("react/jsx-runtime");function Mn(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),l=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...l||t?{lastName:l??""}:{}}}function co(){let[e,t]=(0,ur.useState)(null),n=(0,ur.useRef)(null),r=(0,ur.useRef)(0),o=(0,ur.useCallback)((l,d)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:d}),new Promise(u=>{n.current=u})),[]),a=(0,ur.useCallback)(l=>{let d=n.current;n.current=null,t(null),d?.(l)},[]);return(0,ur.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function uo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,d]=(0,ur.useState)(e.email?.trim()??""),u=(0,Fs.isValidEmail)(l.trim());return(0,Rr.jsxs)("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Rr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Rr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Rr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:m=>d(m.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Rr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Rr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Rr.jsxs)("button",{type:"button",disabled:!u||o,onClick:()=>{n(Mn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function hc(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function jr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function _r(e){if(typeof e!="object"||e===null)return;let t=e;return jr(t.code)??jr(t.type)??jr(t.name)}function po(e){if(!(typeof e!="object"||e===null))return jr(e.decline_code)}function Lo(e){return typeof e!="object"||e===null?!1:jr(e.type)?.toLowerCase()==="card_error"||po(e)!==void 0}function Er(e){let t=hc(e)?.toLowerCase()??"",r=`${_r(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var Ds=require("@flopay/shared"),Oo=require("react");function Tr(){return(0,Oo.useContext)(Qn).flopay}function ma(){return(0,Oo.useContext)(Qn).paypalFlopay??null}function Ns(){return(0,Oo.useContext)(dr)}function Ls(){return(0,Oo.useContext)(Qn).billingApiUrl||(0,Ds.resolveBillingApiUrl)()}function ya(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function fa(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Os=require("@flopay/shared"),Wr=require("react");function dt(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var ga=require("react"),Kr=typeof window>"u"?ga.useEffect:ga.useLayoutEffect;var bc={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function vc(e){return e==="stripe"||e==="paypal"?e:void 0}function Pc(e){let t=vc(e.provider),n={schemaVersion:Os.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=bc[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var pi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function mo(e,t){let n=(0,Wr.useRef)(e);n.current=e;let r=(0,Wr.useRef)(new Set),o=(0,Wr.useRef)(t),a=(0,Wr.useRef)(t);return Kr(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Wr.useCallback)(l=>{if(a.current!==t)return;let d=Pc(l);if(d){if(pi.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}dt(()=>n.current?.(d))}},[t])}var Cc=Symbol.for("@flopay/js.telemetry.bridge.v1"),Sc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function wc(){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 kc(e){let t=wc(),n=(o,a)=>o?o.bind(e):a,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function ha(e){let t=globalThis[Sc];return kc(t?.(e)??{})}function en(e){if(e)return e[Cc]}var kn=require("react");function zo(e){let t=(0,kn.useRef)(0),n=(0,kn.useRef)(null),r=(0,kn.useRef)(null),o=(0,kn.useCallback)((y=r.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),a=(0,kn.useCallback)(y=>{o();let C=t.current+1;return t.current=C,n.current=null,r.current={generation:C,method:y,timer:null,yieldedControl:!1},C},[o]),l=(0,kn.useCallback)(y=>{let C=r.current;return y!==void 0&&C?.generation!==y?!1:(o(C),r.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[o]),d=(0,kn.useCallback)(y=>{let C=r.current,_=y??C?.generation??t.current;(y===void 0||C?.generation===y)&&(o(C),r.current=null),n.current=_},[o]),u=(0,kn.useCallback)(y=>n.current===(y??t.current),[]),m=(0,kn.useCallback)(y=>r.current?.generation===y&&n.current!==y,[]),h=(0,kn.useCallback)(()=>{let y=r.current;y&&(y.yieldedControl=!0,o(y))},[o]),b=(0,kn.useCallback)(()=>{let y=r.current;!y?.yieldedControl||document.visibilityState!=="visible"||(o(y),y.timer=setTimeout(()=>{y.timer=null,r.current?.generation===y.generation&&(r.current=null,n.current=y.generation,e(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return(0,kn.useEffect)(()=>{let y=()=>{document.visibilityState==="visible"?b():h()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",h),window.addEventListener("focus",b),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",h),window.removeEventListener("focus",b),o()}},[o,h,b]),{startAttempt:a,finishAttempt:l,invalidateAttempt:d,isAttemptInvalidated:u,isAttemptCurrent:m,generationRef:t}}var er=require("react/jsx-runtime"),va=45,Ic=1e3,Rc=11e3,_c=["https://www.paypal.com","https://www.sandbox.paypal.com"],mi="We couldn't open PayPal. Try again or choose another payment method.",Ec={width:"100%",minHeight:va,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 Tc(e){return e.includes("No ack for postMessage init()")&&_c.some(t=>e.includes(t))&&e.includes("10000ms")}var Ac={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 xc(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Ac[e.kind]??null}}function Mc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Tc(t)?"paypal_init_timeout":"paypal_init_failure"}function Bc(e,t=!1){return e?t?`${mi} Open this page in your system browser, then try again.`:`${mi} Allow pop-ups for this site, then try again.`:mi}function Fc(e){let t=Lo(e),n=Er(e);return t?{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:"provider_declined"}:{errorCode:n?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:n?"popup_blocked":"provider_error"}}function Dc(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function Nc(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Us({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:d,currency:u,isSubscription:m,providerObjectType:h,approvalPresentation:b,onTokenizedBody:y,onComplete:C,onErrorChange:_,onDecline:ne,onTechnicalFailure:z,isProcessing:ue=!1,onLoadStateChange:k,onInitializationStateChange:$,allowAutomaticRetry:U=!0,onButtonClick:se,runBeforeButtonClick:Se,session:Pe,existingOrderId:pe,telemetry:ye,telemetryContext:yt,onInstrument:He,debug:we=!1}){let Me=Tr(),fe=mo(He,e),Re=(0,E.useMemo)(()=>{if(Me)return null;let O=ha({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:qt.SDK_VERSION,enabled:ye!==!1});return O.setCheckoutContext(yt??{}),O.beginCheckout(yt??{}),O},[n,Me,ye,yt?.checkoutMode,yt?.layout]),Ge=(0,E.useMemo)(()=>en(Me),[Me]);(0,E.useEffect)(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let oe=(0,E.useMemo)(()=>({error:O=>{Ge?Ge.error(O):Re?.error(O),fe({class:"technical_error",errorCode:O.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":O.errorCode,requestCategory:O.requestCategory,provider:O.provider})},log:O=>{Ge?Ge.log(O):Re?.log(O),fe({class:"lifecycle",name:O.name,provider:O.provider})},performance:O=>{Ge?Ge.performance(O):Re?.performance(O)},terminal:O=>{Ge?Ge.terminal(O):Re?.terminal(O)},startTiming:()=>Ge?.now()??Re?.now()??0,elapsed:O=>Ge?.elapsed(O)??Math.max(0,(Re?.now()??O)-O)}),[fe,Ge,Re]),_e=(0,E.useRef)(null),ge=(0,E.useRef)(0),nt=(0,E.useRef)(null),rt=(0,E.useRef)(null),M=(0,E.useRef)(null),V=(0,E.useRef)(!1),[ie,ae]=(0,E.useState)(!1),[Ye,Ce]=(0,E.useState)(!1),[N,ut]=(0,E.useState)(0),ot=(0,E.useRef)(0),[he,le]=(0,E.useState)(!1),H=(0,E.useRef)(!1),Le=(0,E.useRef)(!1),[Oe,ze]=(0,E.useState)(!1),[je,Be]=(0,E.useState)(!1),{request:Ne,collect:ce,finish:dn}=co(),Jt=(0,E.useRef)({sessionId:e,required:!(0,qt.isValidEmail)(r?.trim()||Pe?.customer?.email?.trim())});Jt.current.sessionId!==e&&(Jt.current={sessionId:e,required:!(0,qt.isValidEmail)(r?.trim()||Pe?.customer?.email?.trim())});let ee=Jt.current.required,at=(0,E.useMemo)(()=>n.replace(/\/+$/,""),[n]),Q=Pe?.gateways?.paypal?.providerObjectType??h,be=Q??(m?"subscription":"order"),[g]=(0,E.useState)(ya),q=Pe?.gateways?.paypal?.approvalPresentation??b,Fe=fa(g,q==="app_switch"?"app_switch":void 0,be),Je=Q==="order"||Q==="setup_token",De=(0,E.useMemo)(()=>JSON.stringify([at,l,u,d??"",be,Je,Fe,e,pe??""]),[at,l,u,d,pe,be,Je,Fe,e]),$t=(0,E.useRef)(De),W=$t.current!==De,St=(0,E.useRef)(we),Tt=(0,E.useRef)(null),[ft,un]=(0,E.useState)([]),G=(0,E.useCallback)(O=>{St.current&&un(Ve=>[...Ve,`${new Date().toISOString().slice(11,23)} ${O}`])},[]);(0,E.useEffect)(()=>{St.current=we,we&&G("debug:enabled"),Tt.current?.setEnabled(we)},[G,we]);let Lt=(0,E.useRef)(y),vn=(0,E.useRef)(C),pn=(0,E.useRef)(_),mn=(0,E.useRef)(ne),In=(0,E.useRef)(z),Bn=(0,E.useRef)(se),Fn=(0,E.useRef)(k),Xt=(0,E.useRef)($),Ke=(0,E.useRef)(a),Qe=(0,E.useRef)(Se),wt=(0,E.useRef)(Pe),rn=(0,E.useRef)(r),kt=(0,E.useRef)(o),Vn=(0,E.useRef)(t),gt=(0,E.useRef)(null),At=(0,E.useRef)(new Map),Ot=(0,E.useRef)(new Map),yn=(0,E.useRef)(!1);(0,E.useEffect)(()=>(yn.current=!0,()=>{yn.current=!1}),[]),(0,E.useEffect)(()=>{Lt.current=y},[y]),(0,E.useEffect)(()=>{Ke.current=a},[a]),(0,E.useEffect)(()=>{vn.current=C},[C]),(0,E.useEffect)(()=>{pn.current=_},[_]),(0,E.useEffect)(()=>{mn.current=ne},[ne]),(0,E.useEffect)(()=>{In.current=z},[z]),(0,E.useEffect)(()=>{Bn.current=se},[se]),(0,E.useEffect)(()=>{Fn.current=k},[k]),(0,E.useEffect)(()=>{Xt.current=$},[$]),(0,E.useEffect)(()=>{Qe.current=Se},[Se]),(0,E.useEffect)(()=>{wt.current=Pe},[Pe]),(0,E.useEffect)(()=>{rn.current=r},[r]),(0,E.useEffect)(()=>{kt.current=o},[o]),(0,E.useEffect)(()=>{Vn.current=t},[t]),(0,E.useEffect)(()=>{ot.current=N},[N]),(0,E.useEffect)(()=>{he&&M.current?.focus()},[he,N]);let zt=(0,E.useCallback)(()=>{window.setTimeout(()=>{M.current?.focus()},0)},[]),xt=(0,E.useCallback)(()=>{ae(!1),ut(O=>O+1)},[]),Pn=(0,E.useCallback)(()=>{le(!1),(_e.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??_e.current)?.focus?.()},[]);(0,E.useEffect)(()=>{!ie||!V.current||(V.current=!1,Pn())},[Pn,ie,N]);let Cn=(0,E.useCallback)((O,Ve)=>{let K=Ve?.popupBlocked??Er(O),Rt=Bc(K,g.inAppBrowser),Mt=In.current;if(Mt){let Gt=K&&g.inAppBrowser?new qt.FloPayError(Rt,"api_error",{code:Ve?.code??"paypal_popup_blocked"}):O;Mt("paypal",Gt,Ve);return}pn.current?.(Rt)},[g.inAppBrowser]),It=(0,E.useCallback)(O=>{let Ve=nt.current,K=rt.current;Ve===null||!K||(oe.log({...K,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:O}),oe.performance({...K,stage:"overlay_return",durationMs:oe.elapsed(Ve),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:O}),nt.current=null)},[oe]),de=(0,E.useCallback)((O,Ve,K)=>{let Rt=rt.current;It("overlay_timeout"),Rt&&oe.error({...Rt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Cn(Ve,K),le(!0),xt(),zt()},[It,zt,Cn,xt,oe]),{finishAttempt:on,generationRef:jn,invalidateAttempt:Wt,isAttemptCurrent:Vt,isAttemptInvalidated:an,startAttempt:rr}=zo(de),Dn=(0,E.useCallback)(()=>(le(!1),rr("paypal")),[rr]),Ht=(0,E.useCallback)(O=>{Wt(O?.generation),O?.showRetry&&le(!0),O?.remount&&xt(),O?.focus!==!1&&zt()},[zt,Wt,xt]),$e=O=>{let Ve=gt.current;return Ve&&Ot.current.set(O,Ve),O};(0,E.useEffect)(()=>{$t.current!==De&&($t.current=De,H.current=!1,Le.current=!1,ae(!1),Ce(!1),ze(!1),Xt.current?.("loading"))},[De]),(0,E.useEffect)(()=>{dt(()=>Fn.current?.(ie&&!Oe))},[ie,Oe]);let fn=(0,qt.normalizeGatewayEnvironment)(d);(0,E.useEffect)(()=>{let O={attempt:jn.current+1,...g,presentationMode:Fe},Ve=()=>rt.current??O,K={error:B=>oe.error({...B,...Ve()}),log:B=>oe.log({...B,...Ve()}),performance:B=>oe.performance({...B,...Ve()}),terminal:B=>oe.terminal({...B,...Ve()}),startTiming:oe.startTiming,elapsed:oe.elapsed},Rt=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Mt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(G(`mount clientId=${Rt} env=${d??"(unset)"}\u2192${fn??"live"} ccy=${u} sub=${m}`),G(`ua=${Mt.slice(0,80)}${Mt.length>80?"\u2026":""}`),!l){G("FAIL: clientId empty \u2014 gateway misconfigured"),ze(!0),K.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(!_e.current){G("FAIL: containerRef not attached");return}ge.current=K.startTiming(),K.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,Kn=!1,Ee=()=>Gt||Kn,sn,Wn=!1,Sr=()=>{sn=(0,qt.generateIdempotencyKey)(),sn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Wn=!0},or=null,Lr=!1,Or=null,ar=!1,Mr=()=>{!Or||ar||(ar=!0,Or.close().catch(()=>{}))},Rn=!1,ir=!1,Ft=_e.current,Nn=null,Hn=null,Gn=[],ht=null,_n=!1,Yn=!1,sr=null,gn=B=>{if(!B||typeof B.getBoundingClientRect!="function")return"(no rect)";let f=B.getBoundingClientRect();return`${Math.round(f.width)}\xD7${Math.round(f.height)}`},et=B=>{if(!B)return"(empty)";try{let f=new URL(B,typeof window>"u"?"https://localhost":window.location.href),L=f.pathname.toLowerCase();return L.includes("checkcaptcha")||L.includes("captcha")?`CAPTCHA(${f.host}${L})`:L.includes("risk")||L.includes("challenge")?`RISK(${f.host}${L})`:L.includes("smart/buttons")?`smart-buttons(${f.host})`:`${f.host}${L}`.slice(0,100)}catch{return B.slice(0,80)}},hn=B=>{let f=B.getAttribute("src"),L=B.getAttribute("srcdoc"),S=B.getAttribute("name"),I=B.getAttribute("sandbox"),A=[];return f&&A.push(`src=${et(f)}`),L&&A.push(`srcdoc[${L.length}ch]`),!f&&!L&&A.push("src=(empty) srcdoc=(empty)"),S&&A.push(`name=${S.slice(0,40)}`),I!==null&&A.push(`sandbox="${I.slice(0,40)}"`),A.join(" ")},ln=B=>{if(!(B instanceof HTMLIFrameElement))return"";try{let f=B.contentDocument;if(!f)return"cd=null";let L=f.body?.children.length??0,S=f.body?.innerHTML.length??0,I=f.head?.innerHTML.length??0;return`cd=same-origin readyState=${f.readyState} body[${L}children,${S}ch] head[${I}ch]`}catch(f){return`cd=cross-origin(${f.message.slice(0,30)})`}},Ln=[],wr=B=>{if(Ee())return;let f=B.message??String(B.error??"(no message)");f&&(f.toLowerCase().includes("paypal")||f.toLowerCase().includes("zoid")||f.toLowerCase().includes("postrobot")||f.toLowerCase().includes("storage"))&&(G(`window:error ${f.slice(0,140)}`),Ln.push(f))},zr=B=>{if(Ee())return;let f=B.reason instanceof Error?B.reason.message:String(B.reason??"(no reason)");f&&(f.toLowerCase().includes("paypal")||f.toLowerCase().includes("zoid")||f.toLowerCase().includes("postrobot")||f.toLowerCase().includes("storage"))&&(G(`window:rejection ${f.slice(0,140)}`),Ln.push(f))},kr={value:0},On=()=>{Nn?.disconnect(),Nn=null,Hn?.disconnect(),Hn=null;for(let B of Gn.splice(0))clearTimeout(B);Yn=!1,_n&&typeof window<"u"&&(window.removeEventListener("error",wr),window.removeEventListener("unhandledrejection",zr)),_n=!1},bn=()=>{if(!(_n||Ee()||Rn)){if(_n=!0,Ln.length=0,kr.value=0,typeof window<"u"&&(window.addEventListener("error",wr),window.addEventListener("unhandledrejection",zr)),typeof PerformanceObserver<"u")try{Hn=new PerformanceObserver(B=>{if(!Ee())for(let f of B.getEntries()){if(!f.name.toLowerCase().includes("paypal"))continue;kr.value+=1;let L=Math.round(f.duration);G(`net ${L}ms ${f.name.slice(0,90)}`)}}),Hn.observe({type:"resource",buffered:!0})}catch{}sr?.()}},Yr=()=>{ht&&(clearTimeout(ht),ht=null)},En=()=>{On(),Yr()},Br={setEnabled:B=>{B?bn():On()}};Tt.current=Br,St.current&&bn();let Sn=B=>{if(!B)return!1;let f=B.toLowerCase();return f.includes("zoid destroyed")||f.includes("destroyed all components")||f.includes("window closed")||f.includes("detected container element removed")},zn=B=>{if(Ee()||Sn(B))return;let f=Dr(B)??B;dt(()=>pn.current?.(f))},st=(B,f)=>{if(Gt||Lr)return;Lr=!0,Kn=!0,En(),Mr();let L=xc({kind:B,generationActive:!0,automaticRetryAllowed:U,automaticRetryUsed:H.current});if(L.action==="retry"){H.current=!0,ae(!1),Be(!1),Ce(!0),Xt.current?.("retrying"),or=setTimeout(()=>{Gt||ut(S=>S+1)},Ic);return}if(ae(!1),Be(!1),Ce(!1),ze(!0),L.action!=="ignore"){if(Xt.current?.("exhausted"),L.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",f);return}L.report&&K.error({errorCode:L.report.errorCode,stage:L.report.stage,operationOutcome:L.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),Le.current||(Le.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Mc(B,f)))}};ze(!1);let Jn=async(B,f=gt.current)=>{if(Ee())return;let L=f?.sessionId??e;if(Lt.current){await Lt.current(B,{sessionId:L,accountPatch:f?.accountPatch,nonce:f?.nonce});return}let S=K.startTiming();K.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let I=()=>{K.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),K.performance({stage:"processing",durationMs:K.elapsed(S),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let A=wt.current,w=f?.accountPatch?.email??rn.current,J=f?.accountPatch?.userId??A?.customer?.id??A?.accountData?.userId??"",Xe=f?.accountPatch?.firstName??A?.customer?.firstName??A?.accountData?.firstName,Dt=f?.accountPatch?.lastName??A?.customer?.lastName??A?.accountData?.lastName,me=await new ba.PaymentAPI(at,{telemetry:!1}).processPayment(J,{sessionId:L,nonce:f?.nonce??Vn.current,paymentMethodCategory:"paypal",tokenizedData:B,accountData:{userId:J,email:w??A?.customer?.email??"",...Xe?{firstName:Xe}:{},...Dt?{lastName:Dt}:{},country:f?.accountPatch?.country??A?.customer?.country??A?.accountData?.country??void 0,zip:f?.accountPatch?.zip??A?.customer?.zip??A?.accountData?.zip??void 0}});if(me.ok){if(Kn||Gt&&yn.current)return;I(),K.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),dt(()=>vn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ee())return;let v=await me.json().catch(()=>null),x=v?.message??"PayPal payment failed.",re=Dr(x)??x;I(),me.status===400&&(typeof v?.declineCode=="string"||!Array.isArray(v?.fields))?K.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):me.status===400||me.status===422?K.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):K.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Nc(me.status),failureCategory:me.status>=500?"server_error":void 0}),zn(re),dt(()=>mn.current?.(nn("paypal",re,{code:v?.code,declineCode:v?.declineCode})));return}catch(A){if(Ee())return;I(),K.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let w=A instanceof Error?A.message:"PayPal payment failed.",J=Dr(w)??w;zn(J),dt(()=>mn.current?.(nn("paypal",J)));return}},Zt=()=>new qt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),_t=B=>Ee()?Promise.reject(Zt()):Promise.resolve(B),D=async B=>{if(Ee())throw Zt();Wn||Sr();let f=gt.current,L=f?.sessionId??e,S=f?.nonce??Vn.current;K.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let I;try{I=await new ba.PaymentAPI(at,{telemetry:!1}).createSessionIntent(L,S??"",Je?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:be==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:sn})}catch(A){throw K.error({...(0,qt.classifyTelemetryFailure)(A,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),A}if(Ee())throw Zt();if(I.provider!=="paypal"||I.providerObjectType!==be)throw new Error(B);return K.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),I.providerObjectId},F=(B,f)=>{let L=f?.nonce??Vn.current;if(!L)return;let S=f?.sessionId??e,I=po(B)??_r(B)??"provider_declined";new ba.PaymentAPI(at,{telemetry:!1}).reportSessionIntentDecline(S,L,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:I}).catch(()=>{})},j=N;G("loadScript:scheduled (deferred 1 tick)");let Y=null,pt=setTimeout(()=>{if(Gt){G("loadScript:skipped (cancelled before defer ran)");return}G("loadScript:start");let B=fn==="live"?"production":fn,f={};be==="subscription"?f={intent:"subscription",vault:!0}:be==="order"&&(f={intent:"capture"}),Y=(0,zs.loadScript)({clientId:l,currency:u,...f,...B?{environment:B}:{},...B==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let L=!1;Y.then(S=>{if(L=!0,G(`loadScript:resolved inactive=${Ee()} ns=${!!S} buttons=${!!S?.Buttons}`),Ee())return;if(!S?.Buttons){G("FAIL: namespace missing Buttons factory"),st("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}K.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),K.performance({stage:"provider_ready",durationMs:K.elapsed(ge.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),K.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let I=async(me,v)=>{if(Ee()||ot.current!==j)return;let x=me.vaultSetupToken??me.subscriptionID??me.orderID??"",re=x?Ot.current.get(x):At.current.get(j);if(!(!re||!Vt(re.generation))&&on(re.generation)){Ot.current.delete(x),At.current.delete(re.surfaceKey),It("approved");try{if(Be(!0),dt(()=>pn.current?.(null)),!x)throw new qt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ke=wt.current,xe=Vr(kt.current??[ke?.customer?.firstName,ke?.customer?.lastName].filter(Boolean).join(" ")),Ie=Mn({email:re.accountPatch?.email?.trim()||rn.current?.trim()||ke?.customer?.email?.trim(),firstName:re.accountPatch?.firstName?.trim()||xe.firstName,lastName:re.accountPatch?.lastName?.trim()||xe.lastName});if(!(0,qt.isValidEmail)(Ie.email)||!(Ie.firstName||Ie.lastName))try{let vt=Dc(await v?.order?.get?.());Ie=Mn({email:vt.email||Ie.email,firstName:vt.firstName||Ie.firstName,lastName:vt.lastName||Ie.lastName})}catch{}if((Ke.current||ee)&&!(0,qt.isValidEmail)(Ie.email)){let vt=await ce("PayPal",Ie);if(!vt)return;Ie=vt}(0,qt.isValidEmail)(Ie.email)&&(re.accountPatch=Mn({...re.accountPatch,...Ie}),await Ke.current?.(Ie));let tt;be==="setup_token"?tt={id:x,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Je?tt={id:x,isPaypal:!0,gateway:"paypal",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:tt={id:x,isPaypal:!0},await Jn(tt,re)}catch(ke){zn(ke instanceof Error?ke.message:"PayPal capture failed.")}finally{Ee()||Be(!1)}}},A=me=>{let v=pe?()=>_t(pe):()=>D(me);return async()=>$e(await v())},w=S.Buttons({style:{layout:"horizontal",height:va,tagline:!1},...Fe==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(me,v)=>{if(Ee()){await v.reject();return}Sr();let x=Qe.current,re={};if(x)try{let Ie=await x("paypal");if(Ee()){await v.reject();return}if(!Ie.proceed){gt.current=null,At.current.delete(j),await v.reject();return}re={sessionId:Ie.sessionId,accountPatch:Ie.accountPatch,nonce:Ie.nonce}}catch(Ie){G(`onClick:runBeforeButtonClick rejected msg=${(Ie instanceof Error?Ie.message:String(Ie)).slice(0,120)}`),gt.current=null,At.current.delete(j),await v.reject();return}dt(()=>Bn.current?.("paypal"));let ke=Dn(),xe={generation:ke,surfaceKey:j,...re};gt.current=xe,At.current.set(j,xe),rt.current={...O,attempt:ke},await v.resolve(),K.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),K.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),nt.current=K.startTiming()},createOrder:be==="order"?A("Failed to create PayPal order."):void 0,createSubscription:be==="subscription"?A("Failed to create PayPal subscription."):void 0,createVaultSetupToken:be==="setup_token"?async()=>$e(await D("Failed to create PayPal setup token.")):void 0,onApprove:I,onCancel:()=>{if(Ee())return;let me=At.current.get(j)??gt.current;me&&At.current.delete(me.surfaceKey),gt.current=null,It("cancelled"),K.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),V.current=!0,Ht({generation:me?.generation,remount:!0,focus:!1})},onError:me=>{if(Ee()||ot.current!==j)return;let v=me instanceof Error?me.message:"PayPal failed to render.";if(G(`onError rendered=${Rn} msg=${v.slice(0,120)}`),Rn){let x=At.current.get(j)??gt.current;if(x&&!Vt(x.generation)||!x&&an())return;if(Sn(v)){on(x?.generation);return}let{errorCode:re,popupBlocked:ke,providerDeclined:xe,terminalReason:Ie}=Fc(me);if(It(Ie),xe){K.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ie}),F(me,x),dt(()=>mn.current?.(nn("paypal",v))),x&&At.current.delete(x.surfaceKey),gt.current=null,on(x?.generation);return}K.error({errorCode:re,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ie}),x&&At.current.delete(x.surfaceKey),gt.current=null,Ht({generation:x?.generation,remount:!0,showRetry:!0,focus:!0}),Cn(me,{code:"paypal_runtime_failed",popupBlocked:ke});return}st(Sn(v)?"teardown":"pre_ready_callback",v)}}),J=w.isEligible();if(G(`isEligible=${J}`),K.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!J){ae(!1),st("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}ir=!0,Or=w,sr=()=>{if(!_n||Yn||Ee()||Rn)return;Yn=!0,G(`container:dims ${gn(Ft)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Nn=new MutationObserver(v=>{if(!Ee()){for(let x of v)if(x.type==="childList")x.addedNodes.forEach(re=>{if(!(re instanceof Element))return;let ke=re.tagName.toLowerCase(),xe=(re.getAttribute("title")??"").slice(0,40),Ie=ke==="iframe"?` ${hn(re)}`:"";G(`child+ ${ke}${xe?` title="${xe}"`:""}${Ie} dims=${gn(re)}`)});else if(x.type==="attributes"&&x.target instanceof Element){let re=x.target;if(re.tagName.toLowerCase()!=="iframe")continue;let ke=x.attributeName;(ke==="src"||ke==="srcdoc")&&G(`attr~ iframe ${ke}=${ke==="srcdoc"?`[${(re.getAttribute("srcdoc")??"").length}ch]`:et(re.getAttribute("src"))} dims=${gn(re)}`)}}}),Nn.observe(Ft,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let me=v=>{if(Ee()||Rn)return;let x=Ft.querySelectorAll("iframe"),re=typeof document<"u"&&"hasStorageAccess"in document;G(`watchdog:${v} container=${gn(Ft)} children=${Ft.childElementCount} iframes=${x.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${re} paypalNetRequests=${kr.value}`),x.forEach((ke,xe)=>{let Ie=(ke.getAttribute("title")??"").slice(0,40);G(` iframe[${xe}] ${gn(ke)}${Ie?` title="${Ie}"`:""} ${hn(ke)}`);let tt=ln(ke);tt&&G(` ${tt}`)}),Ln.length===0&&G(" (no PayPal/zoid window errors captured)")};Gn.push(setTimeout(()=>me("3s"),3e3)),Gn.push(setTimeout(()=>me("8s"),8e3)),Gn.push(setTimeout(()=>me("15s"),15e3))},sr(),G("render:start");let Dt=K.startTiming();ht=setTimeout(()=>{Ee()||Rn||(G("watchdog:11s retryable render timeout"),st("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Rc);let Ae=w.render(Ft);(async()=>{try{if(await Ae,G(`render:resolved inactive=${Ee()}`),En(),Ee()){Mr();return}Rn=!0,ae(!0),Ce(!1),Xt.current?.("ready"),K.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),K.performance({stage:"checkout_render",durationMs:K.elapsed(Dt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(me){let v=me instanceof Error?me.message:"PayPal failed to render.";G(`render:rejected msg=${v.slice(0,120)}`),En(),st(Sn(v)?"teardown":"render_rejected",v)}})()}).catch(S=>{let I=S instanceof Error?S.message:"PayPal operation failed.";G(`provider:failed msg=${I.slice(0,120)}`);let A="script_rejected";L&&Sn(I)?A="teardown":L&&ir&&(A="render_rejected"),st(A,I)})},0);return()=>{Gt=!0,clearTimeout(pt),or&&clearTimeout(or),En(),Tt.current===Br&&(Tt.current=null),Mr(),nt.current=null,rt.current=null}},[U,at,l,u,d,be,Fe,Je,e,pe,N,oe,ce,ee,G,It]);let ve=we?(0,er.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Oe?"#fef2f2":"#f3f4f6",border:`1px solid ${Oe?"#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=${ie} failed=${Oe})`,ft.length===0?`
1
+ "use strict";var bc=Object.create;var ba=Object.defineProperty;var vc=Object.getOwnPropertyDescriptor;var Cc=Object.getOwnPropertyNames;var Pc=Object.getPrototypeOf,Sc=Object.prototype.hasOwnProperty;var wc=(e,t)=>{for(var n in t)ba(e,n,{get:t[n],enumerable:!0})},Fs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Cc(t))!Sc.call(e,o)&&o!==n&&ba(e,o,{get:()=>t[o],enumerable:!(r=vc(t,o))||r.enumerable});return e};var Ds=(e,t,n)=>(n=e!=null?bc(Pc(e)):{},Fs(t||!e||!e.__esModule?ba(n,"default",{value:e,enumerable:!0}):n,e)),kc=e=>Fs(ba({},"__esModule",{value:!0}),e);var ou={};wc(ou,{DirectPayPalButton:()=>Go,FloPayAutomaticPaymentButton:()=>Gl,FloPayCardSetup:()=>Zl,FloPayCardSetupError:()=>sa,FloPayCheckout:()=>Xa,FloPayProvider:()=>Jo,SplitCardForm:()=>Wa,VaultCardFields:()=>Io,dropThirdPartyOnlyError:()=>Ql.dropThirdPartyOnlyError,useCheckout:()=>Gs,useFloPay:()=>Br,usePayPalFloPay:()=>wa});module.exports=kc(ou);var Ql=require("@flopay/shared");var Za=require("@flopay/js"),ir=require("@flopay/shared"),Ze=require("react");var Dt=require("react/jsx-runtime");function Ic(){return(0,Dt.jsxs)(Dt.Fragment,{children:[(0,Dt.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,Dt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Dt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Dt.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,Dt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Rc(){return(0,Dt.jsx)(Dt.Fragment,{children:"Go back"})}function _c(){return(0,Dt.jsx)(Dt.Fragment,{children:"Secure card checkout"})}function lo(e){return e!==void 0&&(e===""||e===null||e===!1)}function co({content:e}){return(0,Dt.jsx)(Dt.Fragment,{children:e===void 0?(0,Dt.jsx)(Ic,{}):e})}function uo({content:e}){return(0,Dt.jsx)(Dt.Fragment,{children:e===void 0?(0,Dt.jsx)(Rc,{}):e})}function Uo({content:e}){return(0,Dt.jsx)(Dt.Fragment,{children:e===void 0?(0,Dt.jsx)(_c,{}):e})}var At=require("@flopay/shared"),Ec="Checkout is temporarily unavailable. Please try again later.";function hi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof At.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Tc(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 Os(){return new At.FloPayError(Ec,"api_error",{code:"CheckoutInitializationFailed"})}function bi(e){return!!e?.gateways?.worldpayCorporateGateway}function Or(e){return e?.status==="open"&&bi(e)}function Ls(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card")||Or(r))||t&&e?.data.paypal?.publishableKey)}function Ns(e,t){if(t&&(!(e instanceof At.FloPayError)||e.type==="authentication_error"))return hi(e);if(!(e instanceof At.FloPayError&&Tc(e))){if(!t&&!(e instanceof At.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,At.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof At.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof At.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function po(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,At.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,At.isValidEmail)(l.email))return Promise.reject(new At.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[f,g]of Object.entries(l)){if(c&&f.endsWith("Name")||typeof g!="string")continue;let b=g.trim();b&&(p[f]=b)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function zs(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function vi(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 Us(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*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:n.map((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function Wr(e){if((0,At.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Ci(e,t){return t?{...e,...t}:e}function dn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Ac=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Lr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Ac)if(n.test(t))return r;return e}function xr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Nr(e){return e?.status==="authorized"||e?.status==="complete"}function qs(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function va(e){let t=qs(e);return new At.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Ca(e){return e instanceof At.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function mo(e){let t=qs(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new At.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function qo(e,t){return e==="processing"||(0,At.isMoneySettledOutcome)(e,t)}function $s(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function js(e,t){let n=e;if((0,At.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:l}=await n.retrieveSetupIntent(t);if(l)throw new At.FloPayError(l.message??"Failed to retrieve setup intent.","api_error",{...l.code?{code:l.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new At.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Vs(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function Pi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function $o(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Dr=require("@flopay/js"),$e=require("@flopay/shared"),C=Ds(require("react"),1);var Si=require("react"),rr=(0,Si.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),pr=(0,Si.createContext)({session:null,loading:!1,error:null});var Ea=require("@flopay/js"),Nt=require("@flopay/shared"),Qs=require("@paypal/paypal-js"),I=require("react");var Hs=require("@flopay/shared"),mr=require("react"),Mr=require("react/jsx-runtime");function Dn(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),l=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...l||t?{lastName:l??""}:{}}}function yo(){let[e,t]=(0,mr.useState)(null),n=(0,mr.useRef)(null),r=(0,mr.useRef)(0),o=(0,mr.useCallback)((l,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:c}),new Promise(p=>{n.current=p})),[]),a=(0,mr.useCallback)(l=>{let c=n.current;n.current=null,t(null),c?.(l)},[]);return(0,mr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function fo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,c]=(0,mr.useState)(e.email?.trim()??""),p=(0,Hs.isValidEmail)(l.trim());return(0,Mr.jsxs)("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Mr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Mr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Mr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:f=>c(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Mr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Mr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Mr.jsxs)("button",{type:"button",disabled:!p||o,onClick:()=>{n(Dn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var xc=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Mc=["https://www.paypal.com","https://www.sandbox.paypal.com"];function Pa(e,t,n){let r=`We couldn't open ${e}. Try again or choose another payment method.`;return t?n?`${r} Open this page in your system browser, then try again.`:`${r} Allow pop-ups for this site, then try again.`:r}function Ks(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Gr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Ir(e){if(typeof e!="object"||e===null)return;let t=e;return Gr(t.code)??Gr(t.type)??Gr(t.name)}function go(e){if(!(typeof e!="object"||e===null))return Gr(e.decline_code)}function jo(e){return typeof e!="object"||e===null?!1:Gr(e.type)?.toLowerCase()==="card_error"||go(e)!==void 0}function Bc(e){let t=Ks(e)?.toLowerCase()??"",n=Ir(e)?.toLowerCase()??"";return xc.has(n)?!0:/(?:popup|pop-up).{0,40}(?:block|denied|prevent)/i.test(t)||/(?:block|denied|prevent).{0,40}(?:popup|pop-up)/i.test(t)}function wi(e){if(Ir(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=Ks(e)??"";return n.includes("No ack for postMessage init()")&&Mc.some(r=>n.includes(r))&&n.includes("10000ms")}function Sa(e,t){if(jo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Bc(e)||t.inAppBrowser&&!t.handoffObserved&&wi(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function zr(e){return Sa(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var Ws=require("@flopay/shared"),Vo=require("react");function Br(){return(0,Vo.useContext)(rr).flopay}function wa(){return(0,Vo.useContext)(rr).paypalFlopay??null}function Gs(){return(0,Vo.useContext)(pr)}function Ys(){return(0,Vo.useContext)(rr).billingApiUrl||(0,Ws.resolveBillingApiUrl)()}function Ho(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function ka(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Js=require("@flopay/shared"),Jr=require("react");function ft(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var Ia=require("react"),Yr=typeof window>"u"?Ia.useEffect:Ia.useLayoutEffect;var Fc={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function Dc(e){return e==="stripe"||e==="paypal"?e:void 0}function Oc(e){let t=Dc(e.provider),n={schemaVersion:Js.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Fc[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var ki=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function ho(e,t){let n=(0,Jr.useRef)(e);n.current=e;let r=(0,Jr.useRef)(new Set),o=(0,Jr.useRef)(t),a=(0,Jr.useRef)(t);return Yr(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Jr.useCallback)(l=>{if(a.current!==t)return;let c=Oc(l);if(c){if(ki.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}ft(()=>n.current?.(c))}},[t])}var Xs=require("react"),Ko=(0,Xs.createContext)(null);function Ra(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Lc=Symbol.for("@flopay/js.telemetry.bridge.v1"),Nc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function zc(){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 Uc(e){let t=zc(),n=(o,a)=>o?o.bind(e):a,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function _a(e){let t=globalThis[Nc];return Uc(t?.(e)??{})}function fn(e){if(e)return e[Lc]}var un=require("react");function Wo(e,t){let n=(0,un.useRef)(0),r=(0,un.useRef)(null),o=(0,un.useRef)(null),a=(0,un.useRef)(e),l=(0,un.useRef)(t?.onHandoffObserved);(0,un.useEffect)(()=>{a.current=e,l.current=t?.onHandoffObserved},[e,t?.onHandoffObserved]);let c=(0,un.useCallback)((P=o.current)=>{P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),p=(0,un.useCallback)(P=>{c();let F=n.current+1;return n.current=F,r.current=null,o.current={generation:F,method:P,timer:null,yieldedControl:!1},F},[c]),f=(0,un.useCallback)(P=>{let F=o.current;return P!==void 0&&F?.generation!==P?!1:(c(F),o.current=null,(P===void 0||r.current===P)&&(r.current=null),!0)},[c]),g=(0,un.useCallback)(P=>{let F=o.current,fe=P??F?.generation??n.current;(P===void 0||F?.generation===P)&&(c(F),o.current=null),r.current=fe},[c]),b=(0,un.useCallback)(P=>r.current===(P??n.current),[]),T=(0,un.useCallback)(P=>o.current?.generation===P&&r.current!==P,[]),w=(0,un.useCallback)(()=>{let P=o.current;P&&(c(P),!P.yieldedControl&&(P.yieldedControl=!0,l.current?.(P.method)))},[c]),S=(0,un.useCallback)(()=>{let P=o.current;!P?.yieldedControl||document.visibilityState!=="visible"||(c(P),P.timer=setTimeout(()=>{P.timer=null,o.current?.generation===P.generation&&(o.current=null,r.current=P.generation,a.current(P.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[c]);return(0,un.useEffect)(()=>{let P=()=>{document.visibilityState==="visible"?S():w()};return document.addEventListener("visibilitychange",P),window.addEventListener("blur",w),window.addEventListener("focus",S),()=>{document.removeEventListener("visibilitychange",P),window.removeEventListener("blur",w),window.removeEventListener("focus",S),c()}},[c,w,S]),{startAttempt:p,finishAttempt:f,invalidateAttempt:g,isAttemptInvalidated:b,isAttemptCurrent:T,generationRef:n}}var or=require("react/jsx-runtime"),Ta=45,qc=1e3,$c=11e3,jc={width:"100%",minHeight:Ta,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"},Vc={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 Hc(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Vc[e.kind]??null}}function Zs(e,t){return e==="watchdog_expired"?"paypal_render_timeout":wi(t)?"paypal_init_timeout":"paypal_init_failure"}function Kc(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function Wc(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function el({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:c,currency:p,isSubscription:f,providerObjectType:g,approvalPresentation:b,onTokenizedBody:T,onComplete:w,onErrorChange:S,onDecline:P,onTechnicalFailure:F,isProcessing:fe=!1,onLoadStateChange:R,onInitializationStateChange:H,allowAutomaticRetry:N=!0,onButtonClick:ne,runBeforeButtonClick:pe,session:we,existingOrderId:ge,telemetry:be,telemetryContext:lt,onInstrument:Ue,debug:ve=!1}){let De=Br(),gt=ho(Ue,e),Ce=(0,I.useMemo)(()=>{if(De)return null;let q=_a({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Nt.SDK_VERSION,enabled:be!==!1});return q.setCheckoutContext(lt??{}),q.beginCheckout(lt??{}),q},[n,De,be,lt?.checkoutMode,lt?.layout]),tt=(0,I.useMemo)(()=>fn(De),[De]);(0,I.useEffect)(()=>()=>{Ce&&Ce.flush().catch(()=>{}).finally(()=>Ce.destroy())},[Ce]);let V=(0,I.useMemo)(()=>({error:q=>{tt?tt.error(q):Ce?.error(q),gt({class:"technical_error",errorCode:q.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":q.errorCode,requestCategory:q.requestCategory,provider:q.provider})},log:q=>{tt?tt.log(q):Ce?.log(q),gt({class:"lifecycle",name:q.name,provider:q.provider})},performance:q=>{tt?tt.performance(q):Ce?.performance(q)},terminal:q=>{tt?tt.terminal(q):Ce?.terminal(q)},startTiming:()=>tt?.now()??Ce?.now()??0,elapsed:q=>tt?.elapsed(q)??Math.max(0,(Ce?.now()??q)-q)}),[gt,tt,Ce]),Te=(0,I.useRef)(null),Ke=(0,I.useRef)(0),Ae=(0,I.useRef)(null),We=(0,I.useRef)(null),_=(0,I.useRef)(null),ie=(0,I.useContext)(Ko),me=(0,I.useRef)(null);me.current||(me.current=Ra());let U=ie??me.current,Oe=(0,I.useRef)(null),Ie=(0,I.useRef)(!1),[$,ut]=(0,I.useState)(!1),[nt,Qe]=(0,I.useState)(!1),[Ne,he]=(0,I.useState)(0),bt=(0,I.useRef)(0),[ae,de]=(0,I.useState)(!1),je=(0,I.useRef)(!1),rt=(0,I.useRef)(!1),[pt,G]=(0,I.useState)(!1),[ht,ot]=(0,I.useState)(!1),{request:D,collect:mt,finish:Xt}=yo(),qe=(0,I.useRef)({sessionId:e,required:!(0,Nt.isValidEmail)(r?.trim()||we?.customer?.email?.trim())});qe.current.sessionId!==e&&(qe.current={sessionId:e,required:!(0,Nt.isValidEmail)(r?.trim()||we?.customer?.email?.trim())});let pn=qe.current.required,u=(0,I.useMemo)(()=>n.replace(/\/+$/,""),[n]),ce=we?.gateways?.paypal?.providerObjectType??g,B=ce??(f?"subscription":"order"),[X]=(0,I.useState)(Ho),vt=we?.gateways?.paypal?.approvalPresentation??b,Ge=ka(X,vt==="app_switch"?"app_switch":void 0,B),Ye=ce==="order"||ce==="setup_token",xt=(0,I.useMemo)(()=>JSON.stringify([u,l,p,c??"",B,Ye,Ge,e,ge??""]),[u,l,p,c,ge,B,Ye,Ge,e]),se=(0,I.useRef)(xt),mn=se.current!==xt,et=(0,I.useRef)(ve),Ft=(0,I.useRef)(null),[Rn,Vt]=(0,I.useState)([]),ze=(0,I.useCallback)(q=>{et.current&&Vt(Je=>[...Je,`${new Date().toISOString().slice(11,23)} ${q}`])},[]);(0,I.useEffect)(()=>{et.current=ve,ve&&ze("debug:enabled"),Ft.current?.setEnabled(ve)},[ze,ve]);let zt=(0,I.useRef)(T),hn=(0,I.useRef)(w),bn=(0,I.useRef)(S),wn=(0,I.useRef)(P),On=(0,I.useRef)(F),vn=(0,I.useRef)(ne),Ht=(0,I.useRef)(R),Ve=(0,I.useRef)(H),xe=(0,I.useRef)(a),Ln=(0,I.useRef)(pe),kt=(0,I.useRef)(we),Cn=(0,I.useRef)(r),_n=(0,I.useRef)(o),Kn=(0,I.useRef)(t),Kt=(0,I.useRef)(null),Zt=(0,I.useRef)(new Map),ln=(0,I.useRef)(new Map),It=(0,I.useRef)(!1);(0,I.useEffect)(()=>(It.current=!0,()=>{It.current=!1}),[]),(0,I.useEffect)(()=>{zt.current=T},[T]),(0,I.useEffect)(()=>{xe.current=a},[a]),(0,I.useEffect)(()=>{hn.current=w},[w]),(0,I.useEffect)(()=>{bn.current=S},[S]),(0,I.useEffect)(()=>{wn.current=P},[P]),(0,I.useEffect)(()=>{On.current=F},[F]),(0,I.useEffect)(()=>{vn.current=ne},[ne]),(0,I.useEffect)(()=>{Ht.current=R},[R]),(0,I.useEffect)(()=>{Ve.current=H},[H]),(0,I.useEffect)(()=>{Ln.current=pe},[pe]),(0,I.useEffect)(()=>{kt.current=we},[we]),(0,I.useEffect)(()=>{Cn.current=r},[r]),(0,I.useEffect)(()=>{_n.current=o},[o]),(0,I.useEffect)(()=>{Kn.current=t},[t]),(0,I.useEffect)(()=>{bt.current=Ne},[Ne]),(0,I.useEffect)(()=>{ae&&Oe.current?.focus()},[ae,Ne]);let Mt=(0,I.useCallback)(()=>{window.setTimeout(()=>{Oe.current?.focus()},0)},[]),yn=(0,I.useCallback)(()=>{ut(!1),he(q=>q+1)},[]),Qt=(0,I.useCallback)(()=>{de(!1),(Te.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Te.current)?.focus?.()},[]);(0,I.useEffect)(()=>{!$||!Ie.current||(Ie.current=!1,Qt())},[Qt,$,Ne]);let Ut=(0,I.useCallback)((q,Je)=>{let le=Je?.popupBlocked??zr(q);le&&U.markBlocked();let nn=Pa("PayPal",le,X.inAppBrowser),Pn=On.current;if(Pn){let rn=le&&X.inAppBrowser?new Nt.FloPayError(nn,"api_error",{code:Je?.code??"paypal_popup_blocked"}):q;Pn("paypal",rn,Je);return}bn.current?.(nn)},[U,X.inAppBrowser]),Wt=(0,I.useCallback)(q=>{let Je=Ae.current,le=We.current;Je===null||!le||(V.log({...le,popupCapability:U.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:q}),V.performance({...le,popupCapability:U.current(),stage:"overlay_return",durationMs:V.elapsed(Je),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:q}),Ae.current=null)},[U,V]),Tt=(0,I.useCallback)((q,Je,le)=>{let nn=We.current;Wt("overlay_timeout"),nn&&V.error({...nn,popupCapability:U.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Ut(Je,{...le,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Ge,terminalReason:"overlay_timeout"}),de(!0),yn(),Mt()},[Wt,Mt,Ut,U,Ge,yn,V]),re=(0,I.useCallback)(()=>{U.markAvailable();let q=We.current;q&&(_.current=q.attempt,V.log({...q,popupCapability:U.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[U,V]),{finishAttempt:en,generationRef:tn,invalidateAttempt:sr,isAttemptCurrent:hr,isAttemptInvalidated:Wn,startAttempt:Gt}=Wo(Tt,{onHandoffObserved:re}),lr=(0,I.useCallback)(()=>(de(!1),Gt("paypal")),[Gt]),qt=(0,I.useCallback)(q=>{sr(q?.generation),q?.showRetry&&de(!0),q?.remount&&yn(),q?.focus!==!1&&Mt()},[Mt,sr,yn]),z=q=>{let Je=Kt.current;return Je&&ln.current.set(q,Je),q};(0,I.useEffect)(()=>{se.current!==xt&&(se.current=xt,je.current=!1,rt.current=!1,ut(!1),Qe(!1),G(!1),Ve.current?.("loading"))},[xt]),(0,I.useEffect)(()=>{ft(()=>Ht.current?.($&&!pt))},[$,pt]);let Ct=(0,Nt.normalizeGatewayEnvironment)(c);(0,I.useEffect)(()=>{let q={attempt:tn.current+1,inAppBrowser:X.inAppBrowser,appFamily:X.appFamily,popupCapability:U.current(),presentationMode:Ge},Je=()=>({...We.current??q,popupCapability:U.current()}),le={error:h=>V.error({...h,...Je()}),log:h=>V.log({...h,...Je()}),performance:h=>V.performance({...h,...Je()}),terminal:h=>V.terminal({...h,...Je()}),startTiming:V.startTiming,elapsed:V.elapsed},nn=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Pn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(ze(`mount clientId=${nn} env=${c??"(unset)"}\u2192${Ct??"live"} ccy=${p} sub=${f}`),ze(`ua=${Pn.slice(0,80)}${Pn.length>80?"\u2026":""}`),!l){ze("FAIL: clientId empty \u2014 gateway misconfigured"),G(!0),le.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(!Te.current){ze("FAIL: containerRef not attached");return}Ke.current=le.startTiming(),le.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let rn=!1,br=!1,Re=()=>rn||br,Nn,Gn=!1,Ur=()=>{Nn=(0,Nt.generateIdempotencyKey)(),Nn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Gn=!0},Yn=null,Jn=!1,Yt=null,Ar=!1,vr=()=>{!Yt||Ar||(Ar=!0,Yt.close().catch(()=>{}))},En=!1,Cr=!1,Xn=Te.current,Zn=null,Pr=null,Qn=[],Rt=null,zn=!1,cr=!1,Un=null,Sn=h=>{if(!h||typeof h.getBoundingClientRect!="function")return"(no rect)";let y=h.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},ct=h=>{if(!h)return"(empty)";try{let y=new URL(h,typeof window>"u"?"https://localhost":window.location.href),E=y.pathname.toLowerCase();return E.includes("checkcaptcha")||E.includes("captcha")?`CAPTCHA(${y.host}${E})`:E.includes("risk")||E.includes("challenge")?`RISK(${y.host}${E})`:E.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${E}`.slice(0,100)}catch{return h.slice(0,80)}},kn=h=>{let y=h.getAttribute("src"),E=h.getAttribute("srcdoc"),j=h.getAttribute("name"),ye=h.getAttribute("sandbox"),oe=[];return y&&oe.push(`src=${ct(y)}`),E&&oe.push(`srcdoc[${E.length}ch]`),!y&&!E&&oe.push("src=(empty) srcdoc=(empty)"),j&&oe.push(`name=${j.slice(0,40)}`),ye!==null&&oe.push(`sandbox="${ye.slice(0,40)}"`),oe.join(" ")},cn=h=>{if(!(h instanceof HTMLIFrameElement))return"";try{let y=h.contentDocument;if(!y)return"cd=null";let E=y.body?.children.length??0,j=y.body?.innerHTML.length??0,ye=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${E}children,${j}ch] head[${ye}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},qn=[],qr=h=>{if(Re())return;let y=h.message??String(h.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(ze(`window:error ${y.slice(0,140)}`),qn.push(y))},$n=h=>{if(Re())return;let y=h.reason instanceof Error?h.reason.message:String(h.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(ze(`window:rejection ${y.slice(0,140)}`),qn.push(y))},Sr={value:0},Tn=()=>{Zn?.disconnect(),Zn=null,Pr?.disconnect(),Pr=null;for(let h of Qn.splice(0))clearTimeout(h);cr=!1,zn&&typeof window<"u"&&(window.removeEventListener("error",qr),window.removeEventListener("unhandledrejection",$n)),zn=!1},An=()=>{if(!(zn||Re()||En)){if(zn=!0,qn.length=0,Sr.value=0,typeof window<"u"&&(window.addEventListener("error",qr),window.addEventListener("unhandledrejection",$n)),typeof PerformanceObserver<"u")try{Pr=new PerformanceObserver(h=>{if(!Re())for(let y of h.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;Sr.value+=1;let E=Math.round(y.duration);ze(`net ${E}ms ${y.name.slice(0,90)}`)}}),Pr.observe({type:"resource",buffered:!0})}catch{}Un?.()}},$r=()=>{Rt&&(clearTimeout(Rt),Rt=null)},jn=()=>{Tn(),$r()},jr={setEnabled:h=>{h?An():Tn()}};Ft.current=jr,et.current&&An();let on=h=>{if(!h)return!1;let y=h.toLowerCase();return y.includes("zoid destroyed")||y.includes("destroyed all components")||y.includes("window closed")||y.includes("detected container element removed")},M=h=>{if(Re()||on(h))return;let y=Lr(h)??h;ft(()=>bn.current?.(y))},v=(h,y)=>{if(rn||Jn)return;Jn=!0,br=!0,jn(),vr();let E=Hc({kind:h,generationActive:!0,automaticRetryAllowed:N,automaticRetryUsed:je.current});if(E.action==="retry"){je.current=!0,ut(!1),ot(!1),Qe(!0),Ve.current?.("retrying"),Yn=setTimeout(()=>{rn||he(j=>j+1)},qc);return}if(ut(!1),ot(!1),Qe(!1),G(!0),E.action!=="ignore"){if(Ve.current?.("exhausted"),E.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",y);return}if(E.report){let j=Sa({code:Zs(h,y),message:y},{inAppBrowser:X.inAppBrowser,handoffObserved:!1});j.popupBlocked&&U.markBlocked(),le.error({errorCode:j.popupBlocked?j.errorCode:E.report.errorCode,stage:E.report.stage,operationOutcome:E.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:j.terminalReason})}rt.current||(rt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Zs(h,y)))}};G(!1);let ee=async(h,y=Kt.current)=>{if(Re())return;let E=y?.sessionId??e;if(zt.current){await zt.current(h,{sessionId:E,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let j=le.startTiming();le.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ye=()=>{le.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),le.performance({stage:"processing",durationMs:le.elapsed(j),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let oe=kt.current,J=y?.accountPatch?.email??Cn.current,ue=y?.accountPatch?.userId??oe?.customer?.id??oe?.accountData?.userId??"",Me=y?.accountPatch?.firstName??oe?.customer?.firstName??oe?.accountData?.firstName,St=y?.accountPatch?.lastName??oe?.customer?.lastName??oe?.accountData?.lastName,Q=await new Ea.PaymentAPI(u,{telemetry:!1}).processPayment(ue,{sessionId:E,nonce:y?.nonce??Kn.current,paymentMethodCategory:"paypal",tokenizedData:h,accountData:{userId:ue,email:J??oe?.customer?.email??"",...Me?{firstName:Me}:{},...St?{lastName:St}:{},country:y?.accountPatch?.country??oe?.customer?.country??oe?.accountData?.country??void 0,zip:y?.accountPatch?.zip??oe?.customer?.zip??oe?.accountData?.zip??void 0}});if(Q.ok){if(br||rn&&It.current)return;ye(),le.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),ft(()=>hn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Re())return;let L=await Q.json().catch(()=>null),Y=L?.message??"PayPal payment failed.",Be=Lr(Y)??Y;ye(),Q.status===400&&(typeof L?.declineCode=="string"||!Array.isArray(L?.fields))?le.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Q.status===400||Q.status===422?le.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):le.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Wc(Q.status),failureCategory:Q.status>=500?"server_error":void 0}),M(Be),ft(()=>wn.current?.(dn("paypal",Be,{code:L?.code,declineCode:L?.declineCode})));return}catch(oe){if(Re())return;ye(),le.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let J=oe instanceof Error?oe.message:"PayPal payment failed.",ue=Lr(J)??J;M(ue),ft(()=>wn.current?.(dn("paypal",ue)));return}},K=()=>new Nt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),_e=h=>Re()?Promise.reject(K()):Promise.resolve(h),Ot=async h=>{if(Re())throw K();Gn||Ur();let y=Kt.current,E=y?.sessionId??e,j=y?.nonce??Kn.current;le.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ye;try{ye=await new Ea.PaymentAPI(u,{telemetry:!1}).createSessionIntent(E,j??"",Ye?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Nt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:B==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Nn})}catch(oe){throw le.error({...(0,Nt.classifyTelemetryFailure)(oe,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),oe}if(Re())throw K();if(ye.provider!=="paypal"||ye.providerObjectType!==B)throw new Error(h);return le.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ye.providerObjectId},Se=(h,y)=>{let E=y?.nonce??Kn.current;if(!E)return;let j=y?.sessionId??e,ye=go(h)??Ir(h)??"provider_declined";new Ea.PaymentAPI(u,{telemetry:!1}).reportSessionIntentDecline(j,E,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ye}).catch(()=>{})},Pe=Ne;ze("loadScript:scheduled (deferred 1 tick)");let O=null,Z=setTimeout(()=>{if(rn){ze("loadScript:skipped (cancelled before defer ran)");return}ze("loadScript:start");let h=Ct==="live"?"production":Ct,y={};B==="subscription"?y={intent:"subscription",vault:!0}:B==="order"&&(y={intent:"capture"}),O=(0,Qs.loadScript)({clientId:l,currency:p,...y,...h?{environment:h}:{},...h==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let E=!1;O.then(j=>{if(E=!0,ze(`loadScript:resolved inactive=${Re()} ns=${!!j} buttons=${!!j?.Buttons}`),Re())return;if(!j?.Buttons){ze("FAIL: namespace missing Buttons factory"),v("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}le.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),le.performance({stage:"provider_ready",durationMs:le.elapsed(Ke.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),le.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ye=async(Q,L)=>{if(Re()||bt.current!==Pe)return;let Y=Q.vaultSetupToken??Q.subscriptionID??Q.orderID??"",Be=Y?ln.current.get(Y):Zt.current.get(Pe);if(!(!Be||!hr(Be.generation))&&en(Be.generation)){ln.current.delete(Y),Zt.current.delete(Be.surfaceKey),Wt("approved");try{if(ot(!0),ft(()=>bn.current?.(null)),!Y)throw new Nt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Fe=kt.current,Pt=Wr(_n.current??[Fe?.customer?.firstName,Fe?.customer?.lastName].filter(Boolean).join(" ")),Xe=Dn({email:Be.accountPatch?.email?.trim()||Cn.current?.trim()||Fe?.customer?.email?.trim(),firstName:Be.accountPatch?.firstName?.trim()||Pt.firstName,lastName:Be.accountPatch?.lastName?.trim()||Pt.lastName});if(!(0,Nt.isValidEmail)(Xe.email)||!(Xe.firstName||Xe.lastName))try{let an=Kc(await L?.order?.get?.());Xe=Dn({email:an.email||Xe.email,firstName:an.firstName||Xe.firstName,lastName:an.lastName||Xe.lastName})}catch{}if((xe.current||pn)&&!(0,Nt.isValidEmail)(Xe.email)){let an=await mt("PayPal",Xe);if(!an)return;Xe=an}(0,Nt.isValidEmail)(Xe.email)&&(Be.accountPatch=Dn({...Be.accountPatch,...Xe}),await xe.current?.(Xe));let xn;B==="setup_token"?xn={id:Y,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Nt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Ye?xn={id:Y,isPaypal:!0,gateway:"paypal",paymentMethodType:Nt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:xn={id:Y,isPaypal:!0},await ee(xn,Be)}catch(Fe){M(Fe instanceof Error?Fe.message:"PayPal capture failed.")}finally{Re()||ot(!1)}}},oe=Q=>{let L=ge?()=>_e(ge):()=>Ot(Q);return async()=>z(await L())},J=j.Buttons({style:{layout:"horizontal",height:Ta,tagline:!1},...Ge==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Q,L)=>{if(Re()){await L.reject();return}Ur();let Y=Ln.current,Be={};if(Y)try{let Xe=await Y("paypal");if(Re()){await L.reject();return}if(!Xe.proceed){Kt.current=null,Zt.current.delete(Pe),await L.reject();return}Be={sessionId:Xe.sessionId,accountPatch:Xe.accountPatch,nonce:Xe.nonce}}catch(Xe){ze(`onClick:runBeforeButtonClick rejected msg=${(Xe instanceof Error?Xe.message:String(Xe)).slice(0,120)}`),Kt.current=null,Zt.current.delete(Pe),await L.reject();return}ft(()=>vn.current?.("paypal"));let Fe=lr(),Pt={generation:Fe,surfaceKey:Pe,...Be};Kt.current=Pt,Zt.current.set(Pe,Pt),We.current={...q,attempt:Fe},await L.resolve(),le.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),le.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Ae.current=le.startTiming()},createOrder:B==="order"?oe("Failed to create PayPal order."):void 0,createSubscription:B==="subscription"?oe("Failed to create PayPal subscription."):void 0,createVaultSetupToken:B==="setup_token"?async()=>z(await Ot("Failed to create PayPal setup token.")):void 0,onApprove:ye,onCancel:()=>{if(Re())return;let Q=Zt.current.get(Pe)??Kt.current;Q&&Zt.current.delete(Q.surfaceKey),Kt.current=null,Wt("cancelled"),le.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ie.current=!0,qt({generation:Q?.generation,remount:!0,focus:!1})},onError:Q=>{if(Re()||bt.current!==Pe)return;let L=Q instanceof Error?Q.message:"PayPal failed to render.";if(ze(`onError rendered=${En} msg=${L.slice(0,120)}`),En){let Y=Zt.current.get(Pe)??Kt.current;if(Y&&!hr(Y.generation)||!Y&&Wn())return;if(on(L)){en(Y?.generation);return}let{errorCode:Be,popupBlocked:Fe,providerDeclined:Pt,terminalReason:Xe}=Sa(Q,{inAppBrowser:X.inAppBrowser,handoffObserved:Y!=null&&_.current===Y.generation});if(Fe&&U.markBlocked(),Wt(Xe),Pt){le.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Xe}),Se(Q,Y),ft(()=>wn.current?.(dn("paypal",L))),Y&&Zt.current.delete(Y.surfaceKey),Kt.current=null,en(Y?.generation);return}le.error({errorCode:Be,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Xe}),Y&&Zt.current.delete(Y.surfaceKey),Kt.current=null,qt({generation:Y?.generation,remount:!0,showRetry:!0,focus:!0}),Ut(Q,{code:"paypal_runtime_failed",popupBlocked:Fe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:Ge,terminalReason:Xe});return}v(on(L)?"teardown":"pre_ready_callback",L)}}),ue=J.isEligible();if(ze(`isEligible=${ue}`),le.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ue){ut(!1),v("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Cr=!0,Yt=J,Un=()=>{if(!zn||cr||Re()||En)return;cr=!0,ze(`container:dims ${Sn(Xn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Zn=new MutationObserver(L=>{if(!Re()){for(let Y of L)if(Y.type==="childList")Y.addedNodes.forEach(Be=>{if(!(Be instanceof Element))return;let Fe=Be.tagName.toLowerCase(),Pt=(Be.getAttribute("title")??"").slice(0,40),Xe=Fe==="iframe"?` ${kn(Be)}`:"";ze(`child+ ${Fe}${Pt?` title="${Pt}"`:""}${Xe} dims=${Sn(Be)}`)});else if(Y.type==="attributes"&&Y.target instanceof Element){let Be=Y.target;if(Be.tagName.toLowerCase()!=="iframe")continue;let Fe=Y.attributeName;(Fe==="src"||Fe==="srcdoc")&&ze(`attr~ iframe ${Fe}=${Fe==="srcdoc"?`[${(Be.getAttribute("srcdoc")??"").length}ch]`:ct(Be.getAttribute("src"))} dims=${Sn(Be)}`)}}}),Zn.observe(Xn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Q=L=>{if(Re()||En)return;let Y=Xn.querySelectorAll("iframe"),Be=typeof document<"u"&&"hasStorageAccess"in document;ze(`watchdog:${L} container=${Sn(Xn)} children=${Xn.childElementCount} iframes=${Y.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Be} paypalNetRequests=${Sr.value}`),Y.forEach((Fe,Pt)=>{let Xe=(Fe.getAttribute("title")??"").slice(0,40);ze(` iframe[${Pt}] ${Sn(Fe)}${Xe?` title="${Xe}"`:""} ${kn(Fe)}`);let xn=cn(Fe);xn&&ze(` ${xn}`)}),qn.length===0&&ze(" (no PayPal/zoid window errors captured)")};Qn.push(setTimeout(()=>Q("3s"),3e3)),Qn.push(setTimeout(()=>Q("8s"),8e3)),Qn.push(setTimeout(()=>Q("15s"),15e3))},Un(),ze("render:start");let St=le.startTiming();Rt=setTimeout(()=>{Re()||En||(ze("watchdog:11s retryable render timeout"),v("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},$c);let Le=J.render(Xn);(async()=>{try{if(await Le,ze(`render:resolved inactive=${Re()}`),jn(),Re()){vr();return}En=!0,ut(!0),Qe(!1),Ve.current?.("ready"),le.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),le.performance({stage:"checkout_render",durationMs:le.elapsed(St),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Q){let L=Q instanceof Error?Q.message:"PayPal failed to render.";ze(`render:rejected msg=${L.slice(0,120)}`),jn(),v(on(L)?"teardown":"render_rejected",L)}})()}).catch(j=>{let ye=j instanceof Error?j.message:"PayPal operation failed.";ze(`provider:failed msg=${ye.slice(0,120)}`);let oe="script_rejected";E&&on(ye)?oe="teardown":E&&Cr&&(oe="render_rejected"),v(oe,ye)})},0);return()=>{rn=!0,clearTimeout(Z),Yn&&clearTimeout(Yn),jn(),Ft.current===jr&&(Ft.current=null),vr(),Ae.current=null,We.current=null}},[N,u,l,p,c,B,Ge,Ye,e,ge,Ne,V,mt,pn,ze,Wt]);let at=ve?(0,or.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:pt?"#fef2f2":"#f3f4f6",border:`1px solid ${pt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${$} failed=${pt})`,Rn.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${ft.join(`
4
- `)}`]}):null;return Oe&&!W?we?(0,er.jsx)("div",{children:ve}):null:(0,er.jsxs)("div",{children:[ve,Ne&&(0,er.jsx)(uo,{identity:Ne.identity,methodLabel:Ne.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:dn,onCancel:()=>dn(null)}),(0,er.jsxs)("div",{"aria-hidden":Ye||Ne?!0:void 0,style:Ye||Ne?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:va},children:[!ie&&!Ye&&(0,er.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,er.jsx)("div",{ref:_e,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:va,display:"flex",opacity:ie?1:0},"aria-busy":je||ue},N)]},N),he&&(0,er.jsx)("button",{ref:M,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Pn,style:Ec,children:"Try PayPal again"})]})}function Uo(e){return(0,er.jsx)(Us,{...e})}function qs(e){return(0,er.jsx)(Us,{...e})}var qo=require("react/jsx-runtime");function yo({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,qo.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,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&(0,qo.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,qo.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 Pa=require("@flopay/shared");function fo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var fi=":idempotency-key";function gi(e,t){if(!fo())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function hi(e,t){if(!fo())return null;try{let n=window.sessionStorage.getItem(e+fi);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Ca(e,t){if(fo())try{gi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Sa(e,t){if(Ca(e,t),!!fo())try{hi(e,t)&&window.sessionStorage.removeItem(e+fi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function wa(e,t,n,r){if(fo())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function ka(e,t,n){if(fo())try{window.sessionStorage.setItem(e+fi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function yi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Lc(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([l],[d])=>l<d?-1:l>d?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let l=0;l<t.length;l++){let d=t.charCodeAt(l);n=r^Math.imul(n^d,597399067),r=o^Math.imul(r^d,2869860233),o=a^Math.imul(o^d,951274213),a=n^Math.imul(a^d,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(l=>(l>>>0).toString(16).padStart(8,"0")).join("")}function go(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>yi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>yi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>yi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Lc(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function $s(e,t=!1){let n=go(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function Vs(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=(0,Pa.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,Pa.foldIntoProducts)(t.items,t.subscriptions)).map(m=>({type:m.type,code:m.code??m.providerItemId??m.providerPlanId??"",quantity:m.quantity??1,totalAmount:m.totalAmount,overrideAmount:m.overrideAmount??null,currency:(m.currency??o).toUpperCase()})).sort((m,h)=>`${m.code}:${m.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),l=e.products.map(m=>({type:m.type,code:m.code??"",quantity:m.quantity??1,totalAmount:m.totalAmount,overrideAmount:m.overrideAmount??null,currency:(m.currency??e.currency).toUpperCase()})).sort((m,h)=>`${m.code}:${m.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(a.length!==l.length)return!1;for(let[m,h]of a.entries()){let b=l[m];if(b===void 0||h.code!==b.code||h.type!==void 0&&h.type!==b.type||h.quantity!==b.quantity||h.totalAmount!==b.totalAmount||h.overrideAmount!==b.overrideAmount||h.currency!==b.currency)return!1}let d=[...t.couponCodes??[]].sort(),u=[...e.coupons??[]].sort();return d.length===u.length&&d.every((m,h)=>m===u[h])}var Yt=require("react/jsx-runtime");var Oc={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function tr({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:d=Oc}){let u={fontSize:13,color:d.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,Yt.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,Yt.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,Yt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Yt.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,Yt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:d.spinnerTrackColor,strokeWidth:"3"}),(0,Yt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:d.spinnerAccentColor})]}),e==="success"&&(0,Yt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Yt.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,Yt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Yt.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,Yt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Yt.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,Yt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Yt.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,Yt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:d.labelColors[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&l!==null&&(0,Yt.jsx)("p",{style:u,children:l}),e==="error"&&t&&(0,Yt.jsx)("p",{style:u,children:t}),(0,Yt.jsx)("style",{children:`
3
+ ${Rn.join(`
4
+ `)}`]}):null;return pt&&!mn?ve?(0,or.jsx)("div",{children:at}):null:(0,or.jsxs)("div",{children:[at,D&&(0,or.jsx)(fo,{identity:D.identity,methodLabel:D.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Xt,onCancel:()=>Xt(null)}),(0,or.jsxs)("div",{"aria-hidden":nt||D?!0:void 0,style:nt||D?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ta},children:[!$&&!nt&&(0,or.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,or.jsx)("div",{ref:Te,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ta,display:"flex",opacity:$?1:0},"aria-busy":ht||fe},Ne)]},Ne),ae&&(0,or.jsx)("button",{ref:Oe,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Qt,style:jc,children:"Try PayPal again"})]})}function Go(e){return(0,or.jsx)(el,{...e})}function tl(e){return(0,or.jsx)(el,{...e})}var Yo=require("react/jsx-runtime");function bo({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,Yo.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,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&(0,Yo.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Yo.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 Aa=require("@flopay/shared");function vo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Ri=":idempotency-key";function _i(e,t){if(!vo())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Ei(e,t){if(!vo())return null;try{let n=window.sessionStorage.getItem(e+Ri);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function xa(e,t){if(vo())try{_i(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ma(e,t){if(xa(e,t),!!vo())try{Ei(e,t)&&window.sessionStorage.removeItem(e+Ri)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ba(e,t,n,r){if(vo())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Fa(e,t,n){if(vo())try{window.sessionStorage.setItem(e+Ri,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Ii(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Gc(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([l],[c])=>l<c?-1:l>c?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let l=0;l<t.length;l++){let c=t.charCodeAt(l);n=r^Math.imul(n^c,597399067),r=o^Math.imul(r^c,2869860233),o=a^Math.imul(o^c,951274213),a=n^Math.imul(a^c,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(l=>(l>>>0).toString(16).padStart(8,"0")).join("")}function Co(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Ii(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ii(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ii(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Gc(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function nl(e,t=!1){let n=Co(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function rl(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=(0,Aa.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,Aa.foldIntoProducts)(t.items,t.subscriptions)).map(f=>({type:f.type,code:f.code??f.providerItemId??f.providerPlanId??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??o).toUpperCase()})).sort((f,g)=>`${f.code}:${f.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),l=e.products.map(f=>({type:f.type,code:f.code??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??e.currency).toUpperCase()})).sort((f,g)=>`${f.code}:${f.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(a.length!==l.length)return!1;for(let[f,g]of a.entries()){let b=l[f];if(b===void 0||g.code!==b.code||g.type!==void 0&&g.type!==b.type||g.quantity!==b.quantity||g.totalAmount!==b.totalAmount||g.overrideAmount!==b.overrideAmount||g.currency!==b.currency)return!1}let c=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return c.length===p.length&&c.every((f,g)=>f===p[g])}var Jt=require("react/jsx-runtime");var Yc={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function ar({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:c=Yc}){let p={fontSize:13,color:c.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,Jt.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,Jt.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...c.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,Jt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Jt.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,Jt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:c.spinnerTrackColor,strokeWidth:"3"}),(0,Jt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.spinnerAccentColor})]}),e==="success"&&(0,Jt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Jt.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,Jt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Jt.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,Jt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Jt.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,Jt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Jt.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,Jt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:c.labelColors[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&l!==null&&(0,Jt.jsx)("p",{style:p,children:l}),e==="error"&&t&&(0,Jt.jsx)("p",{style:p,children:t}),(0,Jt.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 js=require("@flopay/shared"),cn=require("react");var Ks=require("react/jsx-runtime");function $o({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=(0,cn.useState)(e instanceof Promise?null:e),[d,u]=(0,cn.useState)(t instanceof Promise||!t?null:t),m=(0,cn.useRef)(null),h=(0,cn.useRef)(null),b=mo(r);(0,cn.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,cn.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,cn.useEffect)(()=>{if(a)return en(a)?.subscribe?.(b)},[b,a]),(0,cn.useEffect)(()=>{if(!(!d||d===a))return en(d)?.subscribe?.(b)},[b,a,d]),(0,cn.useEffect)(()=>{if(!a)return;let _=en(a);return m.current=_?.beginCheckout()??_?.now()??0,_?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{_?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,cn.useEffect)(()=>{let _=!1;return e instanceof Promise?e.then(ne=>{_||l(ne)},()=>{_||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{_=!0}},[b,e]),(0,cn.useEffect)(()=>{let _=!1;if(!t){u(null);return}return t instanceof Promise?t.then(ne=>{_||u(ne)},()=>{_||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):u(t),()=>{_=!0}},[b,t]),(0,cn.useEffect)(()=>{if(!a||h.current===a)return;h.current=a;let _=en(a);_?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),_?.performance({stage:"checkout_render",durationMs:_.elapsed(m.current??0),durationMode:"machine"})},[b,a]);let y=(0,js.resolveBillingApiUrl)(n?.billingApiUrl),C=(0,cn.useMemo)(()=>({flopay:a,paypalFlopay:d,billingApiUrl:y,emitInstrument:b}),[a,d,y,b]);return(0,Ks.jsx)(Qn.Provider,{value:C,children:o})}var Ia="flopay_recent_completion_";function ho(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Ia+e,JSON.stringify(t))}catch{}}function bi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Ia+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Ia+e),!1):!0}catch{return!1}}async function Ra(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}var Hr=require("@flopay/js"),We=require("@flopay/shared");var jo="card",zc=1e3,Hs=3e5;async function Uc(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function qc(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Ko(e){return new We.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Pi(e,t){return Object.assign(e,{checkoutMethod:t})}function Ar(e,t){let n=e instanceof We.FloPayError?e:new We.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Vo(e,t){try{return await e()}catch(n){throw Ar(n,t)}}function Gs(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 $c(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Ci(e){if(typeof document>"u"||typeof window>"u")throw new We.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new We.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let b=new AbortController,y=()=>b.abort();e.signal?.aborted?b.abort():e.signal?.addEventListener("abort",y);let C=window.setTimeout(()=>b.abort(),n);try{let _=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:b.signal});if(!_.ok)return{status:"unknown"};let ne=await _.json().catch(()=>null);return Vc(ne)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",y)}},a,l=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),d=document.activeElement instanceof HTMLElement?document.activeElement:null,u=document.createElement("div");u.setAttribute("data-flopay-auto-3ds-overlay","1"),u.setAttribute("role","dialog"),u.setAttribute("aria-modal","true"),u.setAttribute("aria-label","Card authentication"),u.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}try{let b=await new Promise((y,C)=>{let _=!1,ne=0,z=0,ue=0,k=!1,$=()=>{window.clearTimeout(ne),window.clearInterval(z),window.clearTimeout(ue),window.removeEventListener("message",Pe),m.removeEventListener("load",se),e.signal?.removeEventListener("abort",Se)},U=async()=>{if(!(_||k)){k=!0;try{let pe=await l();if(_||!$c(pe))return;_=!0,$(),y(pe)}finally{k=!1}}},se=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(ue),ue=window.setTimeout(()=>{U()},250))},Se=()=>{_||(_=!0,$(),C(new We.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Pe=pe=>{if(pe.source!==m.contentWindow||h&&pe.origin!==h)return;let ye=pe.data;!ye||typeof ye!="object"||ye.source!=="flopay-vault-3ds-return"||_||(_=!0,$(),y(null))};ne=window.setTimeout(()=>{_||(_=!0,$(),C(new We.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},Hs),e.pollCompletionEndpoint!==!1&&(z=window.setInterval(()=>{U()},t)),m.addEventListener("load",se),window.addEventListener("message",Pe),e.signal?.addEventListener("abort",Se),m.src=e.nextActionRedirectUrl,u.appendChild(m),document.body.appendChild(u),m.focus(),e.signal?.aborted&&Se()});return b||await l()}finally{u.parentNode?.removeChild(u),d?.isConnected&&d.focus()}}async function bo(e,t){let n=t.nonce??t.session.clientSecret,r=new Hr.PaymentAPI(t.billingApiUrl,{telemetry:!1}),o=new AbortController,a=new AbortController,l=()=>{o.abort(t.signal.reason),a.abort(t.signal.reason)};t.signal.aborted?l():t.signal.addEventListener("abort",l,{once:!0});let d=Ci({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:n,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),u=null,m=()=>(u??(u=r.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:zc,nonce:n,statusUrl:`${t.billingApiUrl.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,continueAfterActionRequired:!0,timeoutMs:Hs,signal:a.signal})),u),h=m(),b;try{let C=await Promise.race([d.then(_=>({kind:"challenge",outcome:_})),h.then(_=>({kind:"status",session:_}))]);if(C.kind==="status")o.abort(),b=C.session;else{if(C.outcome.status==="declined")throw br({type:C.outcome.declineReason??"authorization_declined",message:"Card was declined.",gatewayErrorCode:C.outcome.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});b=await m()}}catch(C){throw t.signal.aborted||C instanceof Error&&C.name==="AbortError"?Ko(C):C}finally{t.signal.removeEventListener("abort",l),o.abort(),a.abort()}let y=b.data.session;if(!Nr(y))throw lo(y);return{...Ir(y,t.sessionId),checkoutMethod:"card"}}function Vc(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"authorized":return{status:"authorized",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function br(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=Dr(o)??o,l=Pi(new We.FloPayError(a,"api_error",{code:e?.code??(0,We.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,We.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(l.orderId=e.orderId),l}function vi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function _a(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Ys(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||_a(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of a)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||_a(d)))return d;let l=o.gateways;if(l&&typeof l=="object"){let d=l.stripe;if(d&&typeof d=="object"){let u=d,m=[u.stripeClientSecret,u.clientSecret];for(let h of m)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||_a(h)))return h}}}}async function jc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Ys(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new Hr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(_a(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function vo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let d=e.replace(/\/+$/,""),u=t??n.id,m=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",y=n.customer?.firstName??n.accountData?.firstName??"",C=n.customer?.lastName??n.accountData?.lastName??"",_=n.customer?.country??n.accountData?.country??void 0,ne=n.customer?.zip??n.accountData?.zip??void 0,ue=await new Hr.PaymentAPI(d,l===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:u,nonce:m,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:b,firstName:y,lastName:C,country:_,zip:ne},returnUrl:a??vi(n)});if(ue.ok){let U=typeof ue.json=="function"?await ue.json().catch(()=>null):null;if((0,We.isAuthorizationOnlySession)(n)||U?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof U?.paymentId=="string"?U.paymentId:n.paymentId,sessionId:typeof U?.sessionId=="string"?U.sessionId:u,authorizationExpiresAt:typeof U?.authorizationExpiresAt=="string"?U.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:No(o),checkoutMethod:Ws(o,n)}};let se=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...se?{paymentIntentId:se}:{},paymentMethodId:No(o),checkoutMethod:Ws(o,n)}}}let k;try{k=await ue.json()}catch(U){throw new We.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ue.status,cause:U})}if(k?.type==="3ds_required"&&typeof k.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:k.nextActionRedirectUrl};if(k?.type==="paypal_redirect_required"||k?.type==="3ds_required"){let U=Ys(k);if(!U)throw new We.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ue.status});return{type:k.type,threeDSecureToken:U,paymentMethodId:k.paymentMethodId}}if(k?.gatewayErrorCode==="authentication_required"){let U=await jc({billingApiUrl:d,sessionId:u,nonce:m,responseJson:k});if(U)return U;throw Pi(new We.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let $=new We.FloPayError(k?.message??"Payment failed. Please try again.","api_error",{code:k?.code??k?.gatewayErrorCode,declineCode:k?.declineCode??k?.gatewayDeclineReason,statusCode:ue.status});throw Object.assign($,{telemetryOutcome:(0,We.classifyPaymentRejection)(ue.status,k)})}async function Ea(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:u,signal:m}){let h=t?.getRawProvider();if(!h)throw Ar(new We.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Pi(new We.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,We.isSetupIntentClientSecret)(e.threeDSecureToken),y=null,C=e.paymentMethodId,_=await Vo(()=>Uc(h,e.threeDSecureToken,b),"card");if(_){if(_.error)throw Ar(new We.FloPayError(_.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let z=_.intent;!C&&z?.payment_method&&(typeof z.payment_method=="string"?C=z.payment_method:"id"in z.payment_method&&(C=z.payment_method.id??void 0))}let ne=C?await Vo(()=>qc(h,e.threeDSecureToken,{payment_method:C,return_url:d??vi(l)??window.location.href},b),"card"):null;if(ne){if(ne.error)throw Ar(new We.FloPayError(ne.error.message??"3DS authentication failed.","api_error",{code:ne.error.code}),"card");y=ne.intent}else{let z=await Vo(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(z.error)throw Ar(new We.FloPayError(z.error.message??"3DS authentication failed.","api_error",{code:z.error.code}),"card");y=(b?z.setupIntent:z.paymentIntent)??null}if(y&&(y.status==="requires_capture"||y.status==="succeeded"||y.status==="processing")){let z=await vo({billingApiUrl:o,sessionId:a,session:l,telemetry:u,tokenizedData:{id:y.id,type:"card",threeDSecureActionResultTokenId:y.id},returnUrl:d});return z.type==="success"?{...z.result,paymentIntentId:z.result.paymentIntentId??y.id,paymentMethodId:z.result.paymentMethodId??C}:z.type==="next_action_required"?bo(z,{billingApiUrl:o,sessionId:a??l.id,session:l,signal:m}):Ea(z,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:d,telemetry:u,signal:m})}throw Ar(new We.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw Ar(new We.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await Vo(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(C)throw Ar(new We.FloPayError(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:y}=await Vo(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??vi(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(y)throw Ar(new We.FloPayError(y.message??"PayPal authorization failed.","api_error",{code:y.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new We.FloPayError("Unsupported payment redirect state.","api_error")}function Wo(e){if(e instanceof We.FloPayError){let r=Dr(e.message);return r&&r!==e.message?Object.assign(new We.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Dr(t)??t;return new We.FloPayError(n,"api_error")}function Si(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Fr(e.data.session);if(!t&&!n&&!r)throw new We.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 Ws(e,t){return e?e.isPaypal?"paypal":"card":t&&Fr(t)?"card":void 0}async function wi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=t&&t!==e?t:void 0,[l,d]=await Promise.all([(0,Hr.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,Hr.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(m=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",m),null)):Promise.resolve(null)]);if(!l)throw new We.FloPayError("The payment provider did not initialize.","authentication_error");let u=null;return a?u=d:t&&(u=l),{flopay:l,paypalFlopay:u}}var pr=require("@flopay/js"),p=require("@flopay/shared"),Kt=require("@stripe/react-stripe-js"),s=ks(require("react"),1);var Js={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 qn=require("react");function Xs(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(l=>l.startsWith("background")),a={};for(let[l,d]of Object.entries(e))l in n||o&&l.startsWith("background")||(a[l]=d);for(let l of r)a[l]=n[l];return a}var Kc=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 Wc(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return Kc.has(t.charAt(0).toLowerCase()+t.slice(1))}function Hc(e,t){return typeof t=="number"&&t!==0&&!Wc(e)?`${t}px`:String(t).trim()}function Zs(e,t){if(e.style.cssText="",!!t){for(let[n,r]of Object.entries(t))if(!(r==null||r==="")){if(n.startsWith("--")){e.style.setProperty(n,String(r));continue}e.style[n]=Hc(n,r)}}}var Qs=require("react/jsx-runtime"),ki=new WeakSet;function Po({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:l,onReady:d,onError:u,onValidation:m}){let h=(0,qn.useRef)(null),b=(0,qn.useRef)(d),y=(0,qn.useRef)(u),C=(0,qn.useRef)(m);b.current=d,y.current=u,C.current=m;let _=(0,qn.useRef)(o);_.current=o;let ne=(0,qn.useRef)(null),z=a??void 0,ue=(0,qn.useRef)(z);ue.current=z;let k=(0,qn.useRef)(void 0);return(0,qn.useEffect)(()=>{let $=h.current;if(!$)return;let U=!0,se=!1,Se=()=>{!U||se||(se=!0,b.current?.())},Pe=e.on("ready",()=>{Se()}),pe=e.on("error",we=>{y.current?.(we.message??"There was a problem loading the secure card form.")}),ye=e.on("validation",we=>{C.current?.(we.message??null)}),yt=ue.current??(ki.has(e)?null:void 0),He={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},..._.current?{theme:_.current}:{},...yt===void 0?{}:{submitLabel:yt}};return ne.current=_.current??null,k.current=ue.current,ue.current!==void 0&&ki.add(e),e.mount($,He).then(()=>{Se()}).catch(we=>{U&&y.current?.(we instanceof Error?we.message:"Failed to load the secure card form.")}),()=>{U=!1,Pe(),pe(),ye(),e.unmount()}},[e,t,n,r]),Kr(()=>{let $=h.current;$&&Zs($,l)},[l]),(0,qn.useEffect)(()=>{o!==void 0&&(o===null&&ne.current===null||(ne.current=o,e.applyTheme?.(o)))},[e,o]),(0,qn.useEffect)(()=>{z!==k.current&&(k.current=z,z!==void 0&&ki.add(e),e.setSubmitLabel?.(z??null))},[e,z]),(0,Qs.jsx)("div",{ref:h,"data-testid":"flopay-vault-card-fields"})}var tl=/^#([0-9a-f]{6})$/i,Gc=/^#([0-9a-f]{3})$/i,nl=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,rl=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+|1\.0+)\s*\)$/i,Yc=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,Jc=/^(-?\d+(?:\.\d+)?)(?:px)?$/,Xc=/^(-?\d+(?:\.\d+)?)em$/,Zc=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,Qc=/^[a-z][a-z0-9 -]{0,31}$/i,ed=new Set(["none","uppercase","lowercase","capitalize"]);function ol(e){if(typeof e!="string")return null;let t=e.trim(),n=tl.exec(t);if(n){let h=Number.parseInt(n[1],16);return{r:h>>16&255,g:h>>8&255,b:h&255,a:null}}let r=Gc.exec(t);if(r){let[h,b,y]=r[1].split("").map(C=>Number.parseInt(C+C,16));return{r:h,g:b,b:y,a:null}}let o=nl.exec(t),a=o?null:rl.exec(t),l=o??a;if(!l)return null;let d=Number(l[1]),u=Number(l[2]),m=Number(l[3]);return d>255||u>255||m>255?null:{r:d,g:u,b:m,a:a?Number(a[4]):null}}function al({r:e,g:t,b:n,a:r}){return r===null?`#${(1<<24|e<<16|t<<8|n).toString(16).slice(1)}`:`rgba(${e},${t},${n},${r})`}function Ho(e){if(typeof e!="string")return;let t=e.trim();if(tl.test(t)||nl.test(t))return t;let n=rl.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=ol(t);return r?al(r):void 0}function Ta(e,t=.12){let n=ol(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return al({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function Go(e,t){let n=[],r=0,o="";for(let a of e){if(a==="("&&(r+=1),a===")"&&(r-=1),a===t&&r===0){o.trim()&&n.push(o.trim()),o="";continue}o+=a}return o.trim()&&n.push(o.trim()),n}function Gr(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=Jc.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function td(e,t,n){if(typeof e!="string")return;let r=Xc.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function nd(e){let t=Go(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=Go(o," "),l=Ho(a[0]);if(!l)return;let d=r/(t.length-1)*100,u=a[1]===void 0?d:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),m=n[n.length-1]?.position??-1;if(!Number.isFinite(u)||u<0||u>100||u<m)return;n.push({color:l,position:u})}return{type:"linearGradient",angle:0,stops:n}}function rd(e){if(typeof e!="string")return;let t=e.trim(),n=Ho(t);if(n)return{type:"solid",color:n};let r=Yc.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=nd(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function od(e){return e.type==="solid"?{type:"solid",color:Ta(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:Ta(t.color)}))}}function ad(e){let t=!1,n,r=[];for(let u of Go(e," ")){if(u.toLowerCase()==="inset"){t=!0;continue}let m=Ho(u);if(m){n=m;continue}let h=Gr(u,-128,128);if(h===void 0)return;r.push(h)}if(!n||r.length<2||r.length>4)return;let[o,a,l=0,d=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||l>128||Math.abs(d)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:l,spread:d}}function id(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=Go(t,",").map(ad);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function el(e){if(typeof e!="string")return;let t=Go(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>Qc.test(n)).slice(0,4);return t.length>0?t:void 0}function sd(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=Gr(t[0],0,64),r=Gr(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function ld(e){if(e==="bold")return 700;if(e==="normal")return 400;let t=Number(e);return Number.isInteger(t)&&t>=100&&t<=900?t:void 0}function il({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=rd(r.background??r.backgroundColor),l=Ho(o?.colorPrimaryHover),d=l?{type:"solid",color:l}:a&&od(a),u={fontFamilies:el(r.fontFamily)??el(n),fontSize:Gr(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:ld(r.fontWeight)??600,letterSpacing:td(r.letterSpacing,-.1,.5)??.01,lineHeight:Gr(r.lineHeight,.8,2)??1,textTransform:ed.has(String(r.textTransform))?r.textTransform:"uppercase"},m=sd(r.padding),h=id(r.boxShadow),b=Gr(r.borderRadius,0,9999),y=typeof r.backdropFilter=="string"?Gr(Zc.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Ho(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...d?{hoverBackground:d}:{},typography:u,...m?{spacing:m}:{},...h?{shadow:h}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...y===void 0?{}:{backdropBlur:y}}}function Co(e,t=.12){let n=e.trim(),r=/^[0-9a-fA-F]{6}$/.test(n)?`#${n}`:n;return/^#[0-9a-fA-F]{6}$/.test(r)?Ta(r,t):e}function Ii(e){if(typeof e=="number"||typeof e=="string")return e}function Aa({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",d=n==="buttons",u=t.nameInput,m=o(u?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",h=il({appearance:e,buttonsStyles:t,fontFamily:m});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??Co(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(u?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(d?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:m,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Ii(u?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...h?{submitButton:h}:{}}}var c=require("react/jsx-runtime"),vr="flopay_stripe_resume",sl="flopay_wallet_resume",vl="fw1",cd="fw2",Pl=300*1e3,dd=900,ud=25e3,pd=25e3,md=1e4,Ri={},_i={};function Di(e){return`${cd}:${e}`}function xa(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(Di(e)),!0}catch{return!1}}function Ma(e,t){if(typeof window>"u")return null;let n=Di(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>Pl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(xa(e),null):o}catch{return xa(e),null}}function yd(e){if(typeof window>"u")return!1;try{return localStorage.setItem(Di(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function ll(e,t,n){let r=Ma(e,t);return!r||r.clientSecret!==n?!1:xa(e)}function Ei(e,t,n){if(typeof window>"u")return;Ma(e,t)?.clientSecret===n&&xa(e)}function fd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ti(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let r=n?e.status==="succeeded":Do(e.status),o=fd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function cl(e,t,n){let r=null;try{return await Promise.race([Ms(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},md),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function gd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Cl(e){return e instanceof p.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Fa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new pr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Cl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Yo="flopay_paypal_resume",hd=250,dl="Just a moment \u2014 we are finalizing your order. Please press pay again.",bd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Ni(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Da({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new pr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function vd(e){return e instanceof p.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ai(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Sl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=Vr(n),l=a.firstName?a:Vr(r?.name);return Mn({email:(0,p.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Pd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=Sl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,p.isValidEmail)(l.email)?l:a(o,l)}var Cd=`
9
+ `})]})})}var ol=require("@flopay/shared"),gn=require("react");var al=require("react/jsx-runtime");function Jo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=(0,gn.useState)(e instanceof Promise?null:e),[c,p]=(0,gn.useState)(t instanceof Promise||!t?null:t),f=(0,gn.useRef)(null),g=(0,gn.useRef)(null),b=ho(r);(0,gn.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,gn.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,gn.useEffect)(()=>{if(a)return fn(a)?.subscribe?.(b)},[b,a]),(0,gn.useEffect)(()=>{if(!(!c||c===a))return fn(c)?.subscribe?.(b)},[b,a,c]),(0,gn.useEffect)(()=>{if(!a)return;let S=fn(a);return f.current=S?.beginCheckout()??S?.now()??0,S?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{S?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,gn.useEffect)(()=>{let S=!1;return e instanceof Promise?e.then(P=>{S||l(P)},()=>{S||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{S=!0}},[b,e]),(0,gn.useEffect)(()=>{let S=!1;if(!t){p(null);return}return t instanceof Promise?t.then(P=>{S||p(P)},()=>{S||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{S=!0}},[b,t]),(0,gn.useEffect)(()=>{if(!a||g.current===a)return;g.current=a;let S=fn(a);S?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),S?.performance({stage:"checkout_render",durationMs:S.elapsed(f.current??0),durationMode:"machine"})},[b,a]);let T=(0,ol.resolveBillingApiUrl)(n?.billingApiUrl),w=(0,gn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:T,emitInstrument:b}),[a,c,T,b]);return(0,al.jsx)(rr.Provider,{value:w,children:o})}var Da="flopay_recent_completion_";function Po(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Da+e,JSON.stringify(t))}catch{}}function Ti(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Da+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Da+e),!1):!0}catch{return!1}}async function Oa(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}var Xr=require("@flopay/js"),He=require("@flopay/shared");var Zo="card",Jc=1e3,sl=3e5;async function Xc(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function Zc(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Qo(e){return new He.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function xi(e,t){return Object.assign(e,{checkoutMethod:t})}function Fr(e,t){let n=e instanceof He.FloPayError?e:new He.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Xo(e,t){try{return await e()}catch(n){throw Fr(n,t)}}function ll(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 Qc(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Mi(e){if(typeof document>"u"||typeof window>"u")throw new He.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new He.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let b=new AbortController,T=()=>b.abort();e.signal?.aborted?b.abort():e.signal?.addEventListener("abort",T);let w=window.setTimeout(()=>b.abort(),n);try{let S=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:b.signal});if(!S.ok)return{status:"unknown"};let P=await S.json().catch(()=>null);return ed(P)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",T)}},a,l=()=>e.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),c=document.activeElement instanceof HTMLElement?document.activeElement:null,p=document.createElement("div");p.setAttribute("data-flopay-auto-3ds-overlay","1"),p.setAttribute("role","dialog"),p.setAttribute("aria-modal","true"),p.setAttribute("aria-label","Card authentication"),p.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let f=document.createElement("iframe");f.setAttribute("title","Card authentication"),f.setAttribute("allow","payment"),f.tabIndex=0,f.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let b=await new Promise((T,w)=>{let S=!1,P=0,F=0,fe=0,R=!1,H=()=>{window.clearTimeout(P),window.clearInterval(F),window.clearTimeout(fe),window.removeEventListener("message",we),f.removeEventListener("load",ne),e.signal?.removeEventListener("abort",pe)},N=async()=>{if(!(S||R)){R=!0;try{let ge=await l();if(S||!Qc(ge))return;S=!0,H(),T(ge)}finally{R=!1}}},ne=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(fe),fe=window.setTimeout(()=>{N()},250))},pe=()=>{S||(S=!0,H(),w(new He.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},we=ge=>{if(ge.source!==f.contentWindow||g&&ge.origin!==g)return;let be=ge.data;!be||typeof be!="object"||be.source!=="flopay-vault-3ds-return"||S||(S=!0,H(),T(null))};P=window.setTimeout(()=>{S||(S=!0,H(),w(new He.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},sl),e.pollCompletionEndpoint!==!1&&(F=window.setInterval(()=>{N()},t)),f.addEventListener("load",ne),window.addEventListener("message",we),e.signal?.addEventListener("abort",pe),f.src=e.nextActionRedirectUrl,p.appendChild(f),document.body.appendChild(p),f.focus(),e.signal?.aborted&&pe()});return b||await l()}finally{p.parentNode?.removeChild(p),c?.isConnected&&c.focus()}}async function So(e,t){let n=t.nonce??t.session.clientSecret,r=new Xr.PaymentAPI(t.billingApiUrl,{telemetry:!1}),o=new AbortController,a=new AbortController,l=()=>{o.abort(t.signal.reason),a.abort(t.signal.reason)};t.signal.aborted?l():t.signal.addEventListener("abort",l,{once:!0});let c=Mi({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:n,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),p=null,f=()=>(p??(p=r.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:Jc,nonce:n,statusUrl:`${t.billingApiUrl.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,continueAfterActionRequired:!0,timeoutMs:sl,signal:a.signal})),p),g=f(),b;try{let w=await Promise.race([c.then(S=>({kind:"challenge",outcome:S})),g.then(S=>({kind:"status",session:S}))]);if(w.kind==="status")o.abort(),b=w.session;else{if(w.outcome.status==="declined")throw Rr({type:w.outcome.declineReason??"authorization_declined",message:"Card was declined.",gatewayErrorCode:w.outcome.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});b=await f()}}catch(w){throw t.signal.aborted||w instanceof Error&&w.name==="AbortError"?Qo(w):w}finally{t.signal.removeEventListener("abort",l),o.abort(),a.abort()}let T=b.data.session;if(!Nr(T))throw mo(T);return{...xr(T,t.sessionId),checkoutMethod:"card"}}function ed(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"authorized":return{status:"authorized",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Rr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=Lr(o)??o,l=xi(new He.FloPayError(a,"api_error",{code:e?.code??(0,He.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,He.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(l.orderId=e.orderId),l}function Ai(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function La(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function cl(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||La(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of a)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||La(c)))return c;let l=o.gateways;if(l&&typeof l=="object"){let c=l.stripe;if(c&&typeof c=="object"){let p=c,f=[p.stripeClientSecret,p.clientSecret];for(let g of f)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||La(g)))return g}}}}async function td({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=cl(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new Xr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(La(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function wo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let c=e.replace(/\/+$/,""),p=t??n.id,f=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",T=n.customer?.firstName??n.accountData?.firstName??"",w=n.customer?.lastName??n.accountData?.lastName??"",S=n.customer?.country??n.accountData?.country??void 0,P=n.customer?.zip??n.accountData?.zip??void 0,fe=await new Xr.PaymentAPI(c,l===!1?{telemetry:!1}:void 0).processPayment(g,{sessionId:p,nonce:f,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:g,email:b,firstName:T,lastName:w,country:S,zip:P},returnUrl:a??Ai(n)});if(fe.ok){let N=typeof fe.json=="function"?await fe.json().catch(()=>null):null;if((0,He.isAuthorizationOnlySession)(n)||N?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof N?.paymentId=="string"?N.paymentId:n.paymentId,sessionId:typeof N?.sessionId=="string"?N.sessionId:p,authorizationExpiresAt:typeof N?.authorizationExpiresAt=="string"?N.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:$o(o),checkoutMethod:il(o,n)}};let ne=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ne?{paymentIntentId:ne}:{},paymentMethodId:$o(o),checkoutMethod:il(o,n)}}}let R;try{R=await fe.json()}catch(N){throw new He.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:fe.status,cause:N})}if(R?.type==="3ds_required"&&typeof R.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:R.nextActionRedirectUrl};if(R?.type==="paypal_redirect_required"||R?.type==="3ds_required"){let N=cl(R);if(!N)throw new He.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:fe.status});return{type:R.type,threeDSecureToken:N,paymentMethodId:R.paymentMethodId}}if(R?.gatewayErrorCode==="authentication_required"){let N=await td({billingApiUrl:c,sessionId:p,nonce:f,responseJson:R});if(N)return N;throw xi(new He.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let H=new He.FloPayError(R?.message??"Payment failed. Please try again.","api_error",{code:R?.code??R?.gatewayErrorCode,declineCode:R?.declineCode??R?.gatewayDeclineReason,statusCode:fe.status});throw Object.assign(H,{telemetryOutcome:(0,He.classifyPaymentRejection)(fe.status,R)})}async function Na(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:c,telemetry:p,signal:f}){let g=t?.getRawProvider();if(!g)throw Fr(new He.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw xi(new He.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,He.isSetupIntentClientSecret)(e.threeDSecureToken),T=null,w=e.paymentMethodId,S=await Xo(()=>Xc(g,e.threeDSecureToken,b),"card");if(S){if(S.error)throw Fr(new He.FloPayError(S.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:S.error.code}),"card");let F=S.intent;!w&&F?.payment_method&&(typeof F.payment_method=="string"?w=F.payment_method:"id"in F.payment_method&&(w=F.payment_method.id??void 0))}let P=w?await Xo(()=>Zc(g,e.threeDSecureToken,{payment_method:w,return_url:c??Ai(l)??window.location.href},b),"card"):null;if(P){if(P.error)throw Fr(new He.FloPayError(P.error.message??"3DS authentication failed.","api_error",{code:P.error.code}),"card");T=P.intent}else{let F=await Xo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(F.error)throw Fr(new He.FloPayError(F.error.message??"3DS authentication failed.","api_error",{code:F.error.code}),"card");T=(b?F.setupIntent:F.paymentIntent)??null}if(T&&(T.status==="requires_capture"||T.status==="succeeded"||T.status==="processing")){let F=await wo({billingApiUrl:o,sessionId:a,session:l,telemetry:p,tokenizedData:{id:T.id,type:"card",threeDSecureActionResultTokenId:T.id},returnUrl:c});return F.type==="success"?{...F.result,paymentIntentId:F.result.paymentIntentId??T.id,paymentMethodId:F.result.paymentMethodId??w}:F.type==="next_action_required"?So(F,{billingApiUrl:o,sessionId:a??l.id,session:l,signal:f}):Na(F,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:c,telemetry:p,signal:f})}throw Fr(new He.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw Fr(new He.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await Xo(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(w)throw Fr(new He.FloPayError(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:T}=await Xo(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Ai(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(T)throw Fr(new He.FloPayError(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new He.FloPayError("Unsupported payment redirect state.","api_error")}function ea(e){if(e instanceof He.FloPayError){let r=Lr(e.message);return r&&r!==e.message?Object.assign(new He.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Lr(t)??t;return new He.FloPayError(n,"api_error")}function Bi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Or(e.data.session);if(!t&&!n&&!r)throw new He.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&&Or(t)?"card":void 0}async function Fi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=t&&t!==e?t:void 0,[l,c]=await Promise.all([(0,Xr.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,Xr.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(f=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",f),null)):Promise.resolve(null)]);if(!l)throw new He.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return a?p=c:t&&(p=l),{flopay:l,paypalFlopay:p}}var yr=require("@flopay/js"),m=require("@flopay/shared"),jt=require("@stripe/react-stripe-js"),i=Ds(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 Di(e,t){if(e)return{error:n=>e.error(ko(t,n)),log:n=>e.log(ko(t,n)),performance:n=>e.performance(ko(t,n)),terminal:n=>e.terminal(ko(t,n)),now:()=>e.now(),elapsed:n=>e.elapsed(n),setCheckoutContext:n=>e.setCheckoutContext(n),beginCheckout:n=>e.beginCheckout(n),disable:()=>e.disable(),subscribe:n=>e.subscribe(n),flush:()=>e.flush(),destroy:()=>e.destroy()}}var dl={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 Vn=require("react");function ul(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(l=>l.startsWith("background")),a={};for(let[l,c]of Object.entries(e))l in n||o&&l.startsWith("background")||(a[l]=c);for(let l of r)a[l]=n[l];return a}var nd=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 rd(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return nd.has(t.charAt(0).toLowerCase()+t.slice(1))}function od(e,t){return typeof t=="number"&&t!==0&&!rd(e)?`${t}px`:String(t).trim()}function pl(e,t){if(e.style.cssText="",!!t){for(let[n,r]of Object.entries(t))if(!(r==null||r==="")){if(n.startsWith("--")){e.style.setProperty(n,String(r));continue}e.style[n]=od(n,r)}}}var ml=require("react/jsx-runtime"),Oi=new WeakSet;function Io({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:l,onReady:c,onError:p,onValidation:f}){let g=(0,Vn.useRef)(null),b=(0,Vn.useRef)(c),T=(0,Vn.useRef)(p),w=(0,Vn.useRef)(f);b.current=c,T.current=p,w.current=f;let S=(0,Vn.useRef)(o);S.current=o;let P=(0,Vn.useRef)(null),F=a??void 0,fe=(0,Vn.useRef)(F);fe.current=F;let R=(0,Vn.useRef)(void 0);return(0,Vn.useEffect)(()=>{let H=g.current;if(!H)return;let N=!0,ne=!1,pe=()=>{!N||ne||(ne=!0,b.current?.())},we=e.on("ready",()=>{pe()}),ge=e.on("error",ve=>{T.current?.(ve.message??"There was a problem loading the secure card form.")}),be=e.on("validation",ve=>{w.current?.(ve.message??null)}),lt=fe.current??(Oi.has(e)?null:void 0),Ue={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...S.current?{theme:S.current}:{},...lt===void 0?{}:{submitLabel:lt}};return P.current=S.current??null,R.current=fe.current,fe.current!==void 0&&Oi.add(e),e.mount(H,Ue).then(()=>{pe()}).catch(ve=>{N&&T.current?.(ve instanceof Error?ve.message:"Failed to load the secure card form.")}),()=>{N=!1,we(),ge(),be(),e.unmount()}},[e,t,n,r]),Yr(()=>{let H=g.current;H&&pl(H,l)},[l]),(0,Vn.useEffect)(()=>{o!==void 0&&(o===null&&P.current===null||(P.current=o,e.applyTheme?.(o)))},[e,o]),(0,Vn.useEffect)(()=>{F!==R.current&&(R.current=F,F!==void 0&&Oi.add(e),e.setSubmitLabel?.(F??null))},[e,F]),(0,ml.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields"})}var fl=/^#([0-9a-f]{6})$/i,ad=/^#([0-9a-f]{3})$/i,gl=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,hl=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+|1\.0+)\s*\)$/i,id=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,sd=/^(-?\d+(?:\.\d+)?)(?:px)?$/,ld=/^(-?\d+(?:\.\d+)?)em$/,cd=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,dd=/^[a-z][a-z0-9 -]{0,31}$/i,ud=new Set(["none","uppercase","lowercase","capitalize"]);function bl(e){if(typeof e!="string")return null;let t=e.trim(),n=fl.exec(t);if(n){let g=Number.parseInt(n[1],16);return{r:g>>16&255,g:g>>8&255,b:g&255,a:null}}let r=ad.exec(t);if(r){let[g,b,T]=r[1].split("").map(w=>Number.parseInt(w+w,16));return{r:g,g:b,b:T,a:null}}let o=gl.exec(t),a=o?null:hl.exec(t),l=o??a;if(!l)return null;let c=Number(l[1]),p=Number(l[2]),f=Number(l[3]);return c>255||p>255||f>255?null:{r:c,g:p,b:f,a:a?Number(a[4]):null}}function vl({r:e,g:t,b:n,a:r}){return r===null?`#${(1<<24|e<<16|t<<8|n).toString(16).slice(1)}`:`rgba(${e},${t},${n},${r})`}function ta(e){if(typeof e!="string")return;let t=e.trim();if(fl.test(t)||gl.test(t))return t;let n=hl.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=bl(t);return r?vl(r):void 0}function za(e,t=.12){let n=bl(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return vl({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function na(e,t){let n=[],r=0,o="";for(let a of e){if(a==="("&&(r+=1),a===")"&&(r-=1),a===t&&r===0){o.trim()&&n.push(o.trim()),o="";continue}o+=a}return o.trim()&&n.push(o.trim()),n}function Zr(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=sd.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function pd(e,t,n){if(typeof e!="string")return;let r=ld.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function md(e){let t=na(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=na(o," "),l=ta(a[0]);if(!l)return;let c=r/(t.length-1)*100,p=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),f=n[n.length-1]?.position??-1;if(!Number.isFinite(p)||p<0||p>100||p<f)return;n.push({color:l,position:p})}return{type:"linearGradient",angle:0,stops:n}}function yd(e){if(typeof e!="string")return;let t=e.trim(),n=ta(t);if(n)return{type:"solid",color:n};let r=id.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=md(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function fd(e){return e.type==="solid"?{type:"solid",color:za(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:za(t.color)}))}}function gd(e){let t=!1,n,r=[];for(let p of na(e," ")){if(p.toLowerCase()==="inset"){t=!0;continue}let f=ta(p);if(f){n=f;continue}let g=Zr(p,-128,128);if(g===void 0)return;r.push(g)}if(!n||r.length<2||r.length>4)return;let[o,a,l=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||l>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:l,spread:c}}function hd(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=na(t,",").map(gd);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function yl(e){if(typeof e!="string")return;let t=na(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>dd.test(n)).slice(0,4);return t.length>0?t:void 0}function bd(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=Zr(t[0],0,64),r=Zr(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function vd(e){if(e==="bold")return 700;if(e==="normal")return 400;let t=Number(e);return Number.isInteger(t)&&t>=100&&t<=900?t:void 0}function Cl({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=yd(r.background??r.backgroundColor),l=ta(o?.colorPrimaryHover),c=l?{type:"solid",color:l}:a&&fd(a),p={fontFamilies:yl(r.fontFamily)??yl(n),fontSize:Zr(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:vd(r.fontWeight)??600,letterSpacing:pd(r.letterSpacing,-.1,.5)??.01,lineHeight:Zr(r.lineHeight,.8,2)??1,textTransform:ud.has(String(r.textTransform))?r.textTransform:"uppercase"},f=bd(r.padding),g=hd(r.boxShadow),b=Zr(r.borderRadius,0,9999),T=typeof r.backdropFilter=="string"?Zr(cd.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:ta(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:p,...f?{spacing:f}:{},...g?{shadow:g}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...T===void 0?{}:{backdropBlur:T}}}function Ro(e,t=.12){let n=e.trim(),r=/^[0-9a-fA-F]{6}$/.test(n)?`#${n}`:n;return/^#[0-9a-fA-F]{6}$/.test(r)?za(r,t):e}function Li(e){if(typeof e=="number"||typeof e=="string")return e}function Ua({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",p=t.nameInput,f=o(p?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",g=Cl({appearance:e,buttonsStyles:t,fontFamily:f});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??Ro(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(p?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(c?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:f,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Li(p?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...g?{submitButton:g}:{}}}var d=require("react/jsx-runtime"),_r="flopay_stripe_resume",Pl="flopay_wallet_resume",Bl="fw1",Cd="fw2",Fl=300*1e3,Pd=900,Sd=25e3,wd=25e3,kd=1e4,qa={},Ni={};function Ki(e){return`${Cd}:${e}`}function $a(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(Ki(e)),!0}catch{return!1}}function ja(e,t){if(typeof window>"u")return null;let n=Ki(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>Fl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?($a(e),null):o}catch{return $a(e),null}}function Id(e){if(typeof window>"u")return!1;try{return localStorage.setItem(Ki(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function Sl(e,t,n){let r=ja(e,t);return!r||r.clientSecret!==n?!1:$a(e)}function zi(e,t,n){if(typeof window>"u")return;ja(e,t)?.clientSecret===n&&$a(e)}function Rd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ui(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let r=n?e.status==="succeeded":qo(e.status),o=Rd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function wl(e,t,n){let r=null;try{return await Promise.race([js(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},kd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function _d(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Dl(e){return e instanceof m.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Ha(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new yr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Dl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ra="flopay_paypal_resume",Ed=250,kl="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 Wi(e,t,n,r){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...r?{terminalReason:r}:{}})}async function Ka({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new yr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Ad(e){return e instanceof m.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function qi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Ol({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=Wr(n),l=a.firstName?a:Wr(r?.name);return Dn({email:(0,m.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function xd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=Ol({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,m.isValidEmail)(l.email)?l:a(o,l)}var Md=`
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 @@ ${ft.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
- `,Ba=44,Jo=180,ul=`flopay-card-enter ${Jo}ms cubic-bezier(0, 0, 0.2, 1) both`,pl=`flopay-card-exit ${Jo}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Sd=`flopay-buttons-enter ${Jo}ms cubic-bezier(0, 0, 0.2, 1) both`,wd=`flopay-buttons-exit ${Jo}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function kd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Li(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Id={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Rd(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 Mi={width:"100%",minHeight:Ba,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 _d(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ml(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Bi(e){return e==="paypal"?"PayPal":(0,p.getStripeMethodDisplayName)(e)}function Ed(e,t){let n=`We couldn't open ${Bi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Td(e){let t=(0,p.getPostalCodeExample)(e);return`Enter a valid ${(0,p.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Ad(e,t,n){let r=(0,p.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,l=a&&!o,d=a&&!!o&&!(0,p.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:d}}function xd(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,p.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function yl(e,t){return t instanceof p.FloPayError?t:new p.FloPayError(t instanceof Error?t.message:`${_d(e)} before-click hook failed.`,"validation_error")}function xi(){return(0,c.jsx)("style",{children:Cd})}function Md(e){return typeof e=="number"?`${e}px`:e}function wl(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function kl({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,c.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,c.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,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,c.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:r})]})}function fl(e){return e!=="unavailable"&&e!=="load_error"}function Na(e){return(0,c.jsx)(Fd,{...e})}function gl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:d,onDecline:u,onTechnicalFailure:m,runBeforeButtonClick:h,billingName:b,onBuyerIdentityReady:y,onLoadStateChange:C,placeholderBorderRadius:_}){let ne=Tr(),{emitInstrument:z}=(0,s.useContext)(Qn),ue=(0,Kt.useStripe)(),k=(0,Kt.useElements)(),[$,U]=(0,s.useState)("loading");(0,s.useEffect)(()=>{C?.($)},[$,C]);let[se,Se]=(0,s.useState)(!1),Pe=!(0,p.isValidEmail)(n?.trim())||!b?.trim(),{request:pe,collect:ye,finish:yt}=co(),He=(0,s.useRef)(!1),we=(0,s.useRef)(null),Me=(0,s.useRef)(null),[fe,Re]=(0,s.useState)(0),[Ge,oe]=(0,s.useState)(!1),_e=(0,s.useRef)(!1),ge=(0,s.useRef)(new Map),{startAttempt:nt,finishAttempt:rt,invalidateAttempt:M,isAttemptInvalidated:V,isAttemptCurrent:ie}=zo((he,le,H)=>{m?.(he,le,{...H,popupBlocked:H?.popupBlocked??Er(le)}),oe(!0),Re(Le=>Le+1)});(0,s.useEffect)(()=>{Ge&&Me.current?.focus()},[Ge,fe]);let ae=(0,s.useCallback)(()=>{Re(he=>he+1)},[]),Ye=(0,s.useCallback)((he,le,H)=>{M(H),m?.("paypal",he,{code:le,popupBlocked:Er(he)}),oe(!0),ae()},[M,m,ae]),Ce=(0,s.useCallback)(()=>{window.setTimeout(()=>{(we.current?.querySelector("iframe")??we.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{_e.current&&(_e.current=!1,Ce())},[Ce,fe]);let N=(0,s.useCallback)(()=>{oe(!1),a?.(null),Ce()},[Ce,a]);(0,s.useEffect)(()=>{if(!ue||He.current)return;let he=new URLSearchParams(window.location.search),le=he.get("payment_intent"),H=he.get("payment_intent_client_secret"),Le=he.get("redirect_status");if(!le||!H)return;He.current=!0;let Oe;try{let je=localStorage.getItem(Yo);if(je){let Be=JSON.parse(je);Be.clientSecret===H&&(Oe={...Be.accountPatch?{accountPatch:Be.accountPatch}:{},...Be.sessionId?{sessionId:Be.sessionId}:{},...Be.nonce?{nonce:Be.nonce}:{}})}}catch{}try{localStorage.removeItem(Yo)}catch{}let ze=new URL(window.location.href);ze.searchParams.delete("payment_intent"),ze.searchParams.delete("payment_intent_client_secret"),ze.searchParams.delete("redirect_status"),window.history.replaceState({},"",ze.toString()),(async()=>{try{if(Se(!0),Le==="failed"){let Ne="PayPal payment was declined. Please try again.";a?.(Ne),u?.(nn("paypal",Ne));return}let{paymentIntent:je,error:Be}=await ue.retrievePaymentIntent(H);if(Be){a?.(Be.message??"Failed to retrieve PayPal payment status.");return}if(je&&(je.status==="requires_capture"||je.status==="succeeded")){let Ne=typeof je.payment_method=="string"?je.payment_method:je.payment_method?.id;o({id:Ne??je.id,type:"card",threeDSecureActionResultTokenId:je.id,isPaypal:!0},Oe)}else{let Ne="PayPal payment was not completed. Please try again.";a?.(Ne),u?.(nn("paypal",Ne))}}catch(je){a?.(je instanceof Error?je.message:"Failed to complete PayPal payment.")}finally{Se(!1)}})()},[ue,o,a,u]);let ut=(0,s.useCallback)(async he=>{if(l||se){he.reject();return}let le=h?await h("paypal"):{proceed:!0};if(!le.proceed){ge.current.delete(fe),he.reject();return}let H=nt("paypal");ge.current.set(fe,{generation:H,accountPatch:le.accountPatch,sessionId:le.sessionId,nonce:le.nonce}),oe(!1),d?.("paypal"),he.resolve()},[l,d,h,nt,se,fe]),ot=(0,s.useCallback)(async he=>{if(!ue||!k)return;let le=ge.current.get(fe);if(le&&!ie(le.generation)){ge.current.delete(fe);return}if(!le&&V()||le&&!rt(le.generation))return;le||rt();let H=le??null;if(ge.current.delete(fe),!H&&h){let Ne=await h("paypal");if(!Ne.proceed){he.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}H={accountPatch:Ne.accountPatch,sessionId:Ne.sessionId,nonce:Ne.nonce}}let Le=H?.sessionId??e,Oe=H?.nonce??t,ze=await Pd({event:he,prepared:H,email:n,billingName:b,methodLabel:"PayPal",collect:ye});if(!ze){he.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let je=ze.email,Be={...H?.accountPatch,...Mn(ze,!0)};try{if(Se(!0),a?.(null),!Le||!(0,p.isValidEmail)(je))throw new Error("Missing sessionId or email for PayPal payment");await y?.(ze);let Ne=ue.createPaymentMethod,{error:ce,paymentMethod:dn}=await Ne({type:"paypal"});if(ce){Ye(ce,"stripe_paypal_create_payment_method_failed",le?.generation),he.paymentFailed({reason:"fail"});return}let Jt=await Fa(r,z,Le,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:dn?.id??null,intentKind:"payment"});if(Jt.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ee=Jt.clientSecret,at={return_url:window.location.href};if(dn?.id&&(at.payment_method=dn.id),typeof window<"u")try{localStorage.setItem(Yo,JSON.stringify({clientSecret:ee,sessionId:Le,nonce:Oe,accountPatch:Be}))}catch{}let{error:Z,paymentIntent:Q}=await ue.confirmPayment({clientSecret:ee,confirmParams:at,redirect:"if_required"});if(Z){if(typeof window<"u")try{localStorage.removeItem(Yo)}catch{}if(Lo(Z)){let g=Z.message??"Your payment was declined.";a?.(g),u?.(nn("paypal",g,{code:_r(Z),declineCode:po(Z)})),await Da({billingApiUrl:r,sessionId:Le,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:_r(Z)??"provider_declined"}})}else Ye(Z,"stripe_paypal_confirm_failed",le?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Yo)}catch{}let be=typeof Q?.payment_method=="string"?Q.payment_method:Q?.payment_method?.id;o({id:be??Q?.id,type:"card",threeDSecureActionResultTokenId:Q?.id,isPaypal:!0},{accountPatch:Be,paymentMethodCategory:"paypal",sessionId:Le,nonce:Oe});return}catch(Ne){Ye(Ne,"stripe_paypal_failed",le?.generation)}finally{Se(!1)}},[ue,k,e,t,n,b,ye,y,r,z,o,a,u,h,Ye,rt,ie,V,fe]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(kl,{state:$,placeholderTestId:"flopay-paypal-placeholder",borderRadius:_,children:(0,c.jsxs)("div",{ref:we,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ge&&(0,c.jsx)("button",{ref:Me,type:"button","data-testid":"flopay-paypal-retry-button",onClick:N,style:Mi,children:"Try PayPal again"}),pe&&(0,c.jsx)(uo,{identity:pe.identity,methodLabel:pe.methodLabel,onComplete:yt,onCancel:()=>yt(null)},pe.id),(0,c.jsx)("div",{style:{display:pe?"none":void 0},children:(0,c.jsx)(Kt.ExpressCheckoutElement,{onReady:he=>U(wl(he,["paypal"])),onLoadError:()=>{U("load_error"),Ni(en(ne),"paypal","paypal")},onClick:ut,onConfirm:ot,onCancel:()=>{let he=ge.current.get(fe);ge.current.delete(fe),en(ne)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),M(he?.generation),oe(!1),_e.current=!0,ae()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Pe,emailRequired:Pe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},fe)})]})}),se&&(0,c.jsx)(tr,{status:"processing"})]})}function hl({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:d,onButtonClick:u,onDecline:m,onTechnicalFailure:h,runBeforeButtonClick:b,billingName:y,onBuyerIdentityReady:C,onLoadStateChange:_,placeholderBorderRadius:ne}){let z=Tr(),{emitInstrument:ue}=(0,s.useContext)(Qn),k=(0,Kt.useStripe)(),$=(0,Kt.useElements)(),[U,se]=(0,s.useState)("loading");(0,s.useEffect)(()=>{_?.(U)},[U,_]);let[Se,Pe]=(0,s.useState)(!1),pe=(0,s.useRef)(!(0,p.isValidEmail)(n?.trim())||!y?.trim()).current,{request:ye,collect:yt,finish:He}=co(),we=(0,s.useRef)(null),Me=(0,s.useRef)(null),[fe,Re]=(0,s.useState)(0),[Ge,oe]=(0,s.useState)(!1),[_e,ge]=(0,s.useState)(()=>Ma(e,t)?"blocked":"idle"),[nt,rt]=(0,s.useState)("google_pay"),M=(0,s.useRef)(null),V=(0,s.useRef)(!0),ie=(0,s.useRef)(!1),ae=(0,s.useRef)("google_pay"),Ye=(0,s.useRef)("google_pay"),Ce=(0,s.useRef)(null),N=(0,s.useRef)(null),ut=(0,s.useRef)(new Set);(0,s.useEffect)(()=>(V.current=!0,()=>{V.current=!1;for(let Z of ut.current)window.clearTimeout(Z);ut.current.clear()}),[]);let ot=(0,s.useRef)(new Map),{startAttempt:he,finishAttempt:le,invalidateAttempt:H,isAttemptInvalidated:Le,isAttemptCurrent:Oe,generationRef:ze}=zo((Z,Q,be)=>{h?.(Z,Q,{...be,popupBlocked:be?.popupBlocked??Er(Q)}),rt(Z),oe(!0),Re(g=>g+1)});(0,s.useEffect)(()=>{Ge&&Me.current?.focus()},[Ge,fe]);let je=(0,s.useCallback)(()=>{Re(Z=>Z+1)},[]),Be=(0,s.useCallback)((Z,Q,be,g)=>{H(g),h?.(Z,Q,{code:be,popupBlocked:Er(Q)}),rt(Z),oe(!0),je()},[H,h,je]),Ne=(0,s.useCallback)(()=>{window.setTimeout(()=>{(we.current?.querySelector("iframe")??we.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ie.current&&(ie.current=!1,Ne())},[Ne,fe]);let ce=(0,s.useCallback)(()=>{oe(!1),d?.(null),Ne()},[Ne,d]),dn=(0,s.useCallback)(()=>{M.current?.()},[]);(0,s.useEffect)(()=>{let Z=Ma(e,t);if(!Z)return;let Q=!1,be=!1,g=async()=>{if(!be){be=!0,Q||ge("checking");try{let q=await cl(k,Z.clientSecret,ut.current);if(Q)return;let Fe=Ti(q,Z.providerObjectId,(0,p.isSetupIntentClientSecret)(Z.clientSecret));if(Fe.kind==="confirmed"){if(!ll(e,t,Z.clientSecret))return;M.current=null,ge("idle"),l({id:Fe.paymentMethodId,type:"card",threeDSecureActionResultTokenId:Fe.intentId},{...Z.accountPatch?{accountPatch:Z.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(Fe.kind==="terminal"){Ei(e,t,Z.clientSecret),M.current=null,ge("idle"),rt(Z.paymentMethodType),oe(!0),je();return}ge("blocked")}catch{Q||ge("blocked")}finally{be=!1}}};return M.current=g,ge("blocked"),()=>{Q=!0,M.current===g&&(M.current=null)}},[t,l,je,e,k]);let Jt=(0,s.useCallback)(async Z=>{let Q=!1,be=Ke=>{Q||(Q=!0,Z.paymentFailed({reason:"fail",...Ke?{message:Ke}:{}}))};if(!k||!$){be();return}let g=ot.current.get(fe);if(g&&!Oe(g.generation)){ot.current.delete(fe),be();return}if(!g&&Le()){be();return}if(g&&!le(g.generation)){be();return}g||le();let q=Z.expressPaymentType??g?.method??ae.current,Fe=g??null,Je=ml(q),De;q==="apple_pay"?De="apple_pay":q==="google_pay"&&(De="google_pay");let $t=g?.generation??ze.current,W=en(z),St=W?.now()??globalThis.performance?.now()??Date.now(),Tt=new AbortController,ft=!1,un=!1,G=null,Lt=e,vn="processing",pn="other",mn="provider_runtime",In,Bn=new Promise((Ke,Qe)=>{In=Qe}),Fn=window.setTimeout(()=>{ft=!0,Tt.abort(),In(Ri)},ud),Xt=async(Ke,Qe,wt)=>{vn=Ke,pn=Qe,mn=Qe==="intent_create"||Qe==="session_claim"?"transport_error":"provider_runtime";let rn=W?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([wt,Bn])}finally{let kt=W?.now()??globalThis.performance?.now()??Date.now();W?.performance({stage:Ke,durationMs:Math.max(0,kt-rn),durationMode:"machine",requestCategory:Qe,paymentMethodCategory:"wallet",provider:"stripe",...ft?{statusClass:"timeout"}:{}})}};try{if(Pe(!0),d?.(null),!Fe&&b){let ve=await Xt("processing","other",b(Je));if(!ve.proceed){be();return}Fe={accountPatch:ve.accountPatch,sessionId:ve.sessionId,nonce:ve.nonce}}let Ke=Fe?.sessionId??e;Lt=Ke;let Qe=Fe?.nonce??t,wt=Ce.current??Fe?.accountPatch,rn=Sl({event:Z,fallbackEmail:wt?.email??n,fallbackName:[wt?.firstName,wt?.lastName].join(" ").trim()||y});if(!(0,p.isValidEmail)(rn.email)){be("Buyer details are required."),yt(Bi(q),rn).then(ve=>{ve&&(Ce.current=ve)});return}Ce.current=null;let kt={...Fe?.accountPatch,...Mn(rn,!0)};await Xt("processing","session_claim",Promise.resolve(C?.(rn)));let{error:Vn}=await Xt("tokenization","provider_sdk",$.submit());if(Vn){be(),Be(q,Vn,"stripe_wallet_submit_failed",g?.generation);return}if(!Ke)throw new Error("Missing sessionId or email for payment.");let gt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:q,paymentMethodId:null,intentKind:o},At=JSON.stringify({sessionId:Ke,nonce:Qe??"",request:gt}),Ot=N.current,yn=Ot?.retryIdentity===At?Ot.authorizationAttemptId:(0,p.randomUuidV4)();N.current={authorizationAttemptId:yn,retryIdentity:At};let zt=await Xt("processing","intent_create",Fa(r,ue,Ke,Qe??"",{...gt,authorizationAttemptId:yn},{signal:Tt.signal}));if(zt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let xt=zt.clientSecret,Pn=yd({createdAt:Date.now(),sessionId:Ke,...Qe?{nonce:Qe}:{},clientSecret:xt,providerObjectId:zt.providerObjectId,paymentMethodType:q,accountPatch:kt});window.clearTimeout(Fn),un=!0,W?.performance({stage:"callback",durationMs:Math.max(0,(W?.now()??globalThis.performance?.now()??Date.now())-St),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Cn=W?.now()??globalThis.performance?.now()??Date.now(),It={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...De?{walletType:De}:{},attempt:$t},de=!1,on=null;W?.log({name:"payment.provider_confirmation.started",...It}),G=window.setTimeout(()=>{G!==null&&ut.current.delete(G),de=!0;let ve=W?.now()??globalThis.performance?.now()??Date.now();W?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...It,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ve-Cn),statusClass:"timeout",failureCategory:"provider_runtime"}),W?.flush?.().catch(()=>{}),on?.()},pd),ut.current.add(G);let jn=ve=>{G!==null&&(window.clearTimeout(G),ut.current.delete(G),G=null);let O=W?.now()??globalThis.performance?.now()??Date.now(),Ve=Math.max(0,O-Cn),K=ve;return de&&(ve==="resolved"?K="resolved_late":ve==="returned_error"?K="returned_error_late":K="rejected_late"),W?.log({name:"payment.provider_confirmation.returned",...It,operationOutcome:K}),W?.performance({...It,durationMs:Ve,durationMode:"buyer",operationOutcome:K}),{durationMs:Ve,operationOutcome:K}},Wt=!1,Vt=!1,an=ve=>{if(!ve||typeof ve!="object")return null;let O=ve;if(O.error)return null;let Ve=O.setupIntent??O.paymentIntent,K=Ti(Ve??null,void 0,!!O.setupIntent);return K.kind==="confirmed"?K:null},rr=ve=>{if(Wt||g&&ze.current!==g.generation)return;let O=an(ve);if(!O)return;if(Pn&&!ll(Ke,Qe,xt)){Wt=!0;return}let{intentId:Ve,paymentMethodId:K}=O;Wt=!0,Vt=!0,N.current=null,M.current=null,V.current&&(ge("idle"),Pe(!1));let Rt=`${vl}:${Ke}`;if(typeof window<"u")try{localStorage.setItem(Rt,JSON.stringify({createdAt:Date.now(),sessionId:Ke,nonce:Qe,accountPatch:kt,paymentMethodId:K,providerIntentId:Ve,paymentMethodType:q}))}catch{}try{l({id:K,type:"card",threeDSecureActionResultTokenId:Ve},{accountPatch:kt,paymentMethodCategory:"wallet",sessionId:Ke,nonce:Qe})}finally{if(typeof window<"u")try{localStorage.removeItem(Rt)}catch{}}},Dn=!1;on=async()=>{if(!(Dn||Wt||Vt)){Dn=!0,V.current&&ge("checking");try{let ve=await cl(k,xt,ut.current);if(Wt||Vt)return;let O=(0,p.isSetupIntentClientSecret)(xt),Ve=Ti(ve,zt.providerObjectId,O);if(Ve.kind==="confirmed"){rr(O?{setupIntent:ve}:{paymentIntent:ve});return}if(Ve.kind==="terminal"){if(Vt=!0,Ei(Ke,Qe,xt),N.current=null,M.current=null,!V.current)return;ge("idle"),be(),Be(q,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",g?.generation);return}V.current&&!Vt&&(ge("blocked"),Pe(!1))}catch{V.current&&!Vt&&(ge("blocked"),Pe(!1))}finally{Dn=!1}}},M.current=on;let Ht,$e;try{let ve=await((0,p.isSetupIntentClientSecret)(xt)?k.confirmSetup({elements:$,clientSecret:xt,redirect:"if_required"}):k.confirmPayment({elements:$,clientSecret:xt,redirect:"if_required"}));if(!ve||typeof ve!="object"||(Ht=ve,!Ht.error&&!an(Ht)))throw _i;$e=jn(Ht.error?"returned_error":"resolved")}catch(ve){let O=ve===_i,Ve=jn(O?"returned_error":"rejected");if(W?.error({...O?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:di(ve),...It,operationOutcome:Ve.operationOutcome,durationMs:Ve.durationMs,statusClass:"unknown"}),!V.current||Wt)return;await on?.();return}let fn=Ht.error;if(fn){if(!V.current||Wt)return;if(Lo(fn)){Vt=!0,Ei(Ke,Qe,xt),N.current=null,M.current=null,ge("idle");let ve=fn.message??"Your payment was declined.";be(ve),d?.(ve),m?.(nn(Je,ve,{code:_r(fn),declineCode:po(fn)})),Da({billingApiUrl:r,sessionId:Ke,nonce:Qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:q,providerDeclineReason:_r(fn)??"provider_declined",...zt.intentKind==="payment"&&zt.providerObjectId.startsWith("pi_")?{providerIntentId:zt.providerObjectId}:{}}})}else W?.error({...di(fn),...It,operationOutcome:$e.operationOutcome,durationMs:$e.durationMs,statusClass:"unknown"}),await on?.();return}if(rr(Ht),!Wt)throw new Error("Invalid provider returned for APM intent")}catch(Ke){if(Ke===Ri){let Qe=W?.now()??globalThis.performance?.now()??Date.now();W?.error({errorCode:gd(pn),stage:vn,requestCategory:pn,paymentMethodCategory:"wallet",provider:"stripe",...De?{walletType:De}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Lt,durationMs:Math.max(0,Qe-St),statusClass:"timeout",failureCategory:mn,attempt:$t}),W?.flush?.().catch(()=>{})}be(),Be(q,Ke,Ke===Ri?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",g?.generation)}finally{if(window.clearTimeout(Fn),G!==null&&(window.clearTimeout(G),ut.current.delete(G)),!un){let Ke=W?.now()??globalThis.performance?.now()??Date.now();W?.performance({stage:"callback",durationMs:Math.max(0,Ke-St),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...ft?{statusClass:"timeout"}:{}})}V.current&&Pe(!1)}},[k,$,e,t,n,y,yt,C,r,ue,o,l,d,m,b,Be,le,Oe,Le,ze,z,fe]),ee=(0,s.useMemo)(()=>{let Z=["applePay","googlePay","paypal","link","amazonPay","klarna"],Q=new Set(["applePay","googlePay"]),be=new Set(a.map(p.stripeExpressMethodToOptionKey)),g={};for(let q of Z)be.has(q)?g[q]=Q.has(q)?"always":"auto":g[q]="never";return g},[a]),at=(0,s.useMemo)(()=>a.map(p.stripeExpressMethodToOptionKey),[a]);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(kl,{state:U,placeholderTestId:"flopay-wallet-placeholder",borderRadius:ne,children:(0,c.jsxs)("div",{ref:we,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Ge&&(0,c.jsxs)("button",{ref:Me,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ce,style:Mi,children:["Try ",Bi(nt)," again"]}),_e!=="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:dn,disabled:_e==="checking",style:Mi,children:_e==="checking"?"Checking payment status\u2026":"Check payment status"})]}),ye&&(0,c.jsx)(uo,{identity:ye.identity,methodLabel:ye.methodLabel,onComplete:He,onCancel:()=>He(null)},ye.id),_e==="idle"&&(0,c.jsx)("div",{style:{display:ye?"none":void 0},children:(0,c.jsx)(Kt.ExpressCheckoutElement,{onReady:Z=>{se(wl(Z,at))},onLoadError:Z=>{se("load_error"),Ni(en(z),"stripe","wallet")},onClick:async Z=>{ae.current=Z.expressPaymentType,Ye.current=ml(Z.expressPaymentType);let Q=!0,be=window.setTimeout(()=>{Q=!1,Z.reject()},dd),g=b?await b(Ye.current):{proceed:!0};if(window.clearTimeout(be),!Q)return;if(!g.proceed){ot.current.delete(fe),Z.reject();return}let q=he(Z.expressPaymentType);ot.current.set(fe,{generation:q,method:Z.expressPaymentType,accountPatch:g.accountPatch,sessionId:g.sessionId,nonce:g.nonce}),oe(!1),u?.(Ye.current),Z.resolve()},onConfirm:Jt,onCancel:()=>{let Z=ot.current.get(fe);ot.current.delete(fe),en(z)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),H(Z?.generation),N.current=null,oe(!1),ie.current=!0,je()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ee,emailRequired:pe,billingAddressRequired:pe,layout:{maxColumns:1,overflow:"never"}}},fe)})]})}),Se&&(0,c.jsx)(tr,{status:"processing"})]})}function Il(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function Bd({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:d,borderColor:u,textColor:m,borderRadius:h,fontFamily:b}){let y=(0,p.resolveStripeMethodBrandVariant)(e,t),C=Js[e],[_,ne]=(0,s.useState)(!1),z=!!C&&!_,ue=y?.backgroundColor??d??"#ffffff",k=y?.borderColor??u??"#d1d5db",$=y?.textColor??m??"#262833";return(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ba,padding:"0 1rem",backgroundColor:ue,color:$,border:`1px solid ${k}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"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:n?(0,c.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,p.getStripeMethodDisplayName)(e)}\u2026`}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,p.hasVendoredStripeMethodLogo)(e)?8:0},children:[z?(0,c.jsx)("img",{src:C,alt:"","aria-hidden":"true",onError:()=>ne(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!z&&y?.logoSvg?(0,c.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:y.logoSvg}}):null,(0,c.jsx)("span",{children:(0,p.getStripeMethodDisplayName)(e)})]}),a&&(0,c.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:$,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,c.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Fi({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:d,onErrorChange:u,onDecline:m,onCancel:h,runBeforeButtonClick:b,onButtonClick:y,isProcessing:C,submitButtonColor:_,submitButtonBorderRadius:ne,submitButtonStyle:z,errorText:ue}){let k=Tr(),{emitInstrument:$}=(0,s.useContext)(Qn),U=(0,Kt.useStripe)(),se=(0,Kt.useElements)(),[Se,Pe]=(0,s.useState)(!1),pe=(0,s.useRef)(!1),[ye,yt]=(0,s.useState)(!1),[He,we]=(0,s.useState)("loading"),[Me,fe]=(0,s.useState)(""),Re=!(0,p.isValidEmail)(r?.trim()),Ge=!Re||(0,p.isValidEmail)(Me.trim()),oe=(0,s.useCallback)(async()=>{if(!U||!se||C||pe.current||!ye)return;pe.current=!0,Pe(!0);let _e=b?await b("card"):{proceed:!0};if(!_e.proceed){pe.current=!1,Pe(!1);return}y?.("card");let ge=_e.sessionId??t,nt=_e.nonce??n,rt=Vr(o?.trim()),M=Mn({email:_e.accountPatch?.email?.trim()||r?.trim()||Me.trim(),firstName:_e.accountPatch?.firstName?.trim()||rt.firstName,lastName:_e.accountPatch?.lastName?.trim()||rt.lastName}),V=M.email,ie=Mn({..._e.accountPatch,...M});try{if(u?.(null),!(0,p.isValidEmail)(V))throw new Error("A valid email address is required for payment.");await a?.(M);let ae=await se.submit();if(ae.error){u?.(ae.error.message??"Payment failed.");return}let Ye=[M.firstName,M.lastName].filter(Boolean).join(" "),Ce=await U.createPaymentMethod({elements:se,params:{billing_details:{email:V,...Ye?{name:Ye}:{}}}});if(Ce.error||!Ce.paymentMethod){u?.(Ce.error?.message??"Failed to create payment method.");return}let N=Ce.paymentMethod;if(!ge||!V)throw new Error("Missing sessionId or email for payment.");let ut=N.type||e,ot=await Fa(l,$,ge,nt??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ut,paymentMethodId:null,intentKind:"payment"});if(ot.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let he=ot.clientSecret;if(typeof window<"u")try{localStorage.setItem(vr,JSON.stringify({clientSecret:he,sessionId:ge,nonce:nt,accountPatch:ie,paymentMethodId:N.id,paymentMethodType:N.type??e,gateway:"stripe"}))}catch{}let{error:le,paymentIntent:H}=await U.confirmPayment({clientSecret:he,confirmParams:{return_url:window.location.href,payment_method:N.id},redirect:"if_required"});if(le){if(typeof window<"u")try{localStorage.removeItem(vr)}catch{}let ze=le.message??"Payment failed.";u?.(ze),m?.(nn("card",ze,{code:le.code})),await Da({billingApiUrl:l,sessionId:ge,nonce:nt,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:le.code??"provider_declined"}});return}let Le=H?.status;if(!Do(Le)){if(typeof window<"u")try{localStorage.removeItem(vr)}catch{}let ze=Le==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";u?.(ze),m?.(nn("card",ze,{code:Le??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(vr)}catch{}let Oe=typeof H?.payment_method=="string"?H.payment_method:H?.payment_method?.id;d({id:Oe??N.id,type:"card",threeDSecureActionResultTokenId:H?.id,gateway:"stripe",paymentMethodType:N.type??e},{accountPatch:ie,paymentMethodCategory:"apm",sessionId:ge,nonce:nt})}catch(ae){u?.(ae instanceof Error?ae.message:"Payment failed. Please try again.")}finally{pe.current=!1,Pe(!1)}},[U,se,C,ye,b,y,t,n,r,o,Me,a,l,$,e,d,u,m]);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:Me,onChange:_e=>fe(_e.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,c.jsx)(Kt.PaymentElement,{onReady:()=>we("ready"),onLoadError:()=>{we("load_error"),Ni(en(k),"stripe","apm")},onChange:_e=>{yt(!!_e.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,p.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,c.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{oe()},disabled:!ye||!Ge||Se||C||He!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:_,color:"white",border:"none",borderRadius:ne,fontSize:"1rem",fontWeight:600,cursor:!ye||!Ge||Se||C||He!=="ready"?"not-allowed":"pointer",opacity:!ye||!Ge||Se||C||He!=="ready"?.5:1,transition:"opacity 120ms ease-out",...z??{}},children:Se?"Processing\u2026":`Pay with ${(0,p.getStripeMethodDisplayName)(e)}`}),ue&&(0,c.jsx)(yo,{margin:"0.75rem 0 0",children:ue})]})}function bl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:d,paymentElementBaseOptions:u,onTokenizedBody:m,onErrorChange:h,onButtonClick:b,onDecline:y,runBeforeButtonClick:C,onLoadStateChange:_,isProcessing:ne=!1,submitButtonColor:z="#4A49FF",submitButtonBorderRadius:ue=8,submitButtonStyle:k,buttonAppearance:$,themeId:U,onExpandApm:se,expandedApmMethod:Se}){let{emitInstrument:Pe}=(0,s.useContext)(Qn),[pe,ye]=(0,s.useState)(null),[yt,He]=(0,s.useState)(null),we=(0,s.useRef)(!1),{request:Me,collect:fe,finish:Re}=co();(0,s.useEffect)(()=>{l.length>0&&d?_?.("ready"):d||_?.("loading")},[l.length,d,_]);let Ge=(0,s.useCallback)(async M=>{if(!d||we.current||ne)return;we.current=!0,He(M);let V=C?await C("card"):{proceed:!0};if(!V.proceed){we.current=!1,He(null);return}b?.("card");let ie=V.sessionId??e,ae=V.nonce??t,Ye=Vr([V.accountPatch?.firstName,V.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ce=Mn({email:V.accountPatch?.email?.trim()||n?.trim(),firstName:V.accountPatch?.firstName?.trim()||Ye.firstName,lastName:V.accountPatch?.lastName?.trim()||Ye.lastName});if(!(0,p.isValidEmail)(Ce.email)){He(null);let ot=await fe((0,p.getStripeMethodDisplayName)(M),Ce);if(!ot){we.current=!1;return}Ce=ot,He(M)}let N=Ce.email,ut=Mn({...V.accountPatch,...Ce});try{if(h?.(null),!ie||!(0,p.isValidEmail)(N))throw new Error("Missing sessionId or email for payment.");await o?.(Ce);let ot=await Fa(a,Pe,ie,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:M,paymentMethodId:null,intentKind:"payment"});if(ot.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let he=ot.clientSecret;if(typeof window<"u")try{localStorage.setItem(vr,JSON.stringify({clientSecret:he,sessionId:ie,nonce:ae,accountPatch:ut,paymentMethodType:M,gateway:"stripe"}))}catch{}let{error:le,paymentIntent:H}=await d.confirmPayment({clientSecret:he,confirmParams:{return_url:window.location.href,payment_method_data:{type:M,billing_details:{name:[Ce.firstName,Ce.lastName].filter(Boolean).join(" "),...N?{email:N}:{}}}},redirect:"if_required"});if(le){if(typeof window<"u")try{localStorage.removeItem(vr)}catch{}let ze=le.message??"Payment failed.";h?.(ze),y?.(nn("card",ze,{code:le.code})),await Da({billingApiUrl:a,sessionId:ie,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:M,providerDeclineReason:le.code??"provider_declined"}});return}let Le=H?.status;if(!Do(Le)){if(typeof window<"u")try{localStorage.removeItem(vr)}catch{}let ze=Le==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(ze),y?.(nn("card",ze,{code:Le??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(vr)}catch{}let Oe=typeof H?.payment_method=="string"?H.payment_method:H?.payment_method?.id;m({id:Oe??H?.id,type:"card",threeDSecureActionResultTokenId:H?.id,gateway:"stripe",paymentMethodType:M},{accountPatch:ut,paymentMethodCategory:"apm",sessionId:ie,nonce:ae})}catch(ot){h?.(ot instanceof Error?ot.message:"Payment failed. Please try again.")}finally{we.current=!1,He(null)}},[d,ne,C,b,e,t,n,fe,a,Pe,r,o,m,h,y]),[oe,_e]=(0,s.useState)(null),ge=se?Se??null:oe,nt=(0,s.useCallback)(M=>{we.current||ne||ge&&ge!==M||((0,p.needsStripeMethodExplicitConfirm)(M)?se?se(M):_e(M):Ge(M))},[ge,ne,Ge,se]),rt=(0,s.useMemo)(()=>oe?Il(u,oe):null,[oe,u]);return(0,c.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Me?(0,c.jsx)(uo,{identity:Me.identity,methodLabel:Me.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Me.id):l.map(M=>{let V=Se===M,ie=yt===M,ae=yt!==null&&yt!==M||Se!=null&&Se!==M;return(0,c.jsxs)(s.default.Fragment,{children:[(0,c.jsx)(Bd,{method:M,themeId:U,submitting:ie,disabled:ae,highlighted:V,hasNextStep:(0,p.needsStripeMethodExplicitConfirm)(M),onClick:()=>nt(M),backgroundColor:$?.backgroundColor,borderColor:$?.borderColor,textColor:$?.textColor,borderRadius:$?.borderRadius,fontFamily:$?.fontFamily}),!se&&oe===M&&rt&&d&&(0,c.jsx)(Kt.Elements,{stripe:d,options:rt,children:(0,c.jsx)(Fi,{method:M,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:m,onErrorChange:h,onDecline:y,onCancel:()=>_e(null),runBeforeButtonClick:C,onButtonClick:b,isProcessing:ne,submitButtonColor:z,submitButtonBorderRadius:ue,submitButtonStyle:k})},M)]},M)})})}function Fd({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:l,onError:d,onDecline:u,onTokenizedBody:m,firstName:h,lastName:b,chv:y,className:C,submitLabel:_,isProcessing:ne,error:z,onErrorChange:ue,showPayPal:k=!0,showStripe:$=!0,enabledPaymentMethods:U,enabledPaymentMethodCountries:se,showApplePay:Se=!0,showGooglePay:Pe=!0,layout:pe="default",theme:ye,buttonsTheme:yt,buttonsStyles:He,appearance:we,cardButtonContent:Me,cardBackButtonContent:fe,cardTitleContent:Re,showSecurityFooter:Ge,onButtonClick:oe,onBeforeButtonClick:_e,onBuyerIdentityReady:ge,enableAVS:nt,cardFieldOrder:rt,cardPreFormSlot:M,avsLayout:V="row",country:ie,zip:ae,addressLine1:Ye,addressLine2:Ce,city:N,state:ut,onCountryChange:ot,onZipChange:he,avsCheck:le,checkoutType:H,checkoutLayout:Le,totalAmount:Oe=0,currency:ze="usd",initialCardOpen:je=!1,directPaypal:Be,isSubscription:Ne=!1,session:ce,dataAttachmentPending:dn=!1,dataAttachmentRequiresIdentity:Jt=!1,debug:ee=!1}){let at=Tr(),Z=ma(),Q=(0,s.useContext)(dr),{emitInstrument:be}=(0,s.useContext)(Qn),g=ce??Q.session,q=g?.gateways?.paypal?.providerObjectType??Be?.providerObjectType,Fe=dn||Q.claimPending===!0,Je=Jt||Q.claimRequiresIdentity===!0,De=Fe&&!Je,$t=Ls(),W=n||$t,[St,Tt]=(0,s.useState)(!1),[ft,un]=(0,s.useState)(null),[G,Lt]=(0,s.useState)(ie??"US"),[vn,pn]=(0,s.useState)(ae??""),[mn,In]=(0,s.useState)(Ye??""),[Bn,Fn]=(0,s.useState)(Ce??""),[Xt,Ke]=(0,s.useState)(N??""),[Qe,wt]=(0,s.useState)(ut??""),[rn,kt]=(0,s.useState)(""),[Vn,gt]=(0,s.useState)({}),At=(0,s.useRef)(ae??""),Ot=(0,s.useRef)(ie??"US"),yn=(0,s.useRef)(Ye??""),zt=(0,s.useRef)(Ce??""),xt=(0,s.useRef)(N??""),Pn=(0,s.useRef)(ut??""),Cn=(0,s.useRef)(""),It=(0,s.useRef)({});(0,s.useEffect)(()=>{let i=(R,X,Ue,te,mt)=>{if(It.current[R])return;let lt=X?.trim();!lt||lt===Ue.current||(Ue.current=lt,te(lt),mt?.(lt))};i("country",ie,Ot,Lt,ot),i("zip",ae,At,pn,he),i("addressLine1",Ye,yn,In),i("addressLine2",Ce,zt,Fn),i("city",N,xt,Ke),i("state",ut,Pn,wt)},[ie,ae,Ye,Ce,N,ut,ot,he]);let de=(0,s.useMemo)(()=>(0,p.resolveAVSConfig)(nt),[nt]),on=de!==null,jn=(0,s.useMemo)(()=>(0,p.isAuthorizationOnlySession)(ce),[ce]),Wt=!!ce?.vault?.html,Vt=!!ce?.gateways?.pcivault,an=si(ce),Dn=!!(ce?.gateways?.stripe?.enabledPaymentMethods??U)?.includes("card")||Fr(ce),Ht=Wt||Dn||Vt,$e=!!($&&Ht&&e),[fn,ve]=(0,s.useState)(()=>pe!=="buttons"||je?e??null:null),[O,Ve]=(0,s.useState)(0),K=pe!=="buttons"||je||!!e&&fn===e,Rt=ce?.captureMethod,Mt=(0,s.useRef)(at);(0,s.useEffect)(()=>{Mt.current=at},[at]);let[Gt,Kn]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!$e||!e||!K){Kn(null);return}let i=Mt.current?Mt.current.cardCapture({sessionId:e,captureMethod:Rt}):new pr.PciVaultCardCapture({sessionId:e,captureMethod:Rt,billingApiUrl:W,telemetry:r});return Kn({sessionId:e,captureMethod:Rt,billingApiUrl:W,telemetry:r,capture:i}),()=>{i.unmount()}},[$e,e,K,Rt,W,r]);let Ee=$e&&e&&K&&Gt?.sessionId===e&&Gt.captureMethod===Rt&&Gt.billingApiUrl===W&&Gt.telemetry===r?Gt.capture:null,sn=(0,s.useMemo)(()=>{let i=G,R=de?(0,p.isAVSFieldVisible)(de.postal_code,i):!1;return Ad(i,vn,R)},[de,G,vn]),{avsInvalid:Wn,invalidAvsFields:Sr}=(0,s.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!$e||!de)return{avsInvalid:!1,invalidAvsFields:i};let R=G,X=(mt,lt)=>(0,p.isAVSFieldVisible)(mt,R)&&!lt.trim(),Ue={line1:X(de.address_line_1,mn),city:X(de.city,Xt),state:X(de.state,Qe),zip:sn.empty||sn.malformed};return{avsInvalid:Ue.line1||Ue.city||Ue.state||Ue.zip,invalidAvsFields:Ue}},[$e,de,G,mn,Xt,Qe,sn]),[or,Lr]=(0,s.useState)(!1),[Or,ar]=(0,s.useState)(!1),[Mr,Rn]=(0,s.useState)(!1),[ir,Ft]=(0,s.useState)({line1:!1,city:!1,state:!1}),Nn=(0,s.useRef)(!1),Hn=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Gn=(0,s.useRef)(!1),ht=(0,s.useCallback)(i=>{Hn.current[i]=!0,Gn.current=!0},[]),_n=(0,s.useCallback)(i=>!Nn.current&&Hn.current[i],[]),Yn=(0,s.useCallback)(i=>{_n(i)&&Ft(R=>R[i]?R:{...R,[i]:!0})},[_n]),[sr,gn]=(0,s.useState)(()=>Ai(ce?.vault)),[et,hn]=(0,s.useState)(je&&Ht?"card":"buttons"),[ln,Ln]=(0,s.useState)(null),wr=et==="expanding"||et==="card",zr=ce?.gateways?.stripe&&!an?"stripe":void 0,kr=(0,s.useCallback)(()=>{be?.({class:"card_surface",provider:zr})},[zr,be]),On=(0,s.useRef)(null),bn=(0,s.useCallback)(i=>{On.current&&clearTimeout(On.current),On.current=setTimeout(()=>{On.current=null,i()},Jo)},[]);(0,s.useEffect)(()=>()=>{On.current&&clearTimeout(On.current)},[]);let Yr=(0,s.useCallback)(()=>{kr(),ve(e??null),Ve(i=>i+1),hn("expanding"),bn(()=>hn("card"))},[bn,kr,e]),En=(0,s.useCallback)(()=>{hn("collapsing"),bn(()=>hn("buttons"))},[bn]),Br=(0,s.useCallback)(i=>{Ln(i),hn("apm-expanding"),bn(()=>hn("apm-form"))},[bn]),Sn=(0,s.useCallback)(()=>{hn("apm-collapsing"),bn(()=>{hn("buttons"),Ln(null)})},[bn]);(0,s.useEffect)(()=>{pe==="buttons"&&je&&Ht&&(ve(e??null),hn("card"))},[pe,je,Ht,e]);let[zn,st]=(0,s.useState)(null),Jn=(0,s.useRef)(!1),Zt=(0,s.useRef)(null),_t=(0,s.useRef)("idle"),[D,F]=(0,s.useState)(!1),j=(0,s.useRef)(D);j.current=D;let[Y,pt]=(0,s.useState)(()=>Be?.existingOrderId?{orderId:Be.existingOrderId,attempts:1}:null),B=(0,s.useRef)(Y);(0,s.useEffect)(()=>{B.current=Y},[Y]);let f=(0,s.useRef)(null),L=(0,s.useMemo)(()=>{if(ge||Q.claimBuyerIdentity||ce?.buyerIdentified!==!1||!e||!t)return;let i=`${W}|${e}|${t}`;f.current?.key!==i&&(f.current={key:i,claim:so(new pr.PaymentAPI(W,{telemetry:!1}),e,t,{...a?{userId:a}:{},...h?{firstName:h}:{},...b?{lastName:b}:{}})});let R=f.current.claim;return async X=>{await R(X)}},[ge,Q.claimBuyerIdentity,ce?.buyerIdentified,e,t,W,a,h,b]),S=ge??Q.claimBuyerIdentity??L,I=z??ft,A=(0,s.useMemo)(()=>(0,p.resolveTheme)(ye),[ye]),w=(0,s.useMemo)(()=>{let i=A?.buttonsLayout??(0,p.resolveButtonsLayoutTheme)(yt);return He?{...i,...He,cardButton:{...i.cardButton,...He.cardButton},cardFormContainer:{...i.cardFormContainer,...He.cardFormContainer},backButton:{...i.backButton,...He.backButton},backButtonIcon:{...i.backButtonIcon,...He.backButtonIcon},submitButton:{...i.submitButton,...He.submitButton},title:{...i.title,...He.title}}:i},[A,yt,He]),J=we??A?.appearance,Xe=(0,s.useMemo)(()=>Aa({appearance:J,buttonsStyles:w,layout:pe}),[J,w,pe]),Dt=Q.inlineSessionPatchProcessing??!1,Ae=(ne??St)||Dt,me=W.replace(/\/+$/,""),v=(0,s.useMemo)(()=>ci({userId:a,email:o,firstName:h,lastName:b,country:ie,zip:ae},Vn),[a,o,h,b,ie,ae,Vn]),x=[v.firstName,v.lastName].filter(i=>!!i?.trim()).join(" "),re=!(0,p.isValidEmail)(v.email?.trim()),ke=(0,s.useRef)(null);$e&&ke.current===null&&(ke.current=re);let xe=$e&&(ke.current??re),Ie=(0,s.useMemo)(()=>xd(rn,xe),[rn,xe]),tt=Ie.empty||Ie.malformed,vt=(0,s.useMemo)(()=>at?at.getRawProvider():null,[at]),tn=(0,s.useMemo)(()=>Z?Z.getRawProvider():null,[Z]),Un=Oe||100,Jr=ze.toLowerCase(),Va=(0,s.useMemo)(()=>J?(0,pr.toStripeAppearance)(J):null,[J]),Xr=Va,Ki=(0,s.useMemo)(()=>{let i=Va??{},R=i.rules??{};return{...i,rules:{...R,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...R[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...R[".AccordionItemContents"]??{}}}}},[Va]),Wi=(0,s.useMemo)(()=>({...Bs(Oe,ce?.captureMethod),currency:Jr,...Xr?{appearance:Xr}:null}),[Oe,Jr,ce?.captureMethod,Xr]),Hi=(0,s.useMemo)(()=>({mode:"payment",amount:Un,currency:Jr,captureMethod:"manual",setupFutureUsage:"off_session",...Xr?{appearance:Xr}:null}),[Un,Jr,Xr]),Te=(0,s.useCallback)(i=>{un(i),ue?.(i)},[ue]),ja=(0,s.useRef)(""),[Gi,Ul]=(0,s.useState)(!1),Ka=(0,s.useCallback)(()=>{Ul(!0)},[]);(0,s.useEffect)(()=>{if(!$e||!xe||!S||!Gi||tt||ja.current)return;let i=Mn({email:(0,p.isValidEmail)(v.email?.trim())?v.email?.trim():Cn.current.trim(),firstName:v.firstName?.trim(),lastName:v.lastName?.trim()});ja.current=JSON.stringify(i),gt(R=>({...R,...i})),Promise.resolve(S(i)).catch(R=>{ja.current="",Te(R instanceof Error?R.message:"Failed to attach buyer details.")})},[$e,xe,S,Gi,tt,v.email,v.firstName,v.lastName,Te]),(0,s.useEffect)(()=>{!$e||!Ee||Ee.setCardFieldOrder?.(rt??null,de==null&&!xe)},[$e,Ee,rt,de,xe]),(0,s.useEffect)(()=>{(et==="expanding"||et==="collapsing"||et==="apm-expanding"||et==="apm-collapsing")&&Te(null)},[et,Te]);let fr=(0,s.useCallback)((i,R,X)=>{u?.(nn(i,R,X))},[u]),Zr=(0,s.useCallback)((i,R,X)=>{let Ue=X?.popupBlocked??Er(R),te=Ed(i,Ue),mt=jr(X?.code)??_r(R)??"external_payment_method_failed",lt=new p.FloPayError(te,"api_error",{code:"external_payment_method_failed",param:i});st(null),pe==="buttons"&&(hn("buttons"),Ln(null)),Te(te),d?.(lt),console.error("[FloPay] External payment method failed:",{method:i,code:mt,popupBlocked:Ue})},[pe,d,Te]);(0,s.useEffect)(()=>{if(!$e||!e){gn(null);return}let i=Ai(ce?.vault);if(i){gn(i);return}if(!K){gn(null);return}gn(null);let R=!0;return new pr.PaymentAPI(me).getVaultCapture(e,t).then(X=>{if(!R)return;let Ue=Ai(X);Ue?gn(Ue):Te("Failed to load the secure card form.")}).catch(X=>{R&&Te(X instanceof Error?X.message:"Failed to load the secure card form.")}),()=>{R=!1}},[$e,K,O,e,ce?.vault,me,t,Te]);let lr=(0,s.useRef)({onComplete:l,onError:d,updateError:Te,emitDecline:fr,resolvedAccount:v,avsConfig:de,avsCheckProp:le,sessionId:e,nonce:t,baseUrl:me,captureMethod:ce?.captureMethod,paymentId:ce?.paymentId,authorizationExpiresAt:ce?.authorizationExpiresAt,serverSideCardGateway:an});lr.current={onComplete:l,onError:d,updateError:Te,emitDecline:fr,resolvedAccount:v,avsConfig:de,avsCheckProp:le,sessionId:e,nonce:t,baseUrl:me,captureMethod:ce?.captureMethod,paymentId:ce?.paymentId,authorizationExpiresAt:ce?.authorizationExpiresAt,serverSideCardGateway:an};let Wa=(0,s.useRef)(!1),Yi=(0,s.useCallback)(()=>{let i=lr.current,R=i.resolvedAccount.email?.trim(),X=(0,p.isValidEmail)(R)?R:Cn.current.trim();if(!(0,p.isValidEmail)(X))return null;let Ue=i.resolvedAccount.firstName?.trim(),te=i.resolvedAccount.lastName?.trim(),mt=Ot.current||i.resolvedAccount.country||"US",lt=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.state,mt):!1,hr=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.address_line_1,mt):!1,it=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.postal_code,mt):!1,Bt=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.city,mt):!1,bt=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.address_line_2,mt):!1,ct=hr&&!lt&&it?(0,p.getStateFromPostalCode)(mt,(At.current??"").trim()):null,xn=lt?Pn.current:ct;return{accountData:{userId:i.resolvedAccount.userId??"",email:X,...Ue?{firstName:Ue}:{},...te?{lastName:te}:{},...it&&At.current?{zip:At.current}:{},...Bt&&xt.current?{city:xt.current}:{},...xn?{state:xn}:{},...hr&&yn.current?{addressLine1:yn.current}:{},...bt&&zt.current?{addressLine2:zt.current}:{},country:mt},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,p.isAVSFieldVisible)(i.avsConfig.country,mt),postal_code:it,address_line_1:hr,address_line_2:bt,city:Bt,state:lt}}:{}}},[]),Ji=(0,s.useRef)(Fe);Ji.current=Fe,(0,s.useEffect)(()=>{Fe||I!==dl||lr.current.updateError(null)},[Fe,I]),(0,s.useEffect)(()=>{!$e||!Ee||Ee.setSubmitGate?.(Wn||Fe||tt||D)},[$e,Ee,Wn,Fe,tt,D]),(0,s.useEffect)(()=>{if(!$e||!Ee)return;Wa.current=!1;let i=null,R=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,_t.current="idle",st(null)},400)},X=Ee.on("submitting",()=>{Lr(!0),Zt.current&&clearTimeout(Zt.current),_t.current="validation-window",Zt.current=setTimeout(()=>{Zt.current=null,_t.current==="validation-window"&&(_t.current="processing")},hd),st("processing");let it=lr.current;if(!it.sessionId||!it.nonce)return;let Bt=Yi();if(!Bt){it.updateError("Enter a valid email address."),_t.current="idle",st(null);return}new pr.PaymentAPI(it.baseUrl).patchAccountSnapshot(it.sessionId,it.nonce,Bt,{telemetryMode:"best_effort"}).catch(bt=>{if(!vd(bt))return;let ct=bt instanceof Error?bt.message:"Please check your billing address and try again.";it.updateError(ct),_t.current="idle",st(null),it.onError?.(bt instanceof p.FloPayError?bt:new p.FloPayError(ct,"api_error"))})}),Ue=Ee.on("complete",async it=>{if(ho(it.sessionId??lr.current.sessionId),_t.current="terminal",F(!1),st("success"),await new Promise(xn=>setTimeout(xn,600)),Wa.current)return;Wa.current=!0;let Bt=lr.current,bt=(0,p.isAuthorizationOnlySession)(Bt)||it.outcome==="authorized",ct=Bt.serverSideCardGateway?{}:{paymentIntentId:it.intentId};lr.current.onComplete?.(bt?{status:"authorized",...ct,paymentId:it.paymentId??Bt.paymentId,sessionId:it.sessionId??Bt.sessionId,authorizationExpiresAt:it.authorizationExpiresAt??Bt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...ct,checkoutMethod:"card"})}),te=Ee.on("decline",it=>{let Bt=lr.current,bt=it.message??"Your payment was declined. Please try another card or contact your bank.";_t.current="terminal",F(!1),Bt.updateError(bt),st("error");let ct=it.failureOutcome??(0,p.normalizeCheckoutFailureOutcome)(it.declineReason)??"authorization_declined";Bt.emitDecline("card",bt,{code:ct,declineCode:ct}),R()}),mt=Ee.on("error",it=>{let Bt=lr.current,bt=it.message??"There was a problem processing your payment. Please try again.";_t.current="terminal",F(!1),Bt.updateError(bt),st("error"),Bt.onError?.(new p.FloPayError(bt,"api_error",{code:it.failureOutcome??"capture_failed"})),R()}),lt=Ee.on("challenge_dismissed",()=>{Zt.current&&(clearTimeout(Zt.current),Zt.current=null),_t.current="processing",F(!0),st(null)}),hr=Ee.on("blocked",()=>{if(j.current){lr.current.updateError(bd);return}if(!Ji.current){Lr(!0);return}Ka(),lr.current.updateError(dl)});return()=>{i&&(clearTimeout(i),i=null),Zt.current&&(clearTimeout(Zt.current),Zt.current=null),_t.current="idle",F(!1),st(null),X(),Ue(),te(),mt(),lt(),hr()}},[$e,Ee,Ka,Yi]);let gr=!!Be?.clientId,wo=Array.isArray(U),ea=wo&&U.length>0,ql=wo&&U.includes("paypal"),{expressMethods:ta,paymentElementMethods:ko}=(0,s.useMemo)(()=>(0,p.partitionStripeMethods)(U,{excludePaypal:gr}),[U,gr]),Xi=gr||!!Z,$l=(0,s.useMemo)(()=>Xi?ta.filter(i=>i!=="paypal"):ta,[ta,Xi]),Vl=(0,s.useMemo)(()=>{let i=[];return Se&&i.push("apple_pay"),Pe&&i.push("google_pay"),i},[Se,Pe]),Qr=wo?$l:Vl,jl=$&&Qr.length>0,Ha=on?G:ie,na=(0,s.useMemo)(()=>{let i=Ha?.trim().toUpperCase();return i?se?ko.filter(R=>{let X=se[R];return!X||X.length===0||X.includes(i)}):(0,p.filterStripeMethodsByCountry)(ko,Ha):ko},[ko,Ha,se]),Ga=(0,s.useMemo)(()=>({mode:"payment",amount:Un,currency:Jr,paymentMethodCreation:"manual",appearance:Ki}),[Un,Jr,Ki]),[Zi,Qi]=(0,s.useState)("loading"),[es,ts]=(0,s.useState)("loading"),[ns,rs]=(0,s.useState)("loading"),[Kl,Ya]=(0,s.useState)(!1),[os,Ja]=(0,s.useState)("loading"),[Xa,Wl]=(0,s.useState)();(0,s.useEffect)(()=>{Wl(ya())},[]);let ra=Xa?.inAppBrowser,oa=Xa?fa(Xa,Be?.approvalPresentation,q??(Ne?"subscription":"order")):"popup",as=k&&(gr||(wo?ql:ra===!1)),is=$&&jl,Io=(!De||!!Q.waitForDataAttachment)&&as&&gr,ss=os==="retrying"||os==="exhausted",Ro=!De&&as&&!!tn&&(!gr||ss),eo=!De&&is&&!!vt,_o=!De&&$&&ea&&na.length>0&&!!vt,Hl=Io&&!ss?Kl:Ro&&fl(Zi),Gl=eo&&fl(es),Yl=_o&&ns!=="load_error",ls=i=>i==="loading"||i==="ready",cs=Io||Ro&&ls(Zi)||eo&&ls(es)||_o&&ns!=="load_error",aa=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!aa.current){if(!$&&!k){aa.current=!0;let i=new p.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(i),Te(i.message)}else if(!$&&k&&!gr&&!tn){aa.current=!0;let i=new p.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(i),Te(i.message)}else if(ra!==void 0&&!De&&!Ht&&!cs){aa.current=!0;let i=new p.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?.(i),Te(i.message)}}},[$,k,gr,tn,ra,De,Ht,cs,d,Te]);let ds=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(ds.current||!ea)return;let i=[];Se!==!0&&i.push("showApplePay"),Pe!==!0&&i.push("showGooglePay"),i.length!==0&&(ds.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.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.`))},[ea,Se,Pe]);let us=(0,s.useCallback)((i,R)=>Q.applyInlineSessionPatch?Q.applyInlineSessionPatch(i).then(X=>({error:null,sessionId:X.sessionId||e,nonce:X.session?.clientSecret||t})).catch(X=>{let Ue=yl(R,X);return Te(Ue.message),d?.(Ue),{error:Ue,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Q.applyInlineSessionPatch,t,d,e,Te]),cr=(0,s.useCallback)(async i=>{if(i!=="card"&&De&&await Q.waitForDataAttachment?.(),!_e)return{proceed:!0};try{let R=await _e({method:i,sessionId:e||void 0,createSession:Q.inlineSessionDraft});if(R===!1)return{proceed:!1};if(R&&typeof R=="object"){R.account&&gt(Ue=>({...Ue??{},...R.account}));let X=await us(R,i);return X.error?{proceed:!1,accountPatch:R.account}:{proceed:!0,accountPatch:R.account,sessionId:X.sessionId,nonce:X.nonce}}return{proceed:!0}}catch(R){let X=yl(i,R);return Te(X.message),d?.(X),{proceed:!1}}},[us,Q.inlineSessionDraft,Q.waitForDataAttachment,De,_e,d,e,Te]),ps=(0,s.useCallback)(async(i,R)=>{if(Jn.current)return;Jn.current=!0,Tt(!0),st("processing"),Te(null);let X=R?.sessionId??e,Ue=R?.nonce??t,te=ci(v,R?.accountPatch),mt=R?.completionPaymentMethodId??No(i),lt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,hr=kd(i),it=()=>{be?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:hr})};try{let bt=await new pr.PaymentAPI(me).processPayment(te.userId??"",{sessionId:X,nonce:Ue,paymentMethodCategory:R?.paymentMethodCategory??Rd(i),tokenizedData:lt,accountData:{...R?.accountPatch,userId:te.userId??"",email:te.email??"",firstName:te.firstName||void 0,lastName:te.lastName||void 0,...de?(()=>{let Pt=Ot.current,Zn=(0,p.isAVSFieldVisible)(de.state,Pt),wn=(0,p.isAVSFieldVisible)(de.address_line_1,Pt),Qt=(0,p.isAVSFieldVisible)(de.postal_code,Pt),$r=wn&&!Zn&&Qt?(0,p.getStateFromPostalCode)(Pt,(At.current??"").trim()):null,Bo=Zn?Pn.current:$r;return{country:Pt,...Qt&&At.current?{zip:At.current}:{},...(0,p.isAVSFieldVisible)(de.city,Pt)&&xt.current?{city:xt.current}:{},...Bo?{state:Bo}:{},...wn&&yn.current?{addressLine1:yn.current}:{},...(0,p.isAVSFieldVisible)(de.address_line_2,Pt)&&zt.current?{addressLine2:zt.current}:{}}})():{}},chv:y,avsCheck:le??!1,checkoutType:H,checkoutLayout:Le,avsConfig:de?{country:(0,p.isAVSFieldVisible)(de.country,Ot.current),postal_code:(0,p.isAVSFieldVisible)(de.postal_code,Ot.current),address_line_1:(0,p.isAVSFieldVisible)(de.address_line_1,Ot.current),address_line_2:(0,p.isAVSFieldVisible)(de.address_line_2,Ot.current),city:(0,p.isAVSFieldVisible)(de.city,Ot.current),state:(0,p.isAVSFieldVisible)(de.state,Ot.current)}:void 0});if(bt.ok){let Pt=bt.status===204?null:await bt.json().catch(()=>null),Zn=(0,p.isAuthorizationOnlySession)(ce)||Pt?.status==="authorized";ho(X),st("success"),pt(null),await new Promise($r=>setTimeout($r,600));let wn;typeof Pt?.paymentId=="string"?wn=Pt.paymentId:ce?.paymentId&&(wn=ce.paymentId);let Qt;typeof Pt?.authorizationExpiresAt=="string"?Qt=Pt.authorizationExpiresAt:ce?.authorizationExpiresAt&&(Qt=ce.authorizationExpiresAt),l?.(Zn?{status:"authorized",...wn===void 0?{}:{paymentId:wn},sessionId:typeof Pt?.sessionId=="string"?Pt.sessionId:X,...Qt===void 0?{}:{authorizationExpiresAt:Qt},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:mt,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:mt,checkoutMethod:i.isPaypal?"paypal":"card"});return}let ct=await bt.json().catch(()=>null);if(ct?.type==="paypal_redirect_required"){let Pt=ct.threeDSecureToken,Zn=ct.paymentMethodId||i.id||"";if(!at||!Pt){st("error"),Te("PayPal authorization required but no token provided.");return}try{let wn=Z?.getRawProvider();if(!wn){Te("PayPal is not available.");return}let Qt={return_url:window.location.href};Zn&&(Qt.payment_method=Zn);let{error:$r}=await wn.confirmPayment({clientSecret:Pt,confirmParams:Qt,redirect:"if_required"});if($r){st("error");let Bo=$r.message??"PayPal payment failed.";Te(Bo),fr("paypal",Bo,{code:$r.code})}}catch(wn){st("error"),Te(wn instanceof Error?wn.message:"PayPal authorization failed.")}return}if(ct?.type==="paypal_direct_required"){let Pt=ct.orderId;if(!Pt){st("error"),Te("PayPal retry required but no order id provided.");return}let Zn=B.current?.attempts??0;if(Zn>=2){st("error"),Te("PayPal payment could not be completed after multiple attempts."),fr("paypal","paypal_direct_required retry limit exceeded");return}Ya(!1),Ja("loading"),pt({orderId:Pt,attempts:Zn+1}),st(null);return}(0,p.classifyPaymentRejection)(bt.status,ct)||it(),st("error");let xn=ct?.message??"Payment failed. Please try again.";Te(xn),fr(i.isPaypal?"paypal":"card",xn,{code:ct?.code??ct?.gatewayErrorCode,declineCode:ct?.declineCode??ct?.gatewayDeclineReason}),await new Promise(Pt=>setTimeout(Pt,400))}catch(Bt){Cl(Bt)||it(),st("error"),Te(Bt instanceof Error?Bt.message:"An unexpected error occurred"),await new Promise(bt=>setTimeout(bt,400))}finally{Tt(!1),st(null),Jn.current=!1}},[me,e,t,v,de,le,H,Le,y,at,Z,ce,l,Te,fr,be]),Tn=(0,s.useCallback)((i,R)=>{m?m(i):ps(i,R)},[m,ps]),Eo=`${vl}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(Eo);if(!i)return;let R;try{R=JSON.parse(i)}catch{localStorage.removeItem(Eo);return}if(!R||typeof R.createdAt!="number"||Date.now()-R.createdAt<0||Date.now()-R.createdAt>Pl||typeof R.paymentMethodId!="string"||typeof R.providerIntentId!="string"||typeof R.paymentMethodType!="string"||R.sessionId!==e||!t||R.nonce!==t||!Qr.includes(R.paymentMethodType)){localStorage.removeItem(Eo);return}localStorage.removeItem(Eo),Tn({id:R.paymentMethodId,type:"card",threeDSecureActionResultTokenId:R.providerIntentId,gateway:"stripe",paymentMethodType:R.paymentMethodType},{...R.accountPatch?{accountPatch:R.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Tn,t,e,Eo,Qr]);let ms=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||ms.current)return;let i=new URLSearchParams(window.location.search),R=i.get("payment_intent"),X=i.get("payment_intent_client_secret"),Ue=i.get("redirect_status");if(!R||!X||!at)return;let te=at.getRawProvider();if(!te)return;let mt=ct=>{let xn=localStorage.getItem(ct);if(!xn)return null;try{return JSON.parse(xn)}catch{return localStorage.removeItem(ct),null}},lt=mt(vr)??mt(sl),hr;if(lt?.clientSecret){if(lt.clientSecret!==X)return;hr={...lt.accountPatch?{accountPatch:lt.accountPatch}:{},...lt.sessionId?{sessionId:lt.sessionId}:{},...lt.nonce?{nonce:lt.nonce}:{}}}else if(lt?.sessionId&&lt.sessionId!==e)return;ms.current=!0,localStorage.removeItem(vr),localStorage.removeItem(sl);let it=new URL(window.location.href);it.searchParams.delete("payment_intent"),it.searchParams.delete("payment_intent_client_secret"),it.searchParams.delete("redirect_status"),window.history.replaceState({},"",it.toString());let Bt=lt?.paymentMethodType??lt?.tokenType??"card",bt="card";(async()=>{if(Ue==="failed"){let Qt="Payment was declined. Please try again.";Te(Qt),fr(bt,Qt);return}let{paymentIntent:ct,error:xn}=await te.retrievePaymentIntent(X);if(xn){let Qt=xn.message??"Failed to retrieve payment status.";Te(Qt),fr(bt,Qt,{code:xn.code});return}let Pt=ct?.status,Zn=Do(Pt);if(!ct||!Zn){let Qt=Pt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Te(Qt),fr(bt,Qt,{code:Pt??"missing_payment_intent"});return}let wn=typeof ct.payment_method=="string"?ct.payment_method:ct.payment_method?.id;Tn({id:wn??lt?.paymentMethodId??lt?.tokenId??ct.id,type:"card",threeDSecureActionResultTokenId:ct.id,gateway:lt?.gateway??"stripe",paymentMethodType:Bt},hr)})()},[e,Tn,at,Te,fr]);let Za=(0,s.useCallback)(i=>{i.preventDefault()},[]);if(!($e||at!==null))return(0,c.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let To=pe==="buttons",An=J?.variables,Jl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Qa=An?.colorBackground,Xl=Qa&&!Jl.has(Qa)?Qa:void 0,Ao=w.cardInputBorder??(To?"#e5e7eb":"#A4A4FF"),ys=An?.colorDanger??"#dc2626",Ut=i=>Sr[i]&&(ir[i]||or),ia=tt&&(Mr||or),Xn=i=>i?ys:Ao,sa=(sn.malformed||sn.empty)&&(Or||or),Zl=Xn(sa),ei=w.cardFormContainer?.backgroundColor??Xl??(To?"white":"#EDEDFF"),to=w.cardInputBackground??An?.colorBackground??"white",ti=oo(fe),fs=oo(Re),no=w.nameInput,gs=w.cardInputFontSize??Md(no?.fontSize)??An?.fontSizeBase??"16px",hs=typeof no?.fontFamily=="string"?no.fontFamily:An?.fontFamily??"Poppins, sans-serif",bs=Ii(no?.fontWeight)??400,Ql=w.cardInputColor??(typeof no?.color=="string"?no.color:void 0)??An?.colorText??"#262833",ec=w.cardInputPlaceholderColor??"#9ca3af",jt=An?.borderRadius??"8px",Ur=An?.borderRadius??w.cardButton?.borderRadius??jt,qr=An?.colorPrimary??"#4A49FF",tc=An?.colorPrimaryHover??Co(qr,.12),ni=An?.colorText??"#262833",ri={fontSize:gs,fontFamily:hs,fontWeight:bs,color:Ql,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},xo={marginTop:"0.375rem",...ri,fontSize:"0.75rem",lineHeight:1.4,color:ys},nc={"--flopay-input-placeholder-color":ec,"--flopay-input-font-size":gs,"--flopay-input-font-family":hs,"--flopay-input-font-weight":String(bs)},Mo=w.cardFormContainer??{},oi=Mo.padding??(To?"0":"1rem"),ai=Mo.borderRadius??jt,rc=Ee&&sr?(0,c.jsx)(Po,{capture:Ee,html:sr.html,messageToken:sr.messageToken,expectedOrigin:sr.expectedOrigin,theme:Xe,submitLabel:_,onReady:()=>{if(!xe&&!de||typeof document>"u")return;let i=()=>{let X=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(X){Nn.current=!0;try{X.focus()}finally{Nn.current=!1}}};Gn.current||i()},onError:i=>Te(i),onValidation:i=>{let R=_t.current;(R==="idle"||R==="validation-window")&&(Te(i),i&&_t.current==="validation-window"&&(Zt.current&&(clearTimeout(Zt.current),Zt.current=null),_t.current="idle",st(null)))}}):(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"}),vs=(0,c.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&kr()},style:{backgroundColor:ei,borderRadius:ai,...Mo,padding:oi,...nc,display:"flex",flexDirection:"column"},children:[(0,c.jsx)("style",{children:`
30
+ `,Va=44,oa=180,Il=`flopay-card-enter ${oa}ms cubic-bezier(0, 0, 0.2, 1) both`,Rl=`flopay-card-exit ${oa}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Bd=`flopay-buttons-enter ${oa}ms cubic-bezier(0, 0, 0.2, 1) both`,Fd=`flopay-buttons-exit ${oa}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Dd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Gi(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Od={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ld(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 ji={width:"100%",minHeight:Va,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 Nd(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function _l(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Vi(e){return e==="paypal"?"PayPal":(0,m.getStripeMethodDisplayName)(e)}function zd(e){let t=(0,m.getPostalCodeExample)(e);return`Enter a valid ${(0,m.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Ud(e,t,n){let r=(0,m.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,l=a&&!o,c=a&&!!o&&!(0,m.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:c}}function qd(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,m.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function El(e,t){return t instanceof m.FloPayError?t:new m.FloPayError(t instanceof Error?t.message:`${Nd(e)} before-click hook failed.`,"validation_error")}function $i(){return(0,d.jsx)("style",{children:Md})}function $d(e){return typeof e=="number"?`${e}px`:e}function Ll(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Nl({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,d.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,d.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,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,d.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:r})]})}function Tl(e){return e!=="unavailable"&&e!=="load_error"}function Wa(e){return(0,d.jsx)(Vd,{...e})}function Al({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:c,onDecline:p,onTechnicalFailure:f,runBeforeButtonClick:g,billingName:b,onBuyerIdentityReady:T,onLoadStateChange:w,placeholderBorderRadius:S,popupCapabilityOwner:P,externalTelemetryContext:F}){let fe=Br(),{emitInstrument:R}=(0,i.useContext)(rr),H=(0,jt.useStripe)(),N=(0,jt.useElements)(),ne=(0,i.useMemo)(()=>Di(fn(fe),F),[F,fe]),[pe,we]=(0,i.useState)("loading");(0,i.useEffect)(()=>{w?.(pe)},[pe,w]);let[ge,be]=(0,i.useState)(!1),lt=!(0,m.isValidEmail)(n?.trim())||!b?.trim(),{request:Ue,collect:ve,finish:De}=yo(),gt=(0,i.useRef)(!1),Ce=(0,i.useRef)(null),tt=(0,i.useRef)(null),[V,Te]=(0,i.useState)(0),[Ke,Ae]=(0,i.useState)(!1),We=(0,i.useRef)(!1),_=(0,i.useRef)(new Map),{startAttempt:ie,finishAttempt:me,invalidateAttempt:U,isAttemptInvalidated:Oe,isAttemptCurrent:Ie,generationRef:$}=Wo((ae,de,je)=>{f?.(ae,de,{...je,popupBlocked:je?.popupBlocked??zr(de),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:"popup",terminalReason:"overlay_timeout"}),Ae(!0),Te(rt=>rt+1)},{onHandoffObserved:()=>{P.markAvailable(),ne?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal",attempt:$.current})}});(0,i.useEffect)(()=>{Ke&&tt.current?.focus()},[Ke,V]);let ut=(0,i.useCallback)(()=>{Te(ae=>ae+1)},[]),nt=(0,i.useCallback)((ae,de,je)=>{U(je),f?.("paypal",ae,{code:de,popupBlocked:zr(ae),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:"popup"}),Ae(!0),ut()},[U,f,ut]),Qe=(0,i.useCallback)(()=>{window.setTimeout(()=>{(Ce.current?.querySelector("iframe")??Ce.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{We.current&&(We.current=!1,Qe())},[Qe,V]);let Ne=(0,i.useCallback)(()=>{Ae(!1),a?.(null),Qe()},[Qe,a]);(0,i.useEffect)(()=>{if(!H||gt.current)return;let ae=new URLSearchParams(window.location.search),de=ae.get("payment_intent"),je=ae.get("payment_intent_client_secret"),rt=ae.get("redirect_status");if(!de||!je)return;gt.current=!0;let pt;try{let ht=localStorage.getItem(ra);if(ht){let ot=JSON.parse(ht);ot.clientSecret===je&&(pt={...ot.accountPatch?{accountPatch:ot.accountPatch}:{},...ot.sessionId?{sessionId:ot.sessionId}:{},...ot.nonce?{nonce:ot.nonce}:{}})}}catch{}try{localStorage.removeItem(ra)}catch{}let G=new URL(window.location.href);G.searchParams.delete("payment_intent"),G.searchParams.delete("payment_intent_client_secret"),G.searchParams.delete("redirect_status"),window.history.replaceState({},"",G.toString()),(async()=>{try{if(be(!0),rt==="failed"){let D="PayPal payment was declined. Please try again.";a?.(D),p?.(dn("paypal",D));return}let{paymentIntent:ht,error:ot}=await H.retrievePaymentIntent(je);if(ot){a?.(ot.message??"Failed to retrieve PayPal payment status.");return}if(ht&&(ht.status==="requires_capture"||ht.status==="succeeded")){let D=typeof ht.payment_method=="string"?ht.payment_method:ht.payment_method?.id;o({id:D??ht.id,type:"card",threeDSecureActionResultTokenId:ht.id,isPaypal:!0},pt)}else{let D="PayPal payment was not completed. Please try again.";a?.(D),p?.(dn("paypal",D))}}catch(ht){a?.(ht instanceof Error?ht.message:"Failed to complete PayPal payment.")}finally{be(!1)}})()},[H,o,a,p]);let he=(0,i.useCallback)(async ae=>{if(l||ge){ae.reject();return}let de=g?await g("paypal"):{proceed:!0};if(!de.proceed){_.current.delete(V),ae.reject();return}let je=ie("paypal");_.current.set(V,{generation:je,accountPatch:de.accountPatch,sessionId:de.sessionId,nonce:de.nonce}),Ae(!1),ne?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal",attempt:je}),c?.("paypal"),ae.resolve()},[l,c,ne,g,ie,ge,V]),bt=(0,i.useCallback)(async ae=>{if(!H||!N)return;let de=_.current.get(V);if(de&&!Ie(de.generation)){_.current.delete(V);return}if(!de&&Oe()||de&&!me(de.generation))return;de||me();let je=de??null;if(_.current.delete(V),!je&&g){let D=await g("paypal");if(!D.proceed){ae.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}je={accountPatch:D.accountPatch,sessionId:D.sessionId,nonce:D.nonce}}let rt=je?.sessionId??e,pt=je?.nonce??t,G=await xd({event:ae,prepared:je,email:n,billingName:b,methodLabel:"PayPal",collect:ve});if(!G){ae.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ht=G.email,ot={...je?.accountPatch,...Dn(G,!0)};try{if(be(!0),a?.(null),!rt||!(0,m.isValidEmail)(ht))throw new Error("Missing sessionId or email for PayPal payment");await T?.(G);let D=H.createPaymentMethod,{error:mt,paymentMethod:Xt}=await D({type:"paypal"});if(mt){nt(mt,"stripe_paypal_create_payment_method_failed",de?.generation),ae.paymentFailed({reason:"fail"});return}let qe=await Ha(r,R,rt,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Xt?.id??null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let pn=qe.clientSecret,u={return_url:window.location.href};if(Xt?.id&&(u.payment_method=Xt.id),typeof window<"u")try{localStorage.setItem(ra,JSON.stringify({clientSecret:pn,sessionId:rt,nonce:pt,accountPatch:ot}))}catch{}let{error:x,paymentIntent:ce}=await H.confirmPayment({clientSecret:pn,confirmParams:u,redirect:"if_required"});if(x){if(typeof window<"u")try{localStorage.removeItem(ra)}catch{}if(jo(x)){let X=x.message??"Your payment was declined.";a?.(X),p?.(dn("paypal",X,{code:Ir(x),declineCode:go(x)})),await Ka({billingApiUrl:r,sessionId:rt,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ir(x)??"provider_declined"}})}else nt(x,"stripe_paypal_confirm_failed",de?.generation);return}if(typeof window<"u")try{localStorage.removeItem(ra)}catch{}let B=typeof ce?.payment_method=="string"?ce.payment_method:ce?.payment_method?.id;o({id:B??ce?.id,type:"card",threeDSecureActionResultTokenId:ce?.id,isPaypal:!0},{accountPatch:ot,paymentMethodCategory:"paypal",sessionId:rt,nonce:pt});return}catch(D){nt(D,"stripe_paypal_failed",de?.generation)}finally{be(!1)}},[H,N,e,t,n,b,ve,T,r,R,o,a,p,g,nt,me,Ie,Oe,V]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Nl,{state:pe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:(0,d.jsxs)("div",{ref:Ce,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ke&&(0,d.jsx)("button",{ref:tt,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ne,style:ji,children:"Try PayPal again"}),Ue&&(0,d.jsx)(fo,{identity:Ue.identity,methodLabel:Ue.methodLabel,onComplete:De,onCancel:()=>De(null)},Ue.id),(0,d.jsx)("div",{style:{display:Ue?"none":void 0},children:(0,d.jsx)(jt.ExpressCheckoutElement,{onReady:ae=>we(Ll(ae,["paypal"])),onLoadError:()=>{we("load_error"),Wi(ne,"paypal","paypal","provider_error")},onClick:he,onConfirm:bt,onCancel:()=>{let ae=_.current.get(V);_.current.delete(V),ne?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"cancelled",...ae?{attempt:ae.generation}:{}}),U(ae?.generation),Ae(!1),We.current=!0,ut()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:lt,emailRequired:lt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},V)})]})}),ge&&(0,d.jsx)(ar,{status:"processing"})]})}function xl({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:c,onButtonClick:p,onDecline:f,onTechnicalFailure:g,runBeforeButtonClick:b,billingName:T,onBuyerIdentityReady:w,onLoadStateChange:S,placeholderBorderRadius:P,popupCapabilityOwner:F,externalTelemetryContext:fe}){let R=Br(),{emitInstrument:H}=(0,i.useContext)(rr),N=(0,jt.useStripe)(),ne=(0,jt.useElements)(),pe=(0,i.useMemo)(()=>Di(fn(R),fe),[fe,R]),[we,ge]=(0,i.useState)("loading");(0,i.useEffect)(()=>{S?.(we)},[we,S]);let[be,lt]=(0,i.useState)(!1),Ue=(0,i.useRef)(!(0,m.isValidEmail)(n?.trim())||!T?.trim()).current,{request:ve,collect:De,finish:gt}=yo(),Ce=(0,i.useRef)(null),tt=(0,i.useRef)(null),[V,Te]=(0,i.useState)(0),[Ke,Ae]=(0,i.useState)(!1),[We,_]=(0,i.useState)(()=>ja(e,t)?"blocked":"idle"),[ie,me]=(0,i.useState)("google_pay"),U=(0,i.useRef)(null),Oe=(0,i.useRef)(!0),Ie=(0,i.useRef)(!1),$=(0,i.useRef)("google_pay"),ut=(0,i.useRef)("google_pay"),nt=(0,i.useRef)(null),Qe=(0,i.useRef)(null),Ne=(0,i.useRef)(new Set);(0,i.useEffect)(()=>(Oe.current=!0,()=>{Oe.current=!1;for(let u of Ne.current)window.clearTimeout(u);Ne.current.clear()}),[]);let he=(0,i.useRef)(new Map),{startAttempt:bt,finishAttempt:ae,invalidateAttempt:de,isAttemptInvalidated:je,isAttemptCurrent:rt,generationRef:pt}=Wo((u,x,ce)=>{g?.(u,x,{...ce,popupBlocked:ce?.popupBlocked??zr(x),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),me(u),Ae(!0),Te(B=>B+1)},{onHandoffObserved:u=>{F.markAvailable(),pe?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:pt.current,...u==="apple_pay"||u==="google_pay"?{walletType:u}:{}})}});(0,i.useEffect)(()=>{Ke&&tt.current?.focus()},[Ke,V]);let G=(0,i.useCallback)(()=>{Te(u=>u+1)},[]),ht=(0,i.useCallback)((u,x,ce,B,X=!1)=>{de(B),g?.(u,x,{code:ce,popupBlocked:zr(x),telemetryReported:X,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),me(u),Ae(!0),G()},[de,g,G]),ot=(0,i.useCallback)(()=>{window.setTimeout(()=>{(Ce.current?.querySelector("iframe")??Ce.current)?.focus()},0)},[]);(0,i.useEffect)(()=>{Ie.current&&(Ie.current=!1,ot())},[ot,V]);let D=(0,i.useCallback)(()=>{Ae(!1),c?.(null),ot()},[ot,c]),mt=(0,i.useCallback)(()=>{U.current?.()},[]);(0,i.useEffect)(()=>{let u=ja(e,t);if(!u)return;let x=!1,ce=!1,B=async()=>{if(!ce){ce=!0,x||_("checking");try{let X=await wl(N,u.clientSecret,Ne.current);if(x)return;let vt=Ui(X,u.providerObjectId,(0,m.isSetupIntentClientSecret)(u.clientSecret));if(vt.kind==="confirmed"){if(!Sl(e,t,u.clientSecret))return;U.current=null,_("idle"),l({id:vt.paymentMethodId,type:"card",threeDSecureActionResultTokenId:vt.intentId},{...u.accountPatch?{accountPatch:u.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(vt.kind==="terminal"){zi(e,t,u.clientSecret),U.current=null,_("idle"),me(u.paymentMethodType),Ae(!0),G();return}_("blocked")}catch{x||_("blocked")}finally{ce=!1}}};return U.current=B,_("blocked"),()=>{x=!0,U.current===B&&(U.current=null)}},[t,l,G,e,N]);let Xt=(0,i.useCallback)(async u=>{let x=!1,ce=Ve=>{x||(x=!0,u.paymentFailed({reason:"fail",...Ve?{message:Ve}:{}}))};if(!N||!ne){ce();return}let B=he.current.get(V);if(B&&!rt(B.generation)){he.current.delete(V),ce();return}if(!B&&je()){ce();return}if(B&&!ae(B.generation)){ce();return}B||ae();let X=u.expressPaymentType??B?.method??$.current,vt=B??null,Ge=_l(X),Ye;X==="apple_pay"?Ye="apple_pay":X==="google_pay"&&(Ye="google_pay");let xt=B?.generation??pt.current,se=pe,mn=se?.now()??globalThis.performance?.now()??Date.now(),et=new AbortController,Ft=!1,Rn=!1,Vt=null,ze=e,zt="processing",hn="other",bn="provider_runtime",wn,On=new Promise((Ve,xe)=>{wn=xe}),vn=window.setTimeout(()=>{Ft=!0,et.abort(),wn(qa)},Sd),Ht=async(Ve,xe,Ln)=>{zt=Ve,hn=xe,bn=xe==="intent_create"||xe==="session_claim"?"transport_error":"provider_runtime";let kt=se?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Ln,On])}finally{let Cn=se?.now()??globalThis.performance?.now()??Date.now();se?.performance({stage:Ve,durationMs:Math.max(0,Cn-kt),durationMode:"machine",requestCategory:xe,paymentMethodCategory:"wallet",provider:"stripe",...Ft?{statusClass:"timeout"}:{}})}};try{if(lt(!0),c?.(null),!vt&&b){let z=await Ht("processing","other",b(Ge));if(!z.proceed){ce();return}vt={accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}}let Ve=vt?.sessionId??e;ze=Ve;let xe=vt?.nonce??t,Ln=nt.current??vt?.accountPatch,kt=Ol({event:u,fallbackEmail:Ln?.email??n,fallbackName:[Ln?.firstName,Ln?.lastName].join(" ").trim()||T});if(!(0,m.isValidEmail)(kt.email)){ce("Buyer details are required."),De(Vi(X),kt).then(z=>{z&&(nt.current=z)});return}nt.current=null;let Cn={...vt?.accountPatch,...Dn(kt,!0)};await Ht("processing","session_claim",Promise.resolve(w?.(kt)));let{error:_n}=await Ht("tokenization","provider_sdk",ne.submit());if(_n){ce(),ht(X,_n,"stripe_wallet_submit_failed",B?.generation);return}if(!Ve)throw new Error("Missing sessionId or email for payment.");let Kn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:X,paymentMethodId:null,intentKind:o},Kt=JSON.stringify({sessionId:Ve,nonce:xe??"",request:Kn}),Zt=Qe.current,ln=Zt?.retryIdentity===Kt?Zt.authorizationAttemptId:(0,m.randomUuidV4)();Qe.current={authorizationAttemptId:ln,retryIdentity:Kt};let It=await Ht("processing","intent_create",Ha(r,H,Ve,xe??"",{...Kn,authorizationAttemptId:ln},{signal:et.signal}));if(It.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Mt=It.clientSecret,yn=Id({createdAt:Date.now(),sessionId:Ve,...xe?{nonce:xe}:{},clientSecret:Mt,providerObjectId:It.providerObjectId,paymentMethodType:X,accountPatch:Cn});window.clearTimeout(vn),Rn=!0,se?.performance({stage:"callback",durationMs:Math.max(0,(se?.now()??globalThis.performance?.now()??Date.now())-mn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Qt=se?.now()??globalThis.performance?.now()??Date.now(),Ut={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Ye?{walletType:Ye}:{},attempt:xt},Wt=!1,Tt=null;se?.log({name:"payment.provider_confirmation.started",...Ut}),Vt=window.setTimeout(()=>{Vt!==null&&Ne.current.delete(Vt),Wt=!0;let z=se?.now()??globalThis.performance?.now()??Date.now();se?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Ut,operationOutcome:"watchdog_expired",durationMs:Math.max(0,z-Qt),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),se?.flush?.().catch(()=>{}),Tt?.()},wd),Ne.current.add(Vt);let re=(z,Ct)=>{Vt!==null&&(window.clearTimeout(Vt),Ne.current.delete(Vt),Vt=null);let at=se?.now()??globalThis.performance?.now()??Date.now(),q=Math.max(0,at-Qt),Je=z;Wt&&(z==="resolved"?Je="resolved_late":z==="returned_error"?Je="returned_error_late":Je="rejected_late");let le=Ct??(z==="resolved"?"approved":"provider_error");return se?.log({name:"payment.provider_confirmation.returned",...Ut,operationOutcome:Je,terminalReason:le}),se?.performance({...Ut,durationMs:q,durationMode:"buyer",operationOutcome:Je,terminalReason:le}),{durationMs:q,operationOutcome:Je,terminalReason:le}},en=!1,tn=!1,sr=z=>{if(!z||typeof z!="object")return null;let Ct=z;if(Ct.error)return null;let at=Ct.setupIntent??Ct.paymentIntent,q=Ui(at??null,void 0,!!Ct.setupIntent);return q.kind==="confirmed"?q:null},hr=z=>{if(en||B&&pt.current!==B.generation)return;let Ct=sr(z);if(!Ct)return;if(yn&&!Sl(Ve,xe,Mt)){en=!0;return}let{intentId:at,paymentMethodId:q}=Ct;en=!0,tn=!0,Qe.current=null,U.current=null,Oe.current&&(_("idle"),lt(!1));let Je=`${Bl}:${Ve}`;if(typeof window<"u")try{localStorage.setItem(Je,JSON.stringify({createdAt:Date.now(),sessionId:Ve,nonce:xe,accountPatch:Cn,paymentMethodId:q,providerIntentId:at,paymentMethodType:X}))}catch{}try{l({id:q,type:"card",threeDSecureActionResultTokenId:at},{accountPatch:Cn,paymentMethodCategory:"wallet",sessionId:Ve,nonce:xe})}finally{if(typeof window<"u")try{localStorage.removeItem(Je)}catch{}}},Wn=!1;Tt=async()=>{if(!(Wn||en||tn)){Wn=!0,Oe.current&&_("checking");try{let z=await wl(N,Mt,Ne.current);if(en||tn)return;let Ct=(0,m.isSetupIntentClientSecret)(Mt),at=Ui(z,It.providerObjectId,Ct);if(at.kind==="confirmed"){hr(Ct?{setupIntent:z}:{paymentIntent:z});return}if(at.kind==="terminal"){if(tn=!0,zi(Ve,xe,Mt),Qe.current=null,U.current=null,!Oe.current)return;_("idle"),ce(),ht(X,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",B?.generation,!0);return}Oe.current&&!tn&&(_("blocked"),lt(!1))}catch{Oe.current&&!tn&&(_("blocked"),lt(!1))}finally{Wn=!1}}},U.current=Tt;let Gt,lr;try{let z=await((0,m.isSetupIntentClientSecret)(Mt)?N.confirmSetup({elements:ne,clientSecret:Mt,redirect:"if_required"}):N.confirmPayment({elements:ne,clientSecret:Mt,redirect:"if_required"}));if(!z||typeof z!="object"||(Gt=z,!Gt.error&&!sr(Gt)))throw Ni;lr=re(Gt.error?"returned_error":"resolved",Gt.error&&jo(Gt.error)?"provider_declined":void 0)}catch(z){let Ct=z===Ni,at=re(Ct?"returned_error":"rejected");if(se?.error({...Ct?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Pi(z),...Ut,operationOutcome:at.operationOutcome,durationMs:at.durationMs,statusClass:"unknown",terminalReason:at.terminalReason}),!Oe.current||en)return;await Tt?.();return}let qt=Gt.error;if(qt){if(!Oe.current||en)return;if(jo(qt)){tn=!0,zi(Ve,xe,Mt),Qe.current=null,U.current=null,_("idle");let z=qt.message??"Your payment was declined.";ce(z),c?.(z),f?.(dn(Ge,z,{code:Ir(qt),declineCode:go(qt)})),Ka({billingApiUrl:r,sessionId:Ve,nonce:xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:X,providerDeclineReason:Ir(qt)??"provider_declined",...It.intentKind==="payment"&&It.providerObjectId.startsWith("pi_")?{providerIntentId:It.providerObjectId}:{}}})}else se?.error({...Pi(qt),...Ut,operationOutcome:lr.operationOutcome,durationMs:lr.durationMs,statusClass:"unknown",terminalReason:lr.terminalReason}),await Tt?.();return}if(hr(Gt),!en)throw new Error("Invalid provider returned for APM intent")}catch(Ve){if(Ve===qa){let xe=se?.now()??globalThis.performance?.now()??Date.now();se?.error({errorCode:_d(hn),stage:zt,requestCategory:hn,paymentMethodCategory:"wallet",provider:"stripe",...Ye?{walletType:Ye}:{},operationOutcome:"watchdog_expired",checkoutSessionId:ze,durationMs:Math.max(0,xe-mn),statusClass:"timeout",failureCategory:bn,attempt:xt,terminalReason:"provider_error"}),se?.flush?.().catch(()=>{})}ce(),ht(X,Ve,Ve===qa?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",B?.generation,Ve===qa)}finally{if(window.clearTimeout(vn),Vt!==null&&(window.clearTimeout(Vt),Ne.current.delete(Vt)),!Rn){let Ve=se?.now()??globalThis.performance?.now()??Date.now();se?.performance({stage:"callback",durationMs:Math.max(0,Ve-mn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Ft?{statusClass:"timeout"}:{}})}Oe.current&&lt(!1)}},[N,ne,e,t,n,T,De,w,r,H,o,l,c,f,b,ht,ae,rt,je,pt,pe,V]),qe=(0,i.useMemo)(()=>{let u=["applePay","googlePay","paypal","link","amazonPay","klarna"],x=new Set(["applePay","googlePay"]),ce=new Set(a.map(m.stripeExpressMethodToOptionKey)),B={};for(let X of u)ce.has(X)?B[X]=x.has(X)?"always":"auto":B[X]="never";return B},[a]),pn=(0,i.useMemo)(()=>a.map(m.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Nl,{state:we,placeholderTestId:"flopay-wallet-placeholder",borderRadius:P,children:(0,d.jsxs)("div",{ref:Ce,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Ke&&(0,d.jsxs)("button",{ref:tt,type:"button","data-testid":"flopay-wallet-retry-button",onClick:D,style:ji,children:["Try ",Vi(ie)," again"]}),We!=="idle"&&(0,d.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,d.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,d.jsx)("button",{type:"button",onClick:mt,disabled:We==="checking",style:ji,children:We==="checking"?"Checking payment status\u2026":"Check payment status"})]}),ve&&(0,d.jsx)(fo,{identity:ve.identity,methodLabel:ve.methodLabel,onComplete:gt,onCancel:()=>gt(null)},ve.id),We==="idle"&&(0,d.jsx)("div",{style:{display:ve?"none":void 0},children:(0,d.jsx)(jt.ExpressCheckoutElement,{onReady:u=>{ge(Ll(u,pn))},onLoadError:u=>{ge("load_error"),Wi(pe,"stripe","wallet","provider_error")},onClick:async u=>{$.current=u.expressPaymentType,ut.current=_l(u.expressPaymentType);let x=!0,ce=window.setTimeout(()=>{x=!1,u.reject()},Pd),B=b?await b(ut.current):{proceed:!0};if(window.clearTimeout(ce),!x)return;if(!B.proceed){he.current.delete(V),u.reject();return}let X=bt(u.expressPaymentType);he.current.set(V,{generation:X,method:u.expressPaymentType,accountPatch:B.accountPatch,sessionId:B.sessionId,nonce:B.nonce}),Ae(!1),pe?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:X,...u.expressPaymentType==="apple_pay"||u.expressPaymentType==="google_pay"?{walletType:u.expressPaymentType}:{}}),p?.(ut.current),u.resolve()},onConfirm:Xt,onCancel:()=>{let u=he.current.get(V);he.current.delete(V),pe?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...u?{attempt:u.generation}:{}}),de(u?.generation),Qe.current=null,Ae(!1),Ie.current=!0,G()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:qe,emailRequired:Ue,billingAddressRequired:Ue,layout:{maxColumns:1,overflow:"never"}}},V)})]})}),be&&(0,d.jsx)(ar,{status:"processing"})]})}function zl(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function jd({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:c,borderColor:p,textColor:f,borderRadius:g,fontFamily:b}){let T=(0,m.resolveStripeMethodBrandVariant)(e,t),w=dl[e],[S,P]=(0,i.useState)(!1),F=!!w&&!S,fe=T?.backgroundColor??c??"#ffffff",R=T?.borderColor??p??"#d1d5db",H=T?.textColor??f??"#262833";return(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Va,padding:"0 1rem",backgroundColor:fe,color:H,border:`1px solid ${R}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"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:n?(0,d.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,m.getStripeMethodDisplayName)(e)}\u2026`}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,m.hasVendoredStripeMethodLogo)(e)?8:0},children:[F?(0,d.jsx)("img",{src:w,alt:"","aria-hidden":"true",onError:()=>P(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!F&&T?.logoSvg?(0,d.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:T.logoSvg}}):null,(0,d.jsx)("span",{children:(0,m.getStripeMethodDisplayName)(e)})]}),a&&(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:H,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,d.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Hi({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:c,onErrorChange:p,onDecline:f,onCancel:g,runBeforeButtonClick:b,onButtonClick:T,isProcessing:w,submitButtonColor:S,submitButtonBorderRadius:P,submitButtonStyle:F,errorText:fe}){let R=Br(),{emitInstrument:H}=(0,i.useContext)(rr),N=(0,jt.useStripe)(),ne=(0,jt.useElements)(),[pe,we]=(0,i.useState)(!1),ge=(0,i.useRef)(!1),[be,lt]=(0,i.useState)(!1),[Ue,ve]=(0,i.useState)("loading"),[De,gt]=(0,i.useState)(""),Ce=!(0,m.isValidEmail)(r?.trim()),tt=!Ce||(0,m.isValidEmail)(De.trim()),V=(0,i.useCallback)(async()=>{if(!N||!ne||w||ge.current||!be)return;ge.current=!0,we(!0);let Te=b?await b("card"):{proceed:!0};if(!Te.proceed){ge.current=!1,we(!1);return}T?.("card");let Ke=Te.sessionId??t,Ae=Te.nonce??n,We=Wr(o?.trim()),_=Dn({email:Te.accountPatch?.email?.trim()||r?.trim()||De.trim(),firstName:Te.accountPatch?.firstName?.trim()||We.firstName,lastName:Te.accountPatch?.lastName?.trim()||We.lastName}),ie=_.email,me=Dn({...Te.accountPatch,..._});try{if(p?.(null),!(0,m.isValidEmail)(ie))throw new Error("A valid email address is required for payment.");await a?.(_);let U=await ne.submit();if(U.error){p?.(U.error.message??"Payment failed.");return}let Oe=[_.firstName,_.lastName].filter(Boolean).join(" "),Ie=await N.createPaymentMethod({elements:ne,params:{billing_details:{email:ie,...Oe?{name:Oe}:{}}}});if(Ie.error||!Ie.paymentMethod){p?.(Ie.error?.message??"Failed to create payment method.");return}let $=Ie.paymentMethod;if(!Ke||!ie)throw new Error("Missing sessionId or email for payment.");let ut=$.type||e,nt=await Ha(l,H,Ke,Ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ut,paymentMethodId:null,intentKind:"payment"});if(nt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Qe=nt.clientSecret;if(typeof window<"u")try{localStorage.setItem(_r,JSON.stringify({clientSecret:Qe,sessionId:Ke,nonce:Ae,accountPatch:me,paymentMethodId:$.id,paymentMethodType:$.type??e,gateway:"stripe"}))}catch{}let{error:Ne,paymentIntent:he}=await N.confirmPayment({clientSecret:Qe,confirmParams:{return_url:window.location.href,payment_method:$.id},redirect:"if_required"});if(Ne){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let de=Ne.message??"Payment failed.";p?.(de),f?.(dn("card",de,{code:Ne.code})),await Ka({billingApiUrl:l,sessionId:Ke,nonce:Ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ne.code??"provider_declined"}});return}let bt=he?.status;if(!qo(bt)){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let de=bt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(de),f?.(dn("card",de,{code:bt??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let ae=typeof he?.payment_method=="string"?he.payment_method:he?.payment_method?.id;c({id:ae??$.id,type:"card",threeDSecureActionResultTokenId:he?.id,gateway:"stripe",paymentMethodType:$.type??e},{accountPatch:me,paymentMethodCategory:"apm",sessionId:Ke,nonce:Ae})}catch(U){p?.(U instanceof Error?U.message:"Payment failed. Please try again.")}finally{ge.current=!1,we(!1)}},[N,ne,w,be,b,T,t,n,r,o,De,a,l,H,e,c,p,f]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Ce&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Ce&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:De,onChange:Te=>gt(Te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(jt.PaymentElement,{onReady:()=>ve("ready"),onLoadError:()=>{ve("load_error"),Wi(fn(R),"stripe","apm")},onChange:Te=>{lt(!!Te.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,m.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{V()},disabled:!be||!tt||pe||w||Ue!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:S,color:"white",border:"none",borderRadius:P,fontSize:"1rem",fontWeight:600,cursor:!be||!tt||pe||w||Ue!=="ready"?"not-allowed":"pointer",opacity:!be||!tt||pe||w||Ue!=="ready"?.5:1,transition:"opacity 120ms ease-out",...F??{}},children:pe?"Processing\u2026":`Pay with ${(0,m.getStripeMethodDisplayName)(e)}`}),fe&&(0,d.jsx)(bo,{margin:"0.75rem 0 0",children:fe})]})}function Ml({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:c,paymentElementBaseOptions:p,onTokenizedBody:f,onErrorChange:g,onButtonClick:b,onDecline:T,runBeforeButtonClick:w,onLoadStateChange:S,isProcessing:P=!1,submitButtonColor:F="#4A49FF",submitButtonBorderRadius:fe=8,submitButtonStyle:R,buttonAppearance:H,themeId:N,onExpandApm:ne,expandedApmMethod:pe}){let{emitInstrument:we}=(0,i.useContext)(rr),[ge,be]=(0,i.useState)(null),[lt,Ue]=(0,i.useState)(null),ve=(0,i.useRef)(!1),{request:De,collect:gt,finish:Ce}=yo();(0,i.useEffect)(()=>{l.length>0&&c?S?.("ready"):c||S?.("loading")},[l.length,c,S]);let tt=(0,i.useCallback)(async _=>{if(!c||ve.current||P)return;ve.current=!0,Ue(_);let ie=w?await w("card"):{proceed:!0};if(!ie.proceed){ve.current=!1,Ue(null);return}b?.("card");let me=ie.sessionId??e,U=ie.nonce??t,Oe=Wr([ie.accountPatch?.firstName,ie.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ie=Dn({email:ie.accountPatch?.email?.trim()||n?.trim(),firstName:ie.accountPatch?.firstName?.trim()||Oe.firstName,lastName:ie.accountPatch?.lastName?.trim()||Oe.lastName});if(!(0,m.isValidEmail)(Ie.email)){Ue(null);let nt=await gt((0,m.getStripeMethodDisplayName)(_),Ie);if(!nt){ve.current=!1;return}Ie=nt,Ue(_)}let $=Ie.email,ut=Dn({...ie.accountPatch,...Ie});try{if(g?.(null),!me||!(0,m.isValidEmail)($))throw new Error("Missing sessionId or email for payment.");await o?.(Ie);let nt=await Ha(a,we,me,U??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,paymentMethodId:null,intentKind:"payment"});if(nt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Qe=nt.clientSecret;if(typeof window<"u")try{localStorage.setItem(_r,JSON.stringify({clientSecret:Qe,sessionId:me,nonce:U,accountPatch:ut,paymentMethodType:_,gateway:"stripe"}))}catch{}let{error:Ne,paymentIntent:he}=await c.confirmPayment({clientSecret:Qe,confirmParams:{return_url:window.location.href,payment_method_data:{type:_,billing_details:{name:[Ie.firstName,Ie.lastName].filter(Boolean).join(" "),...$?{email:$}:{}}}},redirect:"if_required"});if(Ne){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let de=Ne.message??"Payment failed.";g?.(de),T?.(dn("card",de,{code:Ne.code})),await Ka({billingApiUrl:a,sessionId:me,nonce:U,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,providerDeclineReason:Ne.code??"provider_declined"}});return}let bt=he?.status;if(!qo(bt)){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let de=bt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(de),T?.(dn("card",de,{code:bt??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let ae=typeof he?.payment_method=="string"?he.payment_method:he?.payment_method?.id;f({id:ae??he?.id,type:"card",threeDSecureActionResultTokenId:he?.id,gateway:"stripe",paymentMethodType:_},{accountPatch:ut,paymentMethodCategory:"apm",sessionId:me,nonce:U})}catch(nt){g?.(nt instanceof Error?nt.message:"Payment failed. Please try again.")}finally{ve.current=!1,Ue(null)}},[c,P,w,b,e,t,n,gt,a,we,r,o,f,g,T]),[V,Te]=(0,i.useState)(null),Ke=ne?pe??null:V,Ae=(0,i.useCallback)(_=>{ve.current||P||Ke&&Ke!==_||((0,m.needsStripeMethodExplicitConfirm)(_)?ne?ne(_):Te(_):tt(_))},[Ke,P,tt,ne]),We=(0,i.useMemo)(()=>V?zl(p,V):null,[V,p]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:De?(0,d.jsx)(fo,{identity:De.identity,methodLabel:De.methodLabel,onComplete:Ce,onCancel:()=>Ce(null)},De.id):l.map(_=>{let ie=pe===_,me=lt===_,U=lt!==null&&lt!==_||pe!=null&&pe!==_;return(0,d.jsxs)(i.default.Fragment,{children:[(0,d.jsx)(jd,{method:_,themeId:N,submitting:me,disabled:U,highlighted:ie,hasNextStep:(0,m.needsStripeMethodExplicitConfirm)(_),onClick:()=>Ae(_),backgroundColor:H?.backgroundColor,borderColor:H?.borderColor,textColor:H?.textColor,borderRadius:H?.borderRadius,fontFamily:H?.fontFamily}),!ne&&V===_&&We&&c&&(0,d.jsx)(jt.Elements,{stripe:c,options:We,children:(0,d.jsx)(Hi,{method:_,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:f,onErrorChange:g,onDecline:T,onCancel:()=>Te(null),runBeforeButtonClick:w,onButtonClick:b,isProcessing:P,submitButtonColor:F,submitButtonBorderRadius:fe,submitButtonStyle:R})},_)]},_)})})}function Vd({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:l,onError:c,onDecline:p,onTokenizedBody:f,firstName:g,lastName:b,chv:T,className:w,submitLabel:S,isProcessing:P,error:F,onErrorChange:fe,showPayPal:R=!0,showStripe:H=!0,enabledPaymentMethods:N,enabledPaymentMethodCountries:ne,showApplePay:pe=!0,showGooglePay:we=!0,layout:ge="default",theme:be,buttonsTheme:lt,buttonsStyles:Ue,appearance:ve,cardButtonContent:De,cardBackButtonContent:gt,cardTitleContent:Ce,showSecurityFooter:tt,onButtonClick:V,onBeforeButtonClick:Te,onBuyerIdentityReady:Ke,enableAVS:Ae,cardFieldOrder:We,cardPreFormSlot:_,avsLayout:ie="row",country:me,zip:U,addressLine1:Oe,addressLine2:Ie,city:$,state:ut,onCountryChange:nt,onZipChange:Qe,avsCheck:Ne,checkoutType:he,checkoutLayout:bt,totalAmount:ae=0,currency:de="usd",initialCardOpen:je=!1,directPaypal:rt,isSubscription:pt=!1,session:G,dataAttachmentPending:ht=!1,dataAttachmentRequiresIdentity:ot=!1,debug:D=!1}){let mt=Br(),Xt=wa(),qe=(0,i.useContext)(pr),{emitInstrument:pn}=(0,i.useContext)(rr),u=(0,i.useRef)(null);u.current||(u.current=Ra());let x=u.current,ce=(0,i.useRef)(null);ce.current||(ce.current=Ho());let B=ce.current,X=(0,i.useMemo)(()=>({browser:B,capability:x,presentationMode:"popup"}),[B,x]),vt=G??qe.session,Ge=vt?.gateways?.paypal?.providerObjectType??rt?.providerObjectType,Ye=ht||qe.claimPending===!0,xt=ot||qe.claimRequiresIdentity===!0,se=Ye&&!xt,mn=Ys(),et=n||mn,[Ft,Rn]=(0,i.useState)(!1),[Vt,ze]=(0,i.useState)(null),[zt,hn]=(0,i.useState)(me??"US"),[bn,wn]=(0,i.useState)(U??""),[On,vn]=(0,i.useState)(Oe??""),[Ht,Ve]=(0,i.useState)(Ie??""),[xe,Ln]=(0,i.useState)($??""),[kt,Cn]=(0,i.useState)(ut??""),[_n,Kn]=(0,i.useState)(""),[Kt,Zt]=(0,i.useState)({}),ln=(0,i.useRef)(U??""),It=(0,i.useRef)(me??"US"),Mt=(0,i.useRef)(Oe??""),yn=(0,i.useRef)(Ie??""),Qt=(0,i.useRef)($??""),Ut=(0,i.useRef)(ut??""),Wt=(0,i.useRef)(""),Tt=(0,i.useRef)({});(0,i.useEffect)(()=>{let s=(k,W,Ee,te,yt)=>{if(Tt.current[k])return;let it=W?.trim();!it||it===Ee.current||(Ee.current=it,te(it),yt?.(it))};s("country",me,It,hn,nt),s("zip",U,ln,wn,Qe),s("addressLine1",Oe,Mt,vn),s("addressLine2",Ie,yn,Ve),s("city",$,Qt,Ln),s("state",ut,Ut,Cn)},[me,U,Oe,Ie,$,ut,nt,Qe]);let re=(0,i.useMemo)(()=>(0,m.resolveAVSConfig)(Ae),[Ae]),en=re!==null,tn=(0,i.useMemo)(()=>(0,m.isAuthorizationOnlySession)(G),[G]),sr=!!G?.vault?.html,hr=!!G?.gateways?.pcivault,Wn=bi(G),lr=!!(G?.gateways?.stripe?.enabledPaymentMethods??N)?.includes("card")||Or(G),qt=sr||lr||hr,z=!!(H&&qt&&e),[Ct,at]=(0,i.useState)(()=>ge!=="buttons"||je?e??null:null),[q,Je]=(0,i.useState)(0),le=ge!=="buttons"||je||!!e&&Ct===e,nn=G?.captureMethod,Pn=(0,i.useRef)(mt);(0,i.useEffect)(()=>{Pn.current=mt},[mt]);let[rn,br]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!z||!e||!le){br(null);return}let s=Pn.current?Pn.current.cardCapture({sessionId:e,captureMethod:nn}):new yr.PciVaultCardCapture({sessionId:e,captureMethod:nn,billingApiUrl:et,telemetry:r});return br({sessionId:e,captureMethod:nn,billingApiUrl:et,telemetry:r,capture:s}),()=>{s.unmount()}},[z,e,le,nn,et,r]);let Re=z&&e&&le&&rn?.sessionId===e&&rn.captureMethod===nn&&rn.billingApiUrl===et&&rn.telemetry===r?rn.capture:null,Nn=(0,i.useMemo)(()=>{let s=zt,k=re?(0,m.isAVSFieldVisible)(re.postal_code,s):!1;return Ud(s,bn,k)},[re,zt,bn]),{avsInvalid:Gn,invalidAvsFields:Ur}=(0,i.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!z||!re)return{avsInvalid:!1,invalidAvsFields:s};let k=zt,W=(yt,it)=>(0,m.isAVSFieldVisible)(yt,k)&&!it.trim(),Ee={line1:W(re.address_line_1,On),city:W(re.city,xe),state:W(re.state,kt),zip:Nn.empty||Nn.malformed};return{avsInvalid:Ee.line1||Ee.city||Ee.state||Ee.zip,invalidAvsFields:Ee}},[z,re,zt,On,xe,kt,Nn]),[Yn,Jn]=(0,i.useState)(!1),[Yt,Ar]=(0,i.useState)(!1),[vr,En]=(0,i.useState)(!1),[Cr,Xn]=(0,i.useState)({line1:!1,city:!1,state:!1}),Zn=(0,i.useRef)(!1),Pr=(0,i.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Qn=(0,i.useRef)(!1),Rt=(0,i.useCallback)(s=>{Pr.current[s]=!0,Qn.current=!0},[]),zn=(0,i.useCallback)(s=>!Zn.current&&Pr.current[s],[]),cr=(0,i.useCallback)(s=>{zn(s)&&Xn(k=>k[s]?k:{...k,[s]:!0})},[zn]),[Un,Sn]=(0,i.useState)(()=>qi(G?.vault)),[ct,kn]=(0,i.useState)(je&&qt?"card":"buttons"),[cn,qn]=(0,i.useState)(null),qr=ct==="expanding"||ct==="card",$n=G?.gateways?.stripe&&!Wn?"stripe":void 0,Sr=(0,i.useCallback)(()=>{pn?.({class:"card_surface",provider:$n})},[$n,pn]),Tn=(0,i.useRef)(null),An=(0,i.useCallback)(s=>{Tn.current&&clearTimeout(Tn.current),Tn.current=setTimeout(()=>{Tn.current=null,s()},oa)},[]);(0,i.useEffect)(()=>()=>{Tn.current&&clearTimeout(Tn.current)},[]);let $r=(0,i.useCallback)(()=>{Sr(),at(e??null),Je(s=>s+1),kn("expanding"),An(()=>kn("card"))},[An,Sr,e]),jn=(0,i.useCallback)(()=>{kn("collapsing"),An(()=>kn("buttons"))},[An]),jr=(0,i.useCallback)(s=>{qn(s),kn("apm-expanding"),An(()=>kn("apm-form"))},[An]),on=(0,i.useCallback)(()=>{kn("apm-collapsing"),An(()=>{kn("buttons"),qn(null)})},[An]);(0,i.useEffect)(()=>{ge==="buttons"&&je&&qt&&(at(e??null),kn("card"))},[ge,je,qt,e]);let[M,v]=(0,i.useState)(null),ee=(0,i.useRef)(!1),K=(0,i.useRef)(null),_e=(0,i.useRef)("idle"),[Ot,Se]=(0,i.useState)(!1),Pe=(0,i.useRef)(Ot);Pe.current=Ot;let[O,Z]=(0,i.useState)(()=>rt?.existingOrderId?{orderId:rt.existingOrderId,attempts:1}:null),h=(0,i.useRef)(O);(0,i.useEffect)(()=>{h.current=O},[O]);let y=(0,i.useRef)(null),E=(0,i.useMemo)(()=>{if(Ke||qe.claimBuyerIdentity||G?.buyerIdentified!==!1||!e||!t)return;let s=`${et}|${e}|${t}`;y.current?.key!==s&&(y.current={key:s,claim:po(new yr.PaymentAPI(et,{telemetry:!1}),e,t,{...a?{userId:a}:{},...g?{firstName:g}:{},...b?{lastName:b}:{}})});let k=y.current.claim;return async W=>{await k(W)}},[Ke,qe.claimBuyerIdentity,G?.buyerIdentified,e,t,et,a,g,b]),j=Ke??qe.claimBuyerIdentity??E,ye=F??Vt,oe=(0,i.useMemo)(()=>(0,m.resolveTheme)(be),[be]),J=(0,i.useMemo)(()=>{let s=oe?.buttonsLayout??(0,m.resolveButtonsLayoutTheme)(lt);return Ue?{...s,...Ue,cardButton:{...s.cardButton,...Ue.cardButton},cardFormContainer:{...s.cardFormContainer,...Ue.cardFormContainer},backButton:{...s.backButton,...Ue.backButton},backButtonIcon:{...s.backButtonIcon,...Ue.backButtonIcon},submitButton:{...s.submitButton,...Ue.submitButton},title:{...s.title,...Ue.title}}:s},[oe,lt,Ue]),ue=ve??oe?.appearance,Me=(0,i.useMemo)(()=>Ua({appearance:ue,buttonsStyles:J,layout:ge}),[ue,J,ge]),St=qe.inlineSessionPatchProcessing??!1,Le=(P??Ft)||St,Q=et.replace(/\/+$/,""),L=(0,i.useMemo)(()=>Ci({userId:a,email:o,firstName:g,lastName:b,country:me,zip:U},Kt),[a,o,g,b,me,U,Kt]),Y=[L.firstName,L.lastName].filter(s=>!!s?.trim()).join(" "),Be=!(0,m.isValidEmail)(L.email?.trim()),Fe=(0,i.useRef)(null);z&&Fe.current===null&&(Fe.current=Be);let Pt=z&&(Fe.current??Be),Xe=(0,i.useMemo)(()=>qd(_n,Pt),[_n,Pt]),xn=Xe.empty||Xe.malformed,an=(0,i.useMemo)(()=>mt?mt.getRawProvider():null,[mt]),Qr=(0,i.useMemo)(()=>Xt?Xt.getRawProvider():null,[Xt]),Eo=ae||100,eo=de.toLowerCase(),ei=(0,i.useMemo)(()=>ue?(0,yr.toStripeAppearance)(ue):null,[ue]),to=ei,ns=(0,i.useMemo)(()=>{let s=ei??{},k=s.rules??{};return{...s,rules:{...k,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...k[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...k[".AccordionItemContents"]??{}}}}},[ei]),rs=(0,i.useMemo)(()=>({...Vs(ae,G?.captureMethod),currency:eo,...to?{appearance:to}:null}),[ae,eo,G?.captureMethod,to]),os=(0,i.useMemo)(()=>({mode:"payment",amount:Eo,currency:eo,captureMethod:"manual",setupFutureUsage:"off_session",...to?{appearance:to}:null}),[Eo,eo,to]),ke=(0,i.useCallback)(s=>{ze(s),fe?.(s)},[fe]),ti=(0,i.useRef)(""),[as,ec]=(0,i.useState)(!1),ni=(0,i.useCallback)(()=>{ec(!0)},[]);(0,i.useEffect)(()=>{if(!z||!Pt||!j||!as||xn||ti.current)return;let s=Dn({email:(0,m.isValidEmail)(L.email?.trim())?L.email?.trim():Wt.current.trim(),firstName:L.firstName?.trim(),lastName:L.lastName?.trim()});ti.current=JSON.stringify(s),Zt(k=>({...k,...s})),Promise.resolve(j(s)).catch(k=>{ti.current="",ke(k instanceof Error?k.message:"Failed to attach buyer details.")})},[z,Pt,j,as,xn,L.email,L.firstName,L.lastName,ke]),(0,i.useEffect)(()=>{!z||!Re||Re.setCardFieldOrder?.(We??null,re==null&&!Pt)},[z,Re,We,re,Pt]),(0,i.useEffect)(()=>{(ct==="expanding"||ct==="collapsing"||ct==="apm-expanding"||ct==="apm-collapsing")&&ke(null)},[ct,ke]);let wr=(0,i.useCallback)((s,k,W)=>{p?.(dn(s,k,W))},[p]),no=(0,i.useCallback)((s,k,W)=>{let Ee=W?.popupBlocked??zr(k);Ee&&x.markBlocked();let te=Pa(Vi(s),Ee,B.inAppBrowser),yt=Ir(k),it=(yt?.toLowerCase()==="error"?void 0:yt)??Gr(W?.code)??"external_payment_method_failed",tr=new m.FloPayError(te,"api_error",{code:"external_payment_method_failed",param:s,details:{providerCode:it,popupBlocked:Ee,inAppBrowser:B.inAppBrowser,appFamily:B.appFamily,popupCapability:x.current(),presentationMode:W?.presentationMode??"popup"}});W?.telemetryReported||fn(mt)?.error(ko({...X,presentationMode:W?.presentationMode??"popup"},{errorCode:Ee?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:W?.provider??(s==="paypal"?"paypal":"stripe"),paymentMethodCategory:W?.paymentMethodCategory??(s==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:W?.terminalReason??(Ee?"popup_blocked":"provider_error")})),v(null),ge==="buttons"&&(kn("buttons"),qn(null)),ke(te),c?.(tr),console.error("[FloPay] External payment method failed:",{method:s,code:it,popupBlocked:Ee})},[B,X,mt,ge,c,x,ke]);(0,i.useEffect)(()=>{if(!z||!e){Sn(null);return}let s=qi(G?.vault);if(s){Sn(s);return}if(!le){Sn(null);return}Sn(null);let k=!0;return new yr.PaymentAPI(Q).getVaultCapture(e,t).then(W=>{if(!k)return;let Ee=qi(W);Ee?Sn(Ee):ke("Failed to load the secure card form.")}).catch(W=>{k&&ke(W instanceof Error?W.message:"Failed to load the secure card form.")}),()=>{k=!1}},[z,le,q,e,G?.vault,Q,t,ke]);let dr=(0,i.useRef)({onComplete:l,onError:c,updateError:ke,emitDecline:wr,resolvedAccount:L,avsConfig:re,avsCheckProp:Ne,sessionId:e,nonce:t,baseUrl:Q,captureMethod:G?.captureMethod,paymentId:G?.paymentId,authorizationExpiresAt:G?.authorizationExpiresAt,serverSideCardGateway:Wn});dr.current={onComplete:l,onError:c,updateError:ke,emitDecline:wr,resolvedAccount:L,avsConfig:re,avsCheckProp:Ne,sessionId:e,nonce:t,baseUrl:Q,captureMethod:G?.captureMethod,paymentId:G?.paymentId,authorizationExpiresAt:G?.authorizationExpiresAt,serverSideCardGateway:Wn};let ri=(0,i.useRef)(!1),is=(0,i.useCallback)(()=>{let s=dr.current,k=s.resolvedAccount.email?.trim(),W=(0,m.isValidEmail)(k)?k:Wt.current.trim();if(!(0,m.isValidEmail)(W))return null;let Ee=s.resolvedAccount.firstName?.trim(),te=s.resolvedAccount.lastName?.trim(),yt=It.current||s.resolvedAccount.country||"US",it=s.avsConfig?(0,m.isAVSFieldVisible)(s.avsConfig.state,yt):!1,tr=s.avsConfig?(0,m.isAVSFieldVisible)(s.avsConfig.address_line_1,yt):!1,st=s.avsConfig?(0,m.isAVSFieldVisible)(s.avsConfig.postal_code,yt):!1,Bt=s.avsConfig?(0,m.isAVSFieldVisible)(s.avsConfig.city,yt):!1,wt=s.avsConfig?(0,m.isAVSFieldVisible)(s.avsConfig.address_line_2,yt):!1,dt=tr&&!it&&st?(0,m.getStateFromPostalCode)(yt,(ln.current??"").trim()):null,Fn=it?Ut.current:dt;return{accountData:{userId:s.resolvedAccount.userId??"",email:W,...Ee?{firstName:Ee}:{},...te?{lastName:te}:{},...st&&ln.current?{zip:ln.current}:{},...Bt&&Qt.current?{city:Qt.current}:{},...Fn?{state:Fn}:{},...tr&&Mt.current?{addressLine1:Mt.current}:{},...wt&&yn.current?{addressLine2:yn.current}:{},country:yt},...s.avsCheckProp===void 0?{}:{avsCheck:s.avsCheckProp},...s.avsConfig?{avsConfig:{country:(0,m.isAVSFieldVisible)(s.avsConfig.country,yt),postal_code:st,address_line_1:tr,address_line_2:wt,city:Bt,state:it}}:{}}},[]),ss=(0,i.useRef)(Ye);ss.current=Ye,(0,i.useEffect)(()=>{Ye||ye!==kl||dr.current.updateError(null)},[Ye,ye]),(0,i.useEffect)(()=>{!z||!Re||Re.setSubmitGate?.(Gn||Ye||xn||Ot)},[z,Re,Gn,Ye,xn,Ot]),(0,i.useEffect)(()=>{if(!z||!Re)return;ri.current=!1;let s=null,k=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,_e.current="idle",v(null)},400)},W=Re.on("submitting",()=>{Jn(!0),K.current&&clearTimeout(K.current),_e.current="validation-window",K.current=setTimeout(()=>{K.current=null,_e.current==="validation-window"&&(_e.current="processing")},Ed),v("processing");let st=dr.current;if(!st.sessionId||!st.nonce)return;let Bt=is();if(!Bt){st.updateError("Enter a valid email address."),_e.current="idle",v(null);return}new yr.PaymentAPI(st.baseUrl).patchAccountSnapshot(st.sessionId,st.nonce,Bt,{telemetryMode:"best_effort"}).catch(wt=>{if(!Ad(wt))return;let dt=wt instanceof Error?wt.message:"Please check your billing address and try again.";st.updateError(dt),_e.current="idle",v(null),st.onError?.(wt instanceof m.FloPayError?wt:new m.FloPayError(dt,"api_error"))})}),Ee=Re.on("complete",async st=>{if(Po(st.sessionId??dr.current.sessionId),_e.current="terminal",Se(!1),v("success"),await new Promise(Fn=>setTimeout(Fn,600)),ri.current)return;ri.current=!0;let Bt=dr.current,wt=(0,m.isAuthorizationOnlySession)(Bt)||st.outcome==="authorized",dt=Bt.serverSideCardGateway?{}:{paymentIntentId:st.intentId};dr.current.onComplete?.(wt?{status:"authorized",...dt,paymentId:st.paymentId??Bt.paymentId,sessionId:st.sessionId??Bt.sessionId,authorizationExpiresAt:st.authorizationExpiresAt??Bt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...dt,checkoutMethod:"card"})}),te=Re.on("decline",st=>{let Bt=dr.current,wt=st.message??"Your payment was declined. Please try another card or contact your bank.";_e.current="terminal",Se(!1),Bt.updateError(wt),v("error");let dt=st.failureOutcome??(0,m.normalizeCheckoutFailureOutcome)(st.declineReason)??"authorization_declined";Bt.emitDecline("card",wt,{code:dt,declineCode:dt}),k()}),yt=Re.on("error",st=>{let Bt=dr.current,wt=st.message??"There was a problem processing your payment. Please try again.";_e.current="terminal",Se(!1),Bt.updateError(wt),v("error"),Bt.onError?.(new m.FloPayError(wt,"api_error",{code:st.failureOutcome??"capture_failed"})),k()}),it=Re.on("challenge_dismissed",()=>{K.current&&(clearTimeout(K.current),K.current=null),_e.current="processing",Se(!0),v(null)}),tr=Re.on("blocked",()=>{if(Pe.current){dr.current.updateError(Td);return}if(!ss.current){Jn(!0);return}ni(),dr.current.updateError(kl)});return()=>{s&&(clearTimeout(s),s=null),K.current&&(clearTimeout(K.current),K.current=null),_e.current="idle",Se(!1),v(null),W(),Ee(),te(),yt(),it(),tr()}},[z,Re,ni,is]);let kr=!!rt?.clientId,To=Array.isArray(N),la=To&&N.length>0,tc=To&&N.includes("paypal"),{expressMethods:ca,paymentElementMethods:Ao}=(0,i.useMemo)(()=>(0,m.partitionStripeMethods)(N,{excludePaypal:kr}),[N,kr]),ls=kr||!!Xt,nc=(0,i.useMemo)(()=>ls?ca.filter(s=>s!=="paypal"):ca,[ca,ls]),rc=(0,i.useMemo)(()=>{let s=[];return pe&&s.push("apple_pay"),we&&s.push("google_pay"),s},[pe,we]),ro=To?nc:rc,oc=H&&ro.length>0,oi=en?zt:me,da=(0,i.useMemo)(()=>{let s=oi?.trim().toUpperCase();return s?ne?Ao.filter(k=>{let W=ne[k];return!W||W.length===0||W.includes(s)}):(0,m.filterStripeMethodsByCountry)(Ao,oi):Ao},[Ao,oi,ne]),ai=(0,i.useMemo)(()=>({mode:"payment",amount:Eo,currency:eo,paymentMethodCreation:"manual",appearance:ns}),[Eo,eo,ns]),[cs,ds]=(0,i.useState)("loading"),[us,ps]=(0,i.useState)("loading"),[ms,ys]=(0,i.useState)("loading"),[ac,ii]=(0,i.useState)(!1),[fs,si]=(0,i.useState)("loading"),[li,ic]=(0,i.useState)();(0,i.useEffect)(()=>{ic(Ho())},[]);let ua=li?.inAppBrowser,pa=li?ka(li,rt?.approvalPresentation,Ge??(pt?"subscription":"order")):"popup",gs=R&&(kr||(To?tc:ua===!1)),hs=H&&oc,xo=(!se||!!qe.waitForDataAttachment)&&gs&&kr,bs=fs==="retrying"||fs==="exhausted",Mo=!se&&gs&&!!Qr&&(!kr||bs),oo=!se&&hs&&!!an,Bo=!se&&H&&la&&da.length>0&&!!an,sc=xo&&!bs?ac:Mo&&Tl(cs),lc=oo&&Tl(us),cc=Bo&&ms!=="load_error",vs=s=>s==="loading"||s==="ready",Cs=xo||Mo&&vs(cs)||oo&&vs(us)||Bo&&ms!=="load_error",ma=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!ma.current){if(!H&&!R){ma.current=!0;let s=new m.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(s),ke(s.message)}else if(!H&&R&&!kr&&!Qr){ma.current=!0;let s=new m.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(s),ke(s.message)}else if(ua!==void 0&&!se&&!qt&&!Cs){ma.current=!0;let s=new m.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"});c?.(s),ke(s.message)}}},[H,R,kr,Qr,ua,se,qt,Cs,c,ke]);let Ps=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(Ps.current||!la)return;let s=[];pe!==!0&&s.push("showApplePay"),we!==!0&&s.push("showGooglePay"),s.length!==0&&(Ps.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.`))},[la,pe,we]);let Ss=(0,i.useCallback)((s,k)=>qe.applyInlineSessionPatch?qe.applyInlineSessionPatch(s).then(W=>({error:null,sessionId:W.sessionId||e,nonce:W.session?.clientSecret||t})).catch(W=>{let Ee=El(k,W);return ke(Ee.message),c?.(Ee),{error:Ee,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[qe.applyInlineSessionPatch,t,c,e,ke]),ur=(0,i.useCallback)(async s=>{if(s!=="card"&&se&&await qe.waitForDataAttachment?.(),!Te)return{proceed:!0};try{let k=await Te({method:s,sessionId:e||void 0,createSession:qe.inlineSessionDraft});if(k===!1)return{proceed:!1};if(k&&typeof k=="object"){k.account&&Zt(Ee=>({...Ee??{},...k.account}));let W=await Ss(k,s);return W.error?{proceed:!1,accountPatch:k.account}:{proceed:!0,accountPatch:k.account,sessionId:W.sessionId,nonce:W.nonce}}return{proceed:!0}}catch(k){let W=El(s,k);return ke(W.message),c?.(W),{proceed:!1}}},[Ss,qe.inlineSessionDraft,qe.waitForDataAttachment,se,Te,c,e,ke]),ws=(0,i.useCallback)(async(s,k)=>{if(ee.current)return;ee.current=!0,Rn(!0),v("processing"),ke(null);let W=k?.sessionId??e,Ee=k?.nonce??t,te=Ci(L,k?.accountPatch),yt=k?.completionPaymentMethodId??$o(s),it=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,tr=Dd(s),st=()=>{pn?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:tr})};try{let wt=await new yr.PaymentAPI(Q).processPayment(te.userId??"",{sessionId:W,nonce:Ee,paymentMethodCategory:k?.paymentMethodCategory??Ld(s),tokenizedData:it,accountData:{...k?.accountPatch,userId:te.userId??"",email:te.email??"",firstName:te.firstName||void 0,lastName:te.lastName||void 0,...re?(()=>{let _t=It.current,nr=(0,m.isAVSFieldVisible)(re.state,_t),In=(0,m.isAVSFieldVisible)(re.address_line_1,_t),sn=(0,m.isAVSFieldVisible)(re.postal_code,_t),Kr=In&&!nr&&sn?(0,m.getStateFromPostalCode)(_t,(ln.current??"").trim()):null,zo=nr?Ut.current:Kr;return{country:_t,...sn&&ln.current?{zip:ln.current}:{},...(0,m.isAVSFieldVisible)(re.city,_t)&&Qt.current?{city:Qt.current}:{},...zo?{state:zo}:{},...In&&Mt.current?{addressLine1:Mt.current}:{},...(0,m.isAVSFieldVisible)(re.address_line_2,_t)&&yn.current?{addressLine2:yn.current}:{}}})():{}},chv:T,avsCheck:Ne??!1,checkoutType:he,checkoutLayout:bt,avsConfig:re?{country:(0,m.isAVSFieldVisible)(re.country,It.current),postal_code:(0,m.isAVSFieldVisible)(re.postal_code,It.current),address_line_1:(0,m.isAVSFieldVisible)(re.address_line_1,It.current),address_line_2:(0,m.isAVSFieldVisible)(re.address_line_2,It.current),city:(0,m.isAVSFieldVisible)(re.city,It.current),state:(0,m.isAVSFieldVisible)(re.state,It.current)}:void 0});if(wt.ok){let _t=wt.status===204?null:await wt.json().catch(()=>null),nr=(0,m.isAuthorizationOnlySession)(G)||_t?.status==="authorized";Po(W),v("success"),Z(null),await new Promise(Kr=>setTimeout(Kr,600));let In;typeof _t?.paymentId=="string"?In=_t.paymentId:G?.paymentId&&(In=G.paymentId);let sn;typeof _t?.authorizationExpiresAt=="string"?sn=_t.authorizationExpiresAt:G?.authorizationExpiresAt&&(sn=G.authorizationExpiresAt),l?.(nr?{status:"authorized",...In===void 0?{}:{paymentId:In},sessionId:typeof _t?.sessionId=="string"?_t.sessionId:W,...sn===void 0?{}:{authorizationExpiresAt:sn},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:yt,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:yt,checkoutMethod:s.isPaypal?"paypal":"card"});return}let dt=await wt.json().catch(()=>null);if(dt?.type==="paypal_redirect_required"){let _t=dt.threeDSecureToken,nr=dt.paymentMethodId||s.id||"";if(!mt||!_t){v("error"),ke("PayPal authorization required but no token provided.");return}try{let In=Xt?.getRawProvider();if(!In){ke("PayPal is not available.");return}let sn={return_url:window.location.href};nr&&(sn.payment_method=nr);let{error:Kr}=await In.confirmPayment({clientSecret:_t,confirmParams:sn,redirect:"if_required"});if(Kr){v("error");let zo=Kr.message??"PayPal payment failed.";ke(zo),wr("paypal",zo,{code:Kr.code})}}catch(In){v("error"),ke(In instanceof Error?In.message:"PayPal authorization failed.")}return}if(dt?.type==="paypal_direct_required"){let _t=dt.orderId;if(!_t){v("error"),ke("PayPal retry required but no order id provided.");return}let nr=h.current?.attempts??0;if(nr>=2){v("error"),ke("PayPal payment could not be completed after multiple attempts."),wr("paypal","paypal_direct_required retry limit exceeded");return}ii(!1),si("loading"),Z({orderId:_t,attempts:nr+1}),v(null);return}(0,m.classifyPaymentRejection)(wt.status,dt)||st(),v("error");let Fn=dt?.message??"Payment failed. Please try again.";ke(Fn),wr(s.isPaypal?"paypal":"card",Fn,{code:dt?.code??dt?.gatewayErrorCode,declineCode:dt?.declineCode??dt?.gatewayDeclineReason}),await new Promise(_t=>setTimeout(_t,400))}catch(Bt){Dl(Bt)||st(),v("error"),ke(Bt instanceof Error?Bt.message:"An unexpected error occurred"),await new Promise(wt=>setTimeout(wt,400))}finally{Rn(!1),v(null),ee.current=!1}},[Q,e,t,L,re,Ne,he,bt,T,mt,Xt,G,l,ke,wr,pn]),Mn=(0,i.useCallback)((s,k)=>{f?f(s):ws(s,k)},[f,ws]),Fo=`${Bl}:${e}`;(0,i.useEffect)(()=>{if(typeof window>"u")return;let s=localStorage.getItem(Fo);if(!s)return;let k;try{k=JSON.parse(s)}catch{localStorage.removeItem(Fo);return}if(!k||typeof k.createdAt!="number"||Date.now()-k.createdAt<0||Date.now()-k.createdAt>Fl||typeof k.paymentMethodId!="string"||typeof k.providerIntentId!="string"||typeof k.paymentMethodType!="string"||k.sessionId!==e||!t||k.nonce!==t||!ro.includes(k.paymentMethodType)){localStorage.removeItem(Fo);return}localStorage.removeItem(Fo),Mn({id:k.paymentMethodId,type:"card",threeDSecureActionResultTokenId:k.providerIntentId,gateway:"stripe",paymentMethodType:k.paymentMethodType},{...k.accountPatch?{accountPatch:k.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Mn,t,e,Fo,ro]);let ks=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(typeof window>"u"||ks.current)return;let s=new URLSearchParams(window.location.search),k=s.get("payment_intent"),W=s.get("payment_intent_client_secret"),Ee=s.get("redirect_status");if(!k||!W||!mt)return;let te=mt.getRawProvider();if(!te)return;let yt=dt=>{let Fn=localStorage.getItem(dt);if(!Fn)return null;try{return JSON.parse(Fn)}catch{return localStorage.removeItem(dt),null}},it=yt(_r)??yt(Pl),tr;if(it?.clientSecret){if(it.clientSecret!==W)return;tr={...it.accountPatch?{accountPatch:it.accountPatch}:{},...it.sessionId?{sessionId:it.sessionId}:{},...it.nonce?{nonce:it.nonce}:{}}}else if(it?.sessionId&&it.sessionId!==e)return;ks.current=!0,localStorage.removeItem(_r),localStorage.removeItem(Pl);let st=new URL(window.location.href);st.searchParams.delete("payment_intent"),st.searchParams.delete("payment_intent_client_secret"),st.searchParams.delete("redirect_status"),window.history.replaceState({},"",st.toString());let Bt=it?.paymentMethodType??it?.tokenType??"card",wt="card";(async()=>{if(Ee==="failed"){let sn="Payment was declined. Please try again.";ke(sn),wr(wt,sn);return}let{paymentIntent:dt,error:Fn}=await te.retrievePaymentIntent(W);if(Fn){let sn=Fn.message??"Failed to retrieve payment status.";ke(sn),wr(wt,sn,{code:Fn.code});return}let _t=dt?.status,nr=qo(_t);if(!dt||!nr){let sn=_t==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ke(sn),wr(wt,sn,{code:_t??"missing_payment_intent"});return}let In=typeof dt.payment_method=="string"?dt.payment_method:dt.payment_method?.id;Mn({id:In??it?.paymentMethodId??it?.tokenId??dt.id,type:"card",threeDSecureActionResultTokenId:dt.id,gateway:it?.gateway??"stripe",paymentMethodType:Bt},tr)})()},[e,Mn,mt,ke,wr]);let ci=(0,i.useCallback)(s=>{s.preventDefault()},[]);if(!(z||mt!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Do=ge==="buttons",Bn=ue?.variables,dc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),di=Bn?.colorBackground,uc=di&&!dc.has(di)?di:void 0,Oo=J.cardInputBorder??(Do?"#e5e7eb":"#A4A4FF"),Is=Bn?.colorDanger??"#dc2626",Lt=s=>Ur[s]&&(Cr[s]||Yn),ya=xn&&(vr||Yn),er=s=>s?Is:Oo,fa=(Nn.malformed||Nn.empty)&&(Yt||Yn),pc=er(fa),ui=J.cardFormContainer?.backgroundColor??uc??(Do?"white":"#EDEDFF"),ao=J.cardInputBackground??Bn?.colorBackground??"white",pi=lo(gt),Rs=lo(Ce),io=J.nameInput,_s=J.cardInputFontSize??$d(io?.fontSize)??Bn?.fontSizeBase??"16px",Es=typeof io?.fontFamily=="string"?io.fontFamily:Bn?.fontFamily??"Poppins, sans-serif",Ts=Li(io?.fontWeight)??400,mc=J.cardInputColor??(typeof io?.color=="string"?io.color:void 0)??Bn?.colorText??"#262833",yc=J.cardInputPlaceholderColor??"#9ca3af",$t=Bn?.borderRadius??"8px",Vr=Bn?.borderRadius??J.cardButton?.borderRadius??$t,Hr=Bn?.colorPrimary??"#4A49FF",fc=Bn?.colorPrimaryHover??Ro(Hr,.12),mi=Bn?.colorText??"#262833",yi={fontSize:_s,fontFamily:Es,fontWeight:Ts,color:mc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Lo={marginTop:"0.375rem",...yi,fontSize:"0.75rem",lineHeight:1.4,color:Is},gc={"--flopay-input-placeholder-color":yc,"--flopay-input-font-size":_s,"--flopay-input-font-family":Es,"--flopay-input-font-weight":String(Ts)},No=J.cardFormContainer??{},fi=No.padding??(Do?"0":"1rem"),gi=No.borderRadius??$t,hc=Re&&Un?(0,d.jsx)(Io,{capture:Re,html:Un.html,messageToken:Un.messageToken,expectedOrigin:Un.expectedOrigin,theme:Me,submitLabel:S,onReady:()=>{if(!Pt&&!re||typeof document>"u")return;let s=()=>{let W=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(W){Zn.current=!0;try{W.focus()}finally{Zn.current=!1}}};Qn.current||s()},onError:s=>ke(s),onValidation:s=>{let k=_e.current;(k==="idle"||k==="validation-window")&&(ke(s),s&&_e.current==="validation-window"&&(K.current&&(clearTimeout(K.current),K.current=null),_e.current="idle",v(null)))}}):(0,d.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),As=(0,d.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&Sr()},style:{backgroundColor:ui,borderRadius:gi,...No,padding:fi,...gc,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${ft.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),To&&wr&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:$e?-2:0},children:[(0,c.jsxs)("button",{type:"button",onClick:En,style:{display:"inline-flex",alignItems:"center",gap:ti?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:w.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...w.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",...w.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)(io,{content:fe})]}),fs?(0,c.jsx)("div",{style:{flex:1}}):(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:w.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...w.title},children:(0,c.jsx)(Fo,{content:Re})})]}),!To&&!fs&&(0,c.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ni,order:$e?-3:0,...w.title},children:(0,c.jsx)(Fo,{content:Re})}),$e&&M&&(0,c.jsx)("div",{style:{order:-2,width:"100%"},children:M}),$e&&xe&&(0,c.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,c.jsx)("div",{style:{backgroundColor:to,border:`1px solid ${Xn(ia)}`,borderRadius:jt,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:rn,onChange:i=>{ht("email"),Cn.current=i.target.value,kt(i.target.value)},onPointerDown:()=>ht("email"),onKeyDown:()=>ht("email"),onBlur:()=>{_n("email")&&Rn(!0),tt||Ka()},disabled:Ae,required:!0,"aria-invalid":ia||void 0,"aria-describedby":ia?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...ri}})}),ia&&(0,c.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:xo,children:Ie.empty?"Email address is required":"Enter a valid email address"})]}),de&&(0,c.jsx)("div",{style:{order:$e?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=G,R=(te=!1)=>({backgroundColor:to,border:`1px solid ${Xn(te)}`,borderRadius:jt,marginTop:"0.5rem",padding:"10px"}),X=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ri}),Ue=(0,p.getStateOptions)(i);return(0,c.jsxs)(c.Fragment,{children:[(0,p.isAVSFieldVisible)(de.address_line_1,i)&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{style:R(Ut("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:mn,onChange:te=>{ht("line1"),It.current.addressLine1=!0,yn.current=te.target.value,In(te.target.value)},onPointerDown:()=>ht("line1"),onKeyDown:()=>ht("line1"),onBlur:()=>Yn("line1"),disabled:Ae,required:!0,"aria-invalid":Ut("line1")||void 0,"aria-describedby":Ut("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:X()})}),Ut("line1")&&(0,c.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:xo,children:"Street address is required"})]}),(0,p.isAVSFieldVisible)(de.address_line_2,i)&&(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:Bn,onChange:te=>{It.current.addressLine2=!0,zt.current=te.target.value,Fn(te.target.value)},disabled:Ae,"data-testid":"flopay-address-line2",style:X()})}),((0,p.isAVSFieldVisible)(de.city,i)||(0,p.isAVSFieldVisible)(de.state,i))&&(0,c.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,p.isAVSFieldVisible)(de.city,i)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:to,borderTop:`1px solid ${Xn(Ut("city"))}`,borderRight:`1px solid ${Xn(Ut("city"))}`,borderBottom:`1px solid ${Xn(Ut("city"))}`,borderLeft:`1px solid ${Xn(Ut("city"))}`,padding:"10px",borderTopLeftRadius:jt,borderBottomLeftRadius:jt,...(0,p.isAVSFieldVisible)(de.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:jt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Xt,onChange:te=>{ht("city"),It.current.city=!0,xt.current=te.target.value,Ke(te.target.value)},onPointerDown:()=>ht("city"),onKeyDown:()=>ht("city"),onBlur:()=>Yn("city"),disabled:Ae,required:!0,"aria-invalid":Ut("city")||void 0,"aria-describedby":Ut("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:X()})}),(0,p.isAVSFieldVisible)(de.state,i)&&(0,c.jsx)("div",{style:{flex:1,backgroundColor:to,borderTop:`1px solid ${Xn(Ut("state"))}`,borderRight:`1px solid ${Xn(Ut("state"))}`,borderBottom:`1px solid ${Xn(Ut("state"))}`,borderLeft:`1px solid ${Xn(Ut("state"))}`,padding:"10px",borderTopRightRadius:jt,borderBottomRightRadius:jt,...(0,p.isAVSFieldVisible)(de.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Xn(Ut("state")||Ut("city"))}`}:{borderRadius:jt}},children:Ue?(0,c.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Qe,onChange:te=>{ht("state"),It.current.state=!0,Pn.current=te.target.value,wt(te.target.value)},onPointerDown:()=>ht("state"),onKeyDown:()=>ht("state"),onBlur:()=>Yn("state"),disabled:Ae,autoComplete:"billing address-level1",required:!0,"aria-invalid":Ut("state")||void 0,"aria-describedby":Ut("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...X(),cursor:"pointer"},children:[(0,c.jsx)("option",{value:"",children:(0,p.getStateLabel)(i)}),Ue.map(te=>(0,c.jsx)("option",{value:te.code,children:te.name},te.code))]}):(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,p.getStateLabel)(i),autoComplete:"billing address-level1",value:Qe,onChange:te=>{ht("state"),It.current.state=!0,Pn.current=te.target.value,wt(te.target.value)},onPointerDown:()=>ht("state"),onKeyDown:()=>ht("state"),onBlur:()=>Yn("state"),disabled:Ae,required:!0,"aria-invalid":Ut("state")||void 0,"aria-describedby":Ut("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:X()})})]}),Ut("city")&&(0,c.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:xo,children:"City is required"}),Ut("state")&&(0,c.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:xo,children:[(0,p.getStateLabel)(i)," is required"]}),((0,p.isAVSFieldVisible)(de.country,i)||(0,p.isAVSFieldVisible)(de.postal_code,i))&&(0,c.jsxs)("div",{style:{display:"flex",flexDirection:V==="column"?"column":"row",gap:V==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,p.isAVSFieldVisible)(de.country,i)&&(0,c.jsx)("div",{style:{flex:V==="row"?1:void 0,backgroundColor:to,borderTop:`1px solid ${Ao}`,borderRight:`1px solid ${Ao}`,borderBottom:`1px solid ${Ao}`,borderLeft:`1px solid ${Ao}`,padding:"10px",...V==="row"&&(0,p.isAVSFieldVisible)(de.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:jt,borderBottomLeftRadius:jt,borderRight:"none"}:{borderRadius:jt}},children:(0,c.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:G,onChange:te=>{It.current.country=!0,Ot.current=te.target.value,Lt(te.target.value),ot?.(te.target.value),Pn.current="",wt("")},disabled:Ae,autoComplete:"billing country","data-testid":"flopay-country",style:{...X(),cursor:"pointer"},children:p.COUNTRY_OPTIONS.map(te=>(0,c.jsxs)("option",{value:te.code,children:[te.flag," ",te.name]},te.code))})}),(0,p.isAVSFieldVisible)(de.postal_code,i)&&(0,c.jsx)("div",{style:{flex:V==="row"?1:void 0,backgroundColor:to,border:`1px solid ${Zl}`,padding:"10px",...V==="row"&&(0,p.isAVSFieldVisible)(de.country,i)?{borderRadius:"0",borderTopRightRadius:jt,borderBottomRightRadius:jt}:{borderRadius:jt}},children:(0,c.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,p.getPostalCodeLabel)(G),autoComplete:"billing postal-code",value:vn,onChange:te=>{ht("zip"),It.current.zip=!0,At.current=te.target.value,pn(te.target.value),he?.(te.target.value)},onPointerDown:()=>ht("zip"),onKeyDown:()=>ht("zip"),onBlur:()=>{_n("zip")&&ar(!0)},disabled:Ae,required:sn.required,"aria-invalid":sa||void 0,"aria-describedby":sa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:X()})})]}),sa&&(0,c.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:xo,children:sn.empty?`${(0,p.getPostalCodeLabel)(i)} is required`:Td(i)})]})})()}),$e&&rc,I&&(0,c.jsx)(yo,{margin:"0.75rem 0",styleOverride:w.errorBanner,children:I})]}),la={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"},Ps=i=>ee?!k||!gr?(0,c.jsx)("pre",{"data-testid":i,style:la,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":i,style:la,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${k}`,` directPaypalConfigured=${gr}`,` inAppBrowserDetected=${String(ra)}`,` shouldRenderDirectPayPal=${Io}`,` shouldRenderStripePayPal=${Ro}`,` hasPaypalStripeInstance=${!!tn}`].join(`
39
- `)}):null,Cs=i=>ee?!$||!vt?(0,c.jsx)("pre",{"data-testid":i,style:la,children:"FloPay/Stripe-debug - not enabled"}):(0,c.jsx)("pre",{"data-testid":i,style:la,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${$}`,` currency=${ze}`,` amountInCents=${Un}`,` enabledPaymentMethods: ${JSON.stringify(U??[])}`,` enabledPaymentMethodsProvided=${wo}`,` hasEnabledMethods=${ea}`,` expressMethods: ${JSON.stringify(ta)}`,` walletExpressMethods: ${JSON.stringify(Qr)}`,` paymentElementMethods: ${JSON.stringify(ko)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(na)}`,` hasStripeInstance=${!!vt}`,` shouldRenderWallets=${eo}`,` shouldRenderPaymentElement=${_o}`].join(`
40
- `)}):null,Ss=et==="apm-expanding"||et==="apm-form"||et==="apm-collapsing",ro;et==="apm-expanding"?ro=ul:et==="apm-collapsing"&&(ro=pl);let ca=ln?Il(Ga,ln):null;if(pe==="buttons"){let i=et==="buttons"||et==="expanding"||et==="apm-expanding",R=et==="expanding"||et==="card"||et==="collapsing",X=Me===void 0?{boxSizing:"border-box",height:Ba,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ue;et==="expanding"||et==="apm-expanding"?Ue=wd:(et==="collapsing"||et==="apm-collapsing")&&(Ue=Sd);let te;return et==="expanding"?te=ul:et==="collapsing"&&(te=pl),(0,c.jsxs)("form",{onSubmit:Za,className:C,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(xi,{}),zn&&(0,c.jsx)(tr,{status:zn,errorMessage:I,authorized:jn}),(0,c.jsxs)("div",{style:{display:"grid"},children:[(0,c.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Ue?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Ue?Id:{},...Ue?{animation:Ue,pointerEvents:"none"}:{}},children:[Ps("flopay-direct-paypal-gate-debug"),Cs("flopay-stripe-gate-debug"),Io&&Be&&(0,c.jsxs)(c.Fragment,{children:[Y&&(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)(Uo,{sessionId:e,nonce:t,billingApiUrl:W,email:v.email,billingName:x||void 0,onBuyerIdentityReady:S,clientId:Be.clientId,environment:Be.environment,currency:ze.toUpperCase(),isSubscription:Ne,providerObjectType:q,approvalPresentation:oa==="popup"?void 0:oa,onTokenizedBody:Tn,onComplete:l,onErrorChange:Te,onDecline:u,onTechnicalFailure:Zr,onButtonClick:oe,runBeforeButtonClick:cr,isProcessing:Ae,onLoadStateChange:Ya,onInitializationStateChange:Ja,session:g,existingOrderId:Y?.orderId,debug:ee},Y?.orderId??"fresh")]}),Ro&&(0,c.jsx)(Kt.Elements,{stripe:tn,options:Hi,children:(0,c.jsx)(gl,{sessionId:e,nonce:t,email:v.email,billingName:x||void 0,onBuyerIdentityReady:S,billingApiUrl:W,onTokenizedBody:Tn,onErrorChange:Te,isProcessing:Ae,onButtonClick:oe,onDecline:u,onTechnicalFailure:Zr,runBeforeButtonClick:cr,onLoadStateChange:Qi,placeholderBorderRadius:Ur})}),eo?(0,c.jsx)(Kt.Elements,{stripe:vt,options:Wi,children:(0,c.jsx)(hl,{sessionId:e,nonce:t,email:v.email,billingName:x||void 0,onBuyerIdentityReady:S,billingApiUrl:W,intentKind:Oe>0?"payment":"setup",expressMethods:Qr,onTokenizedBody:Tn,onErrorChange:Te,onButtonClick:oe,onDecline:u,onTechnicalFailure:Zr,runBeforeButtonClick:cr,onLoadStateChange:ts,placeholderBorderRadius:Ur})}):null,!eo&&is?(0,c.jsx)("div",{style:{height:Ba,borderRadius:Ur,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,_o&&(0,c.jsx)(bl,{sessionId:e,nonce:t,email:v.email,billingName:[v.firstName,v.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:S,billingApiUrl:W,paymentElementMethods:na,stripeInstance:vt,paymentElementBaseOptions:Ga,onTokenizedBody:Tn,onErrorChange:Te,onButtonClick:oe,onDecline:u,runBeforeButtonClick:cr,onLoadStateChange:rs,isProcessing:Ae,submitButtonColor:qr,submitButtonBorderRadius:jt,submitButtonStyle:w.submitButton,onExpandApm:Br,expandedApmMethod:ln,themeId:ye,buttonAppearance:{backgroundColor:w.cardButton?.backgroundColor,borderColor:w.cardInputBorder,textColor:w.cardButton?.color,borderRadius:Ur}}),$e&&(0,c.jsx)("button",{type:"button",onClick:async()=>{Ae||!(await cr("card")).proceed||(oe?.("card"),Yr())},disabled:Ae,style:{width:"100%",...X,...w.cardButton,...Li({themeBundle:A,resolvedPrimaryColor:qr,resolvedBorderRadius:jt,submitButtonStyle:w.submitButton,explicitPrimaryColor:An?.colorPrimary}),fontSize:w.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ae?"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:Ae?.6:1},onMouseEnter:mt=>{!Ae&&(A||An?.colorPrimary)&&(mt.currentTarget.style.backgroundColor=tc)},onMouseLeave:mt=>{(A||An?.colorPrimary)&&(mt.currentTarget.style.backgroundColor=qr)},onMouseDown:mt=>{mt.currentTarget.style.transform="scale(0.985)"},onMouseUp:mt=>{mt.currentTarget.style.transform="scale(1)"},children:(0,c.jsx)(ao,{content:Me})}),I&&et==="buttons"&&(0,c.jsx)(yo,{margin:"0.25rem 0",styleOverride:w.errorBanner,children:I})]}),$e&&R&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...te?{animation:te}:{},...et==="collapsing"?{pointerEvents:"none"}:{}},children:vs}),$&&Ss&&ln&&ca&&vt&&(0,c.jsx)("div",{style:{gridArea:"1 / 1",...ro?{animation:ro}:{},...et==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:ei,borderRadius:ai,...Mo,padding:oi},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:Sn,style:{display:"inline-flex",alignItems:"center",gap:ti?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:w.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...w.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",...w.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)(io,{content:fe})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:w.titleFontSize??"1.05rem",color:ni,paddingRight:80,...w.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(ln)}`})]}),(0,c.jsx)(Kt.Elements,{stripe:vt,options:ca,children:(0,c.jsx)(Fi,{method:ln,sessionId:e,nonce:t,email:v.email,billingName:[v.firstName,v.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:S,billingApiUrl:W,onTokenizedBody:Tn,onErrorChange:Te,onDecline:u,onCancel:Sn,runBeforeButtonClick:cr,onButtonClick:oe,isProcessing:Ae,submitButtonColor:qr,submitButtonBorderRadius:jt,submitButtonStyle:w.submitButton,errorText:I})},ln)]})})]})]})}return Ss&&ln&&ca&&vt&&$?(0,c.jsxs)("form",{onSubmit:Za,className:C,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(xi,{}),zn&&(0,c.jsx)(tr,{status:zn,errorMessage:I,authorized:jn}),(0,c.jsx)("div",{style:{...ro?{animation:ro}:{},...et==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,c.jsxs)("div",{style:{backgroundColor:ei,borderRadius:ai,...Mo,padding:oi},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:Sn,style:{display:"inline-flex",alignItems:"center",gap:ti?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:w.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...w.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",...w.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)(io,{content:fe})]}),(0,c.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:w.titleFontSize??"1.05rem",color:ni,paddingRight:80,...w.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(ln)}`})]}),(0,c.jsx)(Kt.Elements,{stripe:vt,options:ca,children:(0,c.jsx)(Fi,{method:ln,sessionId:e,nonce:t,email:v.email,billingName:[v.firstName,v.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:S,billingApiUrl:W,onTokenizedBody:Tn,onErrorChange:Te,onDecline:u,onCancel:Sn,runBeforeButtonClick:cr,onButtonClick:oe,isProcessing:Ae,submitButtonColor:qr,submitButtonBorderRadius:jt,submitButtonStyle:w.submitButton,errorText:I})},ln)]})})]}):(0,c.jsxs)("form",{onSubmit:Za,className:C,noValidate:!0,style:{position:"relative"},children:[(0,c.jsx)(xi,{}),zn&&(0,c.jsx)(tr,{status:zn,errorMessage:I,authorized:jn}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ps("flopay-direct-paypal-gate-debug-default"),Cs("flopay-stripe-gate-debug-default"),Io&&Be&&(0,c.jsxs)(c.Fragment,{children:[Y&&(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)(Uo,{sessionId:e,nonce:t,billingApiUrl:W,email:v.email,billingName:x||void 0,onBuyerIdentityReady:S,clientId:Be.clientId,environment:Be.environment,currency:ze.toUpperCase(),isSubscription:Ne,providerObjectType:q,approvalPresentation:oa==="popup"?void 0:oa,onTokenizedBody:Tn,onComplete:l,onErrorChange:Te,onDecline:u,onTechnicalFailure:Zr,onButtonClick:oe,runBeforeButtonClick:cr,isProcessing:Ae,onLoadStateChange:Ya,onInitializationStateChange:Ja,session:g,existingOrderId:Y?.orderId,debug:ee},Y?.orderId??"fresh")]}),Ro&&(0,c.jsx)(Kt.Elements,{stripe:tn,options:Hi,children:(0,c.jsx)(gl,{sessionId:e,nonce:t,email:v.email,billingName:x||void 0,onBuyerIdentityReady:S,billingApiUrl:W,onTokenizedBody:Tn,onErrorChange:Te,isProcessing:Ae,onButtonClick:oe,onDecline:u,onTechnicalFailure:Zr,runBeforeButtonClick:cr,onLoadStateChange:Qi,placeholderBorderRadius:Ur})}),eo&&(0,c.jsx)(Kt.Elements,{stripe:vt,options:Wi,children:(0,c.jsx)(hl,{sessionId:e,nonce:t,email:v.email,billingName:x||void 0,onBuyerIdentityReady:S,billingApiUrl:W,intentKind:Oe>0?"payment":"setup",expressMethods:Qr,onTokenizedBody:Tn,onErrorChange:Te,onButtonClick:oe,onDecline:u,onTechnicalFailure:Zr,runBeforeButtonClick:cr,onLoadStateChange:ts,placeholderBorderRadius:Ur})}),_o&&(0,c.jsx)(bl,{sessionId:e,nonce:t,email:v.email,billingName:[v.firstName,v.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:W,paymentElementMethods:na,stripeInstance:vt,paymentElementBaseOptions:Ga,onTokenizedBody:Tn,onErrorChange:Te,onButtonClick:oe,onDecline:u,runBeforeButtonClick:cr,onLoadStateChange:rs,isProcessing:Ae,submitButtonColor:qr,submitButtonBorderRadius:jt,submitButtonStyle:w.submitButton,themeId:ye,onExpandApm:Br,expandedApmMethod:ln,buttonAppearance:{backgroundColor:w.cardButton?.backgroundColor,borderColor:w.cardInputBorder,textColor:w.cardButton?.color,borderRadius:Ur}})]}),$e&&(Gl||Hl||Yl)&&(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,c.jsx)("span",{children:"or pay with card"}),(0,c.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),$e&&vs]})}var T=require("react/jsx-runtime"),So=44,Vi="flopay_checkout_saved_payment_resume",za=new Map,La=new Map;function Rl(e,t){t.settled&&t.consumers===0&&za.get(e)===t&&za.delete(e)}function Dd(e,t,n){let r=La.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};La.set(e,a);let l=()=>{La.get(e)===a&&La.delete(e)};return o.then(l,l),o}function Xo(e){return new Promise(t=>setTimeout(t,e))}function Oa(e,t,n){let r=ha({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:qe.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Zo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Oi(e,t,n,r,o,a){let l=Oa(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Zo(l)}function _l(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function El(e,t,n,r,o){let a=(0,qe.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:a.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:n,paymentMethodCategory:"unknown"}),!1):a.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...a,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function Ml(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function zi(e){return!e||e.data.stripe?.publishableKey?!1:!!Ml(e)?.clientId}var Nd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Ld(e){return new xr.FloPay(Nd,{publishableKey:"provider_unavailable",...e})}async function Ui(e,t){let{publishableKey:n,paypalPublishableKey:r}=Si(e);return{...await wi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function ji(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Od(){if(!ji())return null;try{let e=window.sessionStorage.getItem(Vi);return e?JSON.parse(e):null}catch{return null}}function Tl(e){if(ji())try{window.sessionStorage.setItem(Vi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function qi(){if(ji())try{window.sessionStorage.removeItem(Vi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function zd(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Al(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 $i(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Ud(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function xl(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function qd(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 Ua({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:d,error:u,onComplete:m,onError:h,onInstrument:b,onDecline:y,onCountryChange:C,onZipChange:_,showPayPal:ne=!0,showStripe:z=!0,enabledPaymentMethods:ue,showApplePay:k=!0,showGooglePay:$=!0,debug:U=!1,layout:se,theme:Se,buttonsTheme:Pe,buttonsStyles:pe,cardButtonContent:ye,cardBackButtonContent:yt,cardTitleContent:He,showSecurityFooter:we,onButtonClick:Me,onBeforeButtonClick:fe,enableAVS:Re,cardFieldOrder:Ge,cardPreFormSlot:oe,avsLayout:_e,submitLabel:ge,className:nt,initialErrorMessage:rt=null,initialPayPalOrderId:M,children:V,checkoutMode:ie,confirmLabel:ae,renderConfirmButton:Ye,onSessionCompleted:Ce}){let N=(0,qe.resolveBillingApiUrl)(r),ut=(0,P.useMemo)(()=>(0,qe.resolveTheme)(Se),[Se]),ot=a??ut?.appearance,he=n?"embedded_checkout":"standard_checkout",le=$i(V,se),[H,Le]=(0,P.useState)(null),[Oe,ze]=(0,P.useState)(null),je=(0,P.useRef)(null),Be=(0,P.useRef)(null),Ne=(0,P.useRef)(0),[ce,dn]=(0,P.useState)(null),Jt=(0,P.useRef)(null),[ee,at]=(0,P.useState)(null),Z=(0,P.useMemo)(()=>n?go(n):"",[n]),Q=n?`create:${Z}`:`session:${e??""}`,be=xl(ee),g=(0,P.useRef)(new Set),q=(0,P.useRef)(Q),Fe=(0,P.useRef)(Q);Kr(()=>{Fe.current=Q,q.current!==Q&&(q.current=Q,g.current.clear())},[Q]);let Je=(0,P.useCallback)(D=>{if(Fe.current===Q){if(pi.has(D.name)){if(g.current.has(D.name))return;g.current.add(D.name)}dt(()=>b?.(D))}},[Q,b]),De=mo(Je,Q),$t=(0,P.useRef)(!1),W=(0,P.useCallback)(D=>{if($t.current)return;let F=D.gateway||!be?D:{...D,gateway:be};Je(F)},[Je,be]);(0,P.useEffect)(()=>{De({class:"lifecycle",name:"checkout.mount"})},[De]);let[St,Tt]=(0,P.useState)(e??""),ft=e??St,un=n?"":ft,[G,Lt]=(0,P.useState)(!0),[vn,pn]=(0,P.useState)(null),[mn,In]=(0,P.useState)(0),[Bn,Fn]=(0,P.useState)("full"),[Xt,Ke]=(0,P.useState)(!1),[Qe,wt]=(0,P.useState)(rt),[rn,kt]=(0,P.useState)(null),[Vn,gt]=(0,P.useState)(null),[At,Ot]=(0,P.useState)(!1),[yn,zt]=(0,P.useState)(void 0),[xt,Pn]=(0,P.useState)(""),[Cn,It]=(0,P.useState)(!1),[de,on]=(0,P.useState)(!1),[jn,Wt]=(0,P.useState)(!1),Vt=(0,P.useRef)(null),an=(0,P.useRef)(0),rr=(0,P.useRef)(void 0),[Dn,Ht]=(0,P.useState)("loading"),[$e,fn]=(0,P.useState)(0),ve=(0,P.useRef)(!1),O=(0,P.useRef)(!1),Ve=(0,P.useRef)(!1),K=(0,P.useRef)(null),Rt=(0,P.useRef)(null),Mt=(0,P.useMemo)(()=>({checkoutMode:ie??Bn,layout:Ud(V,se)}),[ie,V,Bn,se]),Gt=(0,P.useRef)(m);Gt.current=m;let Kn=(0,P.useRef)(h);Kn.current=h;let Ee=(0,P.useRef)(y);Ee.current=y;let sn=(0,P.useCallback)(D=>Ra(K,async F=>{try{return await D(F)}catch(j){throw F.aborted?Ko(j):j}}),[]);(0,P.useEffect)(()=>()=>{K.current?.abort(),K.current=null},[]);let Wn=(0,P.useCallback)((D,F)=>{je.current=D,ze(D),Jt.current=F,dn(F)},[]),Sr=(0,P.useCallback)(()=>{let D=Be.current;D&&(Be.current=null,D.destroy())},[]);(0,P.useEffect)(()=>{en(Oe)?.setCheckoutContext(Mt),ce&&ce!==Oe&&en(ce)?.setCheckoutContext(Mt)},[Oe,ce,Mt]);let or=(0,P.useRef)(Ce);or.current=Ce;let Lr=(0,P.useCallback)(D=>{Ht(D),!(D!=="exhausted"||Ve.current)&&(Ve.current=!0,Kn.current?.(new qe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Or=(0,P.useCallback)(()=>{Ht("retrying"),fn(D=>D+1)},[]);(0,P.useEffect)(()=>{Ht("loading"),fn(0),Ve.current=!1},[ft]),(0,P.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:qe.SDK_VERSION,checkout_type:he,checkout_layout:le,billing_api_url:N})},[le,he,N]);let ar=(0,P.useMemo)(()=>n?go(n,!0):"",[n]),Mr=(0,P.useMemo)(()=>xt===ar?yn:void 0,[yn,xt,ar]),Rn=(0,P.useMemo)(()=>n?li(n,Mr):void 0,[n,Mr]),ir=ie??Rn?.checkoutMode??"full",Ft=(0,P.useMemo)(()=>Rn?{...Rn,checkoutMode:ir}:void 0,[Rn,ir]);(0,P.useEffect)(()=>{zt(void 0),Pn(ar),rr.current=void 0,Vt.current=null,Wt(!1)},[ar]),(0,P.useEffect)(()=>{wt(rt)},[rt]);let Nn=(0,P.useCallback)((D,F,j)=>{dt(()=>{Ee.current?.(nn(D,F,j))})},[]),Hn=(0,P.useCallback)(async(D,F)=>{wt(null),gt(null),Ot(!1),kt("processing");let j=F?.sessionId??D.id,Y=D.clientSecret||t,pt=xl(D),B=je.current??Jt.current,f=en(B),L=B?null:Oa(N,o,Mt),S={log:v=>{f?f.log(v):L?.log(v)},error:v=>{f?f.error(v):L?.error(v)},terminal:v=>{f?f.terminal(v):L?.terminal(v)},performance:v=>{f?f.performance(v):L?.performance(v)},now:()=>f?.now()??L?.now()??0,elapsed:v=>f?.elapsed(v)??Math.max(0,(L?.now()??v)-v)},I=S.now(),A=!!(F?.initialAutoProcessingError||F?.initialAutoProcessingPending),w=!1,J,Xe=()=>{w||(w=!0,A=!0,J=S.now(),S.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Dt=!1,Ae=()=>{Dt||(Dt=!0,S.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),S.performance({stage:"processing",durationMs:S.elapsed(I),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),J!==void 0&&S.performance({stage:"recovery",durationMs:S.elapsed(J),durationMode:"machine",paymentMethodCategory:"saved"}))};S.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),$t.current=!0;try{S.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{$t.current=!1}De({class:"lifecycle",name:"payment.processing.started",provider:pt}),A&&Xe();let me;try{let v=Gs(F?.initialAutoProcessingError),x=F?.initialAutoProcessingError?.type==="3ds_required"&&!F.initialAutoProcessingError.threeDSecureToken&&F.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:F.initialAutoProcessingError.nextActionRedirectUrl}:null,re,ke=xe=>(Xe(),sn(Ie=>bo(xe,{billingApiUrl:N,sessionId:j,nonce:Y,session:D,signal:Ie})));if(x)re=await ke(x);else if(v)Xe(),v.type==="paypal_redirect_required"&&Rt.current?.publishableKey&&Tl({sessionId:j,publishableKey:Rt.current.publishableKey,paypalPublishableKey:Rt.current.paypalPublishableKey}),re=await sn(xe=>Ea(v,{flopay:je.current,paypalFlopay:Jt.current,attempt3DS:F?.attempt3DS,billingApiUrl:N,sessionId:j,session:D,telemetry:!1,signal:xe})),v.type==="paypal_redirect_required"&&qi();else if(F?.initialAutoProcessingPending){let xe=F.initialAutoProcessingPending,Ie=new xr.PaymentAPI(N,{telemetry:!1}),tt=await sn(Un=>Ie.waitForCheckoutSessionCompletion(xe.sessionId,{initialDelayMs:xe.retryAfterMs,nonce:Y,statusUrl:xe.statusUrl,signal:Un})),vt=tt.data.session,tn=tt.autoProcessingError?.type==="3ds_required"&&tt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:tt.autoProcessingError.nextActionRedirectUrl}:null;if(tn)re=await ke(tn);else{if(!Nr(vt))throw lo(vt);re=Ir(vt,j)}}else{if(F?.initialAutoProcessingError)throw br(F.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:F.initialAutoProcessingError.checkoutMethod});if(F?.fromCreateSession)return F?.fallbackToFull&&(Fn("full"),Al("full")),!1;{let xe=await vo({billingApiUrl:N,sessionId:j,session:D,nonce:Y,telemetry:!1});xe.type==="success"?re=xe.result:xe.type==="next_action_required"?re=await ke(xe):(Xe(),xe.type==="paypal_redirect_required"&&Rt.current?.publishableKey&&Tl({sessionId:j,publishableKey:Rt.current.publishableKey,paypalPublishableKey:Rt.current.paypalPublishableKey}),re=await sn(Ie=>Ea(xe,{flopay:je.current,paypalFlopay:Jt.current,attempt3DS:F?.attempt3DS,billingApiUrl:N,sessionId:j,session:D,telemetry:!1,signal:Ie})),xe.type==="paypal_redirect_required"&&qi())}}j&&ho(j),Ae(),A&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),S.terminal({outcome:re.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Ot(re.status==="authorized"),kt("success"),await Xo(600),me=()=>Gt.current?.(re)}catch(v){let x=Wo(v);if(x.code==="three_ds_aborted")return!1;let re=x.checkoutMethod??jo;wt(x.message),gt(x.message),Ot(!1),F?.fallbackToFull&&(S.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Fn("full"),Al("full")),Ae();let ke=x.statusCode===void 0?void 0:(0,qe.telemetryStatusClass)(x.statusCode,"unknown"),xe=ke==="4xx"?{requestCategory:"process_payment",statusClass:ke}:{},Ie=ke===void 0||ke==="4xx";if(Ie&&(x.telemetryOutcome==="payment_declined"||!!(x.declineCode||x.code?.toLowerCase().includes("declin"))))S.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...xe});else if(Ie&&(x.telemetryOutcome==="validation_rejected"||x.type==="validation_error"))S.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...xe});else{let tn=(0,qe.classifyTelemetryFailure)(v,A?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Un=x.telemetryRequestCategory??"process_payment";$t.current=!0;try{S.error({...tn,...x.telemetryFailureCategory?{failureCategory:x.telemetryFailureCategory}:{},stage:A?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Un})}finally{$t.current=!1}De({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Un,provider:pt})}return dt(()=>Kn.current?.(x)),Nn(re,x,{code:x.code,declineCode:x.declineCode}),kt("error"),await Promise.allSettled([Xo(400),F?.ensureProvidersReady?F.ensureProvidersReady():Promise.resolve()]),A&&(S.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),S.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ae(),L&&Zo(L),kt(null),gt(null)}return dt(me),!0},[Nn,De,t,N,sn,o,Mt]);(0,P.useEffect)(()=>{if(typeof window>"u"||O.current)return;let D=new URLSearchParams(window.location.search),F=D.get("payment_intent_client_secret");if(!F)return;let j=Od();j&&(O.current=!0,(async()=>{let Y,pt=0;wt(null),gt(null),kt("processing"),Ke(!0);try{if(D.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:B,paypalFlopay:f}=await wi({publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey,billingApiUrl:N,locale:l,telemetry:o});Y=en(f??B),Y?.setCheckoutContext(Mt),pt=Y?.now()??0,Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let L=(f??B)?.getRawProvider();if(!L)throw Object.assign(new qe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:S,error:I}=await L.retrievePaymentIntent(F);if(I)throw Object.assign(new qe.FloPayError(I.message??"Failed to retrieve PayPal payment status.","api_error",{code:I.code}),{checkoutMethod:"paypal"});let A=xs(S?.status);if(!S||A==="failed")throw Object.assign(new qe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let w=typeof S.payment_method=="string"?S.payment_method:S.payment_method?.id,J=A;if(j.sessionId){let Ae=(await new xr.PaymentAPI(N,{telemetry:!1}).getUnifiedCheckoutSession(j.sessionId)).data.session;if(Ae&&Ae.status!=="complete"){let me=await vo({billingApiUrl:N,sessionId:j.sessionId,session:Ae,telemetry:!1,tokenizedData:{id:w??S.id,type:"card",threeDSecureActionResultTokenId:S.id,isPaypal:!0}});if(me.type!=="success")throw Object.assign(new qe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});J=me.result.status}}j.sessionId&&ho(j.sessionId),Y?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.performance({stage:"redirect_resume",durationMs:Y.elapsed(pt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),kt("success"),await Xo(600),dt(()=>Gt.current?.({status:J,paymentIntentId:S.id,paymentMethodId:w,checkoutMethod:"paypal"}))}catch(B){let f=Wo(B),L=f.checkoutMethod??"paypal",S=!!(f.declineCode||f.code?.toLowerCase().includes("declin"));if(Y)Y.performance({stage:"redirect_resume",durationMs:Y.elapsed(pt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),S?Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Y.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(S){let I=Oa(N,o,Mt);I.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Zo(I)}else Oi(N,o,Mt,"REDIRECT_RESUME_FAILED","redirect_resume");wt(f.message),gt(f.message),dt(()=>Kn.current?.(f)),Nn(L,f,{code:f.code,declineCode:f.declineCode}),kt("error"),await Xo(400)}finally{qi(),zd(),kt(null),gt(null),Ke(!1)}})())},[Nn,l,N,o,Mt]);let Gn=(0,P.useRef)(null),ht=(0,P.useMemo)(()=>Ft?go(Ft):"",[Ft]),_n=(0,P.useRef)(Ft);_n.current=Ft,(0,P.useEffect)(()=>{Tt(e??"")},[e]),(0,P.useEffect)(()=>{ve.current=!1,wt(rt),gt(null),Ot(!1),kt(null)},[ht,rt,e]);async function Yn(D,F,j){let Y=Oa(N,o,Mt),pt=new xr.PaymentAPI(N,{telemetry:!1}),B=!1;try{let f=D.idempotencyKey===void 0?void 0:(0,qe.resolveIdempotencyKey)(D.idempotencyKey),L=gi(F,j),S=hi(F,j);L?.canonicalIdentity===j&&S&&S.canonicalIdentity===void 0&&(ka(F,j,S.idempotencyKey),S={...S,canonicalIdentity:j});let I=f??(S?.canonicalIdentity===j?S.idempotencyKey:void 0),A,w=!1;Y.log({name:L?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let J=L?.sid??null,Xe=null,Dt,Ae,me=!1;if(J)try{Xe=await pt.getUnifiedCheckoutSession(J,L?.nonce),L&&L.canonicalIdentity===void 0&&(Vs(Xe.data.session,D)?(wa(F,j,J,L.nonce??Xe.data.session?.clientSecret),S&&S.canonicalIdentity===void 0&&(ka(F,j,S.idempotencyKey),I??(I=S.idempotencyKey))):(Sa(F,j),S=null,I=f,J=null,Xe=null));let x=Xe?.data.session?.status,re=Xe?.data.session,ke=re?.clientSecret||L?.nonce;if(J&&re?.buyerIdentified===!1&&ke&&(Ae=so(pt,J,ke,D.account)),J&&Xe&&x==="complete"){if(bi(J))return{sid:J,result:Xe};Sa(F,j),J=null,Xe=null,w=!0}}catch{Y.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),L?.canonicalIdentity===void 0?(Sa(F,j),I=f):Ca(F,j),J=null}if(!J){!f&&(w||!I)&&(I=(0,qe.resolveIdempotencyKey)(),A=I),I&&ka(F,j,I);let x=Y.now(),re=0;Y.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ke={...D,idempotencyKey:I,avsCheck:!!Re,avsConfig:typeof Re=="object"?Re:void 0,checkoutType:"embedded_checkout",checkoutLayout:$i(V,se)};Object.defineProperty(ke,xr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:tt=>{re=Math.max(re,tt)}}});let xe=()=>{_l(Y,"session_create",x,re)},Ie=tt=>{El(Y,tt,"session_create",x,re)&&De({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,qe.isDetachedSessionEligible)(ke)){let tt=await pt.createDetachedSession(ke);tt.claimed.catch(()=>{}),Xe=tt.shell,J=tt.sessionId,Ae=tt.claim;let vt=Y.now();Y.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Dt=tt.claimed.then(tn=>{let Un=tn.data.session?.id??tt.sessionId;return Un&&wa(F,j,Un,tn.data.session?.clientSecret??tt.nonce),_l(Y,"session_claim",vt),xe(),tn},tn=>{throw Ca(F,j),El(Y,tn,"session_claim",vt,0)&&De({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),tn}).finally(()=>Zo(Y)),Dt.catch(()=>{}),B=!0,Y.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Y.performance({stage:"session_shell",durationMs:Y.now()-x,durationMode:"machine",requestCategory:"session_create",attempt:re,statusClass:"2xx",paymentMethodCategory:"card"})}else Xe=await pt.createAndFetchSession(ke),xe()}catch(tt){throw Ie(tt),tt}J=Xe.data.session?.id??J??"",J&&!Dt&&wa(F,j,J,Xe.data.session?.clientSecret)}let v=Xe?.data.session;return!Ae&&J&&v?.buyerIdentified===!1&&v.clientSecret&&(Ae=so(pt,J,v.clientSecret,D.account)),{sid:J??"",result:Xe,sdkGeneratedIdempotencyKey:A,...Dt?{claimed:Dt}:{},...Ae?{claim:Ae}:{},...me?{claimRequiresIdentity:!0}:{}}}finally{B||Zo(Y)}}let sr=(0,P.useRef)(Yn);Kr(()=>{sr.current=Yn},[Yn]);let gn=(0,P.useCallback)(async(D,F)=>{let j=_n.current;if(!j)throw new qe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let Y=li(j,D),pt=go(Y),B=$s(Y),f=za.get(pt);if(!f){let I={canonicalIdentity:pt,promise:sr.current(Y,B,pt),consumers:0,settled:!1};f=I,za.set(pt,I);let A=()=>{I.settled=!0,Rl(pt,I)};I.promise.then(A,A)}f.consumers+=1;let L=!1,S=()=>{L||(L=!0,f.consumers-=1,Rl(pt,f))};F?.(S);try{let I=await f.promise;Gn.current=pt,D&&(Pn(ar),zt(v=>Es(v,D)));let{sid:A,result:w,claimed:J,claim:Xe,claimRequiresIdentity:Dt}=I;if(rr.current=Xe,Wt(Dt===!0),Le(w),w.data.session&&at(w.data.session),A&&Tt(A),J){an.current+=1;let v=an.current;Vt.current=J,on(!0),J.then(x=>{an.current===v&&(Vt.current===J&&(Vt.current=null),Le(x),x.data.session&&at(x.data.session),on(!1),Wt(!1))},x=>{an.current===v&&(Vt.current===J&&(Vt.current=null),on(!1),Wt(!1),pn(x instanceof qe.FloPayError?x:new qe.FloPayError(x instanceof Error?x.message:"Failed to create session","api_error")))})}else an.current+=1,Vt.current=null,on(!1),Wt(!1);let{flopay:Ae,paypalFlopay:me}=await Ui(w,{billingApiUrl:N,locale:l,telemetry:o});return Wn(Ae,me),Lt(!1),I}catch(I){throw Gn.current===pt&&(Gn.current=null),I}finally{F||S()}},[ar,Wn,l,N,o]),et=(0,P.useRef)(Hn);et.current=Hn;let hn=(0,P.useRef)(gn);hn.current=gn;let ln=(0,P.useCallback)(async D=>{if(!qd(D)||Cn)return{sessionId:St,session:ee};It(!0);try{let F=await gn(D);return{sessionId:F.sid,session:F.result.data.session??null}}finally{It(!1)}},[gn,Cn,St,ee]),Ln=(0,P.useCallback)(async D=>{let F=rr.current;if(!F)return;let j=an.current,Y=await F(D);an.current===j&&(Le(Y),Y.data.session&&at(Y.data.session))},[]),wr=(0,P.useCallback)(async()=>{await Vt.current},[]),zr=(0,P.useCallback)(async()=>(await wr(),{proceed:!0}),[wr]);(0,P.useEffect)(()=>{let D=!1,F,j=++Ne.current;Sr(),pn(null),In(0);let Y=()=>{D=!0,Ne.current===j&&(Ne.current+=1,Sr())},pt=_n.current;if(ht&&pt)return Fn(ir),Lt(!1),Gn.current===ht?Y:(at(Ts(pt,ie)),(async()=>{let L=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),S=ir==="auto"&&!ve.current&&!L;S&&(wt(null),gt(null),kt("processing"));try{let I=await hn.current(void 0,Xe=>{F=Xe}),A=I.result.data.session??null;Rt.current=Si(I.result);let w=zi(I.result),J=bi(I.sid||A?.id);if(!D&&S&&A&&!w&&!J){ve.current=!0,await Dd(ht,I.sdkGeneratedIdempotencyKey,()=>et.current(A,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:I.result.autoProcessingError,initialAutoProcessingPending:I.result.autoProcessingPending,autoProcessingAttempted:I.result.autoProcessingAttempted,sessionId:I.sid||A.id}));return}!D&&S&&((w||J)&&(ve.current=!0),kt(null),gt(null))}catch(I){if(D)return;let A=pa(I);if(S&&A==="session_auto_completed"){ve.current=!0,kt("success"),await Xo(600),D||(dt(()=>{Gt.current?.({status:"succeeded"})}),kt(null),gt(null));return}S&&(kt(null),gt(null));let w=I instanceof qe.FloPayError?I:new qe.FloPayError(I instanceof Error?I.message:"Failed to create session","api_error");pn(w)}finally{F?.(),F=void 0}})(),()=>{Y(),F?.()});Lt(!0);async function B(){let L=!1,S=null;try{let I=new xr.PaymentAPI(N,{telemetry:!1}),A=await I.getUnifiedCheckoutSession(ft,t);if(S=A,D)return;Le(A);let w=A.data.session??null;if(at(w),!w)throw new qe.FloPayError("No session data returned","api_error");let J=w.checkoutMode;if(J==="setup")throw new qe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(w.status==="authorized"){Lt(!1),dt(()=>{Gt.current?.(Ir(w,ft)),or.current?.(w.successUrl??"")});return}if(w.status==="complete"){Lt(!1),dt(()=>{or.current?.(w.successUrl??"")});return}if(w.status==="expired")throw ua(w);L=!0;let Xe=ie??J??"full";Fn(Xe),an.current+=1;let Dt=w.clientSecret||t;rr.current=w.buyerIdentified===!1&&Dt?so(I,ft,Dt,{...w.customer?.id?{userId:w.customer.id}:{}}):void 0,on(!1),Wt(!1);let Ae=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),me=zi(A);if(Xe==="auto"&&!ve.current&&!Ae&&!me){ve.current=!0;let v=f(A);try{if(await et.current(w,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>v,sessionId:ft||w.id}),D)return;await v,D||Lt(!1);return}catch{if(D)return;await v,D||Lt(!1);return}}await f(A),D||Lt(!1)}catch(I){if(D)return;let A=_s(I,L);if(L&&De({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),A){let{errorCode:J,stage:Xe,...Dt}=A;Oi(N,o,Mt,J,Xe,Dt)}if(A?.stage==="provider_load"&&(ie??S?.data.session?.checkoutMode??"full")==="full"&&Rs(S,ne,z)){let J=Ld({billingApiUrl:N,locale:l,telemetry:o});Be.current=J,Wn(J,null),In(1),Lt(!1);return}let w=I instanceof qe.FloPayError&&A?.stage!=="provider_load"?I:Is();w!==I&&dt(()=>Kn.current?.(w)),pn(w),Lt(!1)}}async function f(L){let{flopay:S,paypalFlopay:I,...A}=await Ui(L,{billingApiUrl:N,locale:l,telemetry:o});Rt.current={publishableKey:A.publishableKey,paypalPublishableKey:A.paypalPublishableKey},Wn(S,I),In(0)}return B(),Y},[ie,ht,ir,un,t,ne,z]);let kr=(0,P.useCallback)(async()=>{if(!H||mn!==1)return;let D=Ne.current;In(2);try{let{flopay:F,paypalFlopay:j}=await Ui(H,{billingApiUrl:N,locale:l,telemetry:o});if(Ne.current!==D)return;Sr(),Wn(F,j),In(0)}catch(F){if(Ne.current!==D)return;let{errorCode:j,stage:Y,...pt}=ii(F);Oi(N,o,Mt,j,Y,pt)}},[Sr,Wn,l,mn,N,o,Mt,H]),On=!!(ft&&(ee?.clientSecret||t)),bn=Xt||!On,Yr=(0,P.useCallback)(async()=>{if(!(Xt||!On||!ee)){Ke(!0),wt(null);try{await Hn(ee,{attempt3DS:!0,fallbackToFull:!0,sessionId:ft||ee.id})}finally{Ke(!1)}}},[ft,Xt,On,Hn,ee]),En=Ml(H,M),Br=zi(H),Sn=(0,P.useMemo)(()=>{if(!(!H||!ee||!H.data.stripe?.publishableKey))return{billingApiUrl:N}},[H,ee,N]),zn=!!(n&&!V&&se==="buttons"&&fe&&ir==="full"),st=!!(ft&&(ee?.vault?.html||Fr(ee))),Jn=(0,P.useMemo)(()=>({session:ee,loading:G,error:vn,checkoutMode:Bn,inlineSessionDraft:Ft,applyInlineSessionPatch:zn?ln:void 0,inlineSessionPatchProcessing:Cn,claimPending:de,claimRequiresIdentity:jn,claimBuyerIdentity:Ln,waitForDataAttachment:wr}),[ee,G,vn,Bn,Ft,zn,ln,Cn,de,jn,Ln,wr]),Zt=!!n&&se==="buttons"&&!Br&&!st&&(!Oe||!Sn),_t=rn?(0,T.jsx)(tr,{status:rn,errorMessage:Vn,authorized:At}):null;if(G&&!st){if(d)return(0,T.jsxs)(T.Fragment,{children:[d,_t]});if(se==="buttons"){let D=ut?.buttonsLayout?.cardButton?.borderRadius??ut?.appearance.variables?.borderRadius??8,F=j=>(0,T.jsx)("div",{style:{height:j,borderRadius:D,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ne&&F(So),z&&(k||$)&&F(So),z&&F(So),(0,T.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),_t]})}return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,T.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,T.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),_t]})}return vn?u?(0,T.jsx)(dr.Provider,{value:Jn,children:u(vn)}):(0,T.jsx)(dr.Provider,{value:Jn,children:(0,T.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:vn.message})}):Zt?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(dr.Provider,{value:Jn,children:(0,T.jsx)(Vd,{onButtonClick:Me,showPayPal:ne,showStripe:z,showApplePay:k,showGooglePay:$,theme:Se,buttonsTheme:Pe,buttonsStyles:pe,cardButtonContent:ye,cardBackButtonContent:yt,cardTitleContent:He})}),_t]}):Br&&ee&&En?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(dr.Provider,{value:Jn,children:(0,T.jsxs)("div",{className:nt,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Qe&&(0,T.jsx)(yo,{icon:!1,children:Qe}),Dn==="retrying"&&(0,T.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Dn==="exhausted"&&(0,T.jsxs)("div",{role:"alert",children:[(0,T.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,T.jsx)("button",{type:"button",onClick:Or,children:"Retry PayPal"})]}),Dn!=="exhausted"&&(0,T.jsx)("div",{"aria-hidden":Dn==="retrying"?!0:void 0,style:Dn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,T.jsx)(qs,{sessionId:ft,nonce:ee.clientSecret||void 0,billingApiUrl:N,email:ee.customer?.email||Ft?.account?.email,billingName:[ee.customer?.firstName,ee.customer?.lastName].filter(Boolean).join(" ")||[Ft?.account?.firstName,Ft?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Ln,clientId:En.clientId,environment:En.environment,currency:(ee.currency??"usd").toUpperCase(),isSubscription:ee.mode==="subscription",providerObjectType:En.providerObjectType,approvalPresentation:En.approvalPresentation,existingOrderId:En.existingOrderId,onComplete:m,onErrorChange:wt,onDecline:y,onButtonClick:Me,runBeforeButtonClick:zr,onInitializationStateChange:Lr,allowAutomaticRetry:$e===0,session:ee,telemetry:o,telemetryContext:Mt,onInstrument:W,debug:U},`${Q}:paypal-init-${$e}`)})]})}),_t]}):Bn==="confirm"?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(dr.Provider,{value:Jn,children:(0,T.jsx)($o,{flopay:Oe,paypalFlopay:ce,options:Sn??{billingApiUrl:N},onInstrument:W,children:(0,T.jsxs)("div",{className:nt,children:[Qe&&(0,T.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Qe}),Ye?Ye({onConfirm:Yr,isProcessing:bn}):(0,T.jsx)("button",{type:"button",onClick:Yr,disabled:bn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:bn?"not-allowed":"pointer",opacity:bn?.6:1},children:Xt?"Processing...":ae??"Confirm Purchase"})]})},Q)}),_t]}):(!Oe||!Sn)&&!(st&&Bn==="full")?(0,T.jsx)(T.Fragment,{children:_t}):(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(dr.Provider,{value:Jn,children:(0,T.jsxs)($o,{flopay:Oe,paypalFlopay:ce,options:Sn??{billingApiUrl:N},onInstrument:W,children:[mn===1&&(0,T.jsx)("button",{type:"button",onClick:kr,children:"Retry payment methods"}),V?(0,T.jsxs)(T.Fragment,{children:[Qe&&(0,T.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Qe}),(0,T.jsx)($d,{sessionId:ft,nonce:ee?.clientSecret||void 0,billingApiUrl:N,session:ee,submitLabel:ge,children:V})]}):(0,T.jsx)(Na,{sessionId:ft,nonce:ee?.clientSecret||void 0,telemetry:o,email:ee?.customer?.email||Ft?.account?.email,userId:ee?.customer?.id||Ft?.account?.userId,firstName:ee?.customer?.firstName||Ft?.account?.firstName,lastName:ee?.customer?.lastName||Ft?.account?.lastName,totalAmount:ee?Math.round((0,qe.buildCheckoutDisplayData)(ee).total*100):0,currency:ee?.currency?.toLowerCase()??"usd",onComplete:m,onError:h,onDecline:y,error:Qe,onErrorChange:wt,showPayPal:ne,showStripe:z,enabledPaymentMethods:mn?[]:ue??H?.data.stripe?.enabledPaymentMethods??ee?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:H?.data.stripe?.enabledPaymentMethodCountries,showApplePay:k,showGooglePay:$,layout:se,theme:Se,buttonsTheme:Pe,buttonsStyles:pe,appearance:ot,cardButtonContent:ye,cardBackButtonContent:yt,cardTitleContent:He,onButtonClick:Me,onBeforeButtonClick:fe,onBuyerIdentityReady:Ln,enableAVS:Re,...Ge?{cardFieldOrder:Ge}:{},...oe?{cardPreFormSlot:oe}:{},avsLayout:_e,country:ee?.customer?.country,city:ee?.customer?.city,state:ee?.customer?.state,onCountryChange:C,onZipChange:_,avsCheck:!!Re,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:$i(V,se),className:nt,submitLabel:ge,directPaypal:En,isSubscription:ee?.mode==="subscription",session:ee,dataAttachmentPending:de,dataAttachmentRequiresIdentity:jn,debug:U})]},Q)}),_t]})}function $d({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:a}){return(0,T.jsx)(T.Fragment,{children:P.default.Children.map(a,l=>{if(!P.default.isValidElement(l))return l;let d=l.props,u={};return d.sessionId||(u.sessionId=e),!d.nonce&&t&&(u.nonce=t),d.billingApiUrl||(u.billingApiUrl=n),d.submitLabel===void 0&&o!==void 0&&(u.submitLabel=o),r?.customer&&(d.email||(u.email=r.customer.email),d.userId||(u.userId=r.customer.id),d.firstName||(u.firstName=r.customer.firstName),d.lastName||(u.lastName=r.customer.lastName)),Object.keys(u).length===0?l:P.default.cloneElement(l,u)})})}function Vd({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:d,cardButtonContent:u,cardBackButtonContent:m,cardTitleContent:h}){let[b,y]=(0,P.useState)(!1),C=(0,P.useMemo)(()=>(0,qe.resolveTheme)(a),[a]),_=(0,P.useMemo)(()=>{let k=C?.buttonsLayout??(0,qe.resolveButtonsLayoutTheme)(l);return d?{...k,...d,cardButton:{...k.cardButton,...d.cardButton},cardFormContainer:{...k.cardFormContainer,...d.cardFormContainer},backButton:{...k.backButton,...d.backButton},backButtonIcon:{...k.backButtonIcon,...d.backButtonIcon},submitButton:{...k.submitButton,...d.submitButton},title:{...k.title,...d.title}}:k},[C,l,d]),ne=C?.buttonsLayout?.cardButton?.borderRadius??C?.appearance.variables?.borderRadius??8,z=k=>(0,T.jsx)("div",{style:{height:k,borderRadius:ne,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),ue=u===void 0?{boxSizing:"border-box",height:So,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let k=_.cardInputBorder??"#e5e7eb",$=_.cardInputBackground??"white",U=oo(m),se=oo(h);return(0,T.jsxs)("div",{style:{backgroundColor:_.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",..._.cardFormContainer},children:[(0,T.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,T.jsxs)("button",{type:"button",onClick:()=>y(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:U?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",..._.backButton},children:[(0,T.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",..._.backButtonIcon},children:(0,T.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,T.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,T.jsx)(io,{content:m})]}),se?(0,T.jsx)("div",{style:{flex:1}}):(0,T.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,..._.title},children:(0,T.jsx)(Fo,{content:h})})]}),(0,T.jsx)("div",{style:{backgroundColor:$,border:`1px solid ${k}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,T.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,T.jsxs)("div",{style:{display:"flex"},children:[(0,T.jsx)("div",{style:{flex:1,backgroundColor:$,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${k}`,borderLeft:`1px solid ${k}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,T.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,T.jsx)("div",{style:{flex:1,backgroundColor:$,borderTop:"none",borderRight:`1px solid ${k}`,borderBottom:`1px solid ${k}`,borderLeft:`1px solid ${k}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,T.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,T.jsx)("div",{style:{backgroundColor:$,border:`1px solid ${k}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,T.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,T.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",..._.submitButton,opacity:.5}}),(0,T.jsx)("style",{children:`
38
+ `}),Do&&qr&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:z?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:jn,style:{display:"inline-flex",alignItems:"center",gap:pi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:J.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...J.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...J.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(uo,{content:gt})]}),Rs?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:J.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...J.title},children:(0,d.jsx)(Uo,{content:Ce})})]}),!Do&&!Rs&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:mi,order:z?-3:0,...J.title},children:(0,d.jsx)(Uo,{content:Ce})}),z&&_&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:_}),z&&Pt&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:ao,border:`1px solid ${er(ya)}`,borderRadius:$t,padding:"10px"},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:_n,onChange:s=>{Rt("email"),Wt.current=s.target.value,Kn(s.target.value)},onPointerDown:()=>Rt("email"),onKeyDown:()=>Rt("email"),onBlur:()=>{zn("email")&&En(!0),xn||ni()},disabled:Le,required:!0,"aria-invalid":ya||void 0,"aria-describedby":ya?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...yi}})}),ya&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Lo,children:Xe.empty?"Email address is required":"Enter a valid email address"})]}),re&&(0,d.jsx)("div",{style:{order:z?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=zt,k=(te=!1)=>({backgroundColor:ao,border:`1px solid ${er(te)}`,borderRadius:$t,marginTop:"0.5rem",padding:"10px"}),W=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...yi}),Ee=(0,m.getStateOptions)(s);return(0,d.jsxs)(d.Fragment,{children:[(0,m.isAVSFieldVisible)(re.address_line_1,s)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:k(Lt("line1")),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:On,onChange:te=>{Rt("line1"),Tt.current.addressLine1=!0,Mt.current=te.target.value,vn(te.target.value)},onPointerDown:()=>Rt("line1"),onKeyDown:()=>Rt("line1"),onBlur:()=>cr("line1"),disabled:Le,required:!0,"aria-invalid":Lt("line1")||void 0,"aria-describedby":Lt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:W()})}),Lt("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Lo,children:"Street address is required"})]}),(0,m.isAVSFieldVisible)(re.address_line_2,s)&&(0,d.jsx)("div",{style:k(),children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Ht,onChange:te=>{Tt.current.addressLine2=!0,yn.current=te.target.value,Ve(te.target.value)},disabled:Le,"data-testid":"flopay-address-line2",style:W()})}),((0,m.isAVSFieldVisible)(re.city,s)||(0,m.isAVSFieldVisible)(re.state,s))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,m.isAVSFieldVisible)(re.city,s)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:ao,borderTop:`1px solid ${er(Lt("city"))}`,borderRight:`1px solid ${er(Lt("city"))}`,borderBottom:`1px solid ${er(Lt("city"))}`,borderLeft:`1px solid ${er(Lt("city"))}`,padding:"10px",borderTopLeftRadius:$t,borderBottomLeftRadius:$t,...(0,m.isAVSFieldVisible)(re.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:$t}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:xe,onChange:te=>{Rt("city"),Tt.current.city=!0,Qt.current=te.target.value,Ln(te.target.value)},onPointerDown:()=>Rt("city"),onKeyDown:()=>Rt("city"),onBlur:()=>cr("city"),disabled:Le,required:!0,"aria-invalid":Lt("city")||void 0,"aria-describedby":Lt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:W()})}),(0,m.isAVSFieldVisible)(re.state,s)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:ao,borderTop:`1px solid ${er(Lt("state"))}`,borderRight:`1px solid ${er(Lt("state"))}`,borderBottom:`1px solid ${er(Lt("state"))}`,borderLeft:`1px solid ${er(Lt("state"))}`,padding:"10px",borderTopRightRadius:$t,borderBottomRightRadius:$t,...(0,m.isAVSFieldVisible)(re.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${er(Lt("state")||Lt("city"))}`}:{borderRadius:$t}},children:Ee?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:kt,onChange:te=>{Rt("state"),Tt.current.state=!0,Ut.current=te.target.value,Cn(te.target.value)},onPointerDown:()=>Rt("state"),onKeyDown:()=>Rt("state"),onBlur:()=>cr("state"),disabled:Le,autoComplete:"billing address-level1",required:!0,"aria-invalid":Lt("state")||void 0,"aria-describedby":Lt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...W(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,m.getStateLabel)(s)}),Ee.map(te=>(0,d.jsx)("option",{value:te.code,children:te.name},te.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,m.getStateLabel)(s),autoComplete:"billing address-level1",value:kt,onChange:te=>{Rt("state"),Tt.current.state=!0,Ut.current=te.target.value,Cn(te.target.value)},onPointerDown:()=>Rt("state"),onKeyDown:()=>Rt("state"),onBlur:()=>cr("state"),disabled:Le,required:!0,"aria-invalid":Lt("state")||void 0,"aria-describedby":Lt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:W()})})]}),Lt("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Lo,children:"City is required"}),Lt("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Lo,children:[(0,m.getStateLabel)(s)," is required"]}),((0,m.isAVSFieldVisible)(re.country,s)||(0,m.isAVSFieldVisible)(re.postal_code,s))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:ie==="column"?"column":"row",gap:ie==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,m.isAVSFieldVisible)(re.country,s)&&(0,d.jsx)("div",{style:{flex:ie==="row"?1:void 0,backgroundColor:ao,borderTop:`1px solid ${Oo}`,borderRight:`1px solid ${Oo}`,borderBottom:`1px solid ${Oo}`,borderLeft:`1px solid ${Oo}`,padding:"10px",...ie==="row"&&(0,m.isAVSFieldVisible)(re.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:$t,borderBottomLeftRadius:$t,borderRight:"none"}:{borderRadius:$t}},children:(0,d.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:zt,onChange:te=>{Tt.current.country=!0,It.current=te.target.value,hn(te.target.value),nt?.(te.target.value),Ut.current="",Cn("")},disabled:Le,autoComplete:"billing country","data-testid":"flopay-country",style:{...W(),cursor:"pointer"},children:m.COUNTRY_OPTIONS.map(te=>(0,d.jsxs)("option",{value:te.code,children:[te.flag," ",te.name]},te.code))})}),(0,m.isAVSFieldVisible)(re.postal_code,s)&&(0,d.jsx)("div",{style:{flex:ie==="row"?1:void 0,backgroundColor:ao,border:`1px solid ${pc}`,padding:"10px",...ie==="row"&&(0,m.isAVSFieldVisible)(re.country,s)?{borderRadius:"0",borderTopRightRadius:$t,borderBottomRightRadius:$t}:{borderRadius:$t}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,m.getPostalCodeLabel)(zt),autoComplete:"billing postal-code",value:bn,onChange:te=>{Rt("zip"),Tt.current.zip=!0,ln.current=te.target.value,wn(te.target.value),Qe?.(te.target.value)},onPointerDown:()=>Rt("zip"),onKeyDown:()=>Rt("zip"),onBlur:()=>{zn("zip")&&Ar(!0)},disabled:Le,required:Nn.required,"aria-invalid":fa||void 0,"aria-describedby":fa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:W()})})]}),fa&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Lo,children:Nn.empty?`${(0,m.getPostalCodeLabel)(s)} is required`:zd(s)})]})})()}),z&&hc,ye&&(0,d.jsx)(bo,{margin:"0.75rem 0",styleOverride:J.errorBanner,children:ye})]}),ga={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"},xs=s=>D?!R||!kr?(0,d.jsx)("pre",{"data-testid":s,style:ga,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":s,style:ga,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${R}`,` directPaypalConfigured=${kr}`,` inAppBrowserDetected=${String(ua)}`,` shouldRenderDirectPayPal=${xo}`,` shouldRenderStripePayPal=${Mo}`,` hasPaypalStripeInstance=${!!Qr}`].join(`
39
+ `)}):null,Ms=s=>D?!H||!an?(0,d.jsx)("pre",{"data-testid":s,style:ga,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":s,style:ga,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${H}`,` currency=${de}`,` amountInCents=${Eo}`,` enabledPaymentMethods: ${JSON.stringify(N??[])}`,` enabledPaymentMethodsProvided=${To}`,` hasEnabledMethods=${la}`,` expressMethods: ${JSON.stringify(ca)}`,` walletExpressMethods: ${JSON.stringify(ro)}`,` paymentElementMethods: ${JSON.stringify(Ao)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(da)}`,` hasStripeInstance=${!!an}`,` shouldRenderWallets=${oo}`,` shouldRenderPaymentElement=${Bo}`].join(`
40
+ `)}):null,Bs=ct==="apm-expanding"||ct==="apm-form"||ct==="apm-collapsing",so;ct==="apm-expanding"?so=Il:ct==="apm-collapsing"&&(so=Rl);let ha=cn?zl(ai,cn):null;if(ge==="buttons"){let s=ct==="buttons"||ct==="expanding"||ct==="apm-expanding",k=ct==="expanding"||ct==="card"||ct==="collapsing",W=De===void 0?{boxSizing:"border-box",height:Va,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ee;ct==="expanding"||ct==="apm-expanding"?Ee=Fd:(ct==="collapsing"||ct==="apm-collapsing")&&(Ee=Bd);let te;return ct==="expanding"?te=Il:ct==="collapsing"&&(te=Rl),(0,d.jsxs)("form",{onSubmit:ci,className:w,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)($i,{}),M&&(0,d.jsx)(ar,{status:M,errorMessage:ye,authorized:tn}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Ee?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Ee?Od:{},...Ee?{animation:Ee,pointerEvents:"none"}:{}},children:[xs("flopay-direct-paypal-gate-debug"),Ms("flopay-stripe-gate-debug"),xo&&rt&&(0,d.jsxs)(d.Fragment,{children:[O&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(Ko.Provider,{value:x,children:(0,d.jsx)(Go,{sessionId:e,nonce:t,billingApiUrl:et,email:L.email,billingName:Y||void 0,onBuyerIdentityReady:j,clientId:rt.clientId,environment:rt.environment,currency:de.toUpperCase(),isSubscription:pt,providerObjectType:Ge,approvalPresentation:pa==="popup"?void 0:pa,onTokenizedBody:Mn,onComplete:l,onErrorChange:ke,onDecline:p,onTechnicalFailure:no,onButtonClick:V,runBeforeButtonClick:ur,isProcessing:Le,onLoadStateChange:ii,onInitializationStateChange:si,session:vt,existingOrderId:O?.orderId,debug:D},O?.orderId??"fresh")})]}),Mo&&(0,d.jsx)(jt.Elements,{stripe:Qr,options:os,children:(0,d.jsx)(Al,{sessionId:e,nonce:t,email:L.email,billingName:Y||void 0,onBuyerIdentityReady:j,billingApiUrl:et,onTokenizedBody:Mn,onErrorChange:ke,isProcessing:Le,onButtonClick:V,onDecline:p,onTechnicalFailure:no,runBeforeButtonClick:ur,onLoadStateChange:ds,placeholderBorderRadius:Vr,popupCapabilityOwner:x,externalTelemetryContext:X})}),oo?(0,d.jsx)(jt.Elements,{stripe:an,options:rs,children:(0,d.jsx)(xl,{sessionId:e,nonce:t,email:L.email,billingName:Y||void 0,onBuyerIdentityReady:j,billingApiUrl:et,intentKind:ae>0?"payment":"setup",expressMethods:ro,onTokenizedBody:Mn,onErrorChange:ke,onButtonClick:V,onDecline:p,onTechnicalFailure:no,runBeforeButtonClick:ur,onLoadStateChange:ps,placeholderBorderRadius:Vr,popupCapabilityOwner:x,externalTelemetryContext:X})}):null,!oo&&hs?(0,d.jsx)("div",{style:{height:Va,borderRadius:Vr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Bo&&(0,d.jsx)(Ml,{sessionId:e,nonce:t,email:L.email,billingName:[L.firstName,L.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:j,billingApiUrl:et,paymentElementMethods:da,stripeInstance:an,paymentElementBaseOptions:ai,onTokenizedBody:Mn,onErrorChange:ke,onButtonClick:V,onDecline:p,runBeforeButtonClick:ur,onLoadStateChange:ys,isProcessing:Le,submitButtonColor:Hr,submitButtonBorderRadius:$t,submitButtonStyle:J.submitButton,onExpandApm:jr,expandedApmMethod:cn,themeId:be,buttonAppearance:{backgroundColor:J.cardButton?.backgroundColor,borderColor:J.cardInputBorder,textColor:J.cardButton?.color,borderRadius:Vr}}),z&&(0,d.jsx)("button",{type:"button",onClick:async()=>{Le||!(await ur("card")).proceed||(V?.("card"),$r())},disabled:Le,style:{width:"100%",...W,...J.cardButton,...Gi({themeBundle:oe,resolvedPrimaryColor:Hr,resolvedBorderRadius:$t,submitButtonStyle:J.submitButton,explicitPrimaryColor:Bn?.colorPrimary}),fontSize:J.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Le?"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:Le?.6:1},onMouseEnter:yt=>{!Le&&(oe||Bn?.colorPrimary)&&(yt.currentTarget.style.backgroundColor=fc)},onMouseLeave:yt=>{(oe||Bn?.colorPrimary)&&(yt.currentTarget.style.backgroundColor=Hr)},onMouseDown:yt=>{yt.currentTarget.style.transform="scale(0.985)"},onMouseUp:yt=>{yt.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(co,{content:De})}),ye&&ct==="buttons"&&(0,d.jsx)(bo,{margin:"0.25rem 0",styleOverride:J.errorBanner,children:ye})]}),z&&k&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...te?{animation:te}:{},...ct==="collapsing"?{pointerEvents:"none"}:{}},children:As}),H&&Bs&&cn&&ha&&an&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...so?{animation:so}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:ui,borderRadius:gi,...No,padding:fi},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:on,style:{display:"inline-flex",alignItems:"center",gap:pi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:J.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...J.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...J.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(uo,{content:gt})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:J.titleFontSize??"1.05rem",color:mi,paddingRight:80,...J.title},children:`Pay with ${(0,m.getStripeMethodDisplayName)(cn)}`})]}),(0,d.jsx)(jt.Elements,{stripe:an,options:ha,children:(0,d.jsx)(Hi,{method:cn,sessionId:e,nonce:t,email:L.email,billingName:[L.firstName,L.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:j,billingApiUrl:et,onTokenizedBody:Mn,onErrorChange:ke,onDecline:p,onCancel:on,runBeforeButtonClick:ur,onButtonClick:V,isProcessing:Le,submitButtonColor:Hr,submitButtonBorderRadius:$t,submitButtonStyle:J.submitButton,errorText:ye})},cn)]})})]})]})}return Bs&&cn&&ha&&an&&H?(0,d.jsxs)("form",{onSubmit:ci,className:w,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)($i,{}),M&&(0,d.jsx)(ar,{status:M,errorMessage:ye,authorized:tn}),(0,d.jsx)("div",{style:{...so?{animation:so}:{},...ct==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:ui,borderRadius:gi,...No,padding:fi},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:on,style:{display:"inline-flex",alignItems:"center",gap:pi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:J.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...J.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...J.backButtonIcon},children:(0,d.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(uo,{content:gt})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:J.titleFontSize??"1.05rem",color:mi,paddingRight:80,...J.title},children:`Pay with ${(0,m.getStripeMethodDisplayName)(cn)}`})]}),(0,d.jsx)(jt.Elements,{stripe:an,options:ha,children:(0,d.jsx)(Hi,{method:cn,sessionId:e,nonce:t,email:L.email,billingName:[L.firstName,L.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:j,billingApiUrl:et,onTokenizedBody:Mn,onErrorChange:ke,onDecline:p,onCancel:on,runBeforeButtonClick:ur,onButtonClick:V,isProcessing:Le,submitButtonColor:Hr,submitButtonBorderRadius:$t,submitButtonStyle:J.submitButton,errorText:ye})},cn)]})})]}):(0,d.jsxs)("form",{onSubmit:ci,className:w,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)($i,{}),M&&(0,d.jsx)(ar,{status:M,errorMessage:ye,authorized:tn}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xs("flopay-direct-paypal-gate-debug-default"),Ms("flopay-stripe-gate-debug-default"),xo&&rt&&(0,d.jsxs)(d.Fragment,{children:[O&&(0,d.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,d.jsx)(Ko.Provider,{value:x,children:(0,d.jsx)(Go,{sessionId:e,nonce:t,billingApiUrl:et,email:L.email,billingName:Y||void 0,onBuyerIdentityReady:j,clientId:rt.clientId,environment:rt.environment,currency:de.toUpperCase(),isSubscription:pt,providerObjectType:Ge,approvalPresentation:pa==="popup"?void 0:pa,onTokenizedBody:Mn,onComplete:l,onErrorChange:ke,onDecline:p,onTechnicalFailure:no,onButtonClick:V,runBeforeButtonClick:ur,isProcessing:Le,onLoadStateChange:ii,onInitializationStateChange:si,session:vt,existingOrderId:O?.orderId,debug:D},O?.orderId??"fresh")})]}),Mo&&(0,d.jsx)(jt.Elements,{stripe:Qr,options:os,children:(0,d.jsx)(Al,{sessionId:e,nonce:t,email:L.email,billingName:Y||void 0,onBuyerIdentityReady:j,billingApiUrl:et,onTokenizedBody:Mn,onErrorChange:ke,isProcessing:Le,onButtonClick:V,onDecline:p,onTechnicalFailure:no,runBeforeButtonClick:ur,onLoadStateChange:ds,placeholderBorderRadius:Vr,popupCapabilityOwner:x,externalTelemetryContext:X})}),oo&&(0,d.jsx)(jt.Elements,{stripe:an,options:rs,children:(0,d.jsx)(xl,{sessionId:e,nonce:t,email:L.email,billingName:Y||void 0,onBuyerIdentityReady:j,billingApiUrl:et,intentKind:ae>0?"payment":"setup",expressMethods:ro,onTokenizedBody:Mn,onErrorChange:ke,onButtonClick:V,onDecline:p,onTechnicalFailure:no,runBeforeButtonClick:ur,onLoadStateChange:ps,placeholderBorderRadius:Vr,popupCapabilityOwner:x,externalTelemetryContext:X})}),Bo&&(0,d.jsx)(Ml,{sessionId:e,nonce:t,email:L.email,billingName:[L.firstName,L.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:et,paymentElementMethods:da,stripeInstance:an,paymentElementBaseOptions:ai,onTokenizedBody:Mn,onErrorChange:ke,onButtonClick:V,onDecline:p,runBeforeButtonClick:ur,onLoadStateChange:ys,isProcessing:Le,submitButtonColor:Hr,submitButtonBorderRadius:$t,submitButtonStyle:J.submitButton,themeId:be,onExpandApm:jr,expandedApmMethod:cn,buttonAppearance:{backgroundColor:J.cardButton?.backgroundColor,borderColor:J.cardInputBorder,textColor:J.cardButton?.color,borderRadius:Vr}})]}),z&&(lc||sc||cc)&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,d.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,d.jsx)("span",{children:"or pay with card"}),(0,d.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),z&&As]})}var A=require("react/jsx-runtime"),_o=44,es="flopay_checkout_saved_payment_resume",Ja=new Map,Ga=new Map;function Ul(e,t){t.settled&&t.consumers===0&&Ja.get(e)===t&&Ja.delete(e)}function Hd(e,t,n){let r=Ga.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Ga.set(e,a);let l=()=>{Ga.get(e)===a&&Ga.delete(e)};return o.then(l,l),o}function aa(e){return new Promise(t=>setTimeout(t,e))}function Ya(e,t,n){let r=_a({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:$e.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function ia(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Yi(e,t,n,r,o,a){let l=Ya(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),ia(l)}function ql(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function $l(e,t,n,r,o){let a=(0,$e.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:a.statusClass}),t instanceof $e.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof $e.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):a.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...a,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function Kl(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function Ji(e){return!e||e.data.stripe?.publishableKey?!1:!!Kl(e)?.clientId}var Kd={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Wd(e){return new Dr.FloPay(Kd,{publishableKey:"provider_unavailable",...e})}async function Xi(e,t){let{publishableKey:n,paypalPublishableKey:r}=Bi(e);return{...await Fi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function ts(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Gd(){if(!ts())return null;try{let e=window.sessionStorage.getItem(es);return e?JSON.parse(e):null}catch{return null}}function jl(e){if(ts())try{window.sessionStorage.setItem(es,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Zi(){if(ts())try{window.sessionStorage.removeItem(es)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Yd(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Vl(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 Qi(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Jd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Hl(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 Xa({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:c,error:p,onComplete:f,onError:g,onInstrument:b,onDecline:T,onCountryChange:w,onZipChange:S,showPayPal:P=!0,showStripe:F=!0,enabledPaymentMethods:fe,showApplePay:R=!0,showGooglePay:H=!0,debug:N=!1,layout:ne,theme:pe,buttonsTheme:we,buttonsStyles:ge,cardButtonContent:be,cardBackButtonContent:lt,cardTitleContent:Ue,showSecurityFooter:ve,onButtonClick:De,onBeforeButtonClick:gt,enableAVS:Ce,cardFieldOrder:tt,cardPreFormSlot:V,avsLayout:Te,submitLabel:Ke,className:Ae,initialErrorMessage:We=null,initialPayPalOrderId:_,children:ie,checkoutMode:me,confirmLabel:U,renderConfirmButton:Oe,onSessionCompleted:Ie}){let $=(0,$e.resolveBillingApiUrl)(r),ut=(0,C.useMemo)(()=>(0,$e.resolveTheme)(pe),[pe]),nt=a??ut?.appearance,Qe=n?"embedded_checkout":"standard_checkout",Ne=Qi(ie,ne),[he,bt]=(0,C.useState)(null),[ae,de]=(0,C.useState)(null),je=(0,C.useRef)(null),rt=(0,C.useRef)(null),pt=(0,C.useRef)(0),[G,ht]=(0,C.useState)(null),ot=(0,C.useRef)(null),[D,mt]=(0,C.useState)(null),Xt=(0,C.useMemo)(()=>n?Co(n):"",[n]),qe=n?`create:${Xt}`:`session:${e??""}`,pn=Hl(D),u=(0,C.useRef)(new Set),x=(0,C.useRef)(qe),ce=(0,C.useRef)(qe);Yr(()=>{ce.current=qe,x.current!==qe&&(x.current=qe,u.current.clear())},[qe]);let B=(0,C.useCallback)(M=>{if(ce.current===qe){if(ki.has(M.name)){if(u.current.has(M.name))return;u.current.add(M.name)}ft(()=>b?.(M))}},[qe,b]),X=ho(B,qe),vt=(0,C.useRef)(!1),Ge=(0,C.useCallback)(M=>{if(vt.current)return;let v=M.gateway||!pn?M:{...M,gateway:pn};B(v)},[B,pn]);(0,C.useEffect)(()=>{X({class:"lifecycle",name:"checkout.mount"})},[X]);let[Ye,xt]=(0,C.useState)(e??""),se=e??Ye,mn=n?"":se,[et,Ft]=(0,C.useState)(!0),[Rn,Vt]=(0,C.useState)(null),[ze,zt]=(0,C.useState)(0),[hn,bn]=(0,C.useState)("full"),[wn,On]=(0,C.useState)(!1),[vn,Ht]=(0,C.useState)(We),[Ve,xe]=(0,C.useState)(null),[Ln,kt]=(0,C.useState)(null),[Cn,_n]=(0,C.useState)(!1),[Kn,Kt]=(0,C.useState)(void 0),[Zt,ln]=(0,C.useState)(""),[It,Mt]=(0,C.useState)(!1),[yn,Qt]=(0,C.useState)(!1),[Ut,Wt]=(0,C.useState)(!1),Tt=(0,C.useRef)(null),re=(0,C.useRef)(0),en=(0,C.useRef)(void 0),[tn,sr]=(0,C.useState)("loading"),[hr,Wn]=(0,C.useState)(0),Gt=(0,C.useRef)(!1),lr=(0,C.useRef)(!1),qt=(0,C.useRef)(!1),z=(0,C.useRef)(null),Ct=(0,C.useRef)(null),at=(0,C.useMemo)(()=>({checkoutMode:me??hn,layout:Jd(ie,ne)}),[me,ie,hn,ne]),q=(0,C.useRef)(f);q.current=f;let Je=(0,C.useRef)(g);Je.current=g;let le=(0,C.useRef)(T);le.current=T;let nn=(0,C.useCallback)(M=>Oa(z,async v=>{try{return await M(v)}catch(ee){throw v.aborted?Qo(ee):ee}}),[]);(0,C.useEffect)(()=>()=>{z.current?.abort(),z.current=null},[]);let Pn=(0,C.useCallback)((M,v)=>{je.current=M,de(M),ot.current=v,ht(v)},[]),rn=(0,C.useCallback)(()=>{let M=rt.current;M&&(rt.current=null,M.destroy())},[]);(0,C.useEffect)(()=>{fn(ae)?.setCheckoutContext(at),G&&G!==ae&&fn(G)?.setCheckoutContext(at)},[ae,G,at]);let br=(0,C.useRef)(Ie);br.current=Ie;let Re=(0,C.useCallback)(M=>{sr(M),!(M!=="exhausted"||qt.current)&&(qt.current=!0,Je.current?.(new $e.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Nn=(0,C.useCallback)(()=>{sr("retrying"),Wn(M=>M+1)},[]);(0,C.useEffect)(()=>{sr("loading"),Wn(0),qt.current=!1},[se]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:$e.SDK_VERSION,checkout_type:Qe,checkout_layout:Ne,billing_api_url:$})},[Ne,Qe,$]);let Gn=(0,C.useMemo)(()=>n?Co(n,!0):"",[n]),Ur=(0,C.useMemo)(()=>Zt===Gn?Kn:void 0,[Kn,Zt,Gn]),Yn=(0,C.useMemo)(()=>n?vi(n,Ur):void 0,[n,Ur]),Jn=me??Yn?.checkoutMode??"full",Yt=(0,C.useMemo)(()=>Yn?{...Yn,checkoutMode:Jn}:void 0,[Yn,Jn]);(0,C.useEffect)(()=>{Kt(void 0),ln(Gn),en.current=void 0,Tt.current=null,Wt(!1)},[Gn]),(0,C.useEffect)(()=>{Ht(We)},[We]);let Ar=(0,C.useCallback)((M,v,ee)=>{ft(()=>{le.current?.(dn(M,v,ee))})},[]),vr=(0,C.useCallback)(async(M,v)=>{Ht(null),kt(null),_n(!1),xe("processing");let ee=v?.sessionId??M.id,K=M.clientSecret||t,_e=Hl(M),Ot=je.current??ot.current,Se=fn(Ot),Pe=Ot?null:Ya($,o,at),O={log:ue=>{Se?Se.log(ue):Pe?.log(ue)},error:ue=>{Se?Se.error(ue):Pe?.error(ue)},terminal:ue=>{Se?Se.terminal(ue):Pe?.terminal(ue)},performance:ue=>{Se?Se.performance(ue):Pe?.performance(ue)},now:()=>Se?.now()??Pe?.now()??0,elapsed:ue=>Se?.elapsed(ue)??Math.max(0,(Pe?.now()??ue)-ue)},Z=O.now(),h=!!(v?.initialAutoProcessingError||v?.initialAutoProcessingPending),y=!1,E,j=()=>{y||(y=!0,h=!0,E=O.now(),O.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),O.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ye=!1,oe=()=>{ye||(ye=!0,O.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),O.performance({stage:"processing",durationMs:O.elapsed(Z),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),E!==void 0&&O.performance({stage:"recovery",durationMs:O.elapsed(E),durationMode:"machine",paymentMethodCategory:"saved"}))};O.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),vt.current=!0;try{O.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{vt.current=!1}X({class:"lifecycle",name:"payment.processing.started",provider:_e}),h&&j();let J;try{let ue=ll(v?.initialAutoProcessingError),Me=v?.initialAutoProcessingError?.type==="3ds_required"&&!v.initialAutoProcessingError.threeDSecureToken&&v.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:v.initialAutoProcessingError.nextActionRedirectUrl}:null,St,Le=Q=>(j(),nn(L=>So(Q,{billingApiUrl:$,sessionId:ee,nonce:K,session:M,signal:L})));if(Me)St=await Le(Me);else if(ue)j(),ue.type==="paypal_redirect_required"&&Ct.current?.publishableKey&&jl({sessionId:ee,publishableKey:Ct.current.publishableKey,paypalPublishableKey:Ct.current.paypalPublishableKey}),St=await nn(Q=>Na(ue,{flopay:je.current,paypalFlopay:ot.current,attempt3DS:v?.attempt3DS,billingApiUrl:$,sessionId:ee,session:M,telemetry:!1,signal:Q})),ue.type==="paypal_redirect_required"&&Zi();else if(v?.initialAutoProcessingPending){let Q=v.initialAutoProcessingPending,L=new Dr.PaymentAPI($,{telemetry:!1}),Y=await nn(Pt=>L.waitForCheckoutSessionCompletion(Q.sessionId,{initialDelayMs:Q.retryAfterMs,nonce:K,statusUrl:Q.statusUrl,signal:Pt})),Be=Y.data.session,Fe=Y.autoProcessingError?.type==="3ds_required"&&Y.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Y.autoProcessingError.nextActionRedirectUrl}:null;if(Fe)St=await Le(Fe);else{if(!Nr(Be))throw mo(Be);St=xr(Be,ee)}}else{if(v?.initialAutoProcessingError)throw Rr(v.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:v.initialAutoProcessingError.checkoutMethod});if(v?.fromCreateSession)return v?.fallbackToFull&&(bn("full"),Vl("full")),!1;{let Q=await wo({billingApiUrl:$,sessionId:ee,session:M,nonce:K,telemetry:!1});Q.type==="success"?St=Q.result:Q.type==="next_action_required"?St=await Le(Q):(j(),Q.type==="paypal_redirect_required"&&Ct.current?.publishableKey&&jl({sessionId:ee,publishableKey:Ct.current.publishableKey,paypalPublishableKey:Ct.current.paypalPublishableKey}),St=await nn(L=>Na(Q,{flopay:je.current,paypalFlopay:ot.current,attempt3DS:v?.attempt3DS,billingApiUrl:$,sessionId:ee,session:M,telemetry:!1,signal:L})),Q.type==="paypal_redirect_required"&&Zi())}}ee&&Po(ee),oe(),h&&(O.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),O.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),O.terminal({outcome:St.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),_n(St.status==="authorized"),xe("success"),await aa(600),J=()=>q.current?.(St)}catch(ue){let Me=ea(ue);if(Me.code==="three_ds_aborted")return!1;let St=Me.checkoutMethod??Zo;Ht(Me.message),kt(Me.message),_n(!1),v?.fallbackToFull&&(O.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),bn("full"),Vl("full")),oe();let Le=Me.statusCode===void 0?void 0:(0,$e.telemetryStatusClass)(Me.statusCode,"unknown"),Q=Le==="4xx"?{requestCategory:"process_payment",statusClass:Le}:{},L=Le===void 0||Le==="4xx";if(L&&(Me.telemetryOutcome==="payment_declined"||!!(Me.declineCode||Me.code?.toLowerCase().includes("declin"))))O.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Q});else if(L&&(Me.telemetryOutcome==="validation_rejected"||Me.type==="validation_error"))O.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Q});else{let Fe=(0,$e.classifyTelemetryFailure)(ue,h?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Pt=Me.telemetryRequestCategory??"process_payment";vt.current=!0;try{O.error({...Fe,...Me.telemetryFailureCategory?{failureCategory:Me.telemetryFailureCategory}:{},stage:h?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Pt})}finally{vt.current=!1}X({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Pt,provider:_e})}return ft(()=>Je.current?.(Me)),Ar(St,Me,{code:Me.code,declineCode:Me.declineCode}),xe("error"),await Promise.allSettled([aa(400),v?.ensureProvidersReady?v.ensureProvidersReady():Promise.resolve()]),h&&(O.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),O.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{oe(),Pe&&ia(Pe),xe(null),kt(null)}return ft(J),!0},[Ar,X,t,$,nn,o,at]);(0,C.useEffect)(()=>{if(typeof window>"u"||lr.current)return;let M=new URLSearchParams(window.location.search),v=M.get("payment_intent_client_secret");if(!v)return;let ee=Gd();ee&&(lr.current=!0,(async()=>{let K,_e=0;Ht(null),kt(null),xe("processing"),On(!0);try{if(M.get("redirect_status")==="failed")throw Object.assign(new $e.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Ot,paypalFlopay:Se}=await Fi({publishableKey:ee.publishableKey,paypalPublishableKey:ee.paypalPublishableKey,billingApiUrl:$,locale:l,telemetry:o});K=fn(Se??Ot),K?.setCheckoutContext(at),_e=K?.now()??0,K?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),K?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=(Se??Ot)?.getRawProvider();if(!Pe)throw Object.assign(new $e.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:O,error:Z}=await Pe.retrievePaymentIntent(v);if(Z)throw Object.assign(new $e.FloPayError(Z.message??"Failed to retrieve PayPal payment status.","api_error",{code:Z.code}),{checkoutMethod:"paypal"});let h=$s(O?.status);if(!O||h==="failed")throw Object.assign(new $e.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let y=typeof O.payment_method=="string"?O.payment_method:O.payment_method?.id,E=h;if(ee.sessionId){let oe=(await new Dr.PaymentAPI($,{telemetry:!1}).getUnifiedCheckoutSession(ee.sessionId)).data.session;if(oe&&oe.status!=="complete"){let J=await wo({billingApiUrl:$,sessionId:ee.sessionId,session:oe,telemetry:!1,tokenizedData:{id:y??O.id,type:"card",threeDSecureActionResultTokenId:O.id,isPaypal:!0}});if(J.type!=="success")throw Object.assign(new $e.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});E=J.result.status}}ee.sessionId&&Po(ee.sessionId),K?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),K?.performance({stage:"redirect_resume",durationMs:K.elapsed(_e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),K?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),xe("success"),await aa(600),ft(()=>q.current?.({status:E,paymentIntentId:O.id,paymentMethodId:y,checkoutMethod:"paypal"}))}catch(Ot){let Se=ea(Ot),Pe=Se.checkoutMethod??"paypal",O=!!(Se.declineCode||Se.code?.toLowerCase().includes("declin"));if(K)K.performance({stage:"redirect_resume",durationMs:K.elapsed(_e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),O?K.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):K.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(O){let Z=Ya($,o,at);Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ia(Z)}else Yi($,o,at,"REDIRECT_RESUME_FAILED","redirect_resume");Ht(Se.message),kt(Se.message),ft(()=>Je.current?.(Se)),Ar(Pe,Se,{code:Se.code,declineCode:Se.declineCode}),xe("error"),await aa(400)}finally{Zi(),Yd(),xe(null),kt(null),On(!1)}})())},[Ar,l,$,o,at]);let En=(0,C.useRef)(null),Cr=(0,C.useMemo)(()=>Yt?Co(Yt):"",[Yt]),Xn=(0,C.useRef)(Yt);Xn.current=Yt,(0,C.useEffect)(()=>{xt(e??"")},[e]),(0,C.useEffect)(()=>{Gt.current=!1,Ht(We),kt(null),_n(!1),xe(null)},[Cr,We,e]);async function Zn(M,v,ee){let K=Ya($,o,at),_e=new Dr.PaymentAPI($,{telemetry:!1}),Ot=!1;try{let Se=M.idempotencyKey===void 0?void 0:(0,$e.resolveIdempotencyKey)(M.idempotencyKey),Pe=_i(v,ee),O=Ei(v,ee);Pe?.canonicalIdentity===ee&&O&&O.canonicalIdentity===void 0&&(Fa(v,ee,O.idempotencyKey),O={...O,canonicalIdentity:ee});let Z=Se??(O?.canonicalIdentity===ee?O.idempotencyKey:void 0),h,y=!1;K.log({name:Pe?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let E=Pe?.sid??null,j=null,ye,oe,J=!1;if(E)try{j=await _e.getUnifiedCheckoutSession(E,Pe?.nonce),Pe&&Pe.canonicalIdentity===void 0&&(rl(j.data.session,M)?(Ba(v,ee,E,Pe.nonce??j.data.session?.clientSecret),O&&O.canonicalIdentity===void 0&&(Fa(v,ee,O.idempotencyKey),Z??(Z=O.idempotencyKey))):(Ma(v,ee),O=null,Z=Se,E=null,j=null));let Me=j?.data.session?.status,St=j?.data.session,Le=St?.clientSecret||Pe?.nonce;if(E&&St?.buyerIdentified===!1&&Le&&(oe=po(_e,E,Le,M.account)),E&&j&&Me==="complete"){if(Ti(E))return{sid:E,result:j};Ma(v,ee),E=null,j=null,y=!0}}catch{K.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Pe?.canonicalIdentity===void 0?(Ma(v,ee),Z=Se):xa(v,ee),E=null}if(!E){!Se&&(y||!Z)&&(Z=(0,$e.resolveIdempotencyKey)(),h=Z),Z&&Fa(v,ee,Z);let Me=K.now(),St=0;K.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Le={...M,idempotencyKey:Z,avsCheck:!!Ce,avsConfig:typeof Ce=="object"?Ce:void 0,checkoutType:"embedded_checkout",checkoutLayout:Qi(ie,ne)};Object.defineProperty(Le,Dr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Y=>{St=Math.max(St,Y)}}});let Q=()=>{ql(K,"session_create",Me,St)},L=Y=>{$l(K,Y,"session_create",Me,St)&&X({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,$e.isDetachedSessionEligible)(Le)){let Y=await _e.createDetachedSession(Le);Y.claimed.catch(()=>{}),j=Y.shell,E=Y.sessionId,oe=Y.claim;let Be=K.now();K.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ye=Y.claimed.then(Fe=>{let Pt=Fe.data.session?.id??Y.sessionId;return Pt&&Ba(v,ee,Pt,Fe.data.session?.clientSecret??Y.nonce),ql(K,"session_claim",Be),Q(),Fe},Fe=>{throw xa(v,ee),$l(K,Fe,"session_claim",Be,0)&&X({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Fe}).finally(()=>ia(K)),ye.catch(()=>{}),Ot=!0,K.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),K.performance({stage:"session_shell",durationMs:K.now()-Me,durationMode:"machine",requestCategory:"session_create",attempt:St,statusClass:"2xx",paymentMethodCategory:"card"})}else j=await _e.createAndFetchSession(Le),Q()}catch(Y){throw L(Y),Y}E=j.data.session?.id??E??"",E&&!ye&&Ba(v,ee,E,j.data.session?.clientSecret)}let ue=j?.data.session;return!oe&&E&&ue?.buyerIdentified===!1&&ue.clientSecret&&(oe=po(_e,E,ue.clientSecret,M.account)),{sid:E??"",result:j,sdkGeneratedIdempotencyKey:h,...ye?{claimed:ye}:{},...oe?{claim:oe}:{},...J?{claimRequiresIdentity:!0}:{}}}finally{Ot||ia(K)}}let Pr=(0,C.useRef)(Zn);Yr(()=>{Pr.current=Zn},[Zn]);let Qn=(0,C.useCallback)(async(M,v)=>{let ee=Xn.current;if(!ee)throw new $e.FloPayError("createSession is required to bootstrap checkout.","validation_error");let K=vi(ee,M),_e=Co(K),Ot=nl(K),Se=Ja.get(_e);if(!Se){let Z={canonicalIdentity:_e,promise:Pr.current(K,Ot,_e),consumers:0,settled:!1};Se=Z,Ja.set(_e,Z);let h=()=>{Z.settled=!0,Ul(_e,Z)};Z.promise.then(h,h)}Se.consumers+=1;let Pe=!1,O=()=>{Pe||(Pe=!0,Se.consumers-=1,Ul(_e,Se))};v?.(O);try{let Z=await Se.promise;En.current=_e,M&&(ln(Gn),Kt(ue=>zs(ue,M)));let{sid:h,result:y,claimed:E,claim:j,claimRequiresIdentity:ye}=Z;if(en.current=j,Wt(ye===!0),bt(y),y.data.session&&mt(y.data.session),h&&xt(h),E){re.current+=1;let ue=re.current;Tt.current=E,Qt(!0),E.then(Me=>{re.current===ue&&(Tt.current===E&&(Tt.current=null),bt(Me),Me.data.session&&mt(Me.data.session),Qt(!1),Wt(!1))},Me=>{re.current===ue&&(Tt.current===E&&(Tt.current=null),Qt(!1),Wt(!1),Vt(Me instanceof $e.FloPayError?Me:new $e.FloPayError(Me instanceof Error?Me.message:"Failed to create session","api_error")))})}else re.current+=1,Tt.current=null,Qt(!1),Wt(!1);let{flopay:oe,paypalFlopay:J}=await Xi(y,{billingApiUrl:$,locale:l,telemetry:o});return Pn(oe,J),Ft(!1),Z}catch(Z){throw En.current===_e&&(En.current=null),Z}finally{v||O()}},[Gn,Pn,l,$,o]),Rt=(0,C.useRef)(vr);Rt.current=vr;let zn=(0,C.useRef)(Qn);zn.current=Qn;let cr=(0,C.useCallback)(async M=>{if(!Xd(M)||It)return{sessionId:Ye,session:D};Mt(!0);try{let v=await Qn(M);return{sessionId:v.sid,session:v.result.data.session??null}}finally{Mt(!1)}},[Qn,It,Ye,D]),Un=(0,C.useCallback)(async M=>{let v=en.current;if(!v)return;let ee=re.current,K=await v(M);re.current===ee&&(bt(K),K.data.session&&mt(K.data.session))},[]),Sn=(0,C.useCallback)(async()=>{await Tt.current},[]),ct=(0,C.useCallback)(async()=>(await Sn(),{proceed:!0}),[Sn]);(0,C.useEffect)(()=>{let M=!1,v,ee=++pt.current;rn(),Vt(null),zt(0);let K=()=>{M=!0,pt.current===ee&&(pt.current+=1,rn())},_e=Xn.current;if(Cr&&_e)return bn(Jn),Ft(!1),En.current===Cr?K:(mt(Us(_e,me)),(async()=>{let Pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),O=Jn==="auto"&&!Gt.current&&!Pe;O&&(Ht(null),kt(null),xe("processing"));try{let Z=await zn.current(void 0,j=>{v=j}),h=Z.result.data.session??null;Ct.current=Bi(Z.result);let y=Ji(Z.result),E=Ti(Z.sid||h?.id);if(!M&&O&&h&&!y&&!E){Gt.current=!0,await Hd(Cr,Z.sdkGeneratedIdempotencyKey,()=>Rt.current(h,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Z.result.autoProcessingError,initialAutoProcessingPending:Z.result.autoProcessingPending,autoProcessingAttempted:Z.result.autoProcessingAttempted,sessionId:Z.sid||h.id}));return}!M&&O&&((y||E)&&(Gt.current=!0),xe(null),kt(null))}catch(Z){if(M)return;let h=Ca(Z);if(O&&h==="session_auto_completed"){Gt.current=!0,xe("success"),await aa(600),M||(ft(()=>{q.current?.({status:"succeeded"})}),xe(null),kt(null));return}O&&(xe(null),kt(null));let y=Z instanceof $e.FloPayError?Z:new $e.FloPayError(Z instanceof Error?Z.message:"Failed to create session","api_error");Vt(y)}finally{v?.(),v=void 0}})(),()=>{K(),v?.()});Ft(!0);async function Ot(){let Pe=!1,O=null;try{let Z=new Dr.PaymentAPI($,{telemetry:!1}),h=await Z.getUnifiedCheckoutSession(se,t);if(O=h,M)return;bt(h);let y=h.data.session??null;if(mt(y),!y)throw new $e.FloPayError("No session data returned","api_error");let E=y.checkoutMode;if(E==="setup")throw new $e.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){Ft(!1),ft(()=>{q.current?.(xr(y,se)),br.current?.(y.successUrl??"")});return}if(y.status==="complete"){Ft(!1),ft(()=>{br.current?.(y.successUrl??"")});return}if(y.status==="expired")throw va(y);Pe=!0;let j=me??E??"full";bn(j),re.current+=1;let ye=y.clientSecret||t;en.current=y.buyerIdentified===!1&&ye?po(Z,se,ye,{...y.customer?.id?{userId:y.customer.id}:{}}):void 0,Qt(!1),Wt(!1);let oe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),J=Ji(h);if(j==="auto"&&!Gt.current&&!oe&&!J){Gt.current=!0;let ue=Se(h);try{if(await Rt.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ue,sessionId:se||y.id}),M)return;await ue,M||Ft(!1);return}catch{if(M)return;await ue,M||Ft(!1);return}}await Se(h),M||Ft(!1)}catch(Z){if(M)return;let h=Ns(Z,Pe);if(Pe&&X({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),h){let{errorCode:E,stage:j,...ye}=h;Yi($,o,at,E,j,ye)}if(h?.stage==="provider_load"&&(me??O?.data.session?.checkoutMode??"full")==="full"&&Ls(O,P,F)){let E=Wd({billingApiUrl:$,locale:l,telemetry:o});rt.current=E,Pn(E,null),zt(1),Ft(!1);return}let y=Z instanceof $e.FloPayError&&h?.stage!=="provider_load"?Z:Os();y!==Z&&ft(()=>Je.current?.(y)),Vt(y),Ft(!1)}}async function Se(Pe){let{flopay:O,paypalFlopay:Z,...h}=await Xi(Pe,{billingApiUrl:$,locale:l,telemetry:o});Ct.current={publishableKey:h.publishableKey,paypalPublishableKey:h.paypalPublishableKey},Pn(O,Z),zt(0)}return Ot(),K},[me,Cr,Jn,mn,t,P,F]);let kn=(0,C.useCallback)(async()=>{if(!he||ze!==1)return;let M=pt.current;zt(2);try{let{flopay:v,paypalFlopay:ee}=await Xi(he,{billingApiUrl:$,locale:l,telemetry:o});if(pt.current!==M)return;rn(),Pn(v,ee),zt(0)}catch(v){if(pt.current!==M)return;let{errorCode:ee,stage:K,..._e}=hi(v);Yi($,o,at,ee,K,_e)}},[rn,Pn,l,ze,$,o,at,he]),cn=!!(se&&(D?.clientSecret||t)),qn=wn||!cn,qr=(0,C.useCallback)(async()=>{if(!(wn||!cn||!D)){On(!0),Ht(null);try{await vr(D,{attempt3DS:!0,fallbackToFull:!0,sessionId:se||D.id})}finally{On(!1)}}},[se,wn,cn,vr,D]),$n=Kl(he,_),Sr=Ji(he),Tn=(0,C.useMemo)(()=>{if(!(!he||!D||!he.data.stripe?.publishableKey))return{billingApiUrl:$}},[he,D,$]),An=!!(n&&!ie&&ne==="buttons"&&gt&&Jn==="full"),$r=!!(se&&(D?.vault?.html||Or(D))),jn=(0,C.useMemo)(()=>({session:D,loading:et,error:Rn,checkoutMode:hn,inlineSessionDraft:Yt,applyInlineSessionPatch:An?cr:void 0,inlineSessionPatchProcessing:It,claimPending:yn,claimRequiresIdentity:Ut,claimBuyerIdentity:Un,waitForDataAttachment:Sn}),[D,et,Rn,hn,Yt,An,cr,It,yn,Ut,Un,Sn]),jr=!!n&&ne==="buttons"&&!Sr&&!$r&&(!ae||!Tn),on=Ve?(0,A.jsx)(ar,{status:Ve,errorMessage:Ln,authorized:Cn}):null;if(et&&!$r){if(c)return(0,A.jsxs)(A.Fragment,{children:[c,on]});if(ne==="buttons"){let M=ut?.buttonsLayout?.cardButton?.borderRadius??ut?.appearance.variables?.borderRadius??8,v=ee=>(0,A.jsx)("div",{style:{height:ee,borderRadius:M,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[P&&v(_o),F&&(R||H)&&v(_o),F&&v(_o),(0,A.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),on]})}return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,A.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,A.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),on]})}return Rn?p?(0,A.jsx)(pr.Provider,{value:jn,children:p(Rn)}):(0,A.jsx)(pr.Provider,{value:jn,children:(0,A.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Rn.message})}):jr?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(pr.Provider,{value:jn,children:(0,A.jsx)(Qd,{onButtonClick:De,showPayPal:P,showStripe:F,showApplePay:R,showGooglePay:H,theme:pe,buttonsTheme:we,buttonsStyles:ge,cardButtonContent:be,cardBackButtonContent:lt,cardTitleContent:Ue})}),on]}):Sr&&D&&$n?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(pr.Provider,{value:jn,children:(0,A.jsxs)("div",{className:Ae,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[vn&&(0,A.jsx)(bo,{icon:!1,children:vn}),tn==="retrying"&&(0,A.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),tn==="exhausted"&&(0,A.jsxs)("div",{role:"alert",children:[(0,A.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,A.jsx)("button",{type:"button",onClick:Nn,children:"Retry PayPal"})]}),tn!=="exhausted"&&(0,A.jsx)("div",{"aria-hidden":tn==="retrying"?!0:void 0,style:tn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,A.jsx)(tl,{sessionId:se,nonce:D.clientSecret||void 0,billingApiUrl:$,email:D.customer?.email||Yt?.account?.email,billingName:[D.customer?.firstName,D.customer?.lastName].filter(Boolean).join(" ")||[Yt?.account?.firstName,Yt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Un,clientId:$n.clientId,environment:$n.environment,currency:(D.currency??"usd").toUpperCase(),isSubscription:D.mode==="subscription",providerObjectType:$n.providerObjectType,approvalPresentation:$n.approvalPresentation,existingOrderId:$n.existingOrderId,onComplete:f,onErrorChange:Ht,onDecline:T,onButtonClick:De,runBeforeButtonClick:ct,onInitializationStateChange:Re,allowAutomaticRetry:hr===0,session:D,telemetry:o,telemetryContext:at,onInstrument:Ge,debug:N},`${qe}:paypal-init-${hr}`)})]})}),on]}):hn==="confirm"?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(pr.Provider,{value:jn,children:(0,A.jsx)(Jo,{flopay:ae,paypalFlopay:G,options:Tn??{billingApiUrl:$},onInstrument:Ge,children:(0,A.jsxs)("div",{className:Ae,children:[vn&&(0,A.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:vn}),Oe?Oe({onConfirm:qr,isProcessing:qn}):(0,A.jsx)("button",{type:"button",onClick:qr,disabled:qn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:qn?"not-allowed":"pointer",opacity:qn?.6:1},children:wn?"Processing...":U??"Confirm Purchase"})]})},qe)}),on]}):(!ae||!Tn)&&!($r&&hn==="full")?(0,A.jsx)(A.Fragment,{children:on}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(pr.Provider,{value:jn,children:(0,A.jsxs)(Jo,{flopay:ae,paypalFlopay:G,options:Tn??{billingApiUrl:$},onInstrument:Ge,children:[ze===1&&(0,A.jsx)("button",{type:"button",onClick:kn,children:"Retry payment methods"}),ie?(0,A.jsxs)(A.Fragment,{children:[vn&&(0,A.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:vn}),(0,A.jsx)(Zd,{sessionId:se,nonce:D?.clientSecret||void 0,billingApiUrl:$,session:D,submitLabel:Ke,children:ie})]}):(0,A.jsx)(Wa,{sessionId:se,nonce:D?.clientSecret||void 0,telemetry:o,email:D?.customer?.email||Yt?.account?.email,userId:D?.customer?.id||Yt?.account?.userId,firstName:D?.customer?.firstName||Yt?.account?.firstName,lastName:D?.customer?.lastName||Yt?.account?.lastName,totalAmount:D?Math.round((0,$e.buildCheckoutDisplayData)(D).total*100):0,currency:D?.currency?.toLowerCase()??"usd",onComplete:f,onError:g,onDecline:T,error:vn,onErrorChange:Ht,showPayPal:P,showStripe:F,enabledPaymentMethods:ze?[]:fe??he?.data.stripe?.enabledPaymentMethods??D?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:he?.data.stripe?.enabledPaymentMethodCountries,showApplePay:R,showGooglePay:H,layout:ne,theme:pe,buttonsTheme:we,buttonsStyles:ge,appearance:nt,cardButtonContent:be,cardBackButtonContent:lt,cardTitleContent:Ue,onButtonClick:De,onBeforeButtonClick:gt,onBuyerIdentityReady:Un,enableAVS:Ce,...tt?{cardFieldOrder:tt}:{},...V?{cardPreFormSlot:V}:{},avsLayout:Te,country:D?.customer?.country,city:D?.customer?.city,state:D?.customer?.state,onCountryChange:w,onZipChange:S,avsCheck:!!Ce,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Qi(ie,ne),className:Ae,submitLabel:Ke,directPaypal:$n,isSubscription:D?.mode==="subscription",session:D,dataAttachmentPending:yn,dataAttachmentRequiresIdentity:Ut,debug:N})]},qe)}),on]})}function Zd({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:a}){return(0,A.jsx)(A.Fragment,{children:C.default.Children.map(a,l=>{if(!C.default.isValidElement(l))return l;let c=l.props,p={};return c.sessionId||(p.sessionId=e),!c.nonce&&t&&(p.nonce=t),c.billingApiUrl||(p.billingApiUrl=n),c.submitLabel===void 0&&o!==void 0&&(p.submitLabel=o),r?.customer&&(c.email||(p.email=r.customer.email),c.userId||(p.userId=r.customer.id),c.firstName||(p.firstName=r.customer.firstName),c.lastName||(p.lastName=r.customer.lastName)),Object.keys(p).length===0?l:C.default.cloneElement(l,p)})})}function Qd({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:c,cardButtonContent:p,cardBackButtonContent:f,cardTitleContent:g}){let[b,T]=(0,C.useState)(!1),w=(0,C.useMemo)(()=>(0,$e.resolveTheme)(a),[a]),S=(0,C.useMemo)(()=>{let R=w?.buttonsLayout??(0,$e.resolveButtonsLayoutTheme)(l);return c?{...R,...c,cardButton:{...R.cardButton,...c.cardButton},cardFormContainer:{...R.cardFormContainer,...c.cardFormContainer},backButton:{...R.backButton,...c.backButton},backButtonIcon:{...R.backButtonIcon,...c.backButtonIcon},submitButton:{...R.submitButton,...c.submitButton},title:{...R.title,...c.title}}:R},[w,l,c]),P=w?.buttonsLayout?.cardButton?.borderRadius??w?.appearance.variables?.borderRadius??8,F=R=>(0,A.jsx)("div",{style:{height:R,borderRadius:P,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),fe=p===void 0?{boxSizing:"border-box",height:_o,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let R=S.cardInputBorder??"#e5e7eb",H=S.cardInputBackground??"white",N=lo(f),ne=lo(g);return(0,A.jsxs)("div",{style:{backgroundColor:S.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...S.cardFormContainer},children:[(0,A.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,A.jsxs)("button",{type:"button",onClick:()=>T(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:N?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...S.backButton},children:[(0,A.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...S.backButtonIcon},children:(0,A.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,A.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,A.jsx)(uo,{content:f})]}),ne?(0,A.jsx)("div",{style:{flex:1}}):(0,A.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...S.title},children:(0,A.jsx)(Uo,{content:g})})]}),(0,A.jsx)("div",{style:{backgroundColor:H,border:`1px solid ${R}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,A.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,A.jsxs)("div",{style:{display:"flex"},children:[(0,A.jsx)("div",{style:{flex:1,backgroundColor:H,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${R}`,borderLeft:`1px solid ${R}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,A.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,A.jsx)("div",{style:{flex:1,backgroundColor:H,borderTop:"none",borderRight:`1px solid ${R}`,borderBottom:`1px solid ${R}`,borderLeft:`1px solid ${R}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,A.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,A.jsx)("div",{style:{backgroundColor:H,border:`1px solid ${R}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,A.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,A.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...S.submitButton,opacity:.5}}),(0,A.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,T.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&z(So),n&&(r||o)&&z(So),n&&(0,T.jsx)("button",{type:"button",onClick:()=>{e?.("card"),y(!0)},style:{width:"100%",...ue,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:_.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,..._.cardButton},onMouseDown:k=>{k.currentTarget.style.transform="scale(0.985)"},onMouseUp:k=>{k.currentTarget.style.transform="scale(1)"},children:(0,T.jsx)(ao,{content:u})}),(0,T.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var yr=require("react/jsx-runtime"),jd=44;function Bl(e){return new Promise(t=>setTimeout(t,e))}function Kd(e,t){return e instanceof nr.FloPayError?e:new nr.FloPayError(e instanceof Error?e.message:t,"api_error")}function Wd(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Hd(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 Fl({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:d,subscriptions:u,account:m,successUrl:h,cancelUrl:b,couponCodes:y,tagsData:C,utmMetadata:_,billingApiUrl:ne,locale:z,theme:ue,appearance:k,buttonsTheme:$,buttonsStyles:U,onSuccess:se,onError:Se,onDecline:Pe,children:pe,disabled:ye=!1,type:yt="button",style:He,...we}){let Me=(0,Ze.useMemo)(()=>(0,nr.resolveBillingApiUrl)(ne),[ne]),fe=(0,Ze.useMemo)(()=>Hd({createSession:n,clientId:a,products:l,items:d,subscriptions:u,account:m,successUrl:h,cancelUrl:b,couponCodes:y,tagsData:C,utmMetadata:_}),[m,b,a,y,n,l,d,u,h,C,_]),[Re,Ge]=(0,Ze.useState)(!1),[oe,_e]=(0,Ze.useState)(null),[ge,nt]=(0,Ze.useState)(null),[rt,M]=(0,Ze.useState)(!1),[V,ie]=(0,Ze.useState)(null),ae=(0,Ze.useRef)(!0),Ye=(0,Ze.useRef)(null),Ce=(0,Ze.useRef)(V),N=(0,Ze.useRef)(se),ut=(0,Ze.useRef)(Se),ot=(0,Ze.useRef)(Pe),he=(0,Ze.useCallback)(g=>Ra(Ye,async q=>{try{return await g(q)}catch(Fe){throw q.aborted?Ko(Fe):Fe}}),[]);(0,Ze.useEffect)(()=>{Ce.current=V},[V]),(0,Ze.useEffect)(()=>{N.current=se},[se]),(0,Ze.useEffect)(()=>{ut.current=Se},[Se]),(0,Ze.useEffect)(()=>{ot.current=Pe},[Pe]),(0,Ze.useEffect)(()=>(ae.current=!0,()=>{ae.current=!1,Ye.current?.abort()}),[]),(0,Ze.useEffect)(()=>{if(typeof window>"u")return;let g=q=>{q.key==="Escape"&&ie(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let le=(0,Ze.useCallback)((g,q=jo)=>{ot.current?.(nn(q,g,{code:g.code,declineCode:g.declineCode}))},[]),H=(0,Ze.useCallback)(async g=>{ae.current&&(nt(null),M(g.result.status==="authorized"),_e("success"),await Bl(600),ae.current&&dt(()=>N.current?.(g)))},[]),Le=(0,Ze.useCallback)(async(g,q)=>{ae.current&&(ut.current?.(g),q?.emitDecline&&le(g,q.method),nt(g.message),M(!1),_e("error"),await Bl(400))},[le]),Oe=(0,Ze.useCallback)(async(g,q,Fe)=>{let Je=g.data.session??null;if(!Je)throw new nr.FloPayError("No session data returned","api_error");let De=Je.clientSecret||t;if(Nr(Je)){await H({result:Ir(Je,q),session:Je,sessionId:Je.id||q,autoCompleted:!1});return}if(Je.status==="expired")throw ua(Je);try{if(g.autoProcessingPending){let W=g.autoProcessingPending,St=new qa.PaymentAPI(Me),Tt=await he(G=>St.waitForCheckoutSessionCompletion(W.sessionId,{initialDelayMs:W.retryAfterMs,nonce:De,statusUrl:W.statusUrl,signal:G})),ft=Tt.data.session,un=Tt.autoProcessingError?.type==="3ds_required"&&Tt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Tt.autoProcessingError.nextActionRedirectUrl}:null;if(un&&q&&De){let G=await he(Lt=>bo(un,{billingApiUrl:Me,sessionId:q,nonce:De,session:Je,signal:Lt}));await H({result:G,session:Je,sessionId:Je.id||q,autoCompleted:!1});return}if(Tt.autoProcessingError)throw br(Tt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Tt.autoProcessingError.checkoutMethod});if(!Nr(ft))throw lo(ft);await H({result:Ir(ft,q),session:ft,sessionId:ft.id||q,autoCompleted:!1});return}if(g.autoProcessingError){let W=g.autoProcessingError.nextActionRedirectUrl;if(g.autoProcessingError.type==="3ds_required"&&W&&q&&De){let St=await he(G=>Ci({billingApiUrl:Me,sessionId:q,nonce:De,nextActionRedirectUrl:W,signal:G}));if(St.status==="declined")throw br({type:St.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:St.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let un=(await new qa.PaymentAPI(Me).waitForCheckoutSessionCompletion(q,{initialDelayMs:0,nonce:De})).data.session;if(!Nr(un))throw br({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await H({result:Ir(un,q),session:un,sessionId:un.id||q,autoCompleted:!1});return}throw br(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(Fe?.fromCreateSession&&g.autoProcessingAttempted===!0)throw br({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let $t=await vo({billingApiUrl:Me,sessionId:q??Je.id,session:Je,nonce:De});if($t.type==="next_action_required"&&De){let W=q??Je.id,St=await he(Tt=>bo($t,{billingApiUrl:Me,sessionId:W,nonce:De,session:Je,signal:Tt}));await H({result:St,session:Je,sessionId:Je.id||W,autoCompleted:!1});return}if($t.type!=="success")throw br({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await H({result:$t.result,session:Je,sessionId:Je.id||q,autoCompleted:!1})}catch($t){let W=Wo($t);if(W.code==="three_ds_aborted")return;let St=Je.id||q;await Le(W,{emitDecline:!0,method:W.checkoutMethod??jo}),Wd(W,St)&&St&&ae.current&&ie({sessionId:St,errorMessage:W.message,nonce:De||void 0,payPalOrderId:W.orderId})}},[t,Me,he,Le,H]),ze=(0,Ze.useCallback)(async g=>{if(we.onClick?.(g),!(g.defaultPrevented||ye||Re)){if(ie(null),e&&fe){let q=new nr.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await Le(q),ae.current&&(_e(null),nt(null));return}if(!e&&!fe){let q=new nr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Le(q),ae.current&&(_e(null),nt(null));return}Ge(!0),nt(null),M(!1),_e("processing");try{let q=new qa.PaymentAPI(Me);if(e){let Fe=await q.getUnifiedCheckoutSession(e,t);await Oe(Fe,e);return}try{let Fe=await q.createAndFetchSession({...fe});await Oe(Fe,Fe.data.session?.id??null,{fromCreateSession:!0})}catch(Fe){if(pa(Fe)==="session_auto_completed"){await H({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Fe}}catch(q){await Le(Kd(q,"Automatic payment failed. Please try again."))}finally{ae.current&&(_e(null),nt(null),Ge(!1))}}},[we.onClick,fe,ye,Re,t,Oe,Me,e,Le,H]),je=(0,Ze.useCallback)(g=>{let q=Ce.current;ie(null),N.current?.({result:g,session:null,sessionId:q?.sessionId??null,autoCompleted:!1})},[]),Be=(0,Ze.useCallback)(g=>{ut.current?.(g)},[]),Ne=(0,Ze.useCallback)(g=>{ot.current?.(g)},[]),ce=(0,Ze.useMemo)(()=>(0,nr.resolveTheme)(ue),[ue]),dn=(0,Ze.useMemo)(()=>{let g=ce?.buttonsLayout??(0,nr.resolveButtonsLayoutTheme)($);return U?{...g,...U,cardButton:{...g.cardButton,...U.cardButton}}:g},[ce,$,U]),Jt=(0,Ze.useMemo)(()=>{let g=ce?.appearance;return k?g?{...g,...k,variables:{...g.variables,...k.variables}}:k:g},[k,ce]),ee=Jt?.variables,at=ee?.colorPrimary??"#4A49FF",Z=ee?.colorPrimaryHover??Co(at,.12),Q=ee?.borderRadius??"8px";return(0,yr.jsxs)(yr.Fragment,{children:[(0,yr.jsx)("button",{...we,type:yt,onClick:ze,disabled:ye||Re,"aria-busy":Re,style:{width:"100%",...pe===void 0?{boxSizing:"border-box",height:jd,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...dn.cardButton,...Li({themeBundle:ce,resolvedPrimaryColor:at,resolvedBorderRadius:Q,submitButtonStyle:dn.submitButton,explicitPrimaryColor:ee?.colorPrimary}),fontSize:dn.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ye||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:ye||Re?.6:1,...He},onMouseEnter:g=>{we.onMouseEnter?.(g),!g.defaultPrevented&&!ye&&!Re&&(ce||ee?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Z)},onMouseLeave:g=>{we.onMouseLeave?.(g),!g.defaultPrevented&&(ce||ee?.colorPrimary)&&(g.currentTarget.style.backgroundColor=at)},onMouseDown:g=>{we.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{we.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:(0,yr.jsx)(ao,{content:pe})}),oe&&(0,yr.jsx)(tr,{status:oe,errorMessage:ge,authorized:rt}),V&&(0,yr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&ie(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,yr.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,yr.jsx)(Ua,{sessionId:V.sessionId,nonce:V.nonce,checkoutMode:"full",billingApiUrl:Me,locale:z,theme:ue,...Jt?{appearance:Jt}:{},buttonsTheme:$,buttonsStyles:U,initialErrorMessage:V.errorMessage,initialPayPalOrderId:V.payPalOrderId,cardTitleContent:null,onComplete:je,onError:Be,onDecline:Ne})})})]})}var $a=require("@flopay/js/card-setup"),$n=require("@flopay/shared"),Ct=require("react");var Dl={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Nl(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?Dl.dark:Dl.light,a=t.colorText??(r?"#F1F5F9":"#262833"),l=e.appearance.rules?.[".Label"];return{panel:{...n.background===void 0?{}:{background:n.background},...n.backgroundColor===void 0?{}:{backgroundColor:n.backgroundColor},...n.border===void 0?{}:{border:n.border},...n.borderRadius===void 0?{}:{borderRadius:n.borderRadius},...n.boxShadow===void 0?{}:{boxShadow:n.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(r?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:l?.color??a}}var Cr=require("react/jsx-runtime"),Qo=class extends $n.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Ll(e,t={}){let n=e instanceof $n.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new Qo(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r===void 0?{}:{statusCode:r}})}function Ol({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:d,onComplete:u,onDecline:m,onCancel:h,onValidation:b,onError:y}){let[C,_]=(0,Ct.useState)(null),[ne,z]=(0,Ct.useState)(null),[ue,k]=(0,Ct.useState)(null),[$,U]=(0,Ct.useState)(null),[se,Se]=(0,Ct.useState)(null),Pe=(0,Ct.useRef)(!1),pe=(0,Ct.useRef)(!1),ye=(0,Ct.useMemo)(()=>typeof o=="object"?void 0:(0,$n.resolveTheme)(o),[o]),yt=(0,Ct.useMemo)(()=>typeof o=="object"?o:ye?Aa({appearance:ye.appearance,buttonsStyles:ye.buttonsLayout,layout:"default"}):null,[ye,o]),He=(0,Ct.useMemo)(()=>Xs(ye?.buttonsLayout.cardFormContainer,a),[ye,a]),we=(0,Ct.useMemo)(()=>ye?Nl(ye):void 0,[ye]),Me=(0,Ct.useRef)(d),fe=(0,Ct.useRef)(y),Re=(0,Ct.useRef)(u),Ge=(0,Ct.useRef)(m),oe=(0,Ct.useRef)(h),_e=(0,Ct.useRef)(b),ge=(0,Ct.useRef)(!1),nt=(0,Ct.useRef)(!1),rt=(0,Ct.useRef)(0);return Me.current=d,fe.current=y,Re.current=u,Ge.current=m,oe.current=h,_e.current=b,(0,Ct.useEffect)(()=>{let M=rt.current+1;return rt.current=M,()=>{queueMicrotask(()=>{rt.current===M&&(ge.current||nt.current||(nt.current=!0,dt(()=>{oe.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Ct.useEffect)(()=>{let M=!0,V=new $a.PaymentAPI((0,$n.resolveBillingApiUrl)(n),{telemetry:r});return _(null),z(null),k(null),ge.current=!1,nt.current=!1,(async()=>{try{if(!e.trim())throw new $n.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new $n.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ie=await V.getUnifiedCheckoutSession(e,t);if(!M)return;let ae=ie.data.session;if(!ae||!(0,$n.isCardSetupCheckoutSession)(ae))throw new $n.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Ye=ae.vault;if(Ye?.html?.trim()||(Ye=await V.getVaultCapture(e,t)),!Ye.html?.trim())throw new $n.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!M)return;z(Ye),_(new $a.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ie){if(!M)return;let ae=Ll(ie);ge.current=!0,k(ae),dt(()=>fe.current?.(ae))}})(),()=>{M=!1,V.destroy()}},[n,t,e,r]),(0,Ct.useEffect)(()=>{if(!C)return;let M=!1;pe.current=!1,Pe.current=!1;let V=C.on("submitting",()=>{Pe.current=!0,Se(null),U("processing")}),ie=C.on("complete",Ce=>{ge.current=!0,Pe.current=!1,U("success"),(async()=>(await new Promise(N=>setTimeout(N,600)),!pe.current&&(pe.current=!0,dt(()=>{Re.current?.({status:"succeeded",sessionId:e,...Ce.paymentMethod?{paymentMethod:Ce.paymentMethod}:{}})}),M||U(null))))()}),ae=C.on("decline",Ce=>{ge.current=!0,Pe.current=!1,Se(Ce.message??null),U("error"),dt(()=>{Ge.current?.({status:"declined",sessionId:e,...Ce.declineReason?{reason:Ce.declineReason}:{},...Ce.message?{message:Ce.message}:{}})}),(async()=>(await new Promise(N=>setTimeout(N,400)),M||U(null)))()}),Ye=C.on("challenge_dismissed",()=>{U(null)});return()=>{M=!0,V(),ie(),ae(),Ye()}},[C,e]),ue?(0,Cr.jsx)("div",{role:"alert",children:ue.message}):!C||!ne?.html?(0,Cr.jsx)(Cr.Fragment,{children:l}):(0,Cr.jsxs)(Cr.Fragment,{children:[$&&(0,Cr.jsx)(tr,{status:$,errorMessage:se,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...we?{theme:we}:{}}),(0,Cr.jsx)(Po,{capture:C,html:ne.html,messageToken:ne.messageToken,expectedOrigin:ne.expectedOrigin,theme:yt,containerStyle:He,onReady:()=>{dt(()=>Me.current?.())},onValidation:M=>{dt(()=>_e.current?.(M))},onError:M=>{if(!M)return;Pe.current&&(Pe.current=!1,Se(M),U("error"),setTimeout(()=>U(null),400));let V=Ll(new Error(M),{code:"card_setup_widget_failed",retryable:!0});dt(()=>fe.current?.(V))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,A.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&F(_o),n&&(r||o)&&F(_o),n&&(0,A.jsx)("button",{type:"button",onClick:()=>{e?.("card"),T(!0)},style:{width:"100%",...fe,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:S.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,...S.cardButton},onMouseDown:R=>{R.currentTarget.style.transform="scale(0.985)"},onMouseUp:R=>{R.currentTarget.style.transform="scale(1)"},children:(0,A.jsx)(co,{content:p})}),(0,A.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var gr=require("react/jsx-runtime"),eu=44;function Wl(e){return new Promise(t=>setTimeout(t,e))}function tu(e,t){return e instanceof ir.FloPayError?e:new ir.FloPayError(e instanceof Error?e.message:t,"api_error")}function nu(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 Gl({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:c,subscriptions:p,account:f,successUrl:g,cancelUrl:b,couponCodes:T,tagsData:w,utmMetadata:S,billingApiUrl:P,locale:F,theme:fe,appearance:R,buttonsTheme:H,buttonsStyles:N,onSuccess:ne,onError:pe,onDecline:we,children:ge,disabled:be=!1,type:lt="button",style:Ue,...ve}){let De=(0,Ze.useMemo)(()=>(0,ir.resolveBillingApiUrl)(P),[P]),gt=(0,Ze.useMemo)(()=>ru({createSession:n,clientId:a,products:l,items:c,subscriptions:p,account:f,successUrl:g,cancelUrl:b,couponCodes:T,tagsData:w,utmMetadata:S}),[f,b,a,T,n,l,c,p,g,w,S]),[Ce,tt]=(0,Ze.useState)(!1),[V,Te]=(0,Ze.useState)(null),[Ke,Ae]=(0,Ze.useState)(null),[We,_]=(0,Ze.useState)(!1),[ie,me]=(0,Ze.useState)(null),U=(0,Ze.useRef)(!0),Oe=(0,Ze.useRef)(null),Ie=(0,Ze.useRef)(ie),$=(0,Ze.useRef)(ne),ut=(0,Ze.useRef)(pe),nt=(0,Ze.useRef)(we),Qe=(0,Ze.useCallback)(u=>Oa(Oe,async x=>{try{return await u(x)}catch(ce){throw x.aborted?Qo(ce):ce}}),[]);(0,Ze.useEffect)(()=>{Ie.current=ie},[ie]),(0,Ze.useEffect)(()=>{$.current=ne},[ne]),(0,Ze.useEffect)(()=>{ut.current=pe},[pe]),(0,Ze.useEffect)(()=>{nt.current=we},[we]),(0,Ze.useEffect)(()=>(U.current=!0,()=>{U.current=!1,Oe.current?.abort()}),[]),(0,Ze.useEffect)(()=>{if(typeof window>"u")return;let u=x=>{x.key==="Escape"&&me(null)};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[]);let Ne=(0,Ze.useCallback)((u,x=Zo)=>{nt.current?.(dn(x,u,{code:u.code,declineCode:u.declineCode}))},[]),he=(0,Ze.useCallback)(async u=>{U.current&&(Ae(null),_(u.result.status==="authorized"),Te("success"),await Wl(600),U.current&&ft(()=>$.current?.(u)))},[]),bt=(0,Ze.useCallback)(async(u,x)=>{U.current&&(ut.current?.(u),x?.emitDecline&&Ne(u,x.method),Ae(u.message),_(!1),Te("error"),await Wl(400))},[Ne]),ae=(0,Ze.useCallback)(async(u,x,ce)=>{let B=u.data.session??null;if(!B)throw new ir.FloPayError("No session data returned","api_error");let X=B.clientSecret||t;if(Nr(B)){await he({result:xr(B,x),session:B,sessionId:B.id||x,autoCompleted:!1});return}if(B.status==="expired")throw va(B);try{if(u.autoProcessingPending){let Ge=u.autoProcessingPending,Ye=new Za.PaymentAPI(De),xt=await Qe(et=>Ye.waitForCheckoutSessionCompletion(Ge.sessionId,{initialDelayMs:Ge.retryAfterMs,nonce:X,statusUrl:Ge.statusUrl,signal:et})),se=xt.data.session,mn=xt.autoProcessingError?.type==="3ds_required"&&xt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:xt.autoProcessingError.nextActionRedirectUrl}:null;if(mn&&x&&X){let et=await Qe(Ft=>So(mn,{billingApiUrl:De,sessionId:x,nonce:X,session:B,signal:Ft}));await he({result:et,session:B,sessionId:B.id||x,autoCompleted:!1});return}if(xt.autoProcessingError)throw Rr(xt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:xt.autoProcessingError.checkoutMethod});if(!Nr(se))throw mo(se);await he({result:xr(se,x),session:se,sessionId:se.id||x,autoCompleted:!1});return}if(u.autoProcessingError){let Ge=u.autoProcessingError.nextActionRedirectUrl;if(u.autoProcessingError.type==="3ds_required"&&Ge&&x&&X){let Ye=await Qe(et=>Mi({billingApiUrl:De,sessionId:x,nonce:X,nextActionRedirectUrl:Ge,signal:et}));if(Ye.status==="declined")throw Rr({type:Ye.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ye.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:u.autoProcessingError.checkoutMethod});let mn=(await new Za.PaymentAPI(De).waitForCheckoutSessionCompletion(x,{initialDelayMs:0,nonce:X})).data.session;if(!Nr(mn))throw Rr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:u.autoProcessingError.checkoutMethod});await he({result:xr(mn,x),session:mn,sessionId:mn.id||x,autoCompleted:!1});return}throw Rr(u.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:u.autoProcessingError.checkoutMethod})}if(ce?.fromCreateSession&&u.autoProcessingAttempted===!0)throw Rr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let vt=await wo({billingApiUrl:De,sessionId:x??B.id,session:B,nonce:X});if(vt.type==="next_action_required"&&X){let Ge=x??B.id,Ye=await Qe(xt=>So(vt,{billingApiUrl:De,sessionId:Ge,nonce:X,session:B,signal:xt}));await he({result:Ye,session:B,sessionId:B.id||Ge,autoCompleted:!1});return}if(vt.type!=="success")throw Rr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await he({result:vt.result,session:B,sessionId:B.id||x,autoCompleted:!1})}catch(vt){let Ge=ea(vt);if(Ge.code==="three_ds_aborted")return;let Ye=B.id||x;await bt(Ge,{emitDecline:!0,method:Ge.checkoutMethod??Zo}),nu(Ge,Ye)&&Ye&&U.current&&me({sessionId:Ye,errorMessage:Ge.message,nonce:X||void 0,payPalOrderId:Ge.orderId})}},[t,De,Qe,bt,he]),de=(0,Ze.useCallback)(async u=>{if(ve.onClick?.(u),!(u.defaultPrevented||be||Ce)){if(me(null),e&&gt){let x=new ir.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await bt(x),U.current&&(Te(null),Ae(null));return}if(!e&&!gt){let x=new ir.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await bt(x),U.current&&(Te(null),Ae(null));return}tt(!0),Ae(null),_(!1),Te("processing");try{let x=new Za.PaymentAPI(De);if(e){let ce=await x.getUnifiedCheckoutSession(e,t);await ae(ce,e);return}try{let ce=await x.createAndFetchSession({...gt});await ae(ce,ce.data.session?.id??null,{fromCreateSession:!0})}catch(ce){if(Ca(ce)==="session_auto_completed"){await he({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ce}}catch(x){await bt(tu(x,"Automatic payment failed. Please try again."))}finally{U.current&&(Te(null),Ae(null),tt(!1))}}},[ve.onClick,gt,be,Ce,t,ae,De,e,bt,he]),je=(0,Ze.useCallback)(u=>{let x=Ie.current;me(null),$.current?.({result:u,session:null,sessionId:x?.sessionId??null,autoCompleted:!1})},[]),rt=(0,Ze.useCallback)(u=>{ut.current?.(u)},[]),pt=(0,Ze.useCallback)(u=>{nt.current?.(u)},[]),G=(0,Ze.useMemo)(()=>(0,ir.resolveTheme)(fe),[fe]),ht=(0,Ze.useMemo)(()=>{let u=G?.buttonsLayout??(0,ir.resolveButtonsLayoutTheme)(H);return N?{...u,...N,cardButton:{...u.cardButton,...N.cardButton}}:u},[G,H,N]),ot=(0,Ze.useMemo)(()=>{let u=G?.appearance;return R?u?{...u,...R,variables:{...u.variables,...R.variables}}:R:u},[R,G]),D=ot?.variables,mt=D?.colorPrimary??"#4A49FF",Xt=D?.colorPrimaryHover??Ro(mt,.12),qe=D?.borderRadius??"8px";return(0,gr.jsxs)(gr.Fragment,{children:[(0,gr.jsx)("button",{...ve,type:lt,onClick:de,disabled:be||Ce,"aria-busy":Ce,style:{width:"100%",...ge===void 0?{boxSizing:"border-box",height:eu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...ht.cardButton,...Gi({themeBundle:G,resolvedPrimaryColor:mt,resolvedBorderRadius:qe,submitButtonStyle:ht.submitButton,explicitPrimaryColor:D?.colorPrimary}),fontSize:ht.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:be||Ce?"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:be||Ce?.6:1,...Ue},onMouseEnter:u=>{ve.onMouseEnter?.(u),!u.defaultPrevented&&!be&&!Ce&&(G||D?.colorPrimary)&&(u.currentTarget.style.backgroundColor=Xt)},onMouseLeave:u=>{ve.onMouseLeave?.(u),!u.defaultPrevented&&(G||D?.colorPrimary)&&(u.currentTarget.style.backgroundColor=mt)},onMouseDown:u=>{ve.onMouseDown?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(0.985)")},onMouseUp:u=>{ve.onMouseUp?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(1)")},children:(0,gr.jsx)(co,{content:ge})}),V&&(0,gr.jsx)(ar,{status:V,errorMessage:Ke,authorized:We}),ie&&(0,gr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:u=>{u.target===u.currentTarget&&me(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,gr.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,gr.jsx)(Xa,{sessionId:ie.sessionId,nonce:ie.nonce,checkoutMode:"full",billingApiUrl:De,locale:F,theme:fe,...ot?{appearance:ot}:{},buttonsTheme:H,buttonsStyles:N,initialErrorMessage:ie.errorMessage,initialPayPalOrderId:ie.payPalOrderId,cardTitleContent:null,onComplete:je,onError:rt,onDecline:pt})})})]})}var Qa=require("@flopay/js/card-setup"),Hn=require("@flopay/shared"),Et=require("react");var Yl={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Jl(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?Yl.dark:Yl.light,a=t.colorText??(r?"#F1F5F9":"#262833"),l=e.appearance.rules?.[".Label"];return{panel:{...n.background===void 0?{}:{background:n.background},...n.backgroundColor===void 0?{}:{backgroundColor:n.backgroundColor},...n.border===void 0?{}:{border:n.border},...n.borderRadius===void 0?{}:{borderRadius:n.borderRadius},...n.boxShadow===void 0?{}:{boxShadow:n.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(r?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:l?.color??a}}var Tr=require("react/jsx-runtime"),sa=class extends Hn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Xl(e,t={}){let n=e instanceof Hn.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new sa(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r===void 0?{}:{statusCode:r}})}function Zl({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:c,onComplete:p,onDecline:f,onCancel:g,onValidation:b,onError:T}){let[w,S]=(0,Et.useState)(null),[P,F]=(0,Et.useState)(null),[fe,R]=(0,Et.useState)(null),[H,N]=(0,Et.useState)(null),[ne,pe]=(0,Et.useState)(null),we=(0,Et.useRef)(!1),ge=(0,Et.useRef)(!1),be=(0,Et.useMemo)(()=>typeof o=="object"?void 0:(0,Hn.resolveTheme)(o),[o]),lt=(0,Et.useMemo)(()=>typeof o=="object"?o:be?Ua({appearance:be.appearance,buttonsStyles:be.buttonsLayout,layout:"default"}):null,[be,o]),Ue=(0,Et.useMemo)(()=>ul(be?.buttonsLayout.cardFormContainer,a),[be,a]),ve=(0,Et.useMemo)(()=>be?Jl(be):void 0,[be]),De=(0,Et.useRef)(c),gt=(0,Et.useRef)(T),Ce=(0,Et.useRef)(p),tt=(0,Et.useRef)(f),V=(0,Et.useRef)(g),Te=(0,Et.useRef)(b),Ke=(0,Et.useRef)(!1),Ae=(0,Et.useRef)(!1),We=(0,Et.useRef)(0);return De.current=c,gt.current=T,Ce.current=p,tt.current=f,V.current=g,Te.current=b,(0,Et.useEffect)(()=>{let _=We.current+1;return We.current=_,()=>{queueMicrotask(()=>{We.current===_&&(Ke.current||Ae.current||(Ae.current=!0,ft(()=>{V.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,Et.useEffect)(()=>{let _=!0,ie=new Qa.PaymentAPI((0,Hn.resolveBillingApiUrl)(n),{telemetry:r});return S(null),F(null),R(null),Ke.current=!1,Ae.current=!1,(async()=>{try{if(!e.trim())throw new Hn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Hn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let me=await ie.getUnifiedCheckoutSession(e,t);if(!_)return;let U=me.data.session;if(!U||!(0,Hn.isCardSetupCheckoutSession)(U))throw new Hn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Oe=U.vault;if(Oe?.html?.trim()||(Oe=await ie.getVaultCapture(e,t)),!Oe.html?.trim())throw new Hn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!_)return;F(Oe),S(new Qa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(me){if(!_)return;let U=Xl(me);Ke.current=!0,R(U),ft(()=>gt.current?.(U))}})(),()=>{_=!1,ie.destroy()}},[n,t,e,r]),(0,Et.useEffect)(()=>{if(!w)return;let _=!1;ge.current=!1,we.current=!1;let ie=w.on("submitting",()=>{we.current=!0,pe(null),N("processing")}),me=w.on("complete",Ie=>{Ke.current=!0,we.current=!1,N("success"),(async()=>(await new Promise($=>setTimeout($,600)),!ge.current&&(ge.current=!0,ft(()=>{Ce.current?.({status:"succeeded",sessionId:e,...Ie.paymentMethod?{paymentMethod:Ie.paymentMethod}:{}})}),_||N(null))))()}),U=w.on("decline",Ie=>{Ke.current=!0,we.current=!1,pe(Ie.message??null),N("error"),ft(()=>{tt.current?.({status:"declined",sessionId:e,...Ie.declineReason?{reason:Ie.declineReason}:{},...Ie.message?{message:Ie.message}:{}})}),(async()=>(await new Promise($=>setTimeout($,400)),_||N(null)))()}),Oe=w.on("challenge_dismissed",()=>{N(null)});return()=>{_=!0,ie(),me(),U(),Oe()}},[w,e]),fe?(0,Tr.jsx)("div",{role:"alert",children:fe.message}):!w||!P?.html?(0,Tr.jsx)(Tr.Fragment,{children:l}):(0,Tr.jsxs)(Tr.Fragment,{children:[H&&(0,Tr.jsx)(ar,{status:H,errorMessage:ne,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...ve?{theme:ve}:{}}),(0,Tr.jsx)(Io,{capture:w,html:P.html,messageToken:P.messageToken,expectedOrigin:P.expectedOrigin,theme:lt,containerStyle:Ue,onReady:()=>{ft(()=>De.current?.())},onValidation:_=>{ft(()=>Te.current?.(_))},onError:_=>{if(!_)return;we.current&&(we.current=!1,pe(_),N("error"),setTimeout(()=>N(null),400));let ie=Xl(new Error(_),{code:"card_setup_widget_failed",retryable:!0});ft(()=>gt.current?.(ie))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});