@flopay/react 1.8.15 → 1.8.17
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 +8 -8
- 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 Da,d as ko,e as Qi,f as es,g as Sl,h as wl}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as Ip}from"@flopay/shared";import{PaymentAPI as Pi}from"@flopay/js";import{FloPayError as lo,resolveBillingApiUrl as yd,resolveButtonsLayoutTheme as fd,resolveTheme as gd}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 kl(){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 Il(){return Fn(Yr,{children:"Go back"})}function El(){return Fn(Yr,{children:"Secure card checkout"})}function Kr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Hr({content:e}){return Fn(Yr,{children:e===void 0?Fn(kl,{}):e})}function Vr({content:e}){return Fn(Yr,{children:e===void 0?Fn(Il,{}):e})}function Io({content:e}){return Fn(Yr,{children:e===void 0?Fn(El,{}):e})}import{FloPayError as La,isMoneySettledOutcome as Rl,isSetupIntentClientSecret as _d,isValidEmail as _l}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(!_l(l.email))return Promise.reject(new La("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 Na(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 Oa(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 Tl=[{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 Tl)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 La(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 La(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"||Rl(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,setupFutureUsage:"off_session"}:{mode:"setup"}}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 fa,SESSION_CREATE_TELEMETRY as Jc}from"@flopay/js";import{buildCheckoutDisplayData as Xc,classifyTelemetryFailure as Ws,FloPayError as Vt,foldIntoProducts as Zc,isDetachedSessionEligible as Qc,resolveBillingApiUrl as ed,resolveButtonsLayoutTheme as td,resolveIdempotencyKey as Gs,resolveSessionCurrency as nd,resolveTheme as Qs,SDK_VERSION as el,telemetryStatusClass as rd}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 ss}from"react";var Dn=ss({flopay:null,paypalFlopay:null,billingApiUrl:""}),Vn=ss({session:null,loading:!1,error:null});import{PaymentAPI as qa}from"@flopay/js";import{classifyTelemetryFailure as Vl,FloPayError as ms,generateIdempotencyKey as Yl,isValidEmail as Mo,normalizeGatewayEnvironment as Wl,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as $a,SDK_VERSION as Gl}from"@flopay/shared";import{loadScript as Jl}from"@paypal/paypal-js";import{useCallback as Ao,useEffect as Et,useMemo as Bo,useRef as Je,useState as Tr}from"react";import{isValidEmail as xl}from"@flopay/shared";import{useCallback as ls,useEffect as Ml,useRef as cs,useState as us}from"react";import{jsx as ds,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]=us(null),n=cs(null),r=cs(0),o=ls((l,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:s}),new Promise(k=>{n.current=k})),[]),a=ls(l=>{let s=n.current;n.current=null,t(null),s?.(l)},[]);return Ml(()=>()=>{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]=us(e.email?.trim()??""),k=xl(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",ds("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&&ds("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 Al(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=Al(e)?.toLowerCase()??"",r=`${ar(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Bl}from"@flopay/shared";import{useContext as ta}from"react";function gr(){return ta(Dn).flopay}function za(){return ta(Dn).paypalFlopay??null}function Fl(){return ta(Vn)}function ps(){return ta(Dn).billingApiUrl||Bl()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Nl}from"@flopay/shared";import{useCallback as Ol,useRef as na}from"react";import{useEffect as Dl,useLayoutEffect as Ll}from"react";var xo=typeof window>"u"?Dl:Ll;var zl={"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 Ul(e){return e==="stripe"||e==="paypal"?e:void 0}function ql(e){let t=Ul(e.provider),n={schemaVersion:Nl,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=zl[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 Ua=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]),Ol(l=>{if(a.current!==t)return;let s=ql(l);if(s){if(Ua.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}_t(()=>n.current?.(s))}},[t])}var $l=Symbol.for("@flopay/js.telemetry.bridge.v1"),jl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Kl(){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=Kl(),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[jl];return Hl(t?.(e)??{})}function jt(e){if(e)return e[$l]}import{jsx as xr,jsxs as ja}from"react/jsx-runtime";var oa=45,Xl=1e3,Zl=11e3,Ql=["https://www.paypal.com","https://www.sandbox.paypal.com"],ys="We couldn't open PayPal. Try again or choose another payment method.",ec={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 fs(e){return e.includes("No ack for postMessage init()")&&Ql.some(t=>e.includes(t))&&e.includes("10000ms")}function tc(e){return e?`${ys} Allow pop-ups for this site, then try again.`:ys}function nc(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 gs({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:et,telemetryContext:be,onInstrument:Dt,debug:Xe=!1}){let xe=gr(),Me=Qr(Dt,e),ee=Bo(()=>{if(xe)return null;let w=ra({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Gl,enabled:et!==!1});return w.setCheckoutContext(be??{}),w.beginCheckout(be??{}),w},[n,xe,et,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=Je(null),Fe=Je(0),De=Je(null),ze=Je(!1),[ke,_]=Tr(!1),[ce,Pe]=Tr(!1),[de,K]=Tr(0),Ie=Je(0),[ot,ht]=Tr(!1),Ue=Je(!1),H=Je(!1),[D,B]=Tr(!1),[qe,Ve]=Tr(!1),{request:ie,collect:at,finish:v}=Jr(),P=Je({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]),tt=ae?.gateways?.paypal?.providerObjectType??h,Ae=tt??(g?"subscription":"order"),Ze=tt==="order"||tt==="setup_token",Mt=Bo(()=>JSON.stringify([ne,l,k,s??"",Ae,Ze,e,ve??""]),[ne,l,k,s,ve,Ae,Ze,e]),C=Je(Mt),U=C.current!==Mt,it=Je(Xe),Ye=Je(null),[en,Wt]=Tr([]),E=Ao(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(S),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=S},[S]),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&&De.current?.focus()},[ot,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}st.current?.(tc(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(()=>{C.current!==Mt&&(C.current=Mt,Ue.current=!1,H.current=!1,_(!1),Pe(!1),B(!1),Lt.current?.("loading"))},[Mt]),Et(()=>{_t(()=>mn.current?.(ke&&!D))},[ke,D]);let $e=Wl(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=Yl(),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)},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=Ue.current||!pe;if(ur)return;ur=!0,In=!0,V(),Ot();let ye=d||fs(m);if(ye&&pe&&!Ue.current){Ue.current=!0,_(!1),Ve(!1),Pe(!0),Lt.current?.("retrying"),gn=setTimeout(()=>{Kt||K(re=>re+1)},Xl);return}if(ye||f){if(_(!1),Ve(!1),Pe(!1),B(!0),Lt.current?.("exhausted"),!H.current){H.current=!0;let re=fs(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,Le=await new qa(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(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?.(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 ms("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 qa(ne,{telemetry:!1}).createSessionIntent(f,ye??"",Ze?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:$a,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({...Vl(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 qa(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=Jl({clientId:l,currency:k,...Ae==="subscription"?{intent:"subscription",vault:!0}:Ae==="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(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?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 ms("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()||lt.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=nc(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 at("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:$a}:Ze?{id:oe,isPaypal:!0,gateway:"paypal",paymentMethodType:$a}:{id:oe,isPaypal:!0},Ke)}catch(Le){F(Le instanceof Error?Le.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 Ne=await oe("paypal");if(me()){await R.reject();return}if(!Ne.proceed){Qe.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)}`),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: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)??Qe.current;J&&bt.current.delete(J.surfaceKey),Qe.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)??Qe.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?.(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 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 We=A.startTiming();bn=setTimeout(()=>{me()||hn||(E("watchdog:11s retryable render timeout"),p("PayPal Buttons render did not settle within 11000ms.",!0))},Zl),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,Ae,Ze,e,ve,de,A,at,Re,E]);let dr=Xe?ja("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 kl,h as Il}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as Rp}from"@flopay/shared";import{PaymentAPI as Pi}from"@flopay/js";import{FloPayError as lo,resolveBillingApiUrl as gd,resolveButtonsLayoutTheme as hd,resolveTheme as bd}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 El(){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 Rl(){return Fn(Yr,{children:"Go back"})}function _l(){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(El,{}):e})}function Hr({content:e}){return Fn(Yr,{children:e===void 0?Fn(Rl,{}):e})}function Io({content:e}){return Fn(Yr,{children:e===void 0?Fn(_l,{}):e})}import{FloPayError as Na,isMoneySettledOutcome as Tl,isSetupIntentClientSecret as xd,isValidEmail as xl}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(!xl(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 Ml=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function mr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Ml)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"||Tl(e,t)}function as(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function is(e,t="automatic"){return{...Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}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 Zc}from"@flopay/js";import{buildCheckoutDisplayData as Qc,classifyTelemetryFailure as Js,FloPayError as Ht,foldIntoProducts as ed,isDetachedSessionEligible as td,resolveBillingApiUrl as nd,resolveButtonsLayoutTheme as rd,resolveIdempotencyKey as Xs,resolveSessionCurrency as od,resolveTheme as tl,SDK_VERSION as nl,telemetryStatusClass as ad}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 Wl,FloPayError as ms,generateIdempotencyKey as Gl,isValidEmail as Mo,normalizeGatewayEnvironment as Jl,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as ja,SDK_VERSION as Xl}from"@flopay/shared";import{loadScript as Zl}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 Al}from"@flopay/shared";import{useCallback as cs,useEffect as Bl,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 Bl(()=>()=>{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=Al(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 Fl(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=Fl(e)?.toLowerCase()??"",r=`${ar(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Dl}from"@flopay/shared";import{useContext as ta}from"react";function gr(){return ta(Dn).flopay}function Ua(){return ta(Dn).paypalFlopay??null}function Ll(){return ta(Hn)}function ys(){return ta(Dn).billingApiUrl||Dl()}import{FLO_INSTRUMENT_SCHEMA_VERSION as zl}from"@flopay/shared";import{useCallback as Ul,useRef as na}from"react";import{useEffect as Nl,useLayoutEffect as Ol}from"react";var xo=typeof window>"u"?Nl:Ol;var ql={"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 $l(e){return e==="stripe"||e==="paypal"?e:void 0}function jl(e){let t=$l(e.provider),n={schemaVersion:zl,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=ql[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]),Ul(l=>{if(a.current!==t)return;let s=jl(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 Kl=Symbol.for("@flopay/js.telemetry.bridge.v1"),Vl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Hl(){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 Yl(e){let t=Hl(),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[Vl];return Yl(t?.(e)??{})}function jt(e){if(e)return e[Kl]}import{jsx as xr,jsxs as Ka}from"react/jsx-runtime";var oa=45,Ql=1e3,ec=11e3,tc=["https://www.paypal.com","https://www.sandbox.paypal.com"],fs="We couldn't open PayPal. Try again or choose another payment method.",nc={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()")&&tc.some(t=>e.includes(t))&&e.includes("10000ms")}function rc(e){return e?`${fs} Allow pop-ups for this site, then try again.`:fs}function oc(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:Xl,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 yt=Ze(b),Tt=Ze(T),lt=Ze(M),Rt=Ze(u),pn=Ze(I),an=Ze(Z),yn=Ze(j),Lt=Ze(S),wn=Ze(a),Gt=Ze(se),mt=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(()=>{yt.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(()=>{yn.current=j},[j]),Et(()=>{Lt.current=S},[S]),Et(()=>{Gt.current=se},[se]),Et(()=>{mt.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 mn=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?.(rc(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&&mn()},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(),mn())},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(()=>yn.current?.(ke&&!D))},[ke,D]);let $e=Jl(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,ye=()=>Kt||In,cn,wr=!1,Lr=()=>{cn=Gl(),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=y=>{if(!y||typeof y.getBoundingClientRect!="function")return"(no rect)";let d=y.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},on=y=>{if(!y)return"(empty)";try{let d=new URL(y,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 y.slice(0,80)}},zt=y=>{let d=y.getAttribute("src"),f=y.getAttribute("srcdoc"),me=y.getAttribute("name"),re=y.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)"),me&&je.push(`name=${me.slice(0,40)}`),re!==null&&je.push(`sandbox="${re.slice(0,40)}"`),je.join(" ")},pr=y=>{if(!(y instanceof HTMLIFrameElement))return"";try{let d=y.contentDocument;if(!d)return"cd=null";let f=d.body?.children.length??0,me=d.body?.innerHTML.length??0,re=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${f}children,${me}ch] head[${re}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},jn=[],yr=y=>{if(ye())return;let d=y.message??String(y.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=y=>{if(ye())return;let d=y.reason instanceof Error?y.reason.message:String(y.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",yr),window.removeEventListener("unhandledrejection",En)),vn=!1},x=()=>{if(!(vn||ye()||hn)){if(vn=!0,jn.length=0,Mn.value=0,typeof window<"u"&&(window.addEventListener("error",yr),window.addEventListener("unhandledrejection",En)),typeof PerformanceObserver<"u")try{qn=new PerformanceObserver(y=>{if(!ye())for(let d of y.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:y=>{y?x():Ut()}};We.current=Y,st.current&&x();let Se=y=>{if(!y)return!1;let d=y.toLowerCase();return d.includes("zoid destroyed")||d.includes("destroyed all components")||d.includes("window closed")||d.includes("detected container element removed")},F=y=>{if(ye()||Se(y))return;let d=mr(y)??y;_t(()=>lt.current?.(d))},q=y=>{Kt||(B(!0),y.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:",y))},p=(y,d=!1)=>{if(Kt)return;let f=Ue.current||!pe;if(ur)return;ur=!0,In=!0,H(),Ot();let me=d||gs(y);if(me&&pe&&!Ue.current){Ue.current=!0,_(!1),He(!1),Pe(!0),Lt.current?.("retrying"),gn=setTimeout(()=>{Kt||K(re=>re+1)},Ql);return}if(me||f){if(_(!1),He(!1),Pe(!1),B(!0),Lt.current?.("exhausted"),!V.current){V.current=!0;let re=gs(y)?"paypal_init_timeout":d?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",re)}return}q(y)};B(!1);let O=async(y,d=et.current)=>{if(ye())return;let f=d?.sessionId??e;if(yt.current){await yt.current(y,{sessionId:f,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let me=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(me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let je=mt.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:y,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(ye())return;let Pt=await Le.json().catch(()=>null),Ne=Pt?.message??"PayPal payment failed.",$t=mr(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(ye())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=mr(Je)??Je;F(J),_t(()=>Rt.current?.(Vt("paypal",J)));return}},$=()=>new ms("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),gt=y=>ye()?Promise.reject($()):Promise.resolve(y),vt=async y=>{if(ye())throw $();wr||Lr();let d=et.current,f=d?.sessionId??e,me=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,me??"",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({...Wl(je,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),je}if(ye())throw $();if(re.provider!=="paypal"||re.providerObjectType!==Ae)throw new Error(y);return A.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),re.providerObjectId},te=(y,d)=>{let f=d?.nonce??sn.current;if(!f)return;let me=d?.sessionId??e,re=Zr(y)??ar(y)??"provider_declined";new $a(ne,{telemetry:!1}).reportSessionIntentDecline(me,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 y=$e==="live"?"production":$e;Xt=Zl({clientId:l,currency:k,...Ae==="subscription"?{intent:"subscription",vault:!0}:Ae==="order"?{intent:"capture"}:{},...y?{environment:y}:{},...y==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Xt.then(d=>{if(E(`loadScript:resolved inactive=${ye()} ns=${!!d} buttons=${!!d?.Buttons}`),ye())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(ye()||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 ms("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Le=mt.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=oc(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{ye()||He(!1)}}},me=d.Buttons({style:{layout:"horizontal",height:oa,tagline:!1},onClick:async(J,R)=>{if(ye()){await R.reject();return}Lr();let oe=Gt.current,Ke={};if(oe)try{let Ne=await oe("paypal");if(ye()){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(ye())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(ye()||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=me.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=me,xn=()=>{if(!vn||$n||ye()||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(!ye()){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(ye()||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(()=>{ye()||hn||(E("watchdog:11s retryable render timeout"),p("PayPal Buttons render did not settle within 11000ms.",!0))},ec),me.render(rn).then(()=>{if(E(`render:resolved inactive=${ye()}`),H(),ye()){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:ja("div",{children:[dr,ie&&xr(Xr,{identity:ie.identity,methodLabel:ie.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:v,onCancel:()=>v(null)}),ja("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),ot&&xr("button",{ref:De,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:ln,style:ec,children:"Try PayPal again"})]})}function aa(e){return xr(gs,{...e})}function hs(e){return xr(gs,{...e})}import{jsx as bs,jsxs as rc}from"react/jsx-runtime";function eo({children:e,margin:t,icon:n=!0,styleOverride:r}){return rc("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&&bs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:bs("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 oc}from"@flopay/shared";import{useEffect as hr,useMemo as ac,useRef as vs,useState as Ps}from"react";import{jsx as ic}from"react/jsx-runtime";function ia({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=Ps(e instanceof Promise?null:e),[s,k]=Ps(t instanceof Promise||!t?null:t),g=vs(null),h=vs(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=oc(n?.billingApiUrl),M=ac(()=>({flopay:a,paypalFlopay:s,billingApiUrl:T,emitInstrument:b}),[a,s,T,b]);return ic(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 Cs,PaymentAPI as ws}from"@flopay/js";import{classifyPaymentRejection as sc,FloPayError as Ct,isAuthorizationOnlySession as lc,isSetupIntentClientSecret as cc,normalizeCheckoutFailureOutcome as Ss}from"@flopay/shared";var Do="card";async function dc(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 uc(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 Ya(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 ks(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 pc(e){return e.status==="succeeded"||e.status==="declined"}async function Is(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 mc(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||!pc(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 et=ve.data;!et||typeof et!="object"||et.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 mc(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 Ya(new Ct(a,"api_error",{code:Ss(e?.outcome)??Ss(e?.type)??e?.gatewayErrorCode}),r)}function Va(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 Es(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 yc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Es(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 ws(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 ws(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??Va(n)});if(j.ok){let Z=typeof j.json=="function"?await j.json().catch(()=>null):null;return lc(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=Es(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 yc({billingApiUrl:s,sessionId:k,nonce:g,responseJson:S});if(Z)return Z;throw Ya(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:sc(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 Ya(new Ct("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=cc(e.threeDSecureToken),b=null,T=e.paymentMethodId,M=await Fo(()=>dc(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(()=>uc(g,e.threeDSecureToken,{payment_method:T,return_url:s??Va(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??Va(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([Cs(e,{billingApiUrl:n,locale:r,telemetry:o}),a?Cs(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 fc}from"@flopay/js";import{COUNTRY_OPTIONS as gc,classifyPaymentRejection as hc,FloPayError as Yn,filterStripeMethodsByCountry as bc,getPostalCodeExample as vc,getPostalCodeLabel as Qa,getStateFromPostalCode as Ts,getStateLabel as Wa,getStateOptions as Pc,getStripeMethodDisplayName as Fr,hasVendoredStripeMethodLogo as Cc,isAuthorizationOnlySession as Ga,isAVSFieldVisible as He,isPostalCodeSupported as Sc,isSetupIntentClientSecret as wc,isValidEmail as Qt,isValidPostalCode as kc,needsStripeMethodExplicitConfirm as xs,normalizeCheckoutFailureOutcome as Ic,partitionStripeMethods as Ec,resolveAVSConfig as Rc,resolveButtonsLayoutTheme as _c,resolveStripeMethodBrandVariant as Tc,resolveTheme as xc,stripeExpressMethodToOptionKey as Ms}from"@flopay/shared";import{ExpressCheckoutElement as Us,PaymentElement as Mc,Elements as Ar,useElements as ni,useStripe as ri}from"@stripe/react-stripe-js";import Ac,{useCallback as ge,useContext as oo,useEffect as wt,useMemo as St,useRef as fe,useState as ue}from"react";function Rs(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 _s={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",As="flopay_wallet_resume",qs="fw1",Bc=300*1e3,Fc=900,Dc=25e3,Ja={};function $s(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 ro(e).createSessionIntent(...n)}catch(o){throw $s(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var No="flopay_paypal_resume",Lc=250,Bs="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 ya({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new ro(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Nc(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 js({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 Oc({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=js({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 zc=`
|
|
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:nc,children:"Try PayPal again"})]})}function aa(e){return xr(hs,{...e})}function bs(e){return xr(hs,{...e})}import{jsx as vs,jsxs as ac}from"react/jsx-runtime";function eo({children:e,margin:t,icon:n=!0,styleOverride:r}){return ac("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 ic}from"@flopay/shared";import{useEffect as hr,useMemo as sc,useRef as Ps,useState as Cs}from"react";import{jsx as lc}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=ic(n?.billingApiUrl),M=sc(()=>({flopay:a,paypalFlopay:s,billingApiUrl:T,emitInstrument:b}),[a,s,T,b]);return lc(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 cc,FloPayError as Ct,isAuthorizationOnlySession as dc,isSetupIntentClientSecret as uc,normalizeCheckoutFailureOutcome as ws}from"@flopay/shared";var Do="card";async function pc(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 yc(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 fc(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 fc(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=mr(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 gc({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 dc(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 gc({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:cc(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=uc(e.threeDSecureToken),b=null,T=e.paymentMethodId,M=await Fo(()=>pc(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(()=>yc(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=mr(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=mr(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 hc}from"@flopay/js";import{COUNTRY_OPTIONS as bc,classifyPaymentRejection as vc,FloPayError as Yn,filterStripeMethodsByCountry as Pc,getPostalCodeExample as Cc,getPostalCodeLabel as Qa,getStateFromPostalCode as xs,getStateLabel as Ga,getStateOptions as Sc,getStripeMethodDisplayName as Fr,hasVendoredStripeMethodLogo as wc,isAuthorizationOnlySession as Ja,isAVSFieldVisible as Ve,isPostalCodeSupported as kc,isSetupIntentClientSecret as Ic,isValidEmail as en,isValidPostalCode as Ec,needsStripeMethodExplicitConfirm as Ms,normalizeCheckoutFailureOutcome as Rc,partitionStripeMethods as _c,resolveAVSConfig as Tc,resolveButtonsLayoutTheme as xc,resolveStripeMethodBrandVariant as Mc,resolveTheme as Ac,stripeExpressMethodToOptionKey as As}from"@flopay/shared";import{ExpressCheckoutElement as qs,PaymentElement as Bc,Elements as Ar,useElements as ni,useStripe as ri}from"@stripe/react-stripe-js";import Fc,{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",Dc=300*1e3,Lc=900,Nc=25e3,pa={};function js(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 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",Oc=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 zc(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 Uc({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 qc=`
|
|
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 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 Uc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function qc(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 Ks={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 $c(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Fs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ei(e){return e==="paypal"?"PayPal":Fr(e)}function jc(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 Kc(e){let t=vc(e);return`Enter a valid ${Qa(e)}${t?` (e.g. ${t})`:""}`}function Hc(e,t,n){let r=Sc(e),o=t.trim(),a=n&&r,l=a&&!o,s=a&&!!o&&!kc(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:s}}function Vc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!Qt(n);return{required:t,empty:r,malformed:o,value:n}}function Ds(e,t){return t instanceof Yn?t:new Yn(t instanceof Error?t.message:`${$c(e)} before-click hook failed.`,"validation_error")}function Za(){return c("style",{children:zc})}function Yc(e){return typeof e=="number"?`${e}px`:e}function Vs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Ys({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 Ls(e){return e!=="unavailable"&&e!=="load_error"}function ii(e){return c(Gc,{...e})}function Ns({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=!Qt(n?.trim())||!b?.trim(),{request:et,collect:be,finish:Dt}=Jr(),Xe=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((H,D,B)=>{g?.(H,D,{...B,popupBlocked:B?.popupBlocked??fr(D)}),Be(!0),Q(qe=>qe+1)});wt(()=>{A&&Me.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)}),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 ot=ge(()=>{Be(!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"),qe=H.get("redirect_status");if(!D||!B)return;Xe.current=!0;let Ve;try{let at=localStorage.getItem(No);if(at){let v=JSON.parse(at);v.clientSecret===B&&(Ve={...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?.(Ht("paypal",P));return}let{paymentIntent:at,error:v}=await j.retrievePaymentIntent(B);if(v){a?.(v.message??"Failed to retrieve PayPal payment status.");return}if(at&&(at.status==="requires_capture"||at.status==="succeeded")){let P=typeof at.payment_method=="string"?at.payment_method:at.payment_method?.id;o({id:P??at.id,type:"card",threeDSecureActionResultTokenId:at.id,isPaypal:!0},Ve)}else{let P="PayPal payment was not completed. Please try again.";a?.(P),k?.(Ht("paypal",P))}}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){De.current.delete(ee),H.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"),H.resolve()},[l,s,h,ze,se,ee]),Ue=ge(async H=>{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){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}B={accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}}let qe=B?.sessionId??e,Ve=B?.nonce??t,ie=await Oc({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,v=Sn({...B?.accountPatch,...ie});try{if(ae(!0),a?.(null),!qe||!Qt(at))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),H.paymentFailed({reason:"fail"});return}let W=await ma(r,he,qe,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,Ae={return_url:window.location.href};if(ne?.id&&(Ae.payment_method=ne.id),typeof window<"u")try{localStorage.setItem(No,JSON.stringify({clientSecret:tt,sessionId:qe,nonce:Ve,accountPatch:v}))}catch{}let{error:Ze,paymentIntent:Mt}=await j.confirmPayment({clientSecret:tt,confirmParams:Ae,redirect:"if_required"});if(Ze){if(typeof window<"u")try{localStorage.removeItem(No)}catch{}if(To(Ze)){let U=Ze.message??"Your payment was declined.";a?.(U),k?.(Ht("paypal",U,{code:ar(Ze),declineCode:Zr(Ze)})),await ya({billingApiUrl:r,sessionId:qe,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(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:Ve});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(Ys,{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:ot,style:Ks,children:"Try PayPal again"}),et&&c(Xr,{identity:et.identity,methodLabel:et.methodLabel,onComplete:Dt,onCancel:()=>Dt(null)},et.id),c("div",{style:{display:et?"none":void 0},children:c(Us,{onReady:H=>Z(Vs(H,["paypal"])),onLoadError:()=>{Z("load_error"),oi(jt(I),"paypal","paypal")},onClick:ht,onConfirm:Ue,onCancel:()=>{let H=De.current.get(ee);De.current.delete(ee),jt(I)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),_(H?.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 Os({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),et=fe(!Qt(n?.trim())||!T?.trim()).current,{request:be,collect:Dt,finish:Xe}=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:ot,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 H=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),H()},[Ie,h,H]),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]),Ve=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&&ot()){Re();return}if(ne&&!K(ne.generation)){Re();return}ne||K();let W=v.expressPaymentType??ne?.method??ke.current,tt=ne??null,Ae=Fs(W),Ze=jt(he),Mt=Ze?.now()??globalThis.performance?.now()??Date.now(),C=new AbortController,U=!1,it,Ye=new Promise((E,mt)=>{it=mt}),en=window.setTimeout(()=>{U=!0,C.abort(),it(Ja)},Dc),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(Ae));if(!lt.proceed){Re();return}tt={accountPatch:lt.accountPatch,sessionId:lt.sessionId,nonce:lt.nonce}}let E=tt?.sessionId??e,mt=tt?.nonce??t,Tt=js({event:v,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)){Re("Buyer details are required."),Dt(ei(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){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",ma(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=wc(an)?S.confirmSetup({elements:pe,clientSecret:an,redirect:"if_required"}):S.confirmPayment({elements:pe,clientSecret:an,redirect:"if_required"}),Lt=!1,wn=lt=>{if(Lt||lt.error||ne&&Ue.current!==ne.generation)return;let ft=lt.setupIntent??lt.paymentIntent,sn=ft?.id,Qe=ft?.status,Wn=lt.setupIntent?Qe==="succeeded":Eo(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=`${qs}:${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(To(yt)){let lt=yt.message??"Your payment was declined.";Re(lt),s?.(lt),g?.(Ht(Ae,lt,{code:ar(yt),declineCode:Zr(yt)})),ya({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(tn),!Lt)throw new Error("Invalid provider returned for APM intent")}catch(E){E===Ja&&Ze?.error({errorCode:"REQUEST_TIMEOUT",stage:"callback",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"timeout",failureCategory:"provider_runtime"}),Re(),D(W,E,E===Ja?"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)}},[S,pe,e,t,n,T,Dt,M,r,j,o,l,s,g,b,D,K,ht,ot,Ue,he,ee]),ie=St(()=>{let v=["applePay","googlePay","paypal","link","amazonPay","klarna"],P=new Set(["applePay","googlePay"]),Re=new Set(a.map(Ms)),ne={};for(let W of v)Re.has(W)?ne[W]=P.has(W)?"always":"auto":ne[W]="never";return ne},[a]),at=St(()=>a.map(Ms),[a]);return Te(Br,{children:[c(Ys,{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:Ks,children:["Try ",ei(Fe)," again"]}),be&&c(Xr,{identity:be.identity,methodLabel:be.methodLabel,onComplete:Xe,onCancel:()=>Xe(null)},be.id),c("div",{style:{display:be?"none":void 0},children:c(Us,{onReady:v=>{se(Vs(v,at))},onLoadError:v=>{se("load_error"),oi(jt(he),"stripe","wallet")},onClick:async v=>{ke.current=v.expressPaymentType,_.current=Fs(v.expressPaymentType);let P=!0,Re=window.setTimeout(()=>{P=!1,v.reject()},Fc),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:Ve,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,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 Wc({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=Tc(e,t),M=_s[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:pa,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:Cc(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),et=fe(!1),[be,Dt]=ue(!1),[Xe,xe]=ue("loading"),[Me,ee]=ue(""),Q=!Qt(r?.trim()),A=!Q||Qt(Me.trim()),Be=ge(async()=>{if(!Z||!se||M||et.current||!be)return;et.current=!0,ve(!0);let Fe=b?await b("card"):{proceed:!0};if(!Fe.proceed){et.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),!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(!De||!ce)throw new Error("Missing sessionId or email for payment.");let ht=ot.type||e,Ue=await ma(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 H=Ue.clientSecret;if(typeof window<"u")try{localStorage.setItem(tr,JSON.stringify({clientSecret:H,sessionId:De,nonce:ze,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: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?.(Ht("card",ie,{code:qe??"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:De,nonce:ze})}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,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(Mc,{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()}:{},...Qt(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Be()},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(eo,{margin:"0.75rem 0 0",children:j})]})}function zs({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),[et,be]=ue(null),[Dt,Xe]=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,Xe(_);let ce=M?await M("card"):{proceed:!0};if(!ce.proceed){xe.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 Ue=await ee(Fr(_),Ie);if(!Ue){xe.current=!1;return}Ie=Ue,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 Ue=await ma(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 H=Ue.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 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?.(Ht("card",ie,{code:qe??"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(Ue){h?.(Ue instanceof Error?Ue.message:"Payment failed. Please try again.")}finally{xe.current=!1,Xe(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!==_||(xs(_)?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(Ac.Fragment,{children:[c(Wc,{method:_,themeId:Z,submitting:Pe,disabled:de,highlighted:ce,hasNextStep:xs(_),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 Gc({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:et,buttonsStyles:be,appearance:Dt,cardButtonContent:Xe,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:ot,onZipChange:ht,avsCheck:Ue,checkoutType:H,checkoutLayout:D,totalAmount:B=0,currency:qe="usd",initialCardOpen:Ve=!1,directPaypal:ie,isSubscription:at=!1,session:v,dataAttachmentPending:P=!1,dataAttachmentRequiresIdentity:Re=!1,debug:ne=!1}){let W=gr(),tt=za(),Ae=oo(Vn),{emitInstrument:Ze}=oo(Dn),Mt=v??Ae.session,C=Mt?.gateways?.paypal?.providerObjectType??ie?.providerObjectType,U=P||Ae.claimPending===!0,it=Re||Ae.claimRequiresIdentity===!0,Ye=U&&!it,en=ps(),[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,_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",_,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(()=>Rc(Fe),[Fe]),fn=G!==null,Nn=St(()=>Ga(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"||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:v?.captureMethod}),[W,$e,e,In,v?.captureMethod]),cn=St(()=>{let i=st,y=G?He(G.postal_code,i):!1;return Hc(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=(Ee,Oe)=>He(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,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(()=>Xa(v?.vault)),[Ce,on]=ue(Ve&&Nt?"card":"buttons"),[zt,pr]=ue(null),jn=Ce==="expanding"||Ce==="card",mr=v?.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(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]),nt=Be??Ae.claimBuyerIdentity??Jt,m=u??mt,d=St(()=>xc(ve),[ve]),f=St(()=>{let i=d?.buttonsLayout??_c(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(()=>es({appearance:ye,buttonsStyles:f,layout:ae}),[ye,f,ae]),je=Ae.inlineSessionPatchProcessing??!1,We=(M??Wt)||je,J=te.replace(/\/+$/,""),R=St(()=>Oa({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()),Le=fe(null);$e&&Le.current===null&&(Le.current=Ke);let Pt=$e&&(Le.current??Ke),Ne=St(()=>Vc(Qe,Pt),[Qe,Pt]),$t=Ne.empty||Ne.malformed,Rn=St(()=>W?W.getRawProvider():null,[W]),Nr=St(()=>tt?tt.getRawProvider():null,[tt]),co=B||100,Or=qe.toLowerCase(),va=St(()=>ye?fc(ye):null,[ye]),zr=va,Ci=St(()=>{let i=va??{},y=i.rules??{};return{...i,rules:{...y,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...y[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...y[".AccordionItemContents"]??{}}}}},[va]),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]),Pa=fe(""),[ki,ol]=ue(!1),Ca=ge(()=>{ol(!0)},[]);wt(()=>{if(!$e||!Pt||!nt||!ki||$t||Pa.current)return;let i=Sn({email:Qt(R.email?.trim())?R.email?.trim():Tn.current.trim(),firstName:R.firstName?.trim(),lastName:R.lastName?.trim()});Pa.current=JSON.stringify(i),nn(y=>({...y,...i})),Promise.resolve(nt(i)).catch(y=>{Pa.current="",le(y instanceof Error?y.message:"Failed to attach buyer details.")})},[$e,Pt,nt,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?.(Ht(i,y,N))},[s]),Ur=ge((i,y,N)=>{let _e=N?.popupBlocked??fr(y),z=jc(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 Sa=fe(!1),Ii=ge(()=>{let{resolvedAccount:i,avsConfig:y,avsCheckProp:N}=Zn.current,_e=i.email?.trim(),z=Qt(_e)?_e:Tn.current.trim();if(!Qt(z))return null;let Ee=i.firstName?.trim(),Oe=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?Ts(pt,(bt.current??"").trim()):null,un=Xt?ln.current:Ge;return{accountData:{userId:i.userId??"",email:z,...Ee?{firstName:Ee}:{},...Oe?{lastName:Oe}:{},...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}}:{}}},[]),Ei=fe(U);Ei.current=U,wt(()=>{U||m!==Bs||Zn.current.updateError(null)},[U,m]),wt(()=>{!$e||!me||me.setSubmitGate?.(wr||U||$t)},[$e,me,wr,U,$t]),wt(()=>{if(!$e||!me)return;Sa.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")},Lc),F("processing");let{baseUrl:Oe,sessionId:pt,nonce:Xt,updateError:kt,onError:It}=Zn.current;if(!pt||!Xt)return;let rt=Ii();if(!rt){kt("Enter a valid email address."),O.current="idle",F(null);return}new ro(Oe).patchAccountSnapshot(pt,Xt,rt,{telemetryMode:"best_effort"}).catch(dn=>{if(!Nc(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 Oe=>{if(to(Oe.sessionId??Zn.current.sessionId),O.current="terminal",F("success"),await new Promise(kt=>setTimeout(kt,1200)),Sa.current)return;Sa.current=!0;let pt=Zn.current,Xt=Ga(pt)||Oe.outcome==="authorized";Zn.current.onComplete?.(Xt?{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:Xt}=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??Ic(Oe.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 Oe=>{let{updateError:pt,onError:Xt}=Zn.current,kt=Oe.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: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}Ca(),Zn.current.updateError(Bs)});return()=>{i=!0,p.current&&(clearTimeout(p.current),p.current=null),O.current="idle",y(),N(),_e(),z(),Ee()}},[$e,me,Ca,Ii]);let Qn=!!ie?.clientId,uo=Array.isArray(S),jo=uo&&S.length>0,al=uo&&S.includes("paypal"),{expressMethods:Ko,paymentElementMethods:po}=St(()=>Ec(S,{excludePaypal:Qn}),[S,Qn]),Ri=Qn||!!tt,il=St(()=>Ri?Ko.filter(i=>i!=="paypal"):Ko,[Ko,Ri]),sl=St(()=>{let i=[];return Z&&i.push("apple_pay"),se&&i.push("google_pay"),i},[Z,se]),qr=uo?il:sl,ll=j&&qr.length>0,wa=fn?st:_,Ho=St(()=>{let i=wa?.trim().toUpperCase();return i?pe?po.filter(y=>{let N=pe[y];return!N||N.length===0||N.includes(i)}):bc(po,wa):po},[po,wa,pe]),ka=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"),[cl,Ia]=ue(!1),[Fi,Ea]=ue("loading"),[Vo,dl]=ue();wt(()=>{dl(Rs())},[]);let Di=he&&(Qn||(uo?al:Vo===!1)),Li=j&&ll,mo=!Ye&&Di&&Qn,Ni=Fi==="retrying"||Fi==="exhausted",yo=!Ye&&Di&&!!Nr&&(!Qn||Ni),fo=!Ye&&Li&&!!Rn,go=!Ye&&j&&jo&&Ho.length>0&&!!Rn,ul=mo&&!Ni?cl:yo&&Ls(_i),pl=fo&&Ls(xi),ml=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(Vo!==void 0&&!Ye&&!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,Vo,Ye,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=Ds(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]),Hn=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=Ds(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=Oa(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,Xt=()=>{Ze?.({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??qc(i),tokenizedData:Oe,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),So=Bn&&!un&&Zt?Ts(Ge,(bt.current??"").trim()):null,wo=un?ln.current:So;return{country:Ge,...Zt&&bt.current?{zip:bt.current}:{},...He(G.city,Ge)&&_n.current?{city:_n.current}:{},...wo?{state:wo}:{},...Bn&&kn.current?{addressLine1:kn.current}:{},...He(G.address_line_2,Ge)&&yn.current?{addressLine2:yn.current}:{}}})():{}},chv:b,avsCheck:Ue??!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=Ga(v)||Ge?.status==="authorized";to(N),F("success"),gt(null),await new Promise(Bn=>setTimeout(Bn,1200)),a?.(un?{status:"authorized",...typeof Ge?.paymentId=="string"?{paymentId:Ge.paymentId}:v?.paymentId?{paymentId:v.paymentId}:{},sessionId:typeof Ge?.sessionId=="string"?Ge.sessionId:N,...typeof Ge?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Ge.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 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:So}=await Bn.confirmPayment({clientSecret:Ge,confirmParams:Zt,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(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}Ia(!1),Ea("loading"),gt({orderId:Ge,attempts:un+1}),F(null);return}hc(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){$s(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,Ue,H,D,b,W,tt,v,a,le,Kn,Ze]),Pn=ge((i,y)=>{k?k(i):$i(i,y)},[k,$i]),ho=`${qs}:${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>Bc||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 rt=localStorage.getItem(It);if(!rt)return null;try{return JSON.parse(rt)}catch{return localStorage.removeItem(It),null}},Ee=z(tr)??z(As),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(As);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=Ee?.paymentMethodType??Ee?.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(_e==="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=Eo(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??Ee?.paymentMethodId??Ee?.tokenId??rt.id,type:"card",threeDSecureActionResultTokenId:rt.id,gateway:Ee?.gateway??"stripe",paymentMethodType:Xt},Oe)})()},[e,Pn,W,le,Kn]);let Ra=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,yl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),_a=Cn?.colorBackground,fl=_a&&!yl.has(_a)?_a: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),gl=An(Go),Ta=f.cardFormContainer?.backgroundColor??fl??(bo?"white":"#EDEDFF"),$r=f.cardInputBackground??Cn?.colorBackground??"white",xa=Kr(xe),Hi=Kr(Me),jr=f.nameInput,Vi=f.cardInputFontSize??Yc(jr?.fontSize)??Cn?.fontSizeBase??"16px",Yi=typeof jr?.fontFamily=="string"?jr.fontFamily:Cn?.fontFamily??"Poppins, sans-serif",Wi=Qi(jr?.fontWeight)??400,hl=f.cardInputColor??(typeof jr?.color=="string"?jr.color:void 0)??Cn?.colorText??"#262833",bl=f.cardInputPlaceholderColor??"#9ca3af",At=Cn?.borderRadius??"8px",kr=Cn?.borderRadius??f.cardButton?.borderRadius??At,Ir=Cn?.colorPrimary??"#4A49FF",vl=Cn?.colorPrimaryHover??ko(Ir,.12),Ma=Cn?.colorText??"#262833",Aa={fontSize:Vi,fontFamily:Yi,fontWeight:Wi,color:hl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Po={marginTop:"0.375rem",...Aa,fontSize:"0.75rem",lineHeight:1.4,color:Ki},Pl={"--flopay-input-placeholder-color":bl,"--flopay-input-font-size":Vi,"--flopay-input-font-family":Yi,"--flopay-input-font-weight":String(Wi)},Co=f.cardFormContainer??{},Ba=Co.padding??(bo?"0":"1rem"),Fa=Co.borderRadius??At,Cl=me&&$n?c(Da,{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:Ta,borderRadius:Fa,...Co,padding:Ba,...Pl,display:"flex",flexDirection:"column"},children:[c("style",{children:`
|
|
25
|
+
`,ya=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 $c={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function jc(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:ya,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 Kc(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 Vc(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 Hc(e){let t=Cc(e);return`Enter a valid ${Qa(e)}${t?` (e.g. ${t})`:""}`}function Yc(e,t,n){let r=kc(e),o=t.trim(),a=n&&r,l=a&&!o,s=a&&!!o&&!Ec(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:s}}function Wc(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:`${Kc(e)} before-click hook failed.`,"validation_error")}function Za(){return c("style",{children:qc})}function Gc(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(Xc,{...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 Uc({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 ma(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,yt)=>{st=yt}),tn=window.setTimeout(()=>{U=!0,C.abort(),st(pa)},Nc),Wt=async(E,yt,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:yt,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,yt=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",ma(r,j,E,yt??"",{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,yn=Ic(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:yt,accountPatch:lt,paymentMethodId:nn,providerIntentId:sn,paymentMethodType:W}))}catch{}try{l({id:nn,type:"card",threeDSecureActionResultTokenId:sn},{accountPatch:lt,paymentMethodCategory:"wallet",sessionId:E,nonce:yt})}finally{if(typeof window<"u")try{localStorage.removeItem(bt)}catch{}}};yn.then(Ge=>{U&&wn(Ge)},()=>{});let Gt;try{Gt=await Wt("three_ds_handoff","provider_sdk",yn)}catch(Ge){throw Ge!==pa&&Ye?.error({...ss(Ge),stage:"three_ds_handoff",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"unknown"}),Ge}let mt=Gt.error;if(mt){if(To(mt)){let Ge=mt.message??"Your payment was declined.";Re(Ge),s?.(Ge),g?.(Vt(Ae,Ge,{code:ar(mt),declineCode:Zr(mt)})),fa({billingApiUrl:r,sessionId:E,nonce:yt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:W,providerDeclineReason:ar(mt)??"provider_declined"}})}else Re(),D(W,mt,"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()},Lc),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 Gs(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function Jc({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=Mc(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:ya,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:wc(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 ma(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(Bc,{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 ma(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?Gs(k,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(Fc.Fragment,{children:[c(Jc,{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 Xc({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=ys(),[Wt,E]=ue(!1),[yt,Tt]=ue(null),[lt,Rt]=ue(_??"US"),[pn,an]=ue(ce??""),[yn,Lt]=ue(Pe??""),[wn,Gt]=ue(de??""),[mt,Ge]=ue(K??""),[ft,sn]=ue(Ie??""),[et,Wn]=ue(""),[dt,nn]=ue({}),bt=fe(ce??""),Jt=fe(_??"US"),kn=fe(Pe??""),mn=fe(de??""),_n=fe(K??""),ln=fe(Ie??""),Tn=fe(""),qt=fe({});wt(()=>{let i=(m,N,_e,z,Ee)=>{if(qt.current[m])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,mn,Gt),i("city",K,_n,Ge),i("state",Ie,ln,sn)},[_,ce,Pe,de,K,Ie,at,ht]);let G=St(()=>Tc(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,ye=St(()=>!W||!$e||!e||!In?null:W.cardCapture({sessionId:e,captureMethod:v?.captureMethod}),[W,$e,e,In,v?.captureMethod]),cn=St(()=>{let i=lt,m=G?Ve(G.postal_code,i):!1;return Yc(i,pn,m)},[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 m=lt,N=(Ee,Oe)=>Ve(Ee,m)&&!Oe.trim(),_e={line1:N(G.address_line_1,yn),city:N(G.city,mt),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,yn,mt,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(m=>m[i]?m:{...m,[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",yr=v?.gateways?.stripe?"stripe":void 0,En=ge(()=>{Ye?.({class:"card_surface",provider:yr})},[yr,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 m=we.current.claim;return async N=>{await m(N)}},[Be,Ae.claimBuyerIdentity,v?.buyerIdentified,e,t,te,o,g,h]),rt=Be??Ae.claimBuyerIdentity??Xt,y=u??yt,d=St(()=>Ac(ve),[ve]),f=St(()=>{let i=d?.buttonsLayout??xc(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]),me=Dt??d?.appearance,re=St(()=>es({appearance:me,buttonsStyles:f,layout:ae}),[me,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(()=>Wc(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(()=>me?hc(me):null,[me]),zr=Pa,Ci=St(()=>{let i=Pa??{},m=i.rules??{};return{...i,rules:{...m,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...m[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...m[".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,il]=ue(!1),Sa=ge(()=>{il(!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(m=>({...m,...i})),Promise.resolve(rt(i)).catch(m=>{Ca.current="",le(m instanceof Error?m.message:"Failed to attach buyer details.")})},[$e,Pt,rt,ki,$t,R.email,R.firstName,R.lastName,le]),wt(()=>{!$e||!ye||ye.setCardFieldOrder?.(De??null,G==null&&!Pt)},[$e,ye,De,G,Pt]),wt(()=>{(Ce==="expanding"||Ce==="collapsing"||Ce==="apm-expanding"||Ce==="apm-collapsing")&&le(null)},[Ce,le]);let Kn=ge((i,m,N)=>{s?.(Vt(i,m,N))},[s]),Ur=ge((i,m,N)=>{let _e=N?.popupBlocked??fr(m),z=Vc(i,_e),Ee=_r(N?.code)??ar(m)??"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 m=!0;return new ro(J).getVaultCapture(e,t).then(N=>{if(!m)return;let _e=Xa(N);_e?xn(_e):le("Failed to load the secure card form.")}).catch(N=>{m&&le(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{m=!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:m,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=m?Ve(m.state,pt):!1,kt=m?Ve(m.address_line_1,pt):!1,It=m?Ve(m.postal_code,pt):!1,ot=m?Ve(m.city,pt):!1,dn=m?Ve(m.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&&mn.current?{addressLine2:mn.current}:{},country:pt},...N!==void 0?{avsCheck:N}:{},...m?{avsConfig:{country:Ve(m.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||y!==Fs||Zn.current.updateError(null)},[U,y]),wt(()=>{!$e||!ye||ye.setSubmitGate?.(wr||U||$t)},[$e,ye,wr,U,$t]),wt(()=>{if(!$e||!ye)return;wa.current=!1;let i=!1,m=ye.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")},Oc),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(!zc(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=ye.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=ye.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??Rc(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=ye.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=ye.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",m(),N(),_e(),z(),Ee()}},[$e,ye,Sa,Ii]);let Qn=!!ie?.clientId,uo=Array.isArray(S),jo=uo&&S.length>0,sl=uo&&S.includes("paypal"),{expressMethods:Ko,paymentElementMethods:po}=St(()=>_c(S,{excludePaypal:Qn}),[S,Qn]),Ri=Qn||!!nt,ll=St(()=>Ri?Ko.filter(i=>i!=="paypal"):Ko,[Ko,Ri]),cl=St(()=>{let i=[];return Z&&i.push("apple_pay"),se&&i.push("google_pay"),i},[Z,se]),qr=uo?ll:cl,dl=j&&qr.length>0,ka=fn?lt:_,Vo=St(()=>{let i=ka?.trim().toUpperCase();return i?pe?po.filter(m=>{let N=pe[m];return!N||N.length===0||N.includes(i)}):Pc(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"),[ul,Ea]=ue(!1),[Fi,Ra]=ue("loading"),[Ho,pl]=ue();wt(()=>{pl(_s())},[]);let Di=he&&(Qn||(uo?sl:Ho===!1)),Li=j&&dl,yo=!We&&Di&&Qn,Ni=Fi==="retrying"||Fi==="exhausted",mo=!We&&Di&&!!Nr&&(!Qn||Ni),fo=!We&&Li&&!!Rn,go=!We&&j&&jo&&Vo.length>0&&!!Rn,yl=yo&&!Ni?ul:mo&&Ns(_i),ml=fo&&Ns(xi),fl=go&&Ai!=="load_error",Oi=i=>i==="loading"||i==="ready",zi=yo||mo&&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,m)=>Ae.applyInlineSessionPatch?Ae.applyInlineSessionPatch(i).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let _e=Ls(m,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 m=await A({method:i,sessionId:e||void 0,createSession:Ae.inlineSessionDraft});if(m===!1)return{proceed:!1};if(m&&typeof m=="object"){m.account&&nn(_e=>({..._e??{},...m.account}));let N=await qi(m,i);return N.error?{proceed:!1,accountPatch:m.account}:{proceed:!0,accountPatch:m.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(m){let N=Ls(i,m);return le(N.message),l?.(N),{proceed:!1}}},[qi,Ae.inlineSessionDraft,A,l,e,le]),$i=ge(async(i,m)=>{if(q.current)return;q.current=!0,E(!0),F("processing"),le(null);let N=m?.sessionId??e,_e=m?.nonce??t,z=za(R,m?.accountPatch),Ee=m?.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:m?.paymentMethodCategory??jc(i),tokenizedData:Oe,accountData:{...m?.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)&&mn.current?{addressLine2:mn.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}vc(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,m)=>{k?k(i):$i(i,m)},[k,$i]),ho=`${$s}:${e}`;wt(()=>{if(typeof window>"u")return;let i=localStorage.getItem(ho);if(!i)return;let m;try{m=JSON.parse(i)}catch{localStorage.removeItem(ho);return}if(!m||typeof m.createdAt!="number"||Date.now()-m.createdAt<0||Date.now()-m.createdAt>Dc||typeof m.paymentMethodId!="string"||typeof m.providerIntentId!="string"||typeof m.paymentMethodType!="string"||m.sessionId!==e||!t||m.nonce!==t||!qr.includes(m.paymentMethodType)){localStorage.removeItem(ho);return}localStorage.removeItem(ho),Pn({id:m.paymentMethodId,type:"card",threeDSecureActionResultTokenId:m.providerIntentId,gateway:"stripe",paymentMethodType:m.paymentMethodType},{...m.accountPatch?{accountPatch:m.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),m=i.get("payment_intent"),N=i.get("payment_intent_client_secret"),_e=i.get("redirect_status");if(!m||!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=me?.variables,gl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ta=Cn?.colorBackground,hl=Ta&&!gl.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),bl=An(Go),xa=f.cardFormContainer?.backgroundColor??hl??(bo?"white":"#EDEDFF"),$r=f.cardInputBackground??Cn?.colorBackground??"white",Ma=Kr(xe),Vi=Kr(Me),jr=f.nameInput,Hi=f.cardInputFontSize??Gc(jr?.fontSize)??Cn?.fontSizeBase??"16px",Yi=typeof jr?.fontFamily=="string"?jr.fontFamily:Cn?.fontFamily??"Poppins, sans-serif",Wi=Qi(jr?.fontWeight)??400,vl=f.cardInputColor??(typeof jr?.color=="string"?jr.color:void 0)??Cn?.colorText??"#262833",Pl=f.cardInputPlaceholderColor??"#9ca3af",At=Cn?.borderRadius??"8px",kr=Cn?.borderRadius??f.cardButton?.borderRadius??At,Ir=Cn?.colorPrimary??"#4A49FF",Cl=Cn?.colorPrimaryHover??ko(Ir,.12),Aa=Cn?.colorText??"#262833",Ba={fontSize:Hi,fontFamily:Yi,fontWeight:Wi,color:vl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Po={marginTop:"0.375rem",...Ba,fontSize:"0.75rem",lineHeight:1.4,color:Ki},Sl={"--flopay-input-placeholder-color":Pl,"--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,wl=ye&&$n?c(La,{capture:ye,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 m=O.current;(m==="idle"||m==="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,...Sl,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
|
-
`}),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:
|
|
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(
|
|
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?{...ka,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"},_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:Ra,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?Uc:{},..._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:nt,clientId:ie.clientId,environment:ie.environment,currency:qe.toUpperCase(),isSubscription:at,providerObjectType:C,onTokenizedBody:Pn,onComplete:a,onErrorChange:le,onDecline:s,onTechnicalFailure:Ur,onButtonClick:Q,runBeforeButtonClick:Hn,isProcessing:We,onLoadStateChange:Ia,onInitializationStateChange:Ea,session:Mt,existingOrderId:$?.orderId,debug:ne},$?.orderId??"fresh")]}),yo&&c(Ar,{stripe:Nr,options:wi,children:c(Ns,{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:Ur,runBeforeButtonClick:Hn,onLoadStateChange:Ti,placeholderBorderRadius:kr})}),fo?c(Ar,{stripe:Rn,options:Si,children:c(Os,{sessionId:e,nonce:t,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:nt,billingApiUrl:te,intentKind:B>0?"payment":"setup",expressMethods:qr,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,onTechnicalFailure:Ur,runBeforeButtonClick:Hn,onLoadStateChange:Mi,placeholderBorderRadius:kr})}):Li?c("div",{style:{height:pa,borderRadius:kr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,go&&c(zs,{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:ka,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,runBeforeButtonClick:Hn,onLoadStateChange:Bi,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,...ai({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:Ee=>{!We&&(d||Cn?.colorPrimary)&&(Ee.currentTarget.style.backgroundColor=vl)},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(Hr,{content:Xe})}),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:Ta,borderRadius:Fa,...Co,padding:Ba},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:xa?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(Vr,{content:xe})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Ma,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: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 Zi&&zt&&Zo&&Rn&&j?Te("form",{onSubmit:Ra,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:Ta,borderRadius:Fa,...Co,padding:Ba},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:xa?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(Vr,{content:xe})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Ma,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: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)]})})]}):Te("form",{onSubmit:Ra,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:nt,clientId:ie.clientId,environment:ie.environment,currency:qe.toUpperCase(),isSubscription:at,providerObjectType:C,onTokenizedBody:Pn,onComplete:a,onErrorChange:le,onDecline:s,onTechnicalFailure:Ur,onButtonClick:Q,runBeforeButtonClick:Hn,isProcessing:We,onLoadStateChange:Ia,onInitializationStateChange:Ea,session:Mt,existingOrderId:$?.orderId,debug:ne},$?.orderId??"fresh")]}),yo&&c(Ar,{stripe:Nr,options:wi,children:c(Ns,{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:Ur,runBeforeButtonClick:Hn,onLoadStateChange:Ti,placeholderBorderRadius:kr})}),fo&&c(Ar,{stripe:Rn,options:Si,children:c(Os,{sessionId:e,nonce:t,email:R.email,billingName:oe||void 0,onBuyerIdentityReady:nt,billingApiUrl:te,intentKind:B>0?"payment":"setup",expressMethods:qr,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,onTechnicalFailure:Ur,runBeforeButtonClick:Hn,onLoadStateChange:Mi,placeholderBorderRadius:kr})}),go&&c(zs,{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:ka,onTokenizedBody:Pn,onErrorChange:le,onButtonClick:Q,onDecline:s,runBeforeButtonClick:Hn,onLoadStateChange:Bi,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&&(pl||ul||ml)&&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",ba=new Map,ga=new Map;function Js(e,t){t.settled&&t.consumers===0&&ba.get(e)===t&&ba.delete(e)}function od(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 Oo(e){return new Promise(t=>setTimeout(t,e))}function ha(e,t,n){let r=ra({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:el,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=ha(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),zo(a)}function ad(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 id(){if(!lr())return null;try{let e=window.sessionStorage.getItem(hi);return e?JSON.parse(e):null}catch{return null}}function Xs(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 tl(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{tl(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function nl(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{nl(e,t)&&window.sessionStorage.removeItem(e+bi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function sd(){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 Zs(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 ld(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 cd(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:cd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function dd(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 ud(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=nd(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Zc(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:et,cardButtonContent:be,cardBackButtonContent:Dt,cardTitleContent:Xe,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=ed(r),Ie=Ln(()=>Qs(ae),[ae]),ot=a??Ie?.appearance,ht=n?"embedded_checkout":"standard_checkout",Ue=ke?"custom_layout":se==="buttons"?"buttons_layout":"default_layout",[H,D]=Ft(null),[B,qe]=Ft(null),Ve=Bt(null),[ie,at]=Ft(null),v=Bt(null),[P,Re]=Ft(null),ne=Ln(()=>n?Uo(n):"",[n]),W=n?`create:${ne}`:`session:${e??""}`,tt=P?.gateways?.stripe?"stripe":P?.gateways?.paypal?"paypal":void 0,Ae=Bt(new Set),Ze=Bt(W),Mt=Bt(W);xo(()=>{Mt.current=W,Ze.current!==W&&(Ze.current=W,Ae.current.clear())},[W]);let C=nr(x=>{if(Mt.current===W){if(Ua.has(x.name)){if(Ae.current.has(x.name))return;Ae.current.add(x.name)}_t(()=>b?.(x))}},[W,b]),U=Qr(C,W),it=Bt(!1),Ye=nr(x=>{if(it.current)return;let L=x.gateway||!tt?x:{...x,gateway:tt};C(L)},[C,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(ze),[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:el,checkout_type:ht,checkout_layout:Ue,billing_api_url:K})},[Ue,ht,K]);let gn=Ln(()=>n?Uo(n,!0):"",[n]),ur=Ln(()=>Gt===gn?nn:void 0,[nn,Gt,gn]),Jn=Ln(()=>n?Na(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,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??v.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=ks(L?.initialAutoProcessingError),d;if(m)te(),m.type==="paypal_redirect_required"&&w.current?.publishableKey&&Xs({sessionId:V,publishableKey:w.current.publishableKey,paypalPublishableKey:w.current.paypalPublishableKey}),d=await ca(m,{flopay:Ve.current,paypalFlopay:v.current,attempt3DS:L?.attempt3DS,billingApiUrl:K,sessionId:V,session:x,telemetry:!1}),m.type==="paypal_redirect_required"&&di();else if(L?.initialAutoProcessingPending){let re=(await new fa(K,{telemetry:!1}).waitForCheckoutSessionCompletion(L.initialAutoProcessingPending.sessionId,{initialDelayMs:L.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Gr(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"),Zs("full")),!1;{let f=await no({billingApiUrl:K,sessionId:V,session:x,telemetry:!1});f.type==="success"?d=f.result:(te(),f.type==="paypal_redirect_required"&&w.current?.publishableKey&&Xs({sessionId:V,publishableKey:w.current.publishableKey,paypalPublishableKey:w.current.paypalPublishableKey}),d=await ca(f,{flopay:Ve.current,paypalFlopay:v.current,attempt3DS:L?.attempt3DS,billingApiUrl:K,sessionId:V,session:x,telemetry:!1}),f.type==="paypal_redirect_required"&&di())}}V&&to(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 Oo(1200),nt=()=>Kt.current?.(d)}catch(m){let d=Lo(m),f=d.checkoutMethod??Do;yt(d.message),Qe(d.message),dt(!1),L?.fallbackToFull&&(p.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),mn("full"),Zs("full")),Jt();let ye=d.statusCode!==void 0?rd(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=Ws(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([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{Jt(),q&&zo(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=id();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=as(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 no({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&&to(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 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 $=ha(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),Qe(q.message),_t(()=>In.current?.(q)),zn(p,q,{code:q.code,declineCode:q.declineCode}),ft("error"),await Oo(1500)}finally{di(),sd(),ft(null),Qe(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),Qe(null),dt(!1),ft(null)},[rn,ze,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?Gs(x.idempotencyKey):void 0,p=tl(L,V),O=nl(L,V);p?.canonicalIdentity===V&&O&&O.canonicalIdentity===void 0&&(pi(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&&(ud(we.data.session,x)?(ui(L,V,te,p.nonce??we.data.session?.clientSecret),O&&O.canonicalIdentity===void 0&&(pi(L,V,O.idempotencyKey),$??($=O.idempotencyKey))):(mi(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=Wr(Se,te,re,x.account)),te&&we&&f==="complete"){if(Ha(te))return{sid:te,result:we};mi(L,V),te=null,we=null,vt=!0}}catch{Y.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),p?.canonicalIdentity===void 0?(mi(L,V),$=q):gi(L,V),te=null}if(!te){!q&&(vt||!$)&&($=Gs(),gt=$),$&&pi(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,Jc,{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=Ws(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(Qc(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&&ui(L,V,oe,R.data.session?.clientSecret??J.nonce),je(),R},R=>{throw gi(L,V),We(R),R}).finally(()=>zo(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&&ui(L,V,te,we.data.session?.clientSecret)}let d=we?.data.session;return!nt&&te&&d?.buyerIdentified===!1&&d.clientSecret&&(nt=Wr(Se,te,d.clientSecret,x.account)),{sid:te??"",result:we,sdkGeneratedIdempotencyKey:gt,...Jt?{claimed:Jt}:{},...nt?{claim:nt}:{},...m?{claimRequiresIdentity:!0}:{}}}finally{F||zo(Y)}}let ut=Bt(qn);xo(()=>{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=Na(V,x),Se=Uo(Y),F=dd(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,Js(Se,$)};$.promise.then(gt,gt)}q.consumers+=1;let p=!1,O=()=>{p||(p=!0,q.consumers-=1,Js(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:Jt}=$;if(Nn.current=we,G(Jt===!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 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,qe(d),v.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(!ld(x)||yn)return{sessionId:en,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,en,P]),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&&Re(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}:(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),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 $=ci(p.result),gt=Ha(p.sid||O?.id);if(!x&&q&&O&&!$&&!gt){Nt.current=!0,await od(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 Oo(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(Re(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&>?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||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&&!ad(F)&&li(K,o,ct,"NETWORK_REQUEST_FAILED","session_read"):li(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,qe(p),v.current=O,at(O)}return V(),()=>{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(H),pr=ci(H),jn=Ln(()=>{if(!(!H||!P||!H.data.stripe?.publishableKey))return{billingApiUrl:K}},[H,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=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&&(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(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(md,{onButtonClick:Me,showPayPal:I,showStripe:he,showApplePay:S,showGooglePay:pe,theme:ae,buttonsTheme:ve,buttonsStyles:et,cardButtonContent:be,cardBackButtonContent:Dt,cardTitleContent:Xe})}),Ut]}):pr&&P&&zt?Yt(or,{children:[X(Vn.Provider,{value:En,children:Yt("div",{className:De,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[tn&&X(eo,{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(hs,{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: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:De,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(pd,{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(Xc(P).total*100):0,currency:P?.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:S,showGooglePay:pe,layout:se,theme:ae,buttonsTheme:ve,buttonsStyles:et,appearance:ot,cardButtonContent:be,cardBackButtonContent:Dt,cardTitleContent:Xe,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(H),isSubscription:P?.mode==="subscription",session:P,dataAttachmentPending:ln,dataAttachmentRequiresIdentity:qt,debug:Z})},W)}),Ut]})}function pd({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 md({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(()=>Qs(a),[a]),u=Ln(()=>{let S=M?.buttonsLayout??td(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(Vr,{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:`
|
|
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,m=(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=Sc(i);return Te(Br,{children:[Ve(G.address_line_1,i)&&Te(Br,{children:[c("div",{style:m(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:yn,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:m(),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,mn.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:mt,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:bc.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 ${bl}`,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`:Hc(i)})]})})()}),$e&&wl,y&&c(eo,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:y})]}),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=${yo}`,` shouldRenderStripePayPal=${mo}`,` 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?Gs(Ia,zt):null;if(ae==="buttons"){let i=Ce==="buttons"||Ce==="expanding"||Ce==="apm-expanding",m=Ce==="expanding"||Ce==="card"||Ce==="collapsing",N=Qe===void 0?{boxSizing:"border-box",height:ya,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:y,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?$c:{},..._e?{animation:_e,pointerEvents:"none"}:{}},children:[Ji("flopay-direct-paypal-gate-debug"),Xi("flopay-stripe-gate-debug"),yo&&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")]}),mo&&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:ya,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=Cl)},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})}),y&&Ce==="buttons"&&c(eo,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:y})]}),$e&&m&&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:y})},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:y,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:y})},zt)]})})]}):Te("form",{onSubmit:_a,className:T,noValidate:!0,style:{position:"relative"},children:[c(Za,{}),Se&&c(er,{status:Se,errorMessage:y,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"),yo&&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")]}),mo&&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||yl||fl)&&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 Zs(e,t){t.settled&&t.consumers===0&&va.get(e)===t&&va.delete(e)}function id(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:nl,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 sd(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 ld(){if(!lr())return null;try{let e=window.sessionStorage.getItem(hi);return e?JSON.parse(e):null}catch{return null}}function Qs(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 rl(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{rl(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ol(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 yi(e,t){if(gi(e,t),!!lr())try{ol(e,t)&&window.sessionStorage.removeItem(e+bi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function cd(){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 el(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 dd(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 ud(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=>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:ud(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function pd(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 yd(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=od(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??ed(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=nd(r),Ie=Ln(()=>tl(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,yt=n?"":E,[Tt,lt]=Ft(!0),[Rt,pn]=Ft(null),[an,yn]=Ft("full"),[Lt,wn]=Ft(!1),[Gt,mt]=Ft(ze),[Ge,ft]=Ft(null),[sn,et]=Ft(null),[Wn,dt]=Ft(!1),[nn,bt]=Ft(void 0),[Jt,kn]=Ft(""),[mn,_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 ye=Bt(T);ye.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:nl,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(()=>{mt(ze)},[ze]);let zn=nr((x,L,H)=>{_t(()=>{ye.current?.(Vt(x,L,H))})},[]),Xn=nr(async(x,L)=>{mt(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:y=>{F?F.log(y):q?.log(y)},error:y=>{F?F.error(y):q?.error(y)},terminal:y=>{F?F.terminal(y):q?.terminal(y)},performance:y=>{F?F.performance(y):q?.performance(y)},now:()=>F?.now()??q?.now()??0,elapsed:y=>F?.elapsed(y)??Math.max(0,(q?.now()??y)-y)},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 y=Is(L?.initialAutoProcessingError),d;if(y)te(),y.type==="paypal_redirect_required"&&w.current?.publishableKey&&Qs({sessionId:H,publishableKey:w.current.publishableKey,paypalPublishableKey:w.current.paypalPublishableKey}),d=await ca(y,{flopay:He.current,paypalFlopay:v.current,attempt3DS:L?.attempt3DS,billingApiUrl:K,sessionId:H,session:x,telemetry:!1}),y.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&&(yn("full"),el("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&&Qs({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(y){let d=Lo(y),f=d.checkoutMethod??Do;mt(d.message),et(d.message),dt(!1),L?.fallbackToFull&&(p.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),yn("full"),el("full")),Xt();let me=d.statusCode!==void 0?ad(d.statusCode,"unknown"):void 0,re=me==="4xx"?{requestCategory:"process_payment",statusClass:me}:{},je=me===void 0||me==="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=Js(y,$?"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=ld();H&&($e.current=!0,(async()=>{let Y,Se=0;mt(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 y=await no({billingApiUrl:K,sessionId:H.sessionId,session:rt,telemetry:!1,tokenizedData:{id:vt??O.id,type:"card",threeDSecureActionResultTokenId:O.id,isPaypal:!0}});if(y.type!=="success")throw Object.assign(new Ht("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});te=y.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");mt(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(),cd(),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,mt(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?Xs(x.idempotencyKey):void 0,p=rl(L,H),O=ol(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,y=!1;if(te)try{we=await Se.getUnifiedCheckoutSession(te,p?.nonce),p&&p.canonicalIdentity===void 0&&(yd(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))):(yi(L,H),O=null,$=q,te=null,we=null));let f=we?.data.session?.status,me=we?.data.session,re=me?.clientSecret||p?.nonce;if(te&&me?.buyerIdentified===!1&&re&&(rt=Wr(Se,te,re,x.account)),te&&we&&f==="complete"){if(Ha(te))return{sid:te,result:we};yi(L,H),te=null,we=null,vt=!0}}catch{Y.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),p?.canonicalIdentity===void 0?(yi(L,H),$=q):gi(L,H),te=null}if(!te){!q&&(vt||!$)&&($=Xs(),gt=$),$&&pi(L,H,$);let f=Y.now(),me=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,Zc,{configurable:!1,enumerable:!1,value:{onAttempt:J=>{me=Math.max(me,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:me,statusClass:"2xx"})},Je=J=>{let R=Js(J,"CHECKOUT_SESSION_CREATE_FAILED","unknown");Y.performance({stage:"session_create",durationMs:Y.now()-f,durationMode:"machine",requestCategory:"session_create",attempt:me,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(td(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:me,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}:{},...y?{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=pd(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,Zs(Se,$)};$.promise.then(gt,gt)}q.consumers+=1;let p=!1,O=()=>{p||(p=!0,q.consumers-=1,Zs(Se,q))};L?.(O);try{let $=await q.promise;hn.current=Se,x&&(kn(gn),bt(me=>ns(me,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 me=fn.current;Tn(!0),te.then(re=>{fn.current===me&&(D(re),re.data.session&&Re(re.data.session),Tn(!1),G(!1))},re=>{fn.current===me&&(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:y}=da(vt),{flopay:d,paypalFlopay:f}=await ua({publishableKey:rt,paypalPublishableKey:y,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(!dd(x)||mn)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,mn,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 yn(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&&(mt(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 id(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";yn($),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&&!sd(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,yt,t]);let on=nr(async()=>{if(!(Lt||!P)){wn(!0),mt(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]),yr=!!(n&&!ke&&se==="buttons"&&ee&&On==="full"),En=Ln(()=>({session:P,loading:Tt,error:Rt,checkoutMode:an,inlineSessionDraft:Ot,applyInlineSessionPatch:yr?xn:void 0,inlineSessionPatchProcessing:mn,claimPending:ln,claimRequiresIdentity:qt,claimBuyerIdentity:Ce}),[P,Tt,Rt,an,Ot,yr,xn,mn,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(fd,{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:mt,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(Qc(P).total*100):0,currency:P?.currency?.toLowerCase()??"usd",onComplete:g,onError:h,onDecline:T,error:Gt,onErrorChange:mt,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 fd({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(()=>tl(a),[a]),u=Ln(()=>{let S=M?.buttonsLayout??rd(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:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:X(
|
|
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 kd,jsx as so,jsxs as Id}from"react/jsx-runtime";var vd=44;function al(e){return new Promise(t=>setTimeout(t,e))}function Pd(e,t){return e instanceof lo?e:new lo(e instanceof Error?e.message:t,"api_error")}function Cd(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Sd(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 wd({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(()=>gd(I),[I]),ee=qo(()=>Sd({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 al(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 al(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 yt;try{yt=await Es({billingApiUrl:Me,sessionId:U,nonce:tn,nextActionRedirectUrl:C.autoProcessingError.nextActionRedirectUrl,signal:E.signal})}finally{K.current===E&&(K.current=null)}if(yt.status==="declined")throw br({type:yt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:yt.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),yt=We.id||U;await B(E,{emitDecline:!0,method:E.checkoutMethod??Do}),Cd(E,yt)&&yt&&de.current&&Pe({sessionId:yt,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(Pd(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(()=>bd(j),[j]),Re=qo(()=>{let C=P?.buttonsLayout??hd(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 Id(kd,{children:[so("button",{...xe,type:Dt,onClick:He,disabled:be||Q,"aria-busy":Q,style:{width:"100%",...tt===void 0?{boxSizing:"border-box",height:vd,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,wd as FloPayAutomaticPaymentButton,Il as FloPayCardSetup,kl as FloPayCardSetupError,vi as FloPayCheckout,ia as FloPayProvider,ii as SplitCardForm,La as VaultCardFields,Rp as dropThirdPartyOnlyError,Ll as useCheckout,gr as useFloPay,Ua as usePayPalFloPay};
|