@flopay/react 1.8.2 → 1.8.4
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/README.md +23 -3
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +22 -6
- package/dist/index.d.ts +22 -6
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as Qe,b as xn,c as Xo,d as Kr,e as ii,f as si,g as Is,h as Es}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as uu}from"@flopay/shared";import{PaymentAPI as Ma}from"@flopay/js";import{FloPayError as Ar,resolveBillingApiUrl as sc,resolveButtonsLayoutTheme as lc,resolveTheme as cc}from"@flopay/shared";import{useCallback as Qn,useEffect as _r,useMemo as no,useRef as Tr,useState as ro}from"react";import{Fragment as gr,jsx as fn,jsxs as li}from"react/jsx-runtime";function Rs(){return li(gr,{children:[li("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:[fn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),fn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",fn("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:fn("path",{d:"M9 18l6-6-6-6"})})]})}function _s(){return fn(gr,{children:"Go back"})}function Ts(){return fn(gr,{children:"Secure card checkout"})}function mr(e){return e!==void 0&&(e===""||e===null||e===!1)}function yr({content:e}){return fn(gr,{children:e===void 0?fn(Rs,{}):e})}function fr({content:e}){return fn(gr,{children:e===void 0?fn(_s,{}):e})}function Vr({content:e}){return fn(gr,{children:e===void 0?fn(Ts,{}):e})}import{FloPayError as ci,isMoneySettledOutcome as xs,isSetupIntentClientSecret as Cc}from"@flopay/shared";function di(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 Zo(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 ui(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 Qo(e,t){return t?{...e,...t}:e}function xt(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 As=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Yn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of As)if(n.test(t))return r;return e}function ir(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function hr(e){return e?.status==="authorized"||e?.status==="complete"}function pi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function go(e){let t=pi(e);return new ci(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ho(e){let t=pi(e);return new ci(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 Po(e,t){return e==="processing"||xs(e,t)}function mi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function yi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Hr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as Do,SESSION_CREATE_TELEMETRY as Kl}from"@flopay/js";import{buildCheckoutDisplayData as Vl,classifyTelemetryFailure as Zi,FloPayError as Mt,foldIntoProducts as Hl,isDetachedSessionEligible as Yl,resolveBillingApiUrl as Gl,resolveButtonsLayoutTheme as Wl,resolveIdempotencyKey as Qi,resolveSessionCurrency as Jl,resolveTheme as rs,SDK_VERSION as os,telemetryStatusClass as Xl}from"@flopay/shared";import va,{useCallback as $n,useEffect as Mn,useMemo as hn,useRef as _t,useState as kt}from"react";import{createContext as fi}from"react";var gn=fi({flopay:null,paypalFlopay:null,billingApiUrl:""}),Sn=fi({session:null,loading:!1,error:null});import{PaymentAPI as na}from"@flopay/js";import{classifyTelemetryFailure as Hs,FloPayError as hi,generateIdempotencyKey as Ys,normalizeGatewayEnvironment as Gs,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as ra,SDK_VERSION as Ws}from"@flopay/shared";import{loadScript as Js}from"@paypal/paypal-js";import{useCallback as wo,useEffect as ht,useMemo as Gr,useRef as Ye,useState as lr}from"react";function Ms(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 sr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Nn(e){if(typeof e!="object"||e===null)return;let t=e;return sr(t.code)??sr(t.type)??sr(t.name)}function Pr(e){if(!(typeof e!="object"||e===null))return sr(e.decline_code)}function Yr(e){return typeof e!="object"||e===null?!1:sr(e.type)?.toLowerCase()==="card_error"||Pr(e)!==void 0}function Gn(e){let t=Ms(e)?.toLowerCase()??"",r=`${Nn(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Bs}from"@flopay/shared";import{useContext as vo}from"react";function Wn(){return vo(gn).flopay}function ea(){return vo(gn).paypalFlopay??null}function Fs(){return vo(Sn)}function gi(){return vo(gn).billingApiUrl||Bs()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Os}from"@flopay/shared";import{useCallback as Ns,useRef as Co}from"react";import{useEffect as Ds,useLayoutEffect as Ls}from"react";var bo=typeof window>"u"?Ds:Ls;var zs={"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 Us(e){return e==="stripe"||e==="paypal"?e:void 0}function $s(e){let t=Us(e.provider),n={schemaVersion:Os,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=zs[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 ta=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function vr(e,t){let n=Co(e);n.current=e;let r=Co(new Set),o=Co(t),a=Co(t);return bo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Ns(m=>{if(a.current!==t)return;let d=$s(m);if(d){if(ta.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}Qe(()=>n.current?.(d))}},[t])}var qs=Symbol.for("@flopay/js.telemetry.bridge.v1"),js=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ks(){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 Vs(e){let t=Ks(),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 So(e){let t=globalThis[js];return Vs(t?.(e)??{})}function At(e){if(e)return e[qs]}import{jsx as br,jsxs as oa}from"react/jsx-runtime";var ko=45,Xs=1e3,Zs=11e3,Qs=["https://www.paypal.com","https://www.sandbox.paypal.com"],Pi="We couldn't open PayPal. Try again or choose another payment method.",el={width:"100%",minHeight:ko,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 vi(e){return e.includes("No ack for postMessage init()")&&Qs.some(t=>e.includes(t))&&e.includes("10000ms")}function tl(e){return e?`${Pi} Allow pop-ups for this site, then try again.`:Pi}function bi({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:ne,allowAutomaticRetry:V=!0,onButtonClick:v,runBeforeButtonClick:fe,session:j,existingOrderId:J,telemetry:ce,telemetryContext:Se,onInstrument:re,debug:le=!1}){let Ve=Wn(),Ae=vr(re,e),Ce=Gr(()=>{if(Ve)return null;let I=So({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ws,enabled:ce!==!1});return I.setCheckoutContext(Se??{}),I.beginCheckout(Se??{}),I},[n,Ve,ce,Se?.checkoutMode,Se?.layout]),q=Gr(()=>At(Ve),[Ve]);ht(()=>()=>{Ce&&Ce.flush().catch(()=>{}).finally(()=>Ce.destroy())},[Ce]);let B=Gr(()=>({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]),ee=Ye(null),tt=Ye(0),Me=Ye(null),H=Ye(!1),[de,ae]=lr(!1),[ue,ke]=lr(!1),[pe,Re]=lr(0),O=Ye(0),[w,oe]=lr(!1),qe=Ye(!1),De=Ye(!1),[Z,R]=lr(!1),[Y,$]=lr(!1),Be=Gr(()=>n.replace(/\/+$/,""),[n]),Ie=T??(d?"subscription":"order"),We=T==="order"||T==="setup_token",G=Gr(()=>JSON.stringify([Be,o,m,a??"",Ie,We,e,J??""]),[Be,o,m,a,J,Ie,We,e]),mt=Ye(G),D=mt.current!==G,[Le,Pt]=lr([]),N=I=>{le&&Pt(Xe=>[...Xe,`${new Date().toISOString().slice(11,23)} ${I}`])},vt=Ye(h),ze=Ye(P),Qt=Ye(b),It=Ye(x),k=Ye(U),se=Ye(v),yt=Ye(S),Fe=Ye(ne),jt=Ye(fe),Wt=Ye(j),Ge=Ye(r),bt=Ye(t),Je=Ye(null),Ft=Ye(0),je=Ye(null),Kt=Ye(null),Et=Ye(new Map),en=Ye(new Map),Lt=Ye(!1);ht(()=>(Lt.current=!0,()=>{Lt.current=!1}),[]),ht(()=>{vt.current=h},[h]),ht(()=>{ze.current=P},[P]),ht(()=>{Qt.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=ne},[ne]),ht(()=>{jt.current=fe},[fe]),ht(()=>{Wt.current=j},[j]),ht(()=>{Ge.current=r},[r]),ht(()=>{bt.current=t},[t]),ht(()=>{O.current=pe},[pe]),ht(()=>{w&&Me.current?.focus()},[w,pe]);let kn=wo(()=>{window.setTimeout(()=>{Me.current?.focus()},0)},[]),on=wo(()=>{ae(!1),Re(I=>I+1)},[]),rt=wo(()=>{oe(!1),(ee.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ee.current)?.focus?.()},[]);ht(()=>{!de||!H.current||(H.current=!1,rt())},[rt,de,pe]);let Ot=wo((I,Xe)=>{let Pe=k.current;if(Pe){Pe("paypal",I,Xe);return}Qt.current?.(tl(Xe?.popupBlocked??Gn(I)))},[]),Ke=()=>{je.current?.timer&&(clearTimeout(je.current.timer),je.current.timer=null)},In=()=>{Ke();let I=Ft.current+1;return Ft.current=I,Kt.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,Kt.current=null,!0),Pn=I=>{let Xe=I?.generation??je.current?.generation??Ft.current;(!I?.generation||je.current?.generation===Xe)&&(Ke(),je.current=null),Kt.current=Xe,I?.showRetry&&oe(!0),I?.remount&&on(),I?.focus!==!1&&kn()},Nt=I=>je.current?.generation===I&&Kt.current!==I,te=I=>{typeof document<"u"&&document.visibilityState!=="visible"||(Ke(),I.timer=setTimeout(()=>{je.current?.generation===I.generation&&(je.current=null,Kt.current=I.generation,Ot(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),oe(!0),on(),kn())},600))},jn=()=>{let I=je.current;I?.yieldedControl&&te(I)},En=()=>{let I=je.current;I&&(I.yieldedControl=!0,Ke())},Rn=I=>{let Xe=Je.current;return Xe&&en.current.set(I,Xe),I};ht(()=>{let I=()=>{document.visibilityState==="visible"?jn():En()};return document.addEventListener("visibilitychange",I),window.addEventListener("focus",jn),window.addEventListener("blur",En),()=>{document.removeEventListener("visibilitychange",I),window.removeEventListener("focus",jn),window.removeEventListener("blur",En),Ke()}},[]),ht(()=>{mt.current!==G&&(mt.current=G,qe.current=!1,De.current=!1,ae(!1),ke(!1),R(!1),Fe.current?.("loading"))},[G]),ht(()=>{Qe(()=>yt.current?.(de&&!Z))},[de,Z]);let _n=Gs(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${_n??"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(!ee.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,vn=!1,Oe=()=>Pe||vn,Kn,er=!1,Vt=()=>{Kn=Ys(),Kn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),er=!0},dt=null,Jt=!1,Ht=null,ot=!1,an=()=>{!Ht||ot||(ot=!0,Ht.close().catch(()=>{}))},sn=null,Vn=()=>{sn!==null&&(B.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"overlay_return",durationMs:B.elapsed(sn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),sn=null)},bn=!1,tn=ee.current,ln=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)}`},nn=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)}},cn=l=>{let s=l.getAttribute("src"),c=l.getAttribute("srcdoc"),A=l.getAttribute("name"),K=l.getAttribute("sandbox"),F=[];return s&&F.push(`src=${nn(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(" ")},Fn=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)})`}},dn=[],zt=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)}`),dn.push(s))},Yt=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)}`),dn.push(s))};le&&typeof window<"u"&&(window.addEventListener("error",zt),window.addEventListener("unhandledrejection",Yt));let Gt={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;Gt.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 Hn=()=>{for(ln?.disconnect(),ln=null,me?.disconnect(),me=null;Ct.length;)clearTimeout(Ct.pop());le&&typeof window<"u"&&(window.removeEventListener("error",zt),window.removeEventListener("unhandledrejection",Yt))},Dn=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")},Tn=l=>{if(Oe()||Dn(l))return;let s=Yn(l)??l;Qe(()=>Qt.current?.(s))},Ln=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))},Ut=(l,s=!1)=>{if(Pe)return;let c=qe.current||!V;if(Jt)return;Jt=!0,vn=!0,Hn(),an();let A=s||vi(l);if(A&&V&&!qe.current){qe.current=!0,ae(!1),$(!1),ke(!0),Fe.current?.("retrying"),dt=setTimeout(()=>{Pe||Re(K=>K+1)},Xs);return}if(A||c){if(ae(!1),$(!1),ke(!1),R(!0),Fe.current?.("exhausted"),!De.current){De.current=!0;let K=vi(l)?"paypal_init_timeout":s?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",K)}return}Ln(l)};R(!1);let Ze=async(l,s=Je.current)=>{if(Oe())return;let c=s?.sessionId??e;if(vt.current){await vt.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=Wt.current,C=s?.accountPatch?.email??Ge.current,f=s?.accountPatch?.userId??F?.customer?.id??F?.accountData?.userId??"",g=await new na(Be,{telemetry:!1}).processPayment(f,{sessionId:c,nonce:s?.nonce??bt.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(vn||Pe&&Lt.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),W=E?.message??"PayPal payment failed.",ie=Yn(W)??W;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}),Tn(ie),Qe(()=>It.current?.(xt("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=Yn(C)??C;Tn(f),Qe(()=>It.current?.(xt("paypal",f)));return}},un=()=>new hi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),$t=l=>Oe()?Promise.reject(un()):Promise.resolve(l),ut=async l=>{if(Oe())throw un();er||Vt();let s=Je.current,c=s?.sessionId??e,A=s?.nonce??bt.current;B.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let K;try{K=await new na(Be,{telemetry:!1}).createSessionIntent(c,A??"",We?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:ra,paymentMethodId:null,intentKind:Ie==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Kn})}catch(F){throw B.error({...Hs(F,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),F}if(Oe())throw un();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},Xt=(l,s)=>{let c=s?.nonce??bt.current;if(!c)return;let A=s?.sessionId??e,K=Pr(l)??Nn(l)??"provider_declined";new na(Be,{telemetry:!1}).reportSessionIntentDecline(A,c,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:K}).catch(()=>{})},Rt=pe;N("loadScript:scheduled (deferred 1 tick)");let tr=null,pt=setTimeout(()=>{if(Pe){N("loadScript:skipped (cancelled before defer ran)");return}N("loadScript:start");let l=_n==="live"?"production":_n;tr=Js({clientId:o,currency:m,...Ie==="subscription"?{intent:"subscription",vault:!0}:Ie==="order"?{intent:"capture"}:{},...l?{environment:l}:{},...l==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),tr.then(s=>{if(N(`loadScript:resolved inactive=${Oe()} ns=${!!s} buttons=${!!s?.Buttons}`),Oe())return;if(!s?.Buttons){N("FAIL: namespace missing Buttons factory"),Ut("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?en.current.get(g):Et.current.get(Rt);if(!(!E||!Nt(E.generation))&&ct(E.generation)){en.current.delete(g),Et.current.delete(E.surfaceKey),Vn();try{if($(!0),Qe(()=>Qt.current?.(null)),!g)throw new hi("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:ra}:We?{id:g,isPaypal:!0,gateway:"paypal",paymentMethodType:ra}:{id:g,isPaypal:!0},E)}catch(W){Tn(W instanceof Error?W.message:"PayPal capture failed.")}finally{Oe()||$(!1)}}},A=s.Buttons({style:{layout:"horizontal",height:ko,tagline:!1},onClick:async(y,g)=>{if(Oe()){await g.reject();return}Vt();let E=jt.current,W={};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}W={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:In(),surfaceKey:Rt,...W};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"}),sn=B.startTiming()},createOrder:Ie==="order"?J?()=>$t(J).then(Rn):()=>ut("Failed to create PayPal order.").then(Rn):void 0,createSubscription:Ie==="subscription"?J?()=>$t(J).then(Rn):()=>ut("Failed to create PayPal subscription.").then(Rn):void 0,createVaultSetupToken:Ie==="setup_token"?()=>ut("Failed to create PayPal setup token.").then(Rn):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,Vn(),B.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),H.current=!0,Pn({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=${bn} msg=${g.slice(0,120)}`),bn){let E=Et.current.get(Rt)??Je.current;if(E&&!Nt(E.generation)||!E&&Kt.current===Ft.current)return;if(Dn(g)){ct(E?.generation);return}if(Vn(),Yr(y)){B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Xt(y,E),Qe(()=>It.current?.(xt("paypal",g))),E&&Et.current.delete(E.surfaceKey),Je.current=null,ct(E?.generation);return}let W=g.toLowerCase();B.error({errorCode:W.includes("popup")&&W.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,Pn({generation:E?.generation,remount:!0,showRetry:!0,focus:!0}),Ot(y,{code:"paypal_runtime_failed"});return}Ut(g)}}),K=A.isEligible();if(N(`isEligible=${K}`),B.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!K){ae(!1),Ut("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ht=A,le&&N(`container:dims ${at(tn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),le&&typeof MutationObserver<"u"&&(ln=new MutationObserver(y=>{if(!Oe()){for(let g of y)if(g.type==="childList")g.addedNodes.forEach(E=>{if(!(E instanceof Element))return;let W=E.tagName.toLowerCase(),ie=(E.getAttribute("title")??"").slice(0,40),_e=W==="iframe"?` ${cn(E)}`:"";N(`child+ ${W}${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 W=g.attributeName;(W==="src"||W==="srcdoc")&&N(`attr~ iframe ${W}=${W==="srcdoc"?`[${(E.getAttribute("srcdoc")??"").length}ch]`:nn(E.getAttribute("src"))} dims=${at(E)}`)}}}),ln.observe(tn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let C=y=>{if(Oe()||bn)return;let g=tn.querySelectorAll("iframe"),E=typeof document<"u"&&"hasStorageAccess"in document;N(`watchdog:${y} container=${at(tn)} children=${tn.childElementCount} iframes=${g.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${E} paypalNetRequests=${Gt.value}`),g.forEach((W,ie)=>{let _e=(W.getAttribute("title")??"").slice(0,40);N(` iframe[${ie}] ${at(W)}${_e?` title="${_e}"`:""} ${cn(W)}`);let Ue=Fn(W);Ue&&N(` ${Ue}`)}),dn.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()||bn||(N("watchdog:11s retryable render timeout"),Ut("PayPal Buttons render did not settle within 11000ms.",!0))},Zs)),A.render(tn).then(()=>{if(N(`render:resolved inactive=${Oe()}`),Hn(),Oe()){an();return}bn=!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)}`),Hn(),Ut(g)})}).catch(s=>{let c=s instanceof Error?s.message:"PayPal SDK failed to load.";N(`loadScript:rejected msg=${c.slice(0,120)}`),Ut(c)})},0);return()=>{Pe=!0,clearTimeout(pt),dt&&clearTimeout(dt),Hn(),an()}},[V,Be,o,m,a,Ie,We,e,J,pe,B]);let ur=le?oa("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 jt(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 Bc,classifyTelemetryFailure as Bs,FloPayError as Vt,foldIntoProducts as Mc,isDetachedSessionEligible as Fc,resolveBillingApiUrl as Nc,resolveButtonsLayoutTheme as Dc,resolveIdempotencyKey as Ms,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 Bl,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Aa,SDK_VERSION as Ml}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","data-testid":"flopay-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","data-testid":"flopay-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 Kt(e){if(e)return e[El]}import{jsx as pr,jsxs as Ba}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:B,onErrorChange:D,onDecline:u,onTechnicalFailure:w,isProcessing:ve=!1,onLoadStateChange:H,onInitializationStateChange:C,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:Ml,enabled:He!==!1});return v.setCheckoutContext(be??{}),v.beginCheckout(be??{}),v},[n,Te,He,be?.checkoutMode,be?.layout]),J=bo(()=>Kt(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]),de=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,Be]=nr(!1),[x,K]=nr(!1),[I,P]=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:ue,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,[Bt,Mt]=nr([]),W=v=>{De&&Mt(ut=>[...ut,`${new Date().toISOString().slice(11,23)} ${v}`])},Le=Ve(m),Jt=Ve(B),wt=Ve(D),zt=Ve(u),Rn=Ve(w),_n=Ve(Q),Zn=Ve(H),Xt=Ve(C),cn=Ve(a),dn=Ve(ce),Ft=Ve(oe),vn=Ve(r),bt=Ve(o),ir=Ve(null),Yt=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(()=>{Jt.current=B},[B]),ft(()=>{wt.current=D},[D]),ft(()=>{zt.current=u},[u]),ft(()=>{Rn.current=w},[w]),ft(()=>{_n.current=Q},[Q]),ft(()=>{Zn.current=H},[H]),ft(()=>{Xt.current=C},[C]),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(()=>{Yt.current!==e&&(Yt.current=e,ir.current=null,K(!1),P(!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=>{P(!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{P(!1)}},[]),qn=ho(()=>{T(!1),j(v=>v+1)},[]),Ut=ho(()=>{We(!1),(de.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??de.current)?.focus?.()},[]);ft(()=>{!te||!Ye.current||(Ye.current=!1,Ut())},[Ut,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)},Me=()=>{let v=ot.current;v&&(v.yieldedControl=!0,Pn())},Zt=v=>{let ut=Nt.current;return ut&&tn.current.set(v,ut),v};ft(()=>{let v=()=>{document.visibilityState==="visible"?mn():Me()};return document.addEventListener("visibilitychange",v),window.addEventListener("focus",mn),window.addEventListener("blur",Me),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("focus",mn),window.removeEventListener("blur",Me),Pn()}},[]),ft(()=>{Xe.current!==U&&(Xe.current=U,Se.current=!1,G.current=!1,T(!1),Fe(!1),$(!1),Xt.current?.("loading"))},[U]),ft(()=>{tt(()=>Zn.current?.(te&&!Y))},[te,Y]);let Dt=Bl(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(!de.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,qt,lr=!1,jn=()=>{qt=Al(),qt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),lr=!0},Cn=null,Lt=!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=de.current,Bn=null,Mn=null,$t=[],nn=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"),ke=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)"),ke&&F.push(`name=${ke.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,ke=p.body?.innerHTML.length??0,q=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${k}children,${ke}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{Mn=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)}`)}}),Mn.observe({type:"resource",buffered:!0})}catch{}let Gt=()=>{for(Bn?.disconnect(),Bn=null,Mn?.disconnect(),Mn=null;$t.length;)clearTimeout($t.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(Lt)return;Lt=!0,yn=!0,Gt(),xe();let ke=p||Qi(d);if(ke&&fe&&!Se.current){Se.current=!0,T(!1),Be(!1),Fe(!0),Xt.current?.("retrying"),Cn=setTimeout(()=>{qe||j(q=>q+1)},Nl);return}if(ke||k){if(T(!1),Be(!1),Fe(!1),$(!0),Xt.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 ke=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(ke),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??"",pe=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(pe.ok){if(yn||qe&&un.current)return;q(),L.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),tt(()=>Jt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ze())return;let A=await pe.json().catch(()=>null),le=A?.message??"PayPal payment failed.",st=cr(le)??le;q(),pe.status===400&&(typeof A?.declineCode=="string"||!Array.isArray(A?.fields))?L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):pe.status===400||pe.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:pe.status>=500?"5xx":pe.status>=400?"4xx":pe.status>=300?"3xx":"unknown",failureCategory:pe.status>=500?"server_error":void 0}),E(st),tt(()=>zt.current?.(jt("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(()=>zt.current?.(jt("paypal",Qe)));return}},ne=()=>new Xi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),M=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,ke=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,ke??"",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:qt})}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 ke=p?.sessionId??e,q=$r(d)??tr(d)??"provider_declined";new Ta(rt,{telemetry:!1}).reportSessionIntentDecline(ke,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,pe)=>{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(Be(!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,Ot=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()||Ot.firstName,lastName:le.accountPatch?.lastName?.trim()||Ot.lastName};if(!Go(ge.email)||!(ge.firstName||ge.lastName))try{let bn=Ul(await pe?.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()||Be(!1)}}},ke=p.Buttons({style:{layout:"horizontal",height:Wo,tagline:!1},onClick:async(se,pe)=>{if(Ze()){await pe.reject();return}jn();let A=dn.current,le={accountPatch:ir.current??void 0};if(A)try{let ge=await A("paypal");if(Ze()){await pe.reject();return}if(!ge.proceed){Nt.current=null,xt.current.delete(O),await pe.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 pe.reject();return}tt(()=>_n.current?.("paypal"));let Ot={generation:xn(),surfaceKey:O,...le};Nt.current=Ot,xt.current.set(O,Ot),await pe.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?()=>M(Ce).then(Zt):()=>h("Failed to create PayPal order.").then(Zt):void 0,createSubscription:je==="subscription"?Ce?()=>M(Ce).then(Zt):()=>h("Failed to create PayPal subscription.").then(Zt):void 0,createVaultSetupToken:je==="setup_token"?()=>h("Failed to create PayPal setup token.").then(Zt):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 pe=se instanceof Error?se.message:"PayPal failed to render.";if(W(`onError rendered=${An} msg=${pe.slice(0,120)}`),An){let A=xt.current.get(O)??Nt.current;if(A&&!Tr(A.generation)||!A&&_t.current===zn.current)return;if(_(pe)){Qn(A?.generation);return}if(Tt(),go(se)){L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),f(se,A),tt(()=>zt.current?.(jt("paypal",pe))),A&&xt.current.delete(A.surfaceKey),Nt.current=null,Qn(A?.generation);return}let le=pe.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(pe)}}),q=ke.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=ke,De&&W(`container:dims ${nn(hn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),De&&typeof MutationObserver<"u"&&(Bn=new MutationObserver(se=>{if(!Ze()){for(let pe of se)if(pe.type==="childList")pe.addedNodes.forEach(A=>{if(!(A instanceof Element))return;let le=A.tagName.toLowerCase(),st=(A.getAttribute("title")??"").slice(0,40),Ot=le==="iframe"?` ${er(A)}`:"";W(`child+ ${le}${st?` title="${st}"`:""}${Ot} dims=${nn(A)}`)});else if(pe.type==="attributes"&&pe.target instanceof Element){let A=pe.target;if(A.tagName.toLowerCase()!=="iframe")continue;let le=pe.attributeName;(le==="src"||le==="srcdoc")&&W(`attr~ iframe ${le}=${le==="srcdoc"?`[${(A.getAttribute("srcdoc")??"").length}ch]`:an(A.getAttribute("src"))} dims=${nn(A)}`)}}}),Bn.observe(hn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ge=se=>{if(Ze()||An)return;let pe=hn.querySelectorAll("iframe"),A=typeof document<"u"&&"hasStorageAccess"in document;W(`watchdog:${se} container=${nn(hn)} children=${hn.childElementCount} iframes=${pe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${A} paypalNetRequests=${at.value}`),pe.forEach((le,st)=>{let Ot=(le.getAttribute("title")??"").slice(0,40);W(` iframe[${st}] ${nn(le)}${Ot?` title="${Ot}"`:""} ${er(le)}`);let ge=Ar(le);ge&&W(` ${ge}`)}),Fn.length===0&&W(" (no PayPal/zoid window errors captured)")};De&&($t.push(setTimeout(()=>Ge("3s"),3e3)),$t.push(setTimeout(()=>Ge("8s"),8e3)),$t.push(setTimeout(()=>Ge("15s"),15e3))),W("render:start");let Qe=L.startTiming();$t.push(setTimeout(()=>{Ze()||An||(W("watchdog:11s retryable render timeout"),Z("PayPal Buttons render did not settle within 11000ms.",!0))},Dl)),ke.render(hn).then(()=>{if(W(`render:resolved inactive=${Ze()}`),Gt(),Ze()){xe();return}An=!0,T(!0),Fe(!1),Xt.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 pe=se instanceof Error?se.message:"PayPal failed to render.";W(`render:rejected msg=${pe.slice(0,120)}`),Gt(),Z(pe)})}).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),Gt(),xe()}},[fe,rt,c,S,s,je,y,e,Ce,ie,L,ct]);let $n=De?Ba("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})`,Bt.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return Z&&!D?le?br("div",{children:ur}):null:oa("div",{children:[ur,oa("div",{"aria-hidden":ue?!0:void 0,style:ue?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ko},children:[!de&&!ue&&br("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"}}),br("div",{ref:ee,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ko,display:"flex",opacity:de?1:0},"aria-busy":Y||p},pe)]},pe),w&&br("button",{ref:Me,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:rt,style:el,children:"Try PayPal again"})]})}function Io(e){return br(bi,{...e})}function Ci(e){return br(bi,{...e})}import{jsx as Si,jsxs as nl}from"react/jsx-runtime";function Cr({children:e,margin:t,icon:n=!0,styleOverride:r}){return nl("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&&Si("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Si("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 rl}from"@flopay/shared";import{useEffect as Jn,useMemo as ol,useRef as wi,useState as ki}from"react";import{jsx as al}from"react/jsx-runtime";function Eo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,m]=ki(e instanceof Promise?null:e),[d,T]=ki(t instanceof Promise||!t?null:t),h=wi(null),P=wi(null),b=vr(r);Jn(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),Jn(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),Jn(()=>{if(a)return At(a)?.subscribe?.(b)},[b,a]),Jn(()=>{if(!(!d||d===a))return At(d)?.subscribe?.(b)},[b,a,d]),Jn(()=>{if(!a)return;let p=At(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]),Jn(()=>{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]),Jn(()=>{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]),Jn(()=>{if(!a||P.current===a)return;P.current=a;let p=At(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=rl(n?.billingApiUrl),U=ol(()=>({flopay:a,paypalFlopay:d,billingApiUrl:x,emitInstrument:b}),[a,d,x,b]);return al(gn.Provider,{value:U,children:o})}var Ro="flopay_recent_completion_";function Sr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Ro+e,JSON.stringify(t))}catch{}}function ia(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Ro+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Ro+e),!1):!0}catch{return!1}}import{loadFloPay as Ii,PaymentAPI as Ri}from"@flopay/js";import{classifyPaymentRejection as il,FloPayError as et,isAuthorizationOnlySession as sl,isSetupIntentClientSecret as ll,normalizeCheckoutFailureOutcome as Ei}from"@flopay/shared";var Jr="card";async function cl(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 dl(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 la(e,t){return Object.assign(e,{checkoutMethod:t})}function zn(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 Wr(e,t){try{return await e()}catch(n){throw zn(n,t)}}function _i(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 ul(e){return e.status==="succeeded"||e.status==="declined"}async function Ti(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 pl(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,ne=0,V=!1,v=()=>{window.clearTimeout(p),window.clearInterval(S),window.clearTimeout(ne),window.removeEventListener("message",ce),T.removeEventListener("load",j),e.signal?.removeEventListener("abort",J)},fe=async()=>{if(!(U||V)){V=!0;try{let Se=await a();if(U||!ul(Se))return;U=!0,v(),b(Se)}finally{V=!1}}},j=()=>{window.clearTimeout(ne),ne=window.setTimeout(()=>{fe()},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(()=>{fe()},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 pl(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 Xn(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=Yn(o)??o;return la(new et(a,"api_error",{code:Ei(e?.outcome)??Ei(e?.type)??e?.gatewayErrorCode}),r)}function sa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function _o(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function ml(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 xi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||_o(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||_o(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||_o(P)))return P}}}}async function yl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=xi(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 Ri(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(_o(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function wr({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,ne=new Ri(d,m===!1?{telemetry:!1}:void 0),V=await ml(()=>ne.processPayment(P,{sessionId:T,nonce:h,tokenizedData:o,accountData:{userId:P,email:b,firstName:x,lastName:U,country:p,zip:S},returnUrl:a??sa(n)}));if(V.ok){let j=typeof V.json=="function"?await V.json().catch(()=>null):null;return sl(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:Hr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Hr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let v;try{v=await V.json()}catch{throw new et("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status})}if(v?.type==="paypal_redirect_required"||v?.type==="3ds_required"){let j=xi(v);if(!j)throw new et("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status});return{type:v.type,threeDSecureToken:j,paymentMethodId:v.paymentMethodId}}if(v?.gatewayErrorCode==="authentication_required"){let j=await yl({billingApiUrl:d,sessionId:T,nonce:h,responseJson:v});if(j)return j;throw la(new et("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let fe=new et(v?.message??"Payment failed. Please try again.","api_error",{code:v?.code??v?.gatewayErrorCode,declineCode:v?.declineCode??v?.gatewayDeclineReason,statusCode:V.status});throw Object.assign(fe,{telemetryOutcome:il(V.status,v)})}async function To(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:m,returnUrl:d,telemetry:T}){let h=t?.getRawProvider();if(!h)throw zn(new et("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw la(new et("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=ll(e.threeDSecureToken),b=null,x=e.paymentMethodId,U=await Wr(()=>cl(h,e.threeDSecureToken,P),"card");if(U){if(U.error)throw zn(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 Wr(()=>dl(h,e.threeDSecureToken,{payment_method:x,return_url:d??sa(m)??window.location.href},P),"card"):null;if(p){if(p.error)throw zn(new et(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");b=p.intent}else{let S=await Wr(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(S.error)throw zn(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 wr({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}:To(S,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:m,returnUrl:d,telemetry:T})}throw zn(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 zn(new et("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:x}=await Wr(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(x)throw zn(new et(x.message??"PayPal authorization failed.","api_error",{code:x.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Wr(()=>P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??sa(m)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw zn(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 cr(e){if(e instanceof et){let r=Yn(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=Yn(t)??t;return new et(n,"api_error")}function xo(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 Ao({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([Ii(e,{billingApiUrl:n,locale:r,telemetry:o}),a?Ii(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 Zr,toStripeAppearance as fl}from"@flopay/js";import{COUNTRY_OPTIONS as gl,classifyPaymentRejection as hl,FloPayError as wn,filterStripeMethodsByCountry as Pl,getPostalCodeExample as vl,getPostalCodeLabel as pa,getStateFromPostalCode as Bi,getStateLabel as Fi,getStateOptions as bl,getStripeMethodDisplayName as Ir,hasVendoredStripeMethodLogo as Cl,isAuthorizationOnlySession as ca,isAVSFieldVisible as Te,isPostalCodeSupported as Sl,isSetupIntentClientSecret as wl,isValidPostalCode as kl,needsStripeMethodExplicitConfirm as Di,normalizeCheckoutFailureOutcome as Il,partitionStripeMethods as El,resolveAVSConfig as Rl,resolveButtonsLayoutTheme as _l,resolveStripeMethodBrandVariant as Tl,resolveTheme as xl,stripeExpressMethodToOptionKey as Li}from"@flopay/shared";import{ExpressCheckoutElement as Vi,PaymentElement as Al,Elements as dr,useElements as ya,useStripe as fa}from"@stripe/react-stripe-js";import Ml,{useCallback as he,useContext as Er,useEffect as lt,useMemo as st,useRef as Ee,useState as ye}from"react";function Ai(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 Mi={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 kr,jsx as u,jsxs as xe}from"react/jsx-runtime";var An="flopay_stripe_resume",Oi="flopay_wallet_resume";function Hi(e){return e instanceof wn&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Bo(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Zr(e).createSessionIntent(...n)}catch(o){throw Hi(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Xr="flopay_paypal_resume",Bl=250,Ni="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ga(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Fo({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Zr(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Fl(e){return e instanceof wn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function da(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var Dl=`
|
|
3
|
+
${Bt.join(`
|
|
4
|
+
`)}`]}):null;return Y&&!dt?De?pr("div",{children:$n}):null:Ba("div",{children:[$n,St&&pr(Ir,{identity:St,methodLabel:"PayPal",testId:"flopay-direct-paypal-identity-pane",onComplete:v=>{Un(v)},submitting:I}),ue&&pr(Ir,{identity:ue.identity,methodLabel:ue.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:it,onCancel:()=>it(null)}),Ba("div",{"aria-hidden":ae||St||ue?!0:void 0,style:ae||St||ue?{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:de,"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:Ut,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 Kt(a)?.subscribe?.(m)},[m,a]),mr(()=>{if(!(!s||s===a))return Kt(s)?.subscribe?.(m)},[m,a,s]),mr(()=>{if(!a)return;let u=Kt(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=Kt(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 B=$l(n?.billingApiUrl),D=jl(()=>({flopay:a,paypalFlopay:s,billingApiUrl:B,emitInstrument:m}),[a,s,B,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 B=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(B),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,B)=>{let D=!1,u=0,w=0,ve=0,H=!1,C=()=>{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,C(),m(Ce)}finally{H=!1}}},Q=()=>{window.clearTimeout(ve),ve=window.setTimeout(()=>{fe()},250)},ce=()=>{D||(D=!0,C(),B(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,C(),m(null))};u=window.setTimeout(()=>{D||(D=!0,C(),B(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??"",B=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:B,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 C;try{C=await H.json()}catch{throw new lt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status})}if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let Q=ds(C);if(!Q)throw new lt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status});return{type:C.type,threeDSecureToken:Q,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let Q=await Ql({billingApiUrl:s,sessionId:S,nonce:b,responseJson:C});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(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:H.status});throw Object.assign(fe,{telemetryOutcome:Vl(H.status,C)})}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,B=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;!B&&w?.payment_method&&(typeof w.payment_method=="string"?B=w.payment_method:"id"in w.payment_method&&(B=w.payment_method.id??void 0))}let u=B?await vo(()=>Wl(b,e.threeDSecureToken,{payment_method:B,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??B}: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:B}=await vo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(B)throw rr(new lt(B.message??"PayPal authorization failed.","api_error",{code:B.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 Ee,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 Ie}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
|
-
`,Mo=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 Ll={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Yi={width:"100%",minHeight:Mo,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 Ol(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function zi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Gi(e){return e==="paypal"?"PayPal":Ir(e)}function Nl(e,t){let n=`We couldn't open ${Gi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Wi(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 ne={generation:S,method:p,timer:null,yieldedControl:!1};return r.current=ne,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,ne=p??S?.generation??t.current;(!p||S?.generation===p)&&(o(S),r.current=null),n.current=ne},[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 zl(e){let t=vl(e);return`Enter a valid ${pa(e)}${t?` (e.g. ${t})`:""}`}function Ul(e,t,n){let r=Sl(e),o=t.trim(),a=n&&r,m=a&&!o,d=a&&!!o&&!kl(e,o);return{visible:n,supported:r,required:a,empty:m,malformed:d}}function Ui(e,t){return t instanceof wn?t:new wn(t instanceof Error?t.message:`${Ol(e)} before-click hook failed.`,"validation_error")}function ua(){return u("style",{children:Dl})}function $l(e){return typeof e=="number"?`${e}px`:e}function Ji(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Xi({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 $i(e){return e!=="unavailable"&&e!=="load_error"}function Pa(e){return u(jl,{...e})}function qi({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=Wn(),{emitInstrument:p}=Er(gn),S=fa(),ne=ya(),[V,v]=ye("loading");lt(()=>{b?.(V)},[V,b]);let[fe,j]=ye(!1),J=Ee(!1),ce=Ee(null),Se=Ee(null),[re,le]=ye(0),[Ve,Ae]=ye(!1),Ce=Ee(!1),q=Ee(new Map),{startAttempt:B,finishAttempt:ee,invalidateAttempt:tt,isAttemptInvalidated:Me,isAttemptCurrent:H}=Wi((O,w,oe)=>{h?.(O,w,{...oe,popupBlocked:oe?.popupBlocked??Gn(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:Gn(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(Xr);if(R){let Y=JSON.parse(R);Y.clientSecret===oe&&(De={...Y.accountPatch?{accountPatch:Y.accountPatch}:{},...Y.sessionId?{sessionId:Y.sessionId}:{},...Y.nonce?{nonce:Y.nonce}:{}})}}catch{}try{localStorage.removeItem(Xr)}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?.(xt("paypal",$));return}let{paymentIntent:R,error:Y}=await S.retrievePaymentIntent(oe);if(Y){a?.(Y.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?.(xt("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||fe){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,fe,re]),Re=he(async O=>{if(!S||!ne)return;let w=q.current.get(re);if(w&&!H(w.generation)){q.current.delete(re);return}if(!w&&Me()||w&&!ee(w.generation))return;w||ee();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:Y,paymentMethod:$}=await R({type:"paypal"});if(Y){ae(Y,"stripe_paypal_create_payment_method_failed",w?.generation),O.paymentFailed({reason:"fail"});return}let Be=await Bo(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(Xr,JSON.stringify({clientSecret:Ie,sessionId:qe,nonce:De,accountPatch:oe?.accountPatch}))}catch{}let{error:G,paymentIntent:mt}=await S.confirmPayment({clientSecret:Ie,confirmParams:We,redirect:"if_required"});if(G){if(typeof window<"u")try{localStorage.removeItem(Xr)}catch{}if(Yr(G)){let Le=G.message??"Your payment was declined.";a?.(Le),T?.(xt("paypal",Le,{code:Nn(G),declineCode:Pr(G)})),await Fo({billingApiUrl:r,sessionId:qe,nonce:De,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Nn(G)??"provider_declined"}})}else ae(G,"stripe_paypal_confirm_failed",w?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Xr)}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,ne,e,t,n,r,p,o,a,T,P,ae,ee,H,Me,re]);return xe(kr,{children:[u(Xi,{state:V,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:Yi,children:"Try PayPal again"}),u(Vi,{onReady:O=>v(Ji(O,["paypal"])),onLoadError:()=>{v("load_error"),ga(At(U),"paypal","paypal")},onClick:pe,onConfirm:Re,onCancel:()=>{let O=q.current.get(re);q.current.delete(re),At(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)]})}),fe&&u(xn,{status:"processing"})]})}function ji({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=Wn(),{emitInstrument:S}=Er(gn),ne=fa(),V=ya(),[v,fe]=ye("loading");lt(()=>{x?.(v)},[v,x]);let[j,J]=ye(!1),ce=Ee(null),Se=Ee(null),[re,le]=ye(0),[Ve,Ae]=ye(!1),[Ce,q]=ye("google_pay"),B=Ee(!1),ee=Ee("google_pay"),tt=Ee("google_pay"),Me=Ee(new Map),{startAttempt:H,finishAttempt:de,invalidateAttempt:ae,isAttemptInvalidated:ue,isAttemptCurrent:ke}=Wi((Z,R,Y)=>{P?.(Z,R,{...Y,popupBlocked:Y?.popupBlocked??Gn(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,Y,$)=>{ae($),P?.(Z,R,{code:Y,popupBlocked:Gn(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(!ne||!V)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 Y=Z.expressPaymentType??R?.method??ee.current,$=R??null;Me.current.delete(re);let Be=zi(Y);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,G=$?.nonce??t,mt=$?.accountPatch?.email??n;try{J(!0),d?.(null);let{error:D}=await V.submit();if(D){Re(Y,D,"stripe_wallet_submit_failed",R?.generation);return}let{error:Le,paymentMethod:Pt}=await ne.createPaymentMethod({elements:V});if(Le||!Pt){Re(Y,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 Bo(r,S,We,G??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Y??Be,paymentMethodId:Pt.id,intentKind:o});if(N.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let vt=N.clientSecret,{error:ze,intentId:Qt}=wl(vt)?await ne.confirmCardSetup(vt,{payment_method:Pt.id}).then(It=>({error:It.error,intentId:It.setupIntent?.id})):await ne.confirmCardPayment(vt,{payment_method:Pt.id}).then(It=>({error:It.error,intentId:It.paymentIntent?.id}));if(ze){if(Yr(ze)){let It=ze.message??"Your payment was declined.";d?.(It),h?.(xt(Ie,It,{code:Nn(ze),declineCode:Pr(ze)})),await Fo({billingApiUrl:r,sessionId:We,nonce:G,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Y??Be,providerDeclineReason:Nn(ze)??"provider_declined"}})}else Re(Y,ze,"stripe_wallet_confirm_failed",R?.generation);return}m({id:Pt.id,type:"card",threeDSecureActionResultTokenId:Qt},{accountPatch:$?.accountPatch,sessionId:We,nonce:G})}catch(D){Re(Y,D,"stripe_wallet_failed",R?.generation)}finally{J(!1)}},[ne,V,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"]),Y=new Set(a.map(Li)),$={};for(let Be of Z)Y.has(Be)?$[Be]=R.has(Be)?"always":"auto":$[Be]="never";return $},[a]),De=st(()=>a.map(Li),[a]);return xe(kr,{children:[u(Xi,{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:Yi,children:["Try ",Gi(Ce)," again"]}),u(Vi,{onReady:Z=>{fe(Ji(Z,De))},onLoadError:Z=>{fe("load_error"),ga(At(p),"stripe","wallet")},onClick:async Z=>{ee.current=Z.expressPaymentType,tt.current=zi(Z.expressPaymentType);let R=b?await b(tt.current):{proceed:!0};if(!R.proceed){Me.current.delete(re),Z.reject();return}let Y=H(Z.expressPaymentType);Me.current.set(re,{generation:Y,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),At(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(xn,{status:"processing"})]})}function ql({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=Tl(e,t),U=Mi[e],[p,S]=ye(!1),ne=x?.backgroundColor??d??"#ffffff",V=x?.borderColor??T??"#d1d5db",v=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:Mo,padding:"0 1rem",backgroundColor:ne,color:v,border:`1px solid ${V}`,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 ${Ir(e)}\u2026`}):xe(kr,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:Cl(e)?8:0},children:[U&&!p?u("img",{src:U,alt:"","aria-hidden":"true",onError:()=>S(!0),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:Ir(e)})]}),a&&u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:v,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 ma({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:ne}){let V=Wn(),{emitInstrument:v}=Er(gn),fe=fa(),j=ya(),[J,ce]=ye(!1),Se=Ee(!1),[re,le]=ye(!1),[Ve,Ae]=ye("loading"),Ce=he(async()=>{if(!fe||!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,ee=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 H=await fe.createPaymentMethod({elements:j});if(H.error||!H.paymentMethod){d?.(H.error?.message??"Failed to create payment method.");return}let de=H.paymentMethod;if(!B||!tt)throw new Error("Missing sessionId or email for payment.");let ae=de.type||e,ue=await Bo(a,v,B,ee??"",{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(An,JSON.stringify({clientSecret:ke,sessionId:B,nonce:ee,accountPatch:q.accountPatch,paymentMethodId:de.id,paymentMethodType:de.type??e,gateway:"stripe"}))}catch{}let{error:pe,paymentIntent:Re}=await fe.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(An)}catch{}let oe=pe.message??"Payment failed.";d?.(oe),T?.(xt("card",oe,{code:pe.code})),await Fo({billingApiUrl:a,sessionId:B,nonce:ee,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:pe.code??"provider_declined"}});return}let O=Re?.status;if(!Po(O)){if(typeof window<"u")try{localStorage.removeItem(An)}catch{}let oe=O==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(oe),T?.(xt("card",oe,{code:O??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(An)}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:ee})}catch(Me){d?.(Me instanceof Error?Me.message:"Payment failed. Please try again.")}finally{Se.current=!1,ce(!1)}},[fe,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(Al,{onReady:()=>Ae("ready"),onLoadError:()=>{Ae("load_error"),ga(At(V),"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 ${Ir(e)}`}),ne&&u(Cr,{margin:"0.75rem 0 0",children:ne})]})}function Ki({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:ne=8,submitButtonStyle:V,buttonAppearance:v,themeId:fe,onExpandApm:j,expandedApmMethod:J}){let{emitInstrument:ce}=Er(gn),[Se,re]=ye(null),[le,Ve]=ye(null),Ae=Ee(!1);lt(()=>{a.length>0&&m?U?.("ready"):m||U?.("loading")},[a.length,m,U]);let Ce=he(async H=>{if(!m||Ae.current||p)return;Ae.current=!0,Ve(H);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 Bo(o,ce,ae,ue??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:H,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(An,JSON.stringify({clientSecret:Re,sessionId:ae,nonce:ue,accountPatch:de.accountPatch,paymentMethodType:H,gateway:"stripe"}))}catch{}let{error:O,paymentIntent:w}=await m.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:H,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(An)}catch{}let De=O.message??"Payment failed.";h?.(De),b?.(xt("card",De,{code:O.code})),await Fo({billingApiUrl:o,sessionId:ae,nonce:ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:H,providerDeclineReason:O.code??"provider_declined"}});return}let oe=w?.status;if(!Po(oe)){if(typeof window<"u")try{localStorage.removeItem(An)}catch{}let De=oe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(De),b?.(xt("card",De,{code:oe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(An)}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:H},{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]=ye(null),ee=j?J??null:q,tt=he(H=>{Ae.current||p||ee&&ee!==H||(Di(H)?j?j(H):B(H):Ce(H))},[ee,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(H=>{let de=J===H,ae=le===H,ue=le!==null&&le!==H||J!=null&&J!==H;return xe(Ml.Fragment,{children:[u(ql,{method:H,themeId:fe,submitting:ae,disabled:ue,highlighted:de,hasNextStep:Di(H),onClick:()=>tt(H),backgroundColor:v?.backgroundColor,borderColor:v?.borderColor,textColor:v?.textColor,borderRadius:v?.borderRadius,fontFamily:v?.fontFamily}),!j&&q===H&&Me&&m&&u(dr,{stripe:m,options:Me,children:u(ma,{method:H,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:ne,submitButtonStyle:V})},H)]},H)})})}function jl({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:ne=!0,showStripe:V=!0,enabledPaymentMethods:v,enabledPaymentMethodCountries:fe,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:ee,onBeforeButtonClick:tt,enableAVS:Me,cardFieldOrder:H,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:Y=0,currency:$="usd",initialCardOpen:Be=!1,directPaypal:Ie,isSubscription:We=!1,session:G,dataAttachmentPending:mt=!1,debug:D=!1}){let Le=Wn(),Pt=ea(),N=Er(Sn),{emitInstrument:vt}=Er(gn),ze=mt||N.claimPending===!0,Qt=gi(),[It,k]=ye(!1),[se,yt]=ye(null),[Fe,jt]=ye(ue??"US"),[Wt,Ge]=ye(ke??""),[bt,Je]=ye(pe??""),[Ft,je]=ye(Re??""),[Kt,Et]=ye(O??""),[en,Lt]=ye(w??""),[kn,on]=ye({}),rt=Ee(ke??""),Ot=Ee(ue??"US"),Ke=Ee(pe??""),In=Ee(Re??""),ct=Ee(O??""),Pn=Ee(w??""),Nt=Ee({});lt(()=>{let i=(_,z,Q,L,ge)=>{if(Nt.current[_])return;let we=z?.trim();!we||we===Q.current||(Q.current=we,L(we),ge?.(we))};i("country",ue,Ot,jt,oe),i("zip",ke,rt,Ge,qe),i("addressLine1",pe,Ke,Je),i("addressLine2",Re,In,je),i("city",O,ct,Et),i("state",w,Pn,Lt)},[ue,ke,pe,Re,O,w,oe,qe]);let te=st(()=>Rl(Me),[Me]),jn=te!==null,En=st(()=>ca(G),[G]),Rn=!!G?.vault?.html,_n=!!G?.gateways?.pcivault,I=!!(G?.gateways?.stripe?.enabledPaymentMethods??v)?.includes("card"),Xe=Rn||I||_n,Pe=!!(V&&Xe&&Le&&e),[vn,Oe]=ye(()=>ce!=="buttons"||Be?e??null:null),[Kn,er]=ye(0),Vt=ce!=="buttons"||Be||!!e&&vn===e,dt=st(()=>!Le||!Pe||!e||!Vt?null:Le.cardCapture({sessionId:e,captureMethod:G?.captureMethod}),[Le,Pe,e,Vt,G?.captureMethod]),Jt=st(()=>{let i=Fe,_=te?Te(te.postal_code,i):!1;return Ul(i,Wt,_)},[te,Fe,Wt]),{avsInvalid:Ht,invalidAvsFields:ot}=st(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Pe||!te)return{avsInvalid:!1,invalidAvsFields:i};let _=Fe,z=(ge,we)=>Te(ge,_)&&!we.trim(),Q={line1:z(te.address_line_1,bt),city:z(te.city,Kt),state:z(te.state,en),zip:Jt.empty||Jt.malformed};return{avsInvalid:Q.line1||Q.city||Q.state||Q.zip,invalidAvsFields:Q}},[Pe,te,Fe,bt,Kt,en,Jt]),[an,sn]=ye(!1),[Vn,bn]=ye(!1),[tn,ln]=ye(()=>da(G?.vault)),[me,Ct]=ye(Be&&Xe?"card":"buttons"),[at,nn]=ye(null),cn=me==="expanding"||me==="card",Fn=G?.gateways?.stripe?"stripe":void 0,dn=he(()=>{vt?.({class:"card_surface",provider:Fn})},[Fn,vt]),zt=280,Yt=Ee(null),Gt=he(i=>{Yt.current&&clearTimeout(Yt.current),Yt.current=setTimeout(()=>{Yt.current=null,i()},zt)},[zt]);lt(()=>()=>{Yt.current&&clearTimeout(Yt.current)},[]);let Hn=he(()=>{dn(),Oe(e??null),er(i=>i+1),Ct("expanding"),Gt(()=>Ct("card"))},[Gt,dn,e]),Dn=he(()=>{Ct("collapsing"),Gt(()=>Ct("buttons"))},[Gt]),Tn=he(i=>{nn(i),Ct("apm-expanding"),Gt(()=>Ct("apm-form"))},[Gt]),Ln=he(()=>{Ct("apm-collapsing"),Gt(()=>{Ct("buttons"),nn(null)})},[Gt]);lt(()=>{ce==="buttons"&&Be&&Xe&&(Oe(e??null),Ct("card"))},[ce,Be,Xe,e]);let[Ut,Ze]=ye(null),un=Ee(!1),$t=Ee(null),ut=Ee("idle"),[Xt,Rt]=ye(null),tr=Ee(Xt);lt(()=>{tr.current=Xt},[Xt]);let pt=n||Qt,l=p??se,s=st(()=>xl(Se),[Se]),c=st(()=>{let i=s?.buttonsLayout??_l(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(()=>si({appearance:A,buttonsStyles:c,layout:ce}),[A,c,ce]),F=N.inlineSessionPatchProcessing??!1,C=(U??It)||F,f=pt.replace(/\/+$/,""),y=st(()=>Qo({userId:o,email:r,firstName:h,lastName:P,country:ue,zip:ke},kn),[o,r,h,P,ue,ke,kn]),g=[y.firstName,y.lastName].filter(i=>!!i?.trim()).join(" "),E=st(()=>Le?Le.getRawProvider():null,[Le]),W=st(()=>Pt?Pt.getRawProvider():null,[Pt]),ie=Y||100,_e=st(()=>A?fl(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]),ve=st(()=>{let i=yi(Y);return{...i,currency:$.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...Ue}},[Y,$,Ue]),be=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?.(H??null,te==null)},[Pe,dt,H,te]),lt(()=>{(me==="expanding"||me==="collapsing"||me==="apm-expanding"||me==="apm-collapsing")&&M(null)},[me,M]);let St=he((i,_,z)=>{d?.(xt(i,_,z))},[d]),$e=he((i,_,z)=>{let Q=z?.popupBlocked??Gn(_),L=Nl(i,Q),ge=sr(z?.code)??Nn(_)??"external_payment_method_failed",we=new wn(L,"api_error",{code:"external_payment_method_failed",param:i});Ze(null),ce==="buttons"&&(Ct("buttons"),nn(null)),M(L),m?.(we),console.error("[FloPay] External payment method failed:",{method:i,code:ge,popupBlocked:Q})},[ce,m,M]);lt(()=>{if(!Pe||!e){ln(null);return}let i=da(G?.vault);if(i){ln(i);return}if(!Vt){ln(null);return}ln(null);let _=!0;return new Zr(f).getVaultCapture(e,t).then(z=>{if(!_)return;let Q=da(z);Q?ln(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,Vt,Kn,e,G?.vault?.html,G?.vault?.messageToken,G?.vault?.expectedOrigin,f,t,M]);let nt=Ee({onComplete:a,onError:m,updateError:M,emitDecline:St,resolvedAccount:y,avsConfig:te,avsCheckProp:De,sessionId:e,nonce:t,baseUrl:f,captureMethod:G?.captureMethod,paymentId:G?.paymentId,authorizationExpiresAt:G?.authorizationExpiresAt});nt.current={onComplete:a,onError:m,updateError:M,emitDecline:St,resolvedAccount:y,avsConfig:te,avsCheckProp:De,sessionId:e,nonce:t,baseUrl:f,captureMethod:G?.captureMethod,paymentId:G?.paymentId,authorizationExpiresAt:G?.authorizationExpiresAt};let nr=Ee(!1),Ba=he(()=>{let{resolvedAccount:i,avsConfig:_,avsCheckProp:z}=nt.current,Q=Ot.current||i.country||"US",L=_?Te(_.state,Q):!1,ge=_?Te(_.address_line_1,Q):!1,we=_?Te(_.postal_code,Q):!1,ft=_?Te(_.city,Q):!1,qt=_?Te(_.address_line_2,Q):!1,gt=ge&&!L&&we?Bi(Q,(rt.current??"").trim()):null,it=L?Pn.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}:{},...ge&&Ke.current?{addressLine1:Ke.current}:{},...qt&&In.current?{addressLine2:In.current}:{},country:Q},...z!==void 0?{avsCheck:z}:{},..._?{avsConfig:{country:Te(_.country,Q),postal_code:we,address_line_1:ge,address_line_2:qt,city:ft,state:L}}:{}}},[]),oo=Ee(ze);oo.current=ze,lt(()=>{ze||l!==Ni||nt.current.updateError(null)},[ze,l]),lt(()=>{!Pe||!dt||dt.setSubmitGate?.(Ht||ze)},[Pe,dt,Ht,ze]),lt(()=>{if(!Pe||!dt)return;nr.current=!1;let i=!1,_=dt.on("submitting",()=>{sn(!0),$t.current&&clearTimeout($t.current),ut.current="validation-window",$t.current=setTimeout(()=>{$t.current=null,ut.current==="validation-window"&&(ut.current="processing")},Bl),Ze("processing");let{baseUrl:we,sessionId:ft,nonce:qt,updateError:gt,onError:it}=nt.current;!ft||!qt||new Zr(we).patchAccountSnapshot(ft,qt,Ba(),{telemetryMode:"best_effort"}).catch(Ne=>{if(!Fl(Ne))return;let On=Ne instanceof Error?Ne.message:"Please check your billing address and try again.";gt(On),ut.current="idle",Ze(null),it?.(Ne instanceof wn?Ne:new wn(On,"api_error"))})}),z=dt.on("complete",async we=>{if(Sr(we.sessionId??nt.current.sessionId),ut.current="terminal",Ze("success"),await new Promise(gt=>setTimeout(gt,1200)),nr.current)return;nr.current=!0;let ft=nt.current,qt=ca(ft)||we.outcome==="authorized";nt.current.onComplete?.(qt?{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:qt}=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??Il(we.declineReason)??"authorization_declined";qt("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:qt}=nt.current,gt=we.message??"There was a problem processing your payment. Please try again.";ut.current="terminal",ft(gt),Ze("error"),qt?.(new wn(gt,"api_error",{code:we.failureOutcome??"capture_failed"})),await new Promise(it=>setTimeout(it,1500)),!i&&(ut.current="idle",Ze(null))}),ge=dt.on("blocked",()=>{if(!oo.current){sn(!0);return}nt.current.updateError(Ni)});return()=>{i=!0,$t.current&&(clearTimeout($t.current),$t.current=null),ut.current="idle",_(),z(),Q(),L(),ge()}},[Pe,dt]);let rn=!!Ie?.clientId,Mr=Array.isArray(v),ao=Mr&&v.length>0,ls=Mr&&v.includes("paypal"),{expressMethods:io,paymentElementMethods:Br}=st(()=>El(v,{excludePaypal:rn}),[v,rn]),Fa=rn||!!Pt,cs=st(()=>Fa?io.filter(i=>i!=="paypal"):io,[io,Fa]),ds=st(()=>{let i=[];return j&&i.push("apple_pay"),J&&i.push("google_pay"),i},[j,J]),so=Mr?cs:ds,us=V&&so.length>0,zo=jn?Fe:ue,lo=st(()=>{let i=zo?.trim().toUpperCase();return i?fe?Br.filter(_=>{let z=fe[_];return!z||z.length===0||z.includes(i)}):Pl(Br,zo):Br},[Br,zo,fe]),Uo=st(()=>({mode:"payment",amount:ie,currency:$.toLowerCase(),paymentMethodCreation:"manual",appearance:Tt}),[ie,$,Tt]),[Da,La]=ye("loading"),[Oa,Na]=ye("loading"),[za,Ua]=ye("loading"),[ps,$o]=ye(!1),[$a,qo]=ye("loading"),[co,ms]=ye();lt(()=>{ms(Ai())},[]);let qa=ne&&(rn||(Mr?ls:co===!1)),ja=V&&us,Fr=!ze&&qa&&rn,Ka=$a==="retrying"||$a==="exhausted",Dr=!ze&&qa&&!!W&&(!rn||Ka),Lr=!ze&&ja&&!!E,Or=!ze&&V&&ao&&lo.length>0&&!!E,ys=Fr&&!Ka?ps:Dr&&$i(Da),fs=Lr&&$i(Oa),gs=Or&&za!=="load_error",Va=i=>i==="loading"||i==="ready",Ha=Fr||Dr&&Va(Da)||Lr&&Va(Oa)||Or&&za!=="load_error",uo=Ee(!1);lt(()=>{if(!uo.current){if(!V&&!ne){uo.current=!0;let i=new wn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");m?.(i),M(i.message)}else if(!V&&ne&&!rn&&!W){uo.current=!0;let i=new wn("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(co!==void 0&&!ze&&!Xe&&!Ha){uo.current=!0;let i=new wn("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)}}},[V,ne,rn,W,co,ze,Xe,Ha,m,M]);let Ya=Ee(!1);lt(()=>{if(Ya.current||!ao)return;let i=[];j!==!0&&i.push("showApplePay"),J!==!0&&i.push("showGooglePay"),i.length!==0&&(Ya.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,j,J]);let Ga=he((i,_)=>N.applyInlineSessionPatch?N.applyInlineSessionPatch(i).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let Q=Ui(_,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]),Cn=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&&on(Q=>({...Q??{},..._.account}));let z=await Ga(_,i);return z.error?{proceed:!1,accountPatch:_.account}:{proceed:!0,accountPatch:_.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(_){let z=Ui(i,_);return M(z.message),m?.(z),{proceed:!1}}},[Ga,N.inlineSessionDraft,tt,m,e,M]),Wa=he(async(i,_)=>{if(un.current)return;un.current=!0,k(!0),Ze("processing"),M(null);let z=_?.sessionId??e,Q=_?.nonce??t,L=Qo(y,_?.accountPatch),ge=_?.completionPaymentMethodId??Hr(i),we=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,ft=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,qt=()=>{vt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ft})};try{let it=await new Zr(f).processPayment(L.userId??"",{sessionId:z,nonce:Q,tokenizedData:we,accountData:{userId:L.userId??"",email:L.email??"",firstName:L.firstName??"",lastName:L.lastName??"",...te?(()=>{let He=Ot.current,mn=Te(te.state,He),yn=Te(te.address_line_1,He),Dt=Te(te.postal_code,He),qr=yn&&!mn&&Dt?Bi(He,(rt.current??"").trim()):null,jr=mn?Pn.current:qr;return{country:He,...Dt&&rt.current?{zip:rt.current}:{},...Te(te.city,He)&&ct.current?{city:ct.current}:{},...jr?{state:jr}:{},...yn&&Ke.current?{addressLine1:Ke.current}:{},...Te(te.address_line_2,He)&&In.current?{addressLine2:In.current}:{}}})():{}},chv:b,avsCheck:De??!1,checkoutType:Z,checkoutLayout:R,avsConfig:te?{country:Te(te.country,Ot.current),postal_code:Te(te.postal_code,Ot.current),address_line_1:Te(te.address_line_1,Ot.current),address_line_2:Te(te.address_line_2,Ot.current),city:Te(te.city,Ot.current),state:Te(te.state,Ot.current)}:void 0});if(it.ok){let He=it.status===204?null:await it.json().catch(()=>null),mn=ca(G)||He?.status==="authorized";Sr(z),Ze("success"),Rt(null),await new Promise(yn=>setTimeout(yn,1200)),a?.(mn?{status:"authorized",...typeof He?.paymentId=="string"?{paymentId:He.paymentId}:G?.paymentId?{paymentId:G.paymentId}:{},sessionId:typeof He?.sessionId=="string"?He.sessionId:z,...typeof He?.authorizationExpiresAt=="string"?{authorizationExpiresAt:He.authorizationExpiresAt}:G?.authorizationExpiresAt?{authorizationExpiresAt:G.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:ge,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:ge,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Ne=await it.json().catch(()=>null);if(Ne?.type==="paypal_redirect_required"){let He=Ne.threeDSecureToken,mn=Ne.paymentMethodId||i.id||"";if(!Le||!He){Ze("error"),M("PayPal authorization required but no token provided.");return}try{let yn=Pt?.getRawProvider();if(!yn){M("PayPal is not available.");return}let Dt={return_url:window.location.href};mn&&(Dt.payment_method=mn);let{error:qr}=await yn.confirmPayment({clientSecret:He,confirmParams:Dt,redirect:"if_required"});if(qr){Ze("error");let jr=qr.message??"PayPal payment failed.";M(jr),St("paypal",jr,{code:qr.code})}}catch(yn){Ze("error"),M(yn instanceof Error?yn.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 mn=tr.current?.attempts??0;if(mn>=2){Ze("error"),M("PayPal payment could not be completed after multiple attempts."),St("paypal","paypal_direct_required retry limit exceeded");return}$o(!1),qo("loading"),Rt({orderId:He,attempts:mn+1}),Ze(null);return}hl(it.status,Ne)||qt(),Ze("error");let On=Ne?.message??"Payment failed. Please try again.";M(On),St(i.isPaypal?"paypal":"card",On,{code:Ne?.code??Ne?.gatewayErrorCode,declineCode:Ne?.declineCode??Ne?.gatewayDeclineReason}),await new Promise(He=>setTimeout(He,1500))}catch(gt){Hi(gt)||qt(),Ze("error"),M(gt instanceof Error?gt.message:"An unexpected error occurred"),await new Promise(it=>setTimeout(it,1500))}finally{k(!1),Ze(null),un.current=!1}},[f,e,t,y,g,b,Le,Pt,G,a,m,M,St,vt]),pn=he((i,_)=>{T?T(i):Wa(i,_)},[T,Wa]),Ja=Ee(!1);lt(()=>{if(typeof window>"u"||Ja.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}},ge=L(An)??L(Oi),we;if(ge?.clientSecret){if(ge.clientSecret!==z)return;we={...ge.accountPatch?{accountPatch:ge.accountPatch}:{},...ge.sessionId?{sessionId:ge.sessionId}:{},...ge.nonce?{nonce:ge.nonce}:{}}}else if(ge?.sessionId&&ge.sessionId!==e)return;Ja.current=!0,localStorage.removeItem(An),localStorage.removeItem(Oi);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 qt=ge?.paymentMethodType??ge?.tokenType??"card",gt="card";(async()=>{let it=Le?.getRawProvider();if(!it){let Dt="Payment is not available \u2014 please refresh and try again.";M(Dt),St(gt,Dt);return}if(Q==="failed"){let Dt="Payment was declined. Please try again.";M(Dt),St(gt,Dt);return}let{paymentIntent:Ne,error:On}=await it.retrievePaymentIntent(z);if(On){let Dt=On.message??"Failed to retrieve payment status.";M(Dt),St(gt,Dt,{code:On.code});return}let He=Ne?.status,mn=Po(He);if(!Ne||!mn){let Dt=He==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";M(Dt),St(gt,Dt,{code:He??"missing_payment_intent"});return}let yn=typeof Ne.payment_method=="string"?Ne.payment_method:Ne.payment_method?.id;pn({id:yn??ge?.paymentMethodId??ge?.tokenId??Ne.id,type:"card",threeDSecureActionResultTokenId:Ne.id,gateway:ge?.gateway??"stripe",paymentMethodType:qt},we)})()},[e,pn,Le,M,St]);let jo=he(i=>{i.preventDefault()},[]);if(!(Le!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Nr=ce==="buttons",Zt=A?.variables,hs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ko=Zt?.colorBackground,Ps=Ko&&!hs.has(Ko)?Ko:void 0,zr=c.cardInputBorder??(Nr?"#e5e7eb":"#A4A4FF"),Vo=Zt?.colorDanger??"#dc2626",rr=i=>an&&i?Vo:zr,po=(Jt.malformed||Jt.empty)&&(Vn||an),vs=po?Vo:rr(ot.zip),Ho=c.cardFormContainer?.backgroundColor??Ps??(Nr?"white":"#EDEDFF"),Ur=c.cardInputBackground??Zt?.colorBackground??"white",Yo=mr(Ce),Xa=mr(q),pr=c.nameInput,Za=c.cardInputFontSize??$l(pr?.fontSize)??Zt?.fontSizeBase??"16px",Qa=typeof pr?.fontFamily=="string"?pr.fontFamily:Zt?.fontFamily??"Poppins, sans-serif",ei=ii(pr?.fontWeight)??400,bs=c.cardInputColor??(typeof pr?.color=="string"?pr.color:void 0)??Zt?.colorText??"#262833",Cs=c.cardInputPlaceholderColor??"#9ca3af",wt=Zt?.borderRadius??"8px",or=Zt?.borderRadius??c.cardButton?.borderRadius??wt,ar=Zt?.colorPrimary??"#4A49FF",Ss=Zt?.colorPrimaryHover??Kr(ar,.12),Go=Zt?.colorText??"#262833",ti={fontSize:Za,fontFamily:Qa,fontWeight:ei,color:bs,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ws={"--flopay-input-placeholder-color":Cs,"--flopay-input-font-size":Za,"--flopay-input-font-family":Qa,"--flopay-input-font-weight":String(ei)},$r=c.cardFormContainer??{},Wo=$r.padding??(Nr?"0":"1rem"),Jo=$r.borderRadius??wt,ks=dt&&tn?u(Xo,{capture:dt,html:tn.html,messageToken:tn.messageToken,expectedOrigin:tn.expectedOrigin,theme:K,onReady:()=>{if(!te||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"&&($t.current&&(clearTimeout($t.current),$t.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"}),ni=xe("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&dn()},style:{backgroundColor:Ho,borderRadius:Jo,...$r,padding:Wo,...ws,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=Ee(0),n=Ee(null),r=Ee(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,[]),B=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"?B():D()},w=()=>{D()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",w),window.addEventListener("focus",B),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",w),window.removeEventListener("focus",B),o()}},[o,D,B]),{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:Ie("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:B,onLoadStateChange:D,placeholderBorderRadius:u}){let w=ur(),{emitInstrument:ve}=Yr(In),H=Ka(),C=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=Ee(!1),Te=Ee(null),Ae=Ee(null),[ee,J]=ye(0),[L,de]=ye(!1),et=Ee(!1),Ue=Ee(new Map),{startAttempt:Ye,finishAttempt:te,invalidateAttempt:T,isAttemptInvalidated:ae,isAttemptCurrent:Fe}=xs((G,Y,$)=>{b?.(G,Y,{...$,popupBlocked:$?.popupBlocked??dr(Y)}),de(!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)}),de(!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(()=>{de(!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 Be;try{let K=localStorage.getItem(Co);if(K){let I=JSON.parse(K);I.clientSecret===$&&(Be={...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 P="PayPal payment was declined. Please try again.";a?.(P),S?.(jt("paypal",P));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 P=typeof K.payment_method=="string"?K.payment_method:K.payment_method?.id;o({id:P??K.id,type:"card",threeDSecureActionResultTokenId:K.id,isPaypal:!0},Be)}else{let P="PayPal payment was not completed. Please try again.";a?.(P),S?.(jt("paypal",P))}}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}),de(!1),s?.("paypal"),G.resolve()},[Ue,c,s,g,Ye,ce,ee]),Se=Pe(async G=>{if(!H||!C)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 P=await g("paypal");if(!P.proceed){G.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}}let we=$?.sessionId??e,Be=$?.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 B?.(x);let P=H.createPaymentMethod,{error:nt,paymentMethod:St}=await P({type:"paypal"});if(nt){j(nt,"stripe_paypal_create_payment_method_failed",Y?.generation),G.paymentFailed({reason:"fail"});return}let ue=await oa(r,ve,we,Be??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:St?.id??null,intentKind:"payment"});if(ue.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=ue.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:Be,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?.(jt("paypal",U,{code:tr(rt),declineCode:$r(rt)})),await aa({billingApiUrl:r,sessionId:we,nonce:Be,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:Be});return}catch(P){j(P,"stripe_paypal_failed",Y?.generation)}finally{oe(!1)}},[H,C,e,t,n,m,be,B,r,ve,o,a,S,g,j,te,Fe,ae,ee]);return Ie(fr,{children:[l(As,{state:fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:u,children:Ie("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(Kt(w),"paypal","paypal")},onClick:We,onConfirm:Se,onCancel:()=>{let G=Ue.current.get(ee);Ue.current.delete(ee),Kt(w)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(G?.generation),de(!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:B,onBuyerIdentityReady:D,onLoadStateChange:u,placeholderBorderRadius:w}){let ve=ur(),{emitInstrument:H}=Yr(In),C=Ka(),fe=ja(),[Q,ce]=ye("loading");ht(()=>{u?.(Q)},[Q,u]);let[oe,Ce]=ye(!1),He=!en(n?.trim())||!B?.trim(),{request:be,collect:Rt,finish:De}=qr(),Te=Ee(null),Ae=Ee(null),[ee,J]=ye(0),[L,de]=ye(!1),[et,Ue]=ye("google_pay"),Ye=Ee(!1),te=Ee("google_pay"),T=Ee("google_pay"),ae=Ee(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),de(!0),J(P=>P+1)});ht(()=>{L&&Ae.current?.focus()},[L,ee]);let We=Pe(()=>{J(x=>x+1)},[]),Se=Pe((x,K,I,P)=>{j(P),g?.(x,K,{code:I,popupBlocked:dr(K)}),Ue(x),de(!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(()=>{de(!1),s?.(null),G()},[G,s]),$=Pe(async x=>{if(!C||!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,P=K??null;ae.current.delete(ee);let nt=vs(I);if(!P&&m){let y=await m(nt);if(!y.proceed){x.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}P={accountPatch:y.accountPatch,sessionId:y.sessionId,nonce:y.nonce}}let St=nt,ue=P?.sessionId??e,ct=P?.nonce??t,it=await Rs({event:x,prepared:P,email:n,billingName:B,methodLabel:qa(I),collect:Rt});if(!it){x.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let rt=it.email,je={...P?.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 C.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(!ue)throw new Error("Missing sessionId or email for wallet payment");let dt=await oa(r,H,ue,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 Bt=dt.clientSecret,{error:Mt,intentId:W}=lc(Bt)?await C.confirmCardSetup(Bt,{payment_method:Xe.id}).then(Le=>({error:Le.error,intentId:Le.setupIntent?.id})):await C.confirmCardPayment(Bt,{payment_method:Xe.id}).then(Le=>({error:Le.error,intentId:Le.paymentIntent?.id}));if(Mt){if(go(Mt)){let Le=Mt.message??"Your payment was declined.";s?.(Le),b?.(jt(St,Le,{code:tr(Mt),declineCode:$r(Mt)})),await aa({billingApiUrl:r,sessionId:ue,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I??nt,providerDeclineReason:tr(Mt)??"provider_declined"}})}else Se(I,Mt,"stripe_wallet_confirm_failed",K?.generation);return}c({id:Xe.id,type:"card",threeDSecureActionResultTokenId:W},{accountPatch:je,sessionId:ue,nonce:ct})}catch(y){Se(I,y,"stripe_wallet_failed",K?.generation)}finally{Ce(!1)}},[C,fe,e,t,n,B,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)),P={};for(let nt of x)I.has(nt)?P[nt]=K.has(nt)?"always":"auto":P[nt]="never";return P},[a]),Be=gt(()=>a.map(gs),[a]);return Ie(fr,{children:[l(As,{state:Q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:w,children:Ie("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&&Ie("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,Be))},onLoadError:x=>{ce("load_error"),Va(Kt(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}),de(!1),S?.(T.current),x.resolve()},onConfirm:$,onCancel:()=>{let x=ae.current.get(ee);ae.current.delete(ee),Kt(ve)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),j(x?.generation),de(!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 B=yc(e,t),D=ps[e],[u,w]=ye(!1),ve=B?.backgroundColor??s??"#ffffff",H=B?.borderColor??S??"#d1d5db",C=B?.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:C,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`}):Ie(fr,{children:[Ie("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"}}):B?.logoSvg?l("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:B.logoSvg}}):null,l("span",{children:xr(e)})]}),a&&l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:C,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:B,isProcessing:D,submitButtonColor:u,submitButtonBorderRadius:w,submitButtonStyle:ve,errorText:H}){let C=ur(),{emitInstrument:fe}=Yr(In),Q=Ka(),ce=ja(),[oe,Ce]=ye(!1),He=Ee(!1),[be,Rt]=ye(!1),[De,Te]=ye("loading"),[Ae,ee]=ye(""),[J,L]=ye(""),de=!en(r?.trim()),et=!o?.trim(),Ue=(!de||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}B?.("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:Be}=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?.(jt("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=Be?.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?.(jt("card",I,{code:x??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let K=typeof Be?.payment_method=="string"?Be.payment_method:Be?.payment_method?.id;s({id:K??Se.id,type:"card",threeDSecureActionResultTokenId:Be?.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,B,t,n,r,o,Ae,J,a,c,fe,e,s,S,b]);return Ie("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(de||et)&&Ie("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:[de&&Ie("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&&Ie("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(Kt(C),"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:B,runBeforeButtonClick:D,onLoadStateChange:u,isProcessing:w=!1,submitButtonColor:ve="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:C,buttonAppearance:fe,themeId:Q,onExpandApm:ce,expandedApmMethod:oe}){let{emitInstrument:Ce}=Yr(In),[He,be]=ye(null),[Rt,De]=ye(null),Te=Ee(!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),B?.(jt("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),B?.(jt("card",x,{code:we??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let Be=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;b({id:Be??$?.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,B]),[de,et]=ye(null),Ue=ce?oe??null:de,Ye=Pe(T=>{Te.current||w||Ue&&Ue!==T||(fs(T)?ce?ce(T):et(T):L(T))},[Ue,w,L,ce]),te=gt(()=>de?{...S,paymentMethodTypes:[de]}:null,[de,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 Ie(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&&de===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:B,onCancel:()=>et(null),runBeforeButtonClick:D,onButtonClick:m,isProcessing:w,submitButtonColor:ve,submitButtonBorderRadius:H,submitButtonStyle:C})},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:B,isProcessing:D,error:u,onErrorChange:w,showPayPal:ve=!0,showStripe:H=!0,enabledPaymentMethods:C,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:de,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:Be=!1,directPaypal:x,isSubscription:K=!1,session:I,dataAttachmentPending:P=!1,dataAttachmentRequiresIdentity:nt=!1,debug:St=!1}){let ue=ur(),ct=_a(),it=Yr(Ln),{emitInstrument:rt}=Yr(In),je=P||it.claimPending===!0,y=nt||it.claimRequiresIdentity===!0,U=je&&!y,Xe=Ji(),[dt,Bt]=ye(!1),[Mt,W]=ye(null),[Le,Jt]=ye(T??"US"),[wt,zt]=ye(ae??""),[Rn,_n]=ye(Fe??""),[Zn,Xt]=ye(ie??""),[cn,dn]=ye(j??""),[Ft,vn]=ye(_e??""),[bt,ir]=ye(""),[Yt,sr]=ye(""),[Nt,zn]=ye({}),ot=Ee(ae??""),_t=Ee(T??"US"),xt=Ee(Fe??""),tn=Ee(ie??""),un=Ee(j??""),pn=Ee(_e??""),Un=Ee(""),qn=Ee(""),Ut=Ee({});ht(()=>{let i=(R,N,he,z,Re)=>{if(Ut.current[R])return;let Ne=N?.trim();!Ne||Ne===he.current||(he.current=Ne,z(Ne),Re?.(Ne))};i("country",T,_t,Jt,Je),i("zip",ae,ot,zt,We),i("addressLine1",Fe,xt,_n),i("addressLine2",ie,tn,Xt),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??C)?.includes("card"),mn=Qn||Tn||br,Me=!!(H&&mn&&ue&&e),[Zt,Dt]=ye(()=>oe!=="buttons"||Be?e??null:null),[$n,v]=ye(0),ut=oe!=="buttons"||Be||!!e&&Zt===e,qe=gt(()=>!ue||!Me||!e||!ut?null:ue.cardCapture({sessionId:e,captureMethod:I?.captureMethod}),[ue,Me,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:qt}=gt(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Me||!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}},[Me,X,Le,Rn,cn,Ft,yn]),[lr,jn]=ye(!1),[Cn,Lt]=ye(!1),[fn,gn]=ye(()=>Oa(I?.vault)),[xe,kt]=ye(Be&&mn?"card":"buttons"),[Tt,An]=ye(null),hn=xe==="expanding"||xe==="card",Bn=I?.gateways?.stripe?"stripe":void 0,Mn=Pe(()=>{rt?.({class:"card_surface",provider:Bn})},[Bn,rt]),$t=280,nn=Ee(null),an=Pe(i=>{nn.current&&clearTimeout(nn.current),nn.current=setTimeout(()=>{nn.current=null,i()},$t)},[$t]);ht(()=>()=>{nn.current&&clearTimeout(nn.current)},[]);let er=Pe(()=>{Mn(),Dt(e??null),v(i=>i+1),kt("expanding"),an(()=>kt("card"))},[an,Mn,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"&&Be&&mn&&(Dt(e??null),kt("card"))},[oe,Be,mn,e]);let[Qt,at]=ye(null),Gt=Ee(!1),_=Ee(null),E=Ee("idle"),[V,Z]=ye(null),$e=Ee(V);ht(()=>{$e.current=V},[V]);let ne=n||Xe,M=u??Mt,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]),ke=[k.firstName,k.lastName].filter(i=>!!i?.trim()).join(" "),q=!en(k.email?.trim()),F=!ke.trim(),Ge=Ee(null),Qe=Ee(null);Me&&(Ge.current===null&&(Ge.current=q),Qe.current===null&&(Qe.current=F));let se=Me&&(Ge.current??q),pe=Me&&(Qe.current??F),A=se||pe,le=gt(()=>Rc(bt,se),[bt,se]),st=le.empty||le.malformed,Ot=pe&&!Yt.trim(),ge=gt(()=>ue?ue.getRawProvider():null,[ue]),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]),me=Pe(i=>{W(i),w?.(i)},[w]),da=Ee(""),[ui,$s]=ye(!1),To=Pe(()=>{$s(!0)},[]);ht(()=>{if(!Me||!A||!de||!ui||st||Ot||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(de(R)).catch(N=>{da.current="",me(N instanceof Error?N.message:"Failed to attach buyer details.")})},[Me,A,de,ui,st,Ot,k.email,k.firstName,k.lastName,me]),ht(()=>{!Me||!qe||qe.setCardFieldOrder?.(Ue??null,X==null&&!A)},[Me,qe,Ue,X,A]),ht(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&me(null)},[xe,me]);let Nn=Pe((i,R,N)=>{s?.(jt(i,R,N))},[s]),Br=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)),me(z),c?.(Ne),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:he})},[oe,c,me]);ht(()=>{if(!Me||!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):me("Failed to load the secure card form.")}).catch(N=>{R&&me(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{R=!1}},[Me,ut,$n,e,I?.vault?.html,I?.vault?.messageToken,I?.vault?.expectedOrigin,p,t,me]);let Vn=Ee({onComplete:a,onError:c,updateError:me,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:me,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=Ee(!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,rn=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,on=mt?pn.current:ln;return{accountData:{userId:i.userId??"",email:z,firstName:Ne??"",lastName:It??"",...Ke&&ot.current?{zip:ot.current}:{},...rn&&un.current?{city:un.current}:{},...on?{state:on}:{},...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:rn,state:mt}}:{}}},[]),pi=Ee(je);pi.current=je,ht(()=>{je||M!==bs||Vn.current.updateError(null)},[je,M]),ht(()=>{!Me||!qe||qe.setSubmitGate?.(Ze||je||st||Ot)},[Me,qe,Ze,je,st,Ot]),ht(()=>{if(!Me||!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(rn=>{if(!vc(rn))return;let Oe=rn instanceof Error?rn.message:"Please check your billing address and try again.";mt(Oe),E.current="idle",at(null),yt?.(rn instanceof On?rn: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()}},[Me,qe,To]);let Hn=!!x?.clientId,eo=Array.isArray(C),Ao=eo&&C.length>0,Ks=eo&&C.includes("paypal"),{expressMethods:Bo,paymentElementMethods:to}=gt(()=>uc(C,{excludePaypal:Hn}),[C,Hn]),mi=Hn||!!ct,Vs=gt(()=>mi?Bo.filter(i=>i!=="paypal"):Bo,[Bo,mi]),Hs=gt(()=>{let i=[];return Q&&i.push("apple_pay"),ce&&i.push("google_pay"),i},[Q,ce]),Mo=eo?Vs:Hs,Ys=H&&Mo.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=Ee(!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),me(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),me(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),me(i.message)}}},[H,ve,Hn,bn,No,U,mn,Ii,c,me]);let Ei=Ee(!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 me(he.message),c?.(he),{error:he,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[it.applyInlineSessionPatch,t,c,e,me]),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 me(N.message),c?.(N),{proceed:!1}}},[Ri,it.inlineSessionDraft,L,c,e,me]),_i=Pe(async(i,R)=>{if(Gt.current)return;Gt.current=!0,Bt(!0),at("processing"),me(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),on=ze(X.address_line_1,Oe),Wt=ze(X.postal_code,Oe),co=on&&!ln&&Wt?ms(Oe,(ot.current??"").trim()):null,uo=ln?pn.current:co;return{country:Oe,...Wt&&ot.current?{zip:ot.current}:{},...ze(X.city,Oe)&&un.current?{city:un.current}:{},...uo?{state:uo}:{},...on&&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(on=>setTimeout(on,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(!ue||!Oe){at("error"),me("PayPal authorization required but no token provided.");return}try{let on=ct?.getRawProvider();if(!on){me("PayPal is not available.");return}let Wt={return_url:window.location.href};ln&&(Wt.payment_method=ln);let{error:co}=await on.confirmPayment({clientSecret:Oe,confirmParams:Wt,redirect:"if_required"});if(co){at("error");let uo=co.message??"PayPal payment failed.";me(uo),Nn("paypal",uo,{code:co.code})}}catch(on){at("error"),me(on instanceof Error?on.message:"PayPal authorization failed.")}return}if(Ke?.type==="paypal_direct_required"){let Oe=Ke.orderId;if(!Oe){at("error"),me("PayPal retry required but no order id provided.");return}let ln=$e.current?.attempts??0;if(ln>=2){at("error"),me("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 rn=Ke?.message??"Payment failed. Please try again.";me(rn),Nn(i.isPaypal?"paypal":"card",rn,{code:Ke?.code??Ke?.gatewayErrorCode,declineCode:Ke?.declineCode??Ke?.gatewayDeclineReason}),await new Promise(Oe=>setTimeout(Oe,1500))}catch(mt){Es(mt)||Ct(),at("error"),me(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(yt=>setTimeout(yt,1500))}finally{Bt(!1),at(null),Gt.current=!1}},[p,e,t,k,ke,m,ue,ct,I,a,c,me,Nn,rt]),Sn=Pe((i,R)=>{S?S(i):_i(i,R)},[S,_i]),xi=Ee(!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=ue?.getRawProvider();if(!yt){let Wt="Payment is not available \u2014 please refresh and try again.";me(Wt),Nn(mt,Wt);return}if(he==="failed"){let Wt="Payment was declined. Please try again.";me(Wt),Nn(mt,Wt);return}let{paymentIntent:Ke,error:rn}=await yt.retrievePaymentIntent(N);if(rn){let Wt=rn.message??"Failed to retrieve payment status.";me(Wt),Nn(mt,Wt,{code:rn.code});return}let Oe=Ke?.status,ln=jo(Oe);if(!Ke||!ln){let Wt=Oe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(Wt),Nn(mt,Wt,{code:Oe??"missing_payment_intent"});return}let on=typeof Ke.payment_method=="string"?Ke.payment_method:Ke.payment_method?.id;Sn({id:on??Re?.paymentMethodId??Re?.tokenId??Ke.id,type:"card",threeDSecureActionResultTokenId:Ke.id,gateway:Re?.gateway??"stripe",paymentMethodType:Ct},Ne)})()},[e,Sn,ue,me,Nn]);let ga=Pe(i=>{i.preventDefault()},[]);if(!(ue!==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(qt.zip),va=f.cardFormContainer?.backgroundColor??el??(io?"white":"#EDEDFF"),Cr=f.cardInputBackground??sn?.colorBackground??"white",Pa=Nr(Te),Ti=Nr(Ae),Mr=f.nameInput,Ai=f.cardInputFontSize??_c(Mr?.fontSize)??sn?.fontSizeBase??"16px",Bi=typeof Mr?.fontFamily=="string"?Mr.fontFamily:sn?.fontFamily??"Poppins, sans-serif",Mi=Oi(Mr?.fontWeight)??400,nl=f.cardInputColor??(typeof Mr?.color=="string"?Mr.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:Bi,fontWeight:Mi,color:nl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},al={"--flopay-input-placeholder-color":rl,"--flopay-input-font-size":Ai,"--flopay-input-font-family":Bi,"--flopay-input-font-weight":String(Mi)},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=>me(i),onValidation:i=>{let R=E.current;(R==="idle"||R==="validation-window")&&(me(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=Ie("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Mn()},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
|
-
`}),
|
|
34
|
-
`)}):null,
|
|
35
|
-
`)}):null,ai=me==="apm-expanding"||me==="apm-form"||me==="apm-collapsing",yo=me==="apm-expanding"?`flopay-card-enter ${zt}ms cubic-bezier(0, 0, 0.2, 1) both`:me==="apm-collapsing"?`flopay-card-exit ${zt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,fo=at?{...Uo,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:Mo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Q=me==="expanding"||me==="apm-expanding"?`flopay-buttons-exit ${zt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:me==="collapsing"||me==="apm-collapsing"?`flopay-buttons-enter ${zt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,L=me==="expanding"?`flopay-card-enter ${zt}ms cubic-bezier(0, 0, 0.2, 1) both`:me==="collapsing"?`flopay-card-exit ${zt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return xe("form",{onSubmit:jo,className:x,style:{position:"relative"},children:[u(ua,{}),Ut&&u(xn,{status:Ut,errorMessage:l,authorized:En}),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?Ll:{},...Q?{animation:Q,pointerEvents:"none"}:{}},children:[ri("flopay-direct-paypal-gate-debug"),oi("flopay-stripe-gate-debug"),Fr&&Ie&&xe(kr,{children:[Xt&&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(Io,{sessionId:e,nonce:t,billingApiUrl:pt,email:y.email,clientId:Ie.clientId,environment:Ie.environment,currency:$.toUpperCase(),isSubscription:We,providerObjectType:Ie.providerObjectType,onTokenizedBody:pn,onComplete:a,onErrorChange:M,onDecline:d,onTechnicalFailure:$e,onButtonClick:ee,runBeforeButtonClick:Cn,isProcessing:C,onLoadStateChange:$o,onInitializationStateChange:qo,session:G??null,existingOrderId:Xt?.orderId,debug:D},Xt?.orderId??"fresh")]}),Dr&&u(dr,{stripe:W,options:be,children:u(qi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,onTokenizedBody:pn,onErrorChange:M,isProcessing:C,onButtonClick:ee,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:Cn,onLoadStateChange:La,placeholderBorderRadius:or})}),Lr?u(dr,{stripe:E,options:ve,children:u(ji,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,intentKind:Y>0?"payment":"setup",expressMethods:so,onTokenizedBody:pn,onErrorChange:M,onButtonClick:ee,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:Cn,onLoadStateChange:Na,placeholderBorderRadius:or})}):ja?u("div",{style:{height:Mo,borderRadius:or,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Or&&u(Ki,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,paymentElementMethods:lo,stripeInstance:E,paymentElementBaseOptions:Uo,onTokenizedBody:pn,onErrorChange:M,onButtonClick:ee,onDecline:d,runBeforeButtonClick:Cn,onLoadStateChange:Ua,isProcessing:C,submitButtonColor:ar,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,onExpandApm:Tn,expandedApmMethod:at,themeId:Se,buttonAppearance:{backgroundColor:c.cardButton?.backgroundColor,borderColor:c.cardInputBorder,textColor:c.cardButton?.color,borderRadius:or}}),Pe&&u("button",{type:"button",onClick:async()=>{C||!(await Cn("card")).proceed||(ee?.("card"),Hn())},disabled:C,style:{width:"100%",...z,...c.cardButton,...ha({themeBundle:s,resolvedPrimaryColor:ar,resolvedBorderRadius:wt,submitButtonStyle:c.submitButton,explicitPrimaryColor:Zt?.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:ge=>{!C&&(s||Zt?.colorPrimary)&&(ge.currentTarget.style.backgroundColor=Ss)},onMouseLeave:ge=>{(s||Zt?.colorPrimary)&&(ge.currentTarget.style.backgroundColor=ar)},onMouseDown:ge=>{ge.currentTarget.style.transform="scale(0.985)"},onMouseUp:ge=>{ge.currentTarget.style.transform="scale(1)"},children:u(yr,{content:Ae})}),l&&me==="buttons"&&u(Cr,{margin:"0.25rem 0",styleOverride:c.errorBanner,children:l})]}),Pe&&_&&u("div",{style:{gridArea:"1 / 1",...L?{animation:L}:{},...me==="collapsing"?{pointerEvents:"none"}:{}},children:ni}),V&&ai&&at&&fo&&E&&u("div",{style:{gridArea:"1 / 1",...yo?{animation:yo}:{},...me==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:Ho,borderRadius:Jo,...$r,padding:Wo},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:Ln,style:{display:"inline-flex",alignItems:"center",gap:Yo?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(fr,{content:Ce})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:Go,paddingRight:80,...c.title},children:`Pay with ${Ir(at)}`})]}),u(dr,{stripe:E,options:fo,children:u(ma,{method:at,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,onTokenizedBody:pn,onErrorChange:M,onDecline:d,onCancel:Ln,runBeforeButtonClick:Cn,onButtonClick:ee,isProcessing:C,submitButtonColor:ar,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,errorText:l})},at)]})})]})]})}return ai&&at&&fo&&E&&V?xe("form",{onSubmit:jo,className:x,style:{position:"relative"},children:[u(ua,{}),Ut&&u(xn,{status:Ut,errorMessage:l,authorized:En}),u("div",{style:{...yo?{animation:yo}:{},...me==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:Ho,borderRadius:Jo,...$r,padding:Wo},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:Ln,style:{display:"inline-flex",alignItems:"center",gap:Yo?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(fr,{content:Ce})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:Go,paddingRight:80,...c.title},children:`Pay with ${Ir(at)}`})]}),u(dr,{stripe:E,options:fo,children:u(ma,{method:at,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,onTokenizedBody:pn,onErrorChange:M,onDecline:d,onCancel:Ln,runBeforeButtonClick:Cn,onButtonClick:ee,isProcessing:C,submitButtonColor:ar,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,errorText:l})},at)]})})]}):xe("form",{onSubmit:jo,className:x,style:{position:"relative"},children:[u(ua,{}),Ut&&u(xn,{status:Ut,errorMessage:l,authorized:En}),xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ri("flopay-direct-paypal-gate-debug-default"),oi("flopay-stripe-gate-debug-default"),Fr&&Ie&&xe(kr,{children:[Xt&&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(Io,{sessionId:e,nonce:t,billingApiUrl:pt,email:y.email,clientId:Ie.clientId,environment:Ie.environment,currency:$.toUpperCase(),isSubscription:We,providerObjectType:Ie.providerObjectType,onTokenizedBody:pn,onComplete:a,onErrorChange:M,onDecline:d,onTechnicalFailure:$e,onButtonClick:ee,runBeforeButtonClick:Cn,isProcessing:C,onLoadStateChange:$o,onInitializationStateChange:qo,session:G??null,existingOrderId:Xt?.orderId,debug:D},Xt?.orderId??"fresh")]}),Dr&&u(dr,{stripe:W,options:be,children:u(qi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,onTokenizedBody:pn,onErrorChange:M,isProcessing:C,onButtonClick:ee,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:Cn,onLoadStateChange:La,placeholderBorderRadius:or})}),Lr&&u(dr,{stripe:E,options:ve,children:u(ji,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,intentKind:Y>0?"payment":"setup",expressMethods:so,onTokenizedBody:pn,onErrorChange:M,onButtonClick:ee,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:Cn,onLoadStateChange:Na,placeholderBorderRadius:or})}),Or&&u(Ki,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,paymentElementMethods:lo,stripeInstance:E,paymentElementBaseOptions:Uo,onTokenizedBody:pn,onErrorChange:M,onButtonClick:ee,onDecline:d,runBeforeButtonClick:Cn,onLoadStateChange:Ua,isProcessing:C,submitButtonColor:ar,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,themeId:Se,onExpandApm:Tn,expandedApmMethod:at,buttonAppearance:{backgroundColor:c.cardButton?.backgroundColor,borderColor:c.cardInputBorder,textColor:c.cardButton?.color,borderRadius:or}})]}),Pe&&(fs||ys||gs)&&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&&ni]})}import{Fragment as Bn,jsx as X,jsxs as Bt}from"react/jsx-runtime";var Rr=44,Ta="flopay_checkout_saved_payment_resume",No=new Map,Lo=new Map;function es(e,t){t.settled&&t.consumers===0&&No.get(e)===t&&No.delete(e)}function Zl(e,t,n){let r=Lo.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Lo.set(e,a);let m=()=>{Lo.get(e)===a&&Lo.delete(e)};return o.then(m,m),o}function Qr(e){return new Promise(t=>setTimeout(t,e))}function Oo(e,t,n){let r=So({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:os,enabled:t!==!1});return r.beginCheckout(n),r}function eo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ba(e,t,n,r,o){let a=Oo(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),eo(a)}function Ql(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 Ra(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Ca(e){return!e||e.data.stripe?.publishableKey?!1:!!Ra(e)?.clientId}function qn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ec(){if(!qn())return null;try{let e=window.sessionStorage.getItem(Ta);return e?JSON.parse(e):null}catch{return null}}function ts(e){if(qn())try{window.sessionStorage.setItem(Ta,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Sa(){if(qn())try{window.sessionStorage.removeItem(Ta)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var xa=":idempotency-key";function as(e,t){if(!qn())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 wa(e,t,n,r){if(qn())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 _a(e,t){if(qn())try{as(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function is(e,t){if(!qn())return null;try{let n=window.sessionStorage.getItem(e+xa);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 ka(e,t,n){if(qn())try{window.sessionStorage.setItem(e+xa,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Ia(e,t){if(_a(e,t),!!qn())try{is(e,t)&&window.sessionStorage.removeItem(e+xa)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function tc(){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 ns(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 nc(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 Ea(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function to(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=>Ea(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ea(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ea(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 rc(e,t=!1){let n=to(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 oc(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=Jl(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Hl(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 Aa({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:ne=!0,enabledPaymentMethods:V,showApplePay:v=!0,showGooglePay:fe=!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:ee,cardFieldOrder:tt,cardPreFormSlot:Me,avsLayout:H,className:de,initialErrorMessage:ae=null,children:ue,checkoutMode:ke,confirmLabel:pe,renderConfirmButton:Re,onSessionCompleted:O}){let w=Gl(r),oe=hn(()=>rs(ce),[ce]),qe=a??oe?.appearance,De=n?"embedded_checkout":"standard_checkout",Z=ue?"custom_layout":J==="buttons"?"buttons_layout":"default_layout",[R,Y]=kt(null),[$,Be]=kt(null),Ie=_t(null),[We,G]=kt(null),mt=_t(null),[D,Le]=kt(null),Pt=hn(()=>n?to(n):"",[n]),N=n?`create:${Pt}`:`session:${e??""}`,vt=D?.gateways?.stripe?"stripe":D?.gateways?.paypal?"paypal":void 0,ze=_t(new Set),Qt=_t(N),It=_t(N);bo(()=>{It.current=N,Qt.current!==N&&(Qt.current=N,ze.current.clear())},[N]);let k=$n(l=>{if(It.current===N){if(ta.has(l.name)){if(ze.current.has(l.name))return;ze.current.add(l.name)}Qe(()=>b?.(l))}},[N,b]),se=vr(k,N),yt=_t(!1),Fe=$n(l=>{if(yt.current)return;let s=l.gateway||!vt?l:{...l,gateway:vt};k(s)},[k,vt]);Mn(()=>{se({class:"lifecycle",name:"checkout.mount"})},[se]);let[jt,Wt]=kt(e??""),Ge=e??jt,bt=n?"":Ge,[Je,Ft]=kt(!0),[je,Kt]=kt(null),[Et,en]=kt("full"),[Lt,kn]=kt(!1),[on,rt]=kt(ae),[Ot,Ke]=kt(null),[In,ct]=kt(null),[Pn,Nt]=kt(!1),[te,jn]=kt(void 0),[En,Rn]=kt(""),[_n,ur]=kt(!1),[I,Xe]=kt(!1),Pe=_t(0),[vn,Oe]=kt("loading"),[Kn,er]=kt(0),Vt=_t(!1),dt=_t(!1),Jt=_t(!1),Ht=_t(null),ot=hn(()=>({checkoutMode:ke??Et,layout:ue?"unknown":J==="buttons"?"buttons":"embedded"}),[ke,ue,Et,J]),an=_t(h);an.current=h;let sn=_t(P);sn.current=P;let Vn=_t(x);Vn.current=x,Mn(()=>{At($)?.setCheckoutContext(ot),We&&We!==$&&At(We)?.setCheckoutContext(ot)},[$,We,ot]);let bn=_t(O);bn.current=O;let tn=$n(l=>{Oe(l),!(l!=="exhausted"||Jt.current)&&(Jt.current=!0,sn.current?.(new Mt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),ln=$n(()=>{Oe("retrying"),er(l=>l+1)},[]);Mn(()=>{Oe("loading"),er(0),Jt.current=!1},[Ge]),Mn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:os,checkout_type:De,checkout_layout:Z,billing_api_url:w})},[Z,De,w]);let me=hn(()=>n?to(n,!0):"",[n]),Ct=hn(()=>En===me?te:void 0,[te,En,me]),at=hn(()=>n?Zo(n,Ct):void 0,[n,Ct]),nn=ke??at?.checkoutMode??"full",cn=hn(()=>at?{...at,checkoutMode:nn}:void 0,[at,nn]);Mn(()=>{jn(void 0),Rn(me)},[me]),Mn(()=>{rt(ae)},[ae]);let Fn=$n((l,s,c)=>{Qe(()=>{Vn.current?.(xt(l,s,c))})},[Qe]),dn=$n(async(l,s)=>{rt(null),ct(null),Nt(!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=At(K),C=K?null:Oo(w,o,ot),f={log:ve=>{F?F.log(ve):C?.log(ve)},error:ve=>{F?F.error(ve):C?.error(ve)},terminal:ve=>{F?F.terminal(ve):C?.terminal(ve)},performance:ve=>{F?F.performance(ve):C?.performance(ve)},now:()=>F?.now()??C?.now()??0,elapsed:ve=>F?.elapsed(ve)??Math.max(0,(C?.now()??ve)-ve)},y=f.now(),g=!!(s?.initialAutoProcessingError||s?.initialAutoProcessingPending),E=!1,W,ie=()=>{E||(E=!0,g=!0,W=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"}),W!==void 0&&f.performance({stage:"recovery",durationMs:f.elapsed(W),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 ve=_i(s?.initialAutoProcessingError),be;if(ve)ie(),ve.type==="paypal_redirect_required"&&Ht.current?.publishableKey&&ts({sessionId:c,publishableKey:Ht.current.publishableKey,paypalPublishableKey:Ht.current.paypalPublishableKey}),be=await To(ve,{flopay:Ie.current,paypalFlopay:mt.current,attempt3DS:s?.attempt3DS,billingApiUrl:w,sessionId:c,session:l,telemetry:!1}),ve.type==="paypal_redirect_required"&&Sa();else if(s?.initialAutoProcessingPending){let $e=(await new Do(w,{telemetry:!1}).waitForCheckoutSessionCompletion(s.initialAutoProcessingPending.sessionId,{initialDelayMs:s.initialAutoProcessingPending.retryAfterMs})).data.session;if(!hr($e))throw ho($e);be=ir($e,c)}else{if(s?.initialAutoProcessingError)throw Xn(s.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:s.initialAutoProcessingError.checkoutMethod});if(s?.fromCreateSession)return s?.fallbackToFull&&(en("full"),ns("full")),!1;{let M=await wr({billingApiUrl:w,sessionId:c,session:l,telemetry:!1});M.type==="success"?be=M.result:(ie(),M.type==="paypal_redirect_required"&&Ht.current?.publishableKey&&ts({sessionId:c,publishableKey:Ht.current.publishableKey,paypalPublishableKey:Ht.current.paypalPublishableKey}),be=await To(M,{flopay:Ie.current,paypalFlopay:mt.current,attempt3DS:s?.attempt3DS,billingApiUrl:w,sessionId:c,session:l,telemetry:!1}),M.type==="paypal_redirect_required"&&Sa())}}c&&Sr(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:be.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Nt(be.status==="authorized"),Ke("success"),await Qr(1200),Tt=()=>an.current?.(be)}catch(ve){let be=cr(ve),M=be.checkoutMethod??Jr;rt(be.message),ct(be.message),Nt(!1),s?.fallbackToFull&&(f.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),en("full"),ns("full")),Ue();let St=be.statusCode!==void 0?Xl(be.statusCode,"unknown"):void 0,$e=St==="4xx"?{requestCategory:"process_payment",statusClass:St}:{},nt=St===void 0||St==="4xx";if(nt&&(be.telemetryOutcome==="payment_declined"||!!(be.declineCode||be.code?.toLowerCase().includes("declin"))))f.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...$e});else if(nt&&(be.telemetryOutcome==="validation_rejected"||be.type==="validation_error"))f.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...$e});else{let oo=Zi(ve,g?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),rn=be.telemetryRequestCategory??"process_payment";yt.current=!0;try{f.error({...oo,...be.telemetryFailureCategory?{failureCategory:be.telemetryFailureCategory}:{},stage:g?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:rn})}finally{yt.current=!1}se({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:rn,provider:A})}return Qe(()=>sn.current?.(be)),Fn(M,be,{code:be.code,declineCode:be.declineCode}),Ke("error"),await Promise.allSettled([Qr(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&&eo(C),Ke(null),ct(null)}return Qe(Tt),!0},[Fn,se,Qe,cr,w,o,ot]);Mn(()=>{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=ec();c&&(dt.current=!0,(async()=>{let A,K=0;rt(null),ct(null),Ke("processing"),kn(!0);try{if(l.get("redirect_status")==="failed")throw Object.assign(new Mt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:F,paypalFlopay:C}=await Ao({publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey,billingApiUrl:w,locale:m,telemetry:o});A=At(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 Mt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:y,error:g}=await f.retrievePaymentIntent(s);if(g)throw Object.assign(new Mt(g.message??"Failed to retrieve PayPal payment status.","api_error",{code:g.code}),{checkoutMethod:"paypal"});let E=mi(y?.status);if(!y||E==="failed")throw Object.assign(new Mt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let W=typeof y.payment_method=="string"?y.payment_method:y.payment_method?.id,ie=E;if(c.sessionId){let Tt=(await new Do(w,{telemetry:!1}).getUnifiedCheckoutSession(c.sessionId)).data.session;if(Tt&&Tt.status!=="complete"){let ve=await wr({billingApiUrl:w,sessionId:c.sessionId,session:Tt,telemetry:!1,tokenizedData:{id:W??y.id,type:"card",threeDSecureActionResultTokenId:y.id,isPaypal:!0}});if(ve.type!=="success")throw Object.assign(new Mt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ie=ve.result.status}}c.sessionId&&Sr(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 Qr(1200),Qe(()=>an.current?.({status:ie,paymentIntentId:y.id,paymentMethodId:W,checkoutMethod:"paypal"}))}catch(F){let C=cr(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=Oo(w,o,ot);g.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),eo(g)}else ba(w,o,ot,"REDIRECT_RESUME_FAILED","redirect_resume");rt(C.message),ct(C.message),Qe(()=>sn.current?.(C)),Fn(f,C,{code:C.code,declineCode:C.declineCode}),Ke("error"),await Qr(1500)}finally{Sa(),tc(),Ke(null),ct(null),kn(!1)}})())},[Fn,Qe,m,cr,w,o]);let zt=_t(null),Yt=hn(()=>cn?to(cn):"",[cn]),Gt=_t(cn);Gt.current=cn,Mn(()=>{Wt(e??"")},[e]),Mn(()=>{Vt.current=!1,rt(ae),ct(null),Nt(!1),Ke(null)},[Yt,ae,e]);async function Hn(l,s,c){let A=Oo(w,o,ot),K=new Do(w,{telemetry:!1}),F=!1;try{let C=l.idempotencyKey!==void 0?Qi(l.idempotencyKey):void 0,f=as(s,c),y=is(s,c);f?.canonicalIdentity===c&&y&&y.canonicalIdentity===void 0&&(ka(s,c,y.idempotencyKey),y={...y,canonicalIdentity:c});let g=C??(y?.canonicalIdentity===c?y.idempotencyKey:void 0),E,W=!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&&(oc(_e.data.session,l)?(wa(s,c,ie,f.nonce??_e.data.session?.clientSecret),y&&y.canonicalIdentity===void 0&&(ka(s,c,y.idempotencyKey),g??(g=y.idempotencyKey))):(Ia(s,c),y=null,g=C,ie=null,_e=null));let Tt=_e?.data.session?.status;if(ie&&_e&&Tt==="complete"){if(ia(ie))return{sid:ie,result:_e};Ia(s,c),ie=null,_e=null,W=!0}}catch{A.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),f?.canonicalIdentity===void 0?(Ia(s,c),g=C):_a(s,c),ie=null}if(!ie){!C&&(W||!g)&&(g=Qi(),E=g),g&&ka(s,c,g);let Tt=A.now(),ve=0;A.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let be={...l,idempotencyKey:g,avsCheck:!!ee,avsConfig:typeof ee=="object"?ee:void 0,checkoutType:"embedded_checkout",checkoutLayout:ue?"custom_layout":J==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(be,Kl,{configurable:!1,enumerable:!1,value:{onAttempt:$e=>{ve=Math.max(ve,$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:ve,statusClass:"2xx"})},St=$e=>{let nt=Zi($e,"CHECKOUT_SESSION_CREATE_FAILED","unknown");A.performance({stage:"session_create",durationMs:A.now()-Tt,durationMode:"machine",requestCategory:"session_create",attempt:ve,statusClass:nt.statusClass}),$e instanceof Mt&&$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(Yl(be)){let $e=await K.createDetachedSession(be);$e.claimed.catch(()=>{}),_e=$e.shell,ie=$e.sessionId,Ue=$e.claimed.then(nt=>{let nr=nt.data.session?.id??$e.sessionId;return nr&&wa(s,c,nr,nt.data.session?.clientSecret??$e.nonce),M(),nt},nt=>{throw _a(s,c),St(nt),nt}).finally(()=>eo(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:ve,statusClass:"2xx",paymentMethodCategory:"card"})}else _e=await K.createAndFetchSession(be),M()}catch($e){throw St($e),$e}ie=_e.data.session?.id??ie??"",ie&&!Ue&&wa(s,c,ie,_e.data.session?.clientSecret)}return{sid:ie??"",result:_e,sdkGeneratedIdempotencyKey:E,...Ue?{claimed:Ue}:{}}}finally{F||eo(A)}}let Dn=$n(async(l,s)=>{let c=Gt.current;if(!c)throw new Mt("createSession is required to bootstrap checkout.","validation_error");let A=Zo(c,l),K=to(A),F=rc(A),C=No.get(K);if(!C){let g={canonicalIdentity:K,promise:Hn(A,F,K),consumers:0,settled:!1};C=g,No.set(K,g);let E=()=>{g.settled=!0,es(K,g)};g.promise.then(E,E)}C.consumers+=1;let f=!1,y=()=>{f||(f=!0,C.consumers-=1,es(K,C))};s?.(y);try{let g=await C.promise;zt.current=K,l&&(Rn(me),jn(be=>di(be,l)));let{sid:E,result:W,claimed:ie}=g;if(Y(W),W.data.session&&Le(W.data.session),E&&Wt(E),ie){Pe.current+=1;let be=Pe.current;Xe(!0),ie.then(M=>{Pe.current===be&&(Y(M),M.data.session&&Le(M.data.session),Xe(!1))},M=>{Pe.current===be&&(Xe(!1),Kt(M instanceof Mt?M:new Mt(M instanceof Error?M.message:"Failed to create session","api_error")))})}else Pe.current+=1,Xe(!1);let{publishableKey:_e,paypalPublishableKey:Ue}=xo(W),{flopay:Tt,paypalFlopay:ve}=await Ao({publishableKey:_e,paypalPublishableKey:Ue,billingApiUrl:w,locale:m,telemetry:o});return Ie.current=Tt,Be(Tt),mt.current=ve,G(ve),Ft(!1),g}catch(g){throw zt.current===K&&(zt.current=null),g}finally{s||y()}},[me,m,w,o,ot]),Tn=_t(dn);Tn.current=dn;let Ln=_t(Dn);Ln.current=Dn;let Ut=$n(async l=>{if(!nc(l)||_n)return{sessionId:jt,session:D};ur(!0);try{let s=await Dn(l);return{sessionId:s.sid,session:s.result.data.session??null}}finally{ur(!1)}},[Dn,_n,jt,D]);Mn(()=>{let l=!1,s;if(Kt(null),Yt){let K=Gt.current;return en(nn),Ft(!1),zt.current===Yt?()=>{l=!0}:(Le(ui(K,ke)),(async()=>{let F=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),C=nn==="auto"&&!Vt.current&&!F;C&&(rt(null),ct(null),Ke("processing"));try{let f=await Ln.current(void 0,W=>{s=W}),y=f.result.data.session??null;Ht.current=xo(f.result);let g=Ca(f.result),E=ia(f.sid||y?.id);if(!l&&C&&y&&!g&&!E){Vt.current=!0,await Zl(Yt,f.sdkGeneratedIdempotencyKey,()=>Tn.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)&&(Vt.current=!0),Ke(null),ct(null))}catch(f){if(l)return;let y=f instanceof Mt||typeof f=="object"&&f!==null&&"code"in f?f.code:void 0;if(C&&y==="session_auto_completed"){Vt.current=!0,Ke("success"),await Qr(1200),l||(Qe(()=>{an.current?.({status:"succeeded"})}),Ke(null),ct(null));return}C&&(Ke(null),ct(null));let g=f instanceof Mt?f:new Mt(f instanceof Error?f.message:"Failed to create session","api_error");Kt(g)}finally{s?.(),s=void 0}})(),()=>{l=!0,s?.()})}Ft(!0);async function c(){let K=!1;try{let C=await new Do(w,{telemetry:!1}).getUnifiedCheckoutSession(Ge,t);if(l)return;Y(C);let f=C.data.session??null;if(Le(f),!f)throw new Mt("No session data returned","api_error");let y=f.checkoutMode;if(y==="setup")throw new Mt("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(f.status==="authorized"){Ft(!1),Qe(()=>{an.current?.(ir(f,Ge)),bn.current?.(f.successUrl??"")});return}if(f.status==="complete"){Ft(!1),Qe(()=>{bn.current?.(f.successUrl??"")});return}if(f.status==="expired")throw go(f);K=!0;let g=ke??y??"full";en(g);let E=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),W=Ca(C);if(g==="auto"&&!Vt.current&&!E&&!W){Vt.current=!0;let ie=A(C);try{if(await Tn.current(f,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ie,sessionId:Ge||f.id}),l)return;await ie,l||Ft(!1);return}catch{if(l)return;await ie,l||Ft(!1);return}}await A(C),l||Ft(!1)}catch(F){if(l)return;K&&se({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),F instanceof Mt?!K&&!Ql(F)&&ba(w,o,ot,"NETWORK_REQUEST_FAILED","session_read"):ba(w,o,ot,"INTERNAL_SDK_ERROR","checkout_mount");let C=F instanceof Mt?F:new Mt(F instanceof Error?F.message:"Failed to initialize checkout","api_error");Kt(C),Ft(!1)}}async function A(K){let{publishableKey:F,paypalPublishableKey:C}=xo(K);Ht.current={publishableKey:F,paypalPublishableKey:C};let{flopay:f,paypalFlopay:y}=await Ao({publishableKey:F,paypalPublishableKey:C,billingApiUrl:w,locale:m,telemetry:o});Ie.current=f,Be(f),mt.current=y,G(y)}return c(),()=>{l=!0}},[ke,Yt,nn,bt,Qe,t]);let Ze=$n(async()=>{if(!(Lt||!D)){kn(!0),rt(null);try{await dn(D,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ge||D.id})}finally{kn(!1)}}},[Ge,Lt,dn,D]),un=Ra(R),$t=Ca(R),ut=hn(()=>{if(!(!R||!D||!R.data.stripe?.publishableKey))return{billingApiUrl:w}},[R,D,w]),Xt=!!(n&&!ue&&J==="buttons"&&B&&nn==="full"),Rt=hn(()=>({session:D,loading:Je,error:je,checkoutMode:Et,inlineSessionDraft:cn,applyInlineSessionPatch:Xt?Ut:void 0,inlineSessionPatchProcessing:_n,claimPending:I}),[D,Je,je,Et,cn,Xt,Ut,_n,I]),tr=!!n&&J==="buttons"&&!$t&&(!$||!ut),pt=Ot?X(xn,{status:Ot,errorMessage:In,authorized:Pn}):null;if(Je){if(d)return Bt(Bn,{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 Bt(Bn,{children:[Bt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[S&&s(Rr),ne&&(v||fe)&&s(Rr),ne&&s(Rr),X("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),pt]})}return Bt(Bn,{children:[Bt("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(Sn.Provider,{value:Rt,children:T(je)}):X(Sn.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})}):tr?Bt(Bn,{children:[X(Sn.Provider,{value:Rt,children:X(ic,{onButtonClick:q,showPayPal:S,showStripe:ne,showApplePay:v,showGooglePay:fe,theme:ce,buttonsTheme:Se,buttonsStyles:re,cardButtonContent:le,cardBackButtonContent:Ve,cardTitleContent:Ae})}),pt]}):$t&&D&&un?Bt(Bn,{children:[X(Sn.Provider,{value:Rt,children:Bt("div",{className:de,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[on&&X(Cr,{icon:!1,children:on}),vn==="retrying"&&X("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),vn==="exhausted"&&Bt("div",{role:"alert",children:[X("div",{children:"PayPal is temporarily unavailable. Please try again."}),X("button",{type:"button",onClick:ln,children:"Retry PayPal"})]}),vn!=="exhausted"&&X("div",{"aria-hidden":vn==="retrying"?!0:void 0,style:vn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:X(Ci,{sessionId:Ge,nonce:D.clientSecret||void 0,billingApiUrl:w,email:D.customer?.email,clientId:un.clientId,environment:un.environment,currency:(D.currency??"usd").toUpperCase(),isSubscription:D.mode==="subscription",providerObjectType:un.providerObjectType,onComplete:h,onErrorChange:rt,onDecline:x,onButtonClick:q,onInitializationStateChange:tn,allowAutomaticRetry:Kn===0,session:D,telemetry:o,telemetryContext:ot,onInstrument:Fe,debug:j},`${N}:paypal-init-${Kn}`)})]})}),pt]}):!$||!ut?X(Bn,{children:pt}):Et==="confirm"?Bt(Bn,{children:[X(Sn.Provider,{value:Rt,children:X(Eo,{flopay:$,paypalFlopay:We,options:ut,onInstrument:Fe,children:Bt("div",{className:de,children:[on&&X("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:on}),Re?Re({onConfirm:Ze,isProcessing:Lt}):X("button",{type:"button",onClick:Ze,disabled:Lt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Lt?"not-allowed":"pointer",opacity:Lt?.6:1},children:Lt?"Processing...":pe??"Confirm Purchase"})]})},N)}),pt]}):Bt(Bn,{children:[X(Sn.Provider,{value:Rt,children:X(Eo,{flopay:$,paypalFlopay:We,options:ut,onInstrument:Fe,children:ue?Bt(Bn,{children:[on&&X("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:on}),X(ac,{sessionId:Ge,nonce:D?.clientSecret||void 0,billingApiUrl:w,session:D,children:ue})]}):X(Pa,{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(Vl(D).total*100):0,currency:D?.currency?.toLowerCase()??"usd",onComplete:h,onError:P,onDecline:x,error:on,onErrorChange:rt,showPayPal:S,showStripe:ne,enabledPaymentMethods:V??R?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:R?.data.stripe?.enabledPaymentMethodCountries,showApplePay:v,showGooglePay:fe,layout:J,theme:ce,buttonsTheme:Se,buttonsStyles:re,appearance:qe,cardButtonContent:le,cardBackButtonContent:Ve,cardTitleContent:Ae,onButtonClick:q,onBeforeButtonClick:B,enableAVS:ee,...tt?{cardFieldOrder:tt}:{},...Me?{cardPreFormSlot:Me}:{},avsLayout:H,country:D?.customer?.country,city:D?.customer?.city,state:D?.customer?.state,onCountryChange:U,onZipChange:p,avsCheck:!!ee,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ue?"custom_layout":J==="buttons"?"buttons_layout":"default_layout",className:de,directPaypal:Ra(R),isSubscription:D?.mode==="subscription",session:D,dataAttachmentPending:I,debug:j})},N)}),pt]})}function ac({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return X(Bn,{children:va.Children.map(o,a=>{if(!va.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:va.cloneElement(a,d)})})}function ic({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=hn(()=>rs(a),[a]),p=hn(()=>{let v=U?.buttonsLayout??Wl(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,ne=v=>X("div",{style:{height:v,borderRadius:S,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),V=T===void 0?{boxSizing:"border-box",height:Rr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let v=p.cardInputBorder??"#e5e7eb",fe=p.cardInputBackground??"white",j=mr(h),J=mr(P);return Bt("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:[Bt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Bt("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(fr,{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(Vr,{content:P})})]}),X("div",{style:{backgroundColor:fe,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"}})}),Bt("div",{style:{display:"flex"},children:[X("div",{style:{flex:1,backgroundColor:fe,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:fe,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:fe,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&&Ie("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Me?-2:0},children:[Ie("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:Me?-3:0,...f.title},children:l(mo,{content:Ae})}),Me&&A&&Ie("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[se&&Ie(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}})})]}),pe&&Ie(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:Yt,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:Me?-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 Ie(fr,{children:[ze(X.address_line_1,i)&&l("div",{style:R(qt.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=>{Ut.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=>{Ut.current.addressLine2=!0,tn.current=z.target.value,Xt(z.target.value)},disabled:d,"data-testid":"flopay-address-line2",style:N()})}),(ze(X.city,i)||ze(X.state,i))&&Ie("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(qt.city)}`,borderRight:`1px solid ${Pr(qt.city)}`,borderBottom:`1px solid ${Pr(qt.city)}`,borderLeft:`1px solid ${Pr(qt.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=>{Ut.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(qt.state)}`,padding:"10px",borderTopRightRadius:Pt,borderBottomRightRadius:Pt,...ze(X.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:Pt}},children:he?Ie("select",{id:"flopay-billing-state",name:"billing-state",value:Ft,onChange:z=>{Ut.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=>{Ut.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))&&Ie("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=>{Ut.current.country=!0,_t.current=z.target.value,Jt(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=>Ie("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=>{Ut.current.zip=!0,ot.current=z.target.value,zt(z.target.value),We?.(z.target.value)},onBlur:()=>Lt(!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)})]})})()}),Me&&Ye&&l("div",{style:{order:-2,width:"100%"},children:Ye}),Me&&il,M&&l(Kr,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:M})]}),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(C??[])}`,` enabledPaymentMethodsProvided=${eo}`,` hasEnabledMethods=${Ao}`,` expressMethods: ${JSON.stringify(Bo)}`,` walletExpressMethods: ${JSON.stringify(Mo)}`,` 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 ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="apm-collapsing"?`flopay-card-exit ${$t}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 ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:xe==="collapsing"||xe==="apm-collapsing"?`flopay-buttons-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,z=xe==="expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Ie("form",{onSubmit:ga,className:B,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:M,authorized:xn}),Ie("div",{style:{display:"grid"},children:[Ie("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&&Ie(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:ke||void 0,onBuyerIdentityReady:de,clientId:x.clientId,environment:x.environment,currency:we.toUpperCase(),isSubscription:K,providerObjectType:x.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:me,onDecline:s,onTechnicalFailure:Br,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:ke||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:me,isProcessing:d,onButtonClick:J,onDecline:s,onTechnicalFailure:Br,runBeforeButtonClick:Dn,onLoadStateChange:fi,placeholderBorderRadius:Sr})}),oo?l(_r,{stripe:ge,options:ci,children:l(ws,{sessionId:e,nonce:t,email:k.email,billingName:ke||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,intentKind:$>0?"payment":"setup",expressMethods:Mo,onTokenizedBody:Sn,onErrorChange:me,onButtonClick:J,onDecline:s,onTechnicalFailure:Br,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:de,billingApiUrl:ne,paymentElementMethods:Fo,stripeInstance:ge,paymentElementBaseOptions:ma,onTokenizedBody:Sn,onErrorChange:me,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}}),Me&&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})}),M&&xe==="buttons"&&l(Kr,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:M})]}),Me&&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:Ie("div",{style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca},children:[Ie("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ie("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:de,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:me,onDecline:s,onCancel:Kn,runBeforeButtonClick:Dn,onButtonClick:J,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,errorText:M})},Tt)]})})]})]})}return Li&&Tt&&Uo&&ge&&H?Ie("form",{onSubmit:ga,className:B,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:M,authorized:xn}),l("div",{style:{...zo?{animation:zo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ie("div",{style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca},children:[Ie("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ie("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:de,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:me,onDecline:s,onCancel:Kn,runBeforeButtonClick:Dn,onButtonClick:J,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,errorText:M})},Tt)]})})]}):Ie("form",{onSubmit:ga,className:B,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:M,authorized:xn}),Ie("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&&Ie(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,billingName:ke||void 0,onBuyerIdentityReady:de,clientId:x.clientId,environment:x.environment,currency:we.toUpperCase(),isSubscription:K,providerObjectType:x.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:me,onDecline:s,onTechnicalFailure:Br,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:ke||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:me,isProcessing:d,onButtonClick:J,onDecline:s,onTechnicalFailure:Br,runBeforeButtonClick:Dn,onLoadStateChange:fi,placeholderBorderRadius:Sr})}),oo&&l(_r,{stripe:ge,options:ci,children:l(ws,{sessionId:e,nonce:t,email:k.email,billingName:ke||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,intentKind:$>0?"payment":"setup",expressMethods:Mo,onTokenizedBody:Sn,onErrorChange:me,onButtonClick:J,onDecline:s,onTechnicalFailure:Br,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:me,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}})]}),Me&&(Xs||Js||Zs)&&Ie("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"}})]}),Me&&Fi]})}import{Fragment as Xn,jsx as re,jsxs as Ht}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??Mc(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:B,onCountryChange:D,onZipChange:u,showPayPal:w=!0,showStripe:ve=!0,enabledPaymentMethods:H,showApplePay:C=!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:de,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),Be=At(null),[x,K]=Et(null),I=At(null),[P,nt]=Et(null),St=En(()=>n?Io(n):"",[n]),ue=n?`create:${St}`:`session:${e??""}`,ct=P?.gateways?.stripe?"stripe":P?.gateways?.paypal?"paypal":void 0,it=At(new Set),rt=At(ue),je=At(ue);Vo(()=>{je.current=ue,rt.current!==ue&&(rt.current=ue,it.current.clear())},[ue]);let y=Wn(_=>{if(je.current===ue){if(xa.has(_.name)){if(it.current.has(_.name))return;it.current.add(_.name)}tt(()=>m?.(_))}},[ue,m]),U=jr(y,ue),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[Bt,Mt]=Et(e??""),W=e??Bt,Le=n?"":W,[Jt,wt]=Et(!0),[zt,Rn]=Et(null),[_n,Zn]=Et("full"),[Xt,cn]=Et(!1),[dn,Ft]=Et(Ye),[vn,bt]=Et(null),[ir,Yt]=Et(null),[sr,Nt]=Et(!1),[zn,ot]=Et(void 0),[_t,xt]=Et(""),[tn,un]=Et(!1),[pn,Un]=Et(!1),[qn,Ut]=Et(!1),X=At(0),Pn=At(void 0),[xn,Qn]=Et("loading"),[br,Tr]=Et(0),Tn=At(!1),mn=At(!1),Me=At(!1),Zt=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(B);ut.current=B,Jn(()=>{Kt($)?.setCheckoutContext(Dt),x&&x!==$&&Kt(x)?.setCheckoutContext(Dt)},[$,x,Dt]);let qe=At(ie);qe.current=ie;let yn=Wn(_=>{Qn(_),!(_!=="exhausted"||Me.current)&&(Me.current=!0,v.current?.(new Vt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ze=Wn(()=>{Qn("retrying"),Tr(_=>_+1)},[]);Jn(()=>{Qn("loading"),Tr(0),Me.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 qt=En(()=>n?Io(n,!0):"",[n]),lr=En(()=>_t===qt?zn:void 0,[zn,_t,qt]),jn=En(()=>n?ka(n,lr):void 0,[n,lr]),Cn=T??jn?.checkoutMode??"full",Lt=En(()=>jn?{...jn,checkoutMode:Cn}:void 0,[jn,Cn]);Jn(()=>{ot(void 0),xt(qt),Pn.current=void 0,Ut(!1)},[qt]),Jn(()=>{Ft(Ye)},[Ye]);let fn=Wn((_,E,V)=>{tt(()=>{ut.current?.(jt(_,E,V))})},[tt]),gn=Wn(async(_,E)=>{Ft(null),Yt(null),Nt(!1),bt("processing");let V=E?.sessionId??_.id,Z=_.gateways?.stripe?"stripe":_.gateways?.paypal?"paypal":void 0,$e=Be.current??I.current,ne=Kt($e),M=$e?null:la(j,o,Dt),h={log:q=>{ne?ne.log(q):M?.log(q)},error:q=>{ne?ne.error(q):M?.error(q)},terminal:q=>{ne?ne.terminal(q):M?.terminal(q)},performance:q=>{ne?ne.performance(q):M?.performance(q)},now:()=>ne?.now()??M?.now()??0,elapsed:q=>ne?.elapsed(q)??Math.max(0,(M?.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 ke;try{let q=ls(E?.initialAutoProcessingError),F;if(q)d(),q.type==="paypal_redirect_required"&&Zt.current?.publishableKey&&Ns({sessionId:V,publishableKey:Zt.current.publishableKey,paypalPublishableKey:Zt.current.paypalPublishableKey}),F=await ea(q,{flopay:Be.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"&&Zt.current?.publishableKey&&Ns({sessionId:V,publishableKey:Zt.current.publishableKey,paypalPublishableKey:Zt.current.paypalPublishableKey}),F=await ea(Ge,{flopay:Be.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),ke=()=>$n.current?.(F)}catch(q){let F=Rr(q),Ge=F.checkoutMethod??Po;Ft(F.message),Yt(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}:{},pe=Qe===void 0||Qe==="4xx";if(pe&&(F.telemetryOutcome==="payment_declined"||!!(F.declineCode||F.code?.toLowerCase().includes("declin"))))h.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...se});else if(pe&&(F.telemetryOutcome==="validation_rejected"||F.type==="validation_error"))h.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...se});else{let st=Bs(q,O?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ot=F.telemetryRequestCategory??"process_payment";Xe.current=!0;try{h.error({...st,...F.telemetryFailureCategory?{failureCategory:F.telemetryFailureCategory}:{},stage:O?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ot})}finally{Xe.current=!1}U({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ot,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(),M&&ko(M),bt(null),Yt(null)}return tt(ke),!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),Yt(null),bt("processing"),cn(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new Vt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ne,paypalFlopay:M}=await na({publishableKey:V.publishableKey,paypalPublishableKey:V.paypalPublishableKey,billingApiUrl:j,locale:c,telemetry:o});Z=Kt(M??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=(M??ne)?.getRawProvider();if(!h)throw Object.assign(new Vt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:f,error:O}=await h.retrievePaymentIntent(E);if(O)throw Object.assign(new Vt(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 Vt("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 ke=(await new ia(j,{telemetry:!1}).getUnifiedCheckoutSession(V.sessionId)).data.session;if(ke&&ke.status!=="complete"){let q=await Hr({billingApiUrl:j,sessionId:V.sessionId,session:ke,telemetry:!1,tokenizedData:{id:vt??f.id,type:"card",threeDSecureActionResultTokenId:f.id,isPaypal:!0}});if(q.type!=="success")throw Object.assign(new Vt("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 M=Rr(ne),h=M.checkoutMethod??"paypal",f=!!(M.declineCode||M.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(M.message),Yt(M.message),tt(()=>v.current?.(M)),fn(h,M,{code:M.code,declineCode:M.declineCode}),bt("error"),await wo(1500)}finally{Xa(),$c(),bt(null),Yt(null),cn(!1)}})())},[fn,tt,c,Rr,j,o]);let xe=At(null),kt=En(()=>Lt?Io(Lt):"",[Lt]),Tt=At(Lt);Tt.current=Lt,Jn(()=>{Mt(e??"")},[e]),Jn(()=>{Tn.current=!1,Ft(Ye),Yt(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 M=_.idempotencyKey!==void 0?Ms(_.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=M??(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,ke,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=M,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=M):ri(E,V),d=null}if(!d){!M&&(vt||!O)&&(O=Ms(),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"})},pe=A=>{let le=Bs(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 Vt&&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,ke=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),pe(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 pe(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}:{},...ke?{claim:ke}:{},...q?{claimRequiresIdentity:!0}:{}}}finally{ne||ko(Z)}}let hn=Wn(async(_,E)=>{let V=Tt.current;if(!V)throw new Vt("createSession is required to bootstrap checkout.","validation_error");let Z=ka(V,_),$e=Io(Z),ne=Kc(Z),M=ca.get($e);if(!M){let O={canonicalIdentity:$e,promise:An(Z,ne,$e),consumers:0,settled:!1};M=O,ca.set($e,O);let pt=()=>{O.settled=!0,Fs($e,O)};O.promise.then(pt,pt)}M.consumers+=1;let h=!1,f=()=>{h||(h=!0,M.consumers-=1,Fs($e,M))};E?.(f);try{let O=await M.promise;xe.current=$e,_&&(xt(qt),ot(Qe=>$i(Qe,_)));let{sid:pt,result:vt,claimed:d,claim:p,claimRequiresIdentity:k}=O;if(Pn.current=p,Ut(k===!0),Y(vt),vt.data.session&&nt(vt.data.session),pt&&Mt(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),Ut(!1))},se=>{X.current===Qe&&(Un(!1),Ut(!1),Rn(se instanceof Vt?se:new Vt(se instanceof Error?se.message:"Failed to create session","api_error")))})}else X.current+=1,Un(!1),Ut(!1);let{publishableKey:ke,paypalPublishableKey:q}=ta(vt),{flopay:F,paypalFlopay:Ge}=await na({publishableKey:ke,paypalPublishableKey:q,billingApiUrl:j,locale:c,telemetry:o});return Be.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()}},[qt,c,j,o,Dt]),Bn=At(gn);Bn.current=gn;let Mn=At(hn);Mn.current=hn;let $t=Wn(async _=>{if(!jc(_)||tn)return{sessionId:Bt,session:P};un(!0);try{let E=await hn(_);return{sessionId:E.sid,session:E.result.data.session??null}}finally{un(!1)}},[hn,tn,Bt,P]),nn=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"),M=Cn==="auto"&&!Tn.current&&!ne;M&&(Ft(null),Yt(null),bt("processing"));try{let h=await Mn.current(void 0,vt=>{E=vt}),f=h.result.data.session??null;Zt.current=ta(h.result);let O=Ja(h.result),pt=Fa(h.sid||f?.id);if(!_&&M&&f&&!O&&!pt){Tn.current=!0,await zc(kt,h.sdkGeneratedIdempotencyKey,()=>Bn.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}!_&&M&&((O||pt)&&(Tn.current=!0),bt(null),Yt(null))}catch(h){if(_)return;let f=h instanceof Vt||typeof h=="object"&&h!==null&&"code"in h?h.code:void 0;if(M&&f==="session_auto_completed"){Tn.current=!0,bt("success"),await wo(1200),_||(tt(()=>{$n.current?.({status:"succeeded"})}),bt(null),Yt(null));return}M&&(bt(null),Yt(null));let O=h instanceof Vt?h:new Vt(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 M=await new ia(j,{telemetry:!1}).getUnifiedCheckoutSession(W,t);if(_)return;Y(M);let h=M.data.session??null;if(nt(h),!h)throw new Vt("No session data returned","api_error");let f=h.checkoutMode;if(f==="setup")throw new Vt("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(M);if(O==="auto"&&!Tn.current&&!pt&&!vt){Tn.current=!0;let d=Z(M);try{if(await Bn.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(M),_||wt(!1)}catch(ne){if(_)return;$e&&U({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ne instanceof Vt?!$e&&!Uc(ne)&&Wa(j,o,Dt,"NETWORK_REQUEST_FAILED","session_read"):Wa(j,o,Dt,"INTERNAL_SDK_ERROR","checkout_mount");let M=ne instanceof Vt?ne:new Vt(ne instanceof Error?ne.message:"Failed to initialize checkout","api_error");Rn(M),wt(!1)}}async function Z($e){let{publishableKey:ne,paypalPublishableKey:M}=ta($e);Zt.current={publishableKey:ne,paypalPublishableKey:M};let{flopay:h,paypalFlopay:f}=await na({publishableKey:ne,paypalPublishableKey:M,billingApiUrl:j,locale:c,telemetry:o});Be.current=h,we(h),I.current=f,K(f)}return V(),()=>{_=!0}},[T,kt,Cn,Le,tt,t]);let an=Wn(async()=>{if(!(Xt||!P)){cn(!0),Ft(null);try{await gn(P,{attempt3DS:!0,fallbackToFull:!0,sessionId:W||P.id})}finally{cn(!1)}}},[W,Xt,gn,P]),er=ni(G),Ar=Ja(G),Fn=En(()=>{if(!(!G||!P||!G.data.stripe?.publishableKey))return{billingApiUrl:j}},[G,P,j]),Kn=!!(n&&!te&&ce==="buttons"&&ee&&Cn==="full"),Qt=En(()=>({session:P,loading:Jt,error:zt,checkoutMode:_n,inlineSessionDraft:Lt,applyInlineSessionPatch:Kn?$t:void 0,inlineSessionPatchProcessing:tn,claimPending:pn,claimRequiresIdentity:qn}),[P,Jt,zt,_n,Lt,Kn,$t,tn,pn,qn]),at=!!n&&ce==="buttons"&&!Ar&&(!$||!Fn),Gt=vn?re(Yn,{status:vn,errorMessage:ir,authorized:sr}):null;if(Jt){if(s)return Ht(Xn,{children:[s,Gt]});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 Ht(Xn,{children:[Ht("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[w&&E(Gr),ve&&(C||fe)&&E(Gr),ve&&E(Gr),re("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Gt]})}return Ht(Xn,{children:[Ht("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); } }"})]}),Gt]})}return zt?S?re(Ln.Provider,{value:Qt,children:S(zt)}):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:zt.message})}):at?Ht(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Yc,{onButtonClick:Ae,showPayPal:w,showStripe:ve,showApplePay:C,showGooglePay:fe,theme:oe,buttonsTheme:Ce,buttonsStyles:He,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De})}),Gt]}):Ar&&P&&er?Ht(Xn,{children:[re(Ln.Provider,{value:Qt,children:Ht("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"&&Ht("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:P.clientSecret||void 0,billingApiUrl:j,email:P.customer?.email||Lt?.account?.email,billingName:[P.customer?.firstName,P.customer?.lastName].filter(Boolean).join(" ")||[Lt?.account?.firstName,Lt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:nn,clientId:er.clientId,environment:er.environment,currency:(P.currency??"usd").toUpperCase(),isSubscription:P.mode==="subscription",providerObjectType:er.providerObjectType,onComplete:b,onErrorChange:Ft,onDecline:B,onButtonClick:Ae,onInitializationStateChange:yn,allowAutomaticRetry:br===0,session:P,telemetry:o,telemetryContext:Dt,onInstrument:dt,debug:Q},`${ue}:paypal-init-${br}`)})]})}),Gt]}):!$||!Fn?re(Xn,{children:Gt}):_n==="confirm"?Ht(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Xo,{flopay:$,paypalFlopay:x,options:Fn,onInstrument:dt,children:Ht("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:Xt}):re("button",{type:"button",onClick:an,disabled:Xt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Xt?"not-allowed":"pointer",opacity:Xt?.6:1},children:Xt?"Processing...":ae??"Confirm Purchase"})]})},ue)}),Gt]}):Ht(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Xo,{flopay:$,paypalFlopay:x,options:Fn,onInstrument:dt,children:te?Ht(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:P?.clientSecret||void 0,billingApiUrl:j,session:P,children:te})]}):re(Ya,{sessionId:W,nonce:P?.clientSecret||void 0,email:P?.customer?.email||Lt?.account?.email,userId:P?.customer?.id||Lt?.account?.userId,firstName:P?.customer?.firstName||Lt?.account?.firstName,lastName:P?.customer?.lastName||Lt?.account?.lastName,totalAmount:P?Math.round(Bc(P).total*100):0,currency:P?.currency?.toLowerCase()??"usd",onComplete:b,onError:g,onDecline:B,error:dn,onErrorChange:Ft,showPayPal:w,showStripe:ve,enabledPaymentMethods:H??G?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:G?.data.stripe?.enabledPaymentMethodCountries,showApplePay:C,showGooglePay:fe,layout:ce,theme:oe,buttonsTheme:Ce,buttonsStyles:He,appearance:Je,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De,onButtonClick:Ae,onBeforeButtonClick:ee,onBuyerIdentityReady:nn,enableAVS:J,...L?{cardFieldOrder:L}:{},...de?{cardPreFormSlot:de}:{},avsLayout:et,country:P?.customer?.country,city:P?.customer?.city,state:P?.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:P?.mode==="subscription",session:P,dataAttachmentPending:pn,dataAttachmentRequiresIdentity:qn,debug:Q})},ue)}),Gt]})}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,B]=Et(!1),D=En(()=>Ls(a),[a]),u=En(()=>{let C=D?.buttonsLayout??Dc(c);return s?{...C,...s,cardButton:{...C.cardButton,...s.cardButton},cardFormContainer:{...C.cardFormContainer,...s.cardFormContainer},backButton:{...C.backButton,...s.backButton},backButtonIcon:{...C.backButtonIcon,...s.backButtonIcon},submitButton:{...C.submitButton,...s.submitButton},title:{...C.title,...s.title}}:C},[D,c,s]),w=D?.buttonsLayout?.cardButton?.borderRadius??D?.appearance.variables?.borderRadius??8,ve=C=>re("div",{style:{height:C,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 C=u.cardInputBorder??"#e5e7eb",fe=u.cardInputBackground??"white",Q=Nr(b),ce=Nr(g);return Ht("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:[Ht("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ht("button",{type:"button",onClick:()=>B(!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 ${C}`,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"}})}),Ht("div",{style:{display:"flex"},children:[re("div",{style:{flex:1,backgroundColor:fe,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,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 ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,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 ${C}`,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
|
|
42
|
+
`})]})}return Ht("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"),B(!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:C=>{C.currentTarget.style.transform="scale(0.985)"},onMouseUp:C=>{C.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:B,tagsData:D,utmMetadata:u,billingApiUrl:w,locale:ve,theme:H,appearance:C,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:B,tagsData:D,utmMetadata:u}),[b,m,a,B,n,c,s,S,g,D,u]),[J,L]=Ro(!1),[de,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?.(jt(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 Bt=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 Jt=(await new si(Ae).waitForCheckoutSessionCompletion(y.autoProcessingPending.sessionId,{initialDelayMs:y.autoProcessingPending.retryAfterMs})).data.session;if(!zr(Jt))throw $o(Jt);await Y({result:kr(Jt,U),session:Jt,sessionId:Jt.id||U,autoCompleted:!1});return}if(y.autoProcessingError){if(y.autoProcessingError.type==="3ds_required"&&y.autoProcessingError.nextActionRedirectUrl&&U&&Bt){let W=new AbortController;j.current=W;let Le;try{Le=await cs({billingApiUrl:Ae,sessionId:U,nonce:Bt,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 zt=(await new si(Ae).waitForCheckoutSessionCompletion(U,{initialDelayMs:0,nonce:Bt})).data.session;if(!zr(zt))throw yr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:y.autoProcessingError.checkoutMethod});await Y({result:kr(zt,U),session:zt,sessionId:zt.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 Mt=await Hr({billingApiUrl:Ae,sessionId:U??dt.id,session:dt,nonce:Bt});if(Mt.type!=="success")throw yr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Y({result:Mt.result,session:dt,sessionId:dt.id||U,autoCompleted:!1})}catch(Mt){let W=Rr(Mt),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:Bt||void 0})}},[t,Ae,$,Y]),Be=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)},[]),P=Eo(()=>Jc(H),[H]),nt=Eo(()=>{let y=P?.buttonsLayout??Wc(fe);return Q?{...y,...Q,cardButton:{...y.cardButton,...Q.cardButton}}:y},[P,fe,Q]),St=Eo(()=>{let y=P?.appearance;return C?y?{...y,...C,variables:{...y.variables,...C.variables}}:C:y},[C,P]),ue=St?.variables,ct=ue?.colorPrimary??"#4A49FF",it=ue?.colorPrimaryHover??po(ct,.12),rt=ue?.borderRadius??"8px";return rd(nd,{children:[Xr("button",{...Te,type:Rt,onClick:Be,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:P,resolvedPrimaryColor:ct,resolvedBorderRadius:rt,submitButtonStyle:nt.submitButton,explicitPrimaryColor:ue?.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&&(P||ue?.colorPrimary)&&(y.currentTarget.style.backgroundColor=it)},onMouseLeave:y=>{Te.onMouseLeave?.(y),!y.defaultPrevented&&(P||ue?.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})}),de&&Xr(Yn,{status:de,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};
|