@flopay/react 1.11.0 → 1.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var _d=Object.create;var Xa=Object.defineProperty;var Td=Object.getOwnPropertyDescriptor;var Ad=Object.getOwnPropertyNames;var Md=Object.getPrototypeOf,xd=Object.prototype.hasOwnProperty;var Fd=(e,t)=>{for(var n in t)Xa(e,n,{get:t[n],enumerable:!0})},xl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ad(t))!xd.call(e,o)&&o!==n&&Xa(e,o,{get:()=>t[o],enumerable:!(r=Td(t,o))||r.enumerable});return e};var is=(e,t,n)=>(n=e!=null?_d(Md(e)):{},xl(t||!e||!e.__esModule?Xa(n,"default",{value:e,enumerable:!0}):n,e)),Bd=e=>xl(Xa({},"__esModule",{value:!0}),e);var Bp={};Fd(Bp,{DirectPayPalButton:()=>Sa,FloPayAutomaticPaymentButton:()=>$c,FloPayCardSetup:()=>Hc,FloPayCardSetupError:()=>La,FloPayCheckout:()=>Bi,FloPayPaymentMethodSetup:()=>ld,FloPayProvider:()=>ka,SplitCardForm:()=>Ai,VaultCardFields:()=>lo,dropThirdPartyOnlyError:()=>dd.dropThirdPartyOnlyError,useCheckout:()=>Hl,useFloPay:()=>Wr,usePayPalFloPay:()=>Qa});module.exports=Bd(Bp);var dd=require("@flopay/shared");var Di=require("@flopay/js"),lr=require("@flopay/shared"),ct=require("react");var qt=require("react/jsx-runtime");function Dd(){return(0,qt.jsxs)(qt.Fragment,{children:[(0,qt.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,qt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,qt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,qt.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,qt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Od(){return(0,qt.jsx)(qt.Fragment,{children:"Go back"})}function Ld(){return(0,qt.jsx)(qt.Fragment,{children:"Secure card checkout"})}function Bo(e){return e!==void 0&&(e===""||e===null||e===!1)}function Do({content:e}){return(0,qt.jsx)(qt.Fragment,{children:e===void 0?(0,qt.jsx)(Dd,{}):e})}function Oo({content:e}){return(0,qt.jsx)(qt.Fragment,{children:e===void 0?(0,qt.jsx)(Od,{}):e})}function ga({content:e}){return(0,qt.jsx)(qt.Fragment,{children:e===void 0?(0,qt.jsx)(Ld,{}):e})}var Rt=require("@flopay/shared"),Nd="Checkout is temporarily unavailable. Please try again later.";function ss(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Rt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Ud(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 Fl(){return new Rt.FloPayError(Nd,"api_error",{code:"CheckoutInitializationFailed"})}function ls(e){return!!e?.gateways?.worldpayCorporateGateway}function Qr(e){return e?.status==="open"&&ls(e)}function Bl(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")||Qr(r))||t&&e?.data.paypal?.publishableKey)}function Dl(e,t){if(t&&(!(e instanceof Rt.FloPayError)||e.type==="authentication_error"))return ss(e);if(!(e instanceof Rt.FloPayError&&Ud(e))){if(!t&&!(e instanceof Rt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Rt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Rt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Rt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function Lo(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let i={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,Rt.isCardHolderNamePlaceholder)(i.firstName,i.lastName);if(!(0,Rt.isValidEmail)(i.email))return Promise.reject(new Rt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[d,g]of Object.entries(i)){if(c&&d.endsWith("Name")||typeof g!="string")continue;let b=g.trim();b&&(p[d]=b)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function Ol(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 cs(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 Ll(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,i)=>a+(i.overrideAmount??i.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,i)=>({uuid:`synthetic-${a.type??"item"}-${i}`,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 go(e){if((0,Rt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ds(e,t){return t?{...e,...t}:e}function yn(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,i=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{},...i?{sessionId:i}:{}}}function eo(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var zd=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function to(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of zd)if(n.test(t))return r;return e}function $r(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function jr(e){return e?.status==="authorized"||e?.status==="complete"}function no(e,t){if(e.data.session)return e.data.session;let n=e.raw,r=n?.latestTransactionAttempt?.result,o=n?.status==="authorized"||r==="AUTHORIZED";return o||n?.status==="completed"||r==="SUCCESS"?{...t,status:o?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Nl(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ja(e){let t=Nl(e);return new Rt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Za(e){return e instanceof Rt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function No(e){return Nl(e)?new Rt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Rt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Rt.FloPayError(Rt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ha(e,t){return e==="processing"||(0,Rt.isMoneySettledOutcome)(e,t)}function Ul(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function zl(e,t){let n=e;if((0,Rt.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:i}=await n.retrieveSetupIntent(t);if(i)throw new Rt.FloPayError(i.message??"Failed to retrieve setup intent.","api_error",{...i.code?{code:i.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new Rt.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}var qd=["apple_pay","google_pay"];function ql(e,t="automatic",n){let r=(0,Rt.resolveSetupFutureUsage)(n,qd,"wallet");return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],...r?{setupFutureUsage:r}:{}}}function us(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 ba(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"),rt=require("@flopay/shared"),R=is(require("react"),1);var ps=require("react"),or=(0,ps.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),vr=(0,ps.createContext)({session:null,loading:!1,error:null});var ai=require("@flopay/js"),Wt=require("@flopay/shared"),Xl=require("@paypal/paypal-js"),M=require("react");var Vl=require("@flopay/shared"),Cr=require("react"),Hr=require("react/jsx-runtime");function zn(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),i=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...i||t?{lastName:i??""}:{}}}function Uo(){let[e,t]=(0,Cr.useState)(null),n=(0,Cr.useRef)(null),r=(0,Cr.useRef)(0),o=(0,Cr.useCallback)((i,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:i,identity:c}),new Promise(p=>{n.current=p})),[]),a=(0,Cr.useCallback)(i=>{let c=n.current;n.current=null,t(null),c?.(i)},[]);return(0,Cr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function zo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[i,c]=(0,Cr.useState)(e.email?.trim()??""),p=(0,Vl.isValidEmail)(i.trim());return(0,Hr.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,Hr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Hr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Hr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:i,onChange:d=>c(d.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Hr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Hr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Hr.jsxs)("button",{type:"button",disabled:!p||o,onClick:()=>{n(zn({...e,email:i.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Vd=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),$d=["https://www.paypal.com","https://www.sandbox.paypal.com"];function ro(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 $l(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 ho(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function xr(e){if(typeof e!="object"||e===null)return;let t=e;return ho(t.code)??ho(t.type)??ho(t.name)}function qo(e){if(!(typeof e!="object"||e===null))return ho(e.decline_code)}function bo(e){return typeof e!="object"||e===null?!1:ho(e.type)?.toLowerCase()==="card_error"||qo(e)!==void 0}function jd(e){let t=$l(e)?.toLowerCase()??"",n=xr(e)?.toLowerCase()??"";return Vd.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 ms(e){if(xr(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=$l(e)??"";return n.includes("No ack for postMessage init()")&&$d.some(r=>n.includes(r))&&n.includes("10000ms")}function oo(e,t){if(bo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=jd(e)||t.inAppBrowser&&!t.handoffObserved&&ms(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function ao(e){return oo(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var jl=require("@flopay/shared"),Pa=require("react");function Wr(){return(0,Pa.useContext)(or).flopay}function Qa(){return(0,Pa.useContext)(or).paypalFlopay??null}function Hl(){return(0,Pa.useContext)(vr)}function Wl(){return(0,Pa.useContext)(or).billingApiUrl||(0,jl.resolveBillingApiUrl)()}function Kr(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 ei(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function ti(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Kl=require("@flopay/shared"),vo=require("react");function Je(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 ni=require("react"),Po=typeof window>"u"?ni.useEffect:ni.useLayoutEffect;var Hd={"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 Wd(e){return e==="stripe"||e==="paypal"?e:void 0}function Kd(e){let t=Wd(e.provider),n={schemaVersion:Kl.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Hd[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 ys=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Vo(e,t){let n=(0,vo.useRef)(e);n.current=e;let r=(0,vo.useRef)(new Set),o=(0,vo.useRef)(t),a=(0,vo.useRef)(t);return Po(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,vo.useCallback)(i=>{if(a.current!==t)return;let c=Kd(i);if(c){if(ys.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}Je(()=>n.current?.(c))}},[t])}var Gl=require("react"),va=(0,Gl.createContext)(null);function ri(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Gd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Yd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Xd(){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 Jd(e){let t=Xd(),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 oi(e){let t=globalThis[Yd];return Jd(t?.(e)??{})}function fn(e){if(e)return e[Gd]}var on=require("react");function Ca(e,t){let n=(0,on.useRef)(0),r=(0,on.useRef)(null),o=(0,on.useRef)(null),a=(0,on.useRef)(e),i=(0,on.useRef)(t?.onHandoffObserved),c=(0,on.useRef)(t?.defersMissingTerminal),p=(0,on.useRef)(t?.onMissingTerminalDeferred);(0,on.useEffect)(()=>{a.current=e,i.current=t?.onHandoffObserved,c.current=t?.defersMissingTerminal,p.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let d=(0,on.useCallback)((P=o.current)=>{P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),g=(0,on.useCallback)(P=>{d();let w=n.current+1;return n.current=w,r.current=null,o.current={generation:w,method:P,timer:null,yieldedControl:!1},w},[d]),b=(0,on.useCallback)(P=>{let w=o.current;return P!==void 0&&w?.generation!==P?!1:(d(w),o.current=null,(P===void 0||r.current===P)&&(r.current=null),!0)},[d]),T=(0,on.useCallback)(P=>{let w=o.current,K=P??w?.generation??n.current;(P===void 0||w?.generation===P)&&(d(w),o.current=null),r.current=K},[d]),_=(0,on.useCallback)(P=>r.current===(P??n.current),[]),S=(0,on.useCallback)(P=>o.current?.generation===P&&r.current!==P,[]),A=(0,on.useCallback)(()=>{let P=o.current;P&&(d(P),!P.yieldedControl&&(P.yieldedControl=!0,i.current?.(P.method)))},[d]),I=(0,on.useCallback)(()=>{let P=o.current;!P?.yieldedControl||document.visibilityState!=="visible"||(d(P),P.timer=setTimeout(()=>{if(P.timer=null,o.current?.generation===P.generation){if(c.current?.(P.method)){p.current?.(P.method,P.generation);return}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))},[d]);return(0,on.useEffect)(()=>{let P=()=>{document.visibilityState==="visible"?I():A()};return document.addEventListener("visibilitychange",P),window.addEventListener("blur",A),window.addEventListener("focus",I),()=>{document.removeEventListener("visibilitychange",P),window.removeEventListener("blur",A),window.removeEventListener("focus",I),d()}},[d,A,I]),{startAttempt:g,finishAttempt:b,invalidateAttempt:T,isAttemptInvalidated:_,isAttemptCurrent:S,generationRef:n}}var ar=require("react/jsx-runtime"),ii=45,Zd=1e3,Qd=11e3,eu={width:"100%",minHeight:ii,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"},tu={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 nu(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:tu[e.kind]??null}}function Yl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":ms(t)?"paypal_init_timeout":"paypal_init_failure"}function ru(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 ou(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Jl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:i,environment:c,currency:p,isSubscription:d,providerObjectType:g,approvalPresentation:b,onTokenizedBody:T,onComplete:_,onErrorChange:S,onDecline:A,onTechnicalFailure:I,isProcessing:P=!1,onLoadStateChange:w,onInitializationStateChange:K,allowAutomaticRetry:k=!0,onButtonClick:ge,runBeforeButtonClick:q,session:X,existingOrderId:Se,telemetry:oe,telemetryContext:De,onInstrument:Ze,debug:le=!1}){let Ee=Wr(),He=Vo(Ze,e),Re=(0,M.useMemo)(()=>{if(Ee)return null;let v=oi({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Wt.SDK_VERSION,enabled:oe!==!1});return v.setCheckoutContext(De??{}),v.beginCheckout(De??{}),v},[n,Ee,oe,De?.checkoutMode,De?.layout]),_e=(0,M.useMemo)(()=>fn(Ee),[Ee]);(0,M.useEffect)(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let Ie=(0,M.useMemo)(()=>({error:v=>{_e?_e.error(v):Re?.error(v),He({class:"technical_error",errorCode:v.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":v.errorCode,requestCategory:v.requestCategory,provider:v.provider})},log:v=>{_e?_e.log(v):Re?.log(v),He({class:"lifecycle",name:v.name,provider:v.provider})},performance:v=>{_e?_e.performance(v):Re?.performance(v)},terminal:v=>{_e?_e.terminal(v):Re?.terminal(v)},startTiming:()=>_e?.now()??Re?.now()??0,elapsed:v=>_e?.elapsed(v)??Math.max(0,(Re?.now()??v)-v)}),[He,_e,Re]),ce=(0,M.useRef)(null),de=(0,M.useRef)(0),Pe=(0,M.useRef)(null),Ae=(0,M.useRef)(null),J=(0,M.useRef)(null),ee=(0,M.useContext)(va),he=(0,M.useRef)(null);he.current||(he.current=ri());let U=ee??he.current,we=(0,M.useRef)(null),ie=(0,M.useRef)(!1),[Te,te]=(0,M.useState)(!1),[at,We]=(0,M.useState)(!1),[Ve,ot]=(0,M.useState)(0),Ke=(0,M.useRef)(0),[it,$e]=(0,M.useState)(!1),vt=(0,M.useRef)(!1),Ot=(0,M.useRef)(!1),[ht,_t]=(0,M.useState)(!1),[z,be]=(0,M.useState)(!1),{request:Qe,collect:Z,finish:Le}=Uo(),bt=(0,M.useRef)({sessionId:e,required:!(0,Wt.isValidEmail)(r?.trim()||X?.customer?.email?.trim())});bt.current.sessionId!==e&&(bt.current={sessionId:e,required:!(0,Wt.isValidEmail)(r?.trim()||X?.customer?.email?.trim())});let Ye=bt.current.required,It=(0,M.useMemo)(()=>n.replace(/\/+$/,""),[n]),h=X?.gateways?.paypal?.providerObjectType??g,C=h??(d?"subscription":"order"),[Y]=(0,M.useState)(Kr),W=X?.gateways?.paypal?.approvalPresentation??b,ve=ti(Y,W==="app_switch"?"app_switch":void 0,C),F=h==="order"||h==="setup_token",B=(0,M.useMemo)(()=>JSON.stringify([It,i,p,c??"",C,F,ve,e,Se??""]),[It,i,p,c,Se,C,F,ve,e]),ue=(0,M.useRef)(B),D=ue.current!==B,Me=(0,M.useRef)(le),st=(0,M.useRef)(null),[yt,Ct]=(0,M.useState)([]),Be=(0,M.useCallback)(v=>{Me.current&&Ct(ut=>[...ut,`${new Date().toISOString().slice(11,23)} ${v}`])},[]);(0,M.useEffect)(()=>{Me.current=le,le&&Be("debug:enabled"),st.current?.setEnabled(le)},[Be,le]);let An=(0,M.useRef)(T),$n=(0,M.useRef)(_),hn=(0,M.useRef)(S),Vt=(0,M.useRef)(A),jn=(0,M.useRef)(I),Hn=(0,M.useRef)(ge),Cn=(0,M.useRef)(w),Bt=(0,M.useRef)(K),dt=(0,M.useRef)(a),nt=(0,M.useRef)(q),Mn=(0,M.useRef)(X),Mt=(0,M.useRef)(r),Wn=(0,M.useRef)(o),bn=(0,M.useRef)(t),$t=(0,M.useRef)(null),en=(0,M.useRef)(new Map),cr=(0,M.useRef)(new Map),Qn=(0,M.useRef)(!1);(0,M.useEffect)(()=>(Qn.current=!0,()=>{Qn.current=!1}),[]),(0,M.useEffect)(()=>{An.current=T},[T]),(0,M.useEffect)(()=>{dt.current=a},[a]),(0,M.useEffect)(()=>{$n.current=_},[_]),(0,M.useEffect)(()=>{hn.current=S},[S]),(0,M.useEffect)(()=>{Vt.current=A},[A]),(0,M.useEffect)(()=>{jn.current=I},[I]),(0,M.useEffect)(()=>{Hn.current=ge},[ge]),(0,M.useEffect)(()=>{Cn.current=w},[w]),(0,M.useEffect)(()=>{Bt.current=K},[K]),(0,M.useEffect)(()=>{nt.current=q},[q]),(0,M.useEffect)(()=>{Mn.current=X},[X]),(0,M.useEffect)(()=>{Mt.current=r},[r]),(0,M.useEffect)(()=>{Wn.current=o},[o]),(0,M.useEffect)(()=>{bn.current=t},[t]),(0,M.useEffect)(()=>{Ke.current=Ve},[Ve]),(0,M.useEffect)(()=>{it&&we.current?.focus()},[it,Ve]);let tn=(0,M.useCallback)(()=>{window.setTimeout(()=>{we.current?.focus()},0)},[]),xt=(0,M.useCallback)(()=>{te(!1),ot(v=>v+1)},[]),nn=(0,M.useCallback)(()=>{$e(!1),(ce.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ce.current)?.focus?.()},[]);(0,M.useEffect)(()=>{!Te||!ie.current||(ie.current=!1,nn())},[nn,Te,Ve]);let sn=(0,M.useCallback)((v,ut)=>{let pe=ut?.popupBlocked??ao(v);pe&&U.markBlocked();let Sn=ro("PayPal",pe,Y.inAppBrowser),Kn=jn.current;if(Kn){let Gt=pe&&Y.inAppBrowser?new Wt.FloPayError(Sn,"api_error",{code:ut?.code??"paypal_popup_blocked"}):v;Kn("paypal",Gt,ut);return}hn.current?.(Sn)},[U,Y.inAppBrowser]),Lt=(0,M.useCallback)(v=>{let ut=Pe.current,pe=Ae.current;ut===null||!pe||(Ie.log({...pe,popupCapability:U.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:v}),Ie.performance({...pe,popupCapability:U.current(),stage:"overlay_return",durationMs:Ie.elapsed(ut),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:v}),Pe.current=null)},[U,Ie]),cn=(0,M.useCallback)((v,ut,pe)=>{let Sn=Ae.current;Lt("overlay_timeout"),Sn&&Ie.error({...Sn,popupCapability:U.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),sn(ut,{...pe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ve,terminalReason:"overlay_timeout"}),$e(!0),xt(),tn()},[Lt,tn,sn,U,ve,xt,Ie]),Ut=(0,M.useCallback)(()=>{U.markAvailable();let v=Ae.current;v&&(J.current=v.attempt,Ie.log({...v,popupCapability:U.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[U,Ie]),{finishAttempt:ln,generationRef:Nt,invalidateAttempt:me,isAttemptCurrent:dr,isAttemptInvalidated:ur,startAttempt:pr}=Ca(cn,{onHandoffObserved:Ut}),rn=(0,M.useCallback)(()=>($e(!1),pr("paypal")),[pr]),xn=(0,M.useCallback)(v=>{me(v?.generation),v?.showRetry&&$e(!0),v?.remount&&xt(),v?.focus!==!1&&tn()},[tn,me,xt]),kn=v=>{let ut=$t.current;return ut&&cr.current.set(v,ut),v};(0,M.useEffect)(()=>{ue.current!==B&&(ue.current=B,vt.current=!1,Ot.current=!1,te(!1),We(!1),_t(!1),Bt.current?.("loading"))},[B]),(0,M.useEffect)(()=>{Je(()=>Cn.current?.(Te&&!ht))},[Te,ht]);let ze=(0,Wt.normalizeGatewayEnvironment)(c);(0,M.useEffect)(()=>{let v={attempt:Nt.current+1,inAppBrowser:Y.inAppBrowser,appFamily:Y.appFamily,popupCapability:U.current(),presentationMode:ve},ut=()=>({...Ae.current??v,popupCapability:U.current()}),pe={error:f=>Ie.error({...f,...ut()}),log:f=>Ie.log({...f,...ut()}),performance:f=>Ie.performance({...f,...ut()}),terminal:f=>Ie.terminal({...f,...ut()}),startTiming:Ie.startTiming,elapsed:Ie.elapsed},Sn=i?`${i.slice(0,6)}\u2026(len ${i.length})`:"(empty)",Kn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Be(`mount clientId=${Sn} env=${c??"(unset)"}\u2192${ze??"live"} ccy=${p} sub=${d}`),Be(`ua=${Kn.slice(0,80)}${Kn.length>80?"\u2026":""}`),!i){Be("FAIL: clientId empty \u2014 gateway misconfigured"),_t(!0),pe.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(!ce.current){Be("FAIL: containerRef not attached");return}de.current=pe.startTiming(),pe.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,Fn=!1,ft=()=>Gt||Fn,mr,uo=!1,Ft=()=>{mr=(0,Wt.generateIdempotencyKey)(),mr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),uo=!0},Bn=null,kr=!1,er=null,Yt=!1,yr=()=>{!er||Yt||(Yt=!0,er.close().catch(()=>{}))},Dn=!1,Lr=!1,On=ce.current,Rr=null,Ir=null,Nr=[],Gn=null,tr=!1,Ur=!1,Dt=null,Rn=f=>{if(!f||typeof f.getBoundingClientRect!="function")return"(no rect)";let m=f.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},nr=f=>{if(!f)return"(empty)";try{let m=new URL(f,typeof window>"u"?"https://localhost":window.location.href),N=m.pathname.toLowerCase();return N.includes("checkcaptcha")||N.includes("captcha")?`CAPTCHA(${m.host}${N})`:N.includes("risk")||N.includes("challenge")?`RISK(${m.host}${N})`:N.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${N}`.slice(0,100)}catch{return f.slice(0,80)}},zr=f=>{let m=f.getAttribute("src"),N=f.getAttribute("srcdoc"),H=f.getAttribute("name"),Ce=f.getAttribute("sandbox"),xe=[];return m&&xe.push(`src=${nr(m)}`),N&&xe.push(`srcdoc[${N.length}ch]`),!m&&!N&&xe.push("src=(empty) srcdoc=(empty)"),H&&xe.push(`name=${H.slice(0,40)}`),Ce!==null&&xe.push(`sandbox="${Ce.slice(0,40)}"`),xe.join(" ")},qr=f=>{if(!(f instanceof HTMLIFrameElement))return"";try{let m=f.contentDocument;if(!m)return"cd=null";let N=m.body?.children.length??0,H=m.body?.innerHTML.length??0,Ce=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${N}children,${H}ch] head[${Ce}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},lt=[],dn=f=>{if(ft())return;let m=f.message??String(f.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(Be(`window:error ${m.slice(0,140)}`),lt.push(m))},un=f=>{if(ft())return;let m=f.reason instanceof Error?f.reason.message:String(f.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(Be(`window:rejection ${m.slice(0,140)}`),lt.push(m))},In={value:0},po=()=>{Rr?.disconnect(),Rr=null,Ir?.disconnect(),Ir=null;for(let f of Nr.splice(0))clearTimeout(f);Ur=!1,tr&&typeof window<"u"&&(window.removeEventListener("error",dn),window.removeEventListener("unhandledrejection",un)),tr=!1},Er=()=>{if(!(tr||ft()||Dn)){if(tr=!0,lt.length=0,In.value=0,typeof window<"u"&&(window.addEventListener("error",dn),window.addEventListener("unhandledrejection",un)),typeof PerformanceObserver<"u")try{Ir=new PerformanceObserver(f=>{if(!ft())for(let m of f.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;In.value+=1;let N=Math.round(m.duration);Be(`net ${N}ms ${m.name.slice(0,90)}`)}}),Ir.observe({type:"resource",buffered:!0})}catch{}Dt?.()}},Zr=()=>{Gn&&(clearTimeout(Gn),Gn=null)},En=()=>{po(),Zr()},pn={setEnabled:f=>{f?Er():po()}};st.current=pn,Me.current&&Er();let Vr=f=>{if(!f)return!1;let m=f.toLowerCase();return m.includes("zoid destroyed")||m.includes("destroyed all components")||m.includes("window closed")||m.includes("detected container element removed")},Ln=f=>{if(ft()||Vr(f))return;let m=to(f)??f;Je(()=>hn.current?.(m))},L=(f,m)=>{if(Gt||kr)return;kr=!0,Fn=!0,En(),yr();let N=nu({kind:f,generationActive:!0,automaticRetryAllowed:k,automaticRetryUsed:vt.current});if(N.action==="retry"){vt.current=!0,te(!1),be(!1),We(!0),Bt.current?.("retrying"),Bn=setTimeout(()=>{Gt||ot(H=>H+1)},Zd);return}if(te(!1),be(!1),We(!1),_t(!0),N.action!=="ignore"){if(Bt.current?.("exhausted"),N.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",m);return}if(N.report){let H=oo({code:Yl(f,m),message:m},{inAppBrowser:Y.inAppBrowser,handoffObserved:!1});H.popupBlocked&&U.markBlocked(),pe.error({errorCode:H.popupBlocked?H.errorCode:N.report.errorCode,stage:N.report.stage,operationOutcome:N.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:H.terminalReason})}Ot.current||(Ot.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Yl(f,m)))}};_t(!1);let V=async(f,m=$t.current)=>{if(ft())return;let N=m?.sessionId??e;if(An.current){await An.current(f,{sessionId:N,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let H=pe.startTiming();pe.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Ce=()=>{pe.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"processing",durationMs:pe.elapsed(H),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let xe=Mn.current,et=m?.accountPatch?.email??Mt.current,Pt=m?.accountPatch?.userId??xe?.customer?.id??xe?.accountData?.userId??"",Oe=m?.accountPatch?.firstName??xe?.customer?.firstName??xe?.accountData?.firstName,x=m?.accountPatch?.lastName??xe?.customer?.lastName??xe?.accountData?.lastName,Fe=await new ai.PaymentAPI(It,{telemetry:!1}).processPayment(Pt,{sessionId:N,nonce:m?.nonce??bn.current,paymentMethodCategory:"paypal",tokenizedData:f,accountData:{userId:Pt,email:et??xe?.customer?.email??"",...Oe?{firstName:Oe}:{},...x?{lastName:x}:{},country:m?.accountPatch?.country??xe?.customer?.country??xe?.accountData?.country??void 0,zip:m?.accountPatch?.zip??xe?.customer?.zip??xe?.accountData?.zip??void 0}});if(Fe.ok){if(Fn||Gt&&Qn.current)return;Ce(),pe.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Je(()=>$n.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ft())return;let ke=await Fe.json().catch(()=>null),G=ke?.message??"PayPal payment failed.",ye=to(G)??G;Ce(),Fe.status===400&&(typeof ke?.declineCode=="string"||!Array.isArray(ke?.fields))?pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Fe.status===400||Fe.status===422?pe.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):pe.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ou(Fe.status),failureCategory:Fe.status>=500?"server_error":void 0}),Ln(ye),Je(()=>Vt.current?.(yn("paypal",ye,{code:ke?.code,declineCode:ke?.declineCode})));return}catch(xe){if(ft())return;Ce(),pe.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let et=xe instanceof Error?xe.message:"PayPal payment failed.",Pt=to(et)??et;Ln(Pt),Je(()=>Vt.current?.(yn("paypal",Pt)));return}},re=()=>new Wt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),j=f=>ft()?Promise.reject(re()):Promise.resolve(f),gt=async f=>{if(ft())throw re();uo||Ft();let m=$t.current,N=m?.sessionId??e,H=m?.nonce??bn.current;pe.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Ce;try{Ce=await new ai.PaymentAPI(It,{telemetry:!1}).createSessionIntent(N,H??"",F?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Wt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:C==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:mr})}catch(xe){throw pe.error({...(0,Wt.classifyTelemetryFailure)(xe,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),xe}if(ft())throw re();if(Ce.provider!=="paypal"||Ce.providerObjectType!==C)throw new Error(f);return pe.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Ce.providerObjectId},Et=(f,m)=>{let N=m?.nonce??bn.current;if(!N)return;let H=m?.sessionId??e,Ce=qo(f)??xr(f)??"provider_declined";new ai.PaymentAPI(It,{telemetry:!1}).reportSessionIntentDecline(H,N,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ce}).catch(()=>{})},se=Ve;Be("loadScript:scheduled (deferred 1 tick)");let Xe=null,Q=setTimeout(()=>{if(Gt){Be("loadScript:skipped (cancelled before defer ran)");return}Be("loadScript:start");let f=ze==="live"?"production":ze,m={};C==="subscription"?m={intent:"subscription",vault:!0}:C==="order"&&(m={intent:"capture"}),Xe=(0,Xl.loadScript)({clientId:i,currency:p,...m,...f?{environment:f}:{},...f==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let N=!1;Xe.then(H=>{if(N=!0,Be(`loadScript:resolved inactive=${ft()} ns=${!!H} buttons=${!!H?.Buttons}`),ft())return;if(!H?.Buttons){Be("FAIL: namespace missing Buttons factory"),L("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}pe.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"provider_ready",durationMs:pe.elapsed(de.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),pe.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Ce=async(Fe,ke)=>{if(ft()||Ke.current!==se)return;let G=Fe.vaultSetupToken??Fe.subscriptionID??Fe.orderID??"",ye=G?cr.current.get(G):en.current.get(se);if(!(!ye||!dr(ye.generation))&&ln(ye.generation)){cr.current.delete(G),en.current.delete(ye.surfaceKey),Lt("approved");try{if(be(!0),Je(()=>hn.current?.(null)),!G)throw new Wt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ne=Mn.current,wt=go(Wn.current??[ne?.customer?.firstName,ne?.customer?.lastName].filter(Boolean).join(" ")),Ge=zn({email:ye.accountPatch?.email?.trim()||Mt.current?.trim()||ne?.customer?.email?.trim(),firstName:ye.accountPatch?.firstName?.trim()||wt.firstName,lastName:ye.accountPatch?.lastName?.trim()||wt.lastName});if(!(0,Wt.isValidEmail)(Ge.email)||!(Ge.firstName||Ge.lastName))try{let _n=ru(await ke?.order?.get?.());Ge=zn({email:_n.email||Ge.email,firstName:_n.firstName||Ge.firstName,lastName:_n.lastName||Ge.lastName})}catch{}if((dt.current||Ye)&&!(0,Wt.isValidEmail)(Ge.email)){let _n=await Z("PayPal",Ge);if(!_n)return;Ge=_n}(0,Wt.isValidEmail)(Ge.email)&&(ye.accountPatch=zn({...ye.accountPatch,...Ge}),await dt.current?.(Ge));let fr;C==="setup_token"?fr={id:G,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Wt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:F?fr={id:G,isPaypal:!0,gateway:"paypal",paymentMethodType:Wt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:fr={id:G,isPaypal:!0},await V(fr,ye)}catch(ne){Ln(ne instanceof Error?ne.message:"PayPal capture failed.")}finally{ft()||be(!1)}}},xe=Fe=>{let ke=Se?()=>j(Se):()=>gt(Fe);return async()=>kn(await ke())},et=H.Buttons({style:{layout:"horizontal",height:ii,tagline:!1},...ve==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Fe,ke)=>{if(ft()){await ke.reject();return}Ft();let G=nt.current,ye={};if(G)try{let Ge=await G("paypal");if(ft()){await ke.reject();return}if(!Ge.proceed){$t.current=null,en.current.delete(se),await ke.reject();return}ye={sessionId:Ge.sessionId,accountPatch:Ge.accountPatch,nonce:Ge.nonce}}catch(Ge){Be(`onClick:runBeforeButtonClick rejected msg=${(Ge instanceof Error?Ge.message:String(Ge)).slice(0,120)}`),$t.current=null,en.current.delete(se),await ke.reject();return}Je(()=>Hn.current?.("paypal"));let ne=rn(),wt={generation:ne,surfaceKey:se,...ye};$t.current=wt,en.current.set(se,wt),Ae.current={...v,attempt:ne},await ke.resolve(),pe.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),pe.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Pe.current=pe.startTiming()},createOrder:C==="order"?xe("Failed to create PayPal order."):void 0,createSubscription:C==="subscription"?xe("Failed to create PayPal subscription."):void 0,createVaultSetupToken:C==="setup_token"?async()=>kn(await gt("Failed to create PayPal setup token.")):void 0,onApprove:Ce,onCancel:()=>{if(ft())return;let Fe=en.current.get(se)??$t.current;Fe&&en.current.delete(Fe.surfaceKey),$t.current=null,Lt("cancelled"),pe.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ie.current=!0,xn({generation:Fe?.generation,remount:!0,focus:!1})},onError:Fe=>{if(ft()||Ke.current!==se)return;let ke=Fe instanceof Error?Fe.message:"PayPal failed to render.";if(Be(`onError rendered=${Dn} msg=${ke.slice(0,120)}`),Dn){let G=en.current.get(se)??$t.current;if(G&&!dr(G.generation)||!G&&ur())return;if(Vr(ke)){ln(G?.generation);return}let{errorCode:ye,popupBlocked:ne,providerDeclined:wt,terminalReason:Ge}=oo(Fe,{inAppBrowser:Y.inAppBrowser,handoffObserved:G!=null&&J.current===G.generation});if(ne&&U.markBlocked(),Lt(Ge),wt){pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ge}),Et(Fe,G),Je(()=>Vt.current?.(yn("paypal",ke))),G&&en.current.delete(G.surfaceKey),$t.current=null,ln(G?.generation);return}pe.error({errorCode:ye,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ge}),G&&en.current.delete(G.surfaceKey),$t.current=null,xn({generation:G?.generation,remount:!0,showRetry:!0,focus:!0}),sn(Fe,{code:"paypal_runtime_failed",popupBlocked:ne,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ve,terminalReason:Ge});return}L(Vr(ke)?"teardown":"pre_ready_callback",ke)}}),Pt=et.isEligible();if(Be(`isEligible=${Pt}`),pe.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Pt){te(!1),L("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Lr=!0,er=et,Dt=()=>{if(!tr||Ur||ft()||Dn)return;Ur=!0,Be(`container:dims ${Rn(On)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Rr=new MutationObserver(ke=>{if(!ft()){for(let G of ke)if(G.type==="childList")G.addedNodes.forEach(ye=>{if(!(ye instanceof Element))return;let ne=ye.tagName.toLowerCase(),wt=(ye.getAttribute("title")??"").slice(0,40),Ge=ne==="iframe"?` ${zr(ye)}`:"";Be(`child+ ${ne}${wt?` title="${wt}"`:""}${Ge} dims=${Rn(ye)}`)});else if(G.type==="attributes"&&G.target instanceof Element){let ye=G.target;if(ye.tagName.toLowerCase()!=="iframe")continue;let ne=G.attributeName;(ne==="src"||ne==="srcdoc")&&Be(`attr~ iframe ${ne}=${ne==="srcdoc"?`[${(ye.getAttribute("srcdoc")??"").length}ch]`:nr(ye.getAttribute("src"))} dims=${Rn(ye)}`)}}}),Rr.observe(On,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Fe=ke=>{if(ft()||Dn)return;let G=On.querySelectorAll("iframe"),ye=typeof document<"u"&&"hasStorageAccess"in document;Be(`watchdog:${ke} container=${Rn(On)} children=${On.childElementCount} iframes=${G.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ye} paypalNetRequests=${In.value}`),G.forEach((ne,wt)=>{let Ge=(ne.getAttribute("title")??"").slice(0,40);Be(` iframe[${wt}] ${Rn(ne)}${Ge?` title="${Ge}"`:""} ${zr(ne)}`);let fr=qr(ne);fr&&Be(` ${fr}`)}),lt.length===0&&Be(" (no PayPal/zoid window errors captured)")};Nr.push(setTimeout(()=>Fe("3s"),3e3)),Nr.push(setTimeout(()=>Fe("8s"),8e3)),Nr.push(setTimeout(()=>Fe("15s"),15e3))},Dt(),Be("render:start");let x=pe.startTiming();Gn=setTimeout(()=>{ft()||Dn||(Be("watchdog:11s retryable render timeout"),L("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Qd);let St=et.render(On);(async()=>{try{if(await St,Be(`render:resolved inactive=${ft()}`),En(),ft()){yr();return}Dn=!0,te(!0),We(!1),Bt.current?.("ready"),pe.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"checkout_render",durationMs:pe.elapsed(x),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Fe){let ke=Fe instanceof Error?Fe.message:"PayPal failed to render.";Be(`render:rejected msg=${ke.slice(0,120)}`),En(),L(Vr(ke)?"teardown":"render_rejected",ke)}})()}).catch(H=>{let Ce=H instanceof Error?H.message:"PayPal operation failed.";Be(`provider:failed msg=${Ce.slice(0,120)}`);let xe="script_rejected";N&&Vr(Ce)?xe="teardown":N&&Lr&&(xe="render_rejected"),L(xe,Ce)})},0);return()=>{Gt=!0,clearTimeout(Q),Bn&&clearTimeout(Bn),En(),st.current===pn&&(st.current=null),yr(),Pe.current=null,Ae.current=null}},[k,It,i,p,c,C,ve,F,e,Se,Ve,Ie,Z,Ye,Be,Lt]);let mt=le?(0,ar.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ht?"#fef2f2":"#f3f4f6",border:`1px solid ${ht?"#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=${Te} failed=${ht})`,yt.length===0?`
1
+ "use strict";var Td=Object.create;var Ja=Object.defineProperty;var Ad=Object.getOwnPropertyDescriptor;var Md=Object.getOwnPropertyNames;var xd=Object.getPrototypeOf,Fd=Object.prototype.hasOwnProperty;var Bd=(e,t)=>{for(var n in t)Ja(e,n,{get:t[n],enumerable:!0})},Fl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Md(t))!Fd.call(e,o)&&o!==n&&Ja(e,o,{get:()=>t[o],enumerable:!(r=Ad(t,o))||r.enumerable});return e};var ss=(e,t,n)=>(n=e!=null?Td(xd(e)):{},Fl(t||!e||!e.__esModule?Ja(n,"default",{value:e,enumerable:!0}):n,e)),Dd=e=>Fl(Ja({},"__esModule",{value:!0}),e);var Up={};Bd(Up,{DirectPayPalButton:()=>wa,FloPayAutomaticPaymentButton:()=>$c,FloPayCardSetup:()=>Wc,FloPayCardSetupError:()=>Na,FloPayCheckout:()=>Di,FloPayPaymentMethodSetup:()=>cd,FloPayProvider:()=>Ra,SplitCardForm:()=>Mi,VaultCardFields:()=>co,dropThirdPartyOnlyError:()=>ud.dropThirdPartyOnlyError,useCheckout:()=>Wl,useFloPay:()=>Kr,usePayPalFloPay:()=>ei});module.exports=Dd(Up);var ud=require("@flopay/shared");var Oi=require("@flopay/js"),lr=require("@flopay/shared"),ct=require("react");var Vt=require("react/jsx-runtime");function Od(){return(0,Vt.jsxs)(Vt.Fragment,{children:[(0,Vt.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,Vt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Vt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Vt.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,Vt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Ld(){return(0,Vt.jsx)(Vt.Fragment,{children:"Go back"})}function Nd(){return(0,Vt.jsx)(Vt.Fragment,{children:"Secure card checkout"})}function Do(e){return e!==void 0&&(e===""||e===null||e===!1)}function Oo({content:e}){return(0,Vt.jsx)(Vt.Fragment,{children:e===void 0?(0,Vt.jsx)(Od,{}):e})}function Lo({content:e}){return(0,Vt.jsx)(Vt.Fragment,{children:e===void 0?(0,Vt.jsx)(Ld,{}):e})}function ha({content:e}){return(0,Vt.jsx)(Vt.Fragment,{children:e===void 0?(0,Vt.jsx)(Nd,{}):e})}var Rt=require("@flopay/shared"),Ud="Checkout is temporarily unavailable. Please try again later.";function ls(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Rt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function zd(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 Bl(){return new Rt.FloPayError(Ud,"api_error",{code:"CheckoutInitializationFailed"})}function cs(e){return!!e?.gateways?.worldpayCorporateGateway}function eo(e){return e?.status==="open"&&cs(e)}function Dl(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")||eo(r))||t&&e?.data.paypal?.publishableKey)}function Ol(e,t){if(t&&(!(e instanceof Rt.FloPayError)||e.type==="authentication_error"))return ls(e);if(!(e instanceof Rt.FloPayError&&zd(e))){if(!t&&!(e instanceof Rt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Rt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Rt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Rt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function No(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let i={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,Rt.isCardHolderNamePlaceholder)(i.firstName,i.lastName);if(!(0,Rt.isValidEmail)(i.email))return Promise.reject(new Rt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[d,g]of Object.entries(i)){if(c&&d.endsWith("Name")||typeof g!="string")continue;let b=g.trim();b&&(p[d]=b)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function Ll(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 ds(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 Nl(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,i)=>a+(i.overrideAmount??i.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,i)=>({uuid:`synthetic-${a.type??"item"}-${i}`,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 ho(e){if((0,Rt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function us(e,t){return t?{...e,...t}:e}function mn(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,i=typeof t=="string"?void 0:t.sessionId;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{},...i?{sessionId:i}:{}}}function to(e,t){return t&&e.sessionId===void 0&&Object.defineProperty(e,"sessionId",{value:t,enumerable:!0}),e}var qd=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function no(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of qd)if(n.test(t))return r;return e}function $r(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Hr(e){return e?.status==="authorized"||e?.status==="complete"}function ro(e,t){if(e.data.session)return e.data.session;let n=e.raw,r=n?.latestTransactionAttempt?.result,o=n?.status==="authorized"||r==="AUTHORIZED";return o||n?.status==="completed"||r==="SUCCESS"?{...t,status:o?"authorized":"complete"}:n?.status==="expired"?{...t,status:"expired"}:void 0}function Ul(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Za(e){let t=Ul(e);return new Rt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Qa(e){return e instanceof Rt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Uo(e){return Ul(e)?new Rt.FloPayError("Authorization has expired.","api_error",{code:"authorization_expired"}):e?.status==="expired"?new Rt.FloPayError("Automatic payment failed. Please try again.","api_error",{code:"checkout_session_expired"}):new Rt.FloPayError(Rt.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}function ba(e,t){return e==="processing"||(0,Rt.isMoneySettledOutcome)(e,t)}function zl(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function ql(e,t){let n=e;if((0,Rt.isSetupIntentClientSecret)(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:a,error:i}=await n.retrieveSetupIntent(t);if(i)throw new Rt.FloPayError(i.message??"Failed to retrieve setup intent.","api_error",{...i.code?{code:i.code}:{}});return a??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new Rt.FloPayError(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}var Vd=["apple_pay","google_pay"];function Vl(e,t="automatic",n){let r=(0,Rt.resolveSetupFutureUsage)(n,Vd,"wallet");return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],...r?{setupFutureUsage:r}:{}}}var jd=new Set(["payment_intent_unexpected_state","setup_intent_unexpected_state"]);function ps(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:"deferred_contract_mismatch"}:t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response",reason:jd.has(t.code)?"intent_unexpected_state":"invalid_request"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Pa(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Jr=require("@flopay/js"),rt=require("@flopay/shared"),R=ss(require("react"),1);var ms=require("react"),or=(0,ms.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Pr=(0,ms.createContext)({session:null,loading:!1,error:null});var ii=require("@flopay/js"),Wt=require("@flopay/shared"),Jl=require("@paypal/paypal-js"),M=require("react");var jl=require("@flopay/shared"),vr=require("react"),Wr=require("react/jsx-runtime");function Un(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),i=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...i||t?{lastName:i??""}:{}}}function zo(){let[e,t]=(0,vr.useState)(null),n=(0,vr.useRef)(null),r=(0,vr.useRef)(0),o=(0,vr.useCallback)((i,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:i,identity:c}),new Promise(p=>{n.current=p})),[]),a=(0,vr.useCallback)(i=>{let c=n.current;n.current=null,t(null),c?.(i)},[]);return(0,vr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function qo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[i,c]=(0,vr.useState)(e.email?.trim()??""),p=(0,jl.isValidEmail)(i.trim());return(0,Wr.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,Wr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Wr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Wr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:i,onChange:d=>c(d.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Wr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Wr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Wr.jsxs)("button",{type:"button",disabled:!p||o,onClick:()=>{n(Un({...e,email:i.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var $d=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Hd=["https://www.paypal.com","https://www.sandbox.paypal.com"];function oo(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 $l(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 bo(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mr(e){if(typeof e!="object"||e===null)return;let t=e;return bo(t.code)??bo(t.type)??bo(t.name)}function Vo(e){if(!(typeof e!="object"||e===null))return bo(e.decline_code)}function Po(e){return typeof e!="object"||e===null?!1:bo(e.type)?.toLowerCase()==="card_error"||Vo(e)!==void 0}function Wd(e){let t=$l(e)?.toLowerCase()??"",n=Mr(e)?.toLowerCase()??"";return $d.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 ys(e){if(Mr(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=$l(e)??"";return n.includes("No ack for postMessage init()")&&Hd.some(r=>n.includes(r))&&n.includes("10000ms")}function ao(e,t){if(Po(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Wd(e)||t.inAppBrowser&&!t.handoffObserved&&ys(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function io(e){return ao(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}var Hl=require("@flopay/shared"),va=require("react");function Kr(){return(0,va.useContext)(or).flopay}function ei(){return(0,va.useContext)(or).paypalFlopay??null}function Wl(){return(0,va.useContext)(Pr)}function Kl(){return(0,va.useContext)(or).billingApiUrl||(0,Hl.resolveBillingApiUrl)()}function Gr(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 ti(e,t,n=e.popupCapability){return e.inAppBrowser||n==="blocked"||t==="prefer_redirect"?"redirect":"popup"}function ni(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var Gl=require("@flopay/shared"),Co=require("react");function Je(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 ri=require("react"),vo=typeof window>"u"?ri.useEffect:ri.useLayoutEffect;var Kd={"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 Gd(e){return e==="stripe"||e==="paypal"?e:void 0}function Yd(e){let t=Gd(e.provider),n={schemaVersion:Gl.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Kd[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 fs=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function jo(e,t){let n=(0,Co.useRef)(e);n.current=e;let r=(0,Co.useRef)(new Set),o=(0,Co.useRef)(t),a=(0,Co.useRef)(t);return vo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Co.useCallback)(i=>{if(a.current!==t)return;let c=Yd(i);if(c){if(fs.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}Je(()=>n.current?.(c))}},[t])}var Yl=require("react"),Ca=(0,Yl.createContext)(null);function oi(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var Xd=Symbol.for("@flopay/js.telemetry.bridge.v1"),Jd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Zd(){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 Qd(e){let t=Zd(),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 ai(e){let t=globalThis[Jd];return Qd(t?.(e)??{})}function yn(e){if(e)return e[Xd]}var on=require("react");function Sa(e,t){let n=(0,on.useRef)(0),r=(0,on.useRef)(null),o=(0,on.useRef)(null),a=(0,on.useRef)(e),i=(0,on.useRef)(t?.onHandoffObserved),c=(0,on.useRef)(t?.defersMissingTerminal),p=(0,on.useRef)(t?.onMissingTerminalDeferred);(0,on.useEffect)(()=>{a.current=e,i.current=t?.onHandoffObserved,c.current=t?.defersMissingTerminal,p.current=t?.onMissingTerminalDeferred},[e,t?.onHandoffObserved,t?.defersMissingTerminal,t?.onMissingTerminalDeferred]);let d=(0,on.useCallback)((P=o.current)=>{P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),g=(0,on.useCallback)(P=>{d();let w=n.current+1;return n.current=w,r.current=null,o.current={generation:w,method:P,timer:null,yieldedControl:!1},w},[d]),b=(0,on.useCallback)(P=>{let w=o.current;return P!==void 0&&w?.generation!==P?!1:(d(w),o.current=null,(P===void 0||r.current===P)&&(r.current=null),!0)},[d]),T=(0,on.useCallback)(P=>{let w=o.current,K=P??w?.generation??n.current;(P===void 0||w?.generation===P)&&(d(w),o.current=null),r.current=K},[d]),E=(0,on.useCallback)(P=>r.current===(P??n.current),[]),S=(0,on.useCallback)(P=>o.current?.generation===P&&r.current!==P,[]),A=(0,on.useCallback)(()=>{let P=o.current;P&&(d(P),!P.yieldedControl&&(P.yieldedControl=!0,i.current?.(P.method)))},[d]),_=(0,on.useCallback)(()=>{let P=o.current;!P?.yieldedControl||document.visibilityState!=="visible"||(d(P),P.timer=setTimeout(()=>{if(P.timer=null,o.current?.generation===P.generation){if(c.current?.(P.method)){p.current?.(P.method,P.generation);return}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))},[d]);return(0,on.useEffect)(()=>{let P=()=>{document.visibilityState==="visible"?_():A()};return document.addEventListener("visibilitychange",P),window.addEventListener("blur",A),window.addEventListener("focus",_),()=>{document.removeEventListener("visibilitychange",P),window.removeEventListener("blur",A),window.removeEventListener("focus",_),d()}},[d,A,_]),{startAttempt:g,finishAttempt:b,invalidateAttempt:T,isAttemptInvalidated:E,isAttemptCurrent:S,generationRef:n}}var ar=require("react/jsx-runtime"),si=45,eu=1e3,tu=11e3,nu={width:"100%",minHeight:si,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"},ru={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 ou(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:ru[e.kind]??null}}function Xl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":ys(t)?"paypal_init_timeout":"paypal_init_failure"}function au(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 iu(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function Zl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:i,environment:c,currency:p,isSubscription:d,providerObjectType:g,approvalPresentation:b,onTokenizedBody:T,onComplete:E,onErrorChange:S,onDecline:A,onTechnicalFailure:_,isProcessing:P=!1,onLoadStateChange:w,onInitializationStateChange:K,allowAutomaticRetry:k=!0,onButtonClick:ge,runBeforeButtonClick:z,session:X,existingOrderId:Se,telemetry:ae,telemetryContext:De,onInstrument:Ze,debug:le=!1}){let Ie=Kr(),He=jo(Ze,e),Re=(0,M.useMemo)(()=>{if(Ie)return null;let v=ai({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Wt.SDK_VERSION,enabled:ae!==!1});return v.setCheckoutContext(De??{}),v.beginCheckout(De??{}),v},[n,Ie,ae,De?.checkoutMode,De?.layout]),Ee=(0,M.useMemo)(()=>yn(Ie),[Ie]);(0,M.useEffect)(()=>()=>{Re&&Re.flush().catch(()=>{}).finally(()=>Re.destroy())},[Re]);let _e=(0,M.useMemo)(()=>({error:v=>{Ee?Ee.error(v):Re?.error(v),He({class:"technical_error",errorCode:v.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":v.errorCode,requestCategory:v.requestCategory,provider:v.provider})},log:v=>{Ee?Ee.log(v):Re?.log(v),He({class:"lifecycle",name:v.name,provider:v.provider})},performance:v=>{Ee?Ee.performance(v):Re?.performance(v)},terminal:v=>{Ee?Ee.terminal(v):Re?.terminal(v)},startTiming:()=>Ee?.now()??Re?.now()??0,elapsed:v=>Ee?.elapsed(v)??Math.max(0,(Re?.now()??v)-v)}),[He,Ee,Re]),ce=(0,M.useRef)(null),de=(0,M.useRef)(0),Pe=(0,M.useRef)(null),Ae=(0,M.useRef)(null),J=(0,M.useRef)(null),ee=(0,M.useContext)(Ca),he=(0,M.useRef)(null);he.current||(he.current=oi());let U=ee??he.current,we=(0,M.useRef)(null),ie=(0,M.useRef)(!1),[Te,te]=(0,M.useState)(!1),[at,We]=(0,M.useState)(!1),[je,ot]=(0,M.useState)(0),Ke=(0,M.useRef)(0),[it,$e]=(0,M.useState)(!1),vt=(0,M.useRef)(!1),Lt=(0,M.useRef)(!1),[ht,Tt]=(0,M.useState)(!1),[V,be]=(0,M.useState)(!1),{request:Qe,collect:Z,finish:Le}=zo(),bt=(0,M.useRef)({sessionId:e,required:!(0,Wt.isValidEmail)(r?.trim()||X?.customer?.email?.trim())});bt.current.sessionId!==e&&(bt.current={sessionId:e,required:!(0,Wt.isValidEmail)(r?.trim()||X?.customer?.email?.trim())});let Ye=bt.current.required,_t=(0,M.useMemo)(()=>n.replace(/\/+$/,""),[n]),h=X?.gateways?.paypal?.providerObjectType??g,C=h??(d?"subscription":"order"),[Y]=(0,M.useState)(Gr),W=X?.gateways?.paypal?.approvalPresentation??b,ve=ni(Y,W==="app_switch"?"app_switch":void 0,C),x=h==="order"||h==="setup_token",B=(0,M.useMemo)(()=>JSON.stringify([_t,i,p,c??"",C,x,ve,e,Se??""]),[_t,i,p,c,Se,C,x,ve,e]),ue=(0,M.useRef)(B),D=ue.current!==B,Me=(0,M.useRef)(le),st=(0,M.useRef)(null),[yt,Ct]=(0,M.useState)([]),Be=(0,M.useCallback)(v=>{Me.current&&Ct(ut=>[...ut,`${new Date().toISOString().slice(11,23)} ${v}`])},[]);(0,M.useEffect)(()=>{Me.current=le,le&&Be("debug:enabled"),st.current?.setEnabled(le)},[Be,le]);let Tn=(0,M.useRef)(T),Vn=(0,M.useRef)(E),gn=(0,M.useRef)(S),jt=(0,M.useRef)(A),jn=(0,M.useRef)(_),$n=(0,M.useRef)(ge),vn=(0,M.useRef)(w),Dt=(0,M.useRef)(K),dt=(0,M.useRef)(a),nt=(0,M.useRef)(z),An=(0,M.useRef)(X),Mt=(0,M.useRef)(r),Hn=(0,M.useRef)(o),hn=(0,M.useRef)(t),$t=(0,M.useRef)(null),en=(0,M.useRef)(new Map),cr=(0,M.useRef)(new Map),Qn=(0,M.useRef)(!1);(0,M.useEffect)(()=>(Qn.current=!0,()=>{Qn.current=!1}),[]),(0,M.useEffect)(()=>{Tn.current=T},[T]),(0,M.useEffect)(()=>{dt.current=a},[a]),(0,M.useEffect)(()=>{Vn.current=E},[E]),(0,M.useEffect)(()=>{gn.current=S},[S]),(0,M.useEffect)(()=>{jt.current=A},[A]),(0,M.useEffect)(()=>{jn.current=_},[_]),(0,M.useEffect)(()=>{$n.current=ge},[ge]),(0,M.useEffect)(()=>{vn.current=w},[w]),(0,M.useEffect)(()=>{Dt.current=K},[K]),(0,M.useEffect)(()=>{nt.current=z},[z]),(0,M.useEffect)(()=>{An.current=X},[X]),(0,M.useEffect)(()=>{Mt.current=r},[r]),(0,M.useEffect)(()=>{Hn.current=o},[o]),(0,M.useEffect)(()=>{hn.current=t},[t]),(0,M.useEffect)(()=>{Ke.current=je},[je]),(0,M.useEffect)(()=>{it&&we.current?.focus()},[it,je]);let tn=(0,M.useCallback)(()=>{window.setTimeout(()=>{we.current?.focus()},0)},[]),xt=(0,M.useCallback)(()=>{te(!1),ot(v=>v+1)},[]),nn=(0,M.useCallback)(()=>{$e(!1),(ce.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ce.current)?.focus?.()},[]);(0,M.useEffect)(()=>{!Te||!ie.current||(ie.current=!1,nn())},[nn,Te,je]);let sn=(0,M.useCallback)((v,ut)=>{let pe=ut?.popupBlocked??io(v);pe&&U.markBlocked();let Cn=oo("PayPal",pe,Y.inAppBrowser),Wn=jn.current;if(Wn){let Gt=pe&&Y.inAppBrowser?new Wt.FloPayError(Cn,"api_error",{code:ut?.code??"paypal_popup_blocked"}):v;Wn("paypal",Gt,ut);return}gn.current?.(Cn)},[U,Y.inAppBrowser]),Nt=(0,M.useCallback)(v=>{let ut=Pe.current,pe=Ae.current;ut===null||!pe||(_e.log({...pe,popupCapability:U.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:v}),_e.performance({...pe,popupCapability:U.current(),stage:"overlay_return",durationMs:_e.elapsed(ut),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:v}),Pe.current=null)},[U,_e]),cn=(0,M.useCallback)((v,ut,pe)=>{let Cn=Ae.current;Nt("overlay_timeout"),Cn&&_e.error({...Cn,popupCapability:U.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),sn(ut,{...pe,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ve,terminalReason:"overlay_timeout"}),$e(!0),xt(),tn()},[Nt,tn,sn,U,ve,xt,_e]),zt=(0,M.useCallback)(()=>{U.markAvailable();let v=Ae.current;v&&(J.current=v.attempt,_e.log({...v,popupCapability:U.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[U,_e]),{finishAttempt:ln,generationRef:Ut,invalidateAttempt:me,isAttemptCurrent:dr,isAttemptInvalidated:ur,startAttempt:pr}=Sa(cn,{onHandoffObserved:zt}),rn=(0,M.useCallback)(()=>($e(!1),pr("paypal")),[pr]),Mn=(0,M.useCallback)(v=>{me(v?.generation),v?.showRetry&&$e(!0),v?.remount&&xt(),v?.focus!==!1&&tn()},[tn,me,xt]),wn=v=>{let ut=$t.current;return ut&&cr.current.set(v,ut),v};(0,M.useEffect)(()=>{ue.current!==B&&(ue.current=B,vt.current=!1,Lt.current=!1,te(!1),We(!1),Tt(!1),Dt.current?.("loading"))},[B]),(0,M.useEffect)(()=>{Je(()=>vn.current?.(Te&&!ht))},[Te,ht]);let ze=(0,Wt.normalizeGatewayEnvironment)(c);(0,M.useEffect)(()=>{let v={attempt:Ut.current+1,inAppBrowser:Y.inAppBrowser,appFamily:Y.appFamily,popupCapability:U.current(),presentationMode:ve},ut=()=>({...Ae.current??v,popupCapability:U.current()}),pe={error:f=>_e.error({...f,...ut()}),log:f=>_e.log({...f,...ut()}),performance:f=>_e.performance({...f,...ut()}),terminal:f=>_e.terminal({...f,...ut()}),startTiming:_e.startTiming,elapsed:_e.elapsed},Cn=i?`${i.slice(0,6)}\u2026(len ${i.length})`:"(empty)",Wn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Be(`mount clientId=${Cn} env=${c??"(unset)"}\u2192${ze??"live"} ccy=${p} sub=${d}`),Be(`ua=${Wn.slice(0,80)}${Wn.length>80?"\u2026":""}`),!i){Be("FAIL: clientId empty \u2014 gateway misconfigured"),Tt(!0),pe.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(!ce.current){Be("FAIL: containerRef not attached");return}de.current=pe.startTiming(),pe.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,xn=!1,ft=()=>Gt||xn,mr,po=!1,Ft=()=>{mr=(0,Wt.generateIdempotencyKey)(),mr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),po=!0},Fn=null,wr=!1,er=null,Yt=!1,yr=()=>{!er||Yt||(Yt=!0,er.close().catch(()=>{}))},Bn=!1,Or=!1,Dn=ce.current,kr=null,Rr=null,Lr=[],Kn=null,tr=!1,Nr=!1,Ot=null,kn=f=>{if(!f||typeof f.getBoundingClientRect!="function")return"(no rect)";let m=f.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},nr=f=>{if(!f)return"(empty)";try{let m=new URL(f,typeof window>"u"?"https://localhost":window.location.href),N=m.pathname.toLowerCase();return N.includes("checkcaptcha")||N.includes("captcha")?`CAPTCHA(${m.host}${N})`:N.includes("risk")||N.includes("challenge")?`RISK(${m.host}${N})`:N.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${N}`.slice(0,100)}catch{return f.slice(0,80)}},Ur=f=>{let m=f.getAttribute("src"),N=f.getAttribute("srcdoc"),H=f.getAttribute("name"),Ce=f.getAttribute("sandbox"),xe=[];return m&&xe.push(`src=${nr(m)}`),N&&xe.push(`srcdoc[${N.length}ch]`),!m&&!N&&xe.push("src=(empty) srcdoc=(empty)"),H&&xe.push(`name=${H.slice(0,40)}`),Ce!==null&&xe.push(`sandbox="${Ce.slice(0,40)}"`),xe.join(" ")},zr=f=>{if(!(f instanceof HTMLIFrameElement))return"";try{let m=f.contentDocument;if(!m)return"cd=null";let N=m.body?.children.length??0,H=m.body?.innerHTML.length??0,Ce=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${N}children,${H}ch] head[${Ce}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},lt=[],dn=f=>{if(ft())return;let m=f.message??String(f.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(Be(`window:error ${m.slice(0,140)}`),lt.push(m))},un=f=>{if(ft())return;let m=f.reason instanceof Error?f.reason.message:String(f.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(Be(`window:rejection ${m.slice(0,140)}`),lt.push(m))},Rn={value:0},mo=()=>{kr?.disconnect(),kr=null,Rr?.disconnect(),Rr=null;for(let f of Lr.splice(0))clearTimeout(f);Nr=!1,tr&&typeof window<"u"&&(window.removeEventListener("error",dn),window.removeEventListener("unhandledrejection",un)),tr=!1},_r=()=>{if(!(tr||ft()||Bn)){if(tr=!0,lt.length=0,Rn.value=0,typeof window<"u"&&(window.addEventListener("error",dn),window.addEventListener("unhandledrejection",un)),typeof PerformanceObserver<"u")try{Rr=new PerformanceObserver(f=>{if(!ft())for(let m of f.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;Rn.value+=1;let N=Math.round(m.duration);Be(`net ${N}ms ${m.name.slice(0,90)}`)}}),Rr.observe({type:"resource",buffered:!0})}catch{}Ot?.()}},Qr=()=>{Kn&&(clearTimeout(Kn),Kn=null)},_n=()=>{mo(),Qr()},pn={setEnabled:f=>{f?_r():mo()}};st.current=pn,Me.current&&_r();let qr=f=>{if(!f)return!1;let m=f.toLowerCase();return m.includes("zoid destroyed")||m.includes("destroyed all components")||m.includes("window closed")||m.includes("detected container element removed")},On=f=>{if(ft()||qr(f))return;let m=no(f)??f;Je(()=>gn.current?.(m))},L=(f,m)=>{if(Gt||wr)return;wr=!0,xn=!0,_n(),yr();let N=ou({kind:f,generationActive:!0,automaticRetryAllowed:k,automaticRetryUsed:vt.current});if(N.action==="retry"){vt.current=!0,te(!1),be(!1),We(!0),Dt.current?.("retrying"),Fn=setTimeout(()=>{Gt||ot(H=>H+1)},eu);return}if(te(!1),be(!1),We(!1),Tt(!0),N.action!=="ignore"){if(Dt.current?.("exhausted"),N.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",m);return}if(N.report){let H=ao({code:Xl(f,m),message:m},{inAppBrowser:Y.inAppBrowser,handoffObserved:!1});H.popupBlocked&&U.markBlocked(),pe.error({errorCode:H.popupBlocked?H.errorCode:N.report.errorCode,stage:N.report.stage,operationOutcome:N.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:H.terminalReason})}Lt.current||(Lt.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Xl(f,m)))}};Tt(!1);let q=async(f,m=$t.current)=>{if(ft())return;let N=m?.sessionId??e;if(Tn.current){await Tn.current(f,{sessionId:N,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let H=pe.startTiming();pe.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Ce=()=>{pe.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"processing",durationMs:pe.elapsed(H),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let xe=An.current,et=m?.accountPatch?.email??Mt.current,Pt=m?.accountPatch?.userId??xe?.customer?.id??xe?.accountData?.userId??"",Oe=m?.accountPatch?.firstName??xe?.customer?.firstName??xe?.accountData?.firstName,F=m?.accountPatch?.lastName??xe?.customer?.lastName??xe?.accountData?.lastName,Fe=await new ii.PaymentAPI(_t,{telemetry:!1}).processPayment(Pt,{sessionId:N,nonce:m?.nonce??hn.current,paymentMethodCategory:"paypal",tokenizedData:f,accountData:{userId:Pt,email:et??xe?.customer?.email??"",...Oe?{firstName:Oe}:{},...F?{lastName:F}:{},country:m?.accountPatch?.country??xe?.customer?.country??xe?.accountData?.country??void 0,zip:m?.accountPatch?.zip??xe?.customer?.zip??xe?.accountData?.zip??void 0}});if(Fe.ok){if(xn||Gt&&Qn.current)return;Ce(),pe.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Je(()=>Vn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ft())return;let ke=await Fe.json().catch(()=>null),G=ke?.message??"PayPal payment failed.",ye=no(G)??G;Ce(),Fe.status===400&&(typeof ke?.declineCode=="string"||!Array.isArray(ke?.fields))?pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Fe.status===400||Fe.status===422?pe.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):pe.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:iu(Fe.status),failureCategory:Fe.status>=500?"server_error":void 0}),On(ye),Je(()=>jt.current?.(mn("paypal",ye,{code:ke?.code,declineCode:ke?.declineCode})));return}catch(xe){if(ft())return;Ce(),pe.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let et=xe instanceof Error?xe.message:"PayPal payment failed.",Pt=no(et)??et;On(Pt),Je(()=>jt.current?.(mn("paypal",Pt)));return}},re=()=>new Wt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),$=f=>ft()?Promise.reject(re()):Promise.resolve(f),gt=async f=>{if(ft())throw re();po||Ft();let m=$t.current,N=m?.sessionId??e,H=m?.nonce??hn.current;pe.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Ce;try{Ce=await new ii.PaymentAPI(_t,{telemetry:!1}).createSessionIntent(N,H??"",x?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Wt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:C==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:mr})}catch(xe){throw pe.error({...(0,Wt.classifyTelemetryFailure)(xe,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),xe}if(ft())throw re();if(Ce.provider!=="paypal"||Ce.providerObjectType!==C)throw new Error(f);return pe.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Ce.providerObjectId},It=(f,m)=>{let N=m?.nonce??hn.current;if(!N)return;let H=m?.sessionId??e,Ce=Vo(f)??Mr(f)??"provider_declined";new ii.PaymentAPI(_t,{telemetry:!1}).reportSessionIntentDecline(H,N,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Ce}).catch(()=>{})},se=je;Be("loadScript:scheduled (deferred 1 tick)");let Xe=null,Q=setTimeout(()=>{if(Gt){Be("loadScript:skipped (cancelled before defer ran)");return}Be("loadScript:start");let f=ze==="live"?"production":ze,m={};C==="subscription"?m={intent:"subscription",vault:!0}:C==="order"&&(m={intent:"capture"}),Xe=(0,Jl.loadScript)({clientId:i,currency:p,...m,...f?{environment:f}:{},...f==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let N=!1;Xe.then(H=>{if(N=!0,Be(`loadScript:resolved inactive=${ft()} ns=${!!H} buttons=${!!H?.Buttons}`),ft())return;if(!H?.Buttons){Be("FAIL: namespace missing Buttons factory"),L("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}pe.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"provider_ready",durationMs:pe.elapsed(de.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),pe.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Ce=async(Fe,ke)=>{if(ft()||Ke.current!==se)return;let G=Fe.vaultSetupToken??Fe.subscriptionID??Fe.orderID??"",ye=G?cr.current.get(G):en.current.get(se);if(!(!ye||!dr(ye.generation))&&ln(ye.generation)){cr.current.delete(G),en.current.delete(ye.surfaceKey),Nt("approved");try{if(be(!0),Je(()=>gn.current?.(null)),!G)throw new Wt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ne=An.current,wt=ho(Hn.current??[ne?.customer?.firstName,ne?.customer?.lastName].filter(Boolean).join(" ")),Ge=Un({email:ye.accountPatch?.email?.trim()||Mt.current?.trim()||ne?.customer?.email?.trim(),firstName:ye.accountPatch?.firstName?.trim()||wt.firstName,lastName:ye.accountPatch?.lastName?.trim()||wt.lastName});if(!(0,Wt.isValidEmail)(Ge.email)||!(Ge.firstName||Ge.lastName))try{let In=au(await ke?.order?.get?.());Ge=Un({email:In.email||Ge.email,firstName:In.firstName||Ge.firstName,lastName:In.lastName||Ge.lastName})}catch{}if((dt.current||Ye)&&!(0,Wt.isValidEmail)(Ge.email)){let In=await Z("PayPal",Ge);if(!In)return;Ge=In}(0,Wt.isValidEmail)(Ge.email)&&(ye.accountPatch=Un({...ye.accountPatch,...Ge}),await dt.current?.(Ge));let fr;C==="setup_token"?fr={id:G,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Wt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:x?fr={id:G,isPaypal:!0,gateway:"paypal",paymentMethodType:Wt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:fr={id:G,isPaypal:!0},await q(fr,ye)}catch(ne){On(ne instanceof Error?ne.message:"PayPal capture failed.")}finally{ft()||be(!1)}}},xe=Fe=>{let ke=Se?()=>$(Se):()=>gt(Fe);return async()=>wn(await ke())},et=H.Buttons({style:{layout:"horizontal",height:si,tagline:!1},...ve==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Fe,ke)=>{if(ft()){await ke.reject();return}Ft();let G=nt.current,ye={};if(G)try{let Ge=await G("paypal");if(ft()){await ke.reject();return}if(!Ge.proceed){$t.current=null,en.current.delete(se),await ke.reject();return}ye={sessionId:Ge.sessionId,accountPatch:Ge.accountPatch,nonce:Ge.nonce}}catch(Ge){Be(`onClick:runBeforeButtonClick rejected msg=${(Ge instanceof Error?Ge.message:String(Ge)).slice(0,120)}`),$t.current=null,en.current.delete(se),await ke.reject();return}Je(()=>$n.current?.("paypal"));let ne=rn(),wt={generation:ne,surfaceKey:se,...ye};$t.current=wt,en.current.set(se,wt),Ae.current={...v,attempt:ne},await ke.resolve(),pe.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),pe.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Pe.current=pe.startTiming()},createOrder:C==="order"?xe("Failed to create PayPal order."):void 0,createSubscription:C==="subscription"?xe("Failed to create PayPal subscription."):void 0,createVaultSetupToken:C==="setup_token"?async()=>wn(await gt("Failed to create PayPal setup token.")):void 0,onApprove:Ce,onCancel:()=>{if(ft())return;let Fe=en.current.get(se)??$t.current;Fe&&en.current.delete(Fe.surfaceKey),$t.current=null,Nt("cancelled"),pe.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ie.current=!0,Mn({generation:Fe?.generation,remount:!0,focus:!1})},onError:Fe=>{if(ft()||Ke.current!==se)return;let ke=Fe instanceof Error?Fe.message:"PayPal failed to render.";if(Be(`onError rendered=${Bn} msg=${ke.slice(0,120)}`),Bn){let G=en.current.get(se)??$t.current;if(G&&!dr(G.generation)||!G&&ur())return;if(qr(ke)){ln(G?.generation);return}let{errorCode:ye,popupBlocked:ne,providerDeclined:wt,terminalReason:Ge}=ao(Fe,{inAppBrowser:Y.inAppBrowser,handoffObserved:G!=null&&J.current===G.generation});if(ne&&U.markBlocked(),Nt(Ge),wt){pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ge}),It(Fe,G),Je(()=>jt.current?.(mn("paypal",ke))),G&&en.current.delete(G.surfaceKey),$t.current=null,ln(G?.generation);return}pe.error({errorCode:ye,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ge}),G&&en.current.delete(G.surfaceKey),$t.current=null,Mn({generation:G?.generation,remount:!0,showRetry:!0,focus:!0}),sn(Fe,{code:"paypal_runtime_failed",popupBlocked:ne,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ve,terminalReason:Ge});return}L(qr(ke)?"teardown":"pre_ready_callback",ke)}}),Pt=et.isEligible();if(Be(`isEligible=${Pt}`),pe.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Pt){te(!1),L("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Or=!0,er=et,Ot=()=>{if(!tr||Nr||ft()||Bn)return;Nr=!0,Be(`container:dims ${kn(Dn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(kr=new MutationObserver(ke=>{if(!ft()){for(let G of ke)if(G.type==="childList")G.addedNodes.forEach(ye=>{if(!(ye instanceof Element))return;let ne=ye.tagName.toLowerCase(),wt=(ye.getAttribute("title")??"").slice(0,40),Ge=ne==="iframe"?` ${Ur(ye)}`:"";Be(`child+ ${ne}${wt?` title="${wt}"`:""}${Ge} dims=${kn(ye)}`)});else if(G.type==="attributes"&&G.target instanceof Element){let ye=G.target;if(ye.tagName.toLowerCase()!=="iframe")continue;let ne=G.attributeName;(ne==="src"||ne==="srcdoc")&&Be(`attr~ iframe ${ne}=${ne==="srcdoc"?`[${(ye.getAttribute("srcdoc")??"").length}ch]`:nr(ye.getAttribute("src"))} dims=${kn(ye)}`)}}}),kr.observe(Dn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Fe=ke=>{if(ft()||Bn)return;let G=Dn.querySelectorAll("iframe"),ye=typeof document<"u"&&"hasStorageAccess"in document;Be(`watchdog:${ke} container=${kn(Dn)} children=${Dn.childElementCount} iframes=${G.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ye} paypalNetRequests=${Rn.value}`),G.forEach((ne,wt)=>{let Ge=(ne.getAttribute("title")??"").slice(0,40);Be(` iframe[${wt}] ${kn(ne)}${Ge?` title="${Ge}"`:""} ${Ur(ne)}`);let fr=zr(ne);fr&&Be(` ${fr}`)}),lt.length===0&&Be(" (no PayPal/zoid window errors captured)")};Lr.push(setTimeout(()=>Fe("3s"),3e3)),Lr.push(setTimeout(()=>Fe("8s"),8e3)),Lr.push(setTimeout(()=>Fe("15s"),15e3))},Ot(),Be("render:start");let F=pe.startTiming();Kn=setTimeout(()=>{ft()||Bn||(Be("watchdog:11s retryable render timeout"),L("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},tu);let St=et.render(Dn);(async()=>{try{if(await St,Be(`render:resolved inactive=${ft()}`),_n(),ft()){yr();return}Bn=!0,te(!0),We(!1),Dt.current?.("ready"),pe.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"checkout_render",durationMs:pe.elapsed(F),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Fe){let ke=Fe instanceof Error?Fe.message:"PayPal failed to render.";Be(`render:rejected msg=${ke.slice(0,120)}`),_n(),L(qr(ke)?"teardown":"render_rejected",ke)}})()}).catch(H=>{let Ce=H instanceof Error?H.message:"PayPal operation failed.";Be(`provider:failed msg=${Ce.slice(0,120)}`);let xe="script_rejected";N&&qr(Ce)?xe="teardown":N&&Or&&(xe="render_rejected"),L(xe,Ce)})},0);return()=>{Gt=!0,clearTimeout(Q),Fn&&clearTimeout(Fn),_n(),st.current===pn&&(st.current=null),yr(),Pe.current=null,Ae.current=null}},[k,_t,i,p,c,C,ve,x,e,Se,je,_e,Z,Ye,Be,Nt]);let mt=le?(0,ar.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ht?"#fef2f2":"#f3f4f6",border:`1px solid ${ht?"#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=${Te} failed=${ht})`,yt.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
3
  ${yt.join(`
4
- `)}`]}):null;return ht&&!D?le?(0,ar.jsx)("div",{children:mt}):null:(0,ar.jsxs)("div",{children:[mt,Qe&&(0,ar.jsx)(zo,{identity:Qe.identity,methodLabel:Qe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Le,onCancel:()=>Le(null)}),(0,ar.jsxs)("div",{"aria-hidden":at||Qe?!0:void 0,style:at||Qe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ii},children:[!Te&&!at&&(0,ar.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,ar.jsx)("div",{ref:ce,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ii,display:"flex",opacity:Te?1:0},"aria-busy":z||P},Ve)]},Ve),it&&(0,ar.jsx)("button",{ref:we,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:nn,style:eu,children:"Try PayPal again"})]})}function Sa(e){return(0,ar.jsx)(Jl,{...e})}function Zl(e){return(0,ar.jsx)(Jl,{...e})}var wa=require("react/jsx-runtime");function $o({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,wa.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,wa.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,wa.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 si=require("@flopay/shared");function jo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var gs=":idempotency-key";function hs(e,t){if(!jo())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 bs(e,t){if(!jo())return null;try{let n=window.sessionStorage.getItem(e+gs);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 li(e,t){if(jo())try{hs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ci(e,t){if(li(e,t),!!jo())try{bs(e,t)&&window.sessionStorage.removeItem(e+gs)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function di(e,t,n,r){if(jo())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 ui(e,t,n){if(jo())try{window.sessionStorage.setItem(e+gs,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function fs(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function au(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([i],[c])=>i<c?-1:i>c?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let i=0;i<t.length;i++){let c=t.charCodeAt(i);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(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}function Ho(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=>fs(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>fs(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>fs(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:au(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Ql(e,t=!1){let n=Ho(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 ec(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,si.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,si.foldIntoProducts)(t.items,t.subscriptions)).map(d=>({type:d.type,code:d.code??d.providerItemId??d.providerPlanId??"",quantity:d.quantity??1,totalAmount:d.totalAmount,overrideAmount:d.overrideAmount??null,currency:(d.currency??o).toUpperCase()})).sort((d,g)=>`${d.code}:${d.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),i=e.products.map(d=>({type:d.type,code:d.code??"",quantity:d.quantity??1,totalAmount:d.totalAmount,overrideAmount:d.overrideAmount??null,currency:(d.currency??e.currency).toUpperCase()})).sort((d,g)=>`${d.code}:${d.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(a.length!==i.length)return!1;for(let[d,g]of a.entries()){let b=i[d];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((d,g)=>d===p[g])}var an=require("react/jsx-runtime");var iu={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function qn({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:i="You will be automatically redirected, do not close or navigate away from this window.",theme:c=iu}){let p={fontSize:13,color:c.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,an.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,an.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,an.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,an.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,an.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:c.spinnerTrackColor,strokeWidth:"3"}),(0,an.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.spinnerAccentColor})]}),e==="success"&&(0,an.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,an.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,an.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,an.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,an.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,an.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,an.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,an.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,an.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"&&i!==null&&(0,an.jsx)("p",{style:p,children:i}),e==="error"&&t&&(0,an.jsx)("p",{style:p,children:t}),(0,an.jsx)("style",{children:`
4
+ `)}`]}):null;return ht&&!D?le?(0,ar.jsx)("div",{children:mt}):null:(0,ar.jsxs)("div",{children:[mt,Qe&&(0,ar.jsx)(qo,{identity:Qe.identity,methodLabel:Qe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Le,onCancel:()=>Le(null)}),(0,ar.jsxs)("div",{"aria-hidden":at||Qe?!0:void 0,style:at||Qe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:si},children:[!Te&&!at&&(0,ar.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,ar.jsx)("div",{ref:ce,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:si,display:"flex",opacity:Te?1:0},"aria-busy":V||P},je)]},je),it&&(0,ar.jsx)("button",{ref:we,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:nn,style:nu,children:"Try PayPal again"})]})}function wa(e){return(0,ar.jsx)(Zl,{...e})}function Ql(e){return(0,ar.jsx)(Zl,{...e})}var ka=require("react/jsx-runtime");function $o({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,ka.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,ka.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ka.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 li=require("@flopay/shared");function Ho(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var hs=":idempotency-key";function bs(e,t){if(!Ho())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 Ps(e,t){if(!Ho())return null;try{let n=window.sessionStorage.getItem(e+hs);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 ci(e,t){if(Ho())try{bs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function di(e,t){if(ci(e,t),!!Ho())try{Ps(e,t)&&window.sessionStorage.removeItem(e+hs)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ui(e,t,n,r){if(Ho())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 pi(e,t,n){if(Ho())try{window.sessionStorage.setItem(e+hs,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function gs(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function su(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([i],[c])=>i<c?-1:i>c?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let i=0;i<t.length;i++){let c=t.charCodeAt(i);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(i=>(i>>>0).toString(16).padStart(8,"0")).join("")}function Wo(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=>gs(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>gs(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>gs(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:su(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function ec(e,t=!1){let n=Wo(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 tc(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,li.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,li.foldIntoProducts)(t.items,t.subscriptions)).map(d=>({type:d.type,code:d.code??d.providerItemId??d.providerPlanId??"",quantity:d.quantity??1,totalAmount:d.totalAmount,overrideAmount:d.overrideAmount??null,currency:(d.currency??o).toUpperCase()})).sort((d,g)=>`${d.code}:${d.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),i=e.products.map(d=>({type:d.type,code:d.code??"",quantity:d.quantity??1,totalAmount:d.totalAmount,overrideAmount:d.overrideAmount??null,currency:(d.currency??e.currency).toUpperCase()})).sort((d,g)=>`${d.code}:${d.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(a.length!==i.length)return!1;for(let[d,g]of a.entries()){let b=i[d];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((d,g)=>d===p[g])}var an=require("react/jsx-runtime");var lu={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function zn({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:i="You will be automatically redirected, do not close or navigate away from this window.",theme:c=lu}){let p={fontSize:13,color:c.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,an.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,an.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,an.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,an.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,an.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:c.spinnerTrackColor,strokeWidth:"3"}),(0,an.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.spinnerAccentColor})]}),e==="success"&&(0,an.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,an.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,an.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,an.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,an.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,an.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,an.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,an.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,an.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"&&i!==null&&(0,an.jsx)("p",{style:p,children:i}),e==="error"&&t&&(0,an.jsx)("p",{style:p,children:t}),(0,an.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 tc=require("@flopay/shared"),Pn=require("react");var nc=require("react/jsx-runtime");function ka({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,i]=(0,Pn.useState)(e instanceof Promise?null:e),[c,p]=(0,Pn.useState)(t instanceof Promise||!t?null:t),d=(0,Pn.useRef)(null),g=(0,Pn.useRef)(null),b=Vo(r);(0,Pn.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,Pn.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,Pn.useEffect)(()=>{if(a)return fn(a)?.subscribe?.(b)},[b,a]),(0,Pn.useEffect)(()=>{if(!(!c||c===a))return fn(c)?.subscribe?.(b)},[b,a,c]),(0,Pn.useEffect)(()=>{if(!a)return;let S=fn(a);return d.current=S?.beginCheckout()??S?.now()??0,S?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{S?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,Pn.useEffect)(()=>{let S=!1;return e instanceof Promise?e.then(A=>{S||i(A)},()=>{S||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):i(e),()=>{S=!0}},[b,e]),(0,Pn.useEffect)(()=>{let S=!1;if(!t){p(null);return}return t instanceof Promise?t.then(A=>{S||p(A)},()=>{S||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{S=!0}},[b,t]),(0,Pn.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(d.current??0),durationMode:"machine"})},[b,a]);let T=(0,tc.resolveBillingApiUrl)(n?.billingApiUrl),_=(0,Pn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:T,emitInstrument:b}),[a,c,T,b]);return(0,nc.jsx)(or.Provider,{value:_,children:o})}var pi="flopay_recent_completion_";function Wo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(pi+e,JSON.stringify(t))}catch{}}function Ps(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(pi+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(pi+e),!1):!0}catch{return!1}}async function mi(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 io=require("@flopay/js"),tt=require("@flopay/shared");var Ia="card",su=1e3;async function lu(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:i}=await e.retrieveSetupIntent(t);return{error:i,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 cu(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:i,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:i??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 so(e){return new tt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function vs(){return new tt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Ss(e,t){return Object.assign(e,{checkoutMethod:t})}function Gr(e,t){let n=e instanceof tt.FloPayError?e:new tt.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 Ra(e,t){try{return await e()}catch(n){throw Gr(n,t)}}function oc(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 du(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function ws(e){if(typeof document>"u"||typeof window>"u")throw new tt.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw so();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 _=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 A=await S.json().catch(()=>null);return uu(A)}catch{return{status:"unknown"}}finally{window.clearTimeout(_),e.signal?.removeEventListener("abort",T)}},a,i=()=>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 d=document.createElement("iframe");d.setAttribute("title","Card authentication"),d.setAttribute("allow","payment"),d.tabIndex=0,d.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,_)=>{let S=!1,A=0,I=0,P=0,w=!1,K=()=>{window.clearTimeout(A),window.clearInterval(I),window.clearTimeout(P),window.removeEventListener("message",X),d.removeEventListener("load",ge),e.signal?.removeEventListener("abort",q)},k=async()=>{if(!(S||w)){w=!0;try{let Se=await i();if(S||!du(Se))return;S=!0,K(),T(Se)}finally{w=!1}}},ge=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(P),P=window.setTimeout(()=>{k()},250))},q=()=>{S||(S=!0,K(),_(so()))},X=Se=>{if(Se.source!==d.contentWindow||g&&Se.origin!==g)return;let oe=Se.data;!oe||typeof oe!="object"||oe.source!=="flopay-vault-3ds-return"||S||(S=!0,K(),T(null))};A=window.setTimeout(()=>{S||(S=!0,K(),_(vs()))},tt.THREE_DS_CHALLENGE_WINDOW_MS),e.pollCompletionEndpoint!==!1&&(I=window.setInterval(()=>{k()},t)),d.addEventListener("load",ge),window.addEventListener("message",X),e.signal?.addEventListener("abort",q),d.src=e.nextActionRedirectUrl,p.appendChild(d),document.body.appendChild(p),d.focus(),e.signal?.aborted&&q()});return b||await i()}finally{p.parentNode?.removeChild(p),c?.isConnected&&c.focus()}}async function Ko(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,i=new io.PaymentAPI(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,p=new AbortController,d=new AbortController,g=()=>{p.abort(o.reason),d.abort(o.reason)};o.aborted?g():o.addEventListener("abort",g,{once:!0});let b=ws({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:p.signal,pollCompletionEndpoint:!1}),T=i.waitForCheckoutSessionCompletion(r,{initialDelayMs:su,nonce:a,statusUrl:c,continueAfterActionRequired:!0,timeoutMs:tt.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:d.signal}),_;try{let A=await Promise.race([b,T]);if("data"in A)_=A;else{if(A.status==="declined")throw Fr({type:A.declineReason??"authorization_declined",gatewayErrorCode:A.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(A.status==="timeout")throw vs();_=await T}}catch(A){if(o.aborted||A instanceof Error&&A.name==="AbortError")throw so(A);if(!(A instanceof tt.FloPayError)||A.code!=="three_ds_timeout"&&A.code!=="checkout_processing_timeout")throw A;try{_=await i.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:a,statusUrl:c,timeoutMs:5e3,signal:o})}catch(P){if(o.aborted)throw so(P);if(!(P instanceof tt.FloPayError)||P.code!=="checkout_processing_timeout")throw P}let I=_&&no(_,t.session);if(!jr(I)&&I?.status!=="expired"){if(t.telemetry){let P=new io.PaymentAPI(n);try{P.reportThreeDsAbandoned(r)}finally{P.destroy()}}throw vs()}}finally{o.removeEventListener("abort",g),p.abort(),d.abort()}let S=_&&no(_,t.session);if(!jr(S))throw No(S);return{...$r(S,r),checkoutMethod:"card"}}function uu(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":case"authorized":case"pending":case"timeout":return{status:t,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"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Fr(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=to(o)??o,i=Ss(new tt.FloPayError(a,"api_error",{code:e?.code??(0,tt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,tt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(i.orderId=e.orderId),i}function Cs(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function yi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ac(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||yi(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||yi(c)))return c;let i=o.gateways;if(i&&typeof i=="object"){let c=i.stripe;if(c&&typeof c=="object"){let p=c,d=[p.stripeClientSecret,p.clientSecret];for(let g of d)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||yi(g)))return g}}}}async function pu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ac(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 io.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(yi(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Go({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:i}){let c=e.replace(/\/+$/,""),p=t??n.id,d=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",T=n.customer?.firstName??n.accountData?.firstName??"",_=n.customer?.lastName??n.accountData?.lastName??"",S=n.customer?.country??n.accountData?.country??void 0,A=n.customer?.zip??n.accountData?.zip??void 0,P=await new io.PaymentAPI(c,i===!1?{telemetry:!1}:void 0).processPayment(g,{sessionId:p,nonce:d,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:g,email:b,firstName:T,lastName:_,country:S,zip:A},returnUrl:a??Cs(n)});if(P.ok){let k=typeof P.json=="function"?await P.json().catch(()=>null):null;if((0,tt.isAuthorizationOnlySession)(n)||k?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof k?.paymentId=="string"?k.paymentId:n.paymentId,sessionId:typeof k?.sessionId=="string"?k.sessionId:p,authorizationExpiresAt:typeof k?.authorizationExpiresAt=="string"?k.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:ba(o),checkoutMethod:rc(o,n)}};let ge=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ge?{paymentIntentId:ge}:{},paymentMethodId:ba(o),checkoutMethod:rc(o,n)}}}let w;try{w=await P.json()}catch(k){throw new tt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:P.status,cause:k})}if(w?.type==="3ds_required"&&typeof w.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:w.nextActionRedirectUrl};if(w?.type==="paypal_redirect_required"||w?.type==="3ds_required"){let k=ac(w);if(!k)throw new tt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:P.status});return{type:w.type,threeDSecureToken:k,paymentMethodId:w.paymentMethodId}}if(w?.gatewayErrorCode==="authentication_required"){let k=await pu({billingApiUrl:c,sessionId:p,nonce:d,responseJson:w});if(k)return k;throw Ss(new tt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let K=new tt.FloPayError(w?.message??"Payment failed. Please try again.","api_error",{code:w?.code??w?.gatewayErrorCode,declineCode:w?.declineCode??w?.gatewayDeclineReason,statusCode:P.status});throw Object.assign(K,{telemetryOutcome:(0,tt.classifyPaymentRejection)(P.status,w)})}async function fi(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:d}){let g=t?.getRawProvider();if(!g)throw Gr(new tt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ss(new tt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,tt.isSetupIntentClientSecret)(e.threeDSecureToken),T=null,_=e.paymentMethodId,S=await Ra(()=>lu(g,e.threeDSecureToken,b),"card");if(S){if(S.error)throw Gr(new tt.FloPayError(S.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:S.error.code}),"card");let I=S.intent;!_&&I?.payment_method&&(typeof I.payment_method=="string"?_=I.payment_method:"id"in I.payment_method&&(_=I.payment_method.id??void 0))}let A=_?await Ra(()=>cu(g,e.threeDSecureToken,{payment_method:_,return_url:c??Cs(i)??window.location.href},b),"card"):null;if(A){if(A.error)throw Gr(new tt.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");T=A.intent}else{let I=await Ra(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(I.error)throw Gr(new tt.FloPayError(I.error.message??"3DS authentication failed.","api_error",{code:I.error.code}),"card");T=(b?I.setupIntent:I.paymentIntent)??null}if(T&&(T.status==="requires_capture"||T.status==="succeeded"||T.status==="processing")){let I=await Go({billingApiUrl:o,sessionId:a,session:i,telemetry:p,tokenizedData:{id:T.id,type:"card",threeDSecureActionResultTokenId:T.id},returnUrl:c});return I.type==="success"?{...I.result,paymentIntentId:I.result.paymentIntentId??T.id,paymentMethodId:I.result.paymentMethodId??_}:I.type==="next_action_required"?Ko(I,{billingApiUrl:o,sessionId:a??i.id,session:i,signal:d}):fi(I,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:d})}throw Gr(new tt.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw Gr(new tt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:_}=await Ra(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(_)throw Gr(new tt.FloPayError(_.message??"PayPal authorization failed.","api_error",{code:_.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:T}=await Ra(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Cs(i)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(T)throw Gr(new tt.FloPayError(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new tt.FloPayError("Unsupported payment redirect state.","api_error")}function Ea(e){if(e instanceof tt.FloPayError){let r=to(e.message);return r&&r!==e.message?Object.assign(new tt.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=to(t)??t;return new tt.FloPayError(n,"api_error")}function ks(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Qr(e.data.session);if(!t&&!n&&!r)throw new tt.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 rc(e,t){return e?e.isPaypal?"paypal":"card":t&&Qr(t)?"card":void 0}async function Rs({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,[i,c]=await Promise.all([(0,io.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,io.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(d=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",d),null)):Promise.resolve(null)]);if(!i)throw new tt.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return a?p=c:t&&(p=i),{flopay:i,paypalFlopay:p}}var wr=require("@flopay/js"),y=require("@flopay/shared"),Zt=require("@stripe/react-stripe-js"),s=is(require("react"),1);function Yo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function gi(e,t){if(e)return{error:n=>e.error(Yo(t,n)),log:n=>e.log(Yo(t,n)),performance:n=>e.performance(Yo(t,n)),terminal:n=>e.terminal(Yo(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 Yr=require("@flopay/shared"),sc=require("react");var ic={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 gn=require("react/jsx-runtime"),mu=`
9
+ `})]})})}var nc=require("@flopay/shared"),bn=require("react");var rc=require("react/jsx-runtime");function Ra({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,i]=(0,bn.useState)(e instanceof Promise?null:e),[c,p]=(0,bn.useState)(t instanceof Promise||!t?null:t),d=(0,bn.useRef)(null),g=(0,bn.useRef)(null),b=jo(r);(0,bn.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,bn.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,bn.useEffect)(()=>{if(a)return yn(a)?.subscribe?.(b)},[b,a]),(0,bn.useEffect)(()=>{if(!(!c||c===a))return yn(c)?.subscribe?.(b)},[b,a,c]),(0,bn.useEffect)(()=>{if(!a)return;let S=yn(a);return d.current=S?.beginCheckout()??S?.now()??0,S?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{S?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,bn.useEffect)(()=>{let S=!1;return e instanceof Promise?e.then(A=>{S||i(A)},()=>{S||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):i(e),()=>{S=!0}},[b,e]),(0,bn.useEffect)(()=>{let S=!1;if(!t){p(null);return}return t instanceof Promise?t.then(A=>{S||p(A)},()=>{S||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{S=!0}},[b,t]),(0,bn.useEffect)(()=>{if(!a||g.current===a)return;g.current=a;let S=yn(a);S?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),S?.performance({stage:"checkout_render",durationMs:S.elapsed(d.current??0),durationMode:"machine"})},[b,a]);let T=(0,nc.resolveBillingApiUrl)(n?.billingApiUrl),E=(0,bn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:T,emitInstrument:b}),[a,c,T,b]);return(0,rc.jsx)(or.Provider,{value:E,children:o})}var mi="flopay_recent_completion_";function Ko(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(mi+e,JSON.stringify(t))}catch{}}function vs(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(mi+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(mi+e),!1):!0}catch{return!1}}async function yi(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 so=require("@flopay/js"),tt=require("@flopay/shared");var Ia="card",cu=1e3;async function du(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:i}=await e.retrieveSetupIntent(t);return{error:i,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 uu(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:i,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:i??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 lo(e){return new tt.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Cs(){return new tt.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function ws(e,t){return Object.assign(e,{checkoutMethod:t})}function Yr(e,t){let n=e instanceof tt.FloPayError?e:new tt.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 _a(e,t){try{return await e()}catch(n){throw Yr(n,t)}}function ac(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 pu(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function ks(e){if(typeof document>"u"||typeof window>"u")throw new tt.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw lo();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 E=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 A=await S.json().catch(()=>null);return mu(A)}catch{return{status:"unknown"}}finally{window.clearTimeout(E),e.signal?.removeEventListener("abort",T)}},a,i=()=>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 d=document.createElement("iframe");d.setAttribute("title","Card authentication"),d.setAttribute("allow","payment"),d.tabIndex=0,d.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,E)=>{let S=!1,A=0,_=0,P=0,w=!1,K=()=>{window.clearTimeout(A),window.clearInterval(_),window.clearTimeout(P),window.removeEventListener("message",X),d.removeEventListener("load",ge),e.signal?.removeEventListener("abort",z)},k=async()=>{if(!(S||w)){w=!0;try{let Se=await i();if(S||!pu(Se))return;S=!0,K(),T(Se)}finally{w=!1}}},ge=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(P),P=window.setTimeout(()=>{k()},250))},z=()=>{S||(S=!0,K(),E(lo()))},X=Se=>{if(Se.source!==d.contentWindow||g&&Se.origin!==g)return;let ae=Se.data;!ae||typeof ae!="object"||ae.source!=="flopay-vault-3ds-return"||S||(S=!0,K(),T(null))};A=window.setTimeout(()=>{S||(S=!0,K(),E(Cs()))},tt.THREE_DS_CHALLENGE_WINDOW_MS),e.pollCompletionEndpoint!==!1&&(_=window.setInterval(()=>{k()},t)),d.addEventListener("load",ge),window.addEventListener("message",X),e.signal?.addEventListener("abort",z),d.src=e.nextActionRedirectUrl,p.appendChild(d),document.body.appendChild(p),d.focus(),e.signal?.aborted&&z()});return b||await i()}finally{p.parentNode?.removeChild(p),c?.isConnected&&c.focus()}}async function Go(e,t){let{billingApiUrl:n,sessionId:r,signal:o}=t,a=t.nonce??t.session.clientSecret,i=new so.PaymentAPI(n,{telemetry:!1}),c=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(r)}/status`,p=new AbortController,d=new AbortController,g=()=>{p.abort(o.reason),d.abort(o.reason)};o.aborted?g():o.addEventListener("abort",g,{once:!0});let b=ks({billingApiUrl:n,sessionId:r,nonce:a,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:p.signal,pollCompletionEndpoint:!1}),T=i.waitForCheckoutSessionCompletion(r,{initialDelayMs:cu,nonce:a,statusUrl:c,continueAfterActionRequired:!0,timeoutMs:tt.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:d.signal}),E;try{let A=await Promise.race([b,T]);if("data"in A)E=A;else{if(A.status==="declined")throw xr({type:A.declineReason??"authorization_declined",gatewayErrorCode:A.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});if(A.status==="timeout")throw Cs();E=await T}}catch(A){if(o.aborted||A instanceof Error&&A.name==="AbortError")throw lo(A);if(!(A instanceof tt.FloPayError)||A.code!=="three_ds_timeout"&&A.code!=="checkout_processing_timeout")throw A;try{E=await i.waitForCheckoutSessionCompletion(r,{initialDelayMs:0,nonce:a,statusUrl:c,timeoutMs:5e3,signal:o})}catch(P){if(o.aborted)throw lo(P);if(!(P instanceof tt.FloPayError)||P.code!=="checkout_processing_timeout")throw P}let _=E&&ro(E,t.session);if(!Hr(_)&&_?.status!=="expired"){if(t.telemetry){let P=new so.PaymentAPI(n);try{P.reportThreeDsAbandoned(r)}finally{P.destroy()}}throw Cs()}}finally{o.removeEventListener("abort",g),p.abort(),d.abort()}let S=E&&ro(E,t.session);if(!Hr(S))throw Uo(S);return{...$r(S,r),checkoutMethod:"card"}}function mu(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":case"authorized":case"pending":case"timeout":return{status:t,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"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function xr(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=no(o)??o,i=ws(new tt.FloPayError(a,"api_error",{code:e?.code??(0,tt.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,tt.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(i.orderId=e.orderId),i}function Ss(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function fi(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ic(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||fi(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||fi(c)))return c;let i=o.gateways;if(i&&typeof i=="object"){let c=i.stripe;if(c&&typeof c=="object"){let p=c,d=[p.stripeClientSecret,p.clientSecret];for(let g of d)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||fi(g)))return g}}}}async function yu({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ic(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 so.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(fi(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Yo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:i}){let c=e.replace(/\/+$/,""),p=t??n.id,d=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",T=n.customer?.firstName??n.accountData?.firstName??"",E=n.customer?.lastName??n.accountData?.lastName??"",S=n.customer?.country??n.accountData?.country??void 0,A=n.customer?.zip??n.accountData?.zip??void 0,P=await new so.PaymentAPI(c,i===!1?{telemetry:!1}:void 0).processPayment(g,{sessionId:p,nonce:d,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:g,email:b,firstName:T,lastName:E,country:S,zip:A},returnUrl:a??Ss(n)});if(P.ok){let k=typeof P.json=="function"?await P.json().catch(()=>null):null;if((0,tt.isAuthorizationOnlySession)(n)||k?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof k?.paymentId=="string"?k.paymentId:n.paymentId,sessionId:typeof k?.sessionId=="string"?k.sessionId:p,authorizationExpiresAt:typeof k?.authorizationExpiresAt=="string"?k.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Pa(o),checkoutMethod:oc(o,n)}};let ge=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ge?{paymentIntentId:ge}:{},paymentMethodId:Pa(o),checkoutMethod:oc(o,n)}}}let w;try{w=await P.json()}catch(k){throw new tt.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:P.status,cause:k})}if(w?.type==="3ds_required"&&typeof w.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:w.nextActionRedirectUrl};if(w?.type==="paypal_redirect_required"||w?.type==="3ds_required"){let k=ic(w);if(!k)throw new tt.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:P.status});return{type:w.type,threeDSecureToken:k,paymentMethodId:w.paymentMethodId}}if(w?.gatewayErrorCode==="authentication_required"){let k=await yu({billingApiUrl:c,sessionId:p,nonce:d,responseJson:w});if(k)return k;throw ws(new tt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let K=new tt.FloPayError(w?.message??"Payment failed. Please try again.","api_error",{code:w?.code??w?.gatewayErrorCode,declineCode:w?.declineCode??w?.gatewayDeclineReason,statusCode:P.status});throw Object.assign(K,{telemetryOutcome:(0,tt.classifyPaymentRejection)(P.status,w)})}async function gi(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:d}){let g=t?.getRawProvider();if(!g)throw Yr(new tt.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ws(new tt.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,tt.isSetupIntentClientSecret)(e.threeDSecureToken),T=null,E=e.paymentMethodId,S=await _a(()=>du(g,e.threeDSecureToken,b),"card");if(S){if(S.error)throw Yr(new tt.FloPayError(S.error.message??`Failed to retrieve 3DS ${b?"setup":"payment"} status.`,"api_error",{code:S.error.code}),"card");let _=S.intent;!E&&_?.payment_method&&(typeof _.payment_method=="string"?E=_.payment_method:"id"in _.payment_method&&(E=_.payment_method.id??void 0))}let A=E?await _a(()=>uu(g,e.threeDSecureToken,{payment_method:E,return_url:c??Ss(i)??window.location.href},b),"card"):null;if(A){if(A.error)throw Yr(new tt.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");T=A.intent}else{let _=await _a(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(_.error)throw Yr(new tt.FloPayError(_.error.message??"3DS authentication failed.","api_error",{code:_.error.code}),"card");T=(b?_.setupIntent:_.paymentIntent)??null}if(T&&(T.status==="requires_capture"||T.status==="succeeded"||T.status==="processing")){let _=await Yo({billingApiUrl:o,sessionId:a,session:i,telemetry:p,tokenizedData:{id:T.id,type:"card",threeDSecureActionResultTokenId:T.id},returnUrl:c});return _.type==="success"?{..._.result,paymentIntentId:_.result.paymentIntentId??T.id,paymentMethodId:_.result.paymentMethodId??E}:_.type==="next_action_required"?Go(_,{billingApiUrl:o,sessionId:a??i.id,session:i,signal:d}):gi(_,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:i,returnUrl:c,telemetry:p,signal:d})}throw Yr(new tt.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw Yr(new tt.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:E}=await _a(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(E)throw Yr(new tt.FloPayError(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:T}=await _a(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Ss(i)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(T)throw Yr(new tt.FloPayError(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new tt.FloPayError("Unsupported payment redirect state.","api_error")}function Ea(e){if(e instanceof tt.FloPayError){let r=no(e.message);return r&&r!==e.message?Object.assign(new tt.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode,sessionId:e.sessionId}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=no(t)??t;return new tt.FloPayError(n,"api_error")}function Rs(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||eo(e.data.session);if(!t&&!n&&!r)throw new tt.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 oc(e,t){return e?e.isPaypal?"paypal":"card":t&&eo(t)?"card":void 0}async function _s({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,[i,c]=await Promise.all([(0,so.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,so.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(d=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",d),null)):Promise.resolve(null)]);if(!i)throw new tt.FloPayError("The payment provider did not initialize.","authentication_error");let p=null;return a?p=c:t&&(p=i),{flopay:i,paypalFlopay:p}}var Sr=require("@flopay/js"),y=require("@flopay/shared"),Zt=require("@stripe/react-stripe-js"),s=ss(require("react"),1);function Xo(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function hi(e,t){if(e)return{error:n=>e.error(Xo(t,n)),log:n=>e.log(Xo(t,n)),performance:n=>e.performance(Xo(t,n)),terminal:n=>e.terminal(Xo(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 Xr=require("@flopay/shared"),lc=require("react");var sc={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 fn=require("react/jsx-runtime"),fu=`
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 @@ ${yt.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
- `,Xo=44;function Jo(){return(0,gn.jsx)("style",{children:mu})}function _a(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Ta({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,gn.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,gn.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,gn.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 Is(e){return e!=="unavailable"&&e!=="load_error"}function hi({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:i,backgroundColor:c,borderColor:p,textColor:d,borderRadius:g,fontFamily:b}){let T=(0,Yr.resolveStripeMethodBrandVariant)(e,t),_=ic[e],[S,A]=(0,sc.useState)(!1),I=!!_&&!S,P=T?.backgroundColor??c??"#ffffff",w=T?.borderColor??p??"#d1d5db",K=T?.textColor??d??"#262833";return(0,gn.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&i()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Xo,padding:"0 1rem",backgroundColor:P,color:K,border:`1px solid ${w}`,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,gn.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,Yr.getStripeMethodDisplayName)(e)}\u2026`}):(0,gn.jsxs)(gn.Fragment,{children:[(0,gn.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,Yr.hasVendoredStripeMethodLogo)(e)?8:0},children:[I?(0,gn.jsx)("img",{src:_,alt:"","aria-hidden":"true",onError:()=>A(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!I&&T?.logoSvg?(0,gn.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,gn.jsx)("span",{children:(0,Yr.getStripeMethodDisplayName)(e)})]}),a&&(0,gn.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:K,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,gn.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function bi(e){let t=new Set(e.map(Yr.stripeExpressMethodToOptionKey)),n=r=>r==="applePay"||r==="googlePay"?"always":"auto";return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?n(r):"never"]))}var Pi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},vi={type:"accordion",defaultCollapsed:!1,radios:"never"};function Ci({testId:e,attributes:t,disabled:n,onClick:r,color:o,borderRadius:a,style:i,children:c}){return(0,gn.jsx)("button",{type:"button","data-testid":e,...t,onClick:r,disabled:n,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:o,color:"white",border:"none",borderRadius:a,fontSize:"1rem",fontWeight:600,cursor:n?"not-allowed":"pointer",opacity:n?.5:1,transition:"opacity 120ms ease-out",...i??{}},children:c})}var Jn=require("react");function Si(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(i=>i.startsWith("background")),a={};for(let[i,c]of Object.entries(e))i in n||o&&i.startsWith("background")||(a[i]=c);for(let i of r)a[i]=n[i];return a}var yu=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 fu(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return yu.has(t.charAt(0).toLowerCase()+t.slice(1))}function gu(e,t){return typeof t=="number"&&t!==0&&!fu(e)?`${t}px`:String(t).trim()}function lc(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]=gu(n,r)}}}var Co=require("react/jsx-runtime"),Es=new WeakSet;function lo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:i,onReady:c,onError:p,onValidation:d}){let g=(0,Jn.useRef)(null),b=(0,Jn.useRef)(c),T=(0,Jn.useRef)(p),_=(0,Jn.useRef)(d);b.current=c,T.current=p,_.current=d;let S=(0,Jn.useRef)(o);S.current=o;let A=(0,Jn.useRef)(null),I=a??void 0,P=(0,Jn.useRef)(I);P.current=I;let w=(0,Jn.useRef)(void 0);return(0,Jn.useEffect)(()=>{let K=g.current;if(!K)return;let k=!0,ge=!1,q=()=>{!k||ge||(ge=!0,b.current?.())},X=e.on("ready",()=>{q()}),Se=e.on("error",le=>{T.current?.(le.message??"There was a problem loading the secure card form.")}),oe=e.on("validation",le=>{_.current?.(le.message??null)}),De=P.current??(Es.has(e)?null:void 0),Ze={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...S.current?{theme:S.current}:{},...De===void 0?{}:{submitLabel:De}};return A.current=S.current??null,w.current=P.current,P.current!==void 0&&Es.add(e),e.mount(K,Ze).then(()=>{q()}).catch(le=>{k&&T.current?.(le instanceof Error?le.message:"Failed to load the secure card form.")}),()=>{k=!1,X(),Se(),oe(),e.unmount()}},[e,t,n,r]),Po(()=>{let K=g.current;K&&lc(K,i)},[i]),(0,Jn.useEffect)(()=>{o!==void 0&&(o===null&&A.current===null||(A.current=o,e.applyTheme?.(o)))},[e,o]),(0,Jn.useEffect)(()=>{I!==w.current&&(w.current=I,I!==void 0&&Es.add(e),e.setSubmitLabel?.(I??null))},[e,I]),(0,Co.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields"})}function wi({label:e}){return(0,Co.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,Co.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,Co.jsx)("span",{children:e}),(0,Co.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var dc=/^#([0-9a-f]{6})$/i,hu=/^#([0-9a-f]{3})$/i,uc=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,pc=/^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,bu=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,Pu=/^(-?\d+(?:\.\d+)?)(?:px)?$/,vu=/^(-?\d+(?:\.\d+)?)em$/,Cu=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,Su=/^[a-z][a-z0-9 -]{0,31}$/i,wu=new Set(["none","uppercase","lowercase","capitalize"]);function mc(e){if(typeof e!="string")return null;let t=e.trim(),n=dc.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=hu.exec(t);if(r){let[g,b,T]=r[1].split("").map(_=>Number.parseInt(_+_,16));return{r:g,g:b,b:T,a:null}}let o=uc.exec(t),a=o?null:pc.exec(t),i=o??a;if(!i)return null;let c=Number(i[1]),p=Number(i[2]),d=Number(i[3]);return c>255||p>255||d>255?null:{r:c,g:p,b:d,a:a?Number(a[4]):null}}function yc({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 Aa(e){if(typeof e!="string")return;let t=e.trim();if(dc.test(t)||uc.test(t))return t;let n=pc.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=mc(t);return r?yc(r):void 0}function ki(e,t=.12){let n=mc(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return yc({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function Ma(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 So(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=Pu.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function ku(e,t,n){if(typeof e!="string")return;let r=vu.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Ru(e){let t=Ma(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=Ma(o," "),i=Aa(a[0]);if(!i)return;let c=r/(t.length-1)*100,p=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),d=n[n.length-1]?.position??-1;if(!Number.isFinite(p)||p<0||p>100||p<d)return;n.push({color:i,position:p})}return{type:"linearGradient",angle:0,stops:n}}function Iu(e){if(typeof e!="string")return;let t=e.trim(),n=Aa(t);if(n)return{type:"solid",color:n};let r=bu.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Ru(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Eu(e){return e.type==="solid"?{type:"solid",color:ki(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:ki(t.color)}))}}function _u(e){let t=!1,n,r=[];for(let p of Ma(e," ")){if(p.toLowerCase()==="inset"){t=!0;continue}let d=Aa(p);if(d){n=d;continue}let g=So(p,-128,128);if(g===void 0)return;r.push(g)}if(!n||r.length<2||r.length>4)return;let[o,a,i=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||i>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:i,spread:c}}function Tu(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=Ma(t,",").map(_u);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function cc(e){if(typeof e!="string")return;let t=Ma(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>Su.test(n)).slice(0,4);return t.length>0?t:void 0}function Au(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=So(t[0],0,64),r=So(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function Mu(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 fc({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=Iu(r.background??r.backgroundColor),i=Aa(o?.colorPrimaryHover),c=i?{type:"solid",color:i}:a&&Eu(a),p={fontFamilies:cc(r.fontFamily)??cc(n),fontSize:So(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Mu(r.fontWeight)??600,letterSpacing:ku(r.letterSpacing,-.1,.5)??.01,lineHeight:So(r.lineHeight,.8,2)??1,textTransform:wu.has(String(r.textTransform))?r.textTransform:"uppercase"},d=Au(r.padding),g=Tu(r.boxShadow),b=So(r.borderRadius,0,9999),T=typeof r.backdropFilter=="string"?So(Cu.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Aa(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:p,...d?{spacing:d}:{},...g?{shadow:g}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...T===void 0?{}:{backdropBlur:T}}}function Zo(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)?ki(r,t):e}function _s(e){if(typeof e=="number"||typeof e=="string")return e}function Qo({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,i=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",p=t.nameInput,d=o(p?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",g=fc({appearance:e,buttonsStyles:t,fontFamily:d});return{primaryColor:i,primaryHoverColor:o(r?.colorPrimaryHover)??Zo(i,.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:d,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(_s(p?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...g?{submitButton:g}:{}}}var u=require("react/jsx-runtime"),Br="flopay_stripe_resume",gc="flopay_wallet_resume",_c="fw1",xu="fw2",Tc=300*1e3,Fu=900,Bu=25e3,Du=25e3,Ou=1e4,Ac=["payment_intent","payment_intent_client_secret","redirect_status"],Sr={provider:"paypal",paymentMethodCategory:"paypal"},Ri={},Ts={};function Kt(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function Os(e){return`${xu}:${e}`}function Ii(e){return Kt(Os(e))}function Ei(e,t){if(typeof window>"u")return null;let n=Os(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>Tc||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Ii(e),null):o}catch{return Ii(e),null}}function Lu(e){return Kt(Os(e.sessionId),e)}function hc(e,t,n){let r=Ei(e,t);return!r||r.clientSecret!==n?!1:Ii(e)}function As(e,t,n){if(typeof window>"u")return;Ei(e,t)?.clientSecret===n&&Ii(e)}function Nu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Ms(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":ha(e.status),o=Nu(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function bc(e,t,n){let r=null;try{return await Promise.race([zl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Ou),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Uu(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Mc(e){return e instanceof y.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function _i(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new wr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Mc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Fa="flopay_paypal_resume",xa=new Map;function xc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(Fa);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function zu(){if(typeof window>"u")return!1;let[e,t]=Ls();return e?xc(t)!==null:!1}function Ls(){let e=new URLSearchParams(window.location.search);return Ac.map(t=>e.get(t))}function Ns(){let e=new URL(window.location.href);for(let t of Ac)e.searchParams.delete(t);return e.toString()}function qu(){Kt(Fa),window.history.replaceState({},"",Ns())}var Vu=250,Pc="Just a moment \u2014 we are finalizing your order. Please press pay again.",$u="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Us(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 Ti({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new wr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function ju(e){return e instanceof y.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function xs(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Fc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=go(n),i=a.firstName?a:go(r?.name);return zn({email:(0,y.isValidEmail)(o)?o:r?.email?.trim(),firstName:i.firstName,lastName:i.lastName})}async function Hu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let i=Fc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,y.isValidEmail)(i.email)?i:a(o,i)}var Ba=180,vc=`flopay-card-enter ${Ba}ms cubic-bezier(0, 0, 0.2, 1) both`,Cc=`flopay-card-exit ${Ba}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Wu=`flopay-buttons-enter ${Ba}ms cubic-bezier(0, 0, 0.2, 1) both`,Ku=`flopay-buttons-exit ${Ba}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Gu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function zs(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 Yu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Xu(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 Fs={width:"100%",minHeight:Xo,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 Ju(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Sc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Bs(e){return e==="paypal"?"PayPal":(0,y.getStripeMethodDisplayName)(e)}function Zu(e){let t=(0,y.getPostalCodeExample)(e);return`Enter a valid ${(0,y.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Qu(e,t,n){let r=(0,y.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,i=a&&!o,c=a&&!!o&&!(0,y.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:i,malformed:c}}function ep(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,y.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function wc(e,t){return t instanceof y.FloPayError?t:new y.FloPayError(t instanceof Error?t.message:`${Ju(e)} before-click hook failed.`,"validation_error")}function tp(e){return typeof e=="number"?`${e}px`:e}function Ai(e){return(0,u.jsx)(np,{...e})}function kc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:i=!1,onButtonClick:c,onDecline:p,onTechnicalFailure:d,runBeforeButtonClick:g,billingName:b,onBuyerIdentityReady:T,onLoadStateChange:_,placeholderBorderRadius:S,popupCapabilityOwner:A,externalTelemetryContext:I,presentationMode:P}){let w=Wr(),{emitInstrument:K}=(0,s.useContext)(or),k=(0,Zt.useStripe)(),ge=(0,Zt.useElements)(),q=(0,s.useMemo)(()=>gi(fn(w),I),[I,w]),[X,Se]=(0,s.useState)("loading");(0,s.useEffect)(()=>{_?.(X)},[X,_]);let[oe,De]=(0,s.useState)(!1),Ze=(0,s.useRef)(!1),le=!(0,y.isValidEmail)(n?.trim())||!b?.trim(),{request:Ee,collect:He,finish:Re}=Uo(),_e=(0,s.useRef)(!1),Ie=(0,s.useRef)(null),ce=(0,s.useRef)(null),[de,Pe]=(0,s.useState)(0),[Ae,J]=(0,s.useState)(!1),ee=(0,s.useRef)(!1),he=(0,s.useRef)(new Map),{startAttempt:U,finishAttempt:we,invalidateAttempt:ie,isAttemptInvalidated:Te,isAttemptCurrent:te,generationRef:at}=Ca((z,be,Qe)=>{d?.(z,be,{...Qe,popupBlocked:Qe?.popupBlocked??ao(be),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:P,terminalReason:"overlay_timeout"}),J(!0),Pe(Z=>Z+1)},{onHandoffObserved:()=>{A.markAvailable(),q?.log({name:"provider.popup.opened",stage:"overlay_open",...Sr,attempt:at.current})}});(0,s.useEffect)(()=>{Ae&&ce.current?.focus()},[Ae,de]);let We=(0,s.useCallback)(()=>{Pe(z=>z+1)},[]),Ve=(0,s.useCallback)((z,be,Qe)=>{ie(Qe),d?.("paypal",z,{code:be,popupBlocked:ao(z),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:P}),J(!0),We()},[ie,d,P,We]),ot=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ee.current&&(ee.current=!1,ot())},[ot,de]);let Ke=(0,s.useCallback)(()=>{J(!1),a?.(null),ot()},[ot,a]);(0,s.useEffect)(()=>{if(!k||_e.current)return;let[z,be,Qe]=Ls();if(!z||!be)return;let Z=xc(be);if(!Z)return;_e.current=!0;let Le=!0,bt=xa.get(be);bt||(bt=Qe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>k.retrievePaymentIntent(be)),xa.set(be,bt));let Ye={accountPatch:Z.accountPatch,sessionId:Z.sessionId,nonce:Z.nonce},It=()=>{q?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Sr,requestCategory:"provider_sdk"})};return q?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Sr}),(async()=>{try{De(!0);let h=await bt;if(!Le)return;if(h?.error){xa.delete(be),It(),a?.(h.error.message??"Failed to retrieve PayPal payment status.");return}if(qu(),xa.delete(be),Qe==="failed"){let Y="PayPal payment was declined. Please try again.";q?.terminal({outcome:"payment_declined",...Sr,terminalReason:"provider_declined"}),a?.(Y),p?.(yn("paypal",Y));return}let C=h?.paymentIntent;if(C&&C.id!==z){It(),a?.("Failed to match the returned PayPal payment.");return}if(C&&(C.status==="requires_capture"||C.status==="succeeded")){let Y=typeof C.payment_method=="string"?C.payment_method:C.payment_method?.id;o({id:Y??C.id,type:"card",threeDSecureActionResultTokenId:C.id,isPaypal:!0},{...Ye,presentationMode:"redirect"})}else{let Y="PayPal payment was not completed. Please try again.";q?.terminal({outcome:C?.status==="canceled"?"payment_cancelled":"payment_declined",...Sr,terminalReason:C?.status==="canceled"?"cancelled":"provider_declined"}),a?.(Y),p?.(yn("paypal",Y))}}catch(h){if(!Le)return;xa.delete(be),It(),a?.(h instanceof Error?h.message:"Failed to complete PayPal payment.")}finally{Le&&De(!1)}})(),()=>{Le=!1,_e.current=!1}},[k,o,a,p,q]);let it=(0,s.useCallback)(async(z=!1)=>{let be=g?await g("paypal"):{proceed:!0};if(!be.proceed)return he.current.delete(de),!1;let Qe=U("paypal");return he.current.set(de,{generation:Qe,accountPatch:be.accountPatch,sessionId:be.sessionId,nonce:be.nonce}),J(!1),q?.log({name:`provider.${z?"redirect.started":"handoff.requested"}`,stage:z?"redirect":"overlay_open",...Sr,attempt:Qe}),c?.("paypal"),!0},[c,q,g,U,de]),$e=(0,s.useCallback)(async z=>{if(i||oe||!await it()){z.reject();return}z.resolve()},[i,it,oe]),vt=(0,s.useCallback)(async z=>{if(!k||!ge)return;let be=he.current.get(de);if(be&&!te(be.generation)){he.current.delete(de);return}if(!be&&Te()||be&&!we(be.generation))return;be||we();let Qe=be??null;if(he.current.delete(de),!Qe&&g){let $=await g("paypal");if(!$.proceed){z.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Qe={accountPatch:$.accountPatch,sessionId:$.sessionId,nonce:$.nonce}}let Z=Qe?.sessionId??e,Le=Qe?.nonce??t,bt=await Hu({event:z,prepared:Qe,email:n,billingName:b,methodLabel:"PayPal",collect:He});if(!bt){z.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ye=bt.email,It={...Qe?.accountPatch,...zn(bt,!0)};try{if(De(!0),a?.(null),!Z||!(0,y.isValidEmail)(Ye))throw new Error("Missing sessionId or email for PayPal payment");await T?.(bt);let $=k.createPaymentMethod,{error:h,paymentMethod:C}=await $({type:"paypal"});if(h){Ve(h,"stripe_paypal_create_payment_method_failed",be?.generation),z.paymentFailed({reason:"fail"});return}let Y=await _i(r,K,Z,Le??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:C?.id??null,intentKind:"payment"});if(Y.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let W=Y.clientSecret,ve={return_url:Ns()};if(C?.id&&(ve.payment_method=C.id),!Kt(Fa,{clientSecret:W,sessionId:Z,nonce:Le,accountPatch:It})&&P==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:B,paymentIntent:ue}=await k.confirmPayment({clientSecret:W,confirmParams:ve,redirect:"if_required"});if(B){if(Kt(Fa),bo(B)){let Me=B.message??"Your payment was declined.";q?.terminal({outcome:"payment_declined",...Sr,terminalReason:"provider_declined"}),a?.(Me),p?.(yn("paypal",Me,{code:xr(B),declineCode:qo(B)})),await Ti({billingApiUrl:r,sessionId:Z,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:xr(B)??"provider_declined"}})}else Ve(B,"stripe_paypal_confirm_failed",be?.generation);return}Kt(Fa);let D=typeof ue?.payment_method=="string"?ue.payment_method:ue?.payment_method?.id;o({id:D??ue?.id,type:"card",threeDSecureActionResultTokenId:ue?.id,isPaypal:!0},{accountPatch:It,paymentMethodCategory:"paypal",presentationMode:P,sessionId:Z,nonce:Le});return}catch($){Ve($,"stripe_paypal_failed",be?.generation)}finally{De(!1)}},[k,ge,e,t,n,b,He,T,r,K,o,a,p,g,Ve,we,te,Te,q,P,de]),Ot=(0,s.useCallback)(async()=>{if(!(Ze.current||i||oe||!k||!ge)){Ze.current=!0,De(!0);try{if(!await it(!0))return;await vt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Ze.current=!1,De(!1)}}},[ge,vt,i,it,k,oe]),ht=P==="redirect"?(0,u.jsx)("button",{type:"button",disabled:i||oe,onClick:()=>{Ot()},style:{width:"100%",minHeight:Xo,border:"1px solid #d1d5db",borderRadius:S??8,background:"#ffc439",color:"#111827",cursor:i||oe?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,u.jsx)(Zt.ExpressCheckoutElement,{onReady:z=>Se(_a(z,["paypal"])),onLoadError:()=>{Se("load_error"),Us(q,"paypal","paypal","provider_error")},onClick:$e,onConfirm:vt,onCancel:()=>{let z=he.current.get(de);he.current.delete(de),q?.terminal({outcome:"payment_cancelled",...Sr,terminalReason:"cancelled",...z?{attempt:z.generation}:{}}),ie(z?.generation),J(!1),ee.current=!0,We()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:le,emailRequired:le,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},de),_t=(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ae&&(0,u.jsx)("button",{ref:ce,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ke,style:Fs,children:"Try PayPal again"}),Ee&&(0,u.jsx)(zo,{identity:Ee.identity,methodLabel:Ee.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Ee.id),(0,u.jsx)("div",{style:{display:Ee?"none":void 0},children:ht})]}),oe&&!Ee&&(0,u.jsx)(qn,{status:"processing"})]});return P==="redirect"?_t:(0,u.jsx)(Ta,{state:X,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:_t})}function Rc(e){return e==="apple_pay"||e==="google_pay"}function Ic({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:i,onErrorChange:c,onButtonClick:p,onDecline:d,onTechnicalFailure:g,runBeforeButtonClick:b,billingName:T,onBuyerIdentityReady:_,onLoadStateChange:S,placeholderBorderRadius:A,popupCapabilityOwner:I,externalTelemetryContext:P}){let w=Wr(),{emitInstrument:K}=(0,s.useContext)(or),k=(0,Zt.useStripe)(),ge=(0,Zt.useElements)(),q=(0,s.useMemo)(()=>gi(fn(w),P),[P,w]),[X,Se]=(0,s.useState)("loading");(0,s.useEffect)(()=>{S?.(X)},[X,S]);let[oe,De]=(0,s.useState)(!1),Ze=(0,s.useRef)(!(0,y.isValidEmail)(n?.trim())||!T?.trim()).current,{request:le,collect:Ee,finish:He}=Uo(),Re=(0,s.useRef)(null),_e=(0,s.useRef)(null),[Ie,ce]=(0,s.useState)(0),[de,Pe]=(0,s.useState)(!1),[Ae,J]=(0,s.useState)(()=>Ei(e,t)?"blocked":"idle"),[ee,he]=(0,s.useState)("google_pay"),U=(0,s.useRef)(null),we=(0,s.useRef)(!0),ie=(0,s.useRef)(!1),Te=(0,s.useRef)("google_pay"),te=(0,s.useRef)("google_pay"),at=(0,s.useRef)(null),We=(0,s.useRef)(null),Ve=(0,s.useRef)(new Set),ot=(0,s.useRef)(null);(0,s.useEffect)(()=>(we.current=!0,()=>{we.current=!1;for(let $ of Ve.current)window.clearTimeout($);Ve.current.clear()}),[]);let Ke=(0,s.useRef)(new Map),{startAttempt:it,finishAttempt:$e,invalidateAttempt:vt,isAttemptInvalidated:Ot,isAttemptCurrent:ht,generationRef:_t}=Ca(($,h,C)=>{g?.($,h,{...C,popupBlocked:C?.popupBlocked??ao(h),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),he($),Pe(!0),ce(Y=>Y+1)},{onHandoffObserved:$=>{I.markAvailable(),q?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:_t.current,...$==="apple_pay"||$==="google_pay"?{walletType:$}:{}})},defersMissingTerminal:Rc,onMissingTerminalDeferred:($,h)=>{let C=q?.now()??globalThis.performance?.now()??Date.now(),Y=ot.current,W=Y?.generation===h?Y.startedAt:C;q?.performance({stage:"overlay_return",durationMs:Math.max(0,C-W),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:h,...Rc($)?{walletType:$}:{}}),q?.flush?.().catch(()=>{})}});(0,s.useEffect)(()=>{de&&_e.current?.focus()},[de,Ie]);let z=(0,s.useCallback)(()=>{ce($=>$+1)},[]),be=(0,s.useCallback)(($,h,C,Y,W=!1)=>{vt(Y),g?.($,h,{code:C,popupBlocked:ao(h),telemetryReported:W,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),he($),Pe(!0),z()},[vt,g,z]),Qe=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ie.current&&(ie.current=!1,Qe())},[Qe,Ie]);let Z=(0,s.useCallback)(()=>{Pe(!1),c?.(null),Qe()},[Qe,c]),Le=(0,s.useCallback)(()=>{U.current?.()},[]);(0,s.useEffect)(()=>{let $=Ei(e,t);if(!$)return;let h=!1,C=!1,Y=async()=>{if(!C){C=!0,h||J("checking");try{let W=await bc(k,$.clientSecret,Ve.current);if(h)return;let ve=Ms(W,$.providerObjectId,(0,y.isSetupIntentClientSecret)($.clientSecret));if(ve.kind==="confirmed"){if(!hc(e,t,$.clientSecret))return;U.current=null,J("idle"),i({id:ve.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ve.intentId},{...$.accountPatch?{accountPatch:$.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ve.kind==="terminal"){As(e,t,$.clientSecret),U.current=null,J("idle"),he($.paymentMethodType),Pe(!0),z();return}J("blocked")}catch{h||J("blocked")}finally{C=!1}}};return U.current=Y,J("blocked"),()=>{h=!0,U.current===Y&&(U.current=null)}},[t,i,z,e,k]);let bt=(0,s.useCallback)(async $=>{let h=!1,C=dt=>{h||(h=!0,$.paymentFailed({reason:"fail",...dt?{message:dt}:{}}))};if(!k||!ge){C();return}let Y=Ke.current.get(Ie);if(Y&&!ht(Y.generation)){Ke.current.delete(Ie),C();return}if(!Y&&Ot()){C();return}if(Y&&!$e(Y.generation)){C();return}Y||$e();let W=$.expressPaymentType??Y?.method??Te.current,ve=Y??null,F=Sc(W),B;W==="apple_pay"?B="apple_pay":W==="google_pay"&&(B="google_pay");let ue=Y?.generation??_t.current,D=q,Me=D?.now()??globalThis.performance?.now()??Date.now(),st=new AbortController,yt=!1,Ct=!1,Be=null,An=e,$n="processing",hn="other",Vt="provider_runtime",jn,Hn=new Promise((dt,nt)=>{jn=nt}),Cn=window.setTimeout(()=>{yt=!0,st.abort(),jn(Ri)},Bu),Bt=async(dt,nt,Mn)=>{$n=dt,hn=nt,Vt=nt==="intent_create"||nt==="session_claim"?"transport_error":"provider_runtime";let Mt=D?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Mn,Hn])}finally{let Wn=D?.now()??globalThis.performance?.now()??Date.now();D?.performance({stage:dt,durationMs:Math.max(0,Wn-Mt),durationMode:"machine",requestCategory:nt,paymentMethodCategory:"wallet",provider:"stripe",...yt?{statusClass:"timeout"}:{}})}};try{if(De(!0),c?.(null),!ve&&b){let ze=await Bt("processing","other",b(F));if(!ze.proceed){C();return}ve={accountPatch:ze.accountPatch,sessionId:ze.sessionId,nonce:ze.nonce}}let dt=ve?.sessionId??e;An=dt;let nt=ve?.nonce??t,Mn=at.current??ve?.accountPatch,Mt=Fc({event:$,fallbackEmail:Mn?.email??n,fallbackName:[Mn?.firstName,Mn?.lastName].join(" ").trim()||T});if(!(0,y.isValidEmail)(Mt.email)){C("Buyer details are required."),Ee(Bs(W),Mt).then(ze=>{ze&&(at.current=ze)});return}at.current=null;let Wn={...ve?.accountPatch,...zn(Mt,!0)};await Bt("processing","session_claim",Promise.resolve(_?.(Mt)));let{error:bn}=await Bt("tokenization","provider_sdk",ge.submit());if(bn){C(),be(W,bn,"stripe_wallet_submit_failed",Y?.generation);return}if(!dt)throw new Error("Missing sessionId or email for payment.");let $t={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,paymentMethodId:null,intentKind:o},en=JSON.stringify({sessionId:dt,nonce:nt??"",request:$t}),cr=We.current,Qn=cr?.retryIdentity===en?cr.authorizationAttemptId:(0,y.randomUuidV4)();We.current={authorizationAttemptId:Qn,retryIdentity:en};let tn=await Bt("processing","intent_create",_i(r,K,dt,nt??"",{...$t,authorizationAttemptId:Qn},{signal:st.signal}));if(tn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let xt=tn.clientSecret,nn=Lu({createdAt:Date.now(),sessionId:dt,...nt?{nonce:nt}:{},clientSecret:xt,providerObjectId:tn.providerObjectId,paymentMethodType:W,accountPatch:Wn});window.clearTimeout(Cn),Ct=!0,D?.performance({stage:"callback",durationMs:Math.max(0,(D?.now()??globalThis.performance?.now()??Date.now())-Me),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let sn=D?.now()??globalThis.performance?.now()??Date.now(),Lt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...B?{walletType:B}:{},attempt:ue},cn=!1,Ut=null;D?.log({name:"payment.provider_confirmation.started",...Lt}),Be=window.setTimeout(()=>{Be!==null&&Ve.current.delete(Be),cn=!0;let ze=D?.now()??globalThis.performance?.now()??Date.now();D?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Lt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ze-sn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),D?.flush?.().catch(()=>{}),Ut?.()},Du),Ve.current.add(Be);let ln=(ze,mt)=>{Be!==null&&(window.clearTimeout(Be),Ve.current.delete(Be),Be=null);let v=D?.now()??globalThis.performance?.now()??Date.now(),ut=Math.max(0,v-sn),pe=ze;cn&&(ze==="resolved"?pe="resolved_late":ze==="returned_error"?pe="returned_error_late":pe="rejected_late");let Sn=mt??(ze==="resolved"?"approved":"provider_error");return D?.log({name:"payment.provider_confirmation.returned",...Lt,operationOutcome:pe,terminalReason:Sn}),D?.performance({...Lt,durationMs:ut,durationMode:"buyer",operationOutcome:pe,terminalReason:Sn}),{durationMs:ut,operationOutcome:pe,terminalReason:Sn}},Nt=!1,me=!1,dr=ze=>{if(!ze||typeof ze!="object")return null;let mt=ze;if(mt.error)return null;let v=mt.setupIntent??mt.paymentIntent,ut=Ms(v??null,void 0,!!mt.setupIntent);return ut.kind==="confirmed"?ut:null},ur=ze=>{if(Nt||Y&&_t.current!==Y.generation)return;let mt=dr(ze);if(!mt)return;if(nn&&!hc(dt,nt,xt)){Nt=!0;return}let{intentId:v,paymentMethodId:ut}=mt;Nt=!0,me=!0,We.current=null,U.current=null,we.current&&(J("idle"),De(!1));let pe=`${_c}:${dt}`;Kt(pe,{createdAt:Date.now(),sessionId:dt,nonce:nt,accountPatch:Wn,paymentMethodId:ut,providerIntentId:v,paymentMethodType:W});try{i({id:ut,type:"card",threeDSecureActionResultTokenId:v},{accountPatch:Wn,paymentMethodCategory:"wallet",sessionId:dt,nonce:nt})}finally{Kt(pe)}},pr=!1;Ut=async()=>{if(!(pr||Nt||me)){pr=!0,we.current&&J("checking");try{let ze=await bc(k,xt,Ve.current);if(Nt||me)return;let mt=(0,y.isSetupIntentClientSecret)(xt),v=Ms(ze,tn.providerObjectId,mt);if(v.kind==="confirmed"){ur(mt?{setupIntent:ze}:{paymentIntent:ze});return}if(v.kind==="terminal"){if(me=!0,As(dt,nt,xt),We.current=null,U.current=null,!we.current)return;J("idle"),C(),be(W,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Y?.generation,!0);return}we.current&&!me&&(J("blocked"),De(!1))}catch{we.current&&!me&&(J("blocked"),De(!1))}finally{pr=!1}}},U.current=Ut;let rn,xn;try{let ze=await((0,y.isSetupIntentClientSecret)(xt)?k.confirmSetup({elements:ge,clientSecret:xt,redirect:"if_required"}):k.confirmPayment({elements:ge,clientSecret:xt,redirect:"if_required"}));if(!ze||typeof ze!="object"||(rn=ze,!rn.error&&!dr(rn)))throw Ts;xn=ln(rn.error?"returned_error":"resolved",rn.error&&bo(rn.error)?"provider_declined":void 0)}catch(ze){let mt=ze===Ts,v=ln(mt?"returned_error":"rejected");if(D?.error({...mt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:us(ze),...Lt,operationOutcome:v.operationOutcome,durationMs:v.durationMs,statusClass:"unknown",terminalReason:v.terminalReason}),!we.current||Nt)return;await Ut?.();return}let kn=rn.error;if(kn){if(!we.current||Nt)return;if(bo(kn)){me=!0,As(dt,nt,xt),We.current=null,U.current=null,J("idle");let ze=kn.message??"Your payment was declined.";C(ze),c?.(ze),d?.(yn(F,ze,{code:xr(kn),declineCode:qo(kn)})),Ti({billingApiUrl:r,sessionId:dt,nonce:nt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,providerDeclineReason:xr(kn)??"provider_declined",...tn.intentKind==="payment"&&tn.providerObjectId.startsWith("pi_")?{providerIntentId:tn.providerObjectId}:{}}})}else D?.error({...us(kn),...Lt,operationOutcome:xn.operationOutcome,durationMs:xn.durationMs,statusClass:"unknown",terminalReason:xn.terminalReason}),await Ut?.();return}if(ur(rn),!Nt)throw new Error("Invalid provider returned for APM intent")}catch(dt){if(dt===Ri){let nt=D?.now()??globalThis.performance?.now()??Date.now();D?.error({errorCode:Uu(hn),stage:$n,requestCategory:hn,paymentMethodCategory:"wallet",provider:"stripe",...B?{walletType:B}:{},operationOutcome:"watchdog_expired",checkoutSessionId:An,durationMs:Math.max(0,nt-Me),statusClass:"timeout",failureCategory:Vt,attempt:ue,terminalReason:"provider_error"}),D?.flush?.().catch(()=>{})}C(),be(W,dt,dt===Ri?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Y?.generation,dt===Ri)}finally{if(window.clearTimeout(Cn),Be!==null&&(window.clearTimeout(Be),Ve.current.delete(Be)),!Ct){let dt=D?.now()??globalThis.performance?.now()??Date.now();D?.performance({stage:"callback",durationMs:Math.max(0,dt-Me),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...yt?{statusClass:"timeout"}:{}})}we.current&&De(!1)}},[k,ge,e,t,n,T,Ee,_,r,K,o,i,c,d,b,be,$e,ht,Ot,_t,q,Ie]),Ye=(0,s.useMemo)(()=>bi(a),[a]),It=(0,s.useMemo)(()=>a.map(y.stripeExpressMethodToOptionKey),[a]);return(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(Ta,{state:X,placeholderTestId:"flopay-wallet-placeholder",borderRadius:A,children:(0,u.jsxs)("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[de&&(0,u.jsxs)("button",{ref:_e,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Z,style:Fs,children:["Try ",Bs(ee)," again"]}),Ae!=="idle"&&(0,u.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,u.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,u.jsx)("button",{type:"button",onClick:Le,disabled:Ae==="checking",style:Fs,children:Ae==="checking"?"Checking payment status\u2026":"Check payment status"})]}),le&&(0,u.jsx)(zo,{identity:le.identity,methodLabel:le.methodLabel,onComplete:He,onCancel:()=>He(null)},le.id),Ae==="idle"&&(0,u.jsx)("div",{style:{display:le?"none":void 0},children:(0,u.jsx)(Zt.ExpressCheckoutElement,{onReady:$=>{Se(_a($,It))},onLoadError:$=>{Se("load_error"),Us(q,"stripe","wallet","provider_error")},onClick:async $=>{let h=q?.now()??globalThis.performance?.now()??Date.now();Te.current=$.expressPaymentType,te.current=Sc($.expressPaymentType);let C=!0,Y=window.setTimeout(()=>{C=!1,$.reject()},Fu),W=b?await b(te.current):{proceed:!0};if(window.clearTimeout(Y),!C)return;if(!W.proceed){Ke.current.delete(Ie),$.reject();return}let ve=it($.expressPaymentType);ot.current={generation:ve,startedAt:h},Ke.current.set(Ie,{generation:ve,method:$.expressPaymentType,accountPatch:W.accountPatch,sessionId:W.sessionId,nonce:W.nonce}),Pe(!1),q?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ve,...$.expressPaymentType==="apple_pay"||$.expressPaymentType==="google_pay"?{walletType:$.expressPaymentType}:{}}),p?.(te.current),$.resolve()},onConfirm:bt,onCancel:()=>{let $=Ke.current.get(Ie);Ke.current.delete(Ie),q?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...$?{attempt:$.generation}:{}}),vt($?.generation),We.current=null,Pe(!1),ie.current=!0,z()},options:{...Pi,paymentMethods:Ye,emailRequired:Ze,billingAddressRequired:Ze}},Ie)})]})}),oe&&(0,u.jsx)(qn,{status:"processing"})]})}function Bc(e,t,n){let r=(0,y.resolveSetupFutureUsage)(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...r?{setupFutureUsage:r}:null}}function Ds({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:c,onErrorChange:p,onDecline:d,onCancel:g,runBeforeButtonClick:b,onButtonClick:T,isProcessing:_,submitButtonColor:S,submitButtonBorderRadius:A,submitButtonStyle:I,errorText:P}){let w=Wr(),{emitInstrument:K}=(0,s.useContext)(or),k=(0,Zt.useStripe)(),ge=(0,Zt.useElements)(),[q,X]=(0,s.useState)(!1),Se=(0,s.useRef)(!1),[oe,De]=(0,s.useState)(!1),[Ze,le]=(0,s.useState)("loading"),[Ee,He]=(0,s.useState)(""),Re=!(0,y.isValidEmail)(r?.trim()),_e=!Re||(0,y.isValidEmail)(Ee.trim()),Ie=(0,s.useCallback)(async()=>{if(!k||!ge||_||Se.current||!oe)return;Se.current=!0,X(!0);let ce=b?await b("card"):{proceed:!0};if(!ce.proceed){Se.current=!1,X(!1);return}T?.("card");let de=ce.sessionId??t,Pe=ce.nonce??n,Ae=go(o?.trim()),J=zn({email:ce.accountPatch?.email?.trim()||r?.trim()||Ee.trim(),firstName:ce.accountPatch?.firstName?.trim()||Ae.firstName,lastName:ce.accountPatch?.lastName?.trim()||Ae.lastName}),ee=J.email,he=zn({...ce.accountPatch,...J});try{if(p?.(null),!(0,y.isValidEmail)(ee))throw new Error("A valid email address is required for payment.");await a?.(J);let U=await ge.submit();if(U.error){p?.(U.error.message??"Payment failed.");return}let we=[J.firstName,J.lastName].filter(Boolean).join(" "),ie=await k.createPaymentMethod({elements:ge,params:{billing_details:{email:ee,...we?{name:we}:{}}}});if(ie.error||!ie.paymentMethod){p?.(ie.error?.message??"Failed to create payment method.");return}let Te=ie.paymentMethod;if(!de||!ee)throw new Error("Missing sessionId or email for payment.");let te=Te.type||e,at=await _i(i,K,de,Pe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(at.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let We=at.clientSecret;Kt(Br,{clientSecret:We,sessionId:de,nonce:Pe,accountPatch:he,paymentMethodId:Te.id,paymentMethodType:Te.type??e,gateway:"stripe"});let{error:Ve,paymentIntent:ot}=await k.confirmPayment({clientSecret:We,confirmParams:{return_url:window.location.href,payment_method:Te.id},redirect:"if_required"});if(Ve){Kt(Br);let $e=Ve.message??"Payment failed.";p?.($e),d?.(yn("card",$e,{code:Ve.code})),await Ti({billingApiUrl:i,sessionId:de,nonce:Pe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ve.code??"provider_declined"}});return}let Ke=ot?.status;if(!ha(Ke)){Kt(Br);let $e=Ke==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.($e),d?.(yn("card",$e,{code:Ke??"missing_payment_intent"}));return}Kt(Br);let it=typeof ot?.payment_method=="string"?ot.payment_method:ot?.payment_method?.id;c({id:it??Te.id,type:"card",threeDSecureActionResultTokenId:ot?.id,gateway:"stripe",paymentMethodType:Te.type??e},{accountPatch:he,paymentMethodCategory:"apm",sessionId:de,nonce:Pe})}catch(U){p?.(U instanceof Error?U.message:"Payment failed. Please try again.")}finally{Se.current=!1,X(!1)}},[k,ge,_,oe,b,T,t,n,r,o,Ee,a,i,K,e,c,p,d]);return(0,u.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Re&&(0,u.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Re&&(0,u.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,u.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Ee,onChange:ce=>He(ce.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,u.jsx)(Zt.PaymentElement,{onReady:()=>le("ready"),onLoadError:()=>{le("load_error"),Us(fn(w),"stripe","apm")},onChange:ce=>{De(!!ce.complete)},options:{layout:vi,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,y.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,u.jsx)(Ci,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{Ie()},disabled:!oe||!_e||q||_||Ze!=="ready",color:S,borderRadius:A,style:I,children:q?"Processing\u2026":`Pay with ${(0,y.getStripeMethodDisplayName)(e)}`}),P&&(0,u.jsx)($o,{margin:"0.75rem 0 0",children:P})]})}function Ec({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:i,stripeInstance:c,paymentElementBaseOptions:p,futureUseSession:d,onTokenizedBody:g,onErrorChange:b,onButtonClick:T,onDecline:_,runBeforeButtonClick:S,onLoadStateChange:A,isProcessing:I=!1,submitButtonColor:P="#4A49FF",submitButtonBorderRadius:w=8,submitButtonStyle:K,buttonAppearance:k,themeId:ge,onExpandApm:q,expandedApmMethod:X}){let{emitInstrument:Se}=(0,s.useContext)(or),[oe,De]=(0,s.useState)(null),[Ze,le]=(0,s.useState)(null),Ee=(0,s.useRef)(!1),{request:He,collect:Re,finish:_e}=Uo();(0,s.useEffect)(()=>{i.length>0&&c?A?.("ready"):c||A?.("loading")},[i.length,c,A]);let Ie=(0,s.useCallback)(async ee=>{if(!c||Ee.current||I)return;Ee.current=!0,le(ee);let he=S?await S("card"):{proceed:!0};if(!he.proceed){Ee.current=!1,le(null);return}T?.("card");let U=he.sessionId??e,we=he.nonce??t,ie=go([he.accountPatch?.firstName,he.accountPatch?.lastName].filter(Boolean).join(" ")||r),Te=zn({email:he.accountPatch?.email?.trim()||n?.trim(),firstName:he.accountPatch?.firstName?.trim()||ie.firstName,lastName:he.accountPatch?.lastName?.trim()||ie.lastName});if(!(0,y.isValidEmail)(Te.email)){le(null);let We=await Re((0,y.getStripeMethodDisplayName)(ee),Te);if(!We){Ee.current=!1;return}Te=We,le(ee)}let te=Te.email,at=zn({...he.accountPatch,...Te});try{if(b?.(null),!U||!(0,y.isValidEmail)(te))throw new Error("Missing sessionId or email for payment.");await o?.(Te);let We=await _i(a,Se,U,we??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,paymentMethodId:null,intentKind:"payment"});if(We.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ve=We.clientSecret;Kt(Br,{clientSecret:Ve,sessionId:U,nonce:we,accountPatch:at,paymentMethodType:ee,gateway:"stripe"});let{error:ot,paymentIntent:Ke}=await c.confirmPayment({clientSecret:Ve,confirmParams:{return_url:window.location.href,payment_method_data:{type:ee,billing_details:{name:[Te.firstName,Te.lastName].filter(Boolean).join(" "),...te?{email:te}:{}}}},redirect:"if_required"});if(ot){Kt(Br);let vt=ot.message??"Payment failed.";b?.(vt),_?.(yn("card",vt,{code:ot.code})),await Ti({billingApiUrl:a,sessionId:U,nonce:we,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,providerDeclineReason:ot.code??"provider_declined"}});return}let it=Ke?.status;if(!ha(it)){Kt(Br);let vt=it==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(vt),_?.(yn("card",vt,{code:it??"missing_payment_intent"}));return}Kt(Br);let $e=typeof Ke?.payment_method=="string"?Ke.payment_method:Ke?.payment_method?.id;g({id:$e??Ke?.id,type:"card",threeDSecureActionResultTokenId:Ke?.id,gateway:"stripe",paymentMethodType:ee},{accountPatch:at,paymentMethodCategory:"apm",sessionId:U,nonce:we})}catch(We){b?.(We instanceof Error?We.message:"Payment failed. Please try again.")}finally{Ee.current=!1,le(null)}},[c,I,S,T,e,t,n,Re,a,Se,r,o,g,b,_]),[ce,de]=(0,s.useState)(null),Pe=q?X??null:ce,Ae=(0,s.useCallback)(ee=>{Ee.current||I||Pe&&Pe!==ee||((0,y.needsStripeMethodExplicitConfirm)(ee)?q?q(ee):de(ee):Ie(ee))},[Pe,I,Ie,q]),J=(0,s.useMemo)(()=>ce?Bc(p,ce,d):null,[ce,p,d]);return(0,u.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:He?(0,u.jsx)(zo,{identity:He.identity,methodLabel:He.methodLabel,onComplete:_e,onCancel:()=>_e(null)},He.id):i.map(ee=>{let he=X===ee,U=Ze===ee,we=Ze!==null&&Ze!==ee||X!=null&&X!==ee;return(0,u.jsxs)(s.default.Fragment,{children:[(0,u.jsx)(hi,{method:ee,themeId:ge,submitting:U,disabled:we,highlighted:he,hasNextStep:(0,y.needsStripeMethodExplicitConfirm)(ee),onClick:()=>Ae(ee),backgroundColor:k?.backgroundColor,borderColor:k?.borderColor,textColor:k?.textColor,borderRadius:k?.borderRadius,fontFamily:k?.fontFamily}),!q&&ce===ee&&J&&c&&(0,u.jsx)(Zt.Elements,{stripe:c,options:J,children:(0,u.jsx)(Ds,{method:ee,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:g,onErrorChange:b,onDecline:_,onCancel:()=>de(null),runBeforeButtonClick:S,onButtonClick:T,isProcessing:I,submitButtonColor:P,submitButtonBorderRadius:w,submitButtonStyle:K})},ee)]},ee)})})}function np({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:i,onError:c,onDecline:p,onTokenizedBody:d,firstName:g,lastName:b,chv:T,className:_,submitLabel:S,isProcessing:A,error:I,onErrorChange:P,showPayPal:w=!0,showStripe:K=!0,walletPresentation:k="auto",enabledPaymentMethods:ge,enabledPaymentMethodCountries:q,showApplePay:X=!0,showGooglePay:Se=!0,layout:oe="default",theme:De,buttonsTheme:Ze,buttonsStyles:le,appearance:Ee,cardButtonContent:He,cardBackButtonContent:Re,cardTitleContent:_e,showSecurityFooter:Ie,onButtonClick:ce,onBeforeButtonClick:de,onBuyerIdentityReady:Pe,enableAVS:Ae,cardFieldOrder:J,cardPreFormSlot:ee,avsLayout:he="row",country:U,zip:we,addressLine1:ie,addressLine2:Te,city:te,state:at,onCountryChange:We,onZipChange:Ve,avsCheck:ot,checkoutType:Ke,checkoutLayout:it,totalAmount:$e=0,currency:vt="usd",initialCardOpen:Ot=!1,directPaypal:ht,isSubscription:_t=!1,session:z,dataAttachmentPending:be=!1,dataAttachmentRequiresIdentity:Qe=!1,debug:Z=!1}){let Le=Wr(),bt=Qa(),Ye=(0,s.useContext)(vr),{emitInstrument:It}=(0,s.useContext)(or),$=(0,s.useRef)(null);$.current||($.current=ri());let h=$.current,[,C]=(0,s.useState)(0),Y=(0,s.useRef)(null);Y.current||(Y.current=Kr());let W=Y.current,ve=(0,s.useMemo)(()=>({browser:W,capability:h,presentationMode:"popup"}),[W,h]),F=z??Ye.session,B=(0,s.useMemo)(()=>({futureUse:F?.futureUse,futureUseUnsupported:F?.futureUseUnsupported}),[F?.futureUse,F?.futureUseUnsupported]),ue=F?.gateways?.paypal?.providerObjectType??ht?.providerObjectType,D=be||Ye.claimPending===!0,Me=Qe||Ye.claimRequiresIdentity===!0,st=D&&!Me,yt=Wl(),Ct=n||yt,[Be,An]=(0,s.useState)(!1),[$n,hn]=(0,s.useState)(null),[Vt,jn]=(0,s.useState)(U??""),[Hn,Cn]=(0,s.useState)(we??""),[Bt,dt]=(0,s.useState)(ie??""),[nt,Mn]=(0,s.useState)(Te??""),[Mt,Wn]=(0,s.useState)(te??""),[bn,$t]=(0,s.useState)(at??""),[en,cr]=(0,s.useState)(""),[Qn,tn]=(0,s.useState)({}),xt=(0,s.useRef)(we??""),nn=(0,s.useRef)(U??""),sn=(0,s.useRef)(ie??""),Lt=(0,s.useRef)(Te??""),cn=(0,s.useRef)(te??""),Ut=(0,s.useRef)(at??""),ln=(0,s.useRef)(""),Nt=(0,s.useRef)({});(0,s.useEffect)(()=>{let l=(E,ae,je,fe,Ne)=>{if(Nt.current[E])return;let Jt=ae?.trim();!Jt||Jt===je.current||(je.current=Jt,fe(Jt),Ne?.(Jt))};l("country",U,nn,jn,We),l("zip",we,xt,Cn,Ve),l("addressLine1",ie,sn,dt),l("addressLine2",Te,Lt,Mn),l("city",te,cn,Wn),l("state",at,Ut,$t)},[U,we,ie,Te,te,at,We,Ve]);let me=(0,s.useMemo)(()=>(0,y.resolveAVSConfig)(Ae),[Ae]),dr=me!==null,ur=(0,s.useMemo)(()=>(0,y.isAuthorizationOnlySession)(z),[z]),pr=!!z?.vault?.html,rn=!!z?.gateways?.pcivault,xn=ls(z),ze=!!(z?.gateways?.stripe?.enabledPaymentMethods??ge)?.includes("card")||Qr(z),mt=pr||ze||rn,v=!!(K&&mt&&e),[ut,pe]=(0,s.useState)(()=>oe!=="buttons"||Ot?e??null:null),[Sn,Kn]=(0,s.useState)(0),Gt=oe!=="buttons"||Ot||!!e&&ut===e,Fn=z?.captureMethod,ft=(0,s.useRef)(Le);(0,s.useEffect)(()=>{ft.current=Le},[Le]);let[mr,uo]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!v||!e||!Gt){uo(null);return}let l=ft.current?ft.current.cardCapture({sessionId:e,captureMethod:Fn}):new wr.PciVaultCardCapture({sessionId:e,captureMethod:Fn,billingApiUrl:Ct,telemetry:r});return uo({sessionId:e,captureMethod:Fn,billingApiUrl:Ct,telemetry:r,capture:l}),()=>{l.unmount()}},[v,e,Gt,Fn,Ct,r]);let Ft=v&&e&&Gt&&mr?.sessionId===e&&mr.captureMethod===Fn&&mr.billingApiUrl===Ct&&mr.telemetry===r?mr.capture:null,Bn=(0,s.useMemo)(()=>{let l=Vt,E=me?(0,y.isAVSFieldVisible)(me.postal_code,l):!1;return Qu(l,Hn,E)},[me,Vt,Hn]),{avsInvalid:kr,invalidAvsFields:er}=(0,s.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!v||!me)return{avsInvalid:!1,invalidAvsFields:l};let E=Vt,ae=(Ne,Jt)=>(0,y.isAVSFieldVisible)(Ne,E)&&!Jt.trim(),je={line1:ae(me.address_line_1,Bt),city:ae(me.city,Mt),state:ae(me.state,bn),zip:Bn.empty||Bn.malformed};return{avsInvalid:je.line1||je.city||je.state||je.zip,invalidAvsFields:je}},[v,me,Vt,Bt,Mt,bn,Bn]),[Yt,yr]=(0,s.useState)(!1),[Dn,Lr]=(0,s.useState)(!1),[On,Rr]=(0,s.useState)(!1),[Ir,Nr]=(0,s.useState)({line1:!1,city:!1,state:!1}),Gn=(0,s.useRef)(!1),tr=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Ur=(0,s.useRef)(!1),Dt=(0,s.useCallback)(l=>{tr.current[l]=!0,Ur.current=!0},[]),Rn=(0,s.useCallback)(l=>!Gn.current&&tr.current[l],[]),nr=(0,s.useCallback)(l=>{Rn(l)&&Nr(E=>E[l]?E:{...E,[l]:!0})},[Rn]),[zr,qr]=(0,s.useState)(()=>xs(z?.vault)),[lt,dn]=(0,s.useState)(Ot&&mt?"card":"buttons"),[un,In]=(0,s.useState)(null),po=lt==="expanding"||lt==="card",Er=z?.gateways?.stripe&&!xn?"stripe":void 0,Zr=(0,s.useCallback)(()=>{It?.({class:"card_surface",provider:Er})},[Er,It]),En=(0,s.useRef)(null),pn=(0,s.useCallback)(l=>{En.current&&clearTimeout(En.current),En.current=setTimeout(()=>{En.current=null,l()},Ba)},[]);(0,s.useEffect)(()=>()=>{En.current&&clearTimeout(En.current)},[]);let Vr=(0,s.useCallback)(()=>{Zr(),pe(e??null),Kn(l=>l+1),dn("expanding"),pn(()=>dn("card"))},[pn,Zr,e]),Ln=(0,s.useCallback)(()=>{dn("collapsing"),pn(()=>dn("buttons"))},[pn]),L=(0,s.useCallback)(l=>{In(l),dn("apm-expanding"),pn(()=>dn("apm-form"))},[pn]),V=(0,s.useCallback)(()=>{dn("apm-collapsing"),pn(()=>{dn("buttons"),In(null)})},[pn]);(0,s.useEffect)(()=>{oe==="buttons"&&Ot&&mt&&(pe(e??null),dn("card"))},[oe,Ot,mt,e]);let[re,j]=(0,s.useState)(null),gt=(0,s.useRef)(!1),Et=(0,s.useRef)(null),se=(0,s.useRef)("idle"),[Xe,Q]=(0,s.useState)(!1),f=(0,s.useRef)(Xe);f.current=Xe;let[m,N]=(0,s.useState)(()=>ht?.existingOrderId?{orderId:ht.existingOrderId,attempts:1}:null),H=(0,s.useRef)(m);(0,s.useEffect)(()=>{H.current=m},[m]);let Ce=(0,s.useRef)(null),xe=(0,s.useMemo)(()=>{if(Pe||Ye.claimBuyerIdentity||z?.buyerIdentified!==!1||!e||!t)return;let l=`${Ct}|${e}|${t}`;Ce.current?.key!==l&&(Ce.current={key:l,claim:Lo(new wr.PaymentAPI(Ct,{telemetry:!1}),e,t,{...a?{userId:a}:{},...g?{firstName:g}:{},...b?{lastName:b}:{}})});let E=Ce.current.claim;return async ae=>{await E(ae)}},[Pe,Ye.claimBuyerIdentity,z?.buyerIdentified,e,t,Ct,a,g,b]),et=Pe??Ye.claimBuyerIdentity??xe,Pt=I??$n,Oe=(0,s.useMemo)(()=>(0,y.resolveTheme)(De),[De]),x=(0,s.useMemo)(()=>{let l=Oe?.buttonsLayout??(0,y.resolveButtonsLayoutTheme)(Ze);return le?{...l,...le,cardButton:{...l.cardButton,...le.cardButton},cardFormContainer:{...l.cardFormContainer,...le.cardFormContainer},backButton:{...l.backButton,...le.backButton},backButtonIcon:{...l.backButtonIcon,...le.backButtonIcon},submitButton:{...l.submitButton,...le.submitButton},title:{...l.title,...le.title}}:l},[Oe,Ze,le]),St=Ee??Oe?.appearance,Fe=(0,s.useMemo)(()=>Qo({appearance:St,buttonsStyles:x,layout:oe}),[St,x,oe]),ke=Ye.inlineSessionPatchProcessing??!1,G=(A??Be)||ke,ye=Ct.replace(/\/+$/,""),ne=(0,s.useMemo)(()=>ds({userId:a,email:o,firstName:g,lastName:b,country:U,zip:we},Qn),[a,o,g,b,U,we,Qn]),wt=[ne.firstName,ne.lastName].filter(l=>!!l?.trim()).join(" "),Ge=!(0,y.isValidEmail)(ne.email?.trim()),fr=(0,s.useRef)(null);v&&fr.current===null&&(fr.current=Ge);let _n=v&&(fr.current??Ge),qi=(0,s.useMemo)(()=>ep(en,_n),[en,_n]),ko=qi.empty||qi.malformed,Yn=(0,s.useMemo)(()=>Le?Le.getRawProvider():null,[Le]),Xs=(0,s.useMemo)(()=>bt?bt.getRawProvider():null,[bt]),ra=$e||100,Ro=vt.toLowerCase(),Vi=(0,s.useMemo)(()=>St?(0,wr.toStripeAppearance)(St):null,[St]),Io=Vi,Js=(0,s.useMemo)(()=>{let l=Vi??{},E=l.rules??{};return{...l,rules:{...E,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...E[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...E[".AccordionItemContents"]??{}}}}},[Vi]),Zs=(0,s.useMemo)(()=>({...ql($e,z?.captureMethod,B),currency:Ro,...Io?{appearance:Io}:null}),[$e,Ro,z?.captureMethod,B,Io]),$i=(0,y.resolveSetupFutureUsage)(B,"paypal","paypal"),Qs=(0,s.useMemo)(()=>({mode:"payment",amount:ra,currency:Ro,captureMethod:"manual",...$i?{setupFutureUsage:$i}:null,...Io?{appearance:Io}:null}),[ra,Ro,$i,Io]),qe=(0,s.useCallback)(l=>{hn(l),P?.(l)},[P]),ji=(0,s.useRef)(""),[el,ud]=(0,s.useState)(!1),Hi=(0,s.useCallback)(()=>{ud(!0)},[]);(0,s.useEffect)(()=>{if(!v||!_n||!et||!el||ko||ji.current)return;let l=zn({email:(0,y.isValidEmail)(ne.email?.trim())?ne.email?.trim():ln.current.trim(),firstName:ne.firstName?.trim(),lastName:ne.lastName?.trim()});ji.current=JSON.stringify(l),tn(E=>({...E,...l})),Promise.resolve(et(l)).catch(E=>{ji.current="",qe(E instanceof Error?E.message:"Failed to attach buyer details.")})},[v,_n,et,el,ko,ne.email,ne.firstName,ne.lastName,qe]),(0,s.useEffect)(()=>{!v||!Ft||Ft.setCardFieldOrder?.(J??null,me==null&&!_n)},[v,Ft,J,me,_n]),(0,s.useEffect)(()=>{(lt==="expanding"||lt==="collapsing"||lt==="apm-expanding"||lt==="apm-collapsing")&&qe(null)},[lt,qe]);let _r=(0,s.useCallback)((l,E,ae)=>{p?.(yn(l,E,ae))},[p]),Eo=(0,s.useCallback)((l,E,ae)=>{let je=ae?.popupBlocked??ao(E);je&&h.markBlocked()&&C(pt=>pt+1);let fe=ro(Bs(l),je,W.inAppBrowser),Ne=xr(E),Jt=(Ne?.toLowerCase()==="error"?void 0:Ne)??ho(ae?.code)??"external_payment_method_failed",br=new y.FloPayError(fe,"api_error",{code:"external_payment_method_failed",param:l,details:{providerCode:Jt,popupBlocked:je,inAppBrowser:W.inAppBrowser,appFamily:W.appFamily,popupCapability:h.current(),presentationMode:ae?.presentationMode??"popup"}});ae?.telemetryReported||fn(Le)?.error(Yo({...ve,presentationMode:ae?.presentationMode??"popup"},{errorCode:je?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:ae?.provider??(l==="paypal"?"paypal":"stripe"),paymentMethodCategory:ae?.paymentMethodCategory??(l==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:ae?.terminalReason??(je?"popup_blocked":"provider_error")})),j(null),oe==="buttons"&&(dn("buttons"),In(null)),qe(fe),c?.(br),console.error("[FloPay] External payment method failed:",{method:l,code:Jt,popupBlocked:je})},[W,ve,Le,oe,c,h,qe]);(0,s.useEffect)(()=>{if(!v||!e){qr(null);return}let l=xs(z?.vault);if(l){qr(l);return}if(!Gt){qr(null);return}qr(null);let E=!0;return new wr.PaymentAPI(ye).getVaultCapture(e,t).then(ae=>{if(!E)return;let je=xs(ae);je?qr(je):qe("Failed to load the secure card form.")}).catch(ae=>{E&&qe(ae instanceof Error?ae.message:"Failed to load the secure card form.")}),()=>{E=!1}},[v,Gt,Sn,e,z?.vault,ye,t,qe]);let gr=(0,s.useRef)({onComplete:i,onError:c,updateError:qe,emitDecline:_r,resolvedAccount:ne,avsConfig:me,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:ye,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:xn});gr.current={onComplete:i,onError:c,updateError:qe,emitDecline:_r,resolvedAccount:ne,avsConfig:me,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:ye,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:xn};let Wi=(0,s.useRef)(!1),tl=(0,s.useCallback)(()=>{let l=gr.current,E=l.resolvedAccount.email?.trim(),ae=(0,y.isValidEmail)(E)?E:ln.current.trim();if(!(0,y.isValidEmail)(ae))return null;let je=l.resolvedAccount.firstName?.trim(),fe=l.resolvedAccount.lastName?.trim(),Ne=nn.current.trim()||l.resolvedAccount.country?.trim()||"",Jt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.state,Ne):!1,br=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_1,Ne):!1,pt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.postal_code,Ne):!1,kt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.city,Ne):!1,Tt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_2,Ne):!1,Ht=br&&!Jt&&pt?(0,y.getStateFromPostalCode)(Ne,(xt.current??"").trim()):null,mn=Jt?Ut.current:Ht;return{accountData:{userId:l.resolvedAccount.userId??"",email:ae,...je?{firstName:je}:{},...fe?{lastName:fe}:{},...pt&&xt.current?{zip:xt.current}:{},...kt&&cn.current?{city:cn.current}:{},...mn?{state:mn}:{},...br&&sn.current?{addressLine1:sn.current}:{},...Tt&&Lt.current?{addressLine2:Lt.current}:{},...Ne?{country:Ne}:{}},...l.avsCheckProp===void 0?{}:{avsCheck:l.avsCheckProp},...l.avsConfig?{avsConfig:{country:(0,y.isAVSFieldVisible)(l.avsConfig.country,Ne),postal_code:pt,address_line_1:br,address_line_2:Tt,city:kt,state:Jt}}:{}}},[]),nl=(0,s.useRef)(D);nl.current=D,(0,s.useEffect)(()=>{D||Pt!==Pc||gr.current.updateError(null)},[D,Pt]),(0,s.useEffect)(()=>{!v||!Ft||Ft.setSubmitGate?.(kr||D||ko||Xe)},[v,Ft,kr,D,ko,Xe]),(0,s.useEffect)(()=>{if(!v||!Ft)return;Wi.current=!1;let l=null,E=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null,se.current="idle",j(null)},400)},ae=Ft.on("submitting",()=>{yr(!0),Et.current&&clearTimeout(Et.current),se.current="validation-window",Et.current=setTimeout(()=>{Et.current=null,se.current==="validation-window"&&(se.current="processing")},Vu),j("processing");let pt=gr.current;if(!pt.sessionId||!pt.nonce)return;let kt=tl();if(!kt){pt.updateError("Enter a valid email address."),se.current="idle",j(null);return}new wr.PaymentAPI(pt.baseUrl).patchAccountSnapshot(pt.sessionId,pt.nonce,kt,{telemetryMode:"best_effort"}).catch(Tt=>{if(!ju(Tt))return;let Ht=Tt instanceof Error?Tt.message:"Please check your billing address and try again.";pt.updateError(Ht),se.current="idle",j(null),pt.onError?.(Tt instanceof y.FloPayError?Tt:new y.FloPayError(Ht,"api_error"))})}),je=Ft.on("complete",async pt=>{if(Wo(pt.sessionId??gr.current.sessionId),se.current="terminal",Q(!1),j("success"),await new Promise(mn=>setTimeout(mn,600)),Wi.current)return;Wi.current=!0;let kt=gr.current,Tt=(0,y.isAuthorizationOnlySession)(kt)||pt.outcome==="authorized",Ht=kt.serverSideCardGateway?{}:{paymentIntentId:pt.intentId};gr.current.onComplete?.(Tt?{status:"authorized",...Ht,paymentId:pt.paymentId??kt.paymentId,sessionId:pt.sessionId??kt.sessionId,authorizationExpiresAt:pt.authorizationExpiresAt??kt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Ht,checkoutMethod:"card"})}),fe=Ft.on("decline",pt=>{let kt=gr.current,Tt=pt.message??"Your payment was declined. Please try another card or contact your bank.";se.current="terminal",Q(!1),kt.updateError(Tt),j("error");let Ht=pt.failureOutcome??(0,y.normalizeCheckoutFailureOutcome)(pt.declineReason)??"authorization_declined";kt.emitDecline("card",Tt,{code:Ht,declineCode:Ht}),E()}),Ne=Ft.on("error",pt=>{let kt=gr.current,Tt=pt.message??"There was a problem processing your payment. Please try again.";se.current="terminal",Q(!1),kt.updateError(Tt),j("error"),kt.onError?.(new y.FloPayError(Tt,"api_error",{code:pt.failureOutcome??"capture_failed"})),E()}),Jt=Ft.on("challenge_dismissed",()=>{Et.current&&(clearTimeout(Et.current),Et.current=null),se.current="processing",Q(!0),j(null)}),br=Ft.on("blocked",()=>{if(f.current){gr.current.updateError($u);return}if(!nl.current){yr(!0);return}Hi(),gr.current.updateError(Pc)});return()=>{l&&(clearTimeout(l),l=null),Et.current&&(clearTimeout(Et.current),Et.current=null),se.current="idle",Q(!1),j(null),ae(),je(),fe(),Ne(),Jt(),br()}},[v,Ft,Hi,tl]);let Tr=!!ht?.clientId,oa=Array.isArray(ge),Ua=oa&&ge.length>0,rl=oa&&ge.includes("paypal"),za=(0,s.useRef)(null);za.current===null&&(za.current=zu());let _o=za.current?"redirect":ei(W,k,h.current()),{expressMethods:qa,paymentElementMethods:aa}=(0,s.useMemo)(()=>(0,y.partitionStripeMethods)(ge,{excludePaypal:Tr}),[ge,Tr]),ol=Tr||!!bt||rl&&_o==="redirect",pd=(0,s.useMemo)(()=>ol?qa.filter(l=>l!=="paypal"):qa,[qa,ol]),md=(0,s.useMemo)(()=>{let l=[];return X&&l.push("apple_pay"),Se&&l.push("google_pay"),l},[X,Se]),To=oa?pd:md,yd=K&&To.length>0,Ki=dr?Vt:U,Va=(0,s.useMemo)(()=>{let l=Ki?.trim().toUpperCase();return l?q?aa.filter(E=>{let ae=q[E];return!ae||ae.length===0||ae.includes(l)}):(0,y.filterStripeMethodsByCountry)(aa,Ki):aa},[aa,Ki,q]),Gi=(0,s.useMemo)(()=>({mode:"payment",amount:ra,currency:Ro,paymentMethodCreation:"manual",appearance:Js}),[ra,Ro,Js]),[al,il]=(0,s.useState)("loading"),[sl,ll]=(0,s.useState)("loading"),[cl,dl]=(0,s.useState)("loading"),[fd,Yi]=(0,s.useState)(!1),[ul,Xi]=(0,s.useState)("loading"),[Ji,gd]=(0,s.useState)();(0,s.useEffect)(()=>{gd(Kr())},[]);let $a=Ji?.inAppBrowser,ja=Ji?ti(Ji,ht?.approvalPresentation,ue??(_t?"subscription":"order")):"popup",pl=w&&(Tr||(oa?rl:$a===!1)),ml=K&&yd,ia=(!st||!!Ye.waitForDataAttachment)&&pl&&Tr,yl=ul==="retrying"||ul==="exhausted",sa=null;K&&(bt?sa=Xs:_o==="redirect"&&(sa=Yn));let fl=(0,s.useMemo)(()=>({...ve,presentationMode:_o}),[ve,_o]),la=!st&&pl&&!!sa&&(!Tr||yl),Ao=!st&&ml&&!!Yn,ca=!st&&K&&Ua&&Va.length>0&&!!Yn,hd=ia&&!yl?fd:la&&Is(al),bd=Ao&&Is(sl),Pd=ca&&cl!=="load_error",gl=l=>l==="loading"||l==="ready",hl=ia||la&&gl(al)||Ao&&gl(sl)||ca&&cl!=="load_error",Ha=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Ha.current){if(!K&&!w){Ha.current=!0;let l=new y.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(l),qe(l.message)}else if(!K&&w&&!Tr){Ha.current=!0;let l=new y.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(l),qe(l.message)}else if($a!==void 0&&!st&&!mt&&!hl){Ha.current=!0;let l=new y.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?.(l),qe(l.message)}}},[K,w,Tr,$a,st,mt,hl,c,qe]);let bl=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(bl.current||!Ua)return;let l=[];X!==!0&&l.push("showApplePay"),Se!==!0&&l.push("showGooglePay"),l.length!==0&&(bl.current=!0,console.warn(`[FloPay] ${l.join(" / ")} ${l.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.`))},[Ua,X,Se]);let Pl=(0,s.useCallback)((l,E)=>Ye.applyInlineSessionPatch?Ye.applyInlineSessionPatch(l).then(ae=>({error:null,sessionId:ae.sessionId||e,nonce:ae.session?.clientSecret||t})).catch(ae=>{let je=wc(E,ae);return qe(je.message),c?.(je),{error:je,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ye.applyInlineSessionPatch,t,c,e,qe]),hr=(0,s.useCallback)(async l=>{if(l!=="card"&&st&&await Ye.waitForDataAttachment?.(),!de)return{proceed:!0};try{let E=await de({method:l,sessionId:e||void 0,createSession:Ye.inlineSessionDraft});if(E===!1)return{proceed:!1};if(E&&typeof E=="object"){E.account&&tn(je=>({...je??{},...E.account}));let ae=await Pl(E,l);return ae.error?{proceed:!1,accountPatch:E.account}:{proceed:!0,accountPatch:E.account,sessionId:ae.sessionId,nonce:ae.nonce}}return{proceed:!0}}catch(E){let ae=wc(l,E);return qe(ae.message),c?.(ae),{proceed:!1}}},[Pl,Ye.inlineSessionDraft,Ye.waitForDataAttachment,st,de,c,e,qe]),vl=(0,s.useCallback)(async(l,E)=>{if(gt.current)return;gt.current=!0,An(!0),j("processing"),qe(null);let ae=E?.sessionId??e,je=E?.nonce??t,fe=ds(ne,E?.accountPatch),Ne=E?.completionPaymentMethodId??ba(l),Jt=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,br=Gu(l),pt=E?.presentationMode?gi(fn(Le),{...ve,presentationMode:E.presentationMode}):void 0,kt=()=>{It?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:br}),pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Sr,requestCategory:"process_payment"})};try{let Ht=await new wr.PaymentAPI(ye).processPayment(fe.userId??"",{sessionId:ae,nonce:je,paymentMethodCategory:E?.paymentMethodCategory??Xu(l),tokenizedData:Jt,accountData:{...E?.accountPatch,userId:fe.userId??"",email:fe.email??"",firstName:fe.firstName||void 0,lastName:fe.lastName||void 0,...me?(()=>{let zt=nn.current,Ar=(0,y.isAVSFieldVisible)(me.state,zt),Xn=(0,y.isAVSFieldVisible)(me.address_line_1,zt),Mr=(0,y.isAVSFieldVisible)(me.postal_code,zt),fo=Xn&&!Ar&&Mr?(0,y.getStateFromPostalCode)(zt,(xt.current??"").trim()):null,fa=Ar?Ut.current:fo;return{country:zt,...Mr&&xt.current?{zip:xt.current}:{},...(0,y.isAVSFieldVisible)(me.city,zt)&&cn.current?{city:cn.current}:{},...fa?{state:fa}:{},...Xn&&sn.current?{addressLine1:sn.current}:{},...(0,y.isAVSFieldVisible)(me.address_line_2,zt)&&Lt.current?{addressLine2:Lt.current}:{}}})():{}},chv:T,avsCheck:ot??!1,checkoutType:Ke,checkoutLayout:it,avsConfig:me?{country:(0,y.isAVSFieldVisible)(me.country,nn.current),postal_code:(0,y.isAVSFieldVisible)(me.postal_code,nn.current),address_line_1:(0,y.isAVSFieldVisible)(me.address_line_1,nn.current),address_line_2:(0,y.isAVSFieldVisible)(me.address_line_2,nn.current),city:(0,y.isAVSFieldVisible)(me.city,nn.current),state:(0,y.isAVSFieldVisible)(me.state,nn.current)}:void 0});if(Ht.ok){let zt=Ht.status===204?null:await Ht.json().catch(()=>null),Ar=(0,y.isAuthorizationOnlySession)(z)||zt?.status==="authorized";Wo(ae),pt?.terminal({outcome:"payment_succeeded",...Sr}),j("success"),N(null),await new Promise(fo=>setTimeout(fo,600));let Xn;typeof zt?.paymentId=="string"?Xn=zt.paymentId:z?.paymentId&&(Xn=z.paymentId);let Mr;typeof zt?.authorizationExpiresAt=="string"?Mr=zt.authorizationExpiresAt:z?.authorizationExpiresAt&&(Mr=z.authorizationExpiresAt),i?.(Ar?{status:"authorized",...Xn===void 0?{}:{paymentId:Xn},sessionId:typeof zt?.sessionId=="string"?zt.sessionId:ae,...Mr===void 0?{}:{authorizationExpiresAt:Mr},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Ne,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Ne,checkoutMethod:l.isPaypal?"paypal":"card"});return}let mn=await Ht.json().catch(()=>null);if(mn?.type==="paypal_redirect_required"){let zt=mn.threeDSecureToken,Ar=mn.paymentMethodId||l.id||"";if(!Le||!zt){j("error"),qe("PayPal authorization required but no token provided.");return}try{let Xn=bt?.getRawProvider();if(!Xn){qe("PayPal is not available.");return}let Mr={return_url:window.location.href};Ar&&(Mr.payment_method=Ar);let{error:fo}=await Xn.confirmPayment({clientSecret:zt,confirmParams:Mr,redirect:"if_required"});if(fo){j("error");let fa=fo.message??"PayPal payment failed.";qe(fa),_r("paypal",fa,{code:fo.code})}}catch(Xn){j("error"),qe(Xn instanceof Error?Xn.message:"PayPal authorization failed.")}return}if(mn?.type==="paypal_direct_required"){let zt=mn.orderId;if(!zt){j("error"),qe("PayPal retry required but no order id provided.");return}let Ar=H.current?.attempts??0;if(Ar>=2){j("error"),qe("PayPal payment could not be completed after multiple attempts."),_r("paypal","paypal_direct_required retry limit exceeded");return}Yi(!1),Xi("loading"),N({orderId:zt,attempts:Ar+1}),j(null);return}(0,y.classifyPaymentRejection)(Ht.status,mn)?pt?.terminal({outcome:"payment_declined",...Sr,terminalReason:"provider_declined"}):kt(),j("error");let Pr=mn?.message??"Payment failed. Please try again.";qe(Pr),_r(l.isPaypal?"paypal":"card",Pr,{code:mn?.code??mn?.gatewayErrorCode,declineCode:mn?.declineCode??mn?.gatewayDeclineReason}),await new Promise(zt=>setTimeout(zt,400))}catch(Tt){Mc(Tt)||kt(),j("error"),qe(Tt instanceof Error?Tt.message:"An unexpected error occurred"),await new Promise(Ht=>setTimeout(Ht,400))}finally{An(!1),j(null),gt.current=!1}},[ye,e,t,ne,me,ot,Ke,it,T,Le,bt,z,i,qe,_r,It,ve]),Nn=(0,s.useCallback)((l,E)=>{d?d(l):vl(l,E)},[d,vl]),da=`${_c}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let l=localStorage.getItem(da);if(!l)return;let E;try{E=JSON.parse(l)}catch{Kt(da);return}if(!E||typeof E.createdAt!="number"||Date.now()-E.createdAt<0||Date.now()-E.createdAt>Tc||typeof E.paymentMethodId!="string"||typeof E.providerIntentId!="string"||typeof E.paymentMethodType!="string"||E.sessionId!==e||!t||E.nonce!==t||!To.includes(E.paymentMethodType)){Kt(da);return}Kt(da),Nn({id:E.paymentMethodId,type:"card",threeDSecureActionResultTokenId:E.providerIntentId,gateway:"stripe",paymentMethodType:E.paymentMethodType},{...E.accountPatch?{accountPatch:E.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Nn,t,e,da,To]);let Cl=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||Cl.current)return;let[l,E,ae]=Ls();if(!l||!E||za.current||!Le)return;let je=Le.getRawProvider();if(!je)return;let fe=kt=>{let Tt=localStorage.getItem(kt);if(!Tt)return null;try{return JSON.parse(Tt)}catch{return Kt(kt),null}},Ne=fe(Br)??fe(gc),Jt;if(Ne?.clientSecret){if(Ne.clientSecret!==E)return;Jt={...Ne.accountPatch?{accountPatch:Ne.accountPatch}:{},...Ne.sessionId?{sessionId:Ne.sessionId}:{},...Ne.nonce?{nonce:Ne.nonce}:{}}}else if(Ne?.sessionId&&Ne.sessionId!==e)return;Cl.current=!0,Kt(Br),Kt(gc),window.history.replaceState({},"",Ns());let br=Ne?.paymentMethodType??Ne?.tokenType??"card",pt="card";(async()=>{if(ae==="failed"){let Pr="Payment was declined. Please try again.";qe(Pr),_r(pt,Pr);return}let{paymentIntent:kt,error:Tt}=await je.retrievePaymentIntent(E);if(Tt){let Pr=Tt.message??"Failed to retrieve payment status.";qe(Pr),_r(pt,Pr,{code:Tt.code});return}let Ht=kt?.status,mn=ha(Ht);if(!kt||!mn){let Pr=Ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";qe(Pr),_r(pt,Pr,{code:Ht??"missing_payment_intent"});return}let Ml=typeof kt.payment_method=="string"?kt.payment_method:kt.payment_method?.id;Nn({id:Ml??Ne?.paymentMethodId??Ne?.tokenId??kt.id,type:"card",threeDSecureActionResultTokenId:kt.id,gateway:Ne?.gateway??"stripe",paymentMethodType:br},Jt)})()},[e,Nn,Le,qe,_r]);let Zi=(0,s.useCallback)(l=>{l.preventDefault()},[]);if(!(v||Le!==null))return(0,u.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let ua=oe==="buttons",Un=St?.variables,vd=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Qi=Un?.colorBackground,Cd=Qi&&!vd.has(Qi)?Qi:void 0,pa=x.cardInputBorder??(ua?"#e5e7eb":"#A4A4FF"),Sl=Un?.colorDanger??"#dc2626",jt=l=>er[l]&&(Ir[l]||Yt),Wa=ko&&(On||Yt),rr=l=>l?Sl:pa,Ka=(Bn.malformed||Bn.empty)&&(Dn||Yt),Sd=rr(Ka),es=x.cardFormContainer?.backgroundColor??Cd??(ua?"white":"#EDEDFF"),Mo=x.cardInputBackground??Un?.colorBackground??"white",ts=Bo(Re),wl=Bo(_e),xo=x.nameInput,kl=x.cardInputFontSize??tp(xo?.fontSize)??Un?.fontSizeBase??"16px",Rl=typeof xo?.fontFamily=="string"?xo.fontFamily:Un?.fontFamily??"Poppins, sans-serif",Il=_s(xo?.fontWeight)??400,wd=x.cardInputColor??(typeof xo?.color=="string"?xo.color:void 0)??Un?.colorText??"#262833",kd=x.cardInputPlaceholderColor??"#9ca3af",Xt=Un?.borderRadius??"8px",mo=Un?.borderRadius??x.cardButton?.borderRadius??Xt,yo=Un?.colorPrimary??"#4A49FF",Rd=Un?.colorPrimaryHover??Zo(yo,.12),ns=Un?.colorText??"#262833",rs={fontSize:kl,fontFamily:Rl,fontWeight:Il,color:wd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ma={marginTop:"0.375rem",...rs,fontSize:"0.75rem",lineHeight:1.4,color:Sl},Id={"--flopay-input-placeholder-color":kd,"--flopay-input-font-size":kl,"--flopay-input-font-family":Rl,"--flopay-input-font-weight":String(Il)},ya=x.cardFormContainer??{},os=ya.padding??(ua?"0":"1rem"),as=ya.borderRadius??Xt,Ed=Ft&&zr?(0,u.jsx)(lo,{capture:Ft,html:zr.html,messageToken:zr.messageToken,expectedOrigin:zr.expectedOrigin,theme:Fe,submitLabel:S,onReady:()=>{if(!_n&&!me||typeof document>"u")return;let l=()=>{let ae=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(ae){Gn.current=!0;try{ae.focus()}finally{Gn.current=!1}}};Ur.current||l()},onError:l=>qe(l),onValidation:l=>{let E=se.current;(E==="idle"||E==="validation-window")&&(qe(l),l&&se.current==="validation-window"&&(Et.current&&(clearTimeout(Et.current),Et.current=null),se.current="idle",j(null)))}}):(0,u.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"}),El=(0,u.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&Zr()},style:{backgroundColor:es,borderRadius:as,...ya,padding:os,...Id,display:"flex",flexDirection:"column"},children:[(0,u.jsx)("style",{children:`
30
+ `,Jo=44;function Zo(){return(0,fn.jsx)("style",{children:fu})}function Ta(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Aa({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,fn.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,fn.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,fn.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 Is(e){return e!=="unavailable"&&e!=="load_error"}function bi({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:i,backgroundColor:c,borderColor:p,textColor:d,borderRadius:g,fontFamily:b}){let T=(0,Xr.resolveStripeMethodBrandVariant)(e,t),E=sc[e],[S,A]=(0,lc.useState)(!1),_=!!E&&!S,P=T?.backgroundColor??c??"#ffffff",w=T?.borderColor??p??"#d1d5db",K=T?.textColor??d??"#262833";return(0,fn.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&i()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Jo,padding:"0 1rem",backgroundColor:P,color:K,border:`1px solid ${w}`,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,fn.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,Xr.getStripeMethodDisplayName)(e)}\u2026`}):(0,fn.jsxs)(fn.Fragment,{children:[(0,fn.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,Xr.hasVendoredStripeMethodLogo)(e)?8:0},children:[_?(0,fn.jsx)("img",{src:E,alt:"","aria-hidden":"true",onError:()=>A(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!_&&T?.logoSvg?(0,fn.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,fn.jsx)("span",{children:(0,Xr.getStripeMethodDisplayName)(e)})]}),a&&(0,fn.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:K,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,fn.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Pi(e){let t=new Set(e.map(Xr.stripeExpressMethodToOptionKey)),n=r=>r==="applePay"||r==="googlePay"?"always":"auto";return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(r=>[r,t.has(r)?n(r):"never"]))}var vi={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},Ci={type:"accordion",defaultCollapsed:!1,radios:"never"};function Si({testId:e,attributes:t,disabled:n,onClick:r,color:o,borderRadius:a,style:i,children:c}){return(0,fn.jsx)("button",{type:"button","data-testid":e,...t,onClick:r,disabled:n,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:o,color:"white",border:"none",borderRadius:a,fontSize:"1rem",fontWeight:600,cursor:n?"not-allowed":"pointer",opacity:n?.5:1,transition:"opacity 120ms ease-out",...i??{}},children:c})}var Jn=require("react");function wi(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(i=>i.startsWith("background")),a={};for(let[i,c]of Object.entries(e))i in n||o&&i.startsWith("background")||(a[i]=c);for(let i of r)a[i]=n[i];return a}var gu=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 hu(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return gu.has(t.charAt(0).toLowerCase()+t.slice(1))}function bu(e,t){return typeof t=="number"&&t!==0&&!hu(e)?`${t}px`:String(t).trim()}function cc(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]=bu(n,r)}}}var So=require("react/jsx-runtime"),Es=new WeakSet;function co({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,submitLabel:a,containerStyle:i,onReady:c,onError:p,onValidation:d}){let g=(0,Jn.useRef)(null),b=(0,Jn.useRef)(c),T=(0,Jn.useRef)(p),E=(0,Jn.useRef)(d);b.current=c,T.current=p,E.current=d;let S=(0,Jn.useRef)(o);S.current=o;let A=(0,Jn.useRef)(null),_=a??void 0,P=(0,Jn.useRef)(_);P.current=_;let w=(0,Jn.useRef)(void 0);return(0,Jn.useEffect)(()=>{let K=g.current;if(!K)return;let k=!0,ge=!1,z=()=>{!k||ge||(ge=!0,b.current?.())},X=e.on("ready",()=>{z()}),Se=e.on("error",le=>{T.current?.(le.message??"There was a problem loading the secure card form.")}),ae=e.on("validation",le=>{E.current?.(le.message??null)}),De=P.current??(Es.has(e)?null:void 0),Ze={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...S.current?{theme:S.current}:{},...De===void 0?{}:{submitLabel:De}};return A.current=S.current??null,w.current=P.current,P.current!==void 0&&Es.add(e),e.mount(K,Ze).then(()=>{z()}).catch(le=>{k&&T.current?.(le instanceof Error?le.message:"Failed to load the secure card form.")}),()=>{k=!1,X(),Se(),ae(),e.unmount()}},[e,t,n,r]),vo(()=>{let K=g.current;K&&cc(K,i)},[i]),(0,Jn.useEffect)(()=>{o!==void 0&&(o===null&&A.current===null||(A.current=o,e.applyTheme?.(o)))},[e,o]),(0,Jn.useEffect)(()=>{_!==w.current&&(w.current=_,_!==void 0&&Es.add(e),e.setSubmitLabel?.(_??null))},[e,_]),(0,So.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields"})}function ki({label:e}){return(0,So.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,So.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,So.jsx)("span",{children:e}),(0,So.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var uc=/^#([0-9a-f]{6})$/i,Pu=/^#([0-9a-f]{3})$/i,pc=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,mc=/^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,vu=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,Cu=/^(-?\d+(?:\.\d+)?)(?:px)?$/,Su=/^(-?\d+(?:\.\d+)?)em$/,wu=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,ku=/^[a-z][a-z0-9 -]{0,31}$/i,Ru=new Set(["none","uppercase","lowercase","capitalize"]);function yc(e){if(typeof e!="string")return null;let t=e.trim(),n=uc.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=Pu.exec(t);if(r){let[g,b,T]=r[1].split("").map(E=>Number.parseInt(E+E,16));return{r:g,g:b,b:T,a:null}}let o=pc.exec(t),a=o?null:mc.exec(t),i=o??a;if(!i)return null;let c=Number(i[1]),p=Number(i[2]),d=Number(i[3]);return c>255||p>255||d>255?null:{r:c,g:p,b:d,a:a?Number(a[4]):null}}function fc({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 Ma(e){if(typeof e!="string")return;let t=e.trim();if(uc.test(t)||pc.test(t))return t;let n=mc.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=yc(t);return r?fc(r):void 0}function Ri(e,t=.12){let n=yc(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return fc({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function xa(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 wo(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=Cu.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function _u(e,t,n){if(typeof e!="string")return;let r=Su.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Iu(e){let t=xa(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=xa(o," "),i=Ma(a[0]);if(!i)return;let c=r/(t.length-1)*100,p=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),d=n[n.length-1]?.position??-1;if(!Number.isFinite(p)||p<0||p>100||p<d)return;n.push({color:i,position:p})}return{type:"linearGradient",angle:0,stops:n}}function Eu(e){if(typeof e!="string")return;let t=e.trim(),n=Ma(t);if(n)return{type:"solid",color:n};let r=vu.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Iu(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Tu(e){return e.type==="solid"?{type:"solid",color:Ri(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:Ri(t.color)}))}}function Au(e){let t=!1,n,r=[];for(let p of xa(e," ")){if(p.toLowerCase()==="inset"){t=!0;continue}let d=Ma(p);if(d){n=d;continue}let g=wo(p,-128,128);if(g===void 0)return;r.push(g)}if(!n||r.length<2||r.length>4)return;let[o,a,i=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||i>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:i,spread:c}}function Mu(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=xa(t,",").map(Au);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function dc(e){if(typeof e!="string")return;let t=xa(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>ku.test(n)).slice(0,4);return t.length>0?t:void 0}function xu(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=wo(t[0],0,64),r=wo(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function Fu(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 gc({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=Eu(r.background??r.backgroundColor),i=Ma(o?.colorPrimaryHover),c=i?{type:"solid",color:i}:a&&Tu(a),p={fontFamilies:dc(r.fontFamily)??dc(n),fontSize:wo(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Fu(r.fontWeight)??600,letterSpacing:_u(r.letterSpacing,-.1,.5)??.01,lineHeight:wo(r.lineHeight,.8,2)??1,textTransform:Ru.has(String(r.textTransform))?r.textTransform:"uppercase"},d=xu(r.padding),g=Mu(r.boxShadow),b=wo(r.borderRadius,0,9999),T=typeof r.backdropFilter=="string"?wo(wu.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Ma(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:p,...d?{spacing:d}:{},...g?{shadow:g}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...T===void 0?{}:{backdropBlur:T}}}function Qo(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)?Ri(r,t):e}function Ts(e){if(typeof e=="number"||typeof e=="string")return e}function ea({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,i=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",p=t.nameInput,d=o(p?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",g=gc({appearance:e,buttonsStyles:t,fontFamily:d});return{primaryColor:i,primaryHoverColor:o(r?.colorPrimaryHover)??Qo(i,.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:d,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Ts(p?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...g?{submitButton:g}:{}}}var u=require("react/jsx-runtime"),Fr="flopay_stripe_resume",hc="flopay_wallet_resume",Tc="fw1",Bu="fw2",Ac=300*1e3,Du=900,Ou=25e3,Lu=25e3,Nu=1e4,Mc=["payment_intent","payment_intent_client_secret","redirect_status"],Cr={provider:"paypal",paymentMethodCategory:"paypal"},Uu="x-flopay-process-result-source",zu="status";async function qu(e,t,n){try{let r=(await e.getUnifiedCheckoutSession(t,n)).data.session;if(r?.status==="complete")return null;if(r?.status==="authorized")return{status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}}catch{}}var _i={},As={};function Kt(e,t){if(typeof window>"u")return!1;try{return t===void 0?window.localStorage.removeItem(e):window.localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function Ls(e){return`${Bu}:${e}`}function Ii(e){return Kt(Ls(e))}function Ei(e,t){if(typeof window>"u")return null;let n=Ls(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>Ac||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Ii(e),null):o}catch{return Ii(e),null}}function Vu(e){return Kt(Ls(e.sessionId),e)}function bc(e,t,n){let r=Ei(e,t);return!r||r.clientSecret!==n?!1:Ii(e)}function Ms(e,t,n){if(typeof window>"u")return;Ei(e,t)?.clientSecret===n&&Ii(e)}function ju(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function xs(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":ba(e.status),o=ju(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function Pc(e,t,n){let r=null;try{return await Promise.race([ql(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Nu),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function $u(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function xc(e){return e instanceof y.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Ti(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Sr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw xc(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Ba="flopay_paypal_resume",Fa=new Map;function Fc(e){if(!e||typeof window>"u")return null;try{let t=window.localStorage.getItem(Ba);if(!t)return null;let n=JSON.parse(t);return n?.clientSecret===e?n:null}catch{return null}}function Hu(){if(typeof window>"u")return!1;let[e,t]=Ns();return e?Fc(t)!==null:!1}function Ns(){let e=new URLSearchParams(window.location.search);return Mc.map(t=>e.get(t))}function Us(){let e=new URL(window.location.href);for(let t of Mc)e.searchParams.delete(t);return e.toString()}function Wu(){Kt(Ba),window.history.replaceState({},"",Us())}var Ku=250,vc="Just a moment \u2014 we are finalizing your order. Please press pay again.",Gu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function zs(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 Ai({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Sr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Yu(e){return e instanceof y.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Fs(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Bc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=ho(n),i=a.firstName?a:ho(r?.name);return Un({email:(0,y.isValidEmail)(o)?o:r?.email?.trim(),firstName:i.firstName,lastName:i.lastName})}async function Xu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let i=Bc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,y.isValidEmail)(i.email)?i:a(o,i)}var Da=180,Cc=`flopay-card-enter ${Da}ms cubic-bezier(0, 0, 0.2, 1) both`,Sc=`flopay-card-exit ${Da}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Ju=`flopay-buttons-enter ${Da}ms cubic-bezier(0, 0, 0.2, 1) both`,Zu=`flopay-buttons-exit ${Da}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Qu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function qs(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 ep={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function tp(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 Bs={width:"100%",minHeight:Jo,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 np(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function wc(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ds(e){return e==="paypal"?"PayPal":(0,y.getStripeMethodDisplayName)(e)}function rp(e){let t=(0,y.getPostalCodeExample)(e);return`Enter a valid ${(0,y.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function op(e,t,n){let r=(0,y.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,i=a&&!o,c=a&&!!o&&!(0,y.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:i,malformed:c}}function ap(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,y.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function kc(e,t){return t instanceof y.FloPayError?t:new y.FloPayError(t instanceof Error?t.message:`${np(e)} before-click hook failed.`,"validation_error")}function ip(e){return typeof e=="number"?`${e}px`:e}function Mi(e){return(0,u.jsx)(sp,{...e})}function Rc({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:i=!1,onButtonClick:c,onDecline:p,onTechnicalFailure:d,runBeforeButtonClick:g,billingName:b,onBuyerIdentityReady:T,onLoadStateChange:E,placeholderBorderRadius:S,popupCapabilityOwner:A,externalTelemetryContext:_,presentationMode:P}){let w=Kr(),{emitInstrument:K}=(0,s.useContext)(or),k=(0,Zt.useStripe)(),ge=(0,Zt.useElements)(),z=(0,s.useMemo)(()=>hi(yn(w),_),[_,w]),[X,Se]=(0,s.useState)("loading");(0,s.useEffect)(()=>{E?.(X)},[X,E]);let[ae,De]=(0,s.useState)(!1),Ze=(0,s.useRef)(!1),le=!(0,y.isValidEmail)(n?.trim())||!b?.trim(),{request:Ie,collect:He,finish:Re}=zo(),Ee=(0,s.useRef)(!1),_e=(0,s.useRef)(null),ce=(0,s.useRef)(null),[de,Pe]=(0,s.useState)(0),[Ae,J]=(0,s.useState)(!1),ee=(0,s.useRef)(!1),he=(0,s.useRef)(new Map),{startAttempt:U,finishAttempt:we,invalidateAttempt:ie,isAttemptInvalidated:Te,isAttemptCurrent:te,generationRef:at}=Sa((V,be,Qe)=>{d?.(V,be,{...Qe,popupBlocked:Qe?.popupBlocked??io(be),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:P,terminalReason:"overlay_timeout"}),J(!0),Pe(Z=>Z+1)},{onHandoffObserved:()=>{A.markAvailable(),z?.log({name:"provider.popup.opened",stage:"overlay_open",...Cr,attempt:at.current})}});(0,s.useEffect)(()=>{Ae&&ce.current?.focus()},[Ae,de]);let We=(0,s.useCallback)(()=>{Pe(V=>V+1)},[]),je=(0,s.useCallback)((V,be,Qe)=>{ie(Qe),d?.("paypal",V,{code:be,popupBlocked:io(V),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:P}),J(!0),We()},[ie,d,P,We]),ot=(0,s.useCallback)(()=>{window.setTimeout(()=>{(_e.current?.querySelector("iframe")??_e.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ee.current&&(ee.current=!1,ot())},[ot,de]);let Ke=(0,s.useCallback)(()=>{J(!1),a?.(null),ot()},[ot,a]);(0,s.useEffect)(()=>{if(!k||Ee.current)return;let[V,be,Qe]=Ns();if(!V||!be)return;let Z=Fc(be);if(!Z)return;Ee.current=!0;let Le=!0,bt=Fa.get(be);bt||(bt=Qe==="failed"?Promise.resolve(null):Promise.resolve().then(()=>k.retrievePaymentIntent(be)),Fa.set(be,bt));let Ye={accountPatch:Z.accountPatch,sessionId:Z.sessionId,nonce:Z.nonce},_t=()=>{z?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",...Cr,requestCategory:"provider_sdk"})};return z?.log({name:"provider.redirect.resumed",stage:"redirect_resume",...Cr}),(async()=>{try{De(!0);let h=await bt;if(!Le)return;if(h?.error){Fa.delete(be),_t(),a?.(h.error.message??"Failed to retrieve PayPal payment status.");return}if(Wu(),Fa.delete(be),Qe==="failed"){let Y="PayPal payment was declined. Please try again.";z?.terminal({outcome:"payment_declined",...Cr,terminalReason:"provider_declined"}),a?.(Y),p?.(mn("paypal",Y));return}let C=h?.paymentIntent;if(C&&C.id!==V){_t(),a?.("Failed to match the returned PayPal payment.");return}if(C&&(C.status==="requires_capture"||C.status==="succeeded")){let Y=typeof C.payment_method=="string"?C.payment_method:C.payment_method?.id;o({id:Y??C.id,type:"card",threeDSecureActionResultTokenId:C.id,isPaypal:!0},{...Ye,presentationMode:"redirect"})}else{let Y="PayPal payment was not completed. Please try again.";z?.terminal({outcome:C?.status==="canceled"?"payment_cancelled":"payment_declined",...Cr,terminalReason:C?.status==="canceled"?"cancelled":"provider_declined"}),a?.(Y),p?.(mn("paypal",Y))}}catch(h){if(!Le)return;Fa.delete(be),_t(),a?.(h instanceof Error?h.message:"Failed to complete PayPal payment.")}finally{Le&&De(!1)}})(),()=>{Le=!1,Ee.current=!1}},[k,o,a,p,z]);let it=(0,s.useCallback)(async(V=!1)=>{let be=g?await g("paypal"):{proceed:!0};if(!be.proceed)return he.current.delete(de),!1;let Qe=U("paypal");return he.current.set(de,{generation:Qe,accountPatch:be.accountPatch,sessionId:be.sessionId,nonce:be.nonce}),J(!1),z?.log({name:`provider.${V?"redirect.started":"handoff.requested"}`,stage:V?"redirect":"overlay_open",...Cr,attempt:Qe}),c?.("paypal"),!0},[c,z,g,U,de]),$e=(0,s.useCallback)(async V=>{if(i||ae||!await it()){V.reject();return}V.resolve()},[i,it,ae]),vt=(0,s.useCallback)(async V=>{if(!k||!ge)return;let be=he.current.get(de);if(be&&!te(be.generation)){he.current.delete(de);return}if(!be&&Te()||be&&!we(be.generation))return;be||we();let Qe=be??null;if(he.current.delete(de),!Qe&&g){let j=await g("paypal");if(!j.proceed){V.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Qe={accountPatch:j.accountPatch,sessionId:j.sessionId,nonce:j.nonce}}let Z=Qe?.sessionId??e,Le=Qe?.nonce??t,bt=await Xu({event:V,prepared:Qe,email:n,billingName:b,methodLabel:"PayPal",collect:He});if(!bt){V.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ye=bt.email,_t={...Qe?.accountPatch,...Un(bt,!0)};try{if(De(!0),a?.(null),!Z||!(0,y.isValidEmail)(Ye))throw new Error("Missing sessionId or email for PayPal payment");await T?.(bt);let j=k.createPaymentMethod,{error:h,paymentMethod:C}=await j({type:"paypal"});if(h){je(h,"stripe_paypal_create_payment_method_failed",be?.generation),V.paymentFailed({reason:"fail"});return}let Y=await Ti(r,K,Z,Le??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:C?.id??null,intentKind:"payment"});if(Y.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let W=Y.clientSecret,ve={return_url:Us()};if(C?.id&&(ve.payment_method=C.id),!Kt(Ba,{clientSecret:W,sessionId:Z,nonce:Le,accountPatch:_t})&&P==="redirect")throw new Error("Unable to save PayPal checkout progress. Please try again.");let{error:B,paymentIntent:ue}=await k.confirmPayment({clientSecret:W,confirmParams:ve,redirect:"if_required"});if(B){if(Kt(Ba),Po(B)){let Me=B.message??"Your payment was declined.";z?.terminal({outcome:"payment_declined",...Cr,terminalReason:"provider_declined"}),a?.(Me),p?.(mn("paypal",Me,{code:Mr(B),declineCode:Vo(B)})),await Ai({billingApiUrl:r,sessionId:Z,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mr(B)??"provider_declined"}})}else je(B,"stripe_paypal_confirm_failed",be?.generation);return}Kt(Ba);let D=typeof ue?.payment_method=="string"?ue.payment_method:ue?.payment_method?.id;o({id:D??ue?.id,type:"card",threeDSecureActionResultTokenId:ue?.id,isPaypal:!0},{accountPatch:_t,paymentMethodCategory:"paypal",presentationMode:P,sessionId:Z,nonce:Le});return}catch(j){je(j,"stripe_paypal_failed",be?.generation)}finally{De(!1)}},[k,ge,e,t,n,b,He,T,r,K,o,a,p,g,je,we,te,Te,z,P,de]),Lt=(0,s.useCallback)(async()=>{if(!(Ze.current||i||ae||!k||!ge)){Ze.current=!0,De(!0);try{if(!await it(!0))return;await vt({expressPaymentType:"paypal",paymentFailed:()=>{}})}finally{Ze.current=!1,De(!1)}}},[ge,vt,i,it,k,ae]),ht=P==="redirect"?(0,u.jsx)("button",{type:"button",disabled:i||ae,onClick:()=>{Lt()},style:{width:"100%",minHeight:Jo,border:"1px solid #d1d5db",borderRadius:S??8,background:"#ffc439",color:"#111827",cursor:i||ae?"not-allowed":"pointer",fontSize:"1rem",fontWeight:700},children:"Pay with PayPal"}):(0,u.jsx)(Zt.ExpressCheckoutElement,{onReady:V=>Se(Ta(V,["paypal"])),onLoadError:()=>{Se("load_error"),zs(z,"paypal","paypal","provider_error")},onClick:$e,onConfirm:vt,onCancel:()=>{let V=he.current.get(de);he.current.delete(de),z?.terminal({outcome:"payment_cancelled",...Cr,terminalReason:"cancelled",...V?{attempt:V.generation}:{}}),ie(V?.generation),J(!1),ee.current=!0,We()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:le,emailRequired:le,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},de),Tt=(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("div",{ref:_e,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ae&&(0,u.jsx)("button",{ref:ce,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ke,style:Bs,children:"Try PayPal again"}),Ie&&(0,u.jsx)(qo,{identity:Ie.identity,methodLabel:Ie.methodLabel,onComplete:Re,onCancel:()=>Re(null)},Ie.id),(0,u.jsx)("div",{style:{display:Ie?"none":void 0},children:ht})]}),ae&&!Ie&&(0,u.jsx)(zn,{status:"processing"})]});return P==="redirect"?Tt:(0,u.jsx)(Aa,{state:X,placeholderTestId:"flopay-paypal-placeholder",borderRadius:S,children:Tt})}function _c(e){return e==="apple_pay"||e==="google_pay"}function Ic({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:i,onErrorChange:c,onButtonClick:p,onDecline:d,onTechnicalFailure:g,runBeforeButtonClick:b,billingName:T,onBuyerIdentityReady:E,onLoadStateChange:S,placeholderBorderRadius:A,popupCapabilityOwner:_,externalTelemetryContext:P}){let w=Kr(),{emitInstrument:K}=(0,s.useContext)(or),k=(0,Zt.useStripe)(),ge=(0,Zt.useElements)(),z=(0,s.useMemo)(()=>hi(yn(w),P),[P,w]),[X,Se]=(0,s.useState)("loading");(0,s.useEffect)(()=>{S?.(X)},[X,S]);let[ae,De]=(0,s.useState)(!1),Ze=(0,s.useRef)(!(0,y.isValidEmail)(n?.trim())||!T?.trim()).current,{request:le,collect:Ie,finish:He}=zo(),Re=(0,s.useRef)(null),Ee=(0,s.useRef)(null),[_e,ce]=(0,s.useState)(0),[de,Pe]=(0,s.useState)(!1),[Ae,J]=(0,s.useState)(()=>Ei(e,t)?"blocked":"idle"),[ee,he]=(0,s.useState)("google_pay"),U=(0,s.useRef)(null),we=(0,s.useRef)(!0),ie=(0,s.useRef)(!1),Te=(0,s.useRef)("google_pay"),te=(0,s.useRef)("google_pay"),at=(0,s.useRef)(null),We=(0,s.useRef)(null),je=(0,s.useRef)(new Set),ot=(0,s.useRef)(null);(0,s.useEffect)(()=>(we.current=!0,()=>{we.current=!1;for(let j of je.current)window.clearTimeout(j);je.current.clear()}),[]);let Ke=(0,s.useRef)(new Map),{startAttempt:it,finishAttempt:$e,invalidateAttempt:vt,isAttemptInvalidated:Lt,isAttemptCurrent:ht,generationRef:Tt}=Sa((j,h,C)=>{g?.(j,h,{...C,popupBlocked:C?.popupBlocked??io(h),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),he(j),Pe(!0),ce(Y=>Y+1)},{onHandoffObserved:j=>{_.markAvailable(),z?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:Tt.current,...j==="apple_pay"||j==="google_pay"?{walletType:j}:{}})},defersMissingTerminal:_c,onMissingTerminalDeferred:(j,h)=>{let C=z?.now()??globalThis.performance?.now()??Date.now(),Y=ot.current,W=Y?.generation===h?Y.startedAt:C;z?.performance({stage:"overlay_return",durationMs:Math.max(0,C-W),durationMode:"buyer",provider:"stripe",paymentMethodCategory:"wallet",requestCategory:"provider_sdk",operationOutcome:"watchdog_expired",attempt:h,..._c(j)?{walletType:j}:{}}),z?.flush?.().catch(()=>{})}});(0,s.useEffect)(()=>{de&&Ee.current?.focus()},[de,_e]);let V=(0,s.useCallback)(()=>{ce(j=>j+1)},[]),be=(0,s.useCallback)((j,h,C,Y,W=!1)=>{vt(Y),g?.(j,h,{code:C,popupBlocked:io(h),telemetryReported:W,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),he(j),Pe(!0),V()},[vt,g,V]),Qe=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Re.current?.querySelector("iframe")??Re.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ie.current&&(ie.current=!1,Qe())},[Qe,_e]);let Z=(0,s.useCallback)(()=>{Pe(!1),c?.(null),Qe()},[Qe,c]),Le=(0,s.useCallback)(()=>{U.current?.()},[]);(0,s.useEffect)(()=>{let j=Ei(e,t);if(!j)return;let h=!1,C=!1,Y=async()=>{if(!C){C=!0,h||J("checking");try{let W=await Pc(k,j.clientSecret,je.current);if(h)return;let ve=xs(W,j.providerObjectId,(0,y.isSetupIntentClientSecret)(j.clientSecret));if(ve.kind==="confirmed"){if(!bc(e,t,j.clientSecret))return;U.current=null,J("idle"),i({id:ve.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ve.intentId},{...j.accountPatch?{accountPatch:j.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ve.kind==="terminal"){Ms(e,t,j.clientSecret),U.current=null,J("idle"),he(j.paymentMethodType),Pe(!0),V();return}J("blocked")}catch{h||J("blocked")}finally{C=!1}}};return U.current=Y,J("blocked"),()=>{h=!0,U.current===Y&&(U.current=null)}},[t,i,V,e,k]);let bt=(0,s.useCallback)(async j=>{let h=!1,C=dt=>{h||(h=!0,j.paymentFailed({reason:"fail",...dt?{message:dt}:{}}))};if(!k||!ge){C();return}let Y=Ke.current.get(_e);if(Y&&!ht(Y.generation)){Ke.current.delete(_e),C();return}if(!Y&&Lt()){C();return}if(Y&&!$e(Y.generation)){C();return}Y||$e();let W=j.expressPaymentType??Y?.method??Te.current,ve=Y??null,x=wc(W),B;W==="apple_pay"?B="apple_pay":W==="google_pay"&&(B="google_pay");let ue=Y?.generation??Tt.current,D=z,Me=D?.now()??globalThis.performance?.now()??Date.now(),st=new AbortController,yt=!1,Ct=!1,Be=null,Tn=e,Vn="processing",gn="other",jt="provider_runtime",jn,$n=new Promise((dt,nt)=>{jn=nt}),vn=window.setTimeout(()=>{yt=!0,st.abort(),jn(_i)},Ou),Dt=async(dt,nt,An)=>{Vn=dt,gn=nt,jt=nt==="intent_create"||nt==="session_claim"?"transport_error":"provider_runtime";let Mt=D?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([An,$n])}finally{let Hn=D?.now()??globalThis.performance?.now()??Date.now();D?.performance({stage:dt,durationMs:Math.max(0,Hn-Mt),durationMode:"machine",requestCategory:nt,paymentMethodCategory:"wallet",provider:"stripe",...yt?{statusClass:"timeout"}:{}})}};try{if(De(!0),c?.(null),!ve&&b){let ze=await Dt("processing","other",b(x));if(!ze.proceed){C();return}ve={accountPatch:ze.accountPatch,sessionId:ze.sessionId,nonce:ze.nonce}}let dt=ve?.sessionId??e;Tn=dt;let nt=ve?.nonce??t,An=at.current??ve?.accountPatch,Mt=Bc({event:j,fallbackEmail:An?.email??n,fallbackName:[An?.firstName,An?.lastName].join(" ").trim()||T});if(!(0,y.isValidEmail)(Mt.email)){C("Buyer details are required."),Ie(Ds(W),Mt).then(ze=>{ze&&(at.current=ze)});return}at.current=null;let Hn={...ve?.accountPatch,...Un(Mt,!0)};await Dt("processing","session_claim",Promise.resolve(E?.(Mt)));let{error:hn}=await Dt("tokenization","provider_sdk",ge.submit());if(hn){C(),be(W,hn,"stripe_wallet_submit_failed",Y?.generation);return}if(!dt)throw new Error("Missing sessionId or email for payment.");let $t={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,paymentMethodId:null,intentKind:o},en=JSON.stringify({sessionId:dt,nonce:nt??"",request:$t}),cr=We.current,Qn=cr?.retryIdentity===en?cr.authorizationAttemptId:(0,y.randomUuidV4)();We.current={authorizationAttemptId:Qn,retryIdentity:en};let tn=await Dt("processing","intent_create",Ti(r,K,dt,nt??"",{...$t,authorizationAttemptId:Qn},{signal:st.signal}));if(tn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let xt=tn.clientSecret,nn=Vu({createdAt:Date.now(),sessionId:dt,...nt?{nonce:nt}:{},clientSecret:xt,providerObjectId:tn.providerObjectId,paymentMethodType:W,accountPatch:Hn});window.clearTimeout(vn),Ct=!0,D?.performance({stage:"callback",durationMs:Math.max(0,(D?.now()??globalThis.performance?.now()??Date.now())-Me),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let sn=D?.now()??globalThis.performance?.now()??Date.now(),Nt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...B?{walletType:B}:{},attempt:ue},cn=!1,zt=null;D?.log({name:"payment.provider_confirmation.started",...Nt}),Be=window.setTimeout(()=>{Be!==null&&je.current.delete(Be),cn=!0;let ze=D?.now()??globalThis.performance?.now()??Date.now();D?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...Nt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,ze-sn),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),D?.flush?.().catch(()=>{}),zt?.()},Lu),je.current.add(Be);let ln=(ze,mt)=>{Be!==null&&(window.clearTimeout(Be),je.current.delete(Be),Be=null);let v=D?.now()??globalThis.performance?.now()??Date.now(),ut=Math.max(0,v-sn),pe=ze;cn&&(ze==="resolved"?pe="resolved_late":ze==="returned_error"?pe="returned_error_late":pe="rejected_late");let Cn=mt??(ze==="resolved"?"approved":"provider_error");return D?.log({name:"payment.provider_confirmation.returned",...Nt,operationOutcome:pe,terminalReason:Cn}),D?.performance({...Nt,durationMs:ut,durationMode:"buyer",operationOutcome:pe,terminalReason:Cn}),{durationMs:ut,operationOutcome:pe,terminalReason:Cn}},Ut=!1,me=!1,dr=ze=>{if(!ze||typeof ze!="object")return null;let mt=ze;if(mt.error)return null;let v=mt.setupIntent??mt.paymentIntent,ut=xs(v??null,void 0,!!mt.setupIntent);return ut.kind==="confirmed"?ut:null},ur=ze=>{if(Ut||Y&&Tt.current!==Y.generation)return;let mt=dr(ze);if(!mt)return;if(nn&&!bc(dt,nt,xt)){Ut=!0;return}let{intentId:v,paymentMethodId:ut}=mt;Ut=!0,me=!0,We.current=null,U.current=null,we.current&&(J("idle"),De(!1));let pe=`${Tc}:${dt}`;Kt(pe,{createdAt:Date.now(),sessionId:dt,nonce:nt,accountPatch:Hn,paymentMethodId:ut,providerIntentId:v,paymentMethodType:W});try{i({id:ut,type:"card",threeDSecureActionResultTokenId:v},{accountPatch:Hn,paymentMethodCategory:"wallet",sessionId:dt,nonce:nt})}finally{Kt(pe)}},pr=!1;zt=async()=>{if(!(pr||Ut||me)){pr=!0,we.current&&J("checking");try{let ze=await Pc(k,xt,je.current);if(Ut||me)return;let mt=(0,y.isSetupIntentClientSecret)(xt),v=xs(ze,tn.providerObjectId,mt);if(v.kind==="confirmed"){ur(mt?{setupIntent:ze}:{paymentIntent:ze});return}if(v.kind==="terminal"){if(me=!0,Ms(dt,nt,xt),We.current=null,U.current=null,!we.current)return;J("idle"),C(),be(W,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",Y?.generation,!0);return}we.current&&!me&&(J("blocked"),De(!1))}catch{we.current&&!me&&(J("blocked"),De(!1))}finally{pr=!1}}},U.current=zt;let rn,Mn;try{let ze=await((0,y.isSetupIntentClientSecret)(xt)?k.confirmSetup({elements:ge,clientSecret:xt,redirect:"if_required"}):k.confirmPayment({elements:ge,clientSecret:xt,redirect:"if_required"}));if(!ze||typeof ze!="object"||(rn=ze,!rn.error&&!dr(rn)))throw As;Mn=ln(rn.error?"returned_error":"resolved",rn.error&&Po(rn.error)?"provider_declined":void 0)}catch(ze){let mt=ze===As,v=ln(mt?"returned_error":"rejected");if(D?.error({...mt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:ps(ze),...Nt,operationOutcome:v.operationOutcome,durationMs:v.durationMs,statusClass:"unknown",terminalReason:v.terminalReason}),!we.current||Ut)return;await zt?.();return}let wn=rn.error;if(wn){if(!we.current||Ut)return;if(Po(wn)){me=!0,Ms(dt,nt,xt),We.current=null,U.current=null,J("idle");let ze=wn.message??"Your payment was declined.";C(ze),c?.(ze),d?.(mn(x,ze,{code:Mr(wn),declineCode:Vo(wn)})),Ai({billingApiUrl:r,sessionId:dt,nonce:nt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,providerDeclineReason:Mr(wn)??"provider_declined",...tn.intentKind==="payment"&&tn.providerObjectId.startsWith("pi_")?{providerIntentId:tn.providerObjectId}:{}}})}else D?.error({...ps(wn),...Nt,operationOutcome:Mn.operationOutcome,durationMs:Mn.durationMs,statusClass:"unknown",terminalReason:Mn.terminalReason}),await zt?.();return}if(ur(rn),!Ut)throw new Error("Invalid provider returned for APM intent")}catch(dt){if(dt===_i){let nt=D?.now()??globalThis.performance?.now()??Date.now();D?.error({errorCode:$u(gn),stage:Vn,requestCategory:gn,paymentMethodCategory:"wallet",provider:"stripe",...B?{walletType:B}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Tn,durationMs:Math.max(0,nt-Me),statusClass:"timeout",failureCategory:jt,attempt:ue,terminalReason:"provider_error"}),D?.flush?.().catch(()=>{})}C(),be(W,dt,dt===_i?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Y?.generation,dt===_i)}finally{if(window.clearTimeout(vn),Be!==null&&(window.clearTimeout(Be),je.current.delete(Be)),!Ct){let dt=D?.now()??globalThis.performance?.now()??Date.now();D?.performance({stage:"callback",durationMs:Math.max(0,dt-Me),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...yt?{statusClass:"timeout"}:{}})}we.current&&De(!1)}},[k,ge,e,t,n,T,Ie,E,r,K,o,i,c,d,b,be,$e,ht,Lt,Tt,z,_e]),Ye=(0,s.useMemo)(()=>Pi(a),[a]),_t=(0,s.useMemo)(()=>a.map(y.stripeExpressMethodToOptionKey),[a]);return(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(Aa,{state:X,placeholderTestId:"flopay-wallet-placeholder",borderRadius:A,children:(0,u.jsxs)("div",{ref:Re,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[de&&(0,u.jsxs)("button",{ref:Ee,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Z,style:Bs,children:["Try ",Ds(ee)," again"]}),Ae!=="idle"&&(0,u.jsxs)("div",{role:"status","aria-live":"polite",children:[(0,u.jsx)("p",{children:"We are still confirming your payment. Check its status before trying again."}),(0,u.jsx)("button",{type:"button",onClick:Le,disabled:Ae==="checking",style:Bs,children:Ae==="checking"?"Checking payment status\u2026":"Check payment status"})]}),le&&(0,u.jsx)(qo,{identity:le.identity,methodLabel:le.methodLabel,onComplete:He,onCancel:()=>He(null)},le.id),Ae==="idle"&&(0,u.jsx)("div",{style:{display:le?"none":void 0},children:(0,u.jsx)(Zt.ExpressCheckoutElement,{onReady:j=>{Se(Ta(j,_t))},onLoadError:j=>{Se("load_error"),zs(z,"stripe","wallet","provider_error")},onClick:async j=>{let h=z?.now()??globalThis.performance?.now()??Date.now();Te.current=j.expressPaymentType,te.current=wc(j.expressPaymentType);let C=!0,Y=window.setTimeout(()=>{C=!1,j.reject()},Du),W=b?await b(te.current):{proceed:!0};if(window.clearTimeout(Y),!C)return;if(!W.proceed){Ke.current.delete(_e),j.reject();return}let ve=it(j.expressPaymentType);ot.current={generation:ve,startedAt:h},Ke.current.set(_e,{generation:ve,method:j.expressPaymentType,accountPatch:W.accountPatch,sessionId:W.sessionId,nonce:W.nonce}),Pe(!1),z?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:ve,...j.expressPaymentType==="apple_pay"||j.expressPaymentType==="google_pay"?{walletType:j.expressPaymentType}:{}}),p?.(te.current),j.resolve()},onConfirm:bt,onCancel:()=>{let j=Ke.current.get(_e);Ke.current.delete(_e),z?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...j?{attempt:j.generation}:{}}),vt(j?.generation),We.current=null,Pe(!1),ie.current=!0,V()},options:{...vi,paymentMethods:Ye,emailRequired:Ze,billingAddressRequired:Ze}},_e)})]})}),ae&&(0,u.jsx)(zn,{status:"processing"})]})}function Dc(e,t,n){let r=(0,y.resolveSetupFutureUsage)(n,t,"inline_apm");return{...e,paymentMethodTypes:[t],...r?{setupFutureUsage:r}:null}}function Os({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:c,onErrorChange:p,onDecline:d,onCancel:g,runBeforeButtonClick:b,onButtonClick:T,isProcessing:E,submitButtonColor:S,submitButtonBorderRadius:A,submitButtonStyle:_,errorText:P}){let w=Kr(),{emitInstrument:K}=(0,s.useContext)(or),k=(0,Zt.useStripe)(),ge=(0,Zt.useElements)(),[z,X]=(0,s.useState)(!1),Se=(0,s.useRef)(!1),[ae,De]=(0,s.useState)(!1),[Ze,le]=(0,s.useState)("loading"),[Ie,He]=(0,s.useState)(""),Re=!(0,y.isValidEmail)(r?.trim()),Ee=!Re||(0,y.isValidEmail)(Ie.trim()),_e=(0,s.useCallback)(async()=>{if(!k||!ge||E||Se.current||!ae)return;Se.current=!0,X(!0);let ce=b?await b("card"):{proceed:!0};if(!ce.proceed){Se.current=!1,X(!1);return}T?.("card");let de=ce.sessionId??t,Pe=ce.nonce??n,Ae=ho(o?.trim()),J=Un({email:ce.accountPatch?.email?.trim()||r?.trim()||Ie.trim(),firstName:ce.accountPatch?.firstName?.trim()||Ae.firstName,lastName:ce.accountPatch?.lastName?.trim()||Ae.lastName}),ee=J.email,he=Un({...ce.accountPatch,...J});try{if(p?.(null),!(0,y.isValidEmail)(ee))throw new Error("A valid email address is required for payment.");await a?.(J);let U=await ge.submit();if(U.error){p?.(U.error.message??"Payment failed.");return}let we=[J.firstName,J.lastName].filter(Boolean).join(" "),ie=await k.createPaymentMethod({elements:ge,params:{billing_details:{email:ee,...we?{name:we}:{}}}});if(ie.error||!ie.paymentMethod){p?.(ie.error?.message??"Failed to create payment method.");return}let Te=ie.paymentMethod;if(!de||!ee)throw new Error("Missing sessionId or email for payment.");let te=Te.type||e,at=await Ti(i,K,de,Pe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:te,paymentMethodId:null,intentKind:"payment"});if(at.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let We=at.clientSecret;Kt(Fr,{clientSecret:We,sessionId:de,nonce:Pe,accountPatch:he,paymentMethodId:Te.id,paymentMethodType:Te.type??e,gateway:"stripe"});let{error:je,paymentIntent:ot}=await k.confirmPayment({clientSecret:We,confirmParams:{return_url:window.location.href,payment_method:Te.id},redirect:"if_required"});if(je){Kt(Fr);let $e=je.message??"Payment failed.";p?.($e),d?.(mn("card",$e,{code:je.code})),await Ai({billingApiUrl:i,sessionId:de,nonce:Pe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:je.code??"provider_declined"}});return}let Ke=ot?.status;if(!ba(Ke)){Kt(Fr);let $e=Ke==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.($e),d?.(mn("card",$e,{code:Ke??"missing_payment_intent"}));return}Kt(Fr);let it=typeof ot?.payment_method=="string"?ot.payment_method:ot?.payment_method?.id;c({id:it??Te.id,type:"card",threeDSecureActionResultTokenId:ot?.id,gateway:"stripe",paymentMethodType:Te.type??e},{accountPatch:he,paymentMethodCategory:"apm",sessionId:de,nonce:Pe})}catch(U){p?.(U instanceof Error?U.message:"Payment failed. Please try again.")}finally{Se.current=!1,X(!1)}},[k,ge,E,ae,b,T,t,n,r,o,Ie,a,i,K,e,c,p,d]);return(0,u.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Re&&(0,u.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Re&&(0,u.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,u.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Ie,onChange:ce=>He(ce.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,u.jsx)(Zt.PaymentElement,{onReady:()=>le("ready"),onLoadError:()=>{le("load_error"),zs(yn(w),"stripe","apm")},onChange:ce=>{De(!!ce.complete)},options:{layout:Ci,fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,y.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,u.jsx)(Si,{testId:`flopay-stripe-method-pay-${e}`,onClick:()=>{_e()},disabled:!ae||!Ee||z||E||Ze!=="ready",color:S,borderRadius:A,style:_,children:z?"Processing\u2026":`Pay with ${(0,y.getStripeMethodDisplayName)(e)}`}),P&&(0,u.jsx)($o,{margin:"0.75rem 0 0",children:P})]})}function Ec({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:i,stripeInstance:c,paymentElementBaseOptions:p,futureUseSession:d,onTokenizedBody:g,onErrorChange:b,onButtonClick:T,onDecline:E,runBeforeButtonClick:S,onLoadStateChange:A,isProcessing:_=!1,submitButtonColor:P="#4A49FF",submitButtonBorderRadius:w=8,submitButtonStyle:K,buttonAppearance:k,themeId:ge,onExpandApm:z,expandedApmMethod:X}){let{emitInstrument:Se}=(0,s.useContext)(or),[ae,De]=(0,s.useState)(null),[Ze,le]=(0,s.useState)(null),Ie=(0,s.useRef)(!1),{request:He,collect:Re,finish:Ee}=zo();(0,s.useEffect)(()=>{i.length>0&&c?A?.("ready"):c||A?.("loading")},[i.length,c,A]);let _e=(0,s.useCallback)(async ee=>{if(!c||Ie.current||_)return;Ie.current=!0,le(ee);let he=S?await S("card"):{proceed:!0};if(!he.proceed){Ie.current=!1,le(null);return}T?.("card");let U=he.sessionId??e,we=he.nonce??t,ie=ho([he.accountPatch?.firstName,he.accountPatch?.lastName].filter(Boolean).join(" ")||r),Te=Un({email:he.accountPatch?.email?.trim()||n?.trim(),firstName:he.accountPatch?.firstName?.trim()||ie.firstName,lastName:he.accountPatch?.lastName?.trim()||ie.lastName});if(!(0,y.isValidEmail)(Te.email)){le(null);let We=await Re((0,y.getStripeMethodDisplayName)(ee),Te);if(!We){Ie.current=!1;return}Te=We,le(ee)}let te=Te.email,at=Un({...he.accountPatch,...Te});try{if(b?.(null),!U||!(0,y.isValidEmail)(te))throw new Error("Missing sessionId or email for payment.");await o?.(Te);let We=await Ti(a,Se,U,we??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,paymentMethodId:null,intentKind:"payment"});if(We.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let je=We.clientSecret;Kt(Fr,{clientSecret:je,sessionId:U,nonce:we,accountPatch:at,paymentMethodType:ee,gateway:"stripe"});let{error:ot,paymentIntent:Ke}=await c.confirmPayment({clientSecret:je,confirmParams:{return_url:window.location.href,payment_method_data:{type:ee,billing_details:{name:[Te.firstName,Te.lastName].filter(Boolean).join(" "),...te?{email:te}:{}}}},redirect:"if_required"});if(ot){Kt(Fr);let vt=ot.message??"Payment failed.";b?.(vt),E?.(mn("card",vt,{code:ot.code})),await Ai({billingApiUrl:a,sessionId:U,nonce:we,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,providerDeclineReason:ot.code??"provider_declined"}});return}let it=Ke?.status;if(!ba(it)){Kt(Fr);let vt=it==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(vt),E?.(mn("card",vt,{code:it??"missing_payment_intent"}));return}Kt(Fr);let $e=typeof Ke?.payment_method=="string"?Ke.payment_method:Ke?.payment_method?.id;g({id:$e??Ke?.id,type:"card",threeDSecureActionResultTokenId:Ke?.id,gateway:"stripe",paymentMethodType:ee},{accountPatch:at,paymentMethodCategory:"apm",sessionId:U,nonce:we})}catch(We){b?.(We instanceof Error?We.message:"Payment failed. Please try again.")}finally{Ie.current=!1,le(null)}},[c,_,S,T,e,t,n,Re,a,Se,r,o,g,b,E]),[ce,de]=(0,s.useState)(null),Pe=z?X??null:ce,Ae=(0,s.useCallback)(ee=>{Ie.current||_||Pe&&Pe!==ee||((0,y.needsStripeMethodExplicitConfirm)(ee)?z?z(ee):de(ee):_e(ee))},[Pe,_,_e,z]),J=(0,s.useMemo)(()=>ce?Dc(p,ce,d):null,[ce,p,d]);return(0,u.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:He?(0,u.jsx)(qo,{identity:He.identity,methodLabel:He.methodLabel,onComplete:Ee,onCancel:()=>Ee(null)},He.id):i.map(ee=>{let he=X===ee,U=Ze===ee,we=Ze!==null&&Ze!==ee||X!=null&&X!==ee;return(0,u.jsxs)(s.default.Fragment,{children:[(0,u.jsx)(bi,{method:ee,themeId:ge,submitting:U,disabled:we,highlighted:he,hasNextStep:(0,y.needsStripeMethodExplicitConfirm)(ee),onClick:()=>Ae(ee),backgroundColor:k?.backgroundColor,borderColor:k?.borderColor,textColor:k?.textColor,borderRadius:k?.borderRadius,fontFamily:k?.fontFamily}),!z&&ce===ee&&J&&c&&(0,u.jsx)(Zt.Elements,{stripe:c,options:J,children:(0,u.jsx)(Os,{method:ee,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:g,onErrorChange:b,onDecline:E,onCancel:()=>de(null),runBeforeButtonClick:S,onButtonClick:T,isProcessing:_,submitButtonColor:P,submitButtonBorderRadius:w,submitButtonStyle:K})},ee)]},ee)})})}function sp({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:a,onComplete:i,onError:c,onDecline:p,onTokenizedBody:d,firstName:g,lastName:b,chv:T,className:E,submitLabel:S,isProcessing:A,error:_,onErrorChange:P,showPayPal:w=!0,showStripe:K=!0,walletPresentation:k="auto",enabledPaymentMethods:ge,enabledPaymentMethodCountries:z,showApplePay:X=!0,showGooglePay:Se=!0,layout:ae="default",theme:De,buttonsTheme:Ze,buttonsStyles:le,appearance:Ie,cardButtonContent:He,cardBackButtonContent:Re,cardTitleContent:Ee,showSecurityFooter:_e,onButtonClick:ce,onBeforeButtonClick:de,onBuyerIdentityReady:Pe,enableAVS:Ae,cardFieldOrder:J,cardPreFormSlot:ee,avsLayout:he="row",country:U,zip:we,addressLine1:ie,addressLine2:Te,city:te,state:at,onCountryChange:We,onZipChange:je,avsCheck:ot,checkoutType:Ke,checkoutLayout:it,totalAmount:$e=0,currency:vt="usd",initialCardOpen:Lt=!1,directPaypal:ht,isSubscription:Tt=!1,session:V,dataAttachmentPending:be=!1,dataAttachmentRequiresIdentity:Qe=!1,debug:Z=!1}){let Le=Kr(),bt=ei(),Ye=(0,s.useContext)(Pr),{emitInstrument:_t}=(0,s.useContext)(or),j=(0,s.useRef)(null);j.current||(j.current=oi());let h=j.current,[,C]=(0,s.useState)(0),Y=(0,s.useRef)(null);Y.current||(Y.current=Gr());let W=Y.current,ve=(0,s.useMemo)(()=>({browser:W,capability:h,presentationMode:"popup"}),[W,h]),x=V??Ye.session,B=(0,s.useMemo)(()=>({futureUse:x?.futureUse,futureUseUnsupported:x?.futureUseUnsupported}),[x?.futureUse,x?.futureUseUnsupported]),ue=x?.gateways?.paypal?.providerObjectType??ht?.providerObjectType,D=be||Ye.claimPending===!0,Me=Qe||Ye.claimRequiresIdentity===!0,st=D&&!Me,yt=Kl(),Ct=n||yt,[Be,Tn]=(0,s.useState)(!1),[Vn,gn]=(0,s.useState)(null),[jt,jn]=(0,s.useState)(U??""),[$n,vn]=(0,s.useState)(we??""),[Dt,dt]=(0,s.useState)(ie??""),[nt,An]=(0,s.useState)(Te??""),[Mt,Hn]=(0,s.useState)(te??""),[hn,$t]=(0,s.useState)(at??""),[en,cr]=(0,s.useState)(""),[Qn,tn]=(0,s.useState)({}),xt=(0,s.useRef)(we??""),nn=(0,s.useRef)(U??""),sn=(0,s.useRef)(ie??""),Nt=(0,s.useRef)(Te??""),cn=(0,s.useRef)(te??""),zt=(0,s.useRef)(at??""),ln=(0,s.useRef)(""),Ut=(0,s.useRef)({});(0,s.useEffect)(()=>{let l=(I,oe,Ve,fe,Ne)=>{if(Ut.current[I])return;let Jt=oe?.trim();!Jt||Jt===Ve.current||(Ve.current=Jt,fe(Jt),Ne?.(Jt))};l("country",U,nn,jn,We),l("zip",we,xt,vn,je),l("addressLine1",ie,sn,dt),l("addressLine2",Te,Nt,An),l("city",te,cn,Hn),l("state",at,zt,$t)},[U,we,ie,Te,te,at,We,je]);let me=(0,s.useMemo)(()=>(0,y.resolveAVSConfig)(Ae),[Ae]),dr=me!==null,ur=(0,s.useMemo)(()=>(0,y.isAuthorizationOnlySession)(V),[V]),pr=!!V?.vault?.html,rn=!!V?.gateways?.pcivault,Mn=cs(V),ze=!!(V?.gateways?.stripe?.enabledPaymentMethods??ge)?.includes("card")||eo(V),mt=pr||ze||rn,v=!!(K&&mt&&e),[ut,pe]=(0,s.useState)(()=>ae!=="buttons"||Lt?e??null:null),[Cn,Wn]=(0,s.useState)(0),Gt=ae!=="buttons"||Lt||!!e&&ut===e,xn=V?.captureMethod,ft=(0,s.useRef)(Le);(0,s.useEffect)(()=>{ft.current=Le},[Le]);let[mr,po]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!v||!e||!Gt){po(null);return}let l=ft.current?ft.current.cardCapture({sessionId:e,captureMethod:xn}):new Sr.PciVaultCardCapture({sessionId:e,captureMethod:xn,billingApiUrl:Ct,telemetry:r});return po({sessionId:e,captureMethod:xn,billingApiUrl:Ct,telemetry:r,capture:l}),()=>{l.unmount()}},[v,e,Gt,xn,Ct,r]);let Ft=v&&e&&Gt&&mr?.sessionId===e&&mr.captureMethod===xn&&mr.billingApiUrl===Ct&&mr.telemetry===r?mr.capture:null,Fn=(0,s.useMemo)(()=>{let l=jt,I=me?(0,y.isAVSFieldVisible)(me.postal_code,l):!1;return op(l,$n,I)},[me,jt,$n]),{avsInvalid:wr,invalidAvsFields:er}=(0,s.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!v||!me)return{avsInvalid:!1,invalidAvsFields:l};let I=jt,oe=(Ne,Jt)=>(0,y.isAVSFieldVisible)(Ne,I)&&!Jt.trim(),Ve={line1:oe(me.address_line_1,Dt),city:oe(me.city,Mt),state:oe(me.state,hn),zip:Fn.empty||Fn.malformed};return{avsInvalid:Ve.line1||Ve.city||Ve.state||Ve.zip,invalidAvsFields:Ve}},[v,me,jt,Dt,Mt,hn,Fn]),[Yt,yr]=(0,s.useState)(!1),[Bn,Or]=(0,s.useState)(!1),[Dn,kr]=(0,s.useState)(!1),[Rr,Lr]=(0,s.useState)({line1:!1,city:!1,state:!1}),Kn=(0,s.useRef)(!1),tr=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Nr=(0,s.useRef)(!1),Ot=(0,s.useCallback)(l=>{tr.current[l]=!0,Nr.current=!0},[]),kn=(0,s.useCallback)(l=>!Kn.current&&tr.current[l],[]),nr=(0,s.useCallback)(l=>{kn(l)&&Lr(I=>I[l]?I:{...I,[l]:!0})},[kn]),[Ur,zr]=(0,s.useState)(()=>Fs(V?.vault)),[lt,dn]=(0,s.useState)(Lt&&mt?"card":"buttons"),[un,Rn]=(0,s.useState)(null),mo=lt==="expanding"||lt==="card",_r=V?.gateways?.stripe&&!Mn?"stripe":void 0,Qr=(0,s.useCallback)(()=>{_t?.({class:"card_surface",provider:_r})},[_r,_t]),_n=(0,s.useRef)(null),pn=(0,s.useCallback)(l=>{_n.current&&clearTimeout(_n.current),_n.current=setTimeout(()=>{_n.current=null,l()},Da)},[]);(0,s.useEffect)(()=>()=>{_n.current&&clearTimeout(_n.current)},[]);let qr=(0,s.useCallback)(()=>{Qr(),pe(e??null),Wn(l=>l+1),dn("expanding"),pn(()=>dn("card"))},[pn,Qr,e]),On=(0,s.useCallback)(()=>{dn("collapsing"),pn(()=>dn("buttons"))},[pn]),L=(0,s.useCallback)(l=>{Rn(l),dn("apm-expanding"),pn(()=>dn("apm-form"))},[pn]),q=(0,s.useCallback)(()=>{dn("apm-collapsing"),pn(()=>{dn("buttons"),Rn(null)})},[pn]);(0,s.useEffect)(()=>{ae==="buttons"&&Lt&&mt&&(pe(e??null),dn("card"))},[ae,Lt,mt,e]);let[re,$]=(0,s.useState)(null),gt=(0,s.useRef)(!1),It=(0,s.useRef)(null),se=(0,s.useRef)("idle"),[Xe,Q]=(0,s.useState)(!1),f=(0,s.useRef)(Xe);f.current=Xe;let[m,N]=(0,s.useState)(()=>ht?.existingOrderId?{orderId:ht.existingOrderId,attempts:1}:null),H=(0,s.useRef)(m);(0,s.useEffect)(()=>{H.current=m},[m]);let Ce=(0,s.useRef)(null),xe=(0,s.useMemo)(()=>{if(Pe||Ye.claimBuyerIdentity||V?.buyerIdentified!==!1||!e||!t)return;let l=`${Ct}|${e}|${t}`;Ce.current?.key!==l&&(Ce.current={key:l,claim:No(new Sr.PaymentAPI(Ct,{telemetry:!1}),e,t,{...a?{userId:a}:{},...g?{firstName:g}:{},...b?{lastName:b}:{}})});let I=Ce.current.claim;return async oe=>{await I(oe)}},[Pe,Ye.claimBuyerIdentity,V?.buyerIdentified,e,t,Ct,a,g,b]),et=Pe??Ye.claimBuyerIdentity??xe,Pt=_??Vn,Oe=(0,s.useMemo)(()=>(0,y.resolveTheme)(De),[De]),F=(0,s.useMemo)(()=>{let l=Oe?.buttonsLayout??(0,y.resolveButtonsLayoutTheme)(Ze);return le?{...l,...le,cardButton:{...l.cardButton,...le.cardButton},cardFormContainer:{...l.cardFormContainer,...le.cardFormContainer},backButton:{...l.backButton,...le.backButton},backButtonIcon:{...l.backButtonIcon,...le.backButtonIcon},submitButton:{...l.submitButton,...le.submitButton},title:{...l.title,...le.title}}:l},[Oe,Ze,le]),St=Ie??Oe?.appearance,Fe=(0,s.useMemo)(()=>ea({appearance:St,buttonsStyles:F,layout:ae}),[St,F,ae]),ke=Ye.inlineSessionPatchProcessing??!1,G=(A??Be)||ke,ye=Ct.replace(/\/+$/,""),ne=(0,s.useMemo)(()=>us({userId:a,email:o,firstName:g,lastName:b,country:U,zip:we},Qn),[a,o,g,b,U,we,Qn]),wt=[ne.firstName,ne.lastName].filter(l=>!!l?.trim()).join(" "),Ge=!(0,y.isValidEmail)(ne.email?.trim()),fr=(0,s.useRef)(null);v&&fr.current===null&&(fr.current=Ge);let In=v&&(fr.current??Ge),Vi=(0,s.useMemo)(()=>ap(en,In),[en,In]),Ro=Vi.empty||Vi.malformed,Gn=(0,s.useMemo)(()=>Le?Le.getRawProvider():null,[Le]),Js=(0,s.useMemo)(()=>bt?bt.getRawProvider():null,[bt]),oa=$e||100,_o=vt.toLowerCase(),ji=(0,s.useMemo)(()=>St?(0,Sr.toStripeAppearance)(St):null,[St]),Io=ji,Zs=(0,s.useMemo)(()=>{let l=ji??{},I=l.rules??{};return{...l,rules:{...I,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...I[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...I[".AccordionItemContents"]??{}}}}},[ji]),Qs=(0,s.useMemo)(()=>({...Vl($e,x?.captureMethod,B),currency:_o,...Io?{appearance:Io}:null}),[$e,_o,x?.captureMethod,B,Io]),$i=(0,y.resolveSetupFutureUsage)(B,"paypal","paypal"),el=(0,s.useMemo)(()=>({mode:"payment",amount:oa,currency:_o,captureMethod:"manual",...$i?{setupFutureUsage:$i}:null,...Io?{appearance:Io}:null}),[oa,_o,$i,Io]),qe=(0,s.useCallback)(l=>{gn(l),P?.(l)},[P]),Hi=(0,s.useRef)(""),[tl,pd]=(0,s.useState)(!1),Wi=(0,s.useCallback)(()=>{pd(!0)},[]);(0,s.useEffect)(()=>{if(!v||!In||!et||!tl||Ro||Hi.current)return;let l=Un({email:(0,y.isValidEmail)(ne.email?.trim())?ne.email?.trim():ln.current.trim(),firstName:ne.firstName?.trim(),lastName:ne.lastName?.trim()});Hi.current=JSON.stringify(l),tn(I=>({...I,...l})),Promise.resolve(et(l)).catch(I=>{Hi.current="",qe(I instanceof Error?I.message:"Failed to attach buyer details.")})},[v,In,et,tl,Ro,ne.email,ne.firstName,ne.lastName,qe]),(0,s.useEffect)(()=>{!v||!Ft||Ft.setCardFieldOrder?.(J??null,me==null&&!In)},[v,Ft,J,me,In]),(0,s.useEffect)(()=>{(lt==="expanding"||lt==="collapsing"||lt==="apm-expanding"||lt==="apm-collapsing")&&qe(null)},[lt,qe]);let Ir=(0,s.useCallback)((l,I,oe)=>{p?.(mn(l,I,oe))},[p]),Eo=(0,s.useCallback)((l,I,oe)=>{let Ve=oe?.popupBlocked??io(I);Ve&&h.markBlocked()&&C(pt=>pt+1);let fe=oo(Ds(l),Ve,W.inAppBrowser),Ne=Mr(I),Jt=(Ne?.toLowerCase()==="error"?void 0:Ne)??bo(oe?.code)??"external_payment_method_failed",br=new y.FloPayError(fe,"api_error",{code:"external_payment_method_failed",param:l,details:{providerCode:Jt,popupBlocked:Ve,inAppBrowser:W.inAppBrowser,appFamily:W.appFamily,popupCapability:h.current(),presentationMode:oe?.presentationMode??"popup"}});oe?.telemetryReported||yn(Le)?.error(Xo({...ve,presentationMode:oe?.presentationMode??"popup"},{errorCode:Ve?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:oe?.provider??(l==="paypal"?"paypal":"stripe"),paymentMethodCategory:oe?.paymentMethodCategory??(l==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:oe?.terminalReason??(Ve?"popup_blocked":"provider_error")})),$(null),ae==="buttons"&&(dn("buttons"),Rn(null)),qe(fe),c?.(br),console.error("[FloPay] External payment method failed:",{method:l,code:Jt,popupBlocked:Ve})},[W,ve,Le,ae,c,h,qe]);(0,s.useEffect)(()=>{if(!v||!e){zr(null);return}let l=Fs(V?.vault);if(l){zr(l);return}if(!Gt){zr(null);return}zr(null);let I=!0;return new Sr.PaymentAPI(ye).getVaultCapture(e,t).then(oe=>{if(!I)return;let Ve=Fs(oe);Ve?zr(Ve):qe("Failed to load the secure card form.")}).catch(oe=>{I&&qe(oe instanceof Error?oe.message:"Failed to load the secure card form.")}),()=>{I=!1}},[v,Gt,Cn,e,V?.vault,ye,t,qe]);let gr=(0,s.useRef)({onComplete:i,onError:c,updateError:qe,emitDecline:Ir,resolvedAccount:ne,avsConfig:me,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:ye,captureMethod:V?.captureMethod,paymentId:V?.paymentId,authorizationExpiresAt:V?.authorizationExpiresAt,serverSideCardGateway:Mn});gr.current={onComplete:i,onError:c,updateError:qe,emitDecline:Ir,resolvedAccount:ne,avsConfig:me,avsCheckProp:ot,sessionId:e,nonce:t,baseUrl:ye,captureMethod:V?.captureMethod,paymentId:V?.paymentId,authorizationExpiresAt:V?.authorizationExpiresAt,serverSideCardGateway:Mn};let Ki=(0,s.useRef)(!1),nl=(0,s.useCallback)(()=>{let l=gr.current,I=l.resolvedAccount.email?.trim(),oe=(0,y.isValidEmail)(I)?I:ln.current.trim();if(!(0,y.isValidEmail)(oe))return null;let Ve=l.resolvedAccount.firstName?.trim(),fe=l.resolvedAccount.lastName?.trim(),Ne=nn.current.trim()||l.resolvedAccount.country?.trim()||"",Jt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.state,Ne):!1,br=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_1,Ne):!1,pt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.postal_code,Ne):!1,kt=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.city,Ne):!1,Et=l.avsConfig?(0,y.isAVSFieldVisible)(l.avsConfig.address_line_2,Ne):!1,qt=br&&!Jt&&pt?(0,y.getStateFromPostalCode)(Ne,(xt.current??"").trim()):null,Vr=Jt?zt.current:qt;return{accountData:{userId:l.resolvedAccount.userId??"",email:oe,...Ve?{firstName:Ve}:{},...fe?{lastName:fe}:{},...pt&&xt.current?{zip:xt.current}:{},...kt&&cn.current?{city:cn.current}:{},...Vr?{state:Vr}:{},...br&&sn.current?{addressLine1:sn.current}:{},...Et&&Nt.current?{addressLine2:Nt.current}:{},...Ne?{country:Ne}:{}},...l.avsCheckProp===void 0?{}:{avsCheck:l.avsCheckProp},...l.avsConfig?{avsConfig:{country:(0,y.isAVSFieldVisible)(l.avsConfig.country,Ne),postal_code:pt,address_line_1:br,address_line_2:Et,city:kt,state:Jt}}:{}}},[]),rl=(0,s.useRef)(D);rl.current=D,(0,s.useEffect)(()=>{D||Pt!==vc||gr.current.updateError(null)},[D,Pt]),(0,s.useEffect)(()=>{!v||!Ft||Ft.setSubmitGate?.(wr||D||Ro||Xe)},[v,Ft,wr,D,Ro,Xe]),(0,s.useEffect)(()=>{if(!v||!Ft)return;Ki.current=!1;let l=null,I=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null,se.current="idle",$(null)},400)},oe=Ft.on("submitting",()=>{yr(!0),It.current&&clearTimeout(It.current),se.current="validation-window",It.current=setTimeout(()=>{It.current=null,se.current==="validation-window"&&(se.current="processing")},Ku),$("processing");let pt=gr.current;if(!pt.sessionId||!pt.nonce)return;let kt=nl();if(!kt){pt.updateError("Enter a valid email address."),se.current="idle",$(null);return}new Sr.PaymentAPI(pt.baseUrl).patchAccountSnapshot(pt.sessionId,pt.nonce,kt,{telemetryMode:"best_effort"}).catch(Et=>{if(!Yu(Et))return;let qt=Et instanceof Error?Et.message:"Please check your billing address and try again.";pt.updateError(qt),se.current="idle",$(null),pt.onError?.(Et instanceof y.FloPayError?Et:new y.FloPayError(qt,"api_error"))})}),Ve=Ft.on("complete",async pt=>{if(Ko(pt.sessionId??gr.current.sessionId),se.current="terminal",Q(!1),$("success"),await new Promise(Vr=>setTimeout(Vr,600)),Ki.current)return;Ki.current=!0;let kt=gr.current,Et=(0,y.isAuthorizationOnlySession)(kt)||pt.outcome==="authorized",qt=kt.serverSideCardGateway?{}:{paymentIntentId:pt.intentId};gr.current.onComplete?.(Et?{status:"authorized",...qt,paymentId:pt.paymentId??kt.paymentId,sessionId:pt.sessionId??kt.sessionId,authorizationExpiresAt:pt.authorizationExpiresAt??kt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...qt,checkoutMethod:"card"})}),fe=Ft.on("decline",pt=>{let kt=gr.current,Et=pt.message??"Your payment was declined. Please try another card or contact your bank.";se.current="terminal",Q(!1),kt.updateError(Et),$("error");let qt=pt.failureOutcome??(0,y.normalizeCheckoutFailureOutcome)(pt.declineReason)??"authorization_declined";kt.emitDecline("card",Et,{code:qt,declineCode:qt}),I()}),Ne=Ft.on("error",pt=>{let kt=gr.current,Et=pt.message??"There was a problem processing your payment. Please try again.";se.current="terminal",Q(!1),kt.updateError(Et),$("error"),kt.onError?.(new y.FloPayError(Et,"api_error",{code:pt.failureOutcome??"capture_failed"})),I()}),Jt=Ft.on("challenge_dismissed",()=>{It.current&&(clearTimeout(It.current),It.current=null),se.current="processing",Q(!0),$(null)}),br=Ft.on("blocked",()=>{if(f.current){gr.current.updateError(Gu);return}if(!rl.current){yr(!0);return}Wi(),gr.current.updateError(vc)});return()=>{l&&(clearTimeout(l),l=null),It.current&&(clearTimeout(It.current),It.current=null),se.current="idle",Q(!1),$(null),oe(),Ve(),fe(),Ne(),Jt(),br()}},[v,Ft,Wi,nl]);let Er=!!ht?.clientId,aa=Array.isArray(ge),za=aa&&ge.length>0,ol=aa&&ge.includes("paypal"),qa=(0,s.useRef)(null);qa.current===null&&(qa.current=Hu());let To=qa.current?"redirect":ti(W,k,h.current()),{expressMethods:Va,paymentElementMethods:ia}=(0,s.useMemo)(()=>(0,y.partitionStripeMethods)(ge,{excludePaypal:Er}),[ge,Er]),al=Er||!!bt||ol&&To==="redirect",md=(0,s.useMemo)(()=>al?Va.filter(l=>l!=="paypal"):Va,[Va,al]),yd=(0,s.useMemo)(()=>{let l=[];return X&&l.push("apple_pay"),Se&&l.push("google_pay"),l},[X,Se]),Ao=aa?md:yd,fd=K&&Ao.length>0,Gi=dr?jt:U,ja=(0,s.useMemo)(()=>{let l=Gi?.trim().toUpperCase();return l?z?ia.filter(I=>{let oe=z[I];return!oe||oe.length===0||oe.includes(l)}):(0,y.filterStripeMethodsByCountry)(ia,Gi):ia},[ia,Gi,z]),Yi=(0,s.useMemo)(()=>({mode:"payment",amount:oa,currency:_o,paymentMethodCreation:"manual",appearance:Zs}),[oa,_o,Zs]),[il,sl]=(0,s.useState)("loading"),[ll,cl]=(0,s.useState)("loading"),[dl,ul]=(0,s.useState)("loading"),[gd,Xi]=(0,s.useState)(!1),[pl,Ji]=(0,s.useState)("loading"),[Zi,hd]=(0,s.useState)();(0,s.useEffect)(()=>{hd(Gr())},[]);let $a=Zi?.inAppBrowser,Ha=Zi?ni(Zi,ht?.approvalPresentation,ue??(Tt?"subscription":"order")):"popup",ml=w&&(Er||(aa?ol:$a===!1)),yl=K&&fd,sa=(!st||!!Ye.waitForDataAttachment)&&ml&&Er,fl=pl==="retrying"||pl==="exhausted",la=null;K&&(bt?la=Js:To==="redirect"&&(la=Gn));let gl=(0,s.useMemo)(()=>({...ve,presentationMode:To}),[ve,To]),ca=!st&&ml&&!!la&&(!Er||fl),Mo=!st&&yl&&!!Gn,da=!st&&K&&za&&ja.length>0&&!!Gn,bd=sa&&!fl?gd:ca&&Is(il),Pd=Mo&&Is(ll),vd=da&&dl!=="load_error",hl=l=>l==="loading"||l==="ready",bl=sa||ca&&hl(il)||Mo&&hl(ll)||da&&dl!=="load_error",Wa=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Wa.current){if(!K&&!w){Wa.current=!0;let l=new y.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(l),qe(l.message)}else if(!K&&w&&!Er){Wa.current=!0;let l=new y.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(l),qe(l.message)}else if($a!==void 0&&!st&&!mt&&!bl){Wa.current=!0;let l=new y.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?.(l),qe(l.message)}}},[K,w,Er,$a,st,mt,bl,c,qe]);let Pl=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(Pl.current||!za)return;let l=[];X!==!0&&l.push("showApplePay"),Se!==!0&&l.push("showGooglePay"),l.length!==0&&(Pl.current=!0,console.warn(`[FloPay] ${l.join(" / ")} ${l.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.`))},[za,X,Se]);let vl=(0,s.useCallback)((l,I)=>Ye.applyInlineSessionPatch?Ye.applyInlineSessionPatch(l).then(oe=>({error:null,sessionId:oe.sessionId||e,nonce:oe.session?.clientSecret||t})).catch(oe=>{let Ve=kc(I,oe);return qe(Ve.message),c?.(Ve),{error:Ve,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ye.applyInlineSessionPatch,t,c,e,qe]),hr=(0,s.useCallback)(async l=>{if(l!=="card"&&st&&await Ye.waitForDataAttachment?.(),!de)return{proceed:!0};try{let I=await de({method:l,sessionId:e||void 0,createSession:Ye.inlineSessionDraft});if(I===!1)return{proceed:!1};if(I&&typeof I=="object"){I.account&&tn(Ve=>({...Ve??{},...I.account}));let oe=await vl(I,l);return oe.error?{proceed:!1,accountPatch:I.account}:{proceed:!0,accountPatch:I.account,sessionId:oe.sessionId,nonce:oe.nonce}}return{proceed:!0}}catch(I){let oe=kc(l,I);return qe(oe.message),c?.(oe),{proceed:!1}}},[vl,Ye.inlineSessionDraft,Ye.waitForDataAttachment,st,de,c,e,qe]),Cl=(0,s.useCallback)(async(l,I)=>{if(gt.current)return;gt.current=!0,Tn(!0),$("processing"),qe(null);let oe=I?.sessionId??e,Ve=I?.nonce??t,fe=us(ne,I?.accountPatch),Ne=I?.completionPaymentMethodId??Pa(l),Jt=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,br=Qu(l),pt=I?.presentationMode?hi(yn(Le),{...ve,presentationMode:I.presentationMode}):void 0,kt=()=>{_t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:br}),pt?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",...Cr,requestCategory:"process_payment"})};try{let Et=new Sr.PaymentAPI(ye),qt=await Et.processPayment(fe.userId??"",{sessionId:oe,nonce:Ve,paymentMethodCategory:I?.paymentMethodCategory??tp(l),tokenizedData:Jt,accountData:{...I?.accountPatch,userId:fe.userId??"",email:fe.email??"",firstName:fe.firstName||void 0,lastName:fe.lastName||void 0,...me?(()=>{let Bt=nn.current,Tr=(0,y.isAVSFieldVisible)(me.state,Bt),Xn=(0,y.isAVSFieldVisible)(me.address_line_1,Bt),Ar=(0,y.isAVSFieldVisible)(me.postal_code,Bt),go=Xn&&!Tr&&Ar?(0,y.getStateFromPostalCode)(Bt,(xt.current??"").trim()):null,ga=Tr?zt.current:go;return{country:Bt,...Ar&&xt.current?{zip:xt.current}:{},...(0,y.isAVSFieldVisible)(me.city,Bt)&&cn.current?{city:cn.current}:{},...ga?{state:ga}:{},...Xn&&sn.current?{addressLine1:sn.current}:{},...(0,y.isAVSFieldVisible)(me.address_line_2,Bt)&&Nt.current?{addressLine2:Nt.current}:{}}})():{}},chv:T,avsCheck:ot??!1,checkoutType:Ke,checkoutLayout:it,avsConfig:me?{country:(0,y.isAVSFieldVisible)(me.country,nn.current),postal_code:(0,y.isAVSFieldVisible)(me.postal_code,nn.current),address_line_1:(0,y.isAVSFieldVisible)(me.address_line_1,nn.current),address_line_2:(0,y.isAVSFieldVisible)(me.address_line_2,nn.current),city:(0,y.isAVSFieldVisible)(me.city,nn.current),state:(0,y.isAVSFieldVisible)(me.state,nn.current)}:void 0}),Vr=async Bt=>{let Tr=(0,y.isAuthorizationOnlySession)(V)||Bt?.status==="authorized";Ko(oe),pt?.terminal({outcome:"payment_succeeded",...Cr}),$("success"),N(null),await new Promise(go=>setTimeout(go,600));let Xn;typeof Bt?.paymentId=="string"?Xn=Bt.paymentId:V?.paymentId&&(Xn=V.paymentId);let Ar;typeof Bt?.authorizationExpiresAt=="string"?Ar=Bt.authorizationExpiresAt:V?.authorizationExpiresAt&&(Ar=V.authorizationExpiresAt),i?.(Tr?{status:"authorized",...Xn===void 0?{}:{paymentId:Xn},sessionId:typeof Bt?.sessionId=="string"?Bt.sessionId:oe,...Ar===void 0?{}:{authorizationExpiresAt:Ar},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Ne,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Ne,checkoutMethod:l.isPaypal?"paypal":"card"})};if(qt.ok){await Vr(qt.status===204?null:await qt.json().catch(()=>null));return}let Yn=await qt.json().catch(()=>null);if(Yn?.type==="paypal_redirect_required"){let Bt=Yn.threeDSecureToken,Tr=Yn.paymentMethodId||l.id||"";if(!Le||!Bt){$("error"),qe("PayPal authorization required but no token provided.");return}try{let Xn=bt?.getRawProvider();if(!Xn){qe("PayPal is not available.");return}let Ar={return_url:window.location.href};Tr&&(Ar.payment_method=Tr);let{error:go}=await Xn.confirmPayment({clientSecret:Bt,confirmParams:Ar,redirect:"if_required"});if(go){$("error");let ga=go.message??"PayPal payment failed.";qe(ga),Ir("paypal",ga,{code:go.code})}}catch(Xn){$("error"),qe(Xn instanceof Error?Xn.message:"PayPal authorization failed.")}return}if(Yn?.type==="paypal_direct_required"){let Bt=Yn.orderId;if(!Bt){$("error"),qe("PayPal retry required but no order id provided.");return}let Tr=H.current?.attempts??0;if(Tr>=2){$("error"),qe("PayPal payment could not be completed after multiple attempts."),Ir("paypal","paypal_direct_required retry limit exceeded");return}Xi(!1),Ji("loading"),N({orderId:Bt,attempts:Tr+1}),$(null);return}if(qt.headers.get(Uu)===zu){let Bt=await qu(Et,oe,Ve);if(Bt!==void 0){await Vr(Bt);return}}(0,y.classifyPaymentRejection)(qt.status,Yn)?pt?.terminal({outcome:"payment_declined",...Cr,terminalReason:"provider_declined"}):kt(),$("error");let xl=Yn?.message??"Payment failed. Please try again.";qe(xl),Ir(l.isPaypal?"paypal":"card",xl,{code:Yn?.code??Yn?.gatewayErrorCode,declineCode:Yn?.declineCode??Yn?.gatewayDeclineReason}),await new Promise(Bt=>setTimeout(Bt,400))}catch(Et){xc(Et)||kt(),$("error"),qe(Et instanceof Error?Et.message:"An unexpected error occurred"),await new Promise(qt=>setTimeout(qt,400))}finally{Tn(!1),$(null),gt.current=!1}},[ye,e,t,ne,me,ot,Ke,it,T,Le,bt,V,i,qe,Ir,_t,ve]),Ln=(0,s.useCallback)((l,I)=>{d?d(l):Cl(l,I)},[d,Cl]),ua=`${Tc}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let l=localStorage.getItem(ua);if(!l)return;let I;try{I=JSON.parse(l)}catch{Kt(ua);return}if(!I||typeof I.createdAt!="number"||Date.now()-I.createdAt<0||Date.now()-I.createdAt>Ac||typeof I.paymentMethodId!="string"||typeof I.providerIntentId!="string"||typeof I.paymentMethodType!="string"||I.sessionId!==e||!t||I.nonce!==t||!Ao.includes(I.paymentMethodType)){Kt(ua);return}Kt(ua),Ln({id:I.paymentMethodId,type:"card",threeDSecureActionResultTokenId:I.providerIntentId,gateway:"stripe",paymentMethodType:I.paymentMethodType},{...I.accountPatch?{accountPatch:I.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Ln,t,e,ua,Ao]);let Sl=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||Sl.current)return;let[l,I,oe]=Ns();if(!l||!I||qa.current||!Le)return;let Ve=Le.getRawProvider();if(!Ve)return;let fe=kt=>{let Et=localStorage.getItem(kt);if(!Et)return null;try{return JSON.parse(Et)}catch{return Kt(kt),null}},Ne=fe(Fr)??fe(hc),Jt;if(Ne?.clientSecret){if(Ne.clientSecret!==I)return;Jt={...Ne.accountPatch?{accountPatch:Ne.accountPatch}:{},...Ne.sessionId?{sessionId:Ne.sessionId}:{},...Ne.nonce?{nonce:Ne.nonce}:{}}}else if(Ne?.sessionId&&Ne.sessionId!==e)return;Sl.current=!0,Kt(Fr),Kt(hc),window.history.replaceState({},"",Us());let br=Ne?.paymentMethodType??Ne?.tokenType??"card",pt="card";(async()=>{if(oe==="failed"){let jr="Payment was declined. Please try again.";qe(jr),Ir(pt,jr);return}let{paymentIntent:kt,error:Et}=await Ve.retrievePaymentIntent(I);if(Et){let jr=Et.message??"Failed to retrieve payment status.";qe(jr),Ir(pt,jr,{code:Et.code});return}let qt=kt?.status,Vr=ba(qt);if(!kt||!Vr){let jr=qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";qe(jr),Ir(pt,jr,{code:qt??"missing_payment_intent"});return}let Yn=typeof kt.payment_method=="string"?kt.payment_method:kt.payment_method?.id;Ln({id:Yn??Ne?.paymentMethodId??Ne?.tokenId??kt.id,type:"card",threeDSecureActionResultTokenId:kt.id,gateway:Ne?.gateway??"stripe",paymentMethodType:br},Jt)})()},[e,Ln,Le,qe,Ir]);let Qi=(0,s.useCallback)(l=>{l.preventDefault()},[]);if(!(v||Le!==null))return(0,u.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let pa=ae==="buttons",Nn=St?.variables,Cd=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),es=Nn?.colorBackground,Sd=es&&!Cd.has(es)?es:void 0,ma=F.cardInputBorder??(pa?"#e5e7eb":"#A4A4FF"),wl=Nn?.colorDanger??"#dc2626",Ht=l=>er[l]&&(Rr[l]||Yt),Ka=Ro&&(Dn||Yt),rr=l=>l?wl:ma,Ga=(Fn.malformed||Fn.empty)&&(Bn||Yt),wd=rr(Ga),ts=F.cardFormContainer?.backgroundColor??Sd??(pa?"white":"#EDEDFF"),xo=F.cardInputBackground??Nn?.colorBackground??"white",ns=Do(Re),kl=Do(Ee),Fo=F.nameInput,Rl=F.cardInputFontSize??ip(Fo?.fontSize)??Nn?.fontSizeBase??"16px",_l=typeof Fo?.fontFamily=="string"?Fo.fontFamily:Nn?.fontFamily??"Poppins, sans-serif",Il=Ts(Fo?.fontWeight)??400,kd=F.cardInputColor??(typeof Fo?.color=="string"?Fo.color:void 0)??Nn?.colorText??"#262833",Rd=F.cardInputPlaceholderColor??"#9ca3af",Xt=Nn?.borderRadius??"8px",yo=Nn?.borderRadius??F.cardButton?.borderRadius??Xt,fo=Nn?.colorPrimary??"#4A49FF",_d=Nn?.colorPrimaryHover??Qo(fo,.12),rs=Nn?.colorText??"#262833",os={fontSize:Rl,fontFamily:_l,fontWeight:Il,color:kd,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ya={marginTop:"0.375rem",...os,fontSize:"0.75rem",lineHeight:1.4,color:wl},Id={"--flopay-input-placeholder-color":Rd,"--flopay-input-font-size":Rl,"--flopay-input-font-family":_l,"--flopay-input-font-weight":String(Il)},fa=F.cardFormContainer??{},as=fa.padding??(pa?"0":"1rem"),is=fa.borderRadius??Xt,Ed=Ft&&Ur?(0,u.jsx)(co,{capture:Ft,html:Ur.html,messageToken:Ur.messageToken,expectedOrigin:Ur.expectedOrigin,theme:Fe,submitLabel:S,onReady:()=>{if(!In&&!me||typeof document>"u")return;let l=()=>{let oe=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(oe){Kn.current=!0;try{oe.focus()}finally{Kn.current=!1}}};Nr.current||l()},onError:l=>qe(l),onValidation:l=>{let I=se.current;(I==="idle"||I==="validation-window")&&(qe(l),l&&se.current==="validation-window"&&(It.current&&(clearTimeout(It.current),It.current=null),se.current="idle",$(null)))}}):(0,u.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"}),El=(0,u.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&Qr()},style:{backgroundColor:ts,borderRadius:is,...fa,padding:as,...Id,display:"flex",flexDirection:"column"},children:[(0,u.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 @@ ${yt.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),ua&&po&&(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:v?-2:0},children:[(0,u.jsxs)("button",{type:"button",onClick:Ln,style:{display:"inline-flex",alignItems:"center",gap:ts?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:x.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...x.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...x.backButtonIcon},children:(0,u.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,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Oo,{content:Re})]}),wl?(0,u.jsx)("div",{style:{flex:1}}):(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:x.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...x.title},children:(0,u.jsx)(ga,{content:_e})})]}),!ua&&!wl&&(0,u.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ns,order:v?-3:0,...x.title},children:(0,u.jsx)(ga,{content:_e})}),v&&ee&&(0,u.jsx)("div",{style:{order:-2,width:"100%"},children:ee}),v&&_n&&(0,u.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,u.jsx)("div",{style:{backgroundColor:Mo,border:`1px solid ${rr(Wa)}`,borderRadius:Xt,padding:"10px"},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:en,onChange:l=>{Dt("email"),ln.current=l.target.value,cr(l.target.value)},onPointerDown:()=>Dt("email"),onKeyDown:()=>Dt("email"),onBlur:()=>{Rn("email")&&Rr(!0),ko||Hi()},disabled:G,required:!0,"aria-invalid":Wa||void 0,"aria-describedby":Wa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...rs}})}),Wa&&(0,u.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ma,children:qi.empty?"Email address is required":"Enter a valid email address"})]}),me&&(0,u.jsx)("div",{style:{order:v?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=Vt,E=(fe=!1)=>({backgroundColor:Mo,border:`1px solid ${rr(fe)}`,borderRadius:Xt,marginTop:"0.5rem",padding:"10px"}),ae=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...rs}),je=(0,y.getStateOptions)(l);return(0,u.jsxs)(u.Fragment,{children:[(0,y.isAVSFieldVisible)(me.address_line_1,l)&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)("div",{style:E(jt("line1")),children:(0,u.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:Bt,onChange:fe=>{Dt("line1"),Nt.current.addressLine1=!0,sn.current=fe.target.value,dt(fe.target.value)},onPointerDown:()=>Dt("line1"),onKeyDown:()=>Dt("line1"),onBlur:()=>nr("line1"),disabled:G,required:!0,"aria-invalid":jt("line1")||void 0,"aria-describedby":jt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:ae()})}),jt("line1")&&(0,u.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ma,children:"Street address is required"})]}),(0,y.isAVSFieldVisible)(me.address_line_2,l)&&(0,u.jsx)("div",{style:E(),children:(0,u.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:nt,onChange:fe=>{Nt.current.addressLine2=!0,Lt.current=fe.target.value,Mn(fe.target.value)},disabled:G,"data-testid":"flopay-address-line2",style:ae()})}),((0,y.isAVSFieldVisible)(me.city,l)||(0,y.isAVSFieldVisible)(me.state,l))&&(0,u.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(me.city,l)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Mo,borderTop:`1px solid ${rr(jt("city"))}`,borderRight:`1px solid ${rr(jt("city"))}`,borderBottom:`1px solid ${rr(jt("city"))}`,borderLeft:`1px solid ${rr(jt("city"))}`,padding:"10px",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,...(0,y.isAVSFieldVisible)(me.state,l)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Xt}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Mt,onChange:fe=>{Dt("city"),Nt.current.city=!0,cn.current=fe.target.value,Wn(fe.target.value)},onPointerDown:()=>Dt("city"),onKeyDown:()=>Dt("city"),onBlur:()=>nr("city"),disabled:G,required:!0,"aria-invalid":jt("city")||void 0,"aria-describedby":jt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:ae()})}),(0,y.isAVSFieldVisible)(me.state,l)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:Mo,borderTop:`1px solid ${rr(jt("state"))}`,borderRight:`1px solid ${rr(jt("state"))}`,borderBottom:`1px solid ${rr(jt("state"))}`,borderLeft:`1px solid ${rr(jt("state"))}`,padding:"10px",borderTopRightRadius:Xt,borderBottomRightRadius:Xt,...(0,y.isAVSFieldVisible)(me.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${rr(jt("state")||jt("city"))}`}:{borderRadius:Xt}},children:je?(0,u.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:bn,onChange:fe=>{Dt("state"),Nt.current.state=!0,Ut.current=fe.target.value,$t(fe.target.value)},onPointerDown:()=>Dt("state"),onKeyDown:()=>Dt("state"),onBlur:()=>nr("state"),disabled:G,autoComplete:"billing address-level1",required:!0,"aria-invalid":jt("state")||void 0,"aria-describedby":jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...ae(),cursor:"pointer"},children:[(0,u.jsx)("option",{value:"",children:(0,y.getStateLabel)(l)}),je.map(fe=>(0,u.jsx)("option",{value:fe.code,children:fe.name},fe.code))]}):(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,y.getStateLabel)(l),autoComplete:"billing address-level1",value:bn,onChange:fe=>{Dt("state"),Nt.current.state=!0,Ut.current=fe.target.value,$t(fe.target.value)},onPointerDown:()=>Dt("state"),onKeyDown:()=>Dt("state"),onBlur:()=>nr("state"),disabled:G,required:!0,"aria-invalid":jt("state")||void 0,"aria-describedby":jt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:ae()})})]}),jt("city")&&(0,u.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ma,children:"City is required"}),jt("state")&&(0,u.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ma,children:[(0,y.getStateLabel)(l)," is required"]}),((0,y.isAVSFieldVisible)(me.country,l)||(0,y.isAVSFieldVisible)(me.postal_code,l))&&(0,u.jsxs)("div",{style:{display:"flex",flexDirection:he==="column"?"column":"row",gap:he==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(me.country,l)&&(0,u.jsx)("div",{style:{flex:he==="row"?1:void 0,backgroundColor:Mo,borderTop:`1px solid ${pa}`,borderRight:`1px solid ${pa}`,borderBottom:`1px solid ${pa}`,borderLeft:`1px solid ${pa}`,padding:"10px",...he==="row"&&(0,y.isAVSFieldVisible)(me.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,borderRight:"none"}:{borderRadius:Xt}},children:(0,u.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:Vt,onChange:fe=>{Nt.current.country=!0,nn.current=fe.target.value,jn(fe.target.value),We?.(fe.target.value),Ut.current="",$t("")},disabled:G,autoComplete:"billing country","data-testid":"flopay-country",style:{...ae(),cursor:"pointer"},children:[Vt===""?(0,u.jsx)("option",{value:"",children:"Select country"}):null,y.COUNTRY_OPTIONS.map(fe=>(0,u.jsxs)("option",{value:fe.code,children:[fe.flag," ",fe.name]},fe.code))]})}),(0,y.isAVSFieldVisible)(me.postal_code,l)&&(0,u.jsx)("div",{style:{flex:he==="row"?1:void 0,backgroundColor:Mo,border:`1px solid ${Sd}`,padding:"10px",...he==="row"&&(0,y.isAVSFieldVisible)(me.country,l)?{borderRadius:"0",borderTopRightRadius:Xt,borderBottomRightRadius:Xt}:{borderRadius:Xt}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,y.getPostalCodeLabel)(Vt),autoComplete:"billing postal-code",value:Hn,onChange:fe=>{Dt("zip"),Nt.current.zip=!0,xt.current=fe.target.value,Cn(fe.target.value),Ve?.(fe.target.value)},onPointerDown:()=>Dt("zip"),onKeyDown:()=>Dt("zip"),onBlur:()=>{Rn("zip")&&Lr(!0)},disabled:G,required:Bn.required,"aria-invalid":Ka||void 0,"aria-describedby":Ka?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:ae()})})]}),Ka&&(0,u.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ma,children:Bn.empty?`${(0,y.getPostalCodeLabel)(l)} is required`:Zu(l)})]})})()}),v&&Ed,Pt&&(0,u.jsx)($o,{margin:"0.75rem 0",styleOverride:x.errorBanner,children:Pt})]}),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"},_l=l=>Z?!w||!Tr?(0,u.jsx)("pre",{"data-testid":l,style:Ga,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":l,style:Ga,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${w}`,` directPaypalConfigured=${Tr}`,` inAppBrowserDetected=${String($a)}`,` shouldRenderDirectPayPal=${ia}`,` shouldRenderStripePayPal=${la}`,` hasPaypalStripeInstance=${!!Xs}`].join(`
39
- `)}):null,Tl=l=>Z?!K||!Yn?(0,u.jsx)("pre",{"data-testid":l,style:Ga,children:"FloPay/Stripe-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":l,style:Ga,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${K}`,` currency=${vt}`,` amountInCents=${ra}`,` enabledPaymentMethods: ${JSON.stringify(ge??[])}`,` enabledPaymentMethodsProvided=${oa}`,` hasEnabledMethods=${Ua}`,` expressMethods: ${JSON.stringify(qa)}`,` walletExpressMethods: ${JSON.stringify(To)}`,` paymentElementMethods: ${JSON.stringify(aa)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Va)}`,` hasStripeInstance=${!!Yn}`,` shouldRenderWallets=${Ao}`,` shouldRenderPaymentElement=${ca}`].join(`
40
- `)}):null,Al=lt==="apm-expanding"||lt==="apm-form"||lt==="apm-collapsing",Fo;lt==="apm-expanding"?Fo=vc:lt==="apm-collapsing"&&(Fo=Cc);let Ya=un?Bc(Gi,un,B):null;if(oe==="buttons"){let l=lt==="buttons"||lt==="expanding"||lt==="apm-expanding",E=lt==="expanding"||lt==="card"||lt==="collapsing",ae=He===void 0?{boxSizing:"border-box",height:Xo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},je;lt==="expanding"||lt==="apm-expanding"?je=Ku:(lt==="collapsing"||lt==="apm-collapsing")&&(je=Wu);let fe;return lt==="expanding"?fe=vc:lt==="collapsing"&&(fe=Cc),(0,u.jsxs)("form",{onSubmit:Zi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Jo,{}),re&&(0,u.jsx)(qn,{status:re,errorMessage:Pt,authorized:ur}),(0,u.jsxs)("div",{style:{display:"grid"},children:[(0,u.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!je?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!je?Yu:{},...je?{animation:je,pointerEvents:"none"}:{}},children:[_l("flopay-direct-paypal-gate-debug"),Tl("flopay-stripe-gate-debug"),ia&&ht&&(0,u.jsxs)(u.Fragment,{children:[m&&(0,u.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,u.jsx)(va.Provider,{value:h,children:(0,u.jsx)(Sa,{sessionId:e,nonce:t,billingApiUrl:Ct,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,clientId:ht.clientId,environment:ht.environment,currency:vt.toUpperCase(),isSubscription:_t,providerObjectType:ue,approvalPresentation:ja==="popup"?void 0:ja,onTokenizedBody:Nn,onComplete:i,onErrorChange:qe,onDecline:p,onTechnicalFailure:Eo,onButtonClick:ce,runBeforeButtonClick:hr,isProcessing:G,onLoadStateChange:Yi,onInitializationStateChange:Xi,session:F,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),la&&(0,u.jsx)(Zt.Elements,{stripe:sa,options:Qs,children:(0,u.jsx)(kc,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,onTokenizedBody:Nn,onErrorChange:qe,isProcessing:G,onButtonClick:ce,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:hr,onLoadStateChange:il,placeholderBorderRadius:mo,popupCapabilityOwner:h,externalTelemetryContext:fl,presentationMode:_o})}),Ao?(0,u.jsx)(Zt.Elements,{stripe:Yn,options:Zs,children:(0,u.jsx)(Ic,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,intentKind:$e>0?"payment":"setup",expressMethods:To,onTokenizedBody:Nn,onErrorChange:qe,onButtonClick:ce,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:hr,onLoadStateChange:ll,placeholderBorderRadius:mo,popupCapabilityOwner:h,externalTelemetryContext:ve})}):null,!Ao&&ml?(0,u.jsx)("div",{style:{height:Xo,borderRadius:mo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ca&&(0,u.jsx)(Ec,{sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,paymentElementMethods:Va,stripeInstance:Yn,paymentElementBaseOptions:Gi,futureUseSession:B,onTokenizedBody:Nn,onErrorChange:qe,onButtonClick:ce,onDecline:p,runBeforeButtonClick:hr,onLoadStateChange:dl,isProcessing:G,submitButtonColor:yo,submitButtonBorderRadius:Xt,submitButtonStyle:x.submitButton,onExpandApm:L,expandedApmMethod:un,themeId:De,buttonAppearance:{backgroundColor:x.cardButton?.backgroundColor,borderColor:x.cardInputBorder,textColor:x.cardButton?.color,borderRadius:mo}}),v&&(0,u.jsx)("button",{type:"button",onClick:async()=>{G||!(await hr("card")).proceed||(ce?.("card"),Vr())},disabled:G,style:{width:"100%",...ae,...x.cardButton,...zs({themeBundle:Oe,resolvedPrimaryColor:yo,resolvedBorderRadius:Xt,submitButtonStyle:x.submitButton,explicitPrimaryColor:Un?.colorPrimary}),fontSize:x.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:G?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:G?.6:1},onMouseEnter:Ne=>{!G&&(Oe||Un?.colorPrimary)&&(Ne.currentTarget.style.backgroundColor=Rd)},onMouseLeave:Ne=>{(Oe||Un?.colorPrimary)&&(Ne.currentTarget.style.backgroundColor=yo)},onMouseDown:Ne=>{Ne.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ne=>{Ne.currentTarget.style.transform="scale(1)"},children:(0,u.jsx)(Do,{content:He})}),Pt&&lt==="buttons"&&(0,u.jsx)($o,{margin:"0.25rem 0",styleOverride:x.errorBanner,children:Pt})]}),v&&E&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...fe?{animation:fe}:{},...lt==="collapsing"?{pointerEvents:"none"}:{}},children:El}),K&&Al&&un&&Ya&&Yn&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...Fo?{animation:Fo}:{},...lt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:es,borderRadius:as,...ya,padding:os},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:V,style:{display:"inline-flex",alignItems:"center",gap:ts?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:x.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...x.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...x.backButtonIcon},children:(0,u.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,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Oo,{content:Re})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:x.titleFontSize??"1.05rem",color:ns,paddingRight:80,...x.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(un)}`})]}),(0,u.jsx)(Zt.Elements,{stripe:Yn,options:Ya,children:(0,u.jsx)(Ds,{method:un,sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,onTokenizedBody:Nn,onErrorChange:qe,onDecline:p,onCancel:V,runBeforeButtonClick:hr,onButtonClick:ce,isProcessing:G,submitButtonColor:yo,submitButtonBorderRadius:Xt,submitButtonStyle:x.submitButton,errorText:Pt})},un)]})})]})]})}return Al&&un&&Ya&&Yn&&K?(0,u.jsxs)("form",{onSubmit:Zi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Jo,{}),re&&(0,u.jsx)(qn,{status:re,errorMessage:Pt,authorized:ur}),(0,u.jsx)("div",{style:{...Fo?{animation:Fo}:{},...lt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:es,borderRadius:as,...ya,padding:os},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:V,style:{display:"inline-flex",alignItems:"center",gap:ts?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:x.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...x.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...x.backButtonIcon},children:(0,u.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,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Oo,{content:Re})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:x.titleFontSize??"1.05rem",color:ns,paddingRight:80,...x.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(un)}`})]}),(0,u.jsx)(Zt.Elements,{stripe:Yn,options:Ya,children:(0,u.jsx)(Ds,{method:un,sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,onTokenizedBody:Nn,onErrorChange:qe,onDecline:p,onCancel:V,runBeforeButtonClick:hr,onButtonClick:ce,isProcessing:G,submitButtonColor:yo,submitButtonBorderRadius:Xt,submitButtonStyle:x.submitButton,errorText:Pt})},un)]})})]}):(0,u.jsxs)("form",{onSubmit:Zi,className:_,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Jo,{}),re&&(0,u.jsx)(qn,{status:re,errorMessage:Pt,authorized:ur}),(0,u.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[_l("flopay-direct-paypal-gate-debug-default"),Tl("flopay-stripe-gate-debug-default"),ia&&ht&&(0,u.jsxs)(u.Fragment,{children:[m&&(0,u.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,u.jsx)(va.Provider,{value:h,children:(0,u.jsx)(Sa,{sessionId:e,nonce:t,billingApiUrl:Ct,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,clientId:ht.clientId,environment:ht.environment,currency:vt.toUpperCase(),isSubscription:_t,providerObjectType:ue,approvalPresentation:ja==="popup"?void 0:ja,onTokenizedBody:Nn,onComplete:i,onErrorChange:qe,onDecline:p,onTechnicalFailure:Eo,onButtonClick:ce,runBeforeButtonClick:hr,isProcessing:G,onLoadStateChange:Yi,onInitializationStateChange:Xi,session:F,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),la&&(0,u.jsx)(Zt.Elements,{stripe:sa,options:Qs,children:(0,u.jsx)(kc,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,onTokenizedBody:Nn,onErrorChange:qe,isProcessing:G,onButtonClick:ce,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:hr,onLoadStateChange:il,placeholderBorderRadius:mo,popupCapabilityOwner:h,externalTelemetryContext:fl,presentationMode:_o})}),Ao&&(0,u.jsx)(Zt.Elements,{stripe:Yn,options:Zs,children:(0,u.jsx)(Ic,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,intentKind:$e>0?"payment":"setup",expressMethods:To,onTokenizedBody:Nn,onErrorChange:qe,onButtonClick:ce,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:hr,onLoadStateChange:ll,placeholderBorderRadius:mo,popupCapabilityOwner:h,externalTelemetryContext:ve})}),ca&&(0,u.jsx)(Ec,{sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Ct,paymentElementMethods:Va,stripeInstance:Yn,paymentElementBaseOptions:Gi,futureUseSession:B,onTokenizedBody:Nn,onErrorChange:qe,onButtonClick:ce,onDecline:p,runBeforeButtonClick:hr,onLoadStateChange:dl,isProcessing:G,submitButtonColor:yo,submitButtonBorderRadius:Xt,submitButtonStyle:x.submitButton,themeId:De,onExpandApm:L,expandedApmMethod:un,buttonAppearance:{backgroundColor:x.cardButton?.backgroundColor,borderColor:x.cardInputBorder,textColor:x.cardButton?.color,borderRadius:mo}})]}),v&&(bd||hd||Pd)&&(0,u.jsx)(wi,{label:"or pay with card"}),v&&El]})}var O=require("react/jsx-runtime"),ea=44,Ws="flopay_checkout_saved_payment_resume",Fi=new Map,Mi=new Map;function Dc(e,t){t.settled&&t.consumers===0&&Fi.get(e)===t&&Fi.delete(e)}function rp(e,t,n){let r=Mi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Mi.set(e,a);let i=()=>{Mi.get(e)===a&&Mi.delete(e)};return o.then(i,i),o}function Da(e){return new Promise(t=>setTimeout(t,e))}function xi(e,t,n){let r=oi({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:rt.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Oa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function qs(e,t,n,r,o,a){let i=xi(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Oa(i)}function Oc(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 Lc(e,t,n,r,o){let a=(0,rt.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 rt.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof rt.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 qc(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 Vs(e){return!e||e.data.stripe?.publishableKey?!1:!!qc(e)?.clientId}var op={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function ap(e){return new Xr.FloPay(op,{publishableKey:"provider_unavailable",...e})}async function $s(e,t){let{publishableKey:n,paypalPublishableKey:r}=ks(e);return{...await Rs({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Ks(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ip(){if(!Ks())return null;try{let e=window.sessionStorage.getItem(Ws);return e?JSON.parse(e):null}catch{return null}}function Nc(e){if(Ks())try{window.sessionStorage.setItem(Ws,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function js(){if(Ks())try{window.sessionStorage.removeItem(Ws)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function sp(){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 Uc(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 Hs(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function lp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function zc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function cp(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 Bi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:i,loading:c,error:p,onComplete:d,onError:g,onInstrument:b,onDecline:T,onCountryChange:_,onZipChange:S,showPayPal:A=!0,showStripe:I=!0,walletPresentation:P="auto",enabledPaymentMethods:w,showApplePay:K=!0,showGooglePay:k=!0,debug:ge=!1,layout:q,theme:X,buttonsTheme:Se,buttonsStyles:oe,cardButtonContent:De,cardBackButtonContent:Ze,cardTitleContent:le,showSecurityFooter:Ee,onButtonClick:He,onBeforeButtonClick:Re,enableAVS:_e,cardFieldOrder:Ie,cardPreFormSlot:ce,avsLayout:de,submitLabel:Pe,className:Ae,initialErrorMessage:J=null,initialPayPalOrderId:ee,children:he,checkoutMode:U,confirmLabel:we,renderConfirmButton:ie,onSessionCompleted:Te}){let te=(0,rt.resolveBillingApiUrl)(r),at=(0,R.useMemo)(()=>(0,rt.resolveTheme)(X),[X]),We=a??at?.appearance,Ve=n?"embedded_checkout":"standard_checkout",ot=Hs(he,q),[Ke,it]=(0,R.useState)(null),[$e,vt]=(0,R.useState)(null),Ot=(0,R.useRef)(null),ht=(0,R.useRef)(null),_t=(0,R.useRef)(0),[z,be]=(0,R.useState)(null),Qe=(0,R.useRef)(null),[Z,Le]=(0,R.useState)(null),bt=(0,R.useMemo)(()=>n?Ho(n):"",[n]),Ye=n?`create:${bt}`:`session:${e??""}`,It=zc(Z),$=(0,R.useRef)(new Set),h=(0,R.useRef)(Ye),C=(0,R.useRef)(Ye);Po(()=>{C.current=Ye,h.current!==Ye&&(h.current=Ye,$.current.clear())},[Ye]);let Y=(0,R.useCallback)(L=>{if(C.current===Ye){if(ys.has(L.name)){if($.current.has(L.name))return;$.current.add(L.name)}Je(()=>b?.(L))}},[Ye,b]),W=Vo(Y,Ye),ve=(0,R.useRef)(!1),F=(0,R.useCallback)(L=>{if(ve.current)return;let V=L.gateway||!It?L:{...L,gateway:It};Y(V)},[Y,It]);(0,R.useEffect)(()=>{W({class:"lifecycle",name:"checkout.mount"})},[W]);let[B,ue]=(0,R.useState)(e??""),D=e??B,Me=n?"":D,[st,yt]=(0,R.useState)(!0),[Ct,Be]=(0,R.useState)(null),[An,$n]=(0,R.useState)(0),[hn,Vt]=(0,R.useState)("full"),[jn,Hn]=(0,R.useState)(!1),[Cn,Bt]=(0,R.useState)(J),[dt,nt]=(0,R.useState)(null),[Mn,Mt]=(0,R.useState)(null),[Wn,bn]=(0,R.useState)(!1),[$t,en]=(0,R.useState)(void 0),[cr,Qn]=(0,R.useState)(""),[tn,xt]=(0,R.useState)(!1),[nn,sn]=(0,R.useState)(!1),[Lt,cn]=(0,R.useState)(!1),Ut=(0,R.useRef)(null),ln=(0,R.useRef)(0),Nt=(0,R.useRef)(void 0),[me,dr]=(0,R.useState)("loading"),[ur,pr]=(0,R.useState)(0),rn=(0,R.useRef)(!1),xn=(0,R.useRef)(!1),kn=(0,R.useRef)(!1),ze=(0,R.useRef)(null),mt=(0,R.useRef)(null),v=(0,R.useMemo)(()=>({checkoutMode:U??hn,layout:lp(he,q)}),[U,he,hn,q]),ut=(0,R.useRef)(d);ut.current=d;let pe=(0,R.useRef)(g);pe.current=g;let Sn=(0,R.useRef)(T);Sn.current=T;let Kn=(0,R.useCallback)(L=>mi(ze,async V=>{try{return await L(V)}catch(re){throw V.aborted?so(re):re}}),[]);(0,R.useEffect)(()=>()=>{ze.current?.abort(),ze.current=null},[]);let Gt=(0,R.useCallback)((L,V)=>{Ot.current=L,vt(L),Qe.current=V,be(V)},[]),Fn=(0,R.useCallback)(()=>{let L=ht.current;L&&(ht.current=null,L.destroy())},[]);(0,R.useEffect)(()=>{fn($e)?.setCheckoutContext(v),z&&z!==$e&&fn(z)?.setCheckoutContext(v)},[$e,z,v]);let ft=(0,R.useRef)(Te);ft.current=Te;let mr=(0,R.useCallback)(L=>{dr(L),!(L!=="exhausted"||kn.current)&&(kn.current=!0,pe.current?.(new rt.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),uo=(0,R.useCallback)(()=>{dr("retrying"),pr(L=>L+1)},[]);(0,R.useEffect)(()=>{dr("loading"),pr(0),kn.current=!1},[D]),(0,R.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:rt.SDK_VERSION,checkout_type:Ve,checkout_layout:ot,billing_api_url:te})},[ot,Ve,te]);let Ft=(0,R.useMemo)(()=>n?Ho(n,!0):"",[n]),Bn=(0,R.useMemo)(()=>cr===Ft?$t:void 0,[$t,cr,Ft]),kr=(0,R.useMemo)(()=>n?cs(n,Bn):void 0,[n,Bn]),er=U??kr?.checkoutMode??"full",Yt=(0,R.useMemo)(()=>kr?{...kr,checkoutMode:er}:void 0,[kr,er]);(0,R.useEffect)(()=>{en(void 0),Qn(Ft),Nt.current=void 0,Ut.current=null,cn(!1)},[Ft]),(0,R.useEffect)(()=>{Bt(J)},[J]);let yr=(0,R.useCallback)((L,V,re)=>{Je(()=>{Sn.current?.(yn(L,V,re))})},[]),Dn=(0,R.useCallback)(async(L,V)=>{Bt(null),Mt(null),bn(!1),nt("processing");let re=V?.sessionId??L.id,j=L.clientSecret||t,gt=zc(L),Et=Ot.current??Qe.current,se=fn(Et),Xe=Et?null:xi(te,o,v),Q={log:Oe=>{se?se.log(Oe):Xe?.log(Oe)},error:Oe=>{se?se.error(Oe):Xe?.error(Oe)},terminal:Oe=>{se?se.terminal(Oe):Xe?.terminal(Oe)},performance:Oe=>{se?se.performance(Oe):Xe?.performance(Oe)},now:()=>se?.now()??Xe?.now()??0,elapsed:Oe=>se?.elapsed(Oe)??Math.max(0,(Xe?.now()??Oe)-Oe)},f=Q.now(),m=!!(V?.initialAutoProcessingError||V?.initialAutoProcessingPending),N=!1,H,Ce=()=>{N||(N=!0,m=!0,H=Q.now(),Q.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},xe=!1,et=()=>{xe||(xe=!0,Q.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),Q.performance({stage:"processing",durationMs:Q.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),H!==void 0&&Q.performance({stage:"recovery",durationMs:Q.elapsed(H),durationMode:"machine",paymentMethodCategory:"saved"}))};Q.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ve.current=!0;try{Q.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ve.current=!1}W({class:"lifecycle",name:"payment.processing.started",provider:gt}),m&&Ce();let Pt;try{let Oe=oc(V?.initialAutoProcessingError),x=V?.initialAutoProcessingError?.type==="3ds_required"&&!V.initialAutoProcessingError.threeDSecureToken&&V.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:V.initialAutoProcessingError.nextActionRedirectUrl}:null,St,Fe=ke=>(Ce(),Kn(G=>Ko(ke,{billingApiUrl:te,sessionId:re,nonce:j,session:L,signal:G})));if(x)St=await Fe(x);else if(Oe)Ce(),Oe.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Nc({sessionId:re,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),St=await Kn(ke=>fi(Oe,{flopay:Ot.current,paypalFlopay:Qe.current,attempt3DS:V?.attempt3DS,billingApiUrl:te,sessionId:re,session:L,telemetry:!1,signal:ke})),Oe.type==="paypal_redirect_required"&&js();else if(V?.initialAutoProcessingPending){let ke=V.initialAutoProcessingPending,G=new Xr.PaymentAPI(te,{telemetry:!1}),ye=await Kn(Ge=>G.waitForCheckoutSessionCompletion(ke.sessionId,{initialDelayMs:ke.retryAfterMs,nonce:j,statusUrl:ke.statusUrl,signal:Ge})),ne=no(ye,L),wt=ye.autoProcessingError?.type==="3ds_required"&&ye.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ye.autoProcessingError.nextActionRedirectUrl}:null;if(wt)St=await Fe(wt);else{if(!jr(ne))throw No(ne);St=$r(ne,re)}}else{if(V?.initialAutoProcessingError)throw Fr(V.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:V.initialAutoProcessingError.checkoutMethod});if(V?.fromCreateSession)return V?.fallbackToFull&&(Vt("full"),Uc("full")),!1;{let ke=await Go({billingApiUrl:te,sessionId:re,session:L,nonce:j,telemetry:!1});ke.type==="success"?St=ke.result:ke.type==="next_action_required"?St=await Fe(ke):(Ce(),ke.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Nc({sessionId:re,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),St=await Kn(G=>fi(ke,{flopay:Ot.current,paypalFlopay:Qe.current,attempt3DS:V?.attempt3DS,billingApiUrl:te,sessionId:re,session:L,telemetry:!1,signal:G})),ke.type==="paypal_redirect_required"&&js())}}re&&Wo(re),et(),m&&(Q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),Q.terminal({outcome:St.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),bn(St.status==="authorized"),nt("success"),await Da(600),Pt=()=>ut.current?.(St)}catch(Oe){let x=eo(Ea(Oe),re);if(x.code==="three_ds_aborted")return!1;let St=x.checkoutMethod??Ia;Bt(x.message),Mt(x.message),bn(!1),V?.fallbackToFull&&(Q.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Vt("full"),Uc("full")),et();let Fe=x.statusCode===void 0?void 0:(0,rt.telemetryStatusClass)(x.statusCode,"unknown"),ke=Fe==="4xx"?{requestCategory:"process_payment",statusClass:Fe}:{},G=Fe===void 0||Fe==="4xx";if(G&&(x.telemetryOutcome==="payment_declined"||!!(x.declineCode||x.code?.toLowerCase().includes("declin"))))Q.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ke});else if(G&&(x.telemetryOutcome==="validation_rejected"||x.type==="validation_error"))Q.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ke});else{let wt=(0,rt.classifyTelemetryFailure)(Oe,m?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ge=x.telemetryRequestCategory??"process_payment";ve.current=!0;try{Q.error({...wt,...x.telemetryFailureCategory?{failureCategory:x.telemetryFailureCategory}:{},stage:m?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ge})}finally{ve.current=!1}W({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ge,provider:gt})}return Je(()=>pe.current?.(x)),yr(St,x,{code:x.code,declineCode:x.declineCode}),nt("error"),await Promise.allSettled([Da(400),V?.ensureProvidersReady?V.ensureProvidersReady():Promise.resolve()]),m&&(Q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{et(),Xe&&Oa(Xe),nt(null),Mt(null)}return Je(Pt),!0},[yr,W,t,te,Kn,o,v]);(0,R.useEffect)(()=>{if(typeof window>"u"||xn.current)return;let L=new URLSearchParams(window.location.search),V=L.get("payment_intent_client_secret");if(!V)return;let re=ip();re&&(xn.current=!0,(async()=>{let j,gt=0;Bt(null),Mt(null),nt("processing"),Hn(!0);try{if(L.get("redirect_status")==="failed")throw Object.assign(new rt.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Et,paypalFlopay:se}=await Rs({publishableKey:re.publishableKey,paypalPublishableKey:re.paypalPublishableKey,billingApiUrl:te,locale:i,telemetry:o});j=fn(se??Et),j?.setCheckoutContext(v),gt=j?.now()??0,j?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),j?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Xe=(se??Et)?.getRawProvider();if(!Xe)throw Object.assign(new rt.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:Q,error:f}=await Xe.retrievePaymentIntent(V);if(f)throw Object.assign(new rt.FloPayError(f.message??"Failed to retrieve PayPal payment status.","api_error",{code:f.code}),{checkoutMethod:"paypal"});let m=Ul(Q?.status);if(!Q||m==="failed")throw Object.assign(new rt.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let N=typeof Q.payment_method=="string"?Q.payment_method:Q.payment_method?.id,H=m;if(re.sessionId){let et=(await new Xr.PaymentAPI(te,{telemetry:!1}).getUnifiedCheckoutSession(re.sessionId)).data.session;if(et&&et.status!=="complete"){let Pt=await Go({billingApiUrl:te,sessionId:re.sessionId,session:et,telemetry:!1,tokenizedData:{id:N??Q.id,type:"card",threeDSecureActionResultTokenId:Q.id,isPaypal:!0}});if(Pt.type!=="success")throw Object.assign(new rt.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});H=Pt.result.status}}re.sessionId&&Wo(re.sessionId),j?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),j?.performance({stage:"redirect_resume",durationMs:j.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),j?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),nt("success"),await Da(600),Je(()=>ut.current?.({status:H,paymentIntentId:Q.id,paymentMethodId:N,checkoutMethod:"paypal"}))}catch(Et){let se=eo(Ea(Et),re.sessionId),Xe=se.checkoutMethod??"paypal",Q=!!(se.declineCode||se.code?.toLowerCase().includes("declin"));if(j)j.performance({stage:"redirect_resume",durationMs:j.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Q?j.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):j.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(Q){let f=xi(te,o,v);f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Oa(f)}else qs(te,o,v,"REDIRECT_RESUME_FAILED","redirect_resume");Bt(se.message),Mt(se.message),Je(()=>pe.current?.(se)),yr(Xe,se,{code:se.code,declineCode:se.declineCode}),nt("error"),await Da(400)}finally{js(),sp(),nt(null),Mt(null),Hn(!1)}})())},[yr,i,te,o,v]);let Lr=(0,R.useRef)(null),On=(0,R.useMemo)(()=>Yt?Ho(Yt):"",[Yt]),Rr=(0,R.useRef)(Yt);Rr.current=Yt,(0,R.useEffect)(()=>{ue(e??"")},[e]),(0,R.useEffect)(()=>{rn.current=!1,Bt(J),Mt(null),bn(!1),nt(null)},[On,J,e]);async function Ir(L,V,re){let j=xi(te,o,v),gt=new Xr.PaymentAPI(te,{telemetry:!1}),Et=!1;try{let se=L.idempotencyKey===void 0?void 0:(0,rt.resolveIdempotencyKey)(L.idempotencyKey),Xe=hs(V,re),Q=bs(V,re);Xe?.canonicalIdentity===re&&Q&&Q.canonicalIdentity===void 0&&(ui(V,re,Q.idempotencyKey),Q={...Q,canonicalIdentity:re});let f=se??(Q?.canonicalIdentity===re?Q.idempotencyKey:void 0),m,N=!1;j.log({name:Xe?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let H=Xe?.sid??null,Ce=null,xe,et,Pt=!1;if(H)try{Ce=await gt.getUnifiedCheckoutSession(H,Xe?.nonce),Xe&&Xe.canonicalIdentity===void 0&&(ec(Ce.data.session,L)?(di(V,re,H,Xe.nonce??Ce.data.session?.clientSecret),Q&&Q.canonicalIdentity===void 0&&(ui(V,re,Q.idempotencyKey),f??(f=Q.idempotencyKey))):(ci(V,re),Q=null,f=se,H=null,Ce=null));let x=Ce?.data.session?.status,St=Ce?.data.session,Fe=St?.clientSecret||Xe?.nonce;if(H&&St?.buyerIdentified===!1&&Fe&&(et=Lo(gt,H,Fe,L.account)),H&&Ce&&x==="complete"){if(Ps(H))return{sid:H,result:Ce};ci(V,re),H=null,Ce=null,N=!0}}catch{j.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Xe?.canonicalIdentity===void 0?(ci(V,re),f=se):li(V,re),H=null}if(!H){!se&&(N||!f)&&(f=(0,rt.resolveIdempotencyKey)(),m=f),f&&ui(V,re,f);let x=j.now(),St=0;j.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Fe={...L,idempotencyKey:f,avsCheck:!!_e,avsConfig:typeof _e=="object"?_e:void 0,checkoutType:"embedded_checkout",checkoutLayout:Hs(he,q)};Object.defineProperty(Fe,Xr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ye=>{St=Math.max(St,ye)}}});let ke=()=>{Oc(j,"session_create",x,St)},G=ye=>{Lc(j,ye,"session_create",x,St)&&W({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,rt.isDetachedSessionEligible)(Fe)){let ye=await gt.createDetachedSession(Fe);ye.claimed.catch(()=>{}),Ce=ye.shell,H=ye.sessionId,et=ye.claim;let ne=j.now();j.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),xe=ye.claimed.then(wt=>{let Ge=wt.data.session?.id??ye.sessionId;return Ge&&di(V,re,Ge,wt.data.session?.clientSecret??ye.nonce),Oc(j,"session_claim",ne),ke(),wt},wt=>{throw li(V,re),Lc(j,wt,"session_claim",ne,0)&&W({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),wt}).finally(()=>Oa(j)),xe.catch(()=>{}),Et=!0,j.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),j.performance({stage:"session_shell",durationMs:j.now()-x,durationMode:"machine",requestCategory:"session_create",attempt:St,statusClass:"2xx",paymentMethodCategory:"card"})}else Ce=await gt.createAndFetchSession(Fe),ke()}catch(ye){throw G(ye),ye}H=Ce.data.session?.id??H??"",H&&!xe&&di(V,re,H,Ce.data.session?.clientSecret)}let Oe=Ce?.data.session;return!et&&H&&Oe?.buyerIdentified===!1&&Oe.clientSecret&&(et=Lo(gt,H,Oe.clientSecret,L.account)),{sid:H??"",result:Ce,sdkGeneratedIdempotencyKey:m,...xe?{claimed:xe}:{},...et?{claim:et}:{},...Pt?{claimRequiresIdentity:!0}:{}}}finally{Et||Oa(j)}}let Nr=(0,R.useRef)(Ir);Po(()=>{Nr.current=Ir},[Ir]);let Gn=(0,R.useCallback)(async(L,V)=>{let re=Rr.current;if(!re)throw new rt.FloPayError("createSession is required to bootstrap checkout.","validation_error");let j=cs(re,L),gt=Ho(j),Et=Ql(j),se=Fi.get(gt);if(!se){let f={canonicalIdentity:gt,promise:Nr.current(j,Et,gt),consumers:0,settled:!1};se=f,Fi.set(gt,f);let m=()=>{f.settled=!0,Dc(gt,f)};f.promise.then(m,m)}se.consumers+=1;let Xe=!1,Q=()=>{Xe||(Xe=!0,se.consumers-=1,Dc(gt,se))};V?.(Q);try{let f=await se.promise;Lr.current=gt,L&&(Qn(Ft),en(Oe=>Ol(Oe,L)));let{sid:m,result:N,claimed:H,claim:Ce,claimRequiresIdentity:xe}=f;if(Nt.current=Ce,cn(xe===!0),it(N),N.data.session&&Le(N.data.session),m&&ue(m),H){ln.current+=1;let Oe=ln.current;Ut.current=H,sn(!0),H.then(x=>{ln.current===Oe&&(Ut.current===H&&(Ut.current=null),it(x),x.data.session&&Le(x.data.session),sn(!1),cn(!1))},x=>{ln.current===Oe&&(Ut.current===H&&(Ut.current=null),sn(!1),cn(!1),Be(x instanceof rt.FloPayError?x:new rt.FloPayError(x instanceof Error?x.message:"Failed to create session","api_error")))})}else ln.current+=1,Ut.current=null,sn(!1),cn(!1);let{flopay:et,paypalFlopay:Pt}=await $s(N,{billingApiUrl:te,locale:i,telemetry:o});return Gt(et,Pt),yt(!1),f}catch(f){throw Lr.current===gt&&(Lr.current=null),f}finally{V||Q()}},[Ft,Gt,i,te,o]),tr=(0,R.useRef)(Dn);tr.current=Dn;let Ur=(0,R.useRef)(Gn);Ur.current=Gn;let Dt=(0,R.useCallback)(async L=>{if(!cp(L)||tn)return{sessionId:B,session:Z};xt(!0);try{let V=await Gn(L);return{sessionId:V.sid,session:V.result.data.session??null}}finally{xt(!1)}},[Gn,tn,B,Z]),Rn=(0,R.useCallback)(async L=>{let V=Nt.current;if(!V)return;let re=ln.current,j=await V(L);ln.current===re&&(it(j),j.data.session&&Le(j.data.session))},[]),nr=(0,R.useCallback)(async()=>{await Ut.current},[]),zr=(0,R.useCallback)(async()=>(await nr(),{proceed:!0}),[nr]);(0,R.useEffect)(()=>{let L=!1,V,re=++_t.current;Fn(),Be(null),$n(0);let j=()=>{L=!0,_t.current===re&&(_t.current+=1,Fn())},gt=Rr.current;if(On&&gt)return Vt(er),yt(!1),Lr.current===On?j:(Le(Ll(gt,U)),(async()=>{let Xe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Q=er==="auto"&&!rn.current&&!Xe;Q&&(Bt(null),Mt(null),nt("processing"));try{let f=await Ur.current(void 0,Ce=>{V=Ce}),m=f.result.data.session??null;mt.current=ks(f.result);let N=Vs(f.result),H=Ps(f.sid||m?.id);if(!L&&Q&&m&&!N&&!H){rn.current=!0,await rp(On,f.sdkGeneratedIdempotencyKey,()=>tr.current(m,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:f.result.autoProcessingError,initialAutoProcessingPending:f.result.autoProcessingPending,autoProcessingAttempted:f.result.autoProcessingAttempted,sessionId:f.sid||m.id}));return}!L&&Q&&((N||H)&&(rn.current=!0),nt(null),Mt(null))}catch(f){if(L)return;let m=Za(f);if(Q&&m==="session_auto_completed"){rn.current=!0,nt("success"),await Da(600),L||(Je(()=>{ut.current?.({status:"succeeded"})}),nt(null),Mt(null));return}Q&&(nt(null),Mt(null));let N=f instanceof rt.FloPayError?f:new rt.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error");Be(N)}finally{V?.(),V=void 0}})(),()=>{j(),V?.()});yt(!0);async function Et(){let Xe=!1,Q=null;try{let f=new Xr.PaymentAPI(te,{telemetry:!1}),m=await f.getUnifiedCheckoutSession(D,t);if(Q=m,L)return;it(m);let N=m.data.session??null;if(Le(N),!N)throw new rt.FloPayError("No session data returned","api_error");let H=N.checkoutMode;if(H==="setup")throw new rt.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(N.status==="authorized"){yt(!1),Je(()=>{ut.current?.($r(N,D)),ft.current?.(N.successUrl??"")});return}if(N.status==="complete"){yt(!1),Je(()=>{ft.current?.(N.successUrl??"")});return}if(N.status==="expired")throw Ja(N);Xe=!0;let Ce=U??H??"full";Vt(Ce),ln.current+=1;let xe=N.clientSecret||t;Nt.current=N.buyerIdentified===!1&&xe?Lo(f,D,xe,{...N.customer?.id?{userId:N.customer.id}:{}}):void 0,sn(!1),cn(!1);let et=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Pt=Vs(m);if(Ce==="auto"&&!rn.current&&!et&&!Pt){rn.current=!0;let Oe=se(m);try{if(await tr.current(N,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Oe,sessionId:D||N.id}),L)return;await Oe,L||yt(!1);return}catch{if(L)return;await Oe,L||yt(!1);return}}await se(m),L||yt(!1)}catch(f){if(L)return;let m=Dl(f,Xe);if(Xe&&W({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),m){let{errorCode:H,stage:Ce,...xe}=m;qs(te,o,v,H,Ce,xe)}if(m?.stage==="provider_load"&&(U??Q?.data.session?.checkoutMode??"full")==="full"&&Bl(Q,A,I)){let H=ap({billingApiUrl:te,locale:i,telemetry:o});ht.current=H,Gt(H,null),$n(1),yt(!1);return}let N=f instanceof rt.FloPayError&&m?.stage!=="provider_load"?f:Fl();N!==f&&Je(()=>pe.current?.(N)),Be(N),yt(!1)}}async function se(Xe){let{flopay:Q,paypalFlopay:f,...m}=await $s(Xe,{billingApiUrl:te,locale:i,telemetry:o});mt.current={publishableKey:m.publishableKey,paypalPublishableKey:m.paypalPublishableKey},Gt(Q,f),$n(0)}return Et(),j},[U,On,er,Me,t,A,I]);let qr=(0,R.useCallback)(async()=>{if(!Ke||An!==1)return;let L=_t.current;$n(2);try{let{flopay:V,paypalFlopay:re}=await $s(Ke,{billingApiUrl:te,locale:i,telemetry:o});if(_t.current!==L)return;Fn(),Gt(V,re),$n(0)}catch(V){if(_t.current!==L)return;let{errorCode:re,stage:j,...gt}=ss(V);qs(te,o,v,re,j,gt)}},[Fn,Gt,i,An,te,o,v,Ke]),lt=!!(D&&(Z?.clientSecret||t)),dn=jn||!lt,un=(0,R.useCallback)(async()=>{if(!(jn||!lt||!Z)){Hn(!0),Bt(null);try{await Dn(Z,{attempt3DS:!0,fallbackToFull:!0,sessionId:D||Z.id})}finally{Hn(!1)}}},[D,jn,lt,Dn,Z]),In=qc(Ke,ee),po=Vs(Ke),Er=(0,R.useMemo)(()=>{if(!(!Ke||!Z||!Ke.data.stripe?.publishableKey))return{billingApiUrl:te}},[Ke,Z,te]),Zr=!!(n&&!he&&q==="buttons"&&Re&&er==="full"),En=!!(D&&(Z?.vault?.html||Qr(Z))),pn=(0,R.useMemo)(()=>({session:Z,loading:st,error:Ct,checkoutMode:hn,inlineSessionDraft:Yt,applyInlineSessionPatch:Zr?Dt:void 0,inlineSessionPatchProcessing:tn,claimPending:nn,claimRequiresIdentity:Lt,claimBuyerIdentity:Rn,waitForDataAttachment:nr}),[Z,st,Ct,hn,Yt,Zr,Dt,tn,nn,Lt,Rn,nr]),Vr=!!n&&q==="buttons"&&!po&&!En&&(!$e||!Er),Ln=dt?(0,O.jsx)(qn,{status:dt,errorMessage:Mn,authorized:Wn}):null;if(st&&!En){if(c)return(0,O.jsxs)(O.Fragment,{children:[c,Ln]});if(q==="buttons"){let L=at?.buttonsLayout?.cardButton?.borderRadius??at?.appearance.variables?.borderRadius??8,V=re=>(0,O.jsx)("div",{style:{height:re,borderRadius:L,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[A&&V(ea),I&&(K||k)&&V(ea),I&&V(ea),(0,O.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ln]})}return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,O.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,O.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ln]})}return Ct?p?(0,O.jsx)(vr.Provider,{value:pn,children:p(Ct)}):(0,O.jsx)(vr.Provider,{value:pn,children:(0,O.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ct.message})}):Vr?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(vr.Provider,{value:pn,children:(0,O.jsx)(up,{onButtonClick:He,showPayPal:A,showStripe:I,showApplePay:K,showGooglePay:k,theme:X,buttonsTheme:Se,buttonsStyles:oe,cardButtonContent:De,cardBackButtonContent:Ze,cardTitleContent:le})}),Ln]}):po&&Z&&In?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(vr.Provider,{value:pn,children:(0,O.jsxs)("div",{className:Ae,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Cn&&(0,O.jsx)($o,{icon:!1,children:Cn}),me==="retrying"&&(0,O.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),me==="exhausted"&&(0,O.jsxs)("div",{role:"alert",children:[(0,O.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,O.jsx)("button",{type:"button",onClick:uo,children:"Retry PayPal"})]}),me!=="exhausted"&&(0,O.jsx)("div",{"aria-hidden":me==="retrying"?!0:void 0,style:me==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,O.jsx)(Zl,{sessionId:D,nonce:Z.clientSecret||void 0,billingApiUrl:te,email:Z.customer?.email||Yt?.account?.email,billingName:[Z.customer?.firstName,Z.customer?.lastName].filter(Boolean).join(" ")||[Yt?.account?.firstName,Yt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Rn,clientId:In.clientId,environment:In.environment,currency:(Z.currency??"usd").toUpperCase(),isSubscription:Z.mode==="subscription",providerObjectType:In.providerObjectType,approvalPresentation:In.approvalPresentation,existingOrderId:In.existingOrderId,onComplete:d,onErrorChange:Bt,onDecline:T,onButtonClick:He,runBeforeButtonClick:zr,onInitializationStateChange:mr,allowAutomaticRetry:ur===0,session:Z,telemetry:o,telemetryContext:v,onInstrument:F,debug:ge},`${Ye}:paypal-init-${ur}`)})]})}),Ln]}):hn==="confirm"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(vr.Provider,{value:pn,children:(0,O.jsx)(ka,{flopay:$e,paypalFlopay:z,options:Er??{billingApiUrl:te},onInstrument:F,children:(0,O.jsxs)("div",{className:Ae,children:[Cn&&(0,O.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Cn}),ie?ie({onConfirm:un,isProcessing:dn}):(0,O.jsx)("button",{type:"button",onClick:un,disabled:dn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:dn?"not-allowed":"pointer",opacity:dn?.6:1},children:jn?"Processing...":we??"Confirm Purchase"})]})},Ye)}),Ln]}):(!$e||!Er)&&!(En&&hn==="full")?(0,O.jsx)(O.Fragment,{children:Ln}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(vr.Provider,{value:pn,children:(0,O.jsxs)(ka,{flopay:$e,paypalFlopay:z,options:Er??{billingApiUrl:te},onInstrument:F,children:[An===1&&(0,O.jsx)("button",{type:"button",onClick:qr,children:"Retry payment methods"}),he?(0,O.jsxs)(O.Fragment,{children:[Cn&&(0,O.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Cn}),(0,O.jsx)(dp,{sessionId:D,nonce:Z?.clientSecret||void 0,billingApiUrl:te,session:Z,submitLabel:Pe,walletPresentation:P,children:he})]}):(0,O.jsx)(Ai,{sessionId:D,nonce:Z?.clientSecret||void 0,telemetry:o,email:Z?.customer?.email||Yt?.account?.email,userId:Z?.customer?.id||Yt?.account?.userId,firstName:Z?.customer?.firstName||Yt?.account?.firstName,lastName:Z?.customer?.lastName||Yt?.account?.lastName,totalAmount:Z?Math.round((0,rt.buildCheckoutDisplayData)(Z).total*100):0,currency:Z?.currency?.toLowerCase()??"usd",onComplete:d,onError:g,onDecline:T,error:Cn,onErrorChange:Bt,showPayPal:A,showStripe:I,walletPresentation:P,enabledPaymentMethods:An?[]:w??Ke?.data.stripe?.enabledPaymentMethods??Z?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:K,showGooglePay:k,layout:q,theme:X,buttonsTheme:Se,buttonsStyles:oe,appearance:We,cardButtonContent:De,cardBackButtonContent:Ze,cardTitleContent:le,onButtonClick:He,onBeforeButtonClick:Re,onBuyerIdentityReady:Rn,enableAVS:_e,...Ie?{cardFieldOrder:Ie}:{},...ce?{cardPreFormSlot:ce}:{},avsLayout:de,country:Z?.customer?.country,city:Z?.customer?.city,state:Z?.customer?.state,onCountryChange:_,onZipChange:S,avsCheck:!!_e,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Hs(he,q),className:Ae,submitLabel:Pe,directPaypal:In,isSubscription:Z?.mode==="subscription",session:Z,dataAttachmentPending:nn,dataAttachmentRequiresIdentity:Lt,debug:ge})]},Ye)}),Ln]})}function dp({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:i}){return(0,O.jsx)(O.Fragment,{children:R.default.Children.map(i,c=>{if(!R.default.isValidElement(c))return c;let p=c.props,d={};return p.sessionId||(d.sessionId=e),!p.nonce&&t&&(d.nonce=t),p.billingApiUrl||(d.billingApiUrl=n),p.submitLabel===void 0&&o!==void 0&&(d.submitLabel=o),p.walletPresentation===void 0&&(d.walletPresentation=a),r?.customer&&(p.email||(d.email=r.customer.email),p.userId||(d.userId=r.customer.id),p.firstName||(d.firstName=r.customer.firstName),p.lastName||(d.lastName=r.customer.lastName)),Object.keys(d).length===0?c:R.default.cloneElement(c,d)})})}function up({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:i,buttonsStyles:c,cardButtonContent:p,cardBackButtonContent:d,cardTitleContent:g}){let[b,T]=(0,R.useState)(!1),_=(0,R.useMemo)(()=>(0,rt.resolveTheme)(a),[a]),S=(0,R.useMemo)(()=>{let w=_?.buttonsLayout??(0,rt.resolveButtonsLayoutTheme)(i);return c?{...w,...c,cardButton:{...w.cardButton,...c.cardButton},cardFormContainer:{...w.cardFormContainer,...c.cardFormContainer},backButton:{...w.backButton,...c.backButton},backButtonIcon:{...w.backButtonIcon,...c.backButtonIcon},submitButton:{...w.submitButton,...c.submitButton},title:{...w.title,...c.title}}:w},[_,i,c]),A=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,I=w=>(0,O.jsx)("div",{style:{height:w,borderRadius:A,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),P=p===void 0?{boxSizing:"border-box",height:ea,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let w=S.cardInputBorder??"#e5e7eb",K=S.cardInputBackground??"white",k=Bo(d),ge=Bo(g);return(0,O.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,O.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,O.jsxs)("button",{type:"button",onClick:()=>T(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:k?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...S.backButton},children:[(0,O.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...S.backButtonIcon},children:(0,O.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,O.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,O.jsx)(Oo,{content:d})]}),ge?(0,O.jsx)("div",{style:{flex:1}}):(0,O.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...S.title},children:(0,O.jsx)(ga,{content:g})})]}),(0,O.jsx)("div",{style:{backgroundColor:K,border:`1px solid ${w}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsxs)("div",{style:{display:"flex"},children:[(0,O.jsx)("div",{style:{flex:1,backgroundColor:K,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{flex:1,backgroundColor:K,borderTop:"none",borderRight:`1px solid ${w}`,borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,O.jsx)("div",{style:{backgroundColor:K,border:`1px solid ${w}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.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,O.jsx)("style",{children:`
38
+ `}),pa&&mo&&(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:v?-2:0},children:[(0,u.jsxs)("button",{type:"button",onClick:On,style:{display:"inline-flex",alignItems:"center",gap:ns?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...F.backButtonIcon},children:(0,u.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,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Lo,{content:Re})]}),kl?(0,u.jsx)("div",{style:{flex:1}}):(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...F.title},children:(0,u.jsx)(ha,{content:Ee})})]}),!pa&&!kl&&(0,u.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:rs,order:v?-3:0,...F.title},children:(0,u.jsx)(ha,{content:Ee})}),v&&ee&&(0,u.jsx)("div",{style:{order:-2,width:"100%"},children:ee}),v&&In&&(0,u.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,u.jsx)("div",{style:{backgroundColor:xo,border:`1px solid ${rr(Ka)}`,borderRadius:Xt,padding:"10px"},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:en,onChange:l=>{Ot("email"),ln.current=l.target.value,cr(l.target.value)},onPointerDown:()=>Ot("email"),onKeyDown:()=>Ot("email"),onBlur:()=>{kn("email")&&kr(!0),Ro||Wi()},disabled:G,required:!0,"aria-invalid":Ka||void 0,"aria-describedby":Ka?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...os}})}),Ka&&(0,u.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:ya,children:Vi.empty?"Email address is required":"Enter a valid email address"})]}),me&&(0,u.jsx)("div",{style:{order:v?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=jt,I=(fe=!1)=>({backgroundColor:xo,border:`1px solid ${rr(fe)}`,borderRadius:Xt,marginTop:"0.5rem",padding:"10px"}),oe=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...os}),Ve=(0,y.getStateOptions)(l);return(0,u.jsxs)(u.Fragment,{children:[(0,y.isAVSFieldVisible)(me.address_line_1,l)&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)("div",{style:I(Ht("line1")),children:(0,u.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:Dt,onChange:fe=>{Ot("line1"),Ut.current.addressLine1=!0,sn.current=fe.target.value,dt(fe.target.value)},onPointerDown:()=>Ot("line1"),onKeyDown:()=>Ot("line1"),onBlur:()=>nr("line1"),disabled:G,required:!0,"aria-invalid":Ht("line1")||void 0,"aria-describedby":Ht("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:oe()})}),Ht("line1")&&(0,u.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:ya,children:"Street address is required"})]}),(0,y.isAVSFieldVisible)(me.address_line_2,l)&&(0,u.jsx)("div",{style:I(),children:(0,u.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:nt,onChange:fe=>{Ut.current.addressLine2=!0,Nt.current=fe.target.value,An(fe.target.value)},disabled:G,"data-testid":"flopay-address-line2",style:oe()})}),((0,y.isAVSFieldVisible)(me.city,l)||(0,y.isAVSFieldVisible)(me.state,l))&&(0,u.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(me.city,l)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${rr(Ht("city"))}`,borderRight:`1px solid ${rr(Ht("city"))}`,borderBottom:`1px solid ${rr(Ht("city"))}`,borderLeft:`1px solid ${rr(Ht("city"))}`,padding:"10px",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,...(0,y.isAVSFieldVisible)(me.state,l)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Xt}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Mt,onChange:fe=>{Ot("city"),Ut.current.city=!0,cn.current=fe.target.value,Hn(fe.target.value)},onPointerDown:()=>Ot("city"),onKeyDown:()=>Ot("city"),onBlur:()=>nr("city"),disabled:G,required:!0,"aria-invalid":Ht("city")||void 0,"aria-describedby":Ht("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:oe()})}),(0,y.isAVSFieldVisible)(me.state,l)&&(0,u.jsx)("div",{style:{flex:1,backgroundColor:xo,borderTop:`1px solid ${rr(Ht("state"))}`,borderRight:`1px solid ${rr(Ht("state"))}`,borderBottom:`1px solid ${rr(Ht("state"))}`,borderLeft:`1px solid ${rr(Ht("state"))}`,padding:"10px",borderTopRightRadius:Xt,borderBottomRightRadius:Xt,...(0,y.isAVSFieldVisible)(me.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${rr(Ht("state")||Ht("city"))}`}:{borderRadius:Xt}},children:Ve?(0,u.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:hn,onChange:fe=>{Ot("state"),Ut.current.state=!0,zt.current=fe.target.value,$t(fe.target.value)},onPointerDown:()=>Ot("state"),onKeyDown:()=>Ot("state"),onBlur:()=>nr("state"),disabled:G,autoComplete:"billing address-level1",required:!0,"aria-invalid":Ht("state")||void 0,"aria-describedby":Ht("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...oe(),cursor:"pointer"},children:[(0,u.jsx)("option",{value:"",children:(0,y.getStateLabel)(l)}),Ve.map(fe=>(0,u.jsx)("option",{value:fe.code,children:fe.name},fe.code))]}):(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,y.getStateLabel)(l),autoComplete:"billing address-level1",value:hn,onChange:fe=>{Ot("state"),Ut.current.state=!0,zt.current=fe.target.value,$t(fe.target.value)},onPointerDown:()=>Ot("state"),onKeyDown:()=>Ot("state"),onBlur:()=>nr("state"),disabled:G,required:!0,"aria-invalid":Ht("state")||void 0,"aria-describedby":Ht("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:oe()})})]}),Ht("city")&&(0,u.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:ya,children:"City is required"}),Ht("state")&&(0,u.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:ya,children:[(0,y.getStateLabel)(l)," is required"]}),((0,y.isAVSFieldVisible)(me.country,l)||(0,y.isAVSFieldVisible)(me.postal_code,l))&&(0,u.jsxs)("div",{style:{display:"flex",flexDirection:he==="column"?"column":"row",gap:he==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,y.isAVSFieldVisible)(me.country,l)&&(0,u.jsx)("div",{style:{flex:he==="row"?1:void 0,backgroundColor:xo,borderTop:`1px solid ${ma}`,borderRight:`1px solid ${ma}`,borderBottom:`1px solid ${ma}`,borderLeft:`1px solid ${ma}`,padding:"10px",...he==="row"&&(0,y.isAVSFieldVisible)(me.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Xt,borderBottomLeftRadius:Xt,borderRight:"none"}:{borderRadius:Xt}},children:(0,u.jsxs)("select",{id:"flopay-billing-country",name:"billing-country",value:jt,onChange:fe=>{Ut.current.country=!0,nn.current=fe.target.value,jn(fe.target.value),We?.(fe.target.value),zt.current="",$t("")},disabled:G,autoComplete:"billing country","data-testid":"flopay-country",style:{...oe(),cursor:"pointer"},children:[jt===""?(0,u.jsx)("option",{value:"",children:"Select country"}):null,y.COUNTRY_OPTIONS.map(fe=>(0,u.jsxs)("option",{value:fe.code,children:[fe.flag," ",fe.name]},fe.code))]})}),(0,y.isAVSFieldVisible)(me.postal_code,l)&&(0,u.jsx)("div",{style:{flex:he==="row"?1:void 0,backgroundColor:xo,border:`1px solid ${wd}`,padding:"10px",...he==="row"&&(0,y.isAVSFieldVisible)(me.country,l)?{borderRadius:"0",borderTopRightRadius:Xt,borderBottomRightRadius:Xt}:{borderRadius:Xt}},children:(0,u.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,y.getPostalCodeLabel)(jt),autoComplete:"billing postal-code",value:$n,onChange:fe=>{Ot("zip"),Ut.current.zip=!0,xt.current=fe.target.value,vn(fe.target.value),je?.(fe.target.value)},onPointerDown:()=>Ot("zip"),onKeyDown:()=>Ot("zip"),onBlur:()=>{kn("zip")&&Or(!0)},disabled:G,required:Fn.required,"aria-invalid":Ga||void 0,"aria-describedby":Ga?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:oe()})})]}),Ga&&(0,u.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:ya,children:Fn.empty?`${(0,y.getPostalCodeLabel)(l)} is required`:rp(l)})]})})()}),v&&Ed,Pt&&(0,u.jsx)($o,{margin:"0.75rem 0",styleOverride:F.errorBanner,children:Pt})]}),Ya={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"},Tl=l=>Z?!w||!Er?(0,u.jsx)("pre",{"data-testid":l,style:Ya,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":l,style:Ya,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${w}`,` directPaypalConfigured=${Er}`,` inAppBrowserDetected=${String($a)}`,` shouldRenderDirectPayPal=${sa}`,` shouldRenderStripePayPal=${ca}`,` hasPaypalStripeInstance=${!!Js}`].join(`
39
+ `)}):null,Al=l=>Z?!K||!Gn?(0,u.jsx)("pre",{"data-testid":l,style:Ya,children:"FloPay/Stripe-debug - not enabled"}):(0,u.jsx)("pre",{"data-testid":l,style:Ya,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${K}`,` currency=${vt}`,` amountInCents=${oa}`,` enabledPaymentMethods: ${JSON.stringify(ge??[])}`,` enabledPaymentMethodsProvided=${aa}`,` hasEnabledMethods=${za}`,` expressMethods: ${JSON.stringify(Va)}`,` walletExpressMethods: ${JSON.stringify(Ao)}`,` paymentElementMethods: ${JSON.stringify(ia)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ja)}`,` hasStripeInstance=${!!Gn}`,` shouldRenderWallets=${Mo}`,` shouldRenderPaymentElement=${da}`].join(`
40
+ `)}):null,Ml=lt==="apm-expanding"||lt==="apm-form"||lt==="apm-collapsing",Bo;lt==="apm-expanding"?Bo=Cc:lt==="apm-collapsing"&&(Bo=Sc);let Xa=un?Dc(Yi,un,B):null;if(ae==="buttons"){let l=lt==="buttons"||lt==="expanding"||lt==="apm-expanding",I=lt==="expanding"||lt==="card"||lt==="collapsing",oe=He===void 0?{boxSizing:"border-box",height:Jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ve;lt==="expanding"||lt==="apm-expanding"?Ve=Zu:(lt==="collapsing"||lt==="apm-collapsing")&&(Ve=Ju);let fe;return lt==="expanding"?fe=Cc:lt==="collapsing"&&(fe=Sc),(0,u.jsxs)("form",{onSubmit:Qi,className:E,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Zo,{}),re&&(0,u.jsx)(zn,{status:re,errorMessage:Pt,authorized:ur}),(0,u.jsxs)("div",{style:{display:"grid"},children:[(0,u.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!Ve?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!Ve?ep:{},...Ve?{animation:Ve,pointerEvents:"none"}:{}},children:[Tl("flopay-direct-paypal-gate-debug"),Al("flopay-stripe-gate-debug"),sa&&ht&&(0,u.jsxs)(u.Fragment,{children:[m&&(0,u.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,u.jsx)(Ca.Provider,{value:h,children:(0,u.jsx)(wa,{sessionId:e,nonce:t,billingApiUrl:Ct,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,clientId:ht.clientId,environment:ht.environment,currency:vt.toUpperCase(),isSubscription:Tt,providerObjectType:ue,approvalPresentation:Ha==="popup"?void 0:Ha,onTokenizedBody:Ln,onComplete:i,onErrorChange:qe,onDecline:p,onTechnicalFailure:Eo,onButtonClick:ce,runBeforeButtonClick:hr,isProcessing:G,onLoadStateChange:Xi,onInitializationStateChange:Ji,session:x,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),ca&&(0,u.jsx)(Zt.Elements,{stripe:la,options:el,children:(0,u.jsx)(Rc,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,onTokenizedBody:Ln,onErrorChange:qe,isProcessing:G,onButtonClick:ce,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:hr,onLoadStateChange:sl,placeholderBorderRadius:yo,popupCapabilityOwner:h,externalTelemetryContext:gl,presentationMode:To})}),Mo?(0,u.jsx)(Zt.Elements,{stripe:Gn,options:Qs,children:(0,u.jsx)(Ic,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,intentKind:$e>0?"payment":"setup",expressMethods:Ao,onTokenizedBody:Ln,onErrorChange:qe,onButtonClick:ce,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:hr,onLoadStateChange:cl,placeholderBorderRadius:yo,popupCapabilityOwner:h,externalTelemetryContext:ve})}):null,!Mo&&yl?(0,u.jsx)("div",{style:{height:Jo,borderRadius:yo,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,da&&(0,u.jsx)(Ec,{sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,paymentElementMethods:ja,stripeInstance:Gn,paymentElementBaseOptions:Yi,futureUseSession:B,onTokenizedBody:Ln,onErrorChange:qe,onButtonClick:ce,onDecline:p,runBeforeButtonClick:hr,onLoadStateChange:ul,isProcessing:G,submitButtonColor:fo,submitButtonBorderRadius:Xt,submitButtonStyle:F.submitButton,onExpandApm:L,expandedApmMethod:un,themeId:De,buttonAppearance:{backgroundColor:F.cardButton?.backgroundColor,borderColor:F.cardInputBorder,textColor:F.cardButton?.color,borderRadius:yo}}),v&&(0,u.jsx)("button",{type:"button",onClick:async()=>{G||!(await hr("card")).proceed||(ce?.("card"),qr())},disabled:G,style:{width:"100%",...oe,...F.cardButton,...qs({themeBundle:Oe,resolvedPrimaryColor:fo,resolvedBorderRadius:Xt,submitButtonStyle:F.submitButton,explicitPrimaryColor:Nn?.colorPrimary}),fontSize:F.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:G?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:G?.6:1},onMouseEnter:Ne=>{!G&&(Oe||Nn?.colorPrimary)&&(Ne.currentTarget.style.backgroundColor=_d)},onMouseLeave:Ne=>{(Oe||Nn?.colorPrimary)&&(Ne.currentTarget.style.backgroundColor=fo)},onMouseDown:Ne=>{Ne.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ne=>{Ne.currentTarget.style.transform="scale(1)"},children:(0,u.jsx)(Oo,{content:He})}),Pt&&lt==="buttons"&&(0,u.jsx)($o,{margin:"0.25rem 0",styleOverride:F.errorBanner,children:Pt})]}),v&&I&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...fe?{animation:fe}:{},...lt==="collapsing"?{pointerEvents:"none"}:{}},children:El}),K&&Ml&&un&&Xa&&Gn&&(0,u.jsx)("div",{style:{gridArea:"1 / 1",...Bo?{animation:Bo}:{},...lt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:ts,borderRadius:is,...fa,padding:as},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:q,style:{display:"inline-flex",alignItems:"center",gap:ns?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...F.backButtonIcon},children:(0,u.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,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Lo,{content:Re})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:rs,paddingRight:80,...F.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(un)}`})]}),(0,u.jsx)(Zt.Elements,{stripe:Gn,options:Xa,children:(0,u.jsx)(Os,{method:un,sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,onTokenizedBody:Ln,onErrorChange:qe,onDecline:p,onCancel:q,runBeforeButtonClick:hr,onButtonClick:ce,isProcessing:G,submitButtonColor:fo,submitButtonBorderRadius:Xt,submitButtonStyle:F.submitButton,errorText:Pt})},un)]})})]})]})}return Ml&&un&&Xa&&Gn&&K?(0,u.jsxs)("form",{onSubmit:Qi,className:E,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Zo,{}),re&&(0,u.jsx)(zn,{status:re,errorMessage:Pt,authorized:ur}),(0,u.jsx)("div",{style:{...Bo?{animation:Bo}:{},...lt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,u.jsxs)("div",{style:{backgroundColor:ts,borderRadius:is,...fa,padding:as},children:[(0,u.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,u.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:q,style:{display:"inline-flex",alignItems:"center",gap:ns?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.backButton},"aria-label":"Back to payment methods",children:[(0,u.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...F.backButtonIcon},children:(0,u.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,u.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,u.jsx)(Lo,{content:Re})]}),(0,u.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:rs,paddingRight:80,...F.title},children:`Pay with ${(0,y.getStripeMethodDisplayName)(un)}`})]}),(0,u.jsx)(Zt.Elements,{stripe:Gn,options:Xa,children:(0,u.jsx)(Os,{method:un,sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,onTokenizedBody:Ln,onErrorChange:qe,onDecline:p,onCancel:q,runBeforeButtonClick:hr,onButtonClick:ce,isProcessing:G,submitButtonColor:fo,submitButtonBorderRadius:Xt,submitButtonStyle:F.submitButton,errorText:Pt})},un)]})})]}):(0,u.jsxs)("form",{onSubmit:Qi,className:E,noValidate:!0,style:{position:"relative"},children:[(0,u.jsx)(Zo,{}),re&&(0,u.jsx)(zn,{status:re,errorMessage:Pt,authorized:ur}),(0,u.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Tl("flopay-direct-paypal-gate-debug-default"),Al("flopay-stripe-gate-debug-default"),sa&&ht&&(0,u.jsxs)(u.Fragment,{children:[m&&(0,u.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,u.jsx)(Ca.Provider,{value:h,children:(0,u.jsx)(wa,{sessionId:e,nonce:t,billingApiUrl:Ct,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,clientId:ht.clientId,environment:ht.environment,currency:vt.toUpperCase(),isSubscription:Tt,providerObjectType:ue,approvalPresentation:Ha==="popup"?void 0:Ha,onTokenizedBody:Ln,onComplete:i,onErrorChange:qe,onDecline:p,onTechnicalFailure:Eo,onButtonClick:ce,runBeforeButtonClick:hr,isProcessing:G,onLoadStateChange:Xi,onInitializationStateChange:Ji,session:x,existingOrderId:m?.orderId,debug:Z},m?.orderId??"fresh")})]}),ca&&(0,u.jsx)(Zt.Elements,{stripe:la,options:el,children:(0,u.jsx)(Rc,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,onTokenizedBody:Ln,onErrorChange:qe,isProcessing:G,onButtonClick:ce,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:hr,onLoadStateChange:sl,placeholderBorderRadius:yo,popupCapabilityOwner:h,externalTelemetryContext:gl,presentationMode:To})}),Mo&&(0,u.jsx)(Zt.Elements,{stripe:Gn,options:Qs,children:(0,u.jsx)(Ic,{sessionId:e,nonce:t,email:ne.email,billingName:wt||void 0,onBuyerIdentityReady:et,billingApiUrl:Ct,intentKind:$e>0?"payment":"setup",expressMethods:Ao,onTokenizedBody:Ln,onErrorChange:qe,onButtonClick:ce,onDecline:p,onTechnicalFailure:Eo,runBeforeButtonClick:hr,onLoadStateChange:cl,placeholderBorderRadius:yo,popupCapabilityOwner:h,externalTelemetryContext:ve})}),da&&(0,u.jsx)(Ec,{sessionId:e,nonce:t,email:ne.email,billingName:[ne.firstName,ne.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Ct,paymentElementMethods:ja,stripeInstance:Gn,paymentElementBaseOptions:Yi,futureUseSession:B,onTokenizedBody:Ln,onErrorChange:qe,onButtonClick:ce,onDecline:p,runBeforeButtonClick:hr,onLoadStateChange:ul,isProcessing:G,submitButtonColor:fo,submitButtonBorderRadius:Xt,submitButtonStyle:F.submitButton,themeId:De,onExpandApm:L,expandedApmMethod:un,buttonAppearance:{backgroundColor:F.cardButton?.backgroundColor,borderColor:F.cardInputBorder,textColor:F.cardButton?.color,borderRadius:yo}})]}),v&&(Pd||bd||vd)&&(0,u.jsx)(ki,{label:"or pay with card"}),v&&El]})}var O=require("react/jsx-runtime"),ta=44,Ks="flopay_checkout_saved_payment_resume",Bi=new Map,xi=new Map;function Oc(e,t){t.settled&&t.consumers===0&&Bi.get(e)===t&&Bi.delete(e)}function lp(e,t,n){let r=xi.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};xi.set(e,a);let i=()=>{xi.get(e)===a&&xi.delete(e)};return o.then(i,i),o}function Oa(e){return new Promise(t=>setTimeout(t,e))}function Fi(e,t,n){let r=ai({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:rt.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function La(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Vs(e,t,n,r,o,a){let i=Fi(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),La(i)}function Lc(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 Nc(e,t,n,r,o){let a=(0,rt.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 rt.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof rt.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 Vc(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 js(e){return!e||e.data.stripe?.publishableKey?!1:!!Vc(e)?.clientId}var cp={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function dp(e){return new Jr.FloPay(cp,{publishableKey:"provider_unavailable",...e})}async function $s(e,t){let{publishableKey:n,paypalPublishableKey:r}=Rs(e);return{...await _s({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Gs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function up(){if(!Gs())return null;try{let e=window.sessionStorage.getItem(Ks);return e?JSON.parse(e):null}catch{return null}}function Uc(e){if(Gs())try{window.sessionStorage.setItem(Ks,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Hs(){if(Gs())try{window.sessionStorage.removeItem(Ks)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function pp(){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 zc(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function Ws(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function mp(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function qc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function yp(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 Di({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:i,loading:c,error:p,onComplete:d,onError:g,onInstrument:b,onDecline:T,onCountryChange:E,onZipChange:S,showPayPal:A=!0,showStripe:_=!0,walletPresentation:P="auto",enabledPaymentMethods:w,showApplePay:K=!0,showGooglePay:k=!0,debug:ge=!1,layout:z,theme:X,buttonsTheme:Se,buttonsStyles:ae,cardButtonContent:De,cardBackButtonContent:Ze,cardTitleContent:le,showSecurityFooter:Ie,onButtonClick:He,onBeforeButtonClick:Re,enableAVS:Ee,cardFieldOrder:_e,cardPreFormSlot:ce,avsLayout:de,submitLabel:Pe,className:Ae,initialErrorMessage:J=null,initialPayPalOrderId:ee,children:he,checkoutMode:U,confirmLabel:we,renderConfirmButton:ie,onSessionCompleted:Te}){let te=(0,rt.resolveBillingApiUrl)(r),at=(0,R.useMemo)(()=>(0,rt.resolveTheme)(X),[X]),We=a??at?.appearance,je=n?"embedded_checkout":"standard_checkout",ot=Ws(he,z),[Ke,it]=(0,R.useState)(null),[$e,vt]=(0,R.useState)(null),Lt=(0,R.useRef)(null),ht=(0,R.useRef)(null),Tt=(0,R.useRef)(0),[V,be]=(0,R.useState)(null),Qe=(0,R.useRef)(null),[Z,Le]=(0,R.useState)(null),bt=(0,R.useMemo)(()=>n?Wo(n):"",[n]),Ye=n?`create:${bt}`:`session:${e??""}`,_t=qc(Z),j=(0,R.useRef)(new Set),h=(0,R.useRef)(Ye),C=(0,R.useRef)(Ye);vo(()=>{C.current=Ye,h.current!==Ye&&(h.current=Ye,j.current.clear())},[Ye]);let Y=(0,R.useCallback)(L=>{if(C.current===Ye){if(fs.has(L.name)){if(j.current.has(L.name))return;j.current.add(L.name)}Je(()=>b?.(L))}},[Ye,b]),W=jo(Y,Ye),ve=(0,R.useRef)(!1),x=(0,R.useCallback)(L=>{if(ve.current)return;let q=L.gateway||!_t?L:{...L,gateway:_t};Y(q)},[Y,_t]);(0,R.useEffect)(()=>{W({class:"lifecycle",name:"checkout.mount"})},[W]);let[B,ue]=(0,R.useState)(e??""),D=e??B,Me=n?"":D,[st,yt]=(0,R.useState)(!0),[Ct,Be]=(0,R.useState)(null),[Tn,Vn]=(0,R.useState)(0),[gn,jt]=(0,R.useState)("full"),[jn,$n]=(0,R.useState)(!1),[vn,Dt]=(0,R.useState)(J),[dt,nt]=(0,R.useState)(null),[An,Mt]=(0,R.useState)(null),[Hn,hn]=(0,R.useState)(!1),[$t,en]=(0,R.useState)(void 0),[cr,Qn]=(0,R.useState)(""),[tn,xt]=(0,R.useState)(!1),[nn,sn]=(0,R.useState)(!1),[Nt,cn]=(0,R.useState)(!1),zt=(0,R.useRef)(null),ln=(0,R.useRef)(0),Ut=(0,R.useRef)(void 0),[me,dr]=(0,R.useState)("loading"),[ur,pr]=(0,R.useState)(0),rn=(0,R.useRef)(!1),Mn=(0,R.useRef)(!1),wn=(0,R.useRef)(!1),ze=(0,R.useRef)(null),mt=(0,R.useRef)(null),v=(0,R.useMemo)(()=>({checkoutMode:U??gn,layout:mp(he,z)}),[U,he,gn,z]),ut=(0,R.useRef)(d);ut.current=d;let pe=(0,R.useRef)(g);pe.current=g;let Cn=(0,R.useRef)(T);Cn.current=T;let Wn=(0,R.useCallback)(L=>yi(ze,async q=>{try{return await L(q)}catch(re){throw q.aborted?lo(re):re}}),[]);(0,R.useEffect)(()=>()=>{ze.current?.abort(),ze.current=null},[]);let Gt=(0,R.useCallback)((L,q)=>{Lt.current=L,vt(L),Qe.current=q,be(q)},[]),xn=(0,R.useCallback)(()=>{let L=ht.current;L&&(ht.current=null,L.destroy())},[]);(0,R.useEffect)(()=>{yn($e)?.setCheckoutContext(v),V&&V!==$e&&yn(V)?.setCheckoutContext(v)},[$e,V,v]);let ft=(0,R.useRef)(Te);ft.current=Te;let mr=(0,R.useCallback)(L=>{dr(L),!(L!=="exhausted"||wn.current)&&(wn.current=!0,pe.current?.(new rt.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),po=(0,R.useCallback)(()=>{dr("retrying"),pr(L=>L+1)},[]);(0,R.useEffect)(()=>{dr("loading"),pr(0),wn.current=!1},[D]),(0,R.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:rt.SDK_VERSION,checkout_type:je,checkout_layout:ot,billing_api_url:te})},[ot,je,te]);let Ft=(0,R.useMemo)(()=>n?Wo(n,!0):"",[n]),Fn=(0,R.useMemo)(()=>cr===Ft?$t:void 0,[$t,cr,Ft]),wr=(0,R.useMemo)(()=>n?ds(n,Fn):void 0,[n,Fn]),er=U??wr?.checkoutMode??"full",Yt=(0,R.useMemo)(()=>wr?{...wr,checkoutMode:er}:void 0,[wr,er]);(0,R.useEffect)(()=>{en(void 0),Qn(Ft),Ut.current=void 0,zt.current=null,cn(!1)},[Ft]),(0,R.useEffect)(()=>{Dt(J)},[J]);let yr=(0,R.useCallback)((L,q,re)=>{Je(()=>{Cn.current?.(mn(L,q,re))})},[]),Bn=(0,R.useCallback)(async(L,q)=>{Dt(null),Mt(null),hn(!1),nt("processing");let re=q?.sessionId??L.id,$=L.clientSecret||t,gt=qc(L),It=Lt.current??Qe.current,se=yn(It),Xe=It?null:Fi(te,o,v),Q={log:Oe=>{se?se.log(Oe):Xe?.log(Oe)},error:Oe=>{se?se.error(Oe):Xe?.error(Oe)},terminal:Oe=>{se?se.terminal(Oe):Xe?.terminal(Oe)},performance:Oe=>{se?se.performance(Oe):Xe?.performance(Oe)},now:()=>se?.now()??Xe?.now()??0,elapsed:Oe=>se?.elapsed(Oe)??Math.max(0,(Xe?.now()??Oe)-Oe)},f=Q.now(),m=!!(q?.initialAutoProcessingError||q?.initialAutoProcessingPending),N=!1,H,Ce=()=>{N||(N=!0,m=!0,H=Q.now(),Q.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},xe=!1,et=()=>{xe||(xe=!0,Q.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),Q.performance({stage:"processing",durationMs:Q.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),H!==void 0&&Q.performance({stage:"recovery",durationMs:Q.elapsed(H),durationMode:"machine",paymentMethodCategory:"saved"}))};Q.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ve.current=!0;try{Q.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ve.current=!1}W({class:"lifecycle",name:"payment.processing.started",provider:gt}),m&&Ce();let Pt;try{let Oe=ac(q?.initialAutoProcessingError),F=q?.initialAutoProcessingError?.type==="3ds_required"&&!q.initialAutoProcessingError.threeDSecureToken&&q.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:q.initialAutoProcessingError.nextActionRedirectUrl}:null,St,Fe=ke=>(Ce(),Wn(G=>Go(ke,{billingApiUrl:te,sessionId:re,nonce:$,session:L,signal:G})));if(F)St=await Fe(F);else if(Oe)Ce(),Oe.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Uc({sessionId:re,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),St=await Wn(ke=>gi(Oe,{flopay:Lt.current,paypalFlopay:Qe.current,attempt3DS:q?.attempt3DS,billingApiUrl:te,sessionId:re,session:L,telemetry:!1,signal:ke})),Oe.type==="paypal_redirect_required"&&Hs();else if(q?.initialAutoProcessingPending){let ke=q.initialAutoProcessingPending,G=new Jr.PaymentAPI(te,{telemetry:!1}),ye=await Wn(Ge=>G.waitForCheckoutSessionCompletion(ke.sessionId,{initialDelayMs:ke.retryAfterMs,nonce:$,statusUrl:ke.statusUrl,signal:Ge})),ne=ro(ye,L),wt=ye.autoProcessingError?.type==="3ds_required"&&ye.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:ye.autoProcessingError.nextActionRedirectUrl}:null;if(wt)St=await Fe(wt);else{if(!Hr(ne))throw Uo(ne);St=$r(ne,re)}}else{if(q?.initialAutoProcessingError)throw xr(q.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:q.initialAutoProcessingError.checkoutMethod});if(q?.fromCreateSession)return q?.fallbackToFull&&(jt("full"),zc("full")),!1;{let ke=await Yo({billingApiUrl:te,sessionId:re,session:L,nonce:$,telemetry:!1});ke.type==="success"?St=ke.result:ke.type==="next_action_required"?St=await Fe(ke):(Ce(),ke.type==="paypal_redirect_required"&&mt.current?.publishableKey&&Uc({sessionId:re,publishableKey:mt.current.publishableKey,paypalPublishableKey:mt.current.paypalPublishableKey}),St=await Wn(G=>gi(ke,{flopay:Lt.current,paypalFlopay:Qe.current,attempt3DS:q?.attempt3DS,billingApiUrl:te,sessionId:re,session:L,telemetry:!1,signal:G})),ke.type==="paypal_redirect_required"&&Hs())}}re&&Ko(re),et(),m&&(Q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),Q.terminal({outcome:St.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),hn(St.status==="authorized"),nt("success"),await Oa(600),Pt=()=>ut.current?.(St)}catch(Oe){let F=to(Ea(Oe),re);if(F.code==="three_ds_aborted")return!1;let St=F.checkoutMethod??Ia;Dt(F.message),Mt(F.message),hn(!1),q?.fallbackToFull&&(Q.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),jt("full"),zc("full")),et();let Fe=F.statusCode===void 0?void 0:(0,rt.telemetryStatusClass)(F.statusCode,"unknown"),ke=Fe==="4xx"?{requestCategory:"process_payment",statusClass:Fe}:{},G=Fe===void 0||Fe==="4xx";if(G&&(F.telemetryOutcome==="payment_declined"||!!(F.declineCode||F.code?.toLowerCase().includes("declin"))))Q.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ke});else if(G&&(F.telemetryOutcome==="validation_rejected"||F.type==="validation_error"))Q.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ke});else{let wt=(0,rt.classifyTelemetryFailure)(Oe,m?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ge=F.telemetryRequestCategory??"process_payment";ve.current=!0;try{Q.error({...wt,...F.telemetryFailureCategory?{failureCategory:F.telemetryFailureCategory}:{},stage:m?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ge})}finally{ve.current=!1}W({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ge,provider:gt})}return Je(()=>pe.current?.(F)),yr(St,F,{code:F.code,declineCode:F.declineCode}),nt("error"),await Promise.allSettled([Oa(400),q?.ensureProvidersReady?q.ensureProvidersReady():Promise.resolve()]),m&&(Q.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),Q.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{et(),Xe&&La(Xe),nt(null),Mt(null)}return Je(Pt),!0},[yr,W,t,te,Wn,o,v]);(0,R.useEffect)(()=>{if(typeof window>"u"||Mn.current)return;let L=new URLSearchParams(window.location.search),q=L.get("payment_intent_client_secret");if(!q)return;let re=up();re&&(Mn.current=!0,(async()=>{let $,gt=0;Dt(null),Mt(null),nt("processing"),$n(!0);try{if(L.get("redirect_status")==="failed")throw Object.assign(new rt.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:It,paypalFlopay:se}=await _s({publishableKey:re.publishableKey,paypalPublishableKey:re.paypalPublishableKey,billingApiUrl:te,locale:i,telemetry:o});$=yn(se??It),$?.setCheckoutContext(v),gt=$?.now()??0,$?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),$?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Xe=(se??It)?.getRawProvider();if(!Xe)throw Object.assign(new rt.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:Q,error:f}=await Xe.retrievePaymentIntent(q);if(f)throw Object.assign(new rt.FloPayError(f.message??"Failed to retrieve PayPal payment status.","api_error",{code:f.code}),{checkoutMethod:"paypal"});let m=zl(Q?.status);if(!Q||m==="failed")throw Object.assign(new rt.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let N=typeof Q.payment_method=="string"?Q.payment_method:Q.payment_method?.id,H=m;if(re.sessionId){let et=(await new Jr.PaymentAPI(te,{telemetry:!1}).getUnifiedCheckoutSession(re.sessionId)).data.session;if(et&&et.status!=="complete"){let Pt=await Yo({billingApiUrl:te,sessionId:re.sessionId,session:et,telemetry:!1,tokenizedData:{id:N??Q.id,type:"card",threeDSecureActionResultTokenId:Q.id,isPaypal:!0}});if(Pt.type!=="success")throw Object.assign(new rt.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});H=Pt.result.status}}re.sessionId&&Ko(re.sessionId),$?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),$?.performance({stage:"redirect_resume",durationMs:$.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),$?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),nt("success"),await Oa(600),Je(()=>ut.current?.({status:H,paymentIntentId:Q.id,paymentMethodId:N,checkoutMethod:"paypal"}))}catch(It){let se=to(Ea(It),re.sessionId),Xe=se.checkoutMethod??"paypal",Q=!!(se.declineCode||se.code?.toLowerCase().includes("declin"));if($)$.performance({stage:"redirect_resume",durationMs:$.elapsed(gt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Q?$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):$.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(Q){let f=Fi(te,o,v);f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),La(f)}else Vs(te,o,v,"REDIRECT_RESUME_FAILED","redirect_resume");Dt(se.message),Mt(se.message),Je(()=>pe.current?.(se)),yr(Xe,se,{code:se.code,declineCode:se.declineCode}),nt("error"),await Oa(400)}finally{Hs(),pp(),nt(null),Mt(null),$n(!1)}})())},[yr,i,te,o,v]);let Or=(0,R.useRef)(null),Dn=(0,R.useMemo)(()=>Yt?Wo(Yt):"",[Yt]),kr=(0,R.useRef)(Yt);kr.current=Yt,(0,R.useEffect)(()=>{ue(e??"")},[e]),(0,R.useEffect)(()=>{rn.current=!1,Dt(J),Mt(null),hn(!1),nt(null)},[Dn,J,e]);async function Rr(L,q,re){let $=Fi(te,o,v),gt=new Jr.PaymentAPI(te,{telemetry:!1}),It=!1;try{let se=L.idempotencyKey===void 0?void 0:(0,rt.resolveIdempotencyKey)(L.idempotencyKey),Xe=bs(q,re),Q=Ps(q,re);Xe?.canonicalIdentity===re&&Q&&Q.canonicalIdentity===void 0&&(pi(q,re,Q.idempotencyKey),Q={...Q,canonicalIdentity:re});let f=se??(Q?.canonicalIdentity===re?Q.idempotencyKey:void 0),m,N=!1;$.log({name:Xe?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let H=Xe?.sid??null,Ce=null,xe,et,Pt=!1;if(H)try{Ce=await gt.getUnifiedCheckoutSession(H,Xe?.nonce),Xe&&Xe.canonicalIdentity===void 0&&(tc(Ce.data.session,L)?(ui(q,re,H,Xe.nonce??Ce.data.session?.clientSecret),Q&&Q.canonicalIdentity===void 0&&(pi(q,re,Q.idempotencyKey),f??(f=Q.idempotencyKey))):(di(q,re),Q=null,f=se,H=null,Ce=null));let F=Ce?.data.session?.status,St=Ce?.data.session,Fe=St?.clientSecret||Xe?.nonce;if(H&&St?.buyerIdentified===!1&&Fe&&(et=No(gt,H,Fe,L.account)),H&&Ce&&F==="complete"){if(vs(H))return{sid:H,result:Ce};di(q,re),H=null,Ce=null,N=!0}}catch{$.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Xe?.canonicalIdentity===void 0?(di(q,re),f=se):ci(q,re),H=null}if(!H){!se&&(N||!f)&&(f=(0,rt.resolveIdempotencyKey)(),m=f),f&&pi(q,re,f);let F=$.now(),St=0;$.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Fe={...L,idempotencyKey:f,avsCheck:!!Ee,avsConfig:typeof Ee=="object"?Ee:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ws(he,z)};Object.defineProperty(Fe,Jr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ye=>{St=Math.max(St,ye)}}});let ke=()=>{Lc($,"session_create",F,St)},G=ye=>{Nc($,ye,"session_create",F,St)&&W({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,rt.isDetachedSessionEligible)(Fe)){let ye=await gt.createDetachedSession(Fe);ye.claimed.catch(()=>{}),Ce=ye.shell,H=ye.sessionId,et=ye.claim;let ne=$.now();$.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),xe=ye.claimed.then(wt=>{let Ge=wt.data.session?.id??ye.sessionId;return Ge&&ui(q,re,Ge,wt.data.session?.clientSecret??ye.nonce),Lc($,"session_claim",ne),ke(),wt},wt=>{throw ci(q,re),Nc($,wt,"session_claim",ne,0)&&W({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),wt}).finally(()=>La($)),xe.catch(()=>{}),It=!0,$.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),$.performance({stage:"session_shell",durationMs:$.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:St,statusClass:"2xx",paymentMethodCategory:"card"})}else Ce=await gt.createAndFetchSession(Fe),ke()}catch(ye){throw G(ye),ye}H=Ce.data.session?.id??H??"",H&&!xe&&ui(q,re,H,Ce.data.session?.clientSecret)}let Oe=Ce?.data.session;return!et&&H&&Oe?.buyerIdentified===!1&&Oe.clientSecret&&(et=No(gt,H,Oe.clientSecret,L.account)),{sid:H??"",result:Ce,sdkGeneratedIdempotencyKey:m,...xe?{claimed:xe}:{},...et?{claim:et}:{},...Pt?{claimRequiresIdentity:!0}:{}}}finally{It||La($)}}let Lr=(0,R.useRef)(Rr);vo(()=>{Lr.current=Rr},[Rr]);let Kn=(0,R.useCallback)(async(L,q)=>{let re=kr.current;if(!re)throw new rt.FloPayError("createSession is required to bootstrap checkout.","validation_error");let $=ds(re,L),gt=Wo($),It=ec($),se=Bi.get(gt);if(!se){let f={canonicalIdentity:gt,promise:Lr.current($,It,gt),consumers:0,settled:!1};se=f,Bi.set(gt,f);let m=()=>{f.settled=!0,Oc(gt,f)};f.promise.then(m,m)}se.consumers+=1;let Xe=!1,Q=()=>{Xe||(Xe=!0,se.consumers-=1,Oc(gt,se))};q?.(Q);try{let f=await se.promise;Or.current=gt,L&&(Qn(Ft),en(Oe=>Ll(Oe,L)));let{sid:m,result:N,claimed:H,claim:Ce,claimRequiresIdentity:xe}=f;if(Ut.current=Ce,cn(xe===!0),it(N),N.data.session&&Le(N.data.session),m&&ue(m),H){ln.current+=1;let Oe=ln.current;zt.current=H,sn(!0),H.then(F=>{ln.current===Oe&&(zt.current===H&&(zt.current=null),it(F),F.data.session&&Le(F.data.session),sn(!1),cn(!1))},F=>{ln.current===Oe&&(zt.current===H&&(zt.current=null),sn(!1),cn(!1),Be(F instanceof rt.FloPayError?F:new rt.FloPayError(F instanceof Error?F.message:"Failed to create session","api_error")))})}else ln.current+=1,zt.current=null,sn(!1),cn(!1);let{flopay:et,paypalFlopay:Pt}=await $s(N,{billingApiUrl:te,locale:i,telemetry:o});return Gt(et,Pt),yt(!1),f}catch(f){throw Or.current===gt&&(Or.current=null),f}finally{q||Q()}},[Ft,Gt,i,te,o]),tr=(0,R.useRef)(Bn);tr.current=Bn;let Nr=(0,R.useRef)(Kn);Nr.current=Kn;let Ot=(0,R.useCallback)(async L=>{if(!yp(L)||tn)return{sessionId:B,session:Z};xt(!0);try{let q=await Kn(L);return{sessionId:q.sid,session:q.result.data.session??null}}finally{xt(!1)}},[Kn,tn,B,Z]),kn=(0,R.useCallback)(async L=>{let q=Ut.current;if(!q)return;let re=ln.current,$=await q(L);ln.current===re&&(it($),$.data.session&&Le($.data.session))},[]),nr=(0,R.useCallback)(async()=>{await zt.current},[]),Ur=(0,R.useCallback)(async()=>(await nr(),{proceed:!0}),[nr]);(0,R.useEffect)(()=>{let L=!1,q,re=++Tt.current;xn(),Be(null),Vn(0);let $=()=>{L=!0,Tt.current===re&&(Tt.current+=1,xn())},gt=kr.current;if(Dn&&gt)return jt(er),yt(!1),Or.current===Dn?$:(Le(Nl(gt,U)),(async()=>{let Xe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Q=er==="auto"&&!rn.current&&!Xe;Q&&(Dt(null),Mt(null),nt("processing"));try{let f=await Nr.current(void 0,Ce=>{q=Ce}),m=f.result.data.session??null;mt.current=Rs(f.result);let N=js(f.result),H=vs(f.sid||m?.id);if(!L&&Q&&m&&!N&&!H){rn.current=!0,await lp(Dn,f.sdkGeneratedIdempotencyKey,()=>tr.current(m,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:f.result.autoProcessingError,initialAutoProcessingPending:f.result.autoProcessingPending,autoProcessingAttempted:f.result.autoProcessingAttempted,sessionId:f.sid||m.id}));return}!L&&Q&&((N||H)&&(rn.current=!0),nt(null),Mt(null))}catch(f){if(L)return;let m=Qa(f);if(Q&&m==="session_auto_completed"){rn.current=!0,nt("success"),await Oa(600),L||(Je(()=>{ut.current?.({status:"succeeded"})}),nt(null),Mt(null));return}Q&&(nt(null),Mt(null));let N=f instanceof rt.FloPayError?f:new rt.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error");Be(N)}finally{q?.(),q=void 0}})(),()=>{$(),q?.()});yt(!0);async function It(){let Xe=!1,Q=null;try{let f=new Jr.PaymentAPI(te,{telemetry:!1}),m=await f.getUnifiedCheckoutSession(D,t);if(Q=m,L)return;it(m);let N=m.data.session??null;if(Le(N),!N)throw new rt.FloPayError("No session data returned","api_error");let H=N.checkoutMode;if(H==="setup")throw new rt.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(N.status==="authorized"){yt(!1),Je(()=>{ut.current?.($r(N,D)),ft.current?.(N.successUrl??"")});return}if(N.status==="complete"){yt(!1),Je(()=>{ft.current?.(N.successUrl??"")});return}if(N.status==="expired")throw Za(N);Xe=!0;let Ce=U??H??"full";jt(Ce),ln.current+=1;let xe=N.clientSecret||t;Ut.current=N.buyerIdentified===!1&&xe?No(f,D,xe,{...N.customer?.id?{userId:N.customer.id}:{}}):void 0,sn(!1),cn(!1);let et=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Pt=js(m);if(Ce==="auto"&&!rn.current&&!et&&!Pt){rn.current=!0;let Oe=se(m);try{if(await tr.current(N,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Oe,sessionId:D||N.id}),L)return;await Oe,L||yt(!1);return}catch{if(L)return;await Oe,L||yt(!1);return}}await se(m),L||yt(!1)}catch(f){if(L)return;let m=Ol(f,Xe);if(Xe&&W({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),m){let{errorCode:H,stage:Ce,...xe}=m;Vs(te,o,v,H,Ce,xe)}if(m?.stage==="provider_load"&&(U??Q?.data.session?.checkoutMode??"full")==="full"&&Dl(Q,A,_)){let H=dp({billingApiUrl:te,locale:i,telemetry:o});ht.current=H,Gt(H,null),Vn(1),yt(!1);return}let N=f instanceof rt.FloPayError&&m?.stage!=="provider_load"?f:Bl();N!==f&&Je(()=>pe.current?.(N)),Be(N),yt(!1)}}async function se(Xe){let{flopay:Q,paypalFlopay:f,...m}=await $s(Xe,{billingApiUrl:te,locale:i,telemetry:o});mt.current={publishableKey:m.publishableKey,paypalPublishableKey:m.paypalPublishableKey},Gt(Q,f),Vn(0)}return It(),$},[U,Dn,er,Me,t,A,_]);let zr=(0,R.useCallback)(async()=>{if(!Ke||Tn!==1)return;let L=Tt.current;Vn(2);try{let{flopay:q,paypalFlopay:re}=await $s(Ke,{billingApiUrl:te,locale:i,telemetry:o});if(Tt.current!==L)return;xn(),Gt(q,re),Vn(0)}catch(q){if(Tt.current!==L)return;let{errorCode:re,stage:$,...gt}=ls(q);Vs(te,o,v,re,$,gt)}},[xn,Gt,i,Tn,te,o,v,Ke]),lt=!!(D&&(Z?.clientSecret||t)),dn=jn||!lt,un=(0,R.useCallback)(async()=>{if(!(jn||!lt||!Z)){$n(!0),Dt(null);try{await Bn(Z,{attempt3DS:!0,fallbackToFull:!0,sessionId:D||Z.id})}finally{$n(!1)}}},[D,jn,lt,Bn,Z]),Rn=Vc(Ke,ee),mo=js(Ke),_r=(0,R.useMemo)(()=>{if(!(!Ke||!Z||!Ke.data.stripe?.publishableKey))return{billingApiUrl:te}},[Ke,Z,te]),Qr=!!(n&&!he&&z==="buttons"&&Re&&er==="full"),_n=!!(D&&(Z?.vault?.html||eo(Z))),pn=(0,R.useMemo)(()=>({session:Z,loading:st,error:Ct,checkoutMode:gn,inlineSessionDraft:Yt,applyInlineSessionPatch:Qr?Ot:void 0,inlineSessionPatchProcessing:tn,claimPending:nn,claimRequiresIdentity:Nt,claimBuyerIdentity:kn,waitForDataAttachment:nr}),[Z,st,Ct,gn,Yt,Qr,Ot,tn,nn,Nt,kn,nr]),qr=!!n&&z==="buttons"&&!mo&&!_n&&(!$e||!_r),On=dt?(0,O.jsx)(zn,{status:dt,errorMessage:An,authorized:Hn}):null;if(st&&!_n){if(c)return(0,O.jsxs)(O.Fragment,{children:[c,On]});if(z==="buttons"){let L=at?.buttonsLayout?.cardButton?.borderRadius??at?.appearance.variables?.borderRadius??8,q=re=>(0,O.jsx)("div",{style:{height:re,borderRadius:L,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[A&&q(ta),_&&(K||k)&&q(ta),_&&q(ta),(0,O.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),On]})}return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,O.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,O.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),On]})}return Ct?p?(0,O.jsx)(Pr.Provider,{value:pn,children:p(Ct)}):(0,O.jsx)(Pr.Provider,{value:pn,children:(0,O.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ct.message})}):qr?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:pn,children:(0,O.jsx)(gp,{onButtonClick:He,showPayPal:A,showStripe:_,showApplePay:K,showGooglePay:k,theme:X,buttonsTheme:Se,buttonsStyles:ae,cardButtonContent:De,cardBackButtonContent:Ze,cardTitleContent:le})}),On]}):mo&&Z&&Rn?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:pn,children:(0,O.jsxs)("div",{className:Ae,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[vn&&(0,O.jsx)($o,{icon:!1,children:vn}),me==="retrying"&&(0,O.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),me==="exhausted"&&(0,O.jsxs)("div",{role:"alert",children:[(0,O.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,O.jsx)("button",{type:"button",onClick:po,children:"Retry PayPal"})]}),me!=="exhausted"&&(0,O.jsx)("div",{"aria-hidden":me==="retrying"?!0:void 0,style:me==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,O.jsx)(Ql,{sessionId:D,nonce:Z.clientSecret||void 0,billingApiUrl:te,email:Z.customer?.email||Yt?.account?.email,billingName:[Z.customer?.firstName,Z.customer?.lastName].filter(Boolean).join(" ")||[Yt?.account?.firstName,Yt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:kn,clientId:Rn.clientId,environment:Rn.environment,currency:(Z.currency??"usd").toUpperCase(),isSubscription:Z.mode==="subscription",providerObjectType:Rn.providerObjectType,approvalPresentation:Rn.approvalPresentation,existingOrderId:Rn.existingOrderId,onComplete:d,onErrorChange:Dt,onDecline:T,onButtonClick:He,runBeforeButtonClick:Ur,onInitializationStateChange:mr,allowAutomaticRetry:ur===0,session:Z,telemetry:o,telemetryContext:v,onInstrument:x,debug:ge},`${Ye}:paypal-init-${ur}`)})]})}),On]}):gn==="confirm"?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:pn,children:(0,O.jsx)(Ra,{flopay:$e,paypalFlopay:V,options:_r??{billingApiUrl:te},onInstrument:x,children:(0,O.jsxs)("div",{className:Ae,children:[vn&&(0,O.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:vn}),ie?ie({onConfirm:un,isProcessing:dn}):(0,O.jsx)("button",{type:"button",onClick:un,disabled:dn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:dn?"not-allowed":"pointer",opacity:dn?.6:1},children:jn?"Processing...":we??"Confirm Purchase"})]})},Ye)}),On]}):(!$e||!_r)&&!(_n&&gn==="full")?(0,O.jsx)(O.Fragment,{children:On}):(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Pr.Provider,{value:pn,children:(0,O.jsxs)(Ra,{flopay:$e,paypalFlopay:V,options:_r??{billingApiUrl:te},onInstrument:x,children:[Tn===1&&(0,O.jsx)("button",{type:"button",onClick:zr,children:"Retry payment methods"}),he?(0,O.jsxs)(O.Fragment,{children:[vn&&(0,O.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,O.jsx)(fp,{sessionId:D,nonce:Z?.clientSecret||void 0,billingApiUrl:te,session:Z,submitLabel:Pe,walletPresentation:P,children:he})]}):(0,O.jsx)(Mi,{sessionId:D,nonce:Z?.clientSecret||void 0,telemetry:o,email:Z?.customer?.email||Yt?.account?.email,userId:Z?.customer?.id||Yt?.account?.userId,firstName:Z?.customer?.firstName||Yt?.account?.firstName,lastName:Z?.customer?.lastName||Yt?.account?.lastName,totalAmount:Z?Math.round((0,rt.buildCheckoutDisplayData)(Z).total*100):0,currency:Z?.currency?.toLowerCase()??"usd",onComplete:d,onError:g,onDecline:T,error:vn,onErrorChange:Dt,showPayPal:A,showStripe:_,walletPresentation:P,enabledPaymentMethods:Tn?[]:w??Ke?.data.stripe?.enabledPaymentMethods??Z?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Ke?.data.stripe?.enabledPaymentMethodCountries,showApplePay:K,showGooglePay:k,layout:z,theme:X,buttonsTheme:Se,buttonsStyles:ae,appearance:We,cardButtonContent:De,cardBackButtonContent:Ze,cardTitleContent:le,onButtonClick:He,onBeforeButtonClick:Re,onBuyerIdentityReady:kn,enableAVS:Ee,..._e?{cardFieldOrder:_e}:{},...ce?{cardPreFormSlot:ce}:{},avsLayout:de,country:Z?.customer?.country,city:Z?.customer?.city,state:Z?.customer?.state,onCountryChange:E,onZipChange:S,avsCheck:!!Ee,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ws(he,z),className:Ae,submitLabel:Pe,directPaypal:Rn,isSubscription:Z?.mode==="subscription",session:Z,dataAttachmentPending:nn,dataAttachmentRequiresIdentity:Nt,debug:ge})]},Ye)}),On]})}function fp({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,walletPresentation:a,children:i}){return(0,O.jsx)(O.Fragment,{children:R.default.Children.map(i,c=>{if(!R.default.isValidElement(c))return c;let p=c.props,d={};return p.sessionId||(d.sessionId=e),!p.nonce&&t&&(d.nonce=t),p.billingApiUrl||(d.billingApiUrl=n),p.submitLabel===void 0&&o!==void 0&&(d.submitLabel=o),p.walletPresentation===void 0&&(d.walletPresentation=a),r?.customer&&(p.email||(d.email=r.customer.email),p.userId||(d.userId=r.customer.id),p.firstName||(d.firstName=r.customer.firstName),p.lastName||(d.lastName=r.customer.lastName)),Object.keys(d).length===0?c:R.default.cloneElement(c,d)})})}function gp({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:i,buttonsStyles:c,cardButtonContent:p,cardBackButtonContent:d,cardTitleContent:g}){let[b,T]=(0,R.useState)(!1),E=(0,R.useMemo)(()=>(0,rt.resolveTheme)(a),[a]),S=(0,R.useMemo)(()=>{let w=E?.buttonsLayout??(0,rt.resolveButtonsLayoutTheme)(i);return c?{...w,...c,cardButton:{...w.cardButton,...c.cardButton},cardFormContainer:{...w.cardFormContainer,...c.cardFormContainer},backButton:{...w.backButton,...c.backButton},backButtonIcon:{...w.backButtonIcon,...c.backButtonIcon},submitButton:{...w.submitButton,...c.submitButton},title:{...w.title,...c.title}}:w},[E,i,c]),A=E?.buttonsLayout?.cardButton?.borderRadius??E?.appearance.variables?.borderRadius??8,_=w=>(0,O.jsx)("div",{style:{height:w,borderRadius:A,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),P=p===void 0?{boxSizing:"border-box",height:ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let w=S.cardInputBorder??"#e5e7eb",K=S.cardInputBackground??"white",k=Do(d),ge=Do(g);return(0,O.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,O.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,O.jsxs)("button",{type:"button",onClick:()=>T(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:k?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...S.backButton},children:[(0,O.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...S.backButtonIcon},children:(0,O.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,O.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,O.jsx)(Lo,{content:d})]}),ge?(0,O.jsx)("div",{style:{flex:1}}):(0,O.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...S.title},children:(0,O.jsx)(ha,{content:g})})]}),(0,O.jsx)("div",{style:{backgroundColor:K,border:`1px solid ${w}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsxs)("div",{style:{display:"flex"},children:[(0,O.jsx)("div",{style:{flex:1,backgroundColor:K,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.jsx)("div",{style:{flex:1,backgroundColor:K,borderTop:"none",borderRight:`1px solid ${w}`,borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,O.jsx)("div",{style:{backgroundColor:K,border:`1px solid ${w}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,O.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,O.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,O.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,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&I(ea),n&&(r||o)&&I(ea),n&&(0,O.jsx)("button",{type:"button",onClick:()=>{e?.("card"),T(!0)},style:{width:"100%",...P,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:w=>{w.currentTarget.style.transform="scale(0.985)"},onMouseUp:w=>{w.currentTarget.style.transform="scale(1)"},children:(0,O.jsx)(Do,{content:p})}),(0,O.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var sr=require("react/jsx-runtime"),pp=44;function Vc(e){return new Promise(t=>setTimeout(t,e))}function mp(e,t){return e instanceof lr.FloPayError?e:new lr.FloPayError(e instanceof Error?e.message:t,"api_error")}function yp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function fp(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 $c({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:i,items:c,subscriptions:p,account:d,successUrl:g,cancelUrl:b,couponCodes:T,tagsData:_,utmMetadata:S,billingApiUrl:A,locale:I,theme:P,appearance:w,buttonsTheme:K,buttonsStyles:k,onSuccess:ge,onError:q,onDecline:X,children:Se,disabled:oe=!1,type:De="button",style:Ze,...le}){let Ee=(0,ct.useMemo)(()=>(0,lr.resolveBillingApiUrl)(A),[A]),He=(0,ct.useMemo)(()=>fp({createSession:n,clientId:a,products:i,items:c,subscriptions:p,account:d,successUrl:g,cancelUrl:b,couponCodes:T,tagsData:_,utmMetadata:S}),[d,b,a,T,n,i,c,p,g,_,S]),[Re,_e]=(0,ct.useState)(!1),[Ie,ce]=(0,ct.useState)(null),[de,Pe]=(0,ct.useState)(null),[Ae,J]=(0,ct.useState)(!1),[ee,he]=(0,ct.useState)(null),[U,we]=(0,ct.useState)(null),ie=(0,ct.useRef)(!0),Te=(0,ct.useRef)(null),te=(0,ct.useRef)(U),at=(0,ct.useRef)(ge),We=(0,ct.useRef)(q),Ve=(0,ct.useRef)(X),ot=(0,ct.useCallback)(h=>mi(Te,async C=>{try{return await h(C)}catch(Y){throw C.aborted?so(Y):Y}}),[]);(0,ct.useEffect)(()=>{te.current=U},[U]),(0,ct.useEffect)(()=>{at.current=ge},[ge]),(0,ct.useEffect)(()=>{We.current=q},[q]),(0,ct.useEffect)(()=>{Ve.current=X},[X]),(0,ct.useEffect)(()=>(ie.current=!0,()=>{ie.current=!1,Te.current?.abort()}),[]),(0,ct.useEffect)(()=>{if(typeof window>"u")return;let h=C=>{C.key==="Escape"&&we(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let Ke=(0,ct.useCallback)((h,C=Ia)=>{Ve.current?.(yn(C,h,{code:h.code,declineCode:h.declineCode}))},[]),it=(0,ct.useCallback)(async h=>{ie.current&&(Pe(null),J(h.result.status==="authorized"),ce("success"),await Vc(600),ie.current&&Je(()=>at.current?.(h)))},[]),$e=(0,ct.useCallback)(async(h,C)=>{ie.current&&(We.current?.(h),C?.emitDecline&&Ke(h,C.method),Pe(h.message),J(!1),ce("error"),await Vc(400))},[Ke]),vt=(0,ct.useCallback)(async(h,C,Y)=>{let W=h.data.session??null;if(!W)throw eo(new lr.FloPayError("No session data returned","api_error"),C);let ve=W.clientSecret||t;if(jr(W)){await it({result:$r(W,C),session:W,sessionId:W.id||C,autoCompleted:!1});return}if(W.status==="expired")throw eo(Ja(W),W.id||C);try{if(h.autoProcessingPending){let B=h.autoProcessingPending,ue=new Di.PaymentAPI(Ee),D=await ot(yt=>ue.waitForCheckoutSessionCompletion(B.sessionId,{initialDelayMs:B.retryAfterMs,nonce:ve,statusUrl:B.statusUrl,signal:yt})),Me=no(D,W),st=D.autoProcessingError?.type==="3ds_required"&&D.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:D.autoProcessingError.nextActionRedirectUrl}:null;if(st&&C&&ve){let yt=await ot(Ct=>Ko(st,{billingApiUrl:Ee,sessionId:C,nonce:ve,session:W,signal:Ct,telemetry:!0}));await it({result:yt,session:W,sessionId:W.id||C,autoCompleted:!1});return}if(D.autoProcessingError)throw Fr(D.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.autoProcessingError.checkoutMethod});if(!jr(Me))throw No(Me);await it({result:$r(Me,C),session:Me,sessionId:Me.id||C,autoCompleted:!1});return}if(h.autoProcessingError){let B=h.autoProcessingError.nextActionRedirectUrl;if(h.autoProcessingError.type==="3ds_required"&&B&&C&&ve){let ue=await ot(yt=>ws({billingApiUrl:Ee,sessionId:C,nonce:ve,nextActionRedirectUrl:B,signal:yt}));if(ue.status==="declined")throw Fr({type:ue.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ue.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Me=await new Di.PaymentAPI(Ee).waitForCheckoutSessionCompletion(C,{initialDelayMs:0,nonce:ve}),st=no(Me,W);if(!jr(st))throw Fr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await it({result:$r(st,C),session:st,sessionId:st.id||C,autoCompleted:!1});return}throw Fr(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(Y?.fromCreateSession&&h.autoProcessingAttempted===!0)throw Fr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let F=await Go({billingApiUrl:Ee,sessionId:C??W.id,session:W,nonce:ve});if(F.type==="next_action_required"&&ve){let B=C??W.id,ue=await ot(D=>Ko(F,{billingApiUrl:Ee,sessionId:B,nonce:ve,session:W,signal:D,telemetry:!0}));await it({result:ue,session:W,sessionId:W.id||B,autoCompleted:!1});return}if(F.type!=="success")throw Fr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await it({result:F.result,session:W,sessionId:W.id||C,autoCompleted:!1})}catch(F){let B=W.id||C,ue=eo(Ea(F),B);if(ue.code==="three_ds_aborted")return;if(ue.code==="checkout_processing_timeout"){if(!ie.current)return;he(ue.message),Je(()=>We.current?.(ue));return}await $e(ue,{emitDecline:!0,method:ue.checkoutMethod??Ia}),yp(ue,B)&&B&&ie.current&&we({sessionId:B,errorMessage:ue.message,nonce:ve||void 0,payPalOrderId:ue.orderId})}},[t,Ee,ot,$e,it]),Ot=(0,ct.useCallback)(async h=>{if(le.onClick?.(h),!(h.defaultPrevented||oe||Re)){if(we(null),he(null),e&&He){let C=new lr.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await $e(C),ie.current&&(ce(null),Pe(null));return}if(!e&&!He){let C=new lr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $e(C),ie.current&&(ce(null),Pe(null));return}_e(!0),Pe(null),J(!1),ce("processing");try{let C=new Di.PaymentAPI(Ee);if(e){let Y=await C.getUnifiedCheckoutSession(e,t);await vt(Y,e);return}try{let Y=await C.createAndFetchSession({...He});await vt(Y,Y.data.session?.id??null,{fromCreateSession:!0})}catch(Y){if(Za(Y)==="session_auto_completed"){await it({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Y}}catch(C){await $e(eo(mp(C,"Automatic payment failed. Please try again."),e))}finally{ie.current&&(ce(null),Pe(null),_e(!1))}}},[le.onClick,He,oe,Re,t,vt,Ee,e,$e,it]),ht=(0,ct.useCallback)(h=>{let C=te.current;we(null),at.current?.({result:h,session:null,sessionId:C?.sessionId??null,autoCompleted:!1})},[]),_t=(0,ct.useCallback)(h=>{We.current?.(h)},[]),z=(0,ct.useCallback)(h=>{Ve.current?.(h)},[]),be=(0,ct.useMemo)(()=>(0,lr.resolveTheme)(P),[P]),Qe=(0,ct.useMemo)(()=>{let h=be?.buttonsLayout??(0,lr.resolveButtonsLayoutTheme)(K);return k?{...h,...k,cardButton:{...h.cardButton,...k.cardButton}}:h},[be,K,k]),Z=(0,ct.useMemo)(()=>{let h=be?.appearance;return w?h?{...h,...w,variables:{...h.variables,...w.variables}}:w:h},[w,be]),Le=Z?.variables,bt=Le?.colorPrimary??"#4A49FF",Ye=Le?.colorPrimaryHover??Zo(bt,.12),It=Le?.borderRadius??"8px";return(0,sr.jsxs)(sr.Fragment,{children:[(0,sr.jsx)("button",{...le,type:De,onClick:Ot,disabled:oe||Re,"aria-busy":Re,style:{width:"100%",...Se===void 0?{boxSizing:"border-box",height:pp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Qe.cardButton,...zs({themeBundle:be,resolvedPrimaryColor:bt,resolvedBorderRadius:It,submitButtonStyle:Qe.submitButton,explicitPrimaryColor:Le?.colorPrimary}),fontSize:Qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:oe||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:oe||Re?.6:1,...Ze},onMouseEnter:h=>{le.onMouseEnter?.(h),!h.defaultPrevented&&!oe&&!Re&&(be||Le?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ye)},onMouseLeave:h=>{le.onMouseLeave?.(h),!h.defaultPrevented&&(be||Le?.colorPrimary)&&(h.currentTarget.style.backgroundColor=bt)},onMouseDown:h=>{le.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{le.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,sr.jsx)(Do,{content:Se})}),ee&&(0,sr.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ee}),Ie&&(0,sr.jsx)(qn,{status:Ie,errorMessage:de,authorized:Ae}),U&&(0,sr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&we(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,sr.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,sr.jsx)(Bi,{sessionId:U.sessionId,nonce:U.nonce,checkoutMode:"full",billingApiUrl:Ee,locale:I,theme:P,...Z?{appearance:Z}:{},buttonsTheme:K,buttonsStyles:k,initialErrorMessage:U.errorMessage,initialPayPalOrderId:U.payPalOrderId,cardTitleContent:null,onComplete:ht,onError:_t,onDecline:z})})})]})}var Li=require("@flopay/js/card-setup"),Zn=require("@flopay/shared"),At=require("react");var jc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Oi(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?jc.dark:jc.light,a=t.colorText??(r?"#F1F5F9":"#262833"),i=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:i?.color??a}}var Dr=require("react/jsx-runtime"),La=class extends Zn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Jr(e,t={}){let n=e instanceof Zn.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 La(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 Hc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:i=null,onReady:c,onComplete:p,onDecline:d,onCancel:g,onValidation:b,onError:T}){let[_,S]=(0,At.useState)(null),[A,I]=(0,At.useState)(null),[P,w]=(0,At.useState)(null),[K,k]=(0,At.useState)(null),[ge,q]=(0,At.useState)(null),X=(0,At.useRef)(!1),Se=(0,At.useRef)(!1),oe=(0,At.useMemo)(()=>typeof o=="object"?void 0:(0,Zn.resolveTheme)(o),[o]),De=(0,At.useMemo)(()=>typeof o=="object"?o:oe?Qo({appearance:oe.appearance,buttonsStyles:oe.buttonsLayout,layout:"default"}):null,[oe,o]),Ze=(0,At.useMemo)(()=>Si(oe?.buttonsLayout.cardFormContainer,a),[oe,a]),le=(0,At.useMemo)(()=>oe?Oi(oe):void 0,[oe]),Ee=(0,At.useRef)(c),He=(0,At.useRef)(T),Re=(0,At.useRef)(p),_e=(0,At.useRef)(d),Ie=(0,At.useRef)(g),ce=(0,At.useRef)(b),de=(0,At.useRef)(!1),Pe=(0,At.useRef)(!1),Ae=(0,At.useRef)(0);return Ee.current=c,He.current=T,Re.current=p,_e.current=d,Ie.current=g,ce.current=b,(0,At.useEffect)(()=>{let J=Ae.current+1;return Ae.current=J,()=>{queueMicrotask(()=>{Ae.current===J&&(de.current||Pe.current||(Pe.current=!0,Je(()=>{Ie.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,At.useEffect)(()=>{let J=!0,ee=new Li.PaymentAPI((0,Zn.resolveBillingApiUrl)(n),{telemetry:r});return S(null),I(null),w(null),de.current=!1,Pe.current=!1,(async()=>{try{if(!e.trim())throw new Zn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Zn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let he=await ee.getUnifiedCheckoutSession(e,t);if(!J)return;let U=he.data.session;if(!U||!(0,Zn.isCardSetupCheckoutSession)(U))throw new Zn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let we=U.vault;if(we?.html?.trim()||(we=await ee.getVaultCapture(e,t)),!we.html?.trim())throw new Zn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!J)return;I(we),S(new Li.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(he){if(!J)return;let U=Jr(he);de.current=!0,w(U),Je(()=>He.current?.(U))}})(),()=>{J=!1,ee.destroy()}},[n,t,e,r]),(0,At.useEffect)(()=>{if(!_)return;let J=!1;Se.current=!1,X.current=!1;let ee=_.on("submitting",()=>{X.current=!0,q(null),k("processing")}),he=_.on("complete",ie=>{de.current=!0,X.current=!1,k("success"),(async()=>(await new Promise(Te=>setTimeout(Te,600)),!Se.current&&(Se.current=!0,Je(()=>{Re.current?.({status:"succeeded",sessionId:e,...ie.paymentMethod?{paymentMethod:ie.paymentMethod}:{}})}),J||k(null))))()}),U=_.on("decline",ie=>{de.current=!0,X.current=!1,q(ie.message??null),k("error"),Je(()=>{_e.current?.({status:"declined",sessionId:e,...ie.declineReason?{reason:ie.declineReason}:{},...ie.message?{message:ie.message}:{}})}),(async()=>(await new Promise(Te=>setTimeout(Te,400)),J||k(null)))()}),we=_.on("challenge_dismissed",()=>{k(null)});return()=>{J=!0,ee(),he(),U(),we()}},[_,e]),P?(0,Dr.jsx)("div",{role:"alert",children:P.message}):!_||!A?.html?(0,Dr.jsx)(Dr.Fragment,{children:i}):(0,Dr.jsxs)(Dr.Fragment,{children:[K&&(0,Dr.jsx)(qn,{status:K,errorMessage:ge,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...le?{theme:le}:{}}),(0,Dr.jsx)(lo,{capture:_,html:A.html,messageToken:A.messageToken,expectedOrigin:A.expectedOrigin,theme:De,containerStyle:Ze,onReady:()=>{Je(()=>Ee.current?.())},onValidation:J=>{Je(()=>ce.current?.(J))},onError:J=>{if(!J)return;X.current&&(X.current=!1,q(J),k("error"),setTimeout(()=>k(null),400));let ee=Jr(new Error(J),{code:"card_setup_widget_failed",retryable:!0});Je(()=>He.current?.(ee))}})]})}var Wc=require("@flopay/js/card-setup"),co=require("@flopay/shared"),Kc=require("@paypal/paypal-js"),wo=require("react");var Yc=require("react/jsx-runtime");function Gc({clientId:e,environment:t,currency:n,sessionId:r,nonce:o,billingApiUrl:a,telemetry:i,customer:{userId:c,email:p},onSubmitting:d,onConfirmed:g,onFailed:b,onAbandoned:T}){let _=(0,wo.useRef)(null),S=(0,wo.useRef)({onSubmitting:d,onConfirmed:g,onFailed:b,onAbandoned:T});S.current={onSubmitting:d,onConfirmed:g,onFailed:b,onAbandoned:T};let[A]=(0,wo.useState)(()=>Kr().inAppBrowser);return(0,wo.useEffect)(()=>{let I=!0,P,w=new Wc.PaymentAPI(a,{telemetry:i}),K={userId:c,email:p};return(async()=>{try{let k=await(0,Kc.loadScript)({clientId:e,...n?{currency:n.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),ge=_.current;if(!I||!ge)return;if(!k?.Buttons)throw new co.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let q=k.Buttons({createVaultSetupToken:async()=>{S.current.onSubmitting();let X=await w.createSessionIntent(r,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(X.provider!=="paypal"||X.providerObjectType!=="setup_token")throw new co.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return X.providerObjectId},onApprove:async X=>{let Se=X.vaultSetupToken;if(!Se)throw new co.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let oe=await w.processPayment(K.userId,{sessionId:r,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:Se,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:co.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:K});if(!oe.ok)throw new co.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:oe.status});I&&S.current.onConfirmed()},onCancel:()=>{I&&S.current.onAbandoned()},onError:X=>{if(!I)return;let{popupBlocked:Se}=oo(X,{inAppBrowser:A,handoffObserved:!1});S.current.onFailed(Se?new Error(ro("PayPal",!0,A)):X,{code:Se?"popup_blocked":"paypal_setup_failed",retryable:!0})}});P=()=>q.close(),await q.render(ge)}catch(k){if(!I)return;S.current.onFailed(k,{code:"paypal_unavailable",retryable:!0})}})(),()=>{I=!1,P?.().catch(()=>{}),w.destroy()}},[a,e,n,p,t,A,o,r,i,c]),(0,Yc.jsx)("div",{ref:_,"data-flopay-paypal-setup":""})}var Jc=require("@flopay/js/card-setup"),ta=require("@flopay/shared"),Or=require("@stripe/react-stripe-js"),Zc=require("@stripe/stripe-js"),Tn=require("react");var wn=require("react/jsx-runtime"),Qc={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Gs=new Map;function gp(e){let t=Gs.get(e);if(t)return t;let n=(0,Zc.loadStripe)(e).catch(r=>{throw Gs.delete(e),r});return Gs.set(e,n),n}var hp={night:"night",flat:"flat"};function bp(e){return e?{theme:hp[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function Pp(e){return bo(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Xc(e){return e==="paypal"?"PayPal":(0,ta.getStripeMethodDisplayName)(e)}function vp(){return typeof window>"u"?"":window.location.href}var Cp={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function ed(e){let{publishableKey:t,method:n,currency:r,futureUse:o,futureUseUnsupported:a,appearance:i}=e,[c]=(0,Tn.useState)(()=>gp(t)),p=(0,Tn.useMemo)(()=>{let d=bp(i),g=(0,ta.resolveSetupFutureUsage)({futureUse:o,futureUseUnsupported:a},n,"setup");return{mode:"setup",currency:r.toLowerCase(),paymentMethodTypes:Qc[n]?.types??[n],...g?{setupFutureUsage:g}:{},...d?{appearance:d}:{}}},[i,r,o,a,n]);return(0,wn.jsx)(Or.Elements,{stripe:c,options:p,children:(0,wn.jsx)(Sp,{...e})})}function Sp({method:e,category:t,sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,appearance:i,themeId:c,buttonsLayout:p,onSubmitting:d,onConfirmed:g,onDeclined:b,onFailed:T,onValidation:_,onUnavailable:S}){let A=(0,Or.useStripe)(),I=(0,Or.useElements)(),[P,w]=(0,Tn.useState)(!1),[K,k]=(0,Tn.useState)("loading"),[ge,q]=(0,Tn.useState)(!1),[X,Se]=(0,Tn.useState)(!1),oe=(0,Tn.useRef)(!1),[De]=(0,Tn.useState)(()=>Kr()),[Ze,le]=(0,Tn.useState)(!1),Ee=(0,Tn.useCallback)((de,Pe)=>{if(oo(de,{inAppBrowser:De.inAppBrowser,handoffObserved:!1}).popupBlocked){le(!0),T(new Error(ro(Xc(e),!0,De.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}T(Pe.message===void 0?de:new Error(Pe.message),{code:Pe.code,retryable:!0})},[De.inAppBrowser,e,T]),He=(0,Tn.useCallback)(async()=>{if(!(!A||!I||oe.current)){oe.current=!0,w(!0);try{let de=await I.submit();if(de.error){_(de.error.message??null);return}d();let Pe=await new Jc.PaymentAPI(o,{telemetry:a}).createSessionIntent(n,r,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(Pe.provider!=="stripe"||Pe.intentKind!=="setup")throw new ta.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let Ae=await A.confirmSetup({elements:I,clientSecret:Pe.clientSecret,confirmParams:{return_url:vp()},redirect:"if_required"});if(Ae.error){Pp(Ae.error)?b({...Ae.error.decline_code||Ae.error.code?{reason:Ae.error.decline_code??Ae.error.code}:{},...Ae.error.message?{message:Ae.error.message}:{}}):Ee(Ae.error,{code:"payment_method_setup_provider_failed",message:Ae.error.message??"The payment method could not be saved."});return}g()}catch(de){Ee(de,{code:"payment_method_setup_failed"})}finally{oe.current=!1,w(!1)}}},[o,t,I,e,r,g,b,d,_,Ee,n,A,a]),Re=Qc[e]?.wallet,_e=Re==="paypal"&&ei(De,"auto",Ze?"blocked":De.popupCapability)==="redirect",Ie=i?.variables?.borderRadius??p?.cardButton?.borderRadius??8;if(t==="wallet"&&Re&&!_e)return(0,wn.jsxs)(wn.Fragment,{children:[(0,wn.jsx)(Jo,{}),(0,wn.jsx)(Ta,{state:K,borderRadius:Ie,children:(0,wn.jsx)(Or.ExpressCheckoutElement,{options:{...Pi,paymentMethods:bi([e])},onReady:de=>{let Pe=_a(de,[Re]);k(Pe),Pe==="unavailable"&&S()},onLoadError:()=>{k("load_error"),S()},onConfirm:()=>{He()}})})]});let ce=Xc(e);return(0,wn.jsxs)(wn.Fragment,{children:[ge?(0,wn.jsx)(hi,{method:e,themeId:c,hasNextStep:!0,highlighted:X,disabled:P,onClick:()=>Se(de=>!de),backgroundColor:p?.cardButton?.backgroundColor,borderColor:p?.cardInputBorder,textColor:p?.cardButton?.color,borderRadius:Ie}):null,(0,wn.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!X,style:X?{display:"flex",flexDirection:"column"}:Cp,children:[(0,wn.jsx)(Or.PaymentElement,{options:{layout:vi},onReady:()=>q(!0),onLoadError:()=>S(),onChange:de=>{de.complete&&_(null)}}),(0,wn.jsx)(Ci,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!A||!I||P||!X,onClick:()=>{He()},color:i?.variables?.colorPrimary??"#4A49FF",borderRadius:i?.variables?.borderRadius??"8px",style:p?.submitButton,children:P?"Saving\u2026":`Save ${ce}`})]})]})}var Na=require("@flopay/js/card-setup"),vn=require("@flopay/shared"),Ue=is(require("react"),1);var td=require("@flopay/shared"),wp=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]),kp=new Set(["wallet","apm"]);function na(e){return typeof e=="string"&&e.trim().length>0}function Rp(e){if(typeof e!="object"||e===null)return!1;let t=e;return na(t.family)&&na(t.paymentMethodType)}function Ip(e){let n=e.raw?.data?.currency;return na(n)?n.trim().toUpperCase():null}function nd(e){let t=Ip(e),n=e.data.session?.advertisedPaymentMethods;if(!Array.isArray(n))return{card:!0,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]};let r={card:!1,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]},o=new Set;for(let a of n){if(!Rp(a)||o.has(a.paymentMethodType))continue;let{family:i,paymentMethodType:c,providerType:p,publishableKey:d}=a;if(i==="card"){if(c!=="card")continue;r.card=!0}else if(kp.has(i)){if(p!=="stripe"||c==="card"||!na(d))continue;if(t===null){r.skippedForMissingCurrency.includes(c)||r.skippedForMissingCurrency.push(c);continue}r.stripe.push({method:c,publishableKey:d,currency:t})}else if(i==="paypal"){if(c!==td.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE||p!=="paypal"||!na(d))continue;r.paypal={clientId:d,...na(a.environment)?{environment:a.environment}:{}}}else continue;o.add(c)}return r.paypal&&(r.stripe=r.stripe.filter(a=>a.method!=="paypal")),r}function Ni(e){return[...e.card?["card"]:[],...e.stripe.map(t=>t.method),...e.paypal?["paypal"]:[]]}function rd(e){return Ni(e).length>0}function Ui(e){return wp.has(e)?"wallet":"apm"}var Ep=["setup_intent","setup_intent_client_secret","redirect_status"];function od(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function ad(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let n of Ep)e.searchParams.has(n)&&(e.searchParams.delete(n),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}function id(e){return e==="card"?{processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED"}:{processingLabel:"SAVING PAYMENT METHOD...",successLabel:"PAYMENT METHOD SAVED",errorLabel:"PAYMENT METHOD NOT SAVED"}}var Qt=require("react/jsx-runtime"),_p=15,Tp=2e3;function Ap(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Ys(e){return new Promise(t=>setTimeout(t,e))}async function Mp(e,t,n){if(!t.trim())throw new vn.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!n.trim())throw new vn.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let r=await e.getUnifiedCheckoutSession(t,n),o=r.data.session;if(!o||!(0,vn.isCardSetupCheckoutSession)(o))throw new vn.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let a=nd(r);if(!rd(a)){let{skippedForMissingCurrency:i}=a,c=i.length>0?`FloPay: this setup session advertises only Stripe methods (${i.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new vn.FloPayError(c,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:o,advertisement:a}}async function xp(e,t,n,r){let o=t.vault??null;if(o?.html?.trim()||(o=await e.getVaultCapture(n,r)),!o.html?.trim())throw new vn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return o}var zi=class extends Ue.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(n){this.props.onFailed(n,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function sd({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,theme:i="modern-light",containerStyle:c,loading:p=null,onReady:d,onComplete:g,onDecline:b,onCancel:T,onValidation:_,onError:S}){let[A]=(0,Ue.useState)(od),[I,P]=(0,Ue.useState)(null),[w,K]=(0,Ue.useState)(!1),[k,ge]=(0,Ue.useState)(null),[q,X]=(0,Ue.useState)(null),[Se,oe]=(0,Ue.useState)(null),[De,Ze]=(0,Ue.useState)(null),[le,Ee]=(0,Ue.useState)(()=>new Set),He=(0,Ue.useRef)(le),Re=(0,Ue.useRef)(null);Re.current=I;let _e=(0,Ue.useRef)(!1),Ie=(0,Ue.useRef)(!1),ce=(0,Ue.useRef)(!1),de=(0,Ue.useRef)(!1),Pe=(0,Ue.useRef)(0),Ae=(0,Ue.useRef)(0),J=(0,Ue.useRef)(!1),ee=(0,Ue.useMemo)(()=>typeof i=="object"?void 0:(0,vn.resolveTheme)(i),[i]),he=(0,Ue.useMemo)(()=>typeof i=="object"?i:ee?Qo({appearance:ee.appearance,buttonsStyles:ee.buttonsLayout,layout:"default"}):null,[ee,i]),U=(0,Ue.useMemo)(()=>Si(ee?.buttonsLayout.cardFormContainer,c),[ee,c]),we=(0,Ue.useMemo)(()=>ee?Oi(ee):void 0,[ee]),ie=(0,Ue.useRef)({sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:d,onComplete:g,onDecline:b,onCancel:T,onValidation:_,onError:S});ie.current={sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:d,onComplete:g,onDecline:b,onCancel:T,onValidation:_,onError:S},(0,Ue.useEffect)(()=>{J.current=!0;let F=Pe.current+1;return Pe.current=F,()=>{J.current=!1,Ae.current+=1,queueMicrotask(()=>{Pe.current===F&&(ce.current||de.current||(de.current=!0,Je(()=>{ie.current.onCancel?.({status:"cancelled",sessionId:n})})))})}},[n]);let Te=(0,Ue.useCallback)((F,B)=>{ce.current=!0,_e.current=!1,Ze({status:"success",wording:F,message:null}),(async()=>(await Ys(600),!Ie.current&&(Ie.current=!0,Je(()=>{ie.current.onComplete?.({status:"succeeded",sessionId:ie.current.sessionId,...B?{paymentMethod:B}:{}})}),J.current&&Ze(null))))()},[]),te=(0,Ue.useCallback)((F,B)=>{ce.current=!0,_e.current=!1,Ze({status:"error",wording:F,message:B.message??null}),Je(()=>{ie.current.onDecline?.({status:"declined",sessionId:ie.current.sessionId,...B.reason?{reason:B.reason}:{},...B.message?{message:B.message}:{}})}),(async()=>(await Ys(400),J.current&&Ze(null)))()},[]),at=(0,Ue.useCallback)((F,B)=>{_e.current?(_e.current=!1,Ze({status:"error",wording:F,message:B.message}),setTimeout(()=>{J.current&&Ze(null)},400)):Ze(null),Je(()=>ie.current.onError?.(B))},[]),We=(0,Ue.useCallback)(async F=>{let B=Ae.current+1;Ae.current=B;let ue=()=>!J.current||B!==Ae.current;_e.current=!0,Ze({status:"processing",wording:"payment_method",message:null});let D=new Na.PaymentAPI((0,vn.resolveBillingApiUrl)(ie.current.billingApiUrl),{telemetry:ie.current.telemetry});try{for(let Me=0;Me<_p;Me+=1){if((Me>0||F.waitFirst)&&await Ys(Tp),ue())return;let st=await D.getUnifiedCheckoutSession(ie.current.sessionId,ie.current.nonce);if(ue())return;let yt=st.data.session?.status;if(yt==="complete"){K(!0),Te("payment_method");return}if(yt==="expired")throw new vn.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new vn.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(Me){if(ue())return;let st=Me instanceof vn.FloPayError&&Me.code==="payment_method_setup_unverified";at("payment_method",Jr(Me,st?{retryable:!0}:{}))}finally{D.destroy()}},[at,Te]);(0,Ue.useEffect)(()=>{let F=!0,B=new Na.PaymentAPI((0,vn.resolveBillingApiUrl)(o),{telemetry:a});P(null),K(!1),ge(null),X(null),oe(null);let ue=new Set;return He.current=ue,Ee(ue),ce.current=!1,de.current=!1,Ie.current=!1,(async()=>{try{let{session:D,advertisement:Me}=await Mp(B,n,r);if(!F)return;let st={advertisement:Me,customer:Ap(D),...D.futureUse?{futureUse:D.futureUse}:{},...D.futureUseUnsupported?{futureUseUnsupported:D.futureUseUnsupported}:{}};if(A){if(ad(),D.status==="complete"){K(!0),P(st),Te("payment_method");return}A.failed?te("payment_method",{reason:"redirect_failed"}):We({waitFirst:!0})}let yt=Me.card?await xp(B,D,n,r):null;if(!F)return;P(st),yt&&(X(yt),ge(new Na.PciVaultCardCapture({sessionId:n,operation:"card_setup",telemetry:a})))}catch(D){if(!F)return;let Me=Jr(D);ce.current=!0,oe(Me),Je(()=>ie.current.onError?.(Me))}})(),()=>{F=!1,B.destroy()}},[o,r,A,te,Te,n,a,We]),(0,Ue.useEffect)(()=>{if(!k)return;_e.current=!1;let F=k.on("submitting",()=>{_e.current=!0,Ze({status:"processing",wording:"card",message:null})}),B=k.on("complete",Me=>{Te("card",Me.paymentMethod)}),ue=k.on("decline",Me=>{te("card",{...Me.declineReason?{reason:Me.declineReason}:{},...Me.message?{message:Me.message}:{}})}),D=k.on("challenge_dismissed",()=>{Ze(null)});return()=>{F(),B(),ue(),D()}},[k,te,Te]);let Ve=(0,Ue.useCallback)((F,B,ue)=>{if(ue.retryable){at("payment_method",Jr(B,ue));return}if(He.current.has(F))return;let D=new Set(He.current);D.add(F),He.current=D,Ee(D);let Me=Re.current?.advertisement,st=Me?Ni(Me).some(yt=>!D.has(yt)):!1;at("payment_method",Jr(B,{code:ue.code,retryable:st}))},[at]),ot=(0,Ue.useMemo)(()=>({onSubmitting:()=>{_e.current=!0,Ze({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{We({waitFirst:!1})},onDeclined:F=>te("payment_method",F),onValidation:F=>{Je(()=>ie.current.onValidation?.(F))},onAbandoned:()=>{_e.current=!1,Ze(null)}}),[te,We]),Ke=(0,Ue.useRef)(Ve);Ke.current=Ve;let it=(0,Ue.useRef)(new Map),$e=F=>{let B=it.current.get(F);if(B)return B;let ue=(D,Me)=>Ke.current(F,D,Me);return it.current.set(F,ue),ue},vt=(0,Ue.useCallback)(F=>{if(He.current.has(F))return;let B=new Set(He.current);B.add(F),He.current=B,Ee(B);let ue=Re.current?.advertisement;ue&&Ni(ue).some(Me=>!B.has(Me))||at("payment_method",Jr(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[at]),Ot=(0,Ue.useRef)(vt);Ot.current=vt;let ht=(0,Ue.useRef)(new Map),_t=F=>{let B=ht.current.get(F);if(B)return B;let ue=()=>Ot.current(F);return ht.current.set(F,ue),ue},z=De?(0,Qt.jsx)(qn,{status:De.status,errorMessage:De.message,...id(De.wording),successNote:null,...we?{theme:we}:{}}):null;if(Se)return(0,Qt.jsx)("div",{role:"alert",children:Se.message});if(!I||w)return(0,Qt.jsxs)(Qt.Fragment,{children:[z,I?null:p]});let{advertisement:be,customer:Qe,futureUse:Z,futureUseUnsupported:Le}=I,bt=(0,vn.resolveBillingApiUrl)(o),Ye=a===void 0?{}:{telemetry:a},It=be.stripe.filter(({method:F})=>!le.has(F)),$=le.has("paypal")?null:be.paypal,h=!!(be.card&&k&&q?.html),C=({method:F,publishableKey:B,currency:ue})=>(0,Qt.jsx)("div",{"data-flopay-payment-method":F,style:{display:"contents"},children:(0,Qt.jsx)(zi,{onFailed:$e(F),children:(0,Qt.jsx)(Ue.Suspense,{fallback:null,children:(0,Qt.jsx)(e,{method:F,category:Ui(F),publishableKey:B,currency:ue,...Z?{futureUse:Z}:{},...Le?{futureUseUnsupported:Le}:{},sessionId:n,nonce:r,billingApiUrl:bt,...Ye,...ee?{appearance:ee.appearance,buttonsLayout:ee.buttonsLayout}:{},...typeof i=="string"?{themeId:i}:{},...ot,onFailed:$e(F),onUnavailable:_t(F)})})})},F),Y=It.filter(({method:F})=>Ui(F)==="wallet"),W=It.filter(({method:F})=>Ui(F)!=="wallet"),ve=It.length>0||$!==null;return(0,Qt.jsxs)(Qt.Fragment,{children:[z,ve?(0,Qt.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Y.map(C),$?(0,Qt.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,Qt.jsx)(zi,{onFailed:$e("paypal"),children:(0,Qt.jsx)(Ue.Suspense,{fallback:null,children:(0,Qt.jsx)(t,{clientId:$.clientId,...$.environment?{environment:$.environment}:{},...be.currency?{currency:be.currency}:{},sessionId:n,nonce:r,billingApiUrl:bt,customer:Qe,...Ye,...ot,onFailed:$e("paypal"),onUnavailable:_t("paypal")})})})}):null,W.map(C)]}):null,h&&ve?(0,Qt.jsx)(wi,{label:"or add a card"}):null,h&&k&&q?.html?(0,Qt.jsx)("div",{"data-flopay-payment-method":"card",children:(0,Qt.jsx)(lo,{capture:k,html:q.html,messageToken:q.messageToken,expectedOrigin:q.expectedOrigin,theme:he,containerStyle:U,onReady:()=>{Je(()=>ie.current.onReady?.())},onValidation:F=>{Je(()=>ie.current.onValidation?.(F))},onError:F=>{F&&at("card",Jr(new Error(F),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var cd=require("react/jsx-runtime"),Fp={StripeSetupMethod:ed,PayPalSetupMethod:Gc};function ld(e){return(0,cd.jsx)(sd,{...e,branches:Fp})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,O.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&_(ta),n&&(r||o)&&_(ta),n&&(0,O.jsx)("button",{type:"button",onClick:()=>{e?.("card"),T(!0)},style:{width:"100%",...P,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:w=>{w.currentTarget.style.transform="scale(0.985)"},onMouseUp:w=>{w.currentTarget.style.transform="scale(1)"},children:(0,O.jsx)(Oo,{content:p})}),(0,O.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var sr=require("react/jsx-runtime"),hp=44;function jc(e){return new Promise(t=>setTimeout(t,e))}function bp(e,t){return e instanceof lr.FloPayError?e:new lr.FloPayError(e instanceof Error?e.message:t,"api_error")}function Pp(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function vp(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 $c({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:i,items:c,subscriptions:p,account:d,successUrl:g,cancelUrl:b,couponCodes:T,tagsData:E,utmMetadata:S,billingApiUrl:A,locale:_,theme:P,appearance:w,buttonsTheme:K,buttonsStyles:k,onSuccess:ge,onError:z,onDecline:X,children:Se,disabled:ae=!1,type:De="button",style:Ze,...le}){let Ie=(0,ct.useMemo)(()=>(0,lr.resolveBillingApiUrl)(A),[A]),He=(0,ct.useMemo)(()=>vp({createSession:n,clientId:a,products:i,items:c,subscriptions:p,account:d,successUrl:g,cancelUrl:b,couponCodes:T,tagsData:E,utmMetadata:S}),[d,b,a,T,n,i,c,p,g,E,S]),[Re,Ee]=(0,ct.useState)(!1),[_e,ce]=(0,ct.useState)(null),[de,Pe]=(0,ct.useState)(null),[Ae,J]=(0,ct.useState)(!1),[ee,he]=(0,ct.useState)(null),[U,we]=(0,ct.useState)(null),ie=(0,ct.useRef)(!0),Te=(0,ct.useRef)(null),te=(0,ct.useRef)(U),at=(0,ct.useRef)(ge),We=(0,ct.useRef)(z),je=(0,ct.useRef)(X),ot=(0,ct.useCallback)(h=>yi(Te,async C=>{try{return await h(C)}catch(Y){throw C.aborted?lo(Y):Y}}),[]);(0,ct.useEffect)(()=>{te.current=U},[U]),(0,ct.useEffect)(()=>{at.current=ge},[ge]),(0,ct.useEffect)(()=>{We.current=z},[z]),(0,ct.useEffect)(()=>{je.current=X},[X]),(0,ct.useEffect)(()=>(ie.current=!0,()=>{ie.current=!1,Te.current?.abort()}),[]),(0,ct.useEffect)(()=>{if(typeof window>"u")return;let h=C=>{C.key==="Escape"&&we(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let Ke=(0,ct.useCallback)((h,C=Ia)=>{je.current?.(mn(C,h,{code:h.code,declineCode:h.declineCode}))},[]),it=(0,ct.useCallback)(async h=>{ie.current&&(Pe(null),J(h.result.status==="authorized"),ce("success"),await jc(600),ie.current&&Je(()=>at.current?.(h)))},[]),$e=(0,ct.useCallback)(async(h,C)=>{ie.current&&(We.current?.(h),C?.emitDecline&&Ke(h,C.method),Pe(h.message),J(!1),ce("error"),await jc(400))},[Ke]),vt=(0,ct.useCallback)(async(h,C,Y)=>{let W=h.data.session??null;if(!W)throw to(new lr.FloPayError("No session data returned","api_error"),C);let ve=W.clientSecret||t;if(Hr(W)){await it({result:$r(W,C),session:W,sessionId:W.id||C,autoCompleted:!1});return}if(W.status==="expired")throw to(Za(W),W.id||C);try{if(h.autoProcessingPending){let B=h.autoProcessingPending,ue=new Oi.PaymentAPI(Ie),D=await ot(yt=>ue.waitForCheckoutSessionCompletion(B.sessionId,{initialDelayMs:B.retryAfterMs,nonce:ve,statusUrl:B.statusUrl,signal:yt})),Me=ro(D,W),st=D.autoProcessingError?.type==="3ds_required"&&D.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:D.autoProcessingError.nextActionRedirectUrl}:null;if(st&&C&&ve){let yt=await ot(Ct=>Go(st,{billingApiUrl:Ie,sessionId:C,nonce:ve,session:W,signal:Ct,telemetry:!0}));await it({result:yt,session:W,sessionId:W.id||C,autoCompleted:!1});return}if(D.autoProcessingError)throw xr(D.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.autoProcessingError.checkoutMethod});if(!Hr(Me))throw Uo(Me);await it({result:$r(Me,C),session:Me,sessionId:Me.id||C,autoCompleted:!1});return}if(h.autoProcessingError){let B=h.autoProcessingError.nextActionRedirectUrl;if(h.autoProcessingError.type==="3ds_required"&&B&&C&&ve){let ue=await ot(yt=>ks({billingApiUrl:Ie,sessionId:C,nonce:ve,nextActionRedirectUrl:B,signal:yt}));if(ue.status==="declined")throw xr({type:ue.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ue.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Me=await new Oi.PaymentAPI(Ie).waitForCheckoutSessionCompletion(C,{initialDelayMs:0,nonce:ve}),st=ro(Me,W);if(!Hr(st))throw xr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await it({result:$r(st,C),session:st,sessionId:st.id||C,autoCompleted:!1});return}throw xr(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(Y?.fromCreateSession&&h.autoProcessingAttempted===!0)throw xr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let x=await Yo({billingApiUrl:Ie,sessionId:C??W.id,session:W,nonce:ve});if(x.type==="next_action_required"&&ve){let B=C??W.id,ue=await ot(D=>Go(x,{billingApiUrl:Ie,sessionId:B,nonce:ve,session:W,signal:D,telemetry:!0}));await it({result:ue,session:W,sessionId:W.id||B,autoCompleted:!1});return}if(x.type!=="success")throw xr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await it({result:x.result,session:W,sessionId:W.id||C,autoCompleted:!1})}catch(x){let B=W.id||C,ue=to(Ea(x),B);if(ue.code==="three_ds_aborted")return;if(ue.code==="checkout_processing_timeout"){if(!ie.current)return;he(ue.message),Je(()=>We.current?.(ue));return}await $e(ue,{emitDecline:!0,method:ue.checkoutMethod??Ia}),Pp(ue,B)&&B&&ie.current&&we({sessionId:B,errorMessage:ue.message,nonce:ve||void 0,payPalOrderId:ue.orderId})}},[t,Ie,ot,$e,it]),Lt=(0,ct.useCallback)(async h=>{if(le.onClick?.(h),!(h.defaultPrevented||ae||Re)){if(we(null),he(null),e&&He){let C=new lr.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await $e(C),ie.current&&(ce(null),Pe(null));return}if(!e&&!He){let C=new lr.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $e(C),ie.current&&(ce(null),Pe(null));return}Ee(!0),Pe(null),J(!1),ce("processing");try{let C=new Oi.PaymentAPI(Ie);if(e){let Y=await C.getUnifiedCheckoutSession(e,t);await vt(Y,e);return}try{let Y=await C.createAndFetchSession({...He});await vt(Y,Y.data.session?.id??null,{fromCreateSession:!0})}catch(Y){if(Qa(Y)==="session_auto_completed"){await it({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Y}}catch(C){await $e(to(bp(C,"Automatic payment failed. Please try again."),e))}finally{ie.current&&(ce(null),Pe(null),Ee(!1))}}},[le.onClick,He,ae,Re,t,vt,Ie,e,$e,it]),ht=(0,ct.useCallback)(h=>{let C=te.current;we(null),at.current?.({result:h,session:null,sessionId:C?.sessionId??null,autoCompleted:!1})},[]),Tt=(0,ct.useCallback)(h=>{We.current?.(h)},[]),V=(0,ct.useCallback)(h=>{je.current?.(h)},[]),be=(0,ct.useMemo)(()=>(0,lr.resolveTheme)(P),[P]),Qe=(0,ct.useMemo)(()=>{let h=be?.buttonsLayout??(0,lr.resolveButtonsLayoutTheme)(K);return k?{...h,...k,cardButton:{...h.cardButton,...k.cardButton}}:h},[be,K,k]),Z=(0,ct.useMemo)(()=>{let h=be?.appearance;return w?h?{...h,...w,variables:{...h.variables,...w.variables}}:w:h},[w,be]),Le=Z?.variables,bt=Le?.colorPrimary??"#4A49FF",Ye=Le?.colorPrimaryHover??Qo(bt,.12),_t=Le?.borderRadius??"8px";return(0,sr.jsxs)(sr.Fragment,{children:[(0,sr.jsx)("button",{...le,type:De,onClick:Lt,disabled:ae||Re,"aria-busy":Re,style:{width:"100%",...Se===void 0?{boxSizing:"border-box",height:hp,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Qe.cardButton,...qs({themeBundle:be,resolvedPrimaryColor:bt,resolvedBorderRadius:_t,submitButtonStyle:Qe.submitButton,explicitPrimaryColor:Le?.colorPrimary}),fontSize:Qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ae||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:ae||Re?.6:1,...Ze},onMouseEnter:h=>{le.onMouseEnter?.(h),!h.defaultPrevented&&!ae&&!Re&&(be||Le?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ye)},onMouseLeave:h=>{le.onMouseLeave?.(h),!h.defaultPrevented&&(be||Le?.colorPrimary)&&(h.currentTarget.style.backgroundColor=bt)},onMouseDown:h=>{le.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{le.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:(0,sr.jsx)(Oo,{content:Se})}),ee&&(0,sr.jsx)("p",{role:"status","data-testid":"flopay-automatic-payment-pending-notice",style:{margin:"0.5rem 0 0",fontSize:"0.875rem",textAlign:"center"},children:ee}),_e&&(0,sr.jsx)(zn,{status:_e,errorMessage:de,authorized:Ae}),U&&(0,sr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&we(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,sr.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,sr.jsx)(Di,{sessionId:U.sessionId,nonce:U.nonce,checkoutMode:"full",billingApiUrl:Ie,locale:_,theme:P,...Z?{appearance:Z}:{},buttonsTheme:K,buttonsStyles:k,initialErrorMessage:U.errorMessage,initialPayPalOrderId:U.payPalOrderId,cardTitleContent:null,onComplete:ht,onError:Tt,onDecline:V})})})]})}var Ni=require("@flopay/js/card-setup"),Zn=require("@flopay/shared"),At=require("react");var Hc={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function Li(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?Hc.dark:Hc.light,a=t.colorText??(r?"#F1F5F9":"#262833"),i=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:i?.color??a}}var Br=require("react/jsx-runtime"),Na=class extends Zn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Zr(e,t={}){let n=e instanceof Zn.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 Na(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 Wc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:i=null,onReady:c,onComplete:p,onDecline:d,onCancel:g,onValidation:b,onError:T}){let[E,S]=(0,At.useState)(null),[A,_]=(0,At.useState)(null),[P,w]=(0,At.useState)(null),[K,k]=(0,At.useState)(null),[ge,z]=(0,At.useState)(null),X=(0,At.useRef)(!1),Se=(0,At.useRef)(!1),ae=(0,At.useMemo)(()=>typeof o=="object"?void 0:(0,Zn.resolveTheme)(o),[o]),De=(0,At.useMemo)(()=>typeof o=="object"?o:ae?ea({appearance:ae.appearance,buttonsStyles:ae.buttonsLayout,layout:"default"}):null,[ae,o]),Ze=(0,At.useMemo)(()=>wi(ae?.buttonsLayout.cardFormContainer,a),[ae,a]),le=(0,At.useMemo)(()=>ae?Li(ae):void 0,[ae]),Ie=(0,At.useRef)(c),He=(0,At.useRef)(T),Re=(0,At.useRef)(p),Ee=(0,At.useRef)(d),_e=(0,At.useRef)(g),ce=(0,At.useRef)(b),de=(0,At.useRef)(!1),Pe=(0,At.useRef)(!1),Ae=(0,At.useRef)(0);return Ie.current=c,He.current=T,Re.current=p,Ee.current=d,_e.current=g,ce.current=b,(0,At.useEffect)(()=>{let J=Ae.current+1;return Ae.current=J,()=>{queueMicrotask(()=>{Ae.current===J&&(de.current||Pe.current||(Pe.current=!0,Je(()=>{_e.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,At.useEffect)(()=>{let J=!0,ee=new Ni.PaymentAPI((0,Zn.resolveBillingApiUrl)(n),{telemetry:r});return S(null),_(null),w(null),de.current=!1,Pe.current=!1,(async()=>{try{if(!e.trim())throw new Zn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Zn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let he=await ee.getUnifiedCheckoutSession(e,t);if(!J)return;let U=he.data.session;if(!U||!(0,Zn.isCardSetupCheckoutSession)(U))throw new Zn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let we=U.vault;if(we?.html?.trim()||(we=await ee.getVaultCapture(e,t)),!we.html?.trim())throw new Zn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!J)return;_(we),S(new Ni.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(he){if(!J)return;let U=Zr(he);de.current=!0,w(U),Je(()=>He.current?.(U))}})(),()=>{J=!1,ee.destroy()}},[n,t,e,r]),(0,At.useEffect)(()=>{if(!E)return;let J=!1;Se.current=!1,X.current=!1;let ee=E.on("submitting",()=>{X.current=!0,z(null),k("processing")}),he=E.on("complete",ie=>{de.current=!0,X.current=!1,k("success"),(async()=>(await new Promise(Te=>setTimeout(Te,600)),!Se.current&&(Se.current=!0,Je(()=>{Re.current?.({status:"succeeded",sessionId:e,...ie.paymentMethod?{paymentMethod:ie.paymentMethod}:{}})}),J||k(null))))()}),U=E.on("decline",ie=>{de.current=!0,X.current=!1,z(ie.message??null),k("error"),Je(()=>{Ee.current?.({status:"declined",sessionId:e,...ie.declineReason?{reason:ie.declineReason}:{},...ie.message?{message:ie.message}:{}})}),(async()=>(await new Promise(Te=>setTimeout(Te,400)),J||k(null)))()}),we=E.on("challenge_dismissed",()=>{k(null)});return()=>{J=!0,ee(),he(),U(),we()}},[E,e]),P?(0,Br.jsx)("div",{role:"alert",children:P.message}):!E||!A?.html?(0,Br.jsx)(Br.Fragment,{children:i}):(0,Br.jsxs)(Br.Fragment,{children:[K&&(0,Br.jsx)(zn,{status:K,errorMessage:ge,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...le?{theme:le}:{}}),(0,Br.jsx)(co,{capture:E,html:A.html,messageToken:A.messageToken,expectedOrigin:A.expectedOrigin,theme:De,containerStyle:Ze,onReady:()=>{Je(()=>Ie.current?.())},onValidation:J=>{Je(()=>ce.current?.(J))},onError:J=>{if(!J)return;X.current&&(X.current=!1,z(J),k("error"),setTimeout(()=>k(null),400));let ee=Zr(new Error(J),{code:"card_setup_widget_failed",retryable:!0});Je(()=>He.current?.(ee))}})]})}var Kc=require("@flopay/js/card-setup"),uo=require("@flopay/shared"),Gc=require("@paypal/paypal-js"),ko=require("react");var Xc=require("react/jsx-runtime");function Yc({clientId:e,environment:t,currency:n,sessionId:r,nonce:o,billingApiUrl:a,telemetry:i,customer:{userId:c,email:p},onSubmitting:d,onConfirmed:g,onFailed:b,onAbandoned:T}){let E=(0,ko.useRef)(null),S=(0,ko.useRef)({onSubmitting:d,onConfirmed:g,onFailed:b,onAbandoned:T});S.current={onSubmitting:d,onConfirmed:g,onFailed:b,onAbandoned:T};let[A]=(0,ko.useState)(()=>Gr().inAppBrowser);return(0,ko.useEffect)(()=>{let _=!0,P,w=new Kc.PaymentAPI(a,{telemetry:i}),K={userId:c,email:p};return(async()=>{try{let k=await(0,Gc.loadScript)({clientId:e,...n?{currency:n.toUpperCase()}:{},components:"buttons",...t==="sandbox"||t==="production"?{environment:t}:{}}),ge=E.current;if(!_||!ge)return;if(!k?.Buttons)throw new uo.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let z=k.Buttons({createVaultSetupToken:async()=>{S.current.onSubmitting();let X=await w.createSessionIntent(r,o,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if(X.provider!=="paypal"||X.providerObjectType!=="setup_token")throw new uo.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return X.providerObjectId},onApprove:async X=>{let Se=X.vaultSetupToken;if(!Se)throw new uo.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let ae=await w.processPayment(K.userId,{sessionId:r,nonce:o,paymentMethodCategory:"paypal",tokenizedData:{id:Se,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:uo.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:K});if(!ae.ok)throw new uo.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:ae.status});_&&S.current.onConfirmed()},onCancel:()=>{_&&S.current.onAbandoned()},onError:X=>{if(!_)return;let{popupBlocked:Se}=ao(X,{inAppBrowser:A,handoffObserved:!1});S.current.onFailed(Se?new Error(oo("PayPal",!0,A)):X,{code:Se?"popup_blocked":"paypal_setup_failed",retryable:!0})}});P=()=>z.close(),await z.render(ge)}catch(k){if(!_)return;S.current.onFailed(k,{code:"paypal_unavailable",retryable:!0})}})(),()=>{_=!1,P?.().catch(()=>{}),w.destroy()}},[a,e,n,p,t,A,o,r,i,c]),(0,Xc.jsx)("div",{ref:E,"data-flopay-paypal-setup":""})}var Zc=require("@flopay/js/card-setup"),na=require("@flopay/shared"),Dr=require("@stripe/react-stripe-js"),Qc=require("@stripe/stripe-js"),En=require("react");var Sn=require("react/jsx-runtime"),ed={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Ys=new Map;function Cp(e){let t=Ys.get(e);if(t)return t;let n=(0,Qc.loadStripe)(e).catch(r=>{throw Ys.delete(e),r});return Ys.set(e,n),n}var Sp={night:"night",flat:"flat"};function wp(e){return e?{theme:Sp[e.theme??"default"]??"stripe",...e.variables?{variables:e.variables}:{},...e.rules?{rules:e.rules}:{}}:void 0}function kp(e){return Po(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function Jc(e){return e==="paypal"?"PayPal":(0,na.getStripeMethodDisplayName)(e)}function Rp(){return typeof window>"u"?"":window.location.href}var _p={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"};function td(e){let{publishableKey:t,method:n,currency:r,futureUse:o,futureUseUnsupported:a,appearance:i}=e,[c]=(0,En.useState)(()=>Cp(t)),p=(0,En.useMemo)(()=>{let d=wp(i),g=(0,na.resolveSetupFutureUsage)({futureUse:o,futureUseUnsupported:a},n,"setup");return{mode:"setup",currency:r.toLowerCase(),paymentMethodTypes:ed[n]?.types??[n],...g?{setupFutureUsage:g}:{},...d?{appearance:d}:{}}},[i,r,o,a,n]);return(0,Sn.jsx)(Dr.Elements,{stripe:c,options:p,children:(0,Sn.jsx)(Ip,{...e})})}function Ip({method:e,category:t,sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,appearance:i,themeId:c,buttonsLayout:p,onSubmitting:d,onConfirmed:g,onDeclined:b,onFailed:T,onValidation:E,onUnavailable:S}){let A=(0,Dr.useStripe)(),_=(0,Dr.useElements)(),[P,w]=(0,En.useState)(!1),[K,k]=(0,En.useState)("loading"),[ge,z]=(0,En.useState)(!1),[X,Se]=(0,En.useState)(!1),ae=(0,En.useRef)(!1),[De]=(0,En.useState)(()=>Gr()),[Ze,le]=(0,En.useState)(!1),Ie=(0,En.useCallback)((de,Pe)=>{if(ao(de,{inAppBrowser:De.inAppBrowser,handoffObserved:!1}).popupBlocked){le(!0),T(new Error(oo(Jc(e),!0,De.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}T(Pe.message===void 0?de:new Error(Pe.message),{code:Pe.code,retryable:!0})},[De.inAppBrowser,e,T]),He=(0,En.useCallback)(async()=>{if(!(!A||!_||ae.current)){ae.current=!0,w(!0);try{let de=await _.submit();if(de.error){E(de.error.message??null);return}d();let Pe=await new Zc.PaymentAPI(o,{telemetry:a}).createSessionIntent(n,r,{provider:"stripe",paymentMethodCategory:t,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if(Pe.provider!=="stripe"||Pe.intentKind!=="setup")throw new na.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});let Ae=await A.confirmSetup({elements:_,clientSecret:Pe.clientSecret,confirmParams:{return_url:Rp()},redirect:"if_required"});if(Ae.error){kp(Ae.error)?b({...Ae.error.decline_code||Ae.error.code?{reason:Ae.error.decline_code??Ae.error.code}:{},...Ae.error.message?{message:Ae.error.message}:{}}):Ie(Ae.error,{code:"payment_method_setup_provider_failed",message:Ae.error.message??"The payment method could not be saved."});return}g()}catch(de){Ie(de,{code:"payment_method_setup_failed"})}finally{ae.current=!1,w(!1)}}},[o,t,_,e,r,g,b,d,E,Ie,n,A,a]),Re=ed[e]?.wallet,Ee=Re==="paypal"&&ti(De,"auto",Ze?"blocked":De.popupCapability)==="redirect",_e=i?.variables?.borderRadius??p?.cardButton?.borderRadius??8;if(t==="wallet"&&Re&&!Ee)return(0,Sn.jsxs)(Sn.Fragment,{children:[(0,Sn.jsx)(Zo,{}),(0,Sn.jsx)(Aa,{state:K,borderRadius:_e,children:(0,Sn.jsx)(Dr.ExpressCheckoutElement,{options:{...vi,paymentMethods:Pi([e])},onReady:de=>{let Pe=Ta(de,[Re]);k(Pe),Pe==="unavailable"&&S()},onLoadError:()=>{k("load_error"),S()},onConfirm:()=>{He()}})})]});let ce=Jc(e);return(0,Sn.jsxs)(Sn.Fragment,{children:[ge?(0,Sn.jsx)(bi,{method:e,themeId:c,hasNextStep:!0,highlighted:X,disabled:P,onClick:()=>Se(de=>!de),backgroundColor:p?.cardButton?.backgroundColor,borderColor:p?.cardInputBorder,textColor:p?.cardButton?.color,borderRadius:_e}):null,(0,Sn.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!X,style:X?{display:"flex",flexDirection:"column"}:_p,children:[(0,Sn.jsx)(Dr.PaymentElement,{options:{layout:Ci},onReady:()=>z(!0),onLoadError:()=>S(),onChange:de=>{de.complete&&E(null)}}),(0,Sn.jsx)(Si,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!A||!_||P||!X,onClick:()=>{He()},color:i?.variables?.colorPrimary??"#4A49FF",borderRadius:i?.variables?.borderRadius??"8px",style:p?.submitButton,children:P?"Saving\u2026":`Save ${ce}`})]})]})}var Ua=require("@flopay/js/card-setup"),Pn=require("@flopay/shared"),Ue=ss(require("react"),1);var nd=require("@flopay/shared"),Ep=new Set(["apple_pay","google_pay","link","paypal","amazon_pay"]),Tp=new Set(["wallet","apm"]);function ra(e){return typeof e=="string"&&e.trim().length>0}function Ap(e){if(typeof e!="object"||e===null)return!1;let t=e;return ra(t.family)&&ra(t.paymentMethodType)}function Mp(e){let n=e.raw?.data?.currency;return ra(n)?n.trim().toUpperCase():null}function rd(e){let t=Mp(e),n=e.data.session?.advertisedPaymentMethods;if(!Array.isArray(n))return{card:!0,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]};let r={card:!1,stripe:[],paypal:null,currency:t,skippedForMissingCurrency:[]},o=new Set;for(let a of n){if(!Ap(a)||o.has(a.paymentMethodType))continue;let{family:i,paymentMethodType:c,providerType:p,publishableKey:d}=a;if(i==="card"){if(c!=="card")continue;r.card=!0}else if(Tp.has(i)){if(p!=="stripe"||c==="card"||!ra(d))continue;if(t===null){r.skippedForMissingCurrency.includes(c)||r.skippedForMissingCurrency.push(c);continue}r.stripe.push({method:c,publishableKey:d,currency:t})}else if(i==="paypal"){if(c!==nd.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE||p!=="paypal"||!ra(d))continue;r.paypal={clientId:d,...ra(a.environment)?{environment:a.environment}:{}}}else continue;o.add(c)}return r.paypal&&(r.stripe=r.stripe.filter(a=>a.method!=="paypal")),r}function Ui(e){return[...e.card?["card"]:[],...e.stripe.map(t=>t.method),...e.paypal?["paypal"]:[]]}function od(e){return Ui(e).length>0}function zi(e){return Ep.has(e)?"wallet":"apm"}var xp=["setup_intent","setup_intent_client_secret","redirect_status"];function ad(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function id(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let n of xp)e.searchParams.has(n)&&(e.searchParams.delete(n),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}function sd(e){return e==="card"?{processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED"}:{processingLabel:"SAVING PAYMENT METHOD...",successLabel:"PAYMENT METHOD SAVED",errorLabel:"PAYMENT METHOD NOT SAVED"}}var Qt=require("react/jsx-runtime"),Fp=15,Bp=2e3;function Dp(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function Xs(e){return new Promise(t=>setTimeout(t,e))}async function Op(e,t,n){if(!t.trim())throw new Pn.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!n.trim())throw new Pn.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let r=await e.getUnifiedCheckoutSession(t,n),o=r.data.session;if(!o||!(0,Pn.isCardSetupCheckoutSession)(o))throw new Pn.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let a=rd(r);if(!od(a)){let{skippedForMissingCurrency:i}=a,c=i.length>0?`FloPay: this setup session advertises only Stripe methods (${i.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new Pn.FloPayError(c,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:o,advertisement:a}}async function Lp(e,t,n,r){let o=t.vault??null;if(o?.html?.trim()||(o=await e.getVaultCapture(n,r)),!o.html?.trim())throw new Pn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return o}var qi=class extends Ue.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(n){this.props.onFailed(n,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function ld({branches:{StripeSetupMethod:e,PayPalSetupMethod:t},sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,theme:i="modern-light",containerStyle:c,loading:p=null,onReady:d,onComplete:g,onDecline:b,onCancel:T,onValidation:E,onError:S}){let[A]=(0,Ue.useState)(ad),[_,P]=(0,Ue.useState)(null),[w,K]=(0,Ue.useState)(!1),[k,ge]=(0,Ue.useState)(null),[z,X]=(0,Ue.useState)(null),[Se,ae]=(0,Ue.useState)(null),[De,Ze]=(0,Ue.useState)(null),[le,Ie]=(0,Ue.useState)(()=>new Set),He=(0,Ue.useRef)(le),Re=(0,Ue.useRef)(null);Re.current=_;let Ee=(0,Ue.useRef)(!1),_e=(0,Ue.useRef)(!1),ce=(0,Ue.useRef)(!1),de=(0,Ue.useRef)(!1),Pe=(0,Ue.useRef)(0),Ae=(0,Ue.useRef)(0),J=(0,Ue.useRef)(!1),ee=(0,Ue.useMemo)(()=>typeof i=="object"?void 0:(0,Pn.resolveTheme)(i),[i]),he=(0,Ue.useMemo)(()=>typeof i=="object"?i:ee?ea({appearance:ee.appearance,buttonsStyles:ee.buttonsLayout,layout:"default"}):null,[ee,i]),U=(0,Ue.useMemo)(()=>wi(ee?.buttonsLayout.cardFormContainer,c),[ee,c]),we=(0,Ue.useMemo)(()=>ee?Li(ee):void 0,[ee]),ie=(0,Ue.useRef)({sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:d,onComplete:g,onDecline:b,onCancel:T,onValidation:E,onError:S});ie.current={sessionId:n,nonce:r,billingApiUrl:o,telemetry:a,onReady:d,onComplete:g,onDecline:b,onCancel:T,onValidation:E,onError:S},(0,Ue.useEffect)(()=>{J.current=!0;let x=Pe.current+1;return Pe.current=x,()=>{J.current=!1,Ae.current+=1,queueMicrotask(()=>{Pe.current===x&&(ce.current||de.current||(de.current=!0,Je(()=>{ie.current.onCancel?.({status:"cancelled",sessionId:n})})))})}},[n]);let Te=(0,Ue.useCallback)((x,B)=>{ce.current=!0,Ee.current=!1,Ze({status:"success",wording:x,message:null}),(async()=>(await Xs(600),!_e.current&&(_e.current=!0,Je(()=>{ie.current.onComplete?.({status:"succeeded",sessionId:ie.current.sessionId,...B?{paymentMethod:B}:{}})}),J.current&&Ze(null))))()},[]),te=(0,Ue.useCallback)((x,B)=>{ce.current=!0,Ee.current=!1,Ze({status:"error",wording:x,message:B.message??null}),Je(()=>{ie.current.onDecline?.({status:"declined",sessionId:ie.current.sessionId,...B.reason?{reason:B.reason}:{},...B.message?{message:B.message}:{}})}),(async()=>(await Xs(400),J.current&&Ze(null)))()},[]),at=(0,Ue.useCallback)((x,B)=>{Ee.current?(Ee.current=!1,Ze({status:"error",wording:x,message:B.message}),setTimeout(()=>{J.current&&Ze(null)},400)):Ze(null),Je(()=>ie.current.onError?.(B))},[]),We=(0,Ue.useCallback)(async x=>{let B=Ae.current+1;Ae.current=B;let ue=()=>!J.current||B!==Ae.current;Ee.current=!0,Ze({status:"processing",wording:"payment_method",message:null});let D=new Ua.PaymentAPI((0,Pn.resolveBillingApiUrl)(ie.current.billingApiUrl),{telemetry:ie.current.telemetry});try{for(let Me=0;Me<Fp;Me+=1){if((Me>0||x.waitFirst)&&await Xs(Bp),ue())return;let st=await D.getUnifiedCheckoutSession(ie.current.sessionId,ie.current.nonce);if(ue())return;let yt=st.data.session?.status;if(yt==="complete"){K(!0),Te("payment_method");return}if(yt==="expired")throw new Pn.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new Pn.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(Me){if(ue())return;let st=Me instanceof Pn.FloPayError&&Me.code==="payment_method_setup_unverified";at("payment_method",Zr(Me,st?{retryable:!0}:{}))}finally{D.destroy()}},[at,Te]);(0,Ue.useEffect)(()=>{let x=!0,B=new Ua.PaymentAPI((0,Pn.resolveBillingApiUrl)(o),{telemetry:a});P(null),K(!1),ge(null),X(null),ae(null);let ue=new Set;return He.current=ue,Ie(ue),ce.current=!1,de.current=!1,_e.current=!1,(async()=>{try{let{session:D,advertisement:Me}=await Op(B,n,r);if(!x)return;let st={advertisement:Me,customer:Dp(D),...D.futureUse?{futureUse:D.futureUse}:{},...D.futureUseUnsupported?{futureUseUnsupported:D.futureUseUnsupported}:{}};if(A){if(id(),D.status==="complete"){K(!0),P(st),Te("payment_method");return}A.failed?te("payment_method",{reason:"redirect_failed"}):We({waitFirst:!0})}let yt=Me.card?await Lp(B,D,n,r):null;if(!x)return;P(st),yt&&(X(yt),ge(new Ua.PciVaultCardCapture({sessionId:n,operation:"card_setup",telemetry:a})))}catch(D){if(!x)return;let Me=Zr(D);ce.current=!0,ae(Me),Je(()=>ie.current.onError?.(Me))}})(),()=>{x=!1,B.destroy()}},[o,r,A,te,Te,n,a,We]),(0,Ue.useEffect)(()=>{if(!k)return;Ee.current=!1;let x=k.on("submitting",()=>{Ee.current=!0,Ze({status:"processing",wording:"card",message:null})}),B=k.on("complete",Me=>{Te("card",Me.paymentMethod)}),ue=k.on("decline",Me=>{te("card",{...Me.declineReason?{reason:Me.declineReason}:{},...Me.message?{message:Me.message}:{}})}),D=k.on("challenge_dismissed",()=>{Ze(null)});return()=>{x(),B(),ue(),D()}},[k,te,Te]);let je=(0,Ue.useCallback)((x,B,ue)=>{if(ue.retryable){at("payment_method",Zr(B,ue));return}if(He.current.has(x))return;let D=new Set(He.current);D.add(x),He.current=D,Ie(D);let Me=Re.current?.advertisement,st=Me?Ui(Me).some(yt=>!D.has(yt)):!1;at("payment_method",Zr(B,{code:ue.code,retryable:st}))},[at]),ot=(0,Ue.useMemo)(()=>({onSubmitting:()=>{Ee.current=!0,Ze({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{We({waitFirst:!1})},onDeclined:x=>te("payment_method",x),onValidation:x=>{Je(()=>ie.current.onValidation?.(x))},onAbandoned:()=>{Ee.current=!1,Ze(null)}}),[te,We]),Ke=(0,Ue.useRef)(je);Ke.current=je;let it=(0,Ue.useRef)(new Map),$e=x=>{let B=it.current.get(x);if(B)return B;let ue=(D,Me)=>Ke.current(x,D,Me);return it.current.set(x,ue),ue},vt=(0,Ue.useCallback)(x=>{if(He.current.has(x))return;let B=new Set(He.current);B.add(x),He.current=B,Ie(B);let ue=Re.current?.advertisement;ue&&Ui(ue).some(Me=>!B.has(Me))||at("payment_method",Zr(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[at]),Lt=(0,Ue.useRef)(vt);Lt.current=vt;let ht=(0,Ue.useRef)(new Map),Tt=x=>{let B=ht.current.get(x);if(B)return B;let ue=()=>Lt.current(x);return ht.current.set(x,ue),ue},V=De?(0,Qt.jsx)(zn,{status:De.status,errorMessage:De.message,...sd(De.wording),successNote:null,...we?{theme:we}:{}}):null;if(Se)return(0,Qt.jsx)("div",{role:"alert",children:Se.message});if(!_||w)return(0,Qt.jsxs)(Qt.Fragment,{children:[V,_?null:p]});let{advertisement:be,customer:Qe,futureUse:Z,futureUseUnsupported:Le}=_,bt=(0,Pn.resolveBillingApiUrl)(o),Ye=a===void 0?{}:{telemetry:a},_t=be.stripe.filter(({method:x})=>!le.has(x)),j=le.has("paypal")?null:be.paypal,h=!!(be.card&&k&&z?.html),C=({method:x,publishableKey:B,currency:ue})=>(0,Qt.jsx)("div",{"data-flopay-payment-method":x,style:{display:"contents"},children:(0,Qt.jsx)(qi,{onFailed:$e(x),children:(0,Qt.jsx)(Ue.Suspense,{fallback:null,children:(0,Qt.jsx)(e,{method:x,category:zi(x),publishableKey:B,currency:ue,...Z?{futureUse:Z}:{},...Le?{futureUseUnsupported:Le}:{},sessionId:n,nonce:r,billingApiUrl:bt,...Ye,...ee?{appearance:ee.appearance,buttonsLayout:ee.buttonsLayout}:{},...typeof i=="string"?{themeId:i}:{},...ot,onFailed:$e(x),onUnavailable:Tt(x)})})})},x),Y=_t.filter(({method:x})=>zi(x)==="wallet"),W=_t.filter(({method:x})=>zi(x)!=="wallet"),ve=_t.length>0||j!==null;return(0,Qt.jsxs)(Qt.Fragment,{children:[V,ve?(0,Qt.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Y.map(C),j?(0,Qt.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,Qt.jsx)(qi,{onFailed:$e("paypal"),children:(0,Qt.jsx)(Ue.Suspense,{fallback:null,children:(0,Qt.jsx)(t,{clientId:j.clientId,...j.environment?{environment:j.environment}:{},...be.currency?{currency:be.currency}:{},sessionId:n,nonce:r,billingApiUrl:bt,customer:Qe,...Ye,...ot,onFailed:$e("paypal"),onUnavailable:Tt("paypal")})})})}):null,W.map(C)]}):null,h&&ve?(0,Qt.jsx)(ki,{label:"or add a card"}):null,h&&k&&z?.html?(0,Qt.jsx)("div",{"data-flopay-payment-method":"card",children:(0,Qt.jsx)(co,{capture:k,html:z.html,messageToken:z.messageToken,expectedOrigin:z.expectedOrigin,theme:he,containerStyle:U,onReady:()=>{Je(()=>ie.current.onReady?.())},onValidation:x=>{Je(()=>ie.current.onValidation?.(x))},onError:x=>{x&&at("card",Zr(new Error(x),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var dd=require("react/jsx-runtime"),Np={StripeSetupMethod:td,PayPalSetupMethod:Yc};function cd(e){return(0,dd.jsx)(ld,{...e,branches:Np})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayPaymentMethodSetup,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});