@flopay/react 1.8.3 → 1.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as tt,b as Yn,c as wa,d as po,e as Oi,f as zi,g as sl,h as ll}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as ap}from"@flopay/shared";import{PaymentAPI as si}from"@flopay/js";import{FloPayError as Zr,resolveBillingApiUrl as Gc,resolveButtonsLayoutTheme as Wc,resolveTheme as Jc}from"@flopay/shared";import{useCallback as hr,useEffect as Wr,useMemo as Eo,useRef as Jr,useState as Ro}from"react";import{Fragment as Or,jsx as wn,jsxs as Ui}from"react/jsx-runtime";function cl(){return Ui(Or,{children:[Ui("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[wn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),wn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",wn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:wn("path",{d:"M9 18l6-6-6-6"})})]})}function dl(){return wn(Or,{children:"Go back"})}function ul(){return wn(Or,{children:"Secure card checkout"})}function Nr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Dr({content:e}){return wn(Or,{children:e===void 0?wn(cl,{}):e})}function Lr({content:e}){return wn(Or,{children:e===void 0?wn(dl,{}):e})}function mo({content:e}){return wn(Or,{children:e===void 0?wn(ul,{}):e})}import{FloPayError as qi,isMoneySettledOutcome as pl,isSetupIntentClientSecret as ld}from"@flopay/shared";function $i(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function ka(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ji(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,c)=>a+(c.overrideAmount??c.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,c)=>({uuid:`synthetic-${a.type??"item"}-${c}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function kn(e){let t=e?.trim().split(/\s+/).filter(Boolean)??[];return t.length===0?{}:{firstName:t[0],lastName:t.length>1?t.slice(1).join(" "):void 0}}function Ia(e,t){return t?{...e,...t}:e}function $t(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var ml=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function cr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of ml)if(n.test(t))return r;return e}function kr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function zr(e){return e?.status==="authorized"||e?.status==="complete"}function Ki(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function qo(e){let t=Ki(e);return new qi(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $o(e){let t=Ki(e);return new qi(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function jo(e,t){return e==="processing"||pl(e,t)}function Vi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Hi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function yo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as ia,SESSION_CREATE_TELEMETRY as Ac}from"@flopay/js";import{buildCheckoutDisplayData as Mc,classifyTelemetryFailure as Ms,FloPayError as Kt,foldIntoProducts as Bc,isDetachedSessionEligible as Fc,resolveBillingApiUrl as Nc,resolveButtonsLayoutTheme as Dc,resolveIdempotencyKey as Bs,resolveSessionCurrency as Lc,resolveTheme as Ls,SDK_VERSION as Os,telemetryStatusClass as Oc}from"@flopay/shared";import Ga,{useCallback as Wn,useEffect as Jn,useMemo as En,useRef as At,useState as Et}from"react";import{createContext as Yi}from"react";var In=Yi({flopay:null,paypalFlopay:null,billingApiUrl:""}),Ln=Yi({session:null,loading:!1,error:null});import{PaymentAPI as Ta}from"@flopay/js";import{classifyTelemetryFailure as Tl,FloPayError as Xi,generateIdempotencyKey as Al,isValidEmail as Go,normalizeGatewayEnvironment as Ml,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Aa,SDK_VERSION as Bl}from"@flopay/shared";import{loadScript as Fl}from"@paypal/paypal-js";import{useCallback as ho,useEffect as ft,useMemo as bo,useRef as Ve,useState as nr}from"react";import{isValidEmail as yl}from"@flopay/shared";import{useCallback as Gi,useEffect as fl,useRef as Wi,useState as Ra}from"react";import{jsx as Ea,jsxs as Ur}from"react/jsx-runtime";function fo(e){return!!(e.firstName?.trim()||e.lastName?.trim())}function qr(){let[e,t]=Ra(null),n=Wi(null),r=Wi(0),o=Gi((c,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:c,identity:s}),new Promise(S=>{n.current=S})),[]),a=Gi(c=>{let s=n.current;n.current=null,t(null),s?.(c)},[]);return fl(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Ir({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[c,s]=Ra(e.email?.trim()??""),[S,b]=Ra([e.firstName,e.lastName].filter(Boolean).join(" ")),g=yl(c.trim())&&!!S.trim();return Ur("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[Ur("div",{style:{fontWeight:700},children:["Continue with ",t]}),Ur("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Ea("input",{type:"email",autoComplete:"email",required:!0,value:c,onChange:m=>s(m.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ur("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",Ea("input",{type:"text",autoComplete:"name",required:!0,value:S,onChange:m=>b(m.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ur("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Ea("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Ur("button",{type:"button",disabled:!g||o,onClick:()=>{let m=kn(S);n({email:c.trim(),firstName:m.firstName,lastName:m.lastName})},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function gl(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Er(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function tr(e){if(typeof e!="object"||e===null)return;let t=e;return Er(t.code)??Er(t.type)??Er(t.name)}function $r(e){if(!(typeof e!="object"||e===null))return Er(e.decline_code)}function go(e){return typeof e!="object"||e===null?!1:Er(e.type)?.toLowerCase()==="card_error"||$r(e)!==void 0}function dr(e){let t=gl(e)?.toLowerCase()??"",r=`${tr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as hl}from"@flopay/shared";import{useContext as Ko}from"react";function ur(){return Ko(In).flopay}function _a(){return Ko(In).paypalFlopay??null}function bl(){return Ko(Ln)}function Ji(){return Ko(In).billingApiUrl||hl()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Cl}from"@flopay/shared";import{useCallback as Sl,useRef as Ho}from"react";import{useEffect as vl,useLayoutEffect as Pl}from"react";var Vo=typeof window>"u"?vl:Pl;var wl={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function kl(e){return e==="stripe"||e==="paypal"?e:void 0}function Il(e){let t=kl(e.provider),n={schemaVersion:Cl,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=wl[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var xa=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function jr(e,t){let n=Ho(e);n.current=e;let r=Ho(new Set),o=Ho(t),a=Ho(t);return Vo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Sl(c=>{if(a.current!==t)return;let s=Il(c);if(s){if(xa.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}tt(()=>n.current?.(s))}},[t])}var El=Symbol.for("@flopay/js.telemetry.bridge.v1"),Rl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function _l(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function xl(e){let t=_l(),n=(o,a)=>o?o.bind(e):a,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Yo(e){let t=globalThis[Rl];return xl(t?.(e)??{})}function jt(e){if(e)return e[El]}import{jsx as pr,jsxs as Ma}from"react/jsx-runtime";var Wo=45,Nl=1e3,Dl=11e3,Ll=["https://www.paypal.com","https://www.sandbox.paypal.com"],Zi="We couldn't open PayPal. Try again or choose another payment method.",Ol={width:"100%",minHeight:Wo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Qi(e){return e.includes("No ack for postMessage init()")&&Ll.some(t=>e.includes(t))&&e.includes("10000ms")}function zl(e){return e?`${Zi} Allow pop-ups for this site, then try again.`:Zi}function Ul(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function es({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:c,environment:s,currency:S,isSubscription:b,providerObjectType:g,onTokenizedBody:m,onComplete:M,onErrorChange:D,onDecline:u,onTechnicalFailure:w,isProcessing:ve=!1,onLoadStateChange:H,onInitializationStateChange:P,allowAutomaticRetry:fe=!0,onButtonClick:Q,runBeforeButtonClick:ce,session:oe,existingOrderId:Ce,telemetry:He,telemetryContext:be,onInstrument:Rt,debug:De=!1}){let Te=ur(),Ae=jr(Rt,e),ee=bo(()=>{if(Te)return null;let v=Yo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Bl,enabled:He!==!1});return v.setCheckoutContext(be??{}),v.beginCheckout(be??{}),v},[n,Te,He,be?.checkoutMode,be?.layout]),J=bo(()=>jt(Te),[Te]);ft(()=>()=>{ee&&ee.flush().catch(()=>{}).finally(()=>ee.destroy())},[ee]);let L=bo(()=>({error:v=>{J?J.error(v):ee?.error(v),Ae({class:"technical_error",errorCode:v.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":v.errorCode,requestCategory:v.requestCategory,provider:v.provider})},log:v=>{J?J.log(v):ee?.log(v),Ae({class:"lifecycle",name:v.name,provider:v.provider})},performance:v=>{J?J.performance(v):ee?.performance(v)},terminal:v=>{J?J.terminal(v):ee?.terminal(v)},startTiming:()=>J?.now()??ee?.now()??0,elapsed:v=>J?.elapsed(v)??Math.max(0,(ee?.now()??v)-v)}),[Ae,J,ee]),me=Ve(null),et=Ve(0),Ue=Ve(null),Ye=Ve(!1),[te,T]=nr(!1),[ae,Fe]=nr(!1),[ie,j]=nr(0),_e=Ve(0),[Je,We]=nr(!1),Se=Ve(!1),G=Ve(!1),[Y,$]=nr(!1),[we,Me]=nr(!1),[x,K]=nr(!1),[I,C]=nr(!1),nt=kn(o??[oe?.customer?.firstName,oe?.customer?.lastName].filter(Boolean).join(" ")),St=!x&&a&&!Go(r?.trim()||oe?.customer?.email?.trim())?{email:r?.trim()||oe?.customer?.email?.trim(),firstName:nt.firstName,lastName:nt.lastName}:null,{request:de,collect:ct,finish:it}=qr(),rt=bo(()=>n.replace(/\/+$/,""),[n]),je=g??(b?"subscription":"order"),y=g==="order"||g==="setup_token",U=bo(()=>JSON.stringify([rt,c,S,s??"",je,y,e,Ce??""]),[rt,c,S,s,Ce,je,y,e]),Xe=Ve(U),dt=Xe.current!==U,[Mt,Bt]=nr([]),W=v=>{De&&Bt(ut=>[...ut,`${new Date().toISOString().slice(11,23)} ${v}`])},Le=Ve(m),Wt=Ve(M),wt=Ve(D),Ot=Ve(u),Rn=Ve(w),_n=Ve(Q),Zn=Ve(H),Jt=Ve(P),cn=Ve(a),dn=Ve(ce),Ft=Ve(oe),vn=Ve(r),bt=Ve(o),ir=Ve(null),Ht=Ve(e),sr=Ve(t),Nt=Ve(null),zn=Ve(0),ot=Ve(null),_t=Ve(null),xt=Ve(new Map),tn=Ve(new Map),un=Ve(!1);ft(()=>(un.current=!0,()=>{un.current=!1}),[]),ft(()=>{Le.current=m},[m]),ft(()=>{cn.current=a},[a]),ft(()=>{Wt.current=M},[M]),ft(()=>{wt.current=D},[D]),ft(()=>{Ot.current=u},[u]),ft(()=>{Rn.current=w},[w]),ft(()=>{_n.current=Q},[Q]),ft(()=>{Zn.current=H},[H]),ft(()=>{Jt.current=P},[P]),ft(()=>{dn.current=ce},[ce]),ft(()=>{Ft.current=oe},[oe]),ft(()=>{vn.current=r},[r]),ft(()=>{bt.current=o},[o]),ft(()=>{sr.current=t},[t]),ft(()=>{Ht.current!==e&&(Ht.current=e,ir.current=null,K(!1),C(!1))},[e]),ft(()=>{_e.current=ie},[ie]),ft(()=>{Je&&Ue.current?.focus()},[Je,ie]);let pn=ho(()=>{window.setTimeout(()=>{Ue.current?.focus()},0)},[]),Un=ho(async v=>{C(!0);try{await cn.current?.(v),ir.current=v,vn.current=v.email,bt.current=[v.firstName,v.lastName].filter(Boolean).join(" "),K(!0),tt(()=>wt.current?.(null))}catch(ut){let qe=ut instanceof Error?ut.message:"Buyer details could not be attached to checkout.";tt(()=>wt.current?.(qe))}finally{C(!1)}},[]),qn=ho(()=>{T(!1),j(v=>v+1)},[]),zt=ho(()=>{We(!1),(me.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??me.current)?.focus?.()},[]);ft(()=>{!te||!Ye.current||(Ye.current=!1,zt())},[zt,te,ie]);let X=ho((v,ut)=>{let qe=Rn.current;if(qe){qe("paypal",v,ut);return}wt.current?.(zl(ut?.popupBlocked??dr(v)))},[]),Pn=()=>{ot.current?.timer&&(clearTimeout(ot.current.timer),ot.current.timer=null)},xn=()=>{Pn();let v=zn.current+1;return zn.current=v,_t.current=null,ot.current={generation:v,timer:null,yieldedControl:!1},We(!1),v},Qn=v=>v!==void 0&&ot.current?.generation!==v?!1:(Pn(),ot.current=null,_t.current=null,!0),br=v=>{let ut=v?.generation??ot.current?.generation??zn.current;(!v?.generation||ot.current?.generation===ut)&&(Pn(),ot.current=null),_t.current=ut,v?.showRetry&&We(!0),v?.remount&&qn(),v?.focus!==!1&&pn()},Tr=v=>ot.current?.generation===v&&_t.current!==v,Tn=v=>{typeof document<"u"&&document.visibilityState!=="visible"||(Pn(),v.timer=setTimeout(()=>{ot.current?.generation===v.generation&&(ot.current=null,_t.current=v.generation,X(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),We(!0),qn(),pn())},600))},mn=()=>{let v=ot.current;v?.yieldedControl&&Tn(v)},Be=()=>{let v=ot.current;v&&(v.yieldedControl=!0,Pn())},Xt=v=>{let ut=Nt.current;return ut&&tn.current.set(v,ut),v};ft(()=>{let v=()=>{document.visibilityState==="visible"?mn():Be()};return document.addEventListener("visibilitychange",v),window.addEventListener("focus",mn),window.addEventListener("blur",Be),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("focus",mn),window.removeEventListener("blur",Be),Pn()}},[]),ft(()=>{Xe.current!==U&&(Xe.current=U,Se.current=!1,G.current=!1,T(!1),Fe(!1),$(!1),Jt.current?.("loading"))},[U]),ft(()=>{tt(()=>Zn.current?.(te&&!Y))},[te,Y]);let Dt=Ml(s);ft(()=>{let v=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",ut=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(W(`mount clientId=${v} env=${s??"(unset)"}\u2192${Dt??"live"} ccy=${S} sub=${b}`),W(`ua=${ut.slice(0,80)}${ut.length>80?"\u2026":""}`),!c){W("FAIL: clientId empty \u2014 gateway misconfigured"),$(!0),L.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!me.current){W("FAIL: containerRef not attached");return}et.current=L.startTiming(),L.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let qe=!1,yn=!1,Ze=()=>qe||yn,Ut,lr=!1,jn=()=>{Ut=Al(),Ut||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),lr=!0},Cn=null,Zt=!1,fn=null,gn=!1,xe=()=>{!fn||gn||(gn=!0,fn.close().catch(()=>{}))},kt=null,Tt=()=>{kt!==null&&(L.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"overlay_return",durationMs:L.elapsed(kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),kt=null)},An=!1,hn=me.current,Mn=null,Bn=null,qt=[],on=d=>{if(!d||typeof d.getBoundingClientRect!="function")return"(no rect)";let p=d.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},an=d=>{if(!d)return"(empty)";try{let p=new URL(d,typeof window<"u"?window.location.href:"https://localhost"),k=p.pathname.toLowerCase();return k.includes("checkcaptcha")||k.includes("captcha")?`CAPTCHA(${p.host}${k})`:k.includes("risk")||k.includes("challenge")?`RISK(${p.host}${k})`:k.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${k}`.slice(0,100)}catch{return d.slice(0,80)}},er=d=>{let p=d.getAttribute("src"),k=d.getAttribute("srcdoc"),Ee=d.getAttribute("name"),q=d.getAttribute("sandbox"),F=[];return p&&F.push(`src=${an(p)}`),k&&F.push(`srcdoc[${k.length}ch]`),!p&&!k&&F.push("src=(empty) srcdoc=(empty)"),Ee&&F.push(`name=${Ee.slice(0,40)}`),q!==null&&F.push(`sandbox="${q.slice(0,40)}"`),F.join(" ")},Ar=d=>{if(!(d instanceof HTMLIFrameElement))return"";try{let p=d.contentDocument;if(!p)return"cd=null";let k=p.body?.children.length??0,Ee=p.body?.innerHTML.length??0,q=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${k}children,${Ee}ch] head[${q}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},Fn=[],Kn=d=>{if(Ze())return;let p=d.message??String(d.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(W(`window:error ${p.slice(0,140)}`),Fn.push(p))},Qt=d=>{if(Ze())return;let p=d.reason instanceof Error?d.reason.message:String(d.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(W(`window:rejection ${p.slice(0,140)}`),Fn.push(p))};De&&typeof window<"u"&&(window.addEventListener("error",Kn),window.addEventListener("unhandledrejection",Qt));let at={value:0};if(De&&typeof PerformanceObserver<"u")try{Bn=new PerformanceObserver(d=>{if(!Ze())for(let p of d.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;at.value+=1;let k=Math.round(p.duration);W(`net ${k}ms ${p.name.slice(0,90)}`)}}),Bn.observe({type:"resource",buffered:!0})}catch{}let Yt=()=>{for(Mn?.disconnect(),Mn=null,Bn?.disconnect(),Bn=null;qt.length;)clearTimeout(qt.pop());De&&typeof window<"u"&&(window.removeEventListener("error",Kn),window.removeEventListener("unhandledrejection",Qt))},_=d=>{if(!d)return!1;let p=d.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},E=d=>{if(Ze()||_(d))return;let p=cr(d)??d;tt(()=>wt.current?.(p))},V=d=>{qe||($(!0),d.includes("paypal_ineligible")||L.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",d))},Z=(d,p=!1)=>{if(qe)return;let k=Se.current||!fe;if(Zt)return;Zt=!0,yn=!0,Yt(),xe();let Ee=p||Qi(d);if(Ee&&fe&&!Se.current){Se.current=!0,T(!1),Me(!1),Fe(!0),Jt.current?.("retrying"),Cn=setTimeout(()=>{qe||j(q=>q+1)},Nl);return}if(Ee||k){if(T(!1),Me(!1),Fe(!1),$(!0),Jt.current?.("exhausted"),!G.current){G.current=!0;let q=Qi(d)?"paypal_init_timeout":p?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",q)}return}V(d)};$(!1);let $e=async(d,p=Nt.current)=>{if(Ze())return;let k=p?.sessionId??e;if(Le.current){await Le.current(d,{sessionId:k,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let Ee=L.startTiming();L.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let q=()=>{L.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"processing",durationMs:L.elapsed(Ee),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let F=Ft.current,Ge=p?.accountPatch?.email??vn.current,Qe=p?.accountPatch?.userId??F?.customer?.id??F?.accountData?.userId??"",ue=await new Ta(rt,{telemetry:!1}).processPayment(Qe,{sessionId:k,nonce:p?.nonce??sr.current,tokenizedData:d,accountData:{userId:Qe,email:Ge??F?.customer?.email??"",firstName:p?.accountPatch?.firstName??F?.customer?.firstName??F?.accountData?.firstName??"",lastName:p?.accountPatch?.lastName??F?.customer?.lastName??F?.accountData?.lastName??"",country:p?.accountPatch?.country??F?.customer?.country??F?.accountData?.country??void 0,zip:p?.accountPatch?.zip??F?.customer?.zip??F?.accountData?.zip??void 0}});if(ue.ok){if(yn||qe&&un.current)return;q(),L.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),tt(()=>Wt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ze())return;let A=await ue.json().catch(()=>null),le=A?.message??"PayPal payment failed.",st=cr(le)??le;q(),ue.status===400&&(typeof A?.declineCode=="string"||!Array.isArray(A?.fields))?L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ue.status===400||ue.status===422?L.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):L.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ue.status>=500?"5xx":ue.status>=400?"4xx":ue.status>=300?"3xx":"unknown",failureCategory:ue.status>=500?"server_error":void 0}),E(st),tt(()=>Ot.current?.($t("paypal",st,{code:A?.code,declineCode:A?.declineCode})));return}catch(F){if(Ze())return;q(),L.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ge=F instanceof Error?F.message:"PayPal payment failed.",Qe=cr(Ge)??Ge;E(Qe),tt(()=>Ot.current?.($t("paypal",Qe)));return}},ne=()=>new Xi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),B=d=>Ze()?Promise.reject(ne()):Promise.resolve(d),h=async d=>{if(Ze())throw ne();lr||jn();let p=Nt.current,k=p?.sessionId??e,Ee=p?.nonce??sr.current;L.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let q;try{q=await new Ta(rt,{telemetry:!1}).createSessionIntent(k,Ee??"",y?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Aa,paymentMethodId:null,intentKind:je==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Ut})}catch(F){throw L.error({...Tl(F,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),F}if(Ze())throw ne();if(q.provider!=="paypal"||q.providerObjectType!==je)throw new Error(d);return L.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),q.providerObjectId},f=(d,p)=>{let k=p?.nonce??sr.current;if(!k)return;let Ee=p?.sessionId??e,q=$r(d)??tr(d)??"provider_declined";new Ta(rt,{telemetry:!1}).reportSessionIntentDecline(Ee,k,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:q}).catch(()=>{})},O=ie;W("loadScript:scheduled (deferred 1 tick)");let pt=null,vt=setTimeout(()=>{if(qe){W("loadScript:skipped (cancelled before defer ran)");return}W("loadScript:start");let d=Dt==="live"?"production":Dt;pt=Fl({clientId:c,currency:S,...je==="subscription"?{intent:"subscription",vault:!0}:je==="order"?{intent:"capture"}:{},...d?{environment:d}:{},...d==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),pt.then(p=>{if(W(`loadScript:resolved inactive=${Ze()} ns=${!!p} buttons=${!!p?.Buttons}`),Ze())return;if(!p?.Buttons){W("FAIL: namespace missing Buttons factory"),Z("PayPal SDK did not expose the Buttons factory.");return}L.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"provider_ready",durationMs:L.elapsed(et.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let k=async(se,ue)=>{if(Ze()||_e.current!==O)return;let A=se.vaultSetupToken??se.subscriptionID??se.orderID??"",le=A?tn.current.get(A):xt.current.get(O);if(!(!le||!Tr(le.generation))&&Qn(le.generation)){tn.current.delete(A),xt.current.delete(le.surfaceKey),Tt();try{if(Me(!0),tt(()=>wt.current?.(null)),!A)throw new Xi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let st=Ft.current,Lt=kn(bt.current??[st?.customer?.firstName,st?.customer?.lastName].filter(Boolean).join(" ")),ge={email:le.accountPatch?.email?.trim()||vn.current?.trim()||st?.customer?.email?.trim(),firstName:le.accountPatch?.firstName?.trim()||Lt.firstName,lastName:le.accountPatch?.lastName?.trim()||Lt.lastName};if(!Go(ge.email)||!(ge.firstName||ge.lastName))try{let bn=Ul(await ue?.order?.get?.());ge={email:bn.email||ge.email,firstName:bn.firstName||ge.firstName,lastName:bn.lastName||ge.lastName}}catch{}if(cn.current&&(!Go(ge.email)||!(ge.firstName||ge.lastName))){let bn=await ct("PayPal",ge);if(!bn)return;ge=bn}Go(ge.email)&&(ge.firstName||ge.lastName)&&(le.accountPatch={...le.accountPatch,...ge},await cn.current?.(ge)),await $e(je==="setup_token"?{id:A,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Aa}:y?{id:A,isPaypal:!0,gateway:"paypal",paymentMethodType:Aa}:{id:A,isPaypal:!0},le)}catch(st){E(st instanceof Error?st.message:"PayPal capture failed.")}finally{Ze()||Me(!1)}}},Ee=p.Buttons({style:{layout:"horizontal",height:Wo,tagline:!1},onClick:async(se,ue)=>{if(Ze()){await ue.reject();return}jn();let A=dn.current,le={accountPatch:ir.current??void 0};if(A)try{let ge=await A("paypal");if(Ze()){await ue.reject();return}if(!ge.proceed){Nt.current=null,xt.current.delete(O),await ue.reject();return}le={sessionId:ge.sessionId,accountPatch:{...ir.current,...ge.accountPatch},nonce:ge.nonce}}catch(ge){W(`onClick:runBeforeButtonClick rejected msg=${(ge instanceof Error?ge.message:String(ge)).slice(0,120)}`),Nt.current=null,xt.current.delete(O),await ue.reject();return}tt(()=>_n.current?.("paypal"));let Lt={generation:xn(),surfaceKey:O,...le};Nt.current=Lt,xt.current.set(O,Lt),await ue.resolve(),L.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),kt=L.startTiming()},createOrder:je==="order"?Ce?()=>B(Ce).then(Xt):()=>h("Failed to create PayPal order.").then(Xt):void 0,createSubscription:je==="subscription"?Ce?()=>B(Ce).then(Xt):()=>h("Failed to create PayPal subscription.").then(Xt):void 0,createVaultSetupToken:je==="setup_token"?()=>h("Failed to create PayPal setup token.").then(Xt):void 0,onApprove:k,onCancel:()=>{if(Ze())return;let se=xt.current.get(O)??Nt.current;se&&xt.current.delete(se.surfaceKey),Nt.current=null,Tt(),L.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ye.current=!0,br({generation:se?.generation,remount:!0,focus:!1})},onError:se=>{if(Ze()||_e.current!==O)return;let ue=se instanceof Error?se.message:"PayPal failed to render.";if(W(`onError rendered=${An} msg=${ue.slice(0,120)}`),An){let A=xt.current.get(O)??Nt.current;if(A&&!Tr(A.generation)||!A&&_t.current===zn.current)return;if(_(ue)){Qn(A?.generation);return}if(Tt(),go(se)){L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),f(se,A),tt(()=>Ot.current?.($t("paypal",ue))),A&&xt.current.delete(A.surfaceKey),Nt.current=null,Qn(A?.generation);return}let le=ue.toLowerCase();L.error({errorCode:le.includes("popup")&&le.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),A&&xt.current.delete(A.surfaceKey),Nt.current=null,br({generation:A?.generation,remount:!0,showRetry:!0,focus:!0}),X(se,{code:"paypal_runtime_failed"});return}Z(ue)}}),q=Ee.isEligible();if(W(`isEligible=${q}`),L.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!q){T(!1),Z("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}fn=Ee,De&&W(`container:dims ${on(hn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),De&&typeof MutationObserver<"u"&&(Mn=new MutationObserver(se=>{if(!Ze()){for(let ue of se)if(ue.type==="childList")ue.addedNodes.forEach(A=>{if(!(A instanceof Element))return;let le=A.tagName.toLowerCase(),st=(A.getAttribute("title")??"").slice(0,40),Lt=le==="iframe"?` ${er(A)}`:"";W(`child+ ${le}${st?` title="${st}"`:""}${Lt} dims=${on(A)}`)});else if(ue.type==="attributes"&&ue.target instanceof Element){let A=ue.target;if(A.tagName.toLowerCase()!=="iframe")continue;let le=ue.attributeName;(le==="src"||le==="srcdoc")&&W(`attr~ iframe ${le}=${le==="srcdoc"?`[${(A.getAttribute("srcdoc")??"").length}ch]`:an(A.getAttribute("src"))} dims=${on(A)}`)}}}),Mn.observe(hn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ge=se=>{if(Ze()||An)return;let ue=hn.querySelectorAll("iframe"),A=typeof document<"u"&&"hasStorageAccess"in document;W(`watchdog:${se} container=${on(hn)} children=${hn.childElementCount} iframes=${ue.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${A} paypalNetRequests=${at.value}`),ue.forEach((le,st)=>{let Lt=(le.getAttribute("title")??"").slice(0,40);W(` iframe[${st}] ${on(le)}${Lt?` title="${Lt}"`:""} ${er(le)}`);let ge=Ar(le);ge&&W(` ${ge}`)}),Fn.length===0&&W(" (no PayPal/zoid window errors captured)")};De&&(qt.push(setTimeout(()=>Ge("3s"),3e3)),qt.push(setTimeout(()=>Ge("8s"),8e3)),qt.push(setTimeout(()=>Ge("15s"),15e3))),W("render:start");let Qe=L.startTiming();qt.push(setTimeout(()=>{Ze()||An||(W("watchdog:11s retryable render timeout"),Z("PayPal Buttons render did not settle within 11000ms.",!0))},Dl)),Ee.render(hn).then(()=>{if(W(`render:resolved inactive=${Ze()}`),Yt(),Ze()){xe();return}An=!0,T(!0),Fe(!1),Jt.current?.("ready"),L.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"checkout_render",durationMs:L.elapsed(Qe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(se=>{let ue=se instanceof Error?se.message:"PayPal failed to render.";W(`render:rejected msg=${ue.slice(0,120)}`),Yt(),Z(ue)})}).catch(p=>{let k=p instanceof Error?p.message:"PayPal SDK failed to load.";W(`loadScript:rejected msg=${k.slice(0,120)}`),Z(k)})},0);return()=>{qe=!0,clearTimeout(vt),Cn&&clearTimeout(Cn),Yt(),xe()}},[fe,rt,c,S,s,je,y,e,Ce,ie,L,ct]);let $n=De?Ma("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Y?"#fef2f2":"#f3f4f6",border:`1px solid ${Y?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${te} failed=${Y})`,Mt.length===0?`
|
|
1
|
+
import{a as tt,b as Yn,c as wa,d as po,e as Oi,f as zi,g as sl,h as ll}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as ap}from"@flopay/shared";import{PaymentAPI as si}from"@flopay/js";import{FloPayError as Zr,resolveBillingApiUrl as Gc,resolveButtonsLayoutTheme as Wc,resolveTheme as Jc}from"@flopay/shared";import{useCallback as hr,useEffect as Wr,useMemo as Eo,useRef as Jr,useState as Ro}from"react";import{Fragment as Or,jsx as wn,jsxs as Ui}from"react/jsx-runtime";function cl(){return Ui(Or,{children:[Ui("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[wn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),wn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",wn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:wn("path",{d:"M9 18l6-6-6-6"})})]})}function dl(){return wn(Or,{children:"Go back"})}function ul(){return wn(Or,{children:"Secure card checkout"})}function Nr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Dr({content:e}){return wn(Or,{children:e===void 0?wn(cl,{}):e})}function Lr({content:e}){return wn(Or,{children:e===void 0?wn(dl,{}):e})}function mo({content:e}){return wn(Or,{children:e===void 0?wn(ul,{}):e})}import{FloPayError as qi,isMoneySettledOutcome as pl,isSetupIntentClientSecret as ld}from"@flopay/shared";function $i(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function ka(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ji(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,c)=>a+(c.overrideAmount??c.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,c)=>({uuid:`synthetic-${a.type??"item"}-${c}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function kn(e){let t=e?.trim().split(/\s+/).filter(Boolean)??[];return t.length===0?{}:{firstName:t[0],lastName:t.length>1?t.slice(1).join(" "):void 0}}function Ia(e,t){return t?{...e,...t}:e}function jt(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var ml=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function cr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of ml)if(n.test(t))return r;return e}function kr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function zr(e){return e?.status==="authorized"||e?.status==="complete"}function Ki(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function qo(e){let t=Ki(e);return new qi(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $o(e){let t=Ki(e);return new qi(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function jo(e,t){return e==="processing"||pl(e,t)}function Vi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Hi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function yo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as ia,SESSION_CREATE_TELEMETRY as Ac}from"@flopay/js";import{buildCheckoutDisplayData as Bc,classifyTelemetryFailure as Bs,FloPayError as Vt,foldIntoProducts as Mc,isDetachedSessionEligible as Fc,resolveBillingApiUrl as Nc,resolveButtonsLayoutTheme as Dc,resolveIdempotencyKey as Ms,resolveSessionCurrency as Lc,resolveTheme as Ls,SDK_VERSION as Os,telemetryStatusClass as Oc}from"@flopay/shared";import Ga,{useCallback as Wn,useEffect as Jn,useMemo as En,useRef as At,useState as Et}from"react";import{createContext as Yi}from"react";var In=Yi({flopay:null,paypalFlopay:null,billingApiUrl:""}),Ln=Yi({session:null,loading:!1,error:null});import{PaymentAPI as Ta}from"@flopay/js";import{classifyTelemetryFailure as Tl,FloPayError as Xi,generateIdempotencyKey as Al,isValidEmail as Go,normalizeGatewayEnvironment as Bl,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Aa,SDK_VERSION as Ml}from"@flopay/shared";import{loadScript as Fl}from"@paypal/paypal-js";import{useCallback as ho,useEffect as ft,useMemo as bo,useRef as Ve,useState as nr}from"react";import{isValidEmail as yl}from"@flopay/shared";import{useCallback as Gi,useEffect as fl,useRef as Wi,useState as Ra}from"react";import{jsx as Ea,jsxs as Ur}from"react/jsx-runtime";function fo(e){return!!(e.firstName?.trim()||e.lastName?.trim())}function qr(){let[e,t]=Ra(null),n=Wi(null),r=Wi(0),o=Gi((c,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:c,identity:s}),new Promise(S=>{n.current=S})),[]),a=Gi(c=>{let s=n.current;n.current=null,t(null),s?.(c)},[]);return fl(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Ir({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[c,s]=Ra(e.email?.trim()??""),[S,b]=Ra([e.firstName,e.lastName].filter(Boolean).join(" ")),g=yl(c.trim())&&!!S.trim();return Ur("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[Ur("div",{style:{fontWeight:700},children:["Continue with ",t]}),Ur("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Ea("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:c,onChange:m=>s(m.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ur("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",Ea("input",{type:"text",autoComplete:"name","data-testid":"flopay-name",required:!0,value:S,onChange:m=>b(m.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ur("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Ea("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Ur("button",{type:"button",disabled:!g||o,onClick:()=>{let m=kn(S);n({email:c.trim(),firstName:m.firstName,lastName:m.lastName})},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function gl(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Er(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function tr(e){if(typeof e!="object"||e===null)return;let t=e;return Er(t.code)??Er(t.type)??Er(t.name)}function $r(e){if(!(typeof e!="object"||e===null))return Er(e.decline_code)}function go(e){return typeof e!="object"||e===null?!1:Er(e.type)?.toLowerCase()==="card_error"||$r(e)!==void 0}function dr(e){let t=gl(e)?.toLowerCase()??"",r=`${tr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as hl}from"@flopay/shared";import{useContext as Ko}from"react";function ur(){return Ko(In).flopay}function _a(){return Ko(In).paypalFlopay??null}function bl(){return Ko(Ln)}function Ji(){return Ko(In).billingApiUrl||hl()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Cl}from"@flopay/shared";import{useCallback as Sl,useRef as Ho}from"react";import{useEffect as vl,useLayoutEffect as Pl}from"react";var Vo=typeof window>"u"?vl:Pl;var wl={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function kl(e){return e==="stripe"||e==="paypal"?e:void 0}function Il(e){let t=kl(e.provider),n={schemaVersion:Cl,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=wl[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var xa=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function jr(e,t){let n=Ho(e);n.current=e;let r=Ho(new Set),o=Ho(t),a=Ho(t);return Vo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Sl(c=>{if(a.current!==t)return;let s=Il(c);if(s){if(xa.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}tt(()=>n.current?.(s))}},[t])}var El=Symbol.for("@flopay/js.telemetry.bridge.v1"),Rl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function _l(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function xl(e){let t=_l(),n=(o,a)=>o?o.bind(e):a,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Yo(e){let t=globalThis[Rl];return xl(t?.(e)??{})}function Kt(e){if(e)return e[El]}import{jsx as pr,jsxs as Ba}from"react/jsx-runtime";var Wo=45,Nl=1e3,Dl=11e3,Ll=["https://www.paypal.com","https://www.sandbox.paypal.com"],Zi="We couldn't open PayPal. Try again or choose another payment method.",Ol={width:"100%",minHeight:Wo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Qi(e){return e.includes("No ack for postMessage init()")&&Ll.some(t=>e.includes(t))&&e.includes("10000ms")}function zl(e){return e?`${Zi} Allow pop-ups for this site, then try again.`:Zi}function Ul(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function es({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:c,environment:s,currency:S,isSubscription:b,providerObjectType:g,onTokenizedBody:m,onComplete:B,onErrorChange:D,onDecline:u,onTechnicalFailure:w,isProcessing:ve=!1,onLoadStateChange:H,onInitializationStateChange:C,allowAutomaticRetry:fe=!0,onButtonClick:Q,runBeforeButtonClick:ce,session:oe,existingOrderId:Ce,telemetry:He,telemetryContext:be,onInstrument:Rt,debug:De=!1}){let Te=ur(),Ae=jr(Rt,e),ee=bo(()=>{if(Te)return null;let v=Yo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ml,enabled:He!==!1});return v.setCheckoutContext(be??{}),v.beginCheckout(be??{}),v},[n,Te,He,be?.checkoutMode,be?.layout]),J=bo(()=>Kt(Te),[Te]);ft(()=>()=>{ee&&ee.flush().catch(()=>{}).finally(()=>ee.destroy())},[ee]);let L=bo(()=>({error:v=>{J?J.error(v):ee?.error(v),Ae({class:"technical_error",errorCode:v.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":v.errorCode,requestCategory:v.requestCategory,provider:v.provider})},log:v=>{J?J.log(v):ee?.log(v),Ae({class:"lifecycle",name:v.name,provider:v.provider})},performance:v=>{J?J.performance(v):ee?.performance(v)},terminal:v=>{J?J.terminal(v):ee?.terminal(v)},startTiming:()=>J?.now()??ee?.now()??0,elapsed:v=>J?.elapsed(v)??Math.max(0,(ee?.now()??v)-v)}),[Ae,J,ee]),de=Ve(null),et=Ve(0),Ue=Ve(null),Ye=Ve(!1),[te,T]=nr(!1),[ae,Fe]=nr(!1),[ie,j]=nr(0),_e=Ve(0),[Je,We]=nr(!1),Se=Ve(!1),G=Ve(!1),[Y,$]=nr(!1),[we,Be]=nr(!1),[x,K]=nr(!1),[I,P]=nr(!1),nt=kn(o??[oe?.customer?.firstName,oe?.customer?.lastName].filter(Boolean).join(" ")),St=!x&&a&&!Go(r?.trim()||oe?.customer?.email?.trim())?{email:r?.trim()||oe?.customer?.email?.trim(),firstName:nt.firstName,lastName:nt.lastName}:null,{request:ue,collect:ct,finish:it}=qr(),rt=bo(()=>n.replace(/\/+$/,""),[n]),je=g??(b?"subscription":"order"),y=g==="order"||g==="setup_token",U=bo(()=>JSON.stringify([rt,c,S,s??"",je,y,e,Ce??""]),[rt,c,S,s,Ce,je,y,e]),Xe=Ve(U),dt=Xe.current!==U,[Bt,Mt]=nr([]),W=v=>{De&&Mt(ut=>[...ut,`${new Date().toISOString().slice(11,23)} ${v}`])},Le=Ve(m),Jt=Ve(B),wt=Ve(D),zt=Ve(u),Rn=Ve(w),_n=Ve(Q),Zn=Ve(H),Xt=Ve(C),cn=Ve(a),dn=Ve(ce),Ft=Ve(oe),vn=Ve(r),bt=Ve(o),ir=Ve(null),Yt=Ve(e),sr=Ve(t),Nt=Ve(null),zn=Ve(0),ot=Ve(null),_t=Ve(null),xt=Ve(new Map),tn=Ve(new Map),un=Ve(!1);ft(()=>(un.current=!0,()=>{un.current=!1}),[]),ft(()=>{Le.current=m},[m]),ft(()=>{cn.current=a},[a]),ft(()=>{Jt.current=B},[B]),ft(()=>{wt.current=D},[D]),ft(()=>{zt.current=u},[u]),ft(()=>{Rn.current=w},[w]),ft(()=>{_n.current=Q},[Q]),ft(()=>{Zn.current=H},[H]),ft(()=>{Xt.current=C},[C]),ft(()=>{dn.current=ce},[ce]),ft(()=>{Ft.current=oe},[oe]),ft(()=>{vn.current=r},[r]),ft(()=>{bt.current=o},[o]),ft(()=>{sr.current=t},[t]),ft(()=>{Yt.current!==e&&(Yt.current=e,ir.current=null,K(!1),P(!1))},[e]),ft(()=>{_e.current=ie},[ie]),ft(()=>{Je&&Ue.current?.focus()},[Je,ie]);let pn=ho(()=>{window.setTimeout(()=>{Ue.current?.focus()},0)},[]),Un=ho(async v=>{P(!0);try{await cn.current?.(v),ir.current=v,vn.current=v.email,bt.current=[v.firstName,v.lastName].filter(Boolean).join(" "),K(!0),tt(()=>wt.current?.(null))}catch(ut){let qe=ut instanceof Error?ut.message:"Buyer details could not be attached to checkout.";tt(()=>wt.current?.(qe))}finally{P(!1)}},[]),qn=ho(()=>{T(!1),j(v=>v+1)},[]),Ut=ho(()=>{We(!1),(de.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??de.current)?.focus?.()},[]);ft(()=>{!te||!Ye.current||(Ye.current=!1,Ut())},[Ut,te,ie]);let X=ho((v,ut)=>{let qe=Rn.current;if(qe){qe("paypal",v,ut);return}wt.current?.(zl(ut?.popupBlocked??dr(v)))},[]),Pn=()=>{ot.current?.timer&&(clearTimeout(ot.current.timer),ot.current.timer=null)},xn=()=>{Pn();let v=zn.current+1;return zn.current=v,_t.current=null,ot.current={generation:v,timer:null,yieldedControl:!1},We(!1),v},Qn=v=>v!==void 0&&ot.current?.generation!==v?!1:(Pn(),ot.current=null,_t.current=null,!0),br=v=>{let ut=v?.generation??ot.current?.generation??zn.current;(!v?.generation||ot.current?.generation===ut)&&(Pn(),ot.current=null),_t.current=ut,v?.showRetry&&We(!0),v?.remount&&qn(),v?.focus!==!1&&pn()},Tr=v=>ot.current?.generation===v&&_t.current!==v,Tn=v=>{typeof document<"u"&&document.visibilityState!=="visible"||(Pn(),v.timer=setTimeout(()=>{ot.current?.generation===v.generation&&(ot.current=null,_t.current=v.generation,X(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),We(!0),qn(),pn())},600))},mn=()=>{let v=ot.current;v?.yieldedControl&&Tn(v)},Me=()=>{let v=ot.current;v&&(v.yieldedControl=!0,Pn())},Zt=v=>{let ut=Nt.current;return ut&&tn.current.set(v,ut),v};ft(()=>{let v=()=>{document.visibilityState==="visible"?mn():Me()};return document.addEventListener("visibilitychange",v),window.addEventListener("focus",mn),window.addEventListener("blur",Me),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("focus",mn),window.removeEventListener("blur",Me),Pn()}},[]),ft(()=>{Xe.current!==U&&(Xe.current=U,Se.current=!1,G.current=!1,T(!1),Fe(!1),$(!1),Xt.current?.("loading"))},[U]),ft(()=>{tt(()=>Zn.current?.(te&&!Y))},[te,Y]);let Dt=Bl(s);ft(()=>{let v=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",ut=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(W(`mount clientId=${v} env=${s??"(unset)"}\u2192${Dt??"live"} ccy=${S} sub=${b}`),W(`ua=${ut.slice(0,80)}${ut.length>80?"\u2026":""}`),!c){W("FAIL: clientId empty \u2014 gateway misconfigured"),$(!0),L.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!de.current){W("FAIL: containerRef not attached");return}et.current=L.startTiming(),L.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let qe=!1,yn=!1,Ze=()=>qe||yn,qt,lr=!1,jn=()=>{qt=Al(),qt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),lr=!0},Cn=null,Lt=!1,fn=null,gn=!1,xe=()=>{!fn||gn||(gn=!0,fn.close().catch(()=>{}))},kt=null,Tt=()=>{kt!==null&&(L.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"overlay_return",durationMs:L.elapsed(kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),kt=null)},An=!1,hn=de.current,Bn=null,Mn=null,$t=[],nn=d=>{if(!d||typeof d.getBoundingClientRect!="function")return"(no rect)";let p=d.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},an=d=>{if(!d)return"(empty)";try{let p=new URL(d,typeof window<"u"?window.location.href:"https://localhost"),k=p.pathname.toLowerCase();return k.includes("checkcaptcha")||k.includes("captcha")?`CAPTCHA(${p.host}${k})`:k.includes("risk")||k.includes("challenge")?`RISK(${p.host}${k})`:k.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${k}`.slice(0,100)}catch{return d.slice(0,80)}},er=d=>{let p=d.getAttribute("src"),k=d.getAttribute("srcdoc"),ke=d.getAttribute("name"),q=d.getAttribute("sandbox"),F=[];return p&&F.push(`src=${an(p)}`),k&&F.push(`srcdoc[${k.length}ch]`),!p&&!k&&F.push("src=(empty) srcdoc=(empty)"),ke&&F.push(`name=${ke.slice(0,40)}`),q!==null&&F.push(`sandbox="${q.slice(0,40)}"`),F.join(" ")},Ar=d=>{if(!(d instanceof HTMLIFrameElement))return"";try{let p=d.contentDocument;if(!p)return"cd=null";let k=p.body?.children.length??0,ke=p.body?.innerHTML.length??0,q=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${k}children,${ke}ch] head[${q}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},Fn=[],Kn=d=>{if(Ze())return;let p=d.message??String(d.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(W(`window:error ${p.slice(0,140)}`),Fn.push(p))},Qt=d=>{if(Ze())return;let p=d.reason instanceof Error?d.reason.message:String(d.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(W(`window:rejection ${p.slice(0,140)}`),Fn.push(p))};De&&typeof window<"u"&&(window.addEventListener("error",Kn),window.addEventListener("unhandledrejection",Qt));let at={value:0};if(De&&typeof PerformanceObserver<"u")try{Mn=new PerformanceObserver(d=>{if(!Ze())for(let p of d.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;at.value+=1;let k=Math.round(p.duration);W(`net ${k}ms ${p.name.slice(0,90)}`)}}),Mn.observe({type:"resource",buffered:!0})}catch{}let Gt=()=>{for(Bn?.disconnect(),Bn=null,Mn?.disconnect(),Mn=null;$t.length;)clearTimeout($t.pop());De&&typeof window<"u"&&(window.removeEventListener("error",Kn),window.removeEventListener("unhandledrejection",Qt))},_=d=>{if(!d)return!1;let p=d.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},E=d=>{if(Ze()||_(d))return;let p=cr(d)??d;tt(()=>wt.current?.(p))},V=d=>{qe||($(!0),d.includes("paypal_ineligible")||L.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",d))},Z=(d,p=!1)=>{if(qe)return;let k=Se.current||!fe;if(Lt)return;Lt=!0,yn=!0,Gt(),xe();let ke=p||Qi(d);if(ke&&fe&&!Se.current){Se.current=!0,T(!1),Be(!1),Fe(!0),Xt.current?.("retrying"),Cn=setTimeout(()=>{qe||j(q=>q+1)},Nl);return}if(ke||k){if(T(!1),Be(!1),Fe(!1),$(!0),Xt.current?.("exhausted"),!G.current){G.current=!0;let q=Qi(d)?"paypal_init_timeout":p?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",q)}return}V(d)};$(!1);let $e=async(d,p=Nt.current)=>{if(Ze())return;let k=p?.sessionId??e;if(Le.current){await Le.current(d,{sessionId:k,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let ke=L.startTiming();L.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let q=()=>{L.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"processing",durationMs:L.elapsed(ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let F=Ft.current,Ge=p?.accountPatch?.email??vn.current,Qe=p?.accountPatch?.userId??F?.customer?.id??F?.accountData?.userId??"",pe=await new Ta(rt,{telemetry:!1}).processPayment(Qe,{sessionId:k,nonce:p?.nonce??sr.current,tokenizedData:d,accountData:{userId:Qe,email:Ge??F?.customer?.email??"",firstName:p?.accountPatch?.firstName??F?.customer?.firstName??F?.accountData?.firstName??"",lastName:p?.accountPatch?.lastName??F?.customer?.lastName??F?.accountData?.lastName??"",country:p?.accountPatch?.country??F?.customer?.country??F?.accountData?.country??void 0,zip:p?.accountPatch?.zip??F?.customer?.zip??F?.accountData?.zip??void 0}});if(pe.ok){if(yn||qe&&un.current)return;q(),L.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),tt(()=>Jt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ze())return;let A=await pe.json().catch(()=>null),le=A?.message??"PayPal payment failed.",st=cr(le)??le;q(),pe.status===400&&(typeof A?.declineCode=="string"||!Array.isArray(A?.fields))?L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):pe.status===400||pe.status===422?L.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):L.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:pe.status>=500?"5xx":pe.status>=400?"4xx":pe.status>=300?"3xx":"unknown",failureCategory:pe.status>=500?"server_error":void 0}),E(st),tt(()=>zt.current?.(jt("paypal",st,{code:A?.code,declineCode:A?.declineCode})));return}catch(F){if(Ze())return;q(),L.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ge=F instanceof Error?F.message:"PayPal payment failed.",Qe=cr(Ge)??Ge;E(Qe),tt(()=>zt.current?.(jt("paypal",Qe)));return}},ne=()=>new Xi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),M=d=>Ze()?Promise.reject(ne()):Promise.resolve(d),h=async d=>{if(Ze())throw ne();lr||jn();let p=Nt.current,k=p?.sessionId??e,ke=p?.nonce??sr.current;L.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let q;try{q=await new Ta(rt,{telemetry:!1}).createSessionIntent(k,ke??"",y?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Aa,paymentMethodId:null,intentKind:je==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:qt})}catch(F){throw L.error({...Tl(F,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),F}if(Ze())throw ne();if(q.provider!=="paypal"||q.providerObjectType!==je)throw new Error(d);return L.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),q.providerObjectId},f=(d,p)=>{let k=p?.nonce??sr.current;if(!k)return;let ke=p?.sessionId??e,q=$r(d)??tr(d)??"provider_declined";new Ta(rt,{telemetry:!1}).reportSessionIntentDecline(ke,k,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:q}).catch(()=>{})},O=ie;W("loadScript:scheduled (deferred 1 tick)");let pt=null,vt=setTimeout(()=>{if(qe){W("loadScript:skipped (cancelled before defer ran)");return}W("loadScript:start");let d=Dt==="live"?"production":Dt;pt=Fl({clientId:c,currency:S,...je==="subscription"?{intent:"subscription",vault:!0}:je==="order"?{intent:"capture"}:{},...d?{environment:d}:{},...d==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),pt.then(p=>{if(W(`loadScript:resolved inactive=${Ze()} ns=${!!p} buttons=${!!p?.Buttons}`),Ze())return;if(!p?.Buttons){W("FAIL: namespace missing Buttons factory"),Z("PayPal SDK did not expose the Buttons factory.");return}L.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"provider_ready",durationMs:L.elapsed(et.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let k=async(se,pe)=>{if(Ze()||_e.current!==O)return;let A=se.vaultSetupToken??se.subscriptionID??se.orderID??"",le=A?tn.current.get(A):xt.current.get(O);if(!(!le||!Tr(le.generation))&&Qn(le.generation)){tn.current.delete(A),xt.current.delete(le.surfaceKey),Tt();try{if(Be(!0),tt(()=>wt.current?.(null)),!A)throw new Xi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let st=Ft.current,Ot=kn(bt.current??[st?.customer?.firstName,st?.customer?.lastName].filter(Boolean).join(" ")),ge={email:le.accountPatch?.email?.trim()||vn.current?.trim()||st?.customer?.email?.trim(),firstName:le.accountPatch?.firstName?.trim()||Ot.firstName,lastName:le.accountPatch?.lastName?.trim()||Ot.lastName};if(!Go(ge.email)||!(ge.firstName||ge.lastName))try{let bn=Ul(await pe?.order?.get?.());ge={email:bn.email||ge.email,firstName:bn.firstName||ge.firstName,lastName:bn.lastName||ge.lastName}}catch{}if(cn.current&&(!Go(ge.email)||!(ge.firstName||ge.lastName))){let bn=await ct("PayPal",ge);if(!bn)return;ge=bn}Go(ge.email)&&(ge.firstName||ge.lastName)&&(le.accountPatch={...le.accountPatch,...ge},await cn.current?.(ge)),await $e(je==="setup_token"?{id:A,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Aa}:y?{id:A,isPaypal:!0,gateway:"paypal",paymentMethodType:Aa}:{id:A,isPaypal:!0},le)}catch(st){E(st instanceof Error?st.message:"PayPal capture failed.")}finally{Ze()||Be(!1)}}},ke=p.Buttons({style:{layout:"horizontal",height:Wo,tagline:!1},onClick:async(se,pe)=>{if(Ze()){await pe.reject();return}jn();let A=dn.current,le={accountPatch:ir.current??void 0};if(A)try{let ge=await A("paypal");if(Ze()){await pe.reject();return}if(!ge.proceed){Nt.current=null,xt.current.delete(O),await pe.reject();return}le={sessionId:ge.sessionId,accountPatch:{...ir.current,...ge.accountPatch},nonce:ge.nonce}}catch(ge){W(`onClick:runBeforeButtonClick rejected msg=${(ge instanceof Error?ge.message:String(ge)).slice(0,120)}`),Nt.current=null,xt.current.delete(O),await pe.reject();return}tt(()=>_n.current?.("paypal"));let Ot={generation:xn(),surfaceKey:O,...le};Nt.current=Ot,xt.current.set(O,Ot),await pe.resolve(),L.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),kt=L.startTiming()},createOrder:je==="order"?Ce?()=>M(Ce).then(Zt):()=>h("Failed to create PayPal order.").then(Zt):void 0,createSubscription:je==="subscription"?Ce?()=>M(Ce).then(Zt):()=>h("Failed to create PayPal subscription.").then(Zt):void 0,createVaultSetupToken:je==="setup_token"?()=>h("Failed to create PayPal setup token.").then(Zt):void 0,onApprove:k,onCancel:()=>{if(Ze())return;let se=xt.current.get(O)??Nt.current;se&&xt.current.delete(se.surfaceKey),Nt.current=null,Tt(),L.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ye.current=!0,br({generation:se?.generation,remount:!0,focus:!1})},onError:se=>{if(Ze()||_e.current!==O)return;let pe=se instanceof Error?se.message:"PayPal failed to render.";if(W(`onError rendered=${An} msg=${pe.slice(0,120)}`),An){let A=xt.current.get(O)??Nt.current;if(A&&!Tr(A.generation)||!A&&_t.current===zn.current)return;if(_(pe)){Qn(A?.generation);return}if(Tt(),go(se)){L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),f(se,A),tt(()=>zt.current?.(jt("paypal",pe))),A&&xt.current.delete(A.surfaceKey),Nt.current=null,Qn(A?.generation);return}let le=pe.toLowerCase();L.error({errorCode:le.includes("popup")&&le.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),A&&xt.current.delete(A.surfaceKey),Nt.current=null,br({generation:A?.generation,remount:!0,showRetry:!0,focus:!0}),X(se,{code:"paypal_runtime_failed"});return}Z(pe)}}),q=ke.isEligible();if(W(`isEligible=${q}`),L.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!q){T(!1),Z("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}fn=ke,De&&W(`container:dims ${nn(hn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),De&&typeof MutationObserver<"u"&&(Bn=new MutationObserver(se=>{if(!Ze()){for(let pe of se)if(pe.type==="childList")pe.addedNodes.forEach(A=>{if(!(A instanceof Element))return;let le=A.tagName.toLowerCase(),st=(A.getAttribute("title")??"").slice(0,40),Ot=le==="iframe"?` ${er(A)}`:"";W(`child+ ${le}${st?` title="${st}"`:""}${Ot} dims=${nn(A)}`)});else if(pe.type==="attributes"&&pe.target instanceof Element){let A=pe.target;if(A.tagName.toLowerCase()!=="iframe")continue;let le=pe.attributeName;(le==="src"||le==="srcdoc")&&W(`attr~ iframe ${le}=${le==="srcdoc"?`[${(A.getAttribute("srcdoc")??"").length}ch]`:an(A.getAttribute("src"))} dims=${nn(A)}`)}}}),Bn.observe(hn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ge=se=>{if(Ze()||An)return;let pe=hn.querySelectorAll("iframe"),A=typeof document<"u"&&"hasStorageAccess"in document;W(`watchdog:${se} container=${nn(hn)} children=${hn.childElementCount} iframes=${pe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${A} paypalNetRequests=${at.value}`),pe.forEach((le,st)=>{let Ot=(le.getAttribute("title")??"").slice(0,40);W(` iframe[${st}] ${nn(le)}${Ot?` title="${Ot}"`:""} ${er(le)}`);let ge=Ar(le);ge&&W(` ${ge}`)}),Fn.length===0&&W(" (no PayPal/zoid window errors captured)")};De&&($t.push(setTimeout(()=>Ge("3s"),3e3)),$t.push(setTimeout(()=>Ge("8s"),8e3)),$t.push(setTimeout(()=>Ge("15s"),15e3))),W("render:start");let Qe=L.startTiming();$t.push(setTimeout(()=>{Ze()||An||(W("watchdog:11s retryable render timeout"),Z("PayPal Buttons render did not settle within 11000ms.",!0))},Dl)),ke.render(hn).then(()=>{if(W(`render:resolved inactive=${Ze()}`),Gt(),Ze()){xe();return}An=!0,T(!0),Fe(!1),Xt.current?.("ready"),L.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"checkout_render",durationMs:L.elapsed(Qe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(se=>{let pe=se instanceof Error?se.message:"PayPal failed to render.";W(`render:rejected msg=${pe.slice(0,120)}`),Gt(),Z(pe)})}).catch(p=>{let k=p instanceof Error?p.message:"PayPal SDK failed to load.";W(`loadScript:rejected msg=${k.slice(0,120)}`),Z(k)})},0);return()=>{qe=!0,clearTimeout(vt),Cn&&clearTimeout(Cn),Gt(),xe()}},[fe,rt,c,S,s,je,y,e,Ce,ie,L,ct]);let $n=De?Ba("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Y?"#fef2f2":"#f3f4f6",border:`1px solid ${Y?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${te} failed=${Y})`,Bt.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return Y&&!dt?De?pr("div",{children:$n}):null:Ma("div",{children:[$n,St&&pr(Ir,{identity:St,methodLabel:"PayPal",testId:"flopay-direct-paypal-identity-pane",onComplete:v=>{Un(v)},submitting:I}),de&&pr(Ir,{identity:de.identity,methodLabel:de.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:it,onCancel:()=>it(null)}),Ma("div",{"aria-hidden":ae||St||de?!0:void 0,style:ae||St||de?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Wo},children:[!te&&!ae&&pr("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),pr("div",{ref:me,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Wo,display:"flex",opacity:te?1:0},"aria-busy":we||ve},ie)]},ie),Je&&pr("button",{ref:Ue,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:zt,style:Ol,children:"Try PayPal again"})]})}function Jo(e){return pr(es,{...e})}function ts(e){return pr(es,{...e})}import{jsx as ns,jsxs as ql}from"react/jsx-runtime";function Kr({children:e,margin:t,icon:n=!0,styleOverride:r}){return ql("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&ns("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ns("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{resolveBillingApiUrl as $l}from"@flopay/shared";import{useEffect as mr,useMemo as jl,useRef as rs,useState as os}from"react";import{jsx as Kl}from"react/jsx-runtime";function Xo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,c]=os(e instanceof Promise?null:e),[s,S]=os(t instanceof Promise||!t?null:t),b=rs(null),g=rs(null),m=jr(r);mr(()=>{m({class:"lifecycle",name:"checkout.mount"})},[m]),mr(()=>{a&&m({class:"lifecycle",name:"sdk.initialize.ready"})},[m,a]),mr(()=>{if(a)return jt(a)?.subscribe?.(m)},[m,a]),mr(()=>{if(!(!s||s===a))return jt(s)?.subscribe?.(m)},[m,a,s]),mr(()=>{if(!a)return;let u=jt(a);return b.current=u?.beginCheckout()??u?.now()??0,u?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{u?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),mr(()=>{let u=!1;return e instanceof Promise?e.then(w=>{u||c(w)},()=>{u||m({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{u=!0}},[m,e]),mr(()=>{let u=!1;if(!t){S(null);return}return t instanceof Promise?t.then(w=>{u||S(w)},()=>{u||m({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):S(t),()=>{u=!0}},[m,t]),mr(()=>{if(!a||g.current===a)return;g.current=a;let u=jt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),m({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(b.current??0),durationMode:"machine"})},[m,a]);let M=$l(n?.billingApiUrl),D=jl(()=>({flopay:a,paypalFlopay:s,billingApiUrl:M,emitInstrument:m}),[a,s,M,m]);return Kl(In.Provider,{value:D,children:o})}var Zo="flopay_recent_completion_";function Vr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Zo+e,JSON.stringify(t))}catch{}}function Fa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Zo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Zo+e),!1):!0}catch{return!1}}import{loadFloPay as as,PaymentAPI as ss}from"@flopay/js";import{classifyPaymentRejection as Vl,FloPayError as lt,isAuthorizationOnlySession as Hl,isSetupIntentClientSecret as Yl,normalizeCheckoutFailureOutcome as is}from"@flopay/shared";var Po="card";async function Gl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function Wl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Da(e,t){return Object.assign(e,{checkoutMethod:t})}function rr(e,t){let n=e instanceof lt?e:new lt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function vo(e,t){try{return await e()}catch(n){throw rr(n,t)}}function ls(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Jl(e){return e.status==="succeeded"||e.status==="declined"}async function cs(e){if(typeof document>"u"||typeof window>"u")throw new lt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new lt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let g=new AbortController,m=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",m);let M=window.setTimeout(()=>g.abort(),r);try{let D=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!D.ok)return{status:"unknown"};let u=await D.json().catch(()=>null);return Xl(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(M),e.signal?.removeEventListener("abort",m)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let S=document.createElement("iframe");S.setAttribute("title","Card authentication"),S.setAttribute("allow","payment"),S.tabIndex=0,S.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),S.src=e.nextActionRedirectUrl,s.appendChild(S),document.body.appendChild(s),S.focus();let b=null;try{b=new URL(e.billingApiUrl,window.location.href).origin}catch{b=null}try{let g=await new Promise((m,M)=>{let D=!1,u=0,w=0,ve=0,H=!1,P=()=>{window.clearTimeout(u),window.clearInterval(w),window.clearTimeout(ve),window.removeEventListener("message",oe),S.removeEventListener("load",Q),e.signal?.removeEventListener("abort",ce)},fe=async()=>{if(!(D||H)){H=!0;try{let Ce=await a();if(D||!Jl(Ce))return;D=!0,P(),m(Ce)}finally{H=!1}}},Q=()=>{window.clearTimeout(ve),ve=window.setTimeout(()=>{fe()},250)},ce=()=>{D||(D=!0,P(),M(new lt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},oe=Ce=>{if(Ce.source!==S.contentWindow||b&&Ce.origin!==b)return;let He=Ce.data;!He||typeof He!="object"||He.source!=="flopay-vault-3ds-return"||D||(D=!0,P(),m(null))};u=window.setTimeout(()=>{D||(D=!0,P(),M(new lt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),w=window.setInterval(()=>{fe()},n),S.addEventListener("load",Q),window.addEventListener("message",oe),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return g||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function Xl(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function yr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=cr(o)??o;return Da(new lt(a,"api_error",{code:is(e?.outcome)??is(e?.type)??e?.gatewayErrorCode}),r)}function Na(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Qo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Zl(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function ds(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let s of a)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(s)))return s;let c=o.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let S=s,b=[S.stripeClientSecret,S.clientSecret];for(let g of b)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(g)))return g}}}}async function Ql({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ds(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let s=(await new ss(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Qo(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function Hr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),S=t??n.id,b=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",m=n.customer?.email??n.accountData?.email??"",M=n.customer?.firstName??n.accountData?.firstName??"",D=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,w=n.customer?.zip??n.accountData?.zip??void 0,ve=new ss(s,c===!1?{telemetry:!1}:void 0),H=await Zl(()=>ve.processPayment(g,{sessionId:S,nonce:b,tokenizedData:o,accountData:{userId:g,email:m,firstName:M,lastName:D,country:u,zip:w},returnUrl:a??Na(n)}));if(H.ok){let Q=typeof H.json=="function"?await H.json().catch(()=>null):null;return Hl(n)||Q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Q?.paymentId=="string"?Q.paymentId:n.paymentId,sessionId:typeof Q?.sessionId=="string"?Q.sessionId:S,authorizationExpiresAt:typeof Q?.authorizationExpiresAt=="string"?Q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let P;try{P=await H.json()}catch{throw new lt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status})}if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let Q=ds(P);if(!Q)throw new lt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status});return{type:P.type,threeDSecureToken:Q,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let Q=await Ql({billingApiUrl:s,sessionId:S,nonce:b,responseJson:P});if(Q)return Q;throw Da(new lt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let fe=new lt(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:H.status});throw Object.assign(fe,{telemetryOutcome:Vl(H.status,P)})}async function ea(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:c,returnUrl:s,telemetry:S}){let b=t?.getRawProvider();if(!b)throw rr(new lt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Da(new lt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Yl(e.threeDSecureToken),m=null,M=e.paymentMethodId,D=await vo(()=>Gl(b,e.threeDSecureToken,g),"card");if(D){if(D.error)throw rr(new lt(D.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:D.error.code}),"card");let w=D.intent;!M&&w?.payment_method&&(typeof w.payment_method=="string"?M=w.payment_method:"id"in w.payment_method&&(M=w.payment_method.id??void 0))}let u=M?await vo(()=>Wl(b,e.threeDSecureToken,{payment_method:M,return_url:s??Na(c)??window.location.href},g),"card"):null;if(u){if(u.error)throw rr(new lt(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");m=u.intent}else{let w=await vo(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(w.error)throw rr(new lt(w.error.message??"3DS authentication failed.","api_error",{code:w.error.code}),"card");m=(g?w.setupIntent:w.paymentIntent)??null}if(m&&(m.status==="requires_capture"||m.status==="succeeded"||m.status==="processing")){let w=await Hr({billingApiUrl:o,sessionId:a,session:c,telemetry:S,tokenizedData:{id:m.id,type:"card",threeDSecureActionResultTokenId:m.id},returnUrl:s});return w.type==="success"?{...w.result,paymentIntentId:w.result.paymentIntentId??m.id,paymentMethodId:w.result.paymentMethodId??M}:ea(w,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:c,returnUrl:s,telemetry:S})}throw rr(new lt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw rr(new lt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:M}=await vo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(M)throw rr(new lt(M.message??"PayPal authorization failed.","api_error",{code:M.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:m}=await vo(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Na(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(m)throw rr(new lt(m.message??"PayPal authorization failed.","api_error",{code:m.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new lt("Unsupported payment redirect state.","api_error")}function Rr(e){if(e instanceof lt){let r=cr(e.message);return r&&r!==e.message?Object.assign(new lt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=cr(t)??t;return new lt(n,"api_error")}function ta(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new lt("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function na({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[c,s]=await Promise.all([as(e,{billingApiUrl:n,locale:r,telemetry:o}),a?as(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{PaymentAPI as So,toStripeAppearance as ec}from"@flopay/js";import{COUNTRY_OPTIONS as tc,classifyPaymentRejection as nc,FloPayError as On,filterStripeMethodsByCountry as rc,getPostalCodeExample as oc,getPostalCodeLabel as Ua,getStateFromPostalCode as ms,getStateLabel as ys,getStateOptions as ac,getStripeMethodDisplayName as xr,hasVendoredStripeMethodLogo as ic,isAuthorizationOnlySession as La,isAVSFieldVisible as ze,isPostalCodeSupported as sc,isSetupIntentClientSecret as lc,isValidEmail as en,isValidPostalCode as cc,needsStripeMethodExplicitConfirm as fs,normalizeCheckoutFailureOutcome as dc,partitionStripeMethods as uc,resolveAVSConfig as pc,resolveButtonsLayoutTheme as mc,resolveStripeMethodBrandVariant as yc,resolveTheme as fc,stripeExpressMethodToOptionKey as gs}from"@flopay/shared";import{ExpressCheckoutElement as Is,PaymentElement as gc,Elements as _r,useElements as ja,useStripe as Ka}from"@stripe/react-stripe-js";import hc,{useCallback as Pe,useContext as Yr,useEffect as ht,useMemo as gt,useRef as Ie,useState as ye}from"react";function us(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var ps={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as fr,jsx as l,jsxs as ke}from"react/jsx-runtime";var Gn="flopay_stripe_resume",hs="flopay_wallet_resume";function Es(e){return e instanceof On&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function oa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new So(e).createSessionIntent(...n)}catch(o){throw Es(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Co="flopay_paypal_resume",bc=250,bs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Va(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function aa({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new So(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function vc(e){return e instanceof On&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Oa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Pc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=kn(r?.name),a=kn(n);return{email:r?.email?.trim()||t?.trim(),firstName:o.firstName??a.firstName,lastName:o.lastName??a.lastName}}async function Rs({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let c=Pc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return!en(c.email)||!fo(c)?a(o,c):c}var Cc=`
|
|
3
|
+
${Bt.join(`
|
|
4
|
+
`)}`]}):null;return Y&&!dt?De?pr("div",{children:$n}):null:Ba("div",{children:[$n,St&&pr(Ir,{identity:St,methodLabel:"PayPal",testId:"flopay-direct-paypal-identity-pane",onComplete:v=>{Un(v)},submitting:I}),ue&&pr(Ir,{identity:ue.identity,methodLabel:ue.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:it,onCancel:()=>it(null)}),Ba("div",{"aria-hidden":ae||St||ue?!0:void 0,style:ae||St||ue?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Wo},children:[!te&&!ae&&pr("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),pr("div",{ref:de,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Wo,display:"flex",opacity:te?1:0},"aria-busy":we||ve},ie)]},ie),Je&&pr("button",{ref:Ue,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Ut,style:Ol,children:"Try PayPal again"})]})}function Jo(e){return pr(es,{...e})}function ts(e){return pr(es,{...e})}import{jsx as ns,jsxs as ql}from"react/jsx-runtime";function Kr({children:e,margin:t,icon:n=!0,styleOverride:r}){return ql("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&ns("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ns("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{resolveBillingApiUrl as $l}from"@flopay/shared";import{useEffect as mr,useMemo as jl,useRef as rs,useState as os}from"react";import{jsx as Kl}from"react/jsx-runtime";function Xo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,c]=os(e instanceof Promise?null:e),[s,S]=os(t instanceof Promise||!t?null:t),b=rs(null),g=rs(null),m=jr(r);mr(()=>{m({class:"lifecycle",name:"checkout.mount"})},[m]),mr(()=>{a&&m({class:"lifecycle",name:"sdk.initialize.ready"})},[m,a]),mr(()=>{if(a)return Kt(a)?.subscribe?.(m)},[m,a]),mr(()=>{if(!(!s||s===a))return Kt(s)?.subscribe?.(m)},[m,a,s]),mr(()=>{if(!a)return;let u=Kt(a);return b.current=u?.beginCheckout()??u?.now()??0,u?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{u?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),mr(()=>{let u=!1;return e instanceof Promise?e.then(w=>{u||c(w)},()=>{u||m({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{u=!0}},[m,e]),mr(()=>{let u=!1;if(!t){S(null);return}return t instanceof Promise?t.then(w=>{u||S(w)},()=>{u||m({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):S(t),()=>{u=!0}},[m,t]),mr(()=>{if(!a||g.current===a)return;g.current=a;let u=Kt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),m({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(b.current??0),durationMode:"machine"})},[m,a]);let B=$l(n?.billingApiUrl),D=jl(()=>({flopay:a,paypalFlopay:s,billingApiUrl:B,emitInstrument:m}),[a,s,B,m]);return Kl(In.Provider,{value:D,children:o})}var Zo="flopay_recent_completion_";function Vr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Zo+e,JSON.stringify(t))}catch{}}function Fa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Zo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Zo+e),!1):!0}catch{return!1}}import{loadFloPay as as,PaymentAPI as ss}from"@flopay/js";import{classifyPaymentRejection as Vl,FloPayError as lt,isAuthorizationOnlySession as Hl,isSetupIntentClientSecret as Yl,normalizeCheckoutFailureOutcome as is}from"@flopay/shared";var Po="card";async function Gl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function Wl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Da(e,t){return Object.assign(e,{checkoutMethod:t})}function rr(e,t){let n=e instanceof lt?e:new lt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function vo(e,t){try{return await e()}catch(n){throw rr(n,t)}}function ls(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function Jl(e){return e.status==="succeeded"||e.status==="declined"}async function cs(e){if(typeof document>"u"||typeof window>"u")throw new lt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new lt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let g=new AbortController,m=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",m);let B=window.setTimeout(()=>g.abort(),r);try{let D=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!D.ok)return{status:"unknown"};let u=await D.json().catch(()=>null);return Xl(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(B),e.signal?.removeEventListener("abort",m)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let S=document.createElement("iframe");S.setAttribute("title","Card authentication"),S.setAttribute("allow","payment"),S.tabIndex=0,S.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),S.src=e.nextActionRedirectUrl,s.appendChild(S),document.body.appendChild(s),S.focus();let b=null;try{b=new URL(e.billingApiUrl,window.location.href).origin}catch{b=null}try{let g=await new Promise((m,B)=>{let D=!1,u=0,w=0,ve=0,H=!1,C=()=>{window.clearTimeout(u),window.clearInterval(w),window.clearTimeout(ve),window.removeEventListener("message",oe),S.removeEventListener("load",Q),e.signal?.removeEventListener("abort",ce)},fe=async()=>{if(!(D||H)){H=!0;try{let Ce=await a();if(D||!Jl(Ce))return;D=!0,C(),m(Ce)}finally{H=!1}}},Q=()=>{window.clearTimeout(ve),ve=window.setTimeout(()=>{fe()},250)},ce=()=>{D||(D=!0,C(),B(new lt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},oe=Ce=>{if(Ce.source!==S.contentWindow||b&&Ce.origin!==b)return;let He=Ce.data;!He||typeof He!="object"||He.source!=="flopay-vault-3ds-return"||D||(D=!0,C(),m(null))};u=window.setTimeout(()=>{D||(D=!0,C(),B(new lt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),w=window.setInterval(()=>{fe()},n),S.addEventListener("load",Q),window.addEventListener("message",oe),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return g||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function Xl(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function yr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=cr(o)??o;return Da(new lt(a,"api_error",{code:is(e?.outcome)??is(e?.type)??e?.gatewayErrorCode}),r)}function Na(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Qo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Zl(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function ds(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let s of a)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(s)))return s;let c=o.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let S=s,b=[S.stripeClientSecret,S.clientSecret];for(let g of b)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(g)))return g}}}}async function Ql({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ds(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let s=(await new ss(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Qo(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function Hr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),S=t??n.id,b=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",m=n.customer?.email??n.accountData?.email??"",B=n.customer?.firstName??n.accountData?.firstName??"",D=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,w=n.customer?.zip??n.accountData?.zip??void 0,ve=new ss(s,c===!1?{telemetry:!1}:void 0),H=await Zl(()=>ve.processPayment(g,{sessionId:S,nonce:b,tokenizedData:o,accountData:{userId:g,email:m,firstName:B,lastName:D,country:u,zip:w},returnUrl:a??Na(n)}));if(H.ok){let Q=typeof H.json=="function"?await H.json().catch(()=>null):null;return Hl(n)||Q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Q?.paymentId=="string"?Q.paymentId:n.paymentId,sessionId:typeof Q?.sessionId=="string"?Q.sessionId:S,authorizationExpiresAt:typeof Q?.authorizationExpiresAt=="string"?Q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let C;try{C=await H.json()}catch{throw new lt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status})}if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let Q=ds(C);if(!Q)throw new lt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status});return{type:C.type,threeDSecureToken:Q,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let Q=await Ql({billingApiUrl:s,sessionId:S,nonce:b,responseJson:C});if(Q)return Q;throw Da(new lt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let fe=new lt(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:H.status});throw Object.assign(fe,{telemetryOutcome:Vl(H.status,C)})}async function ea(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:c,returnUrl:s,telemetry:S}){let b=t?.getRawProvider();if(!b)throw rr(new lt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Da(new lt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Yl(e.threeDSecureToken),m=null,B=e.paymentMethodId,D=await vo(()=>Gl(b,e.threeDSecureToken,g),"card");if(D){if(D.error)throw rr(new lt(D.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:D.error.code}),"card");let w=D.intent;!B&&w?.payment_method&&(typeof w.payment_method=="string"?B=w.payment_method:"id"in w.payment_method&&(B=w.payment_method.id??void 0))}let u=B?await vo(()=>Wl(b,e.threeDSecureToken,{payment_method:B,return_url:s??Na(c)??window.location.href},g),"card"):null;if(u){if(u.error)throw rr(new lt(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");m=u.intent}else{let w=await vo(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(w.error)throw rr(new lt(w.error.message??"3DS authentication failed.","api_error",{code:w.error.code}),"card");m=(g?w.setupIntent:w.paymentIntent)??null}if(m&&(m.status==="requires_capture"||m.status==="succeeded"||m.status==="processing")){let w=await Hr({billingApiUrl:o,sessionId:a,session:c,telemetry:S,tokenizedData:{id:m.id,type:"card",threeDSecureActionResultTokenId:m.id},returnUrl:s});return w.type==="success"?{...w.result,paymentIntentId:w.result.paymentIntentId??m.id,paymentMethodId:w.result.paymentMethodId??B}:ea(w,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:c,returnUrl:s,telemetry:S})}throw rr(new lt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw rr(new lt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:B}=await vo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(B)throw rr(new lt(B.message??"PayPal authorization failed.","api_error",{code:B.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:m}=await vo(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Na(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(m)throw rr(new lt(m.message??"PayPal authorization failed.","api_error",{code:m.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new lt("Unsupported payment redirect state.","api_error")}function Rr(e){if(e instanceof lt){let r=cr(e.message);return r&&r!==e.message?Object.assign(new lt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=cr(t)??t;return new lt(n,"api_error")}function ta(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new lt("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function na({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[c,s]=await Promise.all([as(e,{billingApiUrl:n,locale:r,telemetry:o}),a?as(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{PaymentAPI as So,toStripeAppearance as ec}from"@flopay/js";import{COUNTRY_OPTIONS as tc,classifyPaymentRejection as nc,FloPayError as On,filterStripeMethodsByCountry as rc,getPostalCodeExample as oc,getPostalCodeLabel as Ua,getStateFromPostalCode as ms,getStateLabel as ys,getStateOptions as ac,getStripeMethodDisplayName as xr,hasVendoredStripeMethodLogo as ic,isAuthorizationOnlySession as La,isAVSFieldVisible as ze,isPostalCodeSupported as sc,isSetupIntentClientSecret as lc,isValidEmail as en,isValidPostalCode as cc,needsStripeMethodExplicitConfirm as fs,normalizeCheckoutFailureOutcome as dc,partitionStripeMethods as uc,resolveAVSConfig as pc,resolveButtonsLayoutTheme as mc,resolveStripeMethodBrandVariant as yc,resolveTheme as fc,stripeExpressMethodToOptionKey as gs}from"@flopay/shared";import{ExpressCheckoutElement as Is,PaymentElement as gc,Elements as _r,useElements as ja,useStripe as Ka}from"@stripe/react-stripe-js";import hc,{useCallback as Pe,useContext as Yr,useEffect as ht,useMemo as gt,useRef as Ee,useState as ye}from"react";function us(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var ps={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as fr,jsx as l,jsxs as Ie}from"react/jsx-runtime";var Gn="flopay_stripe_resume",hs="flopay_wallet_resume";function Es(e){return e instanceof On&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function oa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new So(e).createSessionIntent(...n)}catch(o){throw Es(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Co="flopay_paypal_resume",bc=250,bs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Va(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function aa({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new So(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function vc(e){return e instanceof On&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Oa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Pc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=kn(r?.name),a=kn(n);return{email:r?.email?.trim()||t?.trim(),firstName:o.firstName??a.firstName,lastName:o.lastName??a.lastName}}async function Rs({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let c=Pc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return!en(c.email)||!fo(c)?a(o,c):c}var Cc=`
|
|
5
5
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
6
6
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
7
7
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -22,7 +22,7 @@ ${Mt.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
|
-
`,ra=44;function Ha(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Sc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},_s={width:"100%",minHeight:ra,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function wc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function vs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function qa(e){return e==="paypal"?"PayPal":xr(e)}function kc(e,t){let n=`We couldn't open ${qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function xs(e){let t=Ie(0),n=Ie(null),r=Ie(null),o=Pe((u=r.current)=>{let w=u;w?.timer&&(clearTimeout(w.timer),w.timer=null)},[]),a=Pe((u,w)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(u),u.timer=setTimeout(()=>{u.timer=null,r.current?.generation===u.generation&&(r.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},w))},[o,e]),c=Pe(u=>{u.yieldedControl&&a(u,600)},[a]),s=Pe(u=>{o();let w=t.current+1;t.current=w,n.current=null;let ve={generation:w,method:u,timer:null,yieldedControl:!1};return r.current=ve,w},[o]),S=Pe(u=>{let w=r.current;return typeof u=="number"&&w?.generation!==u?!1:(o(w),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),b=Pe(u=>{let w=r.current,ve=u??w?.generation??t.current;(!u||w?.generation===u)&&(o(w),r.current=null),n.current=ve},[o]),g=Pe(u=>n.current===(u??t.current),[]),m=Pe(u=>r.current?.generation===u&&n.current!==u,[]),M=Pe(()=>{let u=r.current;u&&c(u)},[c]),D=Pe(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return ht(()=>{let u=()=>{document.visibilityState==="visible"?M():D()},w=()=>{D()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",w),window.addEventListener("focus",M),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",w),window.removeEventListener("focus",M),o()}},[o,D,M]),{startAttempt:s,finishAttempt:S,invalidateAttempt:b,isAttemptInvalidated:g,isAttemptCurrent:m}}function Ic(e){let t=oc(e);return`Enter a valid ${Ua(e)}${t?` (e.g. ${t})`:""}`}function Ec(e,t,n){let r=sc(e),o=t.trim(),a=n&&r,c=a&&!o,s=a&&!!o&&!cc(e,o);return{visible:n,supported:r,required:a,empty:c,malformed:s}}function Rc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!en(n);return{required:t,empty:r,malformed:o,value:n}}function Ps(e,t){return t instanceof On?t:new On(t instanceof Error?t.message:`${wc(e)} before-click hook failed.`,"validation_error")}function za(){return l("style",{children:Cc})}function _c(e){return typeof e=="number"?`${e}px`:e}function Ts(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function As({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:ke("div",{style:{position:"relative",minHeight:44},children:[l("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),l("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function Cs(e){return e!=="unavailable"&&e!=="load_error"}function Ya(e){return l(Tc,{...e})}function Ss({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:S,onTechnicalFailure:b,runBeforeButtonClick:g,billingName:m,onBuyerIdentityReady:M,onLoadStateChange:D,placeholderBorderRadius:u}){let w=ur(),{emitInstrument:ve}=Yr(In),H=Ka(),P=ja(),[fe,Q]=ye("loading");ht(()=>{D?.(fe)},[fe,D]);let[ce,oe]=ye(!1),Ce=!en(n?.trim())||!m?.trim(),{request:He,collect:be,finish:Rt}=qr(),De=Ie(!1),Te=Ie(null),Ae=Ie(null),[ee,J]=ye(0),[L,me]=ye(!1),et=Ie(!1),Ue=Ie(new Map),{startAttempt:Ye,finishAttempt:te,invalidateAttempt:T,isAttemptInvalidated:ae,isAttemptCurrent:Fe}=xs((G,Y,$)=>{b?.(G,Y,{...$,popupBlocked:$?.popupBlocked??dr(Y)}),me(!0),J(we=>we+1)});ht(()=>{L&&Ae.current?.focus()},[L,ee]);let ie=Pe(()=>{J(G=>G+1)},[]),j=Pe((G,Y,$)=>{T($),b?.("paypal",G,{code:Y,popupBlocked:dr(G)}),me(!0),ie()},[T,b,ie]),_e=Pe(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);ht(()=>{et.current&&(et.current=!1,_e())},[_e,ee]);let Je=Pe(()=>{me(!1),a?.(null),_e()},[_e,a]);ht(()=>{if(!H||De.current)return;let G=new URLSearchParams(window.location.search),Y=G.get("payment_intent"),$=G.get("payment_intent_client_secret"),we=G.get("redirect_status");if(!Y||!$)return;De.current=!0;let Me;try{let K=localStorage.getItem(Co);if(K){let I=JSON.parse(K);I.clientSecret===$&&(Me={...I.accountPatch?{accountPatch:I.accountPatch}:{},...I.sessionId?{sessionId:I.sessionId}:{},...I.nonce?{nonce:I.nonce}:{}})}}catch{}try{localStorage.removeItem(Co)}catch{}let x=new URL(window.location.href);x.searchParams.delete("payment_intent"),x.searchParams.delete("payment_intent_client_secret"),x.searchParams.delete("redirect_status"),window.history.replaceState({},"",x.toString()),(async()=>{try{if(oe(!0),we==="failed"){let C="PayPal payment was declined. Please try again.";a?.(C),S?.($t("paypal",C));return}let{paymentIntent:K,error:I}=await H.retrievePaymentIntent($);if(I){a?.(I.message??"Failed to retrieve PayPal payment status.");return}if(K&&(K.status==="requires_capture"||K.status==="succeeded")){let C=typeof K.payment_method=="string"?K.payment_method:K.payment_method?.id;o({id:C??K.id,type:"card",threeDSecureActionResultTokenId:K.id,isPaypal:!0},Me)}else{let C="PayPal payment was not completed. Please try again.";a?.(C),S?.($t("paypal",C))}}catch(K){a?.(K instanceof Error?K.message:"Failed to complete PayPal payment.")}finally{oe(!1)}})()},[H,o,a,S]);let We=Pe(async G=>{if(c||ce){G.reject();return}let Y=g?await g("paypal"):{proceed:!0};if(!Y.proceed){Ue.current.delete(ee),G.reject();return}let $=Ye("paypal");Ue.current.set(ee,{generation:$,accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}),me(!1),s?.("paypal"),G.resolve()},[Ue,c,s,g,Ye,ce,ee]),Se=Pe(async G=>{if(!H||!P)return;let Y=Ue.current.get(ee);if(Y&&!Fe(Y.generation)){Ue.current.delete(ee);return}if(!Y&&ae()||Y&&!te(Y.generation))return;Y||te();let $=Y??null;if(Ue.current.delete(ee),!$&&g){let C=await g("paypal");if(!C.proceed){G.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:C.accountPatch,sessionId:C.sessionId,nonce:C.nonce}}let we=$?.sessionId??e,Me=$?.nonce??t,x=await Rs({event:G,prepared:$,email:n,billingName:m,methodLabel:"PayPal",collect:be});if(!x){G.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let K=x.email,I={...$?.accountPatch,...x};try{if(oe(!0),a?.(null),!we||!en(K))throw new Error("Missing sessionId or email for PayPal payment");await M?.(x);let C=H.createPaymentMethod,{error:nt,paymentMethod:St}=await C({type:"paypal"});if(nt){j(nt,"stripe_paypal_create_payment_method_failed",Y?.generation),G.paymentFailed({reason:"fail"});return}let de=await oa(r,ve,we,Me??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:St?.id??null,intentKind:"payment"});if(de.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=de.clientSecret,it={return_url:window.location.href};if(St?.id&&(it.payment_method=St.id),typeof window<"u")try{localStorage.setItem(Co,JSON.stringify({clientSecret:ct,sessionId:we,nonce:Me,accountPatch:I}))}catch{}let{error:rt,paymentIntent:je}=await H.confirmPayment({clientSecret:ct,confirmParams:it,redirect:"if_required"});if(rt){if(typeof window<"u")try{localStorage.removeItem(Co)}catch{}if(go(rt)){let U=rt.message??"Your payment was declined.";a?.(U),S?.($t("paypal",U,{code:tr(rt),declineCode:$r(rt)})),await aa({billingApiUrl:r,sessionId:we,nonce:Me,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:tr(rt)??"provider_declined"}})}else j(rt,"stripe_paypal_confirm_failed",Y?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Co)}catch{}let y=typeof je?.payment_method=="string"?je.payment_method:je?.payment_method?.id;o({id:y??je?.id,type:"card",threeDSecureActionResultTokenId:je?.id,isPaypal:!0},{accountPatch:I,sessionId:we,nonce:Me});return}catch(C){j(C,"stripe_paypal_failed",Y?.generation)}finally{oe(!1)}},[H,P,e,t,n,m,be,M,r,ve,o,a,S,g,j,te,Fe,ae,ee]);return ke(fr,{children:[l(As,{state:fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:u,children:ke("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[L&&l("button",{ref:Ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Je,style:_s,children:"Try PayPal again"}),He&&l(Ir,{identity:He.identity,methodLabel:He.methodLabel,onComplete:Rt,onCancel:()=>Rt(null)},He.id),l("div",{style:{display:He?"none":void 0},children:l(Is,{onReady:G=>Q(Ts(G,["paypal"])),onLoadError:()=>{Q("load_error"),Va(jt(w),"paypal","paypal")},onClick:We,onConfirm:Se,onCancel:()=>{let G=Ue.current.get(ee);Ue.current.delete(ee),jt(w)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(G?.generation),me(!1),et.current=!0,ie()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Ce,emailRequired:Ce,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),ce&&l(Yn,{status:"processing"})]})}function ws({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:S,onDecline:b,onTechnicalFailure:g,runBeforeButtonClick:m,billingName:M,onBuyerIdentityReady:D,onLoadStateChange:u,placeholderBorderRadius:w}){let ve=ur(),{emitInstrument:H}=Yr(In),P=Ka(),fe=ja(),[Q,ce]=ye("loading");ht(()=>{u?.(Q)},[Q,u]);let[oe,Ce]=ye(!1),He=!en(n?.trim())||!M?.trim(),{request:be,collect:Rt,finish:De}=qr(),Te=Ie(null),Ae=Ie(null),[ee,J]=ye(0),[L,me]=ye(!1),[et,Ue]=ye("google_pay"),Ye=Ie(!1),te=Ie("google_pay"),T=Ie("google_pay"),ae=Ie(new Map),{startAttempt:Fe,finishAttempt:ie,invalidateAttempt:j,isAttemptInvalidated:_e,isAttemptCurrent:Je}=xs((x,K,I)=>{g?.(x,K,{...I,popupBlocked:I?.popupBlocked??dr(K)}),Ue(x),me(!0),J(C=>C+1)});ht(()=>{L&&Ae.current?.focus()},[L,ee]);let We=Pe(()=>{J(x=>x+1)},[]),Se=Pe((x,K,I,C)=>{j(C),g?.(x,K,{code:I,popupBlocked:dr(K)}),Ue(x),me(!0),We()},[j,g,We]),G=Pe(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);ht(()=>{Ye.current&&(Ye.current=!1,G())},[G,ee]);let Y=Pe(()=>{me(!1),s?.(null),G()},[G,s]),$=Pe(async x=>{if(!P||!fe)return;let K=ae.current.get(ee);if(K&&!Je(K.generation)){ae.current.delete(ee);return}if(!K&&_e()||K&&!ie(K.generation))return;K||ie();let I=x.expressPaymentType??K?.method??te.current,C=K??null;ae.current.delete(ee);let nt=vs(I);if(!C&&m){let y=await m(nt);if(!y.proceed){x.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}C={accountPatch:y.accountPatch,sessionId:y.sessionId,nonce:y.nonce}}let St=nt,de=C?.sessionId??e,ct=C?.nonce??t,it=await Rs({event:x,prepared:C,email:n,billingName:M,methodLabel:qa(I),collect:Rt});if(!it){x.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let rt=it.email,je={...C?.accountPatch,...it};try{if(Ce(!0),s?.(null),!en(rt))throw new Error("Missing sessionId or email for wallet payment");await D?.(it);let{error:y}=await fe.submit();if(y){Se(I,y,"stripe_wallet_submit_failed",K?.generation);return}let{error:U,paymentMethod:Xe}=await P.createPaymentMethod({elements:fe});if(U||!Xe){Se(I,U??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",K?.generation);return}if(!de)throw new Error("Missing sessionId or email for wallet payment");let dt=await oa(r,H,de,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I??nt,paymentMethodId:Xe.id,intentKind:o});if(dt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Mt=dt.clientSecret,{error:Bt,intentId:W}=lc(Mt)?await P.confirmCardSetup(Mt,{payment_method:Xe.id}).then(Le=>({error:Le.error,intentId:Le.setupIntent?.id})):await P.confirmCardPayment(Mt,{payment_method:Xe.id}).then(Le=>({error:Le.error,intentId:Le.paymentIntent?.id}));if(Bt){if(go(Bt)){let Le=Bt.message??"Your payment was declined.";s?.(Le),b?.($t(St,Le,{code:tr(Bt),declineCode:$r(Bt)})),await aa({billingApiUrl:r,sessionId:de,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I??nt,providerDeclineReason:tr(Bt)??"provider_declined"}})}else Se(I,Bt,"stripe_wallet_confirm_failed",K?.generation);return}c({id:Xe.id,type:"card",threeDSecureActionResultTokenId:W},{accountPatch:je,sessionId:de,nonce:ct})}catch(y){Se(I,y,"stripe_wallet_failed",K?.generation)}finally{Ce(!1)}},[P,fe,e,t,n,M,Rt,D,r,H,o,c,s,b,m,Se,ie,Je,_e,ee]),we=gt(()=>{let x=["applePay","googlePay","paypal","link","amazonPay","klarna"],K=new Set(["applePay","googlePay"]),I=new Set(a.map(gs)),C={};for(let nt of x)I.has(nt)?C[nt]=K.has(nt)?"always":"auto":C[nt]="never";return C},[a]),Me=gt(()=>a.map(gs),[a]);return ke(fr,{children:[l(As,{state:Q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:w,children:ke("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[L&&ke("button",{ref:Ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Y,style:_s,children:["Try ",qa(et)," again"]}),be&&l(Ir,{identity:be.identity,methodLabel:be.methodLabel,onComplete:De,onCancel:()=>De(null)},be.id),l("div",{style:{display:be?"none":void 0},children:l(Is,{onReady:x=>{ce(Ts(x,Me))},onLoadError:x=>{ce("load_error"),Va(jt(ve),"stripe","wallet")},onClick:async x=>{te.current=x.expressPaymentType,T.current=vs(x.expressPaymentType);let K=m?await m(T.current):{proceed:!0};if(!K.proceed){ae.current.delete(ee),x.reject();return}let I=Fe(x.expressPaymentType);ae.current.set(ee,{generation:I,method:x.expressPaymentType,accountPatch:K.accountPatch,sessionId:K.sessionId,nonce:K.nonce}),me(!1),S?.(T.current),x.resolve()},onConfirm:$,onCancel:()=>{let x=ae.current.get(ee);ae.current.delete(ee),jt(ve)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),j(x?.generation),me(!1),Ye.current=!0,We()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:we,emailRequired:He,billingAddressRequired:He,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),oe&&l(Yn,{status:"processing"})]})}function xc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:S,textColor:b,borderRadius:g,fontFamily:m}){let M=yc(e,t),D=ps[e],[u,w]=ye(!1),ve=M?.backgroundColor??s??"#ffffff",H=M?.borderColor??S??"#d1d5db",P=M?.textColor??b??"#262833";return l("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&c()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ra,padding:"0 1rem",backgroundColor:ve,color:P,border:`1px solid ${H}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:m,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?l("span",{style:{margin:"0 auto"},children:`Connecting to ${xr(e)}\u2026`}):ke(fr,{children:[ke("span",{style:{display:"inline-flex",alignItems:"center",gap:ic(e)?8:0},children:[D&&!u?l("img",{src:D,alt:"","aria-hidden":"true",onError:()=>w(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):M?.logoSvg?l("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:M.logoSvg}}):null,l("span",{children:xr(e)})]}),a&&l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:P,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:l("path",{d:"M9 18l6-6-6-6"})})]})})}function $a({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:c,onTokenizedBody:s,onErrorChange:S,onDecline:b,onCancel:g,runBeforeButtonClick:m,onButtonClick:M,isProcessing:D,submitButtonColor:u,submitButtonBorderRadius:w,submitButtonStyle:ve,errorText:H}){let P=ur(),{emitInstrument:fe}=Yr(In),Q=Ka(),ce=ja(),[oe,Ce]=ye(!1),He=Ie(!1),[be,Rt]=ye(!1),[De,Te]=ye("loading"),[Ae,ee]=ye(""),[J,L]=ye(""),me=!en(r?.trim()),et=!o?.trim(),Ue=(!me||en(Ae.trim()))&&(!et||!!J.trim()),Ye=Pe(async()=>{if(!Q||!ce||D||He.current||!be)return;He.current=!0,Ce(!0);let te=m?await m("card"):{proceed:!0};if(!te.proceed){He.current=!1,Ce(!1);return}M?.("card");let T=te.sessionId??t,ae=te.nonce??n,Fe=kn(o?.trim()||J.trim()),ie={email:te.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:te.accountPatch?.firstName?.trim()||Fe.firstName,lastName:te.accountPatch?.lastName?.trim()||Fe.lastName},j=ie.email,_e={...te.accountPatch,...ie};try{if(S?.(null),!en(j)||!fo(ie))throw new Error("A valid email address and full name are required for payment.");await a?.(ie);let Je=await ce.submit();if(Je.error){S?.(Je.error.message??"Payment failed.");return}let We=await Q.createPaymentMethod({elements:ce,params:{billing_details:{email:j,name:[ie.firstName,ie.lastName].filter(Boolean).join(" ")}}});if(We.error||!We.paymentMethod){S?.(We.error?.message??"Failed to create payment method.");return}let Se=We.paymentMethod;if(!T||!j)throw new Error("Missing sessionId or email for payment.");let G=Se.type||e,Y=await oa(c,fe,T,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:G,paymentMethodId:null,intentKind:"payment"});if(Y.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let $=Y.clientSecret;if(typeof window<"u")try{localStorage.setItem(Gn,JSON.stringify({clientSecret:$,sessionId:T,nonce:ae,accountPatch:_e,paymentMethodId:Se.id,paymentMethodType:Se.type??e,gateway:"stripe"}))}catch{}let{error:we,paymentIntent:Me}=await Q.confirmPayment({clientSecret:$,confirmParams:{return_url:window.location.href,payment_method:Se.id},redirect:"if_required"});if(we){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let I=we.message??"Payment failed.";S?.(I),b?.($t("card",I,{code:we.code})),await aa({billingApiUrl:c,sessionId:T,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:we.code??"provider_declined"}});return}let x=Me?.status;if(!jo(x)){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let I=x==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(I),b?.($t("card",I,{code:x??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let K=typeof Me?.payment_method=="string"?Me.payment_method:Me?.payment_method?.id;s({id:K??Se.id,type:"card",threeDSecureActionResultTokenId:Me?.id,gateway:"stripe",paymentMethodType:Se.type??e},{accountPatch:_e,sessionId:T,nonce:ae})}catch(Je){S?.(Je instanceof Error?Je.message:"Payment failed. Please try again.")}finally{He.current=!1,Ce(!1)}},[Q,ce,D,be,m,M,t,n,r,o,Ae,J,a,c,fe,e,s,S,b]);return ke("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(me||et)&&ke("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:[me&&ke("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",l("input",{type:"email",autoComplete:"email",required:!0,value:Ae,onChange:te=>ee(te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),et&&ke("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",l("input",{type:"text",autoComplete:"name",required:!0,value:J,onChange:te=>L(te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})]}),l(gc,{onReady:()=>Te("ready"),onLoadError:()=>{Te("load_error"),Va(jt(P),"stripe","apm")},onChange:te=>{Rt(!!te.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...en(r?.trim())?{email:r?.trim()}:{}}}}}),l("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ye()},disabled:!be||!Ue||oe||D||De!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:w,fontSize:"1rem",fontWeight:600,cursor:!be||!Ue||oe||D||De!=="ready"?"not-allowed":"pointer",opacity:!be||!Ue||oe||D||De!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ve??{}},children:oe?"Processing\u2026":`Pay with ${xr(e)}`}),H&&l(Kr,{margin:"0.75rem 0 0",children:H})]})}function ks({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:c,stripeInstance:s,paymentElementBaseOptions:S,onTokenizedBody:b,onErrorChange:g,onButtonClick:m,onDecline:M,runBeforeButtonClick:D,onLoadStateChange:u,isProcessing:w=!1,submitButtonColor:ve="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:P,buttonAppearance:fe,themeId:Q,onExpandApm:ce,expandedApmMethod:oe}){let{emitInstrument:Ce}=Yr(In),[He,be]=ye(null),[Rt,De]=ye(null),Te=Ie(!1),{request:Ae,collect:ee,finish:J}=qr();ht(()=>{c.length>0&&s?u?.("ready"):s||u?.("loading")},[c.length,s,u]);let L=Pe(async T=>{if(!s||Te.current||w)return;Te.current=!0,De(T);let ae=D?await D("card"):{proceed:!0};if(!ae.proceed){Te.current=!1,De(null);return}m?.("card");let Fe=ae.sessionId??e,ie=ae.nonce??t,j=kn([ae.accountPatch?.firstName,ae.accountPatch?.lastName].filter(Boolean).join(" ")||r),_e={email:ae.accountPatch?.email?.trim()||n?.trim(),firstName:ae.accountPatch?.firstName?.trim()||j.firstName,lastName:ae.accountPatch?.lastName?.trim()||j.lastName};if(!en(_e.email)||!fo(_e)){De(null);let Se=await ee(xr(T),_e);if(!Se){Te.current=!1;return}_e=Se,De(T)}let Je=_e.email,We={...ae.accountPatch,..._e};try{if(g?.(null),!Fe||!en(Je)||!fo(_e))throw new Error("Missing sessionId or email for payment.");await o?.(_e);let Se=await oa(a,Ce,Fe,ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(Se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let G=Se.clientSecret;if(typeof window<"u")try{localStorage.setItem(Gn,JSON.stringify({clientSecret:G,sessionId:Fe,nonce:ie,accountPatch:We,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:$}=await s.confirmPayment({clientSecret:G,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[_e.firstName,_e.lastName].filter(Boolean).join(" "),...Je?{email:Je}:{}}}},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let x=Y.message??"Payment failed.";g?.(x),M?.($t("card",x,{code:Y.code})),await aa({billingApiUrl:a,sessionId:Fe,nonce:ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:Y.code??"provider_declined"}});return}let we=$?.status;if(!jo(we)){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let x=we==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(x),M?.($t("card",x,{code:we??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let Me=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;b({id:Me??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:We,sessionId:Fe,nonce:ie})}catch(Se){g?.(Se instanceof Error?Se.message:"Payment failed. Please try again.")}finally{Te.current=!1,De(null)}},[s,w,D,m,e,t,n,ee,a,Ce,r,o,b,g,M]),[me,et]=ye(null),Ue=ce?oe??null:me,Ye=Pe(T=>{Te.current||w||Ue&&Ue!==T||(fs(T)?ce?ce(T):et(T):L(T))},[Ue,w,L,ce]),te=gt(()=>me?{...S,paymentMethodTypes:[me]}:null,[me,S]);return l("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ae?l(Ir,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:J,onCancel:()=>J(null)},Ae.id):c.map(T=>{let ae=oe===T,Fe=Rt===T,ie=Rt!==null&&Rt!==T||oe!=null&&oe!==T;return ke(hc.Fragment,{children:[l(xc,{method:T,themeId:Q,submitting:Fe,disabled:ie,highlighted:ae,hasNextStep:fs(T),onClick:()=>Ye(T),backgroundColor:fe?.backgroundColor,borderColor:fe?.borderColor,textColor:fe?.textColor,borderRadius:fe?.borderRadius,fontFamily:fe?.fontFamily}),!ce&&me===T&&te&&s&&l(_r,{stripe:s,options:te,children:l($a,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:b,onErrorChange:g,onDecline:M,onCancel:()=>et(null),runBeforeButtonClick:D,onButtonClick:m,isProcessing:w,submitButtonColor:ve,submitButtonBorderRadius:H,submitButtonStyle:P})},T)]},T)})})}function Tc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:c,onDecline:s,onTokenizedBody:S,firstName:b,lastName:g,chv:m,className:M,isProcessing:D,error:u,onErrorChange:w,showPayPal:ve=!0,showStripe:H=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:fe,showApplePay:Q=!0,showGooglePay:ce=!0,layout:oe="default",theme:Ce,buttonsTheme:He,buttonsStyles:be,appearance:Rt,cardButtonContent:De,cardBackButtonContent:Te,cardTitleContent:Ae,showSecurityFooter:ee,onButtonClick:J,onBeforeButtonClick:L,onBuyerIdentityReady:me,enableAVS:et,cardFieldOrder:Ue,cardPreFormSlot:Ye,avsLayout:te="row",country:T,zip:ae,addressLine1:Fe,addressLine2:ie,city:j,state:_e,onCountryChange:Je,onZipChange:We,avsCheck:Se,checkoutType:G,checkoutLayout:Y,totalAmount:$=0,currency:we="usd",initialCardOpen:Me=!1,directPaypal:x,isSubscription:K=!1,session:I,dataAttachmentPending:C=!1,dataAttachmentRequiresIdentity:nt=!1,debug:St=!1}){let de=ur(),ct=_a(),it=Yr(Ln),{emitInstrument:rt}=Yr(In),je=C||it.claimPending===!0,y=nt||it.claimRequiresIdentity===!0,U=je&&!y,Xe=Ji(),[dt,Mt]=ye(!1),[Bt,W]=ye(null),[Le,Wt]=ye(T??"US"),[wt,Ot]=ye(ae??""),[Rn,_n]=ye(Fe??""),[Zn,Jt]=ye(ie??""),[cn,dn]=ye(j??""),[Ft,vn]=ye(_e??""),[bt,ir]=ye(""),[Ht,sr]=ye(""),[Nt,zn]=ye({}),ot=Ie(ae??""),_t=Ie(T??"US"),xt=Ie(Fe??""),tn=Ie(ie??""),un=Ie(j??""),pn=Ie(_e??""),Un=Ie(""),qn=Ie(""),zt=Ie({});ht(()=>{let i=(R,N,he,z,Re)=>{if(zt.current[R])return;let Ne=N?.trim();!Ne||Ne===he.current||(he.current=Ne,z(Ne),Re?.(Ne))};i("country",T,_t,Wt,Je),i("zip",ae,ot,Ot,We),i("addressLine1",Fe,xt,_n),i("addressLine2",ie,tn,Jt),i("city",j,un,dn),i("state",_e,pn,vn)},[T,ae,Fe,ie,j,_e,Je,We]);let X=gt(()=>pc(et),[et]),Pn=X!==null,xn=gt(()=>La(I),[I]),Qn=!!I?.vault?.html,br=!!I?.gateways?.pcivault,Tn=!!(I?.gateways?.stripe?.enabledPaymentMethods??P)?.includes("card"),mn=Qn||Tn||br,Be=!!(H&&mn&&de&&e),[Xt,Dt]=ye(()=>oe!=="buttons"||Me?e??null:null),[$n,v]=ye(0),ut=oe!=="buttons"||Me||!!e&&Xt===e,qe=gt(()=>!de||!Be||!e||!ut?null:de.cardCapture({sessionId:e,captureMethod:I?.captureMethod}),[de,Be,e,ut,I?.captureMethod]),yn=gt(()=>{let i=Le,R=X?ze(X.postal_code,i):!1;return Ec(i,wt,R)},[X,Le,wt]),{avsInvalid:Ze,invalidAvsFields:Ut}=gt(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Be||!X)return{avsInvalid:!1,invalidAvsFields:i};let R=Le,N=(Re,Ne)=>ze(Re,R)&&!Ne.trim(),he={line1:N(X.address_line_1,Rn),city:N(X.city,cn),state:N(X.state,Ft),zip:yn.empty||yn.malformed};return{avsInvalid:he.line1||he.city||he.state||he.zip,invalidAvsFields:he}},[Be,X,Le,Rn,cn,Ft,yn]),[lr,jn]=ye(!1),[Cn,Zt]=ye(!1),[fn,gn]=ye(()=>Oa(I?.vault)),[xe,kt]=ye(Me&&mn?"card":"buttons"),[Tt,An]=ye(null),hn=xe==="expanding"||xe==="card",Mn=I?.gateways?.stripe?"stripe":void 0,Bn=Pe(()=>{rt?.({class:"card_surface",provider:Mn})},[Mn,rt]),qt=280,on=Ie(null),an=Pe(i=>{on.current&&clearTimeout(on.current),on.current=setTimeout(()=>{on.current=null,i()},qt)},[qt]);ht(()=>()=>{on.current&&clearTimeout(on.current)},[]);let er=Pe(()=>{Bn(),Dt(e??null),v(i=>i+1),kt("expanding"),an(()=>kt("card"))},[an,Bn,e]),Ar=Pe(()=>{kt("collapsing"),an(()=>kt("buttons"))},[an]),Fn=Pe(i=>{An(i),kt("apm-expanding"),an(()=>kt("apm-form"))},[an]),Kn=Pe(()=>{kt("apm-collapsing"),an(()=>{kt("buttons"),An(null)})},[an]);ht(()=>{oe==="buttons"&&Me&&mn&&(Dt(e??null),kt("card"))},[oe,Me,mn,e]);let[Qt,at]=ye(null),Yt=Ie(!1),_=Ie(null),E=Ie("idle"),[V,Z]=ye(null),$e=Ie(V);ht(()=>{$e.current=V},[V]);let ne=n||Xe,B=u??Bt,h=gt(()=>fc(Ce),[Ce]),f=gt(()=>{let i=h?.buttonsLayout??mc(He);return be?{...i,...be,cardButton:{...i.cardButton,...be.cardButton},cardFormContainer:{...i.cardFormContainer,...be.cardFormContainer},backButton:{...i.backButton,...be.backButton},backButtonIcon:{...i.backButtonIcon,...be.backButtonIcon},submitButton:{...i.submitButton,...be.submitButton},title:{...i.title,...be.title}}:i},[h,He,be]),O=Rt??h?.appearance,pt=gt(()=>zi({appearance:O,buttonsStyles:f,layout:oe}),[O,f,oe]),vt=it.inlineSessionPatchProcessing??!1,d=(D??dt)||vt,p=ne.replace(/\/+$/,""),k=gt(()=>Ia({userId:o,email:r,firstName:b,lastName:g,country:T,zip:ae},Nt),[o,r,b,g,T,ae,Nt]),Ee=[k.firstName,k.lastName].filter(i=>!!i?.trim()).join(" "),q=!en(k.email?.trim()),F=!Ee.trim(),Ge=Ie(null),Qe=Ie(null);Be&&(Ge.current===null&&(Ge.current=q),Qe.current===null&&(Qe.current=F));let se=Be&&(Ge.current??q),ue=Be&&(Qe.current??F),A=se||ue,le=gt(()=>Rc(bt,se),[bt,se]),st=le.empty||le.malformed,Lt=ue&&!Ht.trim(),ge=gt(()=>de?de.getRawProvider():null,[de]),bn=gt(()=>ct?ct.getRawProvider():null,[ct]),Qr=$||100,_o=gt(()=>O?ec(O):null,[O]),xo=_o?{appearance:_o}:null,li=gt(()=>{let i=_o??{},R=i.rules??{};return{...i,rules:{...R,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...R[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...R[".AccordionItemContents"]??{}}}}},[_o]),ci=gt(()=>{let i=Hi($);return{...i,currency:we.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...xo}},[$,we,xo]),di=gt(()=>({mode:"payment",amount:Qr,currency:we.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...xo}),[Qr,we,xo]),pe=Pe(i=>{W(i),w?.(i)},[w]),da=Ie(""),[ui,$s]=ye(!1),To=Pe(()=>{$s(!0)},[]);ht(()=>{if(!Be||!A||!me||!ui||st||Lt||da.current)return;let i=kn(qn.current),R={email:en(k.email?.trim())?k.email?.trim():Un.current.trim(),firstName:k.firstName?.trim()||i.firstName,lastName:k.lastName?.trim()||i.lastName};da.current=JSON.stringify(R),zn(N=>({...N,...R})),Promise.resolve(me(R)).catch(N=>{da.current="",pe(N instanceof Error?N.message:"Failed to attach buyer details.")})},[Be,A,me,ui,st,Lt,k.email,k.firstName,k.lastName,pe]),ht(()=>{!Be||!qe||qe.setCardFieldOrder?.(Ue??null,X==null&&!A)},[Be,qe,Ue,X,A]),ht(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&pe(null)},[xe,pe]);let Nn=Pe((i,R,N)=>{s?.($t(i,R,N))},[s]),Mr=Pe((i,R,N)=>{let he=N?.popupBlocked??dr(R),z=kc(i,he),Re=Er(N?.code)??tr(R)??"external_payment_method_failed",Ne=new On(z,"api_error",{code:"external_payment_method_failed",param:i});at(null),oe==="buttons"&&(kt("buttons"),An(null)),pe(z),c?.(Ne),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:he})},[oe,c,pe]);ht(()=>{if(!Be||!e){gn(null);return}let i=Oa(I?.vault);if(i){gn(i);return}if(!ut){gn(null);return}gn(null);let R=!0;return new So(p).getVaultCapture(e,t).then(N=>{if(!R)return;let he=Oa(N);he?gn(he):pe("Failed to load the secure card form.")}).catch(N=>{R&&pe(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{R=!1}},[Be,ut,$n,e,I?.vault?.html,I?.vault?.messageToken,I?.vault?.expectedOrigin,p,t,pe]);let Vn=Ie({onComplete:a,onError:c,updateError:pe,emitDecline:Nn,resolvedAccount:k,avsConfig:X,avsCheckProp:Se,sessionId:e,nonce:t,baseUrl:p,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt});Vn.current={onComplete:a,onError:c,updateError:pe,emitDecline:Nn,resolvedAccount:k,avsConfig:X,avsCheckProp:Se,sessionId:e,nonce:t,baseUrl:p,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt};let ua=Ie(!1),js=Pe(()=>{let{resolvedAccount:i,avsConfig:R,avsCheckProp:N}=Vn.current,he=i.email?.trim(),z=en(he)?he:Un.current.trim();if(!en(z))return null;let Re=kn(qn.current),Ne=i.firstName?.trim()||Re.firstName,It=i.lastName?.trim()||Re.lastName;if(!Ne&&!It)return null;let Ct=_t.current||i.country||"US",mt=R?ze(R.state,Ct):!1,yt=R?ze(R.address_line_1,Ct):!1,Ke=R?ze(R.postal_code,Ct):!1,nn=R?ze(R.city,Ct):!1,Oe=R?ze(R.address_line_2,Ct):!1,ln=yt&&!mt&&Ke?ms(Ct,(ot.current??"").trim()):null,rn=mt?pn.current:ln;return{accountData:{userId:i.userId??"",email:z,firstName:Ne??"",lastName:It??"",...Ke&&ot.current?{zip:ot.current}:{},...nn&&un.current?{city:un.current}:{},...rn?{state:rn}:{},...yt&&xt.current?{addressLine1:xt.current}:{},...Oe&&tn.current?{addressLine2:tn.current}:{},country:Ct},...N!==void 0?{avsCheck:N}:{},...R?{avsConfig:{country:ze(R.country,Ct),postal_code:Ke,address_line_1:yt,address_line_2:Oe,city:nn,state:mt}}:{}}},[]),pi=Ie(je);pi.current=je,ht(()=>{je||B!==bs||Vn.current.updateError(null)},[je,B]),ht(()=>{!Be||!qe||qe.setSubmitGate?.(Ze||je||st||Lt)},[Be,qe,Ze,je,st,Lt]),ht(()=>{if(!Be||!qe)return;ua.current=!1;let i=!1,R=qe.on("submitting",()=>{jn(!0),_.current&&clearTimeout(_.current),E.current="validation-window",_.current=setTimeout(()=>{_.current=null,E.current==="validation-window"&&(E.current="processing")},bc),at("processing");let{baseUrl:Ne,sessionId:It,nonce:Ct,updateError:mt,onError:yt}=Vn.current;if(!It||!Ct)return;let Ke=js();if(!Ke){mt("Enter a valid email address."),E.current="idle",at(null);return}new So(Ne).patchAccountSnapshot(It,Ct,Ke,{telemetryMode:"best_effort"}).catch(nn=>{if(!vc(nn))return;let Oe=nn instanceof Error?nn.message:"Please check your billing address and try again.";mt(Oe),E.current="idle",at(null),yt?.(nn instanceof On?nn:new On(Oe,"api_error"))})}),N=qe.on("complete",async Ne=>{if(Vr(Ne.sessionId??Vn.current.sessionId),E.current="terminal",at("success"),await new Promise(mt=>setTimeout(mt,1200)),ua.current)return;ua.current=!0;let It=Vn.current,Ct=La(It)||Ne.outcome==="authorized";Vn.current.onComplete?.(Ct?{status:"authorized",paymentIntentId:Ne.intentId,paymentId:Ne.paymentId??It.paymentId,sessionId:Ne.sessionId??It.sessionId,authorizationExpiresAt:Ne.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ne.intentId,checkoutMethod:"card"})}),he=qe.on("decline",async Ne=>{let{updateError:It,emitDecline:Ct}=Vn.current,mt=Ne.message??"Your payment was declined. Please try another card or contact your bank.";E.current="terminal",It(mt),at("error");let yt=Ne.failureOutcome??dc(Ne.declineReason)??"authorization_declined";Ct("card",mt,{code:yt,declineCode:yt}),await new Promise(Ke=>setTimeout(Ke,1500)),!i&&(E.current="idle",at(null))}),z=qe.on("error",async Ne=>{let{updateError:It,onError:Ct}=Vn.current,mt=Ne.message??"There was a problem processing your payment. Please try again.";E.current="terminal",It(mt),at("error"),Ct?.(new On(mt,"api_error",{code:Ne.failureOutcome??"capture_failed"})),await new Promise(yt=>setTimeout(yt,1500)),!i&&(E.current="idle",at(null))}),Re=qe.on("blocked",()=>{if(!pi.current){jn(!0);return}To(),Vn.current.updateError(bs)});return()=>{i=!0,_.current&&(clearTimeout(_.current),_.current=null),E.current="idle",R(),N(),he(),z(),Re()}},[Be,qe,To]);let Hn=!!x?.clientId,eo=Array.isArray(P),Ao=eo&&P.length>0,Ks=eo&&P.includes("paypal"),{expressMethods:Mo,paymentElementMethods:to}=gt(()=>uc(P,{excludePaypal:Hn}),[P,Hn]),mi=Hn||!!ct,Vs=gt(()=>mi?Mo.filter(i=>i!=="paypal"):Mo,[Mo,mi]),Hs=gt(()=>{let i=[];return Q&&i.push("apple_pay"),ce&&i.push("google_pay"),i},[Q,ce]),Bo=eo?Vs:Hs,Ys=H&&Bo.length>0,pa=Pn?Le:T,Fo=gt(()=>{let i=pa?.trim().toUpperCase();return i?fe?to.filter(R=>{let N=fe[R];return!N||N.length===0||N.includes(i)}):rc(to,pa):to},[to,pa,fe]),ma=gt(()=>({mode:"payment",amount:Qr,currency:we.toLowerCase(),paymentMethodCreation:"manual",appearance:li}),[Qr,we,li]),[yi,fi]=ye("loading"),[gi,hi]=ye("loading"),[bi,vi]=ye("loading"),[Gs,ya]=ye(!1),[Pi,fa]=ye("loading"),[No,Ws]=ye();ht(()=>{Ws(us())},[]);let Ci=ve&&(Hn||(eo?Ks:No===!1)),Si=H&&Ys,no=!U&&Ci&&Hn,wi=Pi==="retrying"||Pi==="exhausted",ro=!U&&Ci&&!!bn&&(!Hn||wi),oo=!U&&Si&&!!ge,ao=!U&&H&&Ao&&Fo.length>0&&!!ge,Js=no&&!wi?Gs:ro&&Cs(yi),Xs=oo&&Cs(gi),Zs=ao&&bi!=="load_error",ki=i=>i==="loading"||i==="ready",Ii=no||ro&&ki(yi)||oo&&ki(gi)||ao&&bi!=="load_error",Do=Ie(!1);ht(()=>{if(!Do.current){if(!H&&!ve){Do.current=!0;let i=new On("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(i),pe(i.message)}else if(!H&&ve&&!Hn&&!bn){Do.current=!0;let i=new On("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(i),pe(i.message)}else if(No!==void 0&&!U&&!mn&&!Ii){Do.current=!0;let i=new On("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(i),pe(i.message)}}},[H,ve,Hn,bn,No,U,mn,Ii,c,pe]);let Ei=Ie(!1);ht(()=>{if(Ei.current||!Ao)return;let i=[];Q!==!0&&i.push("showApplePay"),ce!==!0&&i.push("showGooglePay"),i.length!==0&&(Ei.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Ao,Q,ce]);let Ri=Pe((i,R)=>it.applyInlineSessionPatch?it.applyInlineSessionPatch(i).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let he=Ps(R,N);return pe(he.message),c?.(he),{error:he,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[it.applyInlineSessionPatch,t,c,e,pe]),Dn=Pe(async i=>{if(!L)return{proceed:!0};try{let R=await L({method:i,sessionId:e||void 0,createSession:it.inlineSessionDraft});if(R===!1)return{proceed:!1};if(R&&typeof R=="object"){R.account&&zn(he=>({...he??{},...R.account}));let N=await Ri(R,i);return N.error?{proceed:!1,accountPatch:R.account}:{proceed:!0,accountPatch:R.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(R){let N=Ps(i,R);return pe(N.message),c?.(N),{proceed:!1}}},[Ri,it.inlineSessionDraft,L,c,e,pe]),_i=Pe(async(i,R)=>{if(Yt.current)return;Yt.current=!0,Mt(!0),at("processing"),pe(null);let N=R?.sessionId??e,he=R?.nonce??t,z=Ia(k,R?.accountPatch),Re=R?.completionPaymentMethodId??yo(i),Ne=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,It=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Ct=()=>{rt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:It})};try{let yt=await new So(p).processPayment(z.userId??"",{sessionId:N,nonce:he,tokenizedData:Ne,accountData:{userId:z.userId??"",email:z.email??"",firstName:z.firstName??"",lastName:z.lastName??"",...X?(()=>{let Oe=_t.current,ln=ze(X.state,Oe),rn=ze(X.address_line_1,Oe),Gt=ze(X.postal_code,Oe),co=rn&&!ln&&Gt?ms(Oe,(ot.current??"").trim()):null,uo=ln?pn.current:co;return{country:Oe,...Gt&&ot.current?{zip:ot.current}:{},...ze(X.city,Oe)&&un.current?{city:un.current}:{},...uo?{state:uo}:{},...rn&&xt.current?{addressLine1:xt.current}:{},...ze(X.address_line_2,Oe)&&tn.current?{addressLine2:tn.current}:{}}})():{}},chv:m,avsCheck:Se??!1,checkoutType:G,checkoutLayout:Y,avsConfig:X?{country:ze(X.country,_t.current),postal_code:ze(X.postal_code,_t.current),address_line_1:ze(X.address_line_1,_t.current),address_line_2:ze(X.address_line_2,_t.current),city:ze(X.city,_t.current),state:ze(X.state,_t.current)}:void 0});if(yt.ok){let Oe=yt.status===204?null:await yt.json().catch(()=>null),ln=La(I)||Oe?.status==="authorized";Vr(N),at("success"),Z(null),await new Promise(rn=>setTimeout(rn,1200)),a?.(ln?{status:"authorized",...typeof Oe?.paymentId=="string"?{paymentId:Oe.paymentId}:I?.paymentId?{paymentId:I.paymentId}:{},sessionId:typeof Oe?.sessionId=="string"?Oe.sessionId:N,...typeof Oe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Oe.authorizationExpiresAt}:I?.authorizationExpiresAt?{authorizationExpiresAt:I.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Ke=await yt.json().catch(()=>null);if(Ke?.type==="paypal_redirect_required"){let Oe=Ke.threeDSecureToken,ln=Ke.paymentMethodId||i.id||"";if(!de||!Oe){at("error"),pe("PayPal authorization required but no token provided.");return}try{let rn=ct?.getRawProvider();if(!rn){pe("PayPal is not available.");return}let Gt={return_url:window.location.href};ln&&(Gt.payment_method=ln);let{error:co}=await rn.confirmPayment({clientSecret:Oe,confirmParams:Gt,redirect:"if_required"});if(co){at("error");let uo=co.message??"PayPal payment failed.";pe(uo),Nn("paypal",uo,{code:co.code})}}catch(rn){at("error"),pe(rn instanceof Error?rn.message:"PayPal authorization failed.")}return}if(Ke?.type==="paypal_direct_required"){let Oe=Ke.orderId;if(!Oe){at("error"),pe("PayPal retry required but no order id provided.");return}let ln=$e.current?.attempts??0;if(ln>=2){at("error"),pe("PayPal payment could not be completed after multiple attempts."),Nn("paypal","paypal_direct_required retry limit exceeded");return}ya(!1),fa("loading"),Z({orderId:Oe,attempts:ln+1}),at(null);return}nc(yt.status,Ke)||Ct(),at("error");let nn=Ke?.message??"Payment failed. Please try again.";pe(nn),Nn(i.isPaypal?"paypal":"card",nn,{code:Ke?.code??Ke?.gatewayErrorCode,declineCode:Ke?.declineCode??Ke?.gatewayDeclineReason}),await new Promise(Oe=>setTimeout(Oe,1500))}catch(mt){Es(mt)||Ct(),at("error"),pe(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(yt=>setTimeout(yt,1500))}finally{Mt(!1),at(null),Yt.current=!1}},[p,e,t,k,Ee,m,de,ct,I,a,c,pe,Nn,rt]),Sn=Pe((i,R)=>{S?S(i):_i(i,R)},[S,_i]),xi=Ie(!1);ht(()=>{if(typeof window>"u"||xi.current)return;let i=new URLSearchParams(window.location.search),R=i.get("payment_intent"),N=i.get("payment_intent_client_secret"),he=i.get("redirect_status");if(!R||!N)return;let z=yt=>{let Ke=localStorage.getItem(yt);if(!Ke)return null;try{return JSON.parse(Ke)}catch{return localStorage.removeItem(yt),null}},Re=z(Gn)??z(hs),Ne;if(Re?.clientSecret){if(Re.clientSecret!==N)return;Ne={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;xi.current=!0,localStorage.removeItem(Gn),localStorage.removeItem(hs);let It=new URL(window.location.href);It.searchParams.delete("payment_intent"),It.searchParams.delete("payment_intent_client_secret"),It.searchParams.delete("redirect_status"),window.history.replaceState({},"",It.toString());let Ct=Re?.paymentMethodType??Re?.tokenType??"card",mt="card";(async()=>{let yt=de?.getRawProvider();if(!yt){let Gt="Payment is not available \u2014 please refresh and try again.";pe(Gt),Nn(mt,Gt);return}if(he==="failed"){let Gt="Payment was declined. Please try again.";pe(Gt),Nn(mt,Gt);return}let{paymentIntent:Ke,error:nn}=await yt.retrievePaymentIntent(N);if(nn){let Gt=nn.message??"Failed to retrieve payment status.";pe(Gt),Nn(mt,Gt,{code:nn.code});return}let Oe=Ke?.status,ln=jo(Oe);if(!Ke||!ln){let Gt=Oe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";pe(Gt),Nn(mt,Gt,{code:Oe??"missing_payment_intent"});return}let rn=typeof Ke.payment_method=="string"?Ke.payment_method:Ke.payment_method?.id;Sn({id:rn??Re?.paymentMethodId??Re?.tokenId??Ke.id,type:"card",threeDSecureActionResultTokenId:Ke.id,gateway:Re?.gateway??"stripe",paymentMethodType:Ct},Ne)})()},[e,Sn,de,pe,Nn]);let ga=Pe(i=>{i.preventDefault()},[]);if(!(de!==null))return l("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let io=oe==="buttons",sn=O?.variables,Qs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ha=sn?.colorBackground,el=ha&&!Qs.has(ha)?ha:void 0,vr=f.cardInputBorder??(io?"#e5e7eb":"#A4A4FF"),ba=sn?.colorDanger??"#dc2626",Pr=i=>lr&&i?ba:vr,Lo=(yn.malformed||yn.empty)&&(Cn||lr),tl=Lo?ba:Pr(Ut.zip),va=f.cardFormContainer?.backgroundColor??el??(io?"white":"#EDEDFF"),Cr=f.cardInputBackground??sn?.colorBackground??"white",Pa=Nr(Te),Ti=Nr(Ae),Br=f.nameInput,Ai=f.cardInputFontSize??_c(Br?.fontSize)??sn?.fontSizeBase??"16px",Mi=typeof Br?.fontFamily=="string"?Br.fontFamily:sn?.fontFamily??"Poppins, sans-serif",Bi=Oi(Br?.fontWeight)??400,nl=f.cardInputColor??(typeof Br?.color=="string"?Br.color:void 0)??sn?.colorText??"#262833",rl=f.cardInputPlaceholderColor??"#9ca3af",Pt=sn?.borderRadius??"8px",Sr=sn?.borderRadius??f.cardButton?.borderRadius??Pt,wr=sn?.colorPrimary??"#4A49FF",ol=sn?.colorPrimaryHover??po(wr,.12),so=sn?.colorText??"#262833",Fr={fontSize:Ai,fontFamily:Mi,fontWeight:Bi,color:nl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},al={"--flopay-input-placeholder-color":rl,"--flopay-input-font-size":Ai,"--flopay-input-font-family":Mi,"--flopay-input-font-weight":String(Bi)},lo=f.cardFormContainer??{},Ca=lo.padding??(io?"0":"1rem"),Sa=lo.borderRadius??Pt,il=qe&&fn?l(wa,{capture:qe,html:fn.html,messageToken:fn.messageToken,expectedOrigin:fn.expectedOrigin,theme:pt,onReady:()=>{if(!A&&!X||typeof document>"u")return;let i=()=>{(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};i();let R=0,N=window.setInterval(()=>{R+=1;let he=document.activeElement;!!he&&he.tagName==="IFRAME"&&he.id==="flopay_vault_form_iframe"?(i(),window.clearInterval(N)):R>=50&&window.clearInterval(N)},100)},onError:i=>pe(i),onValidation:i=>{let R=E.current;(R==="idle"||R==="validation-window")&&(pe(i),i&&E.current==="validation-window"&&(_.current&&(clearTimeout(_.current),_.current=null),E.current="idle",at(null)))}}):l("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Fi=ke("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Bn()},style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca,...al,display:"flex",flexDirection:"column"},children:[l("style",{children:`
|
|
25
|
+
`,ra=44;function Ha(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Sc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},_s={width:"100%",minHeight:ra,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function wc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function vs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function qa(e){return e==="paypal"?"PayPal":xr(e)}function kc(e,t){let n=`We couldn't open ${qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function xs(e){let t=Ee(0),n=Ee(null),r=Ee(null),o=Pe((u=r.current)=>{let w=u;w?.timer&&(clearTimeout(w.timer),w.timer=null)},[]),a=Pe((u,w)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(u),u.timer=setTimeout(()=>{u.timer=null,r.current?.generation===u.generation&&(r.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},w))},[o,e]),c=Pe(u=>{u.yieldedControl&&a(u,600)},[a]),s=Pe(u=>{o();let w=t.current+1;t.current=w,n.current=null;let ve={generation:w,method:u,timer:null,yieldedControl:!1};return r.current=ve,w},[o]),S=Pe(u=>{let w=r.current;return typeof u=="number"&&w?.generation!==u?!1:(o(w),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),b=Pe(u=>{let w=r.current,ve=u??w?.generation??t.current;(!u||w?.generation===u)&&(o(w),r.current=null),n.current=ve},[o]),g=Pe(u=>n.current===(u??t.current),[]),m=Pe(u=>r.current?.generation===u&&n.current!==u,[]),B=Pe(()=>{let u=r.current;u&&c(u)},[c]),D=Pe(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return ht(()=>{let u=()=>{document.visibilityState==="visible"?B():D()},w=()=>{D()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",w),window.addEventListener("focus",B),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",w),window.removeEventListener("focus",B),o()}},[o,D,B]),{startAttempt:s,finishAttempt:S,invalidateAttempt:b,isAttemptInvalidated:g,isAttemptCurrent:m}}function Ic(e){let t=oc(e);return`Enter a valid ${Ua(e)}${t?` (e.g. ${t})`:""}`}function Ec(e,t,n){let r=sc(e),o=t.trim(),a=n&&r,c=a&&!o,s=a&&!!o&&!cc(e,o);return{visible:n,supported:r,required:a,empty:c,malformed:s}}function Rc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!en(n);return{required:t,empty:r,malformed:o,value:n}}function Ps(e,t){return t instanceof On?t:new On(t instanceof Error?t.message:`${wc(e)} before-click hook failed.`,"validation_error")}function za(){return l("style",{children:Cc})}function _c(e){return typeof e=="number"?`${e}px`:e}function Ts(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function As({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:Ie("div",{style:{position:"relative",minHeight:44},children:[l("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),l("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function Cs(e){return e!=="unavailable"&&e!=="load_error"}function Ya(e){return l(Tc,{...e})}function Ss({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:S,onTechnicalFailure:b,runBeforeButtonClick:g,billingName:m,onBuyerIdentityReady:B,onLoadStateChange:D,placeholderBorderRadius:u}){let w=ur(),{emitInstrument:ve}=Yr(In),H=Ka(),C=ja(),[fe,Q]=ye("loading");ht(()=>{D?.(fe)},[fe,D]);let[ce,oe]=ye(!1),Ce=!en(n?.trim())||!m?.trim(),{request:He,collect:be,finish:Rt}=qr(),De=Ee(!1),Te=Ee(null),Ae=Ee(null),[ee,J]=ye(0),[L,de]=ye(!1),et=Ee(!1),Ue=Ee(new Map),{startAttempt:Ye,finishAttempt:te,invalidateAttempt:T,isAttemptInvalidated:ae,isAttemptCurrent:Fe}=xs((G,Y,$)=>{b?.(G,Y,{...$,popupBlocked:$?.popupBlocked??dr(Y)}),de(!0),J(we=>we+1)});ht(()=>{L&&Ae.current?.focus()},[L,ee]);let ie=Pe(()=>{J(G=>G+1)},[]),j=Pe((G,Y,$)=>{T($),b?.("paypal",G,{code:Y,popupBlocked:dr(G)}),de(!0),ie()},[T,b,ie]),_e=Pe(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);ht(()=>{et.current&&(et.current=!1,_e())},[_e,ee]);let Je=Pe(()=>{de(!1),a?.(null),_e()},[_e,a]);ht(()=>{if(!H||De.current)return;let G=new URLSearchParams(window.location.search),Y=G.get("payment_intent"),$=G.get("payment_intent_client_secret"),we=G.get("redirect_status");if(!Y||!$)return;De.current=!0;let Be;try{let K=localStorage.getItem(Co);if(K){let I=JSON.parse(K);I.clientSecret===$&&(Be={...I.accountPatch?{accountPatch:I.accountPatch}:{},...I.sessionId?{sessionId:I.sessionId}:{},...I.nonce?{nonce:I.nonce}:{}})}}catch{}try{localStorage.removeItem(Co)}catch{}let x=new URL(window.location.href);x.searchParams.delete("payment_intent"),x.searchParams.delete("payment_intent_client_secret"),x.searchParams.delete("redirect_status"),window.history.replaceState({},"",x.toString()),(async()=>{try{if(oe(!0),we==="failed"){let P="PayPal payment was declined. Please try again.";a?.(P),S?.(jt("paypal",P));return}let{paymentIntent:K,error:I}=await H.retrievePaymentIntent($);if(I){a?.(I.message??"Failed to retrieve PayPal payment status.");return}if(K&&(K.status==="requires_capture"||K.status==="succeeded")){let P=typeof K.payment_method=="string"?K.payment_method:K.payment_method?.id;o({id:P??K.id,type:"card",threeDSecureActionResultTokenId:K.id,isPaypal:!0},Be)}else{let P="PayPal payment was not completed. Please try again.";a?.(P),S?.(jt("paypal",P))}}catch(K){a?.(K instanceof Error?K.message:"Failed to complete PayPal payment.")}finally{oe(!1)}})()},[H,o,a,S]);let We=Pe(async G=>{if(c||ce){G.reject();return}let Y=g?await g("paypal"):{proceed:!0};if(!Y.proceed){Ue.current.delete(ee),G.reject();return}let $=Ye("paypal");Ue.current.set(ee,{generation:$,accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}),de(!1),s?.("paypal"),G.resolve()},[Ue,c,s,g,Ye,ce,ee]),Se=Pe(async G=>{if(!H||!C)return;let Y=Ue.current.get(ee);if(Y&&!Fe(Y.generation)){Ue.current.delete(ee);return}if(!Y&&ae()||Y&&!te(Y.generation))return;Y||te();let $=Y??null;if(Ue.current.delete(ee),!$&&g){let P=await g("paypal");if(!P.proceed){G.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}}let we=$?.sessionId??e,Be=$?.nonce??t,x=await Rs({event:G,prepared:$,email:n,billingName:m,methodLabel:"PayPal",collect:be});if(!x){G.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let K=x.email,I={...$?.accountPatch,...x};try{if(oe(!0),a?.(null),!we||!en(K))throw new Error("Missing sessionId or email for PayPal payment");await B?.(x);let P=H.createPaymentMethod,{error:nt,paymentMethod:St}=await P({type:"paypal"});if(nt){j(nt,"stripe_paypal_create_payment_method_failed",Y?.generation),G.paymentFailed({reason:"fail"});return}let ue=await oa(r,ve,we,Be??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:St?.id??null,intentKind:"payment"});if(ue.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=ue.clientSecret,it={return_url:window.location.href};if(St?.id&&(it.payment_method=St.id),typeof window<"u")try{localStorage.setItem(Co,JSON.stringify({clientSecret:ct,sessionId:we,nonce:Be,accountPatch:I}))}catch{}let{error:rt,paymentIntent:je}=await H.confirmPayment({clientSecret:ct,confirmParams:it,redirect:"if_required"});if(rt){if(typeof window<"u")try{localStorage.removeItem(Co)}catch{}if(go(rt)){let U=rt.message??"Your payment was declined.";a?.(U),S?.(jt("paypal",U,{code:tr(rt),declineCode:$r(rt)})),await aa({billingApiUrl:r,sessionId:we,nonce:Be,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:tr(rt)??"provider_declined"}})}else j(rt,"stripe_paypal_confirm_failed",Y?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Co)}catch{}let y=typeof je?.payment_method=="string"?je.payment_method:je?.payment_method?.id;o({id:y??je?.id,type:"card",threeDSecureActionResultTokenId:je?.id,isPaypal:!0},{accountPatch:I,sessionId:we,nonce:Be});return}catch(P){j(P,"stripe_paypal_failed",Y?.generation)}finally{oe(!1)}},[H,C,e,t,n,m,be,B,r,ve,o,a,S,g,j,te,Fe,ae,ee]);return Ie(fr,{children:[l(As,{state:fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:u,children:Ie("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[L&&l("button",{ref:Ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Je,style:_s,children:"Try PayPal again"}),He&&l(Ir,{identity:He.identity,methodLabel:He.methodLabel,onComplete:Rt,onCancel:()=>Rt(null)},He.id),l("div",{style:{display:He?"none":void 0},children:l(Is,{onReady:G=>Q(Ts(G,["paypal"])),onLoadError:()=>{Q("load_error"),Va(Kt(w),"paypal","paypal")},onClick:We,onConfirm:Se,onCancel:()=>{let G=Ue.current.get(ee);Ue.current.delete(ee),Kt(w)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(G?.generation),de(!1),et.current=!0,ie()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Ce,emailRequired:Ce,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),ce&&l(Yn,{status:"processing"})]})}function ws({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:S,onDecline:b,onTechnicalFailure:g,runBeforeButtonClick:m,billingName:B,onBuyerIdentityReady:D,onLoadStateChange:u,placeholderBorderRadius:w}){let ve=ur(),{emitInstrument:H}=Yr(In),C=Ka(),fe=ja(),[Q,ce]=ye("loading");ht(()=>{u?.(Q)},[Q,u]);let[oe,Ce]=ye(!1),He=!en(n?.trim())||!B?.trim(),{request:be,collect:Rt,finish:De}=qr(),Te=Ee(null),Ae=Ee(null),[ee,J]=ye(0),[L,de]=ye(!1),[et,Ue]=ye("google_pay"),Ye=Ee(!1),te=Ee("google_pay"),T=Ee("google_pay"),ae=Ee(new Map),{startAttempt:Fe,finishAttempt:ie,invalidateAttempt:j,isAttemptInvalidated:_e,isAttemptCurrent:Je}=xs((x,K,I)=>{g?.(x,K,{...I,popupBlocked:I?.popupBlocked??dr(K)}),Ue(x),de(!0),J(P=>P+1)});ht(()=>{L&&Ae.current?.focus()},[L,ee]);let We=Pe(()=>{J(x=>x+1)},[]),Se=Pe((x,K,I,P)=>{j(P),g?.(x,K,{code:I,popupBlocked:dr(K)}),Ue(x),de(!0),We()},[j,g,We]),G=Pe(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);ht(()=>{Ye.current&&(Ye.current=!1,G())},[G,ee]);let Y=Pe(()=>{de(!1),s?.(null),G()},[G,s]),$=Pe(async x=>{if(!C||!fe)return;let K=ae.current.get(ee);if(K&&!Je(K.generation)){ae.current.delete(ee);return}if(!K&&_e()||K&&!ie(K.generation))return;K||ie();let I=x.expressPaymentType??K?.method??te.current,P=K??null;ae.current.delete(ee);let nt=vs(I);if(!P&&m){let y=await m(nt);if(!y.proceed){x.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}P={accountPatch:y.accountPatch,sessionId:y.sessionId,nonce:y.nonce}}let St=nt,ue=P?.sessionId??e,ct=P?.nonce??t,it=await Rs({event:x,prepared:P,email:n,billingName:B,methodLabel:qa(I),collect:Rt});if(!it){x.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let rt=it.email,je={...P?.accountPatch,...it};try{if(Ce(!0),s?.(null),!en(rt))throw new Error("Missing sessionId or email for wallet payment");await D?.(it);let{error:y}=await fe.submit();if(y){Se(I,y,"stripe_wallet_submit_failed",K?.generation);return}let{error:U,paymentMethod:Xe}=await C.createPaymentMethod({elements:fe});if(U||!Xe){Se(I,U??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",K?.generation);return}if(!ue)throw new Error("Missing sessionId or email for wallet payment");let dt=await oa(r,H,ue,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I??nt,paymentMethodId:Xe.id,intentKind:o});if(dt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Bt=dt.clientSecret,{error:Mt,intentId:W}=lc(Bt)?await C.confirmCardSetup(Bt,{payment_method:Xe.id}).then(Le=>({error:Le.error,intentId:Le.setupIntent?.id})):await C.confirmCardPayment(Bt,{payment_method:Xe.id}).then(Le=>({error:Le.error,intentId:Le.paymentIntent?.id}));if(Mt){if(go(Mt)){let Le=Mt.message??"Your payment was declined.";s?.(Le),b?.(jt(St,Le,{code:tr(Mt),declineCode:$r(Mt)})),await aa({billingApiUrl:r,sessionId:ue,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I??nt,providerDeclineReason:tr(Mt)??"provider_declined"}})}else Se(I,Mt,"stripe_wallet_confirm_failed",K?.generation);return}c({id:Xe.id,type:"card",threeDSecureActionResultTokenId:W},{accountPatch:je,sessionId:ue,nonce:ct})}catch(y){Se(I,y,"stripe_wallet_failed",K?.generation)}finally{Ce(!1)}},[C,fe,e,t,n,B,Rt,D,r,H,o,c,s,b,m,Se,ie,Je,_e,ee]),we=gt(()=>{let x=["applePay","googlePay","paypal","link","amazonPay","klarna"],K=new Set(["applePay","googlePay"]),I=new Set(a.map(gs)),P={};for(let nt of x)I.has(nt)?P[nt]=K.has(nt)?"always":"auto":P[nt]="never";return P},[a]),Be=gt(()=>a.map(gs),[a]);return Ie(fr,{children:[l(As,{state:Q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:w,children:Ie("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[L&&Ie("button",{ref:Ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Y,style:_s,children:["Try ",qa(et)," again"]}),be&&l(Ir,{identity:be.identity,methodLabel:be.methodLabel,onComplete:De,onCancel:()=>De(null)},be.id),l("div",{style:{display:be?"none":void 0},children:l(Is,{onReady:x=>{ce(Ts(x,Be))},onLoadError:x=>{ce("load_error"),Va(Kt(ve),"stripe","wallet")},onClick:async x=>{te.current=x.expressPaymentType,T.current=vs(x.expressPaymentType);let K=m?await m(T.current):{proceed:!0};if(!K.proceed){ae.current.delete(ee),x.reject();return}let I=Fe(x.expressPaymentType);ae.current.set(ee,{generation:I,method:x.expressPaymentType,accountPatch:K.accountPatch,sessionId:K.sessionId,nonce:K.nonce}),de(!1),S?.(T.current),x.resolve()},onConfirm:$,onCancel:()=>{let x=ae.current.get(ee);ae.current.delete(ee),Kt(ve)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),j(x?.generation),de(!1),Ye.current=!0,We()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:we,emailRequired:He,billingAddressRequired:He,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),oe&&l(Yn,{status:"processing"})]})}function xc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:S,textColor:b,borderRadius:g,fontFamily:m}){let B=yc(e,t),D=ps[e],[u,w]=ye(!1),ve=B?.backgroundColor??s??"#ffffff",H=B?.borderColor??S??"#d1d5db",C=B?.textColor??b??"#262833";return l("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&c()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ra,padding:"0 1rem",backgroundColor:ve,color:C,border:`1px solid ${H}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:m,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?l("span",{style:{margin:"0 auto"},children:`Connecting to ${xr(e)}\u2026`}):Ie(fr,{children:[Ie("span",{style:{display:"inline-flex",alignItems:"center",gap:ic(e)?8:0},children:[D&&!u?l("img",{src:D,alt:"","aria-hidden":"true",onError:()=>w(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):B?.logoSvg?l("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:B.logoSvg}}):null,l("span",{children:xr(e)})]}),a&&l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:C,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:l("path",{d:"M9 18l6-6-6-6"})})]})})}function $a({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:c,onTokenizedBody:s,onErrorChange:S,onDecline:b,onCancel:g,runBeforeButtonClick:m,onButtonClick:B,isProcessing:D,submitButtonColor:u,submitButtonBorderRadius:w,submitButtonStyle:ve,errorText:H}){let C=ur(),{emitInstrument:fe}=Yr(In),Q=Ka(),ce=ja(),[oe,Ce]=ye(!1),He=Ee(!1),[be,Rt]=ye(!1),[De,Te]=ye("loading"),[Ae,ee]=ye(""),[J,L]=ye(""),de=!en(r?.trim()),et=!o?.trim(),Ue=(!de||en(Ae.trim()))&&(!et||!!J.trim()),Ye=Pe(async()=>{if(!Q||!ce||D||He.current||!be)return;He.current=!0,Ce(!0);let te=m?await m("card"):{proceed:!0};if(!te.proceed){He.current=!1,Ce(!1);return}B?.("card");let T=te.sessionId??t,ae=te.nonce??n,Fe=kn(o?.trim()||J.trim()),ie={email:te.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:te.accountPatch?.firstName?.trim()||Fe.firstName,lastName:te.accountPatch?.lastName?.trim()||Fe.lastName},j=ie.email,_e={...te.accountPatch,...ie};try{if(S?.(null),!en(j)||!fo(ie))throw new Error("A valid email address and full name are required for payment.");await a?.(ie);let Je=await ce.submit();if(Je.error){S?.(Je.error.message??"Payment failed.");return}let We=await Q.createPaymentMethod({elements:ce,params:{billing_details:{email:j,name:[ie.firstName,ie.lastName].filter(Boolean).join(" ")}}});if(We.error||!We.paymentMethod){S?.(We.error?.message??"Failed to create payment method.");return}let Se=We.paymentMethod;if(!T||!j)throw new Error("Missing sessionId or email for payment.");let G=Se.type||e,Y=await oa(c,fe,T,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:G,paymentMethodId:null,intentKind:"payment"});if(Y.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let $=Y.clientSecret;if(typeof window<"u")try{localStorage.setItem(Gn,JSON.stringify({clientSecret:$,sessionId:T,nonce:ae,accountPatch:_e,paymentMethodId:Se.id,paymentMethodType:Se.type??e,gateway:"stripe"}))}catch{}let{error:we,paymentIntent:Be}=await Q.confirmPayment({clientSecret:$,confirmParams:{return_url:window.location.href,payment_method:Se.id},redirect:"if_required"});if(we){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let I=we.message??"Payment failed.";S?.(I),b?.(jt("card",I,{code:we.code})),await aa({billingApiUrl:c,sessionId:T,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:we.code??"provider_declined"}});return}let x=Be?.status;if(!jo(x)){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let I=x==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(I),b?.(jt("card",I,{code:x??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let K=typeof Be?.payment_method=="string"?Be.payment_method:Be?.payment_method?.id;s({id:K??Se.id,type:"card",threeDSecureActionResultTokenId:Be?.id,gateway:"stripe",paymentMethodType:Se.type??e},{accountPatch:_e,sessionId:T,nonce:ae})}catch(Je){S?.(Je instanceof Error?Je.message:"Payment failed. Please try again.")}finally{He.current=!1,Ce(!1)}},[Q,ce,D,be,m,B,t,n,r,o,Ae,J,a,c,fe,e,s,S,b]);return Ie("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(de||et)&&Ie("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:[de&&Ie("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",l("input",{type:"email",autoComplete:"email",required:!0,value:Ae,onChange:te=>ee(te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),et&&Ie("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",l("input",{type:"text",autoComplete:"name",required:!0,value:J,onChange:te=>L(te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})]}),l(gc,{onReady:()=>Te("ready"),onLoadError:()=>{Te("load_error"),Va(Kt(C),"stripe","apm")},onChange:te=>{Rt(!!te.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...en(r?.trim())?{email:r?.trim()}:{}}}}}),l("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ye()},disabled:!be||!Ue||oe||D||De!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:w,fontSize:"1rem",fontWeight:600,cursor:!be||!Ue||oe||D||De!=="ready"?"not-allowed":"pointer",opacity:!be||!Ue||oe||D||De!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ve??{}},children:oe?"Processing\u2026":`Pay with ${xr(e)}`}),H&&l(Kr,{margin:"0.75rem 0 0",children:H})]})}function ks({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:c,stripeInstance:s,paymentElementBaseOptions:S,onTokenizedBody:b,onErrorChange:g,onButtonClick:m,onDecline:B,runBeforeButtonClick:D,onLoadStateChange:u,isProcessing:w=!1,submitButtonColor:ve="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:C,buttonAppearance:fe,themeId:Q,onExpandApm:ce,expandedApmMethod:oe}){let{emitInstrument:Ce}=Yr(In),[He,be]=ye(null),[Rt,De]=ye(null),Te=Ee(!1),{request:Ae,collect:ee,finish:J}=qr();ht(()=>{c.length>0&&s?u?.("ready"):s||u?.("loading")},[c.length,s,u]);let L=Pe(async T=>{if(!s||Te.current||w)return;Te.current=!0,De(T);let ae=D?await D("card"):{proceed:!0};if(!ae.proceed){Te.current=!1,De(null);return}m?.("card");let Fe=ae.sessionId??e,ie=ae.nonce??t,j=kn([ae.accountPatch?.firstName,ae.accountPatch?.lastName].filter(Boolean).join(" ")||r),_e={email:ae.accountPatch?.email?.trim()||n?.trim(),firstName:ae.accountPatch?.firstName?.trim()||j.firstName,lastName:ae.accountPatch?.lastName?.trim()||j.lastName};if(!en(_e.email)||!fo(_e)){De(null);let Se=await ee(xr(T),_e);if(!Se){Te.current=!1;return}_e=Se,De(T)}let Je=_e.email,We={...ae.accountPatch,..._e};try{if(g?.(null),!Fe||!en(Je)||!fo(_e))throw new Error("Missing sessionId or email for payment.");await o?.(_e);let Se=await oa(a,Ce,Fe,ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(Se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let G=Se.clientSecret;if(typeof window<"u")try{localStorage.setItem(Gn,JSON.stringify({clientSecret:G,sessionId:Fe,nonce:ie,accountPatch:We,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:$}=await s.confirmPayment({clientSecret:G,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[_e.firstName,_e.lastName].filter(Boolean).join(" "),...Je?{email:Je}:{}}}},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let x=Y.message??"Payment failed.";g?.(x),B?.(jt("card",x,{code:Y.code})),await aa({billingApiUrl:a,sessionId:Fe,nonce:ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:Y.code??"provider_declined"}});return}let we=$?.status;if(!jo(we)){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let x=we==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(x),B?.(jt("card",x,{code:we??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let Be=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;b({id:Be??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:We,sessionId:Fe,nonce:ie})}catch(Se){g?.(Se instanceof Error?Se.message:"Payment failed. Please try again.")}finally{Te.current=!1,De(null)}},[s,w,D,m,e,t,n,ee,a,Ce,r,o,b,g,B]),[de,et]=ye(null),Ue=ce?oe??null:de,Ye=Pe(T=>{Te.current||w||Ue&&Ue!==T||(fs(T)?ce?ce(T):et(T):L(T))},[Ue,w,L,ce]),te=gt(()=>de?{...S,paymentMethodTypes:[de]}:null,[de,S]);return l("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ae?l(Ir,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:J,onCancel:()=>J(null)},Ae.id):c.map(T=>{let ae=oe===T,Fe=Rt===T,ie=Rt!==null&&Rt!==T||oe!=null&&oe!==T;return Ie(hc.Fragment,{children:[l(xc,{method:T,themeId:Q,submitting:Fe,disabled:ie,highlighted:ae,hasNextStep:fs(T),onClick:()=>Ye(T),backgroundColor:fe?.backgroundColor,borderColor:fe?.borderColor,textColor:fe?.textColor,borderRadius:fe?.borderRadius,fontFamily:fe?.fontFamily}),!ce&&de===T&&te&&s&&l(_r,{stripe:s,options:te,children:l($a,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:b,onErrorChange:g,onDecline:B,onCancel:()=>et(null),runBeforeButtonClick:D,onButtonClick:m,isProcessing:w,submitButtonColor:ve,submitButtonBorderRadius:H,submitButtonStyle:C})},T)]},T)})})}function Tc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:c,onDecline:s,onTokenizedBody:S,firstName:b,lastName:g,chv:m,className:B,isProcessing:D,error:u,onErrorChange:w,showPayPal:ve=!0,showStripe:H=!0,enabledPaymentMethods:C,enabledPaymentMethodCountries:fe,showApplePay:Q=!0,showGooglePay:ce=!0,layout:oe="default",theme:Ce,buttonsTheme:He,buttonsStyles:be,appearance:Rt,cardButtonContent:De,cardBackButtonContent:Te,cardTitleContent:Ae,showSecurityFooter:ee,onButtonClick:J,onBeforeButtonClick:L,onBuyerIdentityReady:de,enableAVS:et,cardFieldOrder:Ue,cardPreFormSlot:Ye,avsLayout:te="row",country:T,zip:ae,addressLine1:Fe,addressLine2:ie,city:j,state:_e,onCountryChange:Je,onZipChange:We,avsCheck:Se,checkoutType:G,checkoutLayout:Y,totalAmount:$=0,currency:we="usd",initialCardOpen:Be=!1,directPaypal:x,isSubscription:K=!1,session:I,dataAttachmentPending:P=!1,dataAttachmentRequiresIdentity:nt=!1,debug:St=!1}){let ue=ur(),ct=_a(),it=Yr(Ln),{emitInstrument:rt}=Yr(In),je=P||it.claimPending===!0,y=nt||it.claimRequiresIdentity===!0,U=je&&!y,Xe=Ji(),[dt,Bt]=ye(!1),[Mt,W]=ye(null),[Le,Jt]=ye(T??"US"),[wt,zt]=ye(ae??""),[Rn,_n]=ye(Fe??""),[Zn,Xt]=ye(ie??""),[cn,dn]=ye(j??""),[Ft,vn]=ye(_e??""),[bt,ir]=ye(""),[Yt,sr]=ye(""),[Nt,zn]=ye({}),ot=Ee(ae??""),_t=Ee(T??"US"),xt=Ee(Fe??""),tn=Ee(ie??""),un=Ee(j??""),pn=Ee(_e??""),Un=Ee(""),qn=Ee(""),Ut=Ee({});ht(()=>{let i=(R,N,he,z,Re)=>{if(Ut.current[R])return;let Ne=N?.trim();!Ne||Ne===he.current||(he.current=Ne,z(Ne),Re?.(Ne))};i("country",T,_t,Jt,Je),i("zip",ae,ot,zt,We),i("addressLine1",Fe,xt,_n),i("addressLine2",ie,tn,Xt),i("city",j,un,dn),i("state",_e,pn,vn)},[T,ae,Fe,ie,j,_e,Je,We]);let X=gt(()=>pc(et),[et]),Pn=X!==null,xn=gt(()=>La(I),[I]),Qn=!!I?.vault?.html,br=!!I?.gateways?.pcivault,Tn=!!(I?.gateways?.stripe?.enabledPaymentMethods??C)?.includes("card"),mn=Qn||Tn||br,Me=!!(H&&mn&&ue&&e),[Zt,Dt]=ye(()=>oe!=="buttons"||Be?e??null:null),[$n,v]=ye(0),ut=oe!=="buttons"||Be||!!e&&Zt===e,qe=gt(()=>!ue||!Me||!e||!ut?null:ue.cardCapture({sessionId:e,captureMethod:I?.captureMethod}),[ue,Me,e,ut,I?.captureMethod]),yn=gt(()=>{let i=Le,R=X?ze(X.postal_code,i):!1;return Ec(i,wt,R)},[X,Le,wt]),{avsInvalid:Ze,invalidAvsFields:qt}=gt(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Me||!X)return{avsInvalid:!1,invalidAvsFields:i};let R=Le,N=(Re,Ne)=>ze(Re,R)&&!Ne.trim(),he={line1:N(X.address_line_1,Rn),city:N(X.city,cn),state:N(X.state,Ft),zip:yn.empty||yn.malformed};return{avsInvalid:he.line1||he.city||he.state||he.zip,invalidAvsFields:he}},[Me,X,Le,Rn,cn,Ft,yn]),[lr,jn]=ye(!1),[Cn,Lt]=ye(!1),[fn,gn]=ye(()=>Oa(I?.vault)),[xe,kt]=ye(Be&&mn?"card":"buttons"),[Tt,An]=ye(null),hn=xe==="expanding"||xe==="card",Bn=I?.gateways?.stripe?"stripe":void 0,Mn=Pe(()=>{rt?.({class:"card_surface",provider:Bn})},[Bn,rt]),$t=280,nn=Ee(null),an=Pe(i=>{nn.current&&clearTimeout(nn.current),nn.current=setTimeout(()=>{nn.current=null,i()},$t)},[$t]);ht(()=>()=>{nn.current&&clearTimeout(nn.current)},[]);let er=Pe(()=>{Mn(),Dt(e??null),v(i=>i+1),kt("expanding"),an(()=>kt("card"))},[an,Mn,e]),Ar=Pe(()=>{kt("collapsing"),an(()=>kt("buttons"))},[an]),Fn=Pe(i=>{An(i),kt("apm-expanding"),an(()=>kt("apm-form"))},[an]),Kn=Pe(()=>{kt("apm-collapsing"),an(()=>{kt("buttons"),An(null)})},[an]);ht(()=>{oe==="buttons"&&Be&&mn&&(Dt(e??null),kt("card"))},[oe,Be,mn,e]);let[Qt,at]=ye(null),Gt=Ee(!1),_=Ee(null),E=Ee("idle"),[V,Z]=ye(null),$e=Ee(V);ht(()=>{$e.current=V},[V]);let ne=n||Xe,M=u??Mt,h=gt(()=>fc(Ce),[Ce]),f=gt(()=>{let i=h?.buttonsLayout??mc(He);return be?{...i,...be,cardButton:{...i.cardButton,...be.cardButton},cardFormContainer:{...i.cardFormContainer,...be.cardFormContainer},backButton:{...i.backButton,...be.backButton},backButtonIcon:{...i.backButtonIcon,...be.backButtonIcon},submitButton:{...i.submitButton,...be.submitButton},title:{...i.title,...be.title}}:i},[h,He,be]),O=Rt??h?.appearance,pt=gt(()=>zi({appearance:O,buttonsStyles:f,layout:oe}),[O,f,oe]),vt=it.inlineSessionPatchProcessing??!1,d=(D??dt)||vt,p=ne.replace(/\/+$/,""),k=gt(()=>Ia({userId:o,email:r,firstName:b,lastName:g,country:T,zip:ae},Nt),[o,r,b,g,T,ae,Nt]),ke=[k.firstName,k.lastName].filter(i=>!!i?.trim()).join(" "),q=!en(k.email?.trim()),F=!ke.trim(),Ge=Ee(null),Qe=Ee(null);Me&&(Ge.current===null&&(Ge.current=q),Qe.current===null&&(Qe.current=F));let se=Me&&(Ge.current??q),pe=Me&&(Qe.current??F),A=se||pe,le=gt(()=>Rc(bt,se),[bt,se]),st=le.empty||le.malformed,Ot=pe&&!Yt.trim(),ge=gt(()=>ue?ue.getRawProvider():null,[ue]),bn=gt(()=>ct?ct.getRawProvider():null,[ct]),Qr=$||100,_o=gt(()=>O?ec(O):null,[O]),xo=_o?{appearance:_o}:null,li=gt(()=>{let i=_o??{},R=i.rules??{};return{...i,rules:{...R,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...R[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...R[".AccordionItemContents"]??{}}}}},[_o]),ci=gt(()=>{let i=Hi($);return{...i,currency:we.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...xo}},[$,we,xo]),di=gt(()=>({mode:"payment",amount:Qr,currency:we.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...xo}),[Qr,we,xo]),me=Pe(i=>{W(i),w?.(i)},[w]),da=Ee(""),[ui,$s]=ye(!1),To=Pe(()=>{$s(!0)},[]);ht(()=>{if(!Me||!A||!de||!ui||st||Ot||da.current)return;let i=kn(qn.current),R={email:en(k.email?.trim())?k.email?.trim():Un.current.trim(),firstName:k.firstName?.trim()||i.firstName,lastName:k.lastName?.trim()||i.lastName};da.current=JSON.stringify(R),zn(N=>({...N,...R})),Promise.resolve(de(R)).catch(N=>{da.current="",me(N instanceof Error?N.message:"Failed to attach buyer details.")})},[Me,A,de,ui,st,Ot,k.email,k.firstName,k.lastName,me]),ht(()=>{!Me||!qe||qe.setCardFieldOrder?.(Ue??null,X==null&&!A)},[Me,qe,Ue,X,A]),ht(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&me(null)},[xe,me]);let Nn=Pe((i,R,N)=>{s?.(jt(i,R,N))},[s]),Br=Pe((i,R,N)=>{let he=N?.popupBlocked??dr(R),z=kc(i,he),Re=Er(N?.code)??tr(R)??"external_payment_method_failed",Ne=new On(z,"api_error",{code:"external_payment_method_failed",param:i});at(null),oe==="buttons"&&(kt("buttons"),An(null)),me(z),c?.(Ne),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:he})},[oe,c,me]);ht(()=>{if(!Me||!e){gn(null);return}let i=Oa(I?.vault);if(i){gn(i);return}if(!ut){gn(null);return}gn(null);let R=!0;return new So(p).getVaultCapture(e,t).then(N=>{if(!R)return;let he=Oa(N);he?gn(he):me("Failed to load the secure card form.")}).catch(N=>{R&&me(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{R=!1}},[Me,ut,$n,e,I?.vault?.html,I?.vault?.messageToken,I?.vault?.expectedOrigin,p,t,me]);let Vn=Ee({onComplete:a,onError:c,updateError:me,emitDecline:Nn,resolvedAccount:k,avsConfig:X,avsCheckProp:Se,sessionId:e,nonce:t,baseUrl:p,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt});Vn.current={onComplete:a,onError:c,updateError:me,emitDecline:Nn,resolvedAccount:k,avsConfig:X,avsCheckProp:Se,sessionId:e,nonce:t,baseUrl:p,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt};let ua=Ee(!1),js=Pe(()=>{let{resolvedAccount:i,avsConfig:R,avsCheckProp:N}=Vn.current,he=i.email?.trim(),z=en(he)?he:Un.current.trim();if(!en(z))return null;let Re=kn(qn.current),Ne=i.firstName?.trim()||Re.firstName,It=i.lastName?.trim()||Re.lastName;if(!Ne&&!It)return null;let Ct=_t.current||i.country||"US",mt=R?ze(R.state,Ct):!1,yt=R?ze(R.address_line_1,Ct):!1,Ke=R?ze(R.postal_code,Ct):!1,rn=R?ze(R.city,Ct):!1,Oe=R?ze(R.address_line_2,Ct):!1,ln=yt&&!mt&&Ke?ms(Ct,(ot.current??"").trim()):null,on=mt?pn.current:ln;return{accountData:{userId:i.userId??"",email:z,firstName:Ne??"",lastName:It??"",...Ke&&ot.current?{zip:ot.current}:{},...rn&&un.current?{city:un.current}:{},...on?{state:on}:{},...yt&&xt.current?{addressLine1:xt.current}:{},...Oe&&tn.current?{addressLine2:tn.current}:{},country:Ct},...N!==void 0?{avsCheck:N}:{},...R?{avsConfig:{country:ze(R.country,Ct),postal_code:Ke,address_line_1:yt,address_line_2:Oe,city:rn,state:mt}}:{}}},[]),pi=Ee(je);pi.current=je,ht(()=>{je||M!==bs||Vn.current.updateError(null)},[je,M]),ht(()=>{!Me||!qe||qe.setSubmitGate?.(Ze||je||st||Ot)},[Me,qe,Ze,je,st,Ot]),ht(()=>{if(!Me||!qe)return;ua.current=!1;let i=!1,R=qe.on("submitting",()=>{jn(!0),_.current&&clearTimeout(_.current),E.current="validation-window",_.current=setTimeout(()=>{_.current=null,E.current==="validation-window"&&(E.current="processing")},bc),at("processing");let{baseUrl:Ne,sessionId:It,nonce:Ct,updateError:mt,onError:yt}=Vn.current;if(!It||!Ct)return;let Ke=js();if(!Ke){mt("Enter a valid email address."),E.current="idle",at(null);return}new So(Ne).patchAccountSnapshot(It,Ct,Ke,{telemetryMode:"best_effort"}).catch(rn=>{if(!vc(rn))return;let Oe=rn instanceof Error?rn.message:"Please check your billing address and try again.";mt(Oe),E.current="idle",at(null),yt?.(rn instanceof On?rn:new On(Oe,"api_error"))})}),N=qe.on("complete",async Ne=>{if(Vr(Ne.sessionId??Vn.current.sessionId),E.current="terminal",at("success"),await new Promise(mt=>setTimeout(mt,1200)),ua.current)return;ua.current=!0;let It=Vn.current,Ct=La(It)||Ne.outcome==="authorized";Vn.current.onComplete?.(Ct?{status:"authorized",paymentIntentId:Ne.intentId,paymentId:Ne.paymentId??It.paymentId,sessionId:Ne.sessionId??It.sessionId,authorizationExpiresAt:Ne.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ne.intentId,checkoutMethod:"card"})}),he=qe.on("decline",async Ne=>{let{updateError:It,emitDecline:Ct}=Vn.current,mt=Ne.message??"Your payment was declined. Please try another card or contact your bank.";E.current="terminal",It(mt),at("error");let yt=Ne.failureOutcome??dc(Ne.declineReason)??"authorization_declined";Ct("card",mt,{code:yt,declineCode:yt}),await new Promise(Ke=>setTimeout(Ke,1500)),!i&&(E.current="idle",at(null))}),z=qe.on("error",async Ne=>{let{updateError:It,onError:Ct}=Vn.current,mt=Ne.message??"There was a problem processing your payment. Please try again.";E.current="terminal",It(mt),at("error"),Ct?.(new On(mt,"api_error",{code:Ne.failureOutcome??"capture_failed"})),await new Promise(yt=>setTimeout(yt,1500)),!i&&(E.current="idle",at(null))}),Re=qe.on("blocked",()=>{if(!pi.current){jn(!0);return}To(),Vn.current.updateError(bs)});return()=>{i=!0,_.current&&(clearTimeout(_.current),_.current=null),E.current="idle",R(),N(),he(),z(),Re()}},[Me,qe,To]);let Hn=!!x?.clientId,eo=Array.isArray(C),Ao=eo&&C.length>0,Ks=eo&&C.includes("paypal"),{expressMethods:Bo,paymentElementMethods:to}=gt(()=>uc(C,{excludePaypal:Hn}),[C,Hn]),mi=Hn||!!ct,Vs=gt(()=>mi?Bo.filter(i=>i!=="paypal"):Bo,[Bo,mi]),Hs=gt(()=>{let i=[];return Q&&i.push("apple_pay"),ce&&i.push("google_pay"),i},[Q,ce]),Mo=eo?Vs:Hs,Ys=H&&Mo.length>0,pa=Pn?Le:T,Fo=gt(()=>{let i=pa?.trim().toUpperCase();return i?fe?to.filter(R=>{let N=fe[R];return!N||N.length===0||N.includes(i)}):rc(to,pa):to},[to,pa,fe]),ma=gt(()=>({mode:"payment",amount:Qr,currency:we.toLowerCase(),paymentMethodCreation:"manual",appearance:li}),[Qr,we,li]),[yi,fi]=ye("loading"),[gi,hi]=ye("loading"),[bi,vi]=ye("loading"),[Gs,ya]=ye(!1),[Pi,fa]=ye("loading"),[No,Ws]=ye();ht(()=>{Ws(us())},[]);let Ci=ve&&(Hn||(eo?Ks:No===!1)),Si=H&&Ys,no=!U&&Ci&&Hn,wi=Pi==="retrying"||Pi==="exhausted",ro=!U&&Ci&&!!bn&&(!Hn||wi),oo=!U&&Si&&!!ge,ao=!U&&H&&Ao&&Fo.length>0&&!!ge,Js=no&&!wi?Gs:ro&&Cs(yi),Xs=oo&&Cs(gi),Zs=ao&&bi!=="load_error",ki=i=>i==="loading"||i==="ready",Ii=no||ro&&ki(yi)||oo&&ki(gi)||ao&&bi!=="load_error",Do=Ee(!1);ht(()=>{if(!Do.current){if(!H&&!ve){Do.current=!0;let i=new On("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(i),me(i.message)}else if(!H&&ve&&!Hn&&!bn){Do.current=!0;let i=new On("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(i),me(i.message)}else if(No!==void 0&&!U&&!mn&&!Ii){Do.current=!0;let i=new On("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(i),me(i.message)}}},[H,ve,Hn,bn,No,U,mn,Ii,c,me]);let Ei=Ee(!1);ht(()=>{if(Ei.current||!Ao)return;let i=[];Q!==!0&&i.push("showApplePay"),ce!==!0&&i.push("showGooglePay"),i.length!==0&&(Ei.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Ao,Q,ce]);let Ri=Pe((i,R)=>it.applyInlineSessionPatch?it.applyInlineSessionPatch(i).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let he=Ps(R,N);return me(he.message),c?.(he),{error:he,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[it.applyInlineSessionPatch,t,c,e,me]),Dn=Pe(async i=>{if(!L)return{proceed:!0};try{let R=await L({method:i,sessionId:e||void 0,createSession:it.inlineSessionDraft});if(R===!1)return{proceed:!1};if(R&&typeof R=="object"){R.account&&zn(he=>({...he??{},...R.account}));let N=await Ri(R,i);return N.error?{proceed:!1,accountPatch:R.account}:{proceed:!0,accountPatch:R.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(R){let N=Ps(i,R);return me(N.message),c?.(N),{proceed:!1}}},[Ri,it.inlineSessionDraft,L,c,e,me]),_i=Pe(async(i,R)=>{if(Gt.current)return;Gt.current=!0,Bt(!0),at("processing"),me(null);let N=R?.sessionId??e,he=R?.nonce??t,z=Ia(k,R?.accountPatch),Re=R?.completionPaymentMethodId??yo(i),Ne=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,It=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Ct=()=>{rt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:It})};try{let yt=await new So(p).processPayment(z.userId??"",{sessionId:N,nonce:he,tokenizedData:Ne,accountData:{userId:z.userId??"",email:z.email??"",firstName:z.firstName??"",lastName:z.lastName??"",...X?(()=>{let Oe=_t.current,ln=ze(X.state,Oe),on=ze(X.address_line_1,Oe),Wt=ze(X.postal_code,Oe),co=on&&!ln&&Wt?ms(Oe,(ot.current??"").trim()):null,uo=ln?pn.current:co;return{country:Oe,...Wt&&ot.current?{zip:ot.current}:{},...ze(X.city,Oe)&&un.current?{city:un.current}:{},...uo?{state:uo}:{},...on&&xt.current?{addressLine1:xt.current}:{},...ze(X.address_line_2,Oe)&&tn.current?{addressLine2:tn.current}:{}}})():{}},chv:m,avsCheck:Se??!1,checkoutType:G,checkoutLayout:Y,avsConfig:X?{country:ze(X.country,_t.current),postal_code:ze(X.postal_code,_t.current),address_line_1:ze(X.address_line_1,_t.current),address_line_2:ze(X.address_line_2,_t.current),city:ze(X.city,_t.current),state:ze(X.state,_t.current)}:void 0});if(yt.ok){let Oe=yt.status===204?null:await yt.json().catch(()=>null),ln=La(I)||Oe?.status==="authorized";Vr(N),at("success"),Z(null),await new Promise(on=>setTimeout(on,1200)),a?.(ln?{status:"authorized",...typeof Oe?.paymentId=="string"?{paymentId:Oe.paymentId}:I?.paymentId?{paymentId:I.paymentId}:{},sessionId:typeof Oe?.sessionId=="string"?Oe.sessionId:N,...typeof Oe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Oe.authorizationExpiresAt}:I?.authorizationExpiresAt?{authorizationExpiresAt:I.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Ke=await yt.json().catch(()=>null);if(Ke?.type==="paypal_redirect_required"){let Oe=Ke.threeDSecureToken,ln=Ke.paymentMethodId||i.id||"";if(!ue||!Oe){at("error"),me("PayPal authorization required but no token provided.");return}try{let on=ct?.getRawProvider();if(!on){me("PayPal is not available.");return}let Wt={return_url:window.location.href};ln&&(Wt.payment_method=ln);let{error:co}=await on.confirmPayment({clientSecret:Oe,confirmParams:Wt,redirect:"if_required"});if(co){at("error");let uo=co.message??"PayPal payment failed.";me(uo),Nn("paypal",uo,{code:co.code})}}catch(on){at("error"),me(on instanceof Error?on.message:"PayPal authorization failed.")}return}if(Ke?.type==="paypal_direct_required"){let Oe=Ke.orderId;if(!Oe){at("error"),me("PayPal retry required but no order id provided.");return}let ln=$e.current?.attempts??0;if(ln>=2){at("error"),me("PayPal payment could not be completed after multiple attempts."),Nn("paypal","paypal_direct_required retry limit exceeded");return}ya(!1),fa("loading"),Z({orderId:Oe,attempts:ln+1}),at(null);return}nc(yt.status,Ke)||Ct(),at("error");let rn=Ke?.message??"Payment failed. Please try again.";me(rn),Nn(i.isPaypal?"paypal":"card",rn,{code:Ke?.code??Ke?.gatewayErrorCode,declineCode:Ke?.declineCode??Ke?.gatewayDeclineReason}),await new Promise(Oe=>setTimeout(Oe,1500))}catch(mt){Es(mt)||Ct(),at("error"),me(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(yt=>setTimeout(yt,1500))}finally{Bt(!1),at(null),Gt.current=!1}},[p,e,t,k,ke,m,ue,ct,I,a,c,me,Nn,rt]),Sn=Pe((i,R)=>{S?S(i):_i(i,R)},[S,_i]),xi=Ee(!1);ht(()=>{if(typeof window>"u"||xi.current)return;let i=new URLSearchParams(window.location.search),R=i.get("payment_intent"),N=i.get("payment_intent_client_secret"),he=i.get("redirect_status");if(!R||!N)return;let z=yt=>{let Ke=localStorage.getItem(yt);if(!Ke)return null;try{return JSON.parse(Ke)}catch{return localStorage.removeItem(yt),null}},Re=z(Gn)??z(hs),Ne;if(Re?.clientSecret){if(Re.clientSecret!==N)return;Ne={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;xi.current=!0,localStorage.removeItem(Gn),localStorage.removeItem(hs);let It=new URL(window.location.href);It.searchParams.delete("payment_intent"),It.searchParams.delete("payment_intent_client_secret"),It.searchParams.delete("redirect_status"),window.history.replaceState({},"",It.toString());let Ct=Re?.paymentMethodType??Re?.tokenType??"card",mt="card";(async()=>{let yt=ue?.getRawProvider();if(!yt){let Wt="Payment is not available \u2014 please refresh and try again.";me(Wt),Nn(mt,Wt);return}if(he==="failed"){let Wt="Payment was declined. Please try again.";me(Wt),Nn(mt,Wt);return}let{paymentIntent:Ke,error:rn}=await yt.retrievePaymentIntent(N);if(rn){let Wt=rn.message??"Failed to retrieve payment status.";me(Wt),Nn(mt,Wt,{code:rn.code});return}let Oe=Ke?.status,ln=jo(Oe);if(!Ke||!ln){let Wt=Oe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(Wt),Nn(mt,Wt,{code:Oe??"missing_payment_intent"});return}let on=typeof Ke.payment_method=="string"?Ke.payment_method:Ke.payment_method?.id;Sn({id:on??Re?.paymentMethodId??Re?.tokenId??Ke.id,type:"card",threeDSecureActionResultTokenId:Ke.id,gateway:Re?.gateway??"stripe",paymentMethodType:Ct},Ne)})()},[e,Sn,ue,me,Nn]);let ga=Pe(i=>{i.preventDefault()},[]);if(!(ue!==null))return l("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let io=oe==="buttons",sn=O?.variables,Qs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ha=sn?.colorBackground,el=ha&&!Qs.has(ha)?ha:void 0,vr=f.cardInputBorder??(io?"#e5e7eb":"#A4A4FF"),ba=sn?.colorDanger??"#dc2626",Pr=i=>lr&&i?ba:vr,Lo=(yn.malformed||yn.empty)&&(Cn||lr),tl=Lo?ba:Pr(qt.zip),va=f.cardFormContainer?.backgroundColor??el??(io?"white":"#EDEDFF"),Cr=f.cardInputBackground??sn?.colorBackground??"white",Pa=Nr(Te),Ti=Nr(Ae),Mr=f.nameInput,Ai=f.cardInputFontSize??_c(Mr?.fontSize)??sn?.fontSizeBase??"16px",Bi=typeof Mr?.fontFamily=="string"?Mr.fontFamily:sn?.fontFamily??"Poppins, sans-serif",Mi=Oi(Mr?.fontWeight)??400,nl=f.cardInputColor??(typeof Mr?.color=="string"?Mr.color:void 0)??sn?.colorText??"#262833",rl=f.cardInputPlaceholderColor??"#9ca3af",Pt=sn?.borderRadius??"8px",Sr=sn?.borderRadius??f.cardButton?.borderRadius??Pt,wr=sn?.colorPrimary??"#4A49FF",ol=sn?.colorPrimaryHover??po(wr,.12),so=sn?.colorText??"#262833",Fr={fontSize:Ai,fontFamily:Bi,fontWeight:Mi,color:nl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},al={"--flopay-input-placeholder-color":rl,"--flopay-input-font-size":Ai,"--flopay-input-font-family":Bi,"--flopay-input-font-weight":String(Mi)},lo=f.cardFormContainer??{},Ca=lo.padding??(io?"0":"1rem"),Sa=lo.borderRadius??Pt,il=qe&&fn?l(wa,{capture:qe,html:fn.html,messageToken:fn.messageToken,expectedOrigin:fn.expectedOrigin,theme:pt,onReady:()=>{if(!A&&!X||typeof document>"u")return;let i=()=>{(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};i();let R=0,N=window.setInterval(()=>{R+=1;let he=document.activeElement;!!he&&he.tagName==="IFRAME"&&he.id==="flopay_vault_form_iframe"?(i(),window.clearInterval(N)):R>=50&&window.clearInterval(N)},100)},onError:i=>me(i),onValidation:i=>{let R=E.current;(R==="idle"||R==="validation-window")&&(me(i),i&&E.current==="validation-window"&&(_.current&&(clearTimeout(_.current),_.current=null),E.current="idle",at(null)))}}):l("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Fi=Ie("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Mn()},style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca,...al,display:"flex",flexDirection:"column"},children:[l("style",{children:`
|
|
26
26
|
.flopay-shared-input::placeholder {
|
|
27
27
|
color: var(--flopay-input-placeholder-color);
|
|
28
28
|
opacity: 1;
|
|
@@ -30,13 +30,13 @@ ${Mt.join(`
|
|
|
30
30
|
font-family: var(--flopay-input-font-family);
|
|
31
31
|
font-weight: var(--flopay-input-font-weight);
|
|
32
32
|
}
|
|
33
|
-
`}),io&&hn&&
|
|
34
|
-
`)}):null,Di=i=>St?!H||!ge?l("pre",{"data-testid":i,style:Oo,children:"FloPay/Stripe-debug - not enabled"}):l("pre",{"data-testid":i,style:Oo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${H}`,` currency=${we}`,` amountInCents=${Qr}`,` enabledPaymentMethods: ${JSON.stringify(
|
|
35
|
-
`)}):null,Li=xe==="apm-expanding"||xe==="apm-form"||xe==="apm-collapsing",zo=xe==="apm-expanding"?`flopay-card-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="apm-collapsing"?`flopay-card-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Uo=Tt?{...ma,paymentMethodTypes:[Tt]}:null;if(oe==="buttons"){let i=xe==="buttons"||xe==="expanding"||xe==="apm-expanding",R=xe==="expanding"||xe==="card"||xe==="collapsing",N=De===void 0?{boxSizing:"border-box",height:ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"},he=xe==="expanding"||xe==="apm-expanding"?`flopay-buttons-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:xe==="collapsing"||xe==="apm-collapsing"?`flopay-buttons-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,z=xe==="expanding"?`flopay-card-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="collapsing"?`flopay-card-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return ke("form",{onSubmit:ga,className:M,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:B,authorized:xn}),ke("div",{style:{display:"grid"},children:[ke("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!he?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!he?Sc:{},...he?{animation:he,pointerEvents:"none"}:{}},children:[Ni("flopay-direct-paypal-gate-debug"),Di("flopay-stripe-gate-debug"),no&&x&&ke(fr,{children:[V&&l("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),l(Jo,{sessionId:e,nonce:t,billingApiUrl:ne,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,clientId:x.clientId,environment:x.environment,currency:we.toUpperCase(),isSubscription:K,providerObjectType:x.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:pe,onDecline:s,onTechnicalFailure:Mr,onButtonClick:J,runBeforeButtonClick:Dn,isProcessing:d,onLoadStateChange:ya,onInitializationStateChange:fa,session:I??null,existingOrderId:V?.orderId,debug:St},V?.orderId??"fresh")]}),ro&&l(_r,{stripe:bn,options:di,children:l(Ss,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,isProcessing:d,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:fi,placeholderBorderRadius:Sr})}),oo?l(_r,{stripe:ge,options:ci,children:l(ws,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,intentKind:$>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:hi,placeholderBorderRadius:Sr})}):Si?l("div",{style:{height:ra,borderRadius:Sr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ao&&l(ks,{sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,paymentElementMethods:Fo,stripeInstance:ge,paymentElementBaseOptions:ma,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,runBeforeButtonClick:Dn,onLoadStateChange:vi,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,onExpandApm:Fn,expandedApmMethod:Tt,themeId:Ce,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Sr}}),Be&&l("button",{type:"button",onClick:async()=>{d||!(await Dn("card")).proceed||(J?.("card"),er())},disabled:d,style:{width:"100%",...N,...f.cardButton,...Ha({themeBundle:h,resolvedPrimaryColor:wr,resolvedBorderRadius:Pt,submitButtonStyle:f.submitButton,explicitPrimaryColor:sn?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:d?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:d?.6:1},onMouseEnter:Re=>{!d&&(h||sn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=ol)},onMouseLeave:Re=>{(h||sn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=wr)},onMouseDown:Re=>{Re.currentTarget.style.transform="scale(0.985)"},onMouseUp:Re=>{Re.currentTarget.style.transform="scale(1)"},children:l(Dr,{content:De})}),B&&xe==="buttons"&&l(Kr,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:B})]}),Be&&R&&l("div",{style:{gridArea:"1 / 1",...z?{animation:z}:{},...xe==="collapsing"?{pointerEvents:"none"}:{}},children:Fi}),H&&Li&&Tt&&Uo&&ge&&l("div",{style:{gridArea:"1 / 1",...zo?{animation:zo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ke("div",{style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca},children:[ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ke("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Kn,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:so,paddingRight:80,...f.title},children:`Pay with ${xr(Tt)}`})]}),l(_r,{stripe:ge,options:Uo,children:l($a,{method:Tt,sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,onDecline:s,onCancel:Kn,runBeforeButtonClick:Dn,onButtonClick:J,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,errorText:B})},Tt)]})})]})]})}return Li&&Tt&&Uo&&ge&&H?ke("form",{onSubmit:ga,className:M,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:B,authorized:xn}),l("div",{style:{...zo?{animation:zo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ke("div",{style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca},children:[ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ke("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Kn,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:so,paddingRight:80,...f.title},children:`Pay with ${xr(Tt)}`})]}),l(_r,{stripe:ge,options:Uo,children:l($a,{method:Tt,sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,onDecline:s,onCancel:Kn,runBeforeButtonClick:Dn,onButtonClick:J,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,errorText:B})},Tt)]})})]}):ke("form",{onSubmit:ga,className:M,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:B,authorized:xn}),ke("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ni("flopay-direct-paypal-gate-debug-default"),Di("flopay-stripe-gate-debug-default"),no&&x&&ke(fr,{children:[V&&l("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),l(Jo,{sessionId:e,nonce:t,billingApiUrl:ne,email:k.email,clientId:x.clientId,environment:x.environment,currency:we.toUpperCase(),isSubscription:K,providerObjectType:x.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:pe,onDecline:s,onTechnicalFailure:Mr,onButtonClick:J,runBeforeButtonClick:Dn,isProcessing:d,onLoadStateChange:ya,onInitializationStateChange:fa,session:I??null,existingOrderId:V?.orderId,debug:St},V?.orderId??"fresh")]}),ro&&l(_r,{stripe:bn,options:di,children:l(Ss,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,isProcessing:d,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:fi,placeholderBorderRadius:Sr})}),oo&&l(_r,{stripe:ge,options:ci,children:l(ws,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,intentKind:$>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:hi,placeholderBorderRadius:Sr})}),ao&&l(ks,{sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ne,paymentElementMethods:Fo,stripeInstance:ge,paymentElementBaseOptions:ma,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,runBeforeButtonClick:Dn,onLoadStateChange:vi,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,themeId:Ce,onExpandApm:Fn,expandedApmMethod:Tt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Sr}})]}),Be&&(Xs||Js||Zs)&&ke("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[l("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),l("span",{children:"or pay with card"}),l("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Be&&Fi]})}import{Fragment as Xn,jsx as re,jsxs as Vt}from"react/jsx-runtime";var Gr=44,oi="flopay_checkout_saved_payment_resume",ca=new Map,sa=new Map;function Fs(e,t){t.settled&&t.consumers===0&&ca.get(e)===t&&ca.delete(e)}function zc(e,t,n){let r=sa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};sa.set(e,a);let c=()=>{sa.get(e)===a&&sa.delete(e)};return o.then(c,c),o}function wo(e){return new Promise(t=>setTimeout(t,e))}function la(e,t,n){let r=Yo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Os,enabled:t!==!1});return r.beginCheckout(n),r}function ko(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Wa(e,t,n,r,o){let a=la(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),ko(a)}function Uc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function ni(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Ja(e){return!e||e.data.stripe?.publishableKey?!1:!!ni(e)?.clientId}function ar(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function qc(){if(!ar())return null;try{let e=window.sessionStorage.getItem(oi);return e?JSON.parse(e):null}catch{return null}}function Ns(e){if(ar())try{window.sessionStorage.setItem(oi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Xa(){if(ar())try{window.sessionStorage.removeItem(oi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ai=":idempotency-key";function zs(e,t){if(!ar())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Za(e,t,n,r){if(ar())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function ri(e,t){if(ar())try{zs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Us(e,t){if(!ar())return null;try{let n=window.sessionStorage.getItem(e+ai);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Qa(e,t,n){if(ar())try{window.sessionStorage.setItem(e+ai,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ei(e,t){if(ri(e,t),!!ar())try{Us(e,t)&&window.sessionStorage.removeItem(e+ai)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function $c(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Ds(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function jc(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function ti(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Io(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>ti(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ti(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ti(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Kc(e,t=!1){let n=Io(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function Vc(e,t){if(!e?.customer||!e.products)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=Lc(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Bc(t.items,t.subscriptions)).map(b=>({type:b.type,code:b.code??b.providerItemId??b.providerPlanId??"",quantity:b.quantity??1,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount??null,currency:(b.currency??o).toUpperCase()})).sort((b,g)=>`${b.code}:${b.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),c=e.products.map(b=>({type:b.type,code:b.code??"",quantity:b.quantity??1,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount??null,currency:(b.currency??e.currency).toUpperCase()})).sort((b,g)=>`${b.code}:${b.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(a.length!==c.length)return!1;for(let b=0;b<a.length;b+=1){let g=a[b],m=c[b];if(g.code!==m.code||g.type!==void 0&&g.type!==m.type||g.quantity!==m.quantity||g.totalAmount!==m.totalAmount||g.overrideAmount!==m.overrideAmount||g.currency!==m.currency)return!1}let s=[...t.couponCodes??[]].sort(),S=[...e.coupons??[]].sort();return s.length===S.length&&s.every((b,g)=>b===S[g])}function ii({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:c,loading:s,error:S,onComplete:b,onError:g,onInstrument:m,onDecline:M,onCountryChange:D,onZipChange:u,showPayPal:w=!0,showStripe:ve=!0,enabledPaymentMethods:H,showApplePay:P=!0,showGooglePay:fe=!0,debug:Q=!1,layout:ce,theme:oe,buttonsTheme:Ce,buttonsStyles:He,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De,showSecurityFooter:Te,onButtonClick:Ae,onBeforeButtonClick:ee,enableAVS:J,cardFieldOrder:L,cardPreFormSlot:me,avsLayout:et,className:Ue,initialErrorMessage:Ye=null,children:te,checkoutMode:T,confirmLabel:ae,renderConfirmButton:Fe,onSessionCompleted:ie}){let j=Nc(r),_e=En(()=>Ls(oe),[oe]),Je=a??_e?.appearance,We=n?"embedded_checkout":"standard_checkout",Se=te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",[G,Y]=Et(null),[$,we]=Et(null),Me=At(null),[x,K]=Et(null),I=At(null),[C,nt]=Et(null),St=En(()=>n?Io(n):"",[n]),de=n?`create:${St}`:`session:${e??""}`,ct=C?.gateways?.stripe?"stripe":C?.gateways?.paypal?"paypal":void 0,it=At(new Set),rt=At(de),je=At(de);Vo(()=>{je.current=de,rt.current!==de&&(rt.current=de,it.current.clear())},[de]);let y=Wn(_=>{if(je.current===de){if(xa.has(_.name)){if(it.current.has(_.name))return;it.current.add(_.name)}tt(()=>m?.(_))}},[de,m]),U=jr(y,de),Xe=At(!1),dt=Wn(_=>{if(Xe.current)return;let E=_.gateway||!ct?_:{..._,gateway:ct};y(E)},[y,ct]);Jn(()=>{U({class:"lifecycle",name:"checkout.mount"})},[U]);let[Mt,Bt]=Et(e??""),W=e??Mt,Le=n?"":W,[Wt,wt]=Et(!0),[Ot,Rn]=Et(null),[_n,Zn]=Et("full"),[Jt,cn]=Et(!1),[dn,Ft]=Et(Ye),[vn,bt]=Et(null),[ir,Ht]=Et(null),[sr,Nt]=Et(!1),[zn,ot]=Et(void 0),[_t,xt]=Et(""),[tn,un]=Et(!1),[pn,Un]=Et(!1),[qn,zt]=Et(!1),X=At(0),Pn=At(void 0),[xn,Qn]=Et("loading"),[br,Tr]=Et(0),Tn=At(!1),mn=At(!1),Be=At(!1),Xt=At(null),Dt=En(()=>({checkoutMode:T??_n,layout:te?"unknown":ce==="buttons"?"buttons":"embedded"}),[T,te,_n,ce]),$n=At(b);$n.current=b;let v=At(g);v.current=g;let ut=At(M);ut.current=M,Jn(()=>{jt($)?.setCheckoutContext(Dt),x&&x!==$&&jt(x)?.setCheckoutContext(Dt)},[$,x,Dt]);let qe=At(ie);qe.current=ie;let yn=Wn(_=>{Qn(_),!(_!=="exhausted"||Be.current)&&(Be.current=!0,v.current?.(new Kt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ze=Wn(()=>{Qn("retrying"),Tr(_=>_+1)},[]);Jn(()=>{Qn("loading"),Tr(0),Be.current=!1},[W]),Jn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Os,checkout_type:We,checkout_layout:Se,billing_api_url:j})},[Se,We,j]);let Ut=En(()=>n?Io(n,!0):"",[n]),lr=En(()=>_t===Ut?zn:void 0,[zn,_t,Ut]),jn=En(()=>n?ka(n,lr):void 0,[n,lr]),Cn=T??jn?.checkoutMode??"full",Zt=En(()=>jn?{...jn,checkoutMode:Cn}:void 0,[jn,Cn]);Jn(()=>{ot(void 0),xt(Ut),Pn.current=void 0,zt(!1)},[Ut]),Jn(()=>{Ft(Ye)},[Ye]);let fn=Wn((_,E,V)=>{tt(()=>{ut.current?.($t(_,E,V))})},[tt]),gn=Wn(async(_,E)=>{Ft(null),Ht(null),Nt(!1),bt("processing");let V=E?.sessionId??_.id,Z=_.gateways?.stripe?"stripe":_.gateways?.paypal?"paypal":void 0,$e=Me.current??I.current,ne=jt($e),B=$e?null:la(j,o,Dt),h={log:q=>{ne?ne.log(q):B?.log(q)},error:q=>{ne?ne.error(q):B?.error(q)},terminal:q=>{ne?ne.terminal(q):B?.terminal(q)},performance:q=>{ne?ne.performance(q):B?.performance(q)},now:()=>ne?.now()??B?.now()??0,elapsed:q=>ne?.elapsed(q)??Math.max(0,(B?.now()??q)-q)},f=h.now(),O=!!(E?.initialAutoProcessingError||E?.initialAutoProcessingPending),pt=!1,vt,d=()=>{pt||(pt=!0,O=!0,vt=h.now(),h.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},p=!1,k=()=>{p||(p=!0,h.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),h.performance({stage:"processing",durationMs:h.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved"}),vt!==void 0&&h.performance({stage:"recovery",durationMs:h.elapsed(vt),durationMode:"machine",paymentMethodCategory:"saved"}))};h.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Xe.current=!0;try{h.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Xe.current=!1}U({class:"lifecycle",name:"payment.processing.started",provider:Z}),O&&d();let Ee;try{let q=ls(E?.initialAutoProcessingError),F;if(q)d(),q.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&Ns({sessionId:V,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),F=await ea(q,{flopay:Me.current,paypalFlopay:I.current,attempt3DS:E?.attempt3DS,billingApiUrl:j,sessionId:V,session:_,telemetry:!1}),q.type==="paypal_redirect_required"&&Xa();else if(E?.initialAutoProcessingPending){let se=(await new ia(j,{telemetry:!1}).waitForCheckoutSessionCompletion(E.initialAutoProcessingPending.sessionId,{initialDelayMs:E.initialAutoProcessingPending.retryAfterMs})).data.session;if(!zr(se))throw $o(se);F=kr(se,V)}else{if(E?.initialAutoProcessingError)throw yr(E.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:E.initialAutoProcessingError.checkoutMethod});if(E?.fromCreateSession)return E?.fallbackToFull&&(Zn("full"),Ds("full")),!1;{let Ge=await Hr({billingApiUrl:j,sessionId:V,session:_,telemetry:!1});Ge.type==="success"?F=Ge.result:(d(),Ge.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&Ns({sessionId:V,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),F=await ea(Ge,{flopay:Me.current,paypalFlopay:I.current,attempt3DS:E?.attempt3DS,billingApiUrl:j,sessionId:V,session:_,telemetry:!1}),Ge.type==="paypal_redirect_required"&&Xa())}}V&&Vr(V),k(),O&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),h.terminal({outcome:F.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Nt(F.status==="authorized"),bt("success"),await wo(1200),Ee=()=>$n.current?.(F)}catch(q){let F=Rr(q),Ge=F.checkoutMethod??Po;Ft(F.message),Ht(F.message),Nt(!1),E?.fallbackToFull&&(h.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Zn("full"),Ds("full")),k();let Qe=F.statusCode!==void 0?Oc(F.statusCode,"unknown"):void 0,se=Qe==="4xx"?{requestCategory:"process_payment",statusClass:Qe}:{},ue=Qe===void 0||Qe==="4xx";if(ue&&(F.telemetryOutcome==="payment_declined"||!!(F.declineCode||F.code?.toLowerCase().includes("declin"))))h.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...se});else if(ue&&(F.telemetryOutcome==="validation_rejected"||F.type==="validation_error"))h.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...se});else{let st=Ms(q,O?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Lt=F.telemetryRequestCategory??"process_payment";Xe.current=!0;try{h.error({...st,...F.telemetryFailureCategory?{failureCategory:F.telemetryFailureCategory}:{},stage:O?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Lt})}finally{Xe.current=!1}U({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Lt,provider:Z})}return tt(()=>v.current?.(F)),fn(Ge,F,{code:F.code,declineCode:F.declineCode}),bt("error"),await Promise.allSettled([wo(1500),E?.ensureProvidersReady?E.ensureProvidersReady():Promise.resolve()]),O&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{k(),B&&ko(B),bt(null),Ht(null)}return tt(Ee),!0},[fn,U,tt,Rr,j,o,Dt]);Jn(()=>{if(typeof window>"u"||mn.current)return;let _=new URLSearchParams(window.location.search),E=_.get("payment_intent_client_secret");if(!E)return;let V=qc();V&&(mn.current=!0,(async()=>{let Z,$e=0;Ft(null),Ht(null),bt("processing"),cn(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new Kt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ne,paypalFlopay:B}=await na({publishableKey:V.publishableKey,paypalPublishableKey:V.paypalPublishableKey,billingApiUrl:j,locale:c,telemetry:o});Z=jt(B??ne),$e=Z?.now()??0,Z?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let h=(B??ne)?.getRawProvider();if(!h)throw Object.assign(new Kt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:f,error:O}=await h.retrievePaymentIntent(E);if(O)throw Object.assign(new Kt(O.message??"Failed to retrieve PayPal payment status.","api_error",{code:O.code}),{checkoutMethod:"paypal"});let pt=Vi(f?.status);if(!f||pt==="failed")throw Object.assign(new Kt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let vt=typeof f.payment_method=="string"?f.payment_method:f.payment_method?.id,d=pt;if(V.sessionId){let Ee=(await new ia(j,{telemetry:!1}).getUnifiedCheckoutSession(V.sessionId)).data.session;if(Ee&&Ee.status!=="complete"){let q=await Hr({billingApiUrl:j,sessionId:V.sessionId,session:Ee,telemetry:!1,tokenizedData:{id:vt??f.id,type:"card",threeDSecureActionResultTokenId:f.id,isPaypal:!0}});if(q.type!=="success")throw Object.assign(new Kt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});d=q.result.status}}V.sessionId&&Vr(V.sessionId),Z?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.performance({stage:"redirect_resume",durationMs:Z.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),bt("success"),await wo(1200),tt(()=>$n.current?.({status:d,paymentIntentId:f.id,paymentMethodId:vt,checkoutMethod:"paypal"}))}catch(ne){let B=Rr(ne),h=B.checkoutMethod??"paypal",f=!!(B.declineCode||B.code?.toLowerCase().includes("declin"));if(Z)Z.performance({stage:"redirect_resume",durationMs:Z.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),f?Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Z.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(f){let O=la(j,o,Dt);O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ko(O)}else Wa(j,o,Dt,"REDIRECT_RESUME_FAILED","redirect_resume");Ft(B.message),Ht(B.message),tt(()=>v.current?.(B)),fn(h,B,{code:B.code,declineCode:B.declineCode}),bt("error"),await wo(1500)}finally{Xa(),$c(),bt(null),Ht(null),cn(!1)}})())},[fn,tt,c,Rr,j,o]);let xe=At(null),kt=En(()=>Zt?Io(Zt):"",[Zt]),Tt=At(Zt);Tt.current=Zt,Jn(()=>{Bt(e??"")},[e]),Jn(()=>{Tn.current=!1,Ft(Ye),Ht(null),Nt(!1),bt(null)},[kt,Ye,e]);async function An(_,E,V){let Z=la(j,o,Dt),$e=new ia(j,{telemetry:!1}),ne=!1;try{let B=_.idempotencyKey!==void 0?Bs(_.idempotencyKey):void 0,h=zs(E,V),f=Us(E,V);h?.canonicalIdentity===V&&f&&f.canonicalIdentity===void 0&&(Qa(E,V,f.idempotencyKey),f={...f,canonicalIdentity:V});let O=B??(f?.canonicalIdentity===V?f.idempotencyKey:void 0),pt,vt=!1;Z.log({name:h?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let d=h?.sid??null,p=null,k,Ee,q=!1;if(d)try{p=await $e.getUnifiedCheckoutSession(d,h?.nonce),h&&h.canonicalIdentity===void 0&&(Vc(p.data.session,_)?(Za(E,V,d,h.nonce??p.data.session?.clientSecret),f&&f.canonicalIdentity===void 0&&(Qa(E,V,f.idempotencyKey),O??(O=f.idempotencyKey))):(ei(E,V),f=null,O=B,d=null,p=null));let F=p?.data.session?.status;if(d&&p&&F==="complete"){if(Fa(d))return{sid:d,result:p};ei(E,V),d=null,p=null,vt=!0}}catch{Z.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),h?.canonicalIdentity===void 0?(ei(E,V),O=B):ri(E,V),d=null}if(!d){!B&&(vt||!O)&&(O=Bs(),pt=O),O&&Qa(E,V,O);let F=Z.now(),Ge=0;Z.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Qe={..._,idempotencyKey:O,avsCheck:!!J,avsConfig:typeof J=="object"?J:void 0,checkoutType:"embedded_checkout",checkoutLayout:te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Qe,Ac,{configurable:!1,enumerable:!1,value:{onAttempt:A=>{Ge=Math.max(Ge,A)}}});let se=()=>{Z.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),Z.performance({stage:"session_create",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx"})},ue=A=>{let le=Ms(A,"CHECKOUT_SESSION_CREATE_FAILED","unknown");Z.performance({stage:"session_create",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:le.statusClass}),A instanceof Kt&&A.type==="validation_error"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):le.statusClass==="4xx"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(Z.error({...le,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),U({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Fc(Qe)){let A=await $e.createDetachedSession(Qe);A.claimed.catch(()=>{}),p=A.shell,d=A.sessionId,Ee=A.claim,q=!Qe.account.email?.trim(),k=A.claimed.then(le=>{let st=le.data.session?.id??A.sessionId;return st&&Za(E,V,st,le.data.session?.clientSecret??A.nonce),se(),le},le=>{throw ri(E,V),ue(le),le}).finally(()=>ko(Z)),k.catch(()=>{}),ne=!0,Z.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Z.performance({stage:"session_shell",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx",paymentMethodCategory:"card"})}else p=await $e.createAndFetchSession(Qe),se()}catch(A){throw ue(A),A}d=p.data.session?.id??d??"",d&&!k&&Za(E,V,d,p.data.session?.clientSecret)}return{sid:d??"",result:p,sdkGeneratedIdempotencyKey:pt,...k?{claimed:k}:{},...Ee?{claim:Ee}:{},...q?{claimRequiresIdentity:!0}:{}}}finally{ne||ko(Z)}}let hn=Wn(async(_,E)=>{let V=Tt.current;if(!V)throw new Kt("createSession is required to bootstrap checkout.","validation_error");let Z=ka(V,_),$e=Io(Z),ne=Kc(Z),B=ca.get($e);if(!B){let O={canonicalIdentity:$e,promise:An(Z,ne,$e),consumers:0,settled:!1};B=O,ca.set($e,O);let pt=()=>{O.settled=!0,Fs($e,O)};O.promise.then(pt,pt)}B.consumers+=1;let h=!1,f=()=>{h||(h=!0,B.consumers-=1,Fs($e,B))};E?.(f);try{let O=await B.promise;xe.current=$e,_&&(xt(Ut),ot(Qe=>$i(Qe,_)));let{sid:pt,result:vt,claimed:d,claim:p,claimRequiresIdentity:k}=O;if(Pn.current=p,zt(k===!0),Y(vt),vt.data.session&&nt(vt.data.session),pt&&Bt(pt),d){X.current+=1;let Qe=X.current;Un(!0),d.then(se=>{X.current===Qe&&(Y(se),se.data.session&&nt(se.data.session),Un(!1),zt(!1))},se=>{X.current===Qe&&(Un(!1),zt(!1),Rn(se instanceof Kt?se:new Kt(se instanceof Error?se.message:"Failed to create session","api_error")))})}else X.current+=1,Un(!1),zt(!1);let{publishableKey:Ee,paypalPublishableKey:q}=ta(vt),{flopay:F,paypalFlopay:Ge}=await na({publishableKey:Ee,paypalPublishableKey:q,billingApiUrl:j,locale:c,telemetry:o});return Me.current=F,we(F),I.current=Ge,K(Ge),wt(!1),O}catch(O){throw xe.current===$e&&(xe.current=null),O}finally{E||f()}},[Ut,c,j,o,Dt]),Mn=At(gn);Mn.current=gn;let Bn=At(hn);Bn.current=hn;let qt=Wn(async _=>{if(!jc(_)||tn)return{sessionId:Mt,session:C};un(!0);try{let E=await hn(_);return{sessionId:E.sid,session:E.result.data.session??null}}finally{un(!1)}},[hn,tn,Mt,C]),on=Wn(async _=>{let E=Pn.current;E&&await E(_)},[]);Jn(()=>{let _=!1,E;if(Rn(null),kt){let $e=Tt.current;return Zn(Cn),wt(!1),xe.current===kt?()=>{_=!0}:(nt(ji($e,T)),(async()=>{let ne=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=Cn==="auto"&&!Tn.current&&!ne;B&&(Ft(null),Ht(null),bt("processing"));try{let h=await Bn.current(void 0,vt=>{E=vt}),f=h.result.data.session??null;Xt.current=ta(h.result);let O=Ja(h.result),pt=Fa(h.sid||f?.id);if(!_&&B&&f&&!O&&!pt){Tn.current=!0,await zc(kt,h.sdkGeneratedIdempotencyKey,()=>Mn.current(f,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:h.result.autoProcessingError,initialAutoProcessingPending:h.result.autoProcessingPending,autoProcessingAttempted:h.result.autoProcessingAttempted,sessionId:h.sid||f.id}));return}!_&&B&&((O||pt)&&(Tn.current=!0),bt(null),Ht(null))}catch(h){if(_)return;let f=h instanceof Kt||typeof h=="object"&&h!==null&&"code"in h?h.code:void 0;if(B&&f==="session_auto_completed"){Tn.current=!0,bt("success"),await wo(1200),_||(tt(()=>{$n.current?.({status:"succeeded"})}),bt(null),Ht(null));return}B&&(bt(null),Ht(null));let O=h instanceof Kt?h:new Kt(h instanceof Error?h.message:"Failed to create session","api_error");Rn(O)}finally{E?.(),E=void 0}})(),()=>{_=!0,E?.()})}wt(!0);async function V(){let $e=!1;try{let B=await new ia(j,{telemetry:!1}).getUnifiedCheckoutSession(W,t);if(_)return;Y(B);let h=B.data.session??null;if(nt(h),!h)throw new Kt("No session data returned","api_error");let f=h.checkoutMode;if(f==="setup")throw new Kt("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(h.status==="authorized"){wt(!1),tt(()=>{$n.current?.(kr(h,W)),qe.current?.(h.successUrl??"")});return}if(h.status==="complete"){wt(!1),tt(()=>{qe.current?.(h.successUrl??"")});return}if(h.status==="expired")throw qo(h);$e=!0;let O=T??f??"full";Zn(O);let pt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),vt=Ja(B);if(O==="auto"&&!Tn.current&&!pt&&!vt){Tn.current=!0;let d=Z(B);try{if(await Mn.current(h,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>d,sessionId:W||h.id}),_)return;await d,_||wt(!1);return}catch{if(_)return;await d,_||wt(!1);return}}await Z(B),_||wt(!1)}catch(ne){if(_)return;$e&&U({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ne instanceof Kt?!$e&&!Uc(ne)&&Wa(j,o,Dt,"NETWORK_REQUEST_FAILED","session_read"):Wa(j,o,Dt,"INTERNAL_SDK_ERROR","checkout_mount");let B=ne instanceof Kt?ne:new Kt(ne instanceof Error?ne.message:"Failed to initialize checkout","api_error");Rn(B),wt(!1)}}async function Z($e){let{publishableKey:ne,paypalPublishableKey:B}=ta($e);Xt.current={publishableKey:ne,paypalPublishableKey:B};let{flopay:h,paypalFlopay:f}=await na({publishableKey:ne,paypalPublishableKey:B,billingApiUrl:j,locale:c,telemetry:o});Me.current=h,we(h),I.current=f,K(f)}return V(),()=>{_=!0}},[T,kt,Cn,Le,tt,t]);let an=Wn(async()=>{if(!(Jt||!C)){cn(!0),Ft(null);try{await gn(C,{attempt3DS:!0,fallbackToFull:!0,sessionId:W||C.id})}finally{cn(!1)}}},[W,Jt,gn,C]),er=ni(G),Ar=Ja(G),Fn=En(()=>{if(!(!G||!C||!G.data.stripe?.publishableKey))return{billingApiUrl:j}},[G,C,j]),Kn=!!(n&&!te&&ce==="buttons"&&ee&&Cn==="full"),Qt=En(()=>({session:C,loading:Wt,error:Ot,checkoutMode:_n,inlineSessionDraft:Zt,applyInlineSessionPatch:Kn?qt:void 0,inlineSessionPatchProcessing:tn,claimPending:pn,claimRequiresIdentity:qn}),[C,Wt,Ot,_n,Zt,Kn,qt,tn,pn,qn]),at=!!n&&ce==="buttons"&&!Ar&&(!$||!Fn),Yt=vn?re(Yn,{status:vn,errorMessage:ir,authorized:sr}):null;if(Wt){if(s)return Vt(Xn,{children:[s,Yt]});if(ce==="buttons"){let _=_e?.buttonsLayout?.cardButton?.borderRadius??_e?.appearance.variables?.borderRadius??8,E=V=>re("div",{style:{height:V,borderRadius:_,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Vt(Xn,{children:[Vt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[w&&E(Gr),ve&&(P||fe)&&E(Gr),ve&&E(Gr),re("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Yt]})}return Vt(Xn,{children:[Vt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[re("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),re("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Yt]})}return Ot?S?re(Ln.Provider,{value:Qt,children:S(Ot)}):re(Ln.Provider,{value:Qt,children:re("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ot.message})}):at?Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Yc,{onButtonClick:Ae,showPayPal:w,showStripe:ve,showApplePay:P,showGooglePay:fe,theme:oe,buttonsTheme:Ce,buttonsStyles:He,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De})}),Yt]}):Ar&&C&&er?Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:Vt("div",{className:Ue,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[dn&&re(Kr,{icon:!1,children:dn}),xn==="retrying"&&re("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),xn==="exhausted"&&Vt("div",{role:"alert",children:[re("div",{children:"PayPal is temporarily unavailable. Please try again."}),re("button",{type:"button",onClick:Ze,children:"Retry PayPal"})]}),xn!=="exhausted"&&re("div",{"aria-hidden":xn==="retrying"?!0:void 0,style:xn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:re(ts,{sessionId:W,nonce:C.clientSecret||void 0,billingApiUrl:j,email:C.customer?.email,clientId:er.clientId,environment:er.environment,currency:(C.currency??"usd").toUpperCase(),isSubscription:C.mode==="subscription",providerObjectType:er.providerObjectType,onComplete:b,onErrorChange:Ft,onDecline:M,onButtonClick:Ae,onInitializationStateChange:yn,allowAutomaticRetry:br===0,session:C,telemetry:o,telemetryContext:Dt,onInstrument:dt,debug:Q},`${de}:paypal-init-${br}`)})]})}),Yt]}):!$||!Fn?re(Xn,{children:Yt}):_n==="confirm"?Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Xo,{flopay:$,paypalFlopay:x,options:Fn,onInstrument:dt,children:Vt("div",{className:Ue,children:[dn&&re("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:dn}),Fe?Fe({onConfirm:an,isProcessing:Jt}):re("button",{type:"button",onClick:an,disabled:Jt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Jt?"not-allowed":"pointer",opacity:Jt?.6:1},children:Jt?"Processing...":ae??"Confirm Purchase"})]})},de)}),Yt]}):Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Xo,{flopay:$,paypalFlopay:x,options:Fn,onInstrument:dt,children:te?Vt(Xn,{children:[dn&&re("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:dn}),re(Hc,{sessionId:W,nonce:C?.clientSecret||void 0,billingApiUrl:j,session:C,children:te})]}):re(Ya,{sessionId:W,nonce:C?.clientSecret||void 0,email:C?.customer?.email||Zt?.account?.email,userId:C?.customer?.id||Zt?.account?.userId,firstName:C?.customer?.firstName||Zt?.account?.firstName,lastName:C?.customer?.lastName||Zt?.account?.lastName,totalAmount:C?Math.round(Mc(C).total*100):0,currency:C?.currency?.toLowerCase()??"usd",onComplete:b,onError:g,onDecline:M,error:dn,onErrorChange:Ft,showPayPal:w,showStripe:ve,enabledPaymentMethods:H??G?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:G?.data.stripe?.enabledPaymentMethodCountries,showApplePay:P,showGooglePay:fe,layout:ce,theme:oe,buttonsTheme:Ce,buttonsStyles:He,appearance:Je,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De,onButtonClick:Ae,onBeforeButtonClick:ee,onBuyerIdentityReady:on,enableAVS:J,...L?{cardFieldOrder:L}:{},...me?{cardPreFormSlot:me}:{},avsLayout:et,country:C?.customer?.country,city:C?.customer?.city,state:C?.customer?.state,onCountryChange:D,onZipChange:u,avsCheck:!!J,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",className:Ue,directPaypal:ni(G),isSubscription:C?.mode==="subscription",session:C,dataAttachmentPending:pn,dataAttachmentRequiresIdentity:qn,debug:Q})},de)}),Yt]})}function Hc({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return re(Xn,{children:Ga.Children.map(o,a=>{if(!Ga.isValidElement(a))return a;let c=a.props,s={};return c.sessionId||(s.sessionId=e),!c.nonce&&t&&(s.nonce=t),c.billingApiUrl||(s.billingApiUrl=n),r?.customer&&(c.email||(s.email=r.customer.email),c.userId||(s.userId=r.customer.id),c.firstName||(s.firstName=r.customer.firstName),c.lastName||(s.lastName=r.customer.lastName)),Object.keys(s).length===0?a:Ga.cloneElement(a,s)})})}function Yc({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:S,cardBackButtonContent:b,cardTitleContent:g}){let[m,M]=Et(!1),D=En(()=>Ls(a),[a]),u=En(()=>{let P=D?.buttonsLayout??Dc(c);return s?{...P,...s,cardButton:{...P.cardButton,...s.cardButton},cardFormContainer:{...P.cardFormContainer,...s.cardFormContainer},backButton:{...P.backButton,...s.backButton},backButtonIcon:{...P.backButtonIcon,...s.backButtonIcon},submitButton:{...P.submitButton,...s.submitButton},title:{...P.title,...s.title}}:P},[D,c,s]),w=D?.buttonsLayout?.cardButton?.borderRadius??D?.appearance.variables?.borderRadius??8,ve=P=>re("div",{style:{height:P,borderRadius:w,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),H=S===void 0?{boxSizing:"border-box",height:Gr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(m){let P=u.cardInputBorder??"#e5e7eb",fe=u.cardInputBackground??"white",Q=Nr(b),ce=Nr(g);return Vt("div",{style:{backgroundColor:u.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...u.cardFormContainer},children:[Vt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Vt("button",{type:"button",onClick:()=>M(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...u.backButton},children:[re("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:re("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:re("path",{d:"M15 18l-6-6 6-6"})})}),re(Lr,{content:b})]}),ce?re("div",{style:{flex:1}}):re("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:re(mo,{content:g})})]}),re("div",{style:{backgroundColor:fe,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Vt("div",{style:{display:"flex"},children:[re("div",{style:{flex:1,backgroundColor:fe,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:re("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{flex:1,backgroundColor:fe,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),re("div",{style:{backgroundColor:fe,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:re("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),re("style",{children:`
|
|
33
|
+
`}),io&&hn&&Ie("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Me?-2:0},children:[Ie("button",{type:"button",onClick:Ar,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),Ti?l("div",{style:{flex:1}}):l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...f.title},children:l(mo,{content:Ae})})]}),!io&&!Ti&&l("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:so,order:Me?-3:0,...f.title},children:l(mo,{content:Ae})}),Me&&A&&Ie("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[se&&Ie(fr,{children:[l("label",{htmlFor:"flopay-buyer-email",style:{display:"block",color:so,...Fr},children:"Email address"}),l("div",{style:{backgroundColor:Cr,border:`1px solid ${vr}`,borderRadius:Pt,marginTop:"0.375rem",padding:"10px"},children:l("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email",value:bt,onChange:i=>{Un.current=i.target.value,ir(i.target.value)},onBlur:To,disabled:d,required:!0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Fr}})})]}),pe&&Ie(fr,{children:[l("label",{htmlFor:"flopay-buyer-name",style:{display:"block",marginTop:se?"0.75rem":void 0,color:so,...Fr},children:"Full name"}),l("div",{style:{backgroundColor:Cr,border:`1px solid ${vr}`,borderRadius:Pt,marginTop:"0.375rem",padding:"10px"},children:l("input",{className:"flopay-shared-input",id:"flopay-buyer-name",name:"name",autoComplete:"name",value:Yt,onChange:i=>{qn.current=i.target.value,sr(i.target.value)},onBlur:To,disabled:d,required:!0,"data-testid":"flopay-name",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Fr}})})]})]}),X&&l("div",{style:{order:Me?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Le,R=(z=!1)=>({backgroundColor:Cr,border:`1px solid ${Pr(z)}`,borderRadius:Pt,marginTop:"0.5rem",padding:"10px"}),N=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Fr}),he=ac(i);return Ie(fr,{children:[ze(X.address_line_1,i)&&l("div",{style:R(qt.line1),children:l("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Rn,onChange:z=>{Ut.current.addressLine1=!0,xt.current=z.target.value,_n(z.target.value)},disabled:d,required:!0,"data-testid":"flopay-address-line1",style:N()})}),ze(X.address_line_2,i)&&l("div",{style:R(),children:l("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Zn,onChange:z=>{Ut.current.addressLine2=!0,tn.current=z.target.value,Xt(z.target.value)},disabled:d,"data-testid":"flopay-address-line2",style:N()})}),(ze(X.city,i)||ze(X.state,i))&&Ie("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[ze(X.city,i)&&l("div",{style:{flex:1,backgroundColor:Cr,borderTop:`1px solid ${Pr(qt.city)}`,borderRight:`1px solid ${Pr(qt.city)}`,borderBottom:`1px solid ${Pr(qt.city)}`,borderLeft:`1px solid ${Pr(qt.city)}`,padding:"10px",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,...ze(X.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Pt}},children:l("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:cn,onChange:z=>{Ut.current.city=!0,un.current=z.target.value,dn(z.target.value)},disabled:d,required:!0,"data-testid":"flopay-city",style:N()})}),ze(X.state,i)&&l("div",{style:{flex:1,backgroundColor:Cr,border:`1px solid ${Pr(qt.state)}`,padding:"10px",borderTopRightRadius:Pt,borderBottomRightRadius:Pt,...ze(X.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:Pt}},children:he?Ie("select",{id:"flopay-billing-state",name:"billing-state",value:Ft,onChange:z=>{Ut.current.state=!0,pn.current=z.target.value,vn(z.target.value)},disabled:d,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...N(),cursor:"pointer"},children:[l("option",{value:"",children:ys(i)}),he.map(z=>l("option",{value:z.code,children:z.name},z.code))]}):l("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:ys(i),autoComplete:"billing address-level1",value:Ft,onChange:z=>{Ut.current.state=!0,pn.current=z.target.value,vn(z.target.value)},disabled:d,required:!0,"data-testid":"flopay-state",style:N()})})]}),(ze(X.country,i)||ze(X.postal_code,i))&&Ie("div",{style:{display:"flex",flexDirection:te==="column"?"column":"row",gap:te==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[ze(X.country,i)&&l("div",{style:{flex:te==="row"?1:void 0,backgroundColor:Cr,borderTop:`1px solid ${vr}`,borderRight:`1px solid ${vr}`,borderBottom:`1px solid ${vr}`,borderLeft:`1px solid ${vr}`,padding:"10px",...te==="row"&&ze(X.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,borderRight:"none"}:{borderRadius:Pt}},children:l("select",{id:"flopay-billing-country",name:"billing-country",value:Le,onChange:z=>{Ut.current.country=!0,_t.current=z.target.value,Jt(z.target.value),Je?.(z.target.value),pn.current="",vn("")},disabled:d,autoComplete:"billing country","data-testid":"flopay-country",style:{...N(),cursor:"pointer"},children:tc.map(z=>Ie("option",{value:z.code,children:[z.flag," ",z.name]},z.code))})}),ze(X.postal_code,i)&&l("div",{style:{flex:te==="row"?1:void 0,backgroundColor:Cr,border:`1px solid ${tl}`,padding:"10px",...te==="row"&&ze(X.country,i)?{borderRadius:"0",borderTopRightRadius:Pt,borderBottomRightRadius:Pt}:{borderRadius:Pt}},children:l("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Ua(Le),autoComplete:"billing postal-code",value:wt,onChange:z=>{Ut.current.zip=!0,ot.current=z.target.value,zt(z.target.value),We?.(z.target.value)},onBlur:()=>Lt(!0),disabled:d,required:yn.required,"aria-invalid":Lo||void 0,"aria-describedby":Lo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:N()})})]}),Lo&&l("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:ba,...Fr,fontSize:"0.75rem"},children:yn.empty?`${Ua(i)} is required`:Ic(i)})]})})()}),Me&&Ye&&l("div",{style:{order:-2,width:"100%"},children:Ye}),Me&&il,M&&l(Kr,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:M})]}),Oo={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Ni=i=>St?!ve||!Hn?l("pre",{"data-testid":i,style:Oo,children:"FloPay/DirectPayPal-debug - not enabled"}):l("pre",{"data-testid":i,style:Oo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ve}`,` directPaypalConfigured=${Hn}`,` inAppBrowserDetected=${String(No)}`,` shouldRenderDirectPayPal=${no}`,` shouldRenderStripePayPal=${ro}`,` hasPaypalStripeInstance=${!!bn}`].join(`
|
|
34
|
+
`)}):null,Di=i=>St?!H||!ge?l("pre",{"data-testid":i,style:Oo,children:"FloPay/Stripe-debug - not enabled"}):l("pre",{"data-testid":i,style:Oo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${H}`,` currency=${we}`,` amountInCents=${Qr}`,` enabledPaymentMethods: ${JSON.stringify(C??[])}`,` enabledPaymentMethodsProvided=${eo}`,` hasEnabledMethods=${Ao}`,` expressMethods: ${JSON.stringify(Bo)}`,` walletExpressMethods: ${JSON.stringify(Mo)}`,` paymentElementMethods: ${JSON.stringify(to)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Fo)}`,` hasStripeInstance=${!!ge}`,` shouldRenderWallets=${oo}`,` shouldRenderPaymentElement=${ao}`].join(`
|
|
35
|
+
`)}):null,Li=xe==="apm-expanding"||xe==="apm-form"||xe==="apm-collapsing",zo=xe==="apm-expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="apm-collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Uo=Tt?{...ma,paymentMethodTypes:[Tt]}:null;if(oe==="buttons"){let i=xe==="buttons"||xe==="expanding"||xe==="apm-expanding",R=xe==="expanding"||xe==="card"||xe==="collapsing",N=De===void 0?{boxSizing:"border-box",height:ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"},he=xe==="expanding"||xe==="apm-expanding"?`flopay-buttons-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:xe==="collapsing"||xe==="apm-collapsing"?`flopay-buttons-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,z=xe==="expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Ie("form",{onSubmit:ga,className:B,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:M,authorized:xn}),Ie("div",{style:{display:"grid"},children:[Ie("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!he?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!he?Sc:{},...he?{animation:he,pointerEvents:"none"}:{}},children:[Ni("flopay-direct-paypal-gate-debug"),Di("flopay-stripe-gate-debug"),no&&x&&Ie(fr,{children:[V&&l("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),l(Jo,{sessionId:e,nonce:t,billingApiUrl:ne,email:k.email,billingName:ke||void 0,onBuyerIdentityReady:de,clientId:x.clientId,environment:x.environment,currency:we.toUpperCase(),isSubscription:K,providerObjectType:x.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:me,onDecline:s,onTechnicalFailure:Br,onButtonClick:J,runBeforeButtonClick:Dn,isProcessing:d,onLoadStateChange:ya,onInitializationStateChange:fa,session:I??null,existingOrderId:V?.orderId,debug:St},V?.orderId??"fresh")]}),ro&&l(_r,{stripe:bn,options:di,children:l(Ss,{sessionId:e,nonce:t,email:k.email,billingName:ke||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:me,isProcessing:d,onButtonClick:J,onDecline:s,onTechnicalFailure:Br,runBeforeButtonClick:Dn,onLoadStateChange:fi,placeholderBorderRadius:Sr})}),oo?l(_r,{stripe:ge,options:ci,children:l(ws,{sessionId:e,nonce:t,email:k.email,billingName:ke||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,intentKind:$>0?"payment":"setup",expressMethods:Mo,onTokenizedBody:Sn,onErrorChange:me,onButtonClick:J,onDecline:s,onTechnicalFailure:Br,runBeforeButtonClick:Dn,onLoadStateChange:hi,placeholderBorderRadius:Sr})}):Si?l("div",{style:{height:ra,borderRadius:Sr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ao&&l(ks,{sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,paymentElementMethods:Fo,stripeInstance:ge,paymentElementBaseOptions:ma,onTokenizedBody:Sn,onErrorChange:me,onButtonClick:J,onDecline:s,runBeforeButtonClick:Dn,onLoadStateChange:vi,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,onExpandApm:Fn,expandedApmMethod:Tt,themeId:Ce,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Sr}}),Me&&l("button",{type:"button",onClick:async()=>{d||!(await Dn("card")).proceed||(J?.("card"),er())},disabled:d,style:{width:"100%",...N,...f.cardButton,...Ha({themeBundle:h,resolvedPrimaryColor:wr,resolvedBorderRadius:Pt,submitButtonStyle:f.submitButton,explicitPrimaryColor:sn?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:d?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:d?.6:1},onMouseEnter:Re=>{!d&&(h||sn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=ol)},onMouseLeave:Re=>{(h||sn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=wr)},onMouseDown:Re=>{Re.currentTarget.style.transform="scale(0.985)"},onMouseUp:Re=>{Re.currentTarget.style.transform="scale(1)"},children:l(Dr,{content:De})}),M&&xe==="buttons"&&l(Kr,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:M})]}),Me&&R&&l("div",{style:{gridArea:"1 / 1",...z?{animation:z}:{},...xe==="collapsing"?{pointerEvents:"none"}:{}},children:Fi}),H&&Li&&Tt&&Uo&&ge&&l("div",{style:{gridArea:"1 / 1",...zo?{animation:zo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ie("div",{style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca},children:[Ie("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ie("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Kn,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:so,paddingRight:80,...f.title},children:`Pay with ${xr(Tt)}`})]}),l(_r,{stripe:ge,options:Uo,children:l($a,{method:Tt,sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:me,onDecline:s,onCancel:Kn,runBeforeButtonClick:Dn,onButtonClick:J,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,errorText:M})},Tt)]})})]})]})}return Li&&Tt&&Uo&&ge&&H?Ie("form",{onSubmit:ga,className:B,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:M,authorized:xn}),l("div",{style:{...zo?{animation:zo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ie("div",{style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca},children:[Ie("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ie("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Kn,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:so,paddingRight:80,...f.title},children:`Pay with ${xr(Tt)}`})]}),l(_r,{stripe:ge,options:Uo,children:l($a,{method:Tt,sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:me,onDecline:s,onCancel:Kn,runBeforeButtonClick:Dn,onButtonClick:J,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,errorText:M})},Tt)]})})]}):Ie("form",{onSubmit:ga,className:B,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:M,authorized:xn}),Ie("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ni("flopay-direct-paypal-gate-debug-default"),Di("flopay-stripe-gate-debug-default"),no&&x&&Ie(fr,{children:[V&&l("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),l(Jo,{sessionId:e,nonce:t,billingApiUrl:ne,email:k.email,billingName:ke||void 0,onBuyerIdentityReady:de,clientId:x.clientId,environment:x.environment,currency:we.toUpperCase(),isSubscription:K,providerObjectType:x.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:me,onDecline:s,onTechnicalFailure:Br,onButtonClick:J,runBeforeButtonClick:Dn,isProcessing:d,onLoadStateChange:ya,onInitializationStateChange:fa,session:I??null,existingOrderId:V?.orderId,debug:St},V?.orderId??"fresh")]}),ro&&l(_r,{stripe:bn,options:di,children:l(Ss,{sessionId:e,nonce:t,email:k.email,billingName:ke||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:me,isProcessing:d,onButtonClick:J,onDecline:s,onTechnicalFailure:Br,runBeforeButtonClick:Dn,onLoadStateChange:fi,placeholderBorderRadius:Sr})}),oo&&l(_r,{stripe:ge,options:ci,children:l(ws,{sessionId:e,nonce:t,email:k.email,billingName:ke||void 0,onBuyerIdentityReady:de,billingApiUrl:ne,intentKind:$>0?"payment":"setup",expressMethods:Mo,onTokenizedBody:Sn,onErrorChange:me,onButtonClick:J,onDecline:s,onTechnicalFailure:Br,runBeforeButtonClick:Dn,onLoadStateChange:hi,placeholderBorderRadius:Sr})}),ao&&l(ks,{sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ne,paymentElementMethods:Fo,stripeInstance:ge,paymentElementBaseOptions:ma,onTokenizedBody:Sn,onErrorChange:me,onButtonClick:J,onDecline:s,runBeforeButtonClick:Dn,onLoadStateChange:vi,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,themeId:Ce,onExpandApm:Fn,expandedApmMethod:Tt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Sr}})]}),Me&&(Xs||Js||Zs)&&Ie("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[l("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),l("span",{children:"or pay with card"}),l("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Me&&Fi]})}import{Fragment as Xn,jsx as re,jsxs as Ht}from"react/jsx-runtime";var Gr=44,oi="flopay_checkout_saved_payment_resume",ca=new Map,sa=new Map;function Fs(e,t){t.settled&&t.consumers===0&&ca.get(e)===t&&ca.delete(e)}function zc(e,t,n){let r=sa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};sa.set(e,a);let c=()=>{sa.get(e)===a&&sa.delete(e)};return o.then(c,c),o}function wo(e){return new Promise(t=>setTimeout(t,e))}function la(e,t,n){let r=Yo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Os,enabled:t!==!1});return r.beginCheckout(n),r}function ko(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Wa(e,t,n,r,o){let a=la(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),ko(a)}function Uc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function ni(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Ja(e){return!e||e.data.stripe?.publishableKey?!1:!!ni(e)?.clientId}function ar(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function qc(){if(!ar())return null;try{let e=window.sessionStorage.getItem(oi);return e?JSON.parse(e):null}catch{return null}}function Ns(e){if(ar())try{window.sessionStorage.setItem(oi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Xa(){if(ar())try{window.sessionStorage.removeItem(oi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ai=":idempotency-key";function zs(e,t){if(!ar())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Za(e,t,n,r){if(ar())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function ri(e,t){if(ar())try{zs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Us(e,t){if(!ar())return null;try{let n=window.sessionStorage.getItem(e+ai);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Qa(e,t,n){if(ar())try{window.sessionStorage.setItem(e+ai,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ei(e,t){if(ri(e,t),!!ar())try{Us(e,t)&&window.sessionStorage.removeItem(e+ai)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function $c(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Ds(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function jc(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function ti(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Io(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>ti(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ti(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ti(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Kc(e,t=!1){let n=Io(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function Vc(e,t){if(!e?.customer||!e.products)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=Lc(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Mc(t.items,t.subscriptions)).map(b=>({type:b.type,code:b.code??b.providerItemId??b.providerPlanId??"",quantity:b.quantity??1,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount??null,currency:(b.currency??o).toUpperCase()})).sort((b,g)=>`${b.code}:${b.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),c=e.products.map(b=>({type:b.type,code:b.code??"",quantity:b.quantity??1,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount??null,currency:(b.currency??e.currency).toUpperCase()})).sort((b,g)=>`${b.code}:${b.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(a.length!==c.length)return!1;for(let b=0;b<a.length;b+=1){let g=a[b],m=c[b];if(g.code!==m.code||g.type!==void 0&&g.type!==m.type||g.quantity!==m.quantity||g.totalAmount!==m.totalAmount||g.overrideAmount!==m.overrideAmount||g.currency!==m.currency)return!1}let s=[...t.couponCodes??[]].sort(),S=[...e.coupons??[]].sort();return s.length===S.length&&s.every((b,g)=>b===S[g])}function ii({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:c,loading:s,error:S,onComplete:b,onError:g,onInstrument:m,onDecline:B,onCountryChange:D,onZipChange:u,showPayPal:w=!0,showStripe:ve=!0,enabledPaymentMethods:H,showApplePay:C=!0,showGooglePay:fe=!0,debug:Q=!1,layout:ce,theme:oe,buttonsTheme:Ce,buttonsStyles:He,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De,showSecurityFooter:Te,onButtonClick:Ae,onBeforeButtonClick:ee,enableAVS:J,cardFieldOrder:L,cardPreFormSlot:de,avsLayout:et,className:Ue,initialErrorMessage:Ye=null,children:te,checkoutMode:T,confirmLabel:ae,renderConfirmButton:Fe,onSessionCompleted:ie}){let j=Nc(r),_e=En(()=>Ls(oe),[oe]),Je=a??_e?.appearance,We=n?"embedded_checkout":"standard_checkout",Se=te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",[G,Y]=Et(null),[$,we]=Et(null),Be=At(null),[x,K]=Et(null),I=At(null),[P,nt]=Et(null),St=En(()=>n?Io(n):"",[n]),ue=n?`create:${St}`:`session:${e??""}`,ct=P?.gateways?.stripe?"stripe":P?.gateways?.paypal?"paypal":void 0,it=At(new Set),rt=At(ue),je=At(ue);Vo(()=>{je.current=ue,rt.current!==ue&&(rt.current=ue,it.current.clear())},[ue]);let y=Wn(_=>{if(je.current===ue){if(xa.has(_.name)){if(it.current.has(_.name))return;it.current.add(_.name)}tt(()=>m?.(_))}},[ue,m]),U=jr(y,ue),Xe=At(!1),dt=Wn(_=>{if(Xe.current)return;let E=_.gateway||!ct?_:{..._,gateway:ct};y(E)},[y,ct]);Jn(()=>{U({class:"lifecycle",name:"checkout.mount"})},[U]);let[Bt,Mt]=Et(e??""),W=e??Bt,Le=n?"":W,[Jt,wt]=Et(!0),[zt,Rn]=Et(null),[_n,Zn]=Et("full"),[Xt,cn]=Et(!1),[dn,Ft]=Et(Ye),[vn,bt]=Et(null),[ir,Yt]=Et(null),[sr,Nt]=Et(!1),[zn,ot]=Et(void 0),[_t,xt]=Et(""),[tn,un]=Et(!1),[pn,Un]=Et(!1),[qn,Ut]=Et(!1),X=At(0),Pn=At(void 0),[xn,Qn]=Et("loading"),[br,Tr]=Et(0),Tn=At(!1),mn=At(!1),Me=At(!1),Zt=At(null),Dt=En(()=>({checkoutMode:T??_n,layout:te?"unknown":ce==="buttons"?"buttons":"embedded"}),[T,te,_n,ce]),$n=At(b);$n.current=b;let v=At(g);v.current=g;let ut=At(B);ut.current=B,Jn(()=>{Kt($)?.setCheckoutContext(Dt),x&&x!==$&&Kt(x)?.setCheckoutContext(Dt)},[$,x,Dt]);let qe=At(ie);qe.current=ie;let yn=Wn(_=>{Qn(_),!(_!=="exhausted"||Me.current)&&(Me.current=!0,v.current?.(new Vt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ze=Wn(()=>{Qn("retrying"),Tr(_=>_+1)},[]);Jn(()=>{Qn("loading"),Tr(0),Me.current=!1},[W]),Jn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Os,checkout_type:We,checkout_layout:Se,billing_api_url:j})},[Se,We,j]);let qt=En(()=>n?Io(n,!0):"",[n]),lr=En(()=>_t===qt?zn:void 0,[zn,_t,qt]),jn=En(()=>n?ka(n,lr):void 0,[n,lr]),Cn=T??jn?.checkoutMode??"full",Lt=En(()=>jn?{...jn,checkoutMode:Cn}:void 0,[jn,Cn]);Jn(()=>{ot(void 0),xt(qt),Pn.current=void 0,Ut(!1)},[qt]),Jn(()=>{Ft(Ye)},[Ye]);let fn=Wn((_,E,V)=>{tt(()=>{ut.current?.(jt(_,E,V))})},[tt]),gn=Wn(async(_,E)=>{Ft(null),Yt(null),Nt(!1),bt("processing");let V=E?.sessionId??_.id,Z=_.gateways?.stripe?"stripe":_.gateways?.paypal?"paypal":void 0,$e=Be.current??I.current,ne=Kt($e),M=$e?null:la(j,o,Dt),h={log:q=>{ne?ne.log(q):M?.log(q)},error:q=>{ne?ne.error(q):M?.error(q)},terminal:q=>{ne?ne.terminal(q):M?.terminal(q)},performance:q=>{ne?ne.performance(q):M?.performance(q)},now:()=>ne?.now()??M?.now()??0,elapsed:q=>ne?.elapsed(q)??Math.max(0,(M?.now()??q)-q)},f=h.now(),O=!!(E?.initialAutoProcessingError||E?.initialAutoProcessingPending),pt=!1,vt,d=()=>{pt||(pt=!0,O=!0,vt=h.now(),h.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},p=!1,k=()=>{p||(p=!0,h.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),h.performance({stage:"processing",durationMs:h.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved"}),vt!==void 0&&h.performance({stage:"recovery",durationMs:h.elapsed(vt),durationMode:"machine",paymentMethodCategory:"saved"}))};h.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Xe.current=!0;try{h.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Xe.current=!1}U({class:"lifecycle",name:"payment.processing.started",provider:Z}),O&&d();let ke;try{let q=ls(E?.initialAutoProcessingError),F;if(q)d(),q.type==="paypal_redirect_required"&&Zt.current?.publishableKey&&Ns({sessionId:V,publishableKey:Zt.current.publishableKey,paypalPublishableKey:Zt.current.paypalPublishableKey}),F=await ea(q,{flopay:Be.current,paypalFlopay:I.current,attempt3DS:E?.attempt3DS,billingApiUrl:j,sessionId:V,session:_,telemetry:!1}),q.type==="paypal_redirect_required"&&Xa();else if(E?.initialAutoProcessingPending){let se=(await new ia(j,{telemetry:!1}).waitForCheckoutSessionCompletion(E.initialAutoProcessingPending.sessionId,{initialDelayMs:E.initialAutoProcessingPending.retryAfterMs})).data.session;if(!zr(se))throw $o(se);F=kr(se,V)}else{if(E?.initialAutoProcessingError)throw yr(E.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:E.initialAutoProcessingError.checkoutMethod});if(E?.fromCreateSession)return E?.fallbackToFull&&(Zn("full"),Ds("full")),!1;{let Ge=await Hr({billingApiUrl:j,sessionId:V,session:_,telemetry:!1});Ge.type==="success"?F=Ge.result:(d(),Ge.type==="paypal_redirect_required"&&Zt.current?.publishableKey&&Ns({sessionId:V,publishableKey:Zt.current.publishableKey,paypalPublishableKey:Zt.current.paypalPublishableKey}),F=await ea(Ge,{flopay:Be.current,paypalFlopay:I.current,attempt3DS:E?.attempt3DS,billingApiUrl:j,sessionId:V,session:_,telemetry:!1}),Ge.type==="paypal_redirect_required"&&Xa())}}V&&Vr(V),k(),O&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),h.terminal({outcome:F.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Nt(F.status==="authorized"),bt("success"),await wo(1200),ke=()=>$n.current?.(F)}catch(q){let F=Rr(q),Ge=F.checkoutMethod??Po;Ft(F.message),Yt(F.message),Nt(!1),E?.fallbackToFull&&(h.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Zn("full"),Ds("full")),k();let Qe=F.statusCode!==void 0?Oc(F.statusCode,"unknown"):void 0,se=Qe==="4xx"?{requestCategory:"process_payment",statusClass:Qe}:{},pe=Qe===void 0||Qe==="4xx";if(pe&&(F.telemetryOutcome==="payment_declined"||!!(F.declineCode||F.code?.toLowerCase().includes("declin"))))h.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...se});else if(pe&&(F.telemetryOutcome==="validation_rejected"||F.type==="validation_error"))h.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...se});else{let st=Bs(q,O?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ot=F.telemetryRequestCategory??"process_payment";Xe.current=!0;try{h.error({...st,...F.telemetryFailureCategory?{failureCategory:F.telemetryFailureCategory}:{},stage:O?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ot})}finally{Xe.current=!1}U({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ot,provider:Z})}return tt(()=>v.current?.(F)),fn(Ge,F,{code:F.code,declineCode:F.declineCode}),bt("error"),await Promise.allSettled([wo(1500),E?.ensureProvidersReady?E.ensureProvidersReady():Promise.resolve()]),O&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{k(),M&&ko(M),bt(null),Yt(null)}return tt(ke),!0},[fn,U,tt,Rr,j,o,Dt]);Jn(()=>{if(typeof window>"u"||mn.current)return;let _=new URLSearchParams(window.location.search),E=_.get("payment_intent_client_secret");if(!E)return;let V=qc();V&&(mn.current=!0,(async()=>{let Z,$e=0;Ft(null),Yt(null),bt("processing"),cn(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new Vt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ne,paypalFlopay:M}=await na({publishableKey:V.publishableKey,paypalPublishableKey:V.paypalPublishableKey,billingApiUrl:j,locale:c,telemetry:o});Z=Kt(M??ne),$e=Z?.now()??0,Z?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let h=(M??ne)?.getRawProvider();if(!h)throw Object.assign(new Vt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:f,error:O}=await h.retrievePaymentIntent(E);if(O)throw Object.assign(new Vt(O.message??"Failed to retrieve PayPal payment status.","api_error",{code:O.code}),{checkoutMethod:"paypal"});let pt=Vi(f?.status);if(!f||pt==="failed")throw Object.assign(new Vt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let vt=typeof f.payment_method=="string"?f.payment_method:f.payment_method?.id,d=pt;if(V.sessionId){let ke=(await new ia(j,{telemetry:!1}).getUnifiedCheckoutSession(V.sessionId)).data.session;if(ke&&ke.status!=="complete"){let q=await Hr({billingApiUrl:j,sessionId:V.sessionId,session:ke,telemetry:!1,tokenizedData:{id:vt??f.id,type:"card",threeDSecureActionResultTokenId:f.id,isPaypal:!0}});if(q.type!=="success")throw Object.assign(new Vt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});d=q.result.status}}V.sessionId&&Vr(V.sessionId),Z?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.performance({stage:"redirect_resume",durationMs:Z.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),bt("success"),await wo(1200),tt(()=>$n.current?.({status:d,paymentIntentId:f.id,paymentMethodId:vt,checkoutMethod:"paypal"}))}catch(ne){let M=Rr(ne),h=M.checkoutMethod??"paypal",f=!!(M.declineCode||M.code?.toLowerCase().includes("declin"));if(Z)Z.performance({stage:"redirect_resume",durationMs:Z.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),f?Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Z.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(f){let O=la(j,o,Dt);O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ko(O)}else Wa(j,o,Dt,"REDIRECT_RESUME_FAILED","redirect_resume");Ft(M.message),Yt(M.message),tt(()=>v.current?.(M)),fn(h,M,{code:M.code,declineCode:M.declineCode}),bt("error"),await wo(1500)}finally{Xa(),$c(),bt(null),Yt(null),cn(!1)}})())},[fn,tt,c,Rr,j,o]);let xe=At(null),kt=En(()=>Lt?Io(Lt):"",[Lt]),Tt=At(Lt);Tt.current=Lt,Jn(()=>{Mt(e??"")},[e]),Jn(()=>{Tn.current=!1,Ft(Ye),Yt(null),Nt(!1),bt(null)},[kt,Ye,e]);async function An(_,E,V){let Z=la(j,o,Dt),$e=new ia(j,{telemetry:!1}),ne=!1;try{let M=_.idempotencyKey!==void 0?Ms(_.idempotencyKey):void 0,h=zs(E,V),f=Us(E,V);h?.canonicalIdentity===V&&f&&f.canonicalIdentity===void 0&&(Qa(E,V,f.idempotencyKey),f={...f,canonicalIdentity:V});let O=M??(f?.canonicalIdentity===V?f.idempotencyKey:void 0),pt,vt=!1;Z.log({name:h?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let d=h?.sid??null,p=null,k,ke,q=!1;if(d)try{p=await $e.getUnifiedCheckoutSession(d,h?.nonce),h&&h.canonicalIdentity===void 0&&(Vc(p.data.session,_)?(Za(E,V,d,h.nonce??p.data.session?.clientSecret),f&&f.canonicalIdentity===void 0&&(Qa(E,V,f.idempotencyKey),O??(O=f.idempotencyKey))):(ei(E,V),f=null,O=M,d=null,p=null));let F=p?.data.session?.status;if(d&&p&&F==="complete"){if(Fa(d))return{sid:d,result:p};ei(E,V),d=null,p=null,vt=!0}}catch{Z.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),h?.canonicalIdentity===void 0?(ei(E,V),O=M):ri(E,V),d=null}if(!d){!M&&(vt||!O)&&(O=Ms(),pt=O),O&&Qa(E,V,O);let F=Z.now(),Ge=0;Z.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Qe={..._,idempotencyKey:O,avsCheck:!!J,avsConfig:typeof J=="object"?J:void 0,checkoutType:"embedded_checkout",checkoutLayout:te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Qe,Ac,{configurable:!1,enumerable:!1,value:{onAttempt:A=>{Ge=Math.max(Ge,A)}}});let se=()=>{Z.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),Z.performance({stage:"session_create",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx"})},pe=A=>{let le=Bs(A,"CHECKOUT_SESSION_CREATE_FAILED","unknown");Z.performance({stage:"session_create",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:le.statusClass}),A instanceof Vt&&A.type==="validation_error"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):le.statusClass==="4xx"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(Z.error({...le,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),U({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Fc(Qe)){let A=await $e.createDetachedSession(Qe);A.claimed.catch(()=>{}),p=A.shell,d=A.sessionId,ke=A.claim,q=!Qe.account.email?.trim(),k=A.claimed.then(le=>{let st=le.data.session?.id??A.sessionId;return st&&Za(E,V,st,le.data.session?.clientSecret??A.nonce),se(),le},le=>{throw ri(E,V),pe(le),le}).finally(()=>ko(Z)),k.catch(()=>{}),ne=!0,Z.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Z.performance({stage:"session_shell",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx",paymentMethodCategory:"card"})}else p=await $e.createAndFetchSession(Qe),se()}catch(A){throw pe(A),A}d=p.data.session?.id??d??"",d&&!k&&Za(E,V,d,p.data.session?.clientSecret)}return{sid:d??"",result:p,sdkGeneratedIdempotencyKey:pt,...k?{claimed:k}:{},...ke?{claim:ke}:{},...q?{claimRequiresIdentity:!0}:{}}}finally{ne||ko(Z)}}let hn=Wn(async(_,E)=>{let V=Tt.current;if(!V)throw new Vt("createSession is required to bootstrap checkout.","validation_error");let Z=ka(V,_),$e=Io(Z),ne=Kc(Z),M=ca.get($e);if(!M){let O={canonicalIdentity:$e,promise:An(Z,ne,$e),consumers:0,settled:!1};M=O,ca.set($e,O);let pt=()=>{O.settled=!0,Fs($e,O)};O.promise.then(pt,pt)}M.consumers+=1;let h=!1,f=()=>{h||(h=!0,M.consumers-=1,Fs($e,M))};E?.(f);try{let O=await M.promise;xe.current=$e,_&&(xt(qt),ot(Qe=>$i(Qe,_)));let{sid:pt,result:vt,claimed:d,claim:p,claimRequiresIdentity:k}=O;if(Pn.current=p,Ut(k===!0),Y(vt),vt.data.session&&nt(vt.data.session),pt&&Mt(pt),d){X.current+=1;let Qe=X.current;Un(!0),d.then(se=>{X.current===Qe&&(Y(se),se.data.session&&nt(se.data.session),Un(!1),Ut(!1))},se=>{X.current===Qe&&(Un(!1),Ut(!1),Rn(se instanceof Vt?se:new Vt(se instanceof Error?se.message:"Failed to create session","api_error")))})}else X.current+=1,Un(!1),Ut(!1);let{publishableKey:ke,paypalPublishableKey:q}=ta(vt),{flopay:F,paypalFlopay:Ge}=await na({publishableKey:ke,paypalPublishableKey:q,billingApiUrl:j,locale:c,telemetry:o});return Be.current=F,we(F),I.current=Ge,K(Ge),wt(!1),O}catch(O){throw xe.current===$e&&(xe.current=null),O}finally{E||f()}},[qt,c,j,o,Dt]),Bn=At(gn);Bn.current=gn;let Mn=At(hn);Mn.current=hn;let $t=Wn(async _=>{if(!jc(_)||tn)return{sessionId:Bt,session:P};un(!0);try{let E=await hn(_);return{sessionId:E.sid,session:E.result.data.session??null}}finally{un(!1)}},[hn,tn,Bt,P]),nn=Wn(async _=>{let E=Pn.current;E&&await E(_)},[]);Jn(()=>{let _=!1,E;if(Rn(null),kt){let $e=Tt.current;return Zn(Cn),wt(!1),xe.current===kt?()=>{_=!0}:(nt(ji($e,T)),(async()=>{let ne=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),M=Cn==="auto"&&!Tn.current&&!ne;M&&(Ft(null),Yt(null),bt("processing"));try{let h=await Mn.current(void 0,vt=>{E=vt}),f=h.result.data.session??null;Zt.current=ta(h.result);let O=Ja(h.result),pt=Fa(h.sid||f?.id);if(!_&&M&&f&&!O&&!pt){Tn.current=!0,await zc(kt,h.sdkGeneratedIdempotencyKey,()=>Bn.current(f,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:h.result.autoProcessingError,initialAutoProcessingPending:h.result.autoProcessingPending,autoProcessingAttempted:h.result.autoProcessingAttempted,sessionId:h.sid||f.id}));return}!_&&M&&((O||pt)&&(Tn.current=!0),bt(null),Yt(null))}catch(h){if(_)return;let f=h instanceof Vt||typeof h=="object"&&h!==null&&"code"in h?h.code:void 0;if(M&&f==="session_auto_completed"){Tn.current=!0,bt("success"),await wo(1200),_||(tt(()=>{$n.current?.({status:"succeeded"})}),bt(null),Yt(null));return}M&&(bt(null),Yt(null));let O=h instanceof Vt?h:new Vt(h instanceof Error?h.message:"Failed to create session","api_error");Rn(O)}finally{E?.(),E=void 0}})(),()=>{_=!0,E?.()})}wt(!0);async function V(){let $e=!1;try{let M=await new ia(j,{telemetry:!1}).getUnifiedCheckoutSession(W,t);if(_)return;Y(M);let h=M.data.session??null;if(nt(h),!h)throw new Vt("No session data returned","api_error");let f=h.checkoutMode;if(f==="setup")throw new Vt("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(h.status==="authorized"){wt(!1),tt(()=>{$n.current?.(kr(h,W)),qe.current?.(h.successUrl??"")});return}if(h.status==="complete"){wt(!1),tt(()=>{qe.current?.(h.successUrl??"")});return}if(h.status==="expired")throw qo(h);$e=!0;let O=T??f??"full";Zn(O);let pt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),vt=Ja(M);if(O==="auto"&&!Tn.current&&!pt&&!vt){Tn.current=!0;let d=Z(M);try{if(await Bn.current(h,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>d,sessionId:W||h.id}),_)return;await d,_||wt(!1);return}catch{if(_)return;await d,_||wt(!1);return}}await Z(M),_||wt(!1)}catch(ne){if(_)return;$e&&U({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ne instanceof Vt?!$e&&!Uc(ne)&&Wa(j,o,Dt,"NETWORK_REQUEST_FAILED","session_read"):Wa(j,o,Dt,"INTERNAL_SDK_ERROR","checkout_mount");let M=ne instanceof Vt?ne:new Vt(ne instanceof Error?ne.message:"Failed to initialize checkout","api_error");Rn(M),wt(!1)}}async function Z($e){let{publishableKey:ne,paypalPublishableKey:M}=ta($e);Zt.current={publishableKey:ne,paypalPublishableKey:M};let{flopay:h,paypalFlopay:f}=await na({publishableKey:ne,paypalPublishableKey:M,billingApiUrl:j,locale:c,telemetry:o});Be.current=h,we(h),I.current=f,K(f)}return V(),()=>{_=!0}},[T,kt,Cn,Le,tt,t]);let an=Wn(async()=>{if(!(Xt||!P)){cn(!0),Ft(null);try{await gn(P,{attempt3DS:!0,fallbackToFull:!0,sessionId:W||P.id})}finally{cn(!1)}}},[W,Xt,gn,P]),er=ni(G),Ar=Ja(G),Fn=En(()=>{if(!(!G||!P||!G.data.stripe?.publishableKey))return{billingApiUrl:j}},[G,P,j]),Kn=!!(n&&!te&&ce==="buttons"&&ee&&Cn==="full"),Qt=En(()=>({session:P,loading:Jt,error:zt,checkoutMode:_n,inlineSessionDraft:Lt,applyInlineSessionPatch:Kn?$t:void 0,inlineSessionPatchProcessing:tn,claimPending:pn,claimRequiresIdentity:qn}),[P,Jt,zt,_n,Lt,Kn,$t,tn,pn,qn]),at=!!n&&ce==="buttons"&&!Ar&&(!$||!Fn),Gt=vn?re(Yn,{status:vn,errorMessage:ir,authorized:sr}):null;if(Jt){if(s)return Ht(Xn,{children:[s,Gt]});if(ce==="buttons"){let _=_e?.buttonsLayout?.cardButton?.borderRadius??_e?.appearance.variables?.borderRadius??8,E=V=>re("div",{style:{height:V,borderRadius:_,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Ht(Xn,{children:[Ht("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[w&&E(Gr),ve&&(C||fe)&&E(Gr),ve&&E(Gr),re("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Gt]})}return Ht(Xn,{children:[Ht("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[re("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),re("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Gt]})}return zt?S?re(Ln.Provider,{value:Qt,children:S(zt)}):re(Ln.Provider,{value:Qt,children:re("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:zt.message})}):at?Ht(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Yc,{onButtonClick:Ae,showPayPal:w,showStripe:ve,showApplePay:C,showGooglePay:fe,theme:oe,buttonsTheme:Ce,buttonsStyles:He,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De})}),Gt]}):Ar&&P&&er?Ht(Xn,{children:[re(Ln.Provider,{value:Qt,children:Ht("div",{className:Ue,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[dn&&re(Kr,{icon:!1,children:dn}),xn==="retrying"&&re("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),xn==="exhausted"&&Ht("div",{role:"alert",children:[re("div",{children:"PayPal is temporarily unavailable. Please try again."}),re("button",{type:"button",onClick:Ze,children:"Retry PayPal"})]}),xn!=="exhausted"&&re("div",{"aria-hidden":xn==="retrying"?!0:void 0,style:xn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:re(ts,{sessionId:W,nonce:P.clientSecret||void 0,billingApiUrl:j,email:P.customer?.email||Lt?.account?.email,billingName:[P.customer?.firstName,P.customer?.lastName].filter(Boolean).join(" ")||[Lt?.account?.firstName,Lt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:nn,clientId:er.clientId,environment:er.environment,currency:(P.currency??"usd").toUpperCase(),isSubscription:P.mode==="subscription",providerObjectType:er.providerObjectType,onComplete:b,onErrorChange:Ft,onDecline:B,onButtonClick:Ae,onInitializationStateChange:yn,allowAutomaticRetry:br===0,session:P,telemetry:o,telemetryContext:Dt,onInstrument:dt,debug:Q},`${ue}:paypal-init-${br}`)})]})}),Gt]}):!$||!Fn?re(Xn,{children:Gt}):_n==="confirm"?Ht(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Xo,{flopay:$,paypalFlopay:x,options:Fn,onInstrument:dt,children:Ht("div",{className:Ue,children:[dn&&re("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:dn}),Fe?Fe({onConfirm:an,isProcessing:Xt}):re("button",{type:"button",onClick:an,disabled:Xt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Xt?"not-allowed":"pointer",opacity:Xt?.6:1},children:Xt?"Processing...":ae??"Confirm Purchase"})]})},ue)}),Gt]}):Ht(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Xo,{flopay:$,paypalFlopay:x,options:Fn,onInstrument:dt,children:te?Ht(Xn,{children:[dn&&re("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:dn}),re(Hc,{sessionId:W,nonce:P?.clientSecret||void 0,billingApiUrl:j,session:P,children:te})]}):re(Ya,{sessionId:W,nonce:P?.clientSecret||void 0,email:P?.customer?.email||Lt?.account?.email,userId:P?.customer?.id||Lt?.account?.userId,firstName:P?.customer?.firstName||Lt?.account?.firstName,lastName:P?.customer?.lastName||Lt?.account?.lastName,totalAmount:P?Math.round(Bc(P).total*100):0,currency:P?.currency?.toLowerCase()??"usd",onComplete:b,onError:g,onDecline:B,error:dn,onErrorChange:Ft,showPayPal:w,showStripe:ve,enabledPaymentMethods:H??G?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:G?.data.stripe?.enabledPaymentMethodCountries,showApplePay:C,showGooglePay:fe,layout:ce,theme:oe,buttonsTheme:Ce,buttonsStyles:He,appearance:Je,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De,onButtonClick:Ae,onBeforeButtonClick:ee,onBuyerIdentityReady:nn,enableAVS:J,...L?{cardFieldOrder:L}:{},...de?{cardPreFormSlot:de}:{},avsLayout:et,country:P?.customer?.country,city:P?.customer?.city,state:P?.customer?.state,onCountryChange:D,onZipChange:u,avsCheck:!!J,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",className:Ue,directPaypal:ni(G),isSubscription:P?.mode==="subscription",session:P,dataAttachmentPending:pn,dataAttachmentRequiresIdentity:qn,debug:Q})},ue)}),Gt]})}function Hc({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return re(Xn,{children:Ga.Children.map(o,a=>{if(!Ga.isValidElement(a))return a;let c=a.props,s={};return c.sessionId||(s.sessionId=e),!c.nonce&&t&&(s.nonce=t),c.billingApiUrl||(s.billingApiUrl=n),r?.customer&&(c.email||(s.email=r.customer.email),c.userId||(s.userId=r.customer.id),c.firstName||(s.firstName=r.customer.firstName),c.lastName||(s.lastName=r.customer.lastName)),Object.keys(s).length===0?a:Ga.cloneElement(a,s)})})}function Yc({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:S,cardBackButtonContent:b,cardTitleContent:g}){let[m,B]=Et(!1),D=En(()=>Ls(a),[a]),u=En(()=>{let C=D?.buttonsLayout??Dc(c);return s?{...C,...s,cardButton:{...C.cardButton,...s.cardButton},cardFormContainer:{...C.cardFormContainer,...s.cardFormContainer},backButton:{...C.backButton,...s.backButton},backButtonIcon:{...C.backButtonIcon,...s.backButtonIcon},submitButton:{...C.submitButton,...s.submitButton},title:{...C.title,...s.title}}:C},[D,c,s]),w=D?.buttonsLayout?.cardButton?.borderRadius??D?.appearance.variables?.borderRadius??8,ve=C=>re("div",{style:{height:C,borderRadius:w,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),H=S===void 0?{boxSizing:"border-box",height:Gr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(m){let C=u.cardInputBorder??"#e5e7eb",fe=u.cardInputBackground??"white",Q=Nr(b),ce=Nr(g);return Ht("div",{style:{backgroundColor:u.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...u.cardFormContainer},children:[Ht("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ht("button",{type:"button",onClick:()=>B(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...u.backButton},children:[re("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:re("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:re("path",{d:"M15 18l-6-6 6-6"})})}),re(Lr,{content:b})]}),ce?re("div",{style:{flex:1}}):re("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:re(mo,{content:g})})]}),re("div",{style:{backgroundColor:fe,border:`1px solid ${C}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Ht("div",{style:{display:"flex"},children:[re("div",{style:{flex:1,backgroundColor:fe,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomLeftRadius:8,padding:12,height:45},children:re("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{flex:1,backgroundColor:fe,borderTop:"none",borderRight:`1px solid ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),re("div",{style:{backgroundColor:fe,border:`1px solid ${C}`,borderRadius:8,marginTop:8,padding:12,height:45},children:re("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),re("style",{children:`
|
|
36
36
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
37
37
|
@keyframes flopay-interim-expand {
|
|
38
38
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
39
39
|
40% { opacity: 1; }
|
|
40
40
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
41
41
|
}
|
|
42
|
-
`})]})}return
|
|
42
|
+
`})]})}return Ht("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ve(Gr),n&&(r||o)&&ve(Gr),n&&re("button",{type:"button",onClick:()=>{e?.("card"),B(!0)},style:{width:"100%",...H,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:u.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,...u.cardButton},onMouseDown:C=>{C.currentTarget.style.transform="scale(0.985)"},onMouseUp:C=>{C.currentTarget.style.transform="scale(1)"},children:re(Dr,{content:S})}),re("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as nd,jsx as Xr,jsxs as rd}from"react/jsx-runtime";var Xc=44;function qs(e){return new Promise(t=>setTimeout(t,e))}function Zc(e,t){return e instanceof Zr?e:new Zr(e instanceof Error?e.message:t,"api_error")}function Qc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ed(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function td({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:c,items:s,subscriptions:S,account:b,successUrl:g,cancelUrl:m,couponCodes:B,tagsData:D,utmMetadata:u,billingApiUrl:w,locale:ve,theme:H,appearance:C,buttonsTheme:fe,buttonsStyles:Q,onSuccess:ce,onError:oe,onDecline:Ce,children:He,disabled:be=!1,type:Rt="button",style:De,...Te}){let Ae=Eo(()=>Gc(w),[w]),ee=Eo(()=>ed({createSession:n,clientId:a,products:c,items:s,subscriptions:S,account:b,successUrl:g,cancelUrl:m,couponCodes:B,tagsData:D,utmMetadata:u}),[b,m,a,B,n,c,s,S,g,D,u]),[J,L]=Ro(!1),[de,et]=Ro(null),[Ue,Ye]=Ro(null),[te,T]=Ro(!1),[ae,Fe]=Ro(null),ie=Jr(!0),j=Jr(null),_e=Jr(ae),Je=Jr(ce),We=Jr(oe),Se=Jr(Ce);Wr(()=>{_e.current=ae},[ae]),Wr(()=>{Je.current=ce},[ce]),Wr(()=>{We.current=oe},[oe]),Wr(()=>{Se.current=Ce},[Ce]),Wr(()=>(ie.current=!0,()=>{ie.current=!1,j.current?.abort()}),[]),Wr(()=>{if(typeof window>"u")return;let y=U=>{U.key==="Escape"&&Fe(null)};return window.addEventListener("keydown",y),()=>{window.removeEventListener("keydown",y)}},[]);let G=hr((y,U=Po)=>{Se.current?.(jt(U,y,{code:y.code,declineCode:y.declineCode}))},[]),Y=hr(async y=>{ie.current&&(Ye(null),T(y.result.status==="authorized"),et("success"),await qs(1200),ie.current&&Je.current?.(y))},[]),$=hr(async(y,U)=>{ie.current&&(We.current?.(y),U?.emitDecline&&G(y,U.method),Ye(y.message),T(!1),et("error"),await qs(1500))},[G]),we=hr(async(y,U,Xe)=>{let dt=y.data.session??null;if(!dt)throw new Zr("No session data returned","api_error");let Bt=dt.clientSecret||t;if(zr(dt)){await Y({result:kr(dt,U),session:dt,sessionId:dt.id||U,autoCompleted:!1});return}if(dt.status==="expired")throw qo(dt);try{if(y.autoProcessingPending){let Jt=(await new si(Ae).waitForCheckoutSessionCompletion(y.autoProcessingPending.sessionId,{initialDelayMs:y.autoProcessingPending.retryAfterMs})).data.session;if(!zr(Jt))throw $o(Jt);await Y({result:kr(Jt,U),session:Jt,sessionId:Jt.id||U,autoCompleted:!1});return}if(y.autoProcessingError){if(y.autoProcessingError.type==="3ds_required"&&y.autoProcessingError.nextActionRedirectUrl&&U&&Bt){let W=new AbortController;j.current=W;let Le;try{Le=await cs({billingApiUrl:Ae,sessionId:U,nonce:Bt,nextActionRedirectUrl:y.autoProcessingError.nextActionRedirectUrl,signal:W.signal})}finally{j.current===W&&(j.current=null)}if(Le.status==="declined")throw yr({type:Le.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Le.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:y.autoProcessingError.checkoutMethod});let zt=(await new si(Ae).waitForCheckoutSessionCompletion(U,{initialDelayMs:0,nonce:Bt})).data.session;if(!zr(zt))throw yr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:y.autoProcessingError.checkoutMethod});await Y({result:kr(zt,U),session:zt,sessionId:zt.id||U,autoCompleted:!1});return}throw yr(y.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:y.autoProcessingError.checkoutMethod})}if(Xe?.fromCreateSession&&y.autoProcessingAttempted===!0)throw yr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Mt=await Hr({billingApiUrl:Ae,sessionId:U??dt.id,session:dt,nonce:Bt});if(Mt.type!=="success")throw yr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Y({result:Mt.result,session:dt,sessionId:dt.id||U,autoCompleted:!1})}catch(Mt){let W=Rr(Mt),Le=dt.id||U;await $(W,{emitDecline:!0,method:W.checkoutMethod??Po}),Qc(W,Le)&&Le&&ie.current&&Fe({sessionId:Le,errorMessage:W.message,nonce:Bt||void 0})}},[t,Ae,$,Y]),Be=hr(async y=>{if(Te.onClick?.(y),!(y.defaultPrevented||be||J)){if(Fe(null),e&&ee){let U=new Zr("Provide either sessionId or create-session props, not both.","validation_error");await $(U),ie.current&&(et(null),Ye(null));return}if(!e&&!ee){let U=new Zr("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(U),ie.current&&(et(null),Ye(null));return}L(!0),Ye(null),T(!1),et("processing");try{let U=new si(Ae);if(e){let Xe=await U.getUnifiedCheckoutSession(e,t);await we(Xe,e);return}try{let Xe=await U.createAndFetchSession({...ee});await we(Xe,Xe.data.session?.id??null,{fromCreateSession:!0})}catch(Xe){if(Xe instanceof Zr&&Xe.code==="session_auto_completed"){await Y({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Xe}}catch(U){await $(Zc(U,"Automatic payment failed. Please try again."))}finally{ie.current&&(et(null),Ye(null),L(!1))}}},[Te,ee,be,J,t,we,Ae,e,$,Y]),x=hr(y=>{let U=_e.current;Fe(null),Je.current?.({result:y,session:null,sessionId:U?.sessionId??null,autoCompleted:!1})},[]),K=hr(y=>{We.current?.(y)},[]),I=hr(y=>{Se.current?.(y)},[]),P=Eo(()=>Jc(H),[H]),nt=Eo(()=>{let y=P?.buttonsLayout??Wc(fe);return Q?{...y,...Q,cardButton:{...y.cardButton,...Q.cardButton}}:y},[P,fe,Q]),St=Eo(()=>{let y=P?.appearance;return C?y?{...y,...C,variables:{...y.variables,...C.variables}}:C:y},[C,P]),ue=St?.variables,ct=ue?.colorPrimary??"#4A49FF",it=ue?.colorPrimaryHover??po(ct,.12),rt=ue?.borderRadius??"8px";return rd(nd,{children:[Xr("button",{...Te,type:Rt,onClick:Be,disabled:be||J,"aria-busy":J,style:{width:"100%",...He===void 0?{boxSizing:"border-box",height:Xc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...nt.cardButton,...Ha({themeBundle:P,resolvedPrimaryColor:ct,resolvedBorderRadius:rt,submitButtonStyle:nt.submitButton,explicitPrimaryColor:ue?.colorPrimary}),fontSize:nt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:be||J?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:be||J?.6:1,...De},onMouseEnter:y=>{Te.onMouseEnter?.(y),!y.defaultPrevented&&!be&&!J&&(P||ue?.colorPrimary)&&(y.currentTarget.style.backgroundColor=it)},onMouseLeave:y=>{Te.onMouseLeave?.(y),!y.defaultPrevented&&(P||ue?.colorPrimary)&&(y.currentTarget.style.backgroundColor=ct)},onMouseDown:y=>{Te.onMouseDown?.(y),y.defaultPrevented||(y.currentTarget.style.transform="scale(0.985)")},onMouseUp:y=>{Te.onMouseUp?.(y),y.defaultPrevented||(y.currentTarget.style.transform="scale(1)")},children:Xr(Dr,{content:He})}),de&&Xr(Yn,{status:de,errorMessage:Ue,authorized:te}),ae&&Xr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:y=>{y.target===y.currentTarget&&Fe(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:Xr("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:Xr(ii,{sessionId:ae.sessionId,nonce:ae.nonce,checkoutMode:"full",billingApiUrl:Ae,locale:ve,theme:H,...St?{appearance:St}:{},buttonsTheme:fe,buttonsStyles:Q,initialErrorMessage:ae.errorMessage,cardTitleContent:null,onComplete:x,onError:K,onDecline:I})})})]})}export{Jo as DirectPayPalButton,td as FloPayAutomaticPaymentButton,ll as FloPayCardSetup,sl as FloPayCardSetupError,ii as FloPayCheckout,Xo as FloPayProvider,Ya as SplitCardForm,wa as VaultCardFields,ap as dropThirdPartyOnlyError,bl as useCheckout,ur as useFloPay,_a as usePayPalFloPay};
|