@flopay/react 1.8.1 → 1.8.3

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.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import{a as Qe,b as Mn,c as Qo,d as Hr,e as li,f as ci,g as Rs,h as _s}from"./chunk-VWT2TDA6.mjs";import{dropThirdPartyOnlyError as Mu}from"@flopay/shared";import{PaymentAPI as Fa}from"@flopay/js";import{FloPayError as Br,resolveBillingApiUrl as cc,resolveButtonsLayoutTheme as dc,resolveTheme as uc}from"@flopay/shared";import{useCallback as tr,useEffect as xr,useMemo as oo,useRef as Ar,useState as ao}from"react";import{Fragment as Pr,jsx as hn,jsxs as di}from"react/jsx-runtime";function Ts(){return di(Pr,{children:[di("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:[hn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),hn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",hn("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:hn("path",{d:"M9 18l6-6-6-6"})})]})}function xs(){return hn(Pr,{children:"Go back"})}function As(){return hn(Pr,{children:"Secure card checkout"})}function fr(e){return e!==void 0&&(e===""||e===null||e===!1)}function gr({content:e}){return hn(Pr,{children:e===void 0?hn(Ts,{}):e})}function hr({content:e}){return hn(Pr,{children:e===void 0?hn(xs,{}):e})}function Yr({content:e}){return hn(Pr,{children:e===void 0?hn(As,{}):e})}import{FloPayError as ui,isMoneySettledOutcome as Ms,isSetupIntentClientSecret as kc}from"@flopay/shared";function pi(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function ea(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function mi(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,m)=>a+(m.overrideAmount??m.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,m)=>({uuid:`synthetic-${a.type??"item"}-${m}`,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 ta(e,t){return t?{...e,...t}:e}function Mt(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Bs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Wn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Bs)if(n.test(t))return r;return e}function lr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function br(e){return e?.status==="authorized"||e?.status==="complete"}function yi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Po(e){let t=yi(e);return new ui(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function bo(e){let t=yi(e);return new ui(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function vo(e,t){return e==="processing"||Ms(e,t)}function fi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function gi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Gr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as Oo,SESSION_CREATE_TELEMETRY as Hl}from"@flopay/js";import{buildCheckoutDisplayData as Yl,classifyTelemetryFailure as es,FloPayError as Ft,foldIntoProducts as Gl,isDetachedSessionEligible as Wl,resolveBillingApiUrl as Jl,resolveButtonsLayoutTheme as Xl,resolveIdempotencyKey as ts,resolveSessionCurrency as Zl,resolveTheme as as,SDK_VERSION as is,telemetryStatusClass as Ql}from"@flopay/shared";import Ca,{useCallback as jn,useEffect as Fn,useMemo as bn,useRef as _t,useState as kt}from"react";import{createContext as hi}from"react";var Pn=hi({flopay:null,paypalFlopay:null,billingApiUrl:""}),kn=hi({session:null,loading:!1,error:null});import{PaymentAPI as oa}from"@flopay/js";import{classifyTelemetryFailure as Gs,FloPayError as bi,generateIdempotencyKey as Ws,normalizeGatewayEnvironment as Js,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as aa,SDK_VERSION as Xs}from"@flopay/shared";import{loadScript as Zs}from"@paypal/paypal-js";import{useCallback as Io,useEffect as ht,useMemo as Jr,useRef as Ye,useState as dr}from"react";function Fs(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 cr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Un(e){if(typeof e!="object"||e===null)return;let t=e;return cr(t.code)??cr(t.type)??cr(t.name)}function vr(e){if(!(typeof e!="object"||e===null))return cr(e.decline_code)}function Wr(e){return typeof e!="object"||e===null?!1:cr(e.type)?.toLowerCase()==="card_error"||vr(e)!==void 0}function Jn(e){let t=Fs(e)?.toLowerCase()??"",r=`${Un(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Ds}from"@flopay/shared";import{useContext as Co}from"react";function Xn(){return Co(Pn).flopay}function na(){return Co(Pn).paypalFlopay??null}function Ls(){return Co(kn)}function Pi(){return Co(Pn).billingApiUrl||Ds()}import{FLO_INSTRUMENT_SCHEMA_VERSION as zs}from"@flopay/shared";import{useCallback as Us,useRef as wo}from"react";import{useEffect as Os,useLayoutEffect as Ns}from"react";var So=typeof window>"u"?Os:Ns;var $s={"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 qs(e){return e==="stripe"||e==="paypal"?e:void 0}function js(e){let t=qs(e.provider),n={schemaVersion:zs,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=$s[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 ra=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Cr(e,t){let n=wo(e);n.current=e;let r=wo(new Set),o=wo(t),a=wo(t);return So(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Us(m=>{if(a.current!==t)return;let d=js(m);if(d){if(ra.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}Qe(()=>n.current?.(d))}},[t])}var Ks=Symbol.for("@flopay/js.telemetry.bridge.v1"),Vs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Hs(){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 Ys(e){let t=Hs(),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 ko(e){let t=globalThis[Vs];return Ys(t?.(e)??{})}function Bt(e){if(e)return e[Ks]}import{jsx as Sr,jsxs as ia}from"react/jsx-runtime";var Eo=45,Qs=1e3,el=11e3,tl=["https://www.paypal.com","https://www.sandbox.paypal.com"],vi="We couldn't open PayPal. Try again or choose another payment method.",nl={width:"100%",minHeight:Eo,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 Ci(e){return e.includes("No ack for postMessage init()")&&tl.some(t=>e.includes(t))&&e.includes("10000ms")}function rl(e){return e?`${vi} Allow pop-ups for this site, then try again.`:vi}function Si({sessionId:e,nonce:t,billingApiUrl:n,email:r,clientId:o,environment:a,currency:m,isSubscription:d,providerObjectType:T,onTokenizedBody:h,onComplete:P,onErrorChange:b,onDecline:x,onTechnicalFailure:U,isProcessing:p=!1,onLoadStateChange:S,onInitializationStateChange:ee,allowAutomaticRetry:W=!0,onButtonClick:v,runBeforeButtonClick:ye,session:j,existingOrderId:J,telemetry:ce,telemetryContext:Se,onInstrument:re,debug:le=!1}){let Ve=Xn(),Ae=Cr(re,e),Ce=Jr(()=>{if(Ve)return null;let I=ko({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Xs,enabled:ce!==!1});return I.setCheckoutContext(Se??{}),I.beginCheckout(Se??{}),I},[n,Ve,ce,Se?.checkoutMode,Se?.layout]),q=Jr(()=>Bt(Ve),[Ve]);ht(()=>()=>{Ce&&Ce.flush().catch(()=>{}).finally(()=>Ce.destroy())},[Ce]);let B=Jr(()=>({error:I=>{q?q.error(I):Ce?.error(I),Ae({class:"technical_error",errorCode:I.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":I.errorCode,requestCategory:I.requestCategory,provider:I.provider})},log:I=>{q?q.log(I):Ce?.log(I),Ae({class:"lifecycle",name:I.name,provider:I.provider})},performance:I=>{q?q.performance(I):Ce?.performance(I)},terminal:I=>{q?q.terminal(I):Ce?.terminal(I)},startTiming:()=>q?.now()??Ce?.now()??0,elapsed:I=>q?.elapsed(I)??Math.max(0,(Ce?.now()??I)-I)}),[Ae,q,Ce]),te=Ye(null),tt=Ye(0),Me=Ye(null),V=Ye(!1),[de,ae]=dr(!1),[ue,ke]=dr(!1),[pe,Re]=dr(0),O=Ye(0),[w,oe]=dr(!1),qe=Ye(!1),De=Ye(!1),[Z,R]=dr(!1),[H,$]=dr(!1),Be=Jr(()=>n.replace(/\/+$/,""),[n]),Ie=T??(d?"subscription":"order"),We=T==="order"||T==="setup_token",Y=Jr(()=>JSON.stringify([Be,o,m,a??"",Ie,We,e,J??""]),[Be,o,m,a,J,Ie,We,e]),mt=Ye(Y),D=mt.current!==Y,[Le,Pt]=dr([]),N=I=>{le&&Pt(Xe=>[...Xe,`${new Date().toISOString().slice(11,23)} ${I}`])},bt=Ye(h),ze=Ye(P),tn=Ye(b),It=Ye(x),k=Ye(U),se=Ye(v),yt=Ye(S),Fe=Ye(ee),Vt=Ye(ye),Xt=Ye(j),Ge=Ye(r),vt=Ye(t),Je=Ye(null),Lt=Ye(0),je=Ye(null),Ht=Ye(null),Et=Ye(new Map),nn=Ye(new Map),Nt=Ye(!1);ht(()=>(Nt.current=!0,()=>{Nt.current=!1}),[]),ht(()=>{bt.current=h},[h]),ht(()=>{ze.current=P},[P]),ht(()=>{tn.current=b},[b]),ht(()=>{It.current=x},[x]),ht(()=>{k.current=U},[U]),ht(()=>{se.current=v},[v]),ht(()=>{yt.current=S},[S]),ht(()=>{Fe.current=ee},[ee]),ht(()=>{Vt.current=ye},[ye]),ht(()=>{Xt.current=j},[j]),ht(()=>{Ge.current=r},[r]),ht(()=>{vt.current=t},[t]),ht(()=>{O.current=pe},[pe]),ht(()=>{w&&Me.current?.focus()},[w,pe]);let En=Io(()=>{window.setTimeout(()=>{Me.current?.focus()},0)},[]),sn=Io(()=>{ae(!1),Re(I=>I+1)},[]),rt=Io(()=>{oe(!1),(te.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??te.current)?.focus?.()},[]);ht(()=>{!de||!V.current||(V.current=!1,rt())},[rt,de,pe]);let zt=Io((I,Xe)=>{let Pe=k.current;if(Pe){Pe("paypal",I,Xe);return}tn.current?.(rl(Xe?.popupBlocked??Jn(I)))},[]),Ke=()=>{je.current?.timer&&(clearTimeout(je.current.timer),je.current.timer=null)},Rn=()=>{Ke();let I=Lt.current+1;return Lt.current=I,Ht.current=null,je.current={generation:I,timer:null,yieldedControl:!1},oe(!1),I},ct=I=>I!==void 0&&je.current?.generation!==I?!1:(Ke(),je.current=null,Ht.current=null,!0),vn=I=>{let Xe=I?.generation??je.current?.generation??Lt.current;(!I?.generation||je.current?.generation===Xe)&&(Ke(),je.current=null),Ht.current=Xe,I?.showRetry&&oe(!0),I?.remount&&sn(),I?.focus!==!1&&En()},Ut=I=>je.current?.generation===I&&Ht.current!==I,ne=I=>{typeof document<"u"&&document.visibilityState!=="visible"||(Ke(),I.timer=setTimeout(()=>{je.current?.generation===I.generation&&(je.current=null,Ht.current=I.generation,zt(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),oe(!0),sn(),En())},600))},Vn=()=>{let I=je.current;I?.yieldedControl&&ne(I)},_n=()=>{let I=je.current;I&&(I.yieldedControl=!0,Ke())},Tn=I=>{let Xe=Je.current;return Xe&&nn.current.set(I,Xe),I};ht(()=>{let I=()=>{document.visibilityState==="visible"?Vn():_n()};return document.addEventListener("visibilitychange",I),window.addEventListener("focus",Vn),window.addEventListener("blur",_n),()=>{document.removeEventListener("visibilitychange",I),window.removeEventListener("focus",Vn),window.removeEventListener("blur",_n),Ke()}},[]),ht(()=>{mt.current!==Y&&(mt.current=Y,qe.current=!1,De.current=!1,ae(!1),ke(!1),R(!1),Fe.current?.("loading"))},[Y]),ht(()=>{Qe(()=>yt.current?.(de&&!Z))},[de,Z]);let xn=Js(a);ht(()=>{let I=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",Xe=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(N(`mount clientId=${I} env=${a??"(unset)"}\u2192${xn??"live"} ccy=${m} sub=${d}`),N(`ua=${Xe.slice(0,80)}${Xe.length>80?"\u2026":""}`),!o){N("FAIL: clientId empty \u2014 gateway misconfigured"),R(!0),B.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!te.current){N("FAIL: containerRef not attached");return}tt.current=B.startTiming(),B.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=!1,Cn=!1,Oe=()=>Pe||Cn,Hn,nr=!1,Yt=()=>{Hn=Ws(),Hn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),nr=!0},dt=null,Zt=!1,Gt=null,ot=!1,ln=()=>{!Gt||ot||(ot=!0,Gt.close().catch(()=>{}))},cn=null,Yn=()=>{cn!==null&&(B.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"overlay_return",durationMs:B.elapsed(cn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),cn=null)},Sn=!1,rn=te.current,dn=null,me=null,Ct=[],at=l=>{if(!l||typeof l.getBoundingClientRect!="function")return"(no rect)";let s=l.getBoundingClientRect();return`${Math.round(s.width)}\xD7${Math.round(s.height)}`},on=l=>{if(!l)return"(empty)";try{let s=new URL(l,typeof window<"u"?window.location.href:"https://localhost"),c=s.pathname.toLowerCase();return c.includes("checkcaptcha")||c.includes("captcha")?`CAPTCHA(${s.host}${c})`:c.includes("risk")||c.includes("challenge")?`RISK(${s.host}${c})`:c.includes("smart/buttons")?`smart-buttons(${s.host})`:`${s.host}${c}`.slice(0,100)}catch{return l.slice(0,80)}},un=l=>{let s=l.getAttribute("src"),c=l.getAttribute("srcdoc"),A=l.getAttribute("name"),K=l.getAttribute("sandbox"),F=[];return s&&F.push(`src=${on(s)}`),c&&F.push(`srcdoc[${c.length}ch]`),!s&&!c&&F.push("src=(empty) srcdoc=(empty)"),A&&F.push(`name=${A.slice(0,40)}`),K!==null&&F.push(`sandbox="${K.slice(0,40)}"`),F.join(" ")},Ln=l=>{if(!(l instanceof HTMLIFrameElement))return"";try{let s=l.contentDocument;if(!s)return"cd=null";let c=s.body?.children.length??0,A=s.body?.innerHTML.length??0,K=s.head?.innerHTML.length??0;return`cd=same-origin readyState=${s.readyState} body[${c}children,${A}ch] head[${K}ch]`}catch(s){return`cd=cross-origin(${s.message.slice(0,30)})`}},pn=[],$t=l=>{if(Oe())return;let s=l.message??String(l.error??"(no message)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(N(`window:error ${s.slice(0,140)}`),pn.push(s))},Wt=l=>{if(Oe())return;let s=l.reason instanceof Error?l.reason.message:String(l.reason??"(no reason)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(N(`window:rejection ${s.slice(0,140)}`),pn.push(s))};le&&typeof window<"u"&&(window.addEventListener("error",$t),window.addEventListener("unhandledrejection",Wt));let Jt={value:0};if(le&&typeof PerformanceObserver<"u")try{me=new PerformanceObserver(l=>{if(!Oe())for(let s of l.getEntries()){if(!s.name.toLowerCase().includes("paypal"))continue;Jt.value+=1;let c=Math.round(s.duration);N(`net ${c}ms ${s.name.slice(0,90)}`)}}),me.observe({type:"resource",buffered:!0})}catch{}let Gn=()=>{for(dn?.disconnect(),dn=null,me?.disconnect(),me=null;Ct.length;)clearTimeout(Ct.pop());le&&typeof window<"u"&&(window.removeEventListener("error",$t),window.removeEventListener("unhandledrejection",Wt))},On=l=>{if(!l)return!1;let s=l.toLowerCase();return s.includes("zoid destroyed")||s.includes("destroyed all components")||s.includes("window closed")||s.includes("detected container element removed")},An=l=>{if(Oe()||On(l))return;let s=Wn(l)??l;Qe(()=>tn.current?.(s))},Nn=l=>{Pe||(R(!0),l.includes("paypal_ineligible")||B.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",l))},qt=(l,s=!1)=>{if(Pe)return;let c=qe.current||!W;if(Zt)return;Zt=!0,Cn=!0,Gn(),ln();let A=s||Ci(l);if(A&&W&&!qe.current){qe.current=!0,ae(!1),$(!1),ke(!0),Fe.current?.("retrying"),dt=setTimeout(()=>{Pe||Re(K=>K+1)},Qs);return}if(A||c){if(ae(!1),$(!1),ke(!1),R(!0),Fe.current?.("exhausted"),!De.current){De.current=!0;let K=Ci(l)?"paypal_init_timeout":s?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",K)}return}Nn(l)};R(!1);let Ze=async(l,s=Je.current)=>{if(Oe())return;let c=s?.sessionId??e;if(bt.current){await bt.current(l,{sessionId:c,accountPatch:s?.accountPatch,nonce:s?.nonce});return}let A=B.startTiming();B.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let K=()=>{B.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"processing",durationMs:B.elapsed(A),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let F=Xt.current,C=s?.accountPatch?.email??Ge.current,f=s?.accountPatch?.userId??F?.customer?.id??F?.accountData?.userId??"",g=await new oa(Be,{telemetry:!1}).processPayment(f,{sessionId:c,nonce:s?.nonce??vt.current,tokenizedData:l,accountData:{userId:f,email:C??F?.customer?.email??"",firstName:s?.accountPatch?.firstName??F?.customer?.firstName??F?.accountData?.firstName??"",lastName:s?.accountPatch?.lastName??F?.customer?.lastName??F?.accountData?.lastName??"",country:s?.accountPatch?.country??F?.customer?.country??F?.accountData?.country??void 0,zip:s?.accountPatch?.zip??F?.customer?.zip??F?.accountData?.zip??void 0}});if(g.ok){if(Cn||Pe&&Nt.current)return;K(),B.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Qe(()=>ze.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Oe())return;let E=await g.json().catch(()=>null),G=E?.message??"PayPal payment failed.",ie=Wn(G)??G;K(),g.status===400&&(typeof E?.declineCode=="string"||!Array.isArray(E?.fields))?B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):g.status===400||g.status===422?B.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):B.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:g.status>=500?"5xx":g.status>=400?"4xx":g.status>=300?"3xx":"unknown",failureCategory:g.status>=500?"server_error":void 0}),An(ie),Qe(()=>It.current?.(Mt("paypal",ie,{code:E?.code,declineCode:E?.declineCode})));return}catch(F){if(Oe())return;K(),B.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let C=F instanceof Error?F.message:"PayPal payment failed.",f=Wn(C)??C;An(f),Qe(()=>It.current?.(Mt("paypal",f)));return}},mn=()=>new bi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),jt=l=>Oe()?Promise.reject(mn()):Promise.resolve(l),ut=async l=>{if(Oe())throw mn();nr||Yt();let s=Je.current,c=s?.sessionId??e,A=s?.nonce??vt.current;B.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let K;try{K=await new oa(Be,{telemetry:!1}).createSessionIntent(c,A??"",We?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:aa,paymentMethodId:null,intentKind:Ie==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Hn})}catch(F){throw B.error({...Gs(F,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),F}if(Oe())throw mn();if(K.provider!=="paypal"||K.providerObjectType!==Ie)throw new Error(l);return B.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),K.providerObjectId},Qt=(l,s)=>{let c=s?.nonce??vt.current;if(!c)return;let A=s?.sessionId??e,K=vr(l)??Un(l)??"provider_declined";new oa(Be,{telemetry:!1}).reportSessionIntentDecline(A,c,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:K}).catch(()=>{})},Rt=pe;N("loadScript:scheduled (deferred 1 tick)");let rr=null,pt=setTimeout(()=>{if(Pe){N("loadScript:skipped (cancelled before defer ran)");return}N("loadScript:start");let l=xn==="live"?"production":xn;rr=Zs({clientId:o,currency:m,...Ie==="subscription"?{intent:"subscription",vault:!0}:Ie==="order"?{intent:"capture"}:{},...l?{environment:l}:{},...l==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),rr.then(s=>{if(N(`loadScript:resolved inactive=${Oe()} ns=${!!s} buttons=${!!s?.Buttons}`),Oe())return;if(!s?.Buttons){N("FAIL: namespace missing Buttons factory"),qt("PayPal SDK did not expose the Buttons factory.");return}B.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"provider_ready",durationMs:B.elapsed(tt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let c=async y=>{if(Oe()||O.current!==Rt)return;let g=y.vaultSetupToken??y.subscriptionID??y.orderID??"",E=g?nn.current.get(g):Et.current.get(Rt);if(!(!E||!Ut(E.generation))&&ct(E.generation)){nn.current.delete(g),Et.current.delete(E.surfaceKey),Yn();try{if($(!0),Qe(()=>tn.current?.(null)),!g)throw new bi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Ze(Ie==="setup_token"?{id:g,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:aa}:We?{id:g,isPaypal:!0,gateway:"paypal",paymentMethodType:aa}:{id:g,isPaypal:!0},E)}catch(G){An(G instanceof Error?G.message:"PayPal capture failed.")}finally{Oe()||$(!1)}}},A=s.Buttons({style:{layout:"horizontal",height:Eo,tagline:!1},onClick:async(y,g)=>{if(Oe()){await g.reject();return}Yt();let E=Vt.current,G={};if(E)try{let Ue=await E("paypal");if(Oe()){await g.reject();return}if(!Ue.proceed){Je.current=null,Et.current.delete(Rt),await g.reject();return}G={sessionId:Ue.sessionId,accountPatch:Ue.accountPatch,nonce:Ue.nonce}}catch(Ue){N(`onClick:runBeforeButtonClick rejected msg=${(Ue instanceof Error?Ue.message:String(Ue)).slice(0,120)}`),Je.current=null,Et.current.delete(Rt),await g.reject();return}Qe(()=>se.current?.("paypal"));let _e={generation:Rn(),surfaceKey:Rt,...G};Je.current=_e,Et.current.set(Rt,_e),await g.resolve(),B.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),B.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),cn=B.startTiming()},createOrder:Ie==="order"?J?()=>jt(J).then(Tn):()=>ut("Failed to create PayPal order.").then(Tn):void 0,createSubscription:Ie==="subscription"?J?()=>jt(J).then(Tn):()=>ut("Failed to create PayPal subscription.").then(Tn):void 0,createVaultSetupToken:Ie==="setup_token"?()=>ut("Failed to create PayPal setup token.").then(Tn):void 0,onApprove:c,onCancel:()=>{if(Oe())return;let y=Et.current.get(Rt)??Je.current;y&&Et.current.delete(y.surfaceKey),Je.current=null,Yn(),B.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),V.current=!0,vn({generation:y?.generation,remount:!0,focus:!1})},onError:y=>{if(Oe()||O.current!==Rt)return;let g=y instanceof Error?y.message:"PayPal failed to render.";if(N(`onError rendered=${Sn} msg=${g.slice(0,120)}`),Sn){let E=Et.current.get(Rt)??Je.current;if(E&&!Ut(E.generation)||!E&&Ht.current===Lt.current)return;if(On(g)){ct(E?.generation);return}if(Yn(),Wr(y)){B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Qt(y,E),Qe(()=>It.current?.(Mt("paypal",g))),E&&Et.current.delete(E.surfaceKey),Je.current=null,ct(E?.generation);return}let G=g.toLowerCase();B.error({errorCode:G.includes("popup")&&G.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),E&&Et.current.delete(E.surfaceKey),Je.current=null,vn({generation:E?.generation,remount:!0,showRetry:!0,focus:!0}),zt(y,{code:"paypal_runtime_failed"});return}qt(g)}}),K=A.isEligible();if(N(`isEligible=${K}`),B.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!K){ae(!1),qt("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Gt=A,le&&N(`container:dims ${at(rn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),le&&typeof MutationObserver<"u"&&(dn=new MutationObserver(y=>{if(!Oe()){for(let g of y)if(g.type==="childList")g.addedNodes.forEach(E=>{if(!(E instanceof Element))return;let G=E.tagName.toLowerCase(),ie=(E.getAttribute("title")??"").slice(0,40),_e=G==="iframe"?` ${un(E)}`:"";N(`child+ ${G}${ie?` title="${ie}"`:""}${_e} dims=${at(E)}`)});else if(g.type==="attributes"&&g.target instanceof Element){let E=g.target;if(E.tagName.toLowerCase()!=="iframe")continue;let G=g.attributeName;(G==="src"||G==="srcdoc")&&N(`attr~ iframe ${G}=${G==="srcdoc"?`[${(E.getAttribute("srcdoc")??"").length}ch]`:on(E.getAttribute("src"))} dims=${at(E)}`)}}}),dn.observe(rn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let C=y=>{if(Oe()||Sn)return;let g=rn.querySelectorAll("iframe"),E=typeof document<"u"&&"hasStorageAccess"in document;N(`watchdog:${y} container=${at(rn)} children=${rn.childElementCount} iframes=${g.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${E} paypalNetRequests=${Jt.value}`),g.forEach((G,ie)=>{let _e=(G.getAttribute("title")??"").slice(0,40);N(` iframe[${ie}] ${at(G)}${_e?` title="${_e}"`:""} ${un(G)}`);let Ue=Ln(G);Ue&&N(` ${Ue}`)}),pn.length===0&&N(" (no PayPal/zoid window errors captured)")};le&&(Ct.push(setTimeout(()=>C("3s"),3e3)),Ct.push(setTimeout(()=>C("8s"),8e3)),Ct.push(setTimeout(()=>C("15s"),15e3))),N("render:start");let f=B.startTiming();Ct.push(setTimeout(()=>{Oe()||Sn||(N("watchdog:11s retryable render timeout"),qt("PayPal Buttons render did not settle within 11000ms.",!0))},el)),A.render(rn).then(()=>{if(N(`render:resolved inactive=${Oe()}`),Gn(),Oe()){ln();return}Sn=!0,ae(!0),ke(!1),Fe.current?.("ready"),B.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"checkout_render",durationMs:B.elapsed(f),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(y=>{let g=y instanceof Error?y.message:"PayPal failed to render.";N(`render:rejected msg=${g.slice(0,120)}`),Gn(),qt(g)})}).catch(s=>{let c=s instanceof Error?s.message:"PayPal SDK failed to load.";N(`loadScript:rejected msg=${c.slice(0,120)}`),qt(c)})},0);return()=>{Pe=!0,clearTimeout(pt),dt&&clearTimeout(dt),Gn(),ln()}},[W,Be,o,m,a,Ie,We,e,J,pe,B]);let mr=le?ia("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Z?"#fef2f2":"#f3f4f6",border:`1px solid ${Z?"#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=${de} failed=${Z})`,Le.length===0?`
1
+ import{a as tt,b as Yn,c as wa,d as po,e as Oi,f as zi,g as sl,h as ll}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as ap}from"@flopay/shared";import{PaymentAPI as si}from"@flopay/js";import{FloPayError as Zr,resolveBillingApiUrl as Gc,resolveButtonsLayoutTheme as Wc,resolveTheme as Jc}from"@flopay/shared";import{useCallback as hr,useEffect as Wr,useMemo as Eo,useRef as Jr,useState as Ro}from"react";import{Fragment as Or,jsx as wn,jsxs as Ui}from"react/jsx-runtime";function cl(){return Ui(Or,{children:[Ui("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:[wn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),wn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",wn("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:wn("path",{d:"M9 18l6-6-6-6"})})]})}function dl(){return wn(Or,{children:"Go back"})}function ul(){return wn(Or,{children:"Secure card checkout"})}function Nr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Dr({content:e}){return wn(Or,{children:e===void 0?wn(cl,{}):e})}function Lr({content:e}){return wn(Or,{children:e===void 0?wn(dl,{}):e})}function mo({content:e}){return wn(Or,{children:e===void 0?wn(ul,{}):e})}import{FloPayError as qi,isMoneySettledOutcome as pl,isSetupIntentClientSecret as ld}from"@flopay/shared";function $i(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function ka(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ji(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,c)=>a+(c.overrideAmount??c.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,c)=>({uuid:`synthetic-${a.type??"item"}-${c}`,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 kn(e){let t=e?.trim().split(/\s+/).filter(Boolean)??[];return t.length===0?{}:{firstName:t[0],lastName:t.length>1?t.slice(1).join(" "):void 0}}function Ia(e,t){return t?{...e,...t}:e}function $t(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var ml=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function cr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of ml)if(n.test(t))return r;return e}function kr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function zr(e){return e?.status==="authorized"||e?.status==="complete"}function Ki(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function qo(e){let t=Ki(e);return new qi(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $o(e){let t=Ki(e);return new qi(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function jo(e,t){return e==="processing"||pl(e,t)}function Vi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Hi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function yo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as ia,SESSION_CREATE_TELEMETRY as Ac}from"@flopay/js";import{buildCheckoutDisplayData as Mc,classifyTelemetryFailure as Ms,FloPayError as Kt,foldIntoProducts as Bc,isDetachedSessionEligible as Fc,resolveBillingApiUrl as Nc,resolveButtonsLayoutTheme as Dc,resolveIdempotencyKey as Bs,resolveSessionCurrency as Lc,resolveTheme as Ls,SDK_VERSION as Os,telemetryStatusClass as Oc}from"@flopay/shared";import Ga,{useCallback as Wn,useEffect as Jn,useMemo as En,useRef as At,useState as Et}from"react";import{createContext as Yi}from"react";var In=Yi({flopay:null,paypalFlopay:null,billingApiUrl:""}),Ln=Yi({session:null,loading:!1,error:null});import{PaymentAPI as Ta}from"@flopay/js";import{classifyTelemetryFailure as Tl,FloPayError as Xi,generateIdempotencyKey as Al,isValidEmail as Go,normalizeGatewayEnvironment as Ml,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Aa,SDK_VERSION as Bl}from"@flopay/shared";import{loadScript as Fl}from"@paypal/paypal-js";import{useCallback as ho,useEffect as ft,useMemo as bo,useRef as Ve,useState as nr}from"react";import{isValidEmail as yl}from"@flopay/shared";import{useCallback as Gi,useEffect as fl,useRef as Wi,useState as Ra}from"react";import{jsx as Ea,jsxs as Ur}from"react/jsx-runtime";function fo(e){return!!(e.firstName?.trim()||e.lastName?.trim())}function qr(){let[e,t]=Ra(null),n=Wi(null),r=Wi(0),o=Gi((c,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:c,identity:s}),new Promise(S=>{n.current=S})),[]),a=Gi(c=>{let s=n.current;n.current=null,t(null),s?.(c)},[]);return fl(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Ir({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[c,s]=Ra(e.email?.trim()??""),[S,b]=Ra([e.firstName,e.lastName].filter(Boolean).join(" ")),g=yl(c.trim())&&!!S.trim();return Ur("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:[Ur("div",{style:{fontWeight:700},children:["Continue with ",t]}),Ur("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Ea("input",{type:"email",autoComplete:"email",required:!0,value:c,onChange:m=>s(m.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ur("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",Ea("input",{type:"text",autoComplete:"name",required:!0,value:S,onChange:m=>b(m.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ur("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Ea("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Ur("button",{type:"button",disabled:!g||o,onClick:()=>{let m=kn(S);n({email:c.trim(),firstName:m.firstName,lastName:m.lastName})},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function gl(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 Er(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function tr(e){if(typeof e!="object"||e===null)return;let t=e;return Er(t.code)??Er(t.type)??Er(t.name)}function $r(e){if(!(typeof e!="object"||e===null))return Er(e.decline_code)}function go(e){return typeof e!="object"||e===null?!1:Er(e.type)?.toLowerCase()==="card_error"||$r(e)!==void 0}function dr(e){let t=gl(e)?.toLowerCase()??"",r=`${tr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as hl}from"@flopay/shared";import{useContext as Ko}from"react";function ur(){return Ko(In).flopay}function _a(){return Ko(In).paypalFlopay??null}function bl(){return Ko(Ln)}function Ji(){return Ko(In).billingApiUrl||hl()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Cl}from"@flopay/shared";import{useCallback as Sl,useRef as Ho}from"react";import{useEffect as vl,useLayoutEffect as Pl}from"react";var Vo=typeof window>"u"?vl:Pl;var wl={"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 kl(e){return e==="stripe"||e==="paypal"?e:void 0}function Il(e){let t=kl(e.provider),n={schemaVersion:Cl,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=wl[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 xa=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function jr(e,t){let n=Ho(e);n.current=e;let r=Ho(new Set),o=Ho(t),a=Ho(t);return Vo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Sl(c=>{if(a.current!==t)return;let s=Il(c);if(s){if(xa.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}tt(()=>n.current?.(s))}},[t])}var El=Symbol.for("@flopay/js.telemetry.bridge.v1"),Rl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function _l(){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 xl(e){let t=_l(),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 Yo(e){let t=globalThis[Rl];return xl(t?.(e)??{})}function jt(e){if(e)return e[El]}import{jsx as pr,jsxs as Ma}from"react/jsx-runtime";var Wo=45,Nl=1e3,Dl=11e3,Ll=["https://www.paypal.com","https://www.sandbox.paypal.com"],Zi="We couldn't open PayPal. Try again or choose another payment method.",Ol={width:"100%",minHeight:Wo,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 Qi(e){return e.includes("No ack for postMessage init()")&&Ll.some(t=>e.includes(t))&&e.includes("10000ms")}function zl(e){return e?`${Zi} Allow pop-ups for this site, then try again.`:Zi}function Ul(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 es({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:c,environment:s,currency:S,isSubscription:b,providerObjectType:g,onTokenizedBody:m,onComplete:M,onErrorChange:D,onDecline:u,onTechnicalFailure:w,isProcessing:ve=!1,onLoadStateChange:H,onInitializationStateChange:P,allowAutomaticRetry:fe=!0,onButtonClick:Q,runBeforeButtonClick:ce,session:oe,existingOrderId:Ce,telemetry:He,telemetryContext:be,onInstrument:Rt,debug:De=!1}){let Te=ur(),Ae=jr(Rt,e),ee=bo(()=>{if(Te)return null;let v=Yo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Bl,enabled:He!==!1});return v.setCheckoutContext(be??{}),v.beginCheckout(be??{}),v},[n,Te,He,be?.checkoutMode,be?.layout]),J=bo(()=>jt(Te),[Te]);ft(()=>()=>{ee&&ee.flush().catch(()=>{}).finally(()=>ee.destroy())},[ee]);let L=bo(()=>({error:v=>{J?J.error(v):ee?.error(v),Ae({class:"technical_error",errorCode:v.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":v.errorCode,requestCategory:v.requestCategory,provider:v.provider})},log:v=>{J?J.log(v):ee?.log(v),Ae({class:"lifecycle",name:v.name,provider:v.provider})},performance:v=>{J?J.performance(v):ee?.performance(v)},terminal:v=>{J?J.terminal(v):ee?.terminal(v)},startTiming:()=>J?.now()??ee?.now()??0,elapsed:v=>J?.elapsed(v)??Math.max(0,(ee?.now()??v)-v)}),[Ae,J,ee]),me=Ve(null),et=Ve(0),Ue=Ve(null),Ye=Ve(!1),[te,T]=nr(!1),[ae,Fe]=nr(!1),[ie,j]=nr(0),_e=Ve(0),[Je,We]=nr(!1),Se=Ve(!1),G=Ve(!1),[Y,$]=nr(!1),[we,Me]=nr(!1),[x,K]=nr(!1),[I,C]=nr(!1),nt=kn(o??[oe?.customer?.firstName,oe?.customer?.lastName].filter(Boolean).join(" ")),St=!x&&a&&!Go(r?.trim()||oe?.customer?.email?.trim())?{email:r?.trim()||oe?.customer?.email?.trim(),firstName:nt.firstName,lastName:nt.lastName}:null,{request:de,collect:ct,finish:it}=qr(),rt=bo(()=>n.replace(/\/+$/,""),[n]),je=g??(b?"subscription":"order"),y=g==="order"||g==="setup_token",U=bo(()=>JSON.stringify([rt,c,S,s??"",je,y,e,Ce??""]),[rt,c,S,s,Ce,je,y,e]),Xe=Ve(U),dt=Xe.current!==U,[Mt,Bt]=nr([]),W=v=>{De&&Bt(ut=>[...ut,`${new Date().toISOString().slice(11,23)} ${v}`])},Le=Ve(m),Wt=Ve(M),wt=Ve(D),Ot=Ve(u),Rn=Ve(w),_n=Ve(Q),Zn=Ve(H),Jt=Ve(P),cn=Ve(a),dn=Ve(ce),Ft=Ve(oe),vn=Ve(r),bt=Ve(o),ir=Ve(null),Ht=Ve(e),sr=Ve(t),Nt=Ve(null),zn=Ve(0),ot=Ve(null),_t=Ve(null),xt=Ve(new Map),tn=Ve(new Map),un=Ve(!1);ft(()=>(un.current=!0,()=>{un.current=!1}),[]),ft(()=>{Le.current=m},[m]),ft(()=>{cn.current=a},[a]),ft(()=>{Wt.current=M},[M]),ft(()=>{wt.current=D},[D]),ft(()=>{Ot.current=u},[u]),ft(()=>{Rn.current=w},[w]),ft(()=>{_n.current=Q},[Q]),ft(()=>{Zn.current=H},[H]),ft(()=>{Jt.current=P},[P]),ft(()=>{dn.current=ce},[ce]),ft(()=>{Ft.current=oe},[oe]),ft(()=>{vn.current=r},[r]),ft(()=>{bt.current=o},[o]),ft(()=>{sr.current=t},[t]),ft(()=>{Ht.current!==e&&(Ht.current=e,ir.current=null,K(!1),C(!1))},[e]),ft(()=>{_e.current=ie},[ie]),ft(()=>{Je&&Ue.current?.focus()},[Je,ie]);let pn=ho(()=>{window.setTimeout(()=>{Ue.current?.focus()},0)},[]),Un=ho(async v=>{C(!0);try{await cn.current?.(v),ir.current=v,vn.current=v.email,bt.current=[v.firstName,v.lastName].filter(Boolean).join(" "),K(!0),tt(()=>wt.current?.(null))}catch(ut){let qe=ut instanceof Error?ut.message:"Buyer details could not be attached to checkout.";tt(()=>wt.current?.(qe))}finally{C(!1)}},[]),qn=ho(()=>{T(!1),j(v=>v+1)},[]),zt=ho(()=>{We(!1),(me.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??me.current)?.focus?.()},[]);ft(()=>{!te||!Ye.current||(Ye.current=!1,zt())},[zt,te,ie]);let X=ho((v,ut)=>{let qe=Rn.current;if(qe){qe("paypal",v,ut);return}wt.current?.(zl(ut?.popupBlocked??dr(v)))},[]),Pn=()=>{ot.current?.timer&&(clearTimeout(ot.current.timer),ot.current.timer=null)},xn=()=>{Pn();let v=zn.current+1;return zn.current=v,_t.current=null,ot.current={generation:v,timer:null,yieldedControl:!1},We(!1),v},Qn=v=>v!==void 0&&ot.current?.generation!==v?!1:(Pn(),ot.current=null,_t.current=null,!0),br=v=>{let ut=v?.generation??ot.current?.generation??zn.current;(!v?.generation||ot.current?.generation===ut)&&(Pn(),ot.current=null),_t.current=ut,v?.showRetry&&We(!0),v?.remount&&qn(),v?.focus!==!1&&pn()},Tr=v=>ot.current?.generation===v&&_t.current!==v,Tn=v=>{typeof document<"u"&&document.visibilityState!=="visible"||(Pn(),v.timer=setTimeout(()=>{ot.current?.generation===v.generation&&(ot.current=null,_t.current=v.generation,X(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),We(!0),qn(),pn())},600))},mn=()=>{let v=ot.current;v?.yieldedControl&&Tn(v)},Be=()=>{let v=ot.current;v&&(v.yieldedControl=!0,Pn())},Xt=v=>{let ut=Nt.current;return ut&&tn.current.set(v,ut),v};ft(()=>{let v=()=>{document.visibilityState==="visible"?mn():Be()};return document.addEventListener("visibilitychange",v),window.addEventListener("focus",mn),window.addEventListener("blur",Be),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("focus",mn),window.removeEventListener("blur",Be),Pn()}},[]),ft(()=>{Xe.current!==U&&(Xe.current=U,Se.current=!1,G.current=!1,T(!1),Fe(!1),$(!1),Jt.current?.("loading"))},[U]),ft(()=>{tt(()=>Zn.current?.(te&&!Y))},[te,Y]);let Dt=Ml(s);ft(()=>{let v=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",ut=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(W(`mount clientId=${v} env=${s??"(unset)"}\u2192${Dt??"live"} ccy=${S} sub=${b}`),W(`ua=${ut.slice(0,80)}${ut.length>80?"\u2026":""}`),!c){W("FAIL: clientId empty \u2014 gateway misconfigured"),$(!0),L.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(!me.current){W("FAIL: containerRef not attached");return}et.current=L.startTiming(),L.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let qe=!1,yn=!1,Ze=()=>qe||yn,Ut,lr=!1,jn=()=>{Ut=Al(),Ut||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),lr=!0},Cn=null,Zt=!1,fn=null,gn=!1,xe=()=>{!fn||gn||(gn=!0,fn.close().catch(()=>{}))},kt=null,Tt=()=>{kt!==null&&(L.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"overlay_return",durationMs:L.elapsed(kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),kt=null)},An=!1,hn=me.current,Mn=null,Bn=null,qt=[],on=d=>{if(!d||typeof d.getBoundingClientRect!="function")return"(no rect)";let p=d.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},an=d=>{if(!d)return"(empty)";try{let p=new URL(d,typeof window<"u"?window.location.href:"https://localhost"),k=p.pathname.toLowerCase();return k.includes("checkcaptcha")||k.includes("captcha")?`CAPTCHA(${p.host}${k})`:k.includes("risk")||k.includes("challenge")?`RISK(${p.host}${k})`:k.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${k}`.slice(0,100)}catch{return d.slice(0,80)}},er=d=>{let p=d.getAttribute("src"),k=d.getAttribute("srcdoc"),Ee=d.getAttribute("name"),q=d.getAttribute("sandbox"),F=[];return p&&F.push(`src=${an(p)}`),k&&F.push(`srcdoc[${k.length}ch]`),!p&&!k&&F.push("src=(empty) srcdoc=(empty)"),Ee&&F.push(`name=${Ee.slice(0,40)}`),q!==null&&F.push(`sandbox="${q.slice(0,40)}"`),F.join(" ")},Ar=d=>{if(!(d instanceof HTMLIFrameElement))return"";try{let p=d.contentDocument;if(!p)return"cd=null";let k=p.body?.children.length??0,Ee=p.body?.innerHTML.length??0,q=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${k}children,${Ee}ch] head[${q}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},Fn=[],Kn=d=>{if(Ze())return;let p=d.message??String(d.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(W(`window:error ${p.slice(0,140)}`),Fn.push(p))},Qt=d=>{if(Ze())return;let p=d.reason instanceof Error?d.reason.message:String(d.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(W(`window:rejection ${p.slice(0,140)}`),Fn.push(p))};De&&typeof window<"u"&&(window.addEventListener("error",Kn),window.addEventListener("unhandledrejection",Qt));let at={value:0};if(De&&typeof PerformanceObserver<"u")try{Bn=new PerformanceObserver(d=>{if(!Ze())for(let p of d.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;at.value+=1;let k=Math.round(p.duration);W(`net ${k}ms ${p.name.slice(0,90)}`)}}),Bn.observe({type:"resource",buffered:!0})}catch{}let Yt=()=>{for(Mn?.disconnect(),Mn=null,Bn?.disconnect(),Bn=null;qt.length;)clearTimeout(qt.pop());De&&typeof window<"u"&&(window.removeEventListener("error",Kn),window.removeEventListener("unhandledrejection",Qt))},_=d=>{if(!d)return!1;let p=d.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},E=d=>{if(Ze()||_(d))return;let p=cr(d)??d;tt(()=>wt.current?.(p))},V=d=>{qe||($(!0),d.includes("paypal_ineligible")||L.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",d))},Z=(d,p=!1)=>{if(qe)return;let k=Se.current||!fe;if(Zt)return;Zt=!0,yn=!0,Yt(),xe();let Ee=p||Qi(d);if(Ee&&fe&&!Se.current){Se.current=!0,T(!1),Me(!1),Fe(!0),Jt.current?.("retrying"),Cn=setTimeout(()=>{qe||j(q=>q+1)},Nl);return}if(Ee||k){if(T(!1),Me(!1),Fe(!1),$(!0),Jt.current?.("exhausted"),!G.current){G.current=!0;let q=Qi(d)?"paypal_init_timeout":p?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",q)}return}V(d)};$(!1);let $e=async(d,p=Nt.current)=>{if(Ze())return;let k=p?.sessionId??e;if(Le.current){await Le.current(d,{sessionId:k,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let Ee=L.startTiming();L.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let q=()=>{L.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"processing",durationMs:L.elapsed(Ee),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let F=Ft.current,Ge=p?.accountPatch?.email??vn.current,Qe=p?.accountPatch?.userId??F?.customer?.id??F?.accountData?.userId??"",ue=await new Ta(rt,{telemetry:!1}).processPayment(Qe,{sessionId:k,nonce:p?.nonce??sr.current,tokenizedData:d,accountData:{userId:Qe,email:Ge??F?.customer?.email??"",firstName:p?.accountPatch?.firstName??F?.customer?.firstName??F?.accountData?.firstName??"",lastName:p?.accountPatch?.lastName??F?.customer?.lastName??F?.accountData?.lastName??"",country:p?.accountPatch?.country??F?.customer?.country??F?.accountData?.country??void 0,zip:p?.accountPatch?.zip??F?.customer?.zip??F?.accountData?.zip??void 0}});if(ue.ok){if(yn||qe&&un.current)return;q(),L.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),tt(()=>Wt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ze())return;let A=await ue.json().catch(()=>null),le=A?.message??"PayPal payment failed.",st=cr(le)??le;q(),ue.status===400&&(typeof A?.declineCode=="string"||!Array.isArray(A?.fields))?L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ue.status===400||ue.status===422?L.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):L.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ue.status>=500?"5xx":ue.status>=400?"4xx":ue.status>=300?"3xx":"unknown",failureCategory:ue.status>=500?"server_error":void 0}),E(st),tt(()=>Ot.current?.($t("paypal",st,{code:A?.code,declineCode:A?.declineCode})));return}catch(F){if(Ze())return;q(),L.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ge=F instanceof Error?F.message:"PayPal payment failed.",Qe=cr(Ge)??Ge;E(Qe),tt(()=>Ot.current?.($t("paypal",Qe)));return}},ne=()=>new Xi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),B=d=>Ze()?Promise.reject(ne()):Promise.resolve(d),h=async d=>{if(Ze())throw ne();lr||jn();let p=Nt.current,k=p?.sessionId??e,Ee=p?.nonce??sr.current;L.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let q;try{q=await new Ta(rt,{telemetry:!1}).createSessionIntent(k,Ee??"",y?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Aa,paymentMethodId:null,intentKind:je==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Ut})}catch(F){throw L.error({...Tl(F,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),F}if(Ze())throw ne();if(q.provider!=="paypal"||q.providerObjectType!==je)throw new Error(d);return L.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),q.providerObjectId},f=(d,p)=>{let k=p?.nonce??sr.current;if(!k)return;let Ee=p?.sessionId??e,q=$r(d)??tr(d)??"provider_declined";new Ta(rt,{telemetry:!1}).reportSessionIntentDecline(Ee,k,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:q}).catch(()=>{})},O=ie;W("loadScript:scheduled (deferred 1 tick)");let pt=null,vt=setTimeout(()=>{if(qe){W("loadScript:skipped (cancelled before defer ran)");return}W("loadScript:start");let d=Dt==="live"?"production":Dt;pt=Fl({clientId:c,currency:S,...je==="subscription"?{intent:"subscription",vault:!0}:je==="order"?{intent:"capture"}:{},...d?{environment:d}:{},...d==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),pt.then(p=>{if(W(`loadScript:resolved inactive=${Ze()} ns=${!!p} buttons=${!!p?.Buttons}`),Ze())return;if(!p?.Buttons){W("FAIL: namespace missing Buttons factory"),Z("PayPal SDK did not expose the Buttons factory.");return}L.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"provider_ready",durationMs:L.elapsed(et.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let k=async(se,ue)=>{if(Ze()||_e.current!==O)return;let A=se.vaultSetupToken??se.subscriptionID??se.orderID??"",le=A?tn.current.get(A):xt.current.get(O);if(!(!le||!Tr(le.generation))&&Qn(le.generation)){tn.current.delete(A),xt.current.delete(le.surfaceKey),Tt();try{if(Me(!0),tt(()=>wt.current?.(null)),!A)throw new Xi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let st=Ft.current,Lt=kn(bt.current??[st?.customer?.firstName,st?.customer?.lastName].filter(Boolean).join(" ")),ge={email:le.accountPatch?.email?.trim()||vn.current?.trim()||st?.customer?.email?.trim(),firstName:le.accountPatch?.firstName?.trim()||Lt.firstName,lastName:le.accountPatch?.lastName?.trim()||Lt.lastName};if(!Go(ge.email)||!(ge.firstName||ge.lastName))try{let bn=Ul(await ue?.order?.get?.());ge={email:bn.email||ge.email,firstName:bn.firstName||ge.firstName,lastName:bn.lastName||ge.lastName}}catch{}if(cn.current&&(!Go(ge.email)||!(ge.firstName||ge.lastName))){let bn=await ct("PayPal",ge);if(!bn)return;ge=bn}Go(ge.email)&&(ge.firstName||ge.lastName)&&(le.accountPatch={...le.accountPatch,...ge},await cn.current?.(ge)),await $e(je==="setup_token"?{id:A,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Aa}:y?{id:A,isPaypal:!0,gateway:"paypal",paymentMethodType:Aa}:{id:A,isPaypal:!0},le)}catch(st){E(st instanceof Error?st.message:"PayPal capture failed.")}finally{Ze()||Me(!1)}}},Ee=p.Buttons({style:{layout:"horizontal",height:Wo,tagline:!1},onClick:async(se,ue)=>{if(Ze()){await ue.reject();return}jn();let A=dn.current,le={accountPatch:ir.current??void 0};if(A)try{let ge=await A("paypal");if(Ze()){await ue.reject();return}if(!ge.proceed){Nt.current=null,xt.current.delete(O),await ue.reject();return}le={sessionId:ge.sessionId,accountPatch:{...ir.current,...ge.accountPatch},nonce:ge.nonce}}catch(ge){W(`onClick:runBeforeButtonClick rejected msg=${(ge instanceof Error?ge.message:String(ge)).slice(0,120)}`),Nt.current=null,xt.current.delete(O),await ue.reject();return}tt(()=>_n.current?.("paypal"));let Lt={generation:xn(),surfaceKey:O,...le};Nt.current=Lt,xt.current.set(O,Lt),await ue.resolve(),L.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),kt=L.startTiming()},createOrder:je==="order"?Ce?()=>B(Ce).then(Xt):()=>h("Failed to create PayPal order.").then(Xt):void 0,createSubscription:je==="subscription"?Ce?()=>B(Ce).then(Xt):()=>h("Failed to create PayPal subscription.").then(Xt):void 0,createVaultSetupToken:je==="setup_token"?()=>h("Failed to create PayPal setup token.").then(Xt):void 0,onApprove:k,onCancel:()=>{if(Ze())return;let se=xt.current.get(O)??Nt.current;se&&xt.current.delete(se.surfaceKey),Nt.current=null,Tt(),L.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ye.current=!0,br({generation:se?.generation,remount:!0,focus:!1})},onError:se=>{if(Ze()||_e.current!==O)return;let ue=se instanceof Error?se.message:"PayPal failed to render.";if(W(`onError rendered=${An} msg=${ue.slice(0,120)}`),An){let A=xt.current.get(O)??Nt.current;if(A&&!Tr(A.generation)||!A&&_t.current===zn.current)return;if(_(ue)){Qn(A?.generation);return}if(Tt(),go(se)){L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),f(se,A),tt(()=>Ot.current?.($t("paypal",ue))),A&&xt.current.delete(A.surfaceKey),Nt.current=null,Qn(A?.generation);return}let le=ue.toLowerCase();L.error({errorCode:le.includes("popup")&&le.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),A&&xt.current.delete(A.surfaceKey),Nt.current=null,br({generation:A?.generation,remount:!0,showRetry:!0,focus:!0}),X(se,{code:"paypal_runtime_failed"});return}Z(ue)}}),q=Ee.isEligible();if(W(`isEligible=${q}`),L.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!q){T(!1),Z("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}fn=Ee,De&&W(`container:dims ${on(hn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),De&&typeof MutationObserver<"u"&&(Mn=new MutationObserver(se=>{if(!Ze()){for(let ue of se)if(ue.type==="childList")ue.addedNodes.forEach(A=>{if(!(A instanceof Element))return;let le=A.tagName.toLowerCase(),st=(A.getAttribute("title")??"").slice(0,40),Lt=le==="iframe"?` ${er(A)}`:"";W(`child+ ${le}${st?` title="${st}"`:""}${Lt} dims=${on(A)}`)});else if(ue.type==="attributes"&&ue.target instanceof Element){let A=ue.target;if(A.tagName.toLowerCase()!=="iframe")continue;let le=ue.attributeName;(le==="src"||le==="srcdoc")&&W(`attr~ iframe ${le}=${le==="srcdoc"?`[${(A.getAttribute("srcdoc")??"").length}ch]`:an(A.getAttribute("src"))} dims=${on(A)}`)}}}),Mn.observe(hn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ge=se=>{if(Ze()||An)return;let ue=hn.querySelectorAll("iframe"),A=typeof document<"u"&&"hasStorageAccess"in document;W(`watchdog:${se} container=${on(hn)} children=${hn.childElementCount} iframes=${ue.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${A} paypalNetRequests=${at.value}`),ue.forEach((le,st)=>{let Lt=(le.getAttribute("title")??"").slice(0,40);W(` iframe[${st}] ${on(le)}${Lt?` title="${Lt}"`:""} ${er(le)}`);let ge=Ar(le);ge&&W(` ${ge}`)}),Fn.length===0&&W(" (no PayPal/zoid window errors captured)")};De&&(qt.push(setTimeout(()=>Ge("3s"),3e3)),qt.push(setTimeout(()=>Ge("8s"),8e3)),qt.push(setTimeout(()=>Ge("15s"),15e3))),W("render:start");let Qe=L.startTiming();qt.push(setTimeout(()=>{Ze()||An||(W("watchdog:11s retryable render timeout"),Z("PayPal Buttons render did not settle within 11000ms.",!0))},Dl)),Ee.render(hn).then(()=>{if(W(`render:resolved inactive=${Ze()}`),Yt(),Ze()){xe();return}An=!0,T(!0),Fe(!1),Jt.current?.("ready"),L.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"checkout_render",durationMs:L.elapsed(Qe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(se=>{let ue=se instanceof Error?se.message:"PayPal failed to render.";W(`render:rejected msg=${ue.slice(0,120)}`),Yt(),Z(ue)})}).catch(p=>{let k=p instanceof Error?p.message:"PayPal SDK failed to load.";W(`loadScript:rejected msg=${k.slice(0,120)}`),Z(k)})},0);return()=>{qe=!0,clearTimeout(vt),Cn&&clearTimeout(Cn),Yt(),xe()}},[fe,rt,c,S,s,je,y,e,Ce,ie,L,ct]);let $n=De?Ma("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Y?"#fef2f2":"#f3f4f6",border:`1px solid ${Y?"#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=${Y})`,Mt.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${Le.join(`
4
- `)}`]}):null;return Z&&!D?le?Sr("div",{children:mr}):null:ia("div",{children:[mr,ia("div",{"aria-hidden":ue?!0:void 0,style:ue?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Eo},children:[!de&&!ue&&Sr("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"}}),Sr("div",{ref:te,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Eo,display:"flex",opacity:de?1:0},"aria-busy":H||p},pe)]},pe),w&&Sr("button",{ref:Me,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:rt,style:nl,children:"Try PayPal again"})]})}function Ro(e){return Sr(Si,{...e})}function wi(e){return Sr(Si,{...e})}import{jsx as ki,jsxs as ol}from"react/jsx-runtime";function wr({children:e,margin:t,icon:n=!0,styleOverride:r}){return ol("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&&ki("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ki("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{resolveBillingApiUrl as al}from"@flopay/shared";import{useEffect as Zn,useMemo as il,useRef as Ii,useState as Ei}from"react";import{jsx as sl}from"react/jsx-runtime";function _o({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,m]=Ei(e instanceof Promise?null:e),[d,T]=Ei(t instanceof Promise||!t?null:t),h=Ii(null),P=Ii(null),b=Cr(r);Zn(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),Zn(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),Zn(()=>{if(a)return Bt(a)?.subscribe?.(b)},[b,a]),Zn(()=>{if(!(!d||d===a))return Bt(d)?.subscribe?.(b)},[b,a,d]),Zn(()=>{if(!a)return;let p=Bt(a);return h.current=p?.beginCheckout()??p?.now()??0,p?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{p?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),Zn(()=>{let p=!1;return e instanceof Promise?e.then(S=>{p||m(S)},()=>{p||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):m(e),()=>{p=!0}},[b,e]),Zn(()=>{let p=!1;if(!t){T(null);return}return t instanceof Promise?t.then(S=>{p||T(S)},()=>{p||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):T(t),()=>{p=!0}},[b,t]),Zn(()=>{if(!a||P.current===a)return;P.current=a;let p=Bt(a);p?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),p?.performance({stage:"checkout_render",durationMs:p.elapsed(h.current??0),durationMode:"machine"})},[b,a]);let x=al(n?.billingApiUrl),U=il(()=>({flopay:a,paypalFlopay:d,billingApiUrl:x,emitInstrument:b}),[a,d,x,b]);return sl(Pn.Provider,{value:U,children:o})}var To="flopay_recent_completion_";function kr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(To+e,JSON.stringify(t))}catch{}}function la(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(To+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(To+e),!1):!0}catch{return!1}}import{loadFloPay as Ri,PaymentAPI as Ti}from"@flopay/js";import{classifyPaymentRejection as ll,FloPayError as et,isAuthorizationOnlySession as cl,isSetupIntentClientSecret as dl,normalizeCheckoutFailureOutcome as _i}from"@flopay/shared";var Zr="card";async function ul(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:m}=await e.retrieveSetupIntent(t);return{error:m,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 pl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:m,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:m??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 da(e,t){return Object.assign(e,{checkoutMethod:t})}function $n(e,t){let n=e instanceof et?e:new et(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 Xr(e,t){try{return await e()}catch(n){throw $n(n,t)}}function xi(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function ml(e){return e.status==="succeeded"||e.status==="declined"}async function Ai(e){if(typeof document>"u"||typeof window>"u")throw new et("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new et("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let P=new AbortController,b=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",b);let x=window.setTimeout(()=>P.abort(),r);try{let U=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!U.ok)return{status:"unknown"};let p=await U.json().catch(()=>null);return yl(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(x),e.signal?.removeEventListener("abort",b)}},m=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.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 T=document.createElement("iframe");T.setAttribute("title","Card authentication"),T.setAttribute("allow","payment"),T.tabIndex=0,T.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(";"),T.src=e.nextActionRedirectUrl,d.appendChild(T),document.body.appendChild(d),T.focus();let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}try{let P=await new Promise((b,x)=>{let U=!1,p=0,S=0,ee=0,W=!1,v=()=>{window.clearTimeout(p),window.clearInterval(S),window.clearTimeout(ee),window.removeEventListener("message",ce),T.removeEventListener("load",j),e.signal?.removeEventListener("abort",J)},ye=async()=>{if(!(U||W)){W=!0;try{let Se=await a();if(U||!ml(Se))return;U=!0,v(),b(Se)}finally{W=!1}}},j=()=>{window.clearTimeout(ee),ee=window.setTimeout(()=>{ye()},250)},J=()=>{U||(U=!0,v(),x(new et("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ce=Se=>{if(Se.source!==T.contentWindow||h&&Se.origin!==h)return;let re=Se.data;!re||typeof re!="object"||re.source!=="flopay-vault-3ds-return"||U||(U=!0,v(),b(null))};p=window.setTimeout(()=>{U||(U=!0,v(),x(new et("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),S=window.setInterval(()=>{ye()},n),T.addEventListener("load",j),window.addEventListener("message",ce),e.signal?.addEventListener("abort",J),e.signal?.aborted&&J()});return P||await a()}finally{d.parentNode?.removeChild(d),m?.isConnected&&m.focus()}}function yl(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Qn(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=Wn(o)??o;return da(new et(a,"api_error",{code:_i(e?.outcome)??_i(e?.type)??e?.gatewayErrorCode}),r)}function ca(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function xo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function fl(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function Mi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||xo(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let d of a)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||xo(d)))return d;let m=o.gateways;if(m&&typeof m=="object"){let d=m.stripe;if(d&&typeof d=="object"){let T=d,h=[T.stripeClientSecret,T.clientSecret];for(let P of h)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||xo(P)))return P}}}}async function gl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Mi(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new Ti(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(xo(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Ir({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:m}){let d=e.replace(/\/+$/,""),T=t??n.id,h=r??n.clientSecret,P=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",x=n.customer?.firstName??n.accountData?.firstName??"",U=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,S=n.customer?.zip??n.accountData?.zip??void 0,ee=new Ti(d,m===!1?{telemetry:!1}:void 0),W=await fl(()=>ee.processPayment(P,{sessionId:T,nonce:h,tokenizedData:o,accountData:{userId:P,email:b,firstName:x,lastName:U,country:p,zip:S},returnUrl:a??ca(n)}));if(W.ok){let j=typeof W.json=="function"?await W.json().catch(()=>null):null;return cl(n)||j?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof j?.paymentId=="string"?j.paymentId:n.paymentId,sessionId:typeof j?.sessionId=="string"?j.sessionId:T,authorizationExpiresAt:typeof j?.authorizationExpiresAt=="string"?j.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Gr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Gr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let v;try{v=await W.json()}catch{throw new et("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:W.status})}if(v?.type==="paypal_redirect_required"||v?.type==="3ds_required"){let j=Mi(v);if(!j)throw new et("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:W.status});return{type:v.type,threeDSecureToken:j,paymentMethodId:v.paymentMethodId}}if(v?.gatewayErrorCode==="authentication_required"){let j=await gl({billingApiUrl:d,sessionId:T,nonce:h,responseJson:v});if(j)return j;throw da(new et("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ye=new et(v?.message??"Payment failed. Please try again.","api_error",{code:v?.code??v?.gatewayErrorCode,declineCode:v?.declineCode??v?.gatewayDeclineReason,statusCode:W.status});throw Object.assign(ye,{telemetryOutcome:ll(W.status,v)})}async function Ao(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:m,returnUrl:d,telemetry:T}){let h=t?.getRawProvider();if(!h)throw $n(new et("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw da(new et("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=dl(e.threeDSecureToken),b=null,x=e.paymentMethodId,U=await Xr(()=>ul(h,e.threeDSecureToken,P),"card");if(U){if(U.error)throw $n(new et(U.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:U.error.code}),"card");let S=U.intent;!x&&S?.payment_method&&(typeof S.payment_method=="string"?x=S.payment_method:"id"in S.payment_method&&(x=S.payment_method.id??void 0))}let p=x?await Xr(()=>pl(h,e.threeDSecureToken,{payment_method:x,return_url:d??ca(m)??window.location.href},P),"card"):null;if(p){if(p.error)throw $n(new et(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");b=p.intent}else{let S=await Xr(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(S.error)throw $n(new et(S.error.message??"3DS authentication failed.","api_error",{code:S.error.code}),"card");b=(P?S.setupIntent:S.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let S=await Ir({billingApiUrl:o,sessionId:a,session:m,telemetry:T,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:d});return S.type==="success"?{...S.result,paymentIntentId:S.result.paymentIntentId??b.id,paymentMethodId:S.result.paymentMethodId??x}:Ao(S,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:m,returnUrl:d,telemetry:T})}throw $n(new et("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let P=(n??t)?.getRawProvider();if(!P)throw $n(new et("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:x}=await Xr(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(x)throw $n(new et(x.message??"PayPal authorization failed.","api_error",{code:x.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Xr(()=>P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??ca(m)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw $n(new et(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new et("Unsupported payment redirect state.","api_error")}function ur(e){if(e instanceof et){let r=Wn(e.message);return r&&r!==e.message?Object.assign(new et(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Wn(t)??t;return new et(n,"api_error")}function Mo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new et("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function Bo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[m,d]=await Promise.all([Ri(e,{billingApiUrl:n,locale:r,telemetry:o}),a?Ri(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(T=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",T),null)):Promise.resolve(null)]);return{flopay:m,paypalFlopay:t?a?d:m:null}}import{PaymentAPI as eo,toStripeAppearance as hl}from"@flopay/js";import{COUNTRY_OPTIONS as Pl,classifyPaymentRejection as bl,FloPayError as In,filterStripeMethodsByCountry as vl,getPostalCodeExample as Cl,getPostalCodeLabel as ya,getStateFromPostalCode as Di,getStateLabel as Li,getStateOptions as Sl,getStripeMethodDisplayName as Rr,hasVendoredStripeMethodLogo as wl,isAuthorizationOnlySession as ua,isAVSFieldVisible as Te,isPostalCodeSupported as kl,isSetupIntentClientSecret as Il,isValidPostalCode as El,needsStripeMethodExplicitConfirm as Oi,normalizeCheckoutFailureOutcome as Rl,partitionStripeMethods as _l,resolveAVSConfig as Tl,resolveButtonsLayoutTheme as xl,resolveStripeMethodBrandVariant as Al,resolveTheme as Ml,stripeExpressMethodToOptionKey as Ni}from"@flopay/shared";import{ExpressCheckoutElement as Yi,PaymentElement as Bl,Elements as pr,useElements as ga,useStripe as ha}from"@stripe/react-stripe-js";import Fl,{useCallback as he,useContext as _r,useEffect as lt,useMemo as st,useRef as Ee,useState as ge}from"react";function Bi(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var Fi={alipay:new URL("./payment-logos/alipay.svg",import.meta.url).href,bancontact:new URL("./payment-logos/bancontact.svg",import.meta.url).href,blik:new URL("./payment-logos/blik.svg",import.meta.url).href,eps:new URL("./payment-logos/eps.svg",import.meta.url).href,giropay:new URL("./payment-logos/giropay.svg",import.meta.url).href,ideal:new URL("./payment-logos/ideal.svg",import.meta.url).href,klarna:new URL("./payment-logos/klarna.svg",import.meta.url).href,p24:new URL("./payment-logos/p24.svg",import.meta.url).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",import.meta.url).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",import.meta.url).href};import{Fragment as Er,jsx as u,jsxs as xe}from"react/jsx-runtime";var Bn="flopay_stripe_resume",zi="flopay_wallet_resume";function Gi(e){return e instanceof In&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Do(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new eo(e).createSessionIntent(...n)}catch(o){throw Gi(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Qr="flopay_paypal_resume",Dl=250,Ui="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Pa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Lo({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new eo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Ll(e){return e instanceof In&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function pa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var Ol=`
3
+ ${Mt.join(`
4
+ `)}`]}):null;return Y&&!dt?De?pr("div",{children:$n}):null:Ma("div",{children:[$n,St&&pr(Ir,{identity:St,methodLabel:"PayPal",testId:"flopay-direct-paypal-identity-pane",onComplete:v=>{Un(v)},submitting:I}),de&&pr(Ir,{identity:de.identity,methodLabel:de.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:it,onCancel:()=>it(null)}),Ma("div",{"aria-hidden":ae||St||de?!0:void 0,style:ae||St||de?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Wo},children:[!te&&!ae&&pr("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"}}),pr("div",{ref:me,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Wo,display:"flex",opacity:te?1:0},"aria-busy":we||ve},ie)]},ie),Je&&pr("button",{ref:Ue,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:zt,style:Ol,children:"Try PayPal again"})]})}function Jo(e){return pr(es,{...e})}function ts(e){return pr(es,{...e})}import{jsx as ns,jsxs as ql}from"react/jsx-runtime";function Kr({children:e,margin:t,icon:n=!0,styleOverride:r}){return ql("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&&ns("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ns("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{resolveBillingApiUrl as $l}from"@flopay/shared";import{useEffect as mr,useMemo as jl,useRef as rs,useState as os}from"react";import{jsx as Kl}from"react/jsx-runtime";function Xo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,c]=os(e instanceof Promise?null:e),[s,S]=os(t instanceof Promise||!t?null:t),b=rs(null),g=rs(null),m=jr(r);mr(()=>{m({class:"lifecycle",name:"checkout.mount"})},[m]),mr(()=>{a&&m({class:"lifecycle",name:"sdk.initialize.ready"})},[m,a]),mr(()=>{if(a)return jt(a)?.subscribe?.(m)},[m,a]),mr(()=>{if(!(!s||s===a))return jt(s)?.subscribe?.(m)},[m,a,s]),mr(()=>{if(!a)return;let u=jt(a);return b.current=u?.beginCheckout()??u?.now()??0,u?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{u?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),mr(()=>{let u=!1;return e instanceof Promise?e.then(w=>{u||c(w)},()=>{u||m({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{u=!0}},[m,e]),mr(()=>{let u=!1;if(!t){S(null);return}return t instanceof Promise?t.then(w=>{u||S(w)},()=>{u||m({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):S(t),()=>{u=!0}},[m,t]),mr(()=>{if(!a||g.current===a)return;g.current=a;let u=jt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),m({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(b.current??0),durationMode:"machine"})},[m,a]);let M=$l(n?.billingApiUrl),D=jl(()=>({flopay:a,paypalFlopay:s,billingApiUrl:M,emitInstrument:m}),[a,s,M,m]);return Kl(In.Provider,{value:D,children:o})}var Zo="flopay_recent_completion_";function Vr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Zo+e,JSON.stringify(t))}catch{}}function Fa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Zo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Zo+e),!1):!0}catch{return!1}}import{loadFloPay as as,PaymentAPI as ss}from"@flopay/js";import{classifyPaymentRejection as Vl,FloPayError as lt,isAuthorizationOnlySession as Hl,isSetupIntentClientSecret as Yl,normalizeCheckoutFailureOutcome as is}from"@flopay/shared";var Po="card";async function Gl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:c}=await e.retrieveSetupIntent(t);return{error:c,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 Wl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:c??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 Da(e,t){return Object.assign(e,{checkoutMethod:t})}function rr(e,t){let n=e instanceof lt?e:new lt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function vo(e,t){try{return await e()}catch(n){throw rr(n,t)}}function ls(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 Jl(e){return e.status==="succeeded"||e.status==="declined"}async function cs(e){if(typeof document>"u"||typeof window>"u")throw new lt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new lt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let g=new AbortController,m=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",m);let M=window.setTimeout(()=>g.abort(),r);try{let D=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!D.ok)return{status:"unknown"};let u=await D.json().catch(()=>null);return Xl(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(M),e.signal?.removeEventListener("abort",m)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.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 S=document.createElement("iframe");S.setAttribute("title","Card authentication"),S.setAttribute("allow","payment"),S.tabIndex=0,S.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(";"),S.src=e.nextActionRedirectUrl,s.appendChild(S),document.body.appendChild(s),S.focus();let b=null;try{b=new URL(e.billingApiUrl,window.location.href).origin}catch{b=null}try{let g=await new Promise((m,M)=>{let D=!1,u=0,w=0,ve=0,H=!1,P=()=>{window.clearTimeout(u),window.clearInterval(w),window.clearTimeout(ve),window.removeEventListener("message",oe),S.removeEventListener("load",Q),e.signal?.removeEventListener("abort",ce)},fe=async()=>{if(!(D||H)){H=!0;try{let Ce=await a();if(D||!Jl(Ce))return;D=!0,P(),m(Ce)}finally{H=!1}}},Q=()=>{window.clearTimeout(ve),ve=window.setTimeout(()=>{fe()},250)},ce=()=>{D||(D=!0,P(),M(new lt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},oe=Ce=>{if(Ce.source!==S.contentWindow||b&&Ce.origin!==b)return;let He=Ce.data;!He||typeof He!="object"||He.source!=="flopay-vault-3ds-return"||D||(D=!0,P(),m(null))};u=window.setTimeout(()=>{D||(D=!0,P(),M(new lt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),w=window.setInterval(()=>{fe()},n),S.addEventListener("load",Q),window.addEventListener("message",oe),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return g||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function Xl(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function yr(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=cr(o)??o;return Da(new lt(a,"api_error",{code:is(e?.outcome)??is(e?.type)??e?.gatewayErrorCode}),r)}function Na(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Qo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Zl(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function ds(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(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 s of a)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(s)))return s;let c=o.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let S=s,b=[S.stripeClientSecret,S.clientSecret];for(let g of b)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(g)))return g}}}}async function Ql({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ds(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let s=(await new ss(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Qo(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function Hr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),S=t??n.id,b=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",m=n.customer?.email??n.accountData?.email??"",M=n.customer?.firstName??n.accountData?.firstName??"",D=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,w=n.customer?.zip??n.accountData?.zip??void 0,ve=new ss(s,c===!1?{telemetry:!1}:void 0),H=await Zl(()=>ve.processPayment(g,{sessionId:S,nonce:b,tokenizedData:o,accountData:{userId:g,email:m,firstName:M,lastName:D,country:u,zip:w},returnUrl:a??Na(n)}));if(H.ok){let Q=typeof H.json=="function"?await H.json().catch(()=>null):null;return Hl(n)||Q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Q?.paymentId=="string"?Q.paymentId:n.paymentId,sessionId:typeof Q?.sessionId=="string"?Q.sessionId:S,authorizationExpiresAt:typeof Q?.authorizationExpiresAt=="string"?Q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let P;try{P=await H.json()}catch{throw new lt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status})}if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let Q=ds(P);if(!Q)throw new lt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status});return{type:P.type,threeDSecureToken:Q,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let Q=await Ql({billingApiUrl:s,sessionId:S,nonce:b,responseJson:P});if(Q)return Q;throw Da(new lt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let fe=new lt(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:H.status});throw Object.assign(fe,{telemetryOutcome:Vl(H.status,P)})}async function ea(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:c,returnUrl:s,telemetry:S}){let b=t?.getRawProvider();if(!b)throw rr(new lt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Da(new lt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Yl(e.threeDSecureToken),m=null,M=e.paymentMethodId,D=await vo(()=>Gl(b,e.threeDSecureToken,g),"card");if(D){if(D.error)throw rr(new lt(D.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:D.error.code}),"card");let w=D.intent;!M&&w?.payment_method&&(typeof w.payment_method=="string"?M=w.payment_method:"id"in w.payment_method&&(M=w.payment_method.id??void 0))}let u=M?await vo(()=>Wl(b,e.threeDSecureToken,{payment_method:M,return_url:s??Na(c)??window.location.href},g),"card"):null;if(u){if(u.error)throw rr(new lt(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");m=u.intent}else{let w=await vo(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(w.error)throw rr(new lt(w.error.message??"3DS authentication failed.","api_error",{code:w.error.code}),"card");m=(g?w.setupIntent:w.paymentIntent)??null}if(m&&(m.status==="requires_capture"||m.status==="succeeded"||m.status==="processing")){let w=await Hr({billingApiUrl:o,sessionId:a,session:c,telemetry:S,tokenizedData:{id:m.id,type:"card",threeDSecureActionResultTokenId:m.id},returnUrl:s});return w.type==="success"?{...w.result,paymentIntentId:w.result.paymentIntentId??m.id,paymentMethodId:w.result.paymentMethodId??M}:ea(w,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:c,returnUrl:s,telemetry:S})}throw rr(new lt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw rr(new lt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:M}=await vo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(M)throw rr(new lt(M.message??"PayPal authorization failed.","api_error",{code:M.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:m}=await vo(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Na(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(m)throw rr(new lt(m.message??"PayPal authorization failed.","api_error",{code:m.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new lt("Unsupported payment redirect state.","api_error")}function Rr(e){if(e instanceof lt){let r=cr(e.message);return r&&r!==e.message?Object.assign(new lt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=cr(t)??t;return new lt(n,"api_error")}function ta(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new lt("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function na({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[c,s]=await Promise.all([as(e,{billingApiUrl:n,locale:r,telemetry:o}),a?as(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{PaymentAPI as So,toStripeAppearance as ec}from"@flopay/js";import{COUNTRY_OPTIONS as tc,classifyPaymentRejection as nc,FloPayError as On,filterStripeMethodsByCountry as rc,getPostalCodeExample as oc,getPostalCodeLabel as Ua,getStateFromPostalCode as ms,getStateLabel as ys,getStateOptions as ac,getStripeMethodDisplayName as xr,hasVendoredStripeMethodLogo as ic,isAuthorizationOnlySession as La,isAVSFieldVisible as ze,isPostalCodeSupported as sc,isSetupIntentClientSecret as lc,isValidEmail as en,isValidPostalCode as cc,needsStripeMethodExplicitConfirm as fs,normalizeCheckoutFailureOutcome as dc,partitionStripeMethods as uc,resolveAVSConfig as pc,resolveButtonsLayoutTheme as mc,resolveStripeMethodBrandVariant as yc,resolveTheme as fc,stripeExpressMethodToOptionKey as gs}from"@flopay/shared";import{ExpressCheckoutElement as Is,PaymentElement as gc,Elements as _r,useElements as ja,useStripe as Ka}from"@stripe/react-stripe-js";import hc,{useCallback as Pe,useContext as Yr,useEffect as ht,useMemo as gt,useRef as Ie,useState as ye}from"react";function us(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var ps={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"};import{Fragment as fr,jsx as l,jsxs as ke}from"react/jsx-runtime";var Gn="flopay_stripe_resume",hs="flopay_wallet_resume";function Es(e){return e instanceof On&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function oa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new So(e).createSessionIntent(...n)}catch(o){throw Es(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Co="flopay_paypal_resume",bc=250,bs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Va(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function aa({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new So(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function vc(e){return e instanceof On&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Oa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Pc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=kn(r?.name),a=kn(n);return{email:r?.email?.trim()||t?.trim(),firstName:o.firstName??a.firstName,lastName:o.lastName??a.lastName}}async function Rs({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let c=Pc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return!en(c.email)||!fo(c)?a(o,c):c}var Cc=`
5
5
  .paypal-buttons { margin: 0 !important; vertical-align: top !important; }
6
6
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
7
7
  @keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
@@ -22,7 +22,7 @@ ${Le.join(`
22
22
  0% { opacity: 1; transform: translateX(0) scale(1); }
23
23
  100% { opacity: 0; transform: translateX(16px) scale(0.97); }
24
24
  }
25
- `,Fo=44;function ba(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 Nl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Wi={width:"100%",minHeight:Fo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function zl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function $i(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ji(e){return e==="paypal"?"PayPal":Rr(e)}function Ul(e,t){let n=`We couldn't open ${Ji(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Xi(e){let t=Ee(0),n=Ee(null),r=Ee(null),o=he((p=r.current)=>{let S=p;S?.timer&&(clearTimeout(S.timer),S.timer=null)},[]),a=he((p,S)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(p),p.timer=setTimeout(()=>{p.timer=null,r.current?.generation===p.generation&&(r.current=null,n.current=p.generation,e(p.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},S))},[o,e]),m=he(p=>{p.yieldedControl&&a(p,600)},[a]),d=he(p=>{o();let S=t.current+1;t.current=S,n.current=null;let ee={generation:S,method:p,timer:null,yieldedControl:!1};return r.current=ee,S},[o]),T=he(p=>{let S=r.current;return typeof p=="number"&&S?.generation!==p?!1:(o(S),r.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[o]),h=he(p=>{let S=r.current,ee=p??S?.generation??t.current;(!p||S?.generation===p)&&(o(S),r.current=null),n.current=ee},[o]),P=he(p=>n.current===(p??t.current),[]),b=he(p=>r.current?.generation===p&&n.current!==p,[]),x=he(()=>{let p=r.current;p&&m(p)},[m]),U=he(()=>{let p=r.current;p&&(p.yieldedControl=!0,o(p))},[o]);return lt(()=>{let p=()=>{document.visibilityState==="visible"?x():U()},S=()=>{U()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",S),window.addEventListener("focus",x),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",S),window.removeEventListener("focus",x),o()}},[o,U,x]),{startAttempt:d,finishAttempt:T,invalidateAttempt:h,isAttemptInvalidated:P,isAttemptCurrent:b}}function $l(e){let t=Cl(e);return`Enter a valid ${ya(e)}${t?` (e.g. ${t})`:""}`}function ql(e,t,n){let r=kl(e),o=t.trim(),a=n&&r,m=a&&!o,d=a&&!!o&&!El(e,o);return{visible:n,supported:r,required:a,empty:m,malformed:d}}function qi(e,t){return t instanceof In?t:new In(t instanceof Error?t.message:`${zl(e)} before-click hook failed.`,"validation_error")}function ma(){return u("style",{children:Ol})}function jl(e){return typeof e=="number"?`${e}px`:e}function Zi(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Qi({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:xe("div",{style:{position:"relative",minHeight:44},children:[u("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"}}),u("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 ji(e){return e!=="unavailable"&&e!=="load_error"}function va(e){return u(Vl,{...e})}function Ki({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:m=!1,onButtonClick:d,onDecline:T,onTechnicalFailure:h,runBeforeButtonClick:P,onLoadStateChange:b,placeholderBorderRadius:x}){let U=Xn(),{emitInstrument:p}=_r(Pn),S=ha(),ee=ga(),[W,v]=ge("loading");lt(()=>{b?.(W)},[W,b]);let[ye,j]=ge(!1),J=Ee(!1),ce=Ee(null),Se=Ee(null),[re,le]=ge(0),[Ve,Ae]=ge(!1),Ce=Ee(!1),q=Ee(new Map),{startAttempt:B,finishAttempt:te,invalidateAttempt:tt,isAttemptInvalidated:Me,isAttemptCurrent:V}=Xi((O,w,oe)=>{h?.(O,w,{...oe,popupBlocked:oe?.popupBlocked??Jn(w)}),Ae(!0),le(qe=>qe+1)});lt(()=>{Ve&&Se.current?.focus()},[Ve,re]);let de=he(()=>{le(O=>O+1)},[]),ae=he((O,w,oe)=>{tt(oe),h?.("paypal",O,{code:w,popupBlocked:Jn(O)}),Ae(!0),de()},[tt,h,de]),ue=he(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);lt(()=>{Ce.current&&(Ce.current=!1,ue())},[ue,re]);let ke=he(()=>{Ae(!1),a?.(null),ue()},[ue,a]);lt(()=>{if(!S||J.current)return;let O=new URLSearchParams(window.location.search),w=O.get("payment_intent"),oe=O.get("payment_intent_client_secret"),qe=O.get("redirect_status");if(!w||!oe)return;J.current=!0;let De;try{let R=localStorage.getItem(Qr);if(R){let H=JSON.parse(R);H.clientSecret===oe&&(De={...H.accountPatch?{accountPatch:H.accountPatch}:{},...H.sessionId?{sessionId:H.sessionId}:{},...H.nonce?{nonce:H.nonce}:{}})}}catch{}try{localStorage.removeItem(Qr)}catch{}let Z=new URL(window.location.href);Z.searchParams.delete("payment_intent"),Z.searchParams.delete("payment_intent_client_secret"),Z.searchParams.delete("redirect_status"),window.history.replaceState({},"",Z.toString()),(async()=>{try{if(j(!0),qe==="failed"){let $="PayPal payment was declined. Please try again.";a?.($),T?.(Mt("paypal",$));return}let{paymentIntent:R,error:H}=await S.retrievePaymentIntent(oe);if(H){a?.(H.message??"Failed to retrieve PayPal payment status.");return}if(R&&(R.status==="requires_capture"||R.status==="succeeded")){let $=typeof R.payment_method=="string"?R.payment_method:R.payment_method?.id;o({id:$??R.id,type:"card",threeDSecureActionResultTokenId:R.id,isPaypal:!0},De)}else{let $="PayPal payment was not completed. Please try again.";a?.($),T?.(Mt("paypal",$))}}catch(R){a?.(R instanceof Error?R.message:"Failed to complete PayPal payment.")}finally{j(!1)}})()},[S,o,a,T]);let pe=he(async O=>{if(m||ye){O.reject();return}let w=P?await P("paypal"):{proceed:!0};if(!w.proceed){q.current.delete(re),O.reject();return}let oe=B("paypal");q.current.set(re,{generation:oe,accountPatch:w.accountPatch,sessionId:w.sessionId,nonce:w.nonce}),Ae(!1),d?.("paypal"),O.resolve()},[q,m,d,P,B,ye,re]),Re=he(async O=>{if(!S||!ee)return;let w=q.current.get(re);if(w&&!V(w.generation)){q.current.delete(re);return}if(!w&&Me()||w&&!te(w.generation))return;w||te();let oe=w??null;if(q.current.delete(re),!oe&&P){let R=await P("paypal");if(!R.proceed){O.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}oe={accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}}let qe=oe?.sessionId??e,De=oe?.nonce??t,Z=oe?.accountPatch?.email??n;try{if(j(!0),a?.(null),!qe||!Z)throw new Error("Missing sessionId or email for PayPal payment");let R=S.createPaymentMethod,{error:H,paymentMethod:$}=await R({type:"paypal"});if(H){ae(H,"stripe_paypal_create_payment_method_failed",w?.generation),O.paymentFailed({reason:"fail"});return}let Be=await Do(r,p,qe,De??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:$?.id??null,intentKind:"payment"});if(Be.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ie=Be.clientSecret,We={return_url:window.location.href};if($?.id&&(We.payment_method=$.id),typeof window<"u")try{localStorage.setItem(Qr,JSON.stringify({clientSecret:Ie,sessionId:qe,nonce:De,accountPatch:oe?.accountPatch}))}catch{}let{error:Y,paymentIntent:mt}=await S.confirmPayment({clientSecret:Ie,confirmParams:We,redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(Qr)}catch{}if(Wr(Y)){let Le=Y.message??"Your payment was declined.";a?.(Le),T?.(Mt("paypal",Le,{code:Un(Y),declineCode:vr(Y)})),await Lo({billingApiUrl:r,sessionId:qe,nonce:De,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Un(Y)??"provider_declined"}})}else ae(Y,"stripe_paypal_confirm_failed",w?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Qr)}catch{}let D=typeof mt?.payment_method=="string"?mt.payment_method:mt?.payment_method?.id;o({id:D??mt?.id,type:"card",threeDSecureActionResultTokenId:mt?.id,isPaypal:!0},{accountPatch:oe?.accountPatch,sessionId:qe,nonce:De});return}catch(R){ae(R,"stripe_paypal_failed",w?.generation)}finally{j(!1)}},[S,ee,e,t,n,r,p,o,a,T,P,ae,te,V,Me,re]);return xe(Er,{children:[u(Qi,{state:W,placeholderTestId:"flopay-paypal-placeholder",borderRadius:x,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ve&&u("button",{ref:Se,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ke,style:Wi,children:"Try PayPal again"}),u(Yi,{onReady:O=>v(Zi(O,["paypal"])),onLoadError:()=>{v("load_error"),Pa(Bt(U),"paypal","paypal")},onClick:pe,onConfirm:Re,onCancel:()=>{let O=q.current.get(re);q.current.delete(re),Bt(U)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),tt(O?.generation),Ae(!1),Ce.current=!0,de()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},re)]})}),ye&&u(Mn,{status:"processing"})]})}function Vi({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:m,onErrorChange:d,onButtonClick:T,onDecline:h,onTechnicalFailure:P,runBeforeButtonClick:b,onLoadStateChange:x,placeholderBorderRadius:U}){let p=Xn(),{emitInstrument:S}=_r(Pn),ee=ha(),W=ga(),[v,ye]=ge("loading");lt(()=>{x?.(v)},[v,x]);let[j,J]=ge(!1),ce=Ee(null),Se=Ee(null),[re,le]=ge(0),[Ve,Ae]=ge(!1),[Ce,q]=ge("google_pay"),B=Ee(!1),te=Ee("google_pay"),tt=Ee("google_pay"),Me=Ee(new Map),{startAttempt:V,finishAttempt:de,invalidateAttempt:ae,isAttemptInvalidated:ue,isAttemptCurrent:ke}=Xi((Z,R,H)=>{P?.(Z,R,{...H,popupBlocked:H?.popupBlocked??Jn(R)}),q(Z),Ae(!0),le($=>$+1)});lt(()=>{Ve&&Se.current?.focus()},[Ve,re]);let pe=he(()=>{le(Z=>Z+1)},[]),Re=he((Z,R,H,$)=>{ae($),P?.(Z,R,{code:H,popupBlocked:Jn(R)}),q(Z),Ae(!0),pe()},[ae,P,pe]),O=he(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);lt(()=>{B.current&&(B.current=!1,O())},[O,re]);let w=he(()=>{Ae(!1),d?.(null),O()},[O,d]),oe=he(async Z=>{if(!ee||!W)return;let R=Me.current.get(re);if(R&&!ke(R.generation)){Me.current.delete(re);return}if(!R&&ue()||R&&!de(R.generation))return;R||de();let H=Z.expressPaymentType??R?.method??te.current,$=R??null;Me.current.delete(re);let Be=$i(H);if(!$&&b){let D=await b(Be);if(!D.proceed){Z.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}$={accountPatch:D.accountPatch,sessionId:D.sessionId,nonce:D.nonce}}let Ie=Be,We=$?.sessionId??e,Y=$?.nonce??t,mt=$?.accountPatch?.email??n;try{J(!0),d?.(null);let{error:D}=await W.submit();if(D){Re(H,D,"stripe_wallet_submit_failed",R?.generation);return}let{error:Le,paymentMethod:Pt}=await ee.createPaymentMethod({elements:W});if(Le||!Pt){Re(H,Le??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",R?.generation);return}if(!We||!mt)throw new Error("Missing sessionId or email for wallet payment");let N=await Do(r,S,We,Y??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H??Be,paymentMethodId:Pt.id,intentKind:o});if(N.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let bt=N.clientSecret,{error:ze,intentId:tn}=Il(bt)?await ee.confirmCardSetup(bt,{payment_method:Pt.id}).then(It=>({error:It.error,intentId:It.setupIntent?.id})):await ee.confirmCardPayment(bt,{payment_method:Pt.id}).then(It=>({error:It.error,intentId:It.paymentIntent?.id}));if(ze){if(Wr(ze)){let It=ze.message??"Your payment was declined.";d?.(It),h?.(Mt(Ie,It,{code:Un(ze),declineCode:vr(ze)})),await Lo({billingApiUrl:r,sessionId:We,nonce:Y,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H??Be,providerDeclineReason:Un(ze)??"provider_declined"}})}else Re(H,ze,"stripe_wallet_confirm_failed",R?.generation);return}m({id:Pt.id,type:"card",threeDSecureActionResultTokenId:tn},{accountPatch:$?.accountPatch,sessionId:We,nonce:Y})}catch(D){Re(H,D,"stripe_wallet_failed",R?.generation)}finally{J(!1)}},[ee,W,e,t,n,r,S,o,m,d,h,b,Re,de,ke,ue,re]),qe=st(()=>{let Z=["applePay","googlePay","paypal","link","amazonPay","klarna"],R=new Set(["applePay","googlePay"]),H=new Set(a.map(Ni)),$={};for(let Be of Z)H.has(Be)?$[Be]=R.has(Be)?"always":"auto":$[Be]="never";return $},[a]),De=st(()=>a.map(Ni),[a]);return xe(Er,{children:[u(Qi,{state:v,placeholderTestId:"flopay-wallet-placeholder",borderRadius:U,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Ve&&xe("button",{ref:Se,type:"button","data-testid":"flopay-wallet-retry-button",onClick:w,style:Wi,children:["Try ",Ji(Ce)," again"]}),u(Yi,{onReady:Z=>{ye(Zi(Z,De))},onLoadError:Z=>{ye("load_error"),Pa(Bt(p),"stripe","wallet")},onClick:async Z=>{te.current=Z.expressPaymentType,tt.current=$i(Z.expressPaymentType);let R=b?await b(tt.current):{proceed:!0};if(!R.proceed){Me.current.delete(re),Z.reject();return}let H=V(Z.expressPaymentType);Me.current.set(re,{generation:H,method:Z.expressPaymentType,accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}),Ae(!1),T?.(tt.current),Z.resolve()},onConfirm:oe,onCancel:()=>{let Z=Me.current.get(re);Me.current.delete(re),Bt(p)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ae(Z?.generation),Ae(!1),B.current=!0,pe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:qe,layout:{maxColumns:1,overflow:"never"}}},re)]})}),j&&u(Mn,{status:"processing"})]})}function Kl({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:m,backgroundColor:d,borderColor:T,textColor:h,borderRadius:P,fontFamily:b}){let x=Al(e,t),U=Fi[e],p=x?.backgroundColor??d??"#ffffff",S=x?.borderColor??T??"#d1d5db",ee=x?.textColor??h??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&m()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Fo,padding:"0 1rem",backgroundColor:p,color:ee,border:`1px solid ${S}`,borderRadius:P??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?u("span",{style:{margin:"0 auto"},children:`Connecting to ${Rr(e)}\u2026`}):xe(Er,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:wl(e)?8:0},children:[U?u("img",{src:U,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):x?.logoSvg?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:x.logoSvg}}):null,u("span",{children:Rr(e)})]}),a&&u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ee,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:u("path",{d:"M9 18l6-6-6-6"})})]})})}function fa({method:e,sessionId:t,nonce:n,email:r,billingName:o,billingApiUrl:a,onTokenizedBody:m,onErrorChange:d,onDecline:T,onCancel:h,runBeforeButtonClick:P,onButtonClick:b,isProcessing:x,submitButtonColor:U,submitButtonBorderRadius:p,submitButtonStyle:S,errorText:ee}){let W=Xn(),{emitInstrument:v}=_r(Pn),ye=ha(),j=ga(),[J,ce]=ge(!1),Se=Ee(!1),[re,le]=ge(!1),[Ve,Ae]=ge("loading"),Ce=he(async()=>{if(!ye||!j||x||Se.current||!re)return;Se.current=!0,ce(!0);let q=P?await P("card"):{proceed:!0};if(!q.proceed){Se.current=!1,ce(!1);return}b?.("card");let B=q.sessionId??t,te=q.nonce??n,tt=q.accountPatch?.email??r;try{d?.(null);let Me=await j.submit();if(Me.error){d?.(Me.error.message??"Payment failed.");return}let V=await ye.createPaymentMethod({elements:j});if(V.error||!V.paymentMethod){d?.(V.error?.message??"Failed to create payment method.");return}let de=V.paymentMethod;if(!B||!tt)throw new Error("Missing sessionId or email for payment.");let ae=de.type||e,ue=await Do(a,v,B,te??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ae,paymentMethodId:null,intentKind:"payment"});if(ue.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ke=ue.clientSecret;if(typeof window<"u")try{localStorage.setItem(Bn,JSON.stringify({clientSecret:ke,sessionId:B,nonce:te,accountPatch:q.accountPatch,paymentMethodId:de.id,paymentMethodType:de.type??e,gateway:"stripe"}))}catch{}let{error:pe,paymentIntent:Re}=await ye.confirmPayment({clientSecret:ke,confirmParams:{return_url:window.location.href,payment_method:de.id},redirect:"if_required"});if(pe){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let oe=pe.message??"Payment failed.";d?.(oe),T?.(Mt("card",oe,{code:pe.code})),await Lo({billingApiUrl:a,sessionId:B,nonce:te,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:pe.code??"provider_declined"}});return}let O=Re?.status;if(!vo(O)){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let oe=O==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(oe),T?.(Mt("card",oe,{code:O??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let w=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;m({id:w??de.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:de.type??e},{accountPatch:q.accountPatch,sessionId:B,nonce:te})}catch(Me){d?.(Me instanceof Error?Me.message:"Payment failed. Please try again.")}finally{Se.current=!1,ce(!1)}},[ye,j,x,re,P,b,t,n,r,a,v,e,m,d,T]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[u(Bl,{onReady:()=>Ae("ready"),onLoadError:()=>{Ae("load_error"),Pa(Bt(W),"stripe","apm")},onChange:q=>{le(!!q.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...r?{email:r}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ce()},disabled:!re||J||x||Ve!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:U,color:"white",border:"none",borderRadius:p,fontSize:"1rem",fontWeight:600,cursor:!re||J||x||Ve!=="ready"?"not-allowed":"pointer",opacity:!re||J||x||Ve!=="ready"?.5:1,transition:"opacity 120ms ease-out",...S??{}},children:J?"Processing\u2026":`Pay with ${Rr(e)}`}),ee&&u(wr,{margin:"0.75rem 0 0",children:ee})]})}function Hi({sessionId:e,nonce:t,email:n,billingName:r,billingApiUrl:o,paymentElementMethods:a,stripeInstance:m,paymentElementBaseOptions:d,onTokenizedBody:T,onErrorChange:h,onButtonClick:P,onDecline:b,runBeforeButtonClick:x,onLoadStateChange:U,isProcessing:p=!1,submitButtonColor:S="#4A49FF",submitButtonBorderRadius:ee=8,submitButtonStyle:W,buttonAppearance:v,themeId:ye,onExpandApm:j,expandedApmMethod:J}){let{emitInstrument:ce}=_r(Pn),[Se,re]=ge(null),[le,Ve]=ge(null),Ae=Ee(!1);lt(()=>{a.length>0&&m?U?.("ready"):m||U?.("loading")},[a.length,m,U]);let Ce=he(async V=>{if(!m||Ae.current||p)return;Ae.current=!0,Ve(V);let de=x?await x("card"):{proceed:!0};if(!de.proceed){Ae.current=!1,Ve(null);return}P?.("card");let ae=de.sessionId??e,ue=de.nonce??t,ke=de.accountPatch?.email??n;try{if(h?.(null),!ae||!ke)throw new Error("Missing sessionId or email for payment.");let pe=await Do(o,ce,ae,ue??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:V,paymentMethodId:null,intentKind:"payment"});if(pe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=pe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Bn,JSON.stringify({clientSecret:Re,sessionId:ae,nonce:ue,accountPatch:de.accountPatch,paymentMethodType:V,gateway:"stripe"}))}catch{}let{error:O,paymentIntent:w}=await m.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:V,billing_details:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...ke?{email:ke}:{}}}},redirect:"if_required"});if(O){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let De=O.message??"Payment failed.";h?.(De),b?.(Mt("card",De,{code:O.code})),await Lo({billingApiUrl:o,sessionId:ae,nonce:ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:V,providerDeclineReason:O.code??"provider_declined"}});return}let oe=w?.status;if(!vo(oe)){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let De=oe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(De),b?.(Mt("card",De,{code:oe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let qe=typeof w?.payment_method=="string"?w.payment_method:w?.payment_method?.id;T({id:qe??w?.id,type:"card",threeDSecureActionResultTokenId:w?.id,gateway:"stripe",paymentMethodType:V},{accountPatch:de.accountPatch,sessionId:ae,nonce:ue})}catch(pe){h?.(pe instanceof Error?pe.message:"Payment failed. Please try again.")}finally{Ae.current=!1,Ve(null)}},[m,p,x,P,e,t,n,o,ce,r,T,h,b]),[q,B]=ge(null),te=j?J??null:q,tt=he(V=>{Ae.current||p||te&&te!==V||(Oi(V)?j?j(V):B(V):Ce(V))},[te,p,Ce,j]),Me=st(()=>q?{...d,paymentMethodTypes:[q]}:null,[q,d]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(V=>{let de=J===V,ae=le===V,ue=le!==null&&le!==V||J!=null&&J!==V;return xe(Fl.Fragment,{children:[u(Kl,{method:V,themeId:ye,submitting:ae,disabled:ue,highlighted:de,hasNextStep:Oi(V),onClick:()=>tt(V),backgroundColor:v?.backgroundColor,borderColor:v?.borderColor,textColor:v?.textColor,borderRadius:v?.borderRadius,fontFamily:v?.fontFamily}),!j&&q===V&&Me&&m&&u(pr,{stripe:m,options:Me,children:u(fa,{method:V,sessionId:e,email:n,billingName:r,billingApiUrl:o,onTokenizedBody:T,onErrorChange:h,onDecline:b,onCancel:()=>B(null),runBeforeButtonClick:x,onButtonClick:P,isProcessing:p,submitButtonColor:S,submitButtonBorderRadius:ee,submitButtonStyle:W})},V)]},V)})})}function Vl({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:m,onDecline:d,onTokenizedBody:T,firstName:h,lastName:P,chv:b,className:x,isProcessing:U,error:p,onErrorChange:S,showPayPal:ee=!0,showStripe:W=!0,enabledPaymentMethods:v,enabledPaymentMethodCountries:ye,showApplePay:j=!0,showGooglePay:J=!0,layout:ce="default",theme:Se,buttonsTheme:re,buttonsStyles:le,appearance:Ve,cardButtonContent:Ae,cardBackButtonContent:Ce,cardTitleContent:q,showSecurityFooter:B,onButtonClick:te,onBeforeButtonClick:tt,enableAVS:Me,cardFieldOrder:V,cardPreFormSlot:de,avsLayout:ae="row",country:ue,zip:ke,addressLine1:pe,addressLine2:Re,city:O,state:w,onCountryChange:oe,onZipChange:qe,avsCheck:De,checkoutType:Z,checkoutLayout:R,totalAmount:H=0,currency:$="usd",initialCardOpen:Be=!1,directPaypal:Ie,isSubscription:We=!1,session:Y,dataAttachmentPending:mt=!1,debug:D=!1}){let Le=Xn(),Pt=na(),N=_r(kn),{emitInstrument:bt}=_r(Pn),ze=mt||N.claimPending===!0,tn=Pi(),[It,k]=ge(!1),[se,yt]=ge(null),[Fe,Vt]=ge(ue??"US"),[Xt,Ge]=ge(ke??""),[vt,Je]=ge(pe??""),[Lt,je]=ge(Re??""),[Ht,Et]=ge(O??""),[nn,Nt]=ge(w??""),[En,sn]=ge({}),rt=Ee(ke??""),zt=Ee(ue??"US"),Ke=Ee(pe??""),Rn=Ee(Re??""),ct=Ee(O??""),vn=Ee(w??""),Ut=Ee({});lt(()=>{let i=(_,z,Q,L,fe)=>{if(Ut.current[_])return;let we=z?.trim();!we||we===Q.current||(Q.current=we,L(we),fe?.(we))};i("country",ue,zt,Vt,oe),i("zip",ke,rt,Ge,qe),i("addressLine1",pe,Ke,Je),i("addressLine2",Re,Rn,je),i("city",O,ct,Et),i("state",w,vn,Nt)},[ue,ke,pe,Re,O,w,oe,qe]);let ne=st(()=>Tl(Me),[Me]),Vn=ne!==null,_n=st(()=>ua(Y),[Y]),Tn=!!Y?.vault?.html,xn=!!Y?.gateways?.pcivault,I=!!(Y?.gateways?.stripe?.enabledPaymentMethods??v)?.includes("card"),Xe=Tn||I||xn,Pe=!!(W&&Xe&&Le&&e),[Cn,Oe]=ge(()=>ce!=="buttons"||Be?e??null:null),[Hn,nr]=ge(0),Yt=ce!=="buttons"||Be||!!e&&Cn===e,dt=st(()=>!Le||!Pe||!e||!Yt?null:Le.cardCapture({sessionId:e,captureMethod:Y?.captureMethod}),[Le,Pe,e,Yt,Y?.captureMethod]),Zt=st(()=>{let i=Fe,_=ne?Te(ne.postal_code,i):!1;return ql(i,Xt,_)},[ne,Fe,Xt]),{avsInvalid:Gt,invalidAvsFields:ot}=st(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Pe||!ne)return{avsInvalid:!1,invalidAvsFields:i};let _=Fe,z=(fe,we)=>Te(fe,_)&&!we.trim(),Q={line1:z(ne.address_line_1,vt),city:z(ne.city,Ht),state:z(ne.state,nn),zip:Zt.empty||Zt.malformed};return{avsInvalid:Q.line1||Q.city||Q.state||Q.zip,invalidAvsFields:Q}},[Pe,ne,Fe,vt,Ht,nn,Zt]),[ln,cn]=ge(!1),[Yn,Sn]=ge(!1),[rn,dn]=ge(()=>pa(Y?.vault)),[me,Ct]=ge(Be&&Xe?"card":"buttons"),[at,on]=ge(null),un=me==="expanding"||me==="card",Ln=Y?.gateways?.stripe?"stripe":void 0,pn=he(()=>{bt?.({class:"card_surface",provider:Ln})},[Ln,bt]),$t=280,Wt=Ee(null),Jt=he(i=>{Wt.current&&clearTimeout(Wt.current),Wt.current=setTimeout(()=>{Wt.current=null,i()},$t)},[$t]);lt(()=>()=>{Wt.current&&clearTimeout(Wt.current)},[]);let Gn=he(()=>{pn(),Oe(e??null),nr(i=>i+1),Ct("expanding"),Jt(()=>Ct("card"))},[Jt,pn,e]),On=he(()=>{Ct("collapsing"),Jt(()=>Ct("buttons"))},[Jt]),An=he(i=>{on(i),Ct("apm-expanding"),Jt(()=>Ct("apm-form"))},[Jt]),Nn=he(()=>{Ct("apm-collapsing"),Jt(()=>{Ct("buttons"),on(null)})},[Jt]);lt(()=>{ce==="buttons"&&Be&&Xe&&(Oe(e??null),Ct("card"))},[ce,Be,Xe,e]);let[qt,Ze]=ge(null),mn=Ee(!1),jt=Ee(null),ut=Ee("idle"),[Qt,Rt]=ge(null),rr=Ee(Qt);lt(()=>{rr.current=Qt},[Qt]);let pt=n||tn,l=p??se,s=st(()=>Ml(Se),[Se]),c=st(()=>{let i=s?.buttonsLayout??xl(re);return le?{...i,...le,cardButton:{...i.cardButton,...le.cardButton},cardFormContainer:{...i.cardFormContainer,...le.cardFormContainer},backButton:{...i.backButton,...le.backButton},backButtonIcon:{...i.backButtonIcon,...le.backButtonIcon},submitButton:{...i.submitButton,...le.submitButton},title:{...i.title,...le.title}}:i},[s,re,le]),A=Ve??s?.appearance,K=st(()=>ci({appearance:A,buttonsStyles:c,layout:ce}),[A,c,ce]),F=N.inlineSessionPatchProcessing??!1,C=(U??It)||F,f=pt.replace(/\/+$/,""),y=st(()=>ta({userId:o,email:r,firstName:h,lastName:P,country:ue,zip:ke},En),[o,r,h,P,ue,ke,En]),g=[y.firstName,y.lastName].filter(i=>!!i?.trim()).join(" "),E=st(()=>Le?Le.getRawProvider():null,[Le]),G=st(()=>Pt?Pt.getRawProvider():null,[Pt]),ie=H||100,_e=st(()=>A?hl(A):null,[A]),Ue=_e?{appearance:_e}:null,Tt=st(()=>{let i=_e??{},_=i.rules??{};return{...i,rules:{..._,".AccordionItem":{padding:"10px 14px",boxShadow:"none",..._[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",..._[".AccordionItemContents"]??{}}}}},[_e]),be=st(()=>{let i=gi(H);return{...i,currency:$.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...Ue}},[H,$,Ue]),ve=st(()=>({mode:"payment",amount:ie,currency:$.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Ue}),[ie,$,Ue]),M=he(i=>{yt(i),S?.(i)},[S]);lt(()=>{!Pe||!dt||dt.setCardFieldOrder?.(V??null,ne==null)},[Pe,dt,V,ne]),lt(()=>{(me==="expanding"||me==="collapsing"||me==="apm-expanding"||me==="apm-collapsing")&&M(null)},[me,M]);let St=he((i,_,z)=>{d?.(Mt(i,_,z))},[d]),$e=he((i,_,z)=>{let Q=z?.popupBlocked??Jn(_),L=Ul(i,Q),fe=cr(z?.code)??Un(_)??"external_payment_method_failed",we=new In(L,"api_error",{code:"external_payment_method_failed",param:i});Ze(null),ce==="buttons"&&(Ct("buttons"),on(null)),M(L),m?.(we),console.error("[FloPay] External payment method failed:",{method:i,code:fe,popupBlocked:Q})},[ce,m,M]);lt(()=>{if(!Pe||!e){dn(null);return}let i=pa(Y?.vault);if(i){dn(i);return}if(!Yt){dn(null);return}dn(null);let _=!0;return new eo(f).getVaultCapture(e,t).then(z=>{if(!_)return;let Q=pa(z);Q?dn(Q):M("Failed to load the secure card form.")}).catch(z=>{_&&M(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{_=!1}},[Pe,Yt,Hn,e,Y?.vault?.html,Y?.vault?.messageToken,Y?.vault?.expectedOrigin,f,t,M]);let nt=Ee({onComplete:a,onError:m,updateError:M,emitDecline:St,resolvedAccount:y,avsConfig:ne,avsCheckProp:De,sessionId:e,nonce:t,baseUrl:f,captureMethod:Y?.captureMethod,paymentId:Y?.paymentId,authorizationExpiresAt:Y?.authorizationExpiresAt});nt.current={onComplete:a,onError:m,updateError:M,emitDecline:St,resolvedAccount:y,avsConfig:ne,avsCheckProp:De,sessionId:e,nonce:t,baseUrl:f,captureMethod:Y?.captureMethod,paymentId:Y?.paymentId,authorizationExpiresAt:Y?.authorizationExpiresAt};let or=Ee(!1),Da=he(()=>{let{resolvedAccount:i,avsConfig:_,avsCheckProp:z}=nt.current,Q=zt.current||i.country||"US",L=_?Te(_.state,Q):!1,fe=_?Te(_.address_line_1,Q):!1,we=_?Te(_.postal_code,Q):!1,ft=_?Te(_.city,Q):!1,Kt=_?Te(_.address_line_2,Q):!1,gt=fe&&!L&&we?Di(Q,(rt.current??"").trim()):null,it=L?vn.current:gt;return{accountData:{userId:i.userId??"",email:i.email??"",firstName:i.firstName??"",lastName:i.lastName??"",...we&&rt.current?{zip:rt.current}:{},...ft&&ct.current?{city:ct.current}:{},...it?{state:it}:{},...fe&&Ke.current?{addressLine1:Ke.current}:{},...Kt&&Rn.current?{addressLine2:Rn.current}:{},country:Q},...z!==void 0?{avsCheck:z}:{},..._?{avsConfig:{country:Te(_.country,Q),postal_code:we,address_line_1:fe,address_line_2:Kt,city:ft,state:L}}:{}}},[]),io=Ee(ze);io.current=ze,lt(()=>{ze||l!==Ui||nt.current.updateError(null)},[ze,l]),lt(()=>{!Pe||!dt||dt.setSubmitGate?.(Gt||ze)},[Pe,dt,Gt,ze]),lt(()=>{if(!Pe||!dt)return;or.current=!1;let i=!1,_=dt.on("submitting",()=>{cn(!0),jt.current&&clearTimeout(jt.current),ut.current="validation-window",jt.current=setTimeout(()=>{jt.current=null,ut.current==="validation-window"&&(ut.current="processing")},Dl),Ze("processing");let{baseUrl:we,sessionId:ft,nonce:Kt,updateError:gt,onError:it}=nt.current;!ft||!Kt||new eo(we).patchAccountSnapshot(ft,Kt,Da(),{telemetryMode:"best_effort"}).catch(Ne=>{if(!Ll(Ne))return;let zn=Ne instanceof Error?Ne.message:"Please check your billing address and try again.";gt(zn),ut.current="idle",Ze(null),it?.(Ne instanceof In?Ne:new In(zn,"api_error"))})}),z=dt.on("complete",async we=>{if(kr(we.sessionId??nt.current.sessionId),ut.current="terminal",Ze("success"),await new Promise(gt=>setTimeout(gt,1200)),or.current)return;or.current=!0;let ft=nt.current,Kt=ua(ft)||we.outcome==="authorized";nt.current.onComplete?.(Kt?{status:"authorized",paymentIntentId:we.intentId,paymentId:we.paymentId??ft.paymentId,sessionId:we.sessionId??ft.sessionId,authorizationExpiresAt:we.authorizationExpiresAt??ft.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:we.intentId,checkoutMethod:"card"})}),Q=dt.on("decline",async we=>{let{updateError:ft,emitDecline:Kt}=nt.current,gt=we.message??"Your payment was declined. Please try another card or contact your bank.";ut.current="terminal",ft(gt),Ze("error");let it=we.failureOutcome??Rl(we.declineReason)??"authorization_declined";Kt("card",gt,{code:it,declineCode:it}),await new Promise(Ne=>setTimeout(Ne,1500)),!i&&(ut.current="idle",Ze(null))}),L=dt.on("error",async we=>{let{updateError:ft,onError:Kt}=nt.current,gt=we.message??"There was a problem processing your payment. Please try again.";ut.current="terminal",ft(gt),Ze("error"),Kt?.(new In(gt,"api_error",{code:we.failureOutcome??"capture_failed"})),await new Promise(it=>setTimeout(it,1500)),!i&&(ut.current="idle",Ze(null))}),fe=dt.on("blocked",()=>{if(!io.current){cn(!0);return}nt.current.updateError(Ui)});return()=>{i=!0,jt.current&&(clearTimeout(jt.current),jt.current=null),ut.current="idle",_(),z(),Q(),L(),fe()}},[Pe,dt]);let an=!!Ie?.clientId,Fr=Array.isArray(v),so=Fr&&v.length>0,ds=Fr&&v.includes("paypal"),{expressMethods:lo,paymentElementMethods:Dr}=st(()=>_l(v,{excludePaypal:an}),[v,an]),La=an||!!Pt,us=st(()=>La?lo.filter(i=>i!=="paypal"):lo,[lo,La]),ps=st(()=>{let i=[];return j&&i.push("apple_pay"),J&&i.push("google_pay"),i},[j,J]),co=Fr?us:ps,ms=W&&co.length>0,$o=Vn?Fe:ue,uo=st(()=>{let i=$o?.trim().toUpperCase();return i?ye?Dr.filter(_=>{let z=ye[_];return!z||z.length===0||z.includes(i)}):vl(Dr,$o):Dr},[Dr,$o,ye]),qo=st(()=>({mode:"payment",amount:ie,currency:$.toLowerCase(),paymentMethodCreation:"manual",appearance:Tt}),[ie,$,Tt]),[Oa,Na]=ge("loading"),[za,Ua]=ge("loading"),[$a,qa]=ge("loading"),[ys,jo]=ge(!1),[ja,Ko]=ge("loading"),[po,fs]=ge();lt(()=>{fs(Bi())},[]);let Ka=ee&&(an||(Fr?ds:po===!1)),Va=W&&ms,Lr=!ze&&Ka&&an,Ha=ja==="retrying"||ja==="exhausted",Or=!ze&&Ka&&!!G&&(!an||Ha),Nr=!ze&&Va&&!!E,zr=!ze&&W&&so&&uo.length>0&&!!E,gs=Lr&&!Ha?ys:Or&&ji(Oa),hs=Nr&&ji(za),Ps=zr&&$a!=="load_error",Ya=i=>i==="loading"||i==="ready",Ga=Lr||Or&&Ya(Oa)||Nr&&Ya(za)||zr&&$a!=="load_error",mo=Ee(!1);lt(()=>{if(!mo.current){if(!W&&!ee){mo.current=!0;let i=new In("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");m?.(i),M(i.message)}else if(!W&&ee&&!an&&!G){mo.current=!0;let i=new In("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");m?.(i),M(i.message)}else if(po!==void 0&&!ze&&!Xe&&!Ga){mo.current=!0;let i=new In("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"});m?.(i),M(i.message)}}},[W,ee,an,G,po,ze,Xe,Ga,m,M]);let Wa=Ee(!1);lt(()=>{if(Wa.current||!so)return;let i=[];j!==!0&&i.push("showApplePay"),J!==!0&&i.push("showGooglePay"),i.length!==0&&(Wa.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[so,j,J]);let Ja=he((i,_)=>N.applyInlineSessionPatch?N.applyInlineSessionPatch(i).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let Q=qi(_,z);return M(Q.message),m?.(Q),{error:Q,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[N.applyInlineSessionPatch,t,m,e,M]),wn=he(async i=>{if(!tt)return{proceed:!0};try{let _=await tt({method:i,sessionId:e||void 0,createSession:N.inlineSessionDraft});if(_===!1)return{proceed:!1};if(_&&typeof _=="object"){_.account&&sn(Q=>({...Q??{},..._.account}));let z=await Ja(_,i);return z.error?{proceed:!1,accountPatch:_.account}:{proceed:!0,accountPatch:_.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(_){let z=qi(i,_);return M(z.message),m?.(z),{proceed:!1}}},[Ja,N.inlineSessionDraft,tt,m,e,M]),Xa=he(async(i,_)=>{if(mn.current)return;mn.current=!0,k(!0),Ze("processing"),M(null);let z=_?.sessionId??e,Q=_?.nonce??t,L=ta(y,_?.accountPatch),fe=_?.completionPaymentMethodId??Gr(i),we=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,ft=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Kt=()=>{bt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ft})};try{let it=await new eo(f).processPayment(L.userId??"",{sessionId:z,nonce:Q,tokenizedData:we,accountData:{userId:L.userId??"",email:L.email??"",firstName:L.firstName??"",lastName:L.lastName??"",...ne?(()=>{let He=zt.current,fn=Te(ne.state,He),gn=Te(ne.address_line_1,He),Ot=Te(ne.postal_code,He),Kr=gn&&!fn&&Ot?Di(He,(rt.current??"").trim()):null,Vr=fn?vn.current:Kr;return{country:He,...Ot&&rt.current?{zip:rt.current}:{},...Te(ne.city,He)&&ct.current?{city:ct.current}:{},...Vr?{state:Vr}:{},...gn&&Ke.current?{addressLine1:Ke.current}:{},...Te(ne.address_line_2,He)&&Rn.current?{addressLine2:Rn.current}:{}}})():{}},chv:b,avsCheck:De??!1,checkoutType:Z,checkoutLayout:R,avsConfig:ne?{country:Te(ne.country,zt.current),postal_code:Te(ne.postal_code,zt.current),address_line_1:Te(ne.address_line_1,zt.current),address_line_2:Te(ne.address_line_2,zt.current),city:Te(ne.city,zt.current),state:Te(ne.state,zt.current)}:void 0});if(it.ok){let He=it.status===204?null:await it.json().catch(()=>null),fn=ua(Y)||He?.status==="authorized";kr(z),Ze("success"),Rt(null),await new Promise(gn=>setTimeout(gn,1200)),a?.(fn?{status:"authorized",...typeof He?.paymentId=="string"?{paymentId:He.paymentId}:Y?.paymentId?{paymentId:Y.paymentId}:{},sessionId:typeof He?.sessionId=="string"?He.sessionId:z,...typeof He?.authorizationExpiresAt=="string"?{authorizationExpiresAt:He.authorizationExpiresAt}:Y?.authorizationExpiresAt?{authorizationExpiresAt:Y.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Ne=await it.json().catch(()=>null);if(Ne?.type==="paypal_redirect_required"){let He=Ne.threeDSecureToken,fn=Ne.paymentMethodId||i.id||"";if(!Le||!He){Ze("error"),M("PayPal authorization required but no token provided.");return}try{let gn=Pt?.getRawProvider();if(!gn){M("PayPal is not available.");return}let Ot={return_url:window.location.href};fn&&(Ot.payment_method=fn);let{error:Kr}=await gn.confirmPayment({clientSecret:He,confirmParams:Ot,redirect:"if_required"});if(Kr){Ze("error");let Vr=Kr.message??"PayPal payment failed.";M(Vr),St("paypal",Vr,{code:Kr.code})}}catch(gn){Ze("error"),M(gn instanceof Error?gn.message:"PayPal authorization failed.")}return}if(Ne?.type==="paypal_direct_required"){let He=Ne.orderId;if(!He){Ze("error"),M("PayPal retry required but no order id provided.");return}let fn=rr.current?.attempts??0;if(fn>=2){Ze("error"),M("PayPal payment could not be completed after multiple attempts."),St("paypal","paypal_direct_required retry limit exceeded");return}jo(!1),Ko("loading"),Rt({orderId:He,attempts:fn+1}),Ze(null);return}bl(it.status,Ne)||Kt(),Ze("error");let zn=Ne?.message??"Payment failed. Please try again.";M(zn),St(i.isPaypal?"paypal":"card",zn,{code:Ne?.code??Ne?.gatewayErrorCode,declineCode:Ne?.declineCode??Ne?.gatewayDeclineReason}),await new Promise(He=>setTimeout(He,1500))}catch(gt){Gi(gt)||Kt(),Ze("error"),M(gt instanceof Error?gt.message:"An unexpected error occurred"),await new Promise(it=>setTimeout(it,1500))}finally{k(!1),Ze(null),mn.current=!1}},[f,e,t,y,g,b,Le,Pt,Y,a,m,M,St,bt]),yn=he((i,_)=>{T?T(i):Xa(i,_)},[T,Xa]),Za=Ee(!1);lt(()=>{if(typeof window>"u"||Za.current)return;let i=new URLSearchParams(window.location.search),_=i.get("payment_intent"),z=i.get("payment_intent_client_secret"),Q=i.get("redirect_status");if(!_||!z)return;let L=it=>{let Ne=localStorage.getItem(it);if(!Ne)return null;try{return JSON.parse(Ne)}catch{return localStorage.removeItem(it),null}},fe=L(Bn)??L(zi),we;if(fe?.clientSecret){if(fe.clientSecret!==z)return;we={...fe.accountPatch?{accountPatch:fe.accountPatch}:{},...fe.sessionId?{sessionId:fe.sessionId}:{},...fe.nonce?{nonce:fe.nonce}:{}}}else if(fe?.sessionId&&fe.sessionId!==e)return;Za.current=!0,localStorage.removeItem(Bn),localStorage.removeItem(zi);let ft=new URL(window.location.href);ft.searchParams.delete("payment_intent"),ft.searchParams.delete("payment_intent_client_secret"),ft.searchParams.delete("redirect_status"),window.history.replaceState({},"",ft.toString());let Kt=fe?.paymentMethodType??fe?.tokenType??"card",gt="card";(async()=>{let it=Le?.getRawProvider();if(!it){let Ot="Payment is not available \u2014 please refresh and try again.";M(Ot),St(gt,Ot);return}if(Q==="failed"){let Ot="Payment was declined. Please try again.";M(Ot),St(gt,Ot);return}let{paymentIntent:Ne,error:zn}=await it.retrievePaymentIntent(z);if(zn){let Ot=zn.message??"Failed to retrieve payment status.";M(Ot),St(gt,Ot,{code:zn.code});return}let He=Ne?.status,fn=vo(He);if(!Ne||!fn){let Ot=He==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";M(Ot),St(gt,Ot,{code:He??"missing_payment_intent"});return}let gn=typeof Ne.payment_method=="string"?Ne.payment_method:Ne.payment_method?.id;yn({id:gn??fe?.paymentMethodId??fe?.tokenId??Ne.id,type:"card",threeDSecureActionResultTokenId:Ne.id,gateway:fe?.gateway??"stripe",paymentMethodType:Kt},we)})()},[e,yn,Le,M,St]);let Vo=he(i=>{i.preventDefault()},[]);if(!(Le!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ur=ce==="buttons",en=A?.variables,bs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ho=en?.colorBackground,vs=Ho&&!bs.has(Ho)?Ho:void 0,$r=c.cardInputBorder??(Ur?"#e5e7eb":"#A4A4FF"),Yo=en?.colorDanger??"#dc2626",ar=i=>ln&&i?Yo:$r,yo=(Zt.malformed||Zt.empty)&&(Yn||ln),Cs=yo?Yo:ar(ot.zip),Go=c.cardFormContainer?.backgroundColor??vs??(Ur?"white":"#EDEDFF"),qr=c.cardInputBackground??en?.colorBackground??"white",Wo=fr(Ce),Qa=fr(q),yr=c.nameInput,ei=c.cardInputFontSize??jl(yr?.fontSize)??en?.fontSizeBase??"16px",ti=typeof yr?.fontFamily=="string"?yr.fontFamily:en?.fontFamily??"Poppins, sans-serif",ni=li(yr?.fontWeight)??400,Ss=c.cardInputColor??(typeof yr?.color=="string"?yr.color:void 0)??en?.colorText??"#262833",ws=c.cardInputPlaceholderColor??"#9ca3af",wt=en?.borderRadius??"8px",ir=en?.borderRadius??c.cardButton?.borderRadius??wt,sr=en?.colorPrimary??"#4A49FF",ks=en?.colorPrimaryHover??Hr(sr,.12),Jo=en?.colorText??"#262833",ri={fontSize:ei,fontFamily:ti,fontWeight:ni,color:Ss,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Is={"--flopay-input-placeholder-color":ws,"--flopay-input-font-size":ei,"--flopay-input-font-family":ti,"--flopay-input-font-weight":String(ni)},jr=c.cardFormContainer??{},Xo=jr.padding??(Ur?"0":"1rem"),Zo=jr.borderRadius??wt,Es=dt&&rn?u(Qo,{capture:dt,html:rn.html,messageToken:rn.messageToken,expectedOrigin:rn.expectedOrigin,theme:K,onReady:()=>{if(!ne||typeof document>"u")return;let i=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};i();let _=0,z=window.setInterval(()=>{_+=1;let Q=document.activeElement;!!Q&&Q.tagName==="IFRAME"&&Q.id==="flopay_vault_form_iframe"?(i(),window.clearInterval(z)):_>=50&&window.clearInterval(z)},100)},onError:i=>M(i),onValidation:i=>{let _=ut.current;(_==="idle"||_==="validation-window")&&(M(i),i&&ut.current==="validation-window"&&(jt.current&&(clearTimeout(jt.current),jt.current=null),ut.current="idle",Ze(null)))}}):u("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),oi=xe("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&pn()},style:{backgroundColor:Go,borderRadius:Zo,...jr,padding:Xo,...Is,display:"flex",flexDirection:"column"},children:[u("style",{children:`
25
+ `,ra=44;function Ha(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 Sc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},_s={width:"100%",minHeight:ra,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 wc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function vs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function qa(e){return e==="paypal"?"PayPal":xr(e)}function kc(e,t){let n=`We couldn't open ${qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function xs(e){let t=Ie(0),n=Ie(null),r=Ie(null),o=Pe((u=r.current)=>{let w=u;w?.timer&&(clearTimeout(w.timer),w.timer=null)},[]),a=Pe((u,w)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(u),u.timer=setTimeout(()=>{u.timer=null,r.current?.generation===u.generation&&(r.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},w))},[o,e]),c=Pe(u=>{u.yieldedControl&&a(u,600)},[a]),s=Pe(u=>{o();let w=t.current+1;t.current=w,n.current=null;let ve={generation:w,method:u,timer:null,yieldedControl:!1};return r.current=ve,w},[o]),S=Pe(u=>{let w=r.current;return typeof u=="number"&&w?.generation!==u?!1:(o(w),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),b=Pe(u=>{let w=r.current,ve=u??w?.generation??t.current;(!u||w?.generation===u)&&(o(w),r.current=null),n.current=ve},[o]),g=Pe(u=>n.current===(u??t.current),[]),m=Pe(u=>r.current?.generation===u&&n.current!==u,[]),M=Pe(()=>{let u=r.current;u&&c(u)},[c]),D=Pe(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return ht(()=>{let u=()=>{document.visibilityState==="visible"?M():D()},w=()=>{D()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",w),window.addEventListener("focus",M),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",w),window.removeEventListener("focus",M),o()}},[o,D,M]),{startAttempt:s,finishAttempt:S,invalidateAttempt:b,isAttemptInvalidated:g,isAttemptCurrent:m}}function Ic(e){let t=oc(e);return`Enter a valid ${Ua(e)}${t?` (e.g. ${t})`:""}`}function Ec(e,t,n){let r=sc(e),o=t.trim(),a=n&&r,c=a&&!o,s=a&&!!o&&!cc(e,o);return{visible:n,supported:r,required:a,empty:c,malformed:s}}function Rc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!en(n);return{required:t,empty:r,malformed:o,value:n}}function Ps(e,t){return t instanceof On?t:new On(t instanceof Error?t.message:`${wc(e)} before-click hook failed.`,"validation_error")}function za(){return l("style",{children:Cc})}function _c(e){return typeof e=="number"?`${e}px`:e}function Ts(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function As({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:ke("div",{style:{position:"relative",minHeight:44},children:[l("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"}}),l("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 Cs(e){return e!=="unavailable"&&e!=="load_error"}function Ya(e){return l(Tc,{...e})}function Ss({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:S,onTechnicalFailure:b,runBeforeButtonClick:g,billingName:m,onBuyerIdentityReady:M,onLoadStateChange:D,placeholderBorderRadius:u}){let w=ur(),{emitInstrument:ve}=Yr(In),H=Ka(),P=ja(),[fe,Q]=ye("loading");ht(()=>{D?.(fe)},[fe,D]);let[ce,oe]=ye(!1),Ce=!en(n?.trim())||!m?.trim(),{request:He,collect:be,finish:Rt}=qr(),De=Ie(!1),Te=Ie(null),Ae=Ie(null),[ee,J]=ye(0),[L,me]=ye(!1),et=Ie(!1),Ue=Ie(new Map),{startAttempt:Ye,finishAttempt:te,invalidateAttempt:T,isAttemptInvalidated:ae,isAttemptCurrent:Fe}=xs((G,Y,$)=>{b?.(G,Y,{...$,popupBlocked:$?.popupBlocked??dr(Y)}),me(!0),J(we=>we+1)});ht(()=>{L&&Ae.current?.focus()},[L,ee]);let ie=Pe(()=>{J(G=>G+1)},[]),j=Pe((G,Y,$)=>{T($),b?.("paypal",G,{code:Y,popupBlocked:dr(G)}),me(!0),ie()},[T,b,ie]),_e=Pe(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);ht(()=>{et.current&&(et.current=!1,_e())},[_e,ee]);let Je=Pe(()=>{me(!1),a?.(null),_e()},[_e,a]);ht(()=>{if(!H||De.current)return;let G=new URLSearchParams(window.location.search),Y=G.get("payment_intent"),$=G.get("payment_intent_client_secret"),we=G.get("redirect_status");if(!Y||!$)return;De.current=!0;let Me;try{let K=localStorage.getItem(Co);if(K){let I=JSON.parse(K);I.clientSecret===$&&(Me={...I.accountPatch?{accountPatch:I.accountPatch}:{},...I.sessionId?{sessionId:I.sessionId}:{},...I.nonce?{nonce:I.nonce}:{}})}}catch{}try{localStorage.removeItem(Co)}catch{}let x=new URL(window.location.href);x.searchParams.delete("payment_intent"),x.searchParams.delete("payment_intent_client_secret"),x.searchParams.delete("redirect_status"),window.history.replaceState({},"",x.toString()),(async()=>{try{if(oe(!0),we==="failed"){let C="PayPal payment was declined. Please try again.";a?.(C),S?.($t("paypal",C));return}let{paymentIntent:K,error:I}=await H.retrievePaymentIntent($);if(I){a?.(I.message??"Failed to retrieve PayPal payment status.");return}if(K&&(K.status==="requires_capture"||K.status==="succeeded")){let C=typeof K.payment_method=="string"?K.payment_method:K.payment_method?.id;o({id:C??K.id,type:"card",threeDSecureActionResultTokenId:K.id,isPaypal:!0},Me)}else{let C="PayPal payment was not completed. Please try again.";a?.(C),S?.($t("paypal",C))}}catch(K){a?.(K instanceof Error?K.message:"Failed to complete PayPal payment.")}finally{oe(!1)}})()},[H,o,a,S]);let We=Pe(async G=>{if(c||ce){G.reject();return}let Y=g?await g("paypal"):{proceed:!0};if(!Y.proceed){Ue.current.delete(ee),G.reject();return}let $=Ye("paypal");Ue.current.set(ee,{generation:$,accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}),me(!1),s?.("paypal"),G.resolve()},[Ue,c,s,g,Ye,ce,ee]),Se=Pe(async G=>{if(!H||!P)return;let Y=Ue.current.get(ee);if(Y&&!Fe(Y.generation)){Ue.current.delete(ee);return}if(!Y&&ae()||Y&&!te(Y.generation))return;Y||te();let $=Y??null;if(Ue.current.delete(ee),!$&&g){let C=await g("paypal");if(!C.proceed){G.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:C.accountPatch,sessionId:C.sessionId,nonce:C.nonce}}let we=$?.sessionId??e,Me=$?.nonce??t,x=await Rs({event:G,prepared:$,email:n,billingName:m,methodLabel:"PayPal",collect:be});if(!x){G.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let K=x.email,I={...$?.accountPatch,...x};try{if(oe(!0),a?.(null),!we||!en(K))throw new Error("Missing sessionId or email for PayPal payment");await M?.(x);let C=H.createPaymentMethod,{error:nt,paymentMethod:St}=await C({type:"paypal"});if(nt){j(nt,"stripe_paypal_create_payment_method_failed",Y?.generation),G.paymentFailed({reason:"fail"});return}let de=await oa(r,ve,we,Me??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:St?.id??null,intentKind:"payment"});if(de.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=de.clientSecret,it={return_url:window.location.href};if(St?.id&&(it.payment_method=St.id),typeof window<"u")try{localStorage.setItem(Co,JSON.stringify({clientSecret:ct,sessionId:we,nonce:Me,accountPatch:I}))}catch{}let{error:rt,paymentIntent:je}=await H.confirmPayment({clientSecret:ct,confirmParams:it,redirect:"if_required"});if(rt){if(typeof window<"u")try{localStorage.removeItem(Co)}catch{}if(go(rt)){let U=rt.message??"Your payment was declined.";a?.(U),S?.($t("paypal",U,{code:tr(rt),declineCode:$r(rt)})),await aa({billingApiUrl:r,sessionId:we,nonce:Me,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:tr(rt)??"provider_declined"}})}else j(rt,"stripe_paypal_confirm_failed",Y?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Co)}catch{}let y=typeof je?.payment_method=="string"?je.payment_method:je?.payment_method?.id;o({id:y??je?.id,type:"card",threeDSecureActionResultTokenId:je?.id,isPaypal:!0},{accountPatch:I,sessionId:we,nonce:Me});return}catch(C){j(C,"stripe_paypal_failed",Y?.generation)}finally{oe(!1)}},[H,P,e,t,n,m,be,M,r,ve,o,a,S,g,j,te,Fe,ae,ee]);return ke(fr,{children:[l(As,{state:fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:u,children:ke("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[L&&l("button",{ref:Ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Je,style:_s,children:"Try PayPal again"}),He&&l(Ir,{identity:He.identity,methodLabel:He.methodLabel,onComplete:Rt,onCancel:()=>Rt(null)},He.id),l("div",{style:{display:He?"none":void 0},children:l(Is,{onReady:G=>Q(Ts(G,["paypal"])),onLoadError:()=>{Q("load_error"),Va(jt(w),"paypal","paypal")},onClick:We,onConfirm:Se,onCancel:()=>{let G=Ue.current.get(ee);Ue.current.delete(ee),jt(w)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(G?.generation),me(!1),et.current=!0,ie()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Ce,emailRequired:Ce,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),ce&&l(Yn,{status:"processing"})]})}function ws({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:S,onDecline:b,onTechnicalFailure:g,runBeforeButtonClick:m,billingName:M,onBuyerIdentityReady:D,onLoadStateChange:u,placeholderBorderRadius:w}){let ve=ur(),{emitInstrument:H}=Yr(In),P=Ka(),fe=ja(),[Q,ce]=ye("loading");ht(()=>{u?.(Q)},[Q,u]);let[oe,Ce]=ye(!1),He=!en(n?.trim())||!M?.trim(),{request:be,collect:Rt,finish:De}=qr(),Te=Ie(null),Ae=Ie(null),[ee,J]=ye(0),[L,me]=ye(!1),[et,Ue]=ye("google_pay"),Ye=Ie(!1),te=Ie("google_pay"),T=Ie("google_pay"),ae=Ie(new Map),{startAttempt:Fe,finishAttempt:ie,invalidateAttempt:j,isAttemptInvalidated:_e,isAttemptCurrent:Je}=xs((x,K,I)=>{g?.(x,K,{...I,popupBlocked:I?.popupBlocked??dr(K)}),Ue(x),me(!0),J(C=>C+1)});ht(()=>{L&&Ae.current?.focus()},[L,ee]);let We=Pe(()=>{J(x=>x+1)},[]),Se=Pe((x,K,I,C)=>{j(C),g?.(x,K,{code:I,popupBlocked:dr(K)}),Ue(x),me(!0),We()},[j,g,We]),G=Pe(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);ht(()=>{Ye.current&&(Ye.current=!1,G())},[G,ee]);let Y=Pe(()=>{me(!1),s?.(null),G()},[G,s]),$=Pe(async x=>{if(!P||!fe)return;let K=ae.current.get(ee);if(K&&!Je(K.generation)){ae.current.delete(ee);return}if(!K&&_e()||K&&!ie(K.generation))return;K||ie();let I=x.expressPaymentType??K?.method??te.current,C=K??null;ae.current.delete(ee);let nt=vs(I);if(!C&&m){let y=await m(nt);if(!y.proceed){x.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}C={accountPatch:y.accountPatch,sessionId:y.sessionId,nonce:y.nonce}}let St=nt,de=C?.sessionId??e,ct=C?.nonce??t,it=await Rs({event:x,prepared:C,email:n,billingName:M,methodLabel:qa(I),collect:Rt});if(!it){x.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let rt=it.email,je={...C?.accountPatch,...it};try{if(Ce(!0),s?.(null),!en(rt))throw new Error("Missing sessionId or email for wallet payment");await D?.(it);let{error:y}=await fe.submit();if(y){Se(I,y,"stripe_wallet_submit_failed",K?.generation);return}let{error:U,paymentMethod:Xe}=await P.createPaymentMethod({elements:fe});if(U||!Xe){Se(I,U??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",K?.generation);return}if(!de)throw new Error("Missing sessionId or email for wallet payment");let dt=await oa(r,H,de,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I??nt,paymentMethodId:Xe.id,intentKind:o});if(dt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Mt=dt.clientSecret,{error:Bt,intentId:W}=lc(Mt)?await P.confirmCardSetup(Mt,{payment_method:Xe.id}).then(Le=>({error:Le.error,intentId:Le.setupIntent?.id})):await P.confirmCardPayment(Mt,{payment_method:Xe.id}).then(Le=>({error:Le.error,intentId:Le.paymentIntent?.id}));if(Bt){if(go(Bt)){let Le=Bt.message??"Your payment was declined.";s?.(Le),b?.($t(St,Le,{code:tr(Bt),declineCode:$r(Bt)})),await aa({billingApiUrl:r,sessionId:de,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I??nt,providerDeclineReason:tr(Bt)??"provider_declined"}})}else Se(I,Bt,"stripe_wallet_confirm_failed",K?.generation);return}c({id:Xe.id,type:"card",threeDSecureActionResultTokenId:W},{accountPatch:je,sessionId:de,nonce:ct})}catch(y){Se(I,y,"stripe_wallet_failed",K?.generation)}finally{Ce(!1)}},[P,fe,e,t,n,M,Rt,D,r,H,o,c,s,b,m,Se,ie,Je,_e,ee]),we=gt(()=>{let x=["applePay","googlePay","paypal","link","amazonPay","klarna"],K=new Set(["applePay","googlePay"]),I=new Set(a.map(gs)),C={};for(let nt of x)I.has(nt)?C[nt]=K.has(nt)?"always":"auto":C[nt]="never";return C},[a]),Me=gt(()=>a.map(gs),[a]);return ke(fr,{children:[l(As,{state:Q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:w,children:ke("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[L&&ke("button",{ref:Ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Y,style:_s,children:["Try ",qa(et)," again"]}),be&&l(Ir,{identity:be.identity,methodLabel:be.methodLabel,onComplete:De,onCancel:()=>De(null)},be.id),l("div",{style:{display:be?"none":void 0},children:l(Is,{onReady:x=>{ce(Ts(x,Me))},onLoadError:x=>{ce("load_error"),Va(jt(ve),"stripe","wallet")},onClick:async x=>{te.current=x.expressPaymentType,T.current=vs(x.expressPaymentType);let K=m?await m(T.current):{proceed:!0};if(!K.proceed){ae.current.delete(ee),x.reject();return}let I=Fe(x.expressPaymentType);ae.current.set(ee,{generation:I,method:x.expressPaymentType,accountPatch:K.accountPatch,sessionId:K.sessionId,nonce:K.nonce}),me(!1),S?.(T.current),x.resolve()},onConfirm:$,onCancel:()=>{let x=ae.current.get(ee);ae.current.delete(ee),jt(ve)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),j(x?.generation),me(!1),Ye.current=!0,We()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:we,emailRequired:He,billingAddressRequired:He,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),oe&&l(Yn,{status:"processing"})]})}function xc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:S,textColor:b,borderRadius:g,fontFamily:m}){let M=yc(e,t),D=ps[e],[u,w]=ye(!1),ve=M?.backgroundColor??s??"#ffffff",H=M?.borderColor??S??"#d1d5db",P=M?.textColor??b??"#262833";return l("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&c()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ra,padding:"0 1rem",backgroundColor:ve,color:P,border:`1px solid ${H}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:m,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?l("span",{style:{margin:"0 auto"},children:`Connecting to ${xr(e)}\u2026`}):ke(fr,{children:[ke("span",{style:{display:"inline-flex",alignItems:"center",gap:ic(e)?8:0},children:[D&&!u?l("img",{src:D,alt:"","aria-hidden":"true",onError:()=>w(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):M?.logoSvg?l("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:M.logoSvg}}):null,l("span",{children:xr(e)})]}),a&&l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:P,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:l("path",{d:"M9 18l6-6-6-6"})})]})})}function $a({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:c,onTokenizedBody:s,onErrorChange:S,onDecline:b,onCancel:g,runBeforeButtonClick:m,onButtonClick:M,isProcessing:D,submitButtonColor:u,submitButtonBorderRadius:w,submitButtonStyle:ve,errorText:H}){let P=ur(),{emitInstrument:fe}=Yr(In),Q=Ka(),ce=ja(),[oe,Ce]=ye(!1),He=Ie(!1),[be,Rt]=ye(!1),[De,Te]=ye("loading"),[Ae,ee]=ye(""),[J,L]=ye(""),me=!en(r?.trim()),et=!o?.trim(),Ue=(!me||en(Ae.trim()))&&(!et||!!J.trim()),Ye=Pe(async()=>{if(!Q||!ce||D||He.current||!be)return;He.current=!0,Ce(!0);let te=m?await m("card"):{proceed:!0};if(!te.proceed){He.current=!1,Ce(!1);return}M?.("card");let T=te.sessionId??t,ae=te.nonce??n,Fe=kn(o?.trim()||J.trim()),ie={email:te.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:te.accountPatch?.firstName?.trim()||Fe.firstName,lastName:te.accountPatch?.lastName?.trim()||Fe.lastName},j=ie.email,_e={...te.accountPatch,...ie};try{if(S?.(null),!en(j)||!fo(ie))throw new Error("A valid email address and full name are required for payment.");await a?.(ie);let Je=await ce.submit();if(Je.error){S?.(Je.error.message??"Payment failed.");return}let We=await Q.createPaymentMethod({elements:ce,params:{billing_details:{email:j,name:[ie.firstName,ie.lastName].filter(Boolean).join(" ")}}});if(We.error||!We.paymentMethod){S?.(We.error?.message??"Failed to create payment method.");return}let Se=We.paymentMethod;if(!T||!j)throw new Error("Missing sessionId or email for payment.");let G=Se.type||e,Y=await oa(c,fe,T,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:G,paymentMethodId:null,intentKind:"payment"});if(Y.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let $=Y.clientSecret;if(typeof window<"u")try{localStorage.setItem(Gn,JSON.stringify({clientSecret:$,sessionId:T,nonce:ae,accountPatch:_e,paymentMethodId:Se.id,paymentMethodType:Se.type??e,gateway:"stripe"}))}catch{}let{error:we,paymentIntent:Me}=await Q.confirmPayment({clientSecret:$,confirmParams:{return_url:window.location.href,payment_method:Se.id},redirect:"if_required"});if(we){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let I=we.message??"Payment failed.";S?.(I),b?.($t("card",I,{code:we.code})),await aa({billingApiUrl:c,sessionId:T,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:we.code??"provider_declined"}});return}let x=Me?.status;if(!jo(x)){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let I=x==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(I),b?.($t("card",I,{code:x??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let K=typeof Me?.payment_method=="string"?Me.payment_method:Me?.payment_method?.id;s({id:K??Se.id,type:"card",threeDSecureActionResultTokenId:Me?.id,gateway:"stripe",paymentMethodType:Se.type??e},{accountPatch:_e,sessionId:T,nonce:ae})}catch(Je){S?.(Je instanceof Error?Je.message:"Payment failed. Please try again.")}finally{He.current=!1,Ce(!1)}},[Q,ce,D,be,m,M,t,n,r,o,Ae,J,a,c,fe,e,s,S,b]);return ke("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(me||et)&&ke("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:[me&&ke("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",l("input",{type:"email",autoComplete:"email",required:!0,value:Ae,onChange:te=>ee(te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),et&&ke("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",l("input",{type:"text",autoComplete:"name",required:!0,value:J,onChange:te=>L(te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})]}),l(gc,{onReady:()=>Te("ready"),onLoadError:()=>{Te("load_error"),Va(jt(P),"stripe","apm")},onChange:te=>{Rt(!!te.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...en(r?.trim())?{email:r?.trim()}:{}}}}}),l("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ye()},disabled:!be||!Ue||oe||D||De!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:w,fontSize:"1rem",fontWeight:600,cursor:!be||!Ue||oe||D||De!=="ready"?"not-allowed":"pointer",opacity:!be||!Ue||oe||D||De!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ve??{}},children:oe?"Processing\u2026":`Pay with ${xr(e)}`}),H&&l(Kr,{margin:"0.75rem 0 0",children:H})]})}function ks({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:c,stripeInstance:s,paymentElementBaseOptions:S,onTokenizedBody:b,onErrorChange:g,onButtonClick:m,onDecline:M,runBeforeButtonClick:D,onLoadStateChange:u,isProcessing:w=!1,submitButtonColor:ve="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:P,buttonAppearance:fe,themeId:Q,onExpandApm:ce,expandedApmMethod:oe}){let{emitInstrument:Ce}=Yr(In),[He,be]=ye(null),[Rt,De]=ye(null),Te=Ie(!1),{request:Ae,collect:ee,finish:J}=qr();ht(()=>{c.length>0&&s?u?.("ready"):s||u?.("loading")},[c.length,s,u]);let L=Pe(async T=>{if(!s||Te.current||w)return;Te.current=!0,De(T);let ae=D?await D("card"):{proceed:!0};if(!ae.proceed){Te.current=!1,De(null);return}m?.("card");let Fe=ae.sessionId??e,ie=ae.nonce??t,j=kn([ae.accountPatch?.firstName,ae.accountPatch?.lastName].filter(Boolean).join(" ")||r),_e={email:ae.accountPatch?.email?.trim()||n?.trim(),firstName:ae.accountPatch?.firstName?.trim()||j.firstName,lastName:ae.accountPatch?.lastName?.trim()||j.lastName};if(!en(_e.email)||!fo(_e)){De(null);let Se=await ee(xr(T),_e);if(!Se){Te.current=!1;return}_e=Se,De(T)}let Je=_e.email,We={...ae.accountPatch,..._e};try{if(g?.(null),!Fe||!en(Je)||!fo(_e))throw new Error("Missing sessionId or email for payment.");await o?.(_e);let Se=await oa(a,Ce,Fe,ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(Se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let G=Se.clientSecret;if(typeof window<"u")try{localStorage.setItem(Gn,JSON.stringify({clientSecret:G,sessionId:Fe,nonce:ie,accountPatch:We,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:$}=await s.confirmPayment({clientSecret:G,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[_e.firstName,_e.lastName].filter(Boolean).join(" "),...Je?{email:Je}:{}}}},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let x=Y.message??"Payment failed.";g?.(x),M?.($t("card",x,{code:Y.code})),await aa({billingApiUrl:a,sessionId:Fe,nonce:ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:Y.code??"provider_declined"}});return}let we=$?.status;if(!jo(we)){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let x=we==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(x),M?.($t("card",x,{code:we??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let Me=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;b({id:Me??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:We,sessionId:Fe,nonce:ie})}catch(Se){g?.(Se instanceof Error?Se.message:"Payment failed. Please try again.")}finally{Te.current=!1,De(null)}},[s,w,D,m,e,t,n,ee,a,Ce,r,o,b,g,M]),[me,et]=ye(null),Ue=ce?oe??null:me,Ye=Pe(T=>{Te.current||w||Ue&&Ue!==T||(fs(T)?ce?ce(T):et(T):L(T))},[Ue,w,L,ce]),te=gt(()=>me?{...S,paymentMethodTypes:[me]}:null,[me,S]);return l("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ae?l(Ir,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:J,onCancel:()=>J(null)},Ae.id):c.map(T=>{let ae=oe===T,Fe=Rt===T,ie=Rt!==null&&Rt!==T||oe!=null&&oe!==T;return ke(hc.Fragment,{children:[l(xc,{method:T,themeId:Q,submitting:Fe,disabled:ie,highlighted:ae,hasNextStep:fs(T),onClick:()=>Ye(T),backgroundColor:fe?.backgroundColor,borderColor:fe?.borderColor,textColor:fe?.textColor,borderRadius:fe?.borderRadius,fontFamily:fe?.fontFamily}),!ce&&me===T&&te&&s&&l(_r,{stripe:s,options:te,children:l($a,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:b,onErrorChange:g,onDecline:M,onCancel:()=>et(null),runBeforeButtonClick:D,onButtonClick:m,isProcessing:w,submitButtonColor:ve,submitButtonBorderRadius:H,submitButtonStyle:P})},T)]},T)})})}function Tc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:c,onDecline:s,onTokenizedBody:S,firstName:b,lastName:g,chv:m,className:M,isProcessing:D,error:u,onErrorChange:w,showPayPal:ve=!0,showStripe:H=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:fe,showApplePay:Q=!0,showGooglePay:ce=!0,layout:oe="default",theme:Ce,buttonsTheme:He,buttonsStyles:be,appearance:Rt,cardButtonContent:De,cardBackButtonContent:Te,cardTitleContent:Ae,showSecurityFooter:ee,onButtonClick:J,onBeforeButtonClick:L,onBuyerIdentityReady:me,enableAVS:et,cardFieldOrder:Ue,cardPreFormSlot:Ye,avsLayout:te="row",country:T,zip:ae,addressLine1:Fe,addressLine2:ie,city:j,state:_e,onCountryChange:Je,onZipChange:We,avsCheck:Se,checkoutType:G,checkoutLayout:Y,totalAmount:$=0,currency:we="usd",initialCardOpen:Me=!1,directPaypal:x,isSubscription:K=!1,session:I,dataAttachmentPending:C=!1,dataAttachmentRequiresIdentity:nt=!1,debug:St=!1}){let de=ur(),ct=_a(),it=Yr(Ln),{emitInstrument:rt}=Yr(In),je=C||it.claimPending===!0,y=nt||it.claimRequiresIdentity===!0,U=je&&!y,Xe=Ji(),[dt,Mt]=ye(!1),[Bt,W]=ye(null),[Le,Wt]=ye(T??"US"),[wt,Ot]=ye(ae??""),[Rn,_n]=ye(Fe??""),[Zn,Jt]=ye(ie??""),[cn,dn]=ye(j??""),[Ft,vn]=ye(_e??""),[bt,ir]=ye(""),[Ht,sr]=ye(""),[Nt,zn]=ye({}),ot=Ie(ae??""),_t=Ie(T??"US"),xt=Ie(Fe??""),tn=Ie(ie??""),un=Ie(j??""),pn=Ie(_e??""),Un=Ie(""),qn=Ie(""),zt=Ie({});ht(()=>{let i=(R,N,he,z,Re)=>{if(zt.current[R])return;let Ne=N?.trim();!Ne||Ne===he.current||(he.current=Ne,z(Ne),Re?.(Ne))};i("country",T,_t,Wt,Je),i("zip",ae,ot,Ot,We),i("addressLine1",Fe,xt,_n),i("addressLine2",ie,tn,Jt),i("city",j,un,dn),i("state",_e,pn,vn)},[T,ae,Fe,ie,j,_e,Je,We]);let X=gt(()=>pc(et),[et]),Pn=X!==null,xn=gt(()=>La(I),[I]),Qn=!!I?.vault?.html,br=!!I?.gateways?.pcivault,Tn=!!(I?.gateways?.stripe?.enabledPaymentMethods??P)?.includes("card"),mn=Qn||Tn||br,Be=!!(H&&mn&&de&&e),[Xt,Dt]=ye(()=>oe!=="buttons"||Me?e??null:null),[$n,v]=ye(0),ut=oe!=="buttons"||Me||!!e&&Xt===e,qe=gt(()=>!de||!Be||!e||!ut?null:de.cardCapture({sessionId:e,captureMethod:I?.captureMethod}),[de,Be,e,ut,I?.captureMethod]),yn=gt(()=>{let i=Le,R=X?ze(X.postal_code,i):!1;return Ec(i,wt,R)},[X,Le,wt]),{avsInvalid:Ze,invalidAvsFields:Ut}=gt(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Be||!X)return{avsInvalid:!1,invalidAvsFields:i};let R=Le,N=(Re,Ne)=>ze(Re,R)&&!Ne.trim(),he={line1:N(X.address_line_1,Rn),city:N(X.city,cn),state:N(X.state,Ft),zip:yn.empty||yn.malformed};return{avsInvalid:he.line1||he.city||he.state||he.zip,invalidAvsFields:he}},[Be,X,Le,Rn,cn,Ft,yn]),[lr,jn]=ye(!1),[Cn,Zt]=ye(!1),[fn,gn]=ye(()=>Oa(I?.vault)),[xe,kt]=ye(Me&&mn?"card":"buttons"),[Tt,An]=ye(null),hn=xe==="expanding"||xe==="card",Mn=I?.gateways?.stripe?"stripe":void 0,Bn=Pe(()=>{rt?.({class:"card_surface",provider:Mn})},[Mn,rt]),qt=280,on=Ie(null),an=Pe(i=>{on.current&&clearTimeout(on.current),on.current=setTimeout(()=>{on.current=null,i()},qt)},[qt]);ht(()=>()=>{on.current&&clearTimeout(on.current)},[]);let er=Pe(()=>{Bn(),Dt(e??null),v(i=>i+1),kt("expanding"),an(()=>kt("card"))},[an,Bn,e]),Ar=Pe(()=>{kt("collapsing"),an(()=>kt("buttons"))},[an]),Fn=Pe(i=>{An(i),kt("apm-expanding"),an(()=>kt("apm-form"))},[an]),Kn=Pe(()=>{kt("apm-collapsing"),an(()=>{kt("buttons"),An(null)})},[an]);ht(()=>{oe==="buttons"&&Me&&mn&&(Dt(e??null),kt("card"))},[oe,Me,mn,e]);let[Qt,at]=ye(null),Yt=Ie(!1),_=Ie(null),E=Ie("idle"),[V,Z]=ye(null),$e=Ie(V);ht(()=>{$e.current=V},[V]);let ne=n||Xe,B=u??Bt,h=gt(()=>fc(Ce),[Ce]),f=gt(()=>{let i=h?.buttonsLayout??mc(He);return be?{...i,...be,cardButton:{...i.cardButton,...be.cardButton},cardFormContainer:{...i.cardFormContainer,...be.cardFormContainer},backButton:{...i.backButton,...be.backButton},backButtonIcon:{...i.backButtonIcon,...be.backButtonIcon},submitButton:{...i.submitButton,...be.submitButton},title:{...i.title,...be.title}}:i},[h,He,be]),O=Rt??h?.appearance,pt=gt(()=>zi({appearance:O,buttonsStyles:f,layout:oe}),[O,f,oe]),vt=it.inlineSessionPatchProcessing??!1,d=(D??dt)||vt,p=ne.replace(/\/+$/,""),k=gt(()=>Ia({userId:o,email:r,firstName:b,lastName:g,country:T,zip:ae},Nt),[o,r,b,g,T,ae,Nt]),Ee=[k.firstName,k.lastName].filter(i=>!!i?.trim()).join(" "),q=!en(k.email?.trim()),F=!Ee.trim(),Ge=Ie(null),Qe=Ie(null);Be&&(Ge.current===null&&(Ge.current=q),Qe.current===null&&(Qe.current=F));let se=Be&&(Ge.current??q),ue=Be&&(Qe.current??F),A=se||ue,le=gt(()=>Rc(bt,se),[bt,se]),st=le.empty||le.malformed,Lt=ue&&!Ht.trim(),ge=gt(()=>de?de.getRawProvider():null,[de]),bn=gt(()=>ct?ct.getRawProvider():null,[ct]),Qr=$||100,_o=gt(()=>O?ec(O):null,[O]),xo=_o?{appearance:_o}:null,li=gt(()=>{let i=_o??{},R=i.rules??{};return{...i,rules:{...R,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...R[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...R[".AccordionItemContents"]??{}}}}},[_o]),ci=gt(()=>{let i=Hi($);return{...i,currency:we.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...xo}},[$,we,xo]),di=gt(()=>({mode:"payment",amount:Qr,currency:we.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...xo}),[Qr,we,xo]),pe=Pe(i=>{W(i),w?.(i)},[w]),da=Ie(""),[ui,$s]=ye(!1),To=Pe(()=>{$s(!0)},[]);ht(()=>{if(!Be||!A||!me||!ui||st||Lt||da.current)return;let i=kn(qn.current),R={email:en(k.email?.trim())?k.email?.trim():Un.current.trim(),firstName:k.firstName?.trim()||i.firstName,lastName:k.lastName?.trim()||i.lastName};da.current=JSON.stringify(R),zn(N=>({...N,...R})),Promise.resolve(me(R)).catch(N=>{da.current="",pe(N instanceof Error?N.message:"Failed to attach buyer details.")})},[Be,A,me,ui,st,Lt,k.email,k.firstName,k.lastName,pe]),ht(()=>{!Be||!qe||qe.setCardFieldOrder?.(Ue??null,X==null&&!A)},[Be,qe,Ue,X,A]),ht(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&pe(null)},[xe,pe]);let Nn=Pe((i,R,N)=>{s?.($t(i,R,N))},[s]),Mr=Pe((i,R,N)=>{let he=N?.popupBlocked??dr(R),z=kc(i,he),Re=Er(N?.code)??tr(R)??"external_payment_method_failed",Ne=new On(z,"api_error",{code:"external_payment_method_failed",param:i});at(null),oe==="buttons"&&(kt("buttons"),An(null)),pe(z),c?.(Ne),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:he})},[oe,c,pe]);ht(()=>{if(!Be||!e){gn(null);return}let i=Oa(I?.vault);if(i){gn(i);return}if(!ut){gn(null);return}gn(null);let R=!0;return new So(p).getVaultCapture(e,t).then(N=>{if(!R)return;let he=Oa(N);he?gn(he):pe("Failed to load the secure card form.")}).catch(N=>{R&&pe(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{R=!1}},[Be,ut,$n,e,I?.vault?.html,I?.vault?.messageToken,I?.vault?.expectedOrigin,p,t,pe]);let Vn=Ie({onComplete:a,onError:c,updateError:pe,emitDecline:Nn,resolvedAccount:k,avsConfig:X,avsCheckProp:Se,sessionId:e,nonce:t,baseUrl:p,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt});Vn.current={onComplete:a,onError:c,updateError:pe,emitDecline:Nn,resolvedAccount:k,avsConfig:X,avsCheckProp:Se,sessionId:e,nonce:t,baseUrl:p,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt};let ua=Ie(!1),js=Pe(()=>{let{resolvedAccount:i,avsConfig:R,avsCheckProp:N}=Vn.current,he=i.email?.trim(),z=en(he)?he:Un.current.trim();if(!en(z))return null;let Re=kn(qn.current),Ne=i.firstName?.trim()||Re.firstName,It=i.lastName?.trim()||Re.lastName;if(!Ne&&!It)return null;let Ct=_t.current||i.country||"US",mt=R?ze(R.state,Ct):!1,yt=R?ze(R.address_line_1,Ct):!1,Ke=R?ze(R.postal_code,Ct):!1,nn=R?ze(R.city,Ct):!1,Oe=R?ze(R.address_line_2,Ct):!1,ln=yt&&!mt&&Ke?ms(Ct,(ot.current??"").trim()):null,rn=mt?pn.current:ln;return{accountData:{userId:i.userId??"",email:z,firstName:Ne??"",lastName:It??"",...Ke&&ot.current?{zip:ot.current}:{},...nn&&un.current?{city:un.current}:{},...rn?{state:rn}:{},...yt&&xt.current?{addressLine1:xt.current}:{},...Oe&&tn.current?{addressLine2:tn.current}:{},country:Ct},...N!==void 0?{avsCheck:N}:{},...R?{avsConfig:{country:ze(R.country,Ct),postal_code:Ke,address_line_1:yt,address_line_2:Oe,city:nn,state:mt}}:{}}},[]),pi=Ie(je);pi.current=je,ht(()=>{je||B!==bs||Vn.current.updateError(null)},[je,B]),ht(()=>{!Be||!qe||qe.setSubmitGate?.(Ze||je||st||Lt)},[Be,qe,Ze,je,st,Lt]),ht(()=>{if(!Be||!qe)return;ua.current=!1;let i=!1,R=qe.on("submitting",()=>{jn(!0),_.current&&clearTimeout(_.current),E.current="validation-window",_.current=setTimeout(()=>{_.current=null,E.current==="validation-window"&&(E.current="processing")},bc),at("processing");let{baseUrl:Ne,sessionId:It,nonce:Ct,updateError:mt,onError:yt}=Vn.current;if(!It||!Ct)return;let Ke=js();if(!Ke){mt("Enter a valid email address."),E.current="idle",at(null);return}new So(Ne).patchAccountSnapshot(It,Ct,Ke,{telemetryMode:"best_effort"}).catch(nn=>{if(!vc(nn))return;let Oe=nn instanceof Error?nn.message:"Please check your billing address and try again.";mt(Oe),E.current="idle",at(null),yt?.(nn instanceof On?nn:new On(Oe,"api_error"))})}),N=qe.on("complete",async Ne=>{if(Vr(Ne.sessionId??Vn.current.sessionId),E.current="terminal",at("success"),await new Promise(mt=>setTimeout(mt,1200)),ua.current)return;ua.current=!0;let It=Vn.current,Ct=La(It)||Ne.outcome==="authorized";Vn.current.onComplete?.(Ct?{status:"authorized",paymentIntentId:Ne.intentId,paymentId:Ne.paymentId??It.paymentId,sessionId:Ne.sessionId??It.sessionId,authorizationExpiresAt:Ne.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ne.intentId,checkoutMethod:"card"})}),he=qe.on("decline",async Ne=>{let{updateError:It,emitDecline:Ct}=Vn.current,mt=Ne.message??"Your payment was declined. Please try another card or contact your bank.";E.current="terminal",It(mt),at("error");let yt=Ne.failureOutcome??dc(Ne.declineReason)??"authorization_declined";Ct("card",mt,{code:yt,declineCode:yt}),await new Promise(Ke=>setTimeout(Ke,1500)),!i&&(E.current="idle",at(null))}),z=qe.on("error",async Ne=>{let{updateError:It,onError:Ct}=Vn.current,mt=Ne.message??"There was a problem processing your payment. Please try again.";E.current="terminal",It(mt),at("error"),Ct?.(new On(mt,"api_error",{code:Ne.failureOutcome??"capture_failed"})),await new Promise(yt=>setTimeout(yt,1500)),!i&&(E.current="idle",at(null))}),Re=qe.on("blocked",()=>{if(!pi.current){jn(!0);return}To(),Vn.current.updateError(bs)});return()=>{i=!0,_.current&&(clearTimeout(_.current),_.current=null),E.current="idle",R(),N(),he(),z(),Re()}},[Be,qe,To]);let Hn=!!x?.clientId,eo=Array.isArray(P),Ao=eo&&P.length>0,Ks=eo&&P.includes("paypal"),{expressMethods:Mo,paymentElementMethods:to}=gt(()=>uc(P,{excludePaypal:Hn}),[P,Hn]),mi=Hn||!!ct,Vs=gt(()=>mi?Mo.filter(i=>i!=="paypal"):Mo,[Mo,mi]),Hs=gt(()=>{let i=[];return Q&&i.push("apple_pay"),ce&&i.push("google_pay"),i},[Q,ce]),Bo=eo?Vs:Hs,Ys=H&&Bo.length>0,pa=Pn?Le:T,Fo=gt(()=>{let i=pa?.trim().toUpperCase();return i?fe?to.filter(R=>{let N=fe[R];return!N||N.length===0||N.includes(i)}):rc(to,pa):to},[to,pa,fe]),ma=gt(()=>({mode:"payment",amount:Qr,currency:we.toLowerCase(),paymentMethodCreation:"manual",appearance:li}),[Qr,we,li]),[yi,fi]=ye("loading"),[gi,hi]=ye("loading"),[bi,vi]=ye("loading"),[Gs,ya]=ye(!1),[Pi,fa]=ye("loading"),[No,Ws]=ye();ht(()=>{Ws(us())},[]);let Ci=ve&&(Hn||(eo?Ks:No===!1)),Si=H&&Ys,no=!U&&Ci&&Hn,wi=Pi==="retrying"||Pi==="exhausted",ro=!U&&Ci&&!!bn&&(!Hn||wi),oo=!U&&Si&&!!ge,ao=!U&&H&&Ao&&Fo.length>0&&!!ge,Js=no&&!wi?Gs:ro&&Cs(yi),Xs=oo&&Cs(gi),Zs=ao&&bi!=="load_error",ki=i=>i==="loading"||i==="ready",Ii=no||ro&&ki(yi)||oo&&ki(gi)||ao&&bi!=="load_error",Do=Ie(!1);ht(()=>{if(!Do.current){if(!H&&!ve){Do.current=!0;let i=new On("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(i),pe(i.message)}else if(!H&&ve&&!Hn&&!bn){Do.current=!0;let i=new On("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(i),pe(i.message)}else if(No!==void 0&&!U&&!mn&&!Ii){Do.current=!0;let i=new On("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?.(i),pe(i.message)}}},[H,ve,Hn,bn,No,U,mn,Ii,c,pe]);let Ei=Ie(!1);ht(()=>{if(Ei.current||!Ao)return;let i=[];Q!==!0&&i.push("showApplePay"),ce!==!0&&i.push("showGooglePay"),i.length!==0&&(Ei.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Ao,Q,ce]);let Ri=Pe((i,R)=>it.applyInlineSessionPatch?it.applyInlineSessionPatch(i).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let he=Ps(R,N);return pe(he.message),c?.(he),{error:he,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[it.applyInlineSessionPatch,t,c,e,pe]),Dn=Pe(async i=>{if(!L)return{proceed:!0};try{let R=await L({method:i,sessionId:e||void 0,createSession:it.inlineSessionDraft});if(R===!1)return{proceed:!1};if(R&&typeof R=="object"){R.account&&zn(he=>({...he??{},...R.account}));let N=await Ri(R,i);return N.error?{proceed:!1,accountPatch:R.account}:{proceed:!0,accountPatch:R.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(R){let N=Ps(i,R);return pe(N.message),c?.(N),{proceed:!1}}},[Ri,it.inlineSessionDraft,L,c,e,pe]),_i=Pe(async(i,R)=>{if(Yt.current)return;Yt.current=!0,Mt(!0),at("processing"),pe(null);let N=R?.sessionId??e,he=R?.nonce??t,z=Ia(k,R?.accountPatch),Re=R?.completionPaymentMethodId??yo(i),Ne=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,It=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Ct=()=>{rt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:It})};try{let yt=await new So(p).processPayment(z.userId??"",{sessionId:N,nonce:he,tokenizedData:Ne,accountData:{userId:z.userId??"",email:z.email??"",firstName:z.firstName??"",lastName:z.lastName??"",...X?(()=>{let Oe=_t.current,ln=ze(X.state,Oe),rn=ze(X.address_line_1,Oe),Gt=ze(X.postal_code,Oe),co=rn&&!ln&&Gt?ms(Oe,(ot.current??"").trim()):null,uo=ln?pn.current:co;return{country:Oe,...Gt&&ot.current?{zip:ot.current}:{},...ze(X.city,Oe)&&un.current?{city:un.current}:{},...uo?{state:uo}:{},...rn&&xt.current?{addressLine1:xt.current}:{},...ze(X.address_line_2,Oe)&&tn.current?{addressLine2:tn.current}:{}}})():{}},chv:m,avsCheck:Se??!1,checkoutType:G,checkoutLayout:Y,avsConfig:X?{country:ze(X.country,_t.current),postal_code:ze(X.postal_code,_t.current),address_line_1:ze(X.address_line_1,_t.current),address_line_2:ze(X.address_line_2,_t.current),city:ze(X.city,_t.current),state:ze(X.state,_t.current)}:void 0});if(yt.ok){let Oe=yt.status===204?null:await yt.json().catch(()=>null),ln=La(I)||Oe?.status==="authorized";Vr(N),at("success"),Z(null),await new Promise(rn=>setTimeout(rn,1200)),a?.(ln?{status:"authorized",...typeof Oe?.paymentId=="string"?{paymentId:Oe.paymentId}:I?.paymentId?{paymentId:I.paymentId}:{},sessionId:typeof Oe?.sessionId=="string"?Oe.sessionId:N,...typeof Oe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Oe.authorizationExpiresAt}:I?.authorizationExpiresAt?{authorizationExpiresAt:I.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Ke=await yt.json().catch(()=>null);if(Ke?.type==="paypal_redirect_required"){let Oe=Ke.threeDSecureToken,ln=Ke.paymentMethodId||i.id||"";if(!de||!Oe){at("error"),pe("PayPal authorization required but no token provided.");return}try{let rn=ct?.getRawProvider();if(!rn){pe("PayPal is not available.");return}let Gt={return_url:window.location.href};ln&&(Gt.payment_method=ln);let{error:co}=await rn.confirmPayment({clientSecret:Oe,confirmParams:Gt,redirect:"if_required"});if(co){at("error");let uo=co.message??"PayPal payment failed.";pe(uo),Nn("paypal",uo,{code:co.code})}}catch(rn){at("error"),pe(rn instanceof Error?rn.message:"PayPal authorization failed.")}return}if(Ke?.type==="paypal_direct_required"){let Oe=Ke.orderId;if(!Oe){at("error"),pe("PayPal retry required but no order id provided.");return}let ln=$e.current?.attempts??0;if(ln>=2){at("error"),pe("PayPal payment could not be completed after multiple attempts."),Nn("paypal","paypal_direct_required retry limit exceeded");return}ya(!1),fa("loading"),Z({orderId:Oe,attempts:ln+1}),at(null);return}nc(yt.status,Ke)||Ct(),at("error");let nn=Ke?.message??"Payment failed. Please try again.";pe(nn),Nn(i.isPaypal?"paypal":"card",nn,{code:Ke?.code??Ke?.gatewayErrorCode,declineCode:Ke?.declineCode??Ke?.gatewayDeclineReason}),await new Promise(Oe=>setTimeout(Oe,1500))}catch(mt){Es(mt)||Ct(),at("error"),pe(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(yt=>setTimeout(yt,1500))}finally{Mt(!1),at(null),Yt.current=!1}},[p,e,t,k,Ee,m,de,ct,I,a,c,pe,Nn,rt]),Sn=Pe((i,R)=>{S?S(i):_i(i,R)},[S,_i]),xi=Ie(!1);ht(()=>{if(typeof window>"u"||xi.current)return;let i=new URLSearchParams(window.location.search),R=i.get("payment_intent"),N=i.get("payment_intent_client_secret"),he=i.get("redirect_status");if(!R||!N)return;let z=yt=>{let Ke=localStorage.getItem(yt);if(!Ke)return null;try{return JSON.parse(Ke)}catch{return localStorage.removeItem(yt),null}},Re=z(Gn)??z(hs),Ne;if(Re?.clientSecret){if(Re.clientSecret!==N)return;Ne={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;xi.current=!0,localStorage.removeItem(Gn),localStorage.removeItem(hs);let It=new URL(window.location.href);It.searchParams.delete("payment_intent"),It.searchParams.delete("payment_intent_client_secret"),It.searchParams.delete("redirect_status"),window.history.replaceState({},"",It.toString());let Ct=Re?.paymentMethodType??Re?.tokenType??"card",mt="card";(async()=>{let yt=de?.getRawProvider();if(!yt){let Gt="Payment is not available \u2014 please refresh and try again.";pe(Gt),Nn(mt,Gt);return}if(he==="failed"){let Gt="Payment was declined. Please try again.";pe(Gt),Nn(mt,Gt);return}let{paymentIntent:Ke,error:nn}=await yt.retrievePaymentIntent(N);if(nn){let Gt=nn.message??"Failed to retrieve payment status.";pe(Gt),Nn(mt,Gt,{code:nn.code});return}let Oe=Ke?.status,ln=jo(Oe);if(!Ke||!ln){let Gt=Oe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";pe(Gt),Nn(mt,Gt,{code:Oe??"missing_payment_intent"});return}let rn=typeof Ke.payment_method=="string"?Ke.payment_method:Ke.payment_method?.id;Sn({id:rn??Re?.paymentMethodId??Re?.tokenId??Ke.id,type:"card",threeDSecureActionResultTokenId:Ke.id,gateway:Re?.gateway??"stripe",paymentMethodType:Ct},Ne)})()},[e,Sn,de,pe,Nn]);let ga=Pe(i=>{i.preventDefault()},[]);if(!(de!==null))return l("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let io=oe==="buttons",sn=O?.variables,Qs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ha=sn?.colorBackground,el=ha&&!Qs.has(ha)?ha:void 0,vr=f.cardInputBorder??(io?"#e5e7eb":"#A4A4FF"),ba=sn?.colorDanger??"#dc2626",Pr=i=>lr&&i?ba:vr,Lo=(yn.malformed||yn.empty)&&(Cn||lr),tl=Lo?ba:Pr(Ut.zip),va=f.cardFormContainer?.backgroundColor??el??(io?"white":"#EDEDFF"),Cr=f.cardInputBackground??sn?.colorBackground??"white",Pa=Nr(Te),Ti=Nr(Ae),Br=f.nameInput,Ai=f.cardInputFontSize??_c(Br?.fontSize)??sn?.fontSizeBase??"16px",Mi=typeof Br?.fontFamily=="string"?Br.fontFamily:sn?.fontFamily??"Poppins, sans-serif",Bi=Oi(Br?.fontWeight)??400,nl=f.cardInputColor??(typeof Br?.color=="string"?Br.color:void 0)??sn?.colorText??"#262833",rl=f.cardInputPlaceholderColor??"#9ca3af",Pt=sn?.borderRadius??"8px",Sr=sn?.borderRadius??f.cardButton?.borderRadius??Pt,wr=sn?.colorPrimary??"#4A49FF",ol=sn?.colorPrimaryHover??po(wr,.12),so=sn?.colorText??"#262833",Fr={fontSize:Ai,fontFamily:Mi,fontWeight:Bi,color:nl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},al={"--flopay-input-placeholder-color":rl,"--flopay-input-font-size":Ai,"--flopay-input-font-family":Mi,"--flopay-input-font-weight":String(Bi)},lo=f.cardFormContainer??{},Ca=lo.padding??(io?"0":"1rem"),Sa=lo.borderRadius??Pt,il=qe&&fn?l(wa,{capture:qe,html:fn.html,messageToken:fn.messageToken,expectedOrigin:fn.expectedOrigin,theme:pt,onReady:()=>{if(!A&&!X||typeof document>"u")return;let i=()=>{(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};i();let R=0,N=window.setInterval(()=>{R+=1;let he=document.activeElement;!!he&&he.tagName==="IFRAME"&&he.id==="flopay_vault_form_iframe"?(i(),window.clearInterval(N)):R>=50&&window.clearInterval(N)},100)},onError:i=>pe(i),onValidation:i=>{let R=E.current;(R==="idle"||R==="validation-window")&&(pe(i),i&&E.current==="validation-window"&&(_.current&&(clearTimeout(_.current),_.current=null),E.current="idle",at(null)))}}):l("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"}),Fi=ke("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Bn()},style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca,...al,display:"flex",flexDirection:"column"},children:[l("style",{children:`
26
26
  .flopay-shared-input::placeholder {
27
27
  color: var(--flopay-input-placeholder-color);
28
28
  opacity: 1;
@@ -30,13 +30,13 @@ ${Le.join(`
30
30
  font-family: var(--flopay-input-font-family);
31
31
  font-weight: var(--flopay-input-font-weight);
32
32
  }
33
- `}),Ur&&un&&xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Pe?-2:0},children:[xe("button",{type:"button",onClick:On,style:{display:"inline-flex",alignItems:"center",gap:Wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:c.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...c.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...c.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(hr,{content:Ce})]}),Qa?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...c.title},children:u(Yr,{content:q})})]}),!Ur&&!Qa&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Jo,order:Pe?-3:0,...c.title},children:u(Yr,{content:q})}),ne&&u("div",{style:{order:Pe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Fe,_=(L=!1)=>({backgroundColor:qr,border:`1px solid ${ar(L)}`,borderRadius:wt,marginTop:"0.5rem",padding:"10px"}),z=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ri}),Q=Sl(i);return xe(Er,{children:[Te(ne.address_line_1,i)&&u("div",{style:_(ot.line1),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:vt,onChange:L=>{Ut.current.addressLine1=!0,Ke.current=L.target.value,Je(L.target.value)},disabled:C,required:!0,"data-testid":"flopay-address-line1",style:z()})}),Te(ne.address_line_2,i)&&u("div",{style:_(),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Lt,onChange:L=>{Ut.current.addressLine2=!0,Rn.current=L.target.value,je(L.target.value)},disabled:C,"data-testid":"flopay-address-line2",style:z()})}),(Te(ne.city,i)||Te(ne.state,i))&&xe("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Te(ne.city,i)&&u("div",{style:{flex:1,backgroundColor:qr,borderTop:`1px solid ${ar(ot.city)}`,borderRight:`1px solid ${ar(ot.city)}`,borderBottom:`1px solid ${ar(ot.city)}`,borderLeft:`1px solid ${ar(ot.city)}`,padding:"10px",borderTopLeftRadius:wt,borderBottomLeftRadius:wt,...Te(ne.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:wt}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ht,onChange:L=>{Ut.current.city=!0,ct.current=L.target.value,Et(L.target.value)},disabled:C,required:!0,"data-testid":"flopay-city",style:z()})}),Te(ne.state,i)&&u("div",{style:{flex:1,backgroundColor:qr,border:`1px solid ${ar(ot.state)}`,padding:"10px",borderTopRightRadius:wt,borderBottomRightRadius:wt,...Te(ne.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:wt}},children:Q?xe("select",{id:"flopay-billing-state",name:"billing-state",value:nn,onChange:L=>{Ut.current.state=!0,vn.current=L.target.value,Nt(L.target.value)},disabled:C,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...z(),cursor:"pointer"},children:[u("option",{value:"",children:Li(i)}),Q.map(L=>u("option",{value:L.code,children:L.name},L.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Li(i),autoComplete:"billing address-level1",value:nn,onChange:L=>{Ut.current.state=!0,vn.current=L.target.value,Nt(L.target.value)},disabled:C,required:!0,"data-testid":"flopay-state",style:z()})})]}),(Te(ne.country,i)||Te(ne.postal_code,i))&&xe("div",{style:{display:"flex",flexDirection:ae==="column"?"column":"row",gap:ae==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Te(ne.country,i)&&u("div",{style:{flex:ae==="row"?1:void 0,backgroundColor:qr,borderTop:`1px solid ${$r}`,borderRight:`1px solid ${$r}`,borderBottom:`1px solid ${$r}`,borderLeft:`1px solid ${$r}`,padding:"10px",...ae==="row"&&Te(ne.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:wt,borderBottomLeftRadius:wt,borderRight:"none"}:{borderRadius:wt}},children:u("select",{id:"flopay-billing-country",name:"billing-country",value:Fe,onChange:L=>{Ut.current.country=!0,zt.current=L.target.value,Vt(L.target.value),oe?.(L.target.value),vn.current="",Nt("")},disabled:C,autoComplete:"billing country","data-testid":"flopay-country",style:{...z(),cursor:"pointer"},children:Pl.map(L=>xe("option",{value:L.code,children:[L.flag," ",L.name]},L.code))})}),Te(ne.postal_code,i)&&u("div",{style:{flex:ae==="row"?1:void 0,backgroundColor:qr,border:`1px solid ${Cs}`,padding:"10px",...ae==="row"&&Te(ne.country,i)?{borderRadius:"0",borderTopRightRadius:wt,borderBottomRightRadius:wt}:{borderRadius:wt}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ya(Fe),autoComplete:"billing postal-code",value:Xt,onChange:L=>{Ut.current.zip=!0,rt.current=L.target.value,Ge(L.target.value),qe?.(L.target.value)},onBlur:()=>Sn(!0),disabled:C,required:Zt.required,"aria-invalid":yo||void 0,"aria-describedby":yo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:z()})})]}),yo&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Yo,...ri,fontSize:"0.75rem"},children:Zt.empty?`${ya(i)} is required`:$l(i)})]})})()}),Pe&&de&&u("div",{style:{order:-2,width:"100%"},children:de}),Pe&&Es,l&&u(wr,{margin:"0.75rem 0",styleOverride:c.errorBanner,children:l})]}),fo={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"},ai=i=>D?!ee||!an?u("pre",{"data-testid":i,style:fo,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":i,style:fo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ee}`,` directPaypalConfigured=${an}`,` inAppBrowserDetected=${String(po)}`,` shouldRenderDirectPayPal=${Lr}`,` shouldRenderStripePayPal=${Or}`,` hasPaypalStripeInstance=${!!G}`].join(`
34
- `)}):null,ii=i=>D?!W||!E?u("pre",{"data-testid":i,style:fo,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":i,style:fo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${W}`,` currency=${$}`,` amountInCents=${ie}`,` enabledPaymentMethods: ${JSON.stringify(v??[])}`,` enabledPaymentMethodsProvided=${Fr}`,` hasEnabledMethods=${so}`,` expressMethods: ${JSON.stringify(lo)}`,` walletExpressMethods: ${JSON.stringify(co)}`,` paymentElementMethods: ${JSON.stringify(Dr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(uo)}`,` hasStripeInstance=${!!E}`,` shouldRenderWallets=${Nr}`,` shouldRenderPaymentElement=${zr}`].join(`
35
- `)}):null,si=me==="apm-expanding"||me==="apm-form"||me==="apm-collapsing",go=me==="apm-expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:me==="apm-collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,ho=at?{...qo,paymentMethodTypes:[at]}:null;if(ce==="buttons"){let i=me==="buttons"||me==="expanding"||me==="apm-expanding",_=me==="expanding"||me==="card"||me==="collapsing",z=Ae===void 0?{boxSizing:"border-box",height:Fo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Q=me==="expanding"||me==="apm-expanding"?`flopay-buttons-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:me==="collapsing"||me==="apm-collapsing"?`flopay-buttons-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,L=me==="expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:me==="collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return xe("form",{onSubmit:Vo,className:x,style:{position:"relative"},children:[u(ma,{}),qt&&u(Mn,{status:qt,errorMessage:l,authorized:_n}),xe("div",{style:{display:"grid"},children:[xe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Q?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Q?Nl:{},...Q?{animation:Q,pointerEvents:"none"}:{}},children:[ai("flopay-direct-paypal-gate-debug"),ii("flopay-stripe-gate-debug"),Lr&&Ie&&xe(Er,{children:[Qt&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(Ro,{sessionId:e,nonce:t,billingApiUrl:pt,email:y.email,clientId:Ie.clientId,environment:Ie.environment,currency:$.toUpperCase(),isSubscription:We,providerObjectType:Ie.providerObjectType,onTokenizedBody:yn,onComplete:a,onErrorChange:M,onDecline:d,onTechnicalFailure:$e,onButtonClick:te,runBeforeButtonClick:wn,isProcessing:C,onLoadStateChange:jo,onInitializationStateChange:Ko,session:Y??null,existingOrderId:Qt?.orderId,debug:D},Qt?.orderId??"fresh")]}),Or&&u(pr,{stripe:G,options:ve,children:u(Ki,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,onTokenizedBody:yn,onErrorChange:M,isProcessing:C,onButtonClick:te,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:wn,onLoadStateChange:Na,placeholderBorderRadius:ir})}),Nr?u(pr,{stripe:E,options:be,children:u(Vi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,intentKind:H>0?"payment":"setup",expressMethods:co,onTokenizedBody:yn,onErrorChange:M,onButtonClick:te,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:wn,onLoadStateChange:Ua,placeholderBorderRadius:ir})}):Va?u("div",{style:{height:Fo,borderRadius:ir,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,zr&&u(Hi,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,paymentElementMethods:uo,stripeInstance:E,paymentElementBaseOptions:qo,onTokenizedBody:yn,onErrorChange:M,onButtonClick:te,onDecline:d,runBeforeButtonClick:wn,onLoadStateChange:qa,isProcessing:C,submitButtonColor:sr,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,onExpandApm:An,expandedApmMethod:at,themeId:Se,buttonAppearance:{backgroundColor:c.cardButton?.backgroundColor,borderColor:c.cardInputBorder,textColor:c.cardButton?.color,borderRadius:ir}}),Pe&&u("button",{type:"button",onClick:async()=>{C||!(await wn("card")).proceed||(te?.("card"),Gn())},disabled:C,style:{width:"100%",...z,...c.cardButton,...ba({themeBundle:s,resolvedPrimaryColor:sr,resolvedBorderRadius:wt,submitButtonStyle:c.submitButton,explicitPrimaryColor:en?.colorPrimary}),fontSize:c.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:C?"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:C?.6:1},onMouseEnter:fe=>{!C&&(s||en?.colorPrimary)&&(fe.currentTarget.style.backgroundColor=ks)},onMouseLeave:fe=>{(s||en?.colorPrimary)&&(fe.currentTarget.style.backgroundColor=sr)},onMouseDown:fe=>{fe.currentTarget.style.transform="scale(0.985)"},onMouseUp:fe=>{fe.currentTarget.style.transform="scale(1)"},children:u(gr,{content:Ae})}),l&&me==="buttons"&&u(wr,{margin:"0.25rem 0",styleOverride:c.errorBanner,children:l})]}),Pe&&_&&u("div",{style:{gridArea:"1 / 1",...L?{animation:L}:{},...me==="collapsing"?{pointerEvents:"none"}:{}},children:oi}),W&&si&&at&&ho&&E&&u("div",{style:{gridArea:"1 / 1",...go?{animation:go}:{},...me==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:Go,borderRadius:Zo,...jr,padding:Xo},children:[xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[xe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:Wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:c.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...c.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...c.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(hr,{content:Ce})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:Jo,paddingRight:80,...c.title},children:`Pay with ${Rr(at)}`})]}),u(pr,{stripe:E,options:ho,children:u(fa,{method:at,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,onTokenizedBody:yn,onErrorChange:M,onDecline:d,onCancel:Nn,runBeforeButtonClick:wn,onButtonClick:te,isProcessing:C,submitButtonColor:sr,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,errorText:l})},at)]})})]})]})}return si&&at&&ho&&E&&W?xe("form",{onSubmit:Vo,className:x,style:{position:"relative"},children:[u(ma,{}),qt&&u(Mn,{status:qt,errorMessage:l,authorized:_n}),u("div",{style:{...go?{animation:go}:{},...me==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:Go,borderRadius:Zo,...jr,padding:Xo},children:[xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[xe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:Wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:c.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...c.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...c.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(hr,{content:Ce})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:Jo,paddingRight:80,...c.title},children:`Pay with ${Rr(at)}`})]}),u(pr,{stripe:E,options:ho,children:u(fa,{method:at,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,onTokenizedBody:yn,onErrorChange:M,onDecline:d,onCancel:Nn,runBeforeButtonClick:wn,onButtonClick:te,isProcessing:C,submitButtonColor:sr,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,errorText:l})},at)]})})]}):xe("form",{onSubmit:Vo,className:x,style:{position:"relative"},children:[u(ma,{}),qt&&u(Mn,{status:qt,errorMessage:l,authorized:_n}),xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ai("flopay-direct-paypal-gate-debug-default"),ii("flopay-stripe-gate-debug-default"),Lr&&Ie&&xe(Er,{children:[Qt&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(Ro,{sessionId:e,nonce:t,billingApiUrl:pt,email:y.email,clientId:Ie.clientId,environment:Ie.environment,currency:$.toUpperCase(),isSubscription:We,providerObjectType:Ie.providerObjectType,onTokenizedBody:yn,onComplete:a,onErrorChange:M,onDecline:d,onTechnicalFailure:$e,onButtonClick:te,runBeforeButtonClick:wn,isProcessing:C,onLoadStateChange:jo,onInitializationStateChange:Ko,session:Y??null,existingOrderId:Qt?.orderId,debug:D},Qt?.orderId??"fresh")]}),Or&&u(pr,{stripe:G,options:ve,children:u(Ki,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,onTokenizedBody:yn,onErrorChange:M,isProcessing:C,onButtonClick:te,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:wn,onLoadStateChange:Na,placeholderBorderRadius:ir})}),Nr&&u(pr,{stripe:E,options:be,children:u(Vi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,intentKind:H>0?"payment":"setup",expressMethods:co,onTokenizedBody:yn,onErrorChange:M,onButtonClick:te,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:wn,onLoadStateChange:Ua,placeholderBorderRadius:ir})}),zr&&u(Hi,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,paymentElementMethods:uo,stripeInstance:E,paymentElementBaseOptions:qo,onTokenizedBody:yn,onErrorChange:M,onButtonClick:te,onDecline:d,runBeforeButtonClick:wn,onLoadStateChange:qa,isProcessing:C,submitButtonColor:sr,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,themeId:Se,onExpandApm:An,expandedApmMethod:at,buttonAppearance:{backgroundColor:c.cardButton?.backgroundColor,borderColor:c.cardInputBorder,textColor:c.cardButton?.color,borderRadius:ir}})]}),Pe&&(hs||gs||Ps)&&xe("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),u("span",{children:"or pay with card"}),u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Pe&&oi]})}import{Fragment as Dn,jsx as X,jsxs as Dt}from"react/jsx-runtime";var Tr=44,Aa="flopay_checkout_saved_payment_resume",Uo=new Map,No=new Map;function ns(e,t){t.settled&&t.consumers===0&&Uo.get(e)===t&&Uo.delete(e)}function ec(e,t,n){let r=No.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};No.set(e,a);let m=()=>{No.get(e)===a&&No.delete(e)};return o.then(m,m),o}function to(e){return new Promise(t=>setTimeout(t,e))}function zo(e,t,n){let r=ko({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:is,enabled:t!==!1});return r.beginCheckout(n),r}function no(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Sa(e,t,n,r,o){let a=zo(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),no(a)}function tc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function Ta(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function wa(e){return!e||e.data.stripe?.publishableKey?!1:!!Ta(e)?.clientId}function Kn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function nc(){if(!Kn())return null;try{let e=window.sessionStorage.getItem(Aa);return e?JSON.parse(e):null}catch{return null}}function rs(e){if(Kn())try{window.sessionStorage.setItem(Aa,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ka(){if(Kn())try{window.sessionStorage.removeItem(Aa)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Ma=":idempotency-key";function ss(e,t){if(!Kn())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 Ia(e,t,n,r){if(Kn())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 xa(e,t){if(Kn())try{ss(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ls(e,t){if(!Kn())return null;try{let n=window.sessionStorage.getItem(e+Ma);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 Ea(e,t,n){if(Kn())try{window.sessionStorage.setItem(e+Ma,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Ra(e,t){if(xa(e,t),!!Kn())try{ls(e,t)&&window.sessionStorage.removeItem(e+Ma)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function rc(){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 os(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 oc(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function _a(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ro(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=>_a(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>_a(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>_a(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function ac(e,t=!1){let n=ro(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 ic(e,t){if(!e?.customer||!e.products)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=Zl(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Gl(t.items,t.subscriptions)).map(h=>({type:h.type,code:h.code??h.providerItemId??h.providerPlanId??"",quantity:h.quantity??1,totalAmount:h.totalAmount,overrideAmount:h.overrideAmount??null,currency:(h.currency??o).toUpperCase()})).sort((h,P)=>`${h.code}:${h.type??""}`.localeCompare(`${P.code}:${P.type??""}`)),m=e.products.map(h=>({type:h.type,code:h.code??"",quantity:h.quantity??1,totalAmount:h.totalAmount,overrideAmount:h.overrideAmount??null,currency:(h.currency??e.currency).toUpperCase()})).sort((h,P)=>`${h.code}:${h.type??""}`.localeCompare(`${P.code}:${P.type??""}`));if(a.length!==m.length)return!1;for(let h=0;h<a.length;h+=1){let P=a[h],b=m[h];if(P.code!==b.code||P.type!==void 0&&P.type!==b.type||P.quantity!==b.quantity||P.totalAmount!==b.totalAmount||P.overrideAmount!==b.overrideAmount||P.currency!==b.currency)return!1}let d=[...t.couponCodes??[]].sort(),T=[...e.coupons??[]].sort();return d.length===T.length&&d.every((h,P)=>h===T[P])}function Ba({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:m,loading:d,error:T,onComplete:h,onError:P,onInstrument:b,onDecline:x,onCountryChange:U,onZipChange:p,showPayPal:S=!0,showStripe:ee=!0,enabledPaymentMethods:W,showApplePay:v=!0,showGooglePay:ye=!0,debug:j=!1,layout:J,theme:ce,buttonsTheme:Se,buttonsStyles:re,cardButtonContent:le,cardBackButtonContent:Ve,cardTitleContent:Ae,showSecurityFooter:Ce,onButtonClick:q,onBeforeButtonClick:B,enableAVS:te,cardFieldOrder:tt,cardPreFormSlot:Me,avsLayout:V,className:de,initialErrorMessage:ae=null,children:ue,checkoutMode:ke,confirmLabel:pe,renderConfirmButton:Re,onSessionCompleted:O}){let w=Jl(r),oe=bn(()=>as(ce),[ce]),qe=a??oe?.appearance,De=n?"embedded_checkout":"standard_checkout",Z=ue?"custom_layout":J==="buttons"?"buttons_layout":"default_layout",[R,H]=kt(null),[$,Be]=kt(null),Ie=_t(null),[We,Y]=kt(null),mt=_t(null),[D,Le]=kt(null),Pt=bn(()=>n?ro(n):"",[n]),N=n?`create:${Pt}`:`session:${e??""}`,bt=D?.gateways?.stripe?"stripe":D?.gateways?.paypal?"paypal":void 0,ze=_t(new Set),tn=_t(N),It=_t(N);So(()=>{It.current=N,tn.current!==N&&(tn.current=N,ze.current.clear())},[N]);let k=jn(l=>{if(It.current===N){if(ra.has(l.name)){if(ze.current.has(l.name))return;ze.current.add(l.name)}Qe(()=>b?.(l))}},[N,b]),se=Cr(k,N),yt=_t(!1),Fe=jn(l=>{if(yt.current)return;let s=l.gateway||!bt?l:{...l,gateway:bt};k(s)},[k,bt]);Fn(()=>{se({class:"lifecycle",name:"checkout.mount"})},[se]);let[Vt,Xt]=kt(e??""),Ge=e??Vt,vt=n?"":Ge,[Je,Lt]=kt(!0),[je,Ht]=kt(null),[Et,nn]=kt("full"),[Nt,En]=kt(!1),[sn,rt]=kt(ae),[zt,Ke]=kt(null),[Rn,ct]=kt(null),[vn,Ut]=kt(!1),[ne,Vn]=kt(void 0),[_n,Tn]=kt(""),[xn,mr]=kt(!1),[I,Xe]=kt(!1),Pe=_t(0),[Cn,Oe]=kt("loading"),[Hn,nr]=kt(0),Yt=_t(!1),dt=_t(!1),Zt=_t(!1),Gt=_t(null),ot=bn(()=>({checkoutMode:ke??Et,layout:ue?"unknown":J==="buttons"?"buttons":"embedded"}),[ke,ue,Et,J]),ln=_t(h);ln.current=h;let cn=_t(P);cn.current=P;let Yn=_t(x);Yn.current=x,Fn(()=>{Bt($)?.setCheckoutContext(ot),We&&We!==$&&Bt(We)?.setCheckoutContext(ot)},[$,We,ot]);let Sn=_t(O);Sn.current=O;let rn=jn(l=>{Oe(l),!(l!=="exhausted"||Zt.current)&&(Zt.current=!0,cn.current?.(new Ft("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),dn=jn(()=>{Oe("retrying"),nr(l=>l+1)},[]);Fn(()=>{Oe("loading"),nr(0),Zt.current=!1},[Ge]),Fn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:is,checkout_type:De,checkout_layout:Z,billing_api_url:w})},[Z,De,w]);let me=bn(()=>n?ro(n,!0):"",[n]),Ct=bn(()=>_n===me?ne:void 0,[ne,_n,me]),at=bn(()=>n?ea(n,Ct):void 0,[n,Ct]),on=ke??at?.checkoutMode??"full",un=bn(()=>at?{...at,checkoutMode:on}:void 0,[at,on]);Fn(()=>{Vn(void 0),Tn(me)},[me]),Fn(()=>{rt(ae)},[ae]);let Ln=jn((l,s,c)=>{Qe(()=>{Yn.current?.(Mt(l,s,c))})},[Qe]),pn=jn(async(l,s)=>{rt(null),ct(null),Ut(!1),Ke("processing");let c=s?.sessionId??l.id,A=l.gateways?.stripe?"stripe":l.gateways?.paypal?"paypal":void 0,K=Ie.current??mt.current,F=Bt(K),C=K?null:zo(w,o,ot),f={log:be=>{F?F.log(be):C?.log(be)},error:be=>{F?F.error(be):C?.error(be)},terminal:be=>{F?F.terminal(be):C?.terminal(be)},performance:be=>{F?F.performance(be):C?.performance(be)},now:()=>F?.now()??C?.now()??0,elapsed:be=>F?.elapsed(be)??Math.max(0,(C?.now()??be)-be)},y=f.now(),g=!!(s?.initialAutoProcessingError||s?.initialAutoProcessingPending),E=!1,G,ie=()=>{E||(E=!0,g=!0,G=f.now(),f.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},_e=!1,Ue=()=>{_e||(_e=!0,f.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),f.performance({stage:"processing",durationMs:f.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}),G!==void 0&&f.performance({stage:"recovery",durationMs:f.elapsed(G),durationMode:"machine",paymentMethodCategory:"saved"}))};f.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),yt.current=!0;try{f.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{yt.current=!1}se({class:"lifecycle",name:"payment.processing.started",provider:A}),g&&ie();let Tt;try{let be=xi(s?.initialAutoProcessingError),ve;if(be)ie(),be.type==="paypal_redirect_required"&&Gt.current?.publishableKey&&rs({sessionId:c,publishableKey:Gt.current.publishableKey,paypalPublishableKey:Gt.current.paypalPublishableKey}),ve=await Ao(be,{flopay:Ie.current,paypalFlopay:mt.current,attempt3DS:s?.attempt3DS,billingApiUrl:w,sessionId:c,session:l,telemetry:!1}),be.type==="paypal_redirect_required"&&ka();else if(s?.initialAutoProcessingPending){let $e=(await new Oo(w,{telemetry:!1}).waitForCheckoutSessionCompletion(s.initialAutoProcessingPending.sessionId,{initialDelayMs:s.initialAutoProcessingPending.retryAfterMs})).data.session;if(!br($e))throw bo($e);ve=lr($e,c)}else{if(s?.initialAutoProcessingError)throw Qn(s.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:s.initialAutoProcessingError.checkoutMethod});if(s?.fromCreateSession)return s?.fallbackToFull&&(nn("full"),os("full")),!1;{let M=await Ir({billingApiUrl:w,sessionId:c,session:l,telemetry:!1});M.type==="success"?ve=M.result:(ie(),M.type==="paypal_redirect_required"&&Gt.current?.publishableKey&&rs({sessionId:c,publishableKey:Gt.current.publishableKey,paypalPublishableKey:Gt.current.paypalPublishableKey}),ve=await Ao(M,{flopay:Ie.current,paypalFlopay:mt.current,attempt3DS:s?.attempt3DS,billingApiUrl:w,sessionId:c,session:l,telemetry:!1}),M.type==="paypal_redirect_required"&&ka())}}c&&kr(c),Ue(),g&&(f.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),f.terminal({outcome:ve.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Ut(ve.status==="authorized"),Ke("success"),await to(1200),Tt=()=>ln.current?.(ve)}catch(be){let ve=ur(be),M=ve.checkoutMethod??Zr;rt(ve.message),ct(ve.message),Ut(!1),s?.fallbackToFull&&(f.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),nn("full"),os("full")),Ue();let St=ve.statusCode!==void 0?Ql(ve.statusCode,"unknown"):void 0,$e=St==="4xx"?{requestCategory:"process_payment",statusClass:St}:{},nt=St===void 0||St==="4xx";if(nt&&(ve.telemetryOutcome==="payment_declined"||!!(ve.declineCode||ve.code?.toLowerCase().includes("declin"))))f.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...$e});else if(nt&&(ve.telemetryOutcome==="validation_rejected"||ve.type==="validation_error"))f.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...$e});else{let io=es(be,g?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),an=ve.telemetryRequestCategory??"process_payment";yt.current=!0;try{f.error({...io,...ve.telemetryFailureCategory?{failureCategory:ve.telemetryFailureCategory}:{},stage:g?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:an})}finally{yt.current=!1}se({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:an,provider:A})}return Qe(()=>cn.current?.(ve)),Ln(M,ve,{code:ve.code,declineCode:ve.declineCode}),Ke("error"),await Promise.allSettled([to(1500),s?.ensureProvidersReady?s.ensureProvidersReady():Promise.resolve()]),g&&(f.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ue(),C&&no(C),Ke(null),ct(null)}return Qe(Tt),!0},[Ln,se,Qe,ur,w,o,ot]);Fn(()=>{if(typeof window>"u"||dt.current)return;let l=new URLSearchParams(window.location.search),s=l.get("payment_intent_client_secret");if(!s)return;let c=nc();c&&(dt.current=!0,(async()=>{let A,K=0;rt(null),ct(null),Ke("processing"),En(!0);try{if(l.get("redirect_status")==="failed")throw Object.assign(new Ft("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:F,paypalFlopay:C}=await Bo({publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey,billingApiUrl:w,locale:m,telemetry:o});A=Bt(C??F),K=A?.now()??0,A?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),A?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let f=(C??F)?.getRawProvider();if(!f)throw Object.assign(new Ft("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:y,error:g}=await f.retrievePaymentIntent(s);if(g)throw Object.assign(new Ft(g.message??"Failed to retrieve PayPal payment status.","api_error",{code:g.code}),{checkoutMethod:"paypal"});let E=fi(y?.status);if(!y||E==="failed")throw Object.assign(new Ft("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let G=typeof y.payment_method=="string"?y.payment_method:y.payment_method?.id,ie=E;if(c.sessionId){let Tt=(await new Oo(w,{telemetry:!1}).getUnifiedCheckoutSession(c.sessionId)).data.session;if(Tt&&Tt.status!=="complete"){let be=await Ir({billingApiUrl:w,sessionId:c.sessionId,session:Tt,telemetry:!1,tokenizedData:{id:G??y.id,type:"card",threeDSecureActionResultTokenId:y.id,isPaypal:!0}});if(be.type!=="success")throw Object.assign(new Ft("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ie=be.result.status}}c.sessionId&&kr(c.sessionId),A?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),A?.performance({stage:"redirect_resume",durationMs:A.elapsed(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),A?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke("success"),await to(1200),Qe(()=>ln.current?.({status:ie,paymentIntentId:y.id,paymentMethodId:G,checkoutMethod:"paypal"}))}catch(F){let C=ur(F),f=C.checkoutMethod??"paypal",y=!!(C.declineCode||C.code?.toLowerCase().includes("declin"));if(A)A.performance({stage:"redirect_resume",durationMs:A.elapsed(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),y?A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):A.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(y){let g=zo(w,o,ot);g.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),no(g)}else Sa(w,o,ot,"REDIRECT_RESUME_FAILED","redirect_resume");rt(C.message),ct(C.message),Qe(()=>cn.current?.(C)),Ln(f,C,{code:C.code,declineCode:C.declineCode}),Ke("error"),await to(1500)}finally{ka(),rc(),Ke(null),ct(null),En(!1)}})())},[Ln,Qe,m,ur,w,o]);let $t=_t(null),Wt=bn(()=>un?ro(un):"",[un]),Jt=_t(un);Jt.current=un,Fn(()=>{Xt(e??"")},[e]),Fn(()=>{Yt.current=!1,rt(ae),ct(null),Ut(!1),Ke(null)},[Wt,ae,e]);async function Gn(l,s,c){let A=zo(w,o,ot),K=new Oo(w,{telemetry:!1}),F=!1;try{let C=l.idempotencyKey!==void 0?ts(l.idempotencyKey):void 0,f=ss(s,c),y=ls(s,c);f?.canonicalIdentity===c&&y&&y.canonicalIdentity===void 0&&(Ea(s,c,y.idempotencyKey),y={...y,canonicalIdentity:c});let g=C??(y?.canonicalIdentity===c?y.idempotencyKey:void 0),E,G=!1;A.log({name:f?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let ie=f?.sid??null,_e=null,Ue;if(ie)try{_e=await K.getUnifiedCheckoutSession(ie,f?.nonce),f&&f.canonicalIdentity===void 0&&(ic(_e.data.session,l)?(Ia(s,c,ie,f.nonce??_e.data.session?.clientSecret),y&&y.canonicalIdentity===void 0&&(Ea(s,c,y.idempotencyKey),g??(g=y.idempotencyKey))):(Ra(s,c),y=null,g=C,ie=null,_e=null));let Tt=_e?.data.session?.status;if(ie&&_e&&Tt==="complete"){if(la(ie))return{sid:ie,result:_e};Ra(s,c),ie=null,_e=null,G=!0}}catch{A.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),f?.canonicalIdentity===void 0?(Ra(s,c),g=C):xa(s,c),ie=null}if(!ie){!C&&(G||!g)&&(g=ts(),E=g),g&&Ea(s,c,g);let Tt=A.now(),be=0;A.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ve={...l,idempotencyKey:g,avsCheck:!!te,avsConfig:typeof te=="object"?te:void 0,checkoutType:"embedded_checkout",checkoutLayout:ue?"custom_layout":J==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(ve,Hl,{configurable:!1,enumerable:!1,value:{onAttempt:$e=>{be=Math.max(be,$e)}}});let M=()=>{A.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),A.performance({stage:"session_create",durationMs:A.now()-Tt,durationMode:"machine",requestCategory:"session_create",attempt:be,statusClass:"2xx"})},St=$e=>{let nt=es($e,"CHECKOUT_SESSION_CREATE_FAILED","unknown");A.performance({stage:"session_create",durationMs:A.now()-Tt,durationMode:"machine",requestCategory:"session_create",attempt:be,statusClass:nt.statusClass}),$e instanceof Ft&&$e.type==="validation_error"?A.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):nt.statusClass==="4xx"?A.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(A.error({...nt,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),se({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Wl(ve)){let $e=await K.createDetachedSession(ve);$e.claimed.catch(()=>{}),_e=$e.shell,ie=$e.sessionId,Ue=$e.claimed.then(nt=>{let or=nt.data.session?.id??$e.sessionId;return or&&Ia(s,c,or,nt.data.session?.clientSecret??$e.nonce),M(),nt},nt=>{throw xa(s,c),St(nt),nt}).finally(()=>no(A)),Ue.catch(()=>{}),F=!0,A.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),A.performance({stage:"session_shell",durationMs:A.now()-Tt,durationMode:"machine",requestCategory:"session_create",attempt:be,statusClass:"2xx",paymentMethodCategory:"card"})}else _e=await K.createAndFetchSession(ve),M()}catch($e){throw St($e),$e}ie=_e.data.session?.id??ie??"",ie&&!Ue&&Ia(s,c,ie,_e.data.session?.clientSecret)}return{sid:ie??"",result:_e,sdkGeneratedIdempotencyKey:E,...Ue?{claimed:Ue}:{}}}finally{F||no(A)}}let On=jn(async(l,s)=>{let c=Jt.current;if(!c)throw new Ft("createSession is required to bootstrap checkout.","validation_error");let A=ea(c,l),K=ro(A),F=ac(A),C=Uo.get(K);if(!C){let g={canonicalIdentity:K,promise:Gn(A,F,K),consumers:0,settled:!1};C=g,Uo.set(K,g);let E=()=>{g.settled=!0,ns(K,g)};g.promise.then(E,E)}C.consumers+=1;let f=!1,y=()=>{f||(f=!0,C.consumers-=1,ns(K,C))};s?.(y);try{let g=await C.promise;$t.current=K,l&&(Tn(me),Vn(ve=>pi(ve,l)));let{sid:E,result:G,claimed:ie}=g;if(H(G),G.data.session&&Le(G.data.session),E&&Xt(E),ie){Pe.current+=1;let ve=Pe.current;Xe(!0),ie.then(M=>{Pe.current===ve&&(H(M),M.data.session&&Le(M.data.session),Xe(!1))},M=>{Pe.current===ve&&(Xe(!1),Ht(M instanceof Ft?M:new Ft(M instanceof Error?M.message:"Failed to create session","api_error")))})}else Pe.current+=1,Xe(!1);let{publishableKey:_e,paypalPublishableKey:Ue}=Mo(G),{flopay:Tt,paypalFlopay:be}=await Bo({publishableKey:_e,paypalPublishableKey:Ue,billingApiUrl:w,locale:m,telemetry:o});return Ie.current=Tt,Be(Tt),mt.current=be,Y(be),Lt(!1),g}catch(g){throw $t.current===K&&($t.current=null),g}finally{s||y()}},[me,m,w,o,ot]),An=_t(pn);An.current=pn;let Nn=_t(On);Nn.current=On;let qt=jn(async l=>{if(!oc(l)||xn)return{sessionId:Vt,session:D};mr(!0);try{let s=await On(l);return{sessionId:s.sid,session:s.result.data.session??null}}finally{mr(!1)}},[On,xn,Vt,D]);Fn(()=>{let l=!1,s;if(Ht(null),Wt){let K=Jt.current;return nn(on),Lt(!1),$t.current===Wt?()=>{l=!0}:(Le(mi(K,ke)),(async()=>{let F=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),C=on==="auto"&&!Yt.current&&!F;C&&(rt(null),ct(null),Ke("processing"));try{let f=await Nn.current(void 0,G=>{s=G}),y=f.result.data.session??null;Gt.current=Mo(f.result);let g=wa(f.result),E=la(f.sid||y?.id);if(!l&&C&&y&&!g&&!E){Yt.current=!0,await ec(Wt,f.sdkGeneratedIdempotencyKey,()=>An.current(y,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:f.result.autoProcessingError,initialAutoProcessingPending:f.result.autoProcessingPending,autoProcessingAttempted:f.result.autoProcessingAttempted,sessionId:f.sid||y.id}));return}!l&&C&&((g||E)&&(Yt.current=!0),Ke(null),ct(null))}catch(f){if(l)return;let y=f instanceof Ft||typeof f=="object"&&f!==null&&"code"in f?f.code:void 0;if(C&&y==="session_auto_completed"){Yt.current=!0,Ke("success"),await to(1200),l||(Qe(()=>{ln.current?.({status:"succeeded"})}),Ke(null),ct(null));return}C&&(Ke(null),ct(null));let g=f instanceof Ft?f:new Ft(f instanceof Error?f.message:"Failed to create session","api_error");Ht(g)}finally{s?.(),s=void 0}})(),()=>{l=!0,s?.()})}Lt(!0);async function c(){let K=!1;try{let C=await new Oo(w,{telemetry:!1}).getUnifiedCheckoutSession(Ge,t);if(l)return;H(C);let f=C.data.session??null;if(Le(f),!f)throw new Ft("No session data returned","api_error");let y=f.checkoutMode;if(y==="setup")throw new Ft("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(f.status==="authorized"){Lt(!1),Qe(()=>{ln.current?.(lr(f,Ge)),Sn.current?.(f.successUrl??"")});return}if(f.status==="complete"){Lt(!1),Qe(()=>{Sn.current?.(f.successUrl??"")});return}if(f.status==="expired")throw Po(f);K=!0;let g=ke??y??"full";nn(g);let E=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),G=wa(C);if(g==="auto"&&!Yt.current&&!E&&!G){Yt.current=!0;let ie=A(C);try{if(await An.current(f,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ie,sessionId:Ge||f.id}),l)return;await ie,l||Lt(!1);return}catch{if(l)return;await ie,l||Lt(!1);return}}await A(C),l||Lt(!1)}catch(F){if(l)return;K&&se({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),F instanceof Ft?!K&&!tc(F)&&Sa(w,o,ot,"NETWORK_REQUEST_FAILED","session_read"):Sa(w,o,ot,"INTERNAL_SDK_ERROR","checkout_mount");let C=F instanceof Ft?F:new Ft(F instanceof Error?F.message:"Failed to initialize checkout","api_error");Ht(C),Lt(!1)}}async function A(K){let{publishableKey:F,paypalPublishableKey:C}=Mo(K);Gt.current={publishableKey:F,paypalPublishableKey:C};let{flopay:f,paypalFlopay:y}=await Bo({publishableKey:F,paypalPublishableKey:C,billingApiUrl:w,locale:m,telemetry:o});Ie.current=f,Be(f),mt.current=y,Y(y)}return c(),()=>{l=!0}},[ke,Wt,on,vt,Qe,t]);let Ze=jn(async()=>{if(!(Nt||!D)){En(!0),rt(null);try{await pn(D,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ge||D.id})}finally{En(!1)}}},[Ge,Nt,pn,D]),mn=Ta(R),jt=wa(R),ut=bn(()=>{if(!(!R||!D||!R.data.stripe?.publishableKey))return{billingApiUrl:w}},[R,D,w]),Qt=!!(n&&!ue&&J==="buttons"&&B&&on==="full"),Rt=bn(()=>({session:D,loading:Je,error:je,checkoutMode:Et,inlineSessionDraft:un,applyInlineSessionPatch:Qt?qt:void 0,inlineSessionPatchProcessing:xn,claimPending:I}),[D,Je,je,Et,un,Qt,qt,xn,I]),rr=!!n&&J==="buttons"&&!jt&&(!$||!ut),pt=zt?X(Mn,{status:zt,errorMessage:Rn,authorized:vn}):null;if(Je){if(d)return Dt(Dn,{children:[d,pt]});if(J==="buttons"){let l=oe?.buttonsLayout?.cardButton?.borderRadius??oe?.appearance.variables?.borderRadius??8,s=c=>X("div",{style:{height:c,borderRadius:l,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Dt(Dn,{children:[Dt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[S&&s(Tr),ee&&(v||ye)&&s(Tr),ee&&s(Tr),X("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),pt]})}return Dt(Dn,{children:[Dt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[X("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),X("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),pt]})}return je?T?X(kn.Provider,{value:Rt,children:T(je)}):X(kn.Provider,{value:Rt,children:X("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:je.message})}):rr?Dt(Dn,{children:[X(kn.Provider,{value:Rt,children:X(lc,{onButtonClick:q,showPayPal:S,showStripe:ee,showApplePay:v,showGooglePay:ye,theme:ce,buttonsTheme:Se,buttonsStyles:re,cardButtonContent:le,cardBackButtonContent:Ve,cardTitleContent:Ae})}),pt]}):jt&&D&&mn?Dt(Dn,{children:[X(kn.Provider,{value:Rt,children:Dt("div",{className:de,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[sn&&X(wr,{icon:!1,children:sn}),Cn==="retrying"&&X("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Cn==="exhausted"&&Dt("div",{role:"alert",children:[X("div",{children:"PayPal is temporarily unavailable. Please try again."}),X("button",{type:"button",onClick:dn,children:"Retry PayPal"})]}),Cn!=="exhausted"&&X("div",{"aria-hidden":Cn==="retrying"?!0:void 0,style:Cn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:X(wi,{sessionId:Ge,nonce:D.clientSecret||void 0,billingApiUrl:w,email:D.customer?.email,clientId:mn.clientId,environment:mn.environment,currency:(D.currency??"usd").toUpperCase(),isSubscription:D.mode==="subscription",providerObjectType:mn.providerObjectType,onComplete:h,onErrorChange:rt,onDecline:x,onButtonClick:q,onInitializationStateChange:rn,allowAutomaticRetry:Hn===0,session:D,telemetry:o,telemetryContext:ot,onInstrument:Fe,debug:j},`${N}:paypal-init-${Hn}`)})]})}),pt]}):!$||!ut?X(Dn,{children:pt}):Et==="confirm"?Dt(Dn,{children:[X(kn.Provider,{value:Rt,children:X(_o,{flopay:$,paypalFlopay:We,options:ut,onInstrument:Fe,children:Dt("div",{className:de,children:[sn&&X("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:sn}),Re?Re({onConfirm:Ze,isProcessing:Nt}):X("button",{type:"button",onClick:Ze,disabled:Nt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Nt?"not-allowed":"pointer",opacity:Nt?.6:1},children:Nt?"Processing...":pe??"Confirm Purchase"})]})},N)}),pt]}):Dt(Dn,{children:[X(kn.Provider,{value:Rt,children:X(_o,{flopay:$,paypalFlopay:We,options:ut,onInstrument:Fe,children:ue?Dt(Dn,{children:[sn&&X("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:sn}),X(sc,{sessionId:Ge,nonce:D?.clientSecret||void 0,billingApiUrl:w,session:D,children:ue})]}):X(va,{sessionId:Ge,nonce:D?.clientSecret||void 0,email:D?.customer?.email,userId:D?.customer?.id,firstName:D?.customer?.firstName,lastName:D?.customer?.lastName,totalAmount:D?Math.round(Yl(D).total*100):0,currency:D?.currency?.toLowerCase()??"usd",onComplete:h,onError:P,onDecline:x,error:sn,onErrorChange:rt,showPayPal:S,showStripe:ee,enabledPaymentMethods:W??R?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:R?.data.stripe?.enabledPaymentMethodCountries,showApplePay:v,showGooglePay:ye,layout:J,theme:ce,buttonsTheme:Se,buttonsStyles:re,appearance:qe,cardButtonContent:le,cardBackButtonContent:Ve,cardTitleContent:Ae,onButtonClick:q,onBeforeButtonClick:B,enableAVS:te,...tt?{cardFieldOrder:tt}:{},...Me?{cardPreFormSlot:Me}:{},avsLayout:V,country:D?.customer?.country,city:D?.customer?.city,state:D?.customer?.state,onCountryChange:U,onZipChange:p,avsCheck:!!te,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ue?"custom_layout":J==="buttons"?"buttons_layout":"default_layout",className:de,directPaypal:Ta(R),isSubscription:D?.mode==="subscription",session:D,dataAttachmentPending:I,debug:j})},N)}),pt]})}function sc({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return X(Dn,{children:Ca.Children.map(o,a=>{if(!Ca.isValidElement(a))return a;let m=a.props,d={};return m.sessionId||(d.sessionId=e),!m.nonce&&t&&(d.nonce=t),m.billingApiUrl||(d.billingApiUrl=n),r?.customer&&(m.email||(d.email=r.customer.email),m.userId||(d.userId=r.customer.id),m.firstName||(d.firstName=r.customer.firstName),m.lastName||(d.lastName=r.customer.lastName)),Object.keys(d).length===0?a:Ca.cloneElement(a,d)})})}function lc({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:m,buttonsStyles:d,cardButtonContent:T,cardBackButtonContent:h,cardTitleContent:P}){let[b,x]=kt(!1),U=bn(()=>as(a),[a]),p=bn(()=>{let v=U?.buttonsLayout??Xl(m);return d?{...v,...d,cardButton:{...v.cardButton,...d.cardButton},cardFormContainer:{...v.cardFormContainer,...d.cardFormContainer},backButton:{...v.backButton,...d.backButton},backButtonIcon:{...v.backButtonIcon,...d.backButtonIcon},submitButton:{...v.submitButton,...d.submitButton},title:{...v.title,...d.title}}:v},[U,m,d]),S=U?.buttonsLayout?.cardButton?.borderRadius??U?.appearance.variables?.borderRadius??8,ee=v=>X("div",{style:{height:v,borderRadius:S,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),W=T===void 0?{boxSizing:"border-box",height:Tr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let v=p.cardInputBorder??"#e5e7eb",ye=p.cardInputBackground??"white",j=fr(h),J=fr(P);return Dt("div",{style:{backgroundColor:p.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...p.cardFormContainer},children:[Dt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Dt("button",{type:"button",onClick:()=>x(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:j?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...p.backButton},children:[X("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...p.backButtonIcon},children:X("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:X("path",{d:"M15 18l-6-6 6-6"})})}),X(hr,{content:h})]}),J?X("div",{style:{flex:1}}):X("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...p.title},children:X(Yr,{content:P})})]}),X("div",{style:{backgroundColor:ye,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:X("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Dt("div",{style:{display:"flex"},children:[X("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:X("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),X("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:X("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),X("div",{style:{backgroundColor:ye,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:X("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),X("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...p.submitButton,opacity:.5}}),X("style",{children:`
33
+ `}),io&&hn&&ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Be?-2:0},children:[ke("button",{type:"button",onClick:Ar,style:{display:"inline-flex",alignItems:"center",gap:Pa?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:[l("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:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),Ti?l("div",{style:{flex:1}}):l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...f.title},children:l(mo,{content:Ae})})]}),!io&&!Ti&&l("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:so,order:Be?-3:0,...f.title},children:l(mo,{content:Ae})}),Be&&A&&ke("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[se&&ke(fr,{children:[l("label",{htmlFor:"flopay-buyer-email",style:{display:"block",color:so,...Fr},children:"Email address"}),l("div",{style:{backgroundColor:Cr,border:`1px solid ${vr}`,borderRadius:Pt,marginTop:"0.375rem",padding:"10px"},children:l("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email",value:bt,onChange:i=>{Un.current=i.target.value,ir(i.target.value)},onBlur:To,disabled:d,required:!0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Fr}})})]}),ue&&ke(fr,{children:[l("label",{htmlFor:"flopay-buyer-name",style:{display:"block",marginTop:se?"0.75rem":void 0,color:so,...Fr},children:"Full name"}),l("div",{style:{backgroundColor:Cr,border:`1px solid ${vr}`,borderRadius:Pt,marginTop:"0.375rem",padding:"10px"},children:l("input",{className:"flopay-shared-input",id:"flopay-buyer-name",name:"name",autoComplete:"name",value:Ht,onChange:i=>{qn.current=i.target.value,sr(i.target.value)},onBlur:To,disabled:d,required:!0,"data-testid":"flopay-name",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Fr}})})]})]}),X&&l("div",{style:{order:Be?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Le,R=(z=!1)=>({backgroundColor:Cr,border:`1px solid ${Pr(z)}`,borderRadius:Pt,marginTop:"0.5rem",padding:"10px"}),N=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Fr}),he=ac(i);return ke(fr,{children:[ze(X.address_line_1,i)&&l("div",{style:R(Ut.line1),children:l("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:Rn,onChange:z=>{zt.current.addressLine1=!0,xt.current=z.target.value,_n(z.target.value)},disabled:d,required:!0,"data-testid":"flopay-address-line1",style:N()})}),ze(X.address_line_2,i)&&l("div",{style:R(),children:l("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Zn,onChange:z=>{zt.current.addressLine2=!0,tn.current=z.target.value,Jt(z.target.value)},disabled:d,"data-testid":"flopay-address-line2",style:N()})}),(ze(X.city,i)||ze(X.state,i))&&ke("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[ze(X.city,i)&&l("div",{style:{flex:1,backgroundColor:Cr,borderTop:`1px solid ${Pr(Ut.city)}`,borderRight:`1px solid ${Pr(Ut.city)}`,borderBottom:`1px solid ${Pr(Ut.city)}`,borderLeft:`1px solid ${Pr(Ut.city)}`,padding:"10px",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,...ze(X.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Pt}},children:l("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:cn,onChange:z=>{zt.current.city=!0,un.current=z.target.value,dn(z.target.value)},disabled:d,required:!0,"data-testid":"flopay-city",style:N()})}),ze(X.state,i)&&l("div",{style:{flex:1,backgroundColor:Cr,border:`1px solid ${Pr(Ut.state)}`,padding:"10px",borderTopRightRadius:Pt,borderBottomRightRadius:Pt,...ze(X.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:Pt}},children:he?ke("select",{id:"flopay-billing-state",name:"billing-state",value:Ft,onChange:z=>{zt.current.state=!0,pn.current=z.target.value,vn(z.target.value)},disabled:d,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...N(),cursor:"pointer"},children:[l("option",{value:"",children:ys(i)}),he.map(z=>l("option",{value:z.code,children:z.name},z.code))]}):l("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:ys(i),autoComplete:"billing address-level1",value:Ft,onChange:z=>{zt.current.state=!0,pn.current=z.target.value,vn(z.target.value)},disabled:d,required:!0,"data-testid":"flopay-state",style:N()})})]}),(ze(X.country,i)||ze(X.postal_code,i))&&ke("div",{style:{display:"flex",flexDirection:te==="column"?"column":"row",gap:te==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[ze(X.country,i)&&l("div",{style:{flex:te==="row"?1:void 0,backgroundColor:Cr,borderTop:`1px solid ${vr}`,borderRight:`1px solid ${vr}`,borderBottom:`1px solid ${vr}`,borderLeft:`1px solid ${vr}`,padding:"10px",...te==="row"&&ze(X.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,borderRight:"none"}:{borderRadius:Pt}},children:l("select",{id:"flopay-billing-country",name:"billing-country",value:Le,onChange:z=>{zt.current.country=!0,_t.current=z.target.value,Wt(z.target.value),Je?.(z.target.value),pn.current="",vn("")},disabled:d,autoComplete:"billing country","data-testid":"flopay-country",style:{...N(),cursor:"pointer"},children:tc.map(z=>ke("option",{value:z.code,children:[z.flag," ",z.name]},z.code))})}),ze(X.postal_code,i)&&l("div",{style:{flex:te==="row"?1:void 0,backgroundColor:Cr,border:`1px solid ${tl}`,padding:"10px",...te==="row"&&ze(X.country,i)?{borderRadius:"0",borderTopRightRadius:Pt,borderBottomRightRadius:Pt}:{borderRadius:Pt}},children:l("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Ua(Le),autoComplete:"billing postal-code",value:wt,onChange:z=>{zt.current.zip=!0,ot.current=z.target.value,Ot(z.target.value),We?.(z.target.value)},onBlur:()=>Zt(!0),disabled:d,required:yn.required,"aria-invalid":Lo||void 0,"aria-describedby":Lo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:N()})})]}),Lo&&l("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:ba,...Fr,fontSize:"0.75rem"},children:yn.empty?`${Ua(i)} is required`:Ic(i)})]})})()}),Be&&Ye&&l("div",{style:{order:-2,width:"100%"},children:Ye}),Be&&il,B&&l(Kr,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:B})]}),Oo={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"},Ni=i=>St?!ve||!Hn?l("pre",{"data-testid":i,style:Oo,children:"FloPay/DirectPayPal-debug - not enabled"}):l("pre",{"data-testid":i,style:Oo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ve}`,` directPaypalConfigured=${Hn}`,` inAppBrowserDetected=${String(No)}`,` shouldRenderDirectPayPal=${no}`,` shouldRenderStripePayPal=${ro}`,` hasPaypalStripeInstance=${!!bn}`].join(`
34
+ `)}):null,Di=i=>St?!H||!ge?l("pre",{"data-testid":i,style:Oo,children:"FloPay/Stripe-debug - not enabled"}):l("pre",{"data-testid":i,style:Oo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${H}`,` currency=${we}`,` amountInCents=${Qr}`,` enabledPaymentMethods: ${JSON.stringify(P??[])}`,` enabledPaymentMethodsProvided=${eo}`,` hasEnabledMethods=${Ao}`,` expressMethods: ${JSON.stringify(Mo)}`,` walletExpressMethods: ${JSON.stringify(Bo)}`,` paymentElementMethods: ${JSON.stringify(to)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Fo)}`,` hasStripeInstance=${!!ge}`,` shouldRenderWallets=${oo}`,` shouldRenderPaymentElement=${ao}`].join(`
35
+ `)}):null,Li=xe==="apm-expanding"||xe==="apm-form"||xe==="apm-collapsing",zo=xe==="apm-expanding"?`flopay-card-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="apm-collapsing"?`flopay-card-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Uo=Tt?{...ma,paymentMethodTypes:[Tt]}:null;if(oe==="buttons"){let i=xe==="buttons"||xe==="expanding"||xe==="apm-expanding",R=xe==="expanding"||xe==="card"||xe==="collapsing",N=De===void 0?{boxSizing:"border-box",height:ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"},he=xe==="expanding"||xe==="apm-expanding"?`flopay-buttons-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:xe==="collapsing"||xe==="apm-collapsing"?`flopay-buttons-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,z=xe==="expanding"?`flopay-card-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="collapsing"?`flopay-card-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return ke("form",{onSubmit:ga,className:M,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:B,authorized:xn}),ke("div",{style:{display:"grid"},children:[ke("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!he?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!he?Sc:{},...he?{animation:he,pointerEvents:"none"}:{}},children:[Ni("flopay-direct-paypal-gate-debug"),Di("flopay-stripe-gate-debug"),no&&x&&ke(fr,{children:[V&&l("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."}),l(Jo,{sessionId:e,nonce:t,billingApiUrl:ne,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,clientId:x.clientId,environment:x.environment,currency:we.toUpperCase(),isSubscription:K,providerObjectType:x.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:pe,onDecline:s,onTechnicalFailure:Mr,onButtonClick:J,runBeforeButtonClick:Dn,isProcessing:d,onLoadStateChange:ya,onInitializationStateChange:fa,session:I??null,existingOrderId:V?.orderId,debug:St},V?.orderId??"fresh")]}),ro&&l(_r,{stripe:bn,options:di,children:l(Ss,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,isProcessing:d,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:fi,placeholderBorderRadius:Sr})}),oo?l(_r,{stripe:ge,options:ci,children:l(ws,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,intentKind:$>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:hi,placeholderBorderRadius:Sr})}):Si?l("div",{style:{height:ra,borderRadius:Sr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ao&&l(ks,{sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,paymentElementMethods:Fo,stripeInstance:ge,paymentElementBaseOptions:ma,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,runBeforeButtonClick:Dn,onLoadStateChange:vi,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,onExpandApm:Fn,expandedApmMethod:Tt,themeId:Ce,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Sr}}),Be&&l("button",{type:"button",onClick:async()=>{d||!(await Dn("card")).proceed||(J?.("card"),er())},disabled:d,style:{width:"100%",...N,...f.cardButton,...Ha({themeBundle:h,resolvedPrimaryColor:wr,resolvedBorderRadius:Pt,submitButtonStyle:f.submitButton,explicitPrimaryColor:sn?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:d?"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:d?.6:1},onMouseEnter:Re=>{!d&&(h||sn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=ol)},onMouseLeave:Re=>{(h||sn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=wr)},onMouseDown:Re=>{Re.currentTarget.style.transform="scale(0.985)"},onMouseUp:Re=>{Re.currentTarget.style.transform="scale(1)"},children:l(Dr,{content:De})}),B&&xe==="buttons"&&l(Kr,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:B})]}),Be&&R&&l("div",{style:{gridArea:"1 / 1",...z?{animation:z}:{},...xe==="collapsing"?{pointerEvents:"none"}:{}},children:Fi}),H&&Li&&Tt&&Uo&&ge&&l("div",{style:{gridArea:"1 / 1",...zo?{animation:zo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ke("div",{style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca},children:[ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ke("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Kn,style:{display:"inline-flex",alignItems:"center",gap:Pa?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:[l("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:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:so,paddingRight:80,...f.title},children:`Pay with ${xr(Tt)}`})]}),l(_r,{stripe:ge,options:Uo,children:l($a,{method:Tt,sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,onDecline:s,onCancel:Kn,runBeforeButtonClick:Dn,onButtonClick:J,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,errorText:B})},Tt)]})})]})]})}return Li&&Tt&&Uo&&ge&&H?ke("form",{onSubmit:ga,className:M,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:B,authorized:xn}),l("div",{style:{...zo?{animation:zo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ke("div",{style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca},children:[ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ke("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Kn,style:{display:"inline-flex",alignItems:"center",gap:Pa?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:[l("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:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:so,paddingRight:80,...f.title},children:`Pay with ${xr(Tt)}`})]}),l(_r,{stripe:ge,options:Uo,children:l($a,{method:Tt,sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,onDecline:s,onCancel:Kn,runBeforeButtonClick:Dn,onButtonClick:J,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,errorText:B})},Tt)]})})]}):ke("form",{onSubmit:ga,className:M,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:B,authorized:xn}),ke("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ni("flopay-direct-paypal-gate-debug-default"),Di("flopay-stripe-gate-debug-default"),no&&x&&ke(fr,{children:[V&&l("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."}),l(Jo,{sessionId:e,nonce:t,billingApiUrl:ne,email:k.email,clientId:x.clientId,environment:x.environment,currency:we.toUpperCase(),isSubscription:K,providerObjectType:x.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:pe,onDecline:s,onTechnicalFailure:Mr,onButtonClick:J,runBeforeButtonClick:Dn,isProcessing:d,onLoadStateChange:ya,onInitializationStateChange:fa,session:I??null,existingOrderId:V?.orderId,debug:St},V?.orderId??"fresh")]}),ro&&l(_r,{stripe:bn,options:di,children:l(Ss,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,isProcessing:d,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:fi,placeholderBorderRadius:Sr})}),oo&&l(_r,{stripe:ge,options:ci,children:l(ws,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,intentKind:$>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:hi,placeholderBorderRadius:Sr})}),ao&&l(ks,{sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ne,paymentElementMethods:Fo,stripeInstance:ge,paymentElementBaseOptions:ma,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,runBeforeButtonClick:Dn,onLoadStateChange:vi,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,themeId:Ce,onExpandApm:Fn,expandedApmMethod:Tt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Sr}})]}),Be&&(Xs||Js||Zs)&&ke("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[l("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),l("span",{children:"or pay with card"}),l("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Be&&Fi]})}import{Fragment as Xn,jsx as re,jsxs as Vt}from"react/jsx-runtime";var Gr=44,oi="flopay_checkout_saved_payment_resume",ca=new Map,sa=new Map;function Fs(e,t){t.settled&&t.consumers===0&&ca.get(e)===t&&ca.delete(e)}function zc(e,t,n){let r=sa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};sa.set(e,a);let c=()=>{sa.get(e)===a&&sa.delete(e)};return o.then(c,c),o}function wo(e){return new Promise(t=>setTimeout(t,e))}function la(e,t,n){let r=Yo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Os,enabled:t!==!1});return r.beginCheckout(n),r}function ko(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Wa(e,t,n,r,o){let a=la(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),ko(a)}function Uc(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 ni(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Ja(e){return!e||e.data.stripe?.publishableKey?!1:!!ni(e)?.clientId}function ar(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function qc(){if(!ar())return null;try{let e=window.sessionStorage.getItem(oi);return e?JSON.parse(e):null}catch{return null}}function Ns(e){if(ar())try{window.sessionStorage.setItem(oi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Xa(){if(ar())try{window.sessionStorage.removeItem(oi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ai=":idempotency-key";function zs(e,t){if(!ar())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 Za(e,t,n,r){if(ar())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 ri(e,t){if(ar())try{zs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Us(e,t){if(!ar())return null;try{let n=window.sessionStorage.getItem(e+ai);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 Qa(e,t,n){if(ar())try{window.sessionStorage.setItem(e+ai,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ei(e,t){if(ri(e,t),!!ar())try{Us(e,t)&&window.sessionStorage.removeItem(e+ai)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function $c(){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 Ds(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 jc(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function ti(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Io(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=>ti(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ti(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ti(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Kc(e,t=!1){let n=Io(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 Vc(e,t){if(!e?.customer||!e.products)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=Lc(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Bc(t.items,t.subscriptions)).map(b=>({type:b.type,code:b.code??b.providerItemId??b.providerPlanId??"",quantity:b.quantity??1,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount??null,currency:(b.currency??o).toUpperCase()})).sort((b,g)=>`${b.code}:${b.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),c=e.products.map(b=>({type:b.type,code:b.code??"",quantity:b.quantity??1,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount??null,currency:(b.currency??e.currency).toUpperCase()})).sort((b,g)=>`${b.code}:${b.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(a.length!==c.length)return!1;for(let b=0;b<a.length;b+=1){let g=a[b],m=c[b];if(g.code!==m.code||g.type!==void 0&&g.type!==m.type||g.quantity!==m.quantity||g.totalAmount!==m.totalAmount||g.overrideAmount!==m.overrideAmount||g.currency!==m.currency)return!1}let s=[...t.couponCodes??[]].sort(),S=[...e.coupons??[]].sort();return s.length===S.length&&s.every((b,g)=>b===S[g])}function ii({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:c,loading:s,error:S,onComplete:b,onError:g,onInstrument:m,onDecline:M,onCountryChange:D,onZipChange:u,showPayPal:w=!0,showStripe:ve=!0,enabledPaymentMethods:H,showApplePay:P=!0,showGooglePay:fe=!0,debug:Q=!1,layout:ce,theme:oe,buttonsTheme:Ce,buttonsStyles:He,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De,showSecurityFooter:Te,onButtonClick:Ae,onBeforeButtonClick:ee,enableAVS:J,cardFieldOrder:L,cardPreFormSlot:me,avsLayout:et,className:Ue,initialErrorMessage:Ye=null,children:te,checkoutMode:T,confirmLabel:ae,renderConfirmButton:Fe,onSessionCompleted:ie}){let j=Nc(r),_e=En(()=>Ls(oe),[oe]),Je=a??_e?.appearance,We=n?"embedded_checkout":"standard_checkout",Se=te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",[G,Y]=Et(null),[$,we]=Et(null),Me=At(null),[x,K]=Et(null),I=At(null),[C,nt]=Et(null),St=En(()=>n?Io(n):"",[n]),de=n?`create:${St}`:`session:${e??""}`,ct=C?.gateways?.stripe?"stripe":C?.gateways?.paypal?"paypal":void 0,it=At(new Set),rt=At(de),je=At(de);Vo(()=>{je.current=de,rt.current!==de&&(rt.current=de,it.current.clear())},[de]);let y=Wn(_=>{if(je.current===de){if(xa.has(_.name)){if(it.current.has(_.name))return;it.current.add(_.name)}tt(()=>m?.(_))}},[de,m]),U=jr(y,de),Xe=At(!1),dt=Wn(_=>{if(Xe.current)return;let E=_.gateway||!ct?_:{..._,gateway:ct};y(E)},[y,ct]);Jn(()=>{U({class:"lifecycle",name:"checkout.mount"})},[U]);let[Mt,Bt]=Et(e??""),W=e??Mt,Le=n?"":W,[Wt,wt]=Et(!0),[Ot,Rn]=Et(null),[_n,Zn]=Et("full"),[Jt,cn]=Et(!1),[dn,Ft]=Et(Ye),[vn,bt]=Et(null),[ir,Ht]=Et(null),[sr,Nt]=Et(!1),[zn,ot]=Et(void 0),[_t,xt]=Et(""),[tn,un]=Et(!1),[pn,Un]=Et(!1),[qn,zt]=Et(!1),X=At(0),Pn=At(void 0),[xn,Qn]=Et("loading"),[br,Tr]=Et(0),Tn=At(!1),mn=At(!1),Be=At(!1),Xt=At(null),Dt=En(()=>({checkoutMode:T??_n,layout:te?"unknown":ce==="buttons"?"buttons":"embedded"}),[T,te,_n,ce]),$n=At(b);$n.current=b;let v=At(g);v.current=g;let ut=At(M);ut.current=M,Jn(()=>{jt($)?.setCheckoutContext(Dt),x&&x!==$&&jt(x)?.setCheckoutContext(Dt)},[$,x,Dt]);let qe=At(ie);qe.current=ie;let yn=Wn(_=>{Qn(_),!(_!=="exhausted"||Be.current)&&(Be.current=!0,v.current?.(new Kt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ze=Wn(()=>{Qn("retrying"),Tr(_=>_+1)},[]);Jn(()=>{Qn("loading"),Tr(0),Be.current=!1},[W]),Jn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Os,checkout_type:We,checkout_layout:Se,billing_api_url:j})},[Se,We,j]);let Ut=En(()=>n?Io(n,!0):"",[n]),lr=En(()=>_t===Ut?zn:void 0,[zn,_t,Ut]),jn=En(()=>n?ka(n,lr):void 0,[n,lr]),Cn=T??jn?.checkoutMode??"full",Zt=En(()=>jn?{...jn,checkoutMode:Cn}:void 0,[jn,Cn]);Jn(()=>{ot(void 0),xt(Ut),Pn.current=void 0,zt(!1)},[Ut]),Jn(()=>{Ft(Ye)},[Ye]);let fn=Wn((_,E,V)=>{tt(()=>{ut.current?.($t(_,E,V))})},[tt]),gn=Wn(async(_,E)=>{Ft(null),Ht(null),Nt(!1),bt("processing");let V=E?.sessionId??_.id,Z=_.gateways?.stripe?"stripe":_.gateways?.paypal?"paypal":void 0,$e=Me.current??I.current,ne=jt($e),B=$e?null:la(j,o,Dt),h={log:q=>{ne?ne.log(q):B?.log(q)},error:q=>{ne?ne.error(q):B?.error(q)},terminal:q=>{ne?ne.terminal(q):B?.terminal(q)},performance:q=>{ne?ne.performance(q):B?.performance(q)},now:()=>ne?.now()??B?.now()??0,elapsed:q=>ne?.elapsed(q)??Math.max(0,(B?.now()??q)-q)},f=h.now(),O=!!(E?.initialAutoProcessingError||E?.initialAutoProcessingPending),pt=!1,vt,d=()=>{pt||(pt=!0,O=!0,vt=h.now(),h.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},p=!1,k=()=>{p||(p=!0,h.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),h.performance({stage:"processing",durationMs:h.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved"}),vt!==void 0&&h.performance({stage:"recovery",durationMs:h.elapsed(vt),durationMode:"machine",paymentMethodCategory:"saved"}))};h.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Xe.current=!0;try{h.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Xe.current=!1}U({class:"lifecycle",name:"payment.processing.started",provider:Z}),O&&d();let Ee;try{let q=ls(E?.initialAutoProcessingError),F;if(q)d(),q.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&Ns({sessionId:V,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),F=await ea(q,{flopay:Me.current,paypalFlopay:I.current,attempt3DS:E?.attempt3DS,billingApiUrl:j,sessionId:V,session:_,telemetry:!1}),q.type==="paypal_redirect_required"&&Xa();else if(E?.initialAutoProcessingPending){let se=(await new ia(j,{telemetry:!1}).waitForCheckoutSessionCompletion(E.initialAutoProcessingPending.sessionId,{initialDelayMs:E.initialAutoProcessingPending.retryAfterMs})).data.session;if(!zr(se))throw $o(se);F=kr(se,V)}else{if(E?.initialAutoProcessingError)throw yr(E.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:E.initialAutoProcessingError.checkoutMethod});if(E?.fromCreateSession)return E?.fallbackToFull&&(Zn("full"),Ds("full")),!1;{let Ge=await Hr({billingApiUrl:j,sessionId:V,session:_,telemetry:!1});Ge.type==="success"?F=Ge.result:(d(),Ge.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&Ns({sessionId:V,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),F=await ea(Ge,{flopay:Me.current,paypalFlopay:I.current,attempt3DS:E?.attempt3DS,billingApiUrl:j,sessionId:V,session:_,telemetry:!1}),Ge.type==="paypal_redirect_required"&&Xa())}}V&&Vr(V),k(),O&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),h.terminal({outcome:F.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Nt(F.status==="authorized"),bt("success"),await wo(1200),Ee=()=>$n.current?.(F)}catch(q){let F=Rr(q),Ge=F.checkoutMethod??Po;Ft(F.message),Ht(F.message),Nt(!1),E?.fallbackToFull&&(h.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Zn("full"),Ds("full")),k();let Qe=F.statusCode!==void 0?Oc(F.statusCode,"unknown"):void 0,se=Qe==="4xx"?{requestCategory:"process_payment",statusClass:Qe}:{},ue=Qe===void 0||Qe==="4xx";if(ue&&(F.telemetryOutcome==="payment_declined"||!!(F.declineCode||F.code?.toLowerCase().includes("declin"))))h.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...se});else if(ue&&(F.telemetryOutcome==="validation_rejected"||F.type==="validation_error"))h.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...se});else{let st=Ms(q,O?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Lt=F.telemetryRequestCategory??"process_payment";Xe.current=!0;try{h.error({...st,...F.telemetryFailureCategory?{failureCategory:F.telemetryFailureCategory}:{},stage:O?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Lt})}finally{Xe.current=!1}U({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Lt,provider:Z})}return tt(()=>v.current?.(F)),fn(Ge,F,{code:F.code,declineCode:F.declineCode}),bt("error"),await Promise.allSettled([wo(1500),E?.ensureProvidersReady?E.ensureProvidersReady():Promise.resolve()]),O&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{k(),B&&ko(B),bt(null),Ht(null)}return tt(Ee),!0},[fn,U,tt,Rr,j,o,Dt]);Jn(()=>{if(typeof window>"u"||mn.current)return;let _=new URLSearchParams(window.location.search),E=_.get("payment_intent_client_secret");if(!E)return;let V=qc();V&&(mn.current=!0,(async()=>{let Z,$e=0;Ft(null),Ht(null),bt("processing"),cn(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new Kt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ne,paypalFlopay:B}=await na({publishableKey:V.publishableKey,paypalPublishableKey:V.paypalPublishableKey,billingApiUrl:j,locale:c,telemetry:o});Z=jt(B??ne),$e=Z?.now()??0,Z?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let h=(B??ne)?.getRawProvider();if(!h)throw Object.assign(new Kt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:f,error:O}=await h.retrievePaymentIntent(E);if(O)throw Object.assign(new Kt(O.message??"Failed to retrieve PayPal payment status.","api_error",{code:O.code}),{checkoutMethod:"paypal"});let pt=Vi(f?.status);if(!f||pt==="failed")throw Object.assign(new Kt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let vt=typeof f.payment_method=="string"?f.payment_method:f.payment_method?.id,d=pt;if(V.sessionId){let Ee=(await new ia(j,{telemetry:!1}).getUnifiedCheckoutSession(V.sessionId)).data.session;if(Ee&&Ee.status!=="complete"){let q=await Hr({billingApiUrl:j,sessionId:V.sessionId,session:Ee,telemetry:!1,tokenizedData:{id:vt??f.id,type:"card",threeDSecureActionResultTokenId:f.id,isPaypal:!0}});if(q.type!=="success")throw Object.assign(new Kt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});d=q.result.status}}V.sessionId&&Vr(V.sessionId),Z?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.performance({stage:"redirect_resume",durationMs:Z.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),bt("success"),await wo(1200),tt(()=>$n.current?.({status:d,paymentIntentId:f.id,paymentMethodId:vt,checkoutMethod:"paypal"}))}catch(ne){let B=Rr(ne),h=B.checkoutMethod??"paypal",f=!!(B.declineCode||B.code?.toLowerCase().includes("declin"));if(Z)Z.performance({stage:"redirect_resume",durationMs:Z.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),f?Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Z.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(f){let O=la(j,o,Dt);O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ko(O)}else Wa(j,o,Dt,"REDIRECT_RESUME_FAILED","redirect_resume");Ft(B.message),Ht(B.message),tt(()=>v.current?.(B)),fn(h,B,{code:B.code,declineCode:B.declineCode}),bt("error"),await wo(1500)}finally{Xa(),$c(),bt(null),Ht(null),cn(!1)}})())},[fn,tt,c,Rr,j,o]);let xe=At(null),kt=En(()=>Zt?Io(Zt):"",[Zt]),Tt=At(Zt);Tt.current=Zt,Jn(()=>{Bt(e??"")},[e]),Jn(()=>{Tn.current=!1,Ft(Ye),Ht(null),Nt(!1),bt(null)},[kt,Ye,e]);async function An(_,E,V){let Z=la(j,o,Dt),$e=new ia(j,{telemetry:!1}),ne=!1;try{let B=_.idempotencyKey!==void 0?Bs(_.idempotencyKey):void 0,h=zs(E,V),f=Us(E,V);h?.canonicalIdentity===V&&f&&f.canonicalIdentity===void 0&&(Qa(E,V,f.idempotencyKey),f={...f,canonicalIdentity:V});let O=B??(f?.canonicalIdentity===V?f.idempotencyKey:void 0),pt,vt=!1;Z.log({name:h?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let d=h?.sid??null,p=null,k,Ee,q=!1;if(d)try{p=await $e.getUnifiedCheckoutSession(d,h?.nonce),h&&h.canonicalIdentity===void 0&&(Vc(p.data.session,_)?(Za(E,V,d,h.nonce??p.data.session?.clientSecret),f&&f.canonicalIdentity===void 0&&(Qa(E,V,f.idempotencyKey),O??(O=f.idempotencyKey))):(ei(E,V),f=null,O=B,d=null,p=null));let F=p?.data.session?.status;if(d&&p&&F==="complete"){if(Fa(d))return{sid:d,result:p};ei(E,V),d=null,p=null,vt=!0}}catch{Z.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),h?.canonicalIdentity===void 0?(ei(E,V),O=B):ri(E,V),d=null}if(!d){!B&&(vt||!O)&&(O=Bs(),pt=O),O&&Qa(E,V,O);let F=Z.now(),Ge=0;Z.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Qe={..._,idempotencyKey:O,avsCheck:!!J,avsConfig:typeof J=="object"?J:void 0,checkoutType:"embedded_checkout",checkoutLayout:te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Qe,Ac,{configurable:!1,enumerable:!1,value:{onAttempt:A=>{Ge=Math.max(Ge,A)}}});let se=()=>{Z.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),Z.performance({stage:"session_create",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx"})},ue=A=>{let le=Ms(A,"CHECKOUT_SESSION_CREATE_FAILED","unknown");Z.performance({stage:"session_create",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:le.statusClass}),A instanceof Kt&&A.type==="validation_error"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):le.statusClass==="4xx"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(Z.error({...le,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),U({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Fc(Qe)){let A=await $e.createDetachedSession(Qe);A.claimed.catch(()=>{}),p=A.shell,d=A.sessionId,Ee=A.claim,q=!Qe.account.email?.trim(),k=A.claimed.then(le=>{let st=le.data.session?.id??A.sessionId;return st&&Za(E,V,st,le.data.session?.clientSecret??A.nonce),se(),le},le=>{throw ri(E,V),ue(le),le}).finally(()=>ko(Z)),k.catch(()=>{}),ne=!0,Z.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Z.performance({stage:"session_shell",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx",paymentMethodCategory:"card"})}else p=await $e.createAndFetchSession(Qe),se()}catch(A){throw ue(A),A}d=p.data.session?.id??d??"",d&&!k&&Za(E,V,d,p.data.session?.clientSecret)}return{sid:d??"",result:p,sdkGeneratedIdempotencyKey:pt,...k?{claimed:k}:{},...Ee?{claim:Ee}:{},...q?{claimRequiresIdentity:!0}:{}}}finally{ne||ko(Z)}}let hn=Wn(async(_,E)=>{let V=Tt.current;if(!V)throw new Kt("createSession is required to bootstrap checkout.","validation_error");let Z=ka(V,_),$e=Io(Z),ne=Kc(Z),B=ca.get($e);if(!B){let O={canonicalIdentity:$e,promise:An(Z,ne,$e),consumers:0,settled:!1};B=O,ca.set($e,O);let pt=()=>{O.settled=!0,Fs($e,O)};O.promise.then(pt,pt)}B.consumers+=1;let h=!1,f=()=>{h||(h=!0,B.consumers-=1,Fs($e,B))};E?.(f);try{let O=await B.promise;xe.current=$e,_&&(xt(Ut),ot(Qe=>$i(Qe,_)));let{sid:pt,result:vt,claimed:d,claim:p,claimRequiresIdentity:k}=O;if(Pn.current=p,zt(k===!0),Y(vt),vt.data.session&&nt(vt.data.session),pt&&Bt(pt),d){X.current+=1;let Qe=X.current;Un(!0),d.then(se=>{X.current===Qe&&(Y(se),se.data.session&&nt(se.data.session),Un(!1),zt(!1))},se=>{X.current===Qe&&(Un(!1),zt(!1),Rn(se instanceof Kt?se:new Kt(se instanceof Error?se.message:"Failed to create session","api_error")))})}else X.current+=1,Un(!1),zt(!1);let{publishableKey:Ee,paypalPublishableKey:q}=ta(vt),{flopay:F,paypalFlopay:Ge}=await na({publishableKey:Ee,paypalPublishableKey:q,billingApiUrl:j,locale:c,telemetry:o});return Me.current=F,we(F),I.current=Ge,K(Ge),wt(!1),O}catch(O){throw xe.current===$e&&(xe.current=null),O}finally{E||f()}},[Ut,c,j,o,Dt]),Mn=At(gn);Mn.current=gn;let Bn=At(hn);Bn.current=hn;let qt=Wn(async _=>{if(!jc(_)||tn)return{sessionId:Mt,session:C};un(!0);try{let E=await hn(_);return{sessionId:E.sid,session:E.result.data.session??null}}finally{un(!1)}},[hn,tn,Mt,C]),on=Wn(async _=>{let E=Pn.current;E&&await E(_)},[]);Jn(()=>{let _=!1,E;if(Rn(null),kt){let $e=Tt.current;return Zn(Cn),wt(!1),xe.current===kt?()=>{_=!0}:(nt(ji($e,T)),(async()=>{let ne=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=Cn==="auto"&&!Tn.current&&!ne;B&&(Ft(null),Ht(null),bt("processing"));try{let h=await Bn.current(void 0,vt=>{E=vt}),f=h.result.data.session??null;Xt.current=ta(h.result);let O=Ja(h.result),pt=Fa(h.sid||f?.id);if(!_&&B&&f&&!O&&!pt){Tn.current=!0,await zc(kt,h.sdkGeneratedIdempotencyKey,()=>Mn.current(f,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:h.result.autoProcessingError,initialAutoProcessingPending:h.result.autoProcessingPending,autoProcessingAttempted:h.result.autoProcessingAttempted,sessionId:h.sid||f.id}));return}!_&&B&&((O||pt)&&(Tn.current=!0),bt(null),Ht(null))}catch(h){if(_)return;let f=h instanceof Kt||typeof h=="object"&&h!==null&&"code"in h?h.code:void 0;if(B&&f==="session_auto_completed"){Tn.current=!0,bt("success"),await wo(1200),_||(tt(()=>{$n.current?.({status:"succeeded"})}),bt(null),Ht(null));return}B&&(bt(null),Ht(null));let O=h instanceof Kt?h:new Kt(h instanceof Error?h.message:"Failed to create session","api_error");Rn(O)}finally{E?.(),E=void 0}})(),()=>{_=!0,E?.()})}wt(!0);async function V(){let $e=!1;try{let B=await new ia(j,{telemetry:!1}).getUnifiedCheckoutSession(W,t);if(_)return;Y(B);let h=B.data.session??null;if(nt(h),!h)throw new Kt("No session data returned","api_error");let f=h.checkoutMode;if(f==="setup")throw new Kt("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(h.status==="authorized"){wt(!1),tt(()=>{$n.current?.(kr(h,W)),qe.current?.(h.successUrl??"")});return}if(h.status==="complete"){wt(!1),tt(()=>{qe.current?.(h.successUrl??"")});return}if(h.status==="expired")throw qo(h);$e=!0;let O=T??f??"full";Zn(O);let pt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),vt=Ja(B);if(O==="auto"&&!Tn.current&&!pt&&!vt){Tn.current=!0;let d=Z(B);try{if(await Mn.current(h,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>d,sessionId:W||h.id}),_)return;await d,_||wt(!1);return}catch{if(_)return;await d,_||wt(!1);return}}await Z(B),_||wt(!1)}catch(ne){if(_)return;$e&&U({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ne instanceof Kt?!$e&&!Uc(ne)&&Wa(j,o,Dt,"NETWORK_REQUEST_FAILED","session_read"):Wa(j,o,Dt,"INTERNAL_SDK_ERROR","checkout_mount");let B=ne instanceof Kt?ne:new Kt(ne instanceof Error?ne.message:"Failed to initialize checkout","api_error");Rn(B),wt(!1)}}async function Z($e){let{publishableKey:ne,paypalPublishableKey:B}=ta($e);Xt.current={publishableKey:ne,paypalPublishableKey:B};let{flopay:h,paypalFlopay:f}=await na({publishableKey:ne,paypalPublishableKey:B,billingApiUrl:j,locale:c,telemetry:o});Me.current=h,we(h),I.current=f,K(f)}return V(),()=>{_=!0}},[T,kt,Cn,Le,tt,t]);let an=Wn(async()=>{if(!(Jt||!C)){cn(!0),Ft(null);try{await gn(C,{attempt3DS:!0,fallbackToFull:!0,sessionId:W||C.id})}finally{cn(!1)}}},[W,Jt,gn,C]),er=ni(G),Ar=Ja(G),Fn=En(()=>{if(!(!G||!C||!G.data.stripe?.publishableKey))return{billingApiUrl:j}},[G,C,j]),Kn=!!(n&&!te&&ce==="buttons"&&ee&&Cn==="full"),Qt=En(()=>({session:C,loading:Wt,error:Ot,checkoutMode:_n,inlineSessionDraft:Zt,applyInlineSessionPatch:Kn?qt:void 0,inlineSessionPatchProcessing:tn,claimPending:pn,claimRequiresIdentity:qn}),[C,Wt,Ot,_n,Zt,Kn,qt,tn,pn,qn]),at=!!n&&ce==="buttons"&&!Ar&&(!$||!Fn),Yt=vn?re(Yn,{status:vn,errorMessage:ir,authorized:sr}):null;if(Wt){if(s)return Vt(Xn,{children:[s,Yt]});if(ce==="buttons"){let _=_e?.buttonsLayout?.cardButton?.borderRadius??_e?.appearance.variables?.borderRadius??8,E=V=>re("div",{style:{height:V,borderRadius:_,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Vt(Xn,{children:[Vt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[w&&E(Gr),ve&&(P||fe)&&E(Gr),ve&&E(Gr),re("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Yt]})}return Vt(Xn,{children:[Vt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[re("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),re("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Yt]})}return Ot?S?re(Ln.Provider,{value:Qt,children:S(Ot)}):re(Ln.Provider,{value:Qt,children:re("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ot.message})}):at?Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Yc,{onButtonClick:Ae,showPayPal:w,showStripe:ve,showApplePay:P,showGooglePay:fe,theme:oe,buttonsTheme:Ce,buttonsStyles:He,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De})}),Yt]}):Ar&&C&&er?Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:Vt("div",{className:Ue,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[dn&&re(Kr,{icon:!1,children:dn}),xn==="retrying"&&re("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),xn==="exhausted"&&Vt("div",{role:"alert",children:[re("div",{children:"PayPal is temporarily unavailable. Please try again."}),re("button",{type:"button",onClick:Ze,children:"Retry PayPal"})]}),xn!=="exhausted"&&re("div",{"aria-hidden":xn==="retrying"?!0:void 0,style:xn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:re(ts,{sessionId:W,nonce:C.clientSecret||void 0,billingApiUrl:j,email:C.customer?.email,clientId:er.clientId,environment:er.environment,currency:(C.currency??"usd").toUpperCase(),isSubscription:C.mode==="subscription",providerObjectType:er.providerObjectType,onComplete:b,onErrorChange:Ft,onDecline:M,onButtonClick:Ae,onInitializationStateChange:yn,allowAutomaticRetry:br===0,session:C,telemetry:o,telemetryContext:Dt,onInstrument:dt,debug:Q},`${de}:paypal-init-${br}`)})]})}),Yt]}):!$||!Fn?re(Xn,{children:Yt}):_n==="confirm"?Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Xo,{flopay:$,paypalFlopay:x,options:Fn,onInstrument:dt,children:Vt("div",{className:Ue,children:[dn&&re("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:dn}),Fe?Fe({onConfirm:an,isProcessing:Jt}):re("button",{type:"button",onClick:an,disabled:Jt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Jt?"not-allowed":"pointer",opacity:Jt?.6:1},children:Jt?"Processing...":ae??"Confirm Purchase"})]})},de)}),Yt]}):Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Xo,{flopay:$,paypalFlopay:x,options:Fn,onInstrument:dt,children:te?Vt(Xn,{children:[dn&&re("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:dn}),re(Hc,{sessionId:W,nonce:C?.clientSecret||void 0,billingApiUrl:j,session:C,children:te})]}):re(Ya,{sessionId:W,nonce:C?.clientSecret||void 0,email:C?.customer?.email||Zt?.account?.email,userId:C?.customer?.id||Zt?.account?.userId,firstName:C?.customer?.firstName||Zt?.account?.firstName,lastName:C?.customer?.lastName||Zt?.account?.lastName,totalAmount:C?Math.round(Mc(C).total*100):0,currency:C?.currency?.toLowerCase()??"usd",onComplete:b,onError:g,onDecline:M,error:dn,onErrorChange:Ft,showPayPal:w,showStripe:ve,enabledPaymentMethods:H??G?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:G?.data.stripe?.enabledPaymentMethodCountries,showApplePay:P,showGooglePay:fe,layout:ce,theme:oe,buttonsTheme:Ce,buttonsStyles:He,appearance:Je,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De,onButtonClick:Ae,onBeforeButtonClick:ee,onBuyerIdentityReady:on,enableAVS:J,...L?{cardFieldOrder:L}:{},...me?{cardPreFormSlot:me}:{},avsLayout:et,country:C?.customer?.country,city:C?.customer?.city,state:C?.customer?.state,onCountryChange:D,onZipChange:u,avsCheck:!!J,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",className:Ue,directPaypal:ni(G),isSubscription:C?.mode==="subscription",session:C,dataAttachmentPending:pn,dataAttachmentRequiresIdentity:qn,debug:Q})},de)}),Yt]})}function Hc({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return re(Xn,{children:Ga.Children.map(o,a=>{if(!Ga.isValidElement(a))return a;let c=a.props,s={};return c.sessionId||(s.sessionId=e),!c.nonce&&t&&(s.nonce=t),c.billingApiUrl||(s.billingApiUrl=n),r?.customer&&(c.email||(s.email=r.customer.email),c.userId||(s.userId=r.customer.id),c.firstName||(s.firstName=r.customer.firstName),c.lastName||(s.lastName=r.customer.lastName)),Object.keys(s).length===0?a:Ga.cloneElement(a,s)})})}function Yc({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:S,cardBackButtonContent:b,cardTitleContent:g}){let[m,M]=Et(!1),D=En(()=>Ls(a),[a]),u=En(()=>{let P=D?.buttonsLayout??Dc(c);return s?{...P,...s,cardButton:{...P.cardButton,...s.cardButton},cardFormContainer:{...P.cardFormContainer,...s.cardFormContainer},backButton:{...P.backButton,...s.backButton},backButtonIcon:{...P.backButtonIcon,...s.backButtonIcon},submitButton:{...P.submitButton,...s.submitButton},title:{...P.title,...s.title}}:P},[D,c,s]),w=D?.buttonsLayout?.cardButton?.borderRadius??D?.appearance.variables?.borderRadius??8,ve=P=>re("div",{style:{height:P,borderRadius:w,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),H=S===void 0?{boxSizing:"border-box",height:Gr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(m){let P=u.cardInputBorder??"#e5e7eb",fe=u.cardInputBackground??"white",Q=Nr(b),ce=Nr(g);return Vt("div",{style:{backgroundColor:u.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...u.cardFormContainer},children:[Vt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Vt("button",{type:"button",onClick:()=>M(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...u.backButton},children:[re("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:re("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:re("path",{d:"M15 18l-6-6 6-6"})})}),re(Lr,{content:b})]}),ce?re("div",{style:{flex:1}}):re("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:re(mo,{content:g})})]}),re("div",{style:{backgroundColor:fe,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Vt("div",{style:{display:"flex"},children:[re("div",{style:{flex:1,backgroundColor:fe,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:re("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{flex:1,backgroundColor:fe,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),re("div",{style:{backgroundColor:fe,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:re("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),re("style",{children:`
36
36
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
37
37
  @keyframes flopay-interim-expand {
38
38
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
39
39
  40% { opacity: 1; }
40
40
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
41
41
  }
42
- `})]})}return Dt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ee(Tr),n&&(r||o)&&ee(Tr),n&&X("button",{type:"button",onClick:()=>{e?.("card"),x(!0)},style:{width:"100%",...W,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:p.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,...p.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:X(gr,{content:T})}),X("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as hc,jsx as Mr,jsxs as Pc}from"react/jsx-runtime";var pc=44;function cs(e){return new Promise(t=>setTimeout(t,e))}function mc(e,t){return e instanceof Br?e:new Br(e instanceof Error?e.message:t,"api_error")}function yc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function fc(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 gc({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:m,items:d,subscriptions:T,account:h,successUrl:P,cancelUrl:b,couponCodes:x,tagsData:U,utmMetadata:p,billingApiUrl:S,locale:ee,theme:W,appearance:v,buttonsTheme:ye,buttonsStyles:j,onSuccess:J,onError:ce,onDecline:Se,children:re,disabled:le=!1,type:Ve="button",style:Ae,...Ce}){let q=oo(()=>cc(S),[S]),B=oo(()=>fc({createSession:n,clientId:a,products:m,items:d,subscriptions:T,account:h,successUrl:P,cancelUrl:b,couponCodes:x,tagsData:U,utmMetadata:p}),[h,b,a,x,n,m,d,T,P,U,p]),[te,tt]=ao(!1),[Me,V]=ao(null),[de,ae]=ao(null),[ue,ke]=ao(!1),[pe,Re]=ao(null),O=Ar(!0),w=Ar(null),oe=Ar(pe),qe=Ar(J),De=Ar(ce),Z=Ar(Se);xr(()=>{oe.current=pe},[pe]),xr(()=>{qe.current=J},[J]),xr(()=>{De.current=ce},[ce]),xr(()=>{Z.current=Se},[Se]),xr(()=>(O.current=!0,()=>{O.current=!1,w.current?.abort()}),[]),xr(()=>{if(typeof window>"u")return;let k=se=>{se.key==="Escape"&&Re(null)};return window.addEventListener("keydown",k),()=>{window.removeEventListener("keydown",k)}},[]);let R=tr((k,se=Zr)=>{Z.current?.(Mt(se,k,{code:k.code,declineCode:k.declineCode}))},[]),H=tr(async k=>{O.current&&(ae(null),ke(k.result.status==="authorized"),V("success"),await cs(1200),O.current&&qe.current?.(k))},[]),$=tr(async(k,se)=>{O.current&&(De.current?.(k),se?.emitDecline&&R(k,se.method),ae(k.message),ke(!1),V("error"),await cs(1500))},[R]),Be=tr(async(k,se,yt)=>{let Fe=k.data.session??null;if(!Fe)throw new Br("No session data returned","api_error");let Vt=Fe.clientSecret||t;if(br(Fe)){await H({result:lr(Fe,se),session:Fe,sessionId:Fe.id||se,autoCompleted:!1});return}if(Fe.status==="expired")throw Po(Fe);try{if(k.autoProcessingPending){let Je=(await new Fa(q).waitForCheckoutSessionCompletion(k.autoProcessingPending.sessionId,{initialDelayMs:k.autoProcessingPending.retryAfterMs})).data.session;if(!br(Je))throw bo(Je);await H({result:lr(Je,se),session:Je,sessionId:Je.id||se,autoCompleted:!1});return}if(k.autoProcessingError){if(k.autoProcessingError.type==="3ds_required"&&k.autoProcessingError.nextActionRedirectUrl&&se&&Vt){let Ge=new AbortController;w.current=Ge;let vt;try{vt=await Ai({billingApiUrl:q,sessionId:se,nonce:Vt,nextActionRedirectUrl:k.autoProcessingError.nextActionRedirectUrl,signal:Ge.signal})}finally{w.current===Ge&&(w.current=null)}if(vt.status==="declined")throw Qn({type:vt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:vt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:k.autoProcessingError.checkoutMethod});let je=(await new Fa(q).waitForCheckoutSessionCompletion(se,{initialDelayMs:0,nonce:Vt})).data.session;if(!br(je))throw Qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:k.autoProcessingError.checkoutMethod});await H({result:lr(je,se),session:je,sessionId:je.id||se,autoCompleted:!1});return}throw Qn(k.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:k.autoProcessingError.checkoutMethod})}if(yt?.fromCreateSession&&k.autoProcessingAttempted===!0)throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Xt=await Ir({billingApiUrl:q,sessionId:se??Fe.id,session:Fe,nonce:Vt});if(Xt.type!=="success")throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await H({result:Xt.result,session:Fe,sessionId:Fe.id||se,autoCompleted:!1})}catch(Xt){let Ge=ur(Xt),vt=Fe.id||se;await $(Ge,{emitDecline:!0,method:Ge.checkoutMethod??Zr}),yc(Ge,vt)&&vt&&O.current&&Re({sessionId:vt,errorMessage:Ge.message,nonce:Vt||void 0})}},[t,q,$,H]),Ie=tr(async k=>{if(Ce.onClick?.(k),!(k.defaultPrevented||le||te)){if(Re(null),e&&B){let se=new Br("Provide either sessionId or create-session props, not both.","validation_error");await $(se),O.current&&(V(null),ae(null));return}if(!e&&!B){let se=new Br("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(se),O.current&&(V(null),ae(null));return}tt(!0),ae(null),ke(!1),V("processing");try{let se=new Fa(q);if(e){let yt=await se.getUnifiedCheckoutSession(e,t);await Be(yt,e);return}try{let yt=await se.createAndFetchSession({...B});await Be(yt,yt.data.session?.id??null,{fromCreateSession:!0})}catch(yt){if(yt instanceof Br&&yt.code==="session_auto_completed"){await H({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw yt}}catch(se){await $(mc(se,"Automatic payment failed. Please try again."))}finally{O.current&&(V(null),ae(null),tt(!1))}}},[Ce,B,le,te,t,Be,q,e,$,H]),We=tr(k=>{let se=oe.current;Re(null),qe.current?.({result:k,session:null,sessionId:se?.sessionId??null,autoCompleted:!1})},[]),Y=tr(k=>{De.current?.(k)},[]),mt=tr(k=>{Z.current?.(k)},[]),D=oo(()=>uc(W),[W]),Le=oo(()=>{let k=D?.buttonsLayout??dc(ye);return j?{...k,...j,cardButton:{...k.cardButton,...j.cardButton}}:k},[D,ye,j]),Pt=oo(()=>{let k=D?.appearance;return v?k?{...k,...v,variables:{...k.variables,...v.variables}}:v:k},[v,D]),N=Pt?.variables,bt=N?.colorPrimary??"#4A49FF",ze=N?.colorPrimaryHover??Hr(bt,.12),tn=N?.borderRadius??"8px";return Pc(hc,{children:[Mr("button",{...Ce,type:Ve,onClick:Ie,disabled:le||te,"aria-busy":te,style:{width:"100%",...re===void 0?{boxSizing:"border-box",height:pc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Le.cardButton,...ba({themeBundle:D,resolvedPrimaryColor:bt,resolvedBorderRadius:tn,submitButtonStyle:Le.submitButton,explicitPrimaryColor:N?.colorPrimary}),fontSize:Le.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:le||te?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:le||te?.6:1,...Ae},onMouseEnter:k=>{Ce.onMouseEnter?.(k),!k.defaultPrevented&&!le&&!te&&(D||N?.colorPrimary)&&(k.currentTarget.style.backgroundColor=ze)},onMouseLeave:k=>{Ce.onMouseLeave?.(k),!k.defaultPrevented&&(D||N?.colorPrimary)&&(k.currentTarget.style.backgroundColor=bt)},onMouseDown:k=>{Ce.onMouseDown?.(k),k.defaultPrevented||(k.currentTarget.style.transform="scale(0.985)")},onMouseUp:k=>{Ce.onMouseUp?.(k),k.defaultPrevented||(k.currentTarget.style.transform="scale(1)")},children:Mr(gr,{content:re})}),Me&&Mr(Mn,{status:Me,errorMessage:de,authorized:ue}),pe&&Mr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:k=>{k.target===k.currentTarget&&Re(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:Mr("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:Mr(Ba,{sessionId:pe.sessionId,nonce:pe.nonce,checkoutMode:"full",billingApiUrl:q,locale:ee,theme:W,...Pt?{appearance:Pt}:{},buttonsTheme:ye,buttonsStyles:j,initialErrorMessage:pe.errorMessage,cardTitleContent:null,onComplete:We,onError:Y,onDecline:mt})})})]})}export{Ro as DirectPayPalButton,gc as FloPayAutomaticPaymentButton,_s as FloPayCardSetup,Rs as FloPayCardSetupError,Ba as FloPayCheckout,_o as FloPayProvider,va as SplitCardForm,Qo as VaultCardFields,Mu as dropThirdPartyOnlyError,Ls as useCheckout,Xn as useFloPay,na as usePayPalFloPay};
42
+ `})]})}return Vt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ve(Gr),n&&(r||o)&&ve(Gr),n&&re("button",{type:"button",onClick:()=>{e?.("card"),M(!0)},style:{width:"100%",...H,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:u.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,...u.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:re(Dr,{content:S})}),re("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as nd,jsx as Xr,jsxs as rd}from"react/jsx-runtime";var Xc=44;function qs(e){return new Promise(t=>setTimeout(t,e))}function Zc(e,t){return e instanceof Zr?e:new Zr(e instanceof Error?e.message:t,"api_error")}function Qc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ed(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 td({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:c,items:s,subscriptions:S,account:b,successUrl:g,cancelUrl:m,couponCodes:M,tagsData:D,utmMetadata:u,billingApiUrl:w,locale:ve,theme:H,appearance:P,buttonsTheme:fe,buttonsStyles:Q,onSuccess:ce,onError:oe,onDecline:Ce,children:He,disabled:be=!1,type:Rt="button",style:De,...Te}){let Ae=Eo(()=>Gc(w),[w]),ee=Eo(()=>ed({createSession:n,clientId:a,products:c,items:s,subscriptions:S,account:b,successUrl:g,cancelUrl:m,couponCodes:M,tagsData:D,utmMetadata:u}),[b,m,a,M,n,c,s,S,g,D,u]),[J,L]=Ro(!1),[me,et]=Ro(null),[Ue,Ye]=Ro(null),[te,T]=Ro(!1),[ae,Fe]=Ro(null),ie=Jr(!0),j=Jr(null),_e=Jr(ae),Je=Jr(ce),We=Jr(oe),Se=Jr(Ce);Wr(()=>{_e.current=ae},[ae]),Wr(()=>{Je.current=ce},[ce]),Wr(()=>{We.current=oe},[oe]),Wr(()=>{Se.current=Ce},[Ce]),Wr(()=>(ie.current=!0,()=>{ie.current=!1,j.current?.abort()}),[]),Wr(()=>{if(typeof window>"u")return;let y=U=>{U.key==="Escape"&&Fe(null)};return window.addEventListener("keydown",y),()=>{window.removeEventListener("keydown",y)}},[]);let G=hr((y,U=Po)=>{Se.current?.($t(U,y,{code:y.code,declineCode:y.declineCode}))},[]),Y=hr(async y=>{ie.current&&(Ye(null),T(y.result.status==="authorized"),et("success"),await qs(1200),ie.current&&Je.current?.(y))},[]),$=hr(async(y,U)=>{ie.current&&(We.current?.(y),U?.emitDecline&&G(y,U.method),Ye(y.message),T(!1),et("error"),await qs(1500))},[G]),we=hr(async(y,U,Xe)=>{let dt=y.data.session??null;if(!dt)throw new Zr("No session data returned","api_error");let Mt=dt.clientSecret||t;if(zr(dt)){await Y({result:kr(dt,U),session:dt,sessionId:dt.id||U,autoCompleted:!1});return}if(dt.status==="expired")throw qo(dt);try{if(y.autoProcessingPending){let Wt=(await new si(Ae).waitForCheckoutSessionCompletion(y.autoProcessingPending.sessionId,{initialDelayMs:y.autoProcessingPending.retryAfterMs})).data.session;if(!zr(Wt))throw $o(Wt);await Y({result:kr(Wt,U),session:Wt,sessionId:Wt.id||U,autoCompleted:!1});return}if(y.autoProcessingError){if(y.autoProcessingError.type==="3ds_required"&&y.autoProcessingError.nextActionRedirectUrl&&U&&Mt){let W=new AbortController;j.current=W;let Le;try{Le=await cs({billingApiUrl:Ae,sessionId:U,nonce:Mt,nextActionRedirectUrl:y.autoProcessingError.nextActionRedirectUrl,signal:W.signal})}finally{j.current===W&&(j.current=null)}if(Le.status==="declined")throw yr({type:Le.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Le.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:y.autoProcessingError.checkoutMethod});let Ot=(await new si(Ae).waitForCheckoutSessionCompletion(U,{initialDelayMs:0,nonce:Mt})).data.session;if(!zr(Ot))throw yr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:y.autoProcessingError.checkoutMethod});await Y({result:kr(Ot,U),session:Ot,sessionId:Ot.id||U,autoCompleted:!1});return}throw yr(y.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:y.autoProcessingError.checkoutMethod})}if(Xe?.fromCreateSession&&y.autoProcessingAttempted===!0)throw yr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Bt=await Hr({billingApiUrl:Ae,sessionId:U??dt.id,session:dt,nonce:Mt});if(Bt.type!=="success")throw yr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Y({result:Bt.result,session:dt,sessionId:dt.id||U,autoCompleted:!1})}catch(Bt){let W=Rr(Bt),Le=dt.id||U;await $(W,{emitDecline:!0,method:W.checkoutMethod??Po}),Qc(W,Le)&&Le&&ie.current&&Fe({sessionId:Le,errorMessage:W.message,nonce:Mt||void 0})}},[t,Ae,$,Y]),Me=hr(async y=>{if(Te.onClick?.(y),!(y.defaultPrevented||be||J)){if(Fe(null),e&&ee){let U=new Zr("Provide either sessionId or create-session props, not both.","validation_error");await $(U),ie.current&&(et(null),Ye(null));return}if(!e&&!ee){let U=new Zr("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(U),ie.current&&(et(null),Ye(null));return}L(!0),Ye(null),T(!1),et("processing");try{let U=new si(Ae);if(e){let Xe=await U.getUnifiedCheckoutSession(e,t);await we(Xe,e);return}try{let Xe=await U.createAndFetchSession({...ee});await we(Xe,Xe.data.session?.id??null,{fromCreateSession:!0})}catch(Xe){if(Xe instanceof Zr&&Xe.code==="session_auto_completed"){await Y({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Xe}}catch(U){await $(Zc(U,"Automatic payment failed. Please try again."))}finally{ie.current&&(et(null),Ye(null),L(!1))}}},[Te,ee,be,J,t,we,Ae,e,$,Y]),x=hr(y=>{let U=_e.current;Fe(null),Je.current?.({result:y,session:null,sessionId:U?.sessionId??null,autoCompleted:!1})},[]),K=hr(y=>{We.current?.(y)},[]),I=hr(y=>{Se.current?.(y)},[]),C=Eo(()=>Jc(H),[H]),nt=Eo(()=>{let y=C?.buttonsLayout??Wc(fe);return Q?{...y,...Q,cardButton:{...y.cardButton,...Q.cardButton}}:y},[C,fe,Q]),St=Eo(()=>{let y=C?.appearance;return P?y?{...y,...P,variables:{...y.variables,...P.variables}}:P:y},[P,C]),de=St?.variables,ct=de?.colorPrimary??"#4A49FF",it=de?.colorPrimaryHover??po(ct,.12),rt=de?.borderRadius??"8px";return rd(nd,{children:[Xr("button",{...Te,type:Rt,onClick:Me,disabled:be||J,"aria-busy":J,style:{width:"100%",...He===void 0?{boxSizing:"border-box",height:Xc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...nt.cardButton,...Ha({themeBundle:C,resolvedPrimaryColor:ct,resolvedBorderRadius:rt,submitButtonStyle:nt.submitButton,explicitPrimaryColor:de?.colorPrimary}),fontSize:nt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:be||J?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:be||J?.6:1,...De},onMouseEnter:y=>{Te.onMouseEnter?.(y),!y.defaultPrevented&&!be&&!J&&(C||de?.colorPrimary)&&(y.currentTarget.style.backgroundColor=it)},onMouseLeave:y=>{Te.onMouseLeave?.(y),!y.defaultPrevented&&(C||de?.colorPrimary)&&(y.currentTarget.style.backgroundColor=ct)},onMouseDown:y=>{Te.onMouseDown?.(y),y.defaultPrevented||(y.currentTarget.style.transform="scale(0.985)")},onMouseUp:y=>{Te.onMouseUp?.(y),y.defaultPrevented||(y.currentTarget.style.transform="scale(1)")},children:Xr(Dr,{content:He})}),me&&Xr(Yn,{status:me,errorMessage:Ue,authorized:te}),ae&&Xr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:y=>{y.target===y.currentTarget&&Fe(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:Xr("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:Xr(ii,{sessionId:ae.sessionId,nonce:ae.nonce,checkoutMode:"full",billingApiUrl:Ae,locale:ve,theme:H,...St?{appearance:St}:{},buttonsTheme:fe,buttonsStyles:Q,initialErrorMessage:ae.errorMessage,cardTitleContent:null,onComplete:x,onError:K,onDecline:I})})})]})}export{Jo as DirectPayPalButton,td as FloPayAutomaticPaymentButton,ll as FloPayCardSetup,sl as FloPayCardSetupError,ii as FloPayCheckout,Xo as FloPayProvider,Ya as SplitCardForm,wa as VaultCardFields,ap as dropThirdPartyOnlyError,bl as useCheckout,ur as useFloPay,_a as usePayPalFloPay};