@flopay/react 1.8.10 → 1.8.11
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 +7 -7
- package/dist/index.mjs +6 -6
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as St,b as Zn,c as Aa,d as Po,e as Ji,f as Xi,g as bl,h as vl}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as bp}from"@flopay/shared";import{PaymentAPI as hi}from"@flopay/js";import{FloPayError as ao,resolveBillingApiUrl as sd,resolveButtonsLayoutTheme as ld,resolveTheme as cd}from"@flopay/shared";import{useCallback as Pr,useEffect as no,useMemo as Lo,useRef as ro,useState as No}from"react";import{Fragment as Kr,jsx as _n,jsxs as Zi}from"react/jsx-runtime";function Pl(){return Zi(Kr,{children:[Zi("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:[_n("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),_n("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",_n("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:_n("path",{d:"M9 18l6-6-6-6"})})]})}function Cl(){return _n(Kr,{children:"Go back"})}function Sl(){return _n(Kr,{children:"Secure card checkout"})}function qr(e){return e!==void 0&&(e===""||e===null||e===!1)}function $r({content:e}){return _n(Kr,{children:e===void 0?_n(Pl,{}):e})}function jr({content:e}){return _n(Kr,{children:e===void 0?_n(Cl,{}):e})}function Co({content:e}){return _n(Kr,{children:e===void 0?_n(Sl,{}):e})}import{FloPayError as Fa,isMoneySettledOutcome as wl,isSetupIntentClientSecret as Cd,isValidEmail as kl}from"@flopay/shared";function Vr(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()};if(!kl(l.email))return Promise.reject(new Fa("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let s={};for(let[S,f]of Object.entries(l)){if(typeof f!="string")continue;let g=f.trim();g&&(s[S]=g)}return o=e.claimCheckoutSession(t,n,{accountData:s}),o.catch(()=>{}),o}}function Qi(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 Da(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 es(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 Rr(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 La(e,t){return t?{...e,...t}:e}function jt(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Il=[{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 Il)if(n.test(t))return r;return e}function Er(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Hr(e){return e?.status==="authorized"||e?.status==="complete"}function ts(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Xo(e){let t=ts(e);return new Fa(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Zo(e){let t=ts(e);return new Fa(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 Qo(e,t){return e==="processing"||wl(e,t)}function ns(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function rs(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function So(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as ya,SESSION_CREATE_TELEMETRY as jc}from"@flopay/js";import{buildCheckoutDisplayData as Kc,classifyTelemetryFailure as Ks,FloPayError as Vt,foldIntoProducts as Vc,isDetachedSessionEligible as Hc,resolveBillingApiUrl as Yc,resolveButtonsLayoutTheme as Wc,resolveIdempotencyKey as Vs,resolveSessionCurrency as Gc,resolveTheme as Gs,SDK_VERSION as Js,telemetryStatusClass as Jc}from"@flopay/shared";import oi,{useCallback as er,useEffect as tr,useMemo as xn,useRef as Tt,useState as xt}from"react";import{createContext as os}from"react";var Tn=os({flopay:null,paypalFlopay:null,billingApiUrl:""}),Kn=os({session:null,loading:!1,error:null});import{PaymentAPI as za}from"@flopay/js";import{classifyTelemetryFailure as $l,FloPayError as ds,generateIdempotencyKey as jl,isValidEmail as Ro,normalizeGatewayEnvironment as Kl,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Ua,SDK_VERSION as Vl}from"@flopay/shared";import{loadScript as Hl}from"@paypal/paypal-js";import{useCallback as Eo,useEffect as vt,useMemo as _o,useRef as Je,useState as Tr}from"react";import{isValidEmail as Rl}from"@flopay/shared";import{useCallback as as,useEffect as El,useRef as is,useState as ls}from"react";import{jsx as ss,jsxs as wo}from"react/jsx-runtime";function yn(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),a=n?.trim();return{...r,...o?{firstName:o}:{},...a?{lastName:a}:{}}}function Yr(){let[e,t]=ls(null),n=is(null),r=is(0),o=as((l,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:s}),new Promise(S=>{n.current=S})),[]),a=as(l=>{let s=n.current;n.current=null,t(null),s?.(l)},[]);return El(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Wr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,s]=ls(e.email?.trim()??""),S=Rl(l.trim());return wo("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:[wo("div",{style:{fontWeight:700},children:["Continue with ",t]}),wo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",ss("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:f=>s(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),wo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&ss("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),wo("button",{type:"button",disabled:!S||o,onClick:()=>{n(yn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function _l(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 or(e){if(typeof e!="object"||e===null)return;let t=e;return _r(t.code)??_r(t.type)??_r(t.name)}function Gr(e){if(!(typeof e!="object"||e===null))return _r(e.decline_code)}function ko(e){return typeof e!="object"||e===null?!1:_r(e.type)?.toLowerCase()==="card_error"||Gr(e)!==void 0}function fr(e){let t=_l(e)?.toLowerCase()??"",r=`${or(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Tl}from"@flopay/shared";import{useContext as ea}from"react";function gr(){return ea(Tn).flopay}function Na(){return ea(Tn).paypalFlopay??null}function xl(){return ea(Kn)}function cs(){return ea(Tn).billingApiUrl||Tl()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Al}from"@flopay/shared";import{useCallback as Fl,useRef as ta}from"react";import{useEffect as Bl,useLayoutEffect as Ml}from"react";var Io=typeof window>"u"?Bl:Ml;var Dl={"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 Ll(e){return e==="stripe"||e==="paypal"?e:void 0}function Nl(e){let t=Ll(e.provider),n={schemaVersion:Al,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Dl[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 Oa=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Jr(e,t){let n=ta(e);n.current=e;let r=ta(new Set),o=ta(t),a=ta(t);return Io(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Fl(l=>{if(a.current!==t)return;let s=Nl(l);if(s){if(Oa.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}St(()=>n.current?.(s))}},[t])}var Ol=Symbol.for("@flopay/js.telemetry.bridge.v1"),zl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ul(){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 ql(e){let t=Ul(),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 na(e){let t=globalThis[zl];return ql(t?.(e)??{})}function Kt(e){if(e)return e[Ol]}import{jsx as xr,jsxs as qa}from"react/jsx-runtime";var ra=45,Yl=1e3,Wl=11e3,Gl=["https://www.paypal.com","https://www.sandbox.paypal.com"],us="We couldn't open PayPal. Try again or choose another payment method.",Jl={width:"100%",minHeight:ra,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ps(e){return e.includes("No ack for postMessage init()")&&Gl.some(t=>e.includes(t))&&e.includes("10000ms")}function Xl(e){return e?`${us} Allow pop-ups for this site, then try again.`:us}function Zl(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 ms({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:s,currency:S,isSubscription:f,providerObjectType:g,onTokenizedBody:b,onComplete:T,onErrorChange:B,onDecline:u,onTechnicalFailure:w,isProcessing:be=!1,onLoadStateChange:j,onInitializationStateChange:P,allowAutomaticRetry:me=!0,onButtonClick:Q,runBeforeButtonClick:le,session:ae,existingOrderId:ve,telemetry:Ze,telemetryContext:fe,onInstrument:Bt,debug:Xe=!1}){let xe=gr(),Be=Jr(Bt,e),ee=_o(()=>{if(xe)return null;let C=na({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Vl,enabled:Ze!==!1});return C.setCheckoutContext(fe??{}),C.beginCheckout(fe??{}),C},[n,xe,Ze,fe?.checkoutMode,fe?.layout]),te=_o(()=>Kt(xe),[xe]);vt(()=>()=>{ee&&ee.flush().catch(()=>{}).finally(()=>ee.destroy())},[ee]);let M=_o(()=>({error:C=>{te?te.error(C):ee?.error(C),Be({class:"technical_error",errorCode:C.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":C.errorCode,requestCategory:C.requestCategory,provider:C.provider})},log:C=>{te?te.log(C):ee?.log(C),Be({class:"lifecycle",name:C.name,provider:C.provider})},performance:C=>{te?te.performance(C):ee?.performance(C)},terminal:C=>{te?te.terminal(C):ee?.terminal(C)},startTiming:()=>te?.now()??ee?.now()??0,elapsed:C=>te?.elapsed(C)??Math.max(0,(ee?.now()??C)-C)}),[Be,te,ee]),Ae=Je(null),Fe=Je(0),De=Je(null),Ue=Je(!1),[we,_]=Tr(!1),[ie,Le]=Tr(!1),[se,K]=Tr(0),Ee=Je(0),[tt,st]=Tr(!1),Me=Je(!1),V=Je(!1),[z,L]=Tr(!1),[ke,He]=Tr(!1),{request:I,collect:Y,finish:R}=Yr(),v=Je({sessionId:e,required:!Ro(r?.trim()||ae?.customer?.email?.trim())});v.current.sessionId!==e&&(v.current={sessionId:e,required:!Ro(r?.trim()||ae?.customer?.email?.trim())});let rt=v.current.required,Ct=_o(()=>n.replace(/\/+$/,""),[n]),dt=ae?.gateways?.paypal?.providerObjectType??g,Ie=dt??(f?"subscription":"order"),ut=dt==="order"||dt==="setup_token",Et=_o(()=>JSON.stringify([Ct,l,S,s??"",Ie,ut,e,ve??""]),[Ct,l,S,s,ve,Ie,ut,e]),h=Je(Et),H=h.current!==Et,Ye=Je(Xe),qe=Je(null),[zt,Lt]=Tr([]),U=Eo(C=>{Ye.current&&Lt(nt=>[...nt,`${new Date().toISOString().slice(11,23)} ${C}`])},[]);vt(()=>{Ye.current=Xe,Xe&&U("debug:enabled"),qe.current?.setEnabled(Xe)},[U,Xe]);let lt=Je(b),tn=Je(T),gt=Je(B),Ut=Je(u),Bn=Je(w),Mn=Je(Q),An=Je(j),Zt=Je(P),Hn=Je(a),fn=Je(le),qt=Je(ae),rr=Je(r),wt=Je(o),Fn=Je(t),ot=Je(null),lr=Je(0),kt=Je(null),Pn=Je(null),It=Je(new Map),Yt=Je(new Map),gn=Je(!1);vt(()=>(gn.current=!0,()=>{gn.current=!1}),[]),vt(()=>{lt.current=b},[b]),vt(()=>{Hn.current=a},[a]),vt(()=>{tn.current=T},[T]),vt(()=>{gt.current=B},[B]),vt(()=>{Ut.current=u},[u]),vt(()=>{Bn.current=w},[w]),vt(()=>{Mn.current=Q},[Q]),vt(()=>{An.current=j},[j]),vt(()=>{Zt.current=P},[P]),vt(()=>{fn.current=le},[le]),vt(()=>{qt.current=ae},[ae]),vt(()=>{rr.current=r},[r]),vt(()=>{wt.current=o},[o]),vt(()=>{Fn.current=t},[t]),vt(()=>{Ee.current=se},[se]),vt(()=>{tt&&De.current?.focus()},[tt,se]);let sn=Eo(()=>{window.setTimeout(()=>{De.current?.focus()},0)},[]),Cn=Eo(()=>{_(!1),K(C=>C+1)},[]),nn=Eo(()=>{st(!1),(Ae.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ae.current)?.focus?.()},[]);vt(()=>{!we||!Ue.current||(Ue.current=!1,nn())},[nn,we,se]);let Sn=Eo((C,nt)=>{let $t=Bn.current;if($t){$t("paypal",C,nt);return}gt.current?.(Xl(nt?.popupBlocked??fr(C)))},[]),Nt=()=>{kt.current?.timer&&(clearTimeout(kt.current.timer),kt.current.timer=null)},J=()=>{Nt();let C=lr.current+1;return lr.current=C,Pn.current=null,kt.current={generation:C,timer:null,yieldedControl:!1},st(!1),C},ln=C=>C!==void 0&&kt.current?.generation!==C?!1:(Nt(),kt.current=null,Pn.current=null,!0),Dn=C=>{let nt=C?.generation??kt.current?.generation??lr.current;(!C?.generation||kt.current?.generation===nt)&&(Nt(),kt.current=null),Pn.current=nt,C?.showRetry&&st(!0),C?.remount&&Cn(),C?.focus!==!1&&sn()},Yn=C=>kt.current?.generation===C&&Pn.current!==C,Cr=C=>{typeof document<"u"&&document.visibilityState!=="visible"||(Nt(),C.timer=setTimeout(()=>{kt.current?.generation===C.generation&&(kt.current=null,Pn.current=C.generation,Sn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),st(!0),Cn(),sn())},600))},Sr=()=>{let C=kt.current;C?.yieldedControl&&Cr(C)},cr=()=>{let C=kt.current;C&&(C.yieldedControl=!0,Nt())},Mt=C=>{let nt=ot.current;return nt&&Yt.current.set(C,nt),C};vt(()=>{let C=()=>{document.visibilityState==="visible"?Sr():cr()};return document.addEventListener("visibilitychange",C),window.addEventListener("focus",Sr),window.addEventListener("blur",cr),()=>{document.removeEventListener("visibilitychange",C),window.removeEventListener("focus",Sr),window.removeEventListener("blur",cr),Nt()}},[]),vt(()=>{h.current!==Et&&(h.current=Et,Me.current=!1,V.current=!1,_(!1),Le(!1),L(!1),Zt.current?.("loading"))},[Et]),vt(()=>{St(()=>An.current?.(we&&!z))},[we,z]);let $e=Kl(s);vt(()=>{let C=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",nt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(U(`mount clientId=${C} env=${s??"(unset)"}\u2192${$e??"live"} ccy=${S} sub=${f}`),U(`ua=${nt.slice(0,80)}${nt.length>80?"\u2026":""}`),!l){U("FAIL: clientId empty \u2014 gateway misconfigured"),L(!0),M.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(!Ae.current){U("FAIL: containerRef not attached");return}Fe.current=M.startTiming(),M.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let $t=!1,hn=!1,ue=()=>$t||hn,rn,wr=!1,Lr=()=>{rn=jl(),rn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),wr=!0},cn=null,ur=!1,Wn=null,Ln=!1,At=()=>{!Wn||Ln||(Ln=!0,Wn.close().catch(()=>{}))},Nn=null,Gn=()=>{Nn!==null&&(M.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),M.performance({stage:"overlay_return",durationMs:M.elapsed(Nn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Nn=null)},dn=!1,Qt=Ae.current,On=null,zn=null,at=[],un=null,pn=!1,Un=!1,wn=null,Pe=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let d=m.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},en=m=>{if(!m)return"(empty)";try{let d=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),y=d.pathname.toLowerCase();return y.includes("checkcaptcha")||y.includes("captcha")?`CAPTCHA(${d.host}${y})`:y.includes("risk")||y.includes("challenge")?`RISK(${d.host}${y})`:y.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${y}`.slice(0,100)}catch{return m.slice(0,80)}},Ft=m=>{let d=m.getAttribute("src"),y=m.getAttribute("srcdoc"),pe=m.getAttribute("name"),re=m.getAttribute("sandbox"),je=[];return d&&je.push(`src=${en(d)}`),y&&je.push(`srcdoc[${y.length}ch]`),!d&&!y&&je.push("src=(empty) srcdoc=(empty)"),pe&&je.push(`name=${pe.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 y=d.body?.children.length??0,pe=d.body?.innerHTML.length??0,re=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${y}children,${pe}ch] head[${re}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},qn=[],mr=m=>{if(ue())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"))&&(U(`window:error ${d.slice(0,140)}`),qn.push(d))},bn=m=>{if(ue())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"))&&(U(`window:rejection ${d.slice(0,140)}`),qn.push(d))},kn={value:0},Dt=()=>{for(On?.disconnect(),On=null,zn?.disconnect(),zn=null;at.length;)clearTimeout(at.pop());Un=!1,pn&&typeof window<"u"&&(window.removeEventListener("error",mr),window.removeEventListener("unhandledrejection",bn)),pn=!1},x=()=>{if(!(pn||ue()||dn)){if(pn=!0,qn.length=0,kn.value=0,typeof window<"u"&&(window.addEventListener("error",mr),window.addEventListener("unhandledrejection",bn)),typeof PerformanceObserver<"u")try{zn=new PerformanceObserver(m=>{if(!ue())for(let d of m.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;kn.value+=1;let y=Math.round(d.duration);U(`net ${y}ms ${d.name.slice(0,90)}`)}}),zn.observe({type:"resource",buffered:!0})}catch{}wn?.()}},F=()=>{un&&(clearTimeout(un),un=null)},W=()=>{Dt(),F()},G={setEnabled:m=>{m?x():Dt()}};qe.current=G,Ye.current&&x();let Ce=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")},A=m=>{if(ue()||Ce(m))return;let d=yr(m)??m;St(()=>gt.current?.(d))},q=m=>{$t||(L(!0),m.includes("paypal_ineligible")||M.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($t)return;let y=Me.current||!me;if(ur)return;ur=!0,hn=!0,W(),At();let pe=d||ps(m);if(pe&&me&&!Me.current){Me.current=!0,_(!1),He(!1),Le(!0),Zt.current?.("retrying"),cn=setTimeout(()=>{$t||K(re=>re+1)},Yl);return}if(pe||y){if(_(!1),He(!1),Le(!1),L(!0),Zt.current?.("exhausted"),!V.current){V.current=!0;let re=ps(m)?"paypal_init_timeout":d?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",re)}return}q(m)};L(!1);let N=async(m,d=ot.current)=>{if(ue())return;let y=d?.sessionId??e;if(lt.current){await lt.current(m,{sessionId:y,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let pe=M.startTiming();M.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let re=()=>{M.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),M.performance({stage:"processing",durationMs:M.elapsed(pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let je=qt.current,We=d?.accountPatch?.email??rr.current,X=d?.accountPatch?.userId??je?.customer?.id??je?.accountData?.userId??"",E=d?.accountPatch?.firstName??je?.customer?.firstName??je?.accountData?.firstName,oe=d?.accountPatch?.lastName??je?.customer?.lastName??je?.accountData?.lastName,Ne=await new za(Ct,{telemetry:!1}).processPayment(X,{sessionId:y,nonce:d?.nonce??Fn.current,tokenizedData:m,accountData:{userId:X,email:We??je?.customer?.email??"",...E?{firstName:E}:{},...oe?{lastName:oe}:{},country:d?.accountPatch?.country??je?.customer?.country??je?.accountData?.country??void 0,zip:d?.accountPatch?.zip??je?.customer?.zip??je?.accountData?.zip??void 0}});if(Ne.ok){if(hn||$t&&gn.current)return;re(),M.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),St(()=>tn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ue())return;let mt=await Ne.json().catch(()=>null),Oe=mt?.message??"PayPal payment failed.",Ot=yr(Oe)??Oe;re(),Ne.status===400&&(typeof mt?.declineCode=="string"||!Array.isArray(mt?.fields))?M.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Ne.status===400||Ne.status===422?M.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):M.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Ne.status>=500?"5xx":Ne.status>=400?"4xx":Ne.status>=300?"3xx":"unknown",failureCategory:Ne.status>=500?"server_error":void 0}),A(Ot),St(()=>Ut.current?.(jt("paypal",Ot,{code:mt?.code,declineCode:mt?.declineCode})));return}catch(je){if(ue())return;re(),M.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.",X=yr(We)??We;A(X),St(()=>Ut.current?.(jt("paypal",X)));return}},$=()=>new ds("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ct=m=>ue()?Promise.reject($()):Promise.resolve(m),pt=async m=>{if(ue())throw $();wr||Lr();let d=ot.current,y=d?.sessionId??e,pe=d?.nonce??Fn.current;M.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let re;try{re=await new za(Ct,{telemetry:!1}).createSessionIntent(y,pe??"",ut?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ua,paymentMethodId:null,intentKind:Ie==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:rn})}catch(je){throw M.error({...$l(je,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),je}if(ue())throw $();if(re.provider!=="paypal"||re.providerObjectType!==Ie)throw new Error(m);return M.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),re.providerObjectId},ne=(m,d)=>{let y=d?.nonce??Fn.current;if(!y)return;let pe=d?.sessionId??e,re=Gr(m)??or(m)??"provider_declined";new za(Ct,{telemetry:!1}).reportSessionIntentDecline(pe,y,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:re}).catch(()=>{})},Se=se;U("loadScript:scheduled (deferred 1 tick)");let Wt=null,Qe=setTimeout(()=>{if($t){U("loadScript:skipped (cancelled before defer ran)");return}U("loadScript:start");let m=$e==="live"?"production":$e;Wt=Hl({clientId:l,currency:S,...Ie==="subscription"?{intent:"subscription",vault:!0}:Ie==="order"?{intent:"capture"}:{},...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Wt.then(d=>{if(U(`loadScript:resolved inactive=${ue()} ns=${!!d} buttons=${!!d?.Buttons}`),ue())return;if(!d?.Buttons){U("FAIL: namespace missing Buttons factory"),p("PayPal SDK did not expose the Buttons factory.");return}M.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),M.performance({stage:"provider_ready",durationMs:M.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),M.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let y=async(X,E)=>{if(ue()||Ee.current!==Se)return;let oe=X.vaultSetupToken??X.subscriptionID??X.orderID??"",Ke=oe?Yt.current.get(oe):It.current.get(Se);if(!(!Ke||!Yn(Ke.generation))&&ln(Ke.generation)){Yt.current.delete(oe),It.current.delete(Ke.surfaceKey),Gn();try{if(He(!0),St(()=>gt.current?.(null)),!oe)throw new ds("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ne=qt.current,mt=Rr(wt.current??[Ne?.customer?.firstName,Ne?.customer?.lastName].filter(Boolean).join(" ")),Oe=yn({email:Ke.accountPatch?.email?.trim()||rr.current?.trim()||Ne?.customer?.email?.trim(),firstName:Ke.accountPatch?.firstName?.trim()||mt.firstName,lastName:Ke.accountPatch?.lastName?.trim()||mt.lastName});if(!Ro(Oe.email)||!(Oe.firstName||Oe.lastName))try{let Ot=Zl(await E?.order?.get?.());Oe=yn({email:Ot.email||Oe.email,firstName:Ot.firstName||Oe.firstName,lastName:Ot.lastName||Oe.lastName})}catch{}if((Hn.current||rt)&&!Ro(Oe.email)){let Ot=await Y("PayPal",Oe);if(!Ot)return;Oe=Ot}Ro(Oe.email)&&(Ke.accountPatch=yn({...Ke.accountPatch,...Oe}),await Hn.current?.(Oe)),await N(Ie==="setup_token"?{id:oe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ua}:ut?{id:oe,isPaypal:!0,gateway:"paypal",paymentMethodType:Ua}:{id:oe,isPaypal:!0},Ke)}catch(Ne){A(Ne instanceof Error?Ne.message:"PayPal capture failed.")}finally{ue()||He(!1)}}},pe=d.Buttons({style:{layout:"horizontal",height:ra,tagline:!1},onClick:async(X,E)=>{if(ue()){await E.reject();return}Lr();let oe=fn.current,Ke={};if(oe)try{let Oe=await oe("paypal");if(ue()){await E.reject();return}if(!Oe.proceed){ot.current=null,It.current.delete(Se),await E.reject();return}Ke={sessionId:Oe.sessionId,accountPatch:Oe.accountPatch,nonce:Oe.nonce}}catch(Oe){U(`onClick:runBeforeButtonClick rejected msg=${(Oe instanceof Error?Oe.message:String(Oe)).slice(0,120)}`),ot.current=null,It.current.delete(Se),await E.reject();return}St(()=>Mn.current?.("paypal"));let mt={generation:J(),surfaceKey:Se,...Ke};ot.current=mt,It.current.set(Se,mt),await E.resolve(),M.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),M.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),M.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Nn=M.startTiming()},createOrder:Ie==="order"?ve?()=>ct(ve).then(Mt):()=>pt("Failed to create PayPal order.").then(Mt):void 0,createSubscription:Ie==="subscription"?ve?()=>ct(ve).then(Mt):()=>pt("Failed to create PayPal subscription.").then(Mt):void 0,createVaultSetupToken:Ie==="setup_token"?()=>pt("Failed to create PayPal setup token.").then(Mt):void 0,onApprove:y,onCancel:()=>{if(ue())return;let X=It.current.get(Se)??ot.current;X&&It.current.delete(X.surfaceKey),ot.current=null,Gn(),M.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ue.current=!0,Dn({generation:X?.generation,remount:!0,focus:!1})},onError:X=>{if(ue()||Ee.current!==Se)return;let E=X instanceof Error?X.message:"PayPal failed to render.";if(U(`onError rendered=${dn} msg=${E.slice(0,120)}`),dn){let oe=It.current.get(Se)??ot.current;if(oe&&!Yn(oe.generation)||!oe&&Pn.current===lr.current)return;if(Ce(E)){ln(oe?.generation);return}if(Gn(),ko(X)){M.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ne(X,oe),St(()=>Ut.current?.(jt("paypal",E))),oe&&It.current.delete(oe.surfaceKey),ot.current=null,ln(oe?.generation);return}let Ke=E.toLowerCase();M.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&&It.current.delete(oe.surfaceKey),ot.current=null,Dn({generation:oe?.generation,remount:!0,showRetry:!0,focus:!0}),Sn(X,{code:"paypal_runtime_failed"});return}p(E)}}),re=pe.isEligible();if(U(`isEligible=${re}`),M.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}Wn=pe,wn=()=>{if(!pn||Un||ue()||dn)return;Un=!0,U(`container:dims ${Pe(Qt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),typeof MutationObserver<"u"&&(On=new MutationObserver(E=>{if(!ue()){for(let oe of E)if(oe.type==="childList")oe.addedNodes.forEach(Ke=>{if(!(Ke instanceof Element))return;let Ne=Ke.tagName.toLowerCase(),mt=(Ke.getAttribute("title")??"").slice(0,40),Oe=Ne==="iframe"?` ${Ft(Ke)}`:"";U(`child+ ${Ne}${mt?` title="${mt}"`:""}${Oe} dims=${Pe(Ke)}`)});else if(oe.type==="attributes"&&oe.target instanceof Element){let Ke=oe.target;if(Ke.tagName.toLowerCase()!=="iframe")continue;let Ne=oe.attributeName;(Ne==="src"||Ne==="srcdoc")&&U(`attr~ iframe ${Ne}=${Ne==="srcdoc"?`[${(Ke.getAttribute("srcdoc")??"").length}ch]`:en(Ke.getAttribute("src"))} dims=${Pe(Ke)}`)}}}),On.observe(Qt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let X=E=>{if(ue()||dn)return;let oe=Qt.querySelectorAll("iframe"),Ke=typeof document<"u"&&"hasStorageAccess"in document;U(`watchdog:${E} container=${Pe(Qt)} children=${Qt.childElementCount} iframes=${oe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${Ke} paypalNetRequests=${kn.value}`),oe.forEach((Ne,mt)=>{let Oe=(Ne.getAttribute("title")??"").slice(0,40);U(` iframe[${mt}] ${Pe(Ne)}${Oe?` title="${Oe}"`:""} ${Ft(Ne)}`);let Ot=pr(Ne);Ot&&U(` ${Ot}`)}),qn.length===0&&U(" (no PayPal/zoid window errors captured)")};at.push(setTimeout(()=>X("3s"),3e3)),at.push(setTimeout(()=>X("8s"),8e3)),at.push(setTimeout(()=>X("15s"),15e3))},wn(),U("render:start");let We=M.startTiming();un=setTimeout(()=>{ue()||dn||(U("watchdog:11s retryable render timeout"),p("PayPal Buttons render did not settle within 11000ms.",!0))},Wl),pe.render(Qt).then(()=>{if(U(`render:resolved inactive=${ue()}`),W(),ue()){At();return}dn=!0,_(!0),Le(!1),Zt.current?.("ready"),M.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),M.performance({stage:"checkout_render",durationMs:M.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(X=>{let E=X instanceof Error?X.message:"PayPal failed to render.";U(`render:rejected msg=${E.slice(0,120)}`),W(),p(E)})}).catch(d=>{let y=d instanceof Error?d.message:"PayPal SDK failed to load.";U(`loadScript:rejected msg=${y.slice(0,120)}`),p(y)})},0);return()=>{$t=!0,clearTimeout(Qe),cn&&clearTimeout(cn),W(),qe.current===G&&(qe.current=null),At()}},[me,Ct,l,S,s,Ie,ut,e,ve,se,M,Y,rt,U]);let dr=Xe?qa("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:z?"#fef2f2":"#f3f4f6",border:`1px solid ${z?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${we} failed=${z})`,zt.length===0?`
|
|
1
|
+
import{a as St,b as Zn,c as Aa,d as Po,e as Ji,f as Xi,g as bl,h as vl}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as bp}from"@flopay/shared";import{PaymentAPI as hi}from"@flopay/js";import{FloPayError as ao,resolveBillingApiUrl as sd,resolveButtonsLayoutTheme as ld,resolveTheme as cd}from"@flopay/shared";import{useCallback as Pr,useEffect as no,useMemo as Lo,useRef as ro,useState as No}from"react";import{Fragment as Kr,jsx as _n,jsxs as Zi}from"react/jsx-runtime";function Pl(){return Zi(Kr,{children:[Zi("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:[_n("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),_n("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",_n("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:_n("path",{d:"M9 18l6-6-6-6"})})]})}function Cl(){return _n(Kr,{children:"Go back"})}function Sl(){return _n(Kr,{children:"Secure card checkout"})}function qr(e){return e!==void 0&&(e===""||e===null||e===!1)}function $r({content:e}){return _n(Kr,{children:e===void 0?_n(Pl,{}):e})}function jr({content:e}){return _n(Kr,{children:e===void 0?_n(Cl,{}):e})}function Co({content:e}){return _n(Kr,{children:e===void 0?_n(Sl,{}):e})}import{FloPayError as Fa,isMoneySettledOutcome as wl,isSetupIntentClientSecret as Cd,isValidEmail as kl}from"@flopay/shared";function Vr(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()};if(!kl(l.email))return Promise.reject(new Fa("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let s={};for(let[w,f]of Object.entries(l)){if(typeof f!="string")continue;let g=f.trim();g&&(s[w]=g)}return o=e.claimCheckoutSession(t,n,{accountData:s}),o.catch(()=>{}),o}}function Qi(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 Da(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 es(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 Rr(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 La(e,t){return t?{...e,...t}:e}function jt(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Il=[{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 Il)if(n.test(t))return r;return e}function Er(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Hr(e){return e?.status==="authorized"||e?.status==="complete"}function ts(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Xo(e){let t=ts(e);return new Fa(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Zo(e){let t=ts(e);return new Fa(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 Qo(e,t){return e==="processing"||wl(e,t)}function ns(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function rs(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function So(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as ya,SESSION_CREATE_TELEMETRY as jc}from"@flopay/js";import{buildCheckoutDisplayData as Kc,classifyTelemetryFailure as Ks,FloPayError as Vt,foldIntoProducts as Vc,isDetachedSessionEligible as Hc,resolveBillingApiUrl as Yc,resolveButtonsLayoutTheme as Wc,resolveIdempotencyKey as Vs,resolveSessionCurrency as Gc,resolveTheme as Gs,SDK_VERSION as Js,telemetryStatusClass as Jc}from"@flopay/shared";import oi,{useCallback as er,useEffect as tr,useMemo as xn,useRef as Tt,useState as xt}from"react";import{createContext as os}from"react";var Tn=os({flopay:null,paypalFlopay:null,billingApiUrl:""}),Kn=os({session:null,loading:!1,error:null});import{PaymentAPI as za}from"@flopay/js";import{classifyTelemetryFailure as $l,FloPayError as ds,generateIdempotencyKey as jl,isValidEmail as Ro,normalizeGatewayEnvironment as Kl,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Ua,SDK_VERSION as Vl}from"@flopay/shared";import{loadScript as Hl}from"@paypal/paypal-js";import{useCallback as Eo,useEffect as vt,useMemo as _o,useRef as Je,useState as Tr}from"react";import{isValidEmail as Rl}from"@flopay/shared";import{useCallback as as,useEffect as El,useRef as is,useState as ls}from"react";import{jsx as ss,jsxs as wo}from"react/jsx-runtime";function yn(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),a=n?.trim();return{...r,...o?{firstName:o}:{},...a?{lastName:a}:{}}}function Yr(){let[e,t]=ls(null),n=is(null),r=is(0),o=as((l,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:s}),new Promise(w=>{n.current=w})),[]),a=as(l=>{let s=n.current;n.current=null,t(null),s?.(l)},[]);return El(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Wr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,s]=ls(e.email?.trim()??""),w=Rl(l.trim());return wo("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:[wo("div",{style:{fontWeight:700},children:["Continue with ",t]}),wo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",ss("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:f=>s(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),wo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&ss("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),wo("button",{type:"button",disabled:!w||o,onClick:()=>{n(yn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function _l(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 or(e){if(typeof e!="object"||e===null)return;let t=e;return _r(t.code)??_r(t.type)??_r(t.name)}function Gr(e){if(!(typeof e!="object"||e===null))return _r(e.decline_code)}function ko(e){return typeof e!="object"||e===null?!1:_r(e.type)?.toLowerCase()==="card_error"||Gr(e)!==void 0}function fr(e){let t=_l(e)?.toLowerCase()??"",r=`${or(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Tl}from"@flopay/shared";import{useContext as ea}from"react";function gr(){return ea(Tn).flopay}function Na(){return ea(Tn).paypalFlopay??null}function xl(){return ea(Kn)}function cs(){return ea(Tn).billingApiUrl||Tl()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Al}from"@flopay/shared";import{useCallback as Fl,useRef as ta}from"react";import{useEffect as Ml,useLayoutEffect as Bl}from"react";var Io=typeof window>"u"?Ml:Bl;var Dl={"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 Ll(e){return e==="stripe"||e==="paypal"?e:void 0}function Nl(e){let t=Ll(e.provider),n={schemaVersion:Al,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Dl[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 Oa=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Jr(e,t){let n=ta(e);n.current=e;let r=ta(new Set),o=ta(t),a=ta(t);return Io(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Fl(l=>{if(a.current!==t)return;let s=Nl(l);if(s){if(Oa.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}St(()=>n.current?.(s))}},[t])}var Ol=Symbol.for("@flopay/js.telemetry.bridge.v1"),zl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ul(){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 ql(e){let t=Ul(),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 na(e){let t=globalThis[zl];return ql(t?.(e)??{})}function Kt(e){if(e)return e[Ol]}import{jsx as xr,jsxs as qa}from"react/jsx-runtime";var ra=45,Yl=1e3,Wl=11e3,Gl=["https://www.paypal.com","https://www.sandbox.paypal.com"],us="We couldn't open PayPal. Try again or choose another payment method.",Jl={width:"100%",minHeight:ra,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ps(e){return e.includes("No ack for postMessage init()")&&Gl.some(t=>e.includes(t))&&e.includes("10000ms")}function Xl(e){return e?`${us} Allow pop-ups for this site, then try again.`:us}function Zl(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 ms({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:s,currency:w,isSubscription:f,providerObjectType:g,onTokenizedBody:b,onComplete:T,onErrorChange:M,onDecline:u,onTechnicalFailure:k,isProcessing:be=!1,onLoadStateChange:j,onInitializationStateChange:P,allowAutomaticRetry:me=!0,onButtonClick:Q,runBeforeButtonClick:le,session:ae,existingOrderId:ve,telemetry:Ze,telemetryContext:fe,onInstrument:Mt,debug:Xe=!1}){let xe=gr(),Me=Jr(Mt,e),ee=_o(()=>{if(xe)return null;let C=na({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Vl,enabled:Ze!==!1});return C.setCheckoutContext(fe??{}),C.beginCheckout(fe??{}),C},[n,xe,Ze,fe?.checkoutMode,fe?.layout]),te=_o(()=>Kt(xe),[xe]);vt(()=>()=>{ee&&ee.flush().catch(()=>{}).finally(()=>ee.destroy())},[ee]);let B=_o(()=>({error:C=>{te?te.error(C):ee?.error(C),Me({class:"technical_error",errorCode:C.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":C.errorCode,requestCategory:C.requestCategory,provider:C.provider})},log:C=>{te?te.log(C):ee?.log(C),Me({class:"lifecycle",name:C.name,provider:C.provider})},performance:C=>{te?te.performance(C):ee?.performance(C)},terminal:C=>{te?te.terminal(C):ee?.terminal(C)},startTiming:()=>te?.now()??ee?.now()??0,elapsed:C=>te?.elapsed(C)??Math.max(0,(ee?.now()??C)-C)}),[Me,te,ee]),Ae=Je(null),Fe=Je(0),De=Je(null),Ue=Je(!1),[we,_]=Tr(!1),[ie,Le]=Tr(!1),[se,K]=Tr(0),Ee=Je(0),[tt,st]=Tr(!1),Be=Je(!1),V=Je(!1),[z,L]=Tr(!1),[ke,He]=Tr(!1),{request:I,collect:Y,finish:R}=Yr(),v=Je({sessionId:e,required:!Ro(r?.trim()||ae?.customer?.email?.trim())});v.current.sessionId!==e&&(v.current={sessionId:e,required:!Ro(r?.trim()||ae?.customer?.email?.trim())});let rt=v.current.required,Ct=_o(()=>n.replace(/\/+$/,""),[n]),dt=ae?.gateways?.paypal?.providerObjectType??g,Ie=dt??(f?"subscription":"order"),ut=dt==="order"||dt==="setup_token",Et=_o(()=>JSON.stringify([Ct,l,w,s??"",Ie,ut,e,ve??""]),[Ct,l,w,s,ve,Ie,ut,e]),h=Je(Et),H=h.current!==Et,Ye=Je(Xe),qe=Je(null),[zt,Lt]=Tr([]),U=Eo(C=>{Ye.current&&Lt(nt=>[...nt,`${new Date().toISOString().slice(11,23)} ${C}`])},[]);vt(()=>{Ye.current=Xe,Xe&&U("debug:enabled"),qe.current?.setEnabled(Xe)},[U,Xe]);let lt=Je(b),tn=Je(T),gt=Je(M),Ut=Je(u),Mn=Je(k),Bn=Je(Q),An=Je(j),Zt=Je(P),Hn=Je(a),fn=Je(le),qt=Je(ae),rr=Je(r),wt=Je(o),Fn=Je(t),ot=Je(null),lr=Je(0),kt=Je(null),Pn=Je(null),It=Je(new Map),Yt=Je(new Map),gn=Je(!1);vt(()=>(gn.current=!0,()=>{gn.current=!1}),[]),vt(()=>{lt.current=b},[b]),vt(()=>{Hn.current=a},[a]),vt(()=>{tn.current=T},[T]),vt(()=>{gt.current=M},[M]),vt(()=>{Ut.current=u},[u]),vt(()=>{Mn.current=k},[k]),vt(()=>{Bn.current=Q},[Q]),vt(()=>{An.current=j},[j]),vt(()=>{Zt.current=P},[P]),vt(()=>{fn.current=le},[le]),vt(()=>{qt.current=ae},[ae]),vt(()=>{rr.current=r},[r]),vt(()=>{wt.current=o},[o]),vt(()=>{Fn.current=t},[t]),vt(()=>{Ee.current=se},[se]),vt(()=>{tt&&De.current?.focus()},[tt,se]);let sn=Eo(()=>{window.setTimeout(()=>{De.current?.focus()},0)},[]),Cn=Eo(()=>{_(!1),K(C=>C+1)},[]),nn=Eo(()=>{st(!1),(Ae.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ae.current)?.focus?.()},[]);vt(()=>{!we||!Ue.current||(Ue.current=!1,nn())},[nn,we,se]);let Sn=Eo((C,nt)=>{let $t=Mn.current;if($t){$t("paypal",C,nt);return}gt.current?.(Xl(nt?.popupBlocked??fr(C)))},[]),Nt=()=>{kt.current?.timer&&(clearTimeout(kt.current.timer),kt.current.timer=null)},J=()=>{Nt();let C=lr.current+1;return lr.current=C,Pn.current=null,kt.current={generation:C,timer:null,yieldedControl:!1},st(!1),C},ln=C=>C!==void 0&&kt.current?.generation!==C?!1:(Nt(),kt.current=null,Pn.current=null,!0),Dn=C=>{let nt=C?.generation??kt.current?.generation??lr.current;(!C?.generation||kt.current?.generation===nt)&&(Nt(),kt.current=null),Pn.current=nt,C?.showRetry&&st(!0),C?.remount&&Cn(),C?.focus!==!1&&sn()},Yn=C=>kt.current?.generation===C&&Pn.current!==C,Cr=C=>{typeof document<"u"&&document.visibilityState!=="visible"||(Nt(),C.timer=setTimeout(()=>{kt.current?.generation===C.generation&&(kt.current=null,Pn.current=C.generation,Sn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),st(!0),Cn(),sn())},600))},Sr=()=>{let C=kt.current;C?.yieldedControl&&Cr(C)},cr=()=>{let C=kt.current;C&&(C.yieldedControl=!0,Nt())},Bt=C=>{let nt=ot.current;return nt&&Yt.current.set(C,nt),C};vt(()=>{let C=()=>{document.visibilityState==="visible"?Sr():cr()};return document.addEventListener("visibilitychange",C),window.addEventListener("focus",Sr),window.addEventListener("blur",cr),()=>{document.removeEventListener("visibilitychange",C),window.removeEventListener("focus",Sr),window.removeEventListener("blur",cr),Nt()}},[]),vt(()=>{h.current!==Et&&(h.current=Et,Be.current=!1,V.current=!1,_(!1),Le(!1),L(!1),Zt.current?.("loading"))},[Et]),vt(()=>{St(()=>An.current?.(we&&!z))},[we,z]);let $e=Kl(s);vt(()=>{let C=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",nt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(U(`mount clientId=${C} env=${s??"(unset)"}\u2192${$e??"live"} ccy=${w} sub=${f}`),U(`ua=${nt.slice(0,80)}${nt.length>80?"\u2026":""}`),!l){U("FAIL: clientId empty \u2014 gateway misconfigured"),L(!0),B.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Ae.current){U("FAIL: containerRef not attached");return}Fe.current=B.startTiming(),B.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let $t=!1,hn=!1,ue=()=>$t||hn,rn,wr=!1,Lr=()=>{rn=jl(),rn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),wr=!0},cn=null,ur=!1,Wn=null,Ln=!1,At=()=>{!Wn||Ln||(Ln=!0,Wn.close().catch(()=>{}))},Nn=null,Gn=()=>{Nn!==null&&(B.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"overlay_return",durationMs:B.elapsed(Nn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Nn=null)},dn=!1,Qt=Ae.current,On=null,zn=null,at=[],un=null,pn=!1,Un=!1,wn=null,Pe=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let d=m.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},en=m=>{if(!m)return"(empty)";try{let d=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),y=d.pathname.toLowerCase();return y.includes("checkcaptcha")||y.includes("captcha")?`CAPTCHA(${d.host}${y})`:y.includes("risk")||y.includes("challenge")?`RISK(${d.host}${y})`:y.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${y}`.slice(0,100)}catch{return m.slice(0,80)}},Ft=m=>{let d=m.getAttribute("src"),y=m.getAttribute("srcdoc"),pe=m.getAttribute("name"),re=m.getAttribute("sandbox"),je=[];return d&&je.push(`src=${en(d)}`),y&&je.push(`srcdoc[${y.length}ch]`),!d&&!y&&je.push("src=(empty) srcdoc=(empty)"),pe&&je.push(`name=${pe.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 y=d.body?.children.length??0,pe=d.body?.innerHTML.length??0,re=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${y}children,${pe}ch] head[${re}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},qn=[],mr=m=>{if(ue())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"))&&(U(`window:error ${d.slice(0,140)}`),qn.push(d))},bn=m=>{if(ue())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"))&&(U(`window:rejection ${d.slice(0,140)}`),qn.push(d))},kn={value:0},Dt=()=>{for(On?.disconnect(),On=null,zn?.disconnect(),zn=null;at.length;)clearTimeout(at.pop());Un=!1,pn&&typeof window<"u"&&(window.removeEventListener("error",mr),window.removeEventListener("unhandledrejection",bn)),pn=!1},x=()=>{if(!(pn||ue()||dn)){if(pn=!0,qn.length=0,kn.value=0,typeof window<"u"&&(window.addEventListener("error",mr),window.addEventListener("unhandledrejection",bn)),typeof PerformanceObserver<"u")try{zn=new PerformanceObserver(m=>{if(!ue())for(let d of m.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;kn.value+=1;let y=Math.round(d.duration);U(`net ${y}ms ${d.name.slice(0,90)}`)}}),zn.observe({type:"resource",buffered:!0})}catch{}wn?.()}},F=()=>{un&&(clearTimeout(un),un=null)},W=()=>{Dt(),F()},G={setEnabled:m=>{m?x():Dt()}};qe.current=G,Ye.current&&x();let Ce=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")},A=m=>{if(ue()||Ce(m))return;let d=yr(m)??m;St(()=>gt.current?.(d))},q=m=>{$t||(L(!0),m.includes("paypal_ineligible")||B.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",m))},p=(m,d=!1)=>{if($t)return;let y=Be.current||!me;if(ur)return;ur=!0,hn=!0,W(),At();let pe=d||ps(m);if(pe&&me&&!Be.current){Be.current=!0,_(!1),He(!1),Le(!0),Zt.current?.("retrying"),cn=setTimeout(()=>{$t||K(re=>re+1)},Yl);return}if(pe||y){if(_(!1),He(!1),Le(!1),L(!0),Zt.current?.("exhausted"),!V.current){V.current=!0;let re=ps(m)?"paypal_init_timeout":d?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",re)}return}q(m)};L(!1);let N=async(m,d=ot.current)=>{if(ue())return;let y=d?.sessionId??e;if(lt.current){await lt.current(m,{sessionId:y,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let pe=B.startTiming();B.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let re=()=>{B.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"processing",durationMs:B.elapsed(pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let je=qt.current,We=d?.accountPatch?.email??rr.current,X=d?.accountPatch?.userId??je?.customer?.id??je?.accountData?.userId??"",E=d?.accountPatch?.firstName??je?.customer?.firstName??je?.accountData?.firstName,oe=d?.accountPatch?.lastName??je?.customer?.lastName??je?.accountData?.lastName,Ne=await new za(Ct,{telemetry:!1}).processPayment(X,{sessionId:y,nonce:d?.nonce??Fn.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:X,email:We??je?.customer?.email??"",...E?{firstName:E}:{},...oe?{lastName:oe}:{},country:d?.accountPatch?.country??je?.customer?.country??je?.accountData?.country??void 0,zip:d?.accountPatch?.zip??je?.customer?.zip??je?.accountData?.zip??void 0}});if(Ne.ok){if(hn||$t&&gn.current)return;re(),B.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),St(()=>tn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ue())return;let mt=await Ne.json().catch(()=>null),Oe=mt?.message??"PayPal payment failed.",Ot=yr(Oe)??Oe;re(),Ne.status===400&&(typeof mt?.declineCode=="string"||!Array.isArray(mt?.fields))?B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Ne.status===400||Ne.status===422?B.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):B.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Ne.status>=500?"5xx":Ne.status>=400?"4xx":Ne.status>=300?"3xx":"unknown",failureCategory:Ne.status>=500?"server_error":void 0}),A(Ot),St(()=>Ut.current?.(jt("paypal",Ot,{code:mt?.code,declineCode:mt?.declineCode})));return}catch(je){if(ue())return;re(),B.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.",X=yr(We)??We;A(X),St(()=>Ut.current?.(jt("paypal",X)));return}},$=()=>new ds("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ct=m=>ue()?Promise.reject($()):Promise.resolve(m),pt=async m=>{if(ue())throw $();wr||Lr();let d=ot.current,y=d?.sessionId??e,pe=d?.nonce??Fn.current;B.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let re;try{re=await new za(Ct,{telemetry:!1}).createSessionIntent(y,pe??"",ut?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ua,paymentMethodId:null,intentKind:Ie==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:rn})}catch(je){throw B.error({...$l(je,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),je}if(ue())throw $();if(re.provider!=="paypal"||re.providerObjectType!==Ie)throw new Error(m);return B.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),re.providerObjectId},ne=(m,d)=>{let y=d?.nonce??Fn.current;if(!y)return;let pe=d?.sessionId??e,re=Gr(m)??or(m)??"provider_declined";new za(Ct,{telemetry:!1}).reportSessionIntentDecline(pe,y,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:re}).catch(()=>{})},Se=se;U("loadScript:scheduled (deferred 1 tick)");let Wt=null,Qe=setTimeout(()=>{if($t){U("loadScript:skipped (cancelled before defer ran)");return}U("loadScript:start");let m=$e==="live"?"production":$e;Wt=Hl({clientId:l,currency:w,...Ie==="subscription"?{intent:"subscription",vault:!0}:Ie==="order"?{intent:"capture"}:{},...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Wt.then(d=>{if(U(`loadScript:resolved inactive=${ue()} ns=${!!d} buttons=${!!d?.Buttons}`),ue())return;if(!d?.Buttons){U("FAIL: namespace missing Buttons factory"),p("PayPal SDK did not expose the Buttons factory.");return}B.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"provider_ready",durationMs:B.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let y=async(X,E)=>{if(ue()||Ee.current!==Se)return;let oe=X.vaultSetupToken??X.subscriptionID??X.orderID??"",Ke=oe?Yt.current.get(oe):It.current.get(Se);if(!(!Ke||!Yn(Ke.generation))&&ln(Ke.generation)){Yt.current.delete(oe),It.current.delete(Ke.surfaceKey),Gn();try{if(He(!0),St(()=>gt.current?.(null)),!oe)throw new ds("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ne=qt.current,mt=Rr(wt.current??[Ne?.customer?.firstName,Ne?.customer?.lastName].filter(Boolean).join(" ")),Oe=yn({email:Ke.accountPatch?.email?.trim()||rr.current?.trim()||Ne?.customer?.email?.trim(),firstName:Ke.accountPatch?.firstName?.trim()||mt.firstName,lastName:Ke.accountPatch?.lastName?.trim()||mt.lastName});if(!Ro(Oe.email)||!(Oe.firstName||Oe.lastName))try{let Ot=Zl(await E?.order?.get?.());Oe=yn({email:Ot.email||Oe.email,firstName:Ot.firstName||Oe.firstName,lastName:Ot.lastName||Oe.lastName})}catch{}if((Hn.current||rt)&&!Ro(Oe.email)){let Ot=await Y("PayPal",Oe);if(!Ot)return;Oe=Ot}Ro(Oe.email)&&(Ke.accountPatch=yn({...Ke.accountPatch,...Oe}),await Hn.current?.(Oe)),await N(Ie==="setup_token"?{id:oe,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ua}:ut?{id:oe,isPaypal:!0,gateway:"paypal",paymentMethodType:Ua}:{id:oe,isPaypal:!0},Ke)}catch(Ne){A(Ne instanceof Error?Ne.message:"PayPal capture failed.")}finally{ue()||He(!1)}}},pe=d.Buttons({style:{layout:"horizontal",height:ra,tagline:!1},onClick:async(X,E)=>{if(ue()){await E.reject();return}Lr();let oe=fn.current,Ke={};if(oe)try{let Oe=await oe("paypal");if(ue()){await E.reject();return}if(!Oe.proceed){ot.current=null,It.current.delete(Se),await E.reject();return}Ke={sessionId:Oe.sessionId,accountPatch:Oe.accountPatch,nonce:Oe.nonce}}catch(Oe){U(`onClick:runBeforeButtonClick rejected msg=${(Oe instanceof Error?Oe.message:String(Oe)).slice(0,120)}`),ot.current=null,It.current.delete(Se),await E.reject();return}St(()=>Bn.current?.("paypal"));let mt={generation:J(),surfaceKey:Se,...Ke};ot.current=mt,It.current.set(Se,mt),await E.resolve(),B.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),B.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Nn=B.startTiming()},createOrder:Ie==="order"?ve?()=>ct(ve).then(Bt):()=>pt("Failed to create PayPal order.").then(Bt):void 0,createSubscription:Ie==="subscription"?ve?()=>ct(ve).then(Bt):()=>pt("Failed to create PayPal subscription.").then(Bt):void 0,createVaultSetupToken:Ie==="setup_token"?()=>pt("Failed to create PayPal setup token.").then(Bt):void 0,onApprove:y,onCancel:()=>{if(ue())return;let X=It.current.get(Se)??ot.current;X&&It.current.delete(X.surfaceKey),ot.current=null,Gn(),B.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ue.current=!0,Dn({generation:X?.generation,remount:!0,focus:!1})},onError:X=>{if(ue()||Ee.current!==Se)return;let E=X instanceof Error?X.message:"PayPal failed to render.";if(U(`onError rendered=${dn} msg=${E.slice(0,120)}`),dn){let oe=It.current.get(Se)??ot.current;if(oe&&!Yn(oe.generation)||!oe&&Pn.current===lr.current)return;if(Ce(E)){ln(oe?.generation);return}if(Gn(),ko(X)){B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ne(X,oe),St(()=>Ut.current?.(jt("paypal",E))),oe&&It.current.delete(oe.surfaceKey),ot.current=null,ln(oe?.generation);return}let Ke=E.toLowerCase();B.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&&It.current.delete(oe.surfaceKey),ot.current=null,Dn({generation:oe?.generation,remount:!0,showRetry:!0,focus:!0}),Sn(X,{code:"paypal_runtime_failed"});return}p(E)}}),re=pe.isEligible();if(U(`isEligible=${re}`),B.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}Wn=pe,wn=()=>{if(!pn||Un||ue()||dn)return;Un=!0,U(`container:dims ${Pe(Qt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),typeof MutationObserver<"u"&&(On=new MutationObserver(E=>{if(!ue()){for(let oe of E)if(oe.type==="childList")oe.addedNodes.forEach(Ke=>{if(!(Ke instanceof Element))return;let Ne=Ke.tagName.toLowerCase(),mt=(Ke.getAttribute("title")??"").slice(0,40),Oe=Ne==="iframe"?` ${Ft(Ke)}`:"";U(`child+ ${Ne}${mt?` title="${mt}"`:""}${Oe} dims=${Pe(Ke)}`)});else if(oe.type==="attributes"&&oe.target instanceof Element){let Ke=oe.target;if(Ke.tagName.toLowerCase()!=="iframe")continue;let Ne=oe.attributeName;(Ne==="src"||Ne==="srcdoc")&&U(`attr~ iframe ${Ne}=${Ne==="srcdoc"?`[${(Ke.getAttribute("srcdoc")??"").length}ch]`:en(Ke.getAttribute("src"))} dims=${Pe(Ke)}`)}}}),On.observe(Qt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let X=E=>{if(ue()||dn)return;let oe=Qt.querySelectorAll("iframe"),Ke=typeof document<"u"&&"hasStorageAccess"in document;U(`watchdog:${E} container=${Pe(Qt)} children=${Qt.childElementCount} iframes=${oe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${Ke} paypalNetRequests=${kn.value}`),oe.forEach((Ne,mt)=>{let Oe=(Ne.getAttribute("title")??"").slice(0,40);U(` iframe[${mt}] ${Pe(Ne)}${Oe?` title="${Oe}"`:""} ${Ft(Ne)}`);let Ot=pr(Ne);Ot&&U(` ${Ot}`)}),qn.length===0&&U(" (no PayPal/zoid window errors captured)")};at.push(setTimeout(()=>X("3s"),3e3)),at.push(setTimeout(()=>X("8s"),8e3)),at.push(setTimeout(()=>X("15s"),15e3))},wn(),U("render:start");let We=B.startTiming();un=setTimeout(()=>{ue()||dn||(U("watchdog:11s retryable render timeout"),p("PayPal Buttons render did not settle within 11000ms.",!0))},Wl),pe.render(Qt).then(()=>{if(U(`render:resolved inactive=${ue()}`),W(),ue()){At();return}dn=!0,_(!0),Le(!1),Zt.current?.("ready"),B.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"checkout_render",durationMs:B.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(X=>{let E=X instanceof Error?X.message:"PayPal failed to render.";U(`render:rejected msg=${E.slice(0,120)}`),W(),p(E)})}).catch(d=>{let y=d instanceof Error?d.message:"PayPal SDK failed to load.";U(`loadScript:rejected msg=${y.slice(0,120)}`),p(y)})},0);return()=>{$t=!0,clearTimeout(Qe),cn&&clearTimeout(cn),W(),qe.current===G&&(qe.current=null),At()}},[me,Ct,l,w,s,Ie,ut,e,ve,se,B,Y,rt,U]);let dr=Xe?qa("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:z?"#fef2f2":"#f3f4f6",border:`1px solid ${z?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${we} failed=${z})`,zt.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
3
|
${zt.join(`
|
|
4
|
-
`)}`]}):null;return z&&!H?Xe?xr("div",{children:dr}):null:qa("div",{children:[dr,I&&xr(Wr,{identity:I.identity,methodLabel:I.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:R,onCancel:()=>R(null)}),qa("div",{"aria-hidden":ie||I?!0:void 0,style:ie||I?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ra},children:[!we&&!ie&&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:Ae,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ra,display:"flex",opacity:we?1:0},"aria-busy":ke||be},se)]},se),tt&&xr("button",{ref:De,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:nn,style:Jl,children:"Try PayPal again"})]})}function oa(e){return xr(ms,{...e})}function ys(e){return xr(ms,{...e})}import{jsx as fs,jsxs as Ql}from"react/jsx-runtime";function Xr({children:e,margin:t,icon:n=!0,styleOverride:r}){return Ql("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&fs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:fs("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 ec}from"@flopay/shared";import{useEffect as hr,useMemo as tc,useRef as gs,useState as hs}from"react";import{jsx as nc}from"react/jsx-runtime";function aa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=hs(e instanceof Promise?null:e),[s,S]=hs(t instanceof Promise||!t?null:t),f=gs(null),g=gs(null),b=Jr(r);hr(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),hr(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),hr(()=>{if(a)return Kt(a)?.subscribe?.(b)},[b,a]),hr(()=>{if(!(!s||s===a))return Kt(s)?.subscribe?.(b)},[b,a,s]),hr(()=>{if(!a)return;let u=Kt(a);return f.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(w=>{u||l(w)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{u=!0}},[b,e]),hr(()=>{let u=!1;if(!t){S(null);return}return t instanceof Promise?t.then(w=>{u||S(w)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):S(t),()=>{u=!0}},[b,t]),hr(()=>{if(!a||g.current===a)return;g.current=a;let u=Kt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(f.current??0),durationMode:"machine"})},[b,a]);let T=ec(n?.billingApiUrl),B=tc(()=>({flopay:a,paypalFlopay:s,billingApiUrl:T,emitInstrument:b}),[a,s,T,b]);return nc(Tn.Provider,{value:B,children:o})}var ia="flopay_recent_completion_";function Zr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ia+e,JSON.stringify(t))}catch{}}function ja(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ia+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ia+e),!1):!0}catch{return!1}}import{loadFloPay as bs,PaymentAPI as Ps}from"@flopay/js";import{classifyPaymentRejection as rc,FloPayError as yt,isAuthorizationOnlySession as oc,isSetupIntentClientSecret as ac,normalizeCheckoutFailureOutcome as vs}from"@flopay/shared";var xo="card";async function ic(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 sc(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Va(e,t){return Object.assign(e,{checkoutMethod:t})}function ar(e,t){let n=e instanceof yt?e:new yt(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 To(e,t){try{return await e()}catch(n){throw ar(n,t)}}function Cs(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 lc(e){return e.status==="succeeded"||e.status==="declined"}async function Ss(e){if(typeof document>"u"||typeof window>"u")throw new yt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new yt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let g=new AbortController,b=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",b);let T=window.setTimeout(()=>g.abort(),r);try{let B=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!B.ok)return{status:"unknown"};let u=await B.json().catch(()=>null);return cc(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 S=document.createElement("iframe");S.setAttribute("title","Card authentication"),S.setAttribute("allow","payment"),S.tabIndex=0,S.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),S.src=e.nextActionRedirectUrl,s.appendChild(S),document.body.appendChild(s),S.focus();let f=null;try{f=new URL(e.billingApiUrl,window.location.href).origin}catch{f=null}try{let g=await new Promise((b,T)=>{let B=!1,u=0,w=0,be=0,j=!1,P=()=>{window.clearTimeout(u),window.clearInterval(w),window.clearTimeout(be),window.removeEventListener("message",ae),S.removeEventListener("load",Q),e.signal?.removeEventListener("abort",le)},me=async()=>{if(!(B||j)){j=!0;try{let ve=await a();if(B||!lc(ve))return;B=!0,P(),b(ve)}finally{j=!1}}},Q=()=>{window.clearTimeout(be),be=window.setTimeout(()=>{me()},250)},le=()=>{B||(B=!0,P(),T(new yt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=ve=>{if(ve.source!==S.contentWindow||f&&ve.origin!==f)return;let Ze=ve.data;!Ze||typeof Ze!="object"||Ze.source!=="flopay-vault-3ds-return"||B||(B=!0,P(),b(null))};u=window.setTimeout(()=>{B||(B=!0,P(),T(new yt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),w=window.setInterval(()=>{me()},n),S.addEventListener("load",Q),window.addEventListener("message",ae),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return g||await a()}finally{s.parentNode?.removeChild(s),l?.isConnected&&l.focus()}}function cc(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function br(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=yr(o)??o;return Va(new yt(a,"api_error",{code:vs(e?.outcome)??vs(e?.type)??e?.gatewayErrorCode}),r)}function Ka(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function sa(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function dc(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function ws(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||sa(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||sa(s)))return s;let l=o.gateways;if(l&&typeof l=="object"){let s=l.stripe;if(s&&typeof s=="object"){let S=s,f=[S.stripeClientSecret,S.clientSecret];for(let g of f)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||sa(g)))return g}}}}async function uc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ws(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 Ps(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(sa(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function Qr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let s=e.replace(/\/+$/,""),S=t??n.id,f=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",T=n.customer?.firstName??n.accountData?.firstName??"",B=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,w=n.customer?.zip??n.accountData?.zip??void 0,be=new Ps(s,l===!1?{telemetry:!1}:void 0),j=await dc(()=>be.processPayment(g,{sessionId:S,nonce:f,tokenizedData:o,accountData:{userId:g,email:b,firstName:T,lastName:B,country:u,zip:w},returnUrl:a??Ka(n)}));if(j.ok){let Q=typeof j.json=="function"?await j.json().catch(()=>null):null;return oc(n)||Q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Q?.paymentId=="string"?Q.paymentId:n.paymentId,sessionId:typeof Q?.sessionId=="string"?Q.sessionId:S,authorizationExpiresAt:typeof Q?.authorizationExpiresAt=="string"?Q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:So(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:So(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let P;try{P=await j.json()}catch{throw new yt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status})}if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let Q=ws(P);if(!Q)throw new yt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status});return{type:P.type,threeDSecureToken:Q,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let Q=await uc({billingApiUrl:s,sessionId:S,nonce:f,responseJson:P});if(Q)return Q;throw Va(new yt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new yt(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:j.status});throw Object.assign(me,{telemetryOutcome:rc(j.status,P)})}async function la(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:S}){let f=t?.getRawProvider();if(!f)throw ar(new yt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Va(new yt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=ac(e.threeDSecureToken),b=null,T=e.paymentMethodId,B=await To(()=>ic(f,e.threeDSecureToken,g),"card");if(B){if(B.error)throw ar(new yt(B.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:B.error.code}),"card");let w=B.intent;!T&&w?.payment_method&&(typeof w.payment_method=="string"?T=w.payment_method:"id"in w.payment_method&&(T=w.payment_method.id??void 0))}let u=T?await To(()=>sc(f,e.threeDSecureToken,{payment_method:T,return_url:s??Ka(l)??window.location.href},g),"card"):null;if(u){if(u.error)throw ar(new yt(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");b=u.intent}else{let w=await To(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(w.error)throw ar(new yt(w.error.message??"3DS authentication failed.","api_error",{code:w.error.code}),"card");b=(g?w.setupIntent:w.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let w=await Qr({billingApiUrl:o,sessionId:a,session:l,telemetry:S,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:s});return w.type==="success"?{...w.result,paymentIntentId:w.result.paymentIntentId??b.id,paymentMethodId:w.result.paymentMethodId??T}:la(w,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:S})}throw ar(new yt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw ar(new yt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:T}=await To(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(T)throw ar(new yt(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await To(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Ka(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw ar(new yt(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new yt("Unsupported payment redirect state.","api_error")}function Bo(e){if(e instanceof yt){let r=yr(e.message);return r&&r!==e.message?Object.assign(new yt(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 yt(n,"api_error")}function ca(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new yt("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 da({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([bs(e,{billingApiUrl:n,locale:r,telemetry:o}),a?bs(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:l,paypalFlopay:t?a?s:l:null}}import{PaymentAPI as eo,toStripeAppearance as pc}from"@flopay/js";import{COUNTRY_OPTIONS as mc,classifyPaymentRejection as yc,FloPayError as Vn,filterStripeMethodsByCountry as fc,getPostalCodeExample as gc,getPostalCodeLabel as Ja,getStateFromPostalCode as Rs,getStateLabel as Ha,getStateOptions as hc,getStripeMethodDisplayName as Fr,hasVendoredStripeMethodLogo as bc,isAuthorizationOnlySession as Ya,isAVSFieldVisible as Ve,isPostalCodeSupported as vc,isSetupIntentClientSecret as Pc,isValidEmail as Xt,isValidPostalCode as Cc,needsStripeMethodExplicitConfirm as Es,normalizeCheckoutFailureOutcome as Sc,partitionStripeMethods as wc,resolveAVSConfig as kc,resolveButtonsLayoutTheme as Ic,resolveStripeMethodBrandVariant as Rc,resolveTheme as Ec,stripeExpressMethodToOptionKey as _s}from"@flopay/shared";import{ExpressCheckoutElement as Ns,PaymentElement as _c,Elements as Mr,useElements as Qa,useStripe as ei}from"@stripe/react-stripe-js";import Tc,{useCallback as ye,useContext as to,useEffect as Pt,useMemo as ft,useRef as he,useState as de}from"react";function ks(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 Is={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 Ar,jsx as c,jsxs as Te}from"react/jsx-runtime";var Qn="flopay_stripe_resume",Ts="flopay_wallet_resume";function Os(e){return e instanceof Vn&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function pa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new eo(e).createSessionIntent(...n)}catch(o){throw Os(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Mo="flopay_paypal_resume",xc=250,xs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ti(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ma({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new eo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Bc(e){return e instanceof Vn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Wa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Mc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=Rr(r?.name),a=Rr(n);return yn({email:(Xt(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:a.firstName??o.firstName,lastName:a.lastName??o.lastName})}async function zs({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=Mc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return Xt(l.email)?l:a(o,l)}var Ac=`
|
|
4
|
+
`)}`]}):null;return z&&!H?Xe?xr("div",{children:dr}):null:qa("div",{children:[dr,I&&xr(Wr,{identity:I.identity,methodLabel:I.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:R,onCancel:()=>R(null)}),qa("div",{"aria-hidden":ie||I?!0:void 0,style:ie||I?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ra},children:[!we&&!ie&&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:Ae,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ra,display:"flex",opacity:we?1:0},"aria-busy":ke||be},se)]},se),tt&&xr("button",{ref:De,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:nn,style:Jl,children:"Try PayPal again"})]})}function oa(e){return xr(ms,{...e})}function ys(e){return xr(ms,{...e})}import{jsx as fs,jsxs as Ql}from"react/jsx-runtime";function Xr({children:e,margin:t,icon:n=!0,styleOverride:r}){return Ql("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&fs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:fs("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 ec}from"@flopay/shared";import{useEffect as hr,useMemo as tc,useRef as gs,useState as hs}from"react";import{jsx as nc}from"react/jsx-runtime";function aa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=hs(e instanceof Promise?null:e),[s,w]=hs(t instanceof Promise||!t?null:t),f=gs(null),g=gs(null),b=Jr(r);hr(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),hr(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),hr(()=>{if(a)return Kt(a)?.subscribe?.(b)},[b,a]),hr(()=>{if(!(!s||s===a))return Kt(s)?.subscribe?.(b)},[b,a,s]),hr(()=>{if(!a)return;let u=Kt(a);return f.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(k=>{u||l(k)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{u=!0}},[b,e]),hr(()=>{let u=!1;if(!t){w(null);return}return t instanceof Promise?t.then(k=>{u||w(k)},()=>{u||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):w(t),()=>{u=!0}},[b,t]),hr(()=>{if(!a||g.current===a)return;g.current=a;let u=Kt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(f.current??0),durationMode:"machine"})},[b,a]);let T=ec(n?.billingApiUrl),M=tc(()=>({flopay:a,paypalFlopay:s,billingApiUrl:T,emitInstrument:b}),[a,s,T,b]);return nc(Tn.Provider,{value:M,children:o})}var ia="flopay_recent_completion_";function Zr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ia+e,JSON.stringify(t))}catch{}}function ja(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ia+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ia+e),!1):!0}catch{return!1}}import{loadFloPay as bs,PaymentAPI as Ps}from"@flopay/js";import{classifyPaymentRejection as rc,FloPayError as yt,isAuthorizationOnlySession as oc,isSetupIntentClientSecret as ac,normalizeCheckoutFailureOutcome as vs}from"@flopay/shared";var xo="card";async function ic(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 sc(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Va(e,t){return Object.assign(e,{checkoutMethod:t})}function ar(e,t){let n=e instanceof yt?e:new yt(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 To(e,t){try{return await e()}catch(n){throw ar(n,t)}}function Cs(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 lc(e){return e.status==="succeeded"||e.status==="declined"}async function Ss(e){if(typeof document>"u"||typeof window>"u")throw new yt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new yt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let g=new AbortController,b=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",b);let T=window.setTimeout(()=>g.abort(),r);try{let M=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!M.ok)return{status:"unknown"};let u=await M.json().catch(()=>null);return cc(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 w=document.createElement("iframe");w.setAttribute("title","Card authentication"),w.setAttribute("allow","payment"),w.tabIndex=0,w.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(";"),w.src=e.nextActionRedirectUrl,s.appendChild(w),document.body.appendChild(s),w.focus();let f=null;try{f=new URL(e.billingApiUrl,window.location.href).origin}catch{f=null}try{let g=await new Promise((b,T)=>{let M=!1,u=0,k=0,be=0,j=!1,P=()=>{window.clearTimeout(u),window.clearInterval(k),window.clearTimeout(be),window.removeEventListener("message",ae),w.removeEventListener("load",Q),e.signal?.removeEventListener("abort",le)},me=async()=>{if(!(M||j)){j=!0;try{let ve=await a();if(M||!lc(ve))return;M=!0,P(),b(ve)}finally{j=!1}}},Q=()=>{window.clearTimeout(be),be=window.setTimeout(()=>{me()},250)},le=()=>{M||(M=!0,P(),T(new yt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ae=ve=>{if(ve.source!==w.contentWindow||f&&ve.origin!==f)return;let Ze=ve.data;!Ze||typeof Ze!="object"||Ze.source!=="flopay-vault-3ds-return"||M||(M=!0,P(),b(null))};u=window.setTimeout(()=>{M||(M=!0,P(),T(new yt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),k=window.setInterval(()=>{me()},n),w.addEventListener("load",Q),window.addEventListener("message",ae),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return g||await a()}finally{s.parentNode?.removeChild(s),l?.isConnected&&l.focus()}}function cc(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function br(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=yr(o)??o;return Va(new yt(a,"api_error",{code:vs(e?.outcome)??vs(e?.type)??e?.gatewayErrorCode}),r)}function Ka(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function sa(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ws(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||sa(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||sa(s)))return s;let l=o.gateways;if(l&&typeof l=="object"){let s=l.stripe;if(s&&typeof s=="object"){let w=s,f=[w.stripeClientSecret,w.clientSecret];for(let g of f)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||sa(g)))return g}}}}async function dc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ws(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 Ps(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(sa(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function Qr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let s=e.replace(/\/+$/,""),w=t??n.id,f=r??n.clientSecret,g=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,k=n.customer?.zip??n.accountData?.zip??void 0,j=await new Ps(s,l===!1?{telemetry:!1}:void 0).processPayment(g,{sessionId:w,nonce:f,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:g,email:b,firstName:T,lastName:M,country:u,zip:k},returnUrl:a??Ka(n)});if(j.ok){let Q=typeof j.json=="function"?await j.json().catch(()=>null):null;return oc(n)||Q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Q?.paymentId=="string"?Q.paymentId:n.paymentId,sessionId:typeof Q?.sessionId=="string"?Q.sessionId:w,authorizationExpiresAt:typeof Q?.authorizationExpiresAt=="string"?Q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:So(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:So(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let P;try{P=await j.json()}catch{throw new yt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status})}if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let Q=ws(P);if(!Q)throw new yt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:j.status});return{type:P.type,threeDSecureToken:Q,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let Q=await dc({billingApiUrl:s,sessionId:w,nonce:f,responseJson:P});if(Q)return Q;throw Va(new yt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new yt(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:j.status});throw Object.assign(me,{telemetryOutcome:rc(j.status,P)})}async function la(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:w}){let f=t?.getRawProvider();if(!f)throw ar(new yt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Va(new yt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=ac(e.threeDSecureToken),b=null,T=e.paymentMethodId,M=await To(()=>ic(f,e.threeDSecureToken,g),"card");if(M){if(M.error)throw ar(new yt(M.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let k=M.intent;!T&&k?.payment_method&&(typeof k.payment_method=="string"?T=k.payment_method:"id"in k.payment_method&&(T=k.payment_method.id??void 0))}let u=T?await To(()=>sc(f,e.threeDSecureToken,{payment_method:T,return_url:s??Ka(l)??window.location.href},g),"card"):null;if(u){if(u.error)throw ar(new yt(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");b=u.intent}else{let k=await To(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(k.error)throw ar(new yt(k.error.message??"3DS authentication failed.","api_error",{code:k.error.code}),"card");b=(g?k.setupIntent:k.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let k=await Qr({billingApiUrl:o,sessionId:a,session:l,telemetry:w,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:s});return k.type==="success"?{...k.result,paymentIntentId:k.result.paymentIntentId??b.id,paymentMethodId:k.result.paymentMethodId??T}:la(k,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:s,telemetry:w})}throw ar(new yt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw ar(new yt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:T}=await To(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(T)throw ar(new yt(T.message??"PayPal authorization failed.","api_error",{code:T.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await To(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Ka(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw ar(new yt(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new yt("Unsupported payment redirect state.","api_error")}function Mo(e){if(e instanceof yt){let r=yr(e.message);return r&&r!==e.message?Object.assign(new yt(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 yt(n,"api_error")}function ca(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new yt("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 da({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([bs(e,{billingApiUrl:n,locale:r,telemetry:o}),a?bs(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(w=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",w),null)):Promise.resolve(null)]);return{flopay:l,paypalFlopay:t?a?s:l:null}}import{PaymentAPI as eo,toStripeAppearance as uc}from"@flopay/js";import{COUNTRY_OPTIONS as pc,classifyPaymentRejection as mc,FloPayError as Vn,filterStripeMethodsByCountry as yc,getPostalCodeExample as fc,getPostalCodeLabel as Ja,getStateFromPostalCode as Rs,getStateLabel as Ha,getStateOptions as gc,getStripeMethodDisplayName as Fr,hasVendoredStripeMethodLogo as hc,isAuthorizationOnlySession as Ya,isAVSFieldVisible as Ve,isPostalCodeSupported as bc,isSetupIntentClientSecret as vc,isValidEmail as Xt,isValidPostalCode as Pc,needsStripeMethodExplicitConfirm as Es,normalizeCheckoutFailureOutcome as Cc,partitionStripeMethods as Sc,resolveAVSConfig as wc,resolveButtonsLayoutTheme as kc,resolveStripeMethodBrandVariant as Ic,resolveTheme as Rc,stripeExpressMethodToOptionKey as _s}from"@flopay/shared";import{ExpressCheckoutElement as Ns,PaymentElement as Ec,Elements as Br,useElements as Qa,useStripe as ei}from"@stripe/react-stripe-js";import _c,{useCallback as ye,useContext as to,useEffect as Pt,useMemo as ft,useRef as he,useState as de}from"react";function ks(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 Is={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 Ar,jsx as c,jsxs as Te}from"react/jsx-runtime";var Qn="flopay_stripe_resume",Ts="flopay_wallet_resume";function Os(e){return e instanceof Vn&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function pa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new eo(e).createSessionIntent(...n)}catch(o){throw Os(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Bo="flopay_paypal_resume",Tc=250,xs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ti(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ma({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new eo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function xc(e){return e instanceof Vn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Wa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Mc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=Rr(r?.name),a=Rr(n);return yn({email:(Xt(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:a.firstName??o.firstName,lastName:a.lastName??o.lastName})}async function zs({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=Mc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return Xt(l.email)?l:a(o,l)}var Bc=`
|
|
5
5
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
6
6
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
7
7
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -22,7 +22,7 @@ ${zt.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
|
-
`,ua=44,Br=280;function ni(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 Fc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Us={width:"100%",minHeight:ua,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 Dc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Bs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Xa(e){return e==="paypal"?"PayPal":Fr(e)}function Lc(e,t){let n=`We couldn't open ${Xa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function qs(e){let t=he(0),n=he(null),r=he(null),o=ye((u=r.current)=>{let w=u;w?.timer&&(clearTimeout(w.timer),w.timer=null)},[]),a=ye((u,w)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(u),u.timer=setTimeout(()=>{u.timer=null,r.current?.generation===u.generation&&(r.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},w))},[o,e]),l=ye(u=>{u.yieldedControl&&a(u,600)},[a]),s=ye(u=>{o();let w=t.current+1;t.current=w,n.current=null;let be={generation:w,method:u,timer:null,yieldedControl:!1};return r.current=be,w},[o]),S=ye(u=>{let w=r.current;return typeof u=="number"&&w?.generation!==u?!1:(o(w),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),f=ye(u=>{let w=r.current,be=u??w?.generation??t.current;(!u||w?.generation===u)&&(o(w),r.current=null),n.current=be},[o]),g=ye(u=>n.current===(u??t.current),[]),b=ye(u=>r.current?.generation===u&&n.current!==u,[]),T=ye(()=>{let u=r.current;u&&l(u)},[l]),B=ye(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return Pt(()=>{let u=()=>{document.visibilityState==="visible"?T():B()},w=()=>{B()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",w),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",w),window.removeEventListener("focus",T),o()}},[o,B,T]),{startAttempt:s,finishAttempt:S,invalidateAttempt:f,isAttemptInvalidated:g,isAttemptCurrent:b}}function Nc(e){let t=gc(e);return`Enter a valid ${Ja(e)}${t?` (e.g. ${t})`:""}`}function Oc(e,t,n){let r=vc(e),o=t.trim(),a=n&&r,l=a&&!o,s=a&&!!o&&!Cc(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:s}}function zc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!Xt(n);return{required:t,empty:r,malformed:o,value:n}}function Ms(e,t){return t instanceof Vn?t:new Vn(t instanceof Error?t.message:`${Dc(e)} before-click hook failed.`,"validation_error")}function Ga(){return c("style",{children:Ac})}function Uc(e){return typeof e=="number"?`${e}px`:e}function $s(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function js({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 As(e){return e!=="unavailable"&&e!=="load_error"}function ri(e){return c($c,{...e})}function Fs({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:s,onDecline:S,onTechnicalFailure:f,runBeforeButtonClick:g,billingName:b,onBuyerIdentityReady:T,onLoadStateChange:B,placeholderBorderRadius:u}){let w=gr(),{emitInstrument:be}=to(Tn),j=ei(),P=Qa(),[me,Q]=de("loading");Pt(()=>{B?.(me)},[me,B]);let[le,ae]=de(!1),ve=!Xt(n?.trim())||!b?.trim(),{request:Ze,collect:fe,finish:Bt}=Yr(),Xe=he(!1),xe=he(null),Be=he(null),[ee,te]=de(0),[M,Ae]=de(!1),Fe=he(!1),De=he(new Map),{startAttempt:Ue,finishAttempt:we,invalidateAttempt:_,isAttemptInvalidated:ie,isAttemptCurrent:Le}=qs((V,z,L)=>{f?.(V,z,{...L,popupBlocked:L?.popupBlocked??fr(z)}),Ae(!0),te(ke=>ke+1)});Pt(()=>{M&&Be.current?.focus()},[M,ee]);let se=ye(()=>{te(V=>V+1)},[]),K=ye((V,z,L)=>{_(L),f?.("paypal",V,{code:z,popupBlocked:fr(V)}),Ae(!0),se()},[_,f,se]),Ee=ye(()=>{window.setTimeout(()=>{(xe.current?.querySelector("iframe")??xe.current)?.focus()},0)},[]);Pt(()=>{Fe.current&&(Fe.current=!1,Ee())},[Ee,ee]);let tt=ye(()=>{Ae(!1),a?.(null),Ee()},[Ee,a]);Pt(()=>{if(!j||Xe.current)return;let V=new URLSearchParams(window.location.search),z=V.get("payment_intent"),L=V.get("payment_intent_client_secret"),ke=V.get("redirect_status");if(!z||!L)return;Xe.current=!0;let He;try{let Y=localStorage.getItem(Mo);if(Y){let R=JSON.parse(Y);R.clientSecret===L&&(He={...R.accountPatch?{accountPatch:R.accountPatch}:{},...R.sessionId?{sessionId:R.sessionId}:{},...R.nonce?{nonce:R.nonce}:{}})}}catch{}try{localStorage.removeItem(Mo)}catch{}let I=new URL(window.location.href);I.searchParams.delete("payment_intent"),I.searchParams.delete("payment_intent_client_secret"),I.searchParams.delete("redirect_status"),window.history.replaceState({},"",I.toString()),(async()=>{try{if(ae(!0),ke==="failed"){let v="PayPal payment was declined. Please try again.";a?.(v),S?.(jt("paypal",v));return}let{paymentIntent:Y,error:R}=await j.retrievePaymentIntent(L);if(R){a?.(R.message??"Failed to retrieve PayPal payment status.");return}if(Y&&(Y.status==="requires_capture"||Y.status==="succeeded")){let v=typeof Y.payment_method=="string"?Y.payment_method:Y.payment_method?.id;o({id:v??Y.id,type:"card",threeDSecureActionResultTokenId:Y.id,isPaypal:!0},He)}else{let v="PayPal payment was not completed. Please try again.";a?.(v),S?.(jt("paypal",v))}}catch(Y){a?.(Y instanceof Error?Y.message:"Failed to complete PayPal payment.")}finally{ae(!1)}})()},[j,o,a,S]);let st=ye(async V=>{if(l||le){V.reject();return}let z=g?await g("paypal"):{proceed:!0};if(!z.proceed){De.current.delete(ee),V.reject();return}let L=Ue("paypal");De.current.set(ee,{generation:L,accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}),Ae(!1),s?.("paypal"),V.resolve()},[l,s,g,Ue,le,ee]),Me=ye(async V=>{if(!j||!P)return;let z=De.current.get(ee);if(z&&!Le(z.generation)){De.current.delete(ee);return}if(!z&&ie()||z&&!we(z.generation))return;z||we();let L=z??null;if(De.current.delete(ee),!L&&g){let v=await g("paypal");if(!v.proceed){V.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}L={accountPatch:v.accountPatch,sessionId:v.sessionId,nonce:v.nonce}}let ke=L?.sessionId??e,He=L?.nonce??t,I=await zs({event:V,prepared:L,email:n,billingName:b,methodLabel:"PayPal",collect:fe});if(!I){V.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Y=I.email,R=yn({...L?.accountPatch,...I});try{if(ae(!0),a?.(null),!ke||!Xt(Y))throw new Error("Missing sessionId or email for PayPal payment");await T?.(I);let v=j.createPaymentMethod,{error:rt,paymentMethod:Ct}=await v({type:"paypal"});if(rt){K(rt,"stripe_paypal_create_payment_method_failed",z?.generation),V.paymentFailed({reason:"fail"});return}let ge=await pa(r,be,ke,He??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Ct?.id??null,intentKind:"payment"});if(ge.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let dt=ge.clientSecret,Ie={return_url:window.location.href};if(Ct?.id&&(Ie.payment_method=Ct.id),typeof window<"u")try{localStorage.setItem(Mo,JSON.stringify({clientSecret:dt,sessionId:ke,nonce:He,accountPatch:R}))}catch{}let{error:ut,paymentIntent:Et}=await j.confirmPayment({clientSecret:dt,confirmParams:Ie,redirect:"if_required"});if(ut){if(typeof window<"u")try{localStorage.removeItem(Mo)}catch{}if(ko(ut)){let H=ut.message??"Your payment was declined.";a?.(H),S?.(jt("paypal",H,{code:or(ut),declineCode:Gr(ut)})),await ma({billingApiUrl:r,sessionId:ke,nonce:He,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:or(ut)??"provider_declined"}})}else K(ut,"stripe_paypal_confirm_failed",z?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Mo)}catch{}let h=typeof Et?.payment_method=="string"?Et.payment_method:Et?.payment_method?.id;o({id:h??Et?.id,type:"card",threeDSecureActionResultTokenId:Et?.id,isPaypal:!0},{accountPatch:R,sessionId:ke,nonce:He});return}catch(v){K(v,"stripe_paypal_failed",z?.generation)}finally{ae(!1)}},[j,P,e,t,n,b,fe,T,r,be,o,a,S,g,K,we,Le,ie,ee]);return Te(Ar,{children:[c(js,{state:me,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:[M&&c("button",{ref:Be,type:"button","data-testid":"flopay-paypal-retry-button",onClick:tt,style:Us,children:"Try PayPal again"}),Ze&&c(Wr,{identity:Ze.identity,methodLabel:Ze.methodLabel,onComplete:Bt,onCancel:()=>Bt(null)},Ze.id),c("div",{style:{display:Ze?"none":void 0},children:c(Ns,{onReady:V=>Q($s(V,["paypal"])),onLoadError:()=>{Q("load_error"),ti(Kt(w),"paypal","paypal")},onClick:st,onConfirm:Me,onCancel:()=>{let V=De.current.get(ee);De.current.delete(ee),Kt(w)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),_(V?.generation),Ae(!1),Fe.current=!0,se()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ve,emailRequired:ve,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),le&&c(Zn,{status:"processing"})]})}function Ds({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:s,onButtonClick:S,onDecline:f,onTechnicalFailure:g,runBeforeButtonClick:b,billingName:T,onBuyerIdentityReady:B,onLoadStateChange:u,placeholderBorderRadius:w}){let be=gr(),{emitInstrument:j}=to(Tn),P=ei(),me=Qa(),[Q,le]=de("loading");Pt(()=>{u?.(Q)},[Q,u]);let[ae,ve]=de(!1),Ze=!Xt(n?.trim())||!T?.trim(),{request:fe,collect:Bt,finish:Xe}=Yr(),xe=he(null),Be=he(null),[ee,te]=de(0),[M,Ae]=de(!1),[Fe,De]=de("google_pay"),Ue=he(!1),we=he("google_pay"),_=he("google_pay"),ie=he(new Map),{startAttempt:Le,finishAttempt:se,invalidateAttempt:K,isAttemptInvalidated:Ee,isAttemptCurrent:tt}=qs((I,Y,R)=>{g?.(I,Y,{...R,popupBlocked:R?.popupBlocked??fr(Y)}),De(I),Ae(!0),te(v=>v+1)});Pt(()=>{M&&Be.current?.focus()},[M,ee]);let st=ye(()=>{te(I=>I+1)},[]),Me=ye((I,Y,R,v)=>{K(v),g?.(I,Y,{code:R,popupBlocked:fr(Y)}),De(I),Ae(!0),st()},[K,g,st]),V=ye(()=>{window.setTimeout(()=>{(xe.current?.querySelector("iframe")??xe.current)?.focus()},0)},[]);Pt(()=>{Ue.current&&(Ue.current=!1,V())},[V,ee]);let z=ye(()=>{Ae(!1),s?.(null),V()},[V,s]),L=ye(async I=>{if(!P||!me)return;let Y=ie.current.get(ee);if(Y&&!tt(Y.generation)){ie.current.delete(ee);return}if(!Y&&Ee()||Y&&!se(Y.generation))return;Y||se();let R=I.expressPaymentType??Y?.method??we.current,v=Y??null;ie.current.delete(ee);let rt=Bs(R);if(!v&&b){let h=await b(rt);if(!h.proceed){I.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}v={accountPatch:h.accountPatch,sessionId:h.sessionId,nonce:h.nonce}}let Ct=rt,ge=v?.sessionId??e,dt=v?.nonce??t,Ie=await zs({event:I,prepared:v,email:n,billingName:T,methodLabel:Xa(R),collect:Bt});if(!Ie){I.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ut=Ie.email,Et=yn({...v?.accountPatch,...Ie});try{if(ve(!0),s?.(null),!Xt(ut))throw new Error("Missing sessionId or email for wallet payment");await B?.(Ie);let{error:h}=await me.submit();if(h){Me(R,h,"stripe_wallet_submit_failed",Y?.generation);return}let{error:H,paymentMethod:Ye}=await P.createPaymentMethod({elements:me});if(H||!Ye){Me(R,H??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",Y?.generation);return}if(!ge)throw new Error("Missing sessionId or email for wallet payment");let qe=await pa(r,j,ge,dt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:R??rt,paymentMethodId:Ye.id,intentKind:o});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let zt=qe.clientSecret,{error:Lt,intentId:U}=Pc(zt)?await P.confirmCardSetup(zt,{payment_method:Ye.id}).then(lt=>({error:lt.error,intentId:lt.setupIntent?.id})):await P.confirmCardPayment(zt,{payment_method:Ye.id}).then(lt=>({error:lt.error,intentId:lt.paymentIntent?.id}));if(Lt){if(ko(Lt)){let lt=Lt.message??"Your payment was declined.";s?.(lt),f?.(jt(Ct,lt,{code:or(Lt),declineCode:Gr(Lt)})),await ma({billingApiUrl:r,sessionId:ge,nonce:dt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:R??rt,providerDeclineReason:or(Lt)??"provider_declined"}})}else Me(R,Lt,"stripe_wallet_confirm_failed",Y?.generation);return}l({id:Ye.id,type:"card",threeDSecureActionResultTokenId:U},{accountPatch:Et,sessionId:ge,nonce:dt})}catch(h){Me(R,h,"stripe_wallet_failed",Y?.generation)}finally{ve(!1)}},[P,me,e,t,n,T,Bt,B,r,j,o,l,s,f,b,Me,se,tt,Ee,ee]),ke=ft(()=>{let I=["applePay","googlePay","paypal","link","amazonPay","klarna"],Y=new Set(["applePay","googlePay"]),R=new Set(a.map(_s)),v={};for(let rt of I)R.has(rt)?v[rt]=Y.has(rt)?"always":"auto":v[rt]="never";return v},[a]),He=ft(()=>a.map(_s),[a]);return Te(Ar,{children:[c(js,{state:Q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:w,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:[M&&Te("button",{ref:Be,type:"button","data-testid":"flopay-wallet-retry-button",onClick:z,style:Us,children:["Try ",Xa(Fe)," again"]}),fe&&c(Wr,{identity:fe.identity,methodLabel:fe.methodLabel,onComplete:Xe,onCancel:()=>Xe(null)},fe.id),c("div",{style:{display:fe?"none":void 0},children:c(Ns,{onReady:I=>{le($s(I,He))},onLoadError:I=>{le("load_error"),ti(Kt(be),"stripe","wallet")},onClick:async I=>{we.current=I.expressPaymentType,_.current=Bs(I.expressPaymentType);let Y=b?await b(_.current):{proceed:!0};if(!Y.proceed){ie.current.delete(ee),I.reject();return}let R=Le(I.expressPaymentType);ie.current.set(ee,{generation:R,method:I.expressPaymentType,accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}),Ae(!1),S?.(_.current),I.resolve()},onConfirm:L,onCancel:()=>{let I=ie.current.get(ee);ie.current.delete(ee),Kt(be)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),K(I?.generation),Ae(!1),Ue.current=!0,st()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ke,emailRequired:Ze,billingAddressRequired:Ze,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),ae&&c(Zn,{status:"processing"})]})}function qc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:s,borderColor:S,textColor:f,borderRadius:g,fontFamily:b}){let T=Rc(e,t),B=Is[e],[u,w]=de(!1),be=T?.backgroundColor??s??"#ffffff",j=T?.borderColor??S??"#d1d5db",P=T?.textColor??f??"#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:ua,padding:"0 1rem",backgroundColor:be,color:P,border:`1px solid ${j}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow: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(Ar,{children:[Te("span",{style:{display:"inline-flex",alignItems:"center",gap:bc(e)?8:0},children:[B&&!u?c("img",{src:B,alt:"","aria-hidden":"true",onError:()=>w(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):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:P,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:c("path",{d:"M9 18l6-6-6-6"})})]})})}function Za({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:s,onErrorChange:S,onDecline:f,onCancel:g,runBeforeButtonClick:b,onButtonClick:T,isProcessing:B,submitButtonColor:u,submitButtonBorderRadius:w,submitButtonStyle:be,errorText:j}){let P=gr(),{emitInstrument:me}=to(Tn),Q=ei(),le=Qa(),[ae,ve]=de(!1),Ze=he(!1),[fe,Bt]=de(!1),[Xe,xe]=de("loading"),[Be,ee]=de(""),te=!Xt(r?.trim()),M=!te||Xt(Be.trim()),Ae=ye(async()=>{if(!Q||!le||B||Ze.current||!fe)return;Ze.current=!0,ve(!0);let Fe=b?await b("card"):{proceed:!0};if(!Fe.proceed){Ze.current=!1,ve(!1);return}T?.("card");let De=Fe.sessionId??t,Ue=Fe.nonce??n,we=Rr(o?.trim()),_=yn({email:Fe.accountPatch?.email?.trim()||r?.trim()||Be.trim(),firstName:Fe.accountPatch?.firstName?.trim()||we.firstName,lastName:Fe.accountPatch?.lastName?.trim()||we.lastName}),ie=_.email,Le=yn({...Fe.accountPatch,..._});try{if(S?.(null),!Xt(ie))throw new Error("A valid email address is required for payment.");await a?.(_);let se=await le.submit();if(se.error){S?.(se.error.message??"Payment failed.");return}let K=[_.firstName,_.lastName].filter(Boolean).join(" "),Ee=await Q.createPaymentMethod({elements:le,params:{billing_details:{email:ie,...K?{name:K}:{}}}});if(Ee.error||!Ee.paymentMethod){S?.(Ee.error?.message??"Failed to create payment method.");return}let tt=Ee.paymentMethod;if(!De||!ie)throw new Error("Missing sessionId or email for payment.");let st=tt.type||e,Me=await pa(l,me,De,Ue??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:st,paymentMethodId:null,intentKind:"payment"});if(Me.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let V=Me.clientSecret;if(typeof window<"u")try{localStorage.setItem(Qn,JSON.stringify({clientSecret:V,sessionId:De,nonce:Ue,accountPatch:Le,paymentMethodId:tt.id,paymentMethodType:tt.type??e,gateway:"stripe"}))}catch{}let{error:z,paymentIntent:L}=await Q.confirmPayment({clientSecret:V,confirmParams:{return_url:window.location.href,payment_method:tt.id},redirect:"if_required"});if(z){if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let I=z.message??"Payment failed.";S?.(I),f?.(jt("card",I,{code:z.code})),await ma({billingApiUrl:l,sessionId:De,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:z.code??"provider_declined"}});return}let ke=L?.status;if(!Qo(ke)){if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let I=ke==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(I),f?.(jt("card",I,{code:ke??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let He=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;s({id:He??tt.id,type:"card",threeDSecureActionResultTokenId:L?.id,gateway:"stripe",paymentMethodType:tt.type??e},{accountPatch:Le,sessionId:De,nonce:Ue})}catch(se){S?.(se instanceof Error?se.message:"Payment failed. Please try again.")}finally{Ze.current=!1,ve(!1)}},[Q,le,B,fe,b,T,t,n,r,o,Be,a,l,me,e,s,S,f]);return Te("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[te&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:te&&Te("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:Be,onChange:Fe=>ee(Fe.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(_c,{onReady:()=>xe("ready"),onLoadError:()=>{xe("load_error"),ti(Kt(P),"stripe","apm")},onChange:Fe=>{Bt(!!Fe.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...Xt(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ae()},disabled:!fe||!M||ae||B||Xe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:w,fontSize:"1rem",fontWeight:600,cursor:!fe||!M||ae||B||Xe!=="ready"?"not-allowed":"pointer",opacity:!fe||!M||ae||B||Xe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...be??{}},children:ae?"Processing\u2026":`Pay with ${Fr(e)}`}),j&&c(Xr,{margin:"0.75rem 0 0",children:j})]})}function Ls({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:s,paymentElementBaseOptions:S,onTokenizedBody:f,onErrorChange:g,onButtonClick:b,onDecline:T,runBeforeButtonClick:B,onLoadStateChange:u,isProcessing:w=!1,submitButtonColor:be="#4A49FF",submitButtonBorderRadius:j=8,submitButtonStyle:P,buttonAppearance:me,themeId:Q,onExpandApm:le,expandedApmMethod:ae}){let{emitInstrument:ve}=to(Tn),[Ze,fe]=de(null),[Bt,Xe]=de(null),xe=he(!1),{request:Be,collect:ee,finish:te}=Yr();Pt(()=>{l.length>0&&s?u?.("ready"):s||u?.("loading")},[l.length,s,u]);let M=ye(async _=>{if(!s||xe.current||w)return;xe.current=!0,Xe(_);let ie=B?await B("card"):{proceed:!0};if(!ie.proceed){xe.current=!1,Xe(null);return}b?.("card");let Le=ie.sessionId??e,se=ie.nonce??t,K=Rr([ie.accountPatch?.firstName,ie.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ee=yn({email:ie.accountPatch?.email?.trim()||n?.trim(),firstName:ie.accountPatch?.firstName?.trim()||K.firstName,lastName:ie.accountPatch?.lastName?.trim()||K.lastName});if(!Xt(Ee.email)){Xe(null);let Me=await ee(Fr(_),Ee);if(!Me){xe.current=!1;return}Ee=Me,Xe(_)}let tt=Ee.email,st=yn({...ie.accountPatch,...Ee});try{if(g?.(null),!Le||!Xt(tt))throw new Error("Missing sessionId or email for payment.");await o?.(Ee);let Me=await pa(a,ve,Le,se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,paymentMethodId:null,intentKind:"payment"});if(Me.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let V=Me.clientSecret;if(typeof window<"u")try{localStorage.setItem(Qn,JSON.stringify({clientSecret:V,sessionId:Le,nonce:se,accountPatch:st,paymentMethodType:_,gateway:"stripe"}))}catch{}let{error:z,paymentIntent:L}=await s.confirmPayment({clientSecret:V,confirmParams:{return_url:window.location.href,payment_method_data:{type:_,billing_details:{name:[Ee.firstName,Ee.lastName].filter(Boolean).join(" "),...tt?{email:tt}:{}}}},redirect:"if_required"});if(z){if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let I=z.message??"Payment failed.";g?.(I),T?.(jt("card",I,{code:z.code})),await ma({billingApiUrl:a,sessionId:Le,nonce:se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,providerDeclineReason:z.code??"provider_declined"}});return}let ke=L?.status;if(!Qo(ke)){if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let I=ke==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(I),T?.(jt("card",I,{code:ke??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let He=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;f({id:He??L?.id,type:"card",threeDSecureActionResultTokenId:L?.id,gateway:"stripe",paymentMethodType:_},{accountPatch:st,sessionId:Le,nonce:se})}catch(Me){g?.(Me instanceof Error?Me.message:"Payment failed. Please try again.")}finally{xe.current=!1,Xe(null)}},[s,w,B,b,e,t,n,ee,a,ve,r,o,f,g,T]),[Ae,Fe]=de(null),De=le?ae??null:Ae,Ue=ye(_=>{xe.current||w||De&&De!==_||(Es(_)?le?le(_):Fe(_):M(_))},[De,w,M,le]),we=ft(()=>Ae?{...S,paymentMethodTypes:[Ae]}:null,[Ae,S]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Be?c(Wr,{identity:Be.identity,methodLabel:Be.methodLabel,onComplete:te,onCancel:()=>te(null)},Be.id):l.map(_=>{let ie=ae===_,Le=Bt===_,se=Bt!==null&&Bt!==_||ae!=null&&ae!==_;return Te(Tc.Fragment,{children:[c(qc,{method:_,themeId:Q,submitting:Le,disabled:se,highlighted:ie,hasNextStep:Es(_),onClick:()=>Ue(_),backgroundColor:me?.backgroundColor,borderColor:me?.borderColor,textColor:me?.textColor,borderRadius:me?.borderRadius,fontFamily:me?.fontFamily}),!le&&Ae===_&&we&&s&&c(Mr,{stripe:s,options:we,children:c(Za,{method:_,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:f,onErrorChange:g,onDecline:T,onCancel:()=>Fe(null),runBeforeButtonClick:B,onButtonClick:b,isProcessing:w,submitButtonColor:be,submitButtonBorderRadius:j,submitButtonStyle:P})},_)]},_)})})}function $c({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:s,onTokenizedBody:S,firstName:f,lastName:g,chv:b,className:T,isProcessing:B,error:u,onErrorChange:w,showPayPal:be=!0,showStripe:j=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:me,showApplePay:Q=!0,showGooglePay:le=!0,layout:ae="default",theme:ve,buttonsTheme:Ze,buttonsStyles:fe,appearance:Bt,cardButtonContent:Xe,cardBackButtonContent:xe,cardTitleContent:Be,showSecurityFooter:ee,onButtonClick:te,onBeforeButtonClick:M,onBuyerIdentityReady:Ae,enableAVS:Fe,cardFieldOrder:De,cardPreFormSlot:Ue,avsLayout:we="row",country:_,zip:ie,addressLine1:Le,addressLine2:se,city:K,state:Ee,onCountryChange:tt,onZipChange:st,avsCheck:Me,checkoutType:V,checkoutLayout:z,totalAmount:L=0,currency:ke="usd",initialCardOpen:He=!1,directPaypal:I,isSubscription:Y=!1,session:R,dataAttachmentPending:v=!1,dataAttachmentRequiresIdentity:rt=!1,debug:Ct=!1}){let ge=gr(),dt=Na(),Ie=to(Kn),{emitInstrument:ut}=to(Tn),Et=R??Ie.session,h=Et?.gateways?.paypal?.providerObjectType??I?.providerObjectType,H=v||Ie.claimPending===!0,Ye=rt||Ie.claimRequiresIdentity===!0,qe=H&&!Ye,zt=cs(),[Lt,U]=de(!1),[lt,tn]=de(null),[gt,Ut]=de(_??"US"),[Bn,Mn]=de(ie??""),[An,Zt]=de(Le??""),[Hn,fn]=de(se??""),[qt,rr]=de(K??""),[wt,Fn]=de(Ee??""),[ot,lr]=de(""),[kt,Pn]=de({}),It=he(ie??""),Yt=he(_??"US"),gn=he(Le??""),sn=he(se??""),Cn=he(K??""),nn=he(Ee??""),Sn=he(""),Nt=he({});Pt(()=>{let i=(k,D,_e,O,Re)=>{if(Nt.current[k])return;let ze=D?.trim();!ze||ze===_e.current||(_e.current=ze,O(ze),Re?.(ze))};i("country",_,Yt,Ut,tt),i("zip",ie,It,Mn,st),i("addressLine1",Le,gn,Zt),i("addressLine2",se,sn,fn),i("city",K,Cn,rr),i("state",Ee,nn,Fn)},[_,ie,Le,se,K,Ee,tt,st]);let J=ft(()=>kc(Fe),[Fe]),ln=J!==null,Dn=ft(()=>Ya(R),[R]),Yn=!!R?.vault?.html,Cr=!!R?.gateways?.pcivault,cr=!!(R?.gateways?.stripe?.enabledPaymentMethods??P)?.includes("card"),Mt=Yn||cr||Cr,$e=!!(j&&Mt&&ge&&e),[dr,C]=de(()=>ae!=="buttons"||He?e??null:null),[nt,$t]=de(0),hn=ae!=="buttons"||He||!!e&&dr===e,ue=ft(()=>!ge||!$e||!e||!hn?null:ge.cardCapture({sessionId:e,captureMethod:R?.captureMethod}),[ge,$e,e,hn,R?.captureMethod]),rn=ft(()=>{let i=gt,k=J?Ve(J.postal_code,i):!1;return Oc(i,Bn,k)},[J,gt,Bn]),{avsInvalid:wr,invalidAvsFields:Lr}=ft(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!$e||!J)return{avsInvalid:!1,invalidAvsFields:i};let k=gt,D=(Re,ze)=>Ve(Re,k)&&!ze.trim(),_e={line1:D(J.address_line_1,An),city:D(J.city,qt),state:D(J.state,wt),zip:rn.empty||rn.malformed};return{avsInvalid:_e.line1||_e.city||_e.state||_e.zip,invalidAvsFields:_e}},[$e,J,gt,An,qt,wt,rn]),[cn,ur]=de(!1),[Wn,Ln]=de(!1),[At,Nn]=de(!1),[Gn,dn]=de({line1:!1,city:!1,state:!1}),Qt=he(!1),On=he({email:!1,line1:!1,city:!1,state:!1,zip:!1}),zn=he(!1),at=ye(i=>{On.current[i]=!0,zn.current=!0},[]),un=ye(i=>!Qt.current&&On.current[i],[]),pn=ye(i=>{un(i)&&dn(k=>k[i]?k:{...k,[i]:!0})},[un]),[Un,wn]=de(()=>Wa(R?.vault)),[Pe,en]=de(He&&Mt?"card":"buttons"),[Ft,pr]=de(null),qn=Pe==="expanding"||Pe==="card",mr=R?.gateways?.stripe?"stripe":void 0,bn=ye(()=>{ut?.({class:"card_surface",provider:mr})},[mr,ut]),kn=he(null),Dt=ye(i=>{kn.current&&clearTimeout(kn.current),kn.current=setTimeout(()=>{kn.current=null,i()},Br)},[]);Pt(()=>()=>{kn.current&&clearTimeout(kn.current)},[]);let x=ye(()=>{bn(),C(e??null),$t(i=>i+1),en("expanding"),Dt(()=>en("card"))},[Dt,bn,e]),F=ye(()=>{en("collapsing"),Dt(()=>en("buttons"))},[Dt]),W=ye(i=>{pr(i),en("apm-expanding"),Dt(()=>en("apm-form"))},[Dt]),G=ye(()=>{en("apm-collapsing"),Dt(()=>{en("buttons"),pr(null)})},[Dt]);Pt(()=>{ae==="buttons"&&He&&Mt&&(C(e??null),en("card"))},[ae,He,Mt,e]);let[Ce,A]=de(null),q=he(!1),p=he(null),N=he("idle"),[$,ct]=de(null),pt=he($);Pt(()=>{pt.current=$},[$]);let ne=n||zt,Se=he(null),Wt=ft(()=>{if(Ae||Ie.claimBuyerIdentity||R?.buyerIdentified!==!1||!e||!t)return;let i=`${ne}|${e}|${t}`;Se.current?.key!==i&&(Se.current={key:i,claim:Vr(new eo(ne,{telemetry:!1}),e,t,{...o?{userId:o}:{},...f?{firstName:f}:{},...g?{lastName:g}:{}})});let k=Se.current.claim;return async D=>{await k(D)}},[Ae,Ie.claimBuyerIdentity,R?.buyerIdentified,e,t,ne,o,f,g]),Qe=Ae??Ie.claimBuyerIdentity??Wt,m=u??lt,d=ft(()=>Ec(ve),[ve]),y=ft(()=>{let i=d?.buttonsLayout??Ic(Ze);return fe?{...i,...fe,cardButton:{...i.cardButton,...fe.cardButton},cardFormContainer:{...i.cardFormContainer,...fe.cardFormContainer},backButton:{...i.backButton,...fe.backButton},backButtonIcon:{...i.backButtonIcon,...fe.backButtonIcon},submitButton:{...i.submitButton,...fe.submitButton},title:{...i.title,...fe.title}}:i},[d,Ze,fe]),pe=Bt??d?.appearance,re=ft(()=>Xi({appearance:pe,buttonsStyles:y,layout:ae}),[pe,y,ae]),je=Ie.inlineSessionPatchProcessing??!1,We=(B??Lt)||je,X=ne.replace(/\/+$/,""),E=ft(()=>La({userId:o,email:r,firstName:f,lastName:g,country:_,zip:ie},kt),[o,r,f,g,_,ie,kt]),oe=[E.firstName,E.lastName].filter(i=>!!i?.trim()).join(" "),Ke=!Xt(E.email?.trim()),Ne=he(null);$e&&Ne.current===null&&(Ne.current=Ke);let mt=$e&&(Ne.current??Ke),Oe=ft(()=>zc(ot,mt),[ot,mt]),Ot=Oe.empty||Oe.malformed,vn=ft(()=>ge?ge.getRawProvider():null,[ge]),Nr=ft(()=>dt?dt.getRawProvider():null,[dt]),io=L||100,Oo=ft(()=>pe?pc(pe):null,[pe]),zo=Oo?{appearance:Oo}:null,bi=ft(()=>{let i=Oo??{},k=i.rules??{};return{...i,rules:{...k,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...k[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...k[".AccordionItemContents"]??{}}}}},[Oo]),vi=ft(()=>{let i=rs(L);return{...i,currency:ke.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...zo}},[L,ke,zo]),Pi=ft(()=>({mode:"payment",amount:io,currency:ke.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...zo}),[io,ke,zo]),ce=ye(i=>{tn(i),w?.(i)},[w]),ba=he(""),[Ci,el]=de(!1),va=ye(()=>{el(!0)},[]);Pt(()=>{if(!$e||!mt||!Qe||!Ci||Ot||ba.current)return;let i=yn({email:Xt(E.email?.trim())?E.email?.trim():Sn.current.trim(),firstName:E.firstName?.trim(),lastName:E.lastName?.trim()});ba.current=JSON.stringify(i),Pn(k=>({...k,...i})),Promise.resolve(Qe(i)).catch(k=>{ba.current="",ce(k instanceof Error?k.message:"Failed to attach buyer details.")})},[$e,mt,Qe,Ci,Ot,E.email,E.firstName,E.lastName,ce]),Pt(()=>{!$e||!ue||ue.setCardFieldOrder?.(De??null,J==null&&!mt)},[$e,ue,De,J,mt]),Pt(()=>{(Pe==="expanding"||Pe==="collapsing"||Pe==="apm-expanding"||Pe==="apm-collapsing")&&ce(null)},[Pe,ce]);let $n=ye((i,k,D)=>{s?.(jt(i,k,D))},[s]),Or=ye((i,k,D)=>{let _e=D?.popupBlocked??fr(k),O=Lc(i,_e),Re=_r(D?.code)??or(k)??"external_payment_method_failed",ze=new Vn(O,"api_error",{code:"external_payment_method_failed",param:i});A(null),ae==="buttons"&&(en("buttons"),pr(null)),ce(O),l?.(ze),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:_e})},[ae,l,ce]);Pt(()=>{if(!$e||!e){wn(null);return}let i=Wa(R?.vault);if(i){wn(i);return}if(!hn){wn(null);return}wn(null);let k=!0;return new eo(X).getVaultCapture(e,t).then(D=>{if(!k)return;let _e=Wa(D);_e?wn(_e):ce("Failed to load the secure card form.")}).catch(D=>{k&&ce(D instanceof Error?D.message:"Failed to load the secure card form.")}),()=>{k=!1}},[$e,hn,nt,e,R?.vault,X,t,ce]);let Jn=he({onComplete:a,onError:l,updateError:ce,emitDecline:$n,resolvedAccount:E,avsConfig:J,avsCheckProp:Me,sessionId:e,nonce:t,baseUrl:X,captureMethod:R?.captureMethod,paymentId:R?.paymentId,authorizationExpiresAt:R?.authorizationExpiresAt});Jn.current={onComplete:a,onError:l,updateError:ce,emitDecline:$n,resolvedAccount:E,avsConfig:J,avsCheckProp:Me,sessionId:e,nonce:t,baseUrl:X,captureMethod:R?.captureMethod,paymentId:R?.paymentId,authorizationExpiresAt:R?.authorizationExpiresAt};let Pa=he(!1),Si=ye(()=>{let{resolvedAccount:i,avsConfig:k,avsCheckProp:D}=Jn.current,_e=i.email?.trim(),O=Xt(_e)?_e:Sn.current.trim();if(!Xt(O))return null;let Re=i.firstName?.trim(),ze=i.lastName?.trim(),it=Yt.current||i.country||"US",Gt=k?Ve(k.state,it):!1,ht=k?Ve(k.address_line_1,it):!1,bt=k?Ve(k.postal_code,it):!1,et=k?Ve(k.city,it):!1,on=k?Ve(k.address_line_2,it):!1,Ge=ht&&!Gt&&bt?Rs(it,(It.current??"").trim()):null,an=Gt?nn.current:Ge;return{accountData:{userId:i.userId??"",email:O,...Re?{firstName:Re}:{},...ze?{lastName:ze}:{},...bt&&It.current?{zip:It.current}:{},...et&&Cn.current?{city:Cn.current}:{},...an?{state:an}:{},...ht&&gn.current?{addressLine1:gn.current}:{},...on&&sn.current?{addressLine2:sn.current}:{},country:it},...D!==void 0?{avsCheck:D}:{},...k?{avsConfig:{country:Ve(k.country,it),postal_code:bt,address_line_1:ht,address_line_2:on,city:et,state:Gt}}:{}}},[]),wi=he(H);wi.current=H,Pt(()=>{H||m!==xs||Jn.current.updateError(null)},[H,m]),Pt(()=>{!$e||!ue||ue.setSubmitGate?.(wr||H||Ot)},[$e,ue,wr,H,Ot]),Pt(()=>{if(!$e||!ue)return;Pa.current=!1;let i=!1,k=ue.on("submitting",()=>{ur(!0),p.current&&clearTimeout(p.current),N.current="validation-window",p.current=setTimeout(()=>{p.current=null,N.current==="validation-window"&&(N.current="processing")},xc),A("processing");let{baseUrl:ze,sessionId:it,nonce:Gt,updateError:ht,onError:bt}=Jn.current;if(!it||!Gt)return;let et=Si();if(!et){ht("Enter a valid email address."),N.current="idle",A(null);return}new eo(ze).patchAccountSnapshot(it,Gt,et,{telemetryMode:"best_effort"}).catch(on=>{if(!Bc(on))return;let Ge=on instanceof Error?on.message:"Please check your billing address and try again.";ht(Ge),N.current="idle",A(null),bt?.(on instanceof Vn?on:new Vn(Ge,"api_error"))})}),D=ue.on("complete",async ze=>{if(Zr(ze.sessionId??Jn.current.sessionId),N.current="terminal",A("success"),await new Promise(ht=>setTimeout(ht,1200)),Pa.current)return;Pa.current=!0;let it=Jn.current,Gt=Ya(it)||ze.outcome==="authorized";Jn.current.onComplete?.(Gt?{status:"authorized",paymentIntentId:ze.intentId,paymentId:ze.paymentId??it.paymentId,sessionId:ze.sessionId??it.sessionId,authorizationExpiresAt:ze.authorizationExpiresAt??it.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:ze.intentId,checkoutMethod:"card"})}),_e=ue.on("decline",async ze=>{let{updateError:it,emitDecline:Gt}=Jn.current,ht=ze.message??"Your payment was declined. Please try another card or contact your bank.";N.current="terminal",it(ht),A("error");let bt=ze.failureOutcome??Sc(ze.declineReason)??"authorization_declined";Gt("card",ht,{code:bt,declineCode:bt}),await new Promise(et=>setTimeout(et,1500)),!i&&(N.current="idle",A(null))}),O=ue.on("error",async ze=>{let{updateError:it,onError:Gt}=Jn.current,ht=ze.message??"There was a problem processing your payment. Please try again.";N.current="terminal",it(ht),A("error"),Gt?.(new Vn(ht,"api_error",{code:ze.failureOutcome??"capture_failed"})),await new Promise(bt=>setTimeout(bt,1500)),!i&&(N.current="idle",A(null))}),Re=ue.on("blocked",()=>{if(!wi.current){ur(!0);return}va(),Jn.current.updateError(xs)});return()=>{i=!0,p.current&&(clearTimeout(p.current),p.current=null),N.current="idle",k(),D(),_e(),O(),Re()}},[$e,ue,va,Si]);let Xn=!!I?.clientId,so=Array.isArray(P),Uo=so&&P.length>0,tl=so&&P.includes("paypal"),{expressMethods:qo,paymentElementMethods:lo}=ft(()=>wc(P,{excludePaypal:Xn}),[P,Xn]),ki=Xn||!!dt,nl=ft(()=>ki?qo.filter(i=>i!=="paypal"):qo,[qo,ki]),rl=ft(()=>{let i=[];return Q&&i.push("apple_pay"),le&&i.push("google_pay"),i},[Q,le]),$o=so?nl:rl,ol=j&&$o.length>0,Ca=ln?gt:_,jo=ft(()=>{let i=Ca?.trim().toUpperCase();return i?me?lo.filter(k=>{let D=me[k];return!D||D.length===0||D.includes(i)}):fc(lo,Ca):lo},[lo,Ca,me]),Sa=ft(()=>({mode:"payment",amount:io,currency:ke.toLowerCase(),paymentMethodCreation:"manual",appearance:bi}),[io,ke,bi]),[Ii,Ri]=de("loading"),[Ei,_i]=de("loading"),[Ti,xi]=de("loading"),[al,wa]=de(!1),[Bi,ka]=de("loading"),[Ko,il]=de();Pt(()=>{il(ks())},[]);let Mi=be&&(Xn||(so?tl:Ko===!1)),Ai=j&&ol,co=!qe&&Mi&&Xn,Fi=Bi==="retrying"||Bi==="exhausted",uo=!qe&&Mi&&!!Nr&&(!Xn||Fi),po=!qe&&Ai&&!!vn,mo=!qe&&j&&Uo&&jo.length>0&&!!vn,sl=co&&!Fi?al:uo&&As(Ii),ll=po&&As(Ei),cl=mo&&Ti!=="load_error",Di=i=>i==="loading"||i==="ready",Li=co||uo&&Di(Ii)||po&&Di(Ei)||mo&&Ti!=="load_error",Vo=he(!1);Pt(()=>{if(!Vo.current){if(!j&&!be){Vo.current=!0;let i=new Vn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),ce(i.message)}else if(!j&&be&&!Xn&&!Nr){Vo.current=!0;let i=new Vn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(i),ce(i.message)}else if(Ko!==void 0&&!qe&&!Mt&&!Li){Vo.current=!0;let i=new Vn("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),ce(i.message)}}},[j,be,Xn,Nr,Ko,qe,Mt,Li,l,ce]);let Ni=he(!1);Pt(()=>{if(Ni.current||!Uo)return;let i=[];Q!==!0&&i.push("showApplePay"),le!==!0&&i.push("showGooglePay"),i.length!==0&&(Ni.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.`))},[Uo,Q,le]);let Oi=ye((i,k)=>Ie.applyInlineSessionPatch?Ie.applyInlineSessionPatch(i).then(D=>({error:null,sessionId:D.sessionId||e,nonce:D.session?.clientSecret||t})).catch(D=>{let _e=Ms(k,D);return ce(_e.message),l?.(_e),{error:_e,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ie.applyInlineSessionPatch,t,l,e,ce]),jn=ye(async i=>{if(!M)return{proceed:!0};try{let k=await M({method:i,sessionId:e||void 0,createSession:Ie.inlineSessionDraft});if(k===!1)return{proceed:!1};if(k&&typeof k=="object"){k.account&&Pn(_e=>({..._e??{},...k.account}));let D=await Oi(k,i);return D.error?{proceed:!1,accountPatch:k.account}:{proceed:!0,accountPatch:k.account,sessionId:D.sessionId,nonce:D.nonce}}return{proceed:!0}}catch(k){let D=Ms(i,k);return ce(D.message),l?.(D),{proceed:!1}}},[Oi,Ie.inlineSessionDraft,M,l,e,ce]),zi=ye(async(i,k)=>{if(q.current)return;q.current=!0,U(!0),A("processing"),ce(null);let D=k?.sessionId??e,_e=k?.nonce??t,O=La(E,k?.accountPatch),Re=k?.completionPaymentMethodId??So(i),ze=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,it=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Gt=()=>{ut?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:it})};try{let bt=await new eo(X).processPayment(O.userId??"",{sessionId:D,nonce:_e,tokenizedData:ze,accountData:{userId:O.userId??"",email:O.email??"",...O.firstName?{firstName:O.firstName}:{},...O.lastName?{lastName:O.lastName}:{},...J?(()=>{let Ge=Yt.current,an=Ve(J.state,Ge),En=Ve(J.address_line_1,Ge),Jt=Ve(J.postal_code,Ge),bo=En&&!an&&Jt?Rs(Ge,(It.current??"").trim()):null,vo=an?nn.current:bo;return{country:Ge,...Jt&&It.current?{zip:It.current}:{},...Ve(J.city,Ge)&&Cn.current?{city:Cn.current}:{},...vo?{state:vo}:{},...En&&gn.current?{addressLine1:gn.current}:{},...Ve(J.address_line_2,Ge)&&sn.current?{addressLine2:sn.current}:{}}})():{}},chv:b,avsCheck:Me??!1,checkoutType:V,checkoutLayout:z,avsConfig:J?{country:Ve(J.country,Yt.current),postal_code:Ve(J.postal_code,Yt.current),address_line_1:Ve(J.address_line_1,Yt.current),address_line_2:Ve(J.address_line_2,Yt.current),city:Ve(J.city,Yt.current),state:Ve(J.state,Yt.current)}:void 0});if(bt.ok){let Ge=bt.status===204?null:await bt.json().catch(()=>null),an=Ya(R)||Ge?.status==="authorized";Zr(D),A("success"),ct(null),await new Promise(En=>setTimeout(En,1200)),a?.(an?{status:"authorized",...typeof Ge?.paymentId=="string"?{paymentId:Ge.paymentId}:R?.paymentId?{paymentId:R.paymentId}:{},sessionId:typeof Ge?.sessionId=="string"?Ge.sessionId:D,...typeof Ge?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Ge.authorizationExpiresAt}:R?.authorizationExpiresAt?{authorizationExpiresAt:R.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"});return}let et=await bt.json().catch(()=>null);if(et?.type==="paypal_redirect_required"){let Ge=et.threeDSecureToken,an=et.paymentMethodId||i.id||"";if(!ge||!Ge){A("error"),ce("PayPal authorization required but no token provided.");return}try{let En=dt?.getRawProvider();if(!En){ce("PayPal is not available.");return}let Jt={return_url:window.location.href};an&&(Jt.payment_method=an);let{error:bo}=await En.confirmPayment({clientSecret:Ge,confirmParams:Jt,redirect:"if_required"});if(bo){A("error");let vo=bo.message??"PayPal payment failed.";ce(vo),$n("paypal",vo,{code:bo.code})}}catch(En){A("error"),ce(En instanceof Error?En.message:"PayPal authorization failed.")}return}if(et?.type==="paypal_direct_required"){let Ge=et.orderId;if(!Ge){A("error"),ce("PayPal retry required but no order id provided.");return}let an=pt.current?.attempts??0;if(an>=2){A("error"),ce("PayPal payment could not be completed after multiple attempts."),$n("paypal","paypal_direct_required retry limit exceeded");return}wa(!1),ka("loading"),ct({orderId:Ge,attempts:an+1}),A(null);return}yc(bt.status,et)||Gt(),A("error");let on=et?.message??"Payment failed. Please try again.";ce(on),$n(i.isPaypal?"paypal":"card",on,{code:et?.code??et?.gatewayErrorCode,declineCode:et?.declineCode??et?.gatewayDeclineReason}),await new Promise(Ge=>setTimeout(Ge,1500))}catch(ht){Os(ht)||Gt(),A("error"),ce(ht instanceof Error?ht.message:"An unexpected error occurred"),await new Promise(bt=>setTimeout(bt,1500))}finally{U(!1),A(null),q.current=!1}},[X,e,t,E,J,Me,V,z,b,ge,dt,R,a,ce,$n,ut]),In=ye((i,k)=>{S?S(i):zi(i,k)},[S,zi]),Ui=he(!1);Pt(()=>{if(typeof window>"u"||Ui.current)return;let i=new URLSearchParams(window.location.search),k=i.get("payment_intent"),D=i.get("payment_intent_client_secret"),_e=i.get("redirect_status");if(!k||!D)return;let O=bt=>{let et=localStorage.getItem(bt);if(!et)return null;try{return JSON.parse(et)}catch{return localStorage.removeItem(bt),null}},Re=O(Qn)??O(Ts),ze;if(Re?.clientSecret){if(Re.clientSecret!==D)return;ze={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;Ui.current=!0,localStorage.removeItem(Qn),localStorage.removeItem(Ts);let it=new URL(window.location.href);it.searchParams.delete("payment_intent"),it.searchParams.delete("payment_intent_client_secret"),it.searchParams.delete("redirect_status"),window.history.replaceState({},"",it.toString());let Gt=Re?.paymentMethodType??Re?.tokenType??"card",ht="card";(async()=>{let bt=ge?.getRawProvider();if(!bt){let Jt="Payment is not available \u2014 please refresh and try again.";ce(Jt),$n(ht,Jt);return}if(_e==="failed"){let Jt="Payment was declined. Please try again.";ce(Jt),$n(ht,Jt);return}let{paymentIntent:et,error:on}=await bt.retrievePaymentIntent(D);if(on){let Jt=on.message??"Failed to retrieve payment status.";ce(Jt),$n(ht,Jt,{code:on.code});return}let Ge=et?.status,an=Qo(Ge);if(!et||!an){let Jt=Ge==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ce(Jt),$n(ht,Jt,{code:Ge??"missing_payment_intent"});return}let En=typeof et.payment_method=="string"?et.payment_method:et.payment_method?.id;In({id:En??Re?.paymentMethodId??Re?.tokenId??et.id,type:"card",threeDSecureActionResultTokenId:et.id,gateway:Re?.gateway??"stripe",paymentMethodType:Gt},ze)})()},[e,In,ge,ce,$n]);let Ia=ye(i=>{i.preventDefault()},[]);if(!(ge!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let yo=ae==="buttons",mn=pe?.variables,dl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ra=mn?.colorBackground,ul=Ra&&!dl.has(Ra)?Ra:void 0,fo=y.cardInputBorder??(yo?"#e5e7eb":"#A4A4FF"),qi=mn?.colorDanger??"#dc2626",Rt=i=>Lr[i]&&(Gn[i]||cn),Ho=Ot&&(At||cn),Rn=i=>i?qi:fo,Yo=(rn.malformed||rn.empty)&&(Wn||cn),pl=Rn(Yo),Ea=y.cardFormContainer?.backgroundColor??ul??(yo?"white":"#EDEDFF"),zr=y.cardInputBackground??mn?.colorBackground??"white",_a=qr(xe),$i=qr(Be),Ur=y.nameInput,ji=y.cardInputFontSize??Uc(Ur?.fontSize)??mn?.fontSizeBase??"16px",Ki=typeof Ur?.fontFamily=="string"?Ur.fontFamily:mn?.fontFamily??"Poppins, sans-serif",Vi=Ji(Ur?.fontWeight)??400,ml=y.cardInputColor??(typeof Ur?.color=="string"?Ur.color:void 0)??mn?.colorText??"#262833",yl=y.cardInputPlaceholderColor??"#9ca3af",_t=mn?.borderRadius??"8px",kr=mn?.borderRadius??y.cardButton?.borderRadius??_t,Ir=mn?.colorPrimary??"#4A49FF",fl=mn?.colorPrimaryHover??Po(Ir,.12),Ta=mn?.colorText??"#262833",xa={fontSize:ji,fontFamily:Ki,fontWeight:Vi,color:ml,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},go={marginTop:"0.375rem",...xa,fontSize:"0.75rem",lineHeight:1.4,color:qi},gl={"--flopay-input-placeholder-color":yl,"--flopay-input-font-size":ji,"--flopay-input-font-family":Ki,"--flopay-input-font-weight":String(Vi)},ho=y.cardFormContainer??{},Ba=ho.padding??(yo?"0":"1rem"),Ma=ho.borderRadius??_t,hl=ue&&Un?c(Aa,{capture:ue,html:Un.html,messageToken:Un.messageToken,expectedOrigin:Un.expectedOrigin,theme:re,onReady:()=>{if(!mt&&!J||typeof document>"u")return;let i=()=>{let D=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(D){Qt.current=!0;try{D.focus()}finally{Qt.current=!1}}};zn.current||i()},onError:i=>ce(i),onValidation:i=>{let k=N.current;(k==="idle"||k==="validation-window")&&(ce(i),i&&N.current==="validation-window"&&(p.current&&(clearTimeout(p.current),p.current=null),N.current="idle",A(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"}),Hi=Te("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&bn()},style:{backgroundColor:Ea,borderRadius:Ma,...ho,padding:Ba,...gl,display:"flex",flexDirection:"column"},children:[c("style",{children:`
|
|
25
|
+
`,ua=44,Mr=280;function ni(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var Ac={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Fc(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 Us={width:"100%",minHeight:ua,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 Dc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ms(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Xa(e){return e==="paypal"?"PayPal":Fr(e)}function Lc(e,t){let n=`We couldn't open ${Xa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function qs(e){let t=he(0),n=he(null),r=he(null),o=ye((u=r.current)=>{let k=u;k?.timer&&(clearTimeout(k.timer),k.timer=null)},[]),a=ye((u,k)=>{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"}))},k))},[o,e]),l=ye(u=>{u.yieldedControl&&a(u,600)},[a]),s=ye(u=>{o();let k=t.current+1;t.current=k,n.current=null;let be={generation:k,method:u,timer:null,yieldedControl:!1};return r.current=be,k},[o]),w=ye(u=>{let k=r.current;return typeof u=="number"&&k?.generation!==u?!1:(o(k),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),f=ye(u=>{let k=r.current,be=u??k?.generation??t.current;(!u||k?.generation===u)&&(o(k),r.current=null),n.current=be},[o]),g=ye(u=>n.current===(u??t.current),[]),b=ye(u=>r.current?.generation===u&&n.current!==u,[]),T=ye(()=>{let u=r.current;u&&l(u)},[l]),M=ye(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return Pt(()=>{let u=()=>{document.visibilityState==="visible"?T():M()},k=()=>{M()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",k),window.addEventListener("focus",T),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",k),window.removeEventListener("focus",T),o()}},[o,M,T]),{startAttempt:s,finishAttempt:w,invalidateAttempt:f,isAttemptInvalidated:g,isAttemptCurrent:b}}function Nc(e){let t=fc(e);return`Enter a valid ${Ja(e)}${t?` (e.g. ${t})`:""}`}function Oc(e,t,n){let r=bc(e),o=t.trim(),a=n&&r,l=a&&!o,s=a&&!!o&&!Pc(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:s}}function zc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!Xt(n);return{required:t,empty:r,malformed:o,value:n}}function Bs(e,t){return t instanceof Vn?t:new Vn(t instanceof Error?t.message:`${Dc(e)} before-click hook failed.`,"validation_error")}function Ga(){return c("style",{children:Bc})}function Uc(e){return typeof e=="number"?`${e}px`:e}function $s(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function js({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 As(e){return e!=="unavailable"&&e!=="load_error"}function ri(e){return c($c,{...e})}function Fs({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:s,onDecline:w,onTechnicalFailure:f,runBeforeButtonClick:g,billingName:b,onBuyerIdentityReady:T,onLoadStateChange:M,placeholderBorderRadius:u}){let k=gr(),{emitInstrument:be}=to(Tn),j=ei(),P=Qa(),[me,Q]=de("loading");Pt(()=>{M?.(me)},[me,M]);let[le,ae]=de(!1),ve=!Xt(n?.trim())||!b?.trim(),{request:Ze,collect:fe,finish:Mt}=Yr(),Xe=he(!1),xe=he(null),Me=he(null),[ee,te]=de(0),[B,Ae]=de(!1),Fe=he(!1),De=he(new Map),{startAttempt:Ue,finishAttempt:we,invalidateAttempt:_,isAttemptInvalidated:ie,isAttemptCurrent:Le}=qs((V,z,L)=>{f?.(V,z,{...L,popupBlocked:L?.popupBlocked??fr(z)}),Ae(!0),te(ke=>ke+1)});Pt(()=>{B&&Me.current?.focus()},[B,ee]);let se=ye(()=>{te(V=>V+1)},[]),K=ye((V,z,L)=>{_(L),f?.("paypal",V,{code:z,popupBlocked:fr(V)}),Ae(!0),se()},[_,f,se]),Ee=ye(()=>{window.setTimeout(()=>{(xe.current?.querySelector("iframe")??xe.current)?.focus()},0)},[]);Pt(()=>{Fe.current&&(Fe.current=!1,Ee())},[Ee,ee]);let tt=ye(()=>{Ae(!1),a?.(null),Ee()},[Ee,a]);Pt(()=>{if(!j||Xe.current)return;let V=new URLSearchParams(window.location.search),z=V.get("payment_intent"),L=V.get("payment_intent_client_secret"),ke=V.get("redirect_status");if(!z||!L)return;Xe.current=!0;let He;try{let Y=localStorage.getItem(Bo);if(Y){let R=JSON.parse(Y);R.clientSecret===L&&(He={...R.accountPatch?{accountPatch:R.accountPatch}:{},...R.sessionId?{sessionId:R.sessionId}:{},...R.nonce?{nonce:R.nonce}:{}})}}catch{}try{localStorage.removeItem(Bo)}catch{}let I=new URL(window.location.href);I.searchParams.delete("payment_intent"),I.searchParams.delete("payment_intent_client_secret"),I.searchParams.delete("redirect_status"),window.history.replaceState({},"",I.toString()),(async()=>{try{if(ae(!0),ke==="failed"){let v="PayPal payment was declined. Please try again.";a?.(v),w?.(jt("paypal",v));return}let{paymentIntent:Y,error:R}=await j.retrievePaymentIntent(L);if(R){a?.(R.message??"Failed to retrieve PayPal payment status.");return}if(Y&&(Y.status==="requires_capture"||Y.status==="succeeded")){let v=typeof Y.payment_method=="string"?Y.payment_method:Y.payment_method?.id;o({id:v??Y.id,type:"card",threeDSecureActionResultTokenId:Y.id,isPaypal:!0},He)}else{let v="PayPal payment was not completed. Please try again.";a?.(v),w?.(jt("paypal",v))}}catch(Y){a?.(Y instanceof Error?Y.message:"Failed to complete PayPal payment.")}finally{ae(!1)}})()},[j,o,a,w]);let st=ye(async V=>{if(l||le){V.reject();return}let z=g?await g("paypal"):{proceed:!0};if(!z.proceed){De.current.delete(ee),V.reject();return}let L=Ue("paypal");De.current.set(ee,{generation:L,accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}),Ae(!1),s?.("paypal"),V.resolve()},[l,s,g,Ue,le,ee]),Be=ye(async V=>{if(!j||!P)return;let z=De.current.get(ee);if(z&&!Le(z.generation)){De.current.delete(ee);return}if(!z&&ie()||z&&!we(z.generation))return;z||we();let L=z??null;if(De.current.delete(ee),!L&&g){let v=await g("paypal");if(!v.proceed){V.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}L={accountPatch:v.accountPatch,sessionId:v.sessionId,nonce:v.nonce}}let ke=L?.sessionId??e,He=L?.nonce??t,I=await zs({event:V,prepared:L,email:n,billingName:b,methodLabel:"PayPal",collect:fe});if(!I){V.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Y=I.email,R=yn({...L?.accountPatch,...I});try{if(ae(!0),a?.(null),!ke||!Xt(Y))throw new Error("Missing sessionId or email for PayPal payment");await T?.(I);let v=j.createPaymentMethod,{error:rt,paymentMethod:Ct}=await v({type:"paypal"});if(rt){K(rt,"stripe_paypal_create_payment_method_failed",z?.generation),V.paymentFailed({reason:"fail"});return}let ge=await pa(r,be,ke,He??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Ct?.id??null,intentKind:"payment"});if(ge.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let dt=ge.clientSecret,Ie={return_url:window.location.href};if(Ct?.id&&(Ie.payment_method=Ct.id),typeof window<"u")try{localStorage.setItem(Bo,JSON.stringify({clientSecret:dt,sessionId:ke,nonce:He,accountPatch:R}))}catch{}let{error:ut,paymentIntent:Et}=await j.confirmPayment({clientSecret:dt,confirmParams:Ie,redirect:"if_required"});if(ut){if(typeof window<"u")try{localStorage.removeItem(Bo)}catch{}if(ko(ut)){let H=ut.message??"Your payment was declined.";a?.(H),w?.(jt("paypal",H,{code:or(ut),declineCode:Gr(ut)})),await ma({billingApiUrl:r,sessionId:ke,nonce:He,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:or(ut)??"provider_declined"}})}else K(ut,"stripe_paypal_confirm_failed",z?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Bo)}catch{}let h=typeof Et?.payment_method=="string"?Et.payment_method:Et?.payment_method?.id;o({id:h??Et?.id,type:"card",threeDSecureActionResultTokenId:Et?.id,isPaypal:!0},{accountPatch:R,paymentMethodCategory:"paypal",sessionId:ke,nonce:He});return}catch(v){K(v,"stripe_paypal_failed",z?.generation)}finally{ae(!1)}},[j,P,e,t,n,b,fe,T,r,be,o,a,w,g,K,we,Le,ie,ee]);return Te(Ar,{children:[c(js,{state:me,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:[B&&c("button",{ref:Me,type:"button","data-testid":"flopay-paypal-retry-button",onClick:tt,style:Us,children:"Try PayPal again"}),Ze&&c(Wr,{identity:Ze.identity,methodLabel:Ze.methodLabel,onComplete:Mt,onCancel:()=>Mt(null)},Ze.id),c("div",{style:{display:Ze?"none":void 0},children:c(Ns,{onReady:V=>Q($s(V,["paypal"])),onLoadError:()=>{Q("load_error"),ti(Kt(k),"paypal","paypal")},onClick:st,onConfirm:Be,onCancel:()=>{let V=De.current.get(ee);De.current.delete(ee),Kt(k)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),_(V?.generation),Ae(!1),Fe.current=!0,se()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ve,emailRequired:ve,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),le&&c(Zn,{status:"processing"})]})}function Ds({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:s,onButtonClick:w,onDecline:f,onTechnicalFailure:g,runBeforeButtonClick:b,billingName:T,onBuyerIdentityReady:M,onLoadStateChange:u,placeholderBorderRadius:k}){let be=gr(),{emitInstrument:j}=to(Tn),P=ei(),me=Qa(),[Q,le]=de("loading");Pt(()=>{u?.(Q)},[Q,u]);let[ae,ve]=de(!1),Ze=!Xt(n?.trim())||!T?.trim(),{request:fe,collect:Mt,finish:Xe}=Yr(),xe=he(null),Me=he(null),[ee,te]=de(0),[B,Ae]=de(!1),[Fe,De]=de("google_pay"),Ue=he(!1),we=he("google_pay"),_=he("google_pay"),ie=he(new Map),{startAttempt:Le,finishAttempt:se,invalidateAttempt:K,isAttemptInvalidated:Ee,isAttemptCurrent:tt}=qs((I,Y,R)=>{g?.(I,Y,{...R,popupBlocked:R?.popupBlocked??fr(Y)}),De(I),Ae(!0),te(v=>v+1)});Pt(()=>{B&&Me.current?.focus()},[B,ee]);let st=ye(()=>{te(I=>I+1)},[]),Be=ye((I,Y,R,v)=>{K(v),g?.(I,Y,{code:R,popupBlocked:fr(Y)}),De(I),Ae(!0),st()},[K,g,st]),V=ye(()=>{window.setTimeout(()=>{(xe.current?.querySelector("iframe")??xe.current)?.focus()},0)},[]);Pt(()=>{Ue.current&&(Ue.current=!1,V())},[V,ee]);let z=ye(()=>{Ae(!1),s?.(null),V()},[V,s]),L=ye(async I=>{if(!P||!me)return;let Y=ie.current.get(ee);if(Y&&!tt(Y.generation)){ie.current.delete(ee);return}if(!Y&&Ee()||Y&&!se(Y.generation))return;Y||se();let R=I.expressPaymentType??Y?.method??we.current,v=Y??null;ie.current.delete(ee);let rt=Ms(R);if(!v&&b){let h=await b(rt);if(!h.proceed){I.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}v={accountPatch:h.accountPatch,sessionId:h.sessionId,nonce:h.nonce}}let Ct=rt,ge=v?.sessionId??e,dt=v?.nonce??t,Ie=await zs({event:I,prepared:v,email:n,billingName:T,methodLabel:Xa(R),collect:Mt});if(!Ie){I.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ut=Ie.email,Et=yn({...v?.accountPatch,...Ie});try{if(ve(!0),s?.(null),!Xt(ut))throw new Error("Missing sessionId or email for wallet payment");await M?.(Ie);let{error:h}=await me.submit();if(h){Be(R,h,"stripe_wallet_submit_failed",Y?.generation);return}let{error:H,paymentMethod:Ye}=await P.createPaymentMethod({elements:me});if(H||!Ye){Be(R,H??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",Y?.generation);return}if(!ge)throw new Error("Missing sessionId or email for wallet payment");let qe=await pa(r,j,ge,dt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:R??rt,paymentMethodId:Ye.id,intentKind:o});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let zt=qe.clientSecret,{error:Lt,intentId:U}=vc(zt)?await P.confirmCardSetup(zt,{payment_method:Ye.id}).then(lt=>({error:lt.error,intentId:lt.setupIntent?.id})):await P.confirmCardPayment(zt,{payment_method:Ye.id}).then(lt=>({error:lt.error,intentId:lt.paymentIntent?.id}));if(Lt){if(ko(Lt)){let lt=Lt.message??"Your payment was declined.";s?.(lt),f?.(jt(Ct,lt,{code:or(Lt),declineCode:Gr(Lt)})),await ma({billingApiUrl:r,sessionId:ge,nonce:dt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:R??rt,providerDeclineReason:or(Lt)??"provider_declined"}})}else Be(R,Lt,"stripe_wallet_confirm_failed",Y?.generation);return}l({id:Ye.id,type:"card",threeDSecureActionResultTokenId:U},{accountPatch:Et,paymentMethodCategory:"wallet",sessionId:ge,nonce:dt})}catch(h){Be(R,h,"stripe_wallet_failed",Y?.generation)}finally{ve(!1)}},[P,me,e,t,n,T,Mt,M,r,j,o,l,s,f,b,Be,se,tt,Ee,ee]),ke=ft(()=>{let I=["applePay","googlePay","paypal","link","amazonPay","klarna"],Y=new Set(["applePay","googlePay"]),R=new Set(a.map(_s)),v={};for(let rt of I)R.has(rt)?v[rt]=Y.has(rt)?"always":"auto":v[rt]="never";return v},[a]),He=ft(()=>a.map(_s),[a]);return Te(Ar,{children:[c(js,{state:Q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:k,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:[B&&Te("button",{ref:Me,type:"button","data-testid":"flopay-wallet-retry-button",onClick:z,style:Us,children:["Try ",Xa(Fe)," again"]}),fe&&c(Wr,{identity:fe.identity,methodLabel:fe.methodLabel,onComplete:Xe,onCancel:()=>Xe(null)},fe.id),c("div",{style:{display:fe?"none":void 0},children:c(Ns,{onReady:I=>{le($s(I,He))},onLoadError:I=>{le("load_error"),ti(Kt(be),"stripe","wallet")},onClick:async I=>{we.current=I.expressPaymentType,_.current=Ms(I.expressPaymentType);let Y=b?await b(_.current):{proceed:!0};if(!Y.proceed){ie.current.delete(ee),I.reject();return}let R=Le(I.expressPaymentType);ie.current.set(ee,{generation:R,method:I.expressPaymentType,accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}),Ae(!1),w?.(_.current),I.resolve()},onConfirm:L,onCancel:()=>{let I=ie.current.get(ee);ie.current.delete(ee),Kt(be)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),K(I?.generation),Ae(!1),Ue.current=!0,st()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ke,emailRequired:Ze,billingAddressRequired:Ze,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),ae&&c(Zn,{status:"processing"})]})}function qc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:s,borderColor:w,textColor:f,borderRadius:g,fontFamily:b}){let T=Ic(e,t),M=Is[e],[u,k]=de(!1),be=T?.backgroundColor??s??"#ffffff",j=T?.borderColor??w??"#d1d5db",P=T?.textColor??f??"#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:ua,padding:"0 1rem",backgroundColor:be,color:P,border:`1px solid ${j}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow: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(Ar,{children:[Te("span",{style:{display:"inline-flex",alignItems:"center",gap:hc(e)?8:0},children:[M&&!u?c("img",{src:M,alt:"","aria-hidden":"true",onError:()=>k(!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:P,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:c("path",{d:"M9 18l6-6-6-6"})})]})})}function Za({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:s,onErrorChange:w,onDecline:f,onCancel:g,runBeforeButtonClick:b,onButtonClick:T,isProcessing:M,submitButtonColor:u,submitButtonBorderRadius:k,submitButtonStyle:be,errorText:j}){let P=gr(),{emitInstrument:me}=to(Tn),Q=ei(),le=Qa(),[ae,ve]=de(!1),Ze=he(!1),[fe,Mt]=de(!1),[Xe,xe]=de("loading"),[Me,ee]=de(""),te=!Xt(r?.trim()),B=!te||Xt(Me.trim()),Ae=ye(async()=>{if(!Q||!le||M||Ze.current||!fe)return;Ze.current=!0,ve(!0);let Fe=b?await b("card"):{proceed:!0};if(!Fe.proceed){Ze.current=!1,ve(!1);return}T?.("card");let De=Fe.sessionId??t,Ue=Fe.nonce??n,we=Rr(o?.trim()),_=yn({email:Fe.accountPatch?.email?.trim()||r?.trim()||Me.trim(),firstName:Fe.accountPatch?.firstName?.trim()||we.firstName,lastName:Fe.accountPatch?.lastName?.trim()||we.lastName}),ie=_.email,Le=yn({...Fe.accountPatch,..._});try{if(w?.(null),!Xt(ie))throw new Error("A valid email address is required for payment.");await a?.(_);let se=await le.submit();if(se.error){w?.(se.error.message??"Payment failed.");return}let K=[_.firstName,_.lastName].filter(Boolean).join(" "),Ee=await Q.createPaymentMethod({elements:le,params:{billing_details:{email:ie,...K?{name:K}:{}}}});if(Ee.error||!Ee.paymentMethod){w?.(Ee.error?.message??"Failed to create payment method.");return}let tt=Ee.paymentMethod;if(!De||!ie)throw new Error("Missing sessionId or email for payment.");let st=tt.type||e,Be=await pa(l,me,De,Ue??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:st,paymentMethodId:null,intentKind:"payment"});if(Be.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let V=Be.clientSecret;if(typeof window<"u")try{localStorage.setItem(Qn,JSON.stringify({clientSecret:V,sessionId:De,nonce:Ue,accountPatch:Le,paymentMethodId:tt.id,paymentMethodType:tt.type??e,gateway:"stripe"}))}catch{}let{error:z,paymentIntent:L}=await Q.confirmPayment({clientSecret:V,confirmParams:{return_url:window.location.href,payment_method:tt.id},redirect:"if_required"});if(z){if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let I=z.message??"Payment failed.";w?.(I),f?.(jt("card",I,{code:z.code})),await ma({billingApiUrl:l,sessionId:De,nonce:Ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:z.code??"provider_declined"}});return}let ke=L?.status;if(!Qo(ke)){if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let I=ke==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";w?.(I),f?.(jt("card",I,{code:ke??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let He=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;s({id:He??tt.id,type:"card",threeDSecureActionResultTokenId:L?.id,gateway:"stripe",paymentMethodType:tt.type??e},{accountPatch:Le,paymentMethodCategory:"apm",sessionId:De,nonce:Ue})}catch(se){w?.(se instanceof Error?se.message:"Payment failed. Please try again.")}finally{Ze.current=!1,ve(!1)}},[Q,le,M,fe,b,T,t,n,r,o,Me,a,l,me,e,s,w,f]);return Te("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[te&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:te&&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(Ec,{onReady:()=>xe("ready"),onLoadError:()=>{xe("load_error"),ti(Kt(P),"stripe","apm")},onChange:Fe=>{Mt(!!Fe.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...Xt(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ae()},disabled:!fe||!B||ae||M||Xe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:k,fontSize:"1rem",fontWeight:600,cursor:!fe||!B||ae||M||Xe!=="ready"?"not-allowed":"pointer",opacity:!fe||!B||ae||M||Xe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...be??{}},children:ae?"Processing\u2026":`Pay with ${Fr(e)}`}),j&&c(Xr,{margin:"0.75rem 0 0",children:j})]})}function Ls({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:s,paymentElementBaseOptions:w,onTokenizedBody:f,onErrorChange:g,onButtonClick:b,onDecline:T,runBeforeButtonClick:M,onLoadStateChange:u,isProcessing:k=!1,submitButtonColor:be="#4A49FF",submitButtonBorderRadius:j=8,submitButtonStyle:P,buttonAppearance:me,themeId:Q,onExpandApm:le,expandedApmMethod:ae}){let{emitInstrument:ve}=to(Tn),[Ze,fe]=de(null),[Mt,Xe]=de(null),xe=he(!1),{request:Me,collect:ee,finish:te}=Yr();Pt(()=>{l.length>0&&s?u?.("ready"):s||u?.("loading")},[l.length,s,u]);let B=ye(async _=>{if(!s||xe.current||k)return;xe.current=!0,Xe(_);let ie=M?await M("card"):{proceed:!0};if(!ie.proceed){xe.current=!1,Xe(null);return}b?.("card");let Le=ie.sessionId??e,se=ie.nonce??t,K=Rr([ie.accountPatch?.firstName,ie.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ee=yn({email:ie.accountPatch?.email?.trim()||n?.trim(),firstName:ie.accountPatch?.firstName?.trim()||K.firstName,lastName:ie.accountPatch?.lastName?.trim()||K.lastName});if(!Xt(Ee.email)){Xe(null);let Be=await ee(Fr(_),Ee);if(!Be){xe.current=!1;return}Ee=Be,Xe(_)}let tt=Ee.email,st=yn({...ie.accountPatch,...Ee});try{if(g?.(null),!Le||!Xt(tt))throw new Error("Missing sessionId or email for payment.");await o?.(Ee);let Be=await pa(a,ve,Le,se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,paymentMethodId:null,intentKind:"payment"});if(Be.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let V=Be.clientSecret;if(typeof window<"u")try{localStorage.setItem(Qn,JSON.stringify({clientSecret:V,sessionId:Le,nonce:se,accountPatch:st,paymentMethodType:_,gateway:"stripe"}))}catch{}let{error:z,paymentIntent:L}=await s.confirmPayment({clientSecret:V,confirmParams:{return_url:window.location.href,payment_method_data:{type:_,billing_details:{name:[Ee.firstName,Ee.lastName].filter(Boolean).join(" "),...tt?{email:tt}:{}}}},redirect:"if_required"});if(z){if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let I=z.message??"Payment failed.";g?.(I),T?.(jt("card",I,{code:z.code})),await ma({billingApiUrl:a,sessionId:Le,nonce:se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,providerDeclineReason:z.code??"provider_declined"}});return}let ke=L?.status;if(!Qo(ke)){if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let I=ke==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(I),T?.(jt("card",I,{code:ke??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Qn)}catch{}let He=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;f({id:He??L?.id,type:"card",threeDSecureActionResultTokenId:L?.id,gateway:"stripe",paymentMethodType:_},{accountPatch:st,paymentMethodCategory:"apm",sessionId:Le,nonce:se})}catch(Be){g?.(Be instanceof Error?Be.message:"Payment failed. Please try again.")}finally{xe.current=!1,Xe(null)}},[s,k,M,b,e,t,n,ee,a,ve,r,o,f,g,T]),[Ae,Fe]=de(null),De=le?ae??null:Ae,Ue=ye(_=>{xe.current||k||De&&De!==_||(Es(_)?le?le(_):Fe(_):B(_))},[De,k,B,le]),we=ft(()=>Ae?{...w,paymentMethodTypes:[Ae]}:null,[Ae,w]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Me?c(Wr,{identity:Me.identity,methodLabel:Me.methodLabel,onComplete:te,onCancel:()=>te(null)},Me.id):l.map(_=>{let ie=ae===_,Le=Mt===_,se=Mt!==null&&Mt!==_||ae!=null&&ae!==_;return Te(_c.Fragment,{children:[c(qc,{method:_,themeId:Q,submitting:Le,disabled:se,highlighted:ie,hasNextStep:Es(_),onClick:()=>Ue(_),backgroundColor:me?.backgroundColor,borderColor:me?.borderColor,textColor:me?.textColor,borderRadius:me?.borderRadius,fontFamily:me?.fontFamily}),!le&&Ae===_&&we&&s&&c(Br,{stripe:s,options:we,children:c(Za,{method:_,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:f,onErrorChange:g,onDecline:T,onCancel:()=>Fe(null),runBeforeButtonClick:M,onButtonClick:b,isProcessing:k,submitButtonColor:be,submitButtonBorderRadius:j,submitButtonStyle:P})},_)]},_)})})}function $c({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:s,onTokenizedBody:w,firstName:f,lastName:g,chv:b,className:T,isProcessing:M,error:u,onErrorChange:k,showPayPal:be=!0,showStripe:j=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:me,showApplePay:Q=!0,showGooglePay:le=!0,layout:ae="default",theme:ve,buttonsTheme:Ze,buttonsStyles:fe,appearance:Mt,cardButtonContent:Xe,cardBackButtonContent:xe,cardTitleContent:Me,showSecurityFooter:ee,onButtonClick:te,onBeforeButtonClick:B,onBuyerIdentityReady:Ae,enableAVS:Fe,cardFieldOrder:De,cardPreFormSlot:Ue,avsLayout:we="row",country:_,zip:ie,addressLine1:Le,addressLine2:se,city:K,state:Ee,onCountryChange:tt,onZipChange:st,avsCheck:Be,checkoutType:V,checkoutLayout:z,totalAmount:L=0,currency:ke="usd",initialCardOpen:He=!1,directPaypal:I,isSubscription:Y=!1,session:R,dataAttachmentPending:v=!1,dataAttachmentRequiresIdentity:rt=!1,debug:Ct=!1}){let ge=gr(),dt=Na(),Ie=to(Kn),{emitInstrument:ut}=to(Tn),Et=R??Ie.session,h=Et?.gateways?.paypal?.providerObjectType??I?.providerObjectType,H=v||Ie.claimPending===!0,Ye=rt||Ie.claimRequiresIdentity===!0,qe=H&&!Ye,zt=cs(),[Lt,U]=de(!1),[lt,tn]=de(null),[gt,Ut]=de(_??"US"),[Mn,Bn]=de(ie??""),[An,Zt]=de(Le??""),[Hn,fn]=de(se??""),[qt,rr]=de(K??""),[wt,Fn]=de(Ee??""),[ot,lr]=de(""),[kt,Pn]=de({}),It=he(ie??""),Yt=he(_??"US"),gn=he(Le??""),sn=he(se??""),Cn=he(K??""),nn=he(Ee??""),Sn=he(""),Nt=he({});Pt(()=>{let i=(S,D,_e,O,Re)=>{if(Nt.current[S])return;let ze=D?.trim();!ze||ze===_e.current||(_e.current=ze,O(ze),Re?.(ze))};i("country",_,Yt,Ut,tt),i("zip",ie,It,Bn,st),i("addressLine1",Le,gn,Zt),i("addressLine2",se,sn,fn),i("city",K,Cn,rr),i("state",Ee,nn,Fn)},[_,ie,Le,se,K,Ee,tt,st]);let J=ft(()=>wc(Fe),[Fe]),ln=J!==null,Dn=ft(()=>Ya(R),[R]),Yn=!!R?.vault?.html,Cr=!!R?.gateways?.pcivault,cr=!!(R?.gateways?.stripe?.enabledPaymentMethods??P)?.includes("card"),Bt=Yn||cr||Cr,$e=!!(j&&Bt&&ge&&e),[dr,C]=de(()=>ae!=="buttons"||He?e??null:null),[nt,$t]=de(0),hn=ae!=="buttons"||He||!!e&&dr===e,ue=ft(()=>!ge||!$e||!e||!hn?null:ge.cardCapture({sessionId:e,captureMethod:R?.captureMethod}),[ge,$e,e,hn,R?.captureMethod]),rn=ft(()=>{let i=gt,S=J?Ve(J.postal_code,i):!1;return Oc(i,Mn,S)},[J,gt,Mn]),{avsInvalid:wr,invalidAvsFields:Lr}=ft(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!$e||!J)return{avsInvalid:!1,invalidAvsFields:i};let S=gt,D=(Re,ze)=>Ve(Re,S)&&!ze.trim(),_e={line1:D(J.address_line_1,An),city:D(J.city,qt),state:D(J.state,wt),zip:rn.empty||rn.malformed};return{avsInvalid:_e.line1||_e.city||_e.state||_e.zip,invalidAvsFields:_e}},[$e,J,gt,An,qt,wt,rn]),[cn,ur]=de(!1),[Wn,Ln]=de(!1),[At,Nn]=de(!1),[Gn,dn]=de({line1:!1,city:!1,state:!1}),Qt=he(!1),On=he({email:!1,line1:!1,city:!1,state:!1,zip:!1}),zn=he(!1),at=ye(i=>{On.current[i]=!0,zn.current=!0},[]),un=ye(i=>!Qt.current&&On.current[i],[]),pn=ye(i=>{un(i)&&dn(S=>S[i]?S:{...S,[i]:!0})},[un]),[Un,wn]=de(()=>Wa(R?.vault)),[Pe,en]=de(He&&Bt?"card":"buttons"),[Ft,pr]=de(null),qn=Pe==="expanding"||Pe==="card",mr=R?.gateways?.stripe?"stripe":void 0,bn=ye(()=>{ut?.({class:"card_surface",provider:mr})},[mr,ut]),kn=he(null),Dt=ye(i=>{kn.current&&clearTimeout(kn.current),kn.current=setTimeout(()=>{kn.current=null,i()},Mr)},[]);Pt(()=>()=>{kn.current&&clearTimeout(kn.current)},[]);let x=ye(()=>{bn(),C(e??null),$t(i=>i+1),en("expanding"),Dt(()=>en("card"))},[Dt,bn,e]),F=ye(()=>{en("collapsing"),Dt(()=>en("buttons"))},[Dt]),W=ye(i=>{pr(i),en("apm-expanding"),Dt(()=>en("apm-form"))},[Dt]),G=ye(()=>{en("apm-collapsing"),Dt(()=>{en("buttons"),pr(null)})},[Dt]);Pt(()=>{ae==="buttons"&&He&&Bt&&(C(e??null),en("card"))},[ae,He,Bt,e]);let[Ce,A]=de(null),q=he(!1),p=he(null),N=he("idle"),[$,ct]=de(null),pt=he($);Pt(()=>{pt.current=$},[$]);let ne=n||zt,Se=he(null),Wt=ft(()=>{if(Ae||Ie.claimBuyerIdentity||R?.buyerIdentified!==!1||!e||!t)return;let i=`${ne}|${e}|${t}`;Se.current?.key!==i&&(Se.current={key:i,claim:Vr(new eo(ne,{telemetry:!1}),e,t,{...o?{userId:o}:{},...f?{firstName:f}:{},...g?{lastName:g}:{}})});let S=Se.current.claim;return async D=>{await S(D)}},[Ae,Ie.claimBuyerIdentity,R?.buyerIdentified,e,t,ne,o,f,g]),Qe=Ae??Ie.claimBuyerIdentity??Wt,m=u??lt,d=ft(()=>Rc(ve),[ve]),y=ft(()=>{let i=d?.buttonsLayout??kc(Ze);return fe?{...i,...fe,cardButton:{...i.cardButton,...fe.cardButton},cardFormContainer:{...i.cardFormContainer,...fe.cardFormContainer},backButton:{...i.backButton,...fe.backButton},backButtonIcon:{...i.backButtonIcon,...fe.backButtonIcon},submitButton:{...i.submitButton,...fe.submitButton},title:{...i.title,...fe.title}}:i},[d,Ze,fe]),pe=Mt??d?.appearance,re=ft(()=>Xi({appearance:pe,buttonsStyles:y,layout:ae}),[pe,y,ae]),je=Ie.inlineSessionPatchProcessing??!1,We=(M??Lt)||je,X=ne.replace(/\/+$/,""),E=ft(()=>La({userId:o,email:r,firstName:f,lastName:g,country:_,zip:ie},kt),[o,r,f,g,_,ie,kt]),oe=[E.firstName,E.lastName].filter(i=>!!i?.trim()).join(" "),Ke=!Xt(E.email?.trim()),Ne=he(null);$e&&Ne.current===null&&(Ne.current=Ke);let mt=$e&&(Ne.current??Ke),Oe=ft(()=>zc(ot,mt),[ot,mt]),Ot=Oe.empty||Oe.malformed,vn=ft(()=>ge?ge.getRawProvider():null,[ge]),Nr=ft(()=>dt?dt.getRawProvider():null,[dt]),io=L||100,Oo=ft(()=>pe?uc(pe):null,[pe]),zo=Oo?{appearance:Oo}:null,bi=ft(()=>{let i=Oo??{},S=i.rules??{};return{...i,rules:{...S,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...S[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...S[".AccordionItemContents"]??{}}}}},[Oo]),vi=ft(()=>{let i=rs(L);return{...i,currency:ke.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...zo}},[L,ke,zo]),Pi=ft(()=>({mode:"payment",amount:io,currency:ke.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...zo}),[io,ke,zo]),ce=ye(i=>{tn(i),k?.(i)},[k]),ba=he(""),[Ci,el]=de(!1),va=ye(()=>{el(!0)},[]);Pt(()=>{if(!$e||!mt||!Qe||!Ci||Ot||ba.current)return;let i=yn({email:Xt(E.email?.trim())?E.email?.trim():Sn.current.trim(),firstName:E.firstName?.trim(),lastName:E.lastName?.trim()});ba.current=JSON.stringify(i),Pn(S=>({...S,...i})),Promise.resolve(Qe(i)).catch(S=>{ba.current="",ce(S instanceof Error?S.message:"Failed to attach buyer details.")})},[$e,mt,Qe,Ci,Ot,E.email,E.firstName,E.lastName,ce]),Pt(()=>{!$e||!ue||ue.setCardFieldOrder?.(De??null,J==null&&!mt)},[$e,ue,De,J,mt]),Pt(()=>{(Pe==="expanding"||Pe==="collapsing"||Pe==="apm-expanding"||Pe==="apm-collapsing")&&ce(null)},[Pe,ce]);let $n=ye((i,S,D)=>{s?.(jt(i,S,D))},[s]),Or=ye((i,S,D)=>{let _e=D?.popupBlocked??fr(S),O=Lc(i,_e),Re=_r(D?.code)??or(S)??"external_payment_method_failed",ze=new Vn(O,"api_error",{code:"external_payment_method_failed",param:i});A(null),ae==="buttons"&&(en("buttons"),pr(null)),ce(O),l?.(ze),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:_e})},[ae,l,ce]);Pt(()=>{if(!$e||!e){wn(null);return}let i=Wa(R?.vault);if(i){wn(i);return}if(!hn){wn(null);return}wn(null);let S=!0;return new eo(X).getVaultCapture(e,t).then(D=>{if(!S)return;let _e=Wa(D);_e?wn(_e):ce("Failed to load the secure card form.")}).catch(D=>{S&&ce(D instanceof Error?D.message:"Failed to load the secure card form.")}),()=>{S=!1}},[$e,hn,nt,e,R?.vault,X,t,ce]);let Jn=he({onComplete:a,onError:l,updateError:ce,emitDecline:$n,resolvedAccount:E,avsConfig:J,avsCheckProp:Be,sessionId:e,nonce:t,baseUrl:X,captureMethod:R?.captureMethod,paymentId:R?.paymentId,authorizationExpiresAt:R?.authorizationExpiresAt});Jn.current={onComplete:a,onError:l,updateError:ce,emitDecline:$n,resolvedAccount:E,avsConfig:J,avsCheckProp:Be,sessionId:e,nonce:t,baseUrl:X,captureMethod:R?.captureMethod,paymentId:R?.paymentId,authorizationExpiresAt:R?.authorizationExpiresAt};let Pa=he(!1),Si=ye(()=>{let{resolvedAccount:i,avsConfig:S,avsCheckProp:D}=Jn.current,_e=i.email?.trim(),O=Xt(_e)?_e:Sn.current.trim();if(!Xt(O))return null;let Re=i.firstName?.trim(),ze=i.lastName?.trim(),it=Yt.current||i.country||"US",Gt=S?Ve(S.state,it):!1,ht=S?Ve(S.address_line_1,it):!1,bt=S?Ve(S.postal_code,it):!1,et=S?Ve(S.city,it):!1,on=S?Ve(S.address_line_2,it):!1,Ge=ht&&!Gt&&bt?Rs(it,(It.current??"").trim()):null,an=Gt?nn.current:Ge;return{accountData:{userId:i.userId??"",email:O,...Re?{firstName:Re}:{},...ze?{lastName:ze}:{},...bt&&It.current?{zip:It.current}:{},...et&&Cn.current?{city:Cn.current}:{},...an?{state:an}:{},...ht&&gn.current?{addressLine1:gn.current}:{},...on&&sn.current?{addressLine2:sn.current}:{},country:it},...D!==void 0?{avsCheck:D}:{},...S?{avsConfig:{country:Ve(S.country,it),postal_code:bt,address_line_1:ht,address_line_2:on,city:et,state:Gt}}:{}}},[]),wi=he(H);wi.current=H,Pt(()=>{H||m!==xs||Jn.current.updateError(null)},[H,m]),Pt(()=>{!$e||!ue||ue.setSubmitGate?.(wr||H||Ot)},[$e,ue,wr,H,Ot]),Pt(()=>{if(!$e||!ue)return;Pa.current=!1;let i=!1,S=ue.on("submitting",()=>{ur(!0),p.current&&clearTimeout(p.current),N.current="validation-window",p.current=setTimeout(()=>{p.current=null,N.current==="validation-window"&&(N.current="processing")},Tc),A("processing");let{baseUrl:ze,sessionId:it,nonce:Gt,updateError:ht,onError:bt}=Jn.current;if(!it||!Gt)return;let et=Si();if(!et){ht("Enter a valid email address."),N.current="idle",A(null);return}new eo(ze).patchAccountSnapshot(it,Gt,et,{telemetryMode:"best_effort"}).catch(on=>{if(!xc(on))return;let Ge=on instanceof Error?on.message:"Please check your billing address and try again.";ht(Ge),N.current="idle",A(null),bt?.(on instanceof Vn?on:new Vn(Ge,"api_error"))})}),D=ue.on("complete",async ze=>{if(Zr(ze.sessionId??Jn.current.sessionId),N.current="terminal",A("success"),await new Promise(ht=>setTimeout(ht,1200)),Pa.current)return;Pa.current=!0;let it=Jn.current,Gt=Ya(it)||ze.outcome==="authorized";Jn.current.onComplete?.(Gt?{status:"authorized",paymentIntentId:ze.intentId,paymentId:ze.paymentId??it.paymentId,sessionId:ze.sessionId??it.sessionId,authorizationExpiresAt:ze.authorizationExpiresAt??it.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:ze.intentId,checkoutMethod:"card"})}),_e=ue.on("decline",async ze=>{let{updateError:it,emitDecline:Gt}=Jn.current,ht=ze.message??"Your payment was declined. Please try another card or contact your bank.";N.current="terminal",it(ht),A("error");let bt=ze.failureOutcome??Cc(ze.declineReason)??"authorization_declined";Gt("card",ht,{code:bt,declineCode:bt}),await new Promise(et=>setTimeout(et,1500)),!i&&(N.current="idle",A(null))}),O=ue.on("error",async ze=>{let{updateError:it,onError:Gt}=Jn.current,ht=ze.message??"There was a problem processing your payment. Please try again.";N.current="terminal",it(ht),A("error"),Gt?.(new Vn(ht,"api_error",{code:ze.failureOutcome??"capture_failed"})),await new Promise(bt=>setTimeout(bt,1500)),!i&&(N.current="idle",A(null))}),Re=ue.on("blocked",()=>{if(!wi.current){ur(!0);return}va(),Jn.current.updateError(xs)});return()=>{i=!0,p.current&&(clearTimeout(p.current),p.current=null),N.current="idle",S(),D(),_e(),O(),Re()}},[$e,ue,va,Si]);let Xn=!!I?.clientId,so=Array.isArray(P),Uo=so&&P.length>0,tl=so&&P.includes("paypal"),{expressMethods:qo,paymentElementMethods:lo}=ft(()=>Sc(P,{excludePaypal:Xn}),[P,Xn]),ki=Xn||!!dt,nl=ft(()=>ki?qo.filter(i=>i!=="paypal"):qo,[qo,ki]),rl=ft(()=>{let i=[];return Q&&i.push("apple_pay"),le&&i.push("google_pay"),i},[Q,le]),$o=so?nl:rl,ol=j&&$o.length>0,Ca=ln?gt:_,jo=ft(()=>{let i=Ca?.trim().toUpperCase();return i?me?lo.filter(S=>{let D=me[S];return!D||D.length===0||D.includes(i)}):yc(lo,Ca):lo},[lo,Ca,me]),Sa=ft(()=>({mode:"payment",amount:io,currency:ke.toLowerCase(),paymentMethodCreation:"manual",appearance:bi}),[io,ke,bi]),[Ii,Ri]=de("loading"),[Ei,_i]=de("loading"),[Ti,xi]=de("loading"),[al,wa]=de(!1),[Mi,ka]=de("loading"),[Ko,il]=de();Pt(()=>{il(ks())},[]);let Bi=be&&(Xn||(so?tl:Ko===!1)),Ai=j&&ol,co=!qe&&Bi&&Xn,Fi=Mi==="retrying"||Mi==="exhausted",uo=!qe&&Bi&&!!Nr&&(!Xn||Fi),po=!qe&&Ai&&!!vn,mo=!qe&&j&&Uo&&jo.length>0&&!!vn,sl=co&&!Fi?al:uo&&As(Ii),ll=po&&As(Ei),cl=mo&&Ti!=="load_error",Di=i=>i==="loading"||i==="ready",Li=co||uo&&Di(Ii)||po&&Di(Ei)||mo&&Ti!=="load_error",Vo=he(!1);Pt(()=>{if(!Vo.current){if(!j&&!be){Vo.current=!0;let i=new Vn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),ce(i.message)}else if(!j&&be&&!Xn&&!Nr){Vo.current=!0;let i=new Vn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(i),ce(i.message)}else if(Ko!==void 0&&!qe&&!Bt&&!Li){Vo.current=!0;let i=new Vn("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),ce(i.message)}}},[j,be,Xn,Nr,Ko,qe,Bt,Li,l,ce]);let Ni=he(!1);Pt(()=>{if(Ni.current||!Uo)return;let i=[];Q!==!0&&i.push("showApplePay"),le!==!0&&i.push("showGooglePay"),i.length!==0&&(Ni.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.`))},[Uo,Q,le]);let Oi=ye((i,S)=>Ie.applyInlineSessionPatch?Ie.applyInlineSessionPatch(i).then(D=>({error:null,sessionId:D.sessionId||e,nonce:D.session?.clientSecret||t})).catch(D=>{let _e=Bs(S,D);return ce(_e.message),l?.(_e),{error:_e,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ie.applyInlineSessionPatch,t,l,e,ce]),jn=ye(async i=>{if(!B)return{proceed:!0};try{let S=await B({method:i,sessionId:e||void 0,createSession:Ie.inlineSessionDraft});if(S===!1)return{proceed:!1};if(S&&typeof S=="object"){S.account&&Pn(_e=>({..._e??{},...S.account}));let D=await Oi(S,i);return D.error?{proceed:!1,accountPatch:S.account}:{proceed:!0,accountPatch:S.account,sessionId:D.sessionId,nonce:D.nonce}}return{proceed:!0}}catch(S){let D=Bs(i,S);return ce(D.message),l?.(D),{proceed:!1}}},[Oi,Ie.inlineSessionDraft,B,l,e,ce]),zi=ye(async(i,S)=>{if(q.current)return;q.current=!0,U(!0),A("processing"),ce(null);let D=S?.sessionId??e,_e=S?.nonce??t,O=La(E,S?.accountPatch),Re=S?.completionPaymentMethodId??So(i),ze=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,it=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Gt=()=>{ut?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:it})};try{let bt=await new eo(X).processPayment(O.userId??"",{sessionId:D,nonce:_e,paymentMethodCategory:S?.paymentMethodCategory??Fc(i),tokenizedData:ze,accountData:{userId:O.userId??"",email:O.email??"",...O.firstName?{firstName:O.firstName}:{},...O.lastName?{lastName:O.lastName}:{},...J?(()=>{let Ge=Yt.current,an=Ve(J.state,Ge),En=Ve(J.address_line_1,Ge),Jt=Ve(J.postal_code,Ge),bo=En&&!an&&Jt?Rs(Ge,(It.current??"").trim()):null,vo=an?nn.current:bo;return{country:Ge,...Jt&&It.current?{zip:It.current}:{},...Ve(J.city,Ge)&&Cn.current?{city:Cn.current}:{},...vo?{state:vo}:{},...En&&gn.current?{addressLine1:gn.current}:{},...Ve(J.address_line_2,Ge)&&sn.current?{addressLine2:sn.current}:{}}})():{}},chv:b,avsCheck:Be??!1,checkoutType:V,checkoutLayout:z,avsConfig:J?{country:Ve(J.country,Yt.current),postal_code:Ve(J.postal_code,Yt.current),address_line_1:Ve(J.address_line_1,Yt.current),address_line_2:Ve(J.address_line_2,Yt.current),city:Ve(J.city,Yt.current),state:Ve(J.state,Yt.current)}:void 0});if(bt.ok){let Ge=bt.status===204?null:await bt.json().catch(()=>null),an=Ya(R)||Ge?.status==="authorized";Zr(D),A("success"),ct(null),await new Promise(En=>setTimeout(En,1200)),a?.(an?{status:"authorized",...typeof Ge?.paymentId=="string"?{paymentId:Ge.paymentId}:R?.paymentId?{paymentId:R.paymentId}:{},sessionId:typeof Ge?.sessionId=="string"?Ge.sessionId:D,...typeof Ge?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Ge.authorizationExpiresAt}:R?.authorizationExpiresAt?{authorizationExpiresAt:R.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"});return}let et=await bt.json().catch(()=>null);if(et?.type==="paypal_redirect_required"){let Ge=et.threeDSecureToken,an=et.paymentMethodId||i.id||"";if(!ge||!Ge){A("error"),ce("PayPal authorization required but no token provided.");return}try{let En=dt?.getRawProvider();if(!En){ce("PayPal is not available.");return}let Jt={return_url:window.location.href};an&&(Jt.payment_method=an);let{error:bo}=await En.confirmPayment({clientSecret:Ge,confirmParams:Jt,redirect:"if_required"});if(bo){A("error");let vo=bo.message??"PayPal payment failed.";ce(vo),$n("paypal",vo,{code:bo.code})}}catch(En){A("error"),ce(En instanceof Error?En.message:"PayPal authorization failed.")}return}if(et?.type==="paypal_direct_required"){let Ge=et.orderId;if(!Ge){A("error"),ce("PayPal retry required but no order id provided.");return}let an=pt.current?.attempts??0;if(an>=2){A("error"),ce("PayPal payment could not be completed after multiple attempts."),$n("paypal","paypal_direct_required retry limit exceeded");return}wa(!1),ka("loading"),ct({orderId:Ge,attempts:an+1}),A(null);return}mc(bt.status,et)||Gt(),A("error");let on=et?.message??"Payment failed. Please try again.";ce(on),$n(i.isPaypal?"paypal":"card",on,{code:et?.code??et?.gatewayErrorCode,declineCode:et?.declineCode??et?.gatewayDeclineReason}),await new Promise(Ge=>setTimeout(Ge,1500))}catch(ht){Os(ht)||Gt(),A("error"),ce(ht instanceof Error?ht.message:"An unexpected error occurred"),await new Promise(bt=>setTimeout(bt,1500))}finally{U(!1),A(null),q.current=!1}},[X,e,t,E,J,Be,V,z,b,ge,dt,R,a,ce,$n,ut]),In=ye((i,S)=>{w?w(i):zi(i,S)},[w,zi]),Ui=he(!1);Pt(()=>{if(typeof window>"u"||Ui.current)return;let i=new URLSearchParams(window.location.search),S=i.get("payment_intent"),D=i.get("payment_intent_client_secret"),_e=i.get("redirect_status");if(!S||!D)return;let O=bt=>{let et=localStorage.getItem(bt);if(!et)return null;try{return JSON.parse(et)}catch{return localStorage.removeItem(bt),null}},Re=O(Qn)??O(Ts),ze;if(Re?.clientSecret){if(Re.clientSecret!==D)return;ze={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;Ui.current=!0,localStorage.removeItem(Qn),localStorage.removeItem(Ts);let it=new URL(window.location.href);it.searchParams.delete("payment_intent"),it.searchParams.delete("payment_intent_client_secret"),it.searchParams.delete("redirect_status"),window.history.replaceState({},"",it.toString());let Gt=Re?.paymentMethodType??Re?.tokenType??"card",ht="card";(async()=>{let bt=ge?.getRawProvider();if(!bt){let Jt="Payment is not available \u2014 please refresh and try again.";ce(Jt),$n(ht,Jt);return}if(_e==="failed"){let Jt="Payment was declined. Please try again.";ce(Jt),$n(ht,Jt);return}let{paymentIntent:et,error:on}=await bt.retrievePaymentIntent(D);if(on){let Jt=on.message??"Failed to retrieve payment status.";ce(Jt),$n(ht,Jt,{code:on.code});return}let Ge=et?.status,an=Qo(Ge);if(!et||!an){let Jt=Ge==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ce(Jt),$n(ht,Jt,{code:Ge??"missing_payment_intent"});return}let En=typeof et.payment_method=="string"?et.payment_method:et.payment_method?.id;In({id:En??Re?.paymentMethodId??Re?.tokenId??et.id,type:"card",threeDSecureActionResultTokenId:et.id,gateway:Re?.gateway??"stripe",paymentMethodType:Gt},ze)})()},[e,In,ge,ce,$n]);let Ia=ye(i=>{i.preventDefault()},[]);if(!(ge!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let yo=ae==="buttons",mn=pe?.variables,dl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ra=mn?.colorBackground,ul=Ra&&!dl.has(Ra)?Ra:void 0,fo=y.cardInputBorder??(yo?"#e5e7eb":"#A4A4FF"),qi=mn?.colorDanger??"#dc2626",Rt=i=>Lr[i]&&(Gn[i]||cn),Ho=Ot&&(At||cn),Rn=i=>i?qi:fo,Yo=(rn.malformed||rn.empty)&&(Wn||cn),pl=Rn(Yo),Ea=y.cardFormContainer?.backgroundColor??ul??(yo?"white":"#EDEDFF"),zr=y.cardInputBackground??mn?.colorBackground??"white",_a=qr(xe),$i=qr(Me),Ur=y.nameInput,ji=y.cardInputFontSize??Uc(Ur?.fontSize)??mn?.fontSizeBase??"16px",Ki=typeof Ur?.fontFamily=="string"?Ur.fontFamily:mn?.fontFamily??"Poppins, sans-serif",Vi=Ji(Ur?.fontWeight)??400,ml=y.cardInputColor??(typeof Ur?.color=="string"?Ur.color:void 0)??mn?.colorText??"#262833",yl=y.cardInputPlaceholderColor??"#9ca3af",_t=mn?.borderRadius??"8px",kr=mn?.borderRadius??y.cardButton?.borderRadius??_t,Ir=mn?.colorPrimary??"#4A49FF",fl=mn?.colorPrimaryHover??Po(Ir,.12),Ta=mn?.colorText??"#262833",xa={fontSize:ji,fontFamily:Ki,fontWeight:Vi,color:ml,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},go={marginTop:"0.375rem",...xa,fontSize:"0.75rem",lineHeight:1.4,color:qi},gl={"--flopay-input-placeholder-color":yl,"--flopay-input-font-size":ji,"--flopay-input-font-family":Ki,"--flopay-input-font-weight":String(Vi)},ho=y.cardFormContainer??{},Ma=ho.padding??(yo?"0":"1rem"),Ba=ho.borderRadius??_t,hl=ue&&Un?c(Aa,{capture:ue,html:Un.html,messageToken:Un.messageToken,expectedOrigin:Un.expectedOrigin,theme:re,onReady:()=>{if(!mt&&!J||typeof document>"u")return;let i=()=>{let D=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(D){Qt.current=!0;try{D.focus()}finally{Qt.current=!1}}};zn.current||i()},onError:i=>ce(i),onValidation:i=>{let S=N.current;(S==="idle"||S==="validation-window")&&(ce(i),i&&N.current==="validation-window"&&(p.current&&(clearTimeout(p.current),p.current=null),N.current="idle",A(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"}),Hi=Te("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&bn()},style:{backgroundColor:Ea,borderRadius:Ba,...ho,padding:Ma,...gl,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 @@ ${zt.join(`
|
|
|
30
30
|
font-family: var(--flopay-input-font-family);
|
|
31
31
|
font-weight: var(--flopay-input-font-weight);
|
|
32
32
|
}
|
|
33
|
-
`}),yo&&qn&&Te("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:$e?-2:0},children:[Te("button",{type:"button",onClick:F,style:{display:"inline-flex",alignItems:"center",gap:_a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.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",...y.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(jr,{content:xe})]}),$i?c("div",{style:{flex:1}}):c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...y.title},children:c(Co,{content:
|
|
33
|
+
`}),yo&&qn&&Te("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:$e?-2:0},children:[Te("button",{type:"button",onClick:F,style:{display:"inline-flex",alignItems:"center",gap:_a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.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",...y.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(jr,{content:xe})]}),$i?c("div",{style:{flex:1}}):c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...y.title},children:c(Co,{content:Me})})]}),!yo&&!$i&&c("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ta,order:$e?-3:0,...y.title},children:c(Co,{content:Me})}),$e&&Ue&&c("div",{style:{order:-2,width:"100%"},children:Ue}),$e&&mt&&Te("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[c("div",{style:{backgroundColor:zr,border:`1px solid ${Rn(Ho)}`,borderRadius:_t,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:ot,onChange:i=>{at("email"),Sn.current=i.target.value,lr(i.target.value)},onPointerDown:()=>at("email"),onKeyDown:()=>at("email"),onBlur:()=>{un("email")&&Nn(!0),Ot||va()},disabled:We,required:!0,"aria-invalid":Ho||void 0,"aria-describedby":Ho?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...xa}})}),Ho&&c("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:go,children:Oe.empty?"Email address is required":"Enter a valid email address"})]}),J&&c("div",{style:{order:$e?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=gt,S=(O=!1)=>({backgroundColor:zr,border:`1px solid ${Rn(O)}`,borderRadius:_t,marginTop:"0.5rem",padding:"10px"}),D=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...xa}),_e=gc(i);return Te(Ar,{children:[Ve(J.address_line_1,i)&&Te(Ar,{children:[c("div",{style:S(Rt("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:An,onChange:O=>{at("line1"),Nt.current.addressLine1=!0,gn.current=O.target.value,Zt(O.target.value)},onPointerDown:()=>at("line1"),onKeyDown:()=>at("line1"),onBlur:()=>pn("line1"),disabled:We,required:!0,"aria-invalid":Rt("line1")||void 0,"aria-describedby":Rt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:D()})}),Rt("line1")&&c("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:go,children:"Street address is required"})]}),Ve(J.address_line_2,i)&&c("div",{style:S(),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:Hn,onChange:O=>{Nt.current.addressLine2=!0,sn.current=O.target.value,fn(O.target.value)},disabled:We,"data-testid":"flopay-address-line2",style:D()})}),(Ve(J.city,i)||Ve(J.state,i))&&Te("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Ve(J.city,i)&&c("div",{style:{flex:1,backgroundColor:zr,borderTop:`1px solid ${Rn(Rt("city"))}`,borderRight:`1px solid ${Rn(Rt("city"))}`,borderBottom:`1px solid ${Rn(Rt("city"))}`,borderLeft:`1px solid ${Rn(Rt("city"))}`,padding:"10px",borderTopLeftRadius:_t,borderBottomLeftRadius:_t,...Ve(J.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:_t}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:qt,onChange:O=>{at("city"),Nt.current.city=!0,Cn.current=O.target.value,rr(O.target.value)},onPointerDown:()=>at("city"),onKeyDown:()=>at("city"),onBlur:()=>pn("city"),disabled:We,required:!0,"aria-invalid":Rt("city")||void 0,"aria-describedby":Rt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:D()})}),Ve(J.state,i)&&c("div",{style:{flex:1,backgroundColor:zr,borderTop:`1px solid ${Rn(Rt("state"))}`,borderRight:`1px solid ${Rn(Rt("state"))}`,borderBottom:`1px solid ${Rn(Rt("state"))}`,borderLeft:`1px solid ${Rn(Rt("state"))}`,padding:"10px",borderTopRightRadius:_t,borderBottomRightRadius:_t,...Ve(J.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Rn(Rt("state")||Rt("city"))}`}:{borderRadius:_t}},children:_e?Te("select",{id:"flopay-billing-state",name:"billing-state",value:wt,onChange:O=>{at("state"),Nt.current.state=!0,nn.current=O.target.value,Fn(O.target.value)},onPointerDown:()=>at("state"),onKeyDown:()=>at("state"),onBlur:()=>pn("state"),disabled:We,autoComplete:"billing address-level1",required:!0,"aria-invalid":Rt("state")||void 0,"aria-describedby":Rt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...D(),cursor:"pointer"},children:[c("option",{value:"",children:Ha(i)}),_e.map(O=>c("option",{value:O.code,children:O.name},O.code))]}):c("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Ha(i),autoComplete:"billing address-level1",value:wt,onChange:O=>{at("state"),Nt.current.state=!0,nn.current=O.target.value,Fn(O.target.value)},onPointerDown:()=>at("state"),onKeyDown:()=>at("state"),onBlur:()=>pn("state"),disabled:We,required:!0,"aria-invalid":Rt("state")||void 0,"aria-describedby":Rt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:D()})})]}),Rt("city")&&c("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:go,children:"City is required"}),Rt("state")&&Te("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:go,children:[Ha(i)," is required"]}),(Ve(J.country,i)||Ve(J.postal_code,i))&&Te("div",{style:{display:"flex",flexDirection:we==="column"?"column":"row",gap:we==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Ve(J.country,i)&&c("div",{style:{flex:we==="row"?1:void 0,backgroundColor:zr,borderTop:`1px solid ${fo}`,borderRight:`1px solid ${fo}`,borderBottom:`1px solid ${fo}`,borderLeft:`1px solid ${fo}`,padding:"10px",...we==="row"&&Ve(J.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:_t,borderBottomLeftRadius:_t,borderRight:"none"}:{borderRadius:_t}},children:c("select",{id:"flopay-billing-country",name:"billing-country",value:gt,onChange:O=>{Nt.current.country=!0,Yt.current=O.target.value,Ut(O.target.value),tt?.(O.target.value),nn.current="",Fn("")},disabled:We,autoComplete:"billing country","data-testid":"flopay-country",style:{...D(),cursor:"pointer"},children:pc.map(O=>Te("option",{value:O.code,children:[O.flag," ",O.name]},O.code))})}),Ve(J.postal_code,i)&&c("div",{style:{flex:we==="row"?1:void 0,backgroundColor:zr,border:`1px solid ${pl}`,padding:"10px",...we==="row"&&Ve(J.country,i)?{borderRadius:"0",borderTopRightRadius:_t,borderBottomRightRadius:_t}:{borderRadius:_t}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Ja(gt),autoComplete:"billing postal-code",value:Mn,onChange:O=>{at("zip"),Nt.current.zip=!0,It.current=O.target.value,Bn(O.target.value),st?.(O.target.value)},onPointerDown:()=>at("zip"),onKeyDown:()=>at("zip"),onBlur:()=>{un("zip")&&Ln(!0)},disabled:We,required:rn.required,"aria-invalid":Yo||void 0,"aria-describedby":Yo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:D()})})]}),Yo&&c("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:go,children:rn.empty?`${Ja(i)} is required`:Nc(i)})]})})()}),$e&&hl,m&&c(Xr,{margin:"0.75rem 0",styleOverride:y.errorBanner,children:m})]}),Wo={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"},Yi=i=>Ct?!be||!Xn?c("pre",{"data-testid":i,style:Wo,children:"FloPay/DirectPayPal-debug - not enabled"}):c("pre",{"data-testid":i,style:Wo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${be}`,` directPaypalConfigured=${Xn}`,` inAppBrowserDetected=${String(Ko)}`,` shouldRenderDirectPayPal=${co}`,` shouldRenderStripePayPal=${uo}`,` hasPaypalStripeInstance=${!!Nr}`].join(`
|
|
34
34
|
`)}):null,Wi=i=>Ct?!j||!vn?c("pre",{"data-testid":i,style:Wo,children:"FloPay/Stripe-debug - not enabled"}):c("pre",{"data-testid":i,style:Wo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${j}`,` currency=${ke}`,` amountInCents=${io}`,` enabledPaymentMethods: ${JSON.stringify(P??[])}`,` enabledPaymentMethodsProvided=${so}`,` hasEnabledMethods=${Uo}`,` expressMethods: ${JSON.stringify(qo)}`,` walletExpressMethods: ${JSON.stringify($o)}`,` paymentElementMethods: ${JSON.stringify(lo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(jo)}`,` hasStripeInstance=${!!vn}`,` shouldRenderWallets=${po}`,` shouldRenderPaymentElement=${mo}`].join(`
|
|
35
|
-
`)}):null,Gi=Pe==="apm-expanding"||Pe==="apm-form"||Pe==="apm-collapsing",Go=Pe==="apm-expanding"?`flopay-card-enter ${Br}ms cubic-bezier(0, 0, 0.2, 1) both`:Pe==="apm-collapsing"?`flopay-card-exit ${Br}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Jo=Ft?{...Sa,paymentMethodTypes:[Ft]}:null;if(ae==="buttons"){let i=Pe==="buttons"||Pe==="expanding"||Pe==="apm-expanding",k=Pe==="expanding"||Pe==="card"||Pe==="collapsing",D=Xe===void 0?{boxSizing:"border-box",height:ua,padding:"0 1rem"}:{padding:"0.9rem 1rem"},_e=Pe==="expanding"||Pe==="apm-expanding"?`flopay-buttons-exit ${Br}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Pe==="collapsing"||Pe==="apm-collapsing"?`flopay-buttons-enter ${Br}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,O=Pe==="expanding"?`flopay-card-enter ${Br}ms cubic-bezier(0, 0, 0.2, 1) both`:Pe==="collapsing"?`flopay-card-exit ${Br}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Te("form",{onSubmit:Ia,className:T,noValidate:!0,style:{position:"relative"},children:[c(Ga,{}),Ce&&c(Zn,{status:Ce,errorMessage:m,authorized:Dn}),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?Fc:{},..._e?{animation:_e,pointerEvents:"none"}:{}},children:[Yi("flopay-direct-paypal-gate-debug"),Wi("flopay-stripe-gate-debug"),co&&I&&Te(Ar,{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(oa,{sessionId:e,nonce:t,billingApiUrl:ne,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,clientId:I.clientId,environment:I.environment,currency:ke.toUpperCase(),isSubscription:Y,providerObjectType:h,onTokenizedBody:In,onComplete:a,onErrorChange:ce,onDecline:s,onTechnicalFailure:Or,onButtonClick:te,runBeforeButtonClick:jn,isProcessing:We,onLoadStateChange:wa,onInitializationStateChange:ka,session:Et,existingOrderId:$?.orderId,debug:Ct},$?.orderId??"fresh")]}),uo&&c(Mr,{stripe:Nr,options:Pi,children:c(Fs,{sessionId:e,nonce:t,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,onTokenizedBody:In,onErrorChange:ce,isProcessing:We,onButtonClick:te,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:jn,onLoadStateChange:Ri,placeholderBorderRadius:kr})}),po?c(Mr,{stripe:vn,options:vi,children:c(Ds,{sessionId:e,nonce:t,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,intentKind:L>0?"payment":"setup",expressMethods:$o,onTokenizedBody:In,onErrorChange:ce,onButtonClick:te,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:jn,onLoadStateChange:_i,placeholderBorderRadius:kr})}):Ai?c("div",{style:{height:ua,borderRadius:kr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,mo&&c(Ls,{sessionId:e,nonce:t,email:E.email,billingName:[E.firstName,E.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,paymentElementMethods:jo,stripeInstance:vn,paymentElementBaseOptions:Sa,onTokenizedBody:In,onErrorChange:ce,onButtonClick:te,onDecline:s,runBeforeButtonClick:jn,onLoadStateChange:xi,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:y.submitButton,onExpandApm:W,expandedApmMethod:Ft,themeId:ve,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:kr}}),$e&&c("button",{type:"button",onClick:async()=>{We||!(await jn("card")).proceed||(te?.("card"),x())},disabled:We,style:{width:"100%",...D,...y.cardButton,...ni({themeBundle:d,resolvedPrimaryColor:Ir,resolvedBorderRadius:_t,submitButtonStyle:y.submitButton,explicitPrimaryColor:mn?.colorPrimary}),fontSize:y.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:We?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:We?.6:1},onMouseEnter:Re=>{!We&&(d||mn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=fl)},onMouseLeave:Re=>{(d||mn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=Ir)},onMouseDown:Re=>{Re.currentTarget.style.transform="scale(0.985)"},onMouseUp:Re=>{Re.currentTarget.style.transform="scale(1)"},children:c($r,{content:Xe})}),m&&Pe==="buttons"&&c(Xr,{margin:"0.25rem 0",styleOverride:y.errorBanner,children:m})]}),$e&&k&&c("div",{style:{gridArea:"1 / 1",...O?{animation:O}:{},...Pe==="collapsing"?{pointerEvents:"none"}:{}},children:Hi}),j&&Gi&&Ft&&Jo&&vn&&c("div",{style:{gridArea:"1 / 1",...Go?{animation:Go}:{},...Pe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Te("div",{style:{backgroundColor:Ea,borderRadius:Ma,...ho,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:G,style:{display:"inline-flex",alignItems:"center",gap:_a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.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",...y.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(jr,{content:xe})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:Ta,paddingRight:80,...y.title},children:`Pay with ${Fr(Ft)}`})]}),c(Mr,{stripe:vn,options:Jo,children:c(Za,{method:Ft,sessionId:e,nonce:t,email:E.email,billingName:[E.firstName,E.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,onTokenizedBody:In,onErrorChange:ce,onDecline:s,onCancel:G,runBeforeButtonClick:jn,onButtonClick:te,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:y.submitButton,errorText:m})},Ft)]})})]})]})}return Gi&&Ft&&Jo&&vn&&j?Te("form",{onSubmit:Ia,className:T,noValidate:!0,style:{position:"relative"},children:[c(Ga,{}),Ce&&c(Zn,{status:Ce,errorMessage:m,authorized:Dn}),c("div",{style:{...Go?{animation:Go}:{},...Pe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Te("div",{style:{backgroundColor:Ea,borderRadius:Ma,...ho,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:G,style:{display:"inline-flex",alignItems:"center",gap:_a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.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",...y.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(jr,{content:xe})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:Ta,paddingRight:80,...y.title},children:`Pay with ${Fr(Ft)}`})]}),c(Mr,{stripe:vn,options:Jo,children:c(Za,{method:Ft,sessionId:e,nonce:t,email:E.email,billingName:[E.firstName,E.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,onTokenizedBody:In,onErrorChange:ce,onDecline:s,onCancel:G,runBeforeButtonClick:jn,onButtonClick:te,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:y.submitButton,errorText:m})},Ft)]})})]}):Te("form",{onSubmit:Ia,className:T,noValidate:!0,style:{position:"relative"},children:[c(Ga,{}),Ce&&c(Zn,{status:Ce,errorMessage:m,authorized:Dn}),Te("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Yi("flopay-direct-paypal-gate-debug-default"),Wi("flopay-stripe-gate-debug-default"),co&&I&&Te(Ar,{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(oa,{sessionId:e,nonce:t,billingApiUrl:ne,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,clientId:I.clientId,environment:I.environment,currency:ke.toUpperCase(),isSubscription:Y,providerObjectType:h,onTokenizedBody:In,onComplete:a,onErrorChange:ce,onDecline:s,onTechnicalFailure:Or,onButtonClick:te,runBeforeButtonClick:jn,isProcessing:We,onLoadStateChange:wa,onInitializationStateChange:ka,session:Et,existingOrderId:$?.orderId,debug:Ct},$?.orderId??"fresh")]}),uo&&c(Mr,{stripe:Nr,options:Pi,children:c(Fs,{sessionId:e,nonce:t,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,onTokenizedBody:In,onErrorChange:ce,isProcessing:We,onButtonClick:te,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:jn,onLoadStateChange:Ri,placeholderBorderRadius:kr})}),po&&c(Mr,{stripe:vn,options:vi,children:c(Ds,{sessionId:e,nonce:t,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,intentKind:L>0?"payment":"setup",expressMethods:$o,onTokenizedBody:In,onErrorChange:ce,onButtonClick:te,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:jn,onLoadStateChange:_i,placeholderBorderRadius:kr})}),mo&&c(Ls,{sessionId:e,nonce:t,email:E.email,billingName:[E.firstName,E.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ne,paymentElementMethods:jo,stripeInstance:vn,paymentElementBaseOptions:Sa,onTokenizedBody:In,onErrorChange:ce,onButtonClick:te,onDecline:s,runBeforeButtonClick:jn,onLoadStateChange:xi,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:y.submitButton,themeId:ve,onExpandApm:W,expandedApmMethod:Ft,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:kr}})]}),$e&&(ll||sl||cl)&&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&&Hi]})}import{Fragment as nr,jsx as Z,jsxs as Ht}from"react/jsx-runtime";var Dr=44,yi="flopay_checkout_saved_payment_resume",ha=new Map,fa=new Map;function Hs(e,t){t.settled&&t.consumers===0&&ha.get(e)===t&&ha.delete(e)}function Xc(e,t,n){let r=fa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};fa.set(e,a);let l=()=>{fa.get(e)===a&&fa.delete(e)};return o.then(l,l),o}function Ao(e){return new Promise(t=>setTimeout(t,e))}function ga(e,t,n){let r=na({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Js,enabled:t!==!1});return r.beginCheckout(n),r}function Fo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ai(e,t,n,r,o){let a=ga(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Fo(a)}function Zc(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 pi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ii(e){return!e||e.data.stripe?.publishableKey?!1:!!pi(e)?.clientId}function sr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Qc(){if(!sr())return null;try{let e=window.sessionStorage.getItem(yi);return e?JSON.parse(e):null}catch{return null}}function Ys(e){if(sr())try{window.sessionStorage.setItem(yi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function si(){if(sr())try{window.sessionStorage.removeItem(yi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var fi=":idempotency-key";function Xs(e,t){if(!sr())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 li(e,t,n,r){if(sr())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 mi(e,t){if(sr())try{Xs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Zs(e,t){if(!sr())return null;try{let n=window.sessionStorage.getItem(e+fi);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 ci(e,t,n){if(sr())try{window.sessionStorage.setItem(e+fi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function di(e,t){if(mi(e,t),!!sr())try{Zs(e,t)&&window.sessionStorage.removeItem(e+fi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ed(){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 Ws(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 td(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 ui(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function nd(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 Do(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=>ui(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ui(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ui(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:nd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function rd(e,t=!1){let n=Do(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 od(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=Gc(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Vc(t.items,t.subscriptions)).map(f=>({type:f.type,code:f.code??f.providerItemId??f.providerPlanId??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??o).toUpperCase()})).sort((f,g)=>`${f.code}:${f.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),l=e.products.map(f=>({type:f.type,code:f.code??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??e.currency).toUpperCase()})).sort((f,g)=>`${f.code}:${f.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(a.length!==l.length)return!1;for(let f=0;f<a.length;f+=1){let g=a[f],b=l[f];if(g.code!==b.code||g.type!==void 0&&g.type!==b.type||g.quantity!==b.quantity||g.totalAmount!==b.totalAmount||g.overrideAmount!==b.overrideAmount||g.currency!==b.currency)return!1}let s=[...t.couponCodes??[]].sort(),S=[...e.coupons??[]].sort();return s.length===S.length&&s.every((f,g)=>f===S[g])}function gi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:s,error:S,onComplete:f,onError:g,onInstrument:b,onDecline:T,onCountryChange:B,onZipChange:u,showPayPal:w=!0,showStripe:be=!0,enabledPaymentMethods:j,showApplePay:P=!0,showGooglePay:me=!0,debug:Q=!1,layout:le,theme:ae,buttonsTheme:ve,buttonsStyles:Ze,cardButtonContent:fe,cardBackButtonContent:Bt,cardTitleContent:Xe,showSecurityFooter:xe,onButtonClick:Be,onBeforeButtonClick:ee,enableAVS:te,cardFieldOrder:M,cardPreFormSlot:Ae,avsLayout:Fe,className:De,initialErrorMessage:Ue=null,children:we,checkoutMode:_,confirmLabel:ie,renderConfirmButton:Le,onSessionCompleted:se}){let K=Yc(r),Ee=xn(()=>Gs(ae),[ae]),tt=a??Ee?.appearance,st=n?"embedded_checkout":"standard_checkout",Me=we?"custom_layout":le==="buttons"?"buttons_layout":"default_layout",[V,z]=xt(null),[L,ke]=xt(null),He=Tt(null),[I,Y]=xt(null),R=Tt(null),[v,rt]=xt(null),Ct=xn(()=>n?Do(n):"",[n]),ge=n?`create:${Ct}`:`session:${e??""}`,dt=v?.gateways?.stripe?"stripe":v?.gateways?.paypal?"paypal":void 0,Ie=Tt(new Set),ut=Tt(ge),Et=Tt(ge);Io(()=>{Et.current=ge,ut.current!==ge&&(ut.current=ge,Ie.current.clear())},[ge]);let h=er(x=>{if(Et.current===ge){if(Oa.has(x.name)){if(Ie.current.has(x.name))return;Ie.current.add(x.name)}St(()=>b?.(x))}},[ge,b]),H=Jr(h,ge),Ye=Tt(!1),qe=er(x=>{if(Ye.current)return;let F=x.gateway||!dt?x:{...x,gateway:dt};h(F)},[h,dt]);tr(()=>{H({class:"lifecycle",name:"checkout.mount"})},[H]);let[zt,Lt]=xt(e??""),U=e??zt,lt=n?"":U,[tn,gt]=xt(!0),[Ut,Bn]=xt(null),[Mn,An]=xt("full"),[Zt,Hn]=xt(!1),[fn,qt]=xt(Ue),[rr,wt]=xt(null),[Fn,ot]=xt(null),[lr,kt]=xt(!1),[Pn,It]=xt(void 0),[Yt,gn]=xt(""),[sn,Cn]=xt(!1),[nn,Sn]=xt(!1),[Nt,J]=xt(!1),ln=Tt(0),Dn=Tt(void 0),[Yn,Cr]=xt("loading"),[Sr,cr]=xt(0),Mt=Tt(!1),$e=Tt(!1),dr=Tt(!1),C=Tt(null),nt=xn(()=>({checkoutMode:_??Mn,layout:we?"unknown":le==="buttons"?"buttons":"embedded"}),[_,we,Mn,le]),$t=Tt(f);$t.current=f;let hn=Tt(g);hn.current=g;let ue=Tt(T);ue.current=T,tr(()=>{Kt(L)?.setCheckoutContext(nt),I&&I!==L&&Kt(I)?.setCheckoutContext(nt)},[L,I,nt]);let rn=Tt(se);rn.current=se;let wr=er(x=>{Cr(x),!(x!=="exhausted"||dr.current)&&(dr.current=!0,hn.current?.(new Vt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Lr=er(()=>{Cr("retrying"),cr(x=>x+1)},[]);tr(()=>{Cr("loading"),cr(0),dr.current=!1},[U]),tr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Js,checkout_type:st,checkout_layout:Me,billing_api_url:K})},[Me,st,K]);let cn=xn(()=>n?Do(n,!0):"",[n]),ur=xn(()=>Yt===cn?Pn:void 0,[Pn,Yt,cn]),Wn=xn(()=>n?Da(n,ur):void 0,[n,ur]),Ln=_??Wn?.checkoutMode??"full",At=xn(()=>Wn?{...Wn,checkoutMode:Ln}:void 0,[Wn,Ln]);tr(()=>{It(void 0),gn(cn),Dn.current=void 0,J(!1)},[cn]),tr(()=>{qt(Ue)},[Ue]);let Nn=er((x,F,W)=>{St(()=>{ue.current?.(jt(x,F,W))})},[]),Gn=er(async(x,F)=>{qt(null),ot(null),kt(!1),wt("processing");let W=F?.sessionId??x.id,G=x.gateways?.stripe?"stripe":x.gateways?.paypal?"paypal":void 0,Ce=He.current??R.current,A=Kt(Ce),q=Ce?null:ga(K,o,nt),p={log:m=>{A?A.log(m):q?.log(m)},error:m=>{A?A.error(m):q?.error(m)},terminal:m=>{A?A.terminal(m):q?.terminal(m)},performance:m=>{A?A.performance(m):q?.performance(m)},now:()=>A?.now()??q?.now()??0,elapsed:m=>A?.elapsed(m)??Math.max(0,(q?.now()??m)-m)},N=p.now(),$=!!(F?.initialAutoProcessingError||F?.initialAutoProcessingPending),ct=!1,pt,ne=()=>{ct||(ct=!0,$=!0,pt=p.now(),p.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Se=!1,Wt=()=>{Se||(Se=!0,p.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),p.performance({stage:"processing",durationMs:p.elapsed(N),durationMode:"machine",paymentMethodCategory:"saved"}),pt!==void 0&&p.performance({stage:"recovery",durationMs:p.elapsed(pt),durationMode:"machine",paymentMethodCategory:"saved"}))};p.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Ye.current=!0;try{p.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Ye.current=!1}H({class:"lifecycle",name:"payment.processing.started",provider:G}),$&&ne();let Qe;try{let m=Cs(F?.initialAutoProcessingError),d;if(m)ne(),m.type==="paypal_redirect_required"&&C.current?.publishableKey&&Ys({sessionId:W,publishableKey:C.current.publishableKey,paypalPublishableKey:C.current.paypalPublishableKey}),d=await la(m,{flopay:He.current,paypalFlopay:R.current,attempt3DS:F?.attempt3DS,billingApiUrl:K,sessionId:W,session:x,telemetry:!1}),m.type==="paypal_redirect_required"&&si();else if(F?.initialAutoProcessingPending){let re=(await new ya(K,{telemetry:!1}).waitForCheckoutSessionCompletion(F.initialAutoProcessingPending.sessionId,{initialDelayMs:F.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Hr(re))throw Zo(re);d=Er(re,W)}else{if(F?.initialAutoProcessingError)throw br(F.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:F.initialAutoProcessingError.checkoutMethod});if(F?.fromCreateSession)return F?.fallbackToFull&&(An("full"),Ws("full")),!1;{let y=await Qr({billingApiUrl:K,sessionId:W,session:x,telemetry:!1});y.type==="success"?d=y.result:(ne(),y.type==="paypal_redirect_required"&&C.current?.publishableKey&&Ys({sessionId:W,publishableKey:C.current.publishableKey,paypalPublishableKey:C.current.paypalPublishableKey}),d=await la(y,{flopay:He.current,paypalFlopay:R.current,attempt3DS:F?.attempt3DS,billingApiUrl:K,sessionId:W,session:x,telemetry:!1}),y.type==="paypal_redirect_required"&&si())}}W&&Zr(W),Wt(),$&&(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"}),kt(d.status==="authorized"),wt("success"),await Ao(1200),Qe=()=>$t.current?.(d)}catch(m){let d=Bo(m),y=d.checkoutMethod??xo;qt(d.message),ot(d.message),kt(!1),F?.fallbackToFull&&(p.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),An("full"),Ws("full")),Wt();let pe=d.statusCode!==void 0?Jc(d.statusCode,"unknown"):void 0,re=pe==="4xx"?{requestCategory:"process_payment",statusClass:pe}:{},je=pe===void 0||pe==="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 E=Ks(m,$?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),oe=d.telemetryRequestCategory??"process_payment";Ye.current=!0;try{p.error({...E,...d.telemetryFailureCategory?{failureCategory:d.telemetryFailureCategory}:{},stage:$?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:oe})}finally{Ye.current=!1}H({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:oe,provider:G})}return St(()=>hn.current?.(d)),Nn(y,d,{code:d.code,declineCode:d.declineCode}),wt("error"),await Promise.allSettled([Ao(1500),F?.ensureProvidersReady?F.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{Wt(),q&&Fo(q),wt(null),ot(null)}return St(Qe),!0},[Nn,H,K,o,nt]);tr(()=>{if(typeof window>"u"||$e.current)return;let x=new URLSearchParams(window.location.search),F=x.get("payment_intent_client_secret");if(!F)return;let W=Qc();W&&($e.current=!0,(async()=>{let G,Ce=0;qt(null),ot(null),wt("processing"),Hn(!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:A,paypalFlopay:q}=await da({publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey,billingApiUrl:K,locale:l,telemetry:o});G=Kt(q??A),Ce=G?.now()??0,G?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),G?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let p=(q??A)?.getRawProvider();if(!p)throw Object.assign(new Vt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:N,error:$}=await p.retrievePaymentIntent(F);if($)throw Object.assign(new Vt($.message??"Failed to retrieve PayPal payment status.","api_error",{code:$.code}),{checkoutMethod:"paypal"});let ct=ns(N?.status);if(!N||ct==="failed")throw Object.assign(new Vt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let pt=typeof N.payment_method=="string"?N.payment_method:N.payment_method?.id,ne=ct;if(W.sessionId){let Qe=(await new ya(K,{telemetry:!1}).getUnifiedCheckoutSession(W.sessionId)).data.session;if(Qe&&Qe.status!=="complete"){let m=await Qr({billingApiUrl:K,sessionId:W.sessionId,session:Qe,telemetry:!1,tokenizedData:{id:pt??N.id,type:"card",threeDSecureActionResultTokenId:N.id,isPaypal:!0}});if(m.type!=="success")throw Object.assign(new Vt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ne=m.result.status}}W.sessionId&&Zr(W.sessionId),G?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),G?.performance({stage:"redirect_resume",durationMs:G.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),G?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),wt("success"),await Ao(1200),St(()=>$t.current?.({status:ne,paymentIntentId:N.id,paymentMethodId:pt,checkoutMethod:"paypal"}))}catch(A){let q=Bo(A),p=q.checkoutMethod??"paypal",N=!!(q.declineCode||q.code?.toLowerCase().includes("declin"));if(G)G.performance({stage:"redirect_resume",durationMs:G.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),N?G.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):G.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(N){let $=ga(K,o,nt);$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Fo($)}else ai(K,o,nt,"REDIRECT_RESUME_FAILED","redirect_resume");qt(q.message),ot(q.message),St(()=>hn.current?.(q)),Nn(p,q,{code:q.code,declineCode:q.declineCode}),wt("error"),await Ao(1500)}finally{si(),ed(),wt(null),ot(null),Hn(!1)}})())},[Nn,l,K,o,nt]);let dn=Tt(null),Qt=xn(()=>At?Do(At):"",[At]),On=Tt(At);On.current=At,tr(()=>{Lt(e??"")},[e]),tr(()=>{Mt.current=!1,qt(Ue),ot(null),kt(!1),wt(null)},[Qt,Ue,e]);async function zn(x,F,W){let G=ga(K,o,nt),Ce=new ya(K,{telemetry:!1}),A=!1;try{let q=x.idempotencyKey!==void 0?Vs(x.idempotencyKey):void 0,p=Xs(F,W),N=Zs(F,W);p?.canonicalIdentity===W&&N&&N.canonicalIdentity===void 0&&(ci(F,W,N.idempotencyKey),N={...N,canonicalIdentity:W});let $=q??(N?.canonicalIdentity===W?N.idempotencyKey:void 0),ct,pt=!1;G.log({name:p?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let ne=p?.sid??null,Se=null,Wt,Qe,m=!1;if(ne)try{Se=await Ce.getUnifiedCheckoutSession(ne,p?.nonce),p&&p.canonicalIdentity===void 0&&(od(Se.data.session,x)?(li(F,W,ne,p.nonce??Se.data.session?.clientSecret),N&&N.canonicalIdentity===void 0&&(ci(F,W,N.idempotencyKey),$??($=N.idempotencyKey))):(di(F,W),N=null,$=q,ne=null,Se=null));let y=Se?.data.session?.status,pe=Se?.data.session,re=pe?.clientSecret||p?.nonce;if(ne&&pe?.buyerIdentified===!1&&re&&(Qe=Vr(Ce,ne,re,x.account)),ne&&Se&&y==="complete"){if(ja(ne))return{sid:ne,result:Se};di(F,W),ne=null,Se=null,pt=!0}}catch{G.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),p?.canonicalIdentity===void 0?(di(F,W),$=q):mi(F,W),ne=null}if(!ne){!q&&(pt||!$)&&($=Vs(),ct=$),$&&ci(F,W,$);let y=G.now(),pe=0;G.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let re={...x,idempotencyKey:$,avsCheck:!!te,avsConfig:typeof te=="object"?te:void 0,checkoutType:"embedded_checkout",checkoutLayout:we?"custom_layout":le==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(re,jc,{configurable:!1,enumerable:!1,value:{onAttempt:X=>{pe=Math.max(pe,X)}}});let je=()=>{G.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),G.performance({stage:"session_create",durationMs:G.now()-y,durationMode:"machine",requestCategory:"session_create",attempt:pe,statusClass:"2xx"})},We=X=>{let E=Ks(X,"CHECKOUT_SESSION_CREATE_FAILED","unknown");G.performance({stage:"session_create",durationMs:G.now()-y,durationMode:"machine",requestCategory:"session_create",attempt:pe,statusClass:E.statusClass}),X instanceof Vt&&X.type==="validation_error"?G.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):E.statusClass==="4xx"?G.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(G.error({...E,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),H({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Hc(re)){let X=await Ce.createDetachedSession(re);X.claimed.catch(()=>{}),Se=X.shell,ne=X.sessionId,Qe=X.claim,Wt=X.claimed.then(E=>{let oe=E.data.session?.id??X.sessionId;return oe&&li(F,W,oe,E.data.session?.clientSecret??X.nonce),je(),E},E=>{throw mi(F,W),We(E),E}).finally(()=>Fo(G)),Wt.catch(()=>{}),A=!0,G.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),G.performance({stage:"session_shell",durationMs:G.now()-y,durationMode:"machine",requestCategory:"session_create",attempt:pe,statusClass:"2xx",paymentMethodCategory:"card"})}else Se=await Ce.createAndFetchSession(re),je()}catch(X){throw We(X),X}ne=Se.data.session?.id??ne??"",ne&&!Wt&&li(F,W,ne,Se.data.session?.clientSecret)}let d=Se?.data.session;return!Qe&&ne&&d?.buyerIdentified===!1&&d.clientSecret&&(Qe=Vr(Ce,ne,d.clientSecret,x.account)),{sid:ne??"",result:Se,sdkGeneratedIdempotencyKey:ct,...Wt?{claimed:Wt}:{},...Qe?{claim:Qe}:{},...m?{claimRequiresIdentity:!0}:{}}}finally{A||Fo(G)}}let at=Tt(zn);Io(()=>{at.current=zn},[zn]);let un=er(async(x,F)=>{let W=On.current;if(!W)throw new Vt("createSession is required to bootstrap checkout.","validation_error");let G=Da(W,x),Ce=Do(G),A=rd(G),q=ha.get(Ce);if(!q){let $={canonicalIdentity:Ce,promise:at.current(G,A,Ce),consumers:0,settled:!1};q=$,ha.set(Ce,$);let ct=()=>{$.settled=!0,Hs(Ce,$)};$.promise.then(ct,ct)}q.consumers+=1;let p=!1,N=()=>{p||(p=!0,q.consumers-=1,Hs(Ce,q))};F?.(N);try{let $=await q.promise;dn.current=Ce,x&&(gn(cn),It(pe=>Qi(pe,x)));let{sid:ct,result:pt,claimed:ne,claim:Se,claimRequiresIdentity:Wt}=$;if(Dn.current=Se,J(Wt===!0),z(pt),pt.data.session&&rt(pt.data.session),ct&&Lt(ct),ne){ln.current+=1;let pe=ln.current;Sn(!0),ne.then(re=>{ln.current===pe&&(z(re),re.data.session&&rt(re.data.session),Sn(!1),J(!1))},re=>{ln.current===pe&&(Sn(!1),J(!1),Bn(re instanceof Vt?re:new Vt(re instanceof Error?re.message:"Failed to create session","api_error")))})}else ln.current+=1,Sn(!1),J(!1);let{publishableKey:Qe,paypalPublishableKey:m}=ca(pt),{flopay:d,paypalFlopay:y}=await da({publishableKey:Qe,paypalPublishableKey:m,billingApiUrl:K,locale:l,telemetry:o});return He.current=d,ke(d),R.current=y,Y(y),gt(!1),$}catch($){throw dn.current===Ce&&(dn.current=null),$}finally{F||N()}},[cn,l,K,o]),pn=Tt(Gn);pn.current=Gn;let Un=Tt(un);Un.current=un;let wn=er(async x=>{if(!td(x)||sn)return{sessionId:zt,session:v};Cn(!0);try{let F=await un(x);return{sessionId:F.sid,session:F.result.data.session??null}}finally{Cn(!1)}},[un,sn,zt,v]),Pe=er(async x=>{let F=Dn.current;if(!F)return;let W=ln.current,G=await F(x);ln.current===W&&(z(G),G.data.session&&rt(G.data.session))},[]);tr(()=>{let x=!1,F;if(Bn(null),Qt){let Ce=On.current;return An(Ln),gt(!1),dn.current===Qt?()=>{x=!0}:(rt(es(Ce,_)),(async()=>{let A=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),q=Ln==="auto"&&!Mt.current&&!A;q&&(qt(null),ot(null),wt("processing"));try{let p=await Un.current(void 0,pt=>{F=pt}),N=p.result.data.session??null;C.current=ca(p.result);let $=ii(p.result),ct=ja(p.sid||N?.id);if(!x&&q&&N&&!$&&!ct){Mt.current=!0,await Xc(Qt,p.sdkGeneratedIdempotencyKey,()=>pn.current(N,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:p.result.autoProcessingError,initialAutoProcessingPending:p.result.autoProcessingPending,autoProcessingAttempted:p.result.autoProcessingAttempted,sessionId:p.sid||N.id}));return}!x&&q&&(($||ct)&&(Mt.current=!0),wt(null),ot(null))}catch(p){if(x)return;let N=p instanceof Vt||typeof p=="object"&&p!==null&&"code"in p?p.code:void 0;if(q&&N==="session_auto_completed"){Mt.current=!0,wt("success"),await Ao(1200),x||(St(()=>{$t.current?.({status:"succeeded"})}),wt(null),ot(null));return}q&&(wt(null),ot(null));let $=p instanceof Vt?p:new Vt(p instanceof Error?p.message:"Failed to create session","api_error");Bn($)}finally{F?.(),F=void 0}})(),()=>{x=!0,F?.()})}gt(!0);async function W(){let Ce=!1;try{let A=new ya(K,{telemetry:!1}),q=await A.getUnifiedCheckoutSession(U,t);if(x)return;z(q);let p=q.data.session??null;if(rt(p),!p)throw new Vt("No session data returned","api_error");let N=p.checkoutMode;if(N==="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"){gt(!1),St(()=>{$t.current?.(Er(p,U)),rn.current?.(p.successUrl??"")});return}if(p.status==="complete"){gt(!1),St(()=>{rn.current?.(p.successUrl??"")});return}if(p.status==="expired")throw Xo(p);Ce=!0;let $=_??N??"full";An($),ln.current+=1;let ct=p.clientSecret||t;Dn.current=p.buyerIdentified===!1&&ct?Vr(A,U,ct,{...p.customer?.id?{userId:p.customer.id}:{}}):void 0,Sn(!1),J(!1);let pt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ne=ii(q);if($==="auto"&&!Mt.current&&!pt&&!ne){Mt.current=!0;let Se=G(q);try{if(await pn.current(p,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Se,sessionId:U||p.id}),x)return;await Se,x||gt(!1);return}catch{if(x)return;await Se,x||gt(!1);return}}await G(q),x||gt(!1)}catch(A){if(x)return;Ce&&H({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),A instanceof Vt?!Ce&&!Zc(A)&&ai(K,o,nt,"NETWORK_REQUEST_FAILED","session_read"):ai(K,o,nt,"INTERNAL_SDK_ERROR","checkout_mount");let q=A instanceof Vt?A:new Vt(A instanceof Error?A.message:"Failed to initialize checkout","api_error");Bn(q),gt(!1)}}async function G(Ce){let{publishableKey:A,paypalPublishableKey:q}=ca(Ce);C.current={publishableKey:A,paypalPublishableKey:q};let{flopay:p,paypalFlopay:N}=await da({publishableKey:A,paypalPublishableKey:q,billingApiUrl:K,locale:l,telemetry:o});He.current=p,ke(p),R.current=N,Y(N)}return W(),()=>{x=!0}},[_,Qt,Ln,lt,t]);let en=er(async()=>{if(!(Zt||!v)){Hn(!0),qt(null);try{await Gn(v,{attempt3DS:!0,fallbackToFull:!0,sessionId:U||v.id})}finally{Hn(!1)}}},[U,Zt,Gn,v]),Ft=pi(V),pr=ii(V),qn=xn(()=>{if(!(!V||!v||!V.data.stripe?.publishableKey))return{billingApiUrl:K}},[V,v,K]),mr=!!(n&&!we&&le==="buttons"&&ee&&Ln==="full"),bn=xn(()=>({session:v,loading:tn,error:Ut,checkoutMode:Mn,inlineSessionDraft:At,applyInlineSessionPatch:mr?wn:void 0,inlineSessionPatchProcessing:sn,claimPending:nn,claimRequiresIdentity:Nt,claimBuyerIdentity:Pe}),[v,tn,Ut,Mn,At,mr,wn,sn,nn,Nt,Pe]),kn=!!n&&le==="buttons"&&!pr&&(!L||!qn),Dt=rr?Z(Zn,{status:rr,errorMessage:Fn,authorized:lr}):null;if(tn){if(s)return Ht(nr,{children:[s,Dt]});if(le==="buttons"){let x=Ee?.buttonsLayout?.cardButton?.borderRadius??Ee?.appearance.variables?.borderRadius??8,F=W=>Z("div",{style:{height:W,borderRadius:x,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Ht(nr,{children:[Ht("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[w&&F(Dr),be&&(P||me)&&F(Dr),be&&F(Dr),Z("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Dt]})}return Ht(nr,{children:[Ht("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[Z("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),Z("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Dt]})}return Ut?S?Z(Kn.Provider,{value:bn,children:S(Ut)}):Z(Kn.Provider,{value:bn,children:Z("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ut.message})}):kn?Ht(nr,{children:[Z(Kn.Provider,{value:bn,children:Z(id,{onButtonClick:Be,showPayPal:w,showStripe:be,showApplePay:P,showGooglePay:me,theme:ae,buttonsTheme:ve,buttonsStyles:Ze,cardButtonContent:fe,cardBackButtonContent:Bt,cardTitleContent:Xe})}),Dt]}):pr&&v&&Ft?Ht(nr,{children:[Z(Kn.Provider,{value:bn,children:Ht("div",{className:De,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[fn&&Z(Xr,{icon:!1,children:fn}),Yn==="retrying"&&Z("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Yn==="exhausted"&&Ht("div",{role:"alert",children:[Z("div",{children:"PayPal is temporarily unavailable. Please try again."}),Z("button",{type:"button",onClick:Lr,children:"Retry PayPal"})]}),nn?s??Z("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:Z("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):Yn!=="exhausted"?Z("div",{"aria-hidden":Yn==="retrying"?!0:void 0,style:Yn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:Z(ys,{sessionId:U,nonce:v.clientSecret||void 0,billingApiUrl:K,email:v.customer?.email||At?.account?.email,billingName:[v.customer?.firstName,v.customer?.lastName].filter(Boolean).join(" ")||[At?.account?.firstName,At?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Pe,clientId:Ft.clientId,environment:Ft.environment,currency:(v.currency??"usd").toUpperCase(),isSubscription:v.mode==="subscription",providerObjectType:Ft.providerObjectType,onComplete:f,onErrorChange:qt,onDecline:T,onButtonClick:Be,onInitializationStateChange:wr,allowAutomaticRetry:Sr===0,session:v,telemetry:o,telemetryContext:nt,onInstrument:qe,debug:Q},`${ge}:paypal-init-${Sr}`)}):null]})}),Dt]}):!L||!qn?Z(nr,{children:Dt}):Mn==="confirm"?Ht(nr,{children:[Z(Kn.Provider,{value:bn,children:Z(aa,{flopay:L,paypalFlopay:I,options:qn,onInstrument:qe,children:Ht("div",{className:De,children:[fn&&Z("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:fn}),Le?Le({onConfirm:en,isProcessing:Zt}):Z("button",{type:"button",onClick:en,disabled:Zt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Zt?"not-allowed":"pointer",opacity:Zt?.6:1},children:Zt?"Processing...":ie??"Confirm Purchase"})]})},ge)}),Dt]}):Ht(nr,{children:[Z(Kn.Provider,{value:bn,children:Z(aa,{flopay:L,paypalFlopay:I,options:qn,onInstrument:qe,children:we?Ht(nr,{children:[fn&&Z("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:fn}),Z(ad,{sessionId:U,nonce:v?.clientSecret||void 0,billingApiUrl:K,session:v,children:we})]}):Z(ri,{sessionId:U,nonce:v?.clientSecret||void 0,email:v?.customer?.email||At?.account?.email,userId:v?.customer?.id||At?.account?.userId,firstName:v?.customer?.firstName||At?.account?.firstName,lastName:v?.customer?.lastName||At?.account?.lastName,totalAmount:v?Math.round(Kc(v).total*100):0,currency:v?.currency?.toLowerCase()??"usd",onComplete:f,onError:g,onDecline:T,error:fn,onErrorChange:qt,showPayPal:w,showStripe:be,enabledPaymentMethods:j??V?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:V?.data.stripe?.enabledPaymentMethodCountries,showApplePay:P,showGooglePay:me,layout:le,theme:ae,buttonsTheme:ve,buttonsStyles:Ze,appearance:tt,cardButtonContent:fe,cardBackButtonContent:Bt,cardTitleContent:Xe,onButtonClick:Be,onBeforeButtonClick:ee,onBuyerIdentityReady:Pe,enableAVS:te,...M?{cardFieldOrder:M}:{},...Ae?{cardPreFormSlot:Ae}:{},avsLayout:Fe,country:v?.customer?.country,city:v?.customer?.city,state:v?.customer?.state,onCountryChange:B,onZipChange:u,avsCheck:!!te,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:we?"custom_layout":le==="buttons"?"buttons_layout":"default_layout",className:De,directPaypal:pi(V),isSubscription:v?.mode==="subscription",session:v,dataAttachmentPending:nn,dataAttachmentRequiresIdentity:Nt,debug:Q})},ge)}),Dt]})}function ad({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return Z(nr,{children:oi.Children.map(o,a=>{if(!oi.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:oi.cloneElement(a,s)})})}function id({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:s,cardButtonContent:S,cardBackButtonContent:f,cardTitleContent:g}){let[b,T]=xt(!1),B=xn(()=>Gs(a),[a]),u=xn(()=>{let P=B?.buttonsLayout??Wc(l);return s?{...P,...s,cardButton:{...P.cardButton,...s.cardButton},cardFormContainer:{...P.cardFormContainer,...s.cardFormContainer},backButton:{...P.backButton,...s.backButton},backButtonIcon:{...P.backButtonIcon,...s.backButtonIcon},submitButton:{...P.submitButton,...s.submitButton},title:{...P.title,...s.title}}:P},[B,l,s]),w=B?.buttonsLayout?.cardButton?.borderRadius??B?.appearance.variables?.borderRadius??8,be=P=>Z("div",{style:{height:P,borderRadius:w,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),j=S===void 0?{boxSizing:"border-box",height:Dr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let P=u.cardInputBorder??"#e5e7eb",me=u.cardInputBackground??"white",Q=qr(f),le=qr(g);return Ht("div",{style:{backgroundColor:u.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...u.cardFormContainer},children:[Ht("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ht("button",{type:"button",onClick:()=>T(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...u.backButton},children:[Z("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:Z("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:Z("path",{d:"M15 18l-6-6 6-6"})})}),Z(jr,{content:f})]}),le?Z("div",{style:{flex:1}}):Z("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:Z(Co,{content:g})})]}),Z("div",{style:{backgroundColor:me,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:Z("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Ht("div",{style:{display:"flex"},children:[Z("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:Z("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Z("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:Z("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),Z("div",{style:{backgroundColor:me,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:Z("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Z("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),Z("style",{children:`
|
|
35
|
+
`)}):null,Gi=Pe==="apm-expanding"||Pe==="apm-form"||Pe==="apm-collapsing",Go=Pe==="apm-expanding"?`flopay-card-enter ${Mr}ms cubic-bezier(0, 0, 0.2, 1) both`:Pe==="apm-collapsing"?`flopay-card-exit ${Mr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Jo=Ft?{...Sa,paymentMethodTypes:[Ft]}:null;if(ae==="buttons"){let i=Pe==="buttons"||Pe==="expanding"||Pe==="apm-expanding",S=Pe==="expanding"||Pe==="card"||Pe==="collapsing",D=Xe===void 0?{boxSizing:"border-box",height:ua,padding:"0 1rem"}:{padding:"0.9rem 1rem"},_e=Pe==="expanding"||Pe==="apm-expanding"?`flopay-buttons-exit ${Mr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Pe==="collapsing"||Pe==="apm-collapsing"?`flopay-buttons-enter ${Mr}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,O=Pe==="expanding"?`flopay-card-enter ${Mr}ms cubic-bezier(0, 0, 0.2, 1) both`:Pe==="collapsing"?`flopay-card-exit ${Mr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Te("form",{onSubmit:Ia,className:T,noValidate:!0,style:{position:"relative"},children:[c(Ga,{}),Ce&&c(Zn,{status:Ce,errorMessage:m,authorized:Dn}),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?Ac:{},..._e?{animation:_e,pointerEvents:"none"}:{}},children:[Yi("flopay-direct-paypal-gate-debug"),Wi("flopay-stripe-gate-debug"),co&&I&&Te(Ar,{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(oa,{sessionId:e,nonce:t,billingApiUrl:ne,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,clientId:I.clientId,environment:I.environment,currency:ke.toUpperCase(),isSubscription:Y,providerObjectType:h,onTokenizedBody:In,onComplete:a,onErrorChange:ce,onDecline:s,onTechnicalFailure:Or,onButtonClick:te,runBeforeButtonClick:jn,isProcessing:We,onLoadStateChange:wa,onInitializationStateChange:ka,session:Et,existingOrderId:$?.orderId,debug:Ct},$?.orderId??"fresh")]}),uo&&c(Br,{stripe:Nr,options:Pi,children:c(Fs,{sessionId:e,nonce:t,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,onTokenizedBody:In,onErrorChange:ce,isProcessing:We,onButtonClick:te,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:jn,onLoadStateChange:Ri,placeholderBorderRadius:kr})}),po?c(Br,{stripe:vn,options:vi,children:c(Ds,{sessionId:e,nonce:t,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,intentKind:L>0?"payment":"setup",expressMethods:$o,onTokenizedBody:In,onErrorChange:ce,onButtonClick:te,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:jn,onLoadStateChange:_i,placeholderBorderRadius:kr})}):Ai?c("div",{style:{height:ua,borderRadius:kr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,mo&&c(Ls,{sessionId:e,nonce:t,email:E.email,billingName:[E.firstName,E.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,paymentElementMethods:jo,stripeInstance:vn,paymentElementBaseOptions:Sa,onTokenizedBody:In,onErrorChange:ce,onButtonClick:te,onDecline:s,runBeforeButtonClick:jn,onLoadStateChange:xi,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:y.submitButton,onExpandApm:W,expandedApmMethod:Ft,themeId:ve,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:kr}}),$e&&c("button",{type:"button",onClick:async()=>{We||!(await jn("card")).proceed||(te?.("card"),x())},disabled:We,style:{width:"100%",...D,...y.cardButton,...ni({themeBundle:d,resolvedPrimaryColor:Ir,resolvedBorderRadius:_t,submitButtonStyle:y.submitButton,explicitPrimaryColor:mn?.colorPrimary}),fontSize:y.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:We?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:We?.6:1},onMouseEnter:Re=>{!We&&(d||mn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=fl)},onMouseLeave:Re=>{(d||mn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=Ir)},onMouseDown:Re=>{Re.currentTarget.style.transform="scale(0.985)"},onMouseUp:Re=>{Re.currentTarget.style.transform="scale(1)"},children:c($r,{content:Xe})}),m&&Pe==="buttons"&&c(Xr,{margin:"0.25rem 0",styleOverride:y.errorBanner,children:m})]}),$e&&S&&c("div",{style:{gridArea:"1 / 1",...O?{animation:O}:{},...Pe==="collapsing"?{pointerEvents:"none"}:{}},children:Hi}),j&&Gi&&Ft&&Jo&&vn&&c("div",{style:{gridArea:"1 / 1",...Go?{animation:Go}:{},...Pe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Te("div",{style:{backgroundColor:Ea,borderRadius:Ba,...ho,padding:Ma},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:G,style:{display:"inline-flex",alignItems:"center",gap:_a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.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",...y.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(jr,{content:xe})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:Ta,paddingRight:80,...y.title},children:`Pay with ${Fr(Ft)}`})]}),c(Br,{stripe:vn,options:Jo,children:c(Za,{method:Ft,sessionId:e,nonce:t,email:E.email,billingName:[E.firstName,E.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,onTokenizedBody:In,onErrorChange:ce,onDecline:s,onCancel:G,runBeforeButtonClick:jn,onButtonClick:te,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:y.submitButton,errorText:m})},Ft)]})})]})]})}return Gi&&Ft&&Jo&&vn&&j?Te("form",{onSubmit:Ia,className:T,noValidate:!0,style:{position:"relative"},children:[c(Ga,{}),Ce&&c(Zn,{status:Ce,errorMessage:m,authorized:Dn}),c("div",{style:{...Go?{animation:Go}:{},...Pe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Te("div",{style:{backgroundColor:Ea,borderRadius:Ba,...ho,padding:Ma},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:G,style:{display:"inline-flex",alignItems:"center",gap:_a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:y.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...y.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",...y.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(jr,{content:xe})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:y.titleFontSize??"1.05rem",color:Ta,paddingRight:80,...y.title},children:`Pay with ${Fr(Ft)}`})]}),c(Br,{stripe:vn,options:Jo,children:c(Za,{method:Ft,sessionId:e,nonce:t,email:E.email,billingName:[E.firstName,E.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,onTokenizedBody:In,onErrorChange:ce,onDecline:s,onCancel:G,runBeforeButtonClick:jn,onButtonClick:te,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:y.submitButton,errorText:m})},Ft)]})})]}):Te("form",{onSubmit:Ia,className:T,noValidate:!0,style:{position:"relative"},children:[c(Ga,{}),Ce&&c(Zn,{status:Ce,errorMessage:m,authorized:Dn}),Te("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Yi("flopay-direct-paypal-gate-debug-default"),Wi("flopay-stripe-gate-debug-default"),co&&I&&Te(Ar,{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(oa,{sessionId:e,nonce:t,billingApiUrl:ne,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,clientId:I.clientId,environment:I.environment,currency:ke.toUpperCase(),isSubscription:Y,providerObjectType:h,onTokenizedBody:In,onComplete:a,onErrorChange:ce,onDecline:s,onTechnicalFailure:Or,onButtonClick:te,runBeforeButtonClick:jn,isProcessing:We,onLoadStateChange:wa,onInitializationStateChange:ka,session:Et,existingOrderId:$?.orderId,debug:Ct},$?.orderId??"fresh")]}),uo&&c(Br,{stripe:Nr,options:Pi,children:c(Fs,{sessionId:e,nonce:t,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,onTokenizedBody:In,onErrorChange:ce,isProcessing:We,onButtonClick:te,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:jn,onLoadStateChange:Ri,placeholderBorderRadius:kr})}),po&&c(Br,{stripe:vn,options:vi,children:c(Ds,{sessionId:e,nonce:t,email:E.email,billingName:oe||void 0,onBuyerIdentityReady:Qe,billingApiUrl:ne,intentKind:L>0?"payment":"setup",expressMethods:$o,onTokenizedBody:In,onErrorChange:ce,onButtonClick:te,onDecline:s,onTechnicalFailure:Or,runBeforeButtonClick:jn,onLoadStateChange:_i,placeholderBorderRadius:kr})}),mo&&c(Ls,{sessionId:e,nonce:t,email:E.email,billingName:[E.firstName,E.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ne,paymentElementMethods:jo,stripeInstance:vn,paymentElementBaseOptions:Sa,onTokenizedBody:In,onErrorChange:ce,onButtonClick:te,onDecline:s,runBeforeButtonClick:jn,onLoadStateChange:xi,isProcessing:We,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:y.submitButton,themeId:ve,onExpandApm:W,expandedApmMethod:Ft,buttonAppearance:{backgroundColor:y.cardButton?.backgroundColor,borderColor:y.cardInputBorder,textColor:y.cardButton?.color,borderRadius:kr}})]}),$e&&(ll||sl||cl)&&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&&Hi]})}import{Fragment as nr,jsx as Z,jsxs as Ht}from"react/jsx-runtime";var Dr=44,yi="flopay_checkout_saved_payment_resume",ha=new Map,fa=new Map;function Hs(e,t){t.settled&&t.consumers===0&&ha.get(e)===t&&ha.delete(e)}function Xc(e,t,n){let r=fa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};fa.set(e,a);let l=()=>{fa.get(e)===a&&fa.delete(e)};return o.then(l,l),o}function Ao(e){return new Promise(t=>setTimeout(t,e))}function ga(e,t,n){let r=na({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Js,enabled:t!==!1});return r.beginCheckout(n),r}function Fo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ai(e,t,n,r,o){let a=ga(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Fo(a)}function Zc(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 pi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ii(e){return!e||e.data.stripe?.publishableKey?!1:!!pi(e)?.clientId}function sr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Qc(){if(!sr())return null;try{let e=window.sessionStorage.getItem(yi);return e?JSON.parse(e):null}catch{return null}}function Ys(e){if(sr())try{window.sessionStorage.setItem(yi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function si(){if(sr())try{window.sessionStorage.removeItem(yi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var fi=":idempotency-key";function Xs(e,t){if(!sr())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 li(e,t,n,r){if(sr())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 mi(e,t){if(sr())try{Xs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Zs(e,t){if(!sr())return null;try{let n=window.sessionStorage.getItem(e+fi);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 ci(e,t,n){if(sr())try{window.sessionStorage.setItem(e+fi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function di(e,t){if(mi(e,t),!!sr())try{Zs(e,t)&&window.sessionStorage.removeItem(e+fi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ed(){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 Ws(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 td(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 ui(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function nd(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 Do(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=>ui(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ui(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ui(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:nd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function rd(e,t=!1){let n=Do(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 od(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=Gc(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Vc(t.items,t.subscriptions)).map(f=>({type:f.type,code:f.code??f.providerItemId??f.providerPlanId??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??o).toUpperCase()})).sort((f,g)=>`${f.code}:${f.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),l=e.products.map(f=>({type:f.type,code:f.code??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??e.currency).toUpperCase()})).sort((f,g)=>`${f.code}:${f.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(a.length!==l.length)return!1;for(let f=0;f<a.length;f+=1){let g=a[f],b=l[f];if(g.code!==b.code||g.type!==void 0&&g.type!==b.type||g.quantity!==b.quantity||g.totalAmount!==b.totalAmount||g.overrideAmount!==b.overrideAmount||g.currency!==b.currency)return!1}let s=[...t.couponCodes??[]].sort(),w=[...e.coupons??[]].sort();return s.length===w.length&&s.every((f,g)=>f===w[g])}function gi({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:s,error:w,onComplete:f,onError:g,onInstrument:b,onDecline:T,onCountryChange:M,onZipChange:u,showPayPal:k=!0,showStripe:be=!0,enabledPaymentMethods:j,showApplePay:P=!0,showGooglePay:me=!0,debug:Q=!1,layout:le,theme:ae,buttonsTheme:ve,buttonsStyles:Ze,cardButtonContent:fe,cardBackButtonContent:Mt,cardTitleContent:Xe,showSecurityFooter:xe,onButtonClick:Me,onBeforeButtonClick:ee,enableAVS:te,cardFieldOrder:B,cardPreFormSlot:Ae,avsLayout:Fe,className:De,initialErrorMessage:Ue=null,children:we,checkoutMode:_,confirmLabel:ie,renderConfirmButton:Le,onSessionCompleted:se}){let K=Yc(r),Ee=xn(()=>Gs(ae),[ae]),tt=a??Ee?.appearance,st=n?"embedded_checkout":"standard_checkout",Be=we?"custom_layout":le==="buttons"?"buttons_layout":"default_layout",[V,z]=xt(null),[L,ke]=xt(null),He=Tt(null),[I,Y]=xt(null),R=Tt(null),[v,rt]=xt(null),Ct=xn(()=>n?Do(n):"",[n]),ge=n?`create:${Ct}`:`session:${e??""}`,dt=v?.gateways?.stripe?"stripe":v?.gateways?.paypal?"paypal":void 0,Ie=Tt(new Set),ut=Tt(ge),Et=Tt(ge);Io(()=>{Et.current=ge,ut.current!==ge&&(ut.current=ge,Ie.current.clear())},[ge]);let h=er(x=>{if(Et.current===ge){if(Oa.has(x.name)){if(Ie.current.has(x.name))return;Ie.current.add(x.name)}St(()=>b?.(x))}},[ge,b]),H=Jr(h,ge),Ye=Tt(!1),qe=er(x=>{if(Ye.current)return;let F=x.gateway||!dt?x:{...x,gateway:dt};h(F)},[h,dt]);tr(()=>{H({class:"lifecycle",name:"checkout.mount"})},[H]);let[zt,Lt]=xt(e??""),U=e??zt,lt=n?"":U,[tn,gt]=xt(!0),[Ut,Mn]=xt(null),[Bn,An]=xt("full"),[Zt,Hn]=xt(!1),[fn,qt]=xt(Ue),[rr,wt]=xt(null),[Fn,ot]=xt(null),[lr,kt]=xt(!1),[Pn,It]=xt(void 0),[Yt,gn]=xt(""),[sn,Cn]=xt(!1),[nn,Sn]=xt(!1),[Nt,J]=xt(!1),ln=Tt(0),Dn=Tt(void 0),[Yn,Cr]=xt("loading"),[Sr,cr]=xt(0),Bt=Tt(!1),$e=Tt(!1),dr=Tt(!1),C=Tt(null),nt=xn(()=>({checkoutMode:_??Bn,layout:we?"unknown":le==="buttons"?"buttons":"embedded"}),[_,we,Bn,le]),$t=Tt(f);$t.current=f;let hn=Tt(g);hn.current=g;let ue=Tt(T);ue.current=T,tr(()=>{Kt(L)?.setCheckoutContext(nt),I&&I!==L&&Kt(I)?.setCheckoutContext(nt)},[L,I,nt]);let rn=Tt(se);rn.current=se;let wr=er(x=>{Cr(x),!(x!=="exhausted"||dr.current)&&(dr.current=!0,hn.current?.(new Vt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Lr=er(()=>{Cr("retrying"),cr(x=>x+1)},[]);tr(()=>{Cr("loading"),cr(0),dr.current=!1},[U]),tr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Js,checkout_type:st,checkout_layout:Be,billing_api_url:K})},[Be,st,K]);let cn=xn(()=>n?Do(n,!0):"",[n]),ur=xn(()=>Yt===cn?Pn:void 0,[Pn,Yt,cn]),Wn=xn(()=>n?Da(n,ur):void 0,[n,ur]),Ln=_??Wn?.checkoutMode??"full",At=xn(()=>Wn?{...Wn,checkoutMode:Ln}:void 0,[Wn,Ln]);tr(()=>{It(void 0),gn(cn),Dn.current=void 0,J(!1)},[cn]),tr(()=>{qt(Ue)},[Ue]);let Nn=er((x,F,W)=>{St(()=>{ue.current?.(jt(x,F,W))})},[]),Gn=er(async(x,F)=>{qt(null),ot(null),kt(!1),wt("processing");let W=F?.sessionId??x.id,G=x.gateways?.stripe?"stripe":x.gateways?.paypal?"paypal":void 0,Ce=He.current??R.current,A=Kt(Ce),q=Ce?null:ga(K,o,nt),p={log:m=>{A?A.log(m):q?.log(m)},error:m=>{A?A.error(m):q?.error(m)},terminal:m=>{A?A.terminal(m):q?.terminal(m)},performance:m=>{A?A.performance(m):q?.performance(m)},now:()=>A?.now()??q?.now()??0,elapsed:m=>A?.elapsed(m)??Math.max(0,(q?.now()??m)-m)},N=p.now(),$=!!(F?.initialAutoProcessingError||F?.initialAutoProcessingPending),ct=!1,pt,ne=()=>{ct||(ct=!0,$=!0,pt=p.now(),p.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),p.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Se=!1,Wt=()=>{Se||(Se=!0,p.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),p.performance({stage:"processing",durationMs:p.elapsed(N),durationMode:"machine",paymentMethodCategory:"saved"}),pt!==void 0&&p.performance({stage:"recovery",durationMs:p.elapsed(pt),durationMode:"machine",paymentMethodCategory:"saved"}))};p.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Ye.current=!0;try{p.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Ye.current=!1}H({class:"lifecycle",name:"payment.processing.started",provider:G}),$&&ne();let Qe;try{let m=Cs(F?.initialAutoProcessingError),d;if(m)ne(),m.type==="paypal_redirect_required"&&C.current?.publishableKey&&Ys({sessionId:W,publishableKey:C.current.publishableKey,paypalPublishableKey:C.current.paypalPublishableKey}),d=await la(m,{flopay:He.current,paypalFlopay:R.current,attempt3DS:F?.attempt3DS,billingApiUrl:K,sessionId:W,session:x,telemetry:!1}),m.type==="paypal_redirect_required"&&si();else if(F?.initialAutoProcessingPending){let re=(await new ya(K,{telemetry:!1}).waitForCheckoutSessionCompletion(F.initialAutoProcessingPending.sessionId,{initialDelayMs:F.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Hr(re))throw Zo(re);d=Er(re,W)}else{if(F?.initialAutoProcessingError)throw br(F.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:F.initialAutoProcessingError.checkoutMethod});if(F?.fromCreateSession)return F?.fallbackToFull&&(An("full"),Ws("full")),!1;{let y=await Qr({billingApiUrl:K,sessionId:W,session:x,telemetry:!1});y.type==="success"?d=y.result:(ne(),y.type==="paypal_redirect_required"&&C.current?.publishableKey&&Ys({sessionId:W,publishableKey:C.current.publishableKey,paypalPublishableKey:C.current.paypalPublishableKey}),d=await la(y,{flopay:He.current,paypalFlopay:R.current,attempt3DS:F?.attempt3DS,billingApiUrl:K,sessionId:W,session:x,telemetry:!1}),y.type==="paypal_redirect_required"&&si())}}W&&Zr(W),Wt(),$&&(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"}),kt(d.status==="authorized"),wt("success"),await Ao(1200),Qe=()=>$t.current?.(d)}catch(m){let d=Mo(m),y=d.checkoutMethod??xo;qt(d.message),ot(d.message),kt(!1),F?.fallbackToFull&&(p.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),An("full"),Ws("full")),Wt();let pe=d.statusCode!==void 0?Jc(d.statusCode,"unknown"):void 0,re=pe==="4xx"?{requestCategory:"process_payment",statusClass:pe}:{},je=pe===void 0||pe==="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 E=Ks(m,$?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),oe=d.telemetryRequestCategory??"process_payment";Ye.current=!0;try{p.error({...E,...d.telemetryFailureCategory?{failureCategory:d.telemetryFailureCategory}:{},stage:$?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:oe})}finally{Ye.current=!1}H({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:oe,provider:G})}return St(()=>hn.current?.(d)),Nn(y,d,{code:d.code,declineCode:d.declineCode}),wt("error"),await Promise.allSettled([Ao(1500),F?.ensureProvidersReady?F.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{Wt(),q&&Fo(q),wt(null),ot(null)}return St(Qe),!0},[Nn,H,K,o,nt]);tr(()=>{if(typeof window>"u"||$e.current)return;let x=new URLSearchParams(window.location.search),F=x.get("payment_intent_client_secret");if(!F)return;let W=Qc();W&&($e.current=!0,(async()=>{let G,Ce=0;qt(null),ot(null),wt("processing"),Hn(!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:A,paypalFlopay:q}=await da({publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey,billingApiUrl:K,locale:l,telemetry:o});G=Kt(q??A),Ce=G?.now()??0,G?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),G?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let p=(q??A)?.getRawProvider();if(!p)throw Object.assign(new Vt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:N,error:$}=await p.retrievePaymentIntent(F);if($)throw Object.assign(new Vt($.message??"Failed to retrieve PayPal payment status.","api_error",{code:$.code}),{checkoutMethod:"paypal"});let ct=ns(N?.status);if(!N||ct==="failed")throw Object.assign(new Vt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let pt=typeof N.payment_method=="string"?N.payment_method:N.payment_method?.id,ne=ct;if(W.sessionId){let Qe=(await new ya(K,{telemetry:!1}).getUnifiedCheckoutSession(W.sessionId)).data.session;if(Qe&&Qe.status!=="complete"){let m=await Qr({billingApiUrl:K,sessionId:W.sessionId,session:Qe,telemetry:!1,tokenizedData:{id:pt??N.id,type:"card",threeDSecureActionResultTokenId:N.id,isPaypal:!0}});if(m.type!=="success")throw Object.assign(new Vt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ne=m.result.status}}W.sessionId&&Zr(W.sessionId),G?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),G?.performance({stage:"redirect_resume",durationMs:G.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),G?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),wt("success"),await Ao(1200),St(()=>$t.current?.({status:ne,paymentIntentId:N.id,paymentMethodId:pt,checkoutMethod:"paypal"}))}catch(A){let q=Mo(A),p=q.checkoutMethod??"paypal",N=!!(q.declineCode||q.code?.toLowerCase().includes("declin"));if(G)G.performance({stage:"redirect_resume",durationMs:G.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),N?G.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):G.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(N){let $=ga(K,o,nt);$.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Fo($)}else ai(K,o,nt,"REDIRECT_RESUME_FAILED","redirect_resume");qt(q.message),ot(q.message),St(()=>hn.current?.(q)),Nn(p,q,{code:q.code,declineCode:q.declineCode}),wt("error"),await Ao(1500)}finally{si(),ed(),wt(null),ot(null),Hn(!1)}})())},[Nn,l,K,o,nt]);let dn=Tt(null),Qt=xn(()=>At?Do(At):"",[At]),On=Tt(At);On.current=At,tr(()=>{Lt(e??"")},[e]),tr(()=>{Bt.current=!1,qt(Ue),ot(null),kt(!1),wt(null)},[Qt,Ue,e]);async function zn(x,F,W){let G=ga(K,o,nt),Ce=new ya(K,{telemetry:!1}),A=!1;try{let q=x.idempotencyKey!==void 0?Vs(x.idempotencyKey):void 0,p=Xs(F,W),N=Zs(F,W);p?.canonicalIdentity===W&&N&&N.canonicalIdentity===void 0&&(ci(F,W,N.idempotencyKey),N={...N,canonicalIdentity:W});let $=q??(N?.canonicalIdentity===W?N.idempotencyKey:void 0),ct,pt=!1;G.log({name:p?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let ne=p?.sid??null,Se=null,Wt,Qe,m=!1;if(ne)try{Se=await Ce.getUnifiedCheckoutSession(ne,p?.nonce),p&&p.canonicalIdentity===void 0&&(od(Se.data.session,x)?(li(F,W,ne,p.nonce??Se.data.session?.clientSecret),N&&N.canonicalIdentity===void 0&&(ci(F,W,N.idempotencyKey),$??($=N.idempotencyKey))):(di(F,W),N=null,$=q,ne=null,Se=null));let y=Se?.data.session?.status,pe=Se?.data.session,re=pe?.clientSecret||p?.nonce;if(ne&&pe?.buyerIdentified===!1&&re&&(Qe=Vr(Ce,ne,re,x.account)),ne&&Se&&y==="complete"){if(ja(ne))return{sid:ne,result:Se};di(F,W),ne=null,Se=null,pt=!0}}catch{G.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),p?.canonicalIdentity===void 0?(di(F,W),$=q):mi(F,W),ne=null}if(!ne){!q&&(pt||!$)&&($=Vs(),ct=$),$&&ci(F,W,$);let y=G.now(),pe=0;G.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let re={...x,idempotencyKey:$,avsCheck:!!te,avsConfig:typeof te=="object"?te:void 0,checkoutType:"embedded_checkout",checkoutLayout:we?"custom_layout":le==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(re,jc,{configurable:!1,enumerable:!1,value:{onAttempt:X=>{pe=Math.max(pe,X)}}});let je=()=>{G.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),G.performance({stage:"session_create",durationMs:G.now()-y,durationMode:"machine",requestCategory:"session_create",attempt:pe,statusClass:"2xx"})},We=X=>{let E=Ks(X,"CHECKOUT_SESSION_CREATE_FAILED","unknown");G.performance({stage:"session_create",durationMs:G.now()-y,durationMode:"machine",requestCategory:"session_create",attempt:pe,statusClass:E.statusClass}),X instanceof Vt&&X.type==="validation_error"?G.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):E.statusClass==="4xx"?G.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(G.error({...E,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),H({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Hc(re)){let X=await Ce.createDetachedSession(re);X.claimed.catch(()=>{}),Se=X.shell,ne=X.sessionId,Qe=X.claim,Wt=X.claimed.then(E=>{let oe=E.data.session?.id??X.sessionId;return oe&&li(F,W,oe,E.data.session?.clientSecret??X.nonce),je(),E},E=>{throw mi(F,W),We(E),E}).finally(()=>Fo(G)),Wt.catch(()=>{}),A=!0,G.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),G.performance({stage:"session_shell",durationMs:G.now()-y,durationMode:"machine",requestCategory:"session_create",attempt:pe,statusClass:"2xx",paymentMethodCategory:"card"})}else Se=await Ce.createAndFetchSession(re),je()}catch(X){throw We(X),X}ne=Se.data.session?.id??ne??"",ne&&!Wt&&li(F,W,ne,Se.data.session?.clientSecret)}let d=Se?.data.session;return!Qe&&ne&&d?.buyerIdentified===!1&&d.clientSecret&&(Qe=Vr(Ce,ne,d.clientSecret,x.account)),{sid:ne??"",result:Se,sdkGeneratedIdempotencyKey:ct,...Wt?{claimed:Wt}:{},...Qe?{claim:Qe}:{},...m?{claimRequiresIdentity:!0}:{}}}finally{A||Fo(G)}}let at=Tt(zn);Io(()=>{at.current=zn},[zn]);let un=er(async(x,F)=>{let W=On.current;if(!W)throw new Vt("createSession is required to bootstrap checkout.","validation_error");let G=Da(W,x),Ce=Do(G),A=rd(G),q=ha.get(Ce);if(!q){let $={canonicalIdentity:Ce,promise:at.current(G,A,Ce),consumers:0,settled:!1};q=$,ha.set(Ce,$);let ct=()=>{$.settled=!0,Hs(Ce,$)};$.promise.then(ct,ct)}q.consumers+=1;let p=!1,N=()=>{p||(p=!0,q.consumers-=1,Hs(Ce,q))};F?.(N);try{let $=await q.promise;dn.current=Ce,x&&(gn(cn),It(pe=>Qi(pe,x)));let{sid:ct,result:pt,claimed:ne,claim:Se,claimRequiresIdentity:Wt}=$;if(Dn.current=Se,J(Wt===!0),z(pt),pt.data.session&&rt(pt.data.session),ct&&Lt(ct),ne){ln.current+=1;let pe=ln.current;Sn(!0),ne.then(re=>{ln.current===pe&&(z(re),re.data.session&&rt(re.data.session),Sn(!1),J(!1))},re=>{ln.current===pe&&(Sn(!1),J(!1),Mn(re instanceof Vt?re:new Vt(re instanceof Error?re.message:"Failed to create session","api_error")))})}else ln.current+=1,Sn(!1),J(!1);let{publishableKey:Qe,paypalPublishableKey:m}=ca(pt),{flopay:d,paypalFlopay:y}=await da({publishableKey:Qe,paypalPublishableKey:m,billingApiUrl:K,locale:l,telemetry:o});return He.current=d,ke(d),R.current=y,Y(y),gt(!1),$}catch($){throw dn.current===Ce&&(dn.current=null),$}finally{F||N()}},[cn,l,K,o]),pn=Tt(Gn);pn.current=Gn;let Un=Tt(un);Un.current=un;let wn=er(async x=>{if(!td(x)||sn)return{sessionId:zt,session:v};Cn(!0);try{let F=await un(x);return{sessionId:F.sid,session:F.result.data.session??null}}finally{Cn(!1)}},[un,sn,zt,v]),Pe=er(async x=>{let F=Dn.current;if(!F)return;let W=ln.current,G=await F(x);ln.current===W&&(z(G),G.data.session&&rt(G.data.session))},[]);tr(()=>{let x=!1,F;if(Mn(null),Qt){let Ce=On.current;return An(Ln),gt(!1),dn.current===Qt?()=>{x=!0}:(rt(es(Ce,_)),(async()=>{let A=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),q=Ln==="auto"&&!Bt.current&&!A;q&&(qt(null),ot(null),wt("processing"));try{let p=await Un.current(void 0,pt=>{F=pt}),N=p.result.data.session??null;C.current=ca(p.result);let $=ii(p.result),ct=ja(p.sid||N?.id);if(!x&&q&&N&&!$&&!ct){Bt.current=!0,await Xc(Qt,p.sdkGeneratedIdempotencyKey,()=>pn.current(N,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:p.result.autoProcessingError,initialAutoProcessingPending:p.result.autoProcessingPending,autoProcessingAttempted:p.result.autoProcessingAttempted,sessionId:p.sid||N.id}));return}!x&&q&&(($||ct)&&(Bt.current=!0),wt(null),ot(null))}catch(p){if(x)return;let N=p instanceof Vt||typeof p=="object"&&p!==null&&"code"in p?p.code:void 0;if(q&&N==="session_auto_completed"){Bt.current=!0,wt("success"),await Ao(1200),x||(St(()=>{$t.current?.({status:"succeeded"})}),wt(null),ot(null));return}q&&(wt(null),ot(null));let $=p instanceof Vt?p:new Vt(p instanceof Error?p.message:"Failed to create session","api_error");Mn($)}finally{F?.(),F=void 0}})(),()=>{x=!0,F?.()})}gt(!0);async function W(){let Ce=!1;try{let A=new ya(K,{telemetry:!1}),q=await A.getUnifiedCheckoutSession(U,t);if(x)return;z(q);let p=q.data.session??null;if(rt(p),!p)throw new Vt("No session data returned","api_error");let N=p.checkoutMode;if(N==="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"){gt(!1),St(()=>{$t.current?.(Er(p,U)),rn.current?.(p.successUrl??"")});return}if(p.status==="complete"){gt(!1),St(()=>{rn.current?.(p.successUrl??"")});return}if(p.status==="expired")throw Xo(p);Ce=!0;let $=_??N??"full";An($),ln.current+=1;let ct=p.clientSecret||t;Dn.current=p.buyerIdentified===!1&&ct?Vr(A,U,ct,{...p.customer?.id?{userId:p.customer.id}:{}}):void 0,Sn(!1),J(!1);let pt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ne=ii(q);if($==="auto"&&!Bt.current&&!pt&&!ne){Bt.current=!0;let Se=G(q);try{if(await pn.current(p,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Se,sessionId:U||p.id}),x)return;await Se,x||gt(!1);return}catch{if(x)return;await Se,x||gt(!1);return}}await G(q),x||gt(!1)}catch(A){if(x)return;Ce&&H({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),A instanceof Vt?!Ce&&!Zc(A)&&ai(K,o,nt,"NETWORK_REQUEST_FAILED","session_read"):ai(K,o,nt,"INTERNAL_SDK_ERROR","checkout_mount");let q=A instanceof Vt?A:new Vt(A instanceof Error?A.message:"Failed to initialize checkout","api_error");Mn(q),gt(!1)}}async function G(Ce){let{publishableKey:A,paypalPublishableKey:q}=ca(Ce);C.current={publishableKey:A,paypalPublishableKey:q};let{flopay:p,paypalFlopay:N}=await da({publishableKey:A,paypalPublishableKey:q,billingApiUrl:K,locale:l,telemetry:o});He.current=p,ke(p),R.current=N,Y(N)}return W(),()=>{x=!0}},[_,Qt,Ln,lt,t]);let en=er(async()=>{if(!(Zt||!v)){Hn(!0),qt(null);try{await Gn(v,{attempt3DS:!0,fallbackToFull:!0,sessionId:U||v.id})}finally{Hn(!1)}}},[U,Zt,Gn,v]),Ft=pi(V),pr=ii(V),qn=xn(()=>{if(!(!V||!v||!V.data.stripe?.publishableKey))return{billingApiUrl:K}},[V,v,K]),mr=!!(n&&!we&&le==="buttons"&&ee&&Ln==="full"),bn=xn(()=>({session:v,loading:tn,error:Ut,checkoutMode:Bn,inlineSessionDraft:At,applyInlineSessionPatch:mr?wn:void 0,inlineSessionPatchProcessing:sn,claimPending:nn,claimRequiresIdentity:Nt,claimBuyerIdentity:Pe}),[v,tn,Ut,Bn,At,mr,wn,sn,nn,Nt,Pe]),kn=!!n&&le==="buttons"&&!pr&&(!L||!qn),Dt=rr?Z(Zn,{status:rr,errorMessage:Fn,authorized:lr}):null;if(tn){if(s)return Ht(nr,{children:[s,Dt]});if(le==="buttons"){let x=Ee?.buttonsLayout?.cardButton?.borderRadius??Ee?.appearance.variables?.borderRadius??8,F=W=>Z("div",{style:{height:W,borderRadius:x,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Ht(nr,{children:[Ht("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[k&&F(Dr),be&&(P||me)&&F(Dr),be&&F(Dr),Z("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Dt]})}return Ht(nr,{children:[Ht("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[Z("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),Z("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Dt]})}return Ut?w?Z(Kn.Provider,{value:bn,children:w(Ut)}):Z(Kn.Provider,{value:bn,children:Z("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ut.message})}):kn?Ht(nr,{children:[Z(Kn.Provider,{value:bn,children:Z(id,{onButtonClick:Me,showPayPal:k,showStripe:be,showApplePay:P,showGooglePay:me,theme:ae,buttonsTheme:ve,buttonsStyles:Ze,cardButtonContent:fe,cardBackButtonContent:Mt,cardTitleContent:Xe})}),Dt]}):pr&&v&&Ft?Ht(nr,{children:[Z(Kn.Provider,{value:bn,children:Ht("div",{className:De,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[fn&&Z(Xr,{icon:!1,children:fn}),Yn==="retrying"&&Z("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Yn==="exhausted"&&Ht("div",{role:"alert",children:[Z("div",{children:"PayPal is temporarily unavailable. Please try again."}),Z("button",{type:"button",onClick:Lr,children:"Retry PayPal"})]}),nn?s??Z("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:Z("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):Yn!=="exhausted"?Z("div",{"aria-hidden":Yn==="retrying"?!0:void 0,style:Yn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:Z(ys,{sessionId:U,nonce:v.clientSecret||void 0,billingApiUrl:K,email:v.customer?.email||At?.account?.email,billingName:[v.customer?.firstName,v.customer?.lastName].filter(Boolean).join(" ")||[At?.account?.firstName,At?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Pe,clientId:Ft.clientId,environment:Ft.environment,currency:(v.currency??"usd").toUpperCase(),isSubscription:v.mode==="subscription",providerObjectType:Ft.providerObjectType,onComplete:f,onErrorChange:qt,onDecline:T,onButtonClick:Me,onInitializationStateChange:wr,allowAutomaticRetry:Sr===0,session:v,telemetry:o,telemetryContext:nt,onInstrument:qe,debug:Q},`${ge}:paypal-init-${Sr}`)}):null]})}),Dt]}):!L||!qn?Z(nr,{children:Dt}):Bn==="confirm"?Ht(nr,{children:[Z(Kn.Provider,{value:bn,children:Z(aa,{flopay:L,paypalFlopay:I,options:qn,onInstrument:qe,children:Ht("div",{className:De,children:[fn&&Z("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:fn}),Le?Le({onConfirm:en,isProcessing:Zt}):Z("button",{type:"button",onClick:en,disabled:Zt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Zt?"not-allowed":"pointer",opacity:Zt?.6:1},children:Zt?"Processing...":ie??"Confirm Purchase"})]})},ge)}),Dt]}):Ht(nr,{children:[Z(Kn.Provider,{value:bn,children:Z(aa,{flopay:L,paypalFlopay:I,options:qn,onInstrument:qe,children:we?Ht(nr,{children:[fn&&Z("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:fn}),Z(ad,{sessionId:U,nonce:v?.clientSecret||void 0,billingApiUrl:K,session:v,children:we})]}):Z(ri,{sessionId:U,nonce:v?.clientSecret||void 0,email:v?.customer?.email||At?.account?.email,userId:v?.customer?.id||At?.account?.userId,firstName:v?.customer?.firstName||At?.account?.firstName,lastName:v?.customer?.lastName||At?.account?.lastName,totalAmount:v?Math.round(Kc(v).total*100):0,currency:v?.currency?.toLowerCase()??"usd",onComplete:f,onError:g,onDecline:T,error:fn,onErrorChange:qt,showPayPal:k,showStripe:be,enabledPaymentMethods:j??V?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:V?.data.stripe?.enabledPaymentMethodCountries,showApplePay:P,showGooglePay:me,layout:le,theme:ae,buttonsTheme:ve,buttonsStyles:Ze,appearance:tt,cardButtonContent:fe,cardBackButtonContent:Mt,cardTitleContent:Xe,onButtonClick:Me,onBeforeButtonClick:ee,onBuyerIdentityReady:Pe,enableAVS:te,...B?{cardFieldOrder:B}:{},...Ae?{cardPreFormSlot:Ae}:{},avsLayout:Fe,country:v?.customer?.country,city:v?.customer?.city,state:v?.customer?.state,onCountryChange:M,onZipChange:u,avsCheck:!!te,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:we?"custom_layout":le==="buttons"?"buttons_layout":"default_layout",className:De,directPaypal:pi(V),isSubscription:v?.mode==="subscription",session:v,dataAttachmentPending:nn,dataAttachmentRequiresIdentity:Nt,debug:Q})},ge)}),Dt]})}function ad({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return Z(nr,{children:oi.Children.map(o,a=>{if(!oi.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:oi.cloneElement(a,s)})})}function id({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:s,cardButtonContent:w,cardBackButtonContent:f,cardTitleContent:g}){let[b,T]=xt(!1),M=xn(()=>Gs(a),[a]),u=xn(()=>{let P=M?.buttonsLayout??Wc(l);return s?{...P,...s,cardButton:{...P.cardButton,...s.cardButton},cardFormContainer:{...P.cardFormContainer,...s.cardFormContainer},backButton:{...P.backButton,...s.backButton},backButtonIcon:{...P.backButtonIcon,...s.backButtonIcon},submitButton:{...P.submitButton,...s.submitButton},title:{...P.title,...s.title}}:P},[M,l,s]),k=M?.buttonsLayout?.cardButton?.borderRadius??M?.appearance.variables?.borderRadius??8,be=P=>Z("div",{style:{height:P,borderRadius:k,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),j=w===void 0?{boxSizing:"border-box",height:Dr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let P=u.cardInputBorder??"#e5e7eb",me=u.cardInputBackground??"white",Q=qr(f),le=qr(g);return Ht("div",{style:{backgroundColor:u.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...u.cardFormContainer},children:[Ht("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ht("button",{type:"button",onClick:()=>T(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...u.backButton},children:[Z("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:Z("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:Z("path",{d:"M15 18l-6-6 6-6"})})}),Z(jr,{content:f})]}),le?Z("div",{style:{flex:1}}):Z("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:Z(Co,{content:g})})]}),Z("div",{style:{backgroundColor:me,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:Z("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Ht("div",{style:{display:"flex"},children:[Z("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:Z("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Z("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:Z("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),Z("div",{style:{backgroundColor:me,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:Z("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Z("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),Z("style",{children:`
|
|
36
36
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
37
37
|
@keyframes flopay-interim-expand {
|
|
38
38
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
39
39
|
40% { opacity: 1; }
|
|
40
40
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
41
41
|
}
|
|
42
|
-
`})]})}return Ht("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&be(Dr),n&&(r||o)&&be(Dr),n&&Z("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:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:Z($r,{content:
|
|
42
|
+
`})]})}return Ht("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&be(Dr),n&&(r||o)&&be(Dr),n&&Z("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:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:Z($r,{content:w})}),Z("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as fd,jsx as oo,jsxs as gd}from"react/jsx-runtime";var dd=44;function Qs(e){return new Promise(t=>setTimeout(t,e))}function ud(e,t){return e instanceof ao?e:new ao(e instanceof Error?e.message:t,"api_error")}function pd(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function md(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 yd({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:s,subscriptions:w,account:f,successUrl:g,cancelUrl:b,couponCodes:T,tagsData:M,utmMetadata:u,billingApiUrl:k,locale:be,theme:j,appearance:P,buttonsTheme:me,buttonsStyles:Q,onSuccess:le,onError:ae,onDecline:ve,children:Ze,disabled:fe=!1,type:Mt="button",style:Xe,...xe}){let Me=Lo(()=>sd(k),[k]),ee=Lo(()=>md({createSession:n,clientId:a,products:l,items:s,subscriptions:w,account:f,successUrl:g,cancelUrl:b,couponCodes:T,tagsData:M,utmMetadata:u}),[f,b,a,T,n,l,s,w,g,M,u]),[te,B]=No(!1),[Ae,Fe]=No(null),[De,Ue]=No(null),[we,_]=No(!1),[ie,Le]=No(null),se=ro(!0),K=ro(null),Ee=ro(ie),tt=ro(le),st=ro(ae),Be=ro(ve);no(()=>{Ee.current=ie},[ie]),no(()=>{tt.current=le},[le]),no(()=>{st.current=ae},[ae]),no(()=>{Be.current=ve},[ve]),no(()=>(se.current=!0,()=>{se.current=!1,K.current?.abort()}),[]),no(()=>{if(typeof window>"u")return;let h=H=>{H.key==="Escape"&&Le(null)};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[]);let V=Pr((h,H=xo)=>{Be.current?.(jt(H,h,{code:h.code,declineCode:h.declineCode}))},[]),z=Pr(async h=>{se.current&&(Ue(null),_(h.result.status==="authorized"),Fe("success"),await Qs(1200),se.current&&St(()=>tt.current?.(h)))},[]),L=Pr(async(h,H)=>{se.current&&(st.current?.(h),H?.emitDecline&&V(h,H.method),Ue(h.message),_(!1),Fe("error"),await Qs(1500))},[V]),ke=Pr(async(h,H,Ye)=>{let qe=h.data.session??null;if(!qe)throw new ao("No session data returned","api_error");let zt=qe.clientSecret||t;if(Hr(qe)){await z({result:Er(qe,H),session:qe,sessionId:qe.id||H,autoCompleted:!1});return}if(qe.status==="expired")throw Xo(qe);try{if(h.autoProcessingPending){let tn=(await new hi(Me).waitForCheckoutSessionCompletion(h.autoProcessingPending.sessionId,{initialDelayMs:h.autoProcessingPending.retryAfterMs})).data.session;if(!Hr(tn))throw Zo(tn);await z({result:Er(tn,H),session:tn,sessionId:tn.id||H,autoCompleted:!1});return}if(h.autoProcessingError){if(h.autoProcessingError.type==="3ds_required"&&h.autoProcessingError.nextActionRedirectUrl&&H&&zt){let U=new AbortController;K.current=U;let lt;try{lt=await Ss({billingApiUrl:Me,sessionId:H,nonce:zt,nextActionRedirectUrl:h.autoProcessingError.nextActionRedirectUrl,signal:U.signal})}finally{K.current===U&&(K.current=null)}if(lt.status==="declined")throw br({type:lt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:lt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:h.autoProcessingError.checkoutMethod});let Ut=(await new hi(Me).waitForCheckoutSessionCompletion(H,{initialDelayMs:0,nonce:zt})).data.session;if(!Hr(Ut))throw br({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:h.autoProcessingError.checkoutMethod});await z({result:Er(Ut,H),session:Ut,sessionId:Ut.id||H,autoCompleted:!1});return}throw br(h.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:h.autoProcessingError.checkoutMethod})}if(Ye?.fromCreateSession&&h.autoProcessingAttempted===!0)throw br({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Lt=await Qr({billingApiUrl:Me,sessionId:H??qe.id,session:qe,nonce:zt});if(Lt.type!=="success")throw br({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await z({result:Lt.result,session:qe,sessionId:qe.id||H,autoCompleted:!1})}catch(Lt){let U=Mo(Lt),lt=qe.id||H;await L(U,{emitDecline:!0,method:U.checkoutMethod??xo}),pd(U,lt)&<&&se.current&&Le({sessionId:lt,errorMessage:U.message,nonce:zt||void 0})}},[t,Me,L,z]),He=Pr(async h=>{if(xe.onClick?.(h),!(h.defaultPrevented||fe||te)){if(Le(null),e&&ee){let H=new ao("Provide either sessionId or create-session props, not both.","validation_error");await L(H),se.current&&(Fe(null),Ue(null));return}if(!e&&!ee){let H=new ao("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await L(H),se.current&&(Fe(null),Ue(null));return}B(!0),Ue(null),_(!1),Fe("processing");try{let H=new hi(Me);if(e){let Ye=await H.getUnifiedCheckoutSession(e,t);await ke(Ye,e);return}try{let Ye=await H.createAndFetchSession({...ee});await ke(Ye,Ye.data.session?.id??null,{fromCreateSession:!0})}catch(Ye){if((Ye instanceof ao||typeof Ye=="object"&&Ye!==null&&"code"in Ye?Ye.code:void 0)==="session_auto_completed"){await z({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ye}}catch(H){await L(ud(H,"Automatic payment failed. Please try again."))}finally{se.current&&(Fe(null),Ue(null),B(!1))}}},[xe.onClick,ee,fe,te,t,ke,Me,e,L,z]),I=Pr(h=>{let H=Ee.current;Le(null),tt.current?.({result:h,session:null,sessionId:H?.sessionId??null,autoCompleted:!1})},[]),Y=Pr(h=>{st.current?.(h)},[]),R=Pr(h=>{Be.current?.(h)},[]),v=Lo(()=>cd(j),[j]),rt=Lo(()=>{let h=v?.buttonsLayout??ld(me);return Q?{...h,...Q,cardButton:{...h.cardButton,...Q.cardButton}}:h},[v,me,Q]),Ct=Lo(()=>{let h=v?.appearance;return P?h?{...h,...P,variables:{...h.variables,...P.variables}}:P:h},[P,v]),ge=Ct?.variables,dt=ge?.colorPrimary??"#4A49FF",Ie=ge?.colorPrimaryHover??Po(dt,.12),ut=ge?.borderRadius??"8px";return gd(fd,{children:[oo("button",{...xe,type:Mt,onClick:He,disabled:fe||te,"aria-busy":te,style:{width:"100%",...Ze===void 0?{boxSizing:"border-box",height:dd,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...rt.cardButton,...ni({themeBundle:v,resolvedPrimaryColor:dt,resolvedBorderRadius:ut,submitButtonStyle:rt.submitButton,explicitPrimaryColor:ge?.colorPrimary}),fontSize:rt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:fe||te?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:fe||te?.6:1,...Xe},onMouseEnter:h=>{xe.onMouseEnter?.(h),!h.defaultPrevented&&!fe&&!te&&(v||ge?.colorPrimary)&&(h.currentTarget.style.backgroundColor=Ie)},onMouseLeave:h=>{xe.onMouseLeave?.(h),!h.defaultPrevented&&(v||ge?.colorPrimary)&&(h.currentTarget.style.backgroundColor=dt)},onMouseDown:h=>{xe.onMouseDown?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(0.985)")},onMouseUp:h=>{xe.onMouseUp?.(h),h.defaultPrevented||(h.currentTarget.style.transform="scale(1)")},children:oo($r,{content:Ze})}),Ae&&oo(Zn,{status:Ae,errorMessage:De,authorized:we}),ie&&oo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:h=>{h.target===h.currentTarget&&Le(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:oo("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:oo(gi,{sessionId:ie.sessionId,nonce:ie.nonce,checkoutMode:"full",billingApiUrl:Me,locale:be,theme:j,...Ct?{appearance:Ct}:{},buttonsTheme:me,buttonsStyles:Q,initialErrorMessage:ie.errorMessage,cardTitleContent:null,onComplete:I,onError:Y,onDecline:R})})})]})}export{oa as DirectPayPalButton,yd as FloPayAutomaticPaymentButton,vl as FloPayCardSetup,bl as FloPayCardSetupError,gi as FloPayCheckout,aa as FloPayProvider,ri as SplitCardForm,Aa as VaultCardFields,bp as dropThirdPartyOnlyError,xl as useCheckout,gr as useFloPay,Na as usePayPalFloPay};
|