@flopay/react 1.8.8 → 1.8.9
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 +20 -3
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as st,b as jn,c as xa,d as go,e as Yi,f as Gi,g as gl,h as hl}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as yp}from"@flopay/shared";import{PaymentAPI as yi}from"@flopay/js";import{FloPayError as to,resolveBillingApiUrl as od,resolveButtonsLayoutTheme as ad,resolveTheme as id}from"@flopay/shared";import{useCallback as hr,useEffect as Zr,useMemo as To,useRef as Qr,useState as xo}from"react";import{Fragment as Ur,jsx as kn,jsxs as Wi}from"react/jsx-runtime";function bl(){return Wi(Ur,{children:[Wi("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:[kn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),kn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",kn("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:kn("path",{d:"M9 18l6-6-6-6"})})]})}function vl(){return kn(Ur,{children:"Go back"})}function Pl(){return kn(Ur,{children:"Secure card checkout"})}function Nr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Or({content:e}){return kn(Ur,{children:e===void 0?kn(bl,{}):e})}function zr({content:e}){return kn(Ur,{children:e===void 0?kn(vl,{}):e})}function ho({content:e}){return kn(Ur,{children:e===void 0?kn(Pl,{}):e})}import{FloPayError as Ba,isMoneySettledOutcome as Cl,isSetupIntentClientSecret as bd,isValidEmail as Sl}from"@flopay/shared";function qr(e,t,n,r={}){let a;return(i={})=>{if(a)return a;let d={...r,...i,email:i.email?.trim()||r.email?.trim()};if(!Sl(d.email))return Promise.reject(new Ba("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let s={};for(let[S,f]of Object.entries(d)){if(typeof f!="string")continue;let g=f.trim();g&&(s[S]=g)}return a=e.claimCheckoutSession(t,n,{accountData:s}),a.catch(()=>{}),a}}function Ji(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 Aa(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 Xi(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,d)=>i+(d.overrideAmount??d.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:a,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((i,d)=>({uuid:`synthetic-${i.type??"item"}-${d}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Sr(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 Ma(e,t){return t?{...e,...t}:e}function Ft(e,t,n){let r=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...a?{code:a}:{},...i?{declineCode:i}:{}}}var wl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function ur(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of wl)if(n.test(t))return r;return e}function wr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function $r(e){return e?.status==="authorized"||e?.status==="complete"}function Zi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Ko(e){let t=Zi(e);return new Ba(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Vo(e){let t=Zi(e);return new Ba(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 Ho(e,t){return e==="processing"||Cl(e,t)}function Qi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function es(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function bo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as ca,SESSION_CREATE_TELEMETRY as qc}from"@flopay/js";import{buildCheckoutDisplayData as $c,classifyTelemetryFailure as qs,FloPayError as Lt,foldIntoProducts as jc,isDetachedSessionEligible as Kc,resolveBillingApiUrl as Vc,resolveButtonsLayoutTheme as Hc,resolveIdempotencyKey as $s,resolveSessionCurrency as Yc,resolveTheme as Hs,SDK_VERSION as Ys,telemetryStatusClass as Gc}from"@flopay/shared";import ti,{useCallback as Vn,useEffect as Hn,useMemo as Rn,useRef as Tt,useState as It}from"react";import{createContext as ts}from"react";var In=ts({flopay:null,paypalFlopay:null,billingApiUrl:""}),Dn=ts({session:null,loading:!1,error:null});import{PaymentAPI as La}from"@flopay/js";import{classifyTelemetryFailure as Ul,FloPayError as ss,generateIdempotencyKey as ql,isValidEmail as Co,normalizeGatewayEnvironment as $l,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Na,SDK_VERSION as jl}from"@flopay/shared";import{loadScript as Kl}from"@paypal/paypal-js";import{useCallback as Xo,useEffect as vt,useMemo as So,useRef as Je,useState as Ir}from"react";import{isValidEmail as kl}from"@flopay/shared";import{useCallback as ns,useEffect as Il,useRef as rs,useState as as}from"react";import{jsx as os,jsxs as vo}from"react/jsx-runtime";function on(e){let{firstName:t,lastName:n,...r}=e,a=t?.trim(),i=n?.trim();return{...r,...a?{firstName:a}:{},...i?{lastName:i}:{}}}function jr(){let[e,t]=as(null),n=rs(null),r=rs(0),a=ns((d,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:d,identity:s}),new Promise(S=>{n.current=S})),[]),i=ns(d=>{let s=n.current;n.current=null,t(null),s?.(d)},[]);return Il(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:a,finish:i}}function Kr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:a=!1,testId:i="flopay-buyer-identity-pane"}){let[d,s]=as(e.email?.trim()??""),S=kl(d.trim());return vo("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[vo("div",{style:{fontWeight:700},children:["Continue with ",t]}),vo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",os("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:d,onChange:f=>s(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),vo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&os("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),vo("button",{type:"button",disabled:!S||a,onClick:()=>{n(on({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Rl(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 kr(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 kr(t.code)??kr(t.type)??kr(t.name)}function Vr(e){if(!(typeof e!="object"||e===null))return kr(e.decline_code)}function Po(e){return typeof e!="object"||e===null?!1:kr(e.type)?.toLowerCase()==="card_error"||Vr(e)!==void 0}function pr(e){let t=Rl(e)?.toLowerCase()??"",r=`${tr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as El}from"@flopay/shared";import{useContext as Yo}from"react";function mr(){return Yo(In).flopay}function Fa(){return Yo(In).paypalFlopay??null}function _l(){return Yo(Dn)}function is(){return Yo(In).billingApiUrl||El()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Bl}from"@flopay/shared";import{useCallback as Al,useRef as Wo}from"react";import{useEffect as Tl,useLayoutEffect as xl}from"react";var Go=typeof window>"u"?Tl:xl;var Ml={"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 Fl(e){return e==="stripe"||e==="paypal"?e:void 0}function Dl(e){let t=Fl(e.provider),n={schemaVersion:Bl,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Ml[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 Da=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Hr(e,t){let n=Wo(e);n.current=e;let r=Wo(new Set),a=Wo(t),i=Wo(t);return Go(()=>{i.current=t,a.current!==t&&(a.current=t,r.current.clear())},[t]),Al(d=>{if(i.current!==t)return;let s=Dl(d);if(s){if(Da.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}st(()=>n.current?.(s))}},[t])}var Ll=Symbol.for("@flopay/js.telemetry.bridge.v1"),Nl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ol(){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 zl(e){let t=Ol(),n=(a,i)=>a?a.bind(e):i,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):a=>Math.max(0,r()-a),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 Jo(e){let t=globalThis[Nl];return zl(t?.(e)??{})}function Dt(e){if(e)return e[Ll]}import{jsx as Rr,jsxs as Oa}from"react/jsx-runtime";var Zo=45,Vl=1e3,Hl=11e3,Yl=["https://www.paypal.com","https://www.sandbox.paypal.com"],ls="We couldn't open PayPal. Try again or choose another payment method.",Gl={width:"100%",minHeight:Zo,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 cs(e){return e.includes("No ack for postMessage init()")&&Yl.some(t=>e.includes(t))&&e.includes("10000ms")}function Wl(e){return e?`${ls} Allow pop-ups for this site, then try again.`:ls}function Jl(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 ds({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:a,onBuyerIdentityReady:i,clientId:d,environment:s,currency:S,isSubscription:f,providerObjectType:g,onTokenizedBody:b,onComplete:B,onErrorChange:F,onDecline:m,onTechnicalFailure:w,isProcessing:be=!1,onLoadStateChange:V,onInitializationStateChange:C,allowAutomaticRetry:ye=!0,onButtonClick:ne,runBeforeButtonClick:le,session:ce,existingOrderId:ve,telemetry:He,telemetryContext:ge,onInstrument:Rt,debug:Ne=!1}){let Ee=mr(),_e=Hr(Rt,e),re=So(()=>{if(Ee)return null;let y=Jo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:jl,enabled:He!==!1});return y.setCheckoutContext(ge??{}),y.beginCheckout(ge??{}),y},[n,Ee,He,ge?.checkoutMode,ge?.layout]),oe=So(()=>Dt(Ee),[Ee]);vt(()=>()=>{re&&re.flush().catch(()=>{}).finally(()=>re.destroy())},[re]);let D=So(()=>({error:y=>{oe?oe.error(y):re?.error(y),_e({class:"technical_error",errorCode:y.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":y.errorCode,requestCategory:y.requestCategory,provider:y.provider})},log:y=>{oe?oe.log(y):re?.log(y),_e({class:"lifecycle",name:y.name,provider:y.provider})},performance:y=>{oe?oe.performance(y):re?.performance(y)},terminal:y=>{oe?oe.terminal(y):re?.terminal(y)},startTiming:()=>oe?.now()??re?.now()??0,elapsed:y=>oe?.elapsed(y)??Math.max(0,(re?.now()??y)-y)}),[_e,oe,re]),Te=Je(null),xe=Je(0),Be=Je(null),Oe=Je(!1),[Pe,x]=Ir(!1),[ie,Me]=Ir(!1),[se,H]=Ir(0),ke=Je(0),[Xe,nt]=Ir(!1),Ae=Je(!1),G=Je(!1),[$,O]=Ir(!1),[Ce,$e]=Ir(!1),{request:E,collect:W,finish:T}=jr(),P=Je({sessionId:e,required:!Co(r?.trim()||ce?.customer?.email?.trim())});P.current.sessionId!==e&&(P.current={sessionId:e,required:!Co(r?.trim()||ce?.customer?.email?.trim())});let Ze=P.current.required,ft=So(()=>n.replace(/\/+$/,""),[n]),Z=g??(f?"subscription":"order"),Qe=g==="order"||g==="setup_token",Ve=So(()=>JSON.stringify([ft,d,S,s??"",Z,Qe,e,ve??""]),[ft,d,S,s,ve,Z,Qe,e]),gt=Je(Ve),St=gt.current!==Ve,[h,J]=Ir([]),Q=y=>{Ne&&J(ht=>[...ht,`${new Date().toISOString().slice(11,23)} ${y}`])},rt=Je(b),xt=Je(B),Pt=Je(F),Ye=Je(m),je=Je(w),Vt=Je(ne),Ot=Je(V),Bt=Je(C),dn=Je(i),En=Je(le),Nn=Je(ce),Zt=Je(r),_n=Je(a),Gt=Je(t),et=Je(null),un=Je(0),ze=Je(null),On=Je(null),ot=Je(new Map),ar=Je(new Map),zt=Je(!1);vt(()=>(zt.current=!0,()=>{zt.current=!1}),[]),vt(()=>{rt.current=b},[b]),vt(()=>{dn.current=i},[i]),vt(()=>{xt.current=B},[B]),vt(()=>{Pt.current=F},[F]),vt(()=>{Ye.current=m},[m]),vt(()=>{je.current=w},[w]),vt(()=>{Vt.current=ne},[ne]),vt(()=>{Ot.current=V},[V]),vt(()=>{Bt.current=C},[C]),vt(()=>{En.current=le},[le]),vt(()=>{Nn.current=ce},[ce]),vt(()=>{Zt.current=r},[r]),vt(()=>{_n.current=a},[a]),vt(()=>{Gt.current=t},[t]),vt(()=>{ke.current=se},[se]),vt(()=>{Xe&&Be.current?.focus()},[Xe,se]);let Ht=Xo(()=>{window.setTimeout(()=>{Be.current?.focus()},0)},[]),pn=Xo(()=>{x(!1),H(y=>y+1)},[]),an=Xo(()=>{nt(!1),(Te.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Te.current)?.focus?.()},[]);vt(()=>{!Pe||!Oe.current||(Oe.current=!1,an())},[an,Pe,se]);let mn=Xo((y,ht)=>{let Yt=je.current;if(Yt){Yt("paypal",y,ht);return}Pt.current?.(Wl(ht?.popupBlocked??pr(y)))},[]),At=()=>{ze.current?.timer&&(clearTimeout(ze.current.timer),ze.current.timer=null)},ir=()=>{At();let y=un.current+1;return un.current=y,On.current=null,ze.current={generation:y,timer:null,yieldedControl:!1},nt(!1),y},Ut=y=>y!==void 0&&ze.current?.generation!==y?!1:(At(),ze.current=null,On.current=null,!0),ee=y=>{let ht=y?.generation??ze.current?.generation??un.current;(!y?.generation||ze.current?.generation===ht)&&(At(),ze.current=null),On.current=ht,y?.showRetry&&nt(!0),y?.remount&&pn(),y?.focus!==!1&&Ht()},sr=y=>ze.current?.generation===y&&On.current!==y,yn=y=>{typeof document<"u"&&document.visibilityState!=="visible"||(At(),y.timer=setTimeout(()=>{ze.current?.generation===y.generation&&(ze.current=null,On.current=y.generation,mn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),nt(!0),pn(),Ht())},600))},Qt=()=>{let y=ze.current;y?.yieldedControl&&yn(y)},zn=()=>{let y=ze.current;y&&(y.yieldedControl=!0,At())},fn=y=>{let ht=et.current;return ht&&ar.current.set(y,ht),y};vt(()=>{let y=()=>{document.visibilityState==="visible"?Qt():zn()};return document.addEventListener("visibilitychange",y),window.addEventListener("focus",Qt),window.addEventListener("blur",zn),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("focus",Qt),window.removeEventListener("blur",zn),At()}},[]),vt(()=>{gt.current!==Ve&&(gt.current=Ve,Ae.current=!1,G.current=!1,x(!1),Me(!1),O(!1),Bt.current?.("loading"))},[Ve]),vt(()=>{st(()=>Ot.current?.(Pe&&!$))},[Pe,$]);let Gn=$l(s);vt(()=>{let y=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",ht=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(Q(`mount clientId=${y} env=${s??"(unset)"}\u2192${Gn??"live"} ccy=${S} sub=${f}`),Q(`ua=${ht.slice(0,80)}${ht.length>80?"\u2026":""}`),!d){Q("FAIL: clientId empty \u2014 gateway misconfigured"),O(!0),D.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Te.current){Q("FAIL: containerRef not attached");return}xe.current=D.startTiming(),D.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Yt=!1,Wn=!1,Fe=()=>Yt||Wn,wt,dt=!1,Wt=()=>{wt=ql(),wt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),dt=!0},Jn=null,lr=!1,Xn=null,br=!1,hn=()=>{!Xn||br||(br=!0,Xn.close().catch(()=>{}))},Zn=null,Un=()=>{Zn!==null&&(D.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"overlay_return",durationMs:D.elapsed(Zn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Zn=null)},en=!1,bt=Te.current,Tn=null,sn=null,tn=[],nn=p=>{if(!p||typeof p.getBoundingClientRect!="function")return"(no rect)";let l=p.getBoundingClientRect();return`${Math.round(l.width)}\xD7${Math.round(l.height)}`},at=p=>{if(!p)return"(empty)";try{let l=new URL(p,typeof window<"u"?window.location.href:"https://localhost"),c=l.pathname.toLowerCase();return c.includes("checkcaptcha")||c.includes("captcha")?`CAPTCHA(${l.host}${c})`:c.includes("risk")||c.includes("challenge")?`RISK(${l.host}${c})`:c.includes("smart/buttons")?`smart-buttons(${l.host})`:`${l.host}${c}`.slice(0,100)}catch{return p.slice(0,80)}},Qn=p=>{let l=p.getAttribute("src"),c=p.getAttribute("srcdoc"),I=p.getAttribute("name"),R=p.getAttribute("sandbox"),ae=[];return l&&ae.push(`src=${at(l)}`),c&&ae.push(`srcdoc[${c.length}ch]`),!l&&!c&&ae.push("src=(empty) srcdoc=(empty)"),I&&ae.push(`name=${I.slice(0,40)}`),R!==null&&ae.push(`sandbox="${R.slice(0,40)}"`),ae.join(" ")},xn=p=>{if(!(p instanceof HTMLIFrameElement))return"";try{let l=p.contentDocument;if(!l)return"cd=null";let c=l.body?.children.length??0,I=l.body?.innerHTML.length??0,R=l.head?.innerHTML.length??0;return`cd=same-origin readyState=${l.readyState} body[${c}children,${I}ch] head[${R}ch]`}catch(l){return`cd=cross-origin(${l.message.slice(0,30)})`}},bn=[],Bn=p=>{if(Fe())return;let l=p.message??String(p.error??"(no message)");l&&(l.toLowerCase().includes("paypal")||l.toLowerCase().includes("zoid")||l.toLowerCase().includes("postrobot")||l.toLowerCase().includes("storage"))&&(Q(`window:error ${l.slice(0,140)}`),bn.push(l))},De=p=>{if(Fe())return;let l=p.reason instanceof Error?p.reason.message:String(p.reason??"(no reason)");l&&(l.toLowerCase().includes("paypal")||l.toLowerCase().includes("zoid")||l.toLowerCase().includes("postrobot")||l.toLowerCase().includes("storage"))&&(Q(`window:rejection ${l.slice(0,140)}`),bn.push(l))};Ne&&typeof window<"u"&&(window.addEventListener("error",Bn),window.addEventListener("unhandledrejection",De));let Mt={value:0};if(Ne&&typeof PerformanceObserver<"u")try{sn=new PerformanceObserver(p=>{if(!Fe())for(let l of p.getEntries()){if(!l.name.toLowerCase().includes("paypal"))continue;Mt.value+=1;let c=Math.round(l.duration);Q(`net ${c}ms ${l.name.slice(0,90)}`)}}),sn.observe({type:"resource",buffered:!0})}catch{}let Et=()=>{for(Tn?.disconnect(),Tn=null,sn?.disconnect(),sn=null;tn.length;)clearTimeout(tn.pop());Ne&&typeof window<"u"&&(window.removeEventListener("error",Bn),window.removeEventListener("unhandledrejection",De))},An=p=>{if(!p)return!1;let l=p.toLowerCase();return l.includes("zoid destroyed")||l.includes("destroyed all components")||l.includes("window closed")||l.includes("detected container element removed")},cr=p=>{if(Fe()||An(p))return;let l=ur(p)??p;st(()=>Pt.current?.(l))},er=p=>{Yt||(O(!0),p.includes("paypal_ineligible")||D.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:",p))},ln=(p,l=!1)=>{if(Yt)return;let c=Ae.current||!ye;if(lr)return;lr=!0,Wn=!0,Et(),hn();let I=l||cs(p);if(I&&ye&&!Ae.current){Ae.current=!0,x(!1),$e(!1),Me(!0),Bt.current?.("retrying"),Jn=setTimeout(()=>{Yt||H(R=>R+1)},Vl);return}if(I||c){if(x(!1),$e(!1),Me(!1),O(!0),Bt.current?.("exhausted"),!G.current){G.current=!0;let R=cs(p)?"paypal_init_timeout":l?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",R)}return}er(p)};O(!1);let qt=async(p,l=et.current)=>{if(Fe())return;let c=l?.sessionId??e;if(rt.current){await rt.current(p,{sessionId:c,accountPatch:l?.accountPatch,nonce:l?.nonce});return}let I=D.startTiming();D.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let R=()=>{D.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"processing",durationMs:D.elapsed(I),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let ae=Nn.current,Ge=l?.accountPatch?.email??Zt.current,j=l?.accountPatch?.userId??ae?.customer?.id??ae?.accountData?.userId??"",Y=l?.accountPatch?.firstName??ae?.customer?.firstName??ae?.accountData?.firstName,me=l?.accountPatch?.lastName??ae?.customer?.lastName??ae?.accountData?.lastName,v=await new La(ft,{telemetry:!1}).processPayment(j,{sessionId:c,nonce:l?.nonce??Gt.current,tokenizedData:p,accountData:{userId:j,email:Ge??ae?.customer?.email??"",...Y?{firstName:Y}:{},...me?{lastName:me}:{},country:l?.accountPatch?.country??ae?.customer?.country??ae?.accountData?.country??void 0,zip:l?.accountPatch?.zip??ae?.customer?.zip??ae?.accountData?.zip??void 0}});if(v.ok){if(Wn||Yt&&zt.current)return;R(),D.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),st(()=>xt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Fe())return;let U=await v.json().catch(()=>null),_=U?.message??"PayPal payment failed.",K=ur(_)??_;R(),v.status===400&&(typeof U?.declineCode=="string"||!Array.isArray(U?.fields))?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):v.status===400||v.status===422?D.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):D.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:v.status>=500?"5xx":v.status>=400?"4xx":v.status>=300?"3xx":"unknown",failureCategory:v.status>=500?"server_error":void 0}),cr(K),st(()=>Ye.current?.(Ft("paypal",K,{code:U?.code,declineCode:U?.declineCode})));return}catch(ae){if(Fe())return;R(),D.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ge=ae instanceof Error?ae.message:"PayPal payment failed.",j=ur(Ge)??Ge;cr(j),st(()=>Ye.current?.(Ft("paypal",j)));return}},vn=()=>new ss("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),_t=p=>Fe()?Promise.reject(vn()):Promise.resolve(p),M=async p=>{if(Fe())throw vn();dt||Wt();let l=et.current,c=l?.sessionId??e,I=l?.nonce??Gt.current;D.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let R;try{R=await new La(ft,{telemetry:!1}).createSessionIntent(c,I??"",Qe?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Na,paymentMethodId:null,intentKind:Z==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:wt})}catch(ae){throw D.error({...Ul(ae,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ae}if(Fe())throw vn();if(R.provider!=="paypal"||R.providerObjectType!==Z)throw new Error(p);return D.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),R.providerObjectId},L=(p,l)=>{let c=l?.nonce??Gt.current;if(!c)return;let I=l?.sessionId??e,R=Vr(p)??tr(p)??"provider_declined";new La(ft,{telemetry:!1}).reportSessionIntentDecline(I,c,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:R}).catch(()=>{})},z=se;Q("loadScript:scheduled (deferred 1 tick)");let X=null,Se=setTimeout(()=>{if(Yt){Q("loadScript:skipped (cancelled before defer ran)");return}Q("loadScript:start");let p=Gn==="live"?"production":Gn;X=Kl({clientId:d,currency:S,...Z==="subscription"?{intent:"subscription",vault:!0}:Z==="order"?{intent:"capture"}:{},...p?{environment:p}:{},...p==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),X.then(l=>{if(Q(`loadScript:resolved inactive=${Fe()} ns=${!!l} buttons=${!!l?.Buttons}`),Fe())return;if(!l?.Buttons){Q("FAIL: namespace missing Buttons factory"),ln("PayPal SDK did not expose the Buttons factory.");return}D.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"provider_ready",durationMs:D.elapsed(xe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let c=async(Y,me)=>{if(Fe()||ke.current!==z)return;let A=Y.vaultSetupToken??Y.subscriptionID??Y.orderID??"",v=A?ar.current.get(A):ot.current.get(z);if(!(!v||!sr(v.generation))&&Ut(v.generation)){ar.current.delete(A),ot.current.delete(v.surfaceKey),Un();try{if($e(!0),st(()=>Pt.current?.(null)),!A)throw new ss("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let U=Nn.current,_=Sr(_n.current??[U?.customer?.firstName,U?.customer?.lastName].filter(Boolean).join(" ")),K=on({email:v.accountPatch?.email?.trim()||Zt.current?.trim()||U?.customer?.email?.trim(),firstName:v.accountPatch?.firstName?.trim()||_.firstName,lastName:v.accountPatch?.lastName?.trim()||_.lastName});if(!Co(K.email)||!(K.firstName||K.lastName))try{let Ue=Jl(await me?.order?.get?.());K=on({email:Ue.email||K.email,firstName:Ue.firstName||K.firstName,lastName:Ue.lastName||K.lastName})}catch{}if((dn.current||Ze)&&!Co(K.email)){let Ue=await W("PayPal",K);if(!Ue)return;K=Ue}Co(K.email)&&(v.accountPatch=on({...v.accountPatch,...K}),await dn.current?.(K)),await qt(Z==="setup_token"?{id:A,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Na}:Qe?{id:A,isPaypal:!0,gateway:"paypal",paymentMethodType:Na}:{id:A,isPaypal:!0},v)}catch(U){cr(U instanceof Error?U.message:"PayPal capture failed.")}finally{Fe()||$e(!1)}}},I=l.Buttons({style:{layout:"horizontal",height:Zo,tagline:!1},onClick:async(Y,me)=>{if(Fe()){await me.reject();return}Wt();let A=En.current,v={};if(A)try{let K=await A("paypal");if(Fe()){await me.reject();return}if(!K.proceed){et.current=null,ot.current.delete(z),await me.reject();return}v={sessionId:K.sessionId,accountPatch:K.accountPatch,nonce:K.nonce}}catch(K){Q(`onClick:runBeforeButtonClick rejected msg=${(K instanceof Error?K.message:String(K)).slice(0,120)}`),et.current=null,ot.current.delete(z),await me.reject();return}st(()=>Vt.current?.("paypal"));let _={generation:ir(),surfaceKey:z,...v};et.current=_,ot.current.set(z,_),await me.resolve(),D.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Zn=D.startTiming()},createOrder:Z==="order"?ve?()=>_t(ve).then(fn):()=>M("Failed to create PayPal order.").then(fn):void 0,createSubscription:Z==="subscription"?ve?()=>_t(ve).then(fn):()=>M("Failed to create PayPal subscription.").then(fn):void 0,createVaultSetupToken:Z==="setup_token"?()=>M("Failed to create PayPal setup token.").then(fn):void 0,onApprove:c,onCancel:()=>{if(Fe())return;let Y=ot.current.get(z)??et.current;Y&&ot.current.delete(Y.surfaceKey),et.current=null,Un(),D.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Oe.current=!0,ee({generation:Y?.generation,remount:!0,focus:!1})},onError:Y=>{if(Fe()||ke.current!==z)return;let me=Y instanceof Error?Y.message:"PayPal failed to render.";if(Q(`onError rendered=${en} msg=${me.slice(0,120)}`),en){let A=ot.current.get(z)??et.current;if(A&&!sr(A.generation)||!A&&On.current===un.current)return;if(An(me)){Ut(A?.generation);return}if(Un(),Po(Y)){D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),L(Y,A),st(()=>Ye.current?.(Ft("paypal",me))),A&&ot.current.delete(A.surfaceKey),et.current=null,Ut(A?.generation);return}let v=me.toLowerCase();D.error({errorCode:v.includes("popup")&&v.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),A&&ot.current.delete(A.surfaceKey),et.current=null,ee({generation:A?.generation,remount:!0,showRetry:!0,focus:!0}),mn(Y,{code:"paypal_runtime_failed"});return}ln(me)}}),R=I.isEligible();if(Q(`isEligible=${R}`),D.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!R){x(!1),ln("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Xn=I,Ne&&Q(`container:dims ${nn(bt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),Ne&&typeof MutationObserver<"u"&&(Tn=new MutationObserver(Y=>{if(!Fe()){for(let me of Y)if(me.type==="childList")me.addedNodes.forEach(A=>{if(!(A instanceof Element))return;let v=A.tagName.toLowerCase(),U=(A.getAttribute("title")??"").slice(0,40),_=v==="iframe"?` ${Qn(A)}`:"";Q(`child+ ${v}${U?` title="${U}"`:""}${_} dims=${nn(A)}`)});else if(me.type==="attributes"&&me.target instanceof Element){let A=me.target;if(A.tagName.toLowerCase()!=="iframe")continue;let v=me.attributeName;(v==="src"||v==="srcdoc")&&Q(`attr~ iframe ${v}=${v==="srcdoc"?`[${(A.getAttribute("srcdoc")??"").length}ch]`:at(A.getAttribute("src"))} dims=${nn(A)}`)}}}),Tn.observe(bt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ge=Y=>{if(Fe()||en)return;let me=bt.querySelectorAll("iframe"),A=typeof document<"u"&&"hasStorageAccess"in document;Q(`watchdog:${Y} container=${nn(bt)} children=${bt.childElementCount} iframes=${me.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${A} paypalNetRequests=${Mt.value}`),me.forEach((v,U)=>{let _=(v.getAttribute("title")??"").slice(0,40);Q(` iframe[${U}] ${nn(v)}${_?` title="${_}"`:""} ${Qn(v)}`);let K=xn(v);K&&Q(` ${K}`)}),bn.length===0&&Q(" (no PayPal/zoid window errors captured)")};Ne&&(tn.push(setTimeout(()=>Ge("3s"),3e3)),tn.push(setTimeout(()=>Ge("8s"),8e3)),tn.push(setTimeout(()=>Ge("15s"),15e3))),Q("render:start");let j=D.startTiming();tn.push(setTimeout(()=>{Fe()||en||(Q("watchdog:11s retryable render timeout"),ln("PayPal Buttons render did not settle within 11000ms.",!0))},Hl)),I.render(bt).then(()=>{if(Q(`render:resolved inactive=${Fe()}`),Et(),Fe()){hn();return}en=!0,x(!0),Me(!1),Bt.current?.("ready"),D.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"checkout_render",durationMs:D.elapsed(j),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Y=>{let me=Y instanceof Error?Y.message:"PayPal failed to render.";Q(`render:rejected msg=${me.slice(0,120)}`),Et(),ln(me)})}).catch(l=>{let c=l instanceof Error?l.message:"PayPal SDK failed to load.";Q(`loadScript:rejected msg=${c.slice(0,120)}`),ln(c)})},0);return()=>{Yt=!0,clearTimeout(Se),Jn&&clearTimeout(Jn),Et(),hn()}},[ye,ft,d,S,s,Z,Qe,e,ve,se,D,W,Ze]);let gn=Ne?Oa("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:$?"#fef2f2":"#f3f4f6",border:`1px solid ${$?"#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=${Pe} failed=${$})`,h.length===0?`
|
|
1
|
+
import{a as _t,b as Wn,c as Ba,d as bo,e as Wi,f as Gi,g as gl,h as hl}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as fp}from"@flopay/shared";import{PaymentAPI as fi}from"@flopay/js";import{FloPayError as ro,resolveBillingApiUrl as ad,resolveButtonsLayoutTheme as id,resolveTheme as sd}from"@flopay/shared";import{useCallback as vr,useEffect as eo,useMemo as Fo,useRef as to,useState as Do}from"react";import{Fragment as $r,jsx as Mn,jsxs as Ji}from"react/jsx-runtime";function bl(){return Ji($r,{children:[Ji("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:[Mn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Mn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Mn("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:Mn("path",{d:"M9 18l6-6-6-6"})})]})}function vl(){return Mn($r,{children:"Go back"})}function Pl(){return Mn($r,{children:"Secure card checkout"})}function zr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Ur({content:e}){return Mn($r,{children:e===void 0?Mn(bl,{}):e})}function qr({content:e}){return Mn($r,{children:e===void 0?Mn(vl,{}):e})}function vo({content:e}){return Mn($r,{children:e===void 0?Mn(Pl,{}):e})}import{FloPayError as Ma,isMoneySettledOutcome as Cl,isSetupIntentClientSecret as vd,isValidEmail as Sl}from"@flopay/shared";function jr(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()};if(!Sl(l.email))return Promise.reject(new Ma("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let s={};for(let[C,y]of Object.entries(l)){if(typeof y!="string")continue;let f=y.trim();f&&(s[C]=f)}return o=e.claimCheckoutSession(t,n,{accountData:s}),o.catch(()=>{}),o}}function Xi(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:"checkoutMetadata"in e?{checkoutMetadata:e.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Aa(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Zi(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function kr(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 Fa(e,t){return t?{...e,...t}:e}function Ut(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 wl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function mr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of wl)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 Kr(e){return e?.status==="authorized"||e?.status==="complete"}function Qi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Go(e){let t=Qi(e);return new Ma(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Jo(e){let t=Qi(e);return new Ma(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 Xo(e,t){return e==="processing"||Cl(e,t)}function es(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ts(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Po(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as pa,SESSION_CREATE_TELEMETRY as qc}from"@flopay/js";import{buildCheckoutDisplayData as $c,classifyTelemetryFailure as $s,FloPayError as $t,foldIntoProducts as jc,isDetachedSessionEligible as Kc,resolveBillingApiUrl as Vc,resolveButtonsLayoutTheme as Hc,resolveIdempotencyKey as js,resolveSessionCurrency as Yc,resolveTheme as Ys,SDK_VERSION as Ws,telemetryStatusClass as Wc}from"@flopay/shared";import ni,{useCallback as Jn,useEffect as Xn,useMemo as Fn,useRef as Tt,useState as xt}from"react";import{createContext as ns}from"react";var An=ns({flopay:null,paypalFlopay:null,billingApiUrl:""}),qn=ns({session:null,loading:!1,error:null});import{PaymentAPI as Na}from"@flopay/js";import{classifyTelemetryFailure as Ul,FloPayError as ls,generateIdempotencyKey as ql,isValidEmail as ko,normalizeGatewayEnvironment as $l,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Oa,SDK_VERSION as jl}from"@flopay/shared";import{loadScript as Kl}from"@paypal/paypal-js";import{useCallback as Io,useEffect as bt,useMemo as Ro,useRef as Je,useState as Er}from"react";import{isValidEmail as kl}from"@flopay/shared";import{useCallback as rs,useEffect as Il,useRef as os,useState as is}from"react";import{jsx as as,jsxs as Co}from"react/jsx-runtime";function ln(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),a=n?.trim();return{...r,...o?{firstName:o}:{},...a?{lastName:a}:{}}}function Vr(){let[e,t]=is(null),n=os(null),r=os(0),o=rs((l,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:s}),new Promise(C=>{n.current=C})),[]),a=rs(l=>{let s=n.current;n.current=null,t(null),s?.(l)},[]);return Il(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Hr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,s]=is(e.email?.trim()??""),C=kl(l.trim());return Co("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:[Co("div",{style:{fontWeight:700},children:["Continue with ",t]}),Co("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",as("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:y=>s(y.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Co("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&as("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Co("button",{type:"button",disabled:!C||o,onClick:()=>{n(ln({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Rl(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 Rr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function rr(e){if(typeof e!="object"||e===null)return;let t=e;return Rr(t.code)??Rr(t.type)??Rr(t.name)}function Yr(e){if(!(typeof e!="object"||e===null))return Rr(e.decline_code)}function So(e){return typeof e!="object"||e===null?!1:Rr(e.type)?.toLowerCase()==="card_error"||Yr(e)!==void 0}function yr(e){let t=Rl(e)?.toLowerCase()??"",r=`${rr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as El}from"@flopay/shared";import{useContext as Zo}from"react";function fr(){return Zo(An).flopay}function Da(){return Zo(An).paypalFlopay??null}function _l(){return Zo(qn)}function ss(){return Zo(An).billingApiUrl||El()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Bl}from"@flopay/shared";import{useCallback as Ml,useRef as Qo}from"react";import{useEffect as Tl,useLayoutEffect as xl}from"react";var wo=typeof window>"u"?Tl:xl;var Al={"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 Fl(e){return e==="stripe"||e==="paypal"?e:void 0}function Dl(e){let t=Fl(e.provider),n={schemaVersion:Bl,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Al[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 La=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Wr(e,t){let n=Qo(e);n.current=e;let r=Qo(new Set),o=Qo(t),a=Qo(t);return wo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Ml(l=>{if(a.current!==t)return;let s=Dl(l);if(s){if(La.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}_t(()=>n.current?.(s))}},[t])}var Ll=Symbol.for("@flopay/js.telemetry.bridge.v1"),Nl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ol(){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 zl(e){let t=Ol(),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 ea(e){let t=globalThis[Nl];return zl(t?.(e)??{})}function qt(e){if(e)return e[Ll]}import{jsx as _r,jsxs as za}from"react/jsx-runtime";var ta=45,Vl=1e3,Hl=11e3,Yl=["https://www.paypal.com","https://www.sandbox.paypal.com"],cs="We couldn't open PayPal. Try again or choose another payment method.",Wl={width:"100%",minHeight:ta,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ds(e){return e.includes("No ack for postMessage init()")&&Yl.some(t=>e.includes(t))&&e.includes("10000ms")}function Gl(e){return e?`${cs} Allow pop-ups for this site, then try again.`:cs}function Jl(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 us({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:s,currency:C,isSubscription:y,providerObjectType:f,onTokenizedBody:h,onComplete:B,onErrorChange:A,onDecline:u,onTechnicalFailure:S,isProcessing:ve=!1,onLoadStateChange:K,onInitializationStateChange:v,allowAutomaticRetry:ye=!0,onButtonClick:Q,runBeforeButtonClick:ce,session:de,existingOrderId:we,telemetry:Qe,telemetryContext:he,onInstrument:Bt,debug:Xe=!1}){let Ae=fr(),Fe=Wr(Bt,e),ee=Ro(()=>{if(Ae)return null;let I=ea({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:jl,enabled:Qe!==!1});return I.setCheckoutContext(he??{}),I.beginCheckout(he??{}),I},[n,Ae,Qe,he?.checkoutMode,he?.layout]),te=Ro(()=>qt(Ae),[Ae]);bt(()=>()=>{ee&&ee.flush().catch(()=>{}).finally(()=>ee.destroy())},[ee]);let F=Ro(()=>({error:I=>{te?te.error(I):ee?.error(I),Fe({class:"technical_error",errorCode:I.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":I.errorCode,requestCategory:I.requestCategory,provider:I.provider})},log:I=>{te?te.log(I):ee?.log(I),Fe({class:"lifecycle",name:I.name,provider:I.provider})},performance:I=>{te?te.performance(I):ee?.performance(I)},terminal:I=>{te?te.terminal(I):ee?.terminal(I)},startTiming:()=>te?.now()??ee?.now()??0,elapsed:I=>te?.elapsed(I)??Math.max(0,(ee?.now()??I)-I)}),[Fe,te,ee]),Le=Je(null),Ne=Je(0),ze=Je(null),Ke=Je(!1),[ke,T]=Er(!1),[oe,Ue]=Er(!1),[ae,V]=Er(0),Ee=Je(0),[nt,dt]=Er(!1),De=Je(!1),H=Je(!1),[U,O]=Er(!1),[Ie,Ye]=Er(!1),{request:k,collect:Y,finish:E}=Vr(),b=Je({sessionId:e,required:!ko(r?.trim()||de?.customer?.email?.trim())});b.current.sessionId!==e&&(b.current={sessionId:e,required:!ko(r?.trim()||de?.customer?.email?.trim())});let it=b.current.required,Pt=Ro(()=>n.replace(/\/+$/,""),[n]),G=f??(y?"subscription":"order"),st=f==="order"||f==="setup_token",Ze=Ro(()=>JSON.stringify([Pt,l,C,s??"",G,st,e,we??""]),[Pt,l,C,s,we,G,st,e]),Ct=Je(Ze),wt=Ct.current!==Ze,g=Je(Xe),$=Je(null),[lt,yt]=Er([]),ie=Io(I=>{g.current&&yt(Dt=>[...Dt,`${new Date().toISOString().slice(11,23)} ${I}`])},[]);bt(()=>{g.current=Xe,Xe&&ie("debug:enabled"),$.current?.setEnabled(Xe)},[ie,Xe]);let kt=Je(h),ot=Je(B),qe=Je(A),Nt=Je(u),Kt=Je(S),Gt=Je(Q),Dn=Je(K),rn=Je(v),jn=Je(a),cn=Je(ce),Cn=Je(de),on=Je(r),Ot=Je(o),Sn=Je(t),et=Je(null),sr=Je(0),rt=Je(null),Ln=Je(null),ft=Je(new Map),Vt=Je(new Map),dn=Je(!1);bt(()=>(dn.current=!0,()=>{dn.current=!1}),[]),bt(()=>{kt.current=h},[h]),bt(()=>{jn.current=a},[a]),bt(()=>{ot.current=B},[B]),bt(()=>{qe.current=A},[A]),bt(()=>{Nt.current=u},[u]),bt(()=>{Kt.current=S},[S]),bt(()=>{Gt.current=Q},[Q]),bt(()=>{Dn.current=K},[K]),bt(()=>{rn.current=v},[v]),bt(()=>{cn.current=ce},[ce]),bt(()=>{Cn.current=de},[de]),bt(()=>{on.current=r},[r]),bt(()=>{Ot.current=o},[o]),bt(()=>{Sn.current=t},[t]),bt(()=>{Ee.current=ae},[ae]),bt(()=>{nt&&ze.current?.focus()},[nt,ae]);let wn=Io(()=>{window.setTimeout(()=>{ze.current?.focus()},0)},[]),kn=Io(()=>{T(!1),V(I=>I+1)},[]),Zt=Io(()=>{dt(!1),(Le.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Le.current)?.focus?.()},[]);bt(()=>{!ke||!Ke.current||(Ke.current=!1,Zt())},[Zt,ke,ae]);let Qn=Io((I,Dt)=>{let It=Kt.current;if(It){It("paypal",I,Dt);return}qe.current?.(Gl(Dt?.popupBlocked??yr(I)))},[]),Mt=()=>{rt.current?.timer&&(clearTimeout(rt.current.timer),rt.current.timer=null)},X=()=>{Mt();let I=sr.current+1;return sr.current=I,Ln.current=null,rt.current={generation:I,timer:null,yieldedControl:!1},dt(!1),I},er=I=>I!==void 0&&rt.current?.generation!==I?!1:(Mt(),rt.current=null,Ln.current=null,!0),un=I=>{let Dt=I?.generation??rt.current?.generation??sr.current;(!I?.generation||rt.current?.generation===Dt)&&(Mt(),rt.current=null),Ln.current=Dt,I?.showRetry&&dt(!0),I?.remount&&kn(),I?.focus!==!1&&wn()},pn=I=>rt.current?.generation===I&&Ln.current!==I,lr=I=>{typeof document<"u"&&document.visibilityState!=="visible"||(Mt(),I.timer=setTimeout(()=>{rt.current?.generation===I.generation&&(rt.current=null,Ln.current=I.generation,Qn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),dt(!0),kn(),wn())},600))},Kn=()=>{let I=rt.current;I?.yieldedControl&&lr(I)},tr=()=>{let I=rt.current;I&&(I.yieldedControl=!0,Mt())},Qt=I=>{let Dt=et.current;return Dt&&Vt.current.set(I,Dt),I};bt(()=>{let I=()=>{document.visibilityState==="visible"?Kn():tr()};return document.addEventListener("visibilitychange",I),window.addEventListener("focus",Kn),window.addEventListener("blur",tr),()=>{document.removeEventListener("visibilitychange",I),window.removeEventListener("focus",Kn),window.removeEventListener("blur",tr),Mt()}},[]),bt(()=>{Ct.current!==Ze&&(Ct.current=Ze,De.current=!1,H.current=!1,T(!1),Ue(!1),O(!1),rn.current?.("loading"))},[Ze]),bt(()=>{_t(()=>Dn.current?.(ke&&!U))},[ke,U]);let Ve=$l(s);bt(()=>{let I=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Dt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(ie(`mount clientId=${I} env=${s??"(unset)"}\u2192${Ve??"live"} ccy=${C} sub=${y}`),ie(`ua=${Dt.slice(0,80)}${Dt.length>80?"\u2026":""}`),!l){ie("FAIL: clientId empty \u2014 gateway misconfigured"),O(!0),F.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(!Le.current){ie("FAIL: containerRef not attached");return}Ne.current=F.startTiming(),F.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let It=!1,Rt=!1,se=()=>It||Rt,Jt,cr=!1,dr=()=>{Jt=ql(),Jt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),cr=!0},nr=null,Pr=!1,Rn=null,Cr=!1,Vn=()=>{!Rn||Cr||(Cr=!0,Rn.close().catch(()=>{}))},mn=null,At=()=>{mn!==null&&(F.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),F.performance({stage:"overlay_return",durationMs:F.elapsed(mn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),mn=null)},an=!1,en=Le.current,En=null,yn=null,at=[],fn=null,gn=!1,hn=!1,bn=null,_e=P=>{if(!P||typeof P.getBoundingClientRect!="function")return"(no rect)";let p=P.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},Xt=P=>{if(!P)return"(empty)";try{let p=new URL(P,typeof window<"u"?window.location.href:"https://localhost"),d=p.pathname.toLowerCase();return d.includes("checkcaptcha")||d.includes("captcha")?`CAPTCHA(${p.host}${d})`:d.includes("risk")||d.includes("challenge")?`RISK(${p.host}${d})`:d.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${d}`.slice(0,100)}catch{return P.slice(0,80)}},Ft=P=>{let p=P.getAttribute("src"),d=P.getAttribute("srcdoc"),q=P.getAttribute("name"),ge=P.getAttribute("sandbox"),le=[];return p&&le.push(`src=${Xt(p)}`),d&&le.push(`srcdoc[${d.length}ch]`),!p&&!d&&le.push("src=(empty) srcdoc=(empty)"),q&&le.push(`name=${q.slice(0,40)}`),ge!==null&&le.push(`sandbox="${ge.slice(0,40)}"`),le.join(" ")},ur=P=>{if(!(P instanceof HTMLIFrameElement))return"";try{let p=P.contentDocument;if(!p)return"cd=null";let d=p.body?.children.length??0,q=p.body?.innerHTML.length??0,ge=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${d}children,${q}ch] head[${ge}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},Nn=[],pr=P=>{if(se())return;let p=P.message??String(P.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(ie(`window:error ${p.slice(0,140)}`),Nn.push(p))},On=P=>{if(se())return;let p=P.reason instanceof Error?P.reason.message:String(P.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(ie(`window:rejection ${p.slice(0,140)}`),Nn.push(p))},vn={value:0},zt=()=>{for(En?.disconnect(),En=null,yn?.disconnect(),yn=null;at.length;)clearTimeout(at.pop());hn=!1,gn&&typeof window<"u"&&(window.removeEventListener("error",pr),window.removeEventListener("unhandledrejection",On)),gn=!1},Fr=()=>{if(!(gn||se()||an)){if(gn=!0,Nn.length=0,vn.value=0,typeof window<"u"&&(window.addEventListener("error",pr),window.addEventListener("unhandledrejection",On)),typeof PerformanceObserver<"u")try{yn=new PerformanceObserver(P=>{if(!se())for(let p of P.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;vn.value+=1;let d=Math.round(p.duration);ie(`net ${d}ms ${p.name.slice(0,90)}`)}}),yn.observe({type:"resource",buffered:!0})}catch{}bn?.()}},_n=()=>{fn&&(clearTimeout(fn),fn=null)},x=()=>{zt(),_n()},M={setEnabled:P=>{P?Fr():zt()}};$.current=M,g.current&&Fr();let j=P=>{if(!P)return!1;let p=P.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},R=P=>{if(se()||j(P))return;let p=mr(P)??P;_t(()=>qe.current?.(p))},Oe=P=>{It||(O(!0),P.includes("paypal_ineligible")||F.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:",P))},W=(P,p=!1)=>{if(It)return;let d=De.current||!ye;if(Pr)return;Pr=!0,Rt=!0,x(),Vn();let q=p||ds(P);if(q&&ye&&!De.current){De.current=!0,T(!1),Ye(!1),Ue(!0),rn.current?.("retrying"),nr=setTimeout(()=>{It||V(ge=>ge+1)},Vl);return}if(q||d){if(T(!1),Ye(!1),Ue(!1),O(!0),rn.current?.("exhausted"),!H.current){H.current=!0;let ge=ds(P)?"paypal_init_timeout":p?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",ge)}return}Oe(P)};O(!1);let _=async(P,p=et.current)=>{if(se())return;let d=p?.sessionId??e;if(kt.current){await kt.current(P,{sessionId:d,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let q=F.startTiming();F.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ge=()=>{F.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),F.performance({stage:"processing",durationMs:F.elapsed(q),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let le=Cn.current,J=p?.accountPatch?.email??on.current,Ce=p?.accountPatch?.userId??le?.customer?.id??le?.accountData?.userId??"",D=p?.accountPatch?.firstName??le?.customer?.firstName??le?.accountData?.firstName,L=p?.accountPatch?.lastName??le?.customer?.lastName??le?.accountData?.lastName,Se=await new Na(Pt,{telemetry:!1}).processPayment(Ce,{sessionId:d,nonce:p?.nonce??Sn.current,tokenizedData:P,accountData:{userId:Ce,email:J??le?.customer?.email??"",...D?{firstName:D}:{},...L?{lastName:L}:{},country:p?.accountPatch?.country??le?.customer?.country??le?.accountData?.country??void 0,zip:p?.accountPatch?.zip??le?.customer?.zip??le?.accountData?.zip??void 0}});if(Se.ok){if(Rt||It&&dn.current)return;ge(),F.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),_t(()=>ot.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(se())return;let ut=await Se.json().catch(()=>null),$e=ut?.message??"PayPal payment failed.",Lt=mr($e)??$e;ge(),Se.status===400&&(typeof ut?.declineCode=="string"||!Array.isArray(ut?.fields))?F.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Se.status===400||Se.status===422?F.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):F.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Se.status>=500?"5xx":Se.status>=400?"4xx":Se.status>=300?"3xx":"unknown",failureCategory:Se.status>=500?"server_error":void 0}),R(Lt),_t(()=>Nt.current?.(Ut("paypal",Lt,{code:ut?.code,declineCode:ut?.declineCode})));return}catch(le){if(se())return;ge(),F.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let J=le instanceof Error?le.message:"PayPal payment failed.",Ce=mr(J)??J;R(Ce),_t(()=>Nt.current?.(Ut("paypal",Ce)));return}},m=()=>new ls("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),re=P=>se()?Promise.reject(m()):Promise.resolve(P),ne=async P=>{if(se())throw m();cr||dr();let p=et.current,d=p?.sessionId??e,q=p?.nonce??Sn.current;F.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ge;try{ge=await new Na(Pt,{telemetry:!1}).createSessionIntent(d,q??"",st?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Oa,paymentMethodId:null,intentKind:G==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Jt})}catch(le){throw F.error({...Ul(le,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),le}if(se())throw m();if(ge.provider!=="paypal"||ge.providerObjectType!==G)throw new Error(P);return F.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ge.providerObjectId},Te=(P,p)=>{let d=p?.nonce??Sn.current;if(!d)return;let q=p?.sessionId??e,ge=Yr(P)??rr(P)??"provider_declined";new Na(Pt,{telemetry:!1}).reportSessionIntentDecline(q,d,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ge}).catch(()=>{})},We=ae;ie("loadScript:scheduled (deferred 1 tick)");let xe=null,Pe=setTimeout(()=>{if(It){ie("loadScript:skipped (cancelled before defer ran)");return}ie("loadScript:start");let P=Ve==="live"?"production":Ve;xe=Kl({clientId:l,currency:C,...G==="subscription"?{intent:"subscription",vault:!0}:G==="order"?{intent:"capture"}:{},...P?{environment:P}:{},...P==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),xe.then(p=>{if(ie(`loadScript:resolved inactive=${se()} ns=${!!p} buttons=${!!p?.Buttons}`),se())return;if(!p?.Buttons){ie("FAIL: namespace missing Buttons factory"),W("PayPal SDK did not expose the Buttons factory.");return}F.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),F.performance({stage:"provider_ready",durationMs:F.elapsed(Ne.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),F.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let d=async(Ce,D)=>{if(se()||Ee.current!==We)return;let L=Ce.vaultSetupToken??Ce.subscriptionID??Ce.orderID??"",ue=L?Vt.current.get(L):ft.current.get(We);if(!(!ue||!pn(ue.generation))&&er(ue.generation)){Vt.current.delete(L),ft.current.delete(ue.surfaceKey),At();try{if(Ye(!0),_t(()=>qe.current?.(null)),!L)throw new ls("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Se=Cn.current,ut=kr(Ot.current??[Se?.customer?.firstName,Se?.customer?.lastName].filter(Boolean).join(" ")),$e=ln({email:ue.accountPatch?.email?.trim()||on.current?.trim()||Se?.customer?.email?.trim(),firstName:ue.accountPatch?.firstName?.trim()||ut.firstName,lastName:ue.accountPatch?.lastName?.trim()||ut.lastName});if(!ko($e.email)||!($e.firstName||$e.lastName))try{let Lt=Jl(await D?.order?.get?.());$e=ln({email:Lt.email||$e.email,firstName:Lt.firstName||$e.firstName,lastName:Lt.lastName||$e.lastName})}catch{}if((jn.current||it)&&!ko($e.email)){let Lt=await Y("PayPal",$e);if(!Lt)return;$e=Lt}ko($e.email)&&(ue.accountPatch=ln({...ue.accountPatch,...$e}),await jn.current?.($e)),await _(G==="setup_token"?{id:L,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Oa}:st?{id:L,isPaypal:!0,gateway:"paypal",paymentMethodType:Oa}:{id:L,isPaypal:!0},ue)}catch(Se){R(Se instanceof Error?Se.message:"PayPal capture failed.")}finally{se()||Ye(!1)}}},q=p.Buttons({style:{layout:"horizontal",height:ta,tagline:!1},onClick:async(Ce,D)=>{if(se()){await D.reject();return}dr();let L=cn.current,ue={};if(L)try{let $e=await L("paypal");if(se()){await D.reject();return}if(!$e.proceed){et.current=null,ft.current.delete(We),await D.reject();return}ue={sessionId:$e.sessionId,accountPatch:$e.accountPatch,nonce:$e.nonce}}catch($e){ie(`onClick:runBeforeButtonClick rejected msg=${($e instanceof Error?$e.message:String($e)).slice(0,120)}`),et.current=null,ft.current.delete(We),await D.reject();return}_t(()=>Gt.current?.("paypal"));let ut={generation:X(),surfaceKey:We,...ue};et.current=ut,ft.current.set(We,ut),await D.resolve(),F.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),F.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),F.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),mn=F.startTiming()},createOrder:G==="order"?we?()=>re(we).then(Qt):()=>ne("Failed to create PayPal order.").then(Qt):void 0,createSubscription:G==="subscription"?we?()=>re(we).then(Qt):()=>ne("Failed to create PayPal subscription.").then(Qt):void 0,createVaultSetupToken:G==="setup_token"?()=>ne("Failed to create PayPal setup token.").then(Qt):void 0,onApprove:d,onCancel:()=>{if(se())return;let Ce=ft.current.get(We)??et.current;Ce&&ft.current.delete(Ce.surfaceKey),et.current=null,At(),F.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ke.current=!0,un({generation:Ce?.generation,remount:!0,focus:!1})},onError:Ce=>{if(se()||Ee.current!==We)return;let D=Ce instanceof Error?Ce.message:"PayPal failed to render.";if(ie(`onError rendered=${an} msg=${D.slice(0,120)}`),an){let L=ft.current.get(We)??et.current;if(L&&!pn(L.generation)||!L&&Ln.current===sr.current)return;if(j(D)){er(L?.generation);return}if(At(),So(Ce)){F.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Te(Ce,L),_t(()=>Nt.current?.(Ut("paypal",D))),L&&ft.current.delete(L.surfaceKey),et.current=null,er(L?.generation);return}let ue=D.toLowerCase();F.error({errorCode:ue.includes("popup")&&ue.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),L&&ft.current.delete(L.surfaceKey),et.current=null,un({generation:L?.generation,remount:!0,showRetry:!0,focus:!0}),Qn(Ce,{code:"paypal_runtime_failed"});return}W(D)}}),ge=q.isEligible();if(ie(`isEligible=${ge}`),F.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ge){T(!1),W("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Rn=q,bn=()=>{if(!gn||hn||se()||an)return;hn=!0,ie(`container:dims ${_e(en)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),typeof MutationObserver<"u"&&(En=new MutationObserver(D=>{if(!se()){for(let L of D)if(L.type==="childList")L.addedNodes.forEach(ue=>{if(!(ue instanceof Element))return;let Se=ue.tagName.toLowerCase(),ut=(ue.getAttribute("title")??"").slice(0,40),$e=Se==="iframe"?` ${Ft(ue)}`:"";ie(`child+ ${Se}${ut?` title="${ut}"`:""}${$e} dims=${_e(ue)}`)});else if(L.type==="attributes"&&L.target instanceof Element){let ue=L.target;if(ue.tagName.toLowerCase()!=="iframe")continue;let Se=L.attributeName;(Se==="src"||Se==="srcdoc")&&ie(`attr~ iframe ${Se}=${Se==="srcdoc"?`[${(ue.getAttribute("srcdoc")??"").length}ch]`:Xt(ue.getAttribute("src"))} dims=${_e(ue)}`)}}}),En.observe(en,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ce=D=>{if(se()||an)return;let L=en.querySelectorAll("iframe"),ue=typeof document<"u"&&"hasStorageAccess"in document;ie(`watchdog:${D} container=${_e(en)} children=${en.childElementCount} iframes=${L.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${ue} paypalNetRequests=${vn.value}`),L.forEach((Se,ut)=>{let $e=(Se.getAttribute("title")??"").slice(0,40);ie(` iframe[${ut}] ${_e(Se)}${$e?` title="${$e}"`:""} ${Ft(Se)}`);let Lt=ur(Se);Lt&&ie(` ${Lt}`)}),Nn.length===0&&ie(" (no PayPal/zoid window errors captured)")};at.push(setTimeout(()=>Ce("3s"),3e3)),at.push(setTimeout(()=>Ce("8s"),8e3)),at.push(setTimeout(()=>Ce("15s"),15e3))},bn(),ie("render:start");let J=F.startTiming();fn=setTimeout(()=>{se()||an||(ie("watchdog:11s retryable render timeout"),W("PayPal Buttons render did not settle within 11000ms.",!0))},Hl),q.render(en).then(()=>{if(ie(`render:resolved inactive=${se()}`),x(),se()){Vn();return}an=!0,T(!0),Ue(!1),rn.current?.("ready"),F.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),F.performance({stage:"checkout_render",durationMs:F.elapsed(J),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Ce=>{let D=Ce instanceof Error?Ce.message:"PayPal failed to render.";ie(`render:rejected msg=${D.slice(0,120)}`),x(),W(D)})}).catch(p=>{let d=p instanceof Error?p.message:"PayPal SDK failed to load.";ie(`loadScript:rejected msg=${d.slice(0,120)}`),W(d)})},0);return()=>{It=!0,clearTimeout(Pe),nr&&clearTimeout(nr),x(),$.current===M&&($.current=null),Vn()}},[ye,Pt,l,C,s,G,st,e,we,ae,F,Y,it,ie]);let In=Xe?za("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:U?"#fef2f2":"#f3f4f6",border:`1px solid ${U?"#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=${ke} failed=${U})`,lt.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return $&&!St?Ne?Rr("div",{children:gn}):null:Oa("div",{children:[gn,E&&Rr(Kr,{identity:E.identity,methodLabel:E.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:T,onCancel:()=>T(null)}),Oa("div",{"aria-hidden":ie||E?!0:void 0,style:ie||E?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Zo},children:[!Pe&&!ie&&Rr("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"}}),Rr("div",{ref:Te,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Zo,display:"flex",opacity:Pe?1:0},"aria-busy":Ce||be},se)]},se),Xe&&Rr("button",{ref:Be,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:an,style:Gl,children:"Try PayPal again"})]})}function Qo(e){return Rr(ds,{...e})}function us(e){return Rr(ds,{...e})}import{jsx as ps,jsxs as Xl}from"react/jsx-runtime";function Yr({children:e,margin:t,icon:n=!0,styleOverride:r}){return Xl("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&&ps("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ps("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 Zl}from"@flopay/shared";import{useEffect as yr,useMemo as Ql,useRef as ms,useState as ys}from"react";import{jsx as ec}from"react/jsx-runtime";function ea({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:a}){let[i,d]=ys(e instanceof Promise?null:e),[s,S]=ys(t instanceof Promise||!t?null:t),f=ms(null),g=ms(null),b=Hr(r);yr(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),yr(()=>{i&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,i]),yr(()=>{if(i)return Dt(i)?.subscribe?.(b)},[b,i]),yr(()=>{if(!(!s||s===i))return Dt(s)?.subscribe?.(b)},[b,i,s]),yr(()=>{if(!i)return;let m=Dt(i);return f.current=m?.beginCheckout()??m?.now()??0,m?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{m?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),yr(()=>{let m=!1;return e instanceof Promise?e.then(w=>{m||d(w)},()=>{m||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{m=!0}},[b,e]),yr(()=>{let m=!1;if(!t){S(null);return}return t instanceof Promise?t.then(w=>{m||S(w)},()=>{m||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):S(t),()=>{m=!0}},[b,t]),yr(()=>{if(!i||g.current===i)return;g.current=i;let m=Dt(i);m?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),m?.performance({stage:"checkout_render",durationMs:m.elapsed(f.current??0),durationMode:"machine"})},[b,i]);let B=Zl(n?.billingApiUrl),F=Ql(()=>({flopay:i,paypalFlopay:s,billingApiUrl:B,emitInstrument:b}),[i,s,B,b]);return ec(In.Provider,{value:F,children:a})}var ta="flopay_recent_completion_";function Gr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ta+e,JSON.stringify(t))}catch{}}function Ua(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ta+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ta+e),!1):!0}catch{return!1}}import{loadFloPay as fs,PaymentAPI as hs}from"@flopay/js";import{classifyPaymentRejection as tc,FloPayError as lt,isAuthorizationOnlySession as nc,isSetupIntentClientSecret as rc,normalizeCheckoutFailureOutcome as gs}from"@flopay/shared";var ko="card";async function oc(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:d}=await e.retrieveSetupIntent(t);return{error:d,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:r??null}}async function ac(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:d,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:d??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function $a(e,t){return Object.assign(e,{checkoutMethod:t})}function nr(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 wo(e,t){try{return await e()}catch(n){throw nr(n,t)}}function bs(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 ic(e){return e.status==="succeeded"||e.status==="declined"}async function vs(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,a=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let g=new AbortController,b=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",b);let B=window.setTimeout(()=>g.abort(),r);try{let F=await fetch(a,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!F.ok)return{status:"unknown"};let m=await F.json().catch(()=>null);return sc(m)}catch{return{status:"unknown"}}finally{window.clearTimeout(B),e.signal?.removeEventListener("abort",b)}},d=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 f=null;try{f=new URL(e.billingApiUrl,window.location.href).origin}catch{f=null}try{let g=await new Promise((b,B)=>{let F=!1,m=0,w=0,be=0,V=!1,C=()=>{window.clearTimeout(m),window.clearInterval(w),window.clearTimeout(be),window.removeEventListener("message",ce),S.removeEventListener("load",ne),e.signal?.removeEventListener("abort",le)},ye=async()=>{if(!(F||V)){V=!0;try{let ve=await i();if(F||!ic(ve))return;F=!0,C(),b(ve)}finally{V=!1}}},ne=()=>{window.clearTimeout(be),be=window.setTimeout(()=>{ye()},250)},le=()=>{F||(F=!0,C(),B(new lt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ce=ve=>{if(ve.source!==S.contentWindow||f&&ve.origin!==f)return;let He=ve.data;!He||typeof He!="object"||He.source!=="flopay-vault-3ds-return"||F||(F=!0,C(),b(null))};m=window.setTimeout(()=>{F||(F=!0,C(),B(new lt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),w=window.setInterval(()=>{ye()},n),S.addEventListener("load",ne),window.addEventListener("message",ce),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return g||await i()}finally{s.parentNode?.removeChild(s),d?.isConnected&&d.focus()}}function sc(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 fr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=ur(a)??a;return $a(new lt(i,"api_error",{code:gs(e?.outcome)??gs(e?.type)??e?.gatewayErrorCode}),r)}function qa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function na(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function lc(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 Ps(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||na(a)))return a;let r=e?.data;if(r&&typeof r=="object"){let a=r,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let s of i)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||na(s)))return s;let d=a.gateways;if(d&&typeof d=="object"){let s=d.stripe;if(s&&typeof s=="object"){let S=s,f=[S.stripeClientSecret,S.clientSecret];for(let g of f)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||na(g)))return g}}}}async function cc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let a=Ps(r,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let s=(await new hs(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(na(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function Wr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:a,returnUrl:i,telemetry:d}){let s=e.replace(/\/+$/,""),S=t??n.id,f=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",B=n.customer?.firstName??n.accountData?.firstName??"",F=n.customer?.lastName??n.accountData?.lastName??"",m=n.customer?.country??n.accountData?.country??void 0,w=n.customer?.zip??n.accountData?.zip??void 0,be=new hs(s,d===!1?{telemetry:!1}:void 0),V=await lc(()=>be.processPayment(g,{sessionId:S,nonce:f,tokenizedData:a,accountData:{userId:g,email:b,firstName:B,lastName:F,country:m,zip:w},returnUrl:i??qa(n)}));if(V.ok){let ne=typeof V.json=="function"?await V.json().catch(()=>null):null;return nc(n)||ne?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof ne?.paymentId=="string"?ne.paymentId:n.paymentId,sessionId:typeof ne?.sessionId=="string"?ne.sessionId:S,authorizationExpiresAt:typeof ne?.authorizationExpiresAt=="string"?ne.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:bo(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:a?.threeDSecureActionResultTokenId,paymentMethodId:bo(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}}let C;try{C=await V.json()}catch{throw new lt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status})}if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let ne=Ps(C);if(!ne)throw new lt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status});return{type:C.type,threeDSecureToken:ne,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let ne=await cc({billingApiUrl:s,sessionId:S,nonce:f,responseJson:C});if(ne)return ne;throw $a(new lt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ye=new lt(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:V.status});throw Object.assign(ye,{telemetryOutcome:tc(V.status,C)})}async function ra(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:a,sessionId:i,session:d,returnUrl:s,telemetry:S}){let f=t?.getRawProvider();if(!f)throw nr(new lt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw $a(new lt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=rc(e.threeDSecureToken),b=null,B=e.paymentMethodId,F=await wo(()=>oc(f,e.threeDSecureToken,g),"card");if(F){if(F.error)throw nr(new lt(F.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:F.error.code}),"card");let w=F.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 m=B?await wo(()=>ac(f,e.threeDSecureToken,{payment_method:B,return_url:s??qa(d)??window.location.href},g),"card"):null;if(m){if(m.error)throw nr(new lt(m.error.message??"3DS authentication failed.","api_error",{code:m.error.code}),"card");b=m.intent}else{let w=await wo(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(w.error)throw nr(new lt(w.error.message??"3DS authentication failed.","api_error",{code:w.error.code}),"card");b=(g?w.setupIntent:w.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let w=await Wr({billingApiUrl:a,sessionId:i,session:d,telemetry:S,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:s});return w.type==="success"?{...w.result,paymentIntentId:w.result.paymentIntentId??b.id,paymentMethodId:w.result.paymentMethodId??B}:ra(w,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:a,sessionId:i,session:d,returnUrl:s,telemetry:S})}throw nr(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 nr(new lt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:B}=await wo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(B)throw nr(new lt(B.message??"PayPal authorization failed.","api_error",{code:B.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await wo(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??qa(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw nr(new lt(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new lt("Unsupported payment redirect state.","api_error")}function Er(e){if(e instanceof lt){let r=ur(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=ur(t)??t;return new lt(n,"api_error")}function oa(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 aa({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[d,s]=await Promise.all([fs(e,{billingApiUrl:n,locale:r,telemetry:a}),i?fs(t,{billingApiUrl:n,locale:r,telemetry:a}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:d,paypalFlopay:t?i?s:d:null}}import{PaymentAPI as Jr,toStripeAppearance as dc}from"@flopay/js";import{COUNTRY_OPTIONS as uc,classifyPaymentRejection as pc,FloPayError as Ln,filterStripeMethodsByCountry as mc,getPostalCodeExample as yc,getPostalCodeLabel as Ya,getStateFromPostalCode as ws,getStateLabel as ja,getStateOptions as fc,getStripeMethodDisplayName as xr,hasVendoredStripeMethodLogo as gc,isAuthorizationOnlySession as Ka,isAVSFieldVisible as qe,isPostalCodeSupported as hc,isSetupIntentClientSecret as bc,isValidEmail as Kt,isValidPostalCode as vc,needsStripeMethodExplicitConfirm as ks,normalizeCheckoutFailureOutcome as Pc,partitionStripeMethods as Cc,resolveAVSConfig as Sc,resolveButtonsLayoutTheme as wc,resolveStripeMethodBrandVariant as kc,resolveTheme as Ic,stripeExpressMethodToOptionKey as Is}from"@flopay/shared";import{ExpressCheckoutElement as Fs,PaymentElement as Rc,Elements as _r,useElements as Ja,useStripe as Xa}from"@stripe/react-stripe-js";import Ec,{useCallback as fe,useContext as Xr,useEffect as yt,useMemo as ct,useRef as he,useState as pe}from"react";function Cs(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 Ss={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 Tr,jsx as u,jsxs as Re}from"react/jsx-runtime";var Kn="flopay_stripe_resume",Rs="flopay_wallet_resume";function Ds(e){return e instanceof Ln&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function sa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Jr(e).createSessionIntent(...n)}catch(a){throw Ds(a)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),a}}var Io="flopay_paypal_resume",_c=250,Es="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Za(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function la({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Jr(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Tc(e){return e instanceof Ln&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Va(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function xc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,a=Sr(r?.name),i=Sr(n);return on({email:(Kt(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:i.firstName??a.firstName,lastName:i.lastName??a.lastName})}async function Ls({event:e,prepared:t,email:n,billingName:r,methodLabel:a,collect:i}){let d=xc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return Kt(d.email)?d:i(a,d)}var Bc=`
|
|
3
|
+
${lt.join(`
|
|
4
|
+
`)}`]}):null;return U&&!wt?Xe?_r("div",{children:In}):null:za("div",{children:[In,k&&_r(Hr,{identity:k.identity,methodLabel:k.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:E,onCancel:()=>E(null)}),za("div",{"aria-hidden":oe||k?!0:void 0,style:oe||k?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ta},children:[!ke&&!oe&&_r("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"}}),_r("div",{ref:Le,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ta,display:"flex",opacity:ke?1:0},"aria-busy":Ie||ve},ae)]},ae),nt&&_r("button",{ref:ze,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Zt,style:Wl,children:"Try PayPal again"})]})}function na(e){return _r(us,{...e})}function ps(e){return _r(us,{...e})}import{jsx as ms,jsxs as Xl}from"react/jsx-runtime";function Gr({children:e,margin:t,icon:n=!0,styleOverride:r}){return Xl("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&&ms("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ms("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 Zl}from"@flopay/shared";import{useEffect as gr,useMemo as Ql,useRef as ys,useState as fs}from"react";import{jsx as ec}from"react/jsx-runtime";function ra({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=fs(e instanceof Promise?null:e),[s,C]=fs(t instanceof Promise||!t?null:t),y=ys(null),f=ys(null),h=Wr(r);gr(()=>{h({class:"lifecycle",name:"checkout.mount"})},[h]),gr(()=>{a&&h({class:"lifecycle",name:"sdk.initialize.ready"})},[h,a]),gr(()=>{if(a)return qt(a)?.subscribe?.(h)},[h,a]),gr(()=>{if(!(!s||s===a))return qt(s)?.subscribe?.(h)},[h,a,s]),gr(()=>{if(!a)return;let u=qt(a);return y.current=u?.beginCheckout()??u?.now()??0,u?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{u?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),gr(()=>{let u=!1;return e instanceof Promise?e.then(S=>{u||l(S)},()=>{u||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{u=!0}},[h,e]),gr(()=>{let u=!1;if(!t){C(null);return}return t instanceof Promise?t.then(S=>{u||C(S)},()=>{u||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):C(t),()=>{u=!0}},[h,t]),gr(()=>{if(!a||f.current===a)return;f.current=a;let u=qt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),h({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(y.current??0),durationMode:"machine"})},[h,a]);let B=Zl(n?.billingApiUrl),A=Ql(()=>({flopay:a,paypalFlopay:s,billingApiUrl:B,emitInstrument:h}),[a,s,B,h]);return ec(An.Provider,{value:A,children:o})}var oa="flopay_recent_completion_";function Jr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(oa+e,JSON.stringify(t))}catch{}}function qa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(oa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(oa+e),!1):!0}catch{return!1}}import{loadFloPay as gs,PaymentAPI as bs}from"@flopay/js";import{classifyPaymentRejection as tc,FloPayError as pt,isAuthorizationOnlySession as nc,isSetupIntentClientSecret as rc,normalizeCheckoutFailureOutcome as hs}from"@flopay/shared";var _o="card";async function oc(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function ac(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function ja(e,t){return Object.assign(e,{checkoutMethod:t})}function or(e,t){let n=e instanceof pt?e:new pt(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 Eo(e,t){try{return await e()}catch(n){throw or(n,t)}}function vs(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 ic(e){return e.status==="succeeded"||e.status==="declined"}async function Ps(e){if(typeof document>"u"||typeof window>"u")throw new pt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new pt("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 f=new AbortController,h=()=>f.abort();e.signal?.aborted?f.abort():e.signal?.addEventListener("abort",h);let B=window.setTimeout(()=>f.abort(),r);try{let A=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:f.signal});if(!A.ok)return{status:"unknown"};let u=await A.json().catch(()=>null);return sc(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(B),e.signal?.removeEventListener("abort",h)}},l=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 C=document.createElement("iframe");C.setAttribute("title","Card authentication"),C.setAttribute("allow","payment"),C.tabIndex=0,C.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(";"),C.src=e.nextActionRedirectUrl,s.appendChild(C),document.body.appendChild(s),C.focus();let y=null;try{y=new URL(e.billingApiUrl,window.location.href).origin}catch{y=null}try{let f=await new Promise((h,B)=>{let A=!1,u=0,S=0,ve=0,K=!1,v=()=>{window.clearTimeout(u),window.clearInterval(S),window.clearTimeout(ve),window.removeEventListener("message",de),C.removeEventListener("load",Q),e.signal?.removeEventListener("abort",ce)},ye=async()=>{if(!(A||K)){K=!0;try{let we=await a();if(A||!ic(we))return;A=!0,v(),h(we)}finally{K=!1}}},Q=()=>{window.clearTimeout(ve),ve=window.setTimeout(()=>{ye()},250)},ce=()=>{A||(A=!0,v(),B(new pt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},de=we=>{if(we.source!==C.contentWindow||y&&we.origin!==y)return;let Qe=we.data;!Qe||typeof Qe!="object"||Qe.source!=="flopay-vault-3ds-return"||A||(A=!0,v(),h(null))};u=window.setTimeout(()=>{A||(A=!0,v(),B(new pt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),S=window.setInterval(()=>{ye()},n),C.addEventListener("load",Q),window.addEventListener("message",de),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return f||await a()}finally{s.parentNode?.removeChild(s),l?.isConnected&&l.focus()}}function sc(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 hr(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=mr(o)??o;return ja(new pt(a,"api_error",{code:hs(e?.outcome)??hs(e?.type)??e?.gatewayErrorCode}),r)}function $a(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function aa(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function lc(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 Cs(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||aa(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||aa(s)))return s;let l=o.gateways;if(l&&typeof l=="object"){let s=l.stripe;if(s&&typeof s=="object"){let C=s,y=[C.stripeClientSecret,C.clientSecret];for(let f of y)if(typeof f=="string"&&f.length>0&&(!t?.requirePaymentIntentClientSecret||aa(f)))return f}}}}async function cc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Cs(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 bs(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(aa(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function Xr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let s=e.replace(/\/+$/,""),C=t??n.id,y=r??n.clientSecret,f=n.customer?.id??n.accountData?.userId??"",h=n.customer?.email??n.accountData?.email??"",B=n.customer?.firstName??n.accountData?.firstName??"",A=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,S=n.customer?.zip??n.accountData?.zip??void 0,ve=new bs(s,l===!1?{telemetry:!1}:void 0),K=await lc(()=>ve.processPayment(f,{sessionId:C,nonce:y,tokenizedData:o,accountData:{userId:f,email:h,firstName:B,lastName:A,country:u,zip:S},returnUrl:a??$a(n)}));if(K.ok){let Q=typeof K.json=="function"?await K.json().catch(()=>null):null;return nc(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:C,authorizationExpiresAt:typeof Q?.authorizationExpiresAt=="string"?Q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Po(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Po(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let v;try{v=await K.json()}catch{throw new pt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:K.status})}if(v?.type==="paypal_redirect_required"||v?.type==="3ds_required"){let Q=Cs(v);if(!Q)throw new pt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:K.status});return{type:v.type,threeDSecureToken:Q,paymentMethodId:v.paymentMethodId}}if(v?.gatewayErrorCode==="authentication_required"){let Q=await cc({billingApiUrl:s,sessionId:C,nonce:y,responseJson:v});if(Q)return Q;throw ja(new pt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ye=new pt(v?.message??"Payment failed. Please try again.","api_error",{code:v?.code??v?.gatewayErrorCode,declineCode:v?.declineCode??v?.gatewayDeclineReason,statusCode:K.status});throw Object.assign(ye,{telemetryOutcome:tc(K.status,v)})}async function ia(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:C}){let y=t?.getRawProvider();if(!y)throw or(new pt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ja(new pt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let f=rc(e.threeDSecureToken),h=null,B=e.paymentMethodId,A=await Eo(()=>oc(y,e.threeDSecureToken,f),"card");if(A){if(A.error)throw or(new pt(A.error.message??`Failed to retrieve 3DS ${f?"setup":"payment"} status.`,"api_error",{code:A.error.code}),"card");let S=A.intent;!B&&S?.payment_method&&(typeof S.payment_method=="string"?B=S.payment_method:"id"in S.payment_method&&(B=S.payment_method.id??void 0))}let u=B?await Eo(()=>ac(y,e.threeDSecureToken,{payment_method:B,return_url:s??$a(l)??window.location.href},f),"card"):null;if(u){if(u.error)throw or(new pt(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");h=u.intent}else{let S=await Eo(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(S.error)throw or(new pt(S.error.message??"3DS authentication failed.","api_error",{code:S.error.code}),"card");h=(f?S.setupIntent:S.paymentIntent)??null}if(h&&(h.status==="requires_capture"||h.status==="succeeded"||h.status==="processing")){let S=await Xr({billingApiUrl:o,sessionId:a,session:l,telemetry:C,tokenizedData:{id:h.id,type:"card",threeDSecureActionResultTokenId:h.id},returnUrl:s});return S.type==="success"?{...S.result,paymentIntentId:S.result.paymentIntentId??h.id,paymentMethodId:S.result.paymentMethodId??B}:ia(S,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:C})}throw or(new pt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let f=(n??t)?.getRawProvider();if(!f)throw or(new pt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:B}=await Eo(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(B)throw or(new pt(B.message??"PayPal authorization failed.","api_error",{code:B.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:h}=await Eo(()=>f.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??$a(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(h)throw or(new pt(h.message??"PayPal authorization failed.","api_error",{code:h.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new pt("Unsupported payment redirect state.","api_error")}function To(e){if(e instanceof pt){let r=mr(e.message);return r&&r!==e.message?Object.assign(new pt(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=mr(t)??t;return new pt(n,"api_error")}function sa(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new pt("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 la({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[l,s]=await Promise.all([gs(e,{billingApiUrl:n,locale:r,telemetry:o}),a?gs(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);return{flopay:l,paypalFlopay:t?a?s:l:null}}import{PaymentAPI as Zr,toStripeAppearance as dc}from"@flopay/js";import{COUNTRY_OPTIONS as uc,classifyPaymentRejection as pc,FloPayError as $n,filterStripeMethodsByCountry as mc,getPostalCodeExample as yc,getPostalCodeLabel as Wa,getStateFromPostalCode as ks,getStateLabel as Ka,getStateOptions as fc,getStripeMethodDisplayName as Mr,hasVendoredStripeMethodLogo as gc,isAuthorizationOnlySession as Va,isAVSFieldVisible as He,isPostalCodeSupported as hc,isSetupIntentClientSecret as bc,isValidEmail as Wt,isValidPostalCode as vc,needsStripeMethodExplicitConfirm as Is,normalizeCheckoutFailureOutcome as Pc,partitionStripeMethods as Cc,resolveAVSConfig as Sc,resolveButtonsLayoutTheme as wc,resolveStripeMethodBrandVariant as kc,resolveTheme as Ic,stripeExpressMethodToOptionKey as Rs}from"@flopay/shared";import{ExpressCheckoutElement as Ds,PaymentElement as Rc,Elements as xr,useElements as Xa,useStripe as Za}from"@stripe/react-stripe-js";import Ec,{useCallback as fe,useContext as Qr,useEffect as vt,useMemo as mt,useRef as be,useState as me}from"react";function Ss(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 ws={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 Br,jsx as c,jsxs as Me}from"react/jsx-runtime";var Gn="flopay_stripe_resume",Es="flopay_wallet_resume";function Ls(e){return e instanceof $n&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function da(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 Ls(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var xo="flopay_paypal_resume",_c=250,_s="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Qa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ua({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Zr(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Tc(e){return e instanceof $n&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ha(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function xc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=kr(r?.name),a=kr(n);return ln({email:(Wt(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:a.firstName??o.firstName,lastName:a.lastName??o.lastName})}async function Ns({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=xc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return Wt(l.email)?l:a(o,l)}var Bc=`
|
|
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 @@ ${h.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
|
-
`,ia=44;function Qa(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 Ac={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Ns={width:"100%",minHeight:ia,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 Mc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function _s(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ga(e){return e==="paypal"?"PayPal":xr(e)}function Fc(e,t){let n=`We couldn't open ${Ga(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Os(e){let t=he(0),n=he(null),r=he(null),a=fe((m=r.current)=>{let w=m;w?.timer&&(clearTimeout(w.timer),w.timer=null)},[]),i=fe((m,w)=>{typeof document<"u"&&document.visibilityState!=="visible"||(a(m),m.timer=setTimeout(()=>{m.timer=null,r.current?.generation===m.generation&&(r.current=null,n.current=m.generation,e(m.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},w))},[a,e]),d=fe(m=>{m.yieldedControl&&i(m,600)},[i]),s=fe(m=>{a();let w=t.current+1;t.current=w,n.current=null;let be={generation:w,method:m,timer:null,yieldedControl:!1};return r.current=be,w},[a]),S=fe(m=>{let w=r.current;return typeof m=="number"&&w?.generation!==m?!1:(a(w),r.current=null,(typeof m!="number"||n.current===m)&&(n.current=null),!0)},[a]),f=fe(m=>{let w=r.current,be=m??w?.generation??t.current;(!m||w?.generation===m)&&(a(w),r.current=null),n.current=be},[a]),g=fe(m=>n.current===(m??t.current),[]),b=fe(m=>r.current?.generation===m&&n.current!==m,[]),B=fe(()=>{let m=r.current;m&&d(m)},[d]),F=fe(()=>{let m=r.current;m&&(m.yieldedControl=!0,a(m))},[a]);return yt(()=>{let m=()=>{document.visibilityState==="visible"?B():F()},w=()=>{F()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",w),window.addEventListener("focus",B),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",w),window.removeEventListener("focus",B),a()}},[a,F,B]),{startAttempt:s,finishAttempt:S,invalidateAttempt:f,isAttemptInvalidated:g,isAttemptCurrent:b}}function Dc(e){let t=yc(e);return`Enter a valid ${Ya(e)}${t?` (e.g. ${t})`:""}`}function Lc(e,t,n){let r=hc(e),a=t.trim(),i=n&&r,d=i&&!a,s=i&&!!a&&!vc(e,a);return{visible:n,supported:r,required:i,empty:d,malformed:s}}function Nc(e,t){let n=e.trim(),r=t&&!n,a=t&&!!n&&!Kt(n);return{required:t,empty:r,malformed:a,value:n}}function Ts(e,t){return t instanceof Ln?t:new Ln(t instanceof Error?t.message:`${Mc(e)} before-click hook failed.`,"validation_error")}function Ha(){return u("style",{children:Bc})}function Oc(e){return typeof e=="number"?`${e}px`:e}function zs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Us({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:Re("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 xs(e){return e!=="unavailable"&&e!=="load_error"}function ei(e){return u(Uc,{...e})}function Bs({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:a,onErrorChange:i,isProcessing:d=!1,onButtonClick:s,onDecline:S,onTechnicalFailure:f,runBeforeButtonClick:g,billingName:b,onBuyerIdentityReady:B,onLoadStateChange:F,placeholderBorderRadius:m}){let w=mr(),{emitInstrument:be}=Xr(In),V=Xa(),C=Ja(),[ye,ne]=pe("loading");yt(()=>{F?.(ye)},[ye,F]);let[le,ce]=pe(!1),ve=!Kt(n?.trim())||!b?.trim(),{request:He,collect:ge,finish:Rt}=jr(),Ne=he(!1),Ee=he(null),_e=he(null),[re,oe]=pe(0),[D,Te]=pe(!1),xe=he(!1),Be=he(new Map),{startAttempt:Oe,finishAttempt:Pe,invalidateAttempt:x,isAttemptInvalidated:ie,isAttemptCurrent:Me}=Os((G,$,O)=>{f?.(G,$,{...O,popupBlocked:O?.popupBlocked??pr($)}),Te(!0),oe(Ce=>Ce+1)});yt(()=>{D&&_e.current?.focus()},[D,re]);let se=fe(()=>{oe(G=>G+1)},[]),H=fe((G,$,O)=>{x(O),f?.("paypal",G,{code:$,popupBlocked:pr(G)}),Te(!0),se()},[x,f,se]),ke=fe(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);yt(()=>{xe.current&&(xe.current=!1,ke())},[ke,re]);let Xe=fe(()=>{Te(!1),i?.(null),ke()},[ke,i]);yt(()=>{if(!V||Ne.current)return;let G=new URLSearchParams(window.location.search),$=G.get("payment_intent"),O=G.get("payment_intent_client_secret"),Ce=G.get("redirect_status");if(!$||!O)return;Ne.current=!0;let $e;try{let W=localStorage.getItem(Io);if(W){let T=JSON.parse(W);T.clientSecret===O&&($e={...T.accountPatch?{accountPatch:T.accountPatch}:{},...T.sessionId?{sessionId:T.sessionId}:{},...T.nonce?{nonce:T.nonce}:{}})}}catch{}try{localStorage.removeItem(Io)}catch{}let E=new URL(window.location.href);E.searchParams.delete("payment_intent"),E.searchParams.delete("payment_intent_client_secret"),E.searchParams.delete("redirect_status"),window.history.replaceState({},"",E.toString()),(async()=>{try{if(ce(!0),Ce==="failed"){let P="PayPal payment was declined. Please try again.";i?.(P),S?.(Ft("paypal",P));return}let{paymentIntent:W,error:T}=await V.retrievePaymentIntent(O);if(T){i?.(T.message??"Failed to retrieve PayPal payment status.");return}if(W&&(W.status==="requires_capture"||W.status==="succeeded")){let P=typeof W.payment_method=="string"?W.payment_method:W.payment_method?.id;a({id:P??W.id,type:"card",threeDSecureActionResultTokenId:W.id,isPaypal:!0},$e)}else{let P="PayPal payment was not completed. Please try again.";i?.(P),S?.(Ft("paypal",P))}}catch(W){i?.(W instanceof Error?W.message:"Failed to complete PayPal payment.")}finally{ce(!1)}})()},[V,a,i,S]);let nt=fe(async G=>{if(d||le){G.reject();return}let $=g?await g("paypal"):{proceed:!0};if(!$.proceed){Be.current.delete(re),G.reject();return}let O=Oe("paypal");Be.current.set(re,{generation:O,accountPatch:$.accountPatch,sessionId:$.sessionId,nonce:$.nonce}),Te(!1),s?.("paypal"),G.resolve()},[Be,d,s,g,Oe,le,re]),Ae=fe(async G=>{if(!V||!C)return;let $=Be.current.get(re);if($&&!Me($.generation)){Be.current.delete(re);return}if(!$&&ie()||$&&!Pe($.generation))return;$||Pe();let O=$??null;if(Be.current.delete(re),!O&&g){let P=await g("paypal");if(!P.proceed){G.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}O={accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}}let Ce=O?.sessionId??e,$e=O?.nonce??t,E=await Ls({event:G,prepared:O,email:n,billingName:b,methodLabel:"PayPal",collect:ge});if(!E){G.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let W=E.email,T=on({...O?.accountPatch,...E});try{if(ce(!0),i?.(null),!Ce||!Kt(W))throw new Error("Missing sessionId or email for PayPal payment");await B?.(E);let P=V.createPaymentMethod,{error:Ze,paymentMethod:ft}=await P({type:"paypal"});if(Ze){H(Ze,"stripe_paypal_create_payment_method_failed",$?.generation),G.paymentFailed({reason:"fail"});return}let Z=await sa(r,be,Ce,$e??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ft?.id??null,intentKind:"payment"});if(Z.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Qe=Z.clientSecret,Ve={return_url:window.location.href};if(ft?.id&&(Ve.payment_method=ft.id),typeof window<"u")try{localStorage.setItem(Io,JSON.stringify({clientSecret:Qe,sessionId:Ce,nonce:$e,accountPatch:T}))}catch{}let{error:gt,paymentIntent:St}=await V.confirmPayment({clientSecret:Qe,confirmParams:Ve,redirect:"if_required"});if(gt){if(typeof window<"u")try{localStorage.removeItem(Io)}catch{}if(Po(gt)){let J=gt.message??"Your payment was declined.";i?.(J),S?.(Ft("paypal",J,{code:tr(gt),declineCode:Vr(gt)})),await la({billingApiUrl:r,sessionId:Ce,nonce:$e,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:tr(gt)??"provider_declined"}})}else H(gt,"stripe_paypal_confirm_failed",$?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Io)}catch{}let h=typeof St?.payment_method=="string"?St.payment_method:St?.payment_method?.id;a({id:h??St?.id,type:"card",threeDSecureActionResultTokenId:St?.id,isPaypal:!0},{accountPatch:T,sessionId:Ce,nonce:$e});return}catch(P){H(P,"stripe_paypal_failed",$?.generation)}finally{ce(!1)}},[V,C,e,t,n,b,ge,B,r,be,a,i,S,g,H,Pe,Me,ie,re]);return Re(Tr,{children:[u(Us,{state:ye,placeholderTestId:"flopay-paypal-placeholder",borderRadius:m,children:Re("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[D&&u("button",{ref:_e,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Xe,style:Ns,children:"Try PayPal again"}),He&&u(Kr,{identity:He.identity,methodLabel:He.methodLabel,onComplete:Rt,onCancel:()=>Rt(null)},He.id),u("div",{style:{display:He?"none":void 0},children:u(Fs,{onReady:G=>ne(zs(G,["paypal"])),onLoadError:()=>{ne("load_error"),Za(Dt(w),"paypal","paypal")},onClick:nt,onConfirm:Ae,onCancel:()=>{let G=Be.current.get(re);Be.current.delete(re),Dt(w)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),x(G?.generation),Te(!1),xe.current=!0,se()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ve,emailRequired:ve,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},re)})]})}),le&&u(jn,{status:"processing"})]})}function As({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:a,expressMethods:i,onTokenizedBody:d,onErrorChange:s,onButtonClick:S,onDecline:f,onTechnicalFailure:g,runBeforeButtonClick:b,billingName:B,onBuyerIdentityReady:F,onLoadStateChange:m,placeholderBorderRadius:w}){let be=mr(),{emitInstrument:V}=Xr(In),C=Xa(),ye=Ja(),[ne,le]=pe("loading");yt(()=>{m?.(ne)},[ne,m]);let[ce,ve]=pe(!1),He=!Kt(n?.trim())||!B?.trim(),{request:ge,collect:Rt,finish:Ne}=jr(),Ee=he(null),_e=he(null),[re,oe]=pe(0),[D,Te]=pe(!1),[xe,Be]=pe("google_pay"),Oe=he(!1),Pe=he("google_pay"),x=he("google_pay"),ie=he(new Map),{startAttempt:Me,finishAttempt:se,invalidateAttempt:H,isAttemptInvalidated:ke,isAttemptCurrent:Xe}=Os((E,W,T)=>{g?.(E,W,{...T,popupBlocked:T?.popupBlocked??pr(W)}),Be(E),Te(!0),oe(P=>P+1)});yt(()=>{D&&_e.current?.focus()},[D,re]);let nt=fe(()=>{oe(E=>E+1)},[]),Ae=fe((E,W,T,P)=>{H(P),g?.(E,W,{code:T,popupBlocked:pr(W)}),Be(E),Te(!0),nt()},[H,g,nt]),G=fe(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);yt(()=>{Oe.current&&(Oe.current=!1,G())},[G,re]);let $=fe(()=>{Te(!1),s?.(null),G()},[G,s]),O=fe(async E=>{if(!C||!ye)return;let W=ie.current.get(re);if(W&&!Xe(W.generation)){ie.current.delete(re);return}if(!W&&ke()||W&&!se(W.generation))return;W||se();let T=E.expressPaymentType??W?.method??Pe.current,P=W??null;ie.current.delete(re);let Ze=_s(T);if(!P&&b){let h=await b(Ze);if(!h.proceed){E.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}P={accountPatch:h.accountPatch,sessionId:h.sessionId,nonce:h.nonce}}let ft=Ze,Z=P?.sessionId??e,Qe=P?.nonce??t,Ve=await Ls({event:E,prepared:P,email:n,billingName:B,methodLabel:Ga(T),collect:Rt});if(!Ve){E.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let gt=Ve.email,St=on({...P?.accountPatch,...Ve});try{if(ve(!0),s?.(null),!Kt(gt))throw new Error("Missing sessionId or email for wallet payment");await F?.(Ve);let{error:h}=await ye.submit();if(h){Ae(T,h,"stripe_wallet_submit_failed",W?.generation);return}let{error:J,paymentMethod:Q}=await C.createPaymentMethod({elements:ye});if(J||!Q){Ae(T,J??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",W?.generation);return}if(!Z)throw new Error("Missing sessionId or email for wallet payment");let rt=await sa(r,V,Z,Qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:T??Ze,paymentMethodId:Q.id,intentKind:a});if(rt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let xt=rt.clientSecret,{error:Pt,intentId:Ye}=bc(xt)?await C.confirmCardSetup(xt,{payment_method:Q.id}).then(je=>({error:je.error,intentId:je.setupIntent?.id})):await C.confirmCardPayment(xt,{payment_method:Q.id}).then(je=>({error:je.error,intentId:je.paymentIntent?.id}));if(Pt){if(Po(Pt)){let je=Pt.message??"Your payment was declined.";s?.(je),f?.(Ft(ft,je,{code:tr(Pt),declineCode:Vr(Pt)})),await la({billingApiUrl:r,sessionId:Z,nonce:Qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:T??Ze,providerDeclineReason:tr(Pt)??"provider_declined"}})}else Ae(T,Pt,"stripe_wallet_confirm_failed",W?.generation);return}d({id:Q.id,type:"card",threeDSecureActionResultTokenId:Ye},{accountPatch:St,sessionId:Z,nonce:Qe})}catch(h){Ae(T,h,"stripe_wallet_failed",W?.generation)}finally{ve(!1)}},[C,ye,e,t,n,B,Rt,F,r,V,a,d,s,f,b,Ae,se,Xe,ke,re]),Ce=ct(()=>{let E=["applePay","googlePay","paypal","link","amazonPay","klarna"],W=new Set(["applePay","googlePay"]),T=new Set(i.map(Is)),P={};for(let Ze of E)T.has(Ze)?P[Ze]=W.has(Ze)?"always":"auto":P[Ze]="never";return P},[i]),$e=ct(()=>i.map(Is),[i]);return Re(Tr,{children:[u(Us,{state:ne,placeholderTestId:"flopay-wallet-placeholder",borderRadius:w,children:Re("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[D&&Re("button",{ref:_e,type:"button","data-testid":"flopay-wallet-retry-button",onClick:$,style:Ns,children:["Try ",Ga(xe)," again"]}),ge&&u(Kr,{identity:ge.identity,methodLabel:ge.methodLabel,onComplete:Ne,onCancel:()=>Ne(null)},ge.id),u("div",{style:{display:ge?"none":void 0},children:u(Fs,{onReady:E=>{le(zs(E,$e))},onLoadError:E=>{le("load_error"),Za(Dt(be),"stripe","wallet")},onClick:async E=>{Pe.current=E.expressPaymentType,x.current=_s(E.expressPaymentType);let W=b?await b(x.current):{proceed:!0};if(!W.proceed){ie.current.delete(re),E.reject();return}let T=Me(E.expressPaymentType);ie.current.set(re,{generation:T,method:E.expressPaymentType,accountPatch:W.accountPatch,sessionId:W.sessionId,nonce:W.nonce}),Te(!1),S?.(x.current),E.resolve()},onConfirm:O,onCancel:()=>{let E=ie.current.get(re);ie.current.delete(re),Dt(be)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),H(E?.generation),Te(!1),Oe.current=!0,nt()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ce,emailRequired:He,billingAddressRequired:He,layout:{maxColumns:1,overflow:"never"}}},re)})]})}),ce&&u(jn,{status:"processing"})]})}function zc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:d,backgroundColor:s,borderColor:S,textColor:f,borderRadius:g,fontFamily:b}){let B=kc(e,t),F=Ss[e],[m,w]=pe(!1),be=B?.backgroundColor??s??"#ffffff",V=B?.borderColor??S??"#d1d5db",C=B?.textColor??f??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&d()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ia,padding:"0 1rem",backgroundColor:be,color:C,border:`1px solid ${V}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?u("span",{style:{margin:"0 auto"},children:`Connecting to ${xr(e)}\u2026`}):Re(Tr,{children:[Re("span",{style:{display:"inline-flex",alignItems:"center",gap:gc(e)?8:0},children:[F&&!m?u("img",{src:F,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?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:B.logoSvg}}):null,u("span",{children:xr(e)})]}),i&&u("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:u("path",{d:"M9 18l6-6-6-6"})})]})})}function Wa({method:e,sessionId:t,nonce:n,email:r,billingName:a,onBuyerIdentityReady:i,billingApiUrl:d,onTokenizedBody:s,onErrorChange:S,onDecline:f,onCancel:g,runBeforeButtonClick:b,onButtonClick:B,isProcessing:F,submitButtonColor:m,submitButtonBorderRadius:w,submitButtonStyle:be,errorText:V}){let C=mr(),{emitInstrument:ye}=Xr(In),ne=Xa(),le=Ja(),[ce,ve]=pe(!1),He=he(!1),[ge,Rt]=pe(!1),[Ne,Ee]=pe("loading"),[_e,re]=pe(""),oe=!Kt(r?.trim()),D=!oe||Kt(_e.trim()),Te=fe(async()=>{if(!ne||!le||F||He.current||!ge)return;He.current=!0,ve(!0);let xe=b?await b("card"):{proceed:!0};if(!xe.proceed){He.current=!1,ve(!1);return}B?.("card");let Be=xe.sessionId??t,Oe=xe.nonce??n,Pe=Sr(a?.trim()),x=on({email:xe.accountPatch?.email?.trim()||r?.trim()||_e.trim(),firstName:xe.accountPatch?.firstName?.trim()||Pe.firstName,lastName:xe.accountPatch?.lastName?.trim()||Pe.lastName}),ie=x.email,Me=on({...xe.accountPatch,...x});try{if(S?.(null),!Kt(ie))throw new Error("A valid email address is required for payment.");await i?.(x);let se=await le.submit();if(se.error){S?.(se.error.message??"Payment failed.");return}let H=[x.firstName,x.lastName].filter(Boolean).join(" "),ke=await ne.createPaymentMethod({elements:le,params:{billing_details:{email:ie,...H?{name:H}:{}}}});if(ke.error||!ke.paymentMethod){S?.(ke.error?.message??"Failed to create payment method.");return}let Xe=ke.paymentMethod;if(!Be||!ie)throw new Error("Missing sessionId or email for payment.");let nt=Xe.type||e,Ae=await sa(d,ye,Be,Oe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:nt,paymentMethodId:null,intentKind:"payment"});if(Ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let G=Ae.clientSecret;if(typeof window<"u")try{localStorage.setItem(Kn,JSON.stringify({clientSecret:G,sessionId:Be,nonce:Oe,accountPatch:Me,paymentMethodId:Xe.id,paymentMethodType:Xe.type??e,gateway:"stripe"}))}catch{}let{error:$,paymentIntent:O}=await ne.confirmPayment({clientSecret:G,confirmParams:{return_url:window.location.href,payment_method:Xe.id},redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let E=$.message??"Payment failed.";S?.(E),f?.(Ft("card",E,{code:$.code})),await la({billingApiUrl:d,sessionId:Be,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:$.code??"provider_declined"}});return}let Ce=O?.status;if(!Ho(Ce)){if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let E=Ce==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(E),f?.(Ft("card",E,{code:Ce??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let $e=typeof O?.payment_method=="string"?O.payment_method:O?.payment_method?.id;s({id:$e??Xe.id,type:"card",threeDSecureActionResultTokenId:O?.id,gateway:"stripe",paymentMethodType:Xe.type??e},{accountPatch:Me,sessionId:Be,nonce:Oe})}catch(se){S?.(se instanceof Error?se.message:"Payment failed. Please try again.")}finally{He.current=!1,ve(!1)}},[ne,le,F,ge,b,B,t,n,r,a,_e,i,d,ye,e,s,S,f]);return Re("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[oe&&u("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:oe&&Re("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",u("input",{type:"email",autoComplete:"email",required:!0,value:_e,onChange:xe=>re(xe.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),u(Rc,{onReady:()=>Ee("ready"),onLoadError:()=>{Ee("load_error"),Za(Dt(C),"stripe","apm")},onChange:xe=>{Rt(!!xe.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...a?.trim()?{name:a.trim()}:{},...Kt(r?.trim())?{email:r?.trim()}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Te()},disabled:!ge||!D||ce||F||Ne!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:m,color:"white",border:"none",borderRadius:w,fontSize:"1rem",fontWeight:600,cursor:!ge||!D||ce||F||Ne!=="ready"?"not-allowed":"pointer",opacity:!ge||!D||ce||F||Ne!=="ready"?.5:1,transition:"opacity 120ms ease-out",...be??{}},children:ce?"Processing\u2026":`Pay with ${xr(e)}`}),V&&u(Yr,{margin:"0.75rem 0 0",children:V})]})}function Ms({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:a,billingApiUrl:i,paymentElementMethods:d,stripeInstance:s,paymentElementBaseOptions:S,onTokenizedBody:f,onErrorChange:g,onButtonClick:b,onDecline:B,runBeforeButtonClick:F,onLoadStateChange:m,isProcessing:w=!1,submitButtonColor:be="#4A49FF",submitButtonBorderRadius:V=8,submitButtonStyle:C,buttonAppearance:ye,themeId:ne,onExpandApm:le,expandedApmMethod:ce}){let{emitInstrument:ve}=Xr(In),[He,ge]=pe(null),[Rt,Ne]=pe(null),Ee=he(!1),{request:_e,collect:re,finish:oe}=jr();yt(()=>{d.length>0&&s?m?.("ready"):s||m?.("loading")},[d.length,s,m]);let D=fe(async x=>{if(!s||Ee.current||w)return;Ee.current=!0,Ne(x);let ie=F?await F("card"):{proceed:!0};if(!ie.proceed){Ee.current=!1,Ne(null);return}b?.("card");let Me=ie.sessionId??e,se=ie.nonce??t,H=Sr([ie.accountPatch?.firstName,ie.accountPatch?.lastName].filter(Boolean).join(" ")||r),ke=on({email:ie.accountPatch?.email?.trim()||n?.trim(),firstName:ie.accountPatch?.firstName?.trim()||H.firstName,lastName:ie.accountPatch?.lastName?.trim()||H.lastName});if(!Kt(ke.email)){Ne(null);let Ae=await re(xr(x),ke);if(!Ae){Ee.current=!1;return}ke=Ae,Ne(x)}let Xe=ke.email,nt=on({...ie.accountPatch,...ke});try{if(g?.(null),!Me||!Kt(Xe))throw new Error("Missing sessionId or email for payment.");await a?.(ke);let Ae=await sa(i,ve,Me,se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,paymentMethodId:null,intentKind:"payment"});if(Ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let G=Ae.clientSecret;if(typeof window<"u")try{localStorage.setItem(Kn,JSON.stringify({clientSecret:G,sessionId:Me,nonce:se,accountPatch:nt,paymentMethodType:x,gateway:"stripe"}))}catch{}let{error:$,paymentIntent:O}=await s.confirmPayment({clientSecret:G,confirmParams:{return_url:window.location.href,payment_method_data:{type:x,billing_details:{name:[ke.firstName,ke.lastName].filter(Boolean).join(" "),...Xe?{email:Xe}:{}}}},redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let E=$.message??"Payment failed.";g?.(E),B?.(Ft("card",E,{code:$.code})),await la({billingApiUrl:i,sessionId:Me,nonce:se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,providerDeclineReason:$.code??"provider_declined"}});return}let Ce=O?.status;if(!Ho(Ce)){if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let E=Ce==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(E),B?.(Ft("card",E,{code:Ce??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let $e=typeof O?.payment_method=="string"?O.payment_method:O?.payment_method?.id;f({id:$e??O?.id,type:"card",threeDSecureActionResultTokenId:O?.id,gateway:"stripe",paymentMethodType:x},{accountPatch:nt,sessionId:Me,nonce:se})}catch(Ae){g?.(Ae instanceof Error?Ae.message:"Payment failed. Please try again.")}finally{Ee.current=!1,Ne(null)}},[s,w,F,b,e,t,n,re,i,ve,r,a,f,g,B]),[Te,xe]=pe(null),Be=le?ce??null:Te,Oe=fe(x=>{Ee.current||w||Be&&Be!==x||(ks(x)?le?le(x):xe(x):D(x))},[Be,w,D,le]),Pe=ct(()=>Te?{...S,paymentMethodTypes:[Te]}:null,[Te,S]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:_e?u(Kr,{identity:_e.identity,methodLabel:_e.methodLabel,onComplete:oe,onCancel:()=>oe(null)},_e.id):d.map(x=>{let ie=ce===x,Me=Rt===x,se=Rt!==null&&Rt!==x||ce!=null&&ce!==x;return Re(Ec.Fragment,{children:[u(zc,{method:x,themeId:ne,submitting:Me,disabled:se,highlighted:ie,hasNextStep:ks(x),onClick:()=>Oe(x),backgroundColor:ye?.backgroundColor,borderColor:ye?.borderColor,textColor:ye?.textColor,borderRadius:ye?.borderRadius,fontFamily:ye?.fontFamily}),!le&&Te===x&&Pe&&s&&u(_r,{stripe:s,options:Pe,children:u(Wa,{method:x,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:a,billingApiUrl:i,onTokenizedBody:f,onErrorChange:g,onDecline:B,onCancel:()=>xe(null),runBeforeButtonClick:F,onButtonClick:b,isProcessing:w,submitButtonColor:be,submitButtonBorderRadius:V,submitButtonStyle:C})},x)]},x)})})}function Uc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:a,onComplete:i,onError:d,onDecline:s,onTokenizedBody:S,firstName:f,lastName:g,chv:b,className:B,isProcessing:F,error:m,onErrorChange:w,showPayPal:be=!0,showStripe:V=!0,enabledPaymentMethods:C,enabledPaymentMethodCountries:ye,showApplePay:ne=!0,showGooglePay:le=!0,layout:ce="default",theme:ve,buttonsTheme:He,buttonsStyles:ge,appearance:Rt,cardButtonContent:Ne,cardBackButtonContent:Ee,cardTitleContent:_e,showSecurityFooter:re,onButtonClick:oe,onBeforeButtonClick:D,onBuyerIdentityReady:Te,enableAVS:xe,cardFieldOrder:Be,cardPreFormSlot:Oe,avsLayout:Pe="row",country:x,zip:ie,addressLine1:Me,addressLine2:se,city:H,state:ke,onCountryChange:Xe,onZipChange:nt,avsCheck:Ae,checkoutType:G,checkoutLayout:$,totalAmount:O=0,currency:Ce="usd",initialCardOpen:$e=!1,directPaypal:E,isSubscription:W=!1,session:T,dataAttachmentPending:P=!1,dataAttachmentRequiresIdentity:Ze=!1,debug:ft=!1}){let Z=mr(),Qe=Fa(),Ve=Xr(Dn),{emitInstrument:gt}=Xr(In),St=P||Ve.claimPending===!0,h=Ze||Ve.claimRequiresIdentity===!0,J=St&&!h,Q=is(),[rt,xt]=pe(!1),[Pt,Ye]=pe(null),[je,Vt]=pe(x??"US"),[Ot,Bt]=pe(ie??""),[dn,En]=pe(Me??""),[Nn,Zt]=pe(se??""),[_n,Gt]=pe(H??""),[et,un]=pe(ke??""),[ze,On]=pe(""),[ot,ar]=pe({}),zt=he(ie??""),Ht=he(x??"US"),pn=he(Me??""),an=he(se??""),mn=he(H??""),At=he(ke??""),ir=he(""),Ut=he({});yt(()=>{let o=(k,N,Ie,q,we)=>{if(Ut.current[k])return;let Le=N?.trim();!Le||Le===Ie.current||(Ie.current=Le,q(Le),we?.(Le))};o("country",x,Ht,Vt,Xe),o("zip",ie,zt,Bt,nt),o("addressLine1",Me,pn,En),o("addressLine2",se,an,Zt),o("city",H,mn,Gt),o("state",ke,At,un)},[x,ie,Me,se,H,ke,Xe,nt]);let ee=ct(()=>Sc(xe),[xe]),sr=ee!==null,yn=ct(()=>Ka(T),[T]),Qt=!!T?.vault?.html,zn=!!T?.gateways?.pcivault,Gn=!!(T?.gateways?.stripe?.enabledPaymentMethods??C)?.includes("card"),gn=Qt||Gn||zn,y=!!(V&&gn&&Z&&e),[ht,Yt]=pe(()=>ce!=="buttons"||$e?e??null:null),[Wn,Fe]=pe(0),wt=ce!=="buttons"||$e||!!e&&ht===e,dt=ct(()=>!Z||!y||!e||!wt?null:Z.cardCapture({sessionId:e,captureMethod:T?.captureMethod}),[Z,y,e,wt,T?.captureMethod]),Wt=ct(()=>{let o=je,k=ee?qe(ee.postal_code,o):!1;return Lc(o,Ot,k)},[ee,je,Ot]),{avsInvalid:Jn,invalidAvsFields:lr}=ct(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!y||!ee)return{avsInvalid:!1,invalidAvsFields:o};let k=je,N=(we,Le)=>qe(we,k)&&!Le.trim(),Ie={line1:N(ee.address_line_1,dn),city:N(ee.city,_n),state:N(ee.state,et),zip:Wt.empty||Wt.malformed};return{avsInvalid:Ie.line1||Ie.city||Ie.state||Ie.zip,invalidAvsFields:Ie}},[y,ee,je,dn,_n,et,Wt]),[Xn,br]=pe(!1),[hn,Zn]=pe(!1),[Un,en]=pe(!1),[bt,Tn]=pe({line1:!1,city:!1,state:!1}),sn=he(!1),tn=he({email:!1,line1:!1,city:!1,state:!1,zip:!1}),nn=he(!1),at=fe(o=>{tn.current[o]=!0,nn.current=!0},[]),Qn=fe(o=>!sn.current&&tn.current[o],[]),xn=fe(o=>{Qn(o)&&Tn(k=>k[o]?k:{...k,[o]:!0})},[Qn]),[bn,Bn]=pe(()=>Va(T?.vault)),[De,Mt]=pe($e&&gn?"card":"buttons"),[Et,An]=pe(null),cr=De==="expanding"||De==="card",er=T?.gateways?.stripe?"stripe":void 0,ln=fe(()=>{gt?.({class:"card_surface",provider:er})},[er,gt]),qt=280,vn=he(null),_t=fe(o=>{vn.current&&clearTimeout(vn.current),vn.current=setTimeout(()=>{vn.current=null,o()},qt)},[qt]);yt(()=>()=>{vn.current&&clearTimeout(vn.current)},[]);let M=fe(()=>{ln(),Yt(e??null),Fe(o=>o+1),Mt("expanding"),_t(()=>Mt("card"))},[_t,ln,e]),L=fe(()=>{Mt("collapsing"),_t(()=>Mt("buttons"))},[_t]),z=fe(o=>{An(o),Mt("apm-expanding"),_t(()=>Mt("apm-form"))},[_t]),X=fe(()=>{Mt("apm-collapsing"),_t(()=>{Mt("buttons"),An(null)})},[_t]);yt(()=>{ce==="buttons"&&$e&&gn&&(Yt(e??null),Mt("card"))},[ce,$e,gn,e]);let[Se,p]=pe(null),l=he(!1),c=he(null),I=he("idle"),[R,ae]=pe(null),Ge=he(R);yt(()=>{Ge.current=R},[R]);let j=n||Q,Y=he(null),me=ct(()=>{if(Te||Ve.claimBuyerIdentity||T?.buyerIdentified!==!1||!e||!t)return;let o=`${j}|${e}|${t}`;Y.current?.key!==o&&(Y.current={key:o,claim:qr(new Jr(j,{telemetry:!1}),e,t,{...a?{userId:a}:{},...f?{firstName:f}:{},...g?{lastName:g}:{}})});let k=Y.current.claim;return async N=>{await k(N)}},[Te,Ve.claimBuyerIdentity,T?.buyerIdentified,e,t,j,a,f,g]),A=Te??Ve.claimBuyerIdentity??me,v=m??Pt,U=ct(()=>Ic(ve),[ve]),_=ct(()=>{let o=U?.buttonsLayout??wc(He);return ge?{...o,...ge,cardButton:{...o.cardButton,...ge.cardButton},cardFormContainer:{...o.cardFormContainer,...ge.cardFormContainer},backButton:{...o.backButton,...ge.backButton},backButtonIcon:{...o.backButtonIcon,...ge.backButtonIcon},submitButton:{...o.submitButton,...ge.submitButton},title:{...o.title,...ge.title}}:o},[U,He,ge]),K=Rt??U?.appearance,Ue=ct(()=>Gi({appearance:K,buttonsStyles:_,layout:ce}),[K,_,ce]),vr=Ve.inlineSessionPatchProcessing??!1,it=(F??rt)||vr,ut=j.replace(/\/+$/,""),ue=ct(()=>Ma({userId:a,email:r,firstName:f,lastName:g,country:x,zip:ie},ot),[a,r,f,g,x,ie,ot]),cn=[ue.firstName,ue.lastName].filter(o=>!!o?.trim()).join(" "),fi=!Kt(ue.email?.trim()),ma=he(null);y&&ma.current===null&&(ma.current=fi);let dr=y&&(ma.current??fi),ya=ct(()=>Nc(ze,dr),[ze,dr]),Ar=ya.empty||ya.malformed,Pn=ct(()=>Z?Z.getRawProvider():null,[Z]),Mr=ct(()=>Qe?Qe.getRawProvider():null,[Qe]),no=O||100,Bo=ct(()=>K?dc(K):null,[K]),Ao=Bo?{appearance:Bo}:null,gi=ct(()=>{let o=Bo??{},k=o.rules??{};return{...o,rules:{...k,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...k[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...k[".AccordionItemContents"]??{}}}}},[Bo]),hi=ct(()=>{let o=es(O);return{...o,currency:Ce.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...Ao}},[O,Ce,Ao]),bi=ct(()=>({mode:"payment",amount:no,currency:Ce.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Ao}),[no,Ce,Ao]),de=fe(o=>{Ye(o),w?.(o)},[w]),fa=he(""),[vi,Xs]=pe(!1),ga=fe(()=>{Xs(!0)},[]);yt(()=>{if(!y||!dr||!A||!vi||Ar||fa.current)return;let o=on({email:Kt(ue.email?.trim())?ue.email?.trim():ir.current.trim(),firstName:ue.firstName?.trim(),lastName:ue.lastName?.trim()});fa.current=JSON.stringify(o),ar(k=>({...k,...o})),Promise.resolve(A(o)).catch(k=>{fa.current="",de(k instanceof Error?k.message:"Failed to attach buyer details.")})},[y,dr,A,vi,Ar,ue.email,ue.firstName,ue.lastName,de]),yt(()=>{!y||!dt||dt.setCardFieldOrder?.(Be??null,ee==null&&!dr)},[y,dt,Be,ee,dr]),yt(()=>{(De==="expanding"||De==="collapsing"||De==="apm-expanding"||De==="apm-collapsing")&&de(null)},[De,de]);let Mn=fe((o,k,N)=>{s?.(Ft(o,k,N))},[s]),Fr=fe((o,k,N)=>{let Ie=N?.popupBlocked??pr(k),q=Fc(o,Ie),we=kr(N?.code)??tr(k)??"external_payment_method_failed",Le=new Ln(q,"api_error",{code:"external_payment_method_failed",param:o});p(null),ce==="buttons"&&(Mt("buttons"),An(null)),de(q),d?.(Le),console.error("[FloPay] External payment method failed:",{method:o,code:we,popupBlocked:Ie})},[ce,d,de]);yt(()=>{if(!y||!e){Bn(null);return}let o=Va(T?.vault);if(o){Bn(o);return}if(!wt){Bn(null);return}Bn(null);let k=!0;return new Jr(ut).getVaultCapture(e,t).then(N=>{if(!k)return;let Ie=Va(N);Ie?Bn(Ie):de("Failed to load the secure card form.")}).catch(N=>{k&&de(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{k=!1}},[y,wt,Wn,e,T?.vault?.html,T?.vault?.messageToken,T?.vault?.expectedOrigin,ut,t,de]);let qn=he({onComplete:i,onError:d,updateError:de,emitDecline:Mn,resolvedAccount:ue,avsConfig:ee,avsCheckProp:Ae,sessionId:e,nonce:t,baseUrl:ut,captureMethod:T?.captureMethod,paymentId:T?.paymentId,authorizationExpiresAt:T?.authorizationExpiresAt});qn.current={onComplete:i,onError:d,updateError:de,emitDecline:Mn,resolvedAccount:ue,avsConfig:ee,avsCheckProp:Ae,sessionId:e,nonce:t,baseUrl:ut,captureMethod:T?.captureMethod,paymentId:T?.paymentId,authorizationExpiresAt:T?.authorizationExpiresAt};let ha=he(!1),Zs=fe(()=>{let{resolvedAccount:o,avsConfig:k,avsCheckProp:N}=qn.current,Ie=o.email?.trim(),q=Kt(Ie)?Ie:ir.current.trim();if(!Kt(q))return null;let we=o.firstName?.trim(),Le=o.lastName?.trim(),tt=Ht.current||o.country||"US",$t=k?qe(k.state,tt):!1,pt=k?qe(k.address_line_1,tt):!1,mt=k?qe(k.postal_code,tt):!1,We=k?qe(k.city,tt):!1,Jt=k?qe(k.address_line_2,tt):!1,Ke=pt&&!$t&&mt?ws(tt,(zt.current??"").trim()):null,Xt=$t?At.current:Ke;return{accountData:{userId:o.userId??"",email:q,...we?{firstName:we}:{},...Le?{lastName:Le}:{},...mt&&zt.current?{zip:zt.current}:{},...We&&mn.current?{city:mn.current}:{},...Xt?{state:Xt}:{},...pt&&pn.current?{addressLine1:pn.current}:{},...Jt&&an.current?{addressLine2:an.current}:{},country:tt},...N!==void 0?{avsCheck:N}:{},...k?{avsConfig:{country:qe(k.country,tt),postal_code:mt,address_line_1:pt,address_line_2:Jt,city:We,state:$t}}:{}}},[]),Pi=he(St);Pi.current=St,yt(()=>{St||v!==Es||qn.current.updateError(null)},[St,v]),yt(()=>{!y||!dt||dt.setSubmitGate?.(Jn||St||Ar)},[y,dt,Jn,St,Ar]),yt(()=>{if(!y||!dt)return;ha.current=!1;let o=!1,k=dt.on("submitting",()=>{br(!0),c.current&&clearTimeout(c.current),I.current="validation-window",c.current=setTimeout(()=>{c.current=null,I.current==="validation-window"&&(I.current="processing")},_c),p("processing");let{baseUrl:Le,sessionId:tt,nonce:$t,updateError:pt,onError:mt}=qn.current;if(!tt||!$t)return;let We=Zs();if(!We){pt("Enter a valid email address."),I.current="idle",p(null);return}new Jr(Le).patchAccountSnapshot(tt,$t,We,{telemetryMode:"best_effort"}).catch(Jt=>{if(!Tc(Jt))return;let Ke=Jt instanceof Error?Jt.message:"Please check your billing address and try again.";pt(Ke),I.current="idle",p(null),mt?.(Jt instanceof Ln?Jt:new Ln(Ke,"api_error"))})}),N=dt.on("complete",async Le=>{if(Gr(Le.sessionId??qn.current.sessionId),I.current="terminal",p("success"),await new Promise(pt=>setTimeout(pt,1200)),ha.current)return;ha.current=!0;let tt=qn.current,$t=Ka(tt)||Le.outcome==="authorized";qn.current.onComplete?.($t?{status:"authorized",paymentIntentId:Le.intentId,paymentId:Le.paymentId??tt.paymentId,sessionId:Le.sessionId??tt.sessionId,authorizationExpiresAt:Le.authorizationExpiresAt??tt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Le.intentId,checkoutMethod:"card"})}),Ie=dt.on("decline",async Le=>{let{updateError:tt,emitDecline:$t}=qn.current,pt=Le.message??"Your payment was declined. Please try another card or contact your bank.";I.current="terminal",tt(pt),p("error");let mt=Le.failureOutcome??Pc(Le.declineReason)??"authorization_declined";$t("card",pt,{code:mt,declineCode:mt}),await new Promise(We=>setTimeout(We,1500)),!o&&(I.current="idle",p(null))}),q=dt.on("error",async Le=>{let{updateError:tt,onError:$t}=qn.current,pt=Le.message??"There was a problem processing your payment. Please try again.";I.current="terminal",tt(pt),p("error"),$t?.(new Ln(pt,"api_error",{code:Le.failureOutcome??"capture_failed"})),await new Promise(mt=>setTimeout(mt,1500)),!o&&(I.current="idle",p(null))}),we=dt.on("blocked",()=>{if(!Pi.current){br(!0);return}ga(),qn.current.updateError(Es)});return()=>{o=!0,c.current&&(clearTimeout(c.current),c.current=null),I.current="idle",k(),N(),Ie(),q(),we()}},[y,dt,ga]);let $n=!!E?.clientId,ro=Array.isArray(C),Mo=ro&&C.length>0,Qs=ro&&C.includes("paypal"),{expressMethods:Fo,paymentElementMethods:oo}=ct(()=>Cc(C,{excludePaypal:$n}),[C,$n]),Ci=$n||!!Qe,el=ct(()=>Ci?Fo.filter(o=>o!=="paypal"):Fo,[Fo,Ci]),tl=ct(()=>{let o=[];return ne&&o.push("apple_pay"),le&&o.push("google_pay"),o},[ne,le]),Do=ro?el:tl,nl=V&&Do.length>0,ba=sr?je:x,Lo=ct(()=>{let o=ba?.trim().toUpperCase();return o?ye?oo.filter(k=>{let N=ye[k];return!N||N.length===0||N.includes(o)}):mc(oo,ba):oo},[oo,ba,ye]),va=ct(()=>({mode:"payment",amount:no,currency:Ce.toLowerCase(),paymentMethodCreation:"manual",appearance:gi}),[no,Ce,gi]),[Si,wi]=pe("loading"),[ki,Ii]=pe("loading"),[Ri,Ei]=pe("loading"),[rl,Pa]=pe(!1),[_i,Ca]=pe("loading"),[No,ol]=pe();yt(()=>{ol(Cs())},[]);let Ti=be&&($n||(ro?Qs:No===!1)),xi=V&&nl,ao=!J&&Ti&&$n,Bi=_i==="retrying"||_i==="exhausted",io=!J&&Ti&&!!Mr&&(!$n||Bi),so=!J&&xi&&!!Pn,lo=!J&&V&&Mo&&Lo.length>0&&!!Pn,al=ao&&!Bi?rl:io&&xs(Si),il=so&&xs(ki),sl=lo&&Ri!=="load_error",Ai=o=>o==="loading"||o==="ready",Mi=ao||io&&Ai(Si)||so&&Ai(ki)||lo&&Ri!=="load_error",Oo=he(!1);yt(()=>{if(!Oo.current){if(!V&&!be){Oo.current=!0;let o=new Ln("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(o),de(o.message)}else if(!V&&be&&!$n&&!Mr){Oo.current=!0;let o=new Ln("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(o),de(o.message)}else if(No!==void 0&&!J&&!gn&&!Mi){Oo.current=!0;let o=new Ln("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});d?.(o),de(o.message)}}},[V,be,$n,Mr,No,J,gn,Mi,d,de]);let Fi=he(!1);yt(()=>{if(Fi.current||!Mo)return;let o=[];ne!==!0&&o.push("showApplePay"),le!==!0&&o.push("showGooglePay"),o.length!==0&&(Fi.current=!0,console.warn(`[FloPay] ${o.join(" / ")} ${o.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.`))},[Mo,ne,le]);let Di=fe((o,k)=>Ve.applyInlineSessionPatch?Ve.applyInlineSessionPatch(o).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let Ie=Ts(k,N);return de(Ie.message),d?.(Ie),{error:Ie,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ve.applyInlineSessionPatch,t,d,e,de]),Fn=fe(async o=>{if(!D)return{proceed:!0};try{let k=await D({method:o,sessionId:e||void 0,createSession:Ve.inlineSessionDraft});if(k===!1)return{proceed:!1};if(k&&typeof k=="object"){k.account&&ar(Ie=>({...Ie??{},...k.account}));let N=await Di(k,o);return N.error?{proceed:!1,accountPatch:k.account}:{proceed:!0,accountPatch:k.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(k){let N=Ts(o,k);return de(N.message),d?.(N),{proceed:!1}}},[Di,Ve.inlineSessionDraft,D,d,e,de]),Li=fe(async(o,k)=>{if(l.current)return;l.current=!0,xt(!0),p("processing"),de(null);let N=k?.sessionId??e,Ie=k?.nonce??t,q=Ma(ue,k?.accountPatch),we=k?.completionPaymentMethodId??bo(o),Le=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o,tt=o.gateway==="stripe"?"stripe":o.gateway==="paypal"||o.isPaypal?"paypal":void 0,$t=()=>{gt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:tt})};try{let mt=await new Jr(ut).processPayment(q.userId??"",{sessionId:N,nonce:Ie,tokenizedData:Le,accountData:{userId:q.userId??"",email:q.email??"",...q.firstName?{firstName:q.firstName}:{},...q.lastName?{lastName:q.lastName}:{},...ee?(()=>{let Ke=Ht.current,Xt=qe(ee.state,Ke),wn=qe(ee.address_line_1,Ke),jt=qe(ee.postal_code,Ke),yo=wn&&!Xt&&jt?ws(Ke,(zt.current??"").trim()):null,fo=Xt?At.current:yo;return{country:Ke,...jt&&zt.current?{zip:zt.current}:{},...qe(ee.city,Ke)&&mn.current?{city:mn.current}:{},...fo?{state:fo}:{},...wn&&pn.current?{addressLine1:pn.current}:{},...qe(ee.address_line_2,Ke)&&an.current?{addressLine2:an.current}:{}}})():{}},chv:b,avsCheck:Ae??!1,checkoutType:G,checkoutLayout:$,avsConfig:ee?{country:qe(ee.country,Ht.current),postal_code:qe(ee.postal_code,Ht.current),address_line_1:qe(ee.address_line_1,Ht.current),address_line_2:qe(ee.address_line_2,Ht.current),city:qe(ee.city,Ht.current),state:qe(ee.state,Ht.current)}:void 0});if(mt.ok){let Ke=mt.status===204?null:await mt.json().catch(()=>null),Xt=Ka(T)||Ke?.status==="authorized";Gr(N),p("success"),ae(null),await new Promise(wn=>setTimeout(wn,1200)),i?.(Xt?{status:"authorized",...typeof Ke?.paymentId=="string"?{paymentId:Ke.paymentId}:T?.paymentId?{paymentId:T.paymentId}:{},sessionId:typeof Ke?.sessionId=="string"?Ke.sessionId:N,...typeof Ke?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Ke.authorizationExpiresAt}:T?.authorizationExpiresAt?{authorizationExpiresAt:T.authorizationExpiresAt}:{},paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:we,checkoutMethod:o.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:we,checkoutMethod:o.isPaypal?"paypal":"card"});return}let We=await mt.json().catch(()=>null);if(We?.type==="paypal_redirect_required"){let Ke=We.threeDSecureToken,Xt=We.paymentMethodId||o.id||"";if(!Z||!Ke){p("error"),de("PayPal authorization required but no token provided.");return}try{let wn=Qe?.getRawProvider();if(!wn){de("PayPal is not available.");return}let jt={return_url:window.location.href};Xt&&(jt.payment_method=Xt);let{error:yo}=await wn.confirmPayment({clientSecret:Ke,confirmParams:jt,redirect:"if_required"});if(yo){p("error");let fo=yo.message??"PayPal payment failed.";de(fo),Mn("paypal",fo,{code:yo.code})}}catch(wn){p("error"),de(wn instanceof Error?wn.message:"PayPal authorization failed.")}return}if(We?.type==="paypal_direct_required"){let Ke=We.orderId;if(!Ke){p("error"),de("PayPal retry required but no order id provided.");return}let Xt=Ge.current?.attempts??0;if(Xt>=2){p("error"),de("PayPal payment could not be completed after multiple attempts."),Mn("paypal","paypal_direct_required retry limit exceeded");return}Pa(!1),Ca("loading"),ae({orderId:Ke,attempts:Xt+1}),p(null);return}pc(mt.status,We)||$t(),p("error");let Jt=We?.message??"Payment failed. Please try again.";de(Jt),Mn(o.isPaypal?"paypal":"card",Jt,{code:We?.code??We?.gatewayErrorCode,declineCode:We?.declineCode??We?.gatewayDeclineReason}),await new Promise(Ke=>setTimeout(Ke,1500))}catch(pt){Ds(pt)||$t(),p("error"),de(pt instanceof Error?pt.message:"An unexpected error occurred"),await new Promise(mt=>setTimeout(mt,1500))}finally{xt(!1),p(null),l.current=!1}},[ut,e,t,ue,cn,b,Z,Qe,T,i,d,de,Mn,gt]),Cn=fe((o,k)=>{S?S(o):Li(o,k)},[S,Li]),Ni=he(!1);yt(()=>{if(typeof window>"u"||Ni.current)return;let o=new URLSearchParams(window.location.search),k=o.get("payment_intent"),N=o.get("payment_intent_client_secret"),Ie=o.get("redirect_status");if(!k||!N)return;let q=mt=>{let We=localStorage.getItem(mt);if(!We)return null;try{return JSON.parse(We)}catch{return localStorage.removeItem(mt),null}},we=q(Kn)??q(Rs),Le;if(we?.clientSecret){if(we.clientSecret!==N)return;Le={...we.accountPatch?{accountPatch:we.accountPatch}:{},...we.sessionId?{sessionId:we.sessionId}:{},...we.nonce?{nonce:we.nonce}:{}}}else if(we?.sessionId&&we.sessionId!==e)return;Ni.current=!0,localStorage.removeItem(Kn),localStorage.removeItem(Rs);let tt=new URL(window.location.href);tt.searchParams.delete("payment_intent"),tt.searchParams.delete("payment_intent_client_secret"),tt.searchParams.delete("redirect_status"),window.history.replaceState({},"",tt.toString());let $t=we?.paymentMethodType??we?.tokenType??"card",pt="card";(async()=>{let mt=Z?.getRawProvider();if(!mt){let jt="Payment is not available \u2014 please refresh and try again.";de(jt),Mn(pt,jt);return}if(Ie==="failed"){let jt="Payment was declined. Please try again.";de(jt),Mn(pt,jt);return}let{paymentIntent:We,error:Jt}=await mt.retrievePaymentIntent(N);if(Jt){let jt=Jt.message??"Failed to retrieve payment status.";de(jt),Mn(pt,jt,{code:Jt.code});return}let Ke=We?.status,Xt=Ho(Ke);if(!We||!Xt){let jt=Ke==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";de(jt),Mn(pt,jt,{code:Ke??"missing_payment_intent"});return}let wn=typeof We.payment_method=="string"?We.payment_method:We.payment_method?.id;Cn({id:wn??we?.paymentMethodId??we?.tokenId??We.id,type:"card",threeDSecureActionResultTokenId:We.id,gateway:we?.gateway??"stripe",paymentMethodType:$t},Le)})()},[e,Cn,Z,de,Mn]);let Sa=fe(o=>{o.preventDefault()},[]);if(!(Z!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let co=ce==="buttons",rn=K?.variables,ll=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),wa=rn?.colorBackground,cl=wa&&!ll.has(wa)?wa:void 0,uo=_.cardInputBorder??(co?"#e5e7eb":"#A4A4FF"),Oi=rn?.colorDanger??"#dc2626",Ct=o=>lr[o]&&(bt[o]||Xn),zo=Ar&&(Un||Xn),Sn=o=>o?Oi:uo,Uo=(Wt.malformed||Wt.empty)&&(hn||Xn),dl=Sn(Uo),ka=_.cardFormContainer?.backgroundColor??cl??(co?"white":"#EDEDFF"),Dr=_.cardInputBackground??rn?.colorBackground??"white",Ia=Nr(Ee),zi=Nr(_e),Lr=_.nameInput,Ui=_.cardInputFontSize??Oc(Lr?.fontSize)??rn?.fontSizeBase??"16px",qi=typeof Lr?.fontFamily=="string"?Lr.fontFamily:rn?.fontFamily??"Poppins, sans-serif",$i=Yi(Lr?.fontWeight)??400,ul=_.cardInputColor??(typeof Lr?.color=="string"?Lr.color:void 0)??rn?.colorText??"#262833",pl=_.cardInputPlaceholderColor??"#9ca3af",kt=rn?.borderRadius??"8px",Pr=rn?.borderRadius??_.cardButton?.borderRadius??kt,Cr=rn?.colorPrimary??"#4A49FF",ml=rn?.colorPrimaryHover??go(Cr,.12),Ra=rn?.colorText??"#262833",Ea={fontSize:Ui,fontFamily:qi,fontWeight:$i,color:ul,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},po={marginTop:"0.375rem",...Ea,fontSize:"0.75rem",lineHeight:1.4,color:Oi},yl={"--flopay-input-placeholder-color":pl,"--flopay-input-font-size":Ui,"--flopay-input-font-family":qi,"--flopay-input-font-weight":String($i)},mo=_.cardFormContainer??{},_a=mo.padding??(co?"0":"1rem"),Ta=mo.borderRadius??kt,fl=dt&&bn?u(xa,{capture:dt,html:bn.html,messageToken:bn.messageToken,expectedOrigin:bn.expectedOrigin,theme:Ue,onReady:()=>{if(!dr&&!ee||typeof document>"u")return;let o=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){sn.current=!0;try{N.focus()}finally{sn.current=!1}}};nn.current||o()},onError:o=>de(o),onValidation:o=>{let k=I.current;(k==="idle"||k==="validation-window")&&(de(o),o&&I.current==="validation-window"&&(c.current&&(clearTimeout(c.current),c.current=null),I.current="idle",p(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"}),ji=Re("div",{onFocusCapture:o=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(o.target.tagName)&&ln()},style:{backgroundColor:ka,borderRadius:Ta,...mo,padding:_a,...yl,display:"flex",flexDirection:"column"},children:[u("style",{children:`
|
|
25
|
+
`,ca=44,Tr=280;function ei(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 Mc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Os={width:"100%",minHeight:ca,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 Ac(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ts(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ga(e){return e==="paypal"?"PayPal":Mr(e)}function Fc(e,t){let n=`We couldn't open ${Ga(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function zs(e){let t=be(0),n=be(null),r=be(null),o=fe((u=r.current)=>{let S=u;S?.timer&&(clearTimeout(S.timer),S.timer=null)},[]),a=fe((u,S)=>{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"}))},S))},[o,e]),l=fe(u=>{u.yieldedControl&&a(u,600)},[a]),s=fe(u=>{o();let S=t.current+1;t.current=S,n.current=null;let ve={generation:S,method:u,timer:null,yieldedControl:!1};return r.current=ve,S},[o]),C=fe(u=>{let S=r.current;return typeof u=="number"&&S?.generation!==u?!1:(o(S),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),y=fe(u=>{let S=r.current,ve=u??S?.generation??t.current;(!u||S?.generation===u)&&(o(S),r.current=null),n.current=ve},[o]),f=fe(u=>n.current===(u??t.current),[]),h=fe(u=>r.current?.generation===u&&n.current!==u,[]),B=fe(()=>{let u=r.current;u&&l(u)},[l]),A=fe(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return vt(()=>{let u=()=>{document.visibilityState==="visible"?B():A()},S=()=>{A()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",S),window.addEventListener("focus",B),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",S),window.removeEventListener("focus",B),o()}},[o,A,B]),{startAttempt:s,finishAttempt:C,invalidateAttempt:y,isAttemptInvalidated:f,isAttemptCurrent:h}}function Dc(e){let t=yc(e);return`Enter a valid ${Wa(e)}${t?` (e.g. ${t})`:""}`}function Lc(e,t,n){let r=hc(e),o=t.trim(),a=n&&r,l=a&&!o,s=a&&!!o&&!vc(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:s}}function Nc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!Wt(n);return{required:t,empty:r,malformed:o,value:n}}function xs(e,t){return t instanceof $n?t:new $n(t instanceof Error?t.message:`${Ac(e)} before-click hook failed.`,"validation_error")}function Ya(){return c("style",{children:Bc})}function Oc(e){return typeof e=="number"?`${e}px`:e}function Us(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function qs({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:Me("div",{style:{position:"relative",minHeight:44},children:[c("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"}}),c("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 Bs(e){return e!=="unavailable"&&e!=="load_error"}function ti(e){return c(Uc,{...e})}function Ms({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:s,onDecline:C,onTechnicalFailure:y,runBeforeButtonClick:f,billingName:h,onBuyerIdentityReady:B,onLoadStateChange:A,placeholderBorderRadius:u}){let S=fr(),{emitInstrument:ve}=Qr(An),K=Za(),v=Xa(),[ye,Q]=me("loading");vt(()=>{A?.(ye)},[ye,A]);let[ce,de]=me(!1),we=!Wt(n?.trim())||!h?.trim(),{request:Qe,collect:he,finish:Bt}=Vr(),Xe=be(!1),Ae=be(null),Fe=be(null),[ee,te]=me(0),[F,Le]=me(!1),Ne=be(!1),ze=be(new Map),{startAttempt:Ke,finishAttempt:ke,invalidateAttempt:T,isAttemptInvalidated:oe,isAttemptCurrent:Ue}=zs((H,U,O)=>{y?.(H,U,{...O,popupBlocked:O?.popupBlocked??yr(U)}),Le(!0),te(Ie=>Ie+1)});vt(()=>{F&&Fe.current?.focus()},[F,ee]);let ae=fe(()=>{te(H=>H+1)},[]),V=fe((H,U,O)=>{T(O),y?.("paypal",H,{code:U,popupBlocked:yr(H)}),Le(!0),ae()},[T,y,ae]),Ee=fe(()=>{window.setTimeout(()=>{(Ae.current?.querySelector("iframe")??Ae.current)?.focus()},0)},[]);vt(()=>{Ne.current&&(Ne.current=!1,Ee())},[Ee,ee]);let nt=fe(()=>{Le(!1),a?.(null),Ee()},[Ee,a]);vt(()=>{if(!K||Xe.current)return;let H=new URLSearchParams(window.location.search),U=H.get("payment_intent"),O=H.get("payment_intent_client_secret"),Ie=H.get("redirect_status");if(!U||!O)return;Xe.current=!0;let Ye;try{let Y=localStorage.getItem(xo);if(Y){let E=JSON.parse(Y);E.clientSecret===O&&(Ye={...E.accountPatch?{accountPatch:E.accountPatch}:{},...E.sessionId?{sessionId:E.sessionId}:{},...E.nonce?{nonce:E.nonce}:{}})}}catch{}try{localStorage.removeItem(xo)}catch{}let k=new URL(window.location.href);k.searchParams.delete("payment_intent"),k.searchParams.delete("payment_intent_client_secret"),k.searchParams.delete("redirect_status"),window.history.replaceState({},"",k.toString()),(async()=>{try{if(de(!0),Ie==="failed"){let b="PayPal payment was declined. Please try again.";a?.(b),C?.(Ut("paypal",b));return}let{paymentIntent:Y,error:E}=await K.retrievePaymentIntent(O);if(E){a?.(E.message??"Failed to retrieve PayPal payment status.");return}if(Y&&(Y.status==="requires_capture"||Y.status==="succeeded")){let b=typeof Y.payment_method=="string"?Y.payment_method:Y.payment_method?.id;o({id:b??Y.id,type:"card",threeDSecureActionResultTokenId:Y.id,isPaypal:!0},Ye)}else{let b="PayPal payment was not completed. Please try again.";a?.(b),C?.(Ut("paypal",b))}}catch(Y){a?.(Y instanceof Error?Y.message:"Failed to complete PayPal payment.")}finally{de(!1)}})()},[K,o,a,C]);let dt=fe(async H=>{if(l||ce){H.reject();return}let U=f?await f("paypal"):{proceed:!0};if(!U.proceed){ze.current.delete(ee),H.reject();return}let O=Ke("paypal");ze.current.set(ee,{generation:O,accountPatch:U.accountPatch,sessionId:U.sessionId,nonce:U.nonce}),Le(!1),s?.("paypal"),H.resolve()},[l,s,f,Ke,ce,ee]),De=fe(async H=>{if(!K||!v)return;let U=ze.current.get(ee);if(U&&!Ue(U.generation)){ze.current.delete(ee);return}if(!U&&oe()||U&&!ke(U.generation))return;U||ke();let O=U??null;if(ze.current.delete(ee),!O&&f){let b=await f("paypal");if(!b.proceed){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}O={accountPatch:b.accountPatch,sessionId:b.sessionId,nonce:b.nonce}}let Ie=O?.sessionId??e,Ye=O?.nonce??t,k=await Ns({event:H,prepared:O,email:n,billingName:h,methodLabel:"PayPal",collect:he});if(!k){H.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Y=k.email,E=ln({...O?.accountPatch,...k});try{if(de(!0),a?.(null),!Ie||!Wt(Y))throw new Error("Missing sessionId or email for PayPal payment");await B?.(k);let b=K.createPaymentMethod,{error:it,paymentMethod:Pt}=await b({type:"paypal"});if(it){V(it,"stripe_paypal_create_payment_method_failed",U?.generation),H.paymentFailed({reason:"fail"});return}let G=await da(r,ve,Ie,Ye??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Pt?.id??null,intentKind:"payment"});if(G.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let st=G.clientSecret,Ze={return_url:window.location.href};if(Pt?.id&&(Ze.payment_method=Pt.id),typeof window<"u")try{localStorage.setItem(xo,JSON.stringify({clientSecret:st,sessionId:Ie,nonce:Ye,accountPatch:E}))}catch{}let{error:Ct,paymentIntent:wt}=await K.confirmPayment({clientSecret:st,confirmParams:Ze,redirect:"if_required"});if(Ct){if(typeof window<"u")try{localStorage.removeItem(xo)}catch{}if(So(Ct)){let $=Ct.message??"Your payment was declined.";a?.($),C?.(Ut("paypal",$,{code:rr(Ct),declineCode:Yr(Ct)})),await ua({billingApiUrl:r,sessionId:Ie,nonce:Ye,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:rr(Ct)??"provider_declined"}})}else V(Ct,"stripe_paypal_confirm_failed",U?.generation);return}if(typeof window<"u")try{localStorage.removeItem(xo)}catch{}let g=typeof wt?.payment_method=="string"?wt.payment_method:wt?.payment_method?.id;o({id:g??wt?.id,type:"card",threeDSecureActionResultTokenId:wt?.id,isPaypal:!0},{accountPatch:E,sessionId:Ie,nonce:Ye});return}catch(b){V(b,"stripe_paypal_failed",U?.generation)}finally{de(!1)}},[K,v,e,t,n,h,he,B,r,ve,o,a,C,f,V,ke,Ue,oe,ee]);return Me(Br,{children:[c(qs,{state:ye,placeholderTestId:"flopay-paypal-placeholder",borderRadius:u,children:Me("div",{ref:Ae,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[F&&c("button",{ref:Fe,type:"button","data-testid":"flopay-paypal-retry-button",onClick:nt,style:Os,children:"Try PayPal again"}),Qe&&c(Hr,{identity:Qe.identity,methodLabel:Qe.methodLabel,onComplete:Bt,onCancel:()=>Bt(null)},Qe.id),c("div",{style:{display:Qe?"none":void 0},children:c(Ds,{onReady:H=>Q(Us(H,["paypal"])),onLoadError:()=>{Q("load_error"),Qa(qt(S),"paypal","paypal")},onClick:dt,onConfirm:De,onCancel:()=>{let H=ze.current.get(ee);ze.current.delete(ee),qt(S)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(H?.generation),Le(!1),Ne.current=!0,ae()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:we,emailRequired:we,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),ce&&c(Wn,{status:"processing"})]})}function As({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:s,onButtonClick:C,onDecline:y,onTechnicalFailure:f,runBeforeButtonClick:h,billingName:B,onBuyerIdentityReady:A,onLoadStateChange:u,placeholderBorderRadius:S}){let ve=fr(),{emitInstrument:K}=Qr(An),v=Za(),ye=Xa(),[Q,ce]=me("loading");vt(()=>{u?.(Q)},[Q,u]);let[de,we]=me(!1),Qe=!Wt(n?.trim())||!B?.trim(),{request:he,collect:Bt,finish:Xe}=Vr(),Ae=be(null),Fe=be(null),[ee,te]=me(0),[F,Le]=me(!1),[Ne,ze]=me("google_pay"),Ke=be(!1),ke=be("google_pay"),T=be("google_pay"),oe=be(new Map),{startAttempt:Ue,finishAttempt:ae,invalidateAttempt:V,isAttemptInvalidated:Ee,isAttemptCurrent:nt}=zs((k,Y,E)=>{f?.(k,Y,{...E,popupBlocked:E?.popupBlocked??yr(Y)}),ze(k),Le(!0),te(b=>b+1)});vt(()=>{F&&Fe.current?.focus()},[F,ee]);let dt=fe(()=>{te(k=>k+1)},[]),De=fe((k,Y,E,b)=>{V(b),f?.(k,Y,{code:E,popupBlocked:yr(Y)}),ze(k),Le(!0),dt()},[V,f,dt]),H=fe(()=>{window.setTimeout(()=>{(Ae.current?.querySelector("iframe")??Ae.current)?.focus()},0)},[]);vt(()=>{Ke.current&&(Ke.current=!1,H())},[H,ee]);let U=fe(()=>{Le(!1),s?.(null),H()},[H,s]),O=fe(async k=>{if(!v||!ye)return;let Y=oe.current.get(ee);if(Y&&!nt(Y.generation)){oe.current.delete(ee);return}if(!Y&&Ee()||Y&&!ae(Y.generation))return;Y||ae();let E=k.expressPaymentType??Y?.method??ke.current,b=Y??null;oe.current.delete(ee);let it=Ts(E);if(!b&&h){let g=await h(it);if(!g.proceed){k.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}b={accountPatch:g.accountPatch,sessionId:g.sessionId,nonce:g.nonce}}let Pt=it,G=b?.sessionId??e,st=b?.nonce??t,Ze=await Ns({event:k,prepared:b,email:n,billingName:B,methodLabel:Ga(E),collect:Bt});if(!Ze){k.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ct=Ze.email,wt=ln({...b?.accountPatch,...Ze});try{if(we(!0),s?.(null),!Wt(Ct))throw new Error("Missing sessionId or email for wallet payment");await A?.(Ze);let{error:g}=await ye.submit();if(g){De(E,g,"stripe_wallet_submit_failed",Y?.generation);return}let{error:$,paymentMethod:lt}=await v.createPaymentMethod({elements:ye});if($||!lt){De(E,$??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",Y?.generation);return}if(!G)throw new Error("Missing sessionId or email for wallet payment");let yt=await da(r,K,G,st??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:E??it,paymentMethodId:lt.id,intentKind:o});if(yt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let ie=yt.clientSecret,{error:kt,intentId:ot}=bc(ie)?await v.confirmCardSetup(ie,{payment_method:lt.id}).then(qe=>({error:qe.error,intentId:qe.setupIntent?.id})):await v.confirmCardPayment(ie,{payment_method:lt.id}).then(qe=>({error:qe.error,intentId:qe.paymentIntent?.id}));if(kt){if(So(kt)){let qe=kt.message??"Your payment was declined.";s?.(qe),y?.(Ut(Pt,qe,{code:rr(kt),declineCode:Yr(kt)})),await ua({billingApiUrl:r,sessionId:G,nonce:st,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:E??it,providerDeclineReason:rr(kt)??"provider_declined"}})}else De(E,kt,"stripe_wallet_confirm_failed",Y?.generation);return}l({id:lt.id,type:"card",threeDSecureActionResultTokenId:ot},{accountPatch:wt,sessionId:G,nonce:st})}catch(g){De(E,g,"stripe_wallet_failed",Y?.generation)}finally{we(!1)}},[v,ye,e,t,n,B,Bt,A,r,K,o,l,s,y,h,De,ae,nt,Ee,ee]),Ie=mt(()=>{let k=["applePay","googlePay","paypal","link","amazonPay","klarna"],Y=new Set(["applePay","googlePay"]),E=new Set(a.map(Rs)),b={};for(let it of k)E.has(it)?b[it]=Y.has(it)?"always":"auto":b[it]="never";return b},[a]),Ye=mt(()=>a.map(Rs),[a]);return Me(Br,{children:[c(qs,{state:Q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:S,children:Me("div",{ref:Ae,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[F&&Me("button",{ref:Fe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:U,style:Os,children:["Try ",Ga(Ne)," again"]}),he&&c(Hr,{identity:he.identity,methodLabel:he.methodLabel,onComplete:Xe,onCancel:()=>Xe(null)},he.id),c("div",{style:{display:he?"none":void 0},children:c(Ds,{onReady:k=>{ce(Us(k,Ye))},onLoadError:k=>{ce("load_error"),Qa(qt(ve),"stripe","wallet")},onClick:async k=>{ke.current=k.expressPaymentType,T.current=Ts(k.expressPaymentType);let Y=h?await h(T.current):{proceed:!0};if(!Y.proceed){oe.current.delete(ee),k.reject();return}let E=Ue(k.expressPaymentType);oe.current.set(ee,{generation:E,method:k.expressPaymentType,accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}),Le(!1),C?.(T.current),k.resolve()},onConfirm:O,onCancel:()=>{let k=oe.current.get(ee);oe.current.delete(ee),qt(ve)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),V(k?.generation),Le(!1),Ke.current=!0,dt()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ie,emailRequired:Qe,billingAddressRequired:Qe,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),de&&c(Wn,{status:"processing"})]})}function zc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:s,borderColor:C,textColor:y,borderRadius:f,fontFamily:h}){let B=kc(e,t),A=ws[e],[u,S]=me(!1),ve=B?.backgroundColor??s??"#ffffff",K=B?.borderColor??C??"#d1d5db",v=B?.textColor??y??"#262833";return c("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ca,padding:"0 1rem",backgroundColor:ve,color:v,border:`1px solid ${K}`,borderRadius:f??8,fontSize:"0.95rem",fontWeight:600,fontFamily:h,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?c("span",{style:{margin:"0 auto"},children:`Connecting to ${Mr(e)}\u2026`}):Me(Br,{children:[Me("span",{style:{display:"inline-flex",alignItems:"center",gap:gc(e)?8:0},children:[A&&!u?c("img",{src:A,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"}}):B?.logoSvg?c("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:B.logoSvg}}):null,c("span",{children:Mr(e)})]}),a&&c("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:c("path",{d:"M9 18l6-6-6-6"})})]})})}function Ja({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:s,onErrorChange:C,onDecline:y,onCancel:f,runBeforeButtonClick:h,onButtonClick:B,isProcessing:A,submitButtonColor:u,submitButtonBorderRadius:S,submitButtonStyle:ve,errorText:K}){let v=fr(),{emitInstrument:ye}=Qr(An),Q=Za(),ce=Xa(),[de,we]=me(!1),Qe=be(!1),[he,Bt]=me(!1),[Xe,Ae]=me("loading"),[Fe,ee]=me(""),te=!Wt(r?.trim()),F=!te||Wt(Fe.trim()),Le=fe(async()=>{if(!Q||!ce||A||Qe.current||!he)return;Qe.current=!0,we(!0);let Ne=h?await h("card"):{proceed:!0};if(!Ne.proceed){Qe.current=!1,we(!1);return}B?.("card");let ze=Ne.sessionId??t,Ke=Ne.nonce??n,ke=kr(o?.trim()),T=ln({email:Ne.accountPatch?.email?.trim()||r?.trim()||Fe.trim(),firstName:Ne.accountPatch?.firstName?.trim()||ke.firstName,lastName:Ne.accountPatch?.lastName?.trim()||ke.lastName}),oe=T.email,Ue=ln({...Ne.accountPatch,...T});try{if(C?.(null),!Wt(oe))throw new Error("A valid email address is required for payment.");await a?.(T);let ae=await ce.submit();if(ae.error){C?.(ae.error.message??"Payment failed.");return}let V=[T.firstName,T.lastName].filter(Boolean).join(" "),Ee=await Q.createPaymentMethod({elements:ce,params:{billing_details:{email:oe,...V?{name:V}:{}}}});if(Ee.error||!Ee.paymentMethod){C?.(Ee.error?.message??"Failed to create payment method.");return}let nt=Ee.paymentMethod;if(!ze||!oe)throw new Error("Missing sessionId or email for payment.");let dt=nt.type||e,De=await da(l,ye,ze,Ke??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:dt,paymentMethodId:null,intentKind:"payment"});if(De.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let H=De.clientSecret;if(typeof window<"u")try{localStorage.setItem(Gn,JSON.stringify({clientSecret:H,sessionId:ze,nonce:Ke,accountPatch:Ue,paymentMethodId:nt.id,paymentMethodType:nt.type??e,gateway:"stripe"}))}catch{}let{error:U,paymentIntent:O}=await Q.confirmPayment({clientSecret:H,confirmParams:{return_url:window.location.href,payment_method:nt.id},redirect:"if_required"});if(U){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let k=U.message??"Payment failed.";C?.(k),y?.(Ut("card",k,{code:U.code})),await ua({billingApiUrl:l,sessionId:ze,nonce:Ke,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:U.code??"provider_declined"}});return}let Ie=O?.status;if(!Xo(Ie)){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let k=Ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";C?.(k),y?.(Ut("card",k,{code:Ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let Ye=typeof O?.payment_method=="string"?O.payment_method:O?.payment_method?.id;s({id:Ye??nt.id,type:"card",threeDSecureActionResultTokenId:O?.id,gateway:"stripe",paymentMethodType:nt.type??e},{accountPatch:Ue,sessionId:ze,nonce:Ke})}catch(ae){C?.(ae instanceof Error?ae.message:"Payment failed. Please try again.")}finally{Qe.current=!1,we(!1)}},[Q,ce,A,he,h,B,t,n,r,o,Fe,a,l,ye,e,s,C,y]);return Me("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[te&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:te&&Me("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:Fe,onChange:Ne=>ee(Ne.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(Rc,{onReady:()=>Ae("ready"),onLoadError:()=>{Ae("load_error"),Qa(qt(v),"stripe","apm")},onChange:Ne=>{Bt(!!Ne.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...Wt(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Le()},disabled:!he||!F||de||A||Xe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:S,fontSize:"1rem",fontWeight:600,cursor:!he||!F||de||A||Xe!=="ready"?"not-allowed":"pointer",opacity:!he||!F||de||A||Xe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ve??{}},children:de?"Processing\u2026":`Pay with ${Mr(e)}`}),K&&c(Gr,{margin:"0.75rem 0 0",children:K})]})}function Fs({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:s,paymentElementBaseOptions:C,onTokenizedBody:y,onErrorChange:f,onButtonClick:h,onDecline:B,runBeforeButtonClick:A,onLoadStateChange:u,isProcessing:S=!1,submitButtonColor:ve="#4A49FF",submitButtonBorderRadius:K=8,submitButtonStyle:v,buttonAppearance:ye,themeId:Q,onExpandApm:ce,expandedApmMethod:de}){let{emitInstrument:we}=Qr(An),[Qe,he]=me(null),[Bt,Xe]=me(null),Ae=be(!1),{request:Fe,collect:ee,finish:te}=Vr();vt(()=>{l.length>0&&s?u?.("ready"):s||u?.("loading")},[l.length,s,u]);let F=fe(async T=>{if(!s||Ae.current||S)return;Ae.current=!0,Xe(T);let oe=A?await A("card"):{proceed:!0};if(!oe.proceed){Ae.current=!1,Xe(null);return}h?.("card");let Ue=oe.sessionId??e,ae=oe.nonce??t,V=kr([oe.accountPatch?.firstName,oe.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ee=ln({email:oe.accountPatch?.email?.trim()||n?.trim(),firstName:oe.accountPatch?.firstName?.trim()||V.firstName,lastName:oe.accountPatch?.lastName?.trim()||V.lastName});if(!Wt(Ee.email)){Xe(null);let De=await ee(Mr(T),Ee);if(!De){Ae.current=!1;return}Ee=De,Xe(T)}let nt=Ee.email,dt=ln({...oe.accountPatch,...Ee});try{if(f?.(null),!Ue||!Wt(nt))throw new Error("Missing sessionId or email for payment.");await o?.(Ee);let De=await da(a,we,Ue,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(De.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let H=De.clientSecret;if(typeof window<"u")try{localStorage.setItem(Gn,JSON.stringify({clientSecret:H,sessionId:Ue,nonce:ae,accountPatch:dt,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:U,paymentIntent:O}=await s.confirmPayment({clientSecret:H,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[Ee.firstName,Ee.lastName].filter(Boolean).join(" "),...nt?{email:nt}:{}}}},redirect:"if_required"});if(U){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let k=U.message??"Payment failed.";f?.(k),B?.(Ut("card",k,{code:U.code})),await ua({billingApiUrl:a,sessionId:Ue,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:U.code??"provider_declined"}});return}let Ie=O?.status;if(!Xo(Ie)){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let k=Ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(k),B?.(Ut("card",k,{code:Ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let Ye=typeof O?.payment_method=="string"?O.payment_method:O?.payment_method?.id;y({id:Ye??O?.id,type:"card",threeDSecureActionResultTokenId:O?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:dt,sessionId:Ue,nonce:ae})}catch(De){f?.(De instanceof Error?De.message:"Payment failed. Please try again.")}finally{Ae.current=!1,Xe(null)}},[s,S,A,h,e,t,n,ee,a,we,r,o,y,f,B]),[Le,Ne]=me(null),ze=ce?de??null:Le,Ke=fe(T=>{Ae.current||S||ze&&ze!==T||(Is(T)?ce?ce(T):Ne(T):F(T))},[ze,S,F,ce]),ke=mt(()=>Le?{...C,paymentMethodTypes:[Le]}:null,[Le,C]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Fe?c(Hr,{identity:Fe.identity,methodLabel:Fe.methodLabel,onComplete:te,onCancel:()=>te(null)},Fe.id):l.map(T=>{let oe=de===T,Ue=Bt===T,ae=Bt!==null&&Bt!==T||de!=null&&de!==T;return Me(Ec.Fragment,{children:[c(zc,{method:T,themeId:Q,submitting:Ue,disabled:ae,highlighted:oe,hasNextStep:Is(T),onClick:()=>Ke(T),backgroundColor:ye?.backgroundColor,borderColor:ye?.borderColor,textColor:ye?.textColor,borderRadius:ye?.borderRadius,fontFamily:ye?.fontFamily}),!ce&&Le===T&&ke&&s&&c(xr,{stripe:s,options:ke,children:c(Ja,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:y,onErrorChange:f,onDecline:B,onCancel:()=>Ne(null),runBeforeButtonClick:A,onButtonClick:h,isProcessing:S,submitButtonColor:ve,submitButtonBorderRadius:K,submitButtonStyle:v})},T)]},T)})})}function Uc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:s,onTokenizedBody:C,firstName:y,lastName:f,chv:h,className:B,isProcessing:A,error:u,onErrorChange:S,showPayPal:ve=!0,showStripe:K=!0,enabledPaymentMethods:v,enabledPaymentMethodCountries:ye,showApplePay:Q=!0,showGooglePay:ce=!0,layout:de="default",theme:we,buttonsTheme:Qe,buttonsStyles:he,appearance:Bt,cardButtonContent:Xe,cardBackButtonContent:Ae,cardTitleContent:Fe,showSecurityFooter:ee,onButtonClick:te,onBeforeButtonClick:F,onBuyerIdentityReady:Le,enableAVS:Ne,cardFieldOrder:ze,cardPreFormSlot:Ke,avsLayout:ke="row",country:T,zip:oe,addressLine1:Ue,addressLine2:ae,city:V,state:Ee,onCountryChange:nt,onZipChange:dt,avsCheck:De,checkoutType:H,checkoutLayout:U,totalAmount:O=0,currency:Ie="usd",initialCardOpen:Ye=!1,directPaypal:k,isSubscription:Y=!1,session:E,dataAttachmentPending:b=!1,dataAttachmentRequiresIdentity:it=!1,debug:Pt=!1}){let G=fr(),st=Da(),Ze=Qr(qn),{emitInstrument:Ct}=Qr(An),wt=b||Ze.claimPending===!0,g=it||Ze.claimRequiresIdentity===!0,$=wt&&!g,lt=ss(),[yt,ie]=me(!1),[kt,ot]=me(null),[qe,Nt]=me(T??"US"),[Kt,Gt]=me(oe??""),[Dn,rn]=me(Ue??""),[jn,cn]=me(ae??""),[Cn,on]=me(V??""),[Ot,Sn]=me(Ee??""),[et,sr]=me(""),[rt,Ln]=me({}),ft=be(oe??""),Vt=be(T??"US"),dn=be(Ue??""),wn=be(ae??""),kn=be(V??""),Zt=be(Ee??""),Qn=be(""),Mt=be({});vt(()=>{let i=(w,N,Be,z,Re)=>{if(Mt.current[w])return;let je=N?.trim();!je||je===Be.current||(Be.current=je,z(je),Re?.(je))};i("country",T,Vt,Nt,nt),i("zip",oe,ft,Gt,dt),i("addressLine1",Ue,dn,rn),i("addressLine2",ae,wn,cn),i("city",V,kn,on),i("state",Ee,Zt,Sn)},[T,oe,Ue,ae,V,Ee,nt,dt]);let X=mt(()=>Sc(Ne),[Ne]),er=X!==null,un=mt(()=>Va(E),[E]),pn=!!E?.vault?.html,lr=!!E?.gateways?.pcivault,tr=!!(E?.gateways?.stripe?.enabledPaymentMethods??v)?.includes("card"),Qt=pn||tr||lr,Ve=!!(K&&Qt&&G&&e),[In,I]=me(()=>de!=="buttons"||Ye?e??null:null),[Dt,It]=me(0),Rt=de!=="buttons"||Ye||!!e&&In===e,se=mt(()=>!G||!Ve||!e||!Rt?null:G.cardCapture({sessionId:e,captureMethod:E?.captureMethod}),[G,Ve,e,Rt,E?.captureMethod]),Jt=mt(()=>{let i=qe,w=X?He(X.postal_code,i):!1;return Lc(i,Kt,w)},[X,qe,Kt]),{avsInvalid:cr,invalidAvsFields:dr}=mt(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Ve||!X)return{avsInvalid:!1,invalidAvsFields:i};let w=qe,N=(Re,je)=>He(Re,w)&&!je.trim(),Be={line1:N(X.address_line_1,Dn),city:N(X.city,Cn),state:N(X.state,Ot),zip:Jt.empty||Jt.malformed};return{avsInvalid:Be.line1||Be.city||Be.state||Be.zip,invalidAvsFields:Be}},[Ve,X,qe,Dn,Cn,Ot,Jt]),[nr,Pr]=me(!1),[Rn,Cr]=me(!1),[Vn,mn]=me(!1),[At,an]=me({line1:!1,city:!1,state:!1}),en=be(!1),En=be({email:!1,line1:!1,city:!1,state:!1,zip:!1}),yn=be(!1),at=fe(i=>{En.current[i]=!0,yn.current=!0},[]),fn=fe(i=>!en.current&&En.current[i],[]),gn=fe(i=>{fn(i)&&an(w=>w[i]?w:{...w,[i]:!0})},[fn]),[hn,bn]=me(()=>Ha(E?.vault)),[_e,Xt]=me(Ye&&Qt?"card":"buttons"),[Ft,ur]=me(null),Nn=_e==="expanding"||_e==="card",pr=E?.gateways?.stripe?"stripe":void 0,On=fe(()=>{Ct?.({class:"card_surface",provider:pr})},[pr,Ct]),vn=be(null),zt=fe(i=>{vn.current&&clearTimeout(vn.current),vn.current=setTimeout(()=>{vn.current=null,i()},Tr)},[]);vt(()=>()=>{vn.current&&clearTimeout(vn.current)},[]);let Fr=fe(()=>{On(),I(e??null),It(i=>i+1),Xt("expanding"),zt(()=>Xt("card"))},[zt,On,e]),_n=fe(()=>{Xt("collapsing"),zt(()=>Xt("buttons"))},[zt]),x=fe(i=>{ur(i),Xt("apm-expanding"),zt(()=>Xt("apm-form"))},[zt]),M=fe(()=>{Xt("apm-collapsing"),zt(()=>{Xt("buttons"),ur(null)})},[zt]);vt(()=>{de==="buttons"&&Ye&&Qt&&(I(e??null),Xt("card"))},[de,Ye,Qt,e]);let[j,R]=me(null),Oe=be(!1),W=be(null),_=be("idle"),[m,re]=me(null),ne=be(m);vt(()=>{ne.current=m},[m]);let Te=n||lt,We=be(null),xe=mt(()=>{if(Le||Ze.claimBuyerIdentity||E?.buyerIdentified!==!1||!e||!t)return;let i=`${Te}|${e}|${t}`;We.current?.key!==i&&(We.current={key:i,claim:jr(new Zr(Te,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...f?{lastName:f}:{}})});let w=We.current.claim;return async N=>{await w(N)}},[Le,Ze.claimBuyerIdentity,E?.buyerIdentified,e,t,Te,o,y,f]),Pe=Le??Ze.claimBuyerIdentity??xe,P=u??kt,p=mt(()=>Ic(we),[we]),d=mt(()=>{let i=p?.buttonsLayout??wc(Qe);return he?{...i,...he,cardButton:{...i.cardButton,...he.cardButton},cardFormContainer:{...i.cardFormContainer,...he.cardFormContainer},backButton:{...i.backButton,...he.backButton},backButtonIcon:{...i.backButtonIcon,...he.backButtonIcon},submitButton:{...i.submitButton,...he.submitButton},title:{...i.title,...he.title}}:i},[p,Qe,he]),q=Bt??p?.appearance,ge=mt(()=>Gi({appearance:q,buttonsStyles:d,layout:de}),[q,d,de]),le=Ze.inlineSessionPatchProcessing??!1,J=(A??yt)||le,Ce=Te.replace(/\/+$/,""),D=mt(()=>Fa({userId:o,email:r,firstName:y,lastName:f,country:T,zip:oe},rt),[o,r,y,f,T,oe,rt]),L=[D.firstName,D.lastName].filter(i=>!!i?.trim()).join(" "),ue=!Wt(D.email?.trim()),Se=be(null);Ve&&Se.current===null&&(Se.current=ue);let ut=Ve&&(Se.current??ue),$e=mt(()=>Nc(et,ut),[et,ut]),Lt=$e.empty||$e.malformed,Pn=mt(()=>G?G.getRawProvider():null,[G]),Dr=mt(()=>st?st.getRawProvider():null,[st]),oo=O||100,Lo=mt(()=>q?dc(q):null,[q]),No=Lo?{appearance:Lo}:null,gi=mt(()=>{let i=Lo??{},w=i.rules??{};return{...i,rules:{...w,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...w[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...w[".AccordionItemContents"]??{}}}}},[Lo]),hi=mt(()=>{let i=ts(O);return{...i,currency:Ie.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...No}},[O,Ie,No]),bi=mt(()=>({mode:"payment",amount:oo,currency:Ie.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...No}),[oo,Ie,No]),pe=fe(i=>{ot(i),S?.(i)},[S]),ga=be(""),[vi,Zs]=me(!1),ha=fe(()=>{Zs(!0)},[]);vt(()=>{if(!Ve||!ut||!Pe||!vi||Lt||ga.current)return;let i=ln({email:Wt(D.email?.trim())?D.email?.trim():Qn.current.trim(),firstName:D.firstName?.trim(),lastName:D.lastName?.trim()});ga.current=JSON.stringify(i),Ln(w=>({...w,...i})),Promise.resolve(Pe(i)).catch(w=>{ga.current="",pe(w instanceof Error?w.message:"Failed to attach buyer details.")})},[Ve,ut,Pe,vi,Lt,D.email,D.firstName,D.lastName,pe]),vt(()=>{!Ve||!se||se.setCardFieldOrder?.(ze??null,X==null&&!ut)},[Ve,se,ze,X,ut]),vt(()=>{(_e==="expanding"||_e==="collapsing"||_e==="apm-expanding"||_e==="apm-collapsing")&&pe(null)},[_e,pe]);let zn=fe((i,w,N)=>{s?.(Ut(i,w,N))},[s]),Lr=fe((i,w,N)=>{let Be=N?.popupBlocked??yr(w),z=Fc(i,Be),Re=Rr(N?.code)??rr(w)??"external_payment_method_failed",je=new $n(z,"api_error",{code:"external_payment_method_failed",param:i});R(null),de==="buttons"&&(Xt("buttons"),ur(null)),pe(z),l?.(je),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:Be})},[de,l,pe]);vt(()=>{if(!Ve||!e){bn(null);return}let i=Ha(E?.vault);if(i){bn(i);return}if(!Rt){bn(null);return}bn(null);let w=!0;return new Zr(Ce).getVaultCapture(e,t).then(N=>{if(!w)return;let Be=Ha(N);Be?bn(Be):pe("Failed to load the secure card form.")}).catch(N=>{w&&pe(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{w=!1}},[Ve,Rt,Dt,e,E?.vault,Ce,t,pe]);let Hn=be({onComplete:a,onError:l,updateError:pe,emitDecline:zn,resolvedAccount:D,avsConfig:X,avsCheckProp:De,sessionId:e,nonce:t,baseUrl:Ce,captureMethod:E?.captureMethod,paymentId:E?.paymentId,authorizationExpiresAt:E?.authorizationExpiresAt});Hn.current={onComplete:a,onError:l,updateError:pe,emitDecline:zn,resolvedAccount:D,avsConfig:X,avsCheckProp:De,sessionId:e,nonce:t,baseUrl:Ce,captureMethod:E?.captureMethod,paymentId:E?.paymentId,authorizationExpiresAt:E?.authorizationExpiresAt};let ba=be(!1),Pi=fe(()=>{let{resolvedAccount:i,avsConfig:w,avsCheckProp:N}=Hn.current,Be=i.email?.trim(),z=Wt(Be)?Be:Qn.current.trim();if(!Wt(z))return null;let Re=i.firstName?.trim(),je=i.lastName?.trim(),ct=Vt.current||i.country||"US",Ht=w?He(w.state,ct):!1,gt=w?He(w.address_line_1,ct):!1,ht=w?He(w.postal_code,ct):!1,tt=w?He(w.city,ct):!1,tn=w?He(w.address_line_2,ct):!1,Ge=gt&&!Ht&&ht?ks(ct,(ft.current??"").trim()):null,nn=Ht?Zt.current:Ge;return{accountData:{userId:i.userId??"",email:z,...Re?{firstName:Re}:{},...je?{lastName:je}:{},...ht&&ft.current?{zip:ft.current}:{},...tt&&kn.current?{city:kn.current}:{},...nn?{state:nn}:{},...gt&&dn.current?{addressLine1:dn.current}:{},...tn&&wn.current?{addressLine2:wn.current}:{},country:ct},...N!==void 0?{avsCheck:N}:{},...w?{avsConfig:{country:He(w.country,ct),postal_code:ht,address_line_1:gt,address_line_2:tn,city:tt,state:Ht}}:{}}},[]),Ci=be(wt);Ci.current=wt,vt(()=>{wt||P!==_s||Hn.current.updateError(null)},[wt,P]),vt(()=>{!Ve||!se||se.setSubmitGate?.(cr||wt||Lt)},[Ve,se,cr,wt,Lt]),vt(()=>{if(!Ve||!se)return;ba.current=!1;let i=!1,w=se.on("submitting",()=>{Pr(!0),W.current&&clearTimeout(W.current),_.current="validation-window",W.current=setTimeout(()=>{W.current=null,_.current==="validation-window"&&(_.current="processing")},_c),R("processing");let{baseUrl:je,sessionId:ct,nonce:Ht,updateError:gt,onError:ht}=Hn.current;if(!ct||!Ht)return;let tt=Pi();if(!tt){gt("Enter a valid email address."),_.current="idle",R(null);return}new Zr(je).patchAccountSnapshot(ct,Ht,tt,{telemetryMode:"best_effort"}).catch(tn=>{if(!Tc(tn))return;let Ge=tn instanceof Error?tn.message:"Please check your billing address and try again.";gt(Ge),_.current="idle",R(null),ht?.(tn instanceof $n?tn:new $n(Ge,"api_error"))})}),N=se.on("complete",async je=>{if(Jr(je.sessionId??Hn.current.sessionId),_.current="terminal",R("success"),await new Promise(gt=>setTimeout(gt,1200)),ba.current)return;ba.current=!0;let ct=Hn.current,Ht=Va(ct)||je.outcome==="authorized";Hn.current.onComplete?.(Ht?{status:"authorized",paymentIntentId:je.intentId,paymentId:je.paymentId??ct.paymentId,sessionId:je.sessionId??ct.sessionId,authorizationExpiresAt:je.authorizationExpiresAt??ct.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:je.intentId,checkoutMethod:"card"})}),Be=se.on("decline",async je=>{let{updateError:ct,emitDecline:Ht}=Hn.current,gt=je.message??"Your payment was declined. Please try another card or contact your bank.";_.current="terminal",ct(gt),R("error");let ht=je.failureOutcome??Pc(je.declineReason)??"authorization_declined";Ht("card",gt,{code:ht,declineCode:ht}),await new Promise(tt=>setTimeout(tt,1500)),!i&&(_.current="idle",R(null))}),z=se.on("error",async je=>{let{updateError:ct,onError:Ht}=Hn.current,gt=je.message??"There was a problem processing your payment. Please try again.";_.current="terminal",ct(gt),R("error"),Ht?.(new $n(gt,"api_error",{code:je.failureOutcome??"capture_failed"})),await new Promise(ht=>setTimeout(ht,1500)),!i&&(_.current="idle",R(null))}),Re=se.on("blocked",()=>{if(!Ci.current){Pr(!0);return}ha(),Hn.current.updateError(_s)});return()=>{i=!0,W.current&&(clearTimeout(W.current),W.current=null),_.current="idle",w(),N(),Be(),z(),Re()}},[Ve,se,ha,Pi]);let Yn=!!k?.clientId,ao=Array.isArray(v),Oo=ao&&v.length>0,Qs=ao&&v.includes("paypal"),{expressMethods:zo,paymentElementMethods:io}=mt(()=>Cc(v,{excludePaypal:Yn}),[v,Yn]),Si=Yn||!!st,el=mt(()=>Si?zo.filter(i=>i!=="paypal"):zo,[zo,Si]),tl=mt(()=>{let i=[];return Q&&i.push("apple_pay"),ce&&i.push("google_pay"),i},[Q,ce]),Uo=ao?el:tl,nl=K&&Uo.length>0,va=er?qe:T,qo=mt(()=>{let i=va?.trim().toUpperCase();return i?ye?io.filter(w=>{let N=ye[w];return!N||N.length===0||N.includes(i)}):mc(io,va):io},[io,va,ye]),Pa=mt(()=>({mode:"payment",amount:oo,currency:Ie.toLowerCase(),paymentMethodCreation:"manual",appearance:gi}),[oo,Ie,gi]),[wi,ki]=me("loading"),[Ii,Ri]=me("loading"),[Ei,_i]=me("loading"),[rl,Ca]=me(!1),[Ti,Sa]=me("loading"),[$o,ol]=me();vt(()=>{ol(Ss())},[]);let xi=ve&&(Yn||(ao?Qs:$o===!1)),Bi=K&&nl,so=!$&&xi&&Yn,Mi=Ti==="retrying"||Ti==="exhausted",lo=!$&&xi&&!!Dr&&(!Yn||Mi),co=!$&&Bi&&!!Pn,uo=!$&&K&&Oo&&qo.length>0&&!!Pn,al=so&&!Mi?rl:lo&&Bs(wi),il=co&&Bs(Ii),sl=uo&&Ei!=="load_error",Ai=i=>i==="loading"||i==="ready",Fi=so||lo&&Ai(wi)||co&&Ai(Ii)||uo&&Ei!=="load_error",jo=be(!1);vt(()=>{if(!jo.current){if(!K&&!ve){jo.current=!0;let i=new $n("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),pe(i.message)}else if(!K&&ve&&!Yn&&!Dr){jo.current=!0;let i=new $n("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(i),pe(i.message)}else if($o!==void 0&&!$&&!Qt&&!Fi){jo.current=!0;let i=new $n("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"});l?.(i),pe(i.message)}}},[K,ve,Yn,Dr,$o,$,Qt,Fi,l,pe]);let Di=be(!1);vt(()=>{if(Di.current||!Oo)return;let i=[];Q!==!0&&i.push("showApplePay"),ce!==!0&&i.push("showGooglePay"),i.length!==0&&(Di.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.`))},[Oo,Q,ce]);let Li=fe((i,w)=>Ze.applyInlineSessionPatch?Ze.applyInlineSessionPatch(i).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let Be=xs(w,N);return pe(Be.message),l?.(Be),{error:Be,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ze.applyInlineSessionPatch,t,l,e,pe]),Un=fe(async i=>{if(!F)return{proceed:!0};try{let w=await F({method:i,sessionId:e||void 0,createSession:Ze.inlineSessionDraft});if(w===!1)return{proceed:!1};if(w&&typeof w=="object"){w.account&&Ln(Be=>({...Be??{},...w.account}));let N=await Li(w,i);return N.error?{proceed:!1,accountPatch:w.account}:{proceed:!0,accountPatch:w.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(w){let N=xs(i,w);return pe(N.message),l?.(N),{proceed:!1}}},[Li,Ze.inlineSessionDraft,F,l,e,pe]),Ni=fe(async(i,w)=>{if(Oe.current)return;Oe.current=!0,ie(!0),R("processing"),pe(null);let N=w?.sessionId??e,Be=w?.nonce??t,z=Fa(D,w?.accountPatch),Re=w?.completionPaymentMethodId??Po(i),je=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,ct=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Ht=()=>{Ct?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ct})};try{let ht=await new Zr(Ce).processPayment(z.userId??"",{sessionId:N,nonce:Be,tokenizedData:je,accountData:{userId:z.userId??"",email:z.email??"",...z.firstName?{firstName:z.firstName}:{},...z.lastName?{lastName:z.lastName}:{},...X?(()=>{let Ge=Vt.current,nn=He(X.state,Ge),Bn=He(X.address_line_1,Ge),Yt=He(X.postal_code,Ge),go=Bn&&!nn&&Yt?ks(Ge,(ft.current??"").trim()):null,ho=nn?Zt.current:go;return{country:Ge,...Yt&&ft.current?{zip:ft.current}:{},...He(X.city,Ge)&&kn.current?{city:kn.current}:{},...ho?{state:ho}:{},...Bn&&dn.current?{addressLine1:dn.current}:{},...He(X.address_line_2,Ge)&&wn.current?{addressLine2:wn.current}:{}}})():{}},chv:h,avsCheck:De??!1,checkoutType:H,checkoutLayout:U,avsConfig:X?{country:He(X.country,Vt.current),postal_code:He(X.postal_code,Vt.current),address_line_1:He(X.address_line_1,Vt.current),address_line_2:He(X.address_line_2,Vt.current),city:He(X.city,Vt.current),state:He(X.state,Vt.current)}:void 0});if(ht.ok){let Ge=ht.status===204?null:await ht.json().catch(()=>null),nn=Va(E)||Ge?.status==="authorized";Jr(N),R("success"),re(null),await new Promise(Bn=>setTimeout(Bn,1200)),a?.(nn?{status:"authorized",...typeof Ge?.paymentId=="string"?{paymentId:Ge.paymentId}:E?.paymentId?{paymentId:E.paymentId}:{},sessionId:typeof Ge?.sessionId=="string"?Ge.sessionId:N,...typeof Ge?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Ge.authorizationExpiresAt}:E?.authorizationExpiresAt?{authorizationExpiresAt:E.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 tt=await ht.json().catch(()=>null);if(tt?.type==="paypal_redirect_required"){let Ge=tt.threeDSecureToken,nn=tt.paymentMethodId||i.id||"";if(!G||!Ge){R("error"),pe("PayPal authorization required but no token provided.");return}try{let Bn=st?.getRawProvider();if(!Bn){pe("PayPal is not available.");return}let Yt={return_url:window.location.href};nn&&(Yt.payment_method=nn);let{error:go}=await Bn.confirmPayment({clientSecret:Ge,confirmParams:Yt,redirect:"if_required"});if(go){R("error");let ho=go.message??"PayPal payment failed.";pe(ho),zn("paypal",ho,{code:go.code})}}catch(Bn){R("error"),pe(Bn instanceof Error?Bn.message:"PayPal authorization failed.")}return}if(tt?.type==="paypal_direct_required"){let Ge=tt.orderId;if(!Ge){R("error"),pe("PayPal retry required but no order id provided.");return}let nn=ne.current?.attempts??0;if(nn>=2){R("error"),pe("PayPal payment could not be completed after multiple attempts."),zn("paypal","paypal_direct_required retry limit exceeded");return}Ca(!1),Sa("loading"),re({orderId:Ge,attempts:nn+1}),R(null);return}pc(ht.status,tt)||Ht(),R("error");let tn=tt?.message??"Payment failed. Please try again.";pe(tn),zn(i.isPaypal?"paypal":"card",tn,{code:tt?.code??tt?.gatewayErrorCode,declineCode:tt?.declineCode??tt?.gatewayDeclineReason}),await new Promise(Ge=>setTimeout(Ge,1500))}catch(gt){Ls(gt)||Ht(),R("error"),pe(gt instanceof Error?gt.message:"An unexpected error occurred"),await new Promise(ht=>setTimeout(ht,1500))}finally{ie(!1),R(null),Oe.current=!1}},[Ce,e,t,D,X,De,H,U,h,G,st,E,a,pe,zn,Ct]),Tn=fe((i,w)=>{C?C(i):Ni(i,w)},[C,Ni]),Oi=be(!1);vt(()=>{if(typeof window>"u"||Oi.current)return;let i=new URLSearchParams(window.location.search),w=i.get("payment_intent"),N=i.get("payment_intent_client_secret"),Be=i.get("redirect_status");if(!w||!N)return;let z=ht=>{let tt=localStorage.getItem(ht);if(!tt)return null;try{return JSON.parse(tt)}catch{return localStorage.removeItem(ht),null}},Re=z(Gn)??z(Es),je;if(Re?.clientSecret){if(Re.clientSecret!==N)return;je={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;Oi.current=!0,localStorage.removeItem(Gn),localStorage.removeItem(Es);let ct=new URL(window.location.href);ct.searchParams.delete("payment_intent"),ct.searchParams.delete("payment_intent_client_secret"),ct.searchParams.delete("redirect_status"),window.history.replaceState({},"",ct.toString());let Ht=Re?.paymentMethodType??Re?.tokenType??"card",gt="card";(async()=>{let ht=G?.getRawProvider();if(!ht){let Yt="Payment is not available \u2014 please refresh and try again.";pe(Yt),zn(gt,Yt);return}if(Be==="failed"){let Yt="Payment was declined. Please try again.";pe(Yt),zn(gt,Yt);return}let{paymentIntent:tt,error:tn}=await ht.retrievePaymentIntent(N);if(tn){let Yt=tn.message??"Failed to retrieve payment status.";pe(Yt),zn(gt,Yt,{code:tn.code});return}let Ge=tt?.status,nn=Xo(Ge);if(!tt||!nn){let Yt=Ge==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";pe(Yt),zn(gt,Yt,{code:Ge??"missing_payment_intent"});return}let Bn=typeof tt.payment_method=="string"?tt.payment_method:tt.payment_method?.id;Tn({id:Bn??Re?.paymentMethodId??Re?.tokenId??tt.id,type:"card",threeDSecureActionResultTokenId:tt.id,gateway:Re?.gateway??"stripe",paymentMethodType:Ht},je)})()},[e,Tn,G,pe,zn]);let wa=fe(i=>{i.preventDefault()},[]);if(!(G!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let po=de==="buttons",sn=q?.variables,ll=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ka=sn?.colorBackground,cl=ka&&!ll.has(ka)?ka:void 0,mo=d.cardInputBorder??(po?"#e5e7eb":"#A4A4FF"),zi=sn?.colorDanger??"#dc2626",St=i=>dr[i]&&(At[i]||nr),Ko=Lt&&(Vn||nr),xn=i=>i?zi:mo,Vo=(Jt.malformed||Jt.empty)&&(Rn||nr),dl=xn(Vo),Ia=d.cardFormContainer?.backgroundColor??cl??(po?"white":"#EDEDFF"),Nr=d.cardInputBackground??sn?.colorBackground??"white",Ra=zr(Ae),Ui=zr(Fe),Or=d.nameInput,qi=d.cardInputFontSize??Oc(Or?.fontSize)??sn?.fontSizeBase??"16px",$i=typeof Or?.fontFamily=="string"?Or.fontFamily:sn?.fontFamily??"Poppins, sans-serif",ji=Wi(Or?.fontWeight)??400,ul=d.cardInputColor??(typeof Or?.color=="string"?Or.color:void 0)??sn?.colorText??"#262833",pl=d.cardInputPlaceholderColor??"#9ca3af",Et=sn?.borderRadius??"8px",Sr=sn?.borderRadius??d.cardButton?.borderRadius??Et,wr=sn?.colorPrimary??"#4A49FF",ml=sn?.colorPrimaryHover??bo(wr,.12),Ea=sn?.colorText??"#262833",_a={fontSize:qi,fontFamily:$i,fontWeight:ji,color:ul,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},yo={marginTop:"0.375rem",..._a,fontSize:"0.75rem",lineHeight:1.4,color:zi},yl={"--flopay-input-placeholder-color":pl,"--flopay-input-font-size":qi,"--flopay-input-font-family":$i,"--flopay-input-font-weight":String(ji)},fo=d.cardFormContainer??{},Ta=fo.padding??(po?"0":"1rem"),xa=fo.borderRadius??Et,fl=se&&hn?c(Ba,{capture:se,html:hn.html,messageToken:hn.messageToken,expectedOrigin:hn.expectedOrigin,theme:ge,onReady:()=>{if(!ut&&!X||typeof document>"u")return;let i=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){en.current=!0;try{N.focus()}finally{en.current=!1}}};yn.current||i()},onError:i=>pe(i),onValidation:i=>{let w=_.current;(w==="idle"||w==="validation-window")&&(pe(i),i&&_.current==="validation-window"&&(W.current&&(clearTimeout(W.current),W.current=null),_.current="idle",R(null)))}}):c("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"}),Ki=Me("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&On()},style:{backgroundColor:Ia,borderRadius:xa,...fo,padding:Ta,...yl,display:"flex",flexDirection:"column"},children:[c("style",{children:`
|
|
26
26
|
.flopay-shared-input::placeholder {
|
|
27
27
|
color: var(--flopay-input-placeholder-color);
|
|
28
28
|
opacity: 1;
|
|
@@ -30,13 +30,13 @@ ${h.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,Hi=De==="apm-expanding"||De==="apm-form"||De==="apm-collapsing",$o=De==="apm-expanding"?`flopay-card-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:De==="apm-collapsing"?`flopay-card-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,jo=Et?{...va,paymentMethodTypes:[Et]}:null;if(ce==="buttons"){let o=De==="buttons"||De==="expanding"||De==="apm-expanding",k=De==="expanding"||De==="card"||De==="collapsing",N=Ne===void 0?{boxSizing:"border-box",height:ia,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ie=De==="expanding"||De==="apm-expanding"?`flopay-buttons-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:De==="collapsing"||De==="apm-collapsing"?`flopay-buttons-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,q=De==="expanding"?`flopay-card-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:De==="collapsing"?`flopay-card-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Re("form",{onSubmit:Sa,className:B,noValidate:!0,style:{position:"relative"},children:[u(Ha,{}),Se&&u(jn,{status:Se,errorMessage:v,authorized:yn}),Re("div",{style:{display:"grid"},children:[Re("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!o&&!Ie?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!o&&!Ie?Ac:{},...Ie?{animation:Ie,pointerEvents:"none"}:{}},children:[Ki("flopay-direct-paypal-gate-debug"),Vi("flopay-stripe-gate-debug"),ao&&E&&Re(Tr,{children:[R&&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(Qo,{sessionId:e,nonce:t,billingApiUrl:j,email:ue.email,billingName:cn||void 0,onBuyerIdentityReady:A,clientId:E.clientId,environment:E.environment,currency:Ce.toUpperCase(),isSubscription:W,providerObjectType:E.providerObjectType,onTokenizedBody:Cn,onComplete:i,onErrorChange:de,onDecline:s,onTechnicalFailure:Fr,onButtonClick:oe,runBeforeButtonClick:Fn,isProcessing:it,onLoadStateChange:Pa,onInitializationStateChange:Ca,session:T??null,existingOrderId:R?.orderId,debug:ft},R?.orderId??"fresh")]}),io&&u(_r,{stripe:Mr,options:bi,children:u(Bs,{sessionId:e,nonce:t,email:ue.email,billingName:cn||void 0,onBuyerIdentityReady:A,billingApiUrl:j,onTokenizedBody:Cn,onErrorChange:de,isProcessing:it,onButtonClick:oe,onDecline:s,onTechnicalFailure:Fr,runBeforeButtonClick:Fn,onLoadStateChange:wi,placeholderBorderRadius:Pr})}),so?u(_r,{stripe:Pn,options:hi,children:u(As,{sessionId:e,nonce:t,email:ue.email,billingName:cn||void 0,onBuyerIdentityReady:A,billingApiUrl:j,intentKind:O>0?"payment":"setup",expressMethods:Do,onTokenizedBody:Cn,onErrorChange:de,onButtonClick:oe,onDecline:s,onTechnicalFailure:Fr,runBeforeButtonClick:Fn,onLoadStateChange:Ii,placeholderBorderRadius:Pr})}):xi?u("div",{style:{height:ia,borderRadius:Pr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,lo&&u(Ms,{sessionId:e,nonce:t,email:ue.email,billingName:[ue.firstName,ue.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:A,billingApiUrl:j,paymentElementMethods:Lo,stripeInstance:Pn,paymentElementBaseOptions:va,onTokenizedBody:Cn,onErrorChange:de,onButtonClick:oe,onDecline:s,runBeforeButtonClick:Fn,onLoadStateChange:Ei,isProcessing:it,submitButtonColor:Cr,submitButtonBorderRadius:kt,submitButtonStyle:_.submitButton,onExpandApm:z,expandedApmMethod:Et,themeId:ve,buttonAppearance:{backgroundColor:_.cardButton?.backgroundColor,borderColor:_.cardInputBorder,textColor:_.cardButton?.color,borderRadius:Pr}}),y&&u("button",{type:"button",onClick:async()=>{it||!(await Fn("card")).proceed||(oe?.("card"),M())},disabled:it,style:{width:"100%",...N,..._.cardButton,...Qa({themeBundle:U,resolvedPrimaryColor:Cr,resolvedBorderRadius:kt,submitButtonStyle:_.submitButton,explicitPrimaryColor:rn?.colorPrimary}),fontSize:_.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:it?"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:it?.6:1},onMouseEnter:we=>{!it&&(U||rn?.colorPrimary)&&(we.currentTarget.style.backgroundColor=ml)},onMouseLeave:we=>{(U||rn?.colorPrimary)&&(we.currentTarget.style.backgroundColor=Cr)},onMouseDown:we=>{we.currentTarget.style.transform="scale(0.985)"},onMouseUp:we=>{we.currentTarget.style.transform="scale(1)"},children:u(Or,{content:Ne})}),v&&De==="buttons"&&u(Yr,{margin:"0.25rem 0",styleOverride:_.errorBanner,children:v})]}),y&&k&&u("div",{style:{gridArea:"1 / 1",...q?{animation:q}:{},...De==="collapsing"?{pointerEvents:"none"}:{}},children:ji}),V&&Hi&&Et&&jo&&Pn&&u("div",{style:{gridArea:"1 / 1",...$o?{animation:$o}:{},...De==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Re("div",{style:{backgroundColor:ka,borderRadius:Ta,...mo,padding:_a},children:[Re("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Re("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:X,style:{display:"inline-flex",alignItems:"center",gap:Ia?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:_.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,..._.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",..._.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(zr,{content:Ee})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:_.titleFontSize??"1.05rem",color:Ra,paddingRight:80,..._.title},children:`Pay with ${xr(Et)}`})]}),u(_r,{stripe:Pn,options:jo,children:u(Wa,{method:Et,sessionId:e,nonce:t,email:ue.email,billingName:[ue.firstName,ue.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:A,billingApiUrl:j,onTokenizedBody:Cn,onErrorChange:de,onDecline:s,onCancel:X,runBeforeButtonClick:Fn,onButtonClick:oe,isProcessing:it,submitButtonColor:Cr,submitButtonBorderRadius:kt,submitButtonStyle:_.submitButton,errorText:v})},Et)]})})]})]})}return Hi&&Et&&jo&&Pn&&V?Re("form",{onSubmit:Sa,className:B,noValidate:!0,style:{position:"relative"},children:[u(Ha,{}),Se&&u(jn,{status:Se,errorMessage:v,authorized:yn}),u("div",{style:{...$o?{animation:$o}:{},...De==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Re("div",{style:{backgroundColor:ka,borderRadius:Ta,...mo,padding:_a},children:[Re("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Re("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:X,style:{display:"inline-flex",alignItems:"center",gap:Ia?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:_.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,..._.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",..._.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(zr,{content:Ee})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:_.titleFontSize??"1.05rem",color:Ra,paddingRight:80,..._.title},children:`Pay with ${xr(Et)}`})]}),u(_r,{stripe:Pn,options:jo,children:u(Wa,{method:Et,sessionId:e,nonce:t,email:ue.email,billingName:[ue.firstName,ue.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:A,billingApiUrl:j,onTokenizedBody:Cn,onErrorChange:de,onDecline:s,onCancel:X,runBeforeButtonClick:Fn,onButtonClick:oe,isProcessing:it,submitButtonColor:Cr,submitButtonBorderRadius:kt,submitButtonStyle:_.submitButton,errorText:v})},Et)]})})]}):Re("form",{onSubmit:Sa,className:B,noValidate:!0,style:{position:"relative"},children:[u(Ha,{}),Se&&u(jn,{status:Se,errorMessage:v,authorized:yn}),Re("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ki("flopay-direct-paypal-gate-debug-default"),Vi("flopay-stripe-gate-debug-default"),ao&&E&&Re(Tr,{children:[R&&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(Qo,{sessionId:e,nonce:t,billingApiUrl:j,email:ue.email,billingName:cn||void 0,onBuyerIdentityReady:A,clientId:E.clientId,environment:E.environment,currency:Ce.toUpperCase(),isSubscription:W,providerObjectType:E.providerObjectType,onTokenizedBody:Cn,onComplete:i,onErrorChange:de,onDecline:s,onTechnicalFailure:Fr,onButtonClick:oe,runBeforeButtonClick:Fn,isProcessing:it,onLoadStateChange:Pa,onInitializationStateChange:Ca,session:T??null,existingOrderId:R?.orderId,debug:ft},R?.orderId??"fresh")]}),io&&u(_r,{stripe:Mr,options:bi,children:u(Bs,{sessionId:e,nonce:t,email:ue.email,billingName:cn||void 0,onBuyerIdentityReady:A,billingApiUrl:j,onTokenizedBody:Cn,onErrorChange:de,isProcessing:it,onButtonClick:oe,onDecline:s,onTechnicalFailure:Fr,runBeforeButtonClick:Fn,onLoadStateChange:wi,placeholderBorderRadius:Pr})}),so&&u(_r,{stripe:Pn,options:hi,children:u(As,{sessionId:e,nonce:t,email:ue.email,billingName:cn||void 0,onBuyerIdentityReady:A,billingApiUrl:j,intentKind:O>0?"payment":"setup",expressMethods:Do,onTokenizedBody:Cn,onErrorChange:de,onButtonClick:oe,onDecline:s,onTechnicalFailure:Fr,runBeforeButtonClick:Fn,onLoadStateChange:Ii,placeholderBorderRadius:Pr})}),lo&&u(Ms,{sessionId:e,nonce:t,email:ue.email,billingName:[ue.firstName,ue.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:j,paymentElementMethods:Lo,stripeInstance:Pn,paymentElementBaseOptions:va,onTokenizedBody:Cn,onErrorChange:de,onButtonClick:oe,onDecline:s,runBeforeButtonClick:Fn,onLoadStateChange:Ei,isProcessing:it,submitButtonColor:Cr,submitButtonBorderRadius:kt,submitButtonStyle:_.submitButton,themeId:ve,onExpandApm:z,expandedApmMethod:Et,buttonAppearance:{backgroundColor:_.cardButton?.backgroundColor,borderColor:_.cardInputBorder,textColor:_.cardButton?.color,borderRadius:Pr}})]}),y&&(il||al||sl)&&Re("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"}})]}),y&&ji]})}import{Fragment as Yn,jsx as te,jsxs as Nt}from"react/jsx-runtime";var Br=44,ui="flopay_checkout_saved_payment_resume",pa=new Map,da=new Map;function js(e,t){t.settled&&t.consumers===0&&pa.get(e)===t&&pa.delete(e)}function Wc(e,t,n){let r=da.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};da.set(e,i);let d=()=>{da.get(e)===i&&da.delete(e)};return a.then(d,d),a}function Ro(e){return new Promise(t=>setTimeout(t,e))}function ua(e,t,n){let r=Jo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ys,enabled:t!==!1});return r.beginCheckout(n),r}function Eo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ni(e,t,n,r,a){let i=ua(e,t,n);i.error({errorCode:r,stage:a,paymentMethodCategory:"unknown",...a==="session_read"?{requestCategory:"session_read"}:{}}),Eo(i)}function Jc(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 ci(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ri(e){return!e||e.data.stripe?.publishableKey?!1:!!ci(e)?.clientId}function or(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Xc(){if(!or())return null;try{let e=window.sessionStorage.getItem(ui);return e?JSON.parse(e):null}catch{return null}}function Ks(e){if(or())try{window.sessionStorage.setItem(ui,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function oi(){if(or())try{window.sessionStorage.removeItem(ui)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var pi=":idempotency-key";function Gs(e,t){if(!or())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 ai(e,t,n,r){if(or())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(a){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",a)}}function di(e,t){if(or())try{Gs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ws(e,t){if(!or())return null;try{let n=window.sessionStorage.getItem(e+pi);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 ii(e,t,n){if(or())try{window.sessionStorage.setItem(e+pi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function si(e,t){if(di(e,t),!!or())try{Ws(e,t)&&window.sessionStorage.removeItem(e+pi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Zc(){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 Vs(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 Qc(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 li(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function _o(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(a=>li(`${a.type??""}:${a.code??a.providerItemId??a.providerPlanId??""}`,a)).sort(),i:e?.items?.map(a=>li(a.code??a.providerItemId??"",a)).sort(),s:e?.subscriptions?.map(a=>li(a.code??a.providerPlanId??"",a)).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 ed(e,t=!1){let n=_o(e,t),r=0;for(let a=0;a<n.length;a++)r=(r<<5)-r+n.charCodeAt(a)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function td(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 a=Yc(t.currency,t.items,t.subscriptions,t.products);if(!a||e.currency.toUpperCase()!==a.toUpperCase())return!1;let i=(t.products??jc(t.items,t.subscriptions)).map(f=>({type:f.type,code:f.code??f.providerItemId??f.providerPlanId??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??a).toUpperCase()})).sort((f,g)=>`${f.code}:${f.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),d=e.products.map(f=>({type:f.type,code:f.code??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??e.currency).toUpperCase()})).sort((f,g)=>`${f.code}:${f.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(i.length!==d.length)return!1;for(let f=0;f<i.length;f+=1){let g=i[f],b=d[f];if(g.code!==b.code||g.type!==void 0&&g.type!==b.type||g.quantity!==b.quantity||g.totalAmount!==b.totalAmount||g.overrideAmount!==b.overrideAmount||g.currency!==b.currency)return!1}let s=[...t.couponCodes??[]].sort(),S=[...e.coupons??[]].sort();return s.length===S.length&&s.every((f,g)=>f===S[g])}function mi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:a,appearance:i,locale:d,loading:s,error:S,onComplete:f,onError:g,onInstrument:b,onDecline:B,onCountryChange:F,onZipChange:m,showPayPal:w=!0,showStripe:be=!0,enabledPaymentMethods:V,showApplePay:C=!0,showGooglePay:ye=!0,debug:ne=!1,layout:le,theme:ce,buttonsTheme:ve,buttonsStyles:He,cardButtonContent:ge,cardBackButtonContent:Rt,cardTitleContent:Ne,showSecurityFooter:Ee,onButtonClick:_e,onBeforeButtonClick:re,enableAVS:oe,cardFieldOrder:D,cardPreFormSlot:Te,avsLayout:xe,className:Be,initialErrorMessage:Oe=null,children:Pe,checkoutMode:x,confirmLabel:ie,renderConfirmButton:Me,onSessionCompleted:se}){let H=Vc(r),ke=Rn(()=>Hs(ce),[ce]),Xe=i??ke?.appearance,nt=n?"embedded_checkout":"standard_checkout",Ae=Pe?"custom_layout":le==="buttons"?"buttons_layout":"default_layout",[G,$]=It(null),[O,Ce]=It(null),$e=Tt(null),[E,W]=It(null),T=Tt(null),[P,Ze]=It(null),ft=Rn(()=>n?_o(n):"",[n]),Z=n?`create:${ft}`:`session:${e??""}`,Qe=P?.gateways?.stripe?"stripe":P?.gateways?.paypal?"paypal":void 0,Ve=Tt(new Set),gt=Tt(Z),St=Tt(Z);Go(()=>{St.current=Z,gt.current!==Z&&(gt.current=Z,Ve.current.clear())},[Z]);let h=Vn(M=>{if(St.current===Z){if(Da.has(M.name)){if(Ve.current.has(M.name))return;Ve.current.add(M.name)}st(()=>b?.(M))}},[Z,b]),J=Hr(h,Z),Q=Tt(!1),rt=Vn(M=>{if(Q.current)return;let L=M.gateway||!Qe?M:{...M,gateway:Qe};h(L)},[h,Qe]);Hn(()=>{J({class:"lifecycle",name:"checkout.mount"})},[J]);let[xt,Pt]=It(e??""),Ye=e??xt,je=n?"":Ye,[Vt,Ot]=It(!0),[Bt,dn]=It(null),[En,Nn]=It("full"),[Zt,_n]=It(!1),[Gt,et]=It(Oe),[un,ze]=It(null),[On,ot]=It(null),[ar,zt]=It(!1),[Ht,pn]=It(void 0),[an,mn]=It(""),[At,ir]=It(!1),[Ut,ee]=It(!1),[sr,yn]=It(!1),Qt=Tt(0),zn=Tt(void 0),[fn,Gn]=It("loading"),[gn,y]=It(0),ht=Tt(!1),Yt=Tt(!1),Wn=Tt(!1),Fe=Tt(null),wt=Rn(()=>({checkoutMode:x??En,layout:Pe?"unknown":le==="buttons"?"buttons":"embedded"}),[x,Pe,En,le]),dt=Tt(f);dt.current=f;let Wt=Tt(g);Wt.current=g;let Jn=Tt(B);Jn.current=B,Hn(()=>{Dt(O)?.setCheckoutContext(wt),E&&E!==O&&Dt(E)?.setCheckoutContext(wt)},[O,E,wt]);let lr=Tt(se);lr.current=se;let Xn=Vn(M=>{Gn(M),!(M!=="exhausted"||Wn.current)&&(Wn.current=!0,Wt.current?.(new Lt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),br=Vn(()=>{Gn("retrying"),y(M=>M+1)},[]);Hn(()=>{Gn("loading"),y(0),Wn.current=!1},[Ye]),Hn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ys,checkout_type:nt,checkout_layout:Ae,billing_api_url:H})},[Ae,nt,H]);let hn=Rn(()=>n?_o(n,!0):"",[n]),Zn=Rn(()=>an===hn?Ht:void 0,[Ht,an,hn]),Un=Rn(()=>n?Aa(n,Zn):void 0,[n,Zn]),en=x??Un?.checkoutMode??"full",bt=Rn(()=>Un?{...Un,checkoutMode:en}:void 0,[Un,en]);Hn(()=>{pn(void 0),mn(hn),zn.current=void 0,yn(!1)},[hn]),Hn(()=>{et(Oe)},[Oe]);let Tn=Vn((M,L,z)=>{st(()=>{Jn.current?.(Ft(M,L,z))})},[st]),sn=Vn(async(M,L)=>{et(null),ot(null),zt(!1),ze("processing");let z=L?.sessionId??M.id,X=M.gateways?.stripe?"stripe":M.gateways?.paypal?"paypal":void 0,Se=$e.current??T.current,p=Dt(Se),l=Se?null:ua(H,a,wt),c={log:v=>{p?p.log(v):l?.log(v)},error:v=>{p?p.error(v):l?.error(v)},terminal:v=>{p?p.terminal(v):l?.terminal(v)},performance:v=>{p?p.performance(v):l?.performance(v)},now:()=>p?.now()??l?.now()??0,elapsed:v=>p?.elapsed(v)??Math.max(0,(l?.now()??v)-v)},I=c.now(),R=!!(L?.initialAutoProcessingError||L?.initialAutoProcessingPending),ae=!1,Ge,j=()=>{ae||(ae=!0,R=!0,Ge=c.now(),c.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),c.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Y=!1,me=()=>{Y||(Y=!0,c.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),c.performance({stage:"processing",durationMs:c.elapsed(I),durationMode:"machine",paymentMethodCategory:"saved"}),Ge!==void 0&&c.performance({stage:"recovery",durationMs:c.elapsed(Ge),durationMode:"machine",paymentMethodCategory:"saved"}))};c.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Q.current=!0;try{c.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Q.current=!1}J({class:"lifecycle",name:"payment.processing.started",provider:X}),R&&j();let A;try{let v=bs(L?.initialAutoProcessingError),U;if(v)j(),v.type==="paypal_redirect_required"&&Fe.current?.publishableKey&&Ks({sessionId:z,publishableKey:Fe.current.publishableKey,paypalPublishableKey:Fe.current.paypalPublishableKey}),U=await ra(v,{flopay:$e.current,paypalFlopay:T.current,attempt3DS:L?.attempt3DS,billingApiUrl:H,sessionId:z,session:M,telemetry:!1}),v.type==="paypal_redirect_required"&&oi();else if(L?.initialAutoProcessingPending){let Ue=(await new ca(H,{telemetry:!1}).waitForCheckoutSessionCompletion(L.initialAutoProcessingPending.sessionId,{initialDelayMs:L.initialAutoProcessingPending.retryAfterMs})).data.session;if(!$r(Ue))throw Vo(Ue);U=wr(Ue,z)}else{if(L?.initialAutoProcessingError)throw fr(L.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.initialAutoProcessingError.checkoutMethod});if(L?.fromCreateSession)return L?.fallbackToFull&&(Nn("full"),Vs("full")),!1;{let _=await Wr({billingApiUrl:H,sessionId:z,session:M,telemetry:!1});_.type==="success"?U=_.result:(j(),_.type==="paypal_redirect_required"&&Fe.current?.publishableKey&&Ks({sessionId:z,publishableKey:Fe.current.publishableKey,paypalPublishableKey:Fe.current.paypalPublishableKey}),U=await ra(_,{flopay:$e.current,paypalFlopay:T.current,attempt3DS:L?.attempt3DS,billingApiUrl:H,sessionId:z,session:M,telemetry:!1}),_.type==="paypal_redirect_required"&&oi())}}z&&Gr(z),me(),R&&(c.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),c.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),c.terminal({outcome:U.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),zt(U.status==="authorized"),ze("success"),await Ro(1200),A=()=>dt.current?.(U)}catch(v){let U=Er(v),_=U.checkoutMethod??ko;et(U.message),ot(U.message),zt(!1),L?.fallbackToFull&&(c.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Nn("full"),Vs("full")),me();let K=U.statusCode!==void 0?Gc(U.statusCode,"unknown"):void 0,Ue=K==="4xx"?{requestCategory:"process_payment",statusClass:K}:{},vr=K===void 0||K==="4xx";if(vr&&(U.telemetryOutcome==="payment_declined"||!!(U.declineCode||U.code?.toLowerCase().includes("declin"))))c.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ue});else if(vr&&(U.telemetryOutcome==="validation_rejected"||U.type==="validation_error"))c.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ue});else{let ue=qs(v,R?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),cn=U.telemetryRequestCategory??"process_payment";Q.current=!0;try{c.error({...ue,...U.telemetryFailureCategory?{failureCategory:U.telemetryFailureCategory}:{},stage:R?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:cn})}finally{Q.current=!1}J({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:cn,provider:X})}return st(()=>Wt.current?.(U)),Tn(_,U,{code:U.code,declineCode:U.declineCode}),ze("error"),await Promise.allSettled([Ro(1500),L?.ensureProvidersReady?L.ensureProvidersReady():Promise.resolve()]),R&&(c.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),c.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{me(),l&&Eo(l),ze(null),ot(null)}return st(A),!0},[Tn,J,st,Er,H,a,wt]);Hn(()=>{if(typeof window>"u"||Yt.current)return;let M=new URLSearchParams(window.location.search),L=M.get("payment_intent_client_secret");if(!L)return;let z=Xc();z&&(Yt.current=!0,(async()=>{let X,Se=0;et(null),ot(null),ze("processing"),_n(!0);try{if(M.get("redirect_status")==="failed")throw Object.assign(new Lt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:p,paypalFlopay:l}=await aa({publishableKey:z.publishableKey,paypalPublishableKey:z.paypalPublishableKey,billingApiUrl:H,locale:d,telemetry:a});X=Dt(l??p),Se=X?.now()??0,X?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),X?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let c=(l??p)?.getRawProvider();if(!c)throw Object.assign(new Lt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:I,error:R}=await c.retrievePaymentIntent(L);if(R)throw Object.assign(new Lt(R.message??"Failed to retrieve PayPal payment status.","api_error",{code:R.code}),{checkoutMethod:"paypal"});let ae=Qi(I?.status);if(!I||ae==="failed")throw Object.assign(new Lt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ge=typeof I.payment_method=="string"?I.payment_method:I.payment_method?.id,j=ae;if(z.sessionId){let A=(await new ca(H,{telemetry:!1}).getUnifiedCheckoutSession(z.sessionId)).data.session;if(A&&A.status!=="complete"){let v=await Wr({billingApiUrl:H,sessionId:z.sessionId,session:A,telemetry:!1,tokenizedData:{id:Ge??I.id,type:"card",threeDSecureActionResultTokenId:I.id,isPaypal:!0}});if(v.type!=="success")throw Object.assign(new Lt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});j=v.result.status}}z.sessionId&&Gr(z.sessionId),X?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),X?.performance({stage:"redirect_resume",durationMs:X.elapsed(Se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),X?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ze("success"),await Ro(1200),st(()=>dt.current?.({status:j,paymentIntentId:I.id,paymentMethodId:Ge,checkoutMethod:"paypal"}))}catch(p){let l=Er(p),c=l.checkoutMethod??"paypal",I=!!(l.declineCode||l.code?.toLowerCase().includes("declin"));if(X)X.performance({stage:"redirect_resume",durationMs:X.elapsed(Se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),I?X.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):X.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(I){let R=ua(H,a,wt);R.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Eo(R)}else ni(H,a,wt,"REDIRECT_RESUME_FAILED","redirect_resume");et(l.message),ot(l.message),st(()=>Wt.current?.(l)),Tn(c,l,{code:l.code,declineCode:l.declineCode}),ze("error"),await Ro(1500)}finally{oi(),Zc(),ze(null),ot(null),_n(!1)}})())},[Tn,st,d,Er,H,a]);let tn=Tt(null),nn=Rn(()=>bt?_o(bt):"",[bt]),at=Tt(bt);at.current=bt,Hn(()=>{Pt(e??"")},[e]),Hn(()=>{ht.current=!1,et(Oe),ot(null),zt(!1),ze(null)},[nn,Oe,e]);async function Qn(M,L,z){let X=ua(H,a,wt),Se=new ca(H,{telemetry:!1}),p=!1;try{let l=M.idempotencyKey!==void 0?$s(M.idempotencyKey):void 0,c=Gs(L,z),I=Ws(L,z);c?.canonicalIdentity===z&&I&&I.canonicalIdentity===void 0&&(ii(L,z,I.idempotencyKey),I={...I,canonicalIdentity:z});let R=l??(I?.canonicalIdentity===z?I.idempotencyKey:void 0),ae,Ge=!1;X.log({name:c?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let j=c?.sid??null,Y=null,me,A,v=!1;if(j)try{Y=await Se.getUnifiedCheckoutSession(j,c?.nonce),c&&c.canonicalIdentity===void 0&&(td(Y.data.session,M)?(ai(L,z,j,c.nonce??Y.data.session?.clientSecret),I&&I.canonicalIdentity===void 0&&(ii(L,z,I.idempotencyKey),R??(R=I.idempotencyKey))):(si(L,z),I=null,R=l,j=null,Y=null));let _=Y?.data.session?.status,K=Y?.data.session,Ue=K?.clientSecret||c?.nonce;if(j&&K?.buyerIdentified===!1&&Ue&&(A=qr(Se,j,Ue,M.account)),j&&Y&&_==="complete"){if(Ua(j))return{sid:j,result:Y};si(L,z),j=null,Y=null,Ge=!0}}catch{X.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),c?.canonicalIdentity===void 0?(si(L,z),R=l):di(L,z),j=null}if(!j){!l&&(Ge||!R)&&(R=$s(),ae=R),R&&ii(L,z,R);let _=X.now(),K=0;X.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ue={...M,idempotencyKey:R,avsCheck:!!oe,avsConfig:typeof oe=="object"?oe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Pe?"custom_layout":le==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Ue,qc,{configurable:!1,enumerable:!1,value:{onAttempt:ut=>{K=Math.max(K,ut)}}});let vr=()=>{X.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),X.performance({stage:"session_create",durationMs:X.now()-_,durationMode:"machine",requestCategory:"session_create",attempt:K,statusClass:"2xx"})},it=ut=>{let ue=qs(ut,"CHECKOUT_SESSION_CREATE_FAILED","unknown");X.performance({stage:"session_create",durationMs:X.now()-_,durationMode:"machine",requestCategory:"session_create",attempt:K,statusClass:ue.statusClass}),ut instanceof Lt&&ut.type==="validation_error"?X.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ue.statusClass==="4xx"?X.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(X.error({...ue,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),J({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Kc(Ue)){let ut=await Se.createDetachedSession(Ue);ut.claimed.catch(()=>{}),Y=ut.shell,j=ut.sessionId,A=ut.claim,me=ut.claimed.then(ue=>{let cn=ue.data.session?.id??ut.sessionId;return cn&&ai(L,z,cn,ue.data.session?.clientSecret??ut.nonce),vr(),ue},ue=>{throw di(L,z),it(ue),ue}).finally(()=>Eo(X)),me.catch(()=>{}),p=!0,X.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),X.performance({stage:"session_shell",durationMs:X.now()-_,durationMode:"machine",requestCategory:"session_create",attempt:K,statusClass:"2xx",paymentMethodCategory:"card"})}else Y=await Se.createAndFetchSession(Ue),vr()}catch(ut){throw it(ut),ut}j=Y.data.session?.id??j??"",j&&!me&&ai(L,z,j,Y.data.session?.clientSecret)}let U=Y?.data.session;return!A&&j&&U?.buyerIdentified===!1&&U.clientSecret&&(A=qr(Se,j,U.clientSecret,M.account)),{sid:j??"",result:Y,sdkGeneratedIdempotencyKey:ae,...me?{claimed:me}:{},...A?{claim:A}:{},...v?{claimRequiresIdentity:!0}:{}}}finally{p||Eo(X)}}let xn=Vn(async(M,L)=>{let z=at.current;if(!z)throw new Lt("createSession is required to bootstrap checkout.","validation_error");let X=Aa(z,M),Se=_o(X),p=ed(X),l=pa.get(Se);if(!l){let R={canonicalIdentity:Se,promise:Qn(X,p,Se),consumers:0,settled:!1};l=R,pa.set(Se,R);let ae=()=>{R.settled=!0,js(Se,R)};R.promise.then(ae,ae)}l.consumers+=1;let c=!1,I=()=>{c||(c=!0,l.consumers-=1,js(Se,l))};L?.(I);try{let R=await l.promise;tn.current=Se,M&&(mn(hn),pn(K=>Ji(K,M)));let{sid:ae,result:Ge,claimed:j,claim:Y,claimRequiresIdentity:me}=R;if(zn.current=Y,yn(me===!0),$(Ge),Ge.data.session&&Ze(Ge.data.session),ae&&Pt(ae),j){Qt.current+=1;let K=Qt.current;ee(!0),j.then(Ue=>{Qt.current===K&&($(Ue),Ue.data.session&&Ze(Ue.data.session),ee(!1),yn(!1))},Ue=>{Qt.current===K&&(ee(!1),yn(!1),dn(Ue instanceof Lt?Ue:new Lt(Ue instanceof Error?Ue.message:"Failed to create session","api_error")))})}else Qt.current+=1,ee(!1),yn(!1);let{publishableKey:A,paypalPublishableKey:v}=oa(Ge),{flopay:U,paypalFlopay:_}=await aa({publishableKey:A,paypalPublishableKey:v,billingApiUrl:H,locale:d,telemetry:a});return $e.current=U,Ce(U),T.current=_,W(_),Ot(!1),R}catch(R){throw tn.current===Se&&(tn.current=null),R}finally{L||I()}},[hn,d,H,a,wt]),bn=Tt(sn);bn.current=sn;let Bn=Tt(xn);Bn.current=xn;let De=Vn(async M=>{if(!Qc(M)||At)return{sessionId:xt,session:P};ir(!0);try{let L=await xn(M);return{sessionId:L.sid,session:L.result.data.session??null}}finally{ir(!1)}},[xn,At,xt,P]),Mt=Vn(async M=>{let L=zn.current;if(!L)return;let z=Qt.current,X=await L(M);Qt.current===z&&($(X),X.data.session&&Ze(X.data.session))},[]);Hn(()=>{let M=!1,L;if(dn(null),nn){let Se=at.current;return Nn(en),Ot(!1),tn.current===nn?()=>{M=!0}:(Ze(Xi(Se,x)),(async()=>{let p=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),l=en==="auto"&&!ht.current&&!p;l&&(et(null),ot(null),ze("processing"));try{let c=await Bn.current(void 0,Ge=>{L=Ge}),I=c.result.data.session??null;Fe.current=oa(c.result);let R=ri(c.result),ae=Ua(c.sid||I?.id);if(!M&&l&&I&&!R&&!ae){ht.current=!0,await Wc(nn,c.sdkGeneratedIdempotencyKey,()=>bn.current(I,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:c.result.autoProcessingError,initialAutoProcessingPending:c.result.autoProcessingPending,autoProcessingAttempted:c.result.autoProcessingAttempted,sessionId:c.sid||I.id}));return}!M&&l&&((R||ae)&&(ht.current=!0),ze(null),ot(null))}catch(c){if(M)return;let I=c instanceof Lt||typeof c=="object"&&c!==null&&"code"in c?c.code:void 0;if(l&&I==="session_auto_completed"){ht.current=!0,ze("success"),await Ro(1200),M||(st(()=>{dt.current?.({status:"succeeded"})}),ze(null),ot(null));return}l&&(ze(null),ot(null));let R=c instanceof Lt?c:new Lt(c instanceof Error?c.message:"Failed to create session","api_error");dn(R)}finally{L?.(),L=void 0}})(),()=>{M=!0,L?.()})}Ot(!0);async function z(){let Se=!1;try{let p=new ca(H,{telemetry:!1}),l=await p.getUnifiedCheckoutSession(Ye,t);if(M)return;$(l);let c=l.data.session??null;if(Ze(c),!c)throw new Lt("No session data returned","api_error");let I=c.checkoutMode;if(I==="setup")throw new Lt("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(c.status==="authorized"){Ot(!1),st(()=>{dt.current?.(wr(c,Ye)),lr.current?.(c.successUrl??"")});return}if(c.status==="complete"){Ot(!1),st(()=>{lr.current?.(c.successUrl??"")});return}if(c.status==="expired")throw Ko(c);Se=!0;let R=x??I??"full";Nn(R),Qt.current+=1;let ae=c.clientSecret||t;zn.current=c.buyerIdentified===!1&&ae?qr(p,Ye,ae,{...c.customer?.id?{userId:c.customer.id}:{}}):void 0,ee(!1),yn(!1);let Ge=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),j=ri(l);if(R==="auto"&&!ht.current&&!Ge&&!j){ht.current=!0;let Y=X(l);try{if(await bn.current(c,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Y,sessionId:Ye||c.id}),M)return;await Y,M||Ot(!1);return}catch{if(M)return;await Y,M||Ot(!1);return}}await X(l),M||Ot(!1)}catch(p){if(M)return;Se&&J({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),p instanceof Lt?!Se&&!Jc(p)&&ni(H,a,wt,"NETWORK_REQUEST_FAILED","session_read"):ni(H,a,wt,"INTERNAL_SDK_ERROR","checkout_mount");let l=p instanceof Lt?p:new Lt(p instanceof Error?p.message:"Failed to initialize checkout","api_error");dn(l),Ot(!1)}}async function X(Se){let{publishableKey:p,paypalPublishableKey:l}=oa(Se);Fe.current={publishableKey:p,paypalPublishableKey:l};let{flopay:c,paypalFlopay:I}=await aa({publishableKey:p,paypalPublishableKey:l,billingApiUrl:H,locale:d,telemetry:a});$e.current=c,Ce(c),T.current=I,W(I)}return z(),()=>{M=!0}},[x,nn,en,je,st,t]);let Et=Vn(async()=>{if(!(Zt||!P)){_n(!0),et(null);try{await sn(P,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ye||P.id})}finally{_n(!1)}}},[Ye,Zt,sn,P]),An=ci(G),cr=ri(G),er=Rn(()=>{if(!(!G||!P||!G.data.stripe?.publishableKey))return{billingApiUrl:H}},[G,P,H]),ln=!!(n&&!Pe&&le==="buttons"&&re&&en==="full"),qt=Rn(()=>({session:P,loading:Vt,error:Bt,checkoutMode:En,inlineSessionDraft:bt,applyInlineSessionPatch:ln?De:void 0,inlineSessionPatchProcessing:At,claimPending:Ut,claimRequiresIdentity:sr,claimBuyerIdentity:Mt}),[P,Vt,Bt,En,bt,ln,De,At,Ut,sr,Mt]),vn=!!n&&le==="buttons"&&!cr&&(!O||!er),_t=un?te(jn,{status:un,errorMessage:On,authorized:ar}):null;if(Vt){if(s)return Nt(Yn,{children:[s,_t]});if(le==="buttons"){let M=ke?.buttonsLayout?.cardButton?.borderRadius??ke?.appearance.variables?.borderRadius??8,L=z=>te("div",{style:{height:z,borderRadius:M,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Nt(Yn,{children:[Nt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[w&&L(Br),be&&(C||ye)&&L(Br),be&&L(Br),te("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),_t]})}return Nt(Yn,{children:[Nt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[te("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),te("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),_t]})}return Bt?S?te(Dn.Provider,{value:qt,children:S(Bt)}):te(Dn.Provider,{value:qt,children:te("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Bt.message})}):vn?Nt(Yn,{children:[te(Dn.Provider,{value:qt,children:te(rd,{onButtonClick:_e,showPayPal:w,showStripe:be,showApplePay:C,showGooglePay:ye,theme:ce,buttonsTheme:ve,buttonsStyles:He,cardButtonContent:ge,cardBackButtonContent:Rt,cardTitleContent:Ne})}),_t]}):cr&&P&&An?Nt(Yn,{children:[te(Dn.Provider,{value:qt,children:Nt("div",{className:Be,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Gt&&te(Yr,{icon:!1,children:Gt}),fn==="retrying"&&te("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),fn==="exhausted"&&Nt("div",{role:"alert",children:[te("div",{children:"PayPal is temporarily unavailable. Please try again."}),te("button",{type:"button",onClick:br,children:"Retry PayPal"})]}),Ut?s??te("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Br,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:te("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):fn!=="exhausted"?te("div",{"aria-hidden":fn==="retrying"?!0:void 0,style:fn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:te(us,{sessionId:Ye,nonce:P.clientSecret||void 0,billingApiUrl:H,email:P.customer?.email||bt?.account?.email,billingName:[P.customer?.firstName,P.customer?.lastName].filter(Boolean).join(" ")||[bt?.account?.firstName,bt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Mt,clientId:An.clientId,environment:An.environment,currency:(P.currency??"usd").toUpperCase(),isSubscription:P.mode==="subscription",providerObjectType:An.providerObjectType,onComplete:f,onErrorChange:et,onDecline:B,onButtonClick:_e,onInitializationStateChange:Xn,allowAutomaticRetry:gn===0,session:P,telemetry:a,telemetryContext:wt,onInstrument:rt,debug:ne},`${Z}:paypal-init-${gn}`)}):null]})}),_t]}):!O||!er?te(Yn,{children:_t}):En==="confirm"?Nt(Yn,{children:[te(Dn.Provider,{value:qt,children:te(ea,{flopay:O,paypalFlopay:E,options:er,onInstrument:rt,children:Nt("div",{className:Be,children:[Gt&&te("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Gt}),Me?Me({onConfirm:Et,isProcessing:Zt}):te("button",{type:"button",onClick:Et,disabled:Zt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Zt?"not-allowed":"pointer",opacity:Zt?.6:1},children:Zt?"Processing...":ie??"Confirm Purchase"})]})},Z)}),_t]}):Nt(Yn,{children:[te(Dn.Provider,{value:qt,children:te(ea,{flopay:O,paypalFlopay:E,options:er,onInstrument:rt,children:Pe?Nt(Yn,{children:[Gt&&te("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Gt}),te(nd,{sessionId:Ye,nonce:P?.clientSecret||void 0,billingApiUrl:H,session:P,children:Pe})]}):te(ei,{sessionId:Ye,nonce:P?.clientSecret||void 0,email:P?.customer?.email||bt?.account?.email,userId:P?.customer?.id||bt?.account?.userId,firstName:P?.customer?.firstName||bt?.account?.firstName,lastName:P?.customer?.lastName||bt?.account?.lastName,totalAmount:P?Math.round($c(P).total*100):0,currency:P?.currency?.toLowerCase()??"usd",onComplete:f,onError:g,onDecline:B,error:Gt,onErrorChange:et,showPayPal:w,showStripe:be,enabledPaymentMethods:V??G?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:G?.data.stripe?.enabledPaymentMethodCountries,showApplePay:C,showGooglePay:ye,layout:le,theme:ce,buttonsTheme:ve,buttonsStyles:He,appearance:Xe,cardButtonContent:ge,cardBackButtonContent:Rt,cardTitleContent:Ne,onButtonClick:_e,onBeforeButtonClick:re,onBuyerIdentityReady:Mt,enableAVS:oe,...D?{cardFieldOrder:D}:{},...Te?{cardPreFormSlot:Te}:{},avsLayout:xe,country:P?.customer?.country,city:P?.customer?.city,state:P?.customer?.state,onCountryChange:F,onZipChange:m,avsCheck:!!oe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Pe?"custom_layout":le==="buttons"?"buttons_layout":"default_layout",className:Be,directPaypal:ci(G),isSubscription:P?.mode==="subscription",session:P,dataAttachmentPending:Ut,dataAttachmentRequiresIdentity:sr,debug:ne})},Z)}),_t]})}function nd({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:a}){return te(Yn,{children:ti.Children.map(a,i=>{if(!ti.isValidElement(i))return i;let d=i.props,s={};return d.sessionId||(s.sessionId=e),!d.nonce&&t&&(s.nonce=t),d.billingApiUrl||(s.billingApiUrl=n),r?.customer&&(d.email||(s.email=r.customer.email),d.userId||(s.userId=r.customer.id),d.firstName||(s.firstName=r.customer.firstName),d.lastName||(s.lastName=r.customer.lastName)),Object.keys(s).length===0?i:ti.cloneElement(i,s)})})}function rd({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:a,theme:i,buttonsTheme:d,buttonsStyles:s,cardButtonContent:S,cardBackButtonContent:f,cardTitleContent:g}){let[b,B]=It(!1),F=Rn(()=>Hs(i),[i]),m=Rn(()=>{let C=F?.buttonsLayout??Hc(d);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},[F,d,s]),w=F?.buttonsLayout?.cardButton?.borderRadius??F?.appearance.variables?.borderRadius??8,be=C=>te("div",{style:{height:C,borderRadius:w,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),V=S===void 0?{boxSizing:"border-box",height:Br,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let C=m.cardInputBorder??"#e5e7eb",ye=m.cardInputBackground??"white",ne=Nr(f),le=Nr(g);return Nt("div",{style:{backgroundColor:m.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...m.cardFormContainer},children:[Nt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Nt("button",{type:"button",onClick:()=>B(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:ne?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...m.backButton},children:[te("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...m.backButtonIcon},children:te("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:te("path",{d:"M15 18l-6-6 6-6"})})}),te(zr,{content:f})]}),le?te("div",{style:{flex:1}}):te("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...m.title},children:te(ho,{content:g})})]}),te("div",{style:{backgroundColor:ye,border:`1px solid ${C}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:te("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Nt("div",{style:{display:"flex"},children:[te("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomLeftRadius:8,padding:12,height:45},children:te("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),te("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:`1px solid ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomRightRadius:8,padding:12,height:45},children:te("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),te("div",{style:{backgroundColor:ye,border:`1px solid ${C}`,borderRadius:8,marginTop:8,padding:12,height:45},children:te("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),te("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...m.submitButton,opacity:.5}}),te("style",{children:`
|
|
33
|
+
`}),po&&Nn&&Me("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ve?-2:0},children:[Me("button",{type:"button",onClick:_n,style:{display:"inline-flex",alignItems:"center",gap:Ra?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:d.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...d.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...d.backButtonIcon},children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(qr,{content:Ae})]}),Ui?c("div",{style:{flex:1}}):c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:d.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...d.title},children:c(vo,{content:Fe})})]}),!po&&!Ui&&c("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ea,order:Ve?-3:0,...d.title},children:c(vo,{content:Fe})}),Ve&&Ke&&c("div",{style:{order:-2,width:"100%"},children:Ke}),Ve&&ut&&Me("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[c("div",{style:{backgroundColor:Nr,border:`1px solid ${xn(Ko)}`,borderRadius:Et,padding:"10px"},children:c("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:et,onChange:i=>{at("email"),Qn.current=i.target.value,sr(i.target.value)},onPointerDown:()=>at("email"),onKeyDown:()=>at("email"),onBlur:()=>{fn("email")&&mn(!0),Lt||ha()},disabled:J,required:!0,"aria-invalid":Ko||void 0,"aria-describedby":Ko?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",..._a}})}),Ko&&c("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:yo,children:$e.empty?"Email address is required":"Enter a valid email address"})]}),X&&c("div",{style:{order:Ve?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=qe,w=(z=!1)=>({backgroundColor:Nr,border:`1px solid ${xn(z)}`,borderRadius:Et,marginTop:"0.5rem",padding:"10px"}),N=()=>({width:"100%",border:"none",outline:"none",background:"transparent",..._a}),Be=fc(i);return Me(Br,{children:[He(X.address_line_1,i)&&Me(Br,{children:[c("div",{style:w(St("line1")),children:c("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:Dn,onChange:z=>{at("line1"),Mt.current.addressLine1=!0,dn.current=z.target.value,rn(z.target.value)},onPointerDown:()=>at("line1"),onKeyDown:()=>at("line1"),onBlur:()=>gn("line1"),disabled:J,required:!0,"aria-invalid":St("line1")||void 0,"aria-describedby":St("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:N()})}),St("line1")&&c("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:yo,children:"Street address is required"})]}),He(X.address_line_2,i)&&c("div",{style:w(),children:c("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:jn,onChange:z=>{Mt.current.addressLine2=!0,wn.current=z.target.value,cn(z.target.value)},disabled:J,"data-testid":"flopay-address-line2",style:N()})}),(He(X.city,i)||He(X.state,i))&&Me("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[He(X.city,i)&&c("div",{style:{flex:1,backgroundColor:Nr,borderTop:`1px solid ${xn(St("city"))}`,borderRight:`1px solid ${xn(St("city"))}`,borderBottom:`1px solid ${xn(St("city"))}`,borderLeft:`1px solid ${xn(St("city"))}`,padding:"10px",borderTopLeftRadius:Et,borderBottomLeftRadius:Et,...He(X.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Et}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Cn,onChange:z=>{at("city"),Mt.current.city=!0,kn.current=z.target.value,on(z.target.value)},onPointerDown:()=>at("city"),onKeyDown:()=>at("city"),onBlur:()=>gn("city"),disabled:J,required:!0,"aria-invalid":St("city")||void 0,"aria-describedby":St("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:N()})}),He(X.state,i)&&c("div",{style:{flex:1,backgroundColor:Nr,borderTop:`1px solid ${xn(St("state"))}`,borderRight:`1px solid ${xn(St("state"))}`,borderBottom:`1px solid ${xn(St("state"))}`,borderLeft:`1px solid ${xn(St("state"))}`,padding:"10px",borderTopRightRadius:Et,borderBottomRightRadius:Et,...He(X.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${xn(St("state")||St("city"))}`}:{borderRadius:Et}},children:Be?Me("select",{id:"flopay-billing-state",name:"billing-state",value:Ot,onChange:z=>{at("state"),Mt.current.state=!0,Zt.current=z.target.value,Sn(z.target.value)},onPointerDown:()=>at("state"),onKeyDown:()=>at("state"),onBlur:()=>gn("state"),disabled:J,autoComplete:"billing address-level1",required:!0,"aria-invalid":St("state")||void 0,"aria-describedby":St("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...N(),cursor:"pointer"},children:[c("option",{value:"",children:Ka(i)}),Be.map(z=>c("option",{value:z.code,children:z.name},z.code))]}):c("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Ka(i),autoComplete:"billing address-level1",value:Ot,onChange:z=>{at("state"),Mt.current.state=!0,Zt.current=z.target.value,Sn(z.target.value)},onPointerDown:()=>at("state"),onKeyDown:()=>at("state"),onBlur:()=>gn("state"),disabled:J,required:!0,"aria-invalid":St("state")||void 0,"aria-describedby":St("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:N()})})]}),St("city")&&c("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:yo,children:"City is required"}),St("state")&&Me("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:yo,children:[Ka(i)," is required"]}),(He(X.country,i)||He(X.postal_code,i))&&Me("div",{style:{display:"flex",flexDirection:ke==="column"?"column":"row",gap:ke==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[He(X.country,i)&&c("div",{style:{flex:ke==="row"?1:void 0,backgroundColor:Nr,borderTop:`1px solid ${mo}`,borderRight:`1px solid ${mo}`,borderBottom:`1px solid ${mo}`,borderLeft:`1px solid ${mo}`,padding:"10px",...ke==="row"&&He(X.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:Et,borderBottomLeftRadius:Et,borderRight:"none"}:{borderRadius:Et}},children:c("select",{id:"flopay-billing-country",name:"billing-country",value:qe,onChange:z=>{Mt.current.country=!0,Vt.current=z.target.value,Nt(z.target.value),nt?.(z.target.value),Zt.current="",Sn("")},disabled:J,autoComplete:"billing country","data-testid":"flopay-country",style:{...N(),cursor:"pointer"},children:uc.map(z=>Me("option",{value:z.code,children:[z.flag," ",z.name]},z.code))})}),He(X.postal_code,i)&&c("div",{style:{flex:ke==="row"?1:void 0,backgroundColor:Nr,border:`1px solid ${dl}`,padding:"10px",...ke==="row"&&He(X.country,i)?{borderRadius:"0",borderTopRightRadius:Et,borderBottomRightRadius:Et}:{borderRadius:Et}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Wa(qe),autoComplete:"billing postal-code",value:Kt,onChange:z=>{at("zip"),Mt.current.zip=!0,ft.current=z.target.value,Gt(z.target.value),dt?.(z.target.value)},onPointerDown:()=>at("zip"),onKeyDown:()=>at("zip"),onBlur:()=>{fn("zip")&&Cr(!0)},disabled:J,required:Jt.required,"aria-invalid":Vo||void 0,"aria-describedby":Vo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:N()})})]}),Vo&&c("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:yo,children:Jt.empty?`${Wa(i)} is required`:Dc(i)})]})})()}),Ve&&fl,P&&c(Gr,{margin:"0.75rem 0",styleOverride:d.errorBanner,children:P})]}),Ho={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"},Vi=i=>Pt?!ve||!Yn?c("pre",{"data-testid":i,style:Ho,children:"FloPay/DirectPayPal-debug - not enabled"}):c("pre",{"data-testid":i,style:Ho,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ve}`,` directPaypalConfigured=${Yn}`,` inAppBrowserDetected=${String($o)}`,` shouldRenderDirectPayPal=${so}`,` shouldRenderStripePayPal=${lo}`,` hasPaypalStripeInstance=${!!Dr}`].join(`
|
|
34
|
+
`)}):null,Hi=i=>Pt?!K||!Pn?c("pre",{"data-testid":i,style:Ho,children:"FloPay/Stripe-debug - not enabled"}):c("pre",{"data-testid":i,style:Ho,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${K}`,` currency=${Ie}`,` amountInCents=${oo}`,` enabledPaymentMethods: ${JSON.stringify(v??[])}`,` enabledPaymentMethodsProvided=${ao}`,` hasEnabledMethods=${Oo}`,` expressMethods: ${JSON.stringify(zo)}`,` walletExpressMethods: ${JSON.stringify(Uo)}`,` paymentElementMethods: ${JSON.stringify(io)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(qo)}`,` hasStripeInstance=${!!Pn}`,` shouldRenderWallets=${co}`,` shouldRenderPaymentElement=${uo}`].join(`
|
|
35
|
+
`)}):null,Yi=_e==="apm-expanding"||_e==="apm-form"||_e==="apm-collapsing",Yo=_e==="apm-expanding"?`flopay-card-enter ${Tr}ms cubic-bezier(0, 0, 0.2, 1) both`:_e==="apm-collapsing"?`flopay-card-exit ${Tr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Wo=Ft?{...Pa,paymentMethodTypes:[Ft]}:null;if(de==="buttons"){let i=_e==="buttons"||_e==="expanding"||_e==="apm-expanding",w=_e==="expanding"||_e==="card"||_e==="collapsing",N=Xe===void 0?{boxSizing:"border-box",height:ca,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Be=_e==="expanding"||_e==="apm-expanding"?`flopay-buttons-exit ${Tr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:_e==="collapsing"||_e==="apm-collapsing"?`flopay-buttons-enter ${Tr}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,z=_e==="expanding"?`flopay-card-enter ${Tr}ms cubic-bezier(0, 0, 0.2, 1) both`:_e==="collapsing"?`flopay-card-exit ${Tr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Me("form",{onSubmit:wa,className:B,noValidate:!0,style:{position:"relative"},children:[c(Ya,{}),j&&c(Wn,{status:j,errorMessage:P,authorized:un}),Me("div",{style:{display:"grid"},children:[Me("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Be?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Be?Mc:{},...Be?{animation:Be,pointerEvents:"none"}:{}},children:[Vi("flopay-direct-paypal-gate-debug"),Hi("flopay-stripe-gate-debug"),so&&k&&Me(Br,{children:[m&&c("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."}),c(na,{sessionId:e,nonce:t,billingApiUrl:Te,email:D.email,billingName:L||void 0,onBuyerIdentityReady:Pe,clientId:k.clientId,environment:k.environment,currency:Ie.toUpperCase(),isSubscription:Y,providerObjectType:k.providerObjectType,onTokenizedBody:Tn,onComplete:a,onErrorChange:pe,onDecline:s,onTechnicalFailure:Lr,onButtonClick:te,runBeforeButtonClick:Un,isProcessing:J,onLoadStateChange:Ca,onInitializationStateChange:Sa,session:E??null,existingOrderId:m?.orderId,debug:Pt},m?.orderId??"fresh")]}),lo&&c(xr,{stripe:Dr,options:bi,children:c(Ms,{sessionId:e,nonce:t,email:D.email,billingName:L||void 0,onBuyerIdentityReady:Pe,billingApiUrl:Te,onTokenizedBody:Tn,onErrorChange:pe,isProcessing:J,onButtonClick:te,onDecline:s,onTechnicalFailure:Lr,runBeforeButtonClick:Un,onLoadStateChange:ki,placeholderBorderRadius:Sr})}),co?c(xr,{stripe:Pn,options:hi,children:c(As,{sessionId:e,nonce:t,email:D.email,billingName:L||void 0,onBuyerIdentityReady:Pe,billingApiUrl:Te,intentKind:O>0?"payment":"setup",expressMethods:Uo,onTokenizedBody:Tn,onErrorChange:pe,onButtonClick:te,onDecline:s,onTechnicalFailure:Lr,runBeforeButtonClick:Un,onLoadStateChange:Ri,placeholderBorderRadius:Sr})}):Bi?c("div",{style:{height:ca,borderRadius:Sr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,uo&&c(Fs,{sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Pe,billingApiUrl:Te,paymentElementMethods:qo,stripeInstance:Pn,paymentElementBaseOptions:Pa,onTokenizedBody:Tn,onErrorChange:pe,onButtonClick:te,onDecline:s,runBeforeButtonClick:Un,onLoadStateChange:_i,isProcessing:J,submitButtonColor:wr,submitButtonBorderRadius:Et,submitButtonStyle:d.submitButton,onExpandApm:x,expandedApmMethod:Ft,themeId:we,buttonAppearance:{backgroundColor:d.cardButton?.backgroundColor,borderColor:d.cardInputBorder,textColor:d.cardButton?.color,borderRadius:Sr}}),Ve&&c("button",{type:"button",onClick:async()=>{J||!(await Un("card")).proceed||(te?.("card"),Fr())},disabled:J,style:{width:"100%",...N,...d.cardButton,...ei({themeBundle:p,resolvedPrimaryColor:wr,resolvedBorderRadius:Et,submitButtonStyle:d.submitButton,explicitPrimaryColor:sn?.colorPrimary}),fontSize:d.cardButtonFontSize??"0.95rem",fontWeight:600,cursor: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:J?.6:1},onMouseEnter:Re=>{!J&&(p||sn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=ml)},onMouseLeave:Re=>{(p||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:c(Ur,{content:Xe})}),P&&_e==="buttons"&&c(Gr,{margin:"0.25rem 0",styleOverride:d.errorBanner,children:P})]}),Ve&&w&&c("div",{style:{gridArea:"1 / 1",...z?{animation:z}:{},..._e==="collapsing"?{pointerEvents:"none"}:{}},children:Ki}),K&&Yi&&Ft&&Wo&&Pn&&c("div",{style:{gridArea:"1 / 1",...Yo?{animation:Yo}:{},..._e==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Me("div",{style:{backgroundColor:Ia,borderRadius:xa,...fo,padding:Ta},children:[Me("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Me("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:M,style:{display:"inline-flex",alignItems:"center",gap:Ra?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:d.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...d.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...d.backButtonIcon},children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(qr,{content:Ae})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:d.titleFontSize??"1.05rem",color:Ea,paddingRight:80,...d.title},children:`Pay with ${Mr(Ft)}`})]}),c(xr,{stripe:Pn,options:Wo,children:c(Ja,{method:Ft,sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Pe,billingApiUrl:Te,onTokenizedBody:Tn,onErrorChange:pe,onDecline:s,onCancel:M,runBeforeButtonClick:Un,onButtonClick:te,isProcessing:J,submitButtonColor:wr,submitButtonBorderRadius:Et,submitButtonStyle:d.submitButton,errorText:P})},Ft)]})})]})]})}return Yi&&Ft&&Wo&&Pn&&K?Me("form",{onSubmit:wa,className:B,noValidate:!0,style:{position:"relative"},children:[c(Ya,{}),j&&c(Wn,{status:j,errorMessage:P,authorized:un}),c("div",{style:{...Yo?{animation:Yo}:{},..._e==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Me("div",{style:{backgroundColor:Ia,borderRadius:xa,...fo,padding:Ta},children:[Me("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Me("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:M,style:{display:"inline-flex",alignItems:"center",gap:Ra?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:d.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...d.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...d.backButtonIcon},children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(qr,{content:Ae})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:d.titleFontSize??"1.05rem",color:Ea,paddingRight:80,...d.title},children:`Pay with ${Mr(Ft)}`})]}),c(xr,{stripe:Pn,options:Wo,children:c(Ja,{method:Ft,sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Pe,billingApiUrl:Te,onTokenizedBody:Tn,onErrorChange:pe,onDecline:s,onCancel:M,runBeforeButtonClick:Un,onButtonClick:te,isProcessing:J,submitButtonColor:wr,submitButtonBorderRadius:Et,submitButtonStyle:d.submitButton,errorText:P})},Ft)]})})]}):Me("form",{onSubmit:wa,className:B,noValidate:!0,style:{position:"relative"},children:[c(Ya,{}),j&&c(Wn,{status:j,errorMessage:P,authorized:un}),Me("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Vi("flopay-direct-paypal-gate-debug-default"),Hi("flopay-stripe-gate-debug-default"),so&&k&&Me(Br,{children:[m&&c("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."}),c(na,{sessionId:e,nonce:t,billingApiUrl:Te,email:D.email,billingName:L||void 0,onBuyerIdentityReady:Pe,clientId:k.clientId,environment:k.environment,currency:Ie.toUpperCase(),isSubscription:Y,providerObjectType:k.providerObjectType,onTokenizedBody:Tn,onComplete:a,onErrorChange:pe,onDecline:s,onTechnicalFailure:Lr,onButtonClick:te,runBeforeButtonClick:Un,isProcessing:J,onLoadStateChange:Ca,onInitializationStateChange:Sa,session:E??null,existingOrderId:m?.orderId,debug:Pt},m?.orderId??"fresh")]}),lo&&c(xr,{stripe:Dr,options:bi,children:c(Ms,{sessionId:e,nonce:t,email:D.email,billingName:L||void 0,onBuyerIdentityReady:Pe,billingApiUrl:Te,onTokenizedBody:Tn,onErrorChange:pe,isProcessing:J,onButtonClick:te,onDecline:s,onTechnicalFailure:Lr,runBeforeButtonClick:Un,onLoadStateChange:ki,placeholderBorderRadius:Sr})}),co&&c(xr,{stripe:Pn,options:hi,children:c(As,{sessionId:e,nonce:t,email:D.email,billingName:L||void 0,onBuyerIdentityReady:Pe,billingApiUrl:Te,intentKind:O>0?"payment":"setup",expressMethods:Uo,onTokenizedBody:Tn,onErrorChange:pe,onButtonClick:te,onDecline:s,onTechnicalFailure:Lr,runBeforeButtonClick:Un,onLoadStateChange:Ri,placeholderBorderRadius:Sr})}),uo&&c(Fs,{sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Te,paymentElementMethods:qo,stripeInstance:Pn,paymentElementBaseOptions:Pa,onTokenizedBody:Tn,onErrorChange:pe,onButtonClick:te,onDecline:s,runBeforeButtonClick:Un,onLoadStateChange:_i,isProcessing:J,submitButtonColor:wr,submitButtonBorderRadius:Et,submitButtonStyle:d.submitButton,themeId:we,onExpandApm:x,expandedApmMethod:Ft,buttonAppearance:{backgroundColor:d.cardButton?.backgroundColor,borderColor:d.cardInputBorder,textColor:d.cardButton?.color,borderRadius:Sr}})]}),Ve&&(il||al||sl)&&Me("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),c("span",{children:"or pay with card"}),c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ve&&Ki]})}import{Fragment as Zn,jsx as Z,jsxs as jt}from"react/jsx-runtime";var Ar=44,pi="flopay_checkout_saved_payment_resume",fa=new Map,ma=new Map;function Ks(e,t){t.settled&&t.consumers===0&&fa.get(e)===t&&fa.delete(e)}function Gc(e,t,n){let r=ma.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};ma.set(e,a);let l=()=>{ma.get(e)===a&&ma.delete(e)};return o.then(l,l),o}function Bo(e){return new Promise(t=>setTimeout(t,e))}function ya(e,t,n){let r=ea({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ws,enabled:t!==!1});return r.beginCheckout(n),r}function Mo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ri(e,t,n,r,o){let a=ya(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Mo(a)}function Jc(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 di(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function oi(e){return!e||e.data.stripe?.publishableKey?!1:!!di(e)?.clientId}function ir(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Xc(){if(!ir())return null;try{let e=window.sessionStorage.getItem(pi);return e?JSON.parse(e):null}catch{return null}}function Vs(e){if(ir())try{window.sessionStorage.setItem(pi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ai(){if(ir())try{window.sessionStorage.removeItem(pi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var mi=":idempotency-key";function Gs(e,t){if(!ir())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 ii(e,t,n,r){if(ir())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function ui(e,t){if(ir())try{Gs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Js(e,t){if(!ir())return null;try{let n=window.sessionStorage.getItem(e+mi);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 si(e,t,n){if(ir())try{window.sessionStorage.setItem(e+mi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function li(e,t){if(ui(e,t),!!ir())try{Js(e,t)&&window.sessionStorage.removeItem(e+mi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Zc(){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 Hs(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 Qc(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function ci(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ed(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([l],[s])=>l<s?-1:l>s?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let l=0;l<t.length;l++){let s=t.charCodeAt(l);n=r^Math.imul(n^s,597399067),r=o^Math.imul(r^s,2869860233),o=a^Math.imul(o^s,951274213),a=n^Math.imul(a^s,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(l=>(l>>>0).toString(16).padStart(8,"0")).join("")}function Ao(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=>ci(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ci(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ci(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:ed(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function td(e,t=!1){let n=Ao(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 nd(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=Yc(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??jc(t.items,t.subscriptions)).map(y=>({type:y.type,code:y.code??y.providerItemId??y.providerPlanId??"",quantity:y.quantity??1,totalAmount:y.totalAmount,overrideAmount:y.overrideAmount??null,currency:(y.currency??o).toUpperCase()})).sort((y,f)=>`${y.code}:${y.type??""}`.localeCompare(`${f.code}:${f.type??""}`)),l=e.products.map(y=>({type:y.type,code:y.code??"",quantity:y.quantity??1,totalAmount:y.totalAmount,overrideAmount:y.overrideAmount??null,currency:(y.currency??e.currency).toUpperCase()})).sort((y,f)=>`${y.code}:${y.type??""}`.localeCompare(`${f.code}:${f.type??""}`));if(a.length!==l.length)return!1;for(let y=0;y<a.length;y+=1){let f=a[y],h=l[y];if(f.code!==h.code||f.type!==void 0&&f.type!==h.type||f.quantity!==h.quantity||f.totalAmount!==h.totalAmount||f.overrideAmount!==h.overrideAmount||f.currency!==h.currency)return!1}let s=[...t.couponCodes??[]].sort(),C=[...e.coupons??[]].sort();return s.length===C.length&&s.every((y,f)=>y===C[f])}function yi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:s,error:C,onComplete:y,onError:f,onInstrument:h,onDecline:B,onCountryChange:A,onZipChange:u,showPayPal:S=!0,showStripe:ve=!0,enabledPaymentMethods:K,showApplePay:v=!0,showGooglePay:ye=!0,debug:Q=!1,layout:ce,theme:de,buttonsTheme:we,buttonsStyles:Qe,cardButtonContent:he,cardBackButtonContent:Bt,cardTitleContent:Xe,showSecurityFooter:Ae,onButtonClick:Fe,onBeforeButtonClick:ee,enableAVS:te,cardFieldOrder:F,cardPreFormSlot:Le,avsLayout:Ne,className:ze,initialErrorMessage:Ke=null,children:ke,checkoutMode:T,confirmLabel:oe,renderConfirmButton:Ue,onSessionCompleted:ae}){let V=Vc(r),Ee=Fn(()=>Ys(de),[de]),nt=a??Ee?.appearance,dt=n?"embedded_checkout":"standard_checkout",De=ke?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",[H,U]=xt(null),[O,Ie]=xt(null),Ye=Tt(null),[k,Y]=xt(null),E=Tt(null),[b,it]=xt(null),Pt=Fn(()=>n?Ao(n):"",[n]),G=n?`create:${Pt}`:`session:${e??""}`,st=b?.gateways?.stripe?"stripe":b?.gateways?.paypal?"paypal":void 0,Ze=Tt(new Set),Ct=Tt(G),wt=Tt(G);wo(()=>{wt.current=G,Ct.current!==G&&(Ct.current=G,Ze.current.clear())},[G]);let g=Jn(x=>{if(wt.current===G){if(La.has(x.name)){if(Ze.current.has(x.name))return;Ze.current.add(x.name)}_t(()=>h?.(x))}},[G,h]),$=Wr(g,G),lt=Tt(!1),yt=Jn(x=>{if(lt.current)return;let M=x.gateway||!st?x:{...x,gateway:st};g(M)},[g,st]);Xn(()=>{$({class:"lifecycle",name:"checkout.mount"})},[$]);let[ie,kt]=xt(e??""),ot=e??ie,qe=n?"":ot,[Nt,Kt]=xt(!0),[Gt,Dn]=xt(null),[rn,jn]=xt("full"),[cn,Cn]=xt(!1),[on,Ot]=xt(Ke),[Sn,et]=xt(null),[sr,rt]=xt(null),[Ln,ft]=xt(!1),[Vt,dn]=xt(void 0),[wn,kn]=xt(""),[Zt,Qn]=xt(!1),[Mt,X]=xt(!1),[er,un]=xt(!1),pn=Tt(0),lr=Tt(void 0),[Kn,tr]=xt("loading"),[Qt,Ve]=xt(0),In=Tt(!1),I=Tt(!1),Dt=Tt(!1),It=Tt(null),Rt=Fn(()=>({checkoutMode:T??rn,layout:ke?"unknown":ce==="buttons"?"buttons":"embedded"}),[T,ke,rn,ce]),se=Tt(y);se.current=y;let Jt=Tt(f);Jt.current=f;let cr=Tt(B);cr.current=B,Xn(()=>{qt(O)?.setCheckoutContext(Rt),k&&k!==O&&qt(k)?.setCheckoutContext(Rt)},[O,k,Rt]);let dr=Tt(ae);dr.current=ae;let nr=Jn(x=>{tr(x),!(x!=="exhausted"||Dt.current)&&(Dt.current=!0,Jt.current?.(new $t("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Pr=Jn(()=>{tr("retrying"),Ve(x=>x+1)},[]);Xn(()=>{tr("loading"),Ve(0),Dt.current=!1},[ot]),Xn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ws,checkout_type:dt,checkout_layout:De,billing_api_url:V})},[De,dt,V]);let Rn=Fn(()=>n?Ao(n,!0):"",[n]),Cr=Fn(()=>wn===Rn?Vt:void 0,[Vt,wn,Rn]),Vn=Fn(()=>n?Aa(n,Cr):void 0,[n,Cr]),mn=T??Vn?.checkoutMode??"full",At=Fn(()=>Vn?{...Vn,checkoutMode:mn}:void 0,[Vn,mn]);Xn(()=>{dn(void 0),kn(Rn),lr.current=void 0,un(!1)},[Rn]),Xn(()=>{Ot(Ke)},[Ke]);let an=Jn((x,M,j)=>{_t(()=>{cr.current?.(Ut(x,M,j))})},[]),en=Jn(async(x,M)=>{Ot(null),rt(null),ft(!1),et("processing");let j=M?.sessionId??x.id,R=x.gateways?.stripe?"stripe":x.gateways?.paypal?"paypal":void 0,Oe=Ye.current??E.current,W=qt(Oe),_=Oe?null:ya(V,o,Rt),m={log:d=>{W?W.log(d):_?.log(d)},error:d=>{W?W.error(d):_?.error(d)},terminal:d=>{W?W.terminal(d):_?.terminal(d)},performance:d=>{W?W.performance(d):_?.performance(d)},now:()=>W?.now()??_?.now()??0,elapsed:d=>W?.elapsed(d)??Math.max(0,(_?.now()??d)-d)},re=m.now(),ne=!!(M?.initialAutoProcessingError||M?.initialAutoProcessingPending),Te=!1,We,xe=()=>{Te||(Te=!0,ne=!0,We=m.now(),m.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Pe=!1,P=()=>{Pe||(Pe=!0,m.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),m.performance({stage:"processing",durationMs:m.elapsed(re),durationMode:"machine",paymentMethodCategory:"saved"}),We!==void 0&&m.performance({stage:"recovery",durationMs:m.elapsed(We),durationMode:"machine",paymentMethodCategory:"saved"}))};m.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),lt.current=!0;try{m.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{lt.current=!1}$({class:"lifecycle",name:"payment.processing.started",provider:R}),ne&&xe();let p;try{let d=vs(M?.initialAutoProcessingError),q;if(d)xe(),d.type==="paypal_redirect_required"&&It.current?.publishableKey&&Vs({sessionId:j,publishableKey:It.current.publishableKey,paypalPublishableKey:It.current.paypalPublishableKey}),q=await ia(d,{flopay:Ye.current,paypalFlopay:E.current,attempt3DS:M?.attempt3DS,billingApiUrl:V,sessionId:j,session:x,telemetry:!1}),d.type==="paypal_redirect_required"&&ai();else if(M?.initialAutoProcessingPending){let J=(await new pa(V,{telemetry:!1}).waitForCheckoutSessionCompletion(M.initialAutoProcessingPending.sessionId,{initialDelayMs:M.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Kr(J))throw Jo(J);q=Ir(J,j)}else{if(M?.initialAutoProcessingError)throw hr(M.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:M.initialAutoProcessingError.checkoutMethod});if(M?.fromCreateSession)return M?.fallbackToFull&&(jn("full"),Hs("full")),!1;{let ge=await Xr({billingApiUrl:V,sessionId:j,session:x,telemetry:!1});ge.type==="success"?q=ge.result:(xe(),ge.type==="paypal_redirect_required"&&It.current?.publishableKey&&Vs({sessionId:j,publishableKey:It.current.publishableKey,paypalPublishableKey:It.current.paypalPublishableKey}),q=await ia(ge,{flopay:Ye.current,paypalFlopay:E.current,attempt3DS:M?.attempt3DS,billingApiUrl:V,sessionId:j,session:x,telemetry:!1}),ge.type==="paypal_redirect_required"&&ai())}}j&&Jr(j),P(),ne&&(m.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),m.terminal({outcome:q.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),ft(q.status==="authorized"),et("success"),await Bo(1200),p=()=>se.current?.(q)}catch(d){let q=To(d),ge=q.checkoutMethod??_o;Ot(q.message),rt(q.message),ft(!1),M?.fallbackToFull&&(m.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),jn("full"),Hs("full")),P();let le=q.statusCode!==void 0?Wc(q.statusCode,"unknown"):void 0,J=le==="4xx"?{requestCategory:"process_payment",statusClass:le}:{},Ce=le===void 0||le==="4xx";if(Ce&&(q.telemetryOutcome==="payment_declined"||!!(q.declineCode||q.code?.toLowerCase().includes("declin"))))m.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...J});else if(Ce&&(q.telemetryOutcome==="validation_rejected"||q.type==="validation_error"))m.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...J});else{let ue=$s(d,ne?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Se=q.telemetryRequestCategory??"process_payment";lt.current=!0;try{m.error({...ue,...q.telemetryFailureCategory?{failureCategory:q.telemetryFailureCategory}:{},stage:ne?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Se})}finally{lt.current=!1}$({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Se,provider:R})}return _t(()=>Jt.current?.(q)),an(ge,q,{code:q.code,declineCode:q.declineCode}),et("error"),await Promise.allSettled([Bo(1500),M?.ensureProvidersReady?M.ensureProvidersReady():Promise.resolve()]),ne&&(m.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{P(),_&&Mo(_),et(null),rt(null)}return _t(p),!0},[an,$,V,o,Rt]);Xn(()=>{if(typeof window>"u"||I.current)return;let x=new URLSearchParams(window.location.search),M=x.get("payment_intent_client_secret");if(!M)return;let j=Xc();j&&(I.current=!0,(async()=>{let R,Oe=0;Ot(null),rt(null),et("processing"),Cn(!0);try{if(x.get("redirect_status")==="failed")throw Object.assign(new $t("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:W,paypalFlopay:_}=await la({publishableKey:j.publishableKey,paypalPublishableKey:j.paypalPublishableKey,billingApiUrl:V,locale:l,telemetry:o});R=qt(_??W),Oe=R?.now()??0,R?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),R?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let m=(_??W)?.getRawProvider();if(!m)throw Object.assign(new $t("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:re,error:ne}=await m.retrievePaymentIntent(M);if(ne)throw Object.assign(new $t(ne.message??"Failed to retrieve PayPal payment status.","api_error",{code:ne.code}),{checkoutMethod:"paypal"});let Te=es(re?.status);if(!re||Te==="failed")throw Object.assign(new $t("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let We=typeof re.payment_method=="string"?re.payment_method:re.payment_method?.id,xe=Te;if(j.sessionId){let p=(await new pa(V,{telemetry:!1}).getUnifiedCheckoutSession(j.sessionId)).data.session;if(p&&p.status!=="complete"){let d=await Xr({billingApiUrl:V,sessionId:j.sessionId,session:p,telemetry:!1,tokenizedData:{id:We??re.id,type:"card",threeDSecureActionResultTokenId:re.id,isPaypal:!0}});if(d.type!=="success")throw Object.assign(new $t("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});xe=d.result.status}}j.sessionId&&Jr(j.sessionId),R?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),R?.performance({stage:"redirect_resume",durationMs:R.elapsed(Oe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),R?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),et("success"),await Bo(1200),_t(()=>se.current?.({status:xe,paymentIntentId:re.id,paymentMethodId:We,checkoutMethod:"paypal"}))}catch(W){let _=To(W),m=_.checkoutMethod??"paypal",re=!!(_.declineCode||_.code?.toLowerCase().includes("declin"));if(R)R.performance({stage:"redirect_resume",durationMs:R.elapsed(Oe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),re?R.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):R.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(re){let ne=ya(V,o,Rt);ne.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Mo(ne)}else ri(V,o,Rt,"REDIRECT_RESUME_FAILED","redirect_resume");Ot(_.message),rt(_.message),_t(()=>Jt.current?.(_)),an(m,_,{code:_.code,declineCode:_.declineCode}),et("error"),await Bo(1500)}finally{ai(),Zc(),et(null),rt(null),Cn(!1)}})())},[an,l,V,o,Rt]);let En=Tt(null),yn=Fn(()=>At?Ao(At):"",[At]),at=Tt(At);at.current=At,Xn(()=>{kt(e??"")},[e]),Xn(()=>{In.current=!1,Ot(Ke),rt(null),ft(!1),et(null)},[yn,Ke,e]);async function fn(x,M,j){let R=ya(V,o,Rt),Oe=new pa(V,{telemetry:!1}),W=!1;try{let _=x.idempotencyKey!==void 0?js(x.idempotencyKey):void 0,m=Gs(M,j),re=Js(M,j);m?.canonicalIdentity===j&&re&&re.canonicalIdentity===void 0&&(si(M,j,re.idempotencyKey),re={...re,canonicalIdentity:j});let ne=_??(re?.canonicalIdentity===j?re.idempotencyKey:void 0),Te,We=!1;R.log({name:m?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let xe=m?.sid??null,Pe=null,P,p,d=!1;if(xe)try{Pe=await Oe.getUnifiedCheckoutSession(xe,m?.nonce),m&&m.canonicalIdentity===void 0&&(nd(Pe.data.session,x)?(ii(M,j,xe,m.nonce??Pe.data.session?.clientSecret),re&&re.canonicalIdentity===void 0&&(si(M,j,re.idempotencyKey),ne??(ne=re.idempotencyKey))):(li(M,j),re=null,ne=_,xe=null,Pe=null));let ge=Pe?.data.session?.status,le=Pe?.data.session,J=le?.clientSecret||m?.nonce;if(xe&&le?.buyerIdentified===!1&&J&&(p=jr(Oe,xe,J,x.account)),xe&&Pe&&ge==="complete"){if(qa(xe))return{sid:xe,result:Pe};li(M,j),xe=null,Pe=null,We=!0}}catch{R.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),m?.canonicalIdentity===void 0?(li(M,j),ne=_):ui(M,j),xe=null}if(!xe){!_&&(We||!ne)&&(ne=js(),Te=ne),ne&&si(M,j,ne);let ge=R.now(),le=0;R.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let J={...x,idempotencyKey:ne,avsCheck:!!te,avsConfig:typeof te=="object"?te:void 0,checkoutType:"embedded_checkout",checkoutLayout:ke?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(J,qc,{configurable:!1,enumerable:!1,value:{onAttempt:L=>{le=Math.max(le,L)}}});let Ce=()=>{R.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),R.performance({stage:"session_create",durationMs:R.now()-ge,durationMode:"machine",requestCategory:"session_create",attempt:le,statusClass:"2xx"})},D=L=>{let ue=$s(L,"CHECKOUT_SESSION_CREATE_FAILED","unknown");R.performance({stage:"session_create",durationMs:R.now()-ge,durationMode:"machine",requestCategory:"session_create",attempt:le,statusClass:ue.statusClass}),L instanceof $t&&L.type==="validation_error"?R.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ue.statusClass==="4xx"?R.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(R.error({...ue,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),$({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Kc(J)){let L=await Oe.createDetachedSession(J);L.claimed.catch(()=>{}),Pe=L.shell,xe=L.sessionId,p=L.claim,P=L.claimed.then(ue=>{let Se=ue.data.session?.id??L.sessionId;return Se&&ii(M,j,Se,ue.data.session?.clientSecret??L.nonce),Ce(),ue},ue=>{throw ui(M,j),D(ue),ue}).finally(()=>Mo(R)),P.catch(()=>{}),W=!0,R.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),R.performance({stage:"session_shell",durationMs:R.now()-ge,durationMode:"machine",requestCategory:"session_create",attempt:le,statusClass:"2xx",paymentMethodCategory:"card"})}else Pe=await Oe.createAndFetchSession(J),Ce()}catch(L){throw D(L),L}xe=Pe.data.session?.id??xe??"",xe&&!P&&ii(M,j,xe,Pe.data.session?.clientSecret)}let q=Pe?.data.session;return!p&&xe&&q?.buyerIdentified===!1&&q.clientSecret&&(p=jr(Oe,xe,q.clientSecret,x.account)),{sid:xe??"",result:Pe,sdkGeneratedIdempotencyKey:Te,...P?{claimed:P}:{},...p?{claim:p}:{},...d?{claimRequiresIdentity:!0}:{}}}finally{W||Mo(R)}}let gn=Tt(fn);wo(()=>{gn.current=fn},[fn]);let hn=Jn(async(x,M)=>{let j=at.current;if(!j)throw new $t("createSession is required to bootstrap checkout.","validation_error");let R=Aa(j,x),Oe=Ao(R),W=td(R),_=fa.get(Oe);if(!_){let ne={canonicalIdentity:Oe,promise:gn.current(R,W,Oe),consumers:0,settled:!1};_=ne,fa.set(Oe,ne);let Te=()=>{ne.settled=!0,Ks(Oe,ne)};ne.promise.then(Te,Te)}_.consumers+=1;let m=!1,re=()=>{m||(m=!0,_.consumers-=1,Ks(Oe,_))};M?.(re);try{let ne=await _.promise;En.current=Oe,x&&(kn(Rn),dn(le=>Xi(le,x)));let{sid:Te,result:We,claimed:xe,claim:Pe,claimRequiresIdentity:P}=ne;if(lr.current=Pe,un(P===!0),U(We),We.data.session&&it(We.data.session),Te&&kt(Te),xe){pn.current+=1;let le=pn.current;X(!0),xe.then(J=>{pn.current===le&&(U(J),J.data.session&&it(J.data.session),X(!1),un(!1))},J=>{pn.current===le&&(X(!1),un(!1),Dn(J instanceof $t?J:new $t(J instanceof Error?J.message:"Failed to create session","api_error")))})}else pn.current+=1,X(!1),un(!1);let{publishableKey:p,paypalPublishableKey:d}=sa(We),{flopay:q,paypalFlopay:ge}=await la({publishableKey:p,paypalPublishableKey:d,billingApiUrl:V,locale:l,telemetry:o});return Ye.current=q,Ie(q),E.current=ge,Y(ge),Kt(!1),ne}catch(ne){throw En.current===Oe&&(En.current=null),ne}finally{M||re()}},[Rn,l,V,o]),bn=Tt(en);bn.current=en;let _e=Tt(hn);_e.current=hn;let Xt=Jn(async x=>{if(!Qc(x)||Zt)return{sessionId:ie,session:b};Qn(!0);try{let M=await hn(x);return{sessionId:M.sid,session:M.result.data.session??null}}finally{Qn(!1)}},[hn,Zt,ie,b]),Ft=Jn(async x=>{let M=lr.current;if(!M)return;let j=pn.current,R=await M(x);pn.current===j&&(U(R),R.data.session&&it(R.data.session))},[]);Xn(()=>{let x=!1,M;if(Dn(null),yn){let Oe=at.current;return jn(mn),Kt(!1),En.current===yn?()=>{x=!0}:(it(Zi(Oe,T)),(async()=>{let W=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),_=mn==="auto"&&!In.current&&!W;_&&(Ot(null),rt(null),et("processing"));try{let m=await _e.current(void 0,We=>{M=We}),re=m.result.data.session??null;It.current=sa(m.result);let ne=oi(m.result),Te=qa(m.sid||re?.id);if(!x&&_&&re&&!ne&&!Te){In.current=!0,await Gc(yn,m.sdkGeneratedIdempotencyKey,()=>bn.current(re,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:m.result.autoProcessingError,initialAutoProcessingPending:m.result.autoProcessingPending,autoProcessingAttempted:m.result.autoProcessingAttempted,sessionId:m.sid||re.id}));return}!x&&_&&((ne||Te)&&(In.current=!0),et(null),rt(null))}catch(m){if(x)return;let re=m instanceof $t||typeof m=="object"&&m!==null&&"code"in m?m.code:void 0;if(_&&re==="session_auto_completed"){In.current=!0,et("success"),await Bo(1200),x||(_t(()=>{se.current?.({status:"succeeded"})}),et(null),rt(null));return}_&&(et(null),rt(null));let ne=m instanceof $t?m:new $t(m instanceof Error?m.message:"Failed to create session","api_error");Dn(ne)}finally{M?.(),M=void 0}})(),()=>{x=!0,M?.()})}Kt(!0);async function j(){let Oe=!1;try{let W=new pa(V,{telemetry:!1}),_=await W.getUnifiedCheckoutSession(ot,t);if(x)return;U(_);let m=_.data.session??null;if(it(m),!m)throw new $t("No session data returned","api_error");let re=m.checkoutMode;if(re==="setup")throw new $t("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(m.status==="authorized"){Kt(!1),_t(()=>{se.current?.(Ir(m,ot)),dr.current?.(m.successUrl??"")});return}if(m.status==="complete"){Kt(!1),_t(()=>{dr.current?.(m.successUrl??"")});return}if(m.status==="expired")throw Go(m);Oe=!0;let ne=T??re??"full";jn(ne),pn.current+=1;let Te=m.clientSecret||t;lr.current=m.buyerIdentified===!1&&Te?jr(W,ot,Te,{...m.customer?.id?{userId:m.customer.id}:{}}):void 0,X(!1),un(!1);let We=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),xe=oi(_);if(ne==="auto"&&!In.current&&!We&&!xe){In.current=!0;let Pe=R(_);try{if(await bn.current(m,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Pe,sessionId:ot||m.id}),x)return;await Pe,x||Kt(!1);return}catch{if(x)return;await Pe,x||Kt(!1);return}}await R(_),x||Kt(!1)}catch(W){if(x)return;Oe&&$({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),W instanceof $t?!Oe&&!Jc(W)&&ri(V,o,Rt,"NETWORK_REQUEST_FAILED","session_read"):ri(V,o,Rt,"INTERNAL_SDK_ERROR","checkout_mount");let _=W instanceof $t?W:new $t(W instanceof Error?W.message:"Failed to initialize checkout","api_error");Dn(_),Kt(!1)}}async function R(Oe){let{publishableKey:W,paypalPublishableKey:_}=sa(Oe);It.current={publishableKey:W,paypalPublishableKey:_};let{flopay:m,paypalFlopay:re}=await la({publishableKey:W,paypalPublishableKey:_,billingApiUrl:V,locale:l,telemetry:o});Ye.current=m,Ie(m),E.current=re,Y(re)}return j(),()=>{x=!0}},[T,yn,mn,qe,t]);let ur=Jn(async()=>{if(!(cn||!b)){Cn(!0),Ot(null);try{await en(b,{attempt3DS:!0,fallbackToFull:!0,sessionId:ot||b.id})}finally{Cn(!1)}}},[ot,cn,en,b]),Nn=di(H),pr=oi(H),On=Fn(()=>{if(!(!H||!b||!H.data.stripe?.publishableKey))return{billingApiUrl:V}},[H,b,V]),vn=!!(n&&!ke&&ce==="buttons"&&ee&&mn==="full"),zt=Fn(()=>({session:b,loading:Nt,error:Gt,checkoutMode:rn,inlineSessionDraft:At,applyInlineSessionPatch:vn?Xt:void 0,inlineSessionPatchProcessing:Zt,claimPending:Mt,claimRequiresIdentity:er,claimBuyerIdentity:Ft}),[b,Nt,Gt,rn,At,vn,Xt,Zt,Mt,er,Ft]),Fr=!!n&&ce==="buttons"&&!pr&&(!O||!On),_n=Sn?Z(Wn,{status:Sn,errorMessage:sr,authorized:Ln}):null;if(Nt){if(s)return jt(Zn,{children:[s,_n]});if(ce==="buttons"){let x=Ee?.buttonsLayout?.cardButton?.borderRadius??Ee?.appearance.variables?.borderRadius??8,M=j=>Z("div",{style:{height:j,borderRadius:x,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return jt(Zn,{children:[jt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[S&&M(Ar),ve&&(v||ye)&&M(Ar),ve&&M(Ar),Z("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),_n]})}return jt(Zn,{children:[jt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[Z("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),Z("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),_n]})}return Gt?C?Z(qn.Provider,{value:zt,children:C(Gt)}):Z(qn.Provider,{value:zt,children:Z("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Gt.message})}):Fr?jt(Zn,{children:[Z(qn.Provider,{value:zt,children:Z(od,{onButtonClick:Fe,showPayPal:S,showStripe:ve,showApplePay:v,showGooglePay:ye,theme:de,buttonsTheme:we,buttonsStyles:Qe,cardButtonContent:he,cardBackButtonContent:Bt,cardTitleContent:Xe})}),_n]}):pr&&b&&Nn?jt(Zn,{children:[Z(qn.Provider,{value:zt,children:jt("div",{className:ze,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[on&&Z(Gr,{icon:!1,children:on}),Kn==="retrying"&&Z("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Kn==="exhausted"&&jt("div",{role:"alert",children:[Z("div",{children:"PayPal is temporarily unavailable. Please try again."}),Z("button",{type:"button",onClick:Pr,children:"Retry PayPal"})]}),Mt?s??Z("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Ar,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:Z("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):Kn!=="exhausted"?Z("div",{"aria-hidden":Kn==="retrying"?!0:void 0,style:Kn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:Z(ps,{sessionId:ot,nonce:b.clientSecret||void 0,billingApiUrl:V,email:b.customer?.email||At?.account?.email,billingName:[b.customer?.firstName,b.customer?.lastName].filter(Boolean).join(" ")||[At?.account?.firstName,At?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Ft,clientId:Nn.clientId,environment:Nn.environment,currency:(b.currency??"usd").toUpperCase(),isSubscription:b.mode==="subscription",providerObjectType:Nn.providerObjectType,onComplete:y,onErrorChange:Ot,onDecline:B,onButtonClick:Fe,onInitializationStateChange:nr,allowAutomaticRetry:Qt===0,session:b,telemetry:o,telemetryContext:Rt,onInstrument:yt,debug:Q},`${G}:paypal-init-${Qt}`)}):null]})}),_n]}):!O||!On?Z(Zn,{children:_n}):rn==="confirm"?jt(Zn,{children:[Z(qn.Provider,{value:zt,children:Z(ra,{flopay:O,paypalFlopay:k,options:On,onInstrument:yt,children:jt("div",{className:ze,children:[on&&Z("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:on}),Ue?Ue({onConfirm:ur,isProcessing:cn}):Z("button",{type:"button",onClick:ur,disabled:cn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:cn?"not-allowed":"pointer",opacity:cn?.6:1},children:cn?"Processing...":oe??"Confirm Purchase"})]})},G)}),_n]}):jt(Zn,{children:[Z(qn.Provider,{value:zt,children:Z(ra,{flopay:O,paypalFlopay:k,options:On,onInstrument:yt,children:ke?jt(Zn,{children:[on&&Z("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:on}),Z(rd,{sessionId:ot,nonce:b?.clientSecret||void 0,billingApiUrl:V,session:b,children:ke})]}):Z(ti,{sessionId:ot,nonce:b?.clientSecret||void 0,email:b?.customer?.email||At?.account?.email,userId:b?.customer?.id||At?.account?.userId,firstName:b?.customer?.firstName||At?.account?.firstName,lastName:b?.customer?.lastName||At?.account?.lastName,totalAmount:b?Math.round($c(b).total*100):0,currency:b?.currency?.toLowerCase()??"usd",onComplete:y,onError:f,onDecline:B,error:on,onErrorChange:Ot,showPayPal:S,showStripe:ve,enabledPaymentMethods:K??H?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:H?.data.stripe?.enabledPaymentMethodCountries,showApplePay:v,showGooglePay:ye,layout:ce,theme:de,buttonsTheme:we,buttonsStyles:Qe,appearance:nt,cardButtonContent:he,cardBackButtonContent:Bt,cardTitleContent:Xe,onButtonClick:Fe,onBeforeButtonClick:ee,onBuyerIdentityReady:Ft,enableAVS:te,...F?{cardFieldOrder:F}:{},...Le?{cardPreFormSlot:Le}:{},avsLayout:Ne,country:b?.customer?.country,city:b?.customer?.city,state:b?.customer?.state,onCountryChange:A,onZipChange:u,avsCheck:!!te,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ke?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",className:ze,directPaypal:di(H),isSubscription:b?.mode==="subscription",session:b,dataAttachmentPending:Mt,dataAttachmentRequiresIdentity:er,debug:Q})},G)}),_n]})}function rd({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return Z(Zn,{children:ni.Children.map(o,a=>{if(!ni.isValidElement(a))return a;let l=a.props,s={};return l.sessionId||(s.sessionId=e),!l.nonce&&t&&(s.nonce=t),l.billingApiUrl||(s.billingApiUrl=n),r?.customer&&(l.email||(s.email=r.customer.email),l.userId||(s.userId=r.customer.id),l.firstName||(s.firstName=r.customer.firstName),l.lastName||(s.lastName=r.customer.lastName)),Object.keys(s).length===0?a:ni.cloneElement(a,s)})})}function od({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:s,cardButtonContent:C,cardBackButtonContent:y,cardTitleContent:f}){let[h,B]=xt(!1),A=Fn(()=>Ys(a),[a]),u=Fn(()=>{let v=A?.buttonsLayout??Hc(l);return s?{...v,...s,cardButton:{...v.cardButton,...s.cardButton},cardFormContainer:{...v.cardFormContainer,...s.cardFormContainer},backButton:{...v.backButton,...s.backButton},backButtonIcon:{...v.backButtonIcon,...s.backButtonIcon},submitButton:{...v.submitButton,...s.submitButton},title:{...v.title,...s.title}}:v},[A,l,s]),S=A?.buttonsLayout?.cardButton?.borderRadius??A?.appearance.variables?.borderRadius??8,ve=v=>Z("div",{style:{height:v,borderRadius:S,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),K=C===void 0?{boxSizing:"border-box",height:Ar,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(h){let v=u.cardInputBorder??"#e5e7eb",ye=u.cardInputBackground??"white",Q=zr(y),ce=zr(f);return jt("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:[jt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[jt("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:[Z("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:Z("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:Z("path",{d:"M15 18l-6-6 6-6"})})}),Z(qr,{content:y})]}),ce?Z("div",{style:{flex:1}}):Z("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:Z(vo,{content:f})})]}),Z("div",{style:{backgroundColor:ye,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:Z("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),jt("div",{style:{display:"flex"},children:[Z("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:Z("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Z("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:Z("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),Z("div",{style:{backgroundColor:ye,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:Z("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Z("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),Z("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 jt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ve(Ar),n&&(r||o)&&ve(Ar),n&&Z("button",{type:"button",onClick:()=>{e?.("card"),B(!0)},style:{width:"100%",...K,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:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:Z(Ur,{content:C})}),Z("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as md,jsx as no,jsxs as yd}from"react/jsx-runtime";var ld=44;function Xs(e){return new Promise(t=>setTimeout(t,e))}function cd(e,t){return e instanceof ro?e:new ro(e instanceof Error?e.message:t,"api_error")}function dd(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ud(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 pd({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:s,subscriptions:C,account:y,successUrl:f,cancelUrl:h,couponCodes:B,tagsData:A,utmMetadata:u,billingApiUrl:S,locale:ve,theme:K,appearance:v,buttonsTheme:ye,buttonsStyles:Q,onSuccess:ce,onError:de,onDecline:we,children:Qe,disabled:he=!1,type:Bt="button",style:Xe,...Ae}){let Fe=Fo(()=>ad(S),[S]),ee=Fo(()=>ud({createSession:n,clientId:a,products:l,items:s,subscriptions:C,account:y,successUrl:f,cancelUrl:h,couponCodes:B,tagsData:A,utmMetadata:u}),[y,h,a,B,n,l,s,C,f,A,u]),[te,F]=Do(!1),[Le,Ne]=Do(null),[ze,Ke]=Do(null),[ke,T]=Do(!1),[oe,Ue]=Do(null),ae=to(!0),V=to(null),Ee=to(oe),nt=to(ce),dt=to(de),De=to(we);eo(()=>{Ee.current=oe},[oe]),eo(()=>{nt.current=ce},[ce]),eo(()=>{dt.current=de},[de]),eo(()=>{De.current=we},[we]),eo(()=>(ae.current=!0,()=>{ae.current=!1,V.current?.abort()}),[]),eo(()=>{if(typeof window>"u")return;let g=$=>{$.key==="Escape"&&Ue(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let H=vr((g,$=_o)=>{De.current?.(Ut($,g,{code:g.code,declineCode:g.declineCode}))},[]),U=vr(async g=>{ae.current&&(Ke(null),T(g.result.status==="authorized"),Ne("success"),await Xs(1200),ae.current&&nt.current?.(g))},[]),O=vr(async(g,$)=>{ae.current&&(dt.current?.(g),$?.emitDecline&&H(g,$.method),Ke(g.message),T(!1),Ne("error"),await Xs(1500))},[H]),Ie=vr(async(g,$,lt)=>{let yt=g.data.session??null;if(!yt)throw new ro("No session data returned","api_error");let ie=yt.clientSecret||t;if(Kr(yt)){await U({result:Ir(yt,$),session:yt,sessionId:yt.id||$,autoCompleted:!1});return}if(yt.status==="expired")throw Go(yt);try{if(g.autoProcessingPending){let Nt=(await new fi(Fe).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!Kr(Nt))throw Jo(Nt);await U({result:Ir(Nt,$),session:Nt,sessionId:Nt.id||$,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&$&&ie){let ot=new AbortController;V.current=ot;let qe;try{qe=await Ps({billingApiUrl:Fe,sessionId:$,nonce:ie,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:ot.signal})}finally{V.current===ot&&(V.current=null)}if(qe.status==="declined")throw hr({type:qe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:qe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let Gt=(await new fi(Fe).waitForCheckoutSessionCompletion($,{initialDelayMs:0,nonce:ie})).data.session;if(!Kr(Gt))throw hr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await U({result:Ir(Gt,$),session:Gt,sessionId:Gt.id||$,autoCompleted:!1});return}throw hr(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(lt?.fromCreateSession&&g.autoProcessingAttempted===!0)throw hr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let kt=await Xr({billingApiUrl:Fe,sessionId:$??yt.id,session:yt,nonce:ie});if(kt.type!=="success")throw hr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await U({result:kt.result,session:yt,sessionId:yt.id||$,autoCompleted:!1})}catch(kt){let ot=To(kt),qe=yt.id||$;await O(ot,{emitDecline:!0,method:ot.checkoutMethod??_o}),dd(ot,qe)&&qe&&ae.current&&Ue({sessionId:qe,errorMessage:ot.message,nonce:ie||void 0})}},[t,Fe,O,U]),Ye=vr(async g=>{if(Ae.onClick?.(g),!(g.defaultPrevented||he||te)){if(Ue(null),e&&ee){let $=new ro("Provide either sessionId or create-session props, not both.","validation_error");await O($),ae.current&&(Ne(null),Ke(null));return}if(!e&&!ee){let $=new ro("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await O($),ae.current&&(Ne(null),Ke(null));return}F(!0),Ke(null),T(!1),Ne("processing");try{let $=new fi(Fe);if(e){let lt=await $.getUnifiedCheckoutSession(e,t);await Ie(lt,e);return}try{let lt=await $.createAndFetchSession({...ee});await Ie(lt,lt.data.session?.id??null,{fromCreateSession:!0})}catch(lt){if(lt instanceof ro&<.code==="session_auto_completed"){await U({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw lt}}catch($){await O(cd($,"Automatic payment failed. Please try again."))}finally{ae.current&&(Ne(null),Ke(null),F(!1))}}},[Ae.onClick,ee,he,te,t,Ie,Fe,e,O,U]),k=vr(g=>{let $=Ee.current;Ue(null),nt.current?.({result:g,session:null,sessionId:$?.sessionId??null,autoCompleted:!1})},[]),Y=vr(g=>{dt.current?.(g)},[]),E=vr(g=>{De.current?.(g)},[]),b=Fo(()=>sd(K),[K]),it=Fo(()=>{let g=b?.buttonsLayout??id(ye);return Q?{...g,...Q,cardButton:{...g.cardButton,...Q.cardButton}}:g},[b,ye,Q]),Pt=Fo(()=>{let g=b?.appearance;return v?g?{...g,...v,variables:{...g.variables,...v.variables}}:v:g},[v,b]),G=Pt?.variables,st=G?.colorPrimary??"#4A49FF",Ze=G?.colorPrimaryHover??bo(st,.12),Ct=G?.borderRadius??"8px";return yd(md,{children:[no("button",{...Ae,type:Bt,onClick:Ye,disabled:he||te,"aria-busy":te,style:{width:"100%",...Qe===void 0?{boxSizing:"border-box",height:ld,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...it.cardButton,...ei({themeBundle:b,resolvedPrimaryColor:st,resolvedBorderRadius:Ct,submitButtonStyle:it.submitButton,explicitPrimaryColor:G?.colorPrimary}),fontSize:it.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:he||te?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:he||te?.6:1,...Xe},onMouseEnter:g=>{Ae.onMouseEnter?.(g),!g.defaultPrevented&&!he&&!te&&(b||G?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Ze)},onMouseLeave:g=>{Ae.onMouseLeave?.(g),!g.defaultPrevented&&(b||G?.colorPrimary)&&(g.currentTarget.style.backgroundColor=st)},onMouseDown:g=>{Ae.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{Ae.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:no(Ur,{content:Qe})}),Le&&no(Wn,{status:Le,errorMessage:ze,authorized:ke}),oe&&no("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&Ue(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:no("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:no(yi,{sessionId:oe.sessionId,nonce:oe.nonce,checkoutMode:"full",billingApiUrl:Fe,locale:ve,theme:K,...Pt?{appearance:Pt}:{},buttonsTheme:ye,buttonsStyles:Q,initialErrorMessage:oe.errorMessage,cardTitleContent:null,onComplete:k,onError:Y,onDecline:E})})})]})}export{na as DirectPayPalButton,pd as FloPayAutomaticPaymentButton,hl as FloPayCardSetup,gl as FloPayCardSetupError,yi as FloPayCheckout,ra as FloPayProvider,ti as SplitCardForm,Ba as VaultCardFields,fp as dropThirdPartyOnlyError,_l as useCheckout,fr as useFloPay,Da as usePayPalFloPay};
|