@flopay/react 1.8.14 → 1.8.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +9 -9
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as _t,b as er,c as Fa,d as So,e as Zi,f as Qi,g as Cl,h as Sl}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as kp}from"@flopay/shared";import{PaymentAPI as vi}from"@flopay/js";import{FloPayError as io,resolveBillingApiUrl as md,resolveButtonsLayoutTheme as yd,resolveTheme as fd}from"@flopay/shared";import{useCallback as Pr,useEffect as ro,useMemo as zo,useRef as oo,useState as Uo}from"react";import{Fragment as Hr,jsx as Fn,jsxs as es}from"react/jsx-runtime";function wl(){return es(Hr,{children:[es("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[Fn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Fn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Fn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:Fn("path",{d:"M9 18l6-6-6-6"})})]})}function kl(){return Fn(Hr,{children:"Go back"})}function Il(){return Fn(Hr,{children:"Secure card checkout"})}function $r(e){return e!==void 0&&(e===""||e===null||e===!1)}function jr({content:e}){return Fn(Hr,{children:e===void 0?Fn(wl,{}):e})}function Kr({content:e}){return Fn(Hr,{children:e===void 0?Fn(kl,{}):e})}function wo({content:e}){return Fn(Hr,{children:e===void 0?Fn(Il,{}):e})}import{FloPayError as Da,isMoneySettledOutcome as El,isSetupIntentClientSecret as Rd,isValidEmail as Rl}from"@flopay/shared";function Vr(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()};if(!Rl(l.email))return Promise.reject(new Da("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let s={};for(let[k,g]of Object.entries(l)){if(typeof g!="string")continue;let h=g.trim();h&&(s[k]=h)}return o=e.claimCheckoutSession(t,n,{accountData:s}),o.catch(()=>{}),o}}function ts(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:"checkoutMetadata"in e?{checkoutMetadata:e.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function La(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ns(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function Er(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 Na(e,t){return t?{...e,...t}:e}function Ht(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 _l=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function yr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of _l)if(n.test(t))return r;return e}function Rr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Yr(e){return e?.status==="authorized"||e?.status==="complete"}function rs(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Qo(e){let t=rs(e);return new Da(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ea(e){let t=rs(e);return new Da(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 ko(e,t){return e==="processing"||El(e,t)}function os(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function as(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Io(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as fa,SESSION_CREATE_TELEMETRY as Gc}from"@flopay/js";import{buildCheckoutDisplayData as Jc,classifyTelemetryFailure as Ys,FloPayError as Vt,foldIntoProducts as Xc,isDetachedSessionEligible as Zc,resolveBillingApiUrl as Qc,resolveButtonsLayoutTheme as ed,resolveIdempotencyKey as Ws,resolveSessionCurrency as td,resolveTheme as Zs,SDK_VERSION as Qs,telemetryStatusClass as nd}from"@flopay/shared";import ii,{useCallback as nr,useEffect as rr,useMemo as Ln,useRef as Bt,useState as Ft}from"react";import{createContext as is}from"react";var Dn=is({flopay:null,paypalFlopay:null,billingApiUrl:""}),Vn=is({session:null,loading:!1,error:null});import{PaymentAPI as Ua}from"@flopay/js";import{classifyTelemetryFailure as Hl,FloPayError as ps,generateIdempotencyKey as Vl,isValidEmail as To,normalizeGatewayEnvironment as Yl,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as qa,SDK_VERSION as Wl}from"@flopay/shared";import{loadScript as Gl}from"@paypal/paypal-js";import{useCallback as xo,useEffect as Et,useMemo as Mo,useRef as Je,useState as Tr}from"react";import{isValidEmail as Tl}from"@flopay/shared";import{useCallback as ss,useEffect as xl,useRef as ls,useState as ds}from"react";import{jsx as cs,jsxs as Eo}from"react/jsx-runtime";function Sn(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),a=n?.trim();return{...r,...o?{firstName:o}:{},...a?{lastName:a}:{}}}function Wr(){let[e,t]=ds(null),n=ls(null),r=ls(0),o=ss((l,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:s}),new Promise(k=>{n.current=k})),[]),a=ss(l=>{let s=n.current;n.current=null,t(null),s?.(l)},[]);return xl(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Gr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,s]=ds(e.email?.trim()??""),k=Tl(l.trim());return Eo("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:[Eo("div",{style:{fontWeight:700},children:["Continue with ",t]}),Eo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",cs("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:g=>s(g.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Eo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&cs("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Eo("button",{type:"button",disabled:!k||o,onClick:()=>{n(Sn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Ml(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 _r(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function ar(e){if(typeof e!="object"||e===null)return;let t=e;return _r(t.code)??_r(t.type)??_r(t.name)}function Jr(e){if(!(typeof e!="object"||e===null))return _r(e.decline_code)}function Ro(e){return typeof e!="object"||e===null?!1:_r(e.type)?.toLowerCase()==="card_error"||Jr(e)!==void 0}function fr(e){let t=Ml(e)?.toLowerCase()??"",r=`${ar(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Al}from"@flopay/shared";import{useContext as ta}from"react";function gr(){return ta(Dn).flopay}function Oa(){return ta(Dn).paypalFlopay??null}function Bl(){return ta(Vn)}function us(){return ta(Dn).billingApiUrl||Al()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Ll}from"@flopay/shared";import{useCallback as Nl,useRef as na}from"react";import{useEffect as Fl,useLayoutEffect as Dl}from"react";var _o=typeof window>"u"?Fl:Dl;var Ol={"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 zl(e){return e==="stripe"||e==="paypal"?e:void 0}function Ul(e){let t=zl(e.provider),n={schemaVersion:Ll,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Ol[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 za=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Xr(e,t){let n=na(e);n.current=e;let r=na(new Set),o=na(t),a=na(t);return _o(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Nl(l=>{if(a.current!==t)return;let s=Ul(l);if(s){if(za.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}_t(()=>n.current?.(s))}},[t])}var ql=Symbol.for("@flopay/js.telemetry.bridge.v1"),$l=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function jl(){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 Kl(e){let t=jl(),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 ra(e){let t=globalThis[$l];return Kl(t?.(e)??{})}function jt(e){if(e)return e[ql]}import{jsx as xr,jsxs as $a}from"react/jsx-runtime";var oa=45,Jl=1e3,Xl=11e3,Zl=["https://www.paypal.com","https://www.sandbox.paypal.com"],ms="We couldn't open PayPal. Try again or choose another payment method.",Ql={width:"100%",minHeight:oa,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 ys(e){return e.includes("No ack for postMessage init()")&&Zl.some(t=>e.includes(t))&&e.includes("10000ms")}function ec(e){return e?`${ms} Allow pop-ups for this site, then try again.`:ms}function tc(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 fs({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:s,currency:k,isSubscription:g,providerObjectType:h,onTokenizedBody:b,onComplete:T,onErrorChange:M,onDecline:u,onTechnicalFailure:I,isProcessing:he=!1,onLoadStateChange:j,onInitializationStateChange:C,allowAutomaticRetry:pe=!0,onButtonClick:Z,runBeforeButtonClick:se,session:ae,existingOrderId:ve,telemetry:et,telemetryContext:be,onInstrument:Dt,debug:Xe=!1}){let Me=gr(),Ae=Xr(Dt,e),ee=Mo(()=>{if(Me)return null;let w=ra({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Wl,enabled:et!==!1});return w.setCheckoutContext(be??{}),w.beginCheckout(be??{}),w},[n,Me,et,be?.checkoutMode,be?.layout]),Q=Mo(()=>jt(Me),[Me]);Et(()=>()=>{ee&&ee.flush().catch(()=>{}).finally(()=>ee.destroy())},[ee]);let A=Mo(()=>({error:w=>{Q?Q.error(w):ee?.error(w),Ae({class:"technical_error",errorCode:w.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":w.errorCode,requestCategory:w.requestCategory,provider:w.provider})},log:w=>{Q?Q.log(w):ee?.log(w),Ae({class:"lifecycle",name:w.name,provider:w.provider})},performance:w=>{Q?Q.performance(w):ee?.performance(w)},terminal:w=>{Q?Q.terminal(w):ee?.terminal(w)},startTiming:()=>Q?.now()??ee?.now()??0,elapsed:w=>Q?.elapsed(w)??Math.max(0,(ee?.now()??w)-w)}),[Ae,Q,ee]),Fe=Je(null),De=Je(0),Le=Je(null),Ue=Je(!1),[ke,_]=Tr(!1),[ce,Pe]=Tr(!1),[de,K]=Tr(0),Ie=Je(0),[ot,ht]=Tr(!1),qe=Je(!1),H=Je(!1),[D,B]=Tr(!1),[Ee,Ve]=Tr(!1),{request:ie,collect:at,finish:S}=Wr(),v=Je({sessionId:e,required:!To(r?.trim()||ae?.customer?.email?.trim())});v.current.sessionId!==e&&(v.current={sessionId:e,required:!To(r?.trim()||ae?.customer?.email?.trim())});let _e=v.current.required,ne=Mo(()=>n.replace(/\/+$/,""),[n]),tt=ae?.gateways?.paypal?.providerObjectType??h,Be=tt??(g?"subscription":"order"),Ze=tt==="order"||tt==="setup_token",Mt=Mo(()=>JSON.stringify([ne,l,k,s??"",Be,Ze,e,ve??""]),[ne,l,k,s,ve,Be,Ze,e]),P=Je(Mt),U=P.current!==Mt,it=Je(Xe),Ye=Je(null),[en,Wt]=Tr([]),E=xo(w=>{it.current&&Wt(ct=>[...ct,`${new Date().toISOString().slice(11,23)} ${w}`])},[]);Et(()=>{it.current=Xe,Xe&&E("debug:enabled"),Ye.current?.setEnabled(Xe)},[E,Xe]);let mt=Je(b),Tt=Je(T),st=Je(M),Rt=Je(u),pn=Je(I),an=Je(Z),mn=Je(j),Lt=Je(C),wn=Je(a),tn=Je(se),yt=Je(ae),lt=Je(r),ft=Je(o),sn=Je(t),Qe=Je(null),Wn=Je(0),dt=Je(null),nn=Je(null),bt=Je(new Map),Gt=Je(new Map),kn=Je(!1);Et(()=>(kn.current=!0,()=>{kn.current=!1}),[]),Et(()=>{mt.current=b},[b]),Et(()=>{wn.current=a},[a]),Et(()=>{Tt.current=T},[T]),Et(()=>{st.current=M},[M]),Et(()=>{Rt.current=u},[u]),Et(()=>{pn.current=I},[I]),Et(()=>{an.current=Z},[Z]),Et(()=>{mn.current=j},[j]),Et(()=>{Lt.current=C},[C]),Et(()=>{tn.current=se},[se]),Et(()=>{yt.current=ae},[ae]),Et(()=>{lt.current=r},[r]),Et(()=>{ft.current=o},[o]),Et(()=>{sn.current=t},[t]),Et(()=>{Ie.current=de},[de]),Et(()=>{ot&&Le.current?.focus()},[ot,de]);let yn=xo(()=>{window.setTimeout(()=>{Le.current?.focus()},0)},[]),_n=xo(()=>{_(!1),K(w=>w+1)},[]),ln=xo(()=>{ht(!1),(Fe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Fe.current)?.focus?.()},[]);Et(()=>{!ke||!Ue.current||(Ue.current=!1,ln())},[ln,ke,de]);let Tn=xo((w,ct)=>{let Kt=pn.current;if(Kt){Kt("paypal",w,ct);return}st.current?.(ec(ct?.popupBlocked??fr(w)))},[]),qt=()=>{dt.current?.timer&&(clearTimeout(dt.current.timer),dt.current.timer=null)},G=()=>{qt();let w=Wn.current+1;return Wn.current=w,nn.current=null,dt.current={generation:w,timer:null,yieldedControl:!1},ht(!1),w},fn=w=>w!==void 0&&dt.current?.generation!==w?!1:(qt(),dt.current=null,nn.current=null,!0),Nn=w=>{let ct=w?.generation??dt.current?.generation??Wn.current;(!w?.generation||dt.current?.generation===ct)&&(qt(),dt.current=null),nn.current=ct,w?.showRetry&&ht(!0),w?.remount&&_n(),w?.focus!==!1&&yn()},Gn=w=>dt.current?.generation===w&&nn.current!==w,Cr=w=>{typeof document<"u"&&document.visibilityState!=="visible"||(qt(),w.timer=setTimeout(()=>{dt.current?.generation===w.generation&&(dt.current=null,nn.current=w.generation,Tn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),ht(!0),_n(),yn())},600))},Sr=()=>{let w=dt.current;w?.yieldedControl&&Cr(w)},cr=()=>{let w=dt.current;w&&(w.yieldedControl=!0,qt())},Nt=w=>{let ct=Qe.current;return ct&&Gt.current.set(w,ct),w};Et(()=>{let w=()=>{document.visibilityState==="visible"?Sr():cr()};return document.addEventListener("visibilitychange",w),window.addEventListener("focus",Sr),window.addEventListener("blur",cr),()=>{document.removeEventListener("visibilitychange",w),window.removeEventListener("focus",Sr),window.removeEventListener("blur",cr),qt()}},[]),Et(()=>{P.current!==Mt&&(P.current=Mt,qe.current=!1,H.current=!1,_(!1),Pe(!1),B(!1),Lt.current?.("loading"))},[Mt]),Et(()=>{_t(()=>mn.current?.(ke&&!D))},[ke,D]);let $e=Yl(s);Et(()=>{let w=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",ct=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(E(`mount clientId=${w} env=${s??"(unset)"}\u2192${$e??"live"} ccy=${k} sub=${g}`),E(`ua=${ct.slice(0,80)}${ct.length>80?"\u2026":""}`),!l){E("FAIL: clientId empty \u2014 gateway misconfigured"),B(!0),A.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(!Fe.current){E("FAIL: containerRef not attached");return}De.current=A.startTiming(),A.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Kt=!1,In=!1,me=()=>Kt||In,cn,wr=!1,Lr=()=>{cn=Vl(),cn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),wr=!0},gn=null,ur=!1,Jn=null,On=!1,Ot=()=>{!Jn||On||(On=!0,Jn.close().catch(()=>{}))},zn=null,Xn=()=>{zn!==null&&(A.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"overlay_return",durationMs:A.elapsed(zn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),zn=null)},hn=!1,rn=Fe.current,Un=null,qn=null,ut=[],bn=null,vn=!1,$n=!1,xn=null,Ce=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let d=m.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},on=m=>{if(!m)return"(empty)";try{let d=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),f=d.pathname.toLowerCase();return f.includes("checkcaptcha")||f.includes("captcha")?`CAPTCHA(${d.host}${f})`:f.includes("risk")||f.includes("challenge")?`RISK(${d.host}${f})`:f.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${f}`.slice(0,100)}catch{return m.slice(0,80)}},zt=m=>{let d=m.getAttribute("src"),f=m.getAttribute("srcdoc"),ye=m.getAttribute("name"),re=m.getAttribute("sandbox"),je=[];return d&&je.push(`src=${on(d)}`),f&&je.push(`srcdoc[${f.length}ch]`),!d&&!f&&je.push("src=(empty) srcdoc=(empty)"),ye&&je.push(`name=${ye.slice(0,40)}`),re!==null&&je.push(`sandbox="${re.slice(0,40)}"`),je.join(" ")},pr=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let d=m.contentDocument;if(!d)return"cd=null";let f=d.body?.children.length??0,ye=d.body?.innerHTML.length??0,re=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${f}children,${ye}ch] head[${re}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},jn=[],mr=m=>{if(me())return;let d=m.message??String(m.error??"(no message)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(E(`window:error ${d.slice(0,140)}`),jn.push(d))},En=m=>{if(me())return;let d=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(E(`window:rejection ${d.slice(0,140)}`),jn.push(d))},Mn={value:0},Ut=()=>{for(Un?.disconnect(),Un=null,qn?.disconnect(),qn=null;ut.length;)clearTimeout(ut.pop());$n=!1,vn&&typeof window<"u"&&(window.removeEventListener("error",mr),window.removeEventListener("unhandledrejection",En)),vn=!1},x=()=>{if(!(vn||me()||hn)){if(vn=!0,jn.length=0,Mn.value=0,typeof window<"u"&&(window.addEventListener("error",mr),window.addEventListener("unhandledrejection",En)),typeof PerformanceObserver<"u")try{qn=new PerformanceObserver(m=>{if(!me())for(let d of m.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;Mn.value+=1;let f=Math.round(d.duration);E(`net ${f}ms ${d.name.slice(0,90)}`)}}),qn.observe({type:"resource",buffered:!0})}catch{}xn?.()}},L=()=>{bn&&(clearTimeout(bn),bn=null)},V=()=>{Ut(),L()},Y={setEnabled:m=>{m?x():Ut()}};Ye.current=Y,it.current&&x();let Se=m=>{if(!m)return!1;let d=m.toLowerCase();return d.includes("zoid destroyed")||d.includes("destroyed all components")||d.includes("window closed")||d.includes("detected container element removed")},F=m=>{if(me()||Se(m))return;let d=yr(m)??m;_t(()=>st.current?.(d))},q=m=>{Kt||(B(!0),m.includes("paypal_ineligible")||A.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:",m))},p=(m,d=!1)=>{if(Kt)return;let f=qe.current||!pe;if(ur)return;ur=!0,In=!0,V(),Ot();let ye=d||ys(m);if(ye&&pe&&!qe.current){qe.current=!0,_(!1),Ve(!1),Pe(!0),Lt.current?.("retrying"),gn=setTimeout(()=>{Kt||K(re=>re+1)},Jl);return}if(ye||f){if(_(!1),Ve(!1),Pe(!1),B(!0),Lt.current?.("exhausted"),!H.current){H.current=!0;let re=ys(m)?"paypal_init_timeout":d?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",re)}return}q(m)};B(!1);let O=async(m,d=Qe.current)=>{if(me())return;let f=d?.sessionId??e;if(mt.current){await mt.current(m,{sessionId:f,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let ye=A.startTiming();A.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let re=()=>{A.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"processing",durationMs:A.elapsed(ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let je=yt.current,We=d?.accountPatch?.email??lt.current,J=d?.accountPatch?.userId??je?.customer?.id??je?.accountData?.userId??"",R=d?.accountPatch?.firstName??je?.customer?.firstName??je?.accountData?.firstName,oe=d?.accountPatch?.lastName??je?.customer?.lastName??je?.accountData?.lastName,Ne=await new Ua(ne,{telemetry:!1}).processPayment(J,{sessionId:f,nonce:d?.nonce??sn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:J,email:We??je?.customer?.email??"",...R?{firstName:R}:{},...oe?{lastName:oe}:{},country:d?.accountPatch?.country??je?.customer?.country??je?.accountData?.country??void 0,zip:d?.accountPatch?.zip??je?.customer?.zip??je?.accountData?.zip??void 0}});if(Ne.ok){if(In||Kt&&kn.current)return;re(),A.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),_t(()=>Tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(me())return;let Pt=await Ne.json().catch(()=>null),Oe=Pt?.message??"PayPal payment failed.",$t=yr(Oe)??Oe;re(),Ne.status===400&&(typeof Pt?.declineCode=="string"||!Array.isArray(Pt?.fields))?A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Ne.status===400||Ne.status===422?A.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):A.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Ne.status>=500?"5xx":Ne.status>=400?"4xx":Ne.status>=300?"3xx":"unknown",failureCategory:Ne.status>=500?"server_error":void 0}),F($t),_t(()=>Rt.current?.(Ht("paypal",$t,{code:Pt?.code,declineCode:Pt?.declineCode})));return}catch(je){if(me())return;re(),A.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let We=je instanceof Error?je.message:"PayPal payment failed.",J=yr(We)??We;F(J),_t(()=>Rt.current?.(Ht("paypal",J)));return}},$=()=>new ps("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),gt=m=>me()?Promise.reject($()):Promise.resolve(m),vt=async m=>{if(me())throw $();wr||Lr();let d=Qe.current,f=d?.sessionId??e,ye=d?.nonce??sn.current;A.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let re;try{re=await new Ua(ne,{telemetry:!1}).createSessionIntent(f,ye??"",Ze?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:qa,paymentMethodId:null,intentKind:Be==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:cn})}catch(je){throw A.error({...Hl(je,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),je}if(me())throw $();if(re.provider!=="paypal"||re.providerObjectType!==Be)throw new Error(m);return A.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),re.providerObjectId},te=(m,d)=>{let f=d?.nonce??sn.current;if(!f)return;let ye=d?.sessionId??e,re=Jr(m)??ar(m)??"provider_declined";new Ua(ne,{telemetry:!1}).reportSessionIntentDecline(ye,f,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:re}).catch(()=>{})},we=de;E("loadScript:scheduled (deferred 1 tick)");let Jt=null,nt=setTimeout(()=>{if(Kt){E("loadScript:skipped (cancelled before defer ran)");return}E("loadScript:start");let m=$e==="live"?"production":$e;Jt=Gl({clientId:l,currency:k,...Be==="subscription"?{intent:"subscription",vault:!0}:Be==="order"?{intent:"capture"}:{},...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Jt.then(d=>{if(E(`loadScript:resolved inactive=${me()} ns=${!!d} buttons=${!!d?.Buttons}`),me())return;if(!d?.Buttons){E("FAIL: namespace missing Buttons factory"),p("PayPal SDK did not expose the Buttons factory.");return}A.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"provider_ready",durationMs:A.elapsed(De.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let f=async(J,R)=>{if(me()||Ie.current!==we)return;let oe=J.vaultSetupToken??J.subscriptionID??J.orderID??"",Ke=oe?Gt.current.get(oe):bt.current.get(we);if(!(!Ke||!Gn(Ke.generation))&&fn(Ke.generation)){Gt.current.delete(oe),bt.current.delete(Ke.surfaceKey),Xn();try{if(Ve(!0),_t(()=>st.current?.(null)),!oe)throw new ps("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ne=yt.current,Pt=Er(ft.current??[Ne?.customer?.firstName,Ne?.customer?.lastName].filter(Boolean).join(" ")),Oe=Sn({email:Ke.accountPatch?.email?.trim()||lt.current?.trim()||Ne?.customer?.email?.trim(),firstName:Ke.accountPatch?.firstName?.trim()||Pt.firstName,lastName:Ke.accountPatch?.lastName?.trim()||Pt.lastName});if(!To(Oe.email)||!(Oe.firstName||Oe.lastName))try{let $t=tc(await R?.order?.get?.());Oe=Sn({email:$t.email||Oe.email,firstName:$t.firstName||Oe.firstName,lastName:$t.lastName||Oe.lastName})}catch{}if((wn.current||_e)&&!To(Oe.email)){let $t=await at("PayPal",Oe);if(!$t)return;Oe=$t}To(Oe.email)&&(Ke.accountPatch=Sn({...Ke.accountPatch,...Oe}),await wn.current?.(Oe)),await O(Be==="setup_token"?{id:oe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:qa}:Ze?{id:oe,isPaypal:!0,gateway:"paypal",paymentMethodType:qa}:{id:oe,isPaypal:!0},Ke)}catch(Ne){F(Ne instanceof Error?Ne.message:"PayPal capture failed.")}finally{me()||Ve(!1)}}},ye=d.Buttons({style:{layout:"horizontal",height:oa,tagline:!1},onClick:async(J,R)=>{if(me()){await R.reject();return}Lr();let oe=tn.current,Ke={};if(oe)try{let Oe=await oe("paypal");if(me()){await R.reject();return}if(!Oe.proceed){Qe.current=null,bt.current.delete(we),await R.reject();return}Ke={sessionId:Oe.sessionId,accountPatch:Oe.accountPatch,nonce:Oe.nonce}}catch(Oe){E(`onClick:runBeforeButtonClick rejected msg=${(Oe instanceof Error?Oe.message:String(Oe)).slice(0,120)}`),Qe.current=null,bt.current.delete(we),await R.reject();return}_t(()=>an.current?.("paypal"));let Pt={generation:G(),surfaceKey:we,...Ke};Qe.current=Pt,bt.current.set(we,Pt),await R.resolve(),A.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),zn=A.startTiming()},createOrder:Be==="order"?ve?()=>gt(ve).then(Nt):()=>vt("Failed to create PayPal order.").then(Nt):void 0,createSubscription:Be==="subscription"?ve?()=>gt(ve).then(Nt):()=>vt("Failed to create PayPal subscription.").then(Nt):void 0,createVaultSetupToken:Be==="setup_token"?()=>vt("Failed to create PayPal setup token.").then(Nt):void 0,onApprove:f,onCancel:()=>{if(me())return;let J=bt.current.get(we)??Qe.current;J&&bt.current.delete(J.surfaceKey),Qe.current=null,Xn(),A.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ue.current=!0,Nn({generation:J?.generation,remount:!0,focus:!1})},onError:J=>{if(me()||Ie.current!==we)return;let R=J instanceof Error?J.message:"PayPal failed to render.";if(E(`onError rendered=${hn} msg=${R.slice(0,120)}`),hn){let oe=bt.current.get(we)??Qe.current;if(oe&&!Gn(oe.generation)||!oe&&nn.current===Wn.current)return;if(Se(R)){fn(oe?.generation);return}if(Xn(),Ro(J)){A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),te(J,oe),_t(()=>Rt.current?.(Ht("paypal",R))),oe&&bt.current.delete(oe.surfaceKey),Qe.current=null,fn(oe?.generation);return}let Ke=R.toLowerCase();A.error({errorCode:Ke.includes("popup")&&Ke.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),oe&&bt.current.delete(oe.surfaceKey),Qe.current=null,Nn({generation:oe?.generation,remount:!0,showRetry:!0,focus:!0}),Tn(J,{code:"paypal_runtime_failed"});return}p(R)}}),re=ye.isEligible();if(E(`isEligible=${re}`),A.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!re){_(!1),p("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Jn=ye,xn=()=>{if(!vn||$n||me()||hn)return;$n=!0,E(`container:dims ${Ce(rn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),typeof MutationObserver<"u"&&(Un=new MutationObserver(R=>{if(!me()){for(let oe of R)if(oe.type==="childList")oe.addedNodes.forEach(Ke=>{if(!(Ke instanceof Element))return;let Ne=Ke.tagName.toLowerCase(),Pt=(Ke.getAttribute("title")??"").slice(0,40),Oe=Ne==="iframe"?` ${zt(Ke)}`:"";E(`child+ ${Ne}${Pt?` title="${Pt}"`:""}${Oe} dims=${Ce(Ke)}`)});else if(oe.type==="attributes"&&oe.target instanceof Element){let Ke=oe.target;if(Ke.tagName.toLowerCase()!=="iframe")continue;let Ne=oe.attributeName;(Ne==="src"||Ne==="srcdoc")&&E(`attr~ iframe ${Ne}=${Ne==="srcdoc"?`[${(Ke.getAttribute("srcdoc")??"").length}ch]`:on(Ke.getAttribute("src"))} dims=${Ce(Ke)}`)}}}),Un.observe(rn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let J=R=>{if(me()||hn)return;let oe=rn.querySelectorAll("iframe"),Ke=typeof document<"u"&&"hasStorageAccess"in document;E(`watchdog:${R} container=${Ce(rn)} children=${rn.childElementCount} iframes=${oe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${Ke} paypalNetRequests=${Mn.value}`),oe.forEach((Ne,Pt)=>{let Oe=(Ne.getAttribute("title")??"").slice(0,40);E(` iframe[${Pt}] ${Ce(Ne)}${Oe?` title="${Oe}"`:""} ${zt(Ne)}`);let $t=pr(Ne);$t&&E(` ${$t}`)}),jn.length===0&&E(" (no PayPal/zoid window errors captured)")};ut.push(setTimeout(()=>J("3s"),3e3)),ut.push(setTimeout(()=>J("8s"),8e3)),ut.push(setTimeout(()=>J("15s"),15e3))},xn(),E("render:start");let We=A.startTiming();bn=setTimeout(()=>{me()||hn||(E("watchdog:11s retryable render timeout"),p("PayPal Buttons render did not settle within 11000ms.",!0))},Xl),ye.render(rn).then(()=>{if(E(`render:resolved inactive=${me()}`),V(),me()){Ot();return}hn=!0,_(!0),Pe(!1),Lt.current?.("ready"),A.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"checkout_render",durationMs:A.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(J=>{let R=J instanceof Error?J.message:"PayPal failed to render.";E(`render:rejected msg=${R.slice(0,120)}`),V(),p(R)})}).catch(d=>{let f=d instanceof Error?d.message:"PayPal SDK failed to load.";E(`loadScript:rejected msg=${f.slice(0,120)}`),p(f)})},0);return()=>{Kt=!0,clearTimeout(nt),gn&&clearTimeout(gn),V(),Ye.current===Y&&(Ye.current=null),Ot()}},[pe,ne,l,k,s,Be,Ze,e,ve,de,A,at,_e,E]);let dr=Xe?$a("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:D?"#fef2f2":"#f3f4f6",border:`1px solid ${D?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ke} failed=${D})`,en.length===0?`
|
|
1
|
+
import{a as _t,b as er,c as La,d as ko,e as Qi,f as es,g as wl,h as kl}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as Ep}from"@flopay/shared";import{PaymentAPI as Pi}from"@flopay/js";import{FloPayError as lo,resolveBillingApiUrl as fd,resolveButtonsLayoutTheme as gd,resolveTheme as hd}from"@flopay/shared";import{useCallback as Pr,useEffect as ao,useMemo as qo,useRef as io,useState as $o}from"react";import{Fragment as Yr,jsx as Fn,jsxs as ts}from"react/jsx-runtime";function Il(){return ts(Yr,{children:[ts("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[Fn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Fn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Fn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:Fn("path",{d:"M9 18l6-6-6-6"})})]})}function El(){return Fn(Yr,{children:"Go back"})}function Rl(){return Fn(Yr,{children:"Secure card checkout"})}function Kr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Vr({content:e}){return Fn(Yr,{children:e===void 0?Fn(Il,{}):e})}function Hr({content:e}){return Fn(Yr,{children:e===void 0?Fn(El,{}):e})}function Io({content:e}){return Fn(Yr,{children:e===void 0?Fn(Rl,{}):e})}import{FloPayError as Na,isMoneySettledOutcome as _l,isSetupIntentClientSecret as Td,isValidEmail as Tl}from"@flopay/shared";function Wr(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()};if(!Tl(l.email))return Promise.reject(new Na("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let s={};for(let[k,g]of Object.entries(l)){if(typeof g!="string")continue;let h=g.trim();h&&(s[k]=h)}return o=e.claimCheckoutSession(t,n,{accountData:s}),o.catch(()=>{}),o}}function ns(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:"checkoutMetadata"in e?{checkoutMetadata:e.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Oa(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function rs(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function Er(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 za(e,t){return t?{...e,...t}:e}function Vt(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 xl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function yr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of xl)if(n.test(t))return r;return e}function Rr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Gr(e){return e?.status==="authorized"||e?.status==="complete"}function os(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Qo(e){let t=os(e);return new Na(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ea(e){let t=os(e);return new Na(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 Eo(e,t){return e==="processing"||_l(e,t)}function as(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function is(e,t="automatic"){return e&&e>0&&Number.isFinite(e)?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async",setupFutureUsage:"off_session"}:{mode:"setup"}}function ss(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Ro(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as ga,SESSION_CREATE_TELEMETRY as Xc}from"@flopay/js";import{buildCheckoutDisplayData as Zc,classifyTelemetryFailure as Gs,FloPayError as Ht,foldIntoProducts as Qc,isDetachedSessionEligible as ed,resolveBillingApiUrl as td,resolveButtonsLayoutTheme as nd,resolveIdempotencyKey as Js,resolveSessionCurrency as rd,resolveTheme as el,SDK_VERSION as tl,telemetryStatusClass as od}from"@flopay/shared";import si,{useCallback as nr,useEffect as rr,useMemo as Ln,useRef as Bt,useState as Ft}from"react";import{createContext as ls}from"react";var Dn=ls({flopay:null,paypalFlopay:null,billingApiUrl:""}),Hn=ls({session:null,loading:!1,error:null});import{PaymentAPI as $a}from"@flopay/js";import{classifyTelemetryFailure as Yl,FloPayError as ys,generateIdempotencyKey as Wl,isValidEmail as Mo,normalizeGatewayEnvironment as Gl,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as ja,SDK_VERSION as Jl}from"@flopay/shared";import{loadScript as Xl}from"@paypal/paypal-js";import{useCallback as Ao,useEffect as Et,useMemo as Bo,useRef as Ze,useState as Tr}from"react";import{isValidEmail as Ml}from"@flopay/shared";import{useCallback as cs,useEffect as Al,useRef as ds,useState as ps}from"react";import{jsx as us,jsxs as _o}from"react/jsx-runtime";function Sn(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),a=n?.trim();return{...r,...o?{firstName:o}:{},...a?{lastName:a}:{}}}function Jr(){let[e,t]=ps(null),n=ds(null),r=ds(0),o=cs((l,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:s}),new Promise(k=>{n.current=k})),[]),a=cs(l=>{let s=n.current;n.current=null,t(null),s?.(l)},[]);return Al(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Xr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,s]=ps(e.email?.trim()??""),k=Ml(l.trim());return _o("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:[_o("div",{style:{fontWeight:700},children:["Continue with ",t]}),_o("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",us("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:g=>s(g.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),_o("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&us("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),_o("button",{type:"button",disabled:!k||o,onClick:()=>{n(Sn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Bl(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 _r(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function ar(e){if(typeof e!="object"||e===null)return;let t=e;return _r(t.code)??_r(t.type)??_r(t.name)}function Zr(e){if(!(typeof e!="object"||e===null))return _r(e.decline_code)}function To(e){return typeof e!="object"||e===null?!1:_r(e.type)?.toLowerCase()==="card_error"||Zr(e)!==void 0}function fr(e){let t=Bl(e)?.toLowerCase()??"",r=`${ar(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Fl}from"@flopay/shared";import{useContext as ta}from"react";function gr(){return ta(Dn).flopay}function Ua(){return ta(Dn).paypalFlopay??null}function Dl(){return ta(Hn)}function ms(){return ta(Dn).billingApiUrl||Fl()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Ol}from"@flopay/shared";import{useCallback as zl,useRef as na}from"react";import{useEffect as Ll,useLayoutEffect as Nl}from"react";var xo=typeof window>"u"?Ll:Nl;var Ul={"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 ql(e){return e==="stripe"||e==="paypal"?e:void 0}function $l(e){let t=ql(e.provider),n={schemaVersion:Ol,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Ul[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 qa=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Qr(e,t){let n=na(e);n.current=e;let r=na(new Set),o=na(t),a=na(t);return xo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),zl(l=>{if(a.current!==t)return;let s=$l(l);if(s){if(qa.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}_t(()=>n.current?.(s))}},[t])}var jl=Symbol.for("@flopay/js.telemetry.bridge.v1"),Kl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Vl(){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 Hl(e){let t=Vl(),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 ra(e){let t=globalThis[Kl];return Hl(t?.(e)??{})}function jt(e){if(e)return e[jl]}import{jsx as xr,jsxs as Ka}from"react/jsx-runtime";var oa=45,Zl=1e3,Ql=11e3,ec=["https://www.paypal.com","https://www.sandbox.paypal.com"],fs="We couldn't open PayPal. Try again or choose another payment method.",tc={width:"100%",minHeight:oa,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 gs(e){return e.includes("No ack for postMessage init()")&&ec.some(t=>e.includes(t))&&e.includes("10000ms")}function nc(e){return e?`${fs} Allow pop-ups for this site, then try again.`:fs}function rc(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 hs({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:s,currency:k,isSubscription:g,providerObjectType:h,onTokenizedBody:b,onComplete:T,onErrorChange:M,onDecline:u,onTechnicalFailure:I,isProcessing:he=!1,onLoadStateChange:j,onInitializationStateChange:S,allowAutomaticRetry:pe=!0,onButtonClick:Z,runBeforeButtonClick:se,session:ae,existingOrderId:ve,telemetry:tt,telemetryContext:be,onInstrument:Dt,debug:Qe=!1}){let xe=gr(),Me=Qr(Dt,e),ee=Bo(()=>{if(xe)return null;let w=ra({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Jl,enabled:tt!==!1});return w.setCheckoutContext(be??{}),w.beginCheckout(be??{}),w},[n,xe,tt,be?.checkoutMode,be?.layout]),Q=Bo(()=>jt(xe),[xe]);Et(()=>()=>{ee&&ee.flush().catch(()=>{}).finally(()=>ee.destroy())},[ee]);let A=Bo(()=>({error:w=>{Q?Q.error(w):ee?.error(w),Me({class:"technical_error",errorCode:w.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":w.errorCode,requestCategory:w.requestCategory,provider:w.provider})},log:w=>{Q?Q.log(w):ee?.log(w),Me({class:"lifecycle",name:w.name,provider:w.provider})},performance:w=>{Q?Q.performance(w):ee?.performance(w)},terminal:w=>{Q?Q.terminal(w):ee?.terminal(w)},startTiming:()=>Q?.now()??ee?.now()??0,elapsed:w=>Q?.elapsed(w)??Math.max(0,(ee?.now()??w)-w)}),[Me,Q,ee]),Be=Ze(null),Fe=Ze(0),De=Ze(null),ze=Ze(!1),[ke,_]=Tr(!1),[ce,Pe]=Tr(!1),[de,K]=Tr(0),Ie=Ze(0),[at,ht]=Tr(!1),Ue=Ze(!1),V=Ze(!1),[D,B]=Tr(!1),[qe,He]=Tr(!1),{request:ie,collect:it,finish:v}=Jr(),P=Ze({sessionId:e,required:!Mo(r?.trim()||ae?.customer?.email?.trim())});P.current.sessionId!==e&&(P.current={sessionId:e,required:!Mo(r?.trim()||ae?.customer?.email?.trim())});let Re=P.current.required,ne=Bo(()=>n.replace(/\/+$/,""),[n]),nt=ae?.gateways?.paypal?.providerObjectType??h,Ae=nt??(g?"subscription":"order"),Ye=nt==="order"||nt==="setup_token",Mt=Bo(()=>JSON.stringify([ne,l,k,s??"",Ae,Ye,e,ve??""]),[ne,l,k,s,ve,Ae,Ye,e]),C=Ze(Mt),U=C.current!==Mt,st=Ze(Qe),We=Ze(null),[tn,Wt]=Tr([]),E=Ao(w=>{st.current&&Wt(ct=>[...ct,`${new Date().toISOString().slice(11,23)} ${w}`])},[]);Et(()=>{st.current=Qe,Qe&&E("debug:enabled"),We.current?.setEnabled(Qe)},[E,Qe]);let mt=Ze(b),Tt=Ze(T),lt=Ze(M),Rt=Ze(u),pn=Ze(I),an=Ze(Z),mn=Ze(j),Lt=Ze(S),wn=Ze(a),Gt=Ze(se),yt=Ze(ae),Ge=Ze(r),ft=Ze(o),sn=Ze(t),et=Ze(null),Wn=Ze(0),dt=Ze(null),nn=Ze(null),bt=Ze(new Map),Jt=Ze(new Map),kn=Ze(!1);Et(()=>(kn.current=!0,()=>{kn.current=!1}),[]),Et(()=>{mt.current=b},[b]),Et(()=>{wn.current=a},[a]),Et(()=>{Tt.current=T},[T]),Et(()=>{lt.current=M},[M]),Et(()=>{Rt.current=u},[u]),Et(()=>{pn.current=I},[I]),Et(()=>{an.current=Z},[Z]),Et(()=>{mn.current=j},[j]),Et(()=>{Lt.current=S},[S]),Et(()=>{Gt.current=se},[se]),Et(()=>{yt.current=ae},[ae]),Et(()=>{Ge.current=r},[r]),Et(()=>{ft.current=o},[o]),Et(()=>{sn.current=t},[t]),Et(()=>{Ie.current=de},[de]),Et(()=>{at&&De.current?.focus()},[at,de]);let yn=Ao(()=>{window.setTimeout(()=>{De.current?.focus()},0)},[]),_n=Ao(()=>{_(!1),K(w=>w+1)},[]),ln=Ao(()=>{ht(!1),(Be.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Be.current)?.focus?.()},[]);Et(()=>{!ke||!ze.current||(ze.current=!1,ln())},[ln,ke,de]);let Tn=Ao((w,ct)=>{let Kt=pn.current;if(Kt){Kt("paypal",w,ct);return}lt.current?.(nc(ct?.popupBlocked??fr(w)))},[]),qt=()=>{dt.current?.timer&&(clearTimeout(dt.current.timer),dt.current.timer=null)},G=()=>{qt();let w=Wn.current+1;return Wn.current=w,nn.current=null,dt.current={generation:w,timer:null,yieldedControl:!1},ht(!1),w},fn=w=>w!==void 0&&dt.current?.generation!==w?!1:(qt(),dt.current=null,nn.current=null,!0),Nn=w=>{let ct=w?.generation??dt.current?.generation??Wn.current;(!w?.generation||dt.current?.generation===ct)&&(qt(),dt.current=null),nn.current=ct,w?.showRetry&&ht(!0),w?.remount&&_n(),w?.focus!==!1&&yn()},Gn=w=>dt.current?.generation===w&&nn.current!==w,Cr=w=>{typeof document<"u"&&document.visibilityState!=="visible"||(qt(),w.timer=setTimeout(()=>{dt.current?.generation===w.generation&&(dt.current=null,nn.current=w.generation,Tn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),ht(!0),_n(),yn())},600))},Sr=()=>{let w=dt.current;w?.yieldedControl&&Cr(w)},cr=()=>{let w=dt.current;w&&(w.yieldedControl=!0,qt())},Nt=w=>{let ct=et.current;return ct&&Jt.current.set(w,ct),w};Et(()=>{let w=()=>{document.visibilityState==="visible"?Sr():cr()};return document.addEventListener("visibilitychange",w),window.addEventListener("focus",Sr),window.addEventListener("blur",cr),()=>{document.removeEventListener("visibilitychange",w),window.removeEventListener("focus",Sr),window.removeEventListener("blur",cr),qt()}},[]),Et(()=>{C.current!==Mt&&(C.current=Mt,Ue.current=!1,V.current=!1,_(!1),Pe(!1),B(!1),Lt.current?.("loading"))},[Mt]),Et(()=>{_t(()=>mn.current?.(ke&&!D))},[ke,D]);let $e=Gl(s);Et(()=>{let w=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",ct=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(E(`mount clientId=${w} env=${s??"(unset)"}\u2192${$e??"live"} ccy=${k} sub=${g}`),E(`ua=${ct.slice(0,80)}${ct.length>80?"\u2026":""}`),!l){E("FAIL: clientId empty \u2014 gateway misconfigured"),B(!0),A.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(!Be.current){E("FAIL: containerRef not attached");return}Fe.current=A.startTiming(),A.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Kt=!1,In=!1,me=()=>Kt||In,cn,wr=!1,Lr=()=>{cn=Wl(),cn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),wr=!0},gn=null,ur=!1,Jn=null,On=!1,Ot=()=>{!Jn||On||(On=!0,Jn.close().catch(()=>{}))},zn=null,Xn=()=>{zn!==null&&(A.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"overlay_return",durationMs:A.elapsed(zn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),zn=null)},hn=!1,rn=Be.current,Un=null,qn=null,ut=[],bn=null,vn=!1,$n=!1,xn=null,Ce=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let d=m.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},on=m=>{if(!m)return"(empty)";try{let d=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),f=d.pathname.toLowerCase();return f.includes("checkcaptcha")||f.includes("captcha")?`CAPTCHA(${d.host}${f})`:f.includes("risk")||f.includes("challenge")?`RISK(${d.host}${f})`:f.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${f}`.slice(0,100)}catch{return m.slice(0,80)}},zt=m=>{let d=m.getAttribute("src"),f=m.getAttribute("srcdoc"),ye=m.getAttribute("name"),re=m.getAttribute("sandbox"),je=[];return d&&je.push(`src=${on(d)}`),f&&je.push(`srcdoc[${f.length}ch]`),!d&&!f&&je.push("src=(empty) srcdoc=(empty)"),ye&&je.push(`name=${ye.slice(0,40)}`),re!==null&&je.push(`sandbox="${re.slice(0,40)}"`),je.join(" ")},pr=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let d=m.contentDocument;if(!d)return"cd=null";let f=d.body?.children.length??0,ye=d.body?.innerHTML.length??0,re=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${f}children,${ye}ch] head[${re}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},jn=[],mr=m=>{if(me())return;let d=m.message??String(m.error??"(no message)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(E(`window:error ${d.slice(0,140)}`),jn.push(d))},En=m=>{if(me())return;let d=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(E(`window:rejection ${d.slice(0,140)}`),jn.push(d))},Mn={value:0},Ut=()=>{for(Un?.disconnect(),Un=null,qn?.disconnect(),qn=null;ut.length;)clearTimeout(ut.pop());$n=!1,vn&&typeof window<"u"&&(window.removeEventListener("error",mr),window.removeEventListener("unhandledrejection",En)),vn=!1},x=()=>{if(!(vn||me()||hn)){if(vn=!0,jn.length=0,Mn.value=0,typeof window<"u"&&(window.addEventListener("error",mr),window.addEventListener("unhandledrejection",En)),typeof PerformanceObserver<"u")try{qn=new PerformanceObserver(m=>{if(!me())for(let d of m.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;Mn.value+=1;let f=Math.round(d.duration);E(`net ${f}ms ${d.name.slice(0,90)}`)}}),qn.observe({type:"resource",buffered:!0})}catch{}xn?.()}},L=()=>{bn&&(clearTimeout(bn),bn=null)},H=()=>{Ut(),L()},Y={setEnabled:m=>{m?x():Ut()}};We.current=Y,st.current&&x();let Se=m=>{if(!m)return!1;let d=m.toLowerCase();return d.includes("zoid destroyed")||d.includes("destroyed all components")||d.includes("window closed")||d.includes("detected container element removed")},F=m=>{if(me()||Se(m))return;let d=yr(m)??m;_t(()=>lt.current?.(d))},q=m=>{Kt||(B(!0),m.includes("paypal_ineligible")||A.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:",m))},p=(m,d=!1)=>{if(Kt)return;let f=Ue.current||!pe;if(ur)return;ur=!0,In=!0,H(),Ot();let ye=d||gs(m);if(ye&&pe&&!Ue.current){Ue.current=!0,_(!1),He(!1),Pe(!0),Lt.current?.("retrying"),gn=setTimeout(()=>{Kt||K(re=>re+1)},Zl);return}if(ye||f){if(_(!1),He(!1),Pe(!1),B(!0),Lt.current?.("exhausted"),!V.current){V.current=!0;let re=gs(m)?"paypal_init_timeout":d?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",re)}return}q(m)};B(!1);let O=async(m,d=et.current)=>{if(me())return;let f=d?.sessionId??e;if(mt.current){await mt.current(m,{sessionId:f,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let ye=A.startTiming();A.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let re=()=>{A.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"processing",durationMs:A.elapsed(ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let je=yt.current,Je=d?.accountPatch?.email??Ge.current,J=d?.accountPatch?.userId??je?.customer?.id??je?.accountData?.userId??"",R=d?.accountPatch?.firstName??je?.customer?.firstName??je?.accountData?.firstName,oe=d?.accountPatch?.lastName??je?.customer?.lastName??je?.accountData?.lastName,Le=await new $a(ne,{telemetry:!1}).processPayment(J,{sessionId:f,nonce:d?.nonce??sn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:J,email:Je??je?.customer?.email??"",...R?{firstName:R}:{},...oe?{lastName:oe}:{},country:d?.accountPatch?.country??je?.customer?.country??je?.accountData?.country??void 0,zip:d?.accountPatch?.zip??je?.customer?.zip??je?.accountData?.zip??void 0}});if(Le.ok){if(In||Kt&&kn.current)return;re(),A.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),_t(()=>Tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(me())return;let Pt=await Le.json().catch(()=>null),Ne=Pt?.message??"PayPal payment failed.",$t=yr(Ne)??Ne;re(),Le.status===400&&(typeof Pt?.declineCode=="string"||!Array.isArray(Pt?.fields))?A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Le.status===400||Le.status===422?A.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):A.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Le.status>=500?"5xx":Le.status>=400?"4xx":Le.status>=300?"3xx":"unknown",failureCategory:Le.status>=500?"server_error":void 0}),F($t),_t(()=>Rt.current?.(Vt("paypal",$t,{code:Pt?.code,declineCode:Pt?.declineCode})));return}catch(je){if(me())return;re(),A.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Je=je instanceof Error?je.message:"PayPal payment failed.",J=yr(Je)??Je;F(J),_t(()=>Rt.current?.(Vt("paypal",J)));return}},$=()=>new ys("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),gt=m=>me()?Promise.reject($()):Promise.resolve(m),vt=async m=>{if(me())throw $();wr||Lr();let d=et.current,f=d?.sessionId??e,ye=d?.nonce??sn.current;A.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let re;try{re=await new $a(ne,{telemetry:!1}).createSessionIntent(f,ye??"",Ye?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:ja,paymentMethodId:null,intentKind:Ae==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:cn})}catch(je){throw A.error({...Yl(je,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),je}if(me())throw $();if(re.provider!=="paypal"||re.providerObjectType!==Ae)throw new Error(m);return A.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),re.providerObjectId},te=(m,d)=>{let f=d?.nonce??sn.current;if(!f)return;let ye=d?.sessionId??e,re=Zr(m)??ar(m)??"provider_declined";new $a(ne,{telemetry:!1}).reportSessionIntentDecline(ye,f,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:re}).catch(()=>{})},we=de;E("loadScript:scheduled (deferred 1 tick)");let Xt=null,rt=setTimeout(()=>{if(Kt){E("loadScript:skipped (cancelled before defer ran)");return}E("loadScript:start");let m=$e==="live"?"production":$e;Xt=Xl({clientId:l,currency:k,...Ae==="subscription"?{intent:"subscription",vault:!0}:Ae==="order"?{intent:"capture"}:{},...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Xt.then(d=>{if(E(`loadScript:resolved inactive=${me()} ns=${!!d} buttons=${!!d?.Buttons}`),me())return;if(!d?.Buttons){E("FAIL: namespace missing Buttons factory"),p("PayPal SDK did not expose the Buttons factory.");return}A.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"provider_ready",durationMs:A.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let f=async(J,R)=>{if(me()||Ie.current!==we)return;let oe=J.vaultSetupToken??J.subscriptionID??J.orderID??"",Ke=oe?Jt.current.get(oe):bt.current.get(we);if(!(!Ke||!Gn(Ke.generation))&&fn(Ke.generation)){Jt.current.delete(oe),bt.current.delete(Ke.surfaceKey),Xn();try{if(He(!0),_t(()=>lt.current?.(null)),!oe)throw new ys("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Le=yt.current,Pt=Er(ft.current??[Le?.customer?.firstName,Le?.customer?.lastName].filter(Boolean).join(" ")),Ne=Sn({email:Ke.accountPatch?.email?.trim()||Ge.current?.trim()||Le?.customer?.email?.trim(),firstName:Ke.accountPatch?.firstName?.trim()||Pt.firstName,lastName:Ke.accountPatch?.lastName?.trim()||Pt.lastName});if(!Mo(Ne.email)||!(Ne.firstName||Ne.lastName))try{let $t=rc(await R?.order?.get?.());Ne=Sn({email:$t.email||Ne.email,firstName:$t.firstName||Ne.firstName,lastName:$t.lastName||Ne.lastName})}catch{}if((wn.current||Re)&&!Mo(Ne.email)){let $t=await it("PayPal",Ne);if(!$t)return;Ne=$t}Mo(Ne.email)&&(Ke.accountPatch=Sn({...Ke.accountPatch,...Ne}),await wn.current?.(Ne)),await O(Ae==="setup_token"?{id:oe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:ja}:Ye?{id:oe,isPaypal:!0,gateway:"paypal",paymentMethodType:ja}:{id:oe,isPaypal:!0},Ke)}catch(Le){F(Le instanceof Error?Le.message:"PayPal capture failed.")}finally{me()||He(!1)}}},ye=d.Buttons({style:{layout:"horizontal",height:oa,tagline:!1},onClick:async(J,R)=>{if(me()){await R.reject();return}Lr();let oe=Gt.current,Ke={};if(oe)try{let Ne=await oe("paypal");if(me()){await R.reject();return}if(!Ne.proceed){et.current=null,bt.current.delete(we),await R.reject();return}Ke={sessionId:Ne.sessionId,accountPatch:Ne.accountPatch,nonce:Ne.nonce}}catch(Ne){E(`onClick:runBeforeButtonClick rejected msg=${(Ne instanceof Error?Ne.message:String(Ne)).slice(0,120)}`),et.current=null,bt.current.delete(we),await R.reject();return}_t(()=>an.current?.("paypal"));let Pt={generation:G(),surfaceKey:we,...Ke};et.current=Pt,bt.current.set(we,Pt),await R.resolve(),A.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),A.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),zn=A.startTiming()},createOrder:Ae==="order"?ve?()=>gt(ve).then(Nt):()=>vt("Failed to create PayPal order.").then(Nt):void 0,createSubscription:Ae==="subscription"?ve?()=>gt(ve).then(Nt):()=>vt("Failed to create PayPal subscription.").then(Nt):void 0,createVaultSetupToken:Ae==="setup_token"?()=>vt("Failed to create PayPal setup token.").then(Nt):void 0,onApprove:f,onCancel:()=>{if(me())return;let J=bt.current.get(we)??et.current;J&&bt.current.delete(J.surfaceKey),et.current=null,Xn(),A.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ze.current=!0,Nn({generation:J?.generation,remount:!0,focus:!1})},onError:J=>{if(me()||Ie.current!==we)return;let R=J instanceof Error?J.message:"PayPal failed to render.";if(E(`onError rendered=${hn} msg=${R.slice(0,120)}`),hn){let oe=bt.current.get(we)??et.current;if(oe&&!Gn(oe.generation)||!oe&&nn.current===Wn.current)return;if(Se(R)){fn(oe?.generation);return}if(Xn(),To(J)){A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),te(J,oe),_t(()=>Rt.current?.(Vt("paypal",R))),oe&&bt.current.delete(oe.surfaceKey),et.current=null,fn(oe?.generation);return}let Ke=R.toLowerCase();A.error({errorCode:Ke.includes("popup")&&Ke.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),oe&&bt.current.delete(oe.surfaceKey),et.current=null,Nn({generation:oe?.generation,remount:!0,showRetry:!0,focus:!0}),Tn(J,{code:"paypal_runtime_failed"});return}p(R)}}),re=ye.isEligible();if(E(`isEligible=${re}`),A.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!re){_(!1),p("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Jn=ye,xn=()=>{if(!vn||$n||me()||hn)return;$n=!0,E(`container:dims ${Ce(rn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),typeof MutationObserver<"u"&&(Un=new MutationObserver(R=>{if(!me()){for(let oe of R)if(oe.type==="childList")oe.addedNodes.forEach(Ke=>{if(!(Ke instanceof Element))return;let Le=Ke.tagName.toLowerCase(),Pt=(Ke.getAttribute("title")??"").slice(0,40),Ne=Le==="iframe"?` ${zt(Ke)}`:"";E(`child+ ${Le}${Pt?` title="${Pt}"`:""}${Ne} dims=${Ce(Ke)}`)});else if(oe.type==="attributes"&&oe.target instanceof Element){let Ke=oe.target;if(Ke.tagName.toLowerCase()!=="iframe")continue;let Le=oe.attributeName;(Le==="src"||Le==="srcdoc")&&E(`attr~ iframe ${Le}=${Le==="srcdoc"?`[${(Ke.getAttribute("srcdoc")??"").length}ch]`:on(Ke.getAttribute("src"))} dims=${Ce(Ke)}`)}}}),Un.observe(rn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let J=R=>{if(me()||hn)return;let oe=rn.querySelectorAll("iframe"),Ke=typeof document<"u"&&"hasStorageAccess"in document;E(`watchdog:${R} container=${Ce(rn)} children=${rn.childElementCount} iframes=${oe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${Ke} paypalNetRequests=${Mn.value}`),oe.forEach((Le,Pt)=>{let Ne=(Le.getAttribute("title")??"").slice(0,40);E(` iframe[${Pt}] ${Ce(Le)}${Ne?` title="${Ne}"`:""} ${zt(Le)}`);let $t=pr(Le);$t&&E(` ${$t}`)}),jn.length===0&&E(" (no PayPal/zoid window errors captured)")};ut.push(setTimeout(()=>J("3s"),3e3)),ut.push(setTimeout(()=>J("8s"),8e3)),ut.push(setTimeout(()=>J("15s"),15e3))},xn(),E("render:start");let Je=A.startTiming();bn=setTimeout(()=>{me()||hn||(E("watchdog:11s retryable render timeout"),p("PayPal Buttons render did not settle within 11000ms.",!0))},Ql),ye.render(rn).then(()=>{if(E(`render:resolved inactive=${me()}`),H(),me()){Ot();return}hn=!0,_(!0),Pe(!1),Lt.current?.("ready"),A.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),A.performance({stage:"checkout_render",durationMs:A.elapsed(Je),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(J=>{let R=J instanceof Error?J.message:"PayPal failed to render.";E(`render:rejected msg=${R.slice(0,120)}`),H(),p(R)})}).catch(d=>{let f=d instanceof Error?d.message:"PayPal SDK failed to load.";E(`loadScript:rejected msg=${f.slice(0,120)}`),p(f)})},0);return()=>{Kt=!0,clearTimeout(rt),gn&&clearTimeout(gn),H(),We.current===Y&&(We.current=null),Ot()}},[pe,ne,l,k,s,Ae,Ye,e,ve,de,A,it,Re,E]);let dr=Qe?Ka("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:D?"#fef2f2":"#f3f4f6",border:`1px solid ${D?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ke} failed=${D})`,tn.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return D&&!U?Xe?xr("div",{children:dr}):null:$a("div",{children:[dr,ie&&xr(Gr,{identity:ie.identity,methodLabel:ie.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:S,onCancel:()=>S(null)}),$a("div",{"aria-hidden":ce||ie?!0:void 0,style:ce||ie?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:oa},children:[!ke&&!ce&&xr("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"}}),xr("div",{ref:Fe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:oa,display:"flex",opacity:ke?1:0},"aria-busy":Ee||he},de)]},de),ot&&xr("button",{ref:Le,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:ln,style:Ql,children:"Try PayPal again"})]})}function aa(e){return xr(fs,{...e})}function gs(e){return xr(fs,{...e})}import{jsx as hs,jsxs as nc}from"react/jsx-runtime";function Zr({children:e,margin:t,icon:n=!0,styleOverride:r}){return nc("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&&hs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:hs("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 rc}from"@flopay/shared";import{useEffect as hr,useMemo as oc,useRef as bs,useState as vs}from"react";import{jsx as ac}from"react/jsx-runtime";function ia({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=vs(e instanceof Promise?null:e),[s,k]=vs(t instanceof Promise||!t?null:t),g=bs(null),h=bs(null),b=Xr(r);hr(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),hr(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),hr(()=>{if(a)return jt(a)?.subscribe?.(b)},[b,a]),hr(()=>{if(!(!s||s===a))return jt(s)?.subscribe?.(b)},[b,a,s]),hr(()=>{if(!a)return;let u=jt(a);return g.current=u?.beginCheckout()??u?.now()??0,u?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{u?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),hr(()=>{let u=!1;return e instanceof Promise?e.then(I=>{u||l(I)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{u=!0}},[b,e]),hr(()=>{let u=!1;if(!t){k(null);return}return t instanceof Promise?t.then(I=>{u||k(I)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):k(t),()=>{u=!0}},[b,t]),hr(()=>{if(!a||h.current===a)return;h.current=a;let u=jt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(g.current??0),durationMode:"machine"})},[b,a]);let T=rc(n?.billingApiUrl),M=oc(()=>({flopay:a,paypalFlopay:s,billingApiUrl:T,emitInstrument:b}),[a,s,T,b]);return ac(Dn.Provider,{value:M,children:o})}var sa="flopay_recent_completion_";function Qr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(sa+e,JSON.stringify(t))}catch{}}function Ka(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(sa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(sa+e),!1):!0}catch{return!1}}import{loadFloPay as Ps,PaymentAPI as Ss}from"@flopay/js";import{classifyPaymentRejection as ic,FloPayError as Ct,isAuthorizationOnlySession as sc,isSetupIntentClientSecret as lc,normalizeCheckoutFailureOutcome as Cs}from"@flopay/shared";var Bo="card";async function cc(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function dc(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Va(e,t){return Object.assign(e,{checkoutMethod:t})}function ir(e,t){let n=e instanceof Ct?e:new Ct(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 Ao(e,t){try{return await e()}catch(n){throw ir(n,t)}}function ws(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 uc(e){return e.status==="succeeded"||e.status==="declined"}async function ks(e){if(typeof document>"u"||typeof window>"u")throw new Ct("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ct("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 h=new AbortController,b=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",b);let T=window.setTimeout(()=>h.abort(),r);try{let M=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!M.ok)return{status:"unknown"};let u=await M.json().catch(()=>null);return pc(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(T),e.signal?.removeEventListener("abort",b)}},l=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let k=document.createElement("iframe");k.setAttribute("title","Card authentication"),k.setAttribute("allow","payment"),k.tabIndex=0,k.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(";"),k.src=e.nextActionRedirectUrl,s.appendChild(k),document.body.appendChild(s),k.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let h=await new Promise((b,T)=>{let M=!1,u=0,I=0,he=0,j=!1,C=()=>{window.clearTimeout(u),window.clearInterval(I),window.clearTimeout(he),window.removeEventListener("message",ae),k.removeEventListener("load",Z),e.signal?.removeEventListener("abort",se)},pe=async()=>{if(!(M||j)){j=!0;try{let ve=await a();if(M||!uc(ve))return;M=!0,C(),b(ve)}finally{j=!1}}},Z=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{pe()},250)},se=()=>{M||(M=!0,C(),T(new Ct("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=ve=>{if(ve.source!==k.contentWindow||g&&ve.origin!==g)return;let et=ve.data;!et||typeof et!="object"||et.source!=="flopay-vault-3ds-return"||M||(M=!0,C(),b(null))};u=window.setTimeout(()=>{M||(M=!0,C(),T(new Ct("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),I=window.setInterval(()=>{pe()},n),k.addEventListener("load",Z),window.addEventListener("message",ae),e.signal?.addEventListener("abort",se),e.signal?.aborted&&se()});return h||await a()}finally{s.parentNode?.removeChild(s),l?.isConnected&&l.focus()}}function pc(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 br(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=yr(o)??o;return Va(new Ct(a,"api_error",{code:Cs(e?.outcome)??Cs(e?.type)??e?.gatewayErrorCode}),r)}function Ha(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function la(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Is(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||la(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||la(s)))return s;let l=o.gateways;if(l&&typeof l=="object"){let s=l.stripe;if(s&&typeof s=="object"){let k=s,g=[k.stripeClientSecret,k.clientSecret];for(let h of g)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||la(h)))return h}}}}async function mc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Is(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(la(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function eo({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let s=e.replace(/\/+$/,""),k=t??n.id,g=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",T=n.customer?.firstName??n.accountData?.firstName??"",M=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,I=n.customer?.zip??n.accountData?.zip??void 0,j=await new Ss(s,l===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:k,nonce:g,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:b,firstName:T,lastName:M,country:u,zip:I},returnUrl:a??Ha(n)});if(j.ok){let Z=typeof j.json=="function"?await j.json().catch(()=>null):null;return sc(n)||Z?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Z?.paymentId=="string"?Z.paymentId:n.paymentId,sessionId:typeof Z?.sessionId=="string"?Z.sessionId:k,authorizationExpiresAt:typeof Z?.authorizationExpiresAt=="string"?Z.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Io(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Io(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let C;try{C=await j.json()}catch{throw new Ct("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status})}if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let Z=Is(C);if(!Z)throw new Ct("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status});return{type:C.type,threeDSecureToken:Z,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let Z=await mc({billingApiUrl:s,sessionId:k,nonce:g,responseJson:C});if(Z)return Z;throw Va(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let pe=new Ct(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:j.status});throw Object.assign(pe,{telemetryOutcome:ic(j.status,C)})}async function ca(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:k}){let g=t?.getRawProvider();if(!g)throw ir(new Ct("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Va(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=lc(e.threeDSecureToken),b=null,T=e.paymentMethodId,M=await Ao(()=>cc(g,e.threeDSecureToken,h),"card");if(M){if(M.error)throw ir(new Ct(M.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let I=M.intent;!T&&I?.payment_method&&(typeof I.payment_method=="string"?T=I.payment_method:"id"in I.payment_method&&(T=I.payment_method.id??void 0))}let u=T?await Ao(()=>dc(g,e.threeDSecureToken,{payment_method:T,return_url:s??Ha(l)??window.location.href},h),"card"):null;if(u){if(u.error)throw ir(new Ct(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");b=u.intent}else{let I=await Ao(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(I.error)throw ir(new Ct(I.error.message??"3DS authentication failed.","api_error",{code:I.error.code}),"card");b=(h?I.setupIntent:I.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let I=await eo({billingApiUrl:o,sessionId:a,session:l,telemetry:k,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:s});return I.type==="success"?{...I.result,paymentIntentId:I.result.paymentIntentId??b.id,paymentMethodId:I.result.paymentMethodId??T}:ca(I,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:k})}throw ir(new Ct("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw ir(new Ct("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:T}=await Ao(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(T)throw ir(new Ct(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Ao(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Ha(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw ir(new Ct(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ct("Unsupported payment redirect state.","api_error")}function Fo(e){if(e instanceof Ct){let r=yr(e.message);return r&&r!==e.message?Object.assign(new Ct(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=yr(t)??t;return new Ct(n,"api_error")}function da(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ct("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 ua({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[l,s]=await Promise.all([Ps(e,{billingApiUrl:n,locale:r,telemetry:o}),a?Ps(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(k=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",k),null)):Promise.resolve(null)]);return{flopay:l,paypalFlopay:t?a?s:l:null}}import{PaymentAPI as to,toStripeAppearance as yc}from"@flopay/js";import{COUNTRY_OPTIONS as fc,classifyPaymentRejection as gc,FloPayError as Yn,filterStripeMethodsByCountry as hc,getPostalCodeExample as bc,getPostalCodeLabel as Za,getStateFromPostalCode as _s,getStateLabel as Ya,getStateOptions as vc,getStripeMethodDisplayName as Fr,hasVendoredStripeMethodLogo as Pc,isAuthorizationOnlySession as Wa,isAVSFieldVisible as He,isPostalCodeSupported as Cc,isSetupIntentClientSecret as Sc,isValidEmail as Qt,isValidPostalCode as wc,needsStripeMethodExplicitConfirm as Ts,normalizeCheckoutFailureOutcome as kc,partitionStripeMethods as Ic,resolveAVSConfig as Ec,resolveButtonsLayoutTheme as Rc,resolveStripeMethodBrandVariant as _c,resolveTheme as Tc,stripeExpressMethodToOptionKey as xs}from"@flopay/shared";import{ExpressCheckoutElement as zs,PaymentElement as xc,Elements as Ar,useElements as ti,useStripe as ni}from"@stripe/react-stripe-js";import Mc,{useCallback as ge,useContext as no,useEffect as wt,useMemo as St,useRef as fe,useState as ue}from"react";function Es(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 Rs={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as Br,jsx as c,jsxs as xe}from"react/jsx-runtime";var tr="flopay_stripe_resume",Ms="flopay_wallet_resume",Us="fw1",Ac=300*1e3,Bc=900,Fc=25e3,Ga={};function qs(e){return e instanceof Yn&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ma(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new to(e).createSessionIntent(...n)}catch(o){throw qs(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Do="flopay_paypal_resume",Dc=250,As="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ri(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ya({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new to(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Lc(e){return e instanceof Yn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ja(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function $s({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=Er(r?.name),a=Er(n);return Sn({email:(Qt(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:a.firstName??o.firstName,lastName:a.lastName??o.lastName})}async function Nc({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=$s({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return Qt(l.email)?l:a(o,l)}var Oc=`
|
|
3
|
+
${tn.join(`
|
|
4
|
+
`)}`]}):null;return D&&!U?Qe?xr("div",{children:dr}):null:Ka("div",{children:[dr,ie&&xr(Xr,{identity:ie.identity,methodLabel:ie.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:v,onCancel:()=>v(null)}),Ka("div",{"aria-hidden":ce||ie?!0:void 0,style:ce||ie?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:oa},children:[!ke&&!ce&&xr("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"}}),xr("div",{ref:Be,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:oa,display:"flex",opacity:ke?1:0},"aria-busy":qe||he},de)]},de),at&&xr("button",{ref:De,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:ln,style:tc,children:"Try PayPal again"})]})}function aa(e){return xr(hs,{...e})}function bs(e){return xr(hs,{...e})}import{jsx as vs,jsxs as oc}from"react/jsx-runtime";function eo({children:e,margin:t,icon:n=!0,styleOverride:r}){return oc("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&&vs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:vs("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 ac}from"@flopay/shared";import{useEffect as hr,useMemo as ic,useRef as Ps,useState as Cs}from"react";import{jsx as sc}from"react/jsx-runtime";function ia({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=Cs(e instanceof Promise?null:e),[s,k]=Cs(t instanceof Promise||!t?null:t),g=Ps(null),h=Ps(null),b=Qr(r);hr(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),hr(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),hr(()=>{if(a)return jt(a)?.subscribe?.(b)},[b,a]),hr(()=>{if(!(!s||s===a))return jt(s)?.subscribe?.(b)},[b,a,s]),hr(()=>{if(!a)return;let u=jt(a);return g.current=u?.beginCheckout()??u?.now()??0,u?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{u?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),hr(()=>{let u=!1;return e instanceof Promise?e.then(I=>{u||l(I)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{u=!0}},[b,e]),hr(()=>{let u=!1;if(!t){k(null);return}return t instanceof Promise?t.then(I=>{u||k(I)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):k(t),()=>{u=!0}},[b,t]),hr(()=>{if(!a||h.current===a)return;h.current=a;let u=jt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(g.current??0),durationMode:"machine"})},[b,a]);let T=ac(n?.billingApiUrl),M=ic(()=>({flopay:a,paypalFlopay:s,billingApiUrl:T,emitInstrument:b}),[a,s,T,b]);return sc(Dn.Provider,{value:M,children:o})}var sa="flopay_recent_completion_";function to(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(sa+e,JSON.stringify(t))}catch{}}function Ha(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(sa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(sa+e),!1):!0}catch{return!1}}import{loadFloPay as Ss,PaymentAPI as ks}from"@flopay/js";import{classifyPaymentRejection as lc,FloPayError as Ct,isAuthorizationOnlySession as cc,isSetupIntentClientSecret as dc,normalizeCheckoutFailureOutcome as ws}from"@flopay/shared";var Do="card";async function uc(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function pc(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Wa(e,t){return Object.assign(e,{checkoutMethod:t})}function ir(e,t){let n=e instanceof Ct?e:new Ct(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 Fo(e,t){try{return await e()}catch(n){throw ir(n,t)}}function Is(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 mc(e){return e.status==="succeeded"||e.status==="declined"}async function Es(e){if(typeof document>"u"||typeof window>"u")throw new Ct("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ct("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 h=new AbortController,b=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",b);let T=window.setTimeout(()=>h.abort(),r);try{let M=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!M.ok)return{status:"unknown"};let u=await M.json().catch(()=>null);return yc(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(T),e.signal?.removeEventListener("abort",b)}},l=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let k=document.createElement("iframe");k.setAttribute("title","Card authentication"),k.setAttribute("allow","payment"),k.tabIndex=0,k.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(";"),k.src=e.nextActionRedirectUrl,s.appendChild(k),document.body.appendChild(s),k.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let h=await new Promise((b,T)=>{let M=!1,u=0,I=0,he=0,j=!1,S=()=>{window.clearTimeout(u),window.clearInterval(I),window.clearTimeout(he),window.removeEventListener("message",ae),k.removeEventListener("load",Z),e.signal?.removeEventListener("abort",se)},pe=async()=>{if(!(M||j)){j=!0;try{let ve=await a();if(M||!mc(ve))return;M=!0,S(),b(ve)}finally{j=!1}}},Z=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{pe()},250)},se=()=>{M||(M=!0,S(),T(new Ct("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=ve=>{if(ve.source!==k.contentWindow||g&&ve.origin!==g)return;let tt=ve.data;!tt||typeof tt!="object"||tt.source!=="flopay-vault-3ds-return"||M||(M=!0,S(),b(null))};u=window.setTimeout(()=>{M||(M=!0,S(),T(new Ct("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),I=window.setInterval(()=>{pe()},n),k.addEventListener("load",Z),window.addEventListener("message",ae),e.signal?.addEventListener("abort",se),e.signal?.aborted&&se()});return h||await a()}finally{s.parentNode?.removeChild(s),l?.isConnected&&l.focus()}}function yc(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 br(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=yr(o)??o;return Wa(new Ct(a,"api_error",{code:ws(e?.outcome)??ws(e?.type)??e?.gatewayErrorCode}),r)}function Ya(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function la(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Rs(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||la(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||la(s)))return s;let l=o.gateways;if(l&&typeof l=="object"){let s=l.stripe;if(s&&typeof s=="object"){let k=s,g=[k.stripeClientSecret,k.clientSecret];for(let h of g)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||la(h)))return h}}}}async function fc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Rs(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 ks(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(la(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function no({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let s=e.replace(/\/+$/,""),k=t??n.id,g=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",T=n.customer?.firstName??n.accountData?.firstName??"",M=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,I=n.customer?.zip??n.accountData?.zip??void 0,j=await new ks(s,l===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:k,nonce:g,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:b,firstName:T,lastName:M,country:u,zip:I},returnUrl:a??Ya(n)});if(j.ok){let Z=typeof j.json=="function"?await j.json().catch(()=>null):null;return cc(n)||Z?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Z?.paymentId=="string"?Z.paymentId:n.paymentId,sessionId:typeof Z?.sessionId=="string"?Z.sessionId:k,authorizationExpiresAt:typeof Z?.authorizationExpiresAt=="string"?Z.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Ro(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Ro(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let S;try{S=await j.json()}catch{throw new Ct("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let Z=Rs(S);if(!Z)throw new Ct("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status});return{type:S.type,threeDSecureToken:Z,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let Z=await fc({billingApiUrl:s,sessionId:k,nonce:g,responseJson:S});if(Z)return Z;throw Wa(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let pe=new Ct(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:j.status});throw Object.assign(pe,{telemetryOutcome:lc(j.status,S)})}async function ca(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:k}){let g=t?.getRawProvider();if(!g)throw ir(new Ct("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Wa(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=dc(e.threeDSecureToken),b=null,T=e.paymentMethodId,M=await Fo(()=>uc(g,e.threeDSecureToken,h),"card");if(M){if(M.error)throw ir(new Ct(M.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let I=M.intent;!T&&I?.payment_method&&(typeof I.payment_method=="string"?T=I.payment_method:"id"in I.payment_method&&(T=I.payment_method.id??void 0))}let u=T?await Fo(()=>pc(g,e.threeDSecureToken,{payment_method:T,return_url:s??Ya(l)??window.location.href},h),"card"):null;if(u){if(u.error)throw ir(new Ct(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");b=u.intent}else{let I=await Fo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(I.error)throw ir(new Ct(I.error.message??"3DS authentication failed.","api_error",{code:I.error.code}),"card");b=(h?I.setupIntent:I.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let I=await no({billingApiUrl:o,sessionId:a,session:l,telemetry:k,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:s});return I.type==="success"?{...I.result,paymentIntentId:I.result.paymentIntentId??b.id,paymentMethodId:I.result.paymentMethodId??T}:ca(I,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:k})}throw ir(new Ct("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw ir(new Ct("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:T}=await Fo(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(T)throw ir(new Ct(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Fo(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Ya(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw ir(new Ct(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ct("Unsupported payment redirect state.","api_error")}function Lo(e){if(e instanceof Ct){let r=yr(e.message);return r&&r!==e.message?Object.assign(new Ct(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=yr(t)??t;return new Ct(n,"api_error")}function da(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ct("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 ua({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[l,s]=await Promise.all([Ss(e,{billingApiUrl:n,locale:r,telemetry:o}),a?Ss(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(k=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",k),null)):Promise.resolve(null)]);return{flopay:l,paypalFlopay:t?a?s:l:null}}import{PaymentAPI as ro,toStripeAppearance as gc}from"@flopay/js";import{COUNTRY_OPTIONS as hc,classifyPaymentRejection as bc,FloPayError as Yn,filterStripeMethodsByCountry as vc,getPostalCodeExample as Pc,getPostalCodeLabel as Qa,getStateFromPostalCode as xs,getStateLabel as Ga,getStateOptions as Cc,getStripeMethodDisplayName as Fr,hasVendoredStripeMethodLogo as Sc,isAuthorizationOnlySession as Ja,isAVSFieldVisible as Ve,isPostalCodeSupported as wc,isSetupIntentClientSecret as kc,isValidEmail as en,isValidPostalCode as Ic,needsStripeMethodExplicitConfirm as Ms,normalizeCheckoutFailureOutcome as Ec,partitionStripeMethods as Rc,resolveAVSConfig as _c,resolveButtonsLayoutTheme as Tc,resolveStripeMethodBrandVariant as xc,resolveTheme as Mc,stripeExpressMethodToOptionKey as As}from"@flopay/shared";import{ExpressCheckoutElement as qs,PaymentElement as Ac,Elements as Ar,useElements as ni,useStripe as ri}from"@stripe/react-stripe-js";import Bc,{useCallback as ge,useContext as oo,useEffect as wt,useMemo as St,useRef as fe,useState as ue}from"react";function _s(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 Ts={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as Br,jsx as c,jsxs as Te}from"react/jsx-runtime";var tr="flopay_stripe_resume",Bs="flopay_wallet_resume",$s="fw1",Fc=300*1e3,Dc=900,Lc=25e3,pa={};function js(e){return e instanceof Yn&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ya(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new ro(e).createSessionIntent(...n)}catch(o){throw js(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var No="flopay_paypal_resume",Nc=250,Fs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function oi(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function fa({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new ro(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Oc(e){return e instanceof Yn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Xa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Ks({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=Er(r?.name),a=Er(n);return Sn({email:(en(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:a.firstName??o.firstName,lastName:a.lastName??o.lastName})}async function zc({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=Ks({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return en(l.email)?l:a(o,l)}var Uc=`
|
|
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 @@ ${en.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
|
-
`,pa=44,Mr=280;function oi(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 zc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Uc(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var js={width:"100%",minHeight:pa,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 qc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Bs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Qa(e){return e==="paypal"?"PayPal":Fr(e)}function $c(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 Ks(e){let t=fe(0),n=fe(null),r=fe(null),o=ge((u=r.current)=>{let I=u;I?.timer&&(clearTimeout(I.timer),I.timer=null)},[]),a=ge((u,I)=>{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"}))},I))},[o,e]),l=ge(u=>{u.yieldedControl&&a(u,600)},[a]),s=ge(u=>{o();let I=t.current+1;t.current=I,n.current=null;let he={generation:I,method:u,timer:null,yieldedControl:!1};return r.current=he,I},[o]),k=ge(u=>{let I=r.current;return typeof u=="number"&&I?.generation!==u?!1:(o(I),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),g=ge(u=>{let I=r.current,he=u??I?.generation??t.current;(!u||I?.generation===u)&&(o(I),r.current=null),n.current=he},[o]),h=ge(u=>n.current===(u??t.current),[]),b=ge(u=>r.current?.generation===u&&n.current!==u,[]),T=ge(()=>{let u=r.current;u&&l(u)},[l]),M=ge(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return wt(()=>{let u=()=>{document.visibilityState==="visible"?T():M()},I=()=>{M()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",I),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",I),window.removeEventListener("focus",T),o()}},[o,M,T]),{startAttempt:s,finishAttempt:k,invalidateAttempt:g,isAttemptInvalidated:h,isAttemptCurrent:b,generationRef:t}}function jc(e){let t=bc(e);return`Enter a valid ${Za(e)}${t?` (e.g. ${t})`:""}`}function Kc(e,t,n){let r=Cc(e),o=t.trim(),a=n&&r,l=a&&!o,s=a&&!!o&&!wc(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:s}}function Hc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!Qt(n);return{required:t,empty:r,malformed:o,value:n}}function Fs(e,t){return t instanceof Yn?t:new Yn(t instanceof Error?t.message:`${qc(e)} before-click hook failed.`,"validation_error")}function Xa(){return c("style",{children:Oc})}function Vc(e){return typeof e=="number"?`${e}px`:e}function Hs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Vs({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:xe("div",{style:{position:"relative",minHeight:44},children:[c("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),c("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function Ds(e){return e!=="unavailable"&&e!=="load_error"}function ai(e){return c(Wc,{...e})}function Ls({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:s,onDecline:k,onTechnicalFailure:g,runBeforeButtonClick:h,billingName:b,onBuyerIdentityReady:T,onLoadStateChange:M,placeholderBorderRadius:u}){let I=gr(),{emitInstrument:he}=no(Dn),j=ni(),C=ti(),[pe,Z]=ue("loading");wt(()=>{M?.(pe)},[pe,M]);let[se,ae]=ue(!1),ve=!Qt(n?.trim())||!b?.trim(),{request:et,collect:be,finish:Dt}=Wr(),Xe=fe(!1),Me=fe(null),Ae=fe(null),[ee,Q]=ue(0),[A,Fe]=ue(!1),De=fe(!1),Le=fe(new Map),{startAttempt:Ue,finishAttempt:ke,invalidateAttempt:_,isAttemptInvalidated:ce,isAttemptCurrent:Pe}=Ks((H,D,B)=>{g?.(H,D,{...B,popupBlocked:B?.popupBlocked??fr(D)}),Fe(!0),Q(Ee=>Ee+1)});wt(()=>{A&&Ae.current?.focus()},[A,ee]);let de=ge(()=>{Q(H=>H+1)},[]),K=ge((H,D,B)=>{_(B),g?.("paypal",H,{code:D,popupBlocked:fr(H)}),Fe(!0),de()},[_,g,de]),Ie=ge(()=>{window.setTimeout(()=>{(Me.current?.querySelector("iframe")??Me.current)?.focus()},0)},[]);wt(()=>{De.current&&(De.current=!1,Ie())},[Ie,ee]);let ot=ge(()=>{Fe(!1),a?.(null),Ie()},[Ie,a]);wt(()=>{if(!j||Xe.current)return;let H=new URLSearchParams(window.location.search),D=H.get("payment_intent"),B=H.get("payment_intent_client_secret"),Ee=H.get("redirect_status");if(!D||!B)return;Xe.current=!0;let Ve;try{let at=localStorage.getItem(Do);if(at){let S=JSON.parse(at);S.clientSecret===B&&(Ve={...S.accountPatch?{accountPatch:S.accountPatch}:{},...S.sessionId?{sessionId:S.sessionId}:{},...S.nonce?{nonce:S.nonce}:{}})}}catch{}try{localStorage.removeItem(Do)}catch{}let ie=new URL(window.location.href);ie.searchParams.delete("payment_intent"),ie.searchParams.delete("payment_intent_client_secret"),ie.searchParams.delete("redirect_status"),window.history.replaceState({},"",ie.toString()),(async()=>{try{if(ae(!0),Ee==="failed"){let v="PayPal payment was declined. Please try again.";a?.(v),k?.(Ht("paypal",v));return}let{paymentIntent:at,error:S}=await j.retrievePaymentIntent(B);if(S){a?.(S.message??"Failed to retrieve PayPal payment status.");return}if(at&&(at.status==="requires_capture"||at.status==="succeeded")){let v=typeof at.payment_method=="string"?at.payment_method:at.payment_method?.id;o({id:v??at.id,type:"card",threeDSecureActionResultTokenId:at.id,isPaypal:!0},Ve)}else{let v="PayPal payment was not completed. Please try again.";a?.(v),k?.(Ht("paypal",v))}}catch(at){a?.(at instanceof Error?at.message:"Failed to complete PayPal payment.")}finally{ae(!1)}})()},[j,o,a,k]);let ht=ge(async H=>{if(l||se){H.reject();return}let D=h?await h("paypal"):{proceed:!0};if(!D.proceed){Le.current.delete(ee),H.reject();return}let B=Ue("paypal");Le.current.set(ee,{generation:B,accountPatch:D.accountPatch,sessionId:D.sessionId,nonce:D.nonce}),Fe(!1),s?.("paypal"),H.resolve()},[l,s,h,Ue,se,ee]),qe=ge(async H=>{if(!j||!C)return;let D=Le.current.get(ee);if(D&&!Pe(D.generation)){Le.current.delete(ee);return}if(!D&&ce()||D&&!ke(D.generation))return;D||ke();let B=D??null;if(Le.current.delete(ee),!B&&h){let v=await h("paypal");if(!v.proceed){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}B={accountPatch:v.accountPatch,sessionId:v.sessionId,nonce:v.nonce}}let Ee=B?.sessionId??e,Ve=B?.nonce??t,ie=await Nc({event:H,prepared:B,email:n,billingName:b,methodLabel:"PayPal",collect:be});if(!ie){H.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let at=ie.email,S=Sn({...B?.accountPatch,...ie});try{if(ae(!0),a?.(null),!Ee||!Qt(at))throw new Error("Missing sessionId or email for PayPal payment");await T?.(ie);let v=j.createPaymentMethod,{error:_e,paymentMethod:ne}=await v({type:"paypal"});if(_e){K(_e,"stripe_paypal_create_payment_method_failed",D?.generation),H.paymentFailed({reason:"fail"});return}let W=await ma(r,he,Ee,Ve??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ne?.id??null,intentKind:"payment"});if(W.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let tt=W.clientSecret,Be={return_url:window.location.href};if(ne?.id&&(Be.payment_method=ne.id),typeof window<"u")try{localStorage.setItem(Do,JSON.stringify({clientSecret:tt,sessionId:Ee,nonce:Ve,accountPatch:S}))}catch{}let{error:Ze,paymentIntent:Mt}=await j.confirmPayment({clientSecret:tt,confirmParams:Be,redirect:"if_required"});if(Ze){if(typeof window<"u")try{localStorage.removeItem(Do)}catch{}if(Ro(Ze)){let U=Ze.message??"Your payment was declined.";a?.(U),k?.(Ht("paypal",U,{code:ar(Ze),declineCode:Jr(Ze)})),await ya({billingApiUrl:r,sessionId:Ee,nonce:Ve,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ar(Ze)??"provider_declined"}})}else K(Ze,"stripe_paypal_confirm_failed",D?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Do)}catch{}let P=typeof Mt?.payment_method=="string"?Mt.payment_method:Mt?.payment_method?.id;o({id:P??Mt?.id,type:"card",threeDSecureActionResultTokenId:Mt?.id,isPaypal:!0},{accountPatch:S,paymentMethodCategory:"paypal",sessionId:Ee,nonce:Ve});return}catch(v){K(v,"stripe_paypal_failed",D?.generation)}finally{ae(!1)}},[j,C,e,t,n,b,be,T,r,he,o,a,k,h,K,ke,Pe,ce,ee]);return xe(Br,{children:[c(Vs,{state:pe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:u,children:xe("div",{ref:Me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[A&&c("button",{ref:Ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:js,children:"Try PayPal again"}),et&&c(Gr,{identity:et.identity,methodLabel:et.methodLabel,onComplete:Dt,onCancel:()=>Dt(null)},et.id),c("div",{style:{display:et?"none":void 0},children:c(zs,{onReady:H=>Z(Hs(H,["paypal"])),onLoadError:()=>{Z("load_error"),ri(jt(I),"paypal","paypal")},onClick:ht,onConfirm:qe,onCancel:()=>{let H=Le.current.get(ee);Le.current.delete(ee),jt(I)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),_(H?.generation),Fe(!1),De.current=!0,de()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ve,emailRequired:ve,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),se&&c(er,{status:"processing"})]})}function Ns({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:s,onButtonClick:k,onDecline:g,onTechnicalFailure:h,runBeforeButtonClick:b,billingName:T,onBuyerIdentityReady:M,onLoadStateChange:u,placeholderBorderRadius:I}){let he=gr(),{emitInstrument:j}=no(Dn),C=ni(),pe=ti(),[Z,se]=ue("loading");wt(()=>{u?.(Z)},[Z,u]);let[ae,ve]=ue(!1),et=fe(!Qt(n?.trim())||!T?.trim()).current,{request:be,collect:Dt,finish:Xe}=Wr(),Me=fe(null),Ae=fe(null),[ee,Q]=ue(0),[A,Fe]=ue(!1),[De,Le]=ue("google_pay"),Ue=fe(!1),ke=fe("google_pay"),_=fe("google_pay"),ce=fe(null),Pe=fe(new Map),{startAttempt:de,finishAttempt:K,invalidateAttempt:Ie,isAttemptInvalidated:ot,isAttemptCurrent:ht,generationRef:qe}=Ks((S,v,_e)=>{h?.(S,v,{..._e,popupBlocked:_e?.popupBlocked??fr(v)}),Le(S),Fe(!0),Q(ne=>ne+1)});wt(()=>{A&&Ae.current?.focus()},[A,ee]);let H=ge(()=>{Q(S=>S+1)},[]),D=ge((S,v,_e,ne)=>{Ie(ne),h?.(S,v,{code:_e,popupBlocked:fr(v)}),Le(S),Fe(!0),H()},[Ie,h,H]),B=ge(()=>{window.setTimeout(()=>{(Me.current?.querySelector("iframe")??Me.current)?.focus()},0)},[]);wt(()=>{Ue.current&&(Ue.current=!1,B())},[B,ee]);let Ee=ge(()=>{Fe(!1),s?.(null),B()},[B,s]),Ve=ge(async S=>{let v=!1,_e=E=>{v||(v=!0,S.paymentFailed({reason:"fail",...E?{message:E}:{}}))};if(!C||!pe){_e();return}let ne=Pe.current.get(ee);if(ne&&!ht(ne.generation)){Pe.current.delete(ee),_e();return}if(!ne&&ot()){_e();return}if(ne&&!K(ne.generation)){_e();return}ne||K();let W=S.expressPaymentType??ne?.method??ke.current,tt=ne??null,Be=Bs(W),Ze=jt(he),Mt=Ze?.now()??globalThis.performance?.now()??Date.now(),P=new AbortController,U=!1,it,Ye=new Promise((E,mt)=>{it=mt}),en=window.setTimeout(()=>{U=!0,P.abort(),it(Ga)},Fc),Wt=async(E,mt,Tt)=>{let st=Ze?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Tt,Ye])}finally{let Rt=Ze?.now()??globalThis.performance?.now()??Date.now();Ze?.performance({stage:E,durationMs:Math.max(0,Rt-st),durationMode:"machine",requestCategory:mt,paymentMethodCategory:"wallet",provider:"stripe",...U?{statusClass:"timeout"}:{}})}};try{if(ve(!0),s?.(null),!tt&&b){let lt=await Wt("processing","other",b(Be));if(!lt.proceed){_e();return}tt={accountPatch:lt.accountPatch,sessionId:lt.sessionId,nonce:lt.nonce}}let E=tt?.sessionId??e,mt=tt?.nonce??t,Tt=$s({event:S,fallbackEmail:ce.current?.email??tt?.accountPatch?.email??n,fallbackName:[ce.current?.firstName??tt?.accountPatch?.firstName,ce.current?.lastName??tt?.accountPatch?.lastName].filter(Boolean).join(" ")||T});if(!Qt(Tt.email)){_e("Buyer details are required."),Dt(Qa(W),Tt).then(lt=>{lt&&(ce.current=lt)});return}ce.current=null;let st=Sn({...tt?.accountPatch,...Tt});await Wt("processing","provider_sdk",Promise.resolve(M?.(Tt)));let{error:Rt}=await Wt("tokenization","provider_sdk",pe.submit());if(Rt){_e(),D(W,Rt,"stripe_wallet_submit_failed",ne?.generation);return}if(!E)throw new Error("Missing sessionId or email for payment.");let pn=await Wt("processing","intent_create",ma(r,j,E,mt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,paymentMethodId:null,intentKind:o},{signal:P.signal}));if(pn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let an=pn.clientSecret,mn=Sc(an)?C.confirmSetup({elements:pe,clientSecret:an,redirect:"if_required"}):C.confirmPayment({elements:pe,clientSecret:an,redirect:"if_required"}),Lt=!1,wn=lt=>{if(Lt||lt.error||ne&&qe.current!==ne.generation)return;let ft=lt.setupIntent??lt.paymentIntent,sn=ft?.id,Qe=ft?.status,Wn=lt.setupIntent?Qe==="succeeded":ko(typeof Qe=="string"?Qe:void 0),dt=ft?.payment_method,nn=typeof dt=="string"?dt:typeof dt?.id=="string"?dt.id:null;if(!Wn||typeof sn!="string"||!nn)return;Lt=!0;let bt=`${Us}:${E}`;if(typeof window<"u")try{localStorage.setItem(bt,JSON.stringify({createdAt:Date.now(),sessionId:E,nonce:mt,accountPatch:st,paymentMethodId:nn,providerIntentId:sn,paymentMethodType:W}))}catch{}try{l({id:nn,type:"card",threeDSecureActionResultTokenId:sn},{accountPatch:st,paymentMethodCategory:"wallet",sessionId:E,nonce:mt})}finally{if(typeof window<"u")try{localStorage.removeItem(bt)}catch{}}};mn.then(lt=>{U&&wn(lt)},()=>{});let tn=await Wt("three_ds_handoff","provider_sdk",mn),yt=tn.error;if(yt){if(Ro(yt)){let lt=yt.message??"Your payment was declined.";_e(lt),s?.(lt),g?.(Ht(Be,lt,{code:ar(yt),declineCode:Jr(yt)})),ya({billingApiUrl:r,sessionId:E,nonce:mt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,providerDeclineReason:ar(yt)??"provider_declined"}})}else _e(),D(W,yt,"stripe_wallet_confirm_failed",ne?.generation);return}if(wn(tn),!Lt)throw new Error("Invalid provider returned for APM intent")}catch(E){E===Ga&&Ze?.error({errorCode:"REQUEST_TIMEOUT",stage:"callback",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"timeout",failureCategory:"provider_runtime"}),_e(),D(W,E,E===Ga?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",ne?.generation)}finally{window.clearTimeout(en);let E=Ze?.now()??globalThis.performance?.now()??Date.now();Ze?.performance({stage:"callback",durationMs:Math.max(0,E-Mt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...U?{statusClass:"timeout"}:{}}),ve(!1)}},[C,pe,e,t,n,T,Dt,M,r,j,o,l,s,g,b,D,K,ht,ot,qe,he,ee]),ie=St(()=>{let S=["applePay","googlePay","paypal","link","amazonPay","klarna"],v=new Set(["applePay","googlePay"]),_e=new Set(a.map(xs)),ne={};for(let W of S)_e.has(W)?ne[W]=v.has(W)?"always":"auto":ne[W]="never";return ne},[a]),at=St(()=>a.map(xs),[a]);return xe(Br,{children:[c(Vs,{state:Z,placeholderTestId:"flopay-wallet-placeholder",borderRadius:I,children:xe("div",{ref:Me,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[A&&xe("button",{ref:Ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Ee,style:js,children:["Try ",Qa(De)," again"]}),be&&c(Gr,{identity:be.identity,methodLabel:be.methodLabel,onComplete:Xe,onCancel:()=>Xe(null)},be.id),c("div",{style:{display:be?"none":void 0},children:c(zs,{onReady:S=>{se(Hs(S,at))},onLoadError:S=>{se("load_error"),ri(jt(he),"stripe","wallet")},onClick:async S=>{ke.current=S.expressPaymentType,_.current=Bs(S.expressPaymentType);let v=!0,_e=window.setTimeout(()=>{v=!1,S.reject()},Bc),ne=b?await b(_.current):{proceed:!0};if(window.clearTimeout(_e),!v)return;if(!ne.proceed){Pe.current.delete(ee),S.reject();return}let W=de(S.expressPaymentType);Pe.current.set(ee,{generation:W,method:S.expressPaymentType,accountPatch:ne.accountPatch,sessionId:ne.sessionId,nonce:ne.nonce}),Fe(!1),k?.(_.current),S.resolve()},onConfirm:Ve,onCancel:()=>{let S=Pe.current.get(ee);Pe.current.delete(ee),jt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Ie(S?.generation),Fe(!1),Ue.current=!0,H()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ie,emailRequired:et,billingAddressRequired:et,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),ae&&c(er,{status:"processing"})]})}function Yc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:s,borderColor:k,textColor:g,borderRadius:h,fontFamily:b}){let T=_c(e,t),M=Rs[e],[u,I]=ue(!1),he=T?.backgroundColor??s??"#ffffff",j=T?.borderColor??k??"#d1d5db",C=T?.textColor??g??"#262833";return c("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:pa,padding:"0 1rem",backgroundColor:he,color:C,border:`1px solid ${j}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?c("span",{style:{margin:"0 auto"},children:`Connecting to ${Fr(e)}\u2026`}):xe(Br,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:Pc(e)?8:0},children:[M&&!u?c("img",{src:M,alt:"","aria-hidden":"true",onError:()=>I(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):T?.logoSvg?c("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:T.logoSvg}}):null,c("span",{children:Fr(e)})]}),a&&c("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:c("path",{d:"M9 18l6-6-6-6"})})]})})}function ei({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:s,onErrorChange:k,onDecline:g,onCancel:h,runBeforeButtonClick:b,onButtonClick:T,isProcessing:M,submitButtonColor:u,submitButtonBorderRadius:I,submitButtonStyle:he,errorText:j}){let C=gr(),{emitInstrument:pe}=no(Dn),Z=ni(),se=ti(),[ae,ve]=ue(!1),et=fe(!1),[be,Dt]=ue(!1),[Xe,Me]=ue("loading"),[Ae,ee]=ue(""),Q=!Qt(r?.trim()),A=!Q||Qt(Ae.trim()),Fe=ge(async()=>{if(!Z||!se||M||et.current||!be)return;et.current=!0,ve(!0);let De=b?await b("card"):{proceed:!0};if(!De.proceed){et.current=!1,ve(!1);return}T?.("card");let Le=De.sessionId??t,Ue=De.nonce??n,ke=Er(o?.trim()),_=Sn({email:De.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:De.accountPatch?.firstName?.trim()||ke.firstName,lastName:De.accountPatch?.lastName?.trim()||ke.lastName}),ce=_.email,Pe=Sn({...De.accountPatch,..._});try{if(k?.(null),!Qt(ce))throw new Error("A valid email address is required for payment.");await a?.(_);let de=await se.submit();if(de.error){k?.(de.error.message??"Payment failed.");return}let K=[_.firstName,_.lastName].filter(Boolean).join(" "),Ie=await Z.createPaymentMethod({elements:se,params:{billing_details:{email:ce,...K?{name:K}:{}}}});if(Ie.error||!Ie.paymentMethod){k?.(Ie.error?.message??"Failed to create payment method.");return}let ot=Ie.paymentMethod;if(!Le||!ce)throw new Error("Missing sessionId or email for payment.");let ht=ot.type||e,qe=await ma(l,pe,Le,Ue??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ht,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let H=qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(tr,JSON.stringify({clientSecret:H,sessionId:Le,nonce:Ue,accountPatch:Pe,paymentMethodId:ot.id,paymentMethodType:ot.type??e,gateway:"stripe"}))}catch{}let{error:D,paymentIntent:B}=await Z.confirmPayment({clientSecret:H,confirmParams:{return_url:window.location.href,payment_method:ot.id},redirect:"if_required"});if(D){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=D.message??"Payment failed.";k?.(ie),g?.(Ht("card",ie,{code:D.code})),await ya({billingApiUrl:l,sessionId:Le,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:D.code??"provider_declined"}});return}let Ee=B?.status;if(!ko(Ee)){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=Ee==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";k?.(ie),g?.(Ht("card",ie,{code:Ee??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let Ve=typeof B?.payment_method=="string"?B.payment_method:B?.payment_method?.id;s({id:Ve??ot.id,type:"card",threeDSecureActionResultTokenId:B?.id,gateway:"stripe",paymentMethodType:ot.type??e},{accountPatch:Pe,paymentMethodCategory:"apm",sessionId:Le,nonce:Ue})}catch(de){k?.(de instanceof Error?de.message:"Payment failed. Please try again.")}finally{et.current=!1,ve(!1)}},[Z,se,M,be,b,T,t,n,r,o,Ae,a,l,pe,e,s,k,g]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Q&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Q&&xe("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:Ae,onChange:De=>ee(De.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(xc,{onReady:()=>Me("ready"),onLoadError:()=>{Me("load_error"),ri(jt(C),"stripe","apm")},onChange:De=>{Dt(!!De.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...Qt(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Fe()},disabled:!be||!A||ae||M||Xe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:I,fontSize:"1rem",fontWeight:600,cursor:!be||!A||ae||M||Xe!=="ready"?"not-allowed":"pointer",opacity:!be||!A||ae||M||Xe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:ae?"Processing\u2026":`Pay with ${Fr(e)}`}),j&&c(Zr,{margin:"0.75rem 0 0",children:j})]})}function Os({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:s,paymentElementBaseOptions:k,onTokenizedBody:g,onErrorChange:h,onButtonClick:b,onDecline:T,runBeforeButtonClick:M,onLoadStateChange:u,isProcessing:I=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:j=8,submitButtonStyle:C,buttonAppearance:pe,themeId:Z,onExpandApm:se,expandedApmMethod:ae}){let{emitInstrument:ve}=no(Dn),[et,be]=ue(null),[Dt,Xe]=ue(null),Me=fe(!1),{request:Ae,collect:ee,finish:Q}=Wr();wt(()=>{l.length>0&&s?u?.("ready"):s||u?.("loading")},[l.length,s,u]);let A=ge(async _=>{if(!s||Me.current||I)return;Me.current=!0,Xe(_);let ce=M?await M("card"):{proceed:!0};if(!ce.proceed){Me.current=!1,Xe(null);return}b?.("card");let Pe=ce.sessionId??e,de=ce.nonce??t,K=Er([ce.accountPatch?.firstName,ce.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ie=Sn({email:ce.accountPatch?.email?.trim()||n?.trim(),firstName:ce.accountPatch?.firstName?.trim()||K.firstName,lastName:ce.accountPatch?.lastName?.trim()||K.lastName});if(!Qt(Ie.email)){Xe(null);let qe=await ee(Fr(_),Ie);if(!qe){Me.current=!1;return}Ie=qe,Xe(_)}let ot=Ie.email,ht=Sn({...ce.accountPatch,...Ie});try{if(h?.(null),!Pe||!Qt(ot))throw new Error("Missing sessionId or email for payment.");await o?.(Ie);let qe=await ma(a,ve,Pe,de??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let H=qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(tr,JSON.stringify({clientSecret:H,sessionId:Pe,nonce:de,accountPatch:ht,paymentMethodType:_,gateway:"stripe"}))}catch{}let{error:D,paymentIntent:B}=await s.confirmPayment({clientSecret:H,confirmParams:{return_url:window.location.href,payment_method_data:{type:_,billing_details:{name:[Ie.firstName,Ie.lastName].filter(Boolean).join(" "),...ot?{email:ot}:{}}}},redirect:"if_required"});if(D){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=D.message??"Payment failed.";h?.(ie),T?.(Ht("card",ie,{code:D.code})),await ya({billingApiUrl:a,sessionId:Pe,nonce:de,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,providerDeclineReason:D.code??"provider_declined"}});return}let Ee=B?.status;if(!ko(Ee)){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=Ee==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(ie),T?.(Ht("card",ie,{code:Ee??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let Ve=typeof B?.payment_method=="string"?B.payment_method:B?.payment_method?.id;g({id:Ve??B?.id,type:"card",threeDSecureActionResultTokenId:B?.id,gateway:"stripe",paymentMethodType:_},{accountPatch:ht,paymentMethodCategory:"apm",sessionId:Pe,nonce:de})}catch(qe){h?.(qe instanceof Error?qe.message:"Payment failed. Please try again.")}finally{Me.current=!1,Xe(null)}},[s,I,M,b,e,t,n,ee,a,ve,r,o,g,h,T]),[Fe,De]=ue(null),Le=se?ae??null:Fe,Ue=ge(_=>{Me.current||I||Le&&Le!==_||(Ts(_)?se?se(_):De(_):A(_))},[Le,I,A,se]),ke=St(()=>Fe?{...k,paymentMethodTypes:[Fe]}:null,[Fe,k]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ae?c(Gr,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:Q,onCancel:()=>Q(null)},Ae.id):l.map(_=>{let ce=ae===_,Pe=Dt===_,de=Dt!==null&&Dt!==_||ae!=null&&ae!==_;return xe(Mc.Fragment,{children:[c(Yc,{method:_,themeId:Z,submitting:Pe,disabled:de,highlighted:ce,hasNextStep:Ts(_),onClick:()=>Ue(_),backgroundColor:pe?.backgroundColor,borderColor:pe?.borderColor,textColor:pe?.textColor,borderRadius:pe?.borderRadius,fontFamily:pe?.fontFamily}),!se&&Fe===_&&ke&&s&&c(Ar,{stripe:s,options:ke,children:c(ei,{method:_,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:g,onErrorChange:h,onDecline:T,onCancel:()=>De(null),runBeforeButtonClick:M,onButtonClick:b,isProcessing:I,submitButtonColor:he,submitButtonBorderRadius:j,submitButtonStyle:C})},_)]},_)})})}function Wc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:s,onTokenizedBody:k,firstName:g,lastName:h,chv:b,className:T,isProcessing:M,error:u,onErrorChange:I,showPayPal:he=!0,showStripe:j=!0,enabledPaymentMethods:C,enabledPaymentMethodCountries:pe,showApplePay:Z=!0,showGooglePay:se=!0,layout:ae="default",theme:ve,buttonsTheme:et,buttonsStyles:be,appearance:Dt,cardButtonContent:Xe,cardBackButtonContent:Me,cardTitleContent:Ae,showSecurityFooter:ee,onButtonClick:Q,onBeforeButtonClick:A,onBuyerIdentityReady:Fe,enableAVS:De,cardFieldOrder:Le,cardPreFormSlot:Ue,avsLayout:ke="row",country:_,zip:ce,addressLine1:Pe,addressLine2:de,city:K,state:Ie,onCountryChange:ot,onZipChange:ht,avsCheck:qe,checkoutType:H,checkoutLayout:D,totalAmount:B=0,currency:Ee="usd",initialCardOpen:Ve=!1,directPaypal:ie,isSubscription:at=!1,session:S,dataAttachmentPending:v=!1,dataAttachmentRequiresIdentity:_e=!1,debug:ne=!1}){let W=gr(),tt=Oa(),Be=no(Vn),{emitInstrument:Ze}=no(Dn),Mt=S??Be.session,P=Mt?.gateways?.paypal?.providerObjectType??ie?.providerObjectType,U=v||Be.claimPending===!0,it=_e||Be.claimRequiresIdentity===!0,Ye=U&&!it,en=us(),[Wt,E]=ue(!1),[mt,Tt]=ue(null),[st,Rt]=ue(_??"US"),[pn,an]=ue(ce??""),[mn,Lt]=ue(Pe??""),[wn,tn]=ue(de??""),[yt,lt]=ue(K??""),[ft,sn]=ue(Ie??""),[Qe,Wn]=ue(""),[dt,nn]=ue({}),bt=fe(ce??""),Gt=fe(_??"US"),kn=fe(Pe??""),yn=fe(de??""),_n=fe(K??""),ln=fe(Ie??""),Tn=fe(""),qt=fe({});wt(()=>{let i=(y,N,Te,z,Re)=>{if(qt.current[y])return;let ze=N?.trim();!ze||ze===Te.current||(Te.current=ze,z(ze),Re?.(ze))};i("country",_,Gt,Rt,ot),i("zip",ce,bt,an,ht),i("addressLine1",Pe,kn,Lt),i("addressLine2",de,yn,tn),i("city",K,_n,lt),i("state",Ie,ln,sn)},[_,ce,Pe,de,K,Ie,ot,ht]);let G=St(()=>Ec(De),[De]),fn=G!==null,Nn=St(()=>Wa(S),[S]),Gn=!!S?.vault?.html,Cr=!!S?.gateways?.pcivault,cr=!!(S?.gateways?.stripe?.enabledPaymentMethods??C)?.includes("card"),Nt=Gn||cr||Cr,$e=!!(j&&Nt&&W&&e),[dr,w]=ue(()=>ae!=="buttons"||Ve?e??null:null),[ct,Kt]=ue(0),In=ae!=="buttons"||Ve||!!e&&dr===e,me=St(()=>!W||!$e||!e||!In?null:W.cardCapture({sessionId:e,captureMethod:S?.captureMethod}),[W,$e,e,In,S?.captureMethod]),cn=St(()=>{let i=st,y=G?He(G.postal_code,i):!1;return Kc(i,pn,y)},[G,st,pn]),{avsInvalid:wr,invalidAvsFields:Lr}=St(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!$e||!G)return{avsInvalid:!1,invalidAvsFields:i};let y=st,N=(Re,ze)=>He(Re,y)&&!ze.trim(),Te={line1:N(G.address_line_1,mn),city:N(G.city,yt),state:N(G.state,ft),zip:cn.empty||cn.malformed};return{avsInvalid:Te.line1||Te.city||Te.state||Te.zip,invalidAvsFields:Te}},[$e,G,st,mn,yt,ft,cn]),[gn,ur]=ue(!1),[Jn,On]=ue(!1),[Ot,zn]=ue(!1),[Xn,hn]=ue({line1:!1,city:!1,state:!1}),rn=fe(!1),Un=fe({email:!1,line1:!1,city:!1,state:!1,zip:!1}),qn=fe(!1),ut=ge(i=>{Un.current[i]=!0,qn.current=!0},[]),bn=ge(i=>!rn.current&&Un.current[i],[]),vn=ge(i=>{bn(i)&&hn(y=>y[i]?y:{...y,[i]:!0})},[bn]),[$n,xn]=ue(()=>Ja(S?.vault)),[Ce,on]=ue(Ve&&Nt?"card":"buttons"),[zt,pr]=ue(null),jn=Ce==="expanding"||Ce==="card",mr=S?.gateways?.stripe?"stripe":void 0,En=ge(()=>{Ze?.({class:"card_surface",provider:mr})},[mr,Ze]),Mn=fe(null),Ut=ge(i=>{Mn.current&&clearTimeout(Mn.current),Mn.current=setTimeout(()=>{Mn.current=null,i()},Mr)},[]);wt(()=>()=>{Mn.current&&clearTimeout(Mn.current)},[]);let x=ge(()=>{En(),w(e??null),Kt(i=>i+1),on("expanding"),Ut(()=>on("card"))},[Ut,En,e]),L=ge(()=>{on("collapsing"),Ut(()=>on("buttons"))},[Ut]),V=ge(i=>{pr(i),on("apm-expanding"),Ut(()=>on("apm-form"))},[Ut]),Y=ge(()=>{on("apm-collapsing"),Ut(()=>{on("buttons"),pr(null)})},[Ut]);wt(()=>{ae==="buttons"&&Ve&&Nt&&(w(e??null),on("card"))},[ae,Ve,Nt,e]);let[Se,F]=ue(null),q=fe(!1),p=fe(null),O=fe("idle"),[$,gt]=ue(null),vt=fe($);wt(()=>{vt.current=$},[$]);let te=n||en,we=fe(null),Jt=St(()=>{if(Fe||Be.claimBuyerIdentity||S?.buyerIdentified!==!1||!e||!t)return;let i=`${te}|${e}|${t}`;we.current?.key!==i&&(we.current={key:i,claim:Vr(new to(te,{telemetry:!1}),e,t,{...o?{userId:o}:{},...g?{firstName:g}:{},...h?{lastName:h}:{}})});let y=we.current.claim;return async N=>{await y(N)}},[Fe,Be.claimBuyerIdentity,S?.buyerIdentified,e,t,te,o,g,h]),nt=Fe??Be.claimBuyerIdentity??Jt,m=u??mt,d=St(()=>Tc(ve),[ve]),f=St(()=>{let i=d?.buttonsLayout??Rc(et);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},[d,et,be]),ye=Dt??d?.appearance,re=St(()=>Qi({appearance:ye,buttonsStyles:f,layout:ae}),[ye,f,ae]),je=Be.inlineSessionPatchProcessing??!1,We=(M??Wt)||je,J=te.replace(/\/+$/,""),R=St(()=>Na({userId:o,email:r,firstName:g,lastName:h,country:_,zip:ce},dt),[o,r,g,h,_,ce,dt]),oe=[R.firstName,R.lastName].filter(i=>!!i?.trim()).join(" "),Ke=!Qt(R.email?.trim()),Ne=fe(null);$e&&Ne.current===null&&(Ne.current=Ke);let Pt=$e&&(Ne.current??Ke),Oe=St(()=>Hc(Qe,Pt),[Qe,Pt]),$t=Oe.empty||Oe.malformed,Rn=St(()=>W?W.getRawProvider():null,[W]),Nr=St(()=>tt?tt.getRawProvider():null,[tt]),so=B||100,qo=St(()=>ye?yc(ye):null,[ye]),$o=qo?{appearance:qo}:null,Pi=St(()=>{let i=qo??{},y=i.rules??{};return{...i,rules:{...y,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...y[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...y[".AccordionItemContents"]??{}}}}},[qo]),Ci=St(()=>{let i=as(B);return{...i,currency:Ee.toLowerCase(),...i.mode==="payment"?{captureMethod:"manual"}:{},...$o}},[B,Ee,$o]),Si=St(()=>({mode:"payment",amount:so,currency:Ee.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...$o}),[so,Ee,$o]),le=ge(i=>{Tt(i),I?.(i)},[I]),va=fe(""),[wi,rl]=ue(!1),Pa=ge(()=>{rl(!0)},[]);wt(()=>{if(!$e||!Pt||!nt||!wi||$t||va.current)return;let i=Sn({email:Qt(R.email?.trim())?R.email?.trim():Tn.current.trim(),firstName:R.firstName?.trim(),lastName:R.lastName?.trim()});va.current=JSON.stringify(i),nn(y=>({...y,...i})),Promise.resolve(nt(i)).catch(y=>{va.current="",le(y instanceof Error?y.message:"Failed to attach buyer details.")})},[$e,Pt,nt,wi,$t,R.email,R.firstName,R.lastName,le]),wt(()=>{!$e||!me||me.setCardFieldOrder?.(Le??null,G==null&&!Pt)},[$e,me,Le,G,Pt]),wt(()=>{(Ce==="expanding"||Ce==="collapsing"||Ce==="apm-expanding"||Ce==="apm-collapsing")&&le(null)},[Ce,le]);let Kn=ge((i,y,N)=>{s?.(Ht(i,y,N))},[s]),Or=ge((i,y,N)=>{let Te=N?.popupBlocked??fr(y),z=$c(i,Te),Re=_r(N?.code)??ar(y)??"external_payment_method_failed",ze=new Yn(z,"api_error",{code:"external_payment_method_failed",param:i});F(null),ae==="buttons"&&(on("buttons"),pr(null)),le(z),l?.(ze),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:Te})},[ae,l,le]);wt(()=>{if(!$e||!e){xn(null);return}let i=Ja(S?.vault);if(i){xn(i);return}if(!In){xn(null);return}xn(null);let y=!0;return new to(J).getVaultCapture(e,t).then(N=>{if(!y)return;let Te=Ja(N);Te?xn(Te):le("Failed to load the secure card form.")}).catch(N=>{y&&le(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{y=!1}},[$e,In,ct,e,S?.vault,J,t,le]);let Zn=fe({onComplete:a,onError:l,updateError:le,emitDecline:Kn,resolvedAccount:R,avsConfig:G,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:J,captureMethod:S?.captureMethod,paymentId:S?.paymentId,authorizationExpiresAt:S?.authorizationExpiresAt});Zn.current={onComplete:a,onError:l,updateError:le,emitDecline:Kn,resolvedAccount:R,avsConfig:G,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:J,captureMethod:S?.captureMethod,paymentId:S?.paymentId,authorizationExpiresAt:S?.authorizationExpiresAt};let Ca=fe(!1),ki=ge(()=>{let{resolvedAccount:i,avsConfig:y,avsCheckProp:N}=Zn.current,Te=i.email?.trim(),z=Qt(Te)?Te:Tn.current.trim();if(!Qt(z))return null;let Re=i.firstName?.trim(),ze=i.lastName?.trim(),pt=Gt.current||i.country||"US",Xt=y?He(y.state,pt):!1,kt=y?He(y.address_line_1,pt):!1,It=y?He(y.postal_code,pt):!1,rt=y?He(y.city,pt):!1,dn=y?He(y.address_line_2,pt):!1,Ge=kt&&!Xt&&It?_s(pt,(bt.current??"").trim()):null,un=Xt?ln.current:Ge;return{accountData:{userId:i.userId??"",email:z,...Re?{firstName:Re}:{},...ze?{lastName:ze}:{},...It&&bt.current?{zip:bt.current}:{},...rt&&_n.current?{city:_n.current}:{},...un?{state:un}:{},...kt&&kn.current?{addressLine1:kn.current}:{},...dn&&yn.current?{addressLine2:yn.current}:{},country:pt},...N!==void 0?{avsCheck:N}:{},...y?{avsConfig:{country:He(y.country,pt),postal_code:It,address_line_1:kt,address_line_2:dn,city:rt,state:Xt}}:{}}},[]),Ii=fe(U);Ii.current=U,wt(()=>{U||m!==As||Zn.current.updateError(null)},[U,m]),wt(()=>{!$e||!me||me.setSubmitGate?.(wr||U||$t)},[$e,me,wr,U,$t]),wt(()=>{if(!$e||!me)return;Ca.current=!1;let i=!1,y=me.on("submitting",()=>{ur(!0),p.current&&clearTimeout(p.current),O.current="validation-window",p.current=setTimeout(()=>{p.current=null,O.current==="validation-window"&&(O.current="processing")},Dc),F("processing");let{baseUrl:ze,sessionId:pt,nonce:Xt,updateError:kt,onError:It}=Zn.current;if(!pt||!Xt)return;let rt=ki();if(!rt){kt("Enter a valid email address."),O.current="idle",F(null);return}new to(ze).patchAccountSnapshot(pt,Xt,rt,{telemetryMode:"best_effort"}).catch(dn=>{if(!Lc(dn))return;let Ge=dn instanceof Error?dn.message:"Please check your billing address and try again.";kt(Ge),O.current="idle",F(null),It?.(dn instanceof Yn?dn:new Yn(Ge,"api_error"))})}),N=me.on("complete",async ze=>{if(Qr(ze.sessionId??Zn.current.sessionId),O.current="terminal",F("success"),await new Promise(kt=>setTimeout(kt,1200)),Ca.current)return;Ca.current=!0;let pt=Zn.current,Xt=Wa(pt)||ze.outcome==="authorized";Zn.current.onComplete?.(Xt?{status:"authorized",paymentIntentId:ze.intentId,paymentId:ze.paymentId??pt.paymentId,sessionId:ze.sessionId??pt.sessionId,authorizationExpiresAt:ze.authorizationExpiresAt??pt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:ze.intentId,checkoutMethod:"card"})}),Te=me.on("decline",async ze=>{let{updateError:pt,emitDecline:Xt}=Zn.current,kt=ze.message??"Your payment was declined. Please try another card or contact your bank.";O.current="terminal",pt(kt),F("error");let It=ze.failureOutcome??kc(ze.declineReason)??"authorization_declined";Xt("card",kt,{code:It,declineCode:It}),await new Promise(rt=>setTimeout(rt,1500)),!i&&(O.current="idle",F(null))}),z=me.on("error",async ze=>{let{updateError:pt,onError:Xt}=Zn.current,kt=ze.message??"There was a problem processing your payment. Please try again.";O.current="terminal",pt(kt),F("error"),Xt?.(new Yn(kt,"api_error",{code:ze.failureOutcome??"capture_failed"})),await new Promise(It=>setTimeout(It,1500)),!i&&(O.current="idle",F(null))}),Re=me.on("blocked",()=>{if(!Ii.current){ur(!0);return}Pa(),Zn.current.updateError(As)});return()=>{i=!0,p.current&&(clearTimeout(p.current),p.current=null),O.current="idle",y(),N(),Te(),z(),Re()}},[$e,me,Pa,ki]);let Qn=!!ie?.clientId,lo=Array.isArray(C),jo=lo&&C.length>0,ol=lo&&C.includes("paypal"),{expressMethods:Ko,paymentElementMethods:co}=St(()=>Ic(C,{excludePaypal:Qn}),[C,Qn]),Ei=Qn||!!tt,al=St(()=>Ei?Ko.filter(i=>i!=="paypal"):Ko,[Ko,Ei]),il=St(()=>{let i=[];return Z&&i.push("apple_pay"),se&&i.push("google_pay"),i},[Z,se]),zr=lo?al:il,sl=j&&zr.length>0,Sa=fn?st:_,Ho=St(()=>{let i=Sa?.trim().toUpperCase();return i?pe?co.filter(y=>{let N=pe[y];return!N||N.length===0||N.includes(i)}):hc(co,Sa):co},[co,Sa,pe]),wa=St(()=>({mode:"payment",amount:so,currency:Ee.toLowerCase(),paymentMethodCreation:"manual",appearance:Pi}),[so,Ee,Pi]),[Ri,_i]=ue("loading"),[Ti,xi]=ue("loading"),[Mi,Ai]=ue("loading"),[ll,ka]=ue(!1),[Bi,Ia]=ue("loading"),[Vo,cl]=ue();wt(()=>{cl(Es())},[]);let Fi=he&&(Qn||(lo?ol:Vo===!1)),Di=j&&sl,uo=!Ye&&Fi&&Qn,Li=Bi==="retrying"||Bi==="exhausted",po=!Ye&&Fi&&!!Nr&&(!Qn||Li),mo=!Ye&&Di&&!!Rn,yo=!Ye&&j&&jo&&Ho.length>0&&!!Rn,dl=uo&&!Li?ll:po&&Ds(Ri),ul=mo&&Ds(Ti),pl=yo&&Mi!=="load_error",Ni=i=>i==="loading"||i==="ready",Oi=uo||po&&Ni(Ri)||mo&&Ni(Ti)||yo&&Mi!=="load_error",Yo=fe(!1);wt(()=>{if(!Yo.current){if(!j&&!he){Yo.current=!0;let i=new Yn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),le(i.message)}else if(!j&&he&&!Qn&&!Nr){Yo.current=!0;let i=new Yn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(i),le(i.message)}else if(Vo!==void 0&&!Ye&&!Nt&&!Oi){Yo.current=!0;let i=new Yn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(i),le(i.message)}}},[j,he,Qn,Nr,Vo,Ye,Nt,Oi,l,le]);let zi=fe(!1);wt(()=>{if(zi.current||!jo)return;let i=[];Z!==!0&&i.push("showApplePay"),se!==!0&&i.push("showGooglePay"),i.length!==0&&(zi.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.`))},[jo,Z,se]);let Ui=ge((i,y)=>Be.applyInlineSessionPatch?Be.applyInlineSessionPatch(i).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let Te=Fs(y,N);return le(Te.message),l?.(Te),{error:Te,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Be.applyInlineSessionPatch,t,l,e,le]),Hn=ge(async i=>{if(!A)return{proceed:!0};try{let y=await A({method:i,sessionId:e||void 0,createSession:Be.inlineSessionDraft});if(y===!1)return{proceed:!1};if(y&&typeof y=="object"){y.account&&nn(Te=>({...Te??{},...y.account}));let N=await Ui(y,i);return N.error?{proceed:!1,accountPatch:y.account}:{proceed:!0,accountPatch:y.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(y){let N=Fs(i,y);return le(N.message),l?.(N),{proceed:!1}}},[Ui,Be.inlineSessionDraft,A,l,e,le]),qi=ge(async(i,y)=>{if(q.current)return;q.current=!0,E(!0),F("processing"),le(null);let N=y?.sessionId??e,Te=y?.nonce??t,z=Na(R,y?.accountPatch),Re=y?.completionPaymentMethodId??Io(i),ze=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,pt=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Xt=()=>{Ze?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:pt})};try{let It=await new to(J).processPayment(z.userId??"",{sessionId:N,nonce:Te,paymentMethodCategory:y?.paymentMethodCategory??Uc(i),tokenizedData:ze,accountData:{...y?.accountPatch,userId:z.userId??"",email:z.email??"",...z.firstName?{firstName:z.firstName}:{},...z.lastName?{lastName:z.lastName}:{},...G?(()=>{let Ge=Gt.current,un=He(G.state,Ge),Bn=He(G.address_line_1,Ge),Zt=He(G.postal_code,Ge),Po=Bn&&!un&&Zt?_s(Ge,(bt.current??"").trim()):null,Co=un?ln.current:Po;return{country:Ge,...Zt&&bt.current?{zip:bt.current}:{},...He(G.city,Ge)&&_n.current?{city:_n.current}:{},...Co?{state:Co}:{},...Bn&&kn.current?{addressLine1:kn.current}:{},...He(G.address_line_2,Ge)&&yn.current?{addressLine2:yn.current}:{}}})():{}},chv:b,avsCheck:qe??!1,checkoutType:H,checkoutLayout:D,avsConfig:G?{country:He(G.country,Gt.current),postal_code:He(G.postal_code,Gt.current),address_line_1:He(G.address_line_1,Gt.current),address_line_2:He(G.address_line_2,Gt.current),city:He(G.city,Gt.current),state:He(G.state,Gt.current)}:void 0});if(It.ok){let Ge=It.status===204?null:await It.json().catch(()=>null),un=Wa(S)||Ge?.status==="authorized";Qr(N),F("success"),gt(null),await new Promise(Bn=>setTimeout(Bn,1200)),a?.(un?{status:"authorized",...typeof Ge?.paymentId=="string"?{paymentId:Ge.paymentId}:S?.paymentId?{paymentId:S.paymentId}:{},sessionId:typeof Ge?.sessionId=="string"?Ge.sessionId:N,...typeof Ge?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Ge.authorizationExpiresAt}:S?.authorizationExpiresAt?{authorizationExpiresAt:S.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 rt=await It.json().catch(()=>null);if(rt?.type==="paypal_redirect_required"){let Ge=rt.threeDSecureToken,un=rt.paymentMethodId||i.id||"";if(!W||!Ge){F("error"),le("PayPal authorization required but no token provided.");return}try{let Bn=tt?.getRawProvider();if(!Bn){le("PayPal is not available.");return}let Zt={return_url:window.location.href};un&&(Zt.payment_method=un);let{error:Po}=await Bn.confirmPayment({clientSecret:Ge,confirmParams:Zt,redirect:"if_required"});if(Po){F("error");let Co=Po.message??"PayPal payment failed.";le(Co),Kn("paypal",Co,{code:Po.code})}}catch(Bn){F("error"),le(Bn instanceof Error?Bn.message:"PayPal authorization failed.")}return}if(rt?.type==="paypal_direct_required"){let Ge=rt.orderId;if(!Ge){F("error"),le("PayPal retry required but no order id provided.");return}let un=vt.current?.attempts??0;if(un>=2){F("error"),le("PayPal payment could not be completed after multiple attempts."),Kn("paypal","paypal_direct_required retry limit exceeded");return}ka(!1),Ia("loading"),gt({orderId:Ge,attempts:un+1}),F(null);return}gc(It.status,rt)||Xt(),F("error");let dn=rt?.message??"Payment failed. Please try again.";le(dn),Kn(i.isPaypal?"paypal":"card",dn,{code:rt?.code??rt?.gatewayErrorCode,declineCode:rt?.declineCode??rt?.gatewayDeclineReason}),await new Promise(Ge=>setTimeout(Ge,1500))}catch(kt){qs(kt)||Xt(),F("error"),le(kt instanceof Error?kt.message:"An unexpected error occurred"),await new Promise(It=>setTimeout(It,1500))}finally{E(!1),F(null),q.current=!1}},[J,e,t,R,G,qe,H,D,b,W,tt,S,a,le,Kn,Ze]),Pn=ge((i,y)=>{k?k(i):qi(i,y)},[k,qi]),fo=`${Us}:${e}`;wt(()=>{if(typeof window>"u")return;let i=localStorage.getItem(fo);if(!i)return;let y;try{y=JSON.parse(i)}catch{localStorage.removeItem(fo);return}if(!y||typeof y.createdAt!="number"||Date.now()-y.createdAt<0||Date.now()-y.createdAt>Ac||typeof y.paymentMethodId!="string"||typeof y.providerIntentId!="string"||typeof y.paymentMethodType!="string"||y.sessionId!==e||!t||y.nonce!==t||!zr.includes(y.paymentMethodType)){localStorage.removeItem(fo);return}localStorage.removeItem(fo),Pn({id:y.paymentMethodId,type:"card",threeDSecureActionResultTokenId:y.providerIntentId,gateway:"stripe",paymentMethodType:y.paymentMethodType},{...y.accountPatch?{accountPatch:y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Pn,t,e,fo,zr]);let $i=fe(!1);wt(()=>{if(typeof window>"u"||$i.current)return;let i=new URLSearchParams(window.location.search),y=i.get("payment_intent"),N=i.get("payment_intent_client_secret"),Te=i.get("redirect_status");if(!y||!N)return;let z=It=>{let rt=localStorage.getItem(It);if(!rt)return null;try{return JSON.parse(rt)}catch{return localStorage.removeItem(It),null}},Re=z(tr)??z(Ms),ze;if(Re?.clientSecret){if(Re.clientSecret!==N)return;ze={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;$i.current=!0,localStorage.removeItem(tr),localStorage.removeItem(Ms);let pt=new URL(window.location.href);pt.searchParams.delete("payment_intent"),pt.searchParams.delete("payment_intent_client_secret"),pt.searchParams.delete("redirect_status"),window.history.replaceState({},"",pt.toString());let Xt=Re?.paymentMethodType??Re?.tokenType??"card",kt="card";(async()=>{let It=W?.getRawProvider();if(!It){let Zt="Payment is not available \u2014 please refresh and try again.";le(Zt),Kn(kt,Zt);return}if(Te==="failed"){let Zt="Payment was declined. Please try again.";le(Zt),Kn(kt,Zt);return}let{paymentIntent:rt,error:dn}=await It.retrievePaymentIntent(N);if(dn){let Zt=dn.message??"Failed to retrieve payment status.";le(Zt),Kn(kt,Zt,{code:dn.code});return}let Ge=rt?.status,un=ko(Ge);if(!rt||!un){let Zt=Ge==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";le(Zt),Kn(kt,Zt,{code:Ge??"missing_payment_intent"});return}let Bn=typeof rt.payment_method=="string"?rt.payment_method:rt.payment_method?.id;Pn({id:Bn??Re?.paymentMethodId??Re?.tokenId??rt.id,type:"card",threeDSecureActionResultTokenId:rt.id,gateway:Re?.gateway??"stripe",paymentMethodType:Xt},ze)})()},[e,Pn,W,le,Kn]);let Ea=ge(i=>{i.preventDefault()},[]);if(!(W!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let go=ae==="buttons",Cn=ye?.variables,ml=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ra=Cn?.colorBackground,yl=Ra&&!ml.has(Ra)?Ra:void 0,ho=f.cardInputBorder??(go?"#e5e7eb":"#A4A4FF"),ji=Cn?.colorDanger??"#dc2626",xt=i=>Lr[i]&&(Xn[i]||gn),Wo=$t&&(Ot||gn),An=i=>i?ji:ho,Go=(cn.malformed||cn.empty)&&(Jn||gn),fl=An(Go),_a=f.cardFormContainer?.backgroundColor??yl??(go?"white":"#EDEDFF"),Ur=f.cardInputBackground??Cn?.colorBackground??"white",Ta=$r(Me),Ki=$r(Ae),qr=f.nameInput,Hi=f.cardInputFontSize??Vc(qr?.fontSize)??Cn?.fontSizeBase??"16px",Vi=typeof qr?.fontFamily=="string"?qr.fontFamily:Cn?.fontFamily??"Poppins, sans-serif",Yi=Zi(qr?.fontWeight)??400,gl=f.cardInputColor??(typeof qr?.color=="string"?qr.color:void 0)??Cn?.colorText??"#262833",hl=f.cardInputPlaceholderColor??"#9ca3af",At=Cn?.borderRadius??"8px",kr=Cn?.borderRadius??f.cardButton?.borderRadius??At,Ir=Cn?.colorPrimary??"#4A49FF",bl=Cn?.colorPrimaryHover??So(Ir,.12),xa=Cn?.colorText??"#262833",Ma={fontSize:Hi,fontFamily:Vi,fontWeight:Yi,color:gl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},bo={marginTop:"0.375rem",...Ma,fontSize:"0.75rem",lineHeight:1.4,color:ji},vl={"--flopay-input-placeholder-color":hl,"--flopay-input-font-size":Hi,"--flopay-input-font-family":Vi,"--flopay-input-font-weight":String(Yi)},vo=f.cardFormContainer??{},Aa=vo.padding??(go?"0":"1rem"),Ba=vo.borderRadius??At,Pl=me&&$n?c(Fa,{capture:me,html:$n.html,messageToken:$n.messageToken,expectedOrigin:$n.expectedOrigin,theme:re,onReady:()=>{if(!Pt&&!G||typeof document>"u")return;let i=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){rn.current=!0;try{N.focus()}finally{rn.current=!1}}};qn.current||i()},onError:i=>le(i),onValidation:i=>{let y=O.current;(y==="idle"||y==="validation-window")&&(le(i),i&&O.current==="validation-window"&&(p.current&&(clearTimeout(p.current),p.current=null),O.current="idle",F(null)))}}):c("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Wi=xe("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&En()},style:{backgroundColor:_a,borderRadius:Ba,...vo,padding:Aa,...vl,display:"flex",flexDirection:"column"},children:[c("style",{children:`
|
|
25
|
+
`,ma=44,Mr=280;function ai(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 qc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function $c(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var Vs={width:"100%",minHeight:ma,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 jc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ds(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ei(e){return e==="paypal"?"PayPal":Fr(e)}function Kc(e,t){let n=`We couldn't open ${ei(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Hs(e){let t=fe(0),n=fe(null),r=fe(null),o=ge((u=r.current)=>{let I=u;I?.timer&&(clearTimeout(I.timer),I.timer=null)},[]),a=ge((u,I)=>{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"}))},I))},[o,e]),l=ge(u=>{u.yieldedControl&&a(u,600)},[a]),s=ge(u=>{o();let I=t.current+1;t.current=I,n.current=null;let he={generation:I,method:u,timer:null,yieldedControl:!1};return r.current=he,I},[o]),k=ge(u=>{let I=r.current;return typeof u=="number"&&I?.generation!==u?!1:(o(I),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),g=ge(u=>{let I=r.current,he=u??I?.generation??t.current;(!u||I?.generation===u)&&(o(I),r.current=null),n.current=he},[o]),h=ge(u=>n.current===(u??t.current),[]),b=ge(u=>r.current?.generation===u&&n.current!==u,[]),T=ge(()=>{let u=r.current;u&&l(u)},[l]),M=ge(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return wt(()=>{let u=()=>{document.visibilityState==="visible"?T():M()},I=()=>{M()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",I),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",I),window.removeEventListener("focus",T),o()}},[o,M,T]),{startAttempt:s,finishAttempt:k,invalidateAttempt:g,isAttemptInvalidated:h,isAttemptCurrent:b,generationRef:t}}function Vc(e){let t=Pc(e);return`Enter a valid ${Qa(e)}${t?` (e.g. ${t})`:""}`}function Hc(e,t,n){let r=wc(e),o=t.trim(),a=n&&r,l=a&&!o,s=a&&!!o&&!Ic(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:s}}function Yc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!en(n);return{required:t,empty:r,malformed:o,value:n}}function Ls(e,t){return t instanceof Yn?t:new Yn(t instanceof Error?t.message:`${jc(e)} before-click hook failed.`,"validation_error")}function Za(){return c("style",{children:Uc})}function Wc(e){return typeof e=="number"?`${e}px`:e}function Ys(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Ws({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:Te("div",{style:{position:"relative",minHeight:44},children:[c("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),c("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function Ns(e){return e!=="unavailable"&&e!=="load_error"}function ii(e){return c(Jc,{...e})}function Os({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:s,onDecline:k,onTechnicalFailure:g,runBeforeButtonClick:h,billingName:b,onBuyerIdentityReady:T,onLoadStateChange:M,placeholderBorderRadius:u}){let I=gr(),{emitInstrument:he}=oo(Dn),j=ri(),S=ni(),[pe,Z]=ue("loading");wt(()=>{M?.(pe)},[pe,M]);let[se,ae]=ue(!1),ve=!en(n?.trim())||!b?.trim(),{request:tt,collect:be,finish:Dt}=Jr(),Qe=fe(!1),xe=fe(null),Me=fe(null),[ee,Q]=ue(0),[A,Be]=ue(!1),Fe=fe(!1),De=fe(new Map),{startAttempt:ze,finishAttempt:ke,invalidateAttempt:_,isAttemptInvalidated:ce,isAttemptCurrent:Pe}=Hs((V,D,B)=>{g?.(V,D,{...B,popupBlocked:B?.popupBlocked??fr(D)}),Be(!0),Q(qe=>qe+1)});wt(()=>{A&&Me.current?.focus()},[A,ee]);let de=ge(()=>{Q(V=>V+1)},[]),K=ge((V,D,B)=>{_(B),g?.("paypal",V,{code:D,popupBlocked:fr(V)}),Be(!0),de()},[_,g,de]),Ie=ge(()=>{window.setTimeout(()=>{(xe.current?.querySelector("iframe")??xe.current)?.focus()},0)},[]);wt(()=>{Fe.current&&(Fe.current=!1,Ie())},[Ie,ee]);let at=ge(()=>{Be(!1),a?.(null),Ie()},[Ie,a]);wt(()=>{if(!j||Qe.current)return;let V=new URLSearchParams(window.location.search),D=V.get("payment_intent"),B=V.get("payment_intent_client_secret"),qe=V.get("redirect_status");if(!D||!B)return;Qe.current=!0;let He;try{let it=localStorage.getItem(No);if(it){let v=JSON.parse(it);v.clientSecret===B&&(He={...v.accountPatch?{accountPatch:v.accountPatch}:{},...v.sessionId?{sessionId:v.sessionId}:{},...v.nonce?{nonce:v.nonce}:{}})}}catch{}try{localStorage.removeItem(No)}catch{}let ie=new URL(window.location.href);ie.searchParams.delete("payment_intent"),ie.searchParams.delete("payment_intent_client_secret"),ie.searchParams.delete("redirect_status"),window.history.replaceState({},"",ie.toString()),(async()=>{try{if(ae(!0),qe==="failed"){let P="PayPal payment was declined. Please try again.";a?.(P),k?.(Vt("paypal",P));return}let{paymentIntent:it,error:v}=await j.retrievePaymentIntent(B);if(v){a?.(v.message??"Failed to retrieve PayPal payment status.");return}if(it&&(it.status==="requires_capture"||it.status==="succeeded")){let P=typeof it.payment_method=="string"?it.payment_method:it.payment_method?.id;o({id:P??it.id,type:"card",threeDSecureActionResultTokenId:it.id,isPaypal:!0},He)}else{let P="PayPal payment was not completed. Please try again.";a?.(P),k?.(Vt("paypal",P))}}catch(it){a?.(it instanceof Error?it.message:"Failed to complete PayPal payment.")}finally{ae(!1)}})()},[j,o,a,k]);let ht=ge(async V=>{if(l||se){V.reject();return}let D=h?await h("paypal"):{proceed:!0};if(!D.proceed){De.current.delete(ee),V.reject();return}let B=ze("paypal");De.current.set(ee,{generation:B,accountPatch:D.accountPatch,sessionId:D.sessionId,nonce:D.nonce}),Be(!1),s?.("paypal"),V.resolve()},[l,s,h,ze,se,ee]),Ue=ge(async V=>{if(!j||!S)return;let D=De.current.get(ee);if(D&&!Pe(D.generation)){De.current.delete(ee);return}if(!D&&ce()||D&&!ke(D.generation))return;D||ke();let B=D??null;if(De.current.delete(ee),!B&&h){let P=await h("paypal");if(!P.proceed){V.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}B={accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}}let qe=B?.sessionId??e,He=B?.nonce??t,ie=await zc({event:V,prepared:B,email:n,billingName:b,methodLabel:"PayPal",collect:be});if(!ie){V.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let it=ie.email,v=Sn({...B?.accountPatch,...ie});try{if(ae(!0),a?.(null),!qe||!en(it))throw new Error("Missing sessionId or email for PayPal payment");await T?.(ie);let P=j.createPaymentMethod,{error:Re,paymentMethod:ne}=await P({type:"paypal"});if(Re){K(Re,"stripe_paypal_create_payment_method_failed",D?.generation),V.paymentFailed({reason:"fail"});return}let W=await ya(r,he,qe,He??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ne?.id??null,intentKind:"payment"});if(W.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let nt=W.clientSecret,Ae={return_url:window.location.href};if(ne?.id&&(Ae.payment_method=ne.id),typeof window<"u")try{localStorage.setItem(No,JSON.stringify({clientSecret:nt,sessionId:qe,nonce:He,accountPatch:v}))}catch{}let{error:Ye,paymentIntent:Mt}=await j.confirmPayment({clientSecret:nt,confirmParams:Ae,redirect:"if_required"});if(Ye){if(typeof window<"u")try{localStorage.removeItem(No)}catch{}if(To(Ye)){let U=Ye.message??"Your payment was declined.";a?.(U),k?.(Vt("paypal",U,{code:ar(Ye),declineCode:Zr(Ye)})),await fa({billingApiUrl:r,sessionId:qe,nonce:He,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ar(Ye)??"provider_declined"}})}else K(Ye,"stripe_paypal_confirm_failed",D?.generation);return}if(typeof window<"u")try{localStorage.removeItem(No)}catch{}let C=typeof Mt?.payment_method=="string"?Mt.payment_method:Mt?.payment_method?.id;o({id:C??Mt?.id,type:"card",threeDSecureActionResultTokenId:Mt?.id,isPaypal:!0},{accountPatch:v,paymentMethodCategory:"paypal",sessionId:qe,nonce:He});return}catch(P){K(P,"stripe_paypal_failed",D?.generation)}finally{ae(!1)}},[j,S,e,t,n,b,be,T,r,he,o,a,k,h,K,ke,Pe,ce,ee]);return Te(Br,{children:[c(Ws,{state:pe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:u,children:Te("div",{ref:xe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[A&&c("button",{ref:Me,type:"button","data-testid":"flopay-paypal-retry-button",onClick:at,style:Vs,children:"Try PayPal again"}),tt&&c(Xr,{identity:tt.identity,methodLabel:tt.methodLabel,onComplete:Dt,onCancel:()=>Dt(null)},tt.id),c("div",{style:{display:tt?"none":void 0},children:c(qs,{onReady:V=>Z(Ys(V,["paypal"])),onLoadError:()=>{Z("load_error"),oi(jt(I),"paypal","paypal")},onClick:ht,onConfirm:Ue,onCancel:()=>{let V=De.current.get(ee);De.current.delete(ee),jt(I)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),_(V?.generation),Be(!1),Fe.current=!0,de()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ve,emailRequired:ve,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),se&&c(er,{status:"processing"})]})}function zs({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:s,onButtonClick:k,onDecline:g,onTechnicalFailure:h,runBeforeButtonClick:b,billingName:T,onBuyerIdentityReady:M,onLoadStateChange:u,placeholderBorderRadius:I}){let he=gr(),{emitInstrument:j}=oo(Dn),S=ri(),pe=ni(),[Z,se]=ue("loading");wt(()=>{u?.(Z)},[Z,u]);let[ae,ve]=ue(!1),tt=fe(!en(n?.trim())||!T?.trim()).current,{request:be,collect:Dt,finish:Qe}=Jr(),xe=fe(null),Me=fe(null),[ee,Q]=ue(0),[A,Be]=ue(!1),[Fe,De]=ue("google_pay"),ze=fe(!1),ke=fe("google_pay"),_=fe("google_pay"),ce=fe(null),Pe=fe(new Map),{startAttempt:de,finishAttempt:K,invalidateAttempt:Ie,isAttemptInvalidated:at,isAttemptCurrent:ht,generationRef:Ue}=Hs((v,P,Re)=>{h?.(v,P,{...Re,popupBlocked:Re?.popupBlocked??fr(P)}),De(v),Be(!0),Q(ne=>ne+1)});wt(()=>{A&&Me.current?.focus()},[A,ee]);let V=ge(()=>{Q(v=>v+1)},[]),D=ge((v,P,Re,ne)=>{Ie(ne),h?.(v,P,{code:Re,popupBlocked:fr(P)}),De(v),Be(!0),V()},[Ie,h,V]),B=ge(()=>{window.setTimeout(()=>{(xe.current?.querySelector("iframe")??xe.current)?.focus()},0)},[]);wt(()=>{ze.current&&(ze.current=!1,B())},[B,ee]);let qe=ge(()=>{Be(!1),s?.(null),B()},[B,s]),He=ge(async v=>{let P=!1,Re=E=>{P||(P=!0,v.paymentFailed({reason:"fail",...E?{message:E}:{}}))};if(!S||!pe){Re();return}let ne=Pe.current.get(ee);if(ne&&!ht(ne.generation)){Pe.current.delete(ee),Re();return}if(!ne&&at()){Re();return}if(ne&&!K(ne.generation)){Re();return}ne||K();let W=v.expressPaymentType??ne?.method??ke.current,nt=ne??null,Ae=Ds(W),Ye=jt(he),Mt=Ye?.now()??globalThis.performance?.now()??Date.now(),C=new AbortController,U=!1,st,We=new Promise((E,mt)=>{st=mt}),tn=window.setTimeout(()=>{U=!0,C.abort(),st(pa)},Lc),Wt=async(E,mt,Tt)=>{let lt=Ye?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Tt,We])}finally{let Rt=Ye?.now()??globalThis.performance?.now()??Date.now();Ye?.performance({stage:E,durationMs:Math.max(0,Rt-lt),durationMode:"machine",requestCategory:mt,paymentMethodCategory:"wallet",provider:"stripe",...U?{statusClass:"timeout"}:{}})}};try{if(ve(!0),s?.(null),!nt&&b){let Ge=await Wt("processing","other",b(Ae));if(!Ge.proceed){Re();return}nt={accountPatch:Ge.accountPatch,sessionId:Ge.sessionId,nonce:Ge.nonce}}let E=nt?.sessionId??e,mt=nt?.nonce??t,Tt=Ks({event:v,fallbackEmail:ce.current?.email??nt?.accountPatch?.email??n,fallbackName:[ce.current?.firstName??nt?.accountPatch?.firstName,ce.current?.lastName??nt?.accountPatch?.lastName].filter(Boolean).join(" ")||T});if(!en(Tt.email)){Re("Buyer details are required."),Dt(ei(W),Tt).then(Ge=>{Ge&&(ce.current=Ge)});return}ce.current=null;let lt=Sn({...nt?.accountPatch,...Tt});await Wt("processing","provider_sdk",Promise.resolve(M?.(Tt)));let{error:Rt}=await Wt("tokenization","provider_sdk",pe.submit());if(Rt){Re(),D(W,Rt,"stripe_wallet_submit_failed",ne?.generation);return}if(!E)throw new Error("Missing sessionId or email for payment.");let pn=await Wt("processing","intent_create",ya(r,j,E,mt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,paymentMethodId:null,intentKind:o},{signal:C.signal}));if(pn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let an=pn.clientSecret,mn=kc(an)?S.confirmSetup({elements:pe,clientSecret:an,redirect:"if_required"}):S.confirmPayment({elements:pe,clientSecret:an,redirect:"if_required"}),Lt=!1,wn=Ge=>{if(Lt||Ge.error||ne&&Ue.current!==ne.generation)return;let ft=Ge.setupIntent??Ge.paymentIntent,sn=ft?.id,et=ft?.status,Wn=Ge.setupIntent?et==="succeeded":Eo(typeof et=="string"?et:void 0),dt=ft?.payment_method,nn=typeof dt=="string"?dt:typeof dt?.id=="string"?dt.id:null;if(!Wn||typeof sn!="string"||!nn)return;Lt=!0;let bt=`${$s}:${E}`;if(typeof window<"u")try{localStorage.setItem(bt,JSON.stringify({createdAt:Date.now(),sessionId:E,nonce:mt,accountPatch:lt,paymentMethodId:nn,providerIntentId:sn,paymentMethodType:W}))}catch{}try{l({id:nn,type:"card",threeDSecureActionResultTokenId:sn},{accountPatch:lt,paymentMethodCategory:"wallet",sessionId:E,nonce:mt})}finally{if(typeof window<"u")try{localStorage.removeItem(bt)}catch{}}};mn.then(Ge=>{U&&wn(Ge)},()=>{});let Gt;try{Gt=await Wt("three_ds_handoff","provider_sdk",mn)}catch(Ge){throw Ge!==pa&&Ye?.error({...ss(Ge),stage:"three_ds_handoff",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"unknown"}),Ge}let yt=Gt.error;if(yt){if(To(yt)){let Ge=yt.message??"Your payment was declined.";Re(Ge),s?.(Ge),g?.(Vt(Ae,Ge,{code:ar(yt),declineCode:Zr(yt)})),fa({billingApiUrl:r,sessionId:E,nonce:mt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,providerDeclineReason:ar(yt)??"provider_declined"}})}else Re(),D(W,yt,"stripe_wallet_confirm_failed",ne?.generation);return}if(wn(Gt),!Lt)throw new Error("Invalid provider returned for APM intent")}catch(E){E===pa&&Ye?.error({errorCode:"REQUEST_TIMEOUT",stage:"callback",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"timeout",failureCategory:"provider_runtime"}),Re(),D(W,E,E===pa?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",ne?.generation)}finally{window.clearTimeout(tn);let E=Ye?.now()??globalThis.performance?.now()??Date.now();Ye?.performance({stage:"callback",durationMs:Math.max(0,E-Mt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...U?{statusClass:"timeout"}:{}}),ve(!1)}},[S,pe,e,t,n,T,Dt,M,r,j,o,l,s,g,b,D,K,ht,at,Ue,he,ee]),ie=St(()=>{let v=["applePay","googlePay","paypal","link","amazonPay","klarna"],P=new Set(["applePay","googlePay"]),Re=new Set(a.map(As)),ne={};for(let W of v)Re.has(W)?ne[W]=P.has(W)?"always":"auto":ne[W]="never";return ne},[a]),it=St(()=>a.map(As),[a]);return Te(Br,{children:[c(Ws,{state:Z,placeholderTestId:"flopay-wallet-placeholder",borderRadius:I,children:Te("div",{ref:xe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[A&&Te("button",{ref:Me,type:"button","data-testid":"flopay-wallet-retry-button",onClick:qe,style:Vs,children:["Try ",ei(Fe)," again"]}),be&&c(Xr,{identity:be.identity,methodLabel:be.methodLabel,onComplete:Qe,onCancel:()=>Qe(null)},be.id),c("div",{style:{display:be?"none":void 0},children:c(qs,{onReady:v=>{se(Ys(v,it))},onLoadError:v=>{se("load_error"),oi(jt(he),"stripe","wallet")},onClick:async v=>{ke.current=v.expressPaymentType,_.current=Ds(v.expressPaymentType);let P=!0,Re=window.setTimeout(()=>{P=!1,v.reject()},Dc),ne=b?await b(_.current):{proceed:!0};if(window.clearTimeout(Re),!P)return;if(!ne.proceed){Pe.current.delete(ee),v.reject();return}let W=de(v.expressPaymentType);Pe.current.set(ee,{generation:W,method:v.expressPaymentType,accountPatch:ne.accountPatch,sessionId:ne.sessionId,nonce:ne.nonce}),Be(!1),k?.(_.current),v.resolve()},onConfirm:He,onCancel:()=>{let v=Pe.current.get(ee);Pe.current.delete(ee),jt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Ie(v?.generation),Be(!1),ze.current=!0,V()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ie,emailRequired:tt,billingAddressRequired:tt,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),ae&&c(er,{status:"processing"})]})}function Gc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:s,borderColor:k,textColor:g,borderRadius:h,fontFamily:b}){let T=xc(e,t),M=Ts[e],[u,I]=ue(!1),he=T?.backgroundColor??s??"#ffffff",j=T?.borderColor??k??"#d1d5db",S=T?.textColor??g??"#262833";return c("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ma,padding:"0 1rem",backgroundColor:he,color:S,border:`1px solid ${j}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?c("span",{style:{margin:"0 auto"},children:`Connecting to ${Fr(e)}\u2026`}):Te(Br,{children:[Te("span",{style:{display:"inline-flex",alignItems:"center",gap:Sc(e)?8:0},children:[M&&!u?c("img",{src:M,alt:"","aria-hidden":"true",onError:()=>I(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):T?.logoSvg?c("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:T.logoSvg}}):null,c("span",{children:Fr(e)})]}),a&&c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:S,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:c("path",{d:"M9 18l6-6-6-6"})})]})})}function ti({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:s,onErrorChange:k,onDecline:g,onCancel:h,runBeforeButtonClick:b,onButtonClick:T,isProcessing:M,submitButtonColor:u,submitButtonBorderRadius:I,submitButtonStyle:he,errorText:j}){let S=gr(),{emitInstrument:pe}=oo(Dn),Z=ri(),se=ni(),[ae,ve]=ue(!1),tt=fe(!1),[be,Dt]=ue(!1),[Qe,xe]=ue("loading"),[Me,ee]=ue(""),Q=!en(r?.trim()),A=!Q||en(Me.trim()),Be=ge(async()=>{if(!Z||!se||M||tt.current||!be)return;tt.current=!0,ve(!0);let Fe=b?await b("card"):{proceed:!0};if(!Fe.proceed){tt.current=!1,ve(!1);return}T?.("card");let De=Fe.sessionId??t,ze=Fe.nonce??n,ke=Er(o?.trim()),_=Sn({email:Fe.accountPatch?.email?.trim()||r?.trim()||Me.trim(),firstName:Fe.accountPatch?.firstName?.trim()||ke.firstName,lastName:Fe.accountPatch?.lastName?.trim()||ke.lastName}),ce=_.email,Pe=Sn({...Fe.accountPatch,..._});try{if(k?.(null),!en(ce))throw new Error("A valid email address is required for payment.");await a?.(_);let de=await se.submit();if(de.error){k?.(de.error.message??"Payment failed.");return}let K=[_.firstName,_.lastName].filter(Boolean).join(" "),Ie=await Z.createPaymentMethod({elements:se,params:{billing_details:{email:ce,...K?{name:K}:{}}}});if(Ie.error||!Ie.paymentMethod){k?.(Ie.error?.message??"Failed to create payment method.");return}let at=Ie.paymentMethod;if(!De||!ce)throw new Error("Missing sessionId or email for payment.");let ht=at.type||e,Ue=await ya(l,pe,De,ze??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ht,paymentMethodId:null,intentKind:"payment"});if(Ue.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let V=Ue.clientSecret;if(typeof window<"u")try{localStorage.setItem(tr,JSON.stringify({clientSecret:V,sessionId:De,nonce:ze,accountPatch:Pe,paymentMethodId:at.id,paymentMethodType:at.type??e,gateway:"stripe"}))}catch{}let{error:D,paymentIntent:B}=await Z.confirmPayment({clientSecret:V,confirmParams:{return_url:window.location.href,payment_method:at.id},redirect:"if_required"});if(D){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=D.message??"Payment failed.";k?.(ie),g?.(Vt("card",ie,{code:D.code})),await fa({billingApiUrl:l,sessionId:De,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:D.code??"provider_declined"}});return}let qe=B?.status;if(!Eo(qe)){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";k?.(ie),g?.(Vt("card",ie,{code:qe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let He=typeof B?.payment_method=="string"?B.payment_method:B?.payment_method?.id;s({id:He??at.id,type:"card",threeDSecureActionResultTokenId:B?.id,gateway:"stripe",paymentMethodType:at.type??e},{accountPatch:Pe,paymentMethodCategory:"apm",sessionId:De,nonce:ze})}catch(de){k?.(de instanceof Error?de.message:"Payment failed. Please try again.")}finally{tt.current=!1,ve(!1)}},[Z,se,M,be,b,T,t,n,r,o,Me,a,l,pe,e,s,k,g]);return Te("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[Q&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:Q&&Te("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:Me,onChange:Fe=>ee(Fe.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(Ac,{onReady:()=>xe("ready"),onLoadError:()=>{xe("load_error"),oi(jt(S),"stripe","apm")},onChange:Fe=>{Dt(!!Fe.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...en(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Be()},disabled:!be||!A||ae||M||Qe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:I,fontSize:"1rem",fontWeight:600,cursor:!be||!A||ae||M||Qe!=="ready"?"not-allowed":"pointer",opacity:!be||!A||ae||M||Qe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:ae?"Processing\u2026":`Pay with ${Fr(e)}`}),j&&c(eo,{margin:"0.75rem 0 0",children:j})]})}function Us({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:s,paymentElementBaseOptions:k,onTokenizedBody:g,onErrorChange:h,onButtonClick:b,onDecline:T,runBeforeButtonClick:M,onLoadStateChange:u,isProcessing:I=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:j=8,submitButtonStyle:S,buttonAppearance:pe,themeId:Z,onExpandApm:se,expandedApmMethod:ae}){let{emitInstrument:ve}=oo(Dn),[tt,be]=ue(null),[Dt,Qe]=ue(null),xe=fe(!1),{request:Me,collect:ee,finish:Q}=Jr();wt(()=>{l.length>0&&s?u?.("ready"):s||u?.("loading")},[l.length,s,u]);let A=ge(async _=>{if(!s||xe.current||I)return;xe.current=!0,Qe(_);let ce=M?await M("card"):{proceed:!0};if(!ce.proceed){xe.current=!1,Qe(null);return}b?.("card");let Pe=ce.sessionId??e,de=ce.nonce??t,K=Er([ce.accountPatch?.firstName,ce.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ie=Sn({email:ce.accountPatch?.email?.trim()||n?.trim(),firstName:ce.accountPatch?.firstName?.trim()||K.firstName,lastName:ce.accountPatch?.lastName?.trim()||K.lastName});if(!en(Ie.email)){Qe(null);let Ue=await ee(Fr(_),Ie);if(!Ue){xe.current=!1;return}Ie=Ue,Qe(_)}let at=Ie.email,ht=Sn({...ce.accountPatch,...Ie});try{if(h?.(null),!Pe||!en(at))throw new Error("Missing sessionId or email for payment.");await o?.(Ie);let Ue=await ya(a,ve,Pe,de??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,paymentMethodId:null,intentKind:"payment"});if(Ue.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let V=Ue.clientSecret;if(typeof window<"u")try{localStorage.setItem(tr,JSON.stringify({clientSecret:V,sessionId:Pe,nonce:de,accountPatch:ht,paymentMethodType:_,gateway:"stripe"}))}catch{}let{error:D,paymentIntent:B}=await s.confirmPayment({clientSecret:V,confirmParams:{return_url:window.location.href,payment_method_data:{type:_,billing_details:{name:[Ie.firstName,Ie.lastName].filter(Boolean).join(" "),...at?{email:at}:{}}}},redirect:"if_required"});if(D){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=D.message??"Payment failed.";h?.(ie),T?.(Vt("card",ie,{code:D.code})),await fa({billingApiUrl:a,sessionId:Pe,nonce:de,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,providerDeclineReason:D.code??"provider_declined"}});return}let qe=B?.status;if(!Eo(qe)){if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let ie=qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(ie),T?.(Vt("card",ie,{code:qe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(tr)}catch{}let He=typeof B?.payment_method=="string"?B.payment_method:B?.payment_method?.id;g({id:He??B?.id,type:"card",threeDSecureActionResultTokenId:B?.id,gateway:"stripe",paymentMethodType:_},{accountPatch:ht,paymentMethodCategory:"apm",sessionId:Pe,nonce:de})}catch(Ue){h?.(Ue instanceof Error?Ue.message:"Payment failed. Please try again.")}finally{xe.current=!1,Qe(null)}},[s,I,M,b,e,t,n,ee,a,ve,r,o,g,h,T]),[Be,Fe]=ue(null),De=se?ae??null:Be,ze=ge(_=>{xe.current||I||De&&De!==_||(Ms(_)?se?se(_):Fe(_):A(_))},[De,I,A,se]),ke=St(()=>Be?{...k,paymentMethodTypes:[Be]}:null,[Be,k]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Me?c(Xr,{identity:Me.identity,methodLabel:Me.methodLabel,onComplete:Q,onCancel:()=>Q(null)},Me.id):l.map(_=>{let ce=ae===_,Pe=Dt===_,de=Dt!==null&&Dt!==_||ae!=null&&ae!==_;return Te(Bc.Fragment,{children:[c(Gc,{method:_,themeId:Z,submitting:Pe,disabled:de,highlighted:ce,hasNextStep:Ms(_),onClick:()=>ze(_),backgroundColor:pe?.backgroundColor,borderColor:pe?.borderColor,textColor:pe?.textColor,borderRadius:pe?.borderRadius,fontFamily:pe?.fontFamily}),!se&&Be===_&&ke&&s&&c(Ar,{stripe:s,options:ke,children:c(ti,{method:_,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:g,onErrorChange:h,onDecline:T,onCancel:()=>Fe(null),runBeforeButtonClick:M,onButtonClick:b,isProcessing:I,submitButtonColor:he,submitButtonBorderRadius:j,submitButtonStyle:S})},_)]},_)})})}function Jc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:s,onTokenizedBody:k,firstName:g,lastName:h,chv:b,className:T,isProcessing:M,error:u,onErrorChange:I,showPayPal:he=!0,showStripe:j=!0,enabledPaymentMethods:S,enabledPaymentMethodCountries:pe,showApplePay:Z=!0,showGooglePay:se=!0,layout:ae="default",theme:ve,buttonsTheme:tt,buttonsStyles:be,appearance:Dt,cardButtonContent:Qe,cardBackButtonContent:xe,cardTitleContent:Me,showSecurityFooter:ee,onButtonClick:Q,onBeforeButtonClick:A,onBuyerIdentityReady:Be,enableAVS:Fe,cardFieldOrder:De,cardPreFormSlot:ze,avsLayout:ke="row",country:_,zip:ce,addressLine1:Pe,addressLine2:de,city:K,state:Ie,onCountryChange:at,onZipChange:ht,avsCheck:Ue,checkoutType:V,checkoutLayout:D,totalAmount:B=0,currency:qe="usd",initialCardOpen:He=!1,directPaypal:ie,isSubscription:it=!1,session:v,dataAttachmentPending:P=!1,dataAttachmentRequiresIdentity:Re=!1,debug:ne=!1}){let W=gr(),nt=Ua(),Ae=oo(Hn),{emitInstrument:Ye}=oo(Dn),Mt=v??Ae.session,C=Mt?.gateways?.paypal?.providerObjectType??ie?.providerObjectType,U=P||Ae.claimPending===!0,st=Re||Ae.claimRequiresIdentity===!0,We=U&&!st,tn=ms(),[Wt,E]=ue(!1),[mt,Tt]=ue(null),[lt,Rt]=ue(_??"US"),[pn,an]=ue(ce??""),[mn,Lt]=ue(Pe??""),[wn,Gt]=ue(de??""),[yt,Ge]=ue(K??""),[ft,sn]=ue(Ie??""),[et,Wn]=ue(""),[dt,nn]=ue({}),bt=fe(ce??""),Jt=fe(_??"US"),kn=fe(Pe??""),yn=fe(de??""),_n=fe(K??""),ln=fe(Ie??""),Tn=fe(""),qt=fe({});wt(()=>{let i=(y,N,_e,z,Ee)=>{if(qt.current[y])return;let Oe=N?.trim();!Oe||Oe===_e.current||(_e.current=Oe,z(Oe),Ee?.(Oe))};i("country",_,Jt,Rt,at),i("zip",ce,bt,an,ht),i("addressLine1",Pe,kn,Lt),i("addressLine2",de,yn,Gt),i("city",K,_n,Ge),i("state",Ie,ln,sn)},[_,ce,Pe,de,K,Ie,at,ht]);let G=St(()=>_c(Fe),[Fe]),fn=G!==null,Nn=St(()=>Ja(v),[v]),Gn=!!v?.vault?.html,Cr=!!v?.gateways?.pcivault,cr=!!(v?.gateways?.stripe?.enabledPaymentMethods??S)?.includes("card"),Nt=Gn||cr||Cr,$e=!!(j&&Nt&&W&&e),[dr,w]=ue(()=>ae!=="buttons"||He?e??null:null),[ct,Kt]=ue(0),In=ae!=="buttons"||He||!!e&&dr===e,me=St(()=>!W||!$e||!e||!In?null:W.cardCapture({sessionId:e,captureMethod:v?.captureMethod}),[W,$e,e,In,v?.captureMethod]),cn=St(()=>{let i=lt,y=G?Ve(G.postal_code,i):!1;return Hc(i,pn,y)},[G,lt,pn]),{avsInvalid:wr,invalidAvsFields:Lr}=St(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!$e||!G)return{avsInvalid:!1,invalidAvsFields:i};let y=lt,N=(Ee,Oe)=>Ve(Ee,y)&&!Oe.trim(),_e={line1:N(G.address_line_1,mn),city:N(G.city,yt),state:N(G.state,ft),zip:cn.empty||cn.malformed};return{avsInvalid:_e.line1||_e.city||_e.state||_e.zip,invalidAvsFields:_e}},[$e,G,lt,mn,yt,ft,cn]),[gn,ur]=ue(!1),[Jn,On]=ue(!1),[Ot,zn]=ue(!1),[Xn,hn]=ue({line1:!1,city:!1,state:!1}),rn=fe(!1),Un=fe({email:!1,line1:!1,city:!1,state:!1,zip:!1}),qn=fe(!1),ut=ge(i=>{Un.current[i]=!0,qn.current=!0},[]),bn=ge(i=>!rn.current&&Un.current[i],[]),vn=ge(i=>{bn(i)&&hn(y=>y[i]?y:{...y,[i]:!0})},[bn]),[$n,xn]=ue(()=>Xa(v?.vault)),[Ce,on]=ue(He&&Nt?"card":"buttons"),[zt,pr]=ue(null),jn=Ce==="expanding"||Ce==="card",mr=v?.gateways?.stripe?"stripe":void 0,En=ge(()=>{Ye?.({class:"card_surface",provider:mr})},[mr,Ye]),Mn=fe(null),Ut=ge(i=>{Mn.current&&clearTimeout(Mn.current),Mn.current=setTimeout(()=>{Mn.current=null,i()},Mr)},[]);wt(()=>()=>{Mn.current&&clearTimeout(Mn.current)},[]);let x=ge(()=>{En(),w(e??null),Kt(i=>i+1),on("expanding"),Ut(()=>on("card"))},[Ut,En,e]),L=ge(()=>{on("collapsing"),Ut(()=>on("buttons"))},[Ut]),H=ge(i=>{pr(i),on("apm-expanding"),Ut(()=>on("apm-form"))},[Ut]),Y=ge(()=>{on("apm-collapsing"),Ut(()=>{on("buttons"),pr(null)})},[Ut]);wt(()=>{ae==="buttons"&&He&&Nt&&(w(e??null),on("card"))},[ae,He,Nt,e]);let[Se,F]=ue(null),q=fe(!1),p=fe(null),O=fe("idle"),[$,gt]=ue(null),vt=fe($);wt(()=>{vt.current=$},[$]);let te=n||tn,we=fe(null),Xt=St(()=>{if(Be||Ae.claimBuyerIdentity||v?.buyerIdentified!==!1||!e||!t)return;let i=`${te}|${e}|${t}`;we.current?.key!==i&&(we.current={key:i,claim:Wr(new ro(te,{telemetry:!1}),e,t,{...o?{userId:o}:{},...g?{firstName:g}:{},...h?{lastName:h}:{}})});let y=we.current.claim;return async N=>{await y(N)}},[Be,Ae.claimBuyerIdentity,v?.buyerIdentified,e,t,te,o,g,h]),rt=Be??Ae.claimBuyerIdentity??Xt,m=u??mt,d=St(()=>Mc(ve),[ve]),f=St(()=>{let i=d?.buttonsLayout??Tc(tt);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},[d,tt,be]),ye=Dt??d?.appearance,re=St(()=>es({appearance:ye,buttonsStyles:f,layout:ae}),[ye,f,ae]),je=Ae.inlineSessionPatchProcessing??!1,Je=(M??Wt)||je,J=te.replace(/\/+$/,""),R=St(()=>za({userId:o,email:r,firstName:g,lastName:h,country:_,zip:ce},dt),[o,r,g,h,_,ce,dt]),oe=[R.firstName,R.lastName].filter(i=>!!i?.trim()).join(" "),Ke=!en(R.email?.trim()),Le=fe(null);$e&&Le.current===null&&(Le.current=Ke);let Pt=$e&&(Le.current??Ke),Ne=St(()=>Yc(et,Pt),[et,Pt]),$t=Ne.empty||Ne.malformed,Rn=St(()=>W?W.getRawProvider():null,[W]),Nr=St(()=>nt?nt.getRawProvider():null,[nt]),co=B||100,Or=qe.toLowerCase(),Pa=St(()=>ye?gc(ye):null,[ye]),zr=Pa,Ci=St(()=>{let i=Pa??{},y=i.rules??{};return{...i,rules:{...y,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...y[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...y[".AccordionItemContents"]??{}}}}},[Pa]),Si=St(()=>({...is(B,v?.captureMethod),currency:Or,...zr?{appearance:zr}:null}),[B,Or,v?.captureMethod,zr]),wi=St(()=>({mode:"payment",amount:co,currency:Or,captureMethod:"manual",setupFutureUsage:"off_session",...zr?{appearance:zr}:null}),[co,Or,zr]),le=ge(i=>{Tt(i),I?.(i)},[I]),Ca=fe(""),[ki,al]=ue(!1),Sa=ge(()=>{al(!0)},[]);wt(()=>{if(!$e||!Pt||!rt||!ki||$t||Ca.current)return;let i=Sn({email:en(R.email?.trim())?R.email?.trim():Tn.current.trim(),firstName:R.firstName?.trim(),lastName:R.lastName?.trim()});Ca.current=JSON.stringify(i),nn(y=>({...y,...i})),Promise.resolve(rt(i)).catch(y=>{Ca.current="",le(y instanceof Error?y.message:"Failed to attach buyer details.")})},[$e,Pt,rt,ki,$t,R.email,R.firstName,R.lastName,le]),wt(()=>{!$e||!me||me.setCardFieldOrder?.(De??null,G==null&&!Pt)},[$e,me,De,G,Pt]),wt(()=>{(Ce==="expanding"||Ce==="collapsing"||Ce==="apm-expanding"||Ce==="apm-collapsing")&&le(null)},[Ce,le]);let Kn=ge((i,y,N)=>{s?.(Vt(i,y,N))},[s]),Ur=ge((i,y,N)=>{let _e=N?.popupBlocked??fr(y),z=Kc(i,_e),Ee=_r(N?.code)??ar(y)??"external_payment_method_failed",Oe=new Yn(z,"api_error",{code:"external_payment_method_failed",param:i});F(null),ae==="buttons"&&(on("buttons"),pr(null)),le(z),l?.(Oe),console.error("[FloPay] External payment method failed:",{method:i,code:Ee,popupBlocked:_e})},[ae,l,le]);wt(()=>{if(!$e||!e){xn(null);return}let i=Xa(v?.vault);if(i){xn(i);return}if(!In){xn(null);return}xn(null);let y=!0;return new ro(J).getVaultCapture(e,t).then(N=>{if(!y)return;let _e=Xa(N);_e?xn(_e):le("Failed to load the secure card form.")}).catch(N=>{y&&le(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{y=!1}},[$e,In,ct,e,v?.vault,J,t,le]);let Zn=fe({onComplete:a,onError:l,updateError:le,emitDecline:Kn,resolvedAccount:R,avsConfig:G,avsCheckProp:Ue,sessionId:e,nonce:t,baseUrl:J,captureMethod:v?.captureMethod,paymentId:v?.paymentId,authorizationExpiresAt:v?.authorizationExpiresAt});Zn.current={onComplete:a,onError:l,updateError:le,emitDecline:Kn,resolvedAccount:R,avsConfig:G,avsCheckProp:Ue,sessionId:e,nonce:t,baseUrl:J,captureMethod:v?.captureMethod,paymentId:v?.paymentId,authorizationExpiresAt:v?.authorizationExpiresAt};let wa=fe(!1),Ii=ge(()=>{let{resolvedAccount:i,avsConfig:y,avsCheckProp:N}=Zn.current,_e=i.email?.trim(),z=en(_e)?_e:Tn.current.trim();if(!en(z))return null;let Ee=i.firstName?.trim(),Oe=i.lastName?.trim(),pt=Jt.current||i.country||"US",Zt=y?Ve(y.state,pt):!1,kt=y?Ve(y.address_line_1,pt):!1,It=y?Ve(y.postal_code,pt):!1,ot=y?Ve(y.city,pt):!1,dn=y?Ve(y.address_line_2,pt):!1,Xe=kt&&!Zt&&It?xs(pt,(bt.current??"").trim()):null,un=Zt?ln.current:Xe;return{accountData:{userId:i.userId??"",email:z,...Ee?{firstName:Ee}:{},...Oe?{lastName:Oe}:{},...It&&bt.current?{zip:bt.current}:{},...ot&&_n.current?{city:_n.current}:{},...un?{state:un}:{},...kt&&kn.current?{addressLine1:kn.current}:{},...dn&&yn.current?{addressLine2:yn.current}:{},country:pt},...N!==void 0?{avsCheck:N}:{},...y?{avsConfig:{country:Ve(y.country,pt),postal_code:It,address_line_1:kt,address_line_2:dn,city:ot,state:Zt}}:{}}},[]),Ei=fe(U);Ei.current=U,wt(()=>{U||m!==Fs||Zn.current.updateError(null)},[U,m]),wt(()=>{!$e||!me||me.setSubmitGate?.(wr||U||$t)},[$e,me,wr,U,$t]),wt(()=>{if(!$e||!me)return;wa.current=!1;let i=!1,y=me.on("submitting",()=>{ur(!0),p.current&&clearTimeout(p.current),O.current="validation-window",p.current=setTimeout(()=>{p.current=null,O.current==="validation-window"&&(O.current="processing")},Nc),F("processing");let{baseUrl:Oe,sessionId:pt,nonce:Zt,updateError:kt,onError:It}=Zn.current;if(!pt||!Zt)return;let ot=Ii();if(!ot){kt("Enter a valid email address."),O.current="idle",F(null);return}new ro(Oe).patchAccountSnapshot(pt,Zt,ot,{telemetryMode:"best_effort"}).catch(dn=>{if(!Oc(dn))return;let Xe=dn instanceof Error?dn.message:"Please check your billing address and try again.";kt(Xe),O.current="idle",F(null),It?.(dn instanceof Yn?dn:new Yn(Xe,"api_error"))})}),N=me.on("complete",async Oe=>{if(to(Oe.sessionId??Zn.current.sessionId),O.current="terminal",F("success"),await new Promise(kt=>setTimeout(kt,1200)),wa.current)return;wa.current=!0;let pt=Zn.current,Zt=Ja(pt)||Oe.outcome==="authorized";Zn.current.onComplete?.(Zt?{status:"authorized",paymentIntentId:Oe.intentId,paymentId:Oe.paymentId??pt.paymentId,sessionId:Oe.sessionId??pt.sessionId,authorizationExpiresAt:Oe.authorizationExpiresAt??pt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Oe.intentId,checkoutMethod:"card"})}),_e=me.on("decline",async Oe=>{let{updateError:pt,emitDecline:Zt}=Zn.current,kt=Oe.message??"Your payment was declined. Please try another card or contact your bank.";O.current="terminal",pt(kt),F("error");let It=Oe.failureOutcome??Ec(Oe.declineReason)??"authorization_declined";Zt("card",kt,{code:It,declineCode:It}),await new Promise(ot=>setTimeout(ot,1500)),!i&&(O.current="idle",F(null))}),z=me.on("error",async Oe=>{let{updateError:pt,onError:Zt}=Zn.current,kt=Oe.message??"There was a problem processing your payment. Please try again.";O.current="terminal",pt(kt),F("error"),Zt?.(new Yn(kt,"api_error",{code:Oe.failureOutcome??"capture_failed"})),await new Promise(It=>setTimeout(It,1500)),!i&&(O.current="idle",F(null))}),Ee=me.on("blocked",()=>{if(!Ei.current){ur(!0);return}Sa(),Zn.current.updateError(Fs)});return()=>{i=!0,p.current&&(clearTimeout(p.current),p.current=null),O.current="idle",y(),N(),_e(),z(),Ee()}},[$e,me,Sa,Ii]);let Qn=!!ie?.clientId,uo=Array.isArray(S),jo=uo&&S.length>0,il=uo&&S.includes("paypal"),{expressMethods:Ko,paymentElementMethods:po}=St(()=>Rc(S,{excludePaypal:Qn}),[S,Qn]),Ri=Qn||!!nt,sl=St(()=>Ri?Ko.filter(i=>i!=="paypal"):Ko,[Ko,Ri]),ll=St(()=>{let i=[];return Z&&i.push("apple_pay"),se&&i.push("google_pay"),i},[Z,se]),qr=uo?sl:ll,cl=j&&qr.length>0,ka=fn?lt:_,Vo=St(()=>{let i=ka?.trim().toUpperCase();return i?pe?po.filter(y=>{let N=pe[y];return!N||N.length===0||N.includes(i)}):vc(po,ka):po},[po,ka,pe]),Ia=St(()=>({mode:"payment",amount:co,currency:Or,paymentMethodCreation:"manual",appearance:Ci}),[co,Or,Ci]),[_i,Ti]=ue("loading"),[xi,Mi]=ue("loading"),[Ai,Bi]=ue("loading"),[dl,Ea]=ue(!1),[Fi,Ra]=ue("loading"),[Ho,ul]=ue();wt(()=>{ul(_s())},[]);let Di=he&&(Qn||(uo?il:Ho===!1)),Li=j&&cl,mo=!We&&Di&&Qn,Ni=Fi==="retrying"||Fi==="exhausted",yo=!We&&Di&&!!Nr&&(!Qn||Ni),fo=!We&&Li&&!!Rn,go=!We&&j&&jo&&Vo.length>0&&!!Rn,pl=mo&&!Ni?dl:yo&&Ns(_i),ml=fo&&Ns(xi),yl=go&&Ai!=="load_error",Oi=i=>i==="loading"||i==="ready",zi=mo||yo&&Oi(_i)||fo&&Oi(xi)||go&&Ai!=="load_error",Yo=fe(!1);wt(()=>{if(!Yo.current){if(!j&&!he){Yo.current=!0;let i=new Yn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),le(i.message)}else if(!j&&he&&!Qn&&!Nr){Yo.current=!0;let i=new Yn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(i),le(i.message)}else if(Ho!==void 0&&!We&&!Nt&&!zi){Yo.current=!0;let i=new Yn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(i),le(i.message)}}},[j,he,Qn,Nr,Ho,We,Nt,zi,l,le]);let Ui=fe(!1);wt(()=>{if(Ui.current||!jo)return;let i=[];Z!==!0&&i.push("showApplePay"),se!==!0&&i.push("showGooglePay"),i.length!==0&&(Ui.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.`))},[jo,Z,se]);let qi=ge((i,y)=>Ae.applyInlineSessionPatch?Ae.applyInlineSessionPatch(i).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let _e=Ls(y,N);return le(_e.message),l?.(_e),{error:_e,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ae.applyInlineSessionPatch,t,l,e,le]),Vn=ge(async i=>{if(!A)return{proceed:!0};try{let y=await A({method:i,sessionId:e||void 0,createSession:Ae.inlineSessionDraft});if(y===!1)return{proceed:!1};if(y&&typeof y=="object"){y.account&&nn(_e=>({..._e??{},...y.account}));let N=await qi(y,i);return N.error?{proceed:!1,accountPatch:y.account}:{proceed:!0,accountPatch:y.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(y){let N=Ls(i,y);return le(N.message),l?.(N),{proceed:!1}}},[qi,Ae.inlineSessionDraft,A,l,e,le]),$i=ge(async(i,y)=>{if(q.current)return;q.current=!0,E(!0),F("processing"),le(null);let N=y?.sessionId??e,_e=y?.nonce??t,z=za(R,y?.accountPatch),Ee=y?.completionPaymentMethodId??Ro(i),Oe=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,pt=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Zt=()=>{Ye?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:pt})};try{let It=await new ro(J).processPayment(z.userId??"",{sessionId:N,nonce:_e,paymentMethodCategory:y?.paymentMethodCategory??$c(i),tokenizedData:Oe,accountData:{...y?.accountPatch,userId:z.userId??"",email:z.email??"",...z.firstName?{firstName:z.firstName}:{},...z.lastName?{lastName:z.lastName}:{},...G?(()=>{let Xe=Jt.current,un=Ve(G.state,Xe),Bn=Ve(G.address_line_1,Xe),Qt=Ve(G.postal_code,Xe),So=Bn&&!un&&Qt?xs(Xe,(bt.current??"").trim()):null,wo=un?ln.current:So;return{country:Xe,...Qt&&bt.current?{zip:bt.current}:{},...Ve(G.city,Xe)&&_n.current?{city:_n.current}:{},...wo?{state:wo}:{},...Bn&&kn.current?{addressLine1:kn.current}:{},...Ve(G.address_line_2,Xe)&&yn.current?{addressLine2:yn.current}:{}}})():{}},chv:b,avsCheck:Ue??!1,checkoutType:V,checkoutLayout:D,avsConfig:G?{country:Ve(G.country,Jt.current),postal_code:Ve(G.postal_code,Jt.current),address_line_1:Ve(G.address_line_1,Jt.current),address_line_2:Ve(G.address_line_2,Jt.current),city:Ve(G.city,Jt.current),state:Ve(G.state,Jt.current)}:void 0});if(It.ok){let Xe=It.status===204?null:await It.json().catch(()=>null),un=Ja(v)||Xe?.status==="authorized";to(N),F("success"),gt(null),await new Promise(Bn=>setTimeout(Bn,1200)),a?.(un?{status:"authorized",...typeof Xe?.paymentId=="string"?{paymentId:Xe.paymentId}:v?.paymentId?{paymentId:v.paymentId}:{},sessionId:typeof Xe?.sessionId=="string"?Xe.sessionId:N,...typeof Xe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Xe.authorizationExpiresAt}:v?.authorizationExpiresAt?{authorizationExpiresAt:v.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Ee,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Ee,checkoutMethod:i.isPaypal?"paypal":"card"});return}let ot=await It.json().catch(()=>null);if(ot?.type==="paypal_redirect_required"){let Xe=ot.threeDSecureToken,un=ot.paymentMethodId||i.id||"";if(!W||!Xe){F("error"),le("PayPal authorization required but no token provided.");return}try{let Bn=nt?.getRawProvider();if(!Bn){le("PayPal is not available.");return}let Qt={return_url:window.location.href};un&&(Qt.payment_method=un);let{error:So}=await Bn.confirmPayment({clientSecret:Xe,confirmParams:Qt,redirect:"if_required"});if(So){F("error");let wo=So.message??"PayPal payment failed.";le(wo),Kn("paypal",wo,{code:So.code})}}catch(Bn){F("error"),le(Bn instanceof Error?Bn.message:"PayPal authorization failed.")}return}if(ot?.type==="paypal_direct_required"){let Xe=ot.orderId;if(!Xe){F("error"),le("PayPal retry required but no order id provided.");return}let un=vt.current?.attempts??0;if(un>=2){F("error"),le("PayPal payment could not be completed after multiple attempts."),Kn("paypal","paypal_direct_required retry limit exceeded");return}Ea(!1),Ra("loading"),gt({orderId:Xe,attempts:un+1}),F(null);return}bc(It.status,ot)||Zt(),F("error");let dn=ot?.message??"Payment failed. Please try again.";le(dn),Kn(i.isPaypal?"paypal":"card",dn,{code:ot?.code??ot?.gatewayErrorCode,declineCode:ot?.declineCode??ot?.gatewayDeclineReason}),await new Promise(Xe=>setTimeout(Xe,1500))}catch(kt){js(kt)||Zt(),F("error"),le(kt instanceof Error?kt.message:"An unexpected error occurred"),await new Promise(It=>setTimeout(It,1500))}finally{E(!1),F(null),q.current=!1}},[J,e,t,R,G,Ue,V,D,b,W,nt,v,a,le,Kn,Ye]),Pn=ge((i,y)=>{k?k(i):$i(i,y)},[k,$i]),ho=`${$s}:${e}`;wt(()=>{if(typeof window>"u")return;let i=localStorage.getItem(ho);if(!i)return;let y;try{y=JSON.parse(i)}catch{localStorage.removeItem(ho);return}if(!y||typeof y.createdAt!="number"||Date.now()-y.createdAt<0||Date.now()-y.createdAt>Fc||typeof y.paymentMethodId!="string"||typeof y.providerIntentId!="string"||typeof y.paymentMethodType!="string"||y.sessionId!==e||!t||y.nonce!==t||!qr.includes(y.paymentMethodType)){localStorage.removeItem(ho);return}localStorage.removeItem(ho),Pn({id:y.paymentMethodId,type:"card",threeDSecureActionResultTokenId:y.providerIntentId,gateway:"stripe",paymentMethodType:y.paymentMethodType},{...y.accountPatch?{accountPatch:y.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Pn,t,e,ho,qr]);let ji=fe(!1);wt(()=>{if(typeof window>"u"||ji.current)return;let i=new URLSearchParams(window.location.search),y=i.get("payment_intent"),N=i.get("payment_intent_client_secret"),_e=i.get("redirect_status");if(!y||!N)return;let z=It=>{let ot=localStorage.getItem(It);if(!ot)return null;try{return JSON.parse(ot)}catch{return localStorage.removeItem(It),null}},Ee=z(tr)??z(Bs),Oe;if(Ee?.clientSecret){if(Ee.clientSecret!==N)return;Oe={...Ee.accountPatch?{accountPatch:Ee.accountPatch}:{},...Ee.sessionId?{sessionId:Ee.sessionId}:{},...Ee.nonce?{nonce:Ee.nonce}:{}}}else if(Ee?.sessionId&&Ee.sessionId!==e)return;ji.current=!0,localStorage.removeItem(tr),localStorage.removeItem(Bs);let pt=new URL(window.location.href);pt.searchParams.delete("payment_intent"),pt.searchParams.delete("payment_intent_client_secret"),pt.searchParams.delete("redirect_status"),window.history.replaceState({},"",pt.toString());let Zt=Ee?.paymentMethodType??Ee?.tokenType??"card",kt="card";(async()=>{let It=W?.getRawProvider();if(!It){let Qt="Payment is not available \u2014 please refresh and try again.";le(Qt),Kn(kt,Qt);return}if(_e==="failed"){let Qt="Payment was declined. Please try again.";le(Qt),Kn(kt,Qt);return}let{paymentIntent:ot,error:dn}=await It.retrievePaymentIntent(N);if(dn){let Qt=dn.message??"Failed to retrieve payment status.";le(Qt),Kn(kt,Qt,{code:dn.code});return}let Xe=ot?.status,un=Eo(Xe);if(!ot||!un){let Qt=Xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";le(Qt),Kn(kt,Qt,{code:Xe??"missing_payment_intent"});return}let Bn=typeof ot.payment_method=="string"?ot.payment_method:ot.payment_method?.id;Pn({id:Bn??Ee?.paymentMethodId??Ee?.tokenId??ot.id,type:"card",threeDSecureActionResultTokenId:ot.id,gateway:Ee?.gateway??"stripe",paymentMethodType:Zt},Oe)})()},[e,Pn,W,le,Kn]);let _a=ge(i=>{i.preventDefault()},[]);if(!(W!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let bo=ae==="buttons",Cn=ye?.variables,fl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ta=Cn?.colorBackground,gl=Ta&&!fl.has(Ta)?Ta:void 0,vo=f.cardInputBorder??(bo?"#e5e7eb":"#A4A4FF"),Ki=Cn?.colorDanger??"#dc2626",xt=i=>Lr[i]&&(Xn[i]||gn),Wo=$t&&(Ot||gn),An=i=>i?Ki:vo,Go=(cn.malformed||cn.empty)&&(Jn||gn),hl=An(Go),xa=f.cardFormContainer?.backgroundColor??gl??(bo?"white":"#EDEDFF"),$r=f.cardInputBackground??Cn?.colorBackground??"white",Ma=Kr(xe),Vi=Kr(Me),jr=f.nameInput,Hi=f.cardInputFontSize??Wc(jr?.fontSize)??Cn?.fontSizeBase??"16px",Yi=typeof jr?.fontFamily=="string"?jr.fontFamily:Cn?.fontFamily??"Poppins, sans-serif",Wi=Qi(jr?.fontWeight)??400,bl=f.cardInputColor??(typeof jr?.color=="string"?jr.color:void 0)??Cn?.colorText??"#262833",vl=f.cardInputPlaceholderColor??"#9ca3af",At=Cn?.borderRadius??"8px",kr=Cn?.borderRadius??f.cardButton?.borderRadius??At,Ir=Cn?.colorPrimary??"#4A49FF",Pl=Cn?.colorPrimaryHover??ko(Ir,.12),Aa=Cn?.colorText??"#262833",Ba={fontSize:Hi,fontFamily:Yi,fontWeight:Wi,color:bl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Po={marginTop:"0.375rem",...Ba,fontSize:"0.75rem",lineHeight:1.4,color:Ki},Cl={"--flopay-input-placeholder-color":vl,"--flopay-input-font-size":Hi,"--flopay-input-font-family":Yi,"--flopay-input-font-weight":String(Wi)},Co=f.cardFormContainer??{},Fa=Co.padding??(bo?"0":"1rem"),Da=Co.borderRadius??At,Sl=me&&$n?c(La,{capture:me,html:$n.html,messageToken:$n.messageToken,expectedOrigin:$n.expectedOrigin,theme:re,onReady:()=>{if(!Pt&&!G||typeof document>"u")return;let i=()=>{let N=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(N){rn.current=!0;try{N.focus()}finally{rn.current=!1}}};qn.current||i()},onError:i=>le(i),onValidation:i=>{let y=O.current;(y==="idle"||y==="validation-window")&&(le(i),i&&O.current==="validation-window"&&(p.current&&(clearTimeout(p.current),p.current=null),O.current="idle",F(null)))}}):c("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Gi=Te("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&En()},style:{backgroundColor:xa,borderRadius:Da,...Co,padding:Fa,...Cl,display:"flex",flexDirection:"column"},children:[c("style",{children:`
|
|
26
26
|
.flopay-shared-input::placeholder {
|
|
27
27
|
color: var(--flopay-input-placeholder-color);
|
|
28
28
|
opacity: 1;
|
|
@@ -30,13 +30,13 @@ ${en.join(`
|
|
|
30
30
|
font-family: var(--flopay-input-font-family);
|
|
31
31
|
font-weight: var(--flopay-input-font-weight);
|
|
32
32
|
}
|
|
33
|
-
`}),
|
|
34
|
-
`)}):null,
|
|
35
|
-
`)}):null,Xi=Ce==="apm-expanding"||Ce==="apm-form"||Ce==="apm-collapsing",Xo=Ce==="apm-expanding"?`flopay-card-enter ${Mr}ms cubic-bezier(0, 0, 0.2, 1) both`:Ce==="apm-collapsing"?`flopay-card-exit ${Mr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Zo=zt?{...wa,paymentMethodTypes:[zt]}:null;if(ae==="buttons"){let i=Ce==="buttons"||Ce==="expanding"||Ce==="apm-expanding",y=Ce==="expanding"||Ce==="card"||Ce==="collapsing",N=Xe===void 0?{boxSizing:"border-box",height:pa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Te=Ce==="expanding"||Ce==="apm-expanding"?`flopay-buttons-exit ${Mr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ce==="collapsing"||Ce==="apm-collapsing"?`flopay-buttons-enter ${Mr}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,z=Ce==="expanding"?`flopay-card-enter ${Mr}ms cubic-bezier(0, 0, 0.2, 1) both`:Ce==="collapsing"?`flopay-card-exit ${Mr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return xe("form",{onSubmit:Ea,className:T,noValidate:!0,style:{position:"relative"},children:[c(Xa,{}),Se&&c(er,{status:Se,errorMessage:m,authorized:Nn}),xe("div",{style:{display:"grid"},children:[xe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Te?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Te?zc:{},...Te?{animation:Te,pointerEvents:"none"}:{}},children:[Gi("flopay-direct-paypal-gate-debug"),Ji("flopay-stripe-gate-debug"),uo&&ie&&xe(Br,{children:[$&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(aa,{sessionId:e,nonce:t,billingApiUrl:te,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:nt,clientId:ie.clientId,environment:ie.environment,currency:Ee.toUpperCase(),isSubscription:at,providerObjectType:P,onTokenizedBody:Pn,onComplete:a,onErrorChange:le,onDecline:s,onTechnicalFailure:Or,onButtonClick:Q,runBeforeButtonClick:Hn,isProcessing:We,onLoadStateChange:ka,onInitializationStateChange:Ia,session:Mt,existingOrderId:$?.orderId,debug:ne},$?.orderId??"fresh")]}),po&&c(Ar,{stripe:Nr,options:Si,children:c(Ls,{sessionId:e,nonce:t,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:nt,billingApiUrl:te,onTokenizedBody:Pn,onErrorChange:le,isProcessing:We,onButtonClick:Q,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:Hn,onLoadStateChange:_i,placeholderBorderRadius:kr})}),mo?c(Ar,{stripe:Rn,options:Ci,children:c(Ns,{sessionId:e,nonce:t,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:nt,billingApiUrl:te,intentKind:B>0?"payment":"setup",expressMethods:zr,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:Hn,onLoadStateChange:xi,placeholderBorderRadius:kr})}):Di?c("div",{style:{height:pa,borderRadius:kr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,yo&&c(Os,{sessionId:e,nonce:t,email:R.email,billingName:[R.firstName,R.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:nt,billingApiUrl:te,paymentElementMethods:Ho,stripeInstance:Rn,paymentElementBaseOptions:wa,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,runBeforeButtonClick:Hn,onLoadStateChange:Ai,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:At,submitButtonStyle:f.submitButton,onExpandApm:V,expandedApmMethod:zt,themeId:ve,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:kr}}),$e&&c("button",{type:"button",onClick:async()=>{We||!(await Hn("card")).proceed||(Q?.("card"),x())},disabled:We,style:{width:"100%",...N,...f.cardButton,...oi({themeBundle:d,resolvedPrimaryColor:Ir,resolvedBorderRadius:At,submitButtonStyle:f.submitButton,explicitPrimaryColor:Cn?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:We?"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:We?.6:1},onMouseEnter:Re=>{!We&&(d||Cn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=bl)},onMouseLeave:Re=>{(d||Cn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=Ir)},onMouseDown:Re=>{Re.currentTarget.style.transform="scale(0.985)"},onMouseUp:Re=>{Re.currentTarget.style.transform="scale(1)"},children:c(jr,{content:Xe})}),m&&Ce==="buttons"&&c(Zr,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:m})]}),$e&&y&&c("div",{style:{gridArea:"1 / 1",...z?{animation:z}:{},...Ce==="collapsing"?{pointerEvents:"none"}:{}},children:Wi}),j&&Xi&&zt&&Zo&&Rn&&c("div",{style:{gridArea:"1 / 1",...Xo?{animation:Xo}:{},...Ce==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:_a,borderRadius:Ba,...vo,padding:Aa},children:[xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[xe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Y,style:{display:"inline-flex",alignItems:"center",gap:Ta?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:[c("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:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(Kr,{content:Me})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:xa,paddingRight:80,...f.title},children:`Pay with ${Fr(zt)}`})]}),c(Ar,{stripe:Rn,options:Zo,children:c(ei,{method:zt,sessionId:e,nonce:t,email:R.email,billingName:[R.firstName,R.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:nt,billingApiUrl:te,onTokenizedBody:Pn,onErrorChange:le,onDecline:s,onCancel:Y,runBeforeButtonClick:Hn,onButtonClick:Q,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:At,submitButtonStyle:f.submitButton,errorText:m})},zt)]})})]})]})}return Xi&&zt&&Zo&&Rn&&j?xe("form",{onSubmit:Ea,className:T,noValidate:!0,style:{position:"relative"},children:[c(Xa,{}),Se&&c(er,{status:Se,errorMessage:m,authorized:Nn}),c("div",{style:{...Xo?{animation:Xo}:{},...Ce==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:_a,borderRadius:Ba,...vo,padding:Aa},children:[xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[xe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Y,style:{display:"inline-flex",alignItems:"center",gap:Ta?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:[c("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:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(Kr,{content:Me})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:xa,paddingRight:80,...f.title},children:`Pay with ${Fr(zt)}`})]}),c(Ar,{stripe:Rn,options:Zo,children:c(ei,{method:zt,sessionId:e,nonce:t,email:R.email,billingName:[R.firstName,R.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:nt,billingApiUrl:te,onTokenizedBody:Pn,onErrorChange:le,onDecline:s,onCancel:Y,runBeforeButtonClick:Hn,onButtonClick:Q,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:At,submitButtonStyle:f.submitButton,errorText:m})},zt)]})})]}):xe("form",{onSubmit:Ea,className:T,noValidate:!0,style:{position:"relative"},children:[c(Xa,{}),Se&&c(er,{status:Se,errorMessage:m,authorized:Nn}),xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Gi("flopay-direct-paypal-gate-debug-default"),Ji("flopay-stripe-gate-debug-default"),uo&&ie&&xe(Br,{children:[$&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(aa,{sessionId:e,nonce:t,billingApiUrl:te,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:nt,clientId:ie.clientId,environment:ie.environment,currency:Ee.toUpperCase(),isSubscription:at,providerObjectType:P,onTokenizedBody:Pn,onComplete:a,onErrorChange:le,onDecline:s,onTechnicalFailure:Or,onButtonClick:Q,runBeforeButtonClick:Hn,isProcessing:We,onLoadStateChange:ka,onInitializationStateChange:Ia,session:Mt,existingOrderId:$?.orderId,debug:ne},$?.orderId??"fresh")]}),po&&c(Ar,{stripe:Nr,options:Si,children:c(Ls,{sessionId:e,nonce:t,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:nt,billingApiUrl:te,onTokenizedBody:Pn,onErrorChange:le,isProcessing:We,onButtonClick:Q,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:Hn,onLoadStateChange:_i,placeholderBorderRadius:kr})}),mo&&c(Ar,{stripe:Rn,options:Ci,children:c(Ns,{sessionId:e,nonce:t,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:nt,billingApiUrl:te,intentKind:B>0?"payment":"setup",expressMethods:zr,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:Hn,onLoadStateChange:xi,placeholderBorderRadius:kr})}),yo&&c(Os,{sessionId:e,nonce:t,email:R.email,billingName:[R.firstName,R.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:te,paymentElementMethods:Ho,stripeInstance:Rn,paymentElementBaseOptions:wa,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,runBeforeButtonClick:Hn,onLoadStateChange:Ai,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:At,submitButtonStyle:f.submitButton,themeId:ve,onExpandApm:V,expandedApmMethod:zt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:kr}})]}),$e&&(ul||dl||pl)&&xe("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),c("span",{children:"or pay with card"}),c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),$e&&Wi]})}import{Fragment as or,jsx as X,jsxs as Yt}from"react/jsx-runtime";var Dr=44,gi="flopay_checkout_saved_payment_resume",ba=new Map,ga=new Map;function Gs(e,t){t.settled&&t.consumers===0&&ba.get(e)===t&&ba.delete(e)}function rd(e,t,n){let r=ga.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};ga.set(e,a);let l=()=>{ga.get(e)===a&&ga.delete(e)};return o.then(l,l),o}function Lo(e){return new Promise(t=>setTimeout(t,e))}function ha(e,t,n){let r=ra({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Qs,enabled:t!==!1});return r.beginCheckout(n),r}function No(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function si(e,t,n,r,o){let a=ha(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),No(a)}function od(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 yi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function li(e){return!e||e.data.stripe?.publishableKey?!1:!!yi(e)?.clientId}function lr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ad(){if(!lr())return null;try{let e=window.sessionStorage.getItem(gi);return e?JSON.parse(e):null}catch{return null}}function Js(e){if(lr())try{window.sessionStorage.setItem(gi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ci(){if(lr())try{window.sessionStorage.removeItem(gi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var hi=":idempotency-key";function el(e,t){if(!lr())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 di(e,t,n,r){if(lr())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 fi(e,t){if(lr())try{el(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function tl(e,t){if(!lr())return null;try{let n=window.sessionStorage.getItem(e+hi);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 ui(e,t,n){if(lr())try{window.sessionStorage.setItem(e+hi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function pi(e,t){if(fi(e,t),!!lr())try{tl(e,t)&&window.sessionStorage.removeItem(e+hi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function id(){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 Xs(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 sd(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function mi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ld(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([l],[s])=>l<s?-1:l>s?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let l=0;l<t.length;l++){let s=t.charCodeAt(l);n=r^Math.imul(n^s,597399067),r=o^Math.imul(r^s,2869860233),o=a^Math.imul(o^s,951274213),a=n^Math.imul(a^s,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(l=>(l>>>0).toString(16).padStart(8,"0")).join("")}function Oo(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=>mi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>mi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>mi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:ld(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function cd(e,t=!1){let n=Oo(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 dd(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=td(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Xc(t.items,t.subscriptions)).map(g=>({type:g.type,code:g.code??g.providerItemId??g.providerPlanId??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??o).toUpperCase()})).sort((g,h)=>`${g.code}:${g.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),l=e.products.map(g=>({type:g.type,code:g.code??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??e.currency).toUpperCase()})).sort((g,h)=>`${g.code}:${g.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(a.length!==l.length)return!1;for(let g=0;g<a.length;g+=1){let h=a[g],b=l[g];if(h.code!==b.code||h.type!==void 0&&h.type!==b.type||h.quantity!==b.quantity||h.totalAmount!==b.totalAmount||h.overrideAmount!==b.overrideAmount||h.currency!==b.currency)return!1}let s=[...t.couponCodes??[]].sort(),k=[...e.coupons??[]].sort();return s.length===k.length&&s.every((g,h)=>g===k[h])}function bi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:s,error:k,onComplete:g,onError:h,onInstrument:b,onDecline:T,onCountryChange:M,onZipChange:u,showPayPal:I=!0,showStripe:he=!0,enabledPaymentMethods:j,showApplePay:C=!0,showGooglePay:pe=!0,debug:Z=!1,layout:se,theme:ae,buttonsTheme:ve,buttonsStyles:et,cardButtonContent:be,cardBackButtonContent:Dt,cardTitleContent:Xe,showSecurityFooter:Me,onButtonClick:Ae,onBeforeButtonClick:ee,enableAVS:Q,cardFieldOrder:A,cardPreFormSlot:Fe,avsLayout:De,className:Le,initialErrorMessage:Ue=null,children:ke,checkoutMode:_,confirmLabel:ce,renderConfirmButton:Pe,onSessionCompleted:de}){let K=Qc(r),Ie=Ln(()=>Zs(ae),[ae]),ot=a??Ie?.appearance,ht=n?"embedded_checkout":"standard_checkout",qe=ke?"custom_layout":se==="buttons"?"buttons_layout":"default_layout",[H,D]=Ft(null),[B,Ee]=Ft(null),Ve=Bt(null),[ie,at]=Ft(null),S=Bt(null),[v,_e]=Ft(null),ne=Ln(()=>n?Oo(n):"",[n]),W=n?`create:${ne}`:`session:${e??""}`,tt=v?.gateways?.stripe?"stripe":v?.gateways?.paypal?"paypal":void 0,Be=Bt(new Set),Ze=Bt(W),Mt=Bt(W);_o(()=>{Mt.current=W,Ze.current!==W&&(Ze.current=W,Be.current.clear())},[W]);let P=nr(x=>{if(Mt.current===W){if(za.has(x.name)){if(Be.current.has(x.name))return;Be.current.add(x.name)}_t(()=>b?.(x))}},[W,b]),U=Xr(P,W),it=Bt(!1),Ye=nr(x=>{if(it.current)return;let L=x.gateway||!tt?x:{...x,gateway:tt};P(L)},[P,tt]);rr(()=>{U({class:"lifecycle",name:"checkout.mount"})},[U]);let[en,Wt]=Ft(e??""),E=e??en,mt=n?"":E,[Tt,st]=Ft(!0),[Rt,pn]=Ft(null),[an,mn]=Ft("full"),[Lt,wn]=Ft(!1),[tn,yt]=Ft(Ue),[lt,ft]=Ft(null),[sn,Qe]=Ft(null),[Wn,dt]=Ft(!1),[nn,bt]=Ft(void 0),[Gt,kn]=Ft(""),[yn,_n]=Ft(!1),[ln,Tn]=Ft(!1),[qt,G]=Ft(!1),fn=Bt(0),Nn=Bt(void 0),[Gn,Cr]=Ft("loading"),[Sr,cr]=Ft(0),Nt=Bt(!1),$e=Bt(!1),dr=Bt(!1),w=Bt(null),ct=Ln(()=>({checkoutMode:_??an,layout:ke?"unknown":se==="buttons"?"buttons":"embedded"}),[_,ke,an,se]),Kt=Bt(g);Kt.current=g;let In=Bt(h);In.current=h;let me=Bt(T);me.current=T,rr(()=>{jt(B)?.setCheckoutContext(ct),ie&&ie!==B&&jt(ie)?.setCheckoutContext(ct)},[B,ie,ct]);let cn=Bt(de);cn.current=de;let wr=nr(x=>{Cr(x),!(x!=="exhausted"||dr.current)&&(dr.current=!0,In.current?.(new Vt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Lr=nr(()=>{Cr("retrying"),cr(x=>x+1)},[]);rr(()=>{Cr("loading"),cr(0),dr.current=!1},[E]),rr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Qs,checkout_type:ht,checkout_layout:qe,billing_api_url:K})},[qe,ht,K]);let gn=Ln(()=>n?Oo(n,!0):"",[n]),ur=Ln(()=>Gt===gn?nn:void 0,[nn,Gt,gn]),Jn=Ln(()=>n?La(n,ur):void 0,[n,ur]),On=_??Jn?.checkoutMode??"full",Ot=Ln(()=>Jn?{...Jn,checkoutMode:On}:void 0,[Jn,On]);rr(()=>{bt(void 0),kn(gn),Nn.current=void 0,G(!1)},[gn]),rr(()=>{yt(Ue)},[Ue]);let zn=nr((x,L,V)=>{_t(()=>{me.current?.(Ht(x,L,V))})},[]),Xn=nr(async(x,L)=>{yt(null),Qe(null),dt(!1),ft("processing");let V=L?.sessionId??x.id,Y=x.gateways?.stripe?"stripe":x.gateways?.paypal?"paypal":void 0,Se=Ve.current??S.current,F=jt(Se),q=Se?null:ha(K,o,ct),p={log:m=>{F?F.log(m):q?.log(m)},error:m=>{F?F.error(m):q?.error(m)},terminal:m=>{F?F.terminal(m):q?.terminal(m)},performance:m=>{F?F.performance(m):q?.performance(m)},now:()=>F?.now()??q?.now()??0,elapsed:m=>F?.elapsed(m)??Math.max(0,(q?.now()??m)-m)},O=p.now(),$=!!(L?.initialAutoProcessingError||L?.initialAutoProcessingPending),gt=!1,vt,te=()=>{gt||(gt=!0,$=!0,vt=p.now(),p.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},we=!1,Jt=()=>{we||(we=!0,p.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),p.performance({stage:"processing",durationMs:p.elapsed(O),durationMode:"machine",paymentMethodCategory:"saved"}),vt!==void 0&&p.performance({stage:"recovery",durationMs:p.elapsed(vt),durationMode:"machine",paymentMethodCategory:"saved"}))};p.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),it.current=!0;try{p.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{it.current=!1}U({class:"lifecycle",name:"payment.processing.started",provider:Y}),$&&te();let nt;try{let m=ws(L?.initialAutoProcessingError),d;if(m)te(),m.type==="paypal_redirect_required"&&w.current?.publishableKey&&Js({sessionId:V,publishableKey:w.current.publishableKey,paypalPublishableKey:w.current.paypalPublishableKey}),d=await ca(m,{flopay:Ve.current,paypalFlopay:S.current,attempt3DS:L?.attempt3DS,billingApiUrl:K,sessionId:V,session:x,telemetry:!1}),m.type==="paypal_redirect_required"&&ci();else if(L?.initialAutoProcessingPending){let re=(await new fa(K,{telemetry:!1}).waitForCheckoutSessionCompletion(L.initialAutoProcessingPending.sessionId,{initialDelayMs:L.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Yr(re))throw ea(re);d=Rr(re,V)}else{if(L?.initialAutoProcessingError)throw br(L.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.initialAutoProcessingError.checkoutMethod});if(L?.fromCreateSession)return L?.fallbackToFull&&(mn("full"),Xs("full")),!1;{let f=await eo({billingApiUrl:K,sessionId:V,session:x,telemetry:!1});f.type==="success"?d=f.result:(te(),f.type==="paypal_redirect_required"&&w.current?.publishableKey&&Js({sessionId:V,publishableKey:w.current.publishableKey,paypalPublishableKey:w.current.paypalPublishableKey}),d=await ca(f,{flopay:Ve.current,paypalFlopay:S.current,attempt3DS:L?.attempt3DS,billingApiUrl:K,sessionId:V,session:x,telemetry:!1}),f.type==="paypal_redirect_required"&&ci())}}V&&Qr(V),Jt(),$&&(p.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),p.terminal({outcome:d.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),dt(d.status==="authorized"),ft("success"),await Lo(1200),nt=()=>Kt.current?.(d)}catch(m){let d=Fo(m),f=d.checkoutMethod??Bo;yt(d.message),Qe(d.message),dt(!1),L?.fallbackToFull&&(p.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),mn("full"),Xs("full")),Jt();let ye=d.statusCode!==void 0?nd(d.statusCode,"unknown"):void 0,re=ye==="4xx"?{requestCategory:"process_payment",statusClass:ye}:{},je=ye===void 0||ye==="4xx";if(je&&(d.telemetryOutcome==="payment_declined"||!!(d.declineCode||d.code?.toLowerCase().includes("declin"))))p.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...re});else if(je&&(d.telemetryOutcome==="validation_rejected"||d.type==="validation_error"))p.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...re});else{let R=Ys(m,$?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),oe=d.telemetryRequestCategory??"process_payment";it.current=!0;try{p.error({...R,...d.telemetryFailureCategory?{failureCategory:d.telemetryFailureCategory}:{},stage:$?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:oe})}finally{it.current=!1}U({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:oe,provider:Y})}return _t(()=>In.current?.(d)),zn(f,d,{code:d.code,declineCode:d.declineCode}),ft("error"),await Promise.allSettled([Lo(1500),L?.ensureProvidersReady?L.ensureProvidersReady():Promise.resolve()]),$&&(p.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Jt(),q&&No(q),ft(null),Qe(null)}return _t(nt),!0},[zn,U,K,o,ct]);rr(()=>{if(typeof window>"u"||$e.current)return;let x=new URLSearchParams(window.location.search),L=x.get("payment_intent_client_secret");if(!L)return;let V=ad();V&&($e.current=!0,(async()=>{let Y,Se=0;yt(null),Qe(null),ft("processing"),wn(!0);try{if(x.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:F,paypalFlopay:q}=await ua({publishableKey:V.publishableKey,paypalPublishableKey:V.paypalPublishableKey,billingApiUrl:K,locale:l,telemetry:o});Y=jt(q??F),Se=Y?.now()??0,Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let p=(q??F)?.getRawProvider();if(!p)throw Object.assign(new Vt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:O,error:$}=await p.retrievePaymentIntent(L);if($)throw Object.assign(new Vt($.message??"Failed to retrieve PayPal payment status.","api_error",{code:$.code}),{checkoutMethod:"paypal"});let gt=os(O?.status);if(!O||gt==="failed")throw Object.assign(new Vt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let vt=typeof O.payment_method=="string"?O.payment_method:O.payment_method?.id,te=gt;if(V.sessionId){let nt=(await new fa(K,{telemetry:!1}).getUnifiedCheckoutSession(V.sessionId)).data.session;if(nt&&nt.status!=="complete"){let m=await eo({billingApiUrl:K,sessionId:V.sessionId,session:nt,telemetry:!1,tokenizedData:{id:vt??O.id,type:"card",threeDSecureActionResultTokenId:O.id,isPaypal:!0}});if(m.type!=="success")throw Object.assign(new Vt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});te=m.result.status}}V.sessionId&&Qr(V.sessionId),Y?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.performance({stage:"redirect_resume",durationMs:Y.elapsed(Se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ft("success"),await Lo(1200),_t(()=>Kt.current?.({status:te,paymentIntentId:O.id,paymentMethodId:vt,checkoutMethod:"paypal"}))}catch(F){let q=Fo(F),p=q.checkoutMethod??"paypal",O=!!(q.declineCode||q.code?.toLowerCase().includes("declin"));if(Y)Y.performance({stage:"redirect_resume",durationMs:Y.elapsed(Se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),O?Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Y.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(O){let $=ha(K,o,ct);$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),No($)}else si(K,o,ct,"REDIRECT_RESUME_FAILED","redirect_resume");yt(q.message),Qe(q.message),_t(()=>In.current?.(q)),zn(p,q,{code:q.code,declineCode:q.declineCode}),ft("error"),await Lo(1500)}finally{ci(),id(),ft(null),Qe(null),wn(!1)}})())},[zn,l,K,o,ct]);let hn=Bt(null),rn=Ln(()=>Ot?Oo(Ot):"",[Ot]),Un=Bt(Ot);Un.current=Ot,rr(()=>{Wt(e??"")},[e]),rr(()=>{Nt.current=!1,yt(Ue),Qe(null),dt(!1),ft(null)},[rn,Ue,e]);async function qn(x,L,V){let Y=ha(K,o,ct),Se=new fa(K,{telemetry:!1}),F=!1;try{let q=x.idempotencyKey!==void 0?Ws(x.idempotencyKey):void 0,p=el(L,V),O=tl(L,V);p?.canonicalIdentity===V&&O&&O.canonicalIdentity===void 0&&(ui(L,V,O.idempotencyKey),O={...O,canonicalIdentity:V});let $=q??(O?.canonicalIdentity===V?O.idempotencyKey:void 0),gt,vt=!1;Y.log({name:p?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let te=p?.sid??null,we=null,Jt,nt,m=!1;if(te)try{we=await Se.getUnifiedCheckoutSession(te,p?.nonce),p&&p.canonicalIdentity===void 0&&(dd(we.data.session,x)?(di(L,V,te,p.nonce??we.data.session?.clientSecret),O&&O.canonicalIdentity===void 0&&(ui(L,V,O.idempotencyKey),$??($=O.idempotencyKey))):(pi(L,V),O=null,$=q,te=null,we=null));let f=we?.data.session?.status,ye=we?.data.session,re=ye?.clientSecret||p?.nonce;if(te&&ye?.buyerIdentified===!1&&re&&(nt=Vr(Se,te,re,x.account)),te&&we&&f==="complete"){if(Ka(te))return{sid:te,result:we};pi(L,V),te=null,we=null,vt=!0}}catch{Y.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),p?.canonicalIdentity===void 0?(pi(L,V),$=q):fi(L,V),te=null}if(!te){!q&&(vt||!$)&&($=Ws(),gt=$),$&&ui(L,V,$);let f=Y.now(),ye=0;Y.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let re={...x,idempotencyKey:$,avsCheck:!!Q,avsConfig:typeof Q=="object"?Q:void 0,checkoutType:"embedded_checkout",checkoutLayout:ke?"custom_layout":se==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(re,Gc,{configurable:!1,enumerable:!1,value:{onAttempt:J=>{ye=Math.max(ye,J)}}});let je=()=>{Y.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),Y.performance({stage:"session_create",durationMs:Y.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:ye,statusClass:"2xx"})},We=J=>{let R=Ys(J,"CHECKOUT_SESSION_CREATE_FAILED","unknown");Y.performance({stage:"session_create",durationMs:Y.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:ye,statusClass:R.statusClass}),J instanceof Vt&&J.type==="validation_error"?Y.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):R.statusClass==="4xx"?Y.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(Y.error({...R,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),U({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Zc(re)){let J=await Se.createDetachedSession(re);J.claimed.catch(()=>{}),we=J.shell,te=J.sessionId,nt=J.claim,Jt=J.claimed.then(R=>{let oe=R.data.session?.id??J.sessionId;return oe&&di(L,V,oe,R.data.session?.clientSecret??J.nonce),je(),R},R=>{throw fi(L,V),We(R),R}).finally(()=>No(Y)),Jt.catch(()=>{}),F=!0,Y.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Y.performance({stage:"session_shell",durationMs:Y.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:ye,statusClass:"2xx",paymentMethodCategory:"card"})}else we=await Se.createAndFetchSession(re),je()}catch(J){throw We(J),J}te=we.data.session?.id??te??"",te&&!Jt&&di(L,V,te,we.data.session?.clientSecret)}let d=we?.data.session;return!nt&&te&&d?.buyerIdentified===!1&&d.clientSecret&&(nt=Vr(Se,te,d.clientSecret,x.account)),{sid:te??"",result:we,sdkGeneratedIdempotencyKey:gt,...Jt?{claimed:Jt}:{},...nt?{claim:nt}:{},...m?{claimRequiresIdentity:!0}:{}}}finally{F||No(Y)}}let ut=Bt(qn);_o(()=>{ut.current=qn},[qn]);let bn=nr(async(x,L)=>{let V=Un.current;if(!V)throw new Vt("createSession is required to bootstrap checkout.","validation_error");let Y=La(V,x),Se=Oo(Y),F=cd(Y),q=ba.get(Se);if(!q){let $={canonicalIdentity:Se,promise:ut.current(Y,F,Se),consumers:0,settled:!1};q=$,ba.set(Se,$);let gt=()=>{$.settled=!0,Gs(Se,$)};$.promise.then(gt,gt)}q.consumers+=1;let p=!1,O=()=>{p||(p=!0,q.consumers-=1,Gs(Se,q))};L?.(O);try{let $=await q.promise;hn.current=Se,x&&(kn(gn),bt(ye=>ts(ye,x)));let{sid:gt,result:vt,claimed:te,claim:we,claimRequiresIdentity:Jt}=$;if(Nn.current=we,G(Jt===!0),D(vt),vt.data.session&&_e(vt.data.session),gt&&Wt(gt),te){fn.current+=1;let ye=fn.current;Tn(!0),te.then(re=>{fn.current===ye&&(D(re),re.data.session&&_e(re.data.session),Tn(!1),G(!1))},re=>{fn.current===ye&&(Tn(!1),G(!1),pn(re instanceof Vt?re:new Vt(re instanceof Error?re.message:"Failed to create session","api_error")))})}else fn.current+=1,Tn(!1),G(!1);let{publishableKey:nt,paypalPublishableKey:m}=da(vt),{flopay:d,paypalFlopay:f}=await ua({publishableKey:nt,paypalPublishableKey:m,billingApiUrl:K,locale:l,telemetry:o});return Ve.current=d,Ee(d),S.current=f,at(f),st(!1),$}catch($){throw hn.current===Se&&(hn.current=null),$}finally{L||O()}},[gn,l,K,o]),vn=Bt(Xn);vn.current=Xn;let $n=Bt(bn);$n.current=bn;let xn=nr(async x=>{if(!sd(x)||yn)return{sessionId:en,session:v};_n(!0);try{let L=await bn(x);return{sessionId:L.sid,session:L.result.data.session??null}}finally{_n(!1)}},[bn,yn,en,v]),Ce=nr(async x=>{let L=Nn.current;if(!L)return;let V=fn.current,Y=await L(x);fn.current===V&&(D(Y),Y.data.session&&_e(Y.data.session))},[]);rr(()=>{let x=!1,L;if(pn(null),rn){let Se=Un.current;return mn(On),st(!1),hn.current===rn?()=>{x=!0}:(_e(ns(Se,_)),(async()=>{let F=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),q=On==="auto"&&!Nt.current&&!F;q&&(yt(null),Qe(null),ft("processing"));try{let p=await $n.current(void 0,vt=>{L=vt}),O=p.result.data.session??null;w.current=da(p.result);let $=li(p.result),gt=Ka(p.sid||O?.id);if(!x&&q&&O&&!$&&!gt){Nt.current=!0,await rd(rn,p.sdkGeneratedIdempotencyKey,()=>vn.current(O,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:p.result.autoProcessingError,initialAutoProcessingPending:p.result.autoProcessingPending,autoProcessingAttempted:p.result.autoProcessingAttempted,sessionId:p.sid||O.id}));return}!x&&q&&(($||gt)&&(Nt.current=!0),ft(null),Qe(null))}catch(p){if(x)return;let O=p instanceof Vt||typeof p=="object"&&p!==null&&"code"in p?p.code:void 0;if(q&&O==="session_auto_completed"){Nt.current=!0,ft("success"),await Lo(1200),x||(_t(()=>{Kt.current?.({status:"succeeded"})}),ft(null),Qe(null));return}q&&(ft(null),Qe(null));let $=p instanceof Vt?p:new Vt(p instanceof Error?p.message:"Failed to create session","api_error");pn($)}finally{L?.(),L=void 0}})(),()=>{x=!0,L?.()})}st(!0);async function V(){let Se=!1;try{let F=new fa(K,{telemetry:!1}),q=await F.getUnifiedCheckoutSession(E,t);if(x)return;D(q);let p=q.data.session??null;if(_e(p),!p)throw new Vt("No session data returned","api_error");let O=p.checkoutMode;if(O==="setup")throw new Vt("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(p.status==="authorized"){st(!1),_t(()=>{Kt.current?.(Rr(p,E)),cn.current?.(p.successUrl??"")});return}if(p.status==="complete"){st(!1),_t(()=>{cn.current?.(p.successUrl??"")});return}if(p.status==="expired")throw Qo(p);Se=!0;let $=_??O??"full";mn($),fn.current+=1;let gt=p.clientSecret||t;Nn.current=p.buyerIdentified===!1&>?Vr(F,E,gt,{...p.customer?.id?{userId:p.customer.id}:{}}):void 0,Tn(!1),G(!1);let vt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),te=li(q);if($==="auto"&&!Nt.current&&!vt&&!te){Nt.current=!0;let we=Y(q);try{if(await vn.current(p,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>we,sessionId:E||p.id}),x)return;await we,x||st(!1);return}catch{if(x)return;await we,x||st(!1);return}}await Y(q),x||st(!1)}catch(F){if(x)return;Se&&U({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),F instanceof Vt?!Se&&!od(F)&&si(K,o,ct,"NETWORK_REQUEST_FAILED","session_read"):si(K,o,ct,"INTERNAL_SDK_ERROR","checkout_mount");let q=F instanceof Vt?F:new Vt(F instanceof Error?F.message:"Failed to initialize checkout","api_error");pn(q),st(!1)}}async function Y(Se){let{publishableKey:F,paypalPublishableKey:q}=da(Se);w.current={publishableKey:F,paypalPublishableKey:q};let{flopay:p,paypalFlopay:O}=await ua({publishableKey:F,paypalPublishableKey:q,billingApiUrl:K,locale:l,telemetry:o});Ve.current=p,Ee(p),S.current=O,at(O)}return V(),()=>{x=!0}},[_,rn,On,mt,t]);let on=nr(async()=>{if(!(Lt||!v)){wn(!0),yt(null);try{await Xn(v,{attempt3DS:!0,fallbackToFull:!0,sessionId:E||v.id})}finally{wn(!1)}}},[E,Lt,Xn,v]),zt=yi(H),pr=li(H),jn=Ln(()=>{if(!(!H||!v||!H.data.stripe?.publishableKey))return{billingApiUrl:K}},[H,v,K]),mr=!!(n&&!ke&&se==="buttons"&&ee&&On==="full"),En=Ln(()=>({session:v,loading:Tt,error:Rt,checkoutMode:an,inlineSessionDraft:Ot,applyInlineSessionPatch:mr?xn:void 0,inlineSessionPatchProcessing:yn,claimPending:ln,claimRequiresIdentity:qt,claimBuyerIdentity:Ce}),[v,Tt,Rt,an,Ot,mr,xn,yn,ln,qt,Ce]),Mn=!!n&&se==="buttons"&&!pr&&(!B||!jn),Ut=lt?X(er,{status:lt,errorMessage:sn,authorized:Wn}):null;if(Tt){if(s)return Yt(or,{children:[s,Ut]});if(se==="buttons"){let x=Ie?.buttonsLayout?.cardButton?.borderRadius??Ie?.appearance.variables?.borderRadius??8,L=V=>X("div",{style:{height:V,borderRadius:x,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Yt(or,{children:[Yt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[I&&L(Dr),he&&(C||pe)&&L(Dr),he&&L(Dr),X("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ut]})}return Yt(or,{children:[Yt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[X("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),X("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ut]})}return Rt?k?X(Vn.Provider,{value:En,children:k(Rt)}):X(Vn.Provider,{value:En,children:X("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Rt.message})}):Mn?Yt(or,{children:[X(Vn.Provider,{value:En,children:X(pd,{onButtonClick:Ae,showPayPal:I,showStripe:he,showApplePay:C,showGooglePay:pe,theme:ae,buttonsTheme:ve,buttonsStyles:et,cardButtonContent:be,cardBackButtonContent:Dt,cardTitleContent:Xe})}),Ut]}):pr&&v&&zt?Yt(or,{children:[X(Vn.Provider,{value:En,children:Yt("div",{className:Le,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[tn&&X(Zr,{icon:!1,children:tn}),Gn==="retrying"&&X("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Gn==="exhausted"&&Yt("div",{role:"alert",children:[X("div",{children:"PayPal is temporarily unavailable. Please try again."}),X("button",{type:"button",onClick:Lr,children:"Retry PayPal"})]}),ln?s??X("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Dr,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:X("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):Gn!=="exhausted"?X("div",{"aria-hidden":Gn==="retrying"?!0:void 0,style:Gn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:X(gs,{sessionId:E,nonce:v.clientSecret||void 0,billingApiUrl:K,email:v.customer?.email||Ot?.account?.email,billingName:[v.customer?.firstName,v.customer?.lastName].filter(Boolean).join(" ")||[Ot?.account?.firstName,Ot?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Ce,clientId:zt.clientId,environment:zt.environment,currency:(v.currency??"usd").toUpperCase(),isSubscription:v.mode==="subscription",providerObjectType:zt.providerObjectType,onComplete:g,onErrorChange:yt,onDecline:T,onButtonClick:Ae,onInitializationStateChange:wr,allowAutomaticRetry:Sr===0,session:v,telemetry:o,telemetryContext:ct,onInstrument:Ye,debug:Z},`${W}:paypal-init-${Sr}`)}):null]})}),Ut]}):!B||!jn?X(or,{children:Ut}):an==="confirm"?Yt(or,{children:[X(Vn.Provider,{value:En,children:X(ia,{flopay:B,paypalFlopay:ie,options:jn,onInstrument:Ye,children:Yt("div",{className:Le,children:[tn&&X("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:tn}),Pe?Pe({onConfirm:on,isProcessing:Lt}):X("button",{type:"button",onClick:on,disabled:Lt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Lt?"not-allowed":"pointer",opacity:Lt?.6:1},children:Lt?"Processing...":ce??"Confirm Purchase"})]})},W)}),Ut]}):Yt(or,{children:[X(Vn.Provider,{value:En,children:X(ia,{flopay:B,paypalFlopay:ie,options:jn,onInstrument:Ye,children:ke?Yt(or,{children:[tn&&X("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:tn}),X(ud,{sessionId:E,nonce:v?.clientSecret||void 0,billingApiUrl:K,session:v,children:ke})]}):X(ai,{sessionId:E,nonce:v?.clientSecret||void 0,email:v?.customer?.email||Ot?.account?.email,userId:v?.customer?.id||Ot?.account?.userId,firstName:v?.customer?.firstName||Ot?.account?.firstName,lastName:v?.customer?.lastName||Ot?.account?.lastName,totalAmount:v?Math.round(Jc(v).total*100):0,currency:v?.currency?.toLowerCase()??"usd",onComplete:g,onError:h,onDecline:T,error:tn,onErrorChange:yt,showPayPal:I,showStripe:he,enabledPaymentMethods:j??H?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:H?.data.stripe?.enabledPaymentMethodCountries,showApplePay:C,showGooglePay:pe,layout:se,theme:ae,buttonsTheme:ve,buttonsStyles:et,appearance:ot,cardButtonContent:be,cardBackButtonContent:Dt,cardTitleContent:Xe,onButtonClick:Ae,onBeforeButtonClick:ee,onBuyerIdentityReady:Ce,enableAVS:Q,...A?{cardFieldOrder:A}:{},...Fe?{cardPreFormSlot:Fe}:{},avsLayout:De,country:v?.customer?.country,city:v?.customer?.city,state:v?.customer?.state,onCountryChange:M,onZipChange:u,avsCheck:!!Q,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ke?"custom_layout":se==="buttons"?"buttons_layout":"default_layout",className:Le,directPaypal:yi(H),isSubscription:v?.mode==="subscription",session:v,dataAttachmentPending:ln,dataAttachmentRequiresIdentity:qt,debug:Z})},W)}),Ut]})}function ud({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return X(or,{children:ii.Children.map(o,a=>{if(!ii.isValidElement(a))return a;let l=a.props,s={};return l.sessionId||(s.sessionId=e),!l.nonce&&t&&(s.nonce=t),l.billingApiUrl||(s.billingApiUrl=n),r?.customer&&(l.email||(s.email=r.customer.email),l.userId||(s.userId=r.customer.id),l.firstName||(s.firstName=r.customer.firstName),l.lastName||(s.lastName=r.customer.lastName)),Object.keys(s).length===0?a:ii.cloneElement(a,s)})})}function pd({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:s,cardButtonContent:k,cardBackButtonContent:g,cardTitleContent:h}){let[b,T]=Ft(!1),M=Ln(()=>Zs(a),[a]),u=Ln(()=>{let C=M?.buttonsLayout??ed(l);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},[M,l,s]),I=M?.buttonsLayout?.cardButton?.borderRadius??M?.appearance.variables?.borderRadius??8,he=C=>X("div",{style:{height:C,borderRadius:I,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),j=k===void 0?{boxSizing:"border-box",height:Dr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let C=u.cardInputBorder??"#e5e7eb",pe=u.cardInputBackground??"white",Z=$r(g),se=$r(h);return Yt("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:[Yt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Yt("button",{type:"button",onClick:()=>T(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Z?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:[X("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:X("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:X("path",{d:"M15 18l-6-6 6-6"})})}),X(Kr,{content:g})]}),se?X("div",{style:{flex:1}}):X("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:X(wo,{content:h})})]}),X("div",{style:{backgroundColor:pe,border:`1px solid ${C}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:X("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Yt("div",{style:{display:"flex"},children:[X("div",{style:{flex:1,backgroundColor:pe,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomLeftRadius:8,padding:12,height:45},children:X("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),X("div",{style:{flex:1,backgroundColor:pe,borderTop:"none",borderRight:`1px solid ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomRightRadius:8,padding:12,height:45},children:X("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),X("div",{style:{backgroundColor:pe,border:`1px solid ${C}`,borderRadius:8,marginTop:8,padding:12,height:45},children:X("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),X("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),X("style",{children:`
|
|
33
|
+
`}),bo&&jn&&Te("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:$e?-2:0},children:[Te("button",{type:"button",onClick:L,style:{display:"inline-flex",alignItems:"center",gap:Ma?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:[c("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:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(Hr,{content:xe})]}),Vi?c("div",{style:{flex:1}}):c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...f.title},children:c(Io,{content:Me})})]}),!bo&&!Vi&&c("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Aa,order:$e?-3:0,...f.title},children:c(Io,{content:Me})}),$e&&ze&&c("div",{style:{order:-2,width:"100%"},children:ze}),$e&&Pt&&Te("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[c("div",{style:{backgroundColor:$r,border:`1px solid ${An(Wo)}`,borderRadius:At,padding:"10px"},children:c("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:et,onChange:i=>{ut("email"),Tn.current=i.target.value,Wn(i.target.value)},onPointerDown:()=>ut("email"),onKeyDown:()=>ut("email"),onBlur:()=>{bn("email")&&zn(!0),$t||Sa()},disabled:Je,required:!0,"aria-invalid":Wo||void 0,"aria-describedby":Wo?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ba}})}),Wo&&c("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Po,children:Ne.empty?"Email address is required":"Enter a valid email address"})]}),G&&c("div",{style:{order:$e?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=lt,y=(z=!1)=>({backgroundColor:$r,border:`1px solid ${An(z)}`,borderRadius:At,marginTop:"0.5rem",padding:"10px"}),N=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ba}),_e=Cc(i);return Te(Br,{children:[Ve(G.address_line_1,i)&&Te(Br,{children:[c("div",{style:y(xt("line1")),children:c("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:mn,onChange:z=>{ut("line1"),qt.current.addressLine1=!0,kn.current=z.target.value,Lt(z.target.value)},onPointerDown:()=>ut("line1"),onKeyDown:()=>ut("line1"),onBlur:()=>vn("line1"),disabled:Je,required:!0,"aria-invalid":xt("line1")||void 0,"aria-describedby":xt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:N()})}),xt("line1")&&c("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Po,children:"Street address is required"})]}),Ve(G.address_line_2,i)&&c("div",{style:y(),children:c("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:wn,onChange:z=>{qt.current.addressLine2=!0,yn.current=z.target.value,Gt(z.target.value)},disabled:Je,"data-testid":"flopay-address-line2",style:N()})}),(Ve(G.city,i)||Ve(G.state,i))&&Te("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Ve(G.city,i)&&c("div",{style:{flex:1,backgroundColor:$r,borderTop:`1px solid ${An(xt("city"))}`,borderRight:`1px solid ${An(xt("city"))}`,borderBottom:`1px solid ${An(xt("city"))}`,borderLeft:`1px solid ${An(xt("city"))}`,padding:"10px",borderTopLeftRadius:At,borderBottomLeftRadius:At,...Ve(G.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:At}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:yt,onChange:z=>{ut("city"),qt.current.city=!0,_n.current=z.target.value,Ge(z.target.value)},onPointerDown:()=>ut("city"),onKeyDown:()=>ut("city"),onBlur:()=>vn("city"),disabled:Je,required:!0,"aria-invalid":xt("city")||void 0,"aria-describedby":xt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:N()})}),Ve(G.state,i)&&c("div",{style:{flex:1,backgroundColor:$r,borderTop:`1px solid ${An(xt("state"))}`,borderRight:`1px solid ${An(xt("state"))}`,borderBottom:`1px solid ${An(xt("state"))}`,borderLeft:`1px solid ${An(xt("state"))}`,padding:"10px",borderTopRightRadius:At,borderBottomRightRadius:At,...Ve(G.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${An(xt("state")||xt("city"))}`}:{borderRadius:At}},children:_e?Te("select",{id:"flopay-billing-state",name:"billing-state",value:ft,onChange:z=>{ut("state"),qt.current.state=!0,ln.current=z.target.value,sn(z.target.value)},onPointerDown:()=>ut("state"),onKeyDown:()=>ut("state"),onBlur:()=>vn("state"),disabled:Je,autoComplete:"billing address-level1",required:!0,"aria-invalid":xt("state")||void 0,"aria-describedby":xt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...N(),cursor:"pointer"},children:[c("option",{value:"",children:Ga(i)}),_e.map(z=>c("option",{value:z.code,children:z.name},z.code))]}):c("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Ga(i),autoComplete:"billing address-level1",value:ft,onChange:z=>{ut("state"),qt.current.state=!0,ln.current=z.target.value,sn(z.target.value)},onPointerDown:()=>ut("state"),onKeyDown:()=>ut("state"),onBlur:()=>vn("state"),disabled:Je,required:!0,"aria-invalid":xt("state")||void 0,"aria-describedby":xt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:N()})})]}),xt("city")&&c("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Po,children:"City is required"}),xt("state")&&Te("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Po,children:[Ga(i)," is required"]}),(Ve(G.country,i)||Ve(G.postal_code,i))&&Te("div",{style:{display:"flex",flexDirection:ke==="column"?"column":"row",gap:ke==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Ve(G.country,i)&&c("div",{style:{flex:ke==="row"?1:void 0,backgroundColor:$r,borderTop:`1px solid ${vo}`,borderRight:`1px solid ${vo}`,borderBottom:`1px solid ${vo}`,borderLeft:`1px solid ${vo}`,padding:"10px",...ke==="row"&&Ve(G.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:At,borderBottomLeftRadius:At,borderRight:"none"}:{borderRadius:At}},children:c("select",{id:"flopay-billing-country",name:"billing-country",value:lt,onChange:z=>{qt.current.country=!0,Jt.current=z.target.value,Rt(z.target.value),at?.(z.target.value),ln.current="",sn("")},disabled:Je,autoComplete:"billing country","data-testid":"flopay-country",style:{...N(),cursor:"pointer"},children:hc.map(z=>Te("option",{value:z.code,children:[z.flag," ",z.name]},z.code))})}),Ve(G.postal_code,i)&&c("div",{style:{flex:ke==="row"?1:void 0,backgroundColor:$r,border:`1px solid ${hl}`,padding:"10px",...ke==="row"&&Ve(G.country,i)?{borderRadius:"0",borderTopRightRadius:At,borderBottomRightRadius:At}:{borderRadius:At}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Qa(lt),autoComplete:"billing postal-code",value:pn,onChange:z=>{ut("zip"),qt.current.zip=!0,bt.current=z.target.value,an(z.target.value),ht?.(z.target.value)},onPointerDown:()=>ut("zip"),onKeyDown:()=>ut("zip"),onBlur:()=>{bn("zip")&&On(!0)},disabled:Je,required:cn.required,"aria-invalid":Go||void 0,"aria-describedby":Go?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:N()})})]}),Go&&c("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Po,children:cn.empty?`${Qa(i)} is required`:Vc(i)})]})})()}),$e&&Sl,m&&c(eo,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:m})]}),Jo={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"},Ji=i=>ne?!he||!Qn?c("pre",{"data-testid":i,style:Jo,children:"FloPay/DirectPayPal-debug - not enabled"}):c("pre",{"data-testid":i,style:Jo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${he}`,` directPaypalConfigured=${Qn}`,` inAppBrowserDetected=${String(Ho)}`,` shouldRenderDirectPayPal=${mo}`,` shouldRenderStripePayPal=${yo}`,` hasPaypalStripeInstance=${!!Nr}`].join(`
|
|
34
|
+
`)}):null,Xi=i=>ne?!j||!Rn?c("pre",{"data-testid":i,style:Jo,children:"FloPay/Stripe-debug - not enabled"}):c("pre",{"data-testid":i,style:Jo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${j}`,` currency=${qe}`,` amountInCents=${co}`,` enabledPaymentMethods: ${JSON.stringify(S??[])}`,` enabledPaymentMethodsProvided=${uo}`,` hasEnabledMethods=${jo}`,` expressMethods: ${JSON.stringify(Ko)}`,` walletExpressMethods: ${JSON.stringify(qr)}`,` paymentElementMethods: ${JSON.stringify(po)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Vo)}`,` hasStripeInstance=${!!Rn}`,` shouldRenderWallets=${fo}`,` shouldRenderPaymentElement=${go}`].join(`
|
|
35
|
+
`)}):null,Zi=Ce==="apm-expanding"||Ce==="apm-form"||Ce==="apm-collapsing",Xo=Ce==="apm-expanding"?`flopay-card-enter ${Mr}ms cubic-bezier(0, 0, 0.2, 1) both`:Ce==="apm-collapsing"?`flopay-card-exit ${Mr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Zo=zt?{...Ia,paymentMethodTypes:[zt]}:null;if(ae==="buttons"){let i=Ce==="buttons"||Ce==="expanding"||Ce==="apm-expanding",y=Ce==="expanding"||Ce==="card"||Ce==="collapsing",N=Qe===void 0?{boxSizing:"border-box",height:ma,padding:"0 1rem"}:{padding:"0.9rem 1rem"},_e=Ce==="expanding"||Ce==="apm-expanding"?`flopay-buttons-exit ${Mr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ce==="collapsing"||Ce==="apm-collapsing"?`flopay-buttons-enter ${Mr}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,z=Ce==="expanding"?`flopay-card-enter ${Mr}ms cubic-bezier(0, 0, 0.2, 1) both`:Ce==="collapsing"?`flopay-card-exit ${Mr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Te("form",{onSubmit:_a,className:T,noValidate:!0,style:{position:"relative"},children:[c(Za,{}),Se&&c(er,{status:Se,errorMessage:m,authorized:Nn}),Te("div",{style:{display:"grid"},children:[Te("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!_e?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!_e?qc:{},..._e?{animation:_e,pointerEvents:"none"}:{}},children:[Ji("flopay-direct-paypal-gate-debug"),Xi("flopay-stripe-gate-debug"),mo&&ie&&Te(Br,{children:[$&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(aa,{sessionId:e,nonce:t,billingApiUrl:te,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:rt,clientId:ie.clientId,environment:ie.environment,currency:qe.toUpperCase(),isSubscription:it,providerObjectType:C,onTokenizedBody:Pn,onComplete:a,onErrorChange:le,onDecline:s,onTechnicalFailure:Ur,onButtonClick:Q,runBeforeButtonClick:Vn,isProcessing:Je,onLoadStateChange:Ea,onInitializationStateChange:Ra,session:Mt,existingOrderId:$?.orderId,debug:ne},$?.orderId??"fresh")]}),yo&&c(Ar,{stripe:Nr,options:wi,children:c(Os,{sessionId:e,nonce:t,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:rt,billingApiUrl:te,onTokenizedBody:Pn,onErrorChange:le,isProcessing:Je,onButtonClick:Q,onDecline:s,onTechnicalFailure:Ur,runBeforeButtonClick:Vn,onLoadStateChange:Ti,placeholderBorderRadius:kr})}),fo?c(Ar,{stripe:Rn,options:Si,children:c(zs,{sessionId:e,nonce:t,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:rt,billingApiUrl:te,intentKind:B>0?"payment":"setup",expressMethods:qr,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,onTechnicalFailure:Ur,runBeforeButtonClick:Vn,onLoadStateChange:Mi,placeholderBorderRadius:kr})}):Li?c("div",{style:{height:ma,borderRadius:kr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,go&&c(Us,{sessionId:e,nonce:t,email:R.email,billingName:[R.firstName,R.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:rt,billingApiUrl:te,paymentElementMethods:Vo,stripeInstance:Rn,paymentElementBaseOptions:Ia,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,runBeforeButtonClick:Vn,onLoadStateChange:Bi,isProcessing:Je,submitButtonColor:Ir,submitButtonBorderRadius:At,submitButtonStyle:f.submitButton,onExpandApm:H,expandedApmMethod:zt,themeId:ve,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:kr}}),$e&&c("button",{type:"button",onClick:async()=>{Je||!(await Vn("card")).proceed||(Q?.("card"),x())},disabled:Je,style:{width:"100%",...N,...f.cardButton,...ai({themeBundle:d,resolvedPrimaryColor:Ir,resolvedBorderRadius:At,submitButtonStyle:f.submitButton,explicitPrimaryColor:Cn?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Je?"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:Je?.6:1},onMouseEnter:Ee=>{!Je&&(d||Cn?.colorPrimary)&&(Ee.currentTarget.style.backgroundColor=Pl)},onMouseLeave:Ee=>{(d||Cn?.colorPrimary)&&(Ee.currentTarget.style.backgroundColor=Ir)},onMouseDown:Ee=>{Ee.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ee=>{Ee.currentTarget.style.transform="scale(1)"},children:c(Vr,{content:Qe})}),m&&Ce==="buttons"&&c(eo,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:m})]}),$e&&y&&c("div",{style:{gridArea:"1 / 1",...z?{animation:z}:{},...Ce==="collapsing"?{pointerEvents:"none"}:{}},children:Gi}),j&&Zi&&zt&&Zo&&Rn&&c("div",{style:{gridArea:"1 / 1",...Xo?{animation:Xo}:{},...Ce==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Te("div",{style:{backgroundColor:xa,borderRadius:Da,...Co,padding:Fa},children:[Te("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Te("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Y,style:{display:"inline-flex",alignItems:"center",gap:Ma?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:[c("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:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(Hr,{content:xe})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Aa,paddingRight:80,...f.title},children:`Pay with ${Fr(zt)}`})]}),c(Ar,{stripe:Rn,options:Zo,children:c(ti,{method:zt,sessionId:e,nonce:t,email:R.email,billingName:[R.firstName,R.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:rt,billingApiUrl:te,onTokenizedBody:Pn,onErrorChange:le,onDecline:s,onCancel:Y,runBeforeButtonClick:Vn,onButtonClick:Q,isProcessing:Je,submitButtonColor:Ir,submitButtonBorderRadius:At,submitButtonStyle:f.submitButton,errorText:m})},zt)]})})]})]})}return Zi&&zt&&Zo&&Rn&&j?Te("form",{onSubmit:_a,className:T,noValidate:!0,style:{position:"relative"},children:[c(Za,{}),Se&&c(er,{status:Se,errorMessage:m,authorized:Nn}),c("div",{style:{...Xo?{animation:Xo}:{},...Ce==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Te("div",{style:{backgroundColor:xa,borderRadius:Da,...Co,padding:Fa},children:[Te("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Te("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Y,style:{display:"inline-flex",alignItems:"center",gap:Ma?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:[c("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:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(Hr,{content:xe})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Aa,paddingRight:80,...f.title},children:`Pay with ${Fr(zt)}`})]}),c(Ar,{stripe:Rn,options:Zo,children:c(ti,{method:zt,sessionId:e,nonce:t,email:R.email,billingName:[R.firstName,R.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:rt,billingApiUrl:te,onTokenizedBody:Pn,onErrorChange:le,onDecline:s,onCancel:Y,runBeforeButtonClick:Vn,onButtonClick:Q,isProcessing:Je,submitButtonColor:Ir,submitButtonBorderRadius:At,submitButtonStyle:f.submitButton,errorText:m})},zt)]})})]}):Te("form",{onSubmit:_a,className:T,noValidate:!0,style:{position:"relative"},children:[c(Za,{}),Se&&c(er,{status:Se,errorMessage:m,authorized:Nn}),Te("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ji("flopay-direct-paypal-gate-debug-default"),Xi("flopay-stripe-gate-debug-default"),mo&&ie&&Te(Br,{children:[$&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(aa,{sessionId:e,nonce:t,billingApiUrl:te,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:rt,clientId:ie.clientId,environment:ie.environment,currency:qe.toUpperCase(),isSubscription:it,providerObjectType:C,onTokenizedBody:Pn,onComplete:a,onErrorChange:le,onDecline:s,onTechnicalFailure:Ur,onButtonClick:Q,runBeforeButtonClick:Vn,isProcessing:Je,onLoadStateChange:Ea,onInitializationStateChange:Ra,session:Mt,existingOrderId:$?.orderId,debug:ne},$?.orderId??"fresh")]}),yo&&c(Ar,{stripe:Nr,options:wi,children:c(Os,{sessionId:e,nonce:t,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:rt,billingApiUrl:te,onTokenizedBody:Pn,onErrorChange:le,isProcessing:Je,onButtonClick:Q,onDecline:s,onTechnicalFailure:Ur,runBeforeButtonClick:Vn,onLoadStateChange:Ti,placeholderBorderRadius:kr})}),fo&&c(Ar,{stripe:Rn,options:Si,children:c(zs,{sessionId:e,nonce:t,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:rt,billingApiUrl:te,intentKind:B>0?"payment":"setup",expressMethods:qr,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,onTechnicalFailure:Ur,runBeforeButtonClick:Vn,onLoadStateChange:Mi,placeholderBorderRadius:kr})}),go&&c(Us,{sessionId:e,nonce:t,email:R.email,billingName:[R.firstName,R.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:te,paymentElementMethods:Vo,stripeInstance:Rn,paymentElementBaseOptions:Ia,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,runBeforeButtonClick:Vn,onLoadStateChange:Bi,isProcessing:Je,submitButtonColor:Ir,submitButtonBorderRadius:At,submitButtonStyle:f.submitButton,themeId:ve,onExpandApm:H,expandedApmMethod:zt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:kr}})]}),$e&&(ml||pl||yl)&&Te("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),c("span",{children:"or pay with card"}),c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),$e&&Gi]})}import{Fragment as or,jsx as X,jsxs as Yt}from"react/jsx-runtime";var Dr=44,hi="flopay_checkout_saved_payment_resume",va=new Map,ha=new Map;function Xs(e,t){t.settled&&t.consumers===0&&va.get(e)===t&&va.delete(e)}function ad(e,t,n){let r=ha.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};ha.set(e,a);let l=()=>{ha.get(e)===a&&ha.delete(e)};return o.then(l,l),o}function Oo(e){return new Promise(t=>setTimeout(t,e))}function ba(e,t,n){let r=ra({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:tl,enabled:t!==!1});return r.beginCheckout(n),r}function zo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function li(e,t,n,r,o){let a=ba(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),zo(a)}function id(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 fi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ci(e){return!e||e.data.stripe?.publishableKey?!1:!!fi(e)?.clientId}function lr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function sd(){if(!lr())return null;try{let e=window.sessionStorage.getItem(hi);return e?JSON.parse(e):null}catch{return null}}function Zs(e){if(lr())try{window.sessionStorage.setItem(hi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function di(){if(lr())try{window.sessionStorage.removeItem(hi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var bi=":idempotency-key";function nl(e,t){if(!lr())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 ui(e,t,n,r){if(lr())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 gi(e,t){if(lr())try{nl(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function rl(e,t){if(!lr())return null;try{let n=window.sessionStorage.getItem(e+bi);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 pi(e,t,n){if(lr())try{window.sessionStorage.setItem(e+bi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function mi(e,t){if(gi(e,t),!!lr())try{rl(e,t)&&window.sessionStorage.removeItem(e+bi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ld(){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 Qs(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 cd(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function yi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function dd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([l],[s])=>l<s?-1:l>s?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let l=0;l<t.length;l++){let s=t.charCodeAt(l);n=r^Math.imul(n^s,597399067),r=o^Math.imul(r^s,2869860233),o=a^Math.imul(o^s,951274213),a=n^Math.imul(a^s,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(l=>(l>>>0).toString(16).padStart(8,"0")).join("")}function Uo(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=>yi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>yi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>yi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:dd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function ud(e,t=!1){let n=Uo(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 pd(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=rd(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Qc(t.items,t.subscriptions)).map(g=>({type:g.type,code:g.code??g.providerItemId??g.providerPlanId??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??o).toUpperCase()})).sort((g,h)=>`${g.code}:${g.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),l=e.products.map(g=>({type:g.type,code:g.code??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??e.currency).toUpperCase()})).sort((g,h)=>`${g.code}:${g.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(a.length!==l.length)return!1;for(let g=0;g<a.length;g+=1){let h=a[g],b=l[g];if(h.code!==b.code||h.type!==void 0&&h.type!==b.type||h.quantity!==b.quantity||h.totalAmount!==b.totalAmount||h.overrideAmount!==b.overrideAmount||h.currency!==b.currency)return!1}let s=[...t.couponCodes??[]].sort(),k=[...e.coupons??[]].sort();return s.length===k.length&&s.every((g,h)=>g===k[h])}function vi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:s,error:k,onComplete:g,onError:h,onInstrument:b,onDecline:T,onCountryChange:M,onZipChange:u,showPayPal:I=!0,showStripe:he=!0,enabledPaymentMethods:j,showApplePay:S=!0,showGooglePay:pe=!0,debug:Z=!1,layout:se,theme:ae,buttonsTheme:ve,buttonsStyles:tt,cardButtonContent:be,cardBackButtonContent:Dt,cardTitleContent:Qe,showSecurityFooter:xe,onButtonClick:Me,onBeforeButtonClick:ee,enableAVS:Q,cardFieldOrder:A,cardPreFormSlot:Be,avsLayout:Fe,className:De,initialErrorMessage:ze=null,children:ke,checkoutMode:_,confirmLabel:ce,renderConfirmButton:Pe,onSessionCompleted:de}){let K=td(r),Ie=Ln(()=>el(ae),[ae]),at=a??Ie?.appearance,ht=n?"embedded_checkout":"standard_checkout",Ue=ke?"custom_layout":se==="buttons"?"buttons_layout":"default_layout",[V,D]=Ft(null),[B,qe]=Ft(null),He=Bt(null),[ie,it]=Ft(null),v=Bt(null),[P,Re]=Ft(null),ne=Ln(()=>n?Uo(n):"",[n]),W=n?`create:${ne}`:`session:${e??""}`,nt=P?.gateways?.stripe?"stripe":P?.gateways?.paypal?"paypal":void 0,Ae=Bt(new Set),Ye=Bt(W),Mt=Bt(W);xo(()=>{Mt.current=W,Ye.current!==W&&(Ye.current=W,Ae.current.clear())},[W]);let C=nr(x=>{if(Mt.current===W){if(qa.has(x.name)){if(Ae.current.has(x.name))return;Ae.current.add(x.name)}_t(()=>b?.(x))}},[W,b]),U=Qr(C,W),st=Bt(!1),We=nr(x=>{if(st.current)return;let L=x.gateway||!nt?x:{...x,gateway:nt};C(L)},[C,nt]);rr(()=>{U({class:"lifecycle",name:"checkout.mount"})},[U]);let[tn,Wt]=Ft(e??""),E=e??tn,mt=n?"":E,[Tt,lt]=Ft(!0),[Rt,pn]=Ft(null),[an,mn]=Ft("full"),[Lt,wn]=Ft(!1),[Gt,yt]=Ft(ze),[Ge,ft]=Ft(null),[sn,et]=Ft(null),[Wn,dt]=Ft(!1),[nn,bt]=Ft(void 0),[Jt,kn]=Ft(""),[yn,_n]=Ft(!1),[ln,Tn]=Ft(!1),[qt,G]=Ft(!1),fn=Bt(0),Nn=Bt(void 0),[Gn,Cr]=Ft("loading"),[Sr,cr]=Ft(0),Nt=Bt(!1),$e=Bt(!1),dr=Bt(!1),w=Bt(null),ct=Ln(()=>({checkoutMode:_??an,layout:ke?"unknown":se==="buttons"?"buttons":"embedded"}),[_,ke,an,se]),Kt=Bt(g);Kt.current=g;let In=Bt(h);In.current=h;let me=Bt(T);me.current=T,rr(()=>{jt(B)?.setCheckoutContext(ct),ie&&ie!==B&&jt(ie)?.setCheckoutContext(ct)},[B,ie,ct]);let cn=Bt(de);cn.current=de;let wr=nr(x=>{Cr(x),!(x!=="exhausted"||dr.current)&&(dr.current=!0,In.current?.(new Ht("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Lr=nr(()=>{Cr("retrying"),cr(x=>x+1)},[]);rr(()=>{Cr("loading"),cr(0),dr.current=!1},[E]),rr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:tl,checkout_type:ht,checkout_layout:Ue,billing_api_url:K})},[Ue,ht,K]);let gn=Ln(()=>n?Uo(n,!0):"",[n]),ur=Ln(()=>Jt===gn?nn:void 0,[nn,Jt,gn]),Jn=Ln(()=>n?Oa(n,ur):void 0,[n,ur]),On=_??Jn?.checkoutMode??"full",Ot=Ln(()=>Jn?{...Jn,checkoutMode:On}:void 0,[Jn,On]);rr(()=>{bt(void 0),kn(gn),Nn.current=void 0,G(!1)},[gn]),rr(()=>{yt(ze)},[ze]);let zn=nr((x,L,H)=>{_t(()=>{me.current?.(Vt(x,L,H))})},[]),Xn=nr(async(x,L)=>{yt(null),et(null),dt(!1),ft("processing");let H=L?.sessionId??x.id,Y=x.gateways?.stripe?"stripe":x.gateways?.paypal?"paypal":void 0,Se=He.current??v.current,F=jt(Se),q=Se?null:ba(K,o,ct),p={log:m=>{F?F.log(m):q?.log(m)},error:m=>{F?F.error(m):q?.error(m)},terminal:m=>{F?F.terminal(m):q?.terminal(m)},performance:m=>{F?F.performance(m):q?.performance(m)},now:()=>F?.now()??q?.now()??0,elapsed:m=>F?.elapsed(m)??Math.max(0,(q?.now()??m)-m)},O=p.now(),$=!!(L?.initialAutoProcessingError||L?.initialAutoProcessingPending),gt=!1,vt,te=()=>{gt||(gt=!0,$=!0,vt=p.now(),p.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},we=!1,Xt=()=>{we||(we=!0,p.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),p.performance({stage:"processing",durationMs:p.elapsed(O),durationMode:"machine",paymentMethodCategory:"saved"}),vt!==void 0&&p.performance({stage:"recovery",durationMs:p.elapsed(vt),durationMode:"machine",paymentMethodCategory:"saved"}))};p.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),st.current=!0;try{p.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{st.current=!1}U({class:"lifecycle",name:"payment.processing.started",provider:Y}),$&&te();let rt;try{let m=Is(L?.initialAutoProcessingError),d;if(m)te(),m.type==="paypal_redirect_required"&&w.current?.publishableKey&&Zs({sessionId:H,publishableKey:w.current.publishableKey,paypalPublishableKey:w.current.paypalPublishableKey}),d=await ca(m,{flopay:He.current,paypalFlopay:v.current,attempt3DS:L?.attempt3DS,billingApiUrl:K,sessionId:H,session:x,telemetry:!1}),m.type==="paypal_redirect_required"&&di();else if(L?.initialAutoProcessingPending){let re=(await new ga(K,{telemetry:!1}).waitForCheckoutSessionCompletion(L.initialAutoProcessingPending.sessionId,{initialDelayMs:L.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Gr(re))throw ea(re);d=Rr(re,H)}else{if(L?.initialAutoProcessingError)throw br(L.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.initialAutoProcessingError.checkoutMethod});if(L?.fromCreateSession)return L?.fallbackToFull&&(mn("full"),Qs("full")),!1;{let f=await no({billingApiUrl:K,sessionId:H,session:x,telemetry:!1});f.type==="success"?d=f.result:(te(),f.type==="paypal_redirect_required"&&w.current?.publishableKey&&Zs({sessionId:H,publishableKey:w.current.publishableKey,paypalPublishableKey:w.current.paypalPublishableKey}),d=await ca(f,{flopay:He.current,paypalFlopay:v.current,attempt3DS:L?.attempt3DS,billingApiUrl:K,sessionId:H,session:x,telemetry:!1}),f.type==="paypal_redirect_required"&&di())}}H&&to(H),Xt(),$&&(p.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),p.terminal({outcome:d.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),dt(d.status==="authorized"),ft("success"),await Oo(1200),rt=()=>Kt.current?.(d)}catch(m){let d=Lo(m),f=d.checkoutMethod??Do;yt(d.message),et(d.message),dt(!1),L?.fallbackToFull&&(p.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),mn("full"),Qs("full")),Xt();let ye=d.statusCode!==void 0?od(d.statusCode,"unknown"):void 0,re=ye==="4xx"?{requestCategory:"process_payment",statusClass:ye}:{},je=ye===void 0||ye==="4xx";if(je&&(d.telemetryOutcome==="payment_declined"||!!(d.declineCode||d.code?.toLowerCase().includes("declin"))))p.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...re});else if(je&&(d.telemetryOutcome==="validation_rejected"||d.type==="validation_error"))p.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...re});else{let R=Gs(m,$?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),oe=d.telemetryRequestCategory??"process_payment";st.current=!0;try{p.error({...R,...d.telemetryFailureCategory?{failureCategory:d.telemetryFailureCategory}:{},stage:$?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:oe})}finally{st.current=!1}U({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:oe,provider:Y})}return _t(()=>In.current?.(d)),zn(f,d,{code:d.code,declineCode:d.declineCode}),ft("error"),await Promise.allSettled([Oo(1500),L?.ensureProvidersReady?L.ensureProvidersReady():Promise.resolve()]),$&&(p.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Xt(),q&&zo(q),ft(null),et(null)}return _t(rt),!0},[zn,U,K,o,ct]);rr(()=>{if(typeof window>"u"||$e.current)return;let x=new URLSearchParams(window.location.search),L=x.get("payment_intent_client_secret");if(!L)return;let H=sd();H&&($e.current=!0,(async()=>{let Y,Se=0;yt(null),et(null),ft("processing"),wn(!0);try{if(x.get("redirect_status")==="failed")throw Object.assign(new Ht("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:F,paypalFlopay:q}=await ua({publishableKey:H.publishableKey,paypalPublishableKey:H.paypalPublishableKey,billingApiUrl:K,locale:l,telemetry:o});Y=jt(q??F),Se=Y?.now()??0,Y?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let p=(q??F)?.getRawProvider();if(!p)throw Object.assign(new Ht("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:O,error:$}=await p.retrievePaymentIntent(L);if($)throw Object.assign(new Ht($.message??"Failed to retrieve PayPal payment status.","api_error",{code:$.code}),{checkoutMethod:"paypal"});let gt=as(O?.status);if(!O||gt==="failed")throw Object.assign(new Ht("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let vt=typeof O.payment_method=="string"?O.payment_method:O.payment_method?.id,te=gt;if(H.sessionId){let rt=(await new ga(K,{telemetry:!1}).getUnifiedCheckoutSession(H.sessionId)).data.session;if(rt&&rt.status!=="complete"){let m=await no({billingApiUrl:K,sessionId:H.sessionId,session:rt,telemetry:!1,tokenizedData:{id:vt??O.id,type:"card",threeDSecureActionResultTokenId:O.id,isPaypal:!0}});if(m.type!=="success")throw Object.assign(new Ht("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});te=m.result.status}}H.sessionId&&to(H.sessionId),Y?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.performance({stage:"redirect_resume",durationMs:Y.elapsed(Se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Y?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ft("success"),await Oo(1200),_t(()=>Kt.current?.({status:te,paymentIntentId:O.id,paymentMethodId:vt,checkoutMethod:"paypal"}))}catch(F){let q=Lo(F),p=q.checkoutMethod??"paypal",O=!!(q.declineCode||q.code?.toLowerCase().includes("declin"));if(Y)Y.performance({stage:"redirect_resume",durationMs:Y.elapsed(Se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),O?Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Y.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(O){let $=ba(K,o,ct);$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),zo($)}else li(K,o,ct,"REDIRECT_RESUME_FAILED","redirect_resume");yt(q.message),et(q.message),_t(()=>In.current?.(q)),zn(p,q,{code:q.code,declineCode:q.declineCode}),ft("error"),await Oo(1500)}finally{di(),ld(),ft(null),et(null),wn(!1)}})())},[zn,l,K,o,ct]);let hn=Bt(null),rn=Ln(()=>Ot?Uo(Ot):"",[Ot]),Un=Bt(Ot);Un.current=Ot,rr(()=>{Wt(e??"")},[e]),rr(()=>{Nt.current=!1,yt(ze),et(null),dt(!1),ft(null)},[rn,ze,e]);async function qn(x,L,H){let Y=ba(K,o,ct),Se=new ga(K,{telemetry:!1}),F=!1;try{let q=x.idempotencyKey!==void 0?Js(x.idempotencyKey):void 0,p=nl(L,H),O=rl(L,H);p?.canonicalIdentity===H&&O&&O.canonicalIdentity===void 0&&(pi(L,H,O.idempotencyKey),O={...O,canonicalIdentity:H});let $=q??(O?.canonicalIdentity===H?O.idempotencyKey:void 0),gt,vt=!1;Y.log({name:p?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let te=p?.sid??null,we=null,Xt,rt,m=!1;if(te)try{we=await Se.getUnifiedCheckoutSession(te,p?.nonce),p&&p.canonicalIdentity===void 0&&(pd(we.data.session,x)?(ui(L,H,te,p.nonce??we.data.session?.clientSecret),O&&O.canonicalIdentity===void 0&&(pi(L,H,O.idempotencyKey),$??($=O.idempotencyKey))):(mi(L,H),O=null,$=q,te=null,we=null));let f=we?.data.session?.status,ye=we?.data.session,re=ye?.clientSecret||p?.nonce;if(te&&ye?.buyerIdentified===!1&&re&&(rt=Wr(Se,te,re,x.account)),te&&we&&f==="complete"){if(Ha(te))return{sid:te,result:we};mi(L,H),te=null,we=null,vt=!0}}catch{Y.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),p?.canonicalIdentity===void 0?(mi(L,H),$=q):gi(L,H),te=null}if(!te){!q&&(vt||!$)&&($=Js(),gt=$),$&&pi(L,H,$);let f=Y.now(),ye=0;Y.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let re={...x,idempotencyKey:$,avsCheck:!!Q,avsConfig:typeof Q=="object"?Q:void 0,checkoutType:"embedded_checkout",checkoutLayout:ke?"custom_layout":se==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(re,Xc,{configurable:!1,enumerable:!1,value:{onAttempt:J=>{ye=Math.max(ye,J)}}});let je=()=>{Y.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),Y.performance({stage:"session_create",durationMs:Y.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:ye,statusClass:"2xx"})},Je=J=>{let R=Gs(J,"CHECKOUT_SESSION_CREATE_FAILED","unknown");Y.performance({stage:"session_create",durationMs:Y.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:ye,statusClass:R.statusClass}),J instanceof Ht&&J.type==="validation_error"?Y.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):R.statusClass==="4xx"?Y.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(Y.error({...R,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),U({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(ed(re)){let J=await Se.createDetachedSession(re);J.claimed.catch(()=>{}),we=J.shell,te=J.sessionId,rt=J.claim,Xt=J.claimed.then(R=>{let oe=R.data.session?.id??J.sessionId;return oe&&ui(L,H,oe,R.data.session?.clientSecret??J.nonce),je(),R},R=>{throw gi(L,H),Je(R),R}).finally(()=>zo(Y)),Xt.catch(()=>{}),F=!0,Y.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),Y.performance({stage:"session_shell",durationMs:Y.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:ye,statusClass:"2xx",paymentMethodCategory:"card"})}else we=await Se.createAndFetchSession(re),je()}catch(J){throw Je(J),J}te=we.data.session?.id??te??"",te&&!Xt&&ui(L,H,te,we.data.session?.clientSecret)}let d=we?.data.session;return!rt&&te&&d?.buyerIdentified===!1&&d.clientSecret&&(rt=Wr(Se,te,d.clientSecret,x.account)),{sid:te??"",result:we,sdkGeneratedIdempotencyKey:gt,...Xt?{claimed:Xt}:{},...rt?{claim:rt}:{},...m?{claimRequiresIdentity:!0}:{}}}finally{F||zo(Y)}}let ut=Bt(qn);xo(()=>{ut.current=qn},[qn]);let bn=nr(async(x,L)=>{let H=Un.current;if(!H)throw new Ht("createSession is required to bootstrap checkout.","validation_error");let Y=Oa(H,x),Se=Uo(Y),F=ud(Y),q=va.get(Se);if(!q){let $={canonicalIdentity:Se,promise:ut.current(Y,F,Se),consumers:0,settled:!1};q=$,va.set(Se,$);let gt=()=>{$.settled=!0,Xs(Se,$)};$.promise.then(gt,gt)}q.consumers+=1;let p=!1,O=()=>{p||(p=!0,q.consumers-=1,Xs(Se,q))};L?.(O);try{let $=await q.promise;hn.current=Se,x&&(kn(gn),bt(ye=>ns(ye,x)));let{sid:gt,result:vt,claimed:te,claim:we,claimRequiresIdentity:Xt}=$;if(Nn.current=we,G(Xt===!0),D(vt),vt.data.session&&Re(vt.data.session),gt&&Wt(gt),te){fn.current+=1;let ye=fn.current;Tn(!0),te.then(re=>{fn.current===ye&&(D(re),re.data.session&&Re(re.data.session),Tn(!1),G(!1))},re=>{fn.current===ye&&(Tn(!1),G(!1),pn(re instanceof Ht?re:new Ht(re instanceof Error?re.message:"Failed to create session","api_error")))})}else fn.current+=1,Tn(!1),G(!1);let{publishableKey:rt,paypalPublishableKey:m}=da(vt),{flopay:d,paypalFlopay:f}=await ua({publishableKey:rt,paypalPublishableKey:m,billingApiUrl:K,locale:l,telemetry:o});return He.current=d,qe(d),v.current=f,it(f),lt(!1),$}catch($){throw hn.current===Se&&(hn.current=null),$}finally{L||O()}},[gn,l,K,o]),vn=Bt(Xn);vn.current=Xn;let $n=Bt(bn);$n.current=bn;let xn=nr(async x=>{if(!cd(x)||yn)return{sessionId:tn,session:P};_n(!0);try{let L=await bn(x);return{sessionId:L.sid,session:L.result.data.session??null}}finally{_n(!1)}},[bn,yn,tn,P]),Ce=nr(async x=>{let L=Nn.current;if(!L)return;let H=fn.current,Y=await L(x);fn.current===H&&(D(Y),Y.data.session&&Re(Y.data.session))},[]);rr(()=>{let x=!1,L;if(pn(null),rn){let Se=Un.current;return mn(On),lt(!1),hn.current===rn?()=>{x=!0}:(Re(rs(Se,_)),(async()=>{let F=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),q=On==="auto"&&!Nt.current&&!F;q&&(yt(null),et(null),ft("processing"));try{let p=await $n.current(void 0,vt=>{L=vt}),O=p.result.data.session??null;w.current=da(p.result);let $=ci(p.result),gt=Ha(p.sid||O?.id);if(!x&&q&&O&&!$&&!gt){Nt.current=!0,await ad(rn,p.sdkGeneratedIdempotencyKey,()=>vn.current(O,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:p.result.autoProcessingError,initialAutoProcessingPending:p.result.autoProcessingPending,autoProcessingAttempted:p.result.autoProcessingAttempted,sessionId:p.sid||O.id}));return}!x&&q&&(($||gt)&&(Nt.current=!0),ft(null),et(null))}catch(p){if(x)return;let O=p instanceof Ht||typeof p=="object"&&p!==null&&"code"in p?p.code:void 0;if(q&&O==="session_auto_completed"){Nt.current=!0,ft("success"),await Oo(1200),x||(_t(()=>{Kt.current?.({status:"succeeded"})}),ft(null),et(null));return}q&&(ft(null),et(null));let $=p instanceof Ht?p:new Ht(p instanceof Error?p.message:"Failed to create session","api_error");pn($)}finally{L?.(),L=void 0}})(),()=>{x=!0,L?.()})}lt(!0);async function H(){let Se=!1;try{let F=new ga(K,{telemetry:!1}),q=await F.getUnifiedCheckoutSession(E,t);if(x)return;D(q);let p=q.data.session??null;if(Re(p),!p)throw new Ht("No session data returned","api_error");let O=p.checkoutMode;if(O==="setup")throw new Ht("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(p.status==="authorized"){lt(!1),_t(()=>{Kt.current?.(Rr(p,E)),cn.current?.(p.successUrl??"")});return}if(p.status==="complete"){lt(!1),_t(()=>{cn.current?.(p.successUrl??"")});return}if(p.status==="expired")throw Qo(p);Se=!0;let $=_??O??"full";mn($),fn.current+=1;let gt=p.clientSecret||t;Nn.current=p.buyerIdentified===!1&>?Wr(F,E,gt,{...p.customer?.id?{userId:p.customer.id}:{}}):void 0,Tn(!1),G(!1);let vt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),te=ci(q);if($==="auto"&&!Nt.current&&!vt&&!te){Nt.current=!0;let we=Y(q);try{if(await vn.current(p,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>we,sessionId:E||p.id}),x)return;await we,x||lt(!1);return}catch{if(x)return;await we,x||lt(!1);return}}await Y(q),x||lt(!1)}catch(F){if(x)return;Se&&U({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),F instanceof Ht?!Se&&!id(F)&&li(K,o,ct,"NETWORK_REQUEST_FAILED","session_read"):li(K,o,ct,"INTERNAL_SDK_ERROR","checkout_mount");let q=F instanceof Ht?F:new Ht(F instanceof Error?F.message:"Failed to initialize checkout","api_error");pn(q),lt(!1)}}async function Y(Se){let{publishableKey:F,paypalPublishableKey:q}=da(Se);w.current={publishableKey:F,paypalPublishableKey:q};let{flopay:p,paypalFlopay:O}=await ua({publishableKey:F,paypalPublishableKey:q,billingApiUrl:K,locale:l,telemetry:o});He.current=p,qe(p),v.current=O,it(O)}return H(),()=>{x=!0}},[_,rn,On,mt,t]);let on=nr(async()=>{if(!(Lt||!P)){wn(!0),yt(null);try{await Xn(P,{attempt3DS:!0,fallbackToFull:!0,sessionId:E||P.id})}finally{wn(!1)}}},[E,Lt,Xn,P]),zt=fi(V),pr=ci(V),jn=Ln(()=>{if(!(!V||!P||!V.data.stripe?.publishableKey))return{billingApiUrl:K}},[V,P,K]),mr=!!(n&&!ke&&se==="buttons"&&ee&&On==="full"),En=Ln(()=>({session:P,loading:Tt,error:Rt,checkoutMode:an,inlineSessionDraft:Ot,applyInlineSessionPatch:mr?xn:void 0,inlineSessionPatchProcessing:yn,claimPending:ln,claimRequiresIdentity:qt,claimBuyerIdentity:Ce}),[P,Tt,Rt,an,Ot,mr,xn,yn,ln,qt,Ce]),Mn=!!n&&se==="buttons"&&!pr&&(!B||!jn),Ut=Ge?X(er,{status:Ge,errorMessage:sn,authorized:Wn}):null;if(Tt){if(s)return Yt(or,{children:[s,Ut]});if(se==="buttons"){let x=Ie?.buttonsLayout?.cardButton?.borderRadius??Ie?.appearance.variables?.borderRadius??8,L=H=>X("div",{style:{height:H,borderRadius:x,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Yt(or,{children:[Yt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[I&&L(Dr),he&&(S||pe)&&L(Dr),he&&L(Dr),X("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ut]})}return Yt(or,{children:[Yt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[X("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),X("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ut]})}return Rt?k?X(Hn.Provider,{value:En,children:k(Rt)}):X(Hn.Provider,{value:En,children:X("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Rt.message})}):Mn?Yt(or,{children:[X(Hn.Provider,{value:En,children:X(yd,{onButtonClick:Me,showPayPal:I,showStripe:he,showApplePay:S,showGooglePay:pe,theme:ae,buttonsTheme:ve,buttonsStyles:tt,cardButtonContent:be,cardBackButtonContent:Dt,cardTitleContent:Qe})}),Ut]}):pr&&P&&zt?Yt(or,{children:[X(Hn.Provider,{value:En,children:Yt("div",{className:De,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Gt&&X(eo,{icon:!1,children:Gt}),Gn==="retrying"&&X("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Gn==="exhausted"&&Yt("div",{role:"alert",children:[X("div",{children:"PayPal is temporarily unavailable. Please try again."}),X("button",{type:"button",onClick:Lr,children:"Retry PayPal"})]}),ln?s??X("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Dr,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:X("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):Gn!=="exhausted"?X("div",{"aria-hidden":Gn==="retrying"?!0:void 0,style:Gn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:X(bs,{sessionId:E,nonce:P.clientSecret||void 0,billingApiUrl:K,email:P.customer?.email||Ot?.account?.email,billingName:[P.customer?.firstName,P.customer?.lastName].filter(Boolean).join(" ")||[Ot?.account?.firstName,Ot?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Ce,clientId:zt.clientId,environment:zt.environment,currency:(P.currency??"usd").toUpperCase(),isSubscription:P.mode==="subscription",providerObjectType:zt.providerObjectType,onComplete:g,onErrorChange:yt,onDecline:T,onButtonClick:Me,onInitializationStateChange:wr,allowAutomaticRetry:Sr===0,session:P,telemetry:o,telemetryContext:ct,onInstrument:We,debug:Z},`${W}:paypal-init-${Sr}`)}):null]})}),Ut]}):!B||!jn?X(or,{children:Ut}):an==="confirm"?Yt(or,{children:[X(Hn.Provider,{value:En,children:X(ia,{flopay:B,paypalFlopay:ie,options:jn,onInstrument:We,children:Yt("div",{className:De,children:[Gt&&X("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Gt}),Pe?Pe({onConfirm:on,isProcessing:Lt}):X("button",{type:"button",onClick:on,disabled:Lt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Lt?"not-allowed":"pointer",opacity:Lt?.6:1},children:Lt?"Processing...":ce??"Confirm Purchase"})]})},W)}),Ut]}):Yt(or,{children:[X(Hn.Provider,{value:En,children:X(ia,{flopay:B,paypalFlopay:ie,options:jn,onInstrument:We,children:ke?Yt(or,{children:[Gt&&X("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Gt}),X(md,{sessionId:E,nonce:P?.clientSecret||void 0,billingApiUrl:K,session:P,children:ke})]}):X(ii,{sessionId:E,nonce:P?.clientSecret||void 0,email:P?.customer?.email||Ot?.account?.email,userId:P?.customer?.id||Ot?.account?.userId,firstName:P?.customer?.firstName||Ot?.account?.firstName,lastName:P?.customer?.lastName||Ot?.account?.lastName,totalAmount:P?Math.round(Zc(P).total*100):0,currency:P?.currency?.toLowerCase()??"usd",onComplete:g,onError:h,onDecline:T,error:Gt,onErrorChange:yt,showPayPal:I,showStripe:he,enabledPaymentMethods:j??V?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:V?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:pe,layout:se,theme:ae,buttonsTheme:ve,buttonsStyles:tt,appearance:at,cardButtonContent:be,cardBackButtonContent:Dt,cardTitleContent:Qe,onButtonClick:Me,onBeforeButtonClick:ee,onBuyerIdentityReady:Ce,enableAVS:Q,...A?{cardFieldOrder:A}:{},...Be?{cardPreFormSlot:Be}:{},avsLayout:Fe,country:P?.customer?.country,city:P?.customer?.city,state:P?.customer?.state,onCountryChange:M,onZipChange:u,avsCheck:!!Q,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ke?"custom_layout":se==="buttons"?"buttons_layout":"default_layout",className:De,directPaypal:fi(V),isSubscription:P?.mode==="subscription",session:P,dataAttachmentPending:ln,dataAttachmentRequiresIdentity:qt,debug:Z})},W)}),Ut]})}function md({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return X(or,{children:si.Children.map(o,a=>{if(!si.isValidElement(a))return a;let l=a.props,s={};return l.sessionId||(s.sessionId=e),!l.nonce&&t&&(s.nonce=t),l.billingApiUrl||(s.billingApiUrl=n),r?.customer&&(l.email||(s.email=r.customer.email),l.userId||(s.userId=r.customer.id),l.firstName||(s.firstName=r.customer.firstName),l.lastName||(s.lastName=r.customer.lastName)),Object.keys(s).length===0?a:si.cloneElement(a,s)})})}function yd({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:s,cardButtonContent:k,cardBackButtonContent:g,cardTitleContent:h}){let[b,T]=Ft(!1),M=Ln(()=>el(a),[a]),u=Ln(()=>{let S=M?.buttonsLayout??nd(l);return s?{...S,...s,cardButton:{...S.cardButton,...s.cardButton},cardFormContainer:{...S.cardFormContainer,...s.cardFormContainer},backButton:{...S.backButton,...s.backButton},backButtonIcon:{...S.backButtonIcon,...s.backButtonIcon},submitButton:{...S.submitButton,...s.submitButton},title:{...S.title,...s.title}}:S},[M,l,s]),I=M?.buttonsLayout?.cardButton?.borderRadius??M?.appearance.variables?.borderRadius??8,he=S=>X("div",{style:{height:S,borderRadius:I,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),j=k===void 0?{boxSizing:"border-box",height:Dr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let S=u.cardInputBorder??"#e5e7eb",pe=u.cardInputBackground??"white",Z=Kr(g),se=Kr(h);return Yt("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:[Yt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Yt("button",{type:"button",onClick:()=>T(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Z?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:[X("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:X("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:X("path",{d:"M15 18l-6-6 6-6"})})}),X(Hr,{content:g})]}),se?X("div",{style:{flex:1}}):X("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:X(Io,{content:h})})]}),X("div",{style:{backgroundColor:pe,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:X("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Yt("div",{style:{display:"flex"},children:[X("div",{style:{flex:1,backgroundColor:pe,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:X("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),X("div",{style:{flex:1,backgroundColor:pe,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:X("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),X("div",{style:{backgroundColor:pe,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:X("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),X("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),X("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 Yt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&he(Dr),n&&(r||o)&&he(Dr),n&&X("button",{type:"button",onClick:()=>{e?.("card"),T(!0)},style:{width:"100%",...j,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:
|
|
42
|
+
`})]})}return Yt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&he(Dr),n&&(r||o)&&he(Dr),n&&X("button",{type:"button",onClick:()=>{e?.("card"),T(!0)},style:{width:"100%",...j,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:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:X(Vr,{content:k})}),X("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as wd,jsx as so,jsxs as kd}from"react/jsx-runtime";var bd=44;function ol(e){return new Promise(t=>setTimeout(t,e))}function vd(e,t){return e instanceof lo?e:new lo(e instanceof Error?e.message:t,"api_error")}function Pd(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Cd(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 Sd({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:s,subscriptions:k,account:g,successUrl:h,cancelUrl:b,couponCodes:T,tagsData:M,utmMetadata:u,billingApiUrl:I,locale:he,theme:j,appearance:S,buttonsTheme:pe,buttonsStyles:Z,onSuccess:se,onError:ae,onDecline:ve,children:tt,disabled:be=!1,type:Dt="button",style:Qe,...xe}){let Me=qo(()=>fd(I),[I]),ee=qo(()=>Cd({createSession:n,clientId:a,products:l,items:s,subscriptions:k,account:g,successUrl:h,cancelUrl:b,couponCodes:T,tagsData:M,utmMetadata:u}),[g,b,a,T,n,l,s,k,h,M,u]),[Q,A]=$o(!1),[Be,Fe]=$o(null),[De,ze]=$o(null),[ke,_]=$o(!1),[ce,Pe]=$o(null),de=io(!0),K=io(null),Ie=io(ce),at=io(se),ht=io(ae),Ue=io(ve);ao(()=>{Ie.current=ce},[ce]),ao(()=>{at.current=se},[se]),ao(()=>{ht.current=ae},[ae]),ao(()=>{Ue.current=ve},[ve]),ao(()=>(de.current=!0,()=>{de.current=!1,K.current?.abort()}),[]),ao(()=>{if(typeof window>"u")return;let C=U=>{U.key==="Escape"&&Pe(null)};return window.addEventListener("keydown",C),()=>{window.removeEventListener("keydown",C)}},[]);let V=Pr((C,U=Do)=>{Ue.current?.(Vt(U,C,{code:C.code,declineCode:C.declineCode}))},[]),D=Pr(async C=>{de.current&&(ze(null),_(C.result.status==="authorized"),Fe("success"),await ol(1200),de.current&&_t(()=>at.current?.(C)))},[]),B=Pr(async(C,U)=>{de.current&&(ht.current?.(C),U?.emitDecline&&V(C,U.method),ze(C.message),_(!1),Fe("error"),await ol(1500))},[V]),qe=Pr(async(C,U,st)=>{let We=C.data.session??null;if(!We)throw new lo("No session data returned","api_error");let tn=We.clientSecret||t;if(Gr(We)){await D({result:Rr(We,U),session:We,sessionId:We.id||U,autoCompleted:!1});return}if(We.status==="expired")throw Qo(We);try{if(C.autoProcessingPending){let Tt=(await new Pi(Me).waitForCheckoutSessionCompletion(C.autoProcessingPending.sessionId,{initialDelayMs:C.autoProcessingPending.retryAfterMs})).data.session;if(!Gr(Tt))throw ea(Tt);await D({result:Rr(Tt,U),session:Tt,sessionId:Tt.id||U,autoCompleted:!1});return}if(C.autoProcessingError){if(C.autoProcessingError.type==="3ds_required"&&C.autoProcessingError.nextActionRedirectUrl&&U&&tn){let E=new AbortController;K.current=E;let mt;try{mt=await Es({billingApiUrl:Me,sessionId:U,nonce:tn,nextActionRedirectUrl:C.autoProcessingError.nextActionRedirectUrl,signal:E.signal})}finally{K.current===E&&(K.current=null)}if(mt.status==="declined")throw br({type:mt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:mt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:C.autoProcessingError.checkoutMethod});let Rt=(await new Pi(Me).waitForCheckoutSessionCompletion(U,{initialDelayMs:0,nonce:tn})).data.session;if(!Gr(Rt))throw br({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:C.autoProcessingError.checkoutMethod});await D({result:Rr(Rt,U),session:Rt,sessionId:Rt.id||U,autoCompleted:!1});return}throw br(C.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:C.autoProcessingError.checkoutMethod})}if(st?.fromCreateSession&&C.autoProcessingAttempted===!0)throw br({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Wt=await no({billingApiUrl:Me,sessionId:U??We.id,session:We,nonce:tn});if(Wt.type!=="success")throw br({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await D({result:Wt.result,session:We,sessionId:We.id||U,autoCompleted:!1})}catch(Wt){let E=Lo(Wt),mt=We.id||U;await B(E,{emitDecline:!0,method:E.checkoutMethod??Do}),Pd(E,mt)&&mt&&de.current&&Pe({sessionId:mt,errorMessage:E.message,nonce:tn||void 0})}},[t,Me,B,D]),He=Pr(async C=>{if(xe.onClick?.(C),!(C.defaultPrevented||be||Q)){if(Pe(null),e&&ee){let U=new lo("Provide either sessionId or create-session props, not both.","validation_error");await B(U),de.current&&(Fe(null),ze(null));return}if(!e&&!ee){let U=new lo("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await B(U),de.current&&(Fe(null),ze(null));return}A(!0),ze(null),_(!1),Fe("processing");try{let U=new Pi(Me);if(e){let st=await U.getUnifiedCheckoutSession(e,t);await qe(st,e);return}try{let st=await U.createAndFetchSession({...ee});await qe(st,st.data.session?.id??null,{fromCreateSession:!0})}catch(st){if((st instanceof lo||typeof st=="object"&&st!==null&&"code"in st?st.code:void 0)==="session_auto_completed"){await D({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw st}}catch(U){await B(vd(U,"Automatic payment failed. Please try again."))}finally{de.current&&(Fe(null),ze(null),A(!1))}}},[xe.onClick,ee,be,Q,t,qe,Me,e,B,D]),ie=Pr(C=>{let U=Ie.current;Pe(null),at.current?.({result:C,session:null,sessionId:U?.sessionId??null,autoCompleted:!1})},[]),it=Pr(C=>{ht.current?.(C)},[]),v=Pr(C=>{Ue.current?.(C)},[]),P=qo(()=>hd(j),[j]),Re=qo(()=>{let C=P?.buttonsLayout??gd(pe);return Z?{...C,...Z,cardButton:{...C.cardButton,...Z.cardButton}}:C},[P,pe,Z]),ne=qo(()=>{let C=P?.appearance;return S?C?{...C,...S,variables:{...C.variables,...S.variables}}:S:C},[S,P]),W=ne?.variables,nt=W?.colorPrimary??"#4A49FF",Ae=W?.colorPrimaryHover??ko(nt,.12),Ye=W?.borderRadius??"8px";return kd(wd,{children:[so("button",{...xe,type:Dt,onClick:He,disabled:be||Q,"aria-busy":Q,style:{width:"100%",...tt===void 0?{boxSizing:"border-box",height:bd,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Re.cardButton,...ai({themeBundle:P,resolvedPrimaryColor:nt,resolvedBorderRadius:Ye,submitButtonStyle:Re.submitButton,explicitPrimaryColor:W?.colorPrimary}),fontSize:Re.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:be||Q?"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||Q?.6:1,...Qe},onMouseEnter:C=>{xe.onMouseEnter?.(C),!C.defaultPrevented&&!be&&!Q&&(P||W?.colorPrimary)&&(C.currentTarget.style.backgroundColor=Ae)},onMouseLeave:C=>{xe.onMouseLeave?.(C),!C.defaultPrevented&&(P||W?.colorPrimary)&&(C.currentTarget.style.backgroundColor=nt)},onMouseDown:C=>{xe.onMouseDown?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(0.985)")},onMouseUp:C=>{xe.onMouseUp?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(1)")},children:so(Vr,{content:tt})}),Be&&so(er,{status:Be,errorMessage:De,authorized:ke}),ce&&so("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:C=>{C.target===C.currentTarget&&Pe(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:so("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:so(vi,{sessionId:ce.sessionId,nonce:ce.nonce,checkoutMode:"full",billingApiUrl:Me,locale:he,theme:j,...ne?{appearance:ne}:{},buttonsTheme:pe,buttonsStyles:Z,initialErrorMessage:ce.errorMessage,cardTitleContent:null,onComplete:ie,onError:it,onDecline:v})})})]})}export{aa as DirectPayPalButton,Sd as FloPayAutomaticPaymentButton,kl as FloPayCardSetup,wl as FloPayCardSetupError,vi as FloPayCheckout,ia as FloPayProvider,ii as SplitCardForm,La as VaultCardFields,Ep as dropThirdPartyOnlyError,Dl as useCheckout,gr as useFloPay,Ua as usePayPalFloPay};
|