@flopay/react 1.6.0 → 1.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -72
- package/dist/card-setup-entry.cjs +2 -2
- package/dist/card-setup-entry.d.cts +1 -1
- package/dist/card-setup-entry.d.ts +1 -1
- package/dist/card-setup-entry.mjs +1 -1
- package/dist/chunk-VWT2TDA6.mjs +6 -0
- package/dist/index.cjs +10 -10
- package/dist/index.d.cts +241 -364
- package/dist/index.d.ts +241 -364
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
- package/dist/chunk-P5QXEIBB.mjs +0 -6
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as jo,b as ut,c as xn,d as Sn,e as wn,f as Or,g as Qa,h as Za,i as hs,j as Ps}from"./chunk-P5QXEIBB.mjs";import{useCallback as ws,useEffect as zr,useState as qo,useMemo as ks,useRef as Ko}from"react";import{resolveBillingApiUrl as Rs}from"@flopay/shared";import{createContext as ei}from"react";var Tn=ei({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),mn=ei({session:null,loading:!1,error:null});var bs=Symbol.for("@flopay/js.telemetry.bridge.v1"),vs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Cs(){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:()=>{},flush:async()=>{},destroy:()=>{}}}function Ss(e){let t=Cs(),n=(a,i)=>a?a.bind(e):i,s=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:s,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,s()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function lo(e){let t=globalThis[vs];return Ss(t?.(e)??{})}function At(e){if(e)return e[bs]}import{jsx as Is}from"react/jsx-runtime";function co({flopay:e,paypalFlopay:t,options:n,children:s}){let[a,i]=qo(e instanceof Promise?null:e),[p,l]=qo(t instanceof Promise||!t?null:t),[b,z]=qo(null),g=Ko(null),R=Ko(null),v=Ko(null);zr(()=>{if(!a)return;let w=At(a);return g.current=w?.beginCheckout()??w?.now()??0,w?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{w?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),zr(()=>{let w=!1;return e instanceof Promise?e.then(I=>{w||i(I)}):i(e),()=>{w=!0}},[e]),zr(()=>{let w=!1;if(!t){l(null);return}return t instanceof Promise?t.then(I=>{w||l(I)}):l(t),()=>{w=!0}},[t]),zr(()=>{if(!a){z(null);return}let w=a.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return z(w),()=>{w.destroy()}},[a,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),zr(()=>{if(!a||!b||R.current===b)return;R.current=b;let w=At(a);w?.log({name:"checkout.rendered",stage:"checkout_render"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(g.current??0),durationMode:"machine"})},[b,a]);let A=ws(()=>{if(!a||!b||v.current===b)return;v.current=b;let w=At(a);w?.log({name:"checkout.interactive",stage:"checkout_interactive"}),w?.performance({stage:"checkout_interactive",durationMs:w.elapsed(g.current??0),durationMode:"machine"})},[b,a]),u=Rs(n?.billingApiUrl),h=ks(()=>({flopay:a,paypalFlopay:p,elements:b,billingApiUrl:u,reportInteractive:A}),[a,p,b,u,A]);return Is(Tn.Provider,{value:h,children:s})}import pa,{useCallback as or,useEffect as Bn,useMemo as yn,useRef as Ut,useState as bt}from"react";import{PaymentAPI as Ro,SESSION_CREATE_TELEMETRY as xl}from"@flopay/js";import{SDK_VERSION as Yi,FloPayError as Et,classifyTelemetryFailure as Ui,isDetachedSessionEligible as Tl,resolveBillingApiUrl as Ml,buildCheckoutDisplayData as $i,resolveButtonsLayoutTheme as Al,resolveIdempotencyKey as ji,resolveTheme as Wi,telemetryStatusClass as Bl}from"@flopay/shared";import"react";import{Fragment as pr,jsx as sn,jsxs as ti}from"react/jsx-runtime";function Es(){return ti(pr,{children:[ti("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:[sn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),sn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",sn("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:sn("path",{d:"M9 18l6-6-6-6"})})]})}function _s(){return sn(pr,{children:"Go back"})}function xs(){return sn(pr,{children:"Secure card checkout"})}function cr(e){return e!==void 0&&(e===""||e===null||e===!1)}function dr({content:e}){return sn(pr,{children:e===void 0?sn(Es,{}):e})}function ur({content:e}){return sn(pr,{children:e===void 0?sn(_s,{}):e})}function Nr({content:e}){return sn(pr,{children:e===void 0?sn(xs,{}):e})}import{ExpressCheckoutElement as _i,PaymentElement as Vs,Elements as nr,useElements as aa,useStripe as ia}from"@stripe/react-stripe-js";import{isAuthorizationOnlySession as ea,normalizeCheckoutFailureOutcome as Hs,resolveButtonsLayoutTheme as Ys,getPostalCodeLabel as ra,getStateLabel as gi,getStateOptions as Ws,COUNTRY_OPTIONS as Gs,resolveAVSConfig as Js,isAVSFieldVisible as Oe,getStateFromPostalCode as hi,isPostalCodeSupported as Xs,isValidPostalCode as Qs,getPostalCodeExample as Zs,filterStripeMethodsByCountry as el,getStripeMethodDisplayName as br,hasVendoredStripeMethodLogo as tl,needsStripeMethodExplicitConfirm as Pi,resolveStripeMethodBrandVariant as nl,partitionStripeMethods as rl,stripeExpressMethodToOptionKey as bi}from"@flopay/shared";import{PaymentAPI as qn,toStripeAppearance as ol}from"@flopay/js";import"react";import{jsx as ni,jsxs as Ts}from"react/jsx-runtime";function mr({children:e,margin:t,icon:n=!0,styleOverride:s}){return Ts("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"}:{},...s??{}},children:[n&&ni("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ni("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]})}var ri={alipay:new URL("./payment-logos/alipay.svg",import.meta.url).href,bancontact:new URL("./payment-logos/bancontact.svg",import.meta.url).href,blik:new URL("./payment-logos/blik.svg",import.meta.url).href,eps:new URL("./payment-logos/eps.svg",import.meta.url).href,giropay:new URL("./payment-logos/giropay.svg",import.meta.url).href,ideal:new URL("./payment-logos/ideal.svg",import.meta.url).href,klarna:new URL("./payment-logos/klarna.svg",import.meta.url).href,p24:new URL("./payment-logos/p24.svg",import.meta.url).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",import.meta.url).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",import.meta.url).href};import al,{useCallback as Ee,useContext as il,useEffect as ct,useMemo as lt,useRef as Be,useState as ke}from"react";import{useContext as Ur}from"react";import{resolveBillingApiUrl as Ms}from"@flopay/shared";function kn(){return Ur(Tn).flopay}function Vo(){return Ur(Tn).paypalFlopay??null}function Ho(){return Ur(Tn).elements}function As(){return Ur(mn)}function uo(){return Ur(Tn).billingApiUrl||Ms()}import{FloPayError as oi,isMoneySettledOutcome as Bs,isSetupIntentClientSecret as Vc}from"@flopay/shared";function ai(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Yo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ii(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],s=n.reduce((i,p)=>i+(p.overrideAmount??p.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(s*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,p)=>({uuid:`synthetic-${i.type??"item"}-${p}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Wo(e,t){return t?{...e,...t}:e}function It(e,t,n){let s=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:s,...a?{code:a}:{},...i?{declineCode:i}:{}}}var Fs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function $n(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:s}of Fs)if(n.test(t))return s;return e}function Zn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function yr(e){return e?.status==="authorized"||e?.status==="complete"}function si(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function po(e){let t=si(e);return new oi(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function mo(e){let t=si(e);return new oi(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 yo(e,t){return e==="processing"||Bs(e,t)}function li(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ci(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function $r(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var fo="flopay_recent_completion_";function fr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(fo+e,JSON.stringify(t))}catch{}}function Go(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(fo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(fo+e),!1):!0}catch{return!1}}function di(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}import{useCallback as go,useEffect as pt,useMemo as qr,useRef as Ze,useState as tr}from"react";import{loadScript as Ls}from"@paypal/paypal-js";import{PaymentAPI as Jo}from"@flopay/js";import{FloPayError as ui,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Xo,SDK_VERSION as Os,generateIdempotencyKey as zs,normalizeGatewayEnvironment as Ns}from"@flopay/shared";function Ds(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function er(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Mn(e){if(typeof e!="object"||e===null)return;let t=e;return er(t.code)??er(t.type)??er(t.name)}function gr(e){if(!(typeof e!="object"||e===null))return er(e.decline_code)}function jr(e){return typeof e!="object"||e===null?!1:er(e.type)?.toLowerCase()==="card_error"||gr(e)!==void 0}function jn(e){let t=Ds(e)?.toLowerCase()??"",s=`${Mn(e)?.toLowerCase()??""} ${t}`;return s.includes("popup")&&s.includes("block")}import{jsx as hr,jsxs as Qo}from"react/jsx-runtime";var ho=45,Us=1e3,$s=11e3,js=["https://www.paypal.com","https://www.sandbox.paypal.com"],pi="We couldn't open PayPal. Try again or choose another payment method.",qs={width:"100%",minHeight:ho,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 mi(e){return e.includes("No ack for postMessage init()")&&js.some(t=>e.includes(t))&&e.includes("10000ms")}function Ks(e){return e?`${pi} Allow pop-ups for this site, then try again.`:pi}function yi({sessionId:e,nonce:t,billingApiUrl:n,email:s,clientId:a,environment:i,currency:p,isSubscription:l,providerObjectType:b,onTokenizedBody:z,onComplete:g,onErrorChange:R,onDecline:v,onTechnicalFailure:A,isProcessing:u=!1,onLoadStateChange:h,onInitializationStateChange:w,allowAutomaticRetry:I=!0,onButtonClick:y,runBeforeButtonClick:he,session:F,existingOrderId:te,telemetry:be,telemetryContext:j,debug:q=!1}){let oe=kn(),ie=qr(()=>{if(oe)return null;let B=lo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Os,enabled:be!==!1});return B.setCheckoutContext(j??{}),B.beginCheckout(j??{}),B},[n,oe,be,j?.checkoutMode,j?.layout]),Ne=qr(()=>At(oe),[oe]);pt(()=>()=>{ie&&ie.flush().catch(()=>{}).finally(()=>ie.destroy())},[ie]);let f=qr(()=>({error:B=>{Ne?Ne.error(B):ie?.error(B)},log:B=>{Ne?Ne.log(B):ie?.log(B)},performance:B=>{Ne?Ne.performance(B):ie?.performance(B)},terminal:B=>{Ne?Ne.terminal(B):ie?.terminal(B)},startTiming:()=>Ne?.now()??ie?.now()??0,elapsed:B=>Ne?.elapsed(B)??Math.max(0,(ie?.now()??B)-B)}),[Ne,ie]),ae=Ze(null),Fe=Ze(0),ve=Ze(null),Re=Ze(!1),[J,le]=tr(!1),[De,se]=tr(!1),[_e,Ue]=tr(0),xe=Ze(0),[H,P]=tr(!1),Q=Ze(!1),We=Ze(!1),[Le,Z]=tr(!1),[_,ce]=tr(!1),K=qr(()=>n.replace(/\/+$/,""),[n]),de=b??(l?"subscription":"order"),et=b==="order"||b==="setup_token",$e=qr(()=>JSON.stringify([K,a,p,i??"",de,et,e,te??""]),[K,a,p,i,te,de,et,e]),it=Ze($e),ue=it.current!==$e,[G,tt]=tr([]),Y=B=>{q&&tt(ot=>[...ot,`${new Date().toISOString().slice(11,23)} ${B}`])},mt=Ze(z),je=Ze(g),qe=Ze(R),$t=Ze(v),nt=Ze(A),en=Ze(y),S=Ze(h),pe=Ze(w),Je=Ze(he),Xe=Ze(F),xt=Ze(s),yt=Ze(t),Te=Ze(null),ft=Ze(0),Ie=Ze(null),tn=Ze(null),Ke=Ze(new Map),Dn=Ze(new Map),Jt=Ze(!1);pt(()=>(Jt.current=!0,()=>{Jt.current=!1}),[]),pt(()=>{mt.current=z},[z]),pt(()=>{je.current=g},[g]),pt(()=>{qe.current=R},[R]),pt(()=>{$t.current=v},[v]),pt(()=>{nt.current=A},[A]),pt(()=>{en.current=y},[y]),pt(()=>{S.current=h},[h]),pt(()=>{pe.current=w},[w]),pt(()=>{Je.current=he},[he]),pt(()=>{Xe.current=F},[F]),pt(()=>{xt.current=s},[s]),pt(()=>{yt.current=t},[t]),pt(()=>{xe.current=_e},[_e]),pt(()=>{H&&ve.current?.focus()},[H,_e]);let fn=go(()=>{window.setTimeout(()=>{ve.current?.focus()},0)},[]),Ln=go(()=>{le(!1),Ue(B=>B+1)},[]),On=go(()=>{P(!1),(ae.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ae.current)?.focus?.()},[]);pt(()=>{!J||!Re.current||(Re.current=!1,On())},[On,J,_e]);let jt=go((B,ot)=>{let He=nt.current;if(He){He("paypal",B,ot);return}qe.current?.(Ks(ot?.popupBlocked??jn(B)))},[]),dt=()=>{Ie.current?.timer&&(clearTimeout(Ie.current.timer),Ie.current.timer=null)},ln=()=>{dt();let B=ft.current+1;return ft.current=B,tn.current=null,Ie.current={generation:B,timer:null,yieldedControl:!1},P(!1),B},qt=B=>B!==void 0&&Ie.current?.generation!==B?!1:(dt(),Ie.current=null,tn.current=null,!0),Kt=B=>{let ot=B?.generation??Ie.current?.generation??ft.current;(!B?.generation||Ie.current?.generation===ot)&&(dt(),Ie.current=null),tn.current=ot,B?.showRetry&&P(!0),B?.remount&&Ln(),B?.focus!==!1&&fn()},Vt=B=>Ie.current?.generation===B&&tn.current!==B,Bt=B=>{typeof document<"u"&&document.visibilityState!=="visible"||(dt(),B.timer=setTimeout(()=>{Ie.current?.generation===B.generation&&(Ie.current=null,tn.current=B.generation,jt(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),P(!0),Ln(),fn())},600))},X=()=>{let B=Ie.current;B?.yieldedControl&&Bt(B)},zn=()=>{let B=Ie.current;B&&(B.yieldedControl=!0,dt())},nn=B=>{let ot=Te.current;return ot&&Dn.current.set(B,ot),B};pt(()=>{let B=()=>{document.visibilityState==="visible"?X():zn()};return document.addEventListener("visibilitychange",B),window.addEventListener("focus",X),window.addEventListener("blur",zn),()=>{document.removeEventListener("visibilitychange",B),window.removeEventListener("focus",X),window.removeEventListener("blur",zn),dt()}},[]),pt(()=>{it.current!==$e&&(it.current=$e,Q.current=!1,We.current=!1,le(!1),se(!1),Z(!1),pe.current?.("loading"))},[$e]),pt(()=>{ut(()=>S.current?.(J&&!Le))},[J,Le]);let Xt=Ns(i);pt(()=>{let B=a?`${a.slice(0,6)}\u2026(len ${a.length})`:"(empty)",ot=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(Y(`mount clientId=${B} env=${i??"(unset)"}\u2192${Xt??"live"} ccy=${p} sub=${l}`),Y(`ua=${ot.slice(0,80)}${ot.length>80?"\u2026":""}`),!a){Y("FAIL: clientId empty \u2014 gateway misconfigured"),Z(!0),f.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!ae.current){Y("FAIL: containerRef not attached");return}Fe.current=f.startTiming(),f.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let He=!1,Ve=!1,Ye=()=>He||Ve,_n,Nn=!1,ar=()=>{_n=zs(),_n||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Nn=!0},gn=null,at=!1,Ht=null,hn=!1,Ct=()=>{!Ht||hn||(hn=!0,Ht.close().catch(()=>{}))},Lt=null,cn=()=>{Lt!==null&&(f.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),f.performance({stage:"overlay_return",durationMs:f.elapsed(Lt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Lt=null)},rn=!1,Qt=ae.current,Zt=null,Ft=null,Se=[],St=c=>{if(!c||typeof c.getBoundingClientRect!="function")return"(no rect)";let o=c.getBoundingClientRect();return`${Math.round(o.width)}\xD7${Math.round(o.height)}`},gt=c=>{if(!c)return"(empty)";try{let o=new URL(c,typeof window<"u"?window.location.href:"https://localhost"),E=o.pathname.toLowerCase();return E.includes("checkcaptcha")||E.includes("captcha")?`CAPTCHA(${o.host}${E})`:E.includes("risk")||E.includes("challenge")?`RISK(${o.host}${E})`:E.includes("smart/buttons")?`smart-buttons(${o.host})`:`${o.host}${E}`.slice(0,100)}catch{return c.slice(0,80)}},Pn=c=>{let o=c.getAttribute("src"),E=c.getAttribute("srcdoc"),ye=c.getAttribute("name"),Pe=c.getAttribute("sandbox"),V=[];return o&&V.push(`src=${gt(o)}`),E&&V.push(`srcdoc[${E.length}ch]`),!o&&!E&&V.push("src=(empty) srcdoc=(empty)"),ye&&V.push(`name=${ye.slice(0,40)}`),Pe!==null&&V.push(`sandbox="${Pe.slice(0,40)}"`),V.join(" ")},ir=c=>{if(!(c instanceof HTMLIFrameElement))return"";try{let o=c.contentDocument;if(!o)return"cd=null";let E=o.body?.children.length??0,ye=o.body?.innerHTML.length??0,Pe=o.head?.innerHTML.length??0;return`cd=same-origin readyState=${o.readyState} body[${E}children,${ye}ch] head[${Pe}ch]`}catch(o){return`cd=cross-origin(${o.message.slice(0,30)})`}},Ot=[],on=c=>{if(Ye())return;let o=c.message??String(c.error??"(no message)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(Y(`window:error ${o.slice(0,140)}`),Ot.push(o))},Dt=c=>{if(Ye())return;let o=c.reason instanceof Error?c.reason.message:String(c.reason??"(no reason)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(Y(`window:rejection ${o.slice(0,140)}`),Ot.push(o))};q&&typeof window<"u"&&(window.addEventListener("error",on),window.addEventListener("unhandledrejection",Dt));let Yn={value:0};if(q&&typeof PerformanceObserver<"u")try{Ft=new PerformanceObserver(c=>{if(!Ye())for(let o of c.getEntries()){if(!o.name.toLowerCase().includes("paypal"))continue;Yn.value+=1;let E=Math.round(o.duration);Y(`net ${E}ms ${o.name.slice(0,90)}`)}}),Ft.observe({type:"resource",buffered:!0})}catch{}let dn=()=>{for(Zt?.disconnect(),Zt=null,Ft?.disconnect(),Ft=null;Se.length;)clearTimeout(Se.pop());q&&typeof window<"u"&&(window.removeEventListener("error",on),window.removeEventListener("unhandledrejection",Dt))},Un=c=>{if(!c)return!1;let o=c.toLowerCase();return o.includes("zoid destroyed")||o.includes("destroyed all components")||o.includes("window closed")||o.includes("detected container element removed")},zt=c=>{if(Ye()||Un(c))return;let o=$n(c)??c;ut(()=>qe.current?.(o))},bn=c=>{He||(Z(!0),c.includes("paypal_ineligible")||f.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",c))},Me=(c,o=!1)=>{if(He)return;let E=Q.current||!I;if(at)return;at=!0,Ve=!0,dn(),Ct();let ye=o||mi(c);if(ye&&I&&!Q.current){Q.current=!0,le(!1),ce(!1),se(!0),pe.current?.("retrying"),gn=setTimeout(()=>{He||Ue(Pe=>Pe+1)},Us);return}if(ye||E){if(le(!1),ce(!1),se(!1),Z(!0),pe.current?.("exhausted"),!We.current){We.current=!0;let Pe=mi(c)?"paypal_init_timeout":o?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Pe)}return}bn(c)};Z(!1);let k=async(c,o=Te.current)=>{if(Ye())return;let E=o?.sessionId??e;if(mt.current){await mt.current(c,{sessionId:E,accountPatch:o?.accountPatch,nonce:o?.nonce});return}let ye=f.startTiming();f.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=()=>{f.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),f.performance({stage:"processing",durationMs:f.elapsed(ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let V=Xe.current,Ge=o?.accountPatch?.email??xt.current,x=o?.accountPatch?.userId??V?.customer?.id??V?.accountData?.userId??"",C=await new Jo(K,{telemetry:!1}).processPayment(x,{sessionId:E,nonce:o?.nonce??yt.current,tokenizedData:c,accountData:{userId:x,email:Ge??V?.customer?.email??"",firstName:o?.accountPatch?.firstName??V?.customer?.firstName??V?.accountData?.firstName??"",lastName:o?.accountPatch?.lastName??V?.customer?.lastName??V?.accountData?.lastName??"",country:o?.accountPatch?.country??V?.customer?.country??V?.accountData?.country??void 0,zip:o?.accountPatch?.zip??V?.customer?.zip??V?.accountData?.zip??void 0}});if(C.ok){if(Ve||He&&Jt.current)return;Pe(),f.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut(()=>je.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ye())return;let T=await C.json().catch(()=>null),ne=T?.message??"PayPal payment failed.",vt=$n(ne)??ne;Pe(),C.status===400&&(typeof T?.declineCode=="string"||!Array.isArray(T?.fields))?f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):C.status===400||C.status===422?f.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):f.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:C.status>=500?"5xx":C.status>=400?"4xx":C.status>=300?"3xx":"unknown",failureCategory:C.status>=500?"server_error":void 0}),zt(vt),ut(()=>$t.current?.(It("paypal",vt,{code:T?.code,declineCode:T?.declineCode})));return}catch(V){if(Ye())return;Pe(),f.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ge=V instanceof Error?V.message:"PayPal payment failed.",x=$n(Ge)??Ge;zt(x),ut(()=>$t.current?.(It("paypal",x)));return}},D=()=>new ui("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),L=c=>Ye()?Promise.reject(D()):Promise.resolve(c),fe=async c=>{if(Ye())throw D();Nn||ar();let o=Te.current,E=o?.sessionId??e,ye=o?.nonce??yt.current;f.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Pe=await new Jo(K,{telemetry:!1}).createSessionIntent(E,ye??"",et?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Xo,paymentMethodId:null,intentKind:de==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:_n});if(Ye())throw D();if(Pe.provider!=="paypal"||Pe.providerObjectType!==de)throw new Error(c);return f.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Pe.providerObjectId},Ce=(c,o)=>{let E=o?.nonce??yt.current;if(!E)return;let ye=o?.sessionId??e,Pe=gr(c)??Mn(c)??"provider_declined";new Jo(K,{telemetry:!1}).reportSessionIntentDecline(ye,E,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Pe}).catch(()=>{})},W=_e;Y("loadScript:scheduled (deferred 1 tick)");let m=null,O=setTimeout(()=>{if(He){Y("loadScript:skipped (cancelled before defer ran)");return}Y("loadScript:start");let c=Xt==="live"?"production":Xt;m=Ls({clientId:a,currency:p,...de==="subscription"?{intent:"subscription",vault:!0}:de==="order"?{intent:"capture"}:{},...c?{environment:c}:{},...c==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),m.then(o=>{if(Y(`loadScript:resolved inactive=${Ye()} ns=${!!o} buttons=${!!o?.Buttons}`),Ye())return;if(!o?.Buttons){Y("FAIL: namespace missing Buttons factory"),Me("PayPal SDK did not expose the Buttons factory.");return}f.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),f.performance({stage:"provider_ready",durationMs:f.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),f.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let E=async N=>{if(Ye()||xe.current!==W)return;let C=N.vaultSetupToken??N.subscriptionID??N.orderID??"",T=C?Dn.current.get(C):Ke.current.get(W);if(!(!T||!Vt(T.generation))&&qt(T.generation)){Dn.current.delete(C),Ke.current.delete(T.surfaceKey),cn();try{if(ce(!0),ut(()=>qe.current?.(null)),!C)throw new ui("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await k(de==="setup_token"?{id:C,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Xo}:et?{id:C,isPaypal:!0,gateway:"paypal",paymentMethodType:Xo}:{id:C,isPaypal:!0},T)}catch(ne){zt(ne instanceof Error?ne.message:"PayPal capture failed.")}finally{Ye()||ce(!1)}}},ye=o.Buttons({style:{layout:"horizontal",height:ho,tagline:!1},onClick:async(N,C)=>{if(Ye()){await C.reject();return}ar();let T=Je.current,ne={};if(T)try{let Nt=await T("paypal");if(Ye()){await C.reject();return}if(!Nt.proceed){Te.current=null,Ke.current.delete(W),await C.reject();return}ne={sessionId:Nt.sessionId,accountPatch:Nt.accountPatch,nonce:Nt.nonce}}catch(Nt){Y(`onClick:runBeforeButtonClick rejected msg=${(Nt instanceof Error?Nt.message:String(Nt)).slice(0,120)}`),Te.current=null,Ke.current.delete(W),await C.reject();return}ut(()=>en.current?.("paypal"));let Yt={generation:ln(),surfaceKey:W,...ne};Te.current=Yt,Ke.current.set(W,Yt),await C.resolve(),f.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),f.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),f.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Lt=f.startTiming()},createOrder:de==="order"?te?()=>L(te).then(nn):()=>fe("Failed to create PayPal order.").then(nn):void 0,createSubscription:de==="subscription"?te?()=>L(te).then(nn):()=>fe("Failed to create PayPal subscription.").then(nn):void 0,createVaultSetupToken:de==="setup_token"?()=>fe("Failed to create PayPal setup token.").then(nn):void 0,onApprove:E,onCancel:()=>{if(Ye())return;let N=Ke.current.get(W)??Te.current;N&&Ke.current.delete(N.surfaceKey),Te.current=null,cn(),f.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Re.current=!0,Kt({generation:N?.generation,remount:!0,focus:!1})},onError:N=>{if(Ye()||xe.current!==W)return;let C=N instanceof Error?N.message:"PayPal failed to render.";if(Y(`onError rendered=${rn} msg=${C.slice(0,120)}`),rn){let T=Ke.current.get(W)??Te.current;if(T&&!Vt(T.generation)||!T&&tn.current===ft.current)return;if(Un(C)){qt(T?.generation);return}if(cn(),jr(N)){f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ce(N,T),ut(()=>$t.current?.(It("paypal",C))),T&&Ke.current.delete(T.surfaceKey),Te.current=null,qt(T?.generation);return}let ne=C.toLowerCase();f.error({errorCode:ne.includes("popup")&&ne.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),T&&Ke.current.delete(T.surfaceKey),Te.current=null,Kt({generation:T?.generation,remount:!0,showRetry:!0,focus:!0}),jt(N,{code:"paypal_runtime_failed"});return}Me(C)}}),Pe=ye.isEligible();if(Y(`isEligible=${Pe}`),f.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Pe){le(!1),Me("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ht=ye,q&&Y(`container:dims ${St(Qt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),q&&typeof MutationObserver<"u"&&(Zt=new MutationObserver(N=>{if(!Ye()){for(let C of N)if(C.type==="childList")C.addedNodes.forEach(T=>{if(!(T instanceof Element))return;let ne=T.tagName.toLowerCase(),vt=(T.getAttribute("title")??"").slice(0,40),Yt=ne==="iframe"?` ${Pn(T)}`:"";Y(`child+ ${ne}${vt?` title="${vt}"`:""}${Yt} dims=${St(T)}`)});else if(C.type==="attributes"&&C.target instanceof Element){let T=C.target;if(T.tagName.toLowerCase()!=="iframe")continue;let ne=C.attributeName;(ne==="src"||ne==="srcdoc")&&Y(`attr~ iframe ${ne}=${ne==="srcdoc"?`[${(T.getAttribute("srcdoc")??"").length}ch]`:gt(T.getAttribute("src"))} dims=${St(T)}`)}}}),Zt.observe(Qt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ge=N=>{if(Ye()||rn)return;let C=Qt.querySelectorAll("iframe"),T=typeof document<"u"&&"hasStorageAccess"in document;Y(`watchdog:${N} container=${St(Qt)} children=${Qt.childElementCount} iframes=${C.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${T} paypalNetRequests=${Yn.value}`),C.forEach((ne,vt)=>{let Yt=(ne.getAttribute("title")??"").slice(0,40);Y(` iframe[${vt}] ${St(ne)}${Yt?` title="${Yt}"`:""} ${Pn(ne)}`);let Nt=ir(ne);Nt&&Y(` ${Nt}`)}),Ot.length===0&&Y(" (no PayPal/zoid window errors captured)")};q&&(Se.push(setTimeout(()=>Ge("3s"),3e3)),Se.push(setTimeout(()=>Ge("8s"),8e3)),Se.push(setTimeout(()=>Ge("15s"),15e3))),Y("render:start");let x=f.startTiming();Se.push(setTimeout(()=>{Ye()||rn||(Y("watchdog:11s retryable render timeout"),Me("PayPal Buttons render did not settle within 11000ms.",!0))},$s)),ye.render(Qt).then(()=>{if(Y(`render:resolved inactive=${Ye()}`),dn(),Ye()){Ct();return}rn=!0,le(!0),se(!1),pe.current?.("ready"),f.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),f.performance({stage:"checkout_render",durationMs:f.elapsed(x),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(N=>{let C=N instanceof Error?N.message:"PayPal failed to render.";Y(`render:rejected msg=${C.slice(0,120)}`),dn(),Me(C)})}).catch(o=>{let E=o instanceof Error?o.message:"PayPal SDK failed to load.";Y(`loadScript:rejected msg=${E.slice(0,120)}`),Me(E)})},0);return()=>{He=!0,clearTimeout(O),gn&&clearTimeout(gn),dn(),Ct()}},[I,K,a,p,i,de,et,e,te,_e,f]);let Hn=q?Qo("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Le?"#fef2f2":"#f3f4f6",border:`1px solid ${Le?"#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=${J} failed=${Le})`,G.length===0?`
|
|
1
|
+
import{a as Qe,b as Mn,c as Qo,d as Hr,e as li,f as ci,g as Rs,h as _s}from"./chunk-VWT2TDA6.mjs";import{dropThirdPartyOnlyError as Mu}from"@flopay/shared";import{PaymentAPI as Fa}from"@flopay/js";import{FloPayError as Br,resolveBillingApiUrl as cc,resolveButtonsLayoutTheme as dc,resolveTheme as uc}from"@flopay/shared";import{useCallback as tr,useEffect as xr,useMemo as oo,useRef as Ar,useState as ao}from"react";import{Fragment as Pr,jsx as hn,jsxs as di}from"react/jsx-runtime";function Ts(){return di(Pr,{children:[di("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:[hn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),hn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",hn("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:hn("path",{d:"M9 18l6-6-6-6"})})]})}function xs(){return hn(Pr,{children:"Go back"})}function As(){return hn(Pr,{children:"Secure card checkout"})}function fr(e){return e!==void 0&&(e===""||e===null||e===!1)}function gr({content:e}){return hn(Pr,{children:e===void 0?hn(Ts,{}):e})}function hr({content:e}){return hn(Pr,{children:e===void 0?hn(xs,{}):e})}function Yr({content:e}){return hn(Pr,{children:e===void 0?hn(As,{}):e})}import{FloPayError as ui,isMoneySettledOutcome as Ms,isSetupIntentClientSecret as kc}from"@flopay/shared";function pi(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function ea(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function mi(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,m)=>a+(m.overrideAmount??m.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,m)=>({uuid:`synthetic-${a.type??"item"}-${m}`,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 ta(e,t){return t?{...e,...t}:e}function Mt(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 Bs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Wn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Bs)if(n.test(t))return r;return e}function lr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function br(e){return e?.status==="authorized"||e?.status==="complete"}function yi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Po(e){let t=yi(e);return new ui(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function bo(e){let t=yi(e);return new ui(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 vo(e,t){return e==="processing"||Ms(e,t)}function fi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function gi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Gr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as Oo,SESSION_CREATE_TELEMETRY as Hl}from"@flopay/js";import{buildCheckoutDisplayData as Yl,classifyTelemetryFailure as es,FloPayError as Ft,foldIntoProducts as Gl,isDetachedSessionEligible as Wl,resolveBillingApiUrl as Jl,resolveButtonsLayoutTheme as Xl,resolveIdempotencyKey as ts,resolveSessionCurrency as Zl,resolveTheme as as,SDK_VERSION as is,telemetryStatusClass as Ql}from"@flopay/shared";import Ca,{useCallback as jn,useEffect as Fn,useMemo as bn,useRef as _t,useState as kt}from"react";import{createContext as hi}from"react";var Pn=hi({flopay:null,paypalFlopay:null,billingApiUrl:""}),kn=hi({session:null,loading:!1,error:null});import{PaymentAPI as oa}from"@flopay/js";import{classifyTelemetryFailure as Gs,FloPayError as bi,generateIdempotencyKey as Ws,normalizeGatewayEnvironment as Js,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as aa,SDK_VERSION as Xs}from"@flopay/shared";import{loadScript as Zs}from"@paypal/paypal-js";import{useCallback as Io,useEffect as ht,useMemo as Jr,useRef as Ye,useState as dr}from"react";function Fs(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 cr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Un(e){if(typeof e!="object"||e===null)return;let t=e;return cr(t.code)??cr(t.type)??cr(t.name)}function vr(e){if(!(typeof e!="object"||e===null))return cr(e.decline_code)}function Wr(e){return typeof e!="object"||e===null?!1:cr(e.type)?.toLowerCase()==="card_error"||vr(e)!==void 0}function Jn(e){let t=Fs(e)?.toLowerCase()??"",r=`${Un(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Ds}from"@flopay/shared";import{useContext as Co}from"react";function Xn(){return Co(Pn).flopay}function na(){return Co(Pn).paypalFlopay??null}function Ls(){return Co(kn)}function Pi(){return Co(Pn).billingApiUrl||Ds()}import{FLO_INSTRUMENT_SCHEMA_VERSION as zs}from"@flopay/shared";import{useCallback as Us,useRef as wo}from"react";import{useEffect as Os,useLayoutEffect as Ns}from"react";var So=typeof window>"u"?Os:Ns;var $s={"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 qs(e){return e==="stripe"||e==="paypal"?e:void 0}function js(e){let t=qs(e.provider),n={schemaVersion:zs,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=$s[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 ra=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Cr(e,t){let n=wo(e);n.current=e;let r=wo(new Set),o=wo(t),a=wo(t);return So(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Us(m=>{if(a.current!==t)return;let d=js(m);if(d){if(ra.has(d.name)){if(r.current.has(d.name))return;r.current.add(d.name)}Qe(()=>n.current?.(d))}},[t])}var Ks=Symbol.for("@flopay/js.telemetry.bridge.v1"),Vs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Hs(){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 Ys(e){let t=Hs(),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 ko(e){let t=globalThis[Vs];return Ys(t?.(e)??{})}function Bt(e){if(e)return e[Ks]}import{jsx as Sr,jsxs as ia}from"react/jsx-runtime";var Eo=45,Qs=1e3,el=11e3,tl=["https://www.paypal.com","https://www.sandbox.paypal.com"],vi="We couldn't open PayPal. Try again or choose another payment method.",nl={width:"100%",minHeight:Eo,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 Ci(e){return e.includes("No ack for postMessage init()")&&tl.some(t=>e.includes(t))&&e.includes("10000ms")}function rl(e){return e?`${vi} Allow pop-ups for this site, then try again.`:vi}function Si({sessionId:e,nonce:t,billingApiUrl:n,email:r,clientId:o,environment:a,currency:m,isSubscription:d,providerObjectType:T,onTokenizedBody:h,onComplete:P,onErrorChange:b,onDecline:x,onTechnicalFailure:U,isProcessing:p=!1,onLoadStateChange:S,onInitializationStateChange:ee,allowAutomaticRetry:W=!0,onButtonClick:v,runBeforeButtonClick:ye,session:j,existingOrderId:J,telemetry:ce,telemetryContext:Se,onInstrument:re,debug:le=!1}){let Ve=Xn(),Ae=Cr(re,e),Ce=Jr(()=>{if(Ve)return null;let I=ko({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Xs,enabled:ce!==!1});return I.setCheckoutContext(Se??{}),I.beginCheckout(Se??{}),I},[n,Ve,ce,Se?.checkoutMode,Se?.layout]),q=Jr(()=>Bt(Ve),[Ve]);ht(()=>()=>{Ce&&Ce.flush().catch(()=>{}).finally(()=>Ce.destroy())},[Ce]);let B=Jr(()=>({error:I=>{q?q.error(I):Ce?.error(I),Ae({class:"technical_error",errorCode:I.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":I.errorCode,requestCategory:I.requestCategory,provider:I.provider})},log:I=>{q?q.log(I):Ce?.log(I),Ae({class:"lifecycle",name:I.name,provider:I.provider})},performance:I=>{q?q.performance(I):Ce?.performance(I)},terminal:I=>{q?q.terminal(I):Ce?.terminal(I)},startTiming:()=>q?.now()??Ce?.now()??0,elapsed:I=>q?.elapsed(I)??Math.max(0,(Ce?.now()??I)-I)}),[Ae,q,Ce]),te=Ye(null),tt=Ye(0),Me=Ye(null),V=Ye(!1),[de,ae]=dr(!1),[ue,ke]=dr(!1),[pe,Re]=dr(0),O=Ye(0),[w,oe]=dr(!1),qe=Ye(!1),De=Ye(!1),[Z,R]=dr(!1),[H,$]=dr(!1),Be=Jr(()=>n.replace(/\/+$/,""),[n]),Ie=T??(d?"subscription":"order"),We=T==="order"||T==="setup_token",Y=Jr(()=>JSON.stringify([Be,o,m,a??"",Ie,We,e,J??""]),[Be,o,m,a,J,Ie,We,e]),mt=Ye(Y),D=mt.current!==Y,[Le,Pt]=dr([]),N=I=>{le&&Pt(Xe=>[...Xe,`${new Date().toISOString().slice(11,23)} ${I}`])},bt=Ye(h),ze=Ye(P),tn=Ye(b),It=Ye(x),k=Ye(U),se=Ye(v),yt=Ye(S),Fe=Ye(ee),Vt=Ye(ye),Xt=Ye(j),Ge=Ye(r),vt=Ye(t),Je=Ye(null),Lt=Ye(0),je=Ye(null),Ht=Ye(null),Et=Ye(new Map),nn=Ye(new Map),Nt=Ye(!1);ht(()=>(Nt.current=!0,()=>{Nt.current=!1}),[]),ht(()=>{bt.current=h},[h]),ht(()=>{ze.current=P},[P]),ht(()=>{tn.current=b},[b]),ht(()=>{It.current=x},[x]),ht(()=>{k.current=U},[U]),ht(()=>{se.current=v},[v]),ht(()=>{yt.current=S},[S]),ht(()=>{Fe.current=ee},[ee]),ht(()=>{Vt.current=ye},[ye]),ht(()=>{Xt.current=j},[j]),ht(()=>{Ge.current=r},[r]),ht(()=>{vt.current=t},[t]),ht(()=>{O.current=pe},[pe]),ht(()=>{w&&Me.current?.focus()},[w,pe]);let En=Io(()=>{window.setTimeout(()=>{Me.current?.focus()},0)},[]),sn=Io(()=>{ae(!1),Re(I=>I+1)},[]),rt=Io(()=>{oe(!1),(te.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??te.current)?.focus?.()},[]);ht(()=>{!de||!V.current||(V.current=!1,rt())},[rt,de,pe]);let zt=Io((I,Xe)=>{let Pe=k.current;if(Pe){Pe("paypal",I,Xe);return}tn.current?.(rl(Xe?.popupBlocked??Jn(I)))},[]),Ke=()=>{je.current?.timer&&(clearTimeout(je.current.timer),je.current.timer=null)},Rn=()=>{Ke();let I=Lt.current+1;return Lt.current=I,Ht.current=null,je.current={generation:I,timer:null,yieldedControl:!1},oe(!1),I},ct=I=>I!==void 0&&je.current?.generation!==I?!1:(Ke(),je.current=null,Ht.current=null,!0),vn=I=>{let Xe=I?.generation??je.current?.generation??Lt.current;(!I?.generation||je.current?.generation===Xe)&&(Ke(),je.current=null),Ht.current=Xe,I?.showRetry&&oe(!0),I?.remount&&sn(),I?.focus!==!1&&En()},Ut=I=>je.current?.generation===I&&Ht.current!==I,ne=I=>{typeof document<"u"&&document.visibilityState!=="visible"||(Ke(),I.timer=setTimeout(()=>{je.current?.generation===I.generation&&(je.current=null,Ht.current=I.generation,zt(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),oe(!0),sn(),En())},600))},Vn=()=>{let I=je.current;I?.yieldedControl&&ne(I)},_n=()=>{let I=je.current;I&&(I.yieldedControl=!0,Ke())},Tn=I=>{let Xe=Je.current;return Xe&&nn.current.set(I,Xe),I};ht(()=>{let I=()=>{document.visibilityState==="visible"?Vn():_n()};return document.addEventListener("visibilitychange",I),window.addEventListener("focus",Vn),window.addEventListener("blur",_n),()=>{document.removeEventListener("visibilitychange",I),window.removeEventListener("focus",Vn),window.removeEventListener("blur",_n),Ke()}},[]),ht(()=>{mt.current!==Y&&(mt.current=Y,qe.current=!1,De.current=!1,ae(!1),ke(!1),R(!1),Fe.current?.("loading"))},[Y]),ht(()=>{Qe(()=>yt.current?.(de&&!Z))},[de,Z]);let xn=Js(a);ht(()=>{let I=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",Xe=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(N(`mount clientId=${I} env=${a??"(unset)"}\u2192${xn??"live"} ccy=${m} sub=${d}`),N(`ua=${Xe.slice(0,80)}${Xe.length>80?"\u2026":""}`),!o){N("FAIL: clientId empty \u2014 gateway misconfigured"),R(!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(!te.current){N("FAIL: containerRef not attached");return}tt.current=B.startTiming(),B.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Pe=!1,Cn=!1,Oe=()=>Pe||Cn,Hn,nr=!1,Yt=()=>{Hn=Ws(),Hn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),nr=!0},dt=null,Zt=!1,Gt=null,ot=!1,ln=()=>{!Gt||ot||(ot=!0,Gt.close().catch(()=>{}))},cn=null,Yn=()=>{cn!==null&&(B.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"overlay_return",durationMs:B.elapsed(cn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),cn=null)},Sn=!1,rn=te.current,dn=null,me=null,Ct=[],at=l=>{if(!l||typeof l.getBoundingClientRect!="function")return"(no rect)";let s=l.getBoundingClientRect();return`${Math.round(s.width)}\xD7${Math.round(s.height)}`},on=l=>{if(!l)return"(empty)";try{let s=new URL(l,typeof window<"u"?window.location.href:"https://localhost"),c=s.pathname.toLowerCase();return c.includes("checkcaptcha")||c.includes("captcha")?`CAPTCHA(${s.host}${c})`:c.includes("risk")||c.includes("challenge")?`RISK(${s.host}${c})`:c.includes("smart/buttons")?`smart-buttons(${s.host})`:`${s.host}${c}`.slice(0,100)}catch{return l.slice(0,80)}},un=l=>{let s=l.getAttribute("src"),c=l.getAttribute("srcdoc"),A=l.getAttribute("name"),K=l.getAttribute("sandbox"),F=[];return s&&F.push(`src=${on(s)}`),c&&F.push(`srcdoc[${c.length}ch]`),!s&&!c&&F.push("src=(empty) srcdoc=(empty)"),A&&F.push(`name=${A.slice(0,40)}`),K!==null&&F.push(`sandbox="${K.slice(0,40)}"`),F.join(" ")},Ln=l=>{if(!(l instanceof HTMLIFrameElement))return"";try{let s=l.contentDocument;if(!s)return"cd=null";let c=s.body?.children.length??0,A=s.body?.innerHTML.length??0,K=s.head?.innerHTML.length??0;return`cd=same-origin readyState=${s.readyState} body[${c}children,${A}ch] head[${K}ch]`}catch(s){return`cd=cross-origin(${s.message.slice(0,30)})`}},pn=[],$t=l=>{if(Oe())return;let s=l.message??String(l.error??"(no message)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(N(`window:error ${s.slice(0,140)}`),pn.push(s))},Wt=l=>{if(Oe())return;let s=l.reason instanceof Error?l.reason.message:String(l.reason??"(no reason)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(N(`window:rejection ${s.slice(0,140)}`),pn.push(s))};le&&typeof window<"u"&&(window.addEventListener("error",$t),window.addEventListener("unhandledrejection",Wt));let Jt={value:0};if(le&&typeof PerformanceObserver<"u")try{me=new PerformanceObserver(l=>{if(!Oe())for(let s of l.getEntries()){if(!s.name.toLowerCase().includes("paypal"))continue;Jt.value+=1;let c=Math.round(s.duration);N(`net ${c}ms ${s.name.slice(0,90)}`)}}),me.observe({type:"resource",buffered:!0})}catch{}let Gn=()=>{for(dn?.disconnect(),dn=null,me?.disconnect(),me=null;Ct.length;)clearTimeout(Ct.pop());le&&typeof window<"u"&&(window.removeEventListener("error",$t),window.removeEventListener("unhandledrejection",Wt))},On=l=>{if(!l)return!1;let s=l.toLowerCase();return s.includes("zoid destroyed")||s.includes("destroyed all components")||s.includes("window closed")||s.includes("detected container element removed")},An=l=>{if(Oe()||On(l))return;let s=Wn(l)??l;Qe(()=>tn.current?.(s))},Nn=l=>{Pe||(R(!0),l.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:",l))},qt=(l,s=!1)=>{if(Pe)return;let c=qe.current||!W;if(Zt)return;Zt=!0,Cn=!0,Gn(),ln();let A=s||Ci(l);if(A&&W&&!qe.current){qe.current=!0,ae(!1),$(!1),ke(!0),Fe.current?.("retrying"),dt=setTimeout(()=>{Pe||Re(K=>K+1)},Qs);return}if(A||c){if(ae(!1),$(!1),ke(!1),R(!0),Fe.current?.("exhausted"),!De.current){De.current=!0;let K=Ci(l)?"paypal_init_timeout":s?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",K)}return}Nn(l)};R(!1);let Ze=async(l,s=Je.current)=>{if(Oe())return;let c=s?.sessionId??e;if(bt.current){await bt.current(l,{sessionId:c,accountPatch:s?.accountPatch,nonce:s?.nonce});return}let A=B.startTiming();B.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let K=()=>{B.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"processing",durationMs:B.elapsed(A),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let F=Xt.current,C=s?.accountPatch?.email??Ge.current,f=s?.accountPatch?.userId??F?.customer?.id??F?.accountData?.userId??"",g=await new oa(Be,{telemetry:!1}).processPayment(f,{sessionId:c,nonce:s?.nonce??vt.current,tokenizedData:l,accountData:{userId:f,email:C??F?.customer?.email??"",firstName:s?.accountPatch?.firstName??F?.customer?.firstName??F?.accountData?.firstName??"",lastName:s?.accountPatch?.lastName??F?.customer?.lastName??F?.accountData?.lastName??"",country:s?.accountPatch?.country??F?.customer?.country??F?.accountData?.country??void 0,zip:s?.accountPatch?.zip??F?.customer?.zip??F?.accountData?.zip??void 0}});if(g.ok){if(Cn||Pe&&Nt.current)return;K(),B.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Qe(()=>ze.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Oe())return;let E=await g.json().catch(()=>null),G=E?.message??"PayPal payment failed.",ie=Wn(G)??G;K(),g.status===400&&(typeof E?.declineCode=="string"||!Array.isArray(E?.fields))?B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):g.status===400||g.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:g.status>=500?"5xx":g.status>=400?"4xx":g.status>=300?"3xx":"unknown",failureCategory:g.status>=500?"server_error":void 0}),An(ie),Qe(()=>It.current?.(Mt("paypal",ie,{code:E?.code,declineCode:E?.declineCode})));return}catch(F){if(Oe())return;K(),B.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let C=F instanceof Error?F.message:"PayPal payment failed.",f=Wn(C)??C;An(f),Qe(()=>It.current?.(Mt("paypal",f)));return}},mn=()=>new bi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),jt=l=>Oe()?Promise.reject(mn()):Promise.resolve(l),ut=async l=>{if(Oe())throw mn();nr||Yt();let s=Je.current,c=s?.sessionId??e,A=s?.nonce??vt.current;B.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let K;try{K=await new oa(Be,{telemetry:!1}).createSessionIntent(c,A??"",We?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:aa,paymentMethodId:null,intentKind:Ie==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Hn})}catch(F){throw B.error({...Gs(F,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),F}if(Oe())throw mn();if(K.provider!=="paypal"||K.providerObjectType!==Ie)throw new Error(l);return B.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),K.providerObjectId},Qt=(l,s)=>{let c=s?.nonce??vt.current;if(!c)return;let A=s?.sessionId??e,K=vr(l)??Un(l)??"provider_declined";new oa(Be,{telemetry:!1}).reportSessionIntentDecline(A,c,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:K}).catch(()=>{})},Rt=pe;N("loadScript:scheduled (deferred 1 tick)");let rr=null,pt=setTimeout(()=>{if(Pe){N("loadScript:skipped (cancelled before defer ran)");return}N("loadScript:start");let l=xn==="live"?"production":xn;rr=Zs({clientId:o,currency:m,...Ie==="subscription"?{intent:"subscription",vault:!0}:Ie==="order"?{intent:"capture"}:{},...l?{environment:l}:{},...l==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),rr.then(s=>{if(N(`loadScript:resolved inactive=${Oe()} ns=${!!s} buttons=${!!s?.Buttons}`),Oe())return;if(!s?.Buttons){N("FAIL: namespace missing Buttons factory"),qt("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(tt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let c=async y=>{if(Oe()||O.current!==Rt)return;let g=y.vaultSetupToken??y.subscriptionID??y.orderID??"",E=g?nn.current.get(g):Et.current.get(Rt);if(!(!E||!Ut(E.generation))&&ct(E.generation)){nn.current.delete(g),Et.current.delete(E.surfaceKey),Yn();try{if($(!0),Qe(()=>tn.current?.(null)),!g)throw new bi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Ze(Ie==="setup_token"?{id:g,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:aa}:We?{id:g,isPaypal:!0,gateway:"paypal",paymentMethodType:aa}:{id:g,isPaypal:!0},E)}catch(G){An(G instanceof Error?G.message:"PayPal capture failed.")}finally{Oe()||$(!1)}}},A=s.Buttons({style:{layout:"horizontal",height:Eo,tagline:!1},onClick:async(y,g)=>{if(Oe()){await g.reject();return}Yt();let E=Vt.current,G={};if(E)try{let Ue=await E("paypal");if(Oe()){await g.reject();return}if(!Ue.proceed){Je.current=null,Et.current.delete(Rt),await g.reject();return}G={sessionId:Ue.sessionId,accountPatch:Ue.accountPatch,nonce:Ue.nonce}}catch(Ue){N(`onClick:runBeforeButtonClick rejected msg=${(Ue instanceof Error?Ue.message:String(Ue)).slice(0,120)}`),Je.current=null,Et.current.delete(Rt),await g.reject();return}Qe(()=>se.current?.("paypal"));let _e={generation:Rn(),surfaceKey:Rt,...G};Je.current=_e,Et.current.set(Rt,_e),await g.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"}),cn=B.startTiming()},createOrder:Ie==="order"?J?()=>jt(J).then(Tn):()=>ut("Failed to create PayPal order.").then(Tn):void 0,createSubscription:Ie==="subscription"?J?()=>jt(J).then(Tn):()=>ut("Failed to create PayPal subscription.").then(Tn):void 0,createVaultSetupToken:Ie==="setup_token"?()=>ut("Failed to create PayPal setup token.").then(Tn):void 0,onApprove:c,onCancel:()=>{if(Oe())return;let y=Et.current.get(Rt)??Je.current;y&&Et.current.delete(y.surfaceKey),Je.current=null,Yn(),B.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),V.current=!0,vn({generation:y?.generation,remount:!0,focus:!1})},onError:y=>{if(Oe()||O.current!==Rt)return;let g=y instanceof Error?y.message:"PayPal failed to render.";if(N(`onError rendered=${Sn} msg=${g.slice(0,120)}`),Sn){let E=Et.current.get(Rt)??Je.current;if(E&&!Ut(E.generation)||!E&&Ht.current===Lt.current)return;if(On(g)){ct(E?.generation);return}if(Yn(),Wr(y)){B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Qt(y,E),Qe(()=>It.current?.(Mt("paypal",g))),E&&Et.current.delete(E.surfaceKey),Je.current=null,ct(E?.generation);return}let G=g.toLowerCase();B.error({errorCode:G.includes("popup")&&G.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),E&&Et.current.delete(E.surfaceKey),Je.current=null,vn({generation:E?.generation,remount:!0,showRetry:!0,focus:!0}),zt(y,{code:"paypal_runtime_failed"});return}qt(g)}}),K=A.isEligible();if(N(`isEligible=${K}`),B.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!K){ae(!1),qt("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Gt=A,le&&N(`container:dims ${at(rn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),le&&typeof MutationObserver<"u"&&(dn=new MutationObserver(y=>{if(!Oe()){for(let g of y)if(g.type==="childList")g.addedNodes.forEach(E=>{if(!(E instanceof Element))return;let G=E.tagName.toLowerCase(),ie=(E.getAttribute("title")??"").slice(0,40),_e=G==="iframe"?` ${un(E)}`:"";N(`child+ ${G}${ie?` title="${ie}"`:""}${_e} dims=${at(E)}`)});else if(g.type==="attributes"&&g.target instanceof Element){let E=g.target;if(E.tagName.toLowerCase()!=="iframe")continue;let G=g.attributeName;(G==="src"||G==="srcdoc")&&N(`attr~ iframe ${G}=${G==="srcdoc"?`[${(E.getAttribute("srcdoc")??"").length}ch]`:on(E.getAttribute("src"))} dims=${at(E)}`)}}}),dn.observe(rn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let C=y=>{if(Oe()||Sn)return;let g=rn.querySelectorAll("iframe"),E=typeof document<"u"&&"hasStorageAccess"in document;N(`watchdog:${y} container=${at(rn)} children=${rn.childElementCount} iframes=${g.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${E} paypalNetRequests=${Jt.value}`),g.forEach((G,ie)=>{let _e=(G.getAttribute("title")??"").slice(0,40);N(` iframe[${ie}] ${at(G)}${_e?` title="${_e}"`:""} ${un(G)}`);let Ue=Ln(G);Ue&&N(` ${Ue}`)}),pn.length===0&&N(" (no PayPal/zoid window errors captured)")};le&&(Ct.push(setTimeout(()=>C("3s"),3e3)),Ct.push(setTimeout(()=>C("8s"),8e3)),Ct.push(setTimeout(()=>C("15s"),15e3))),N("render:start");let f=B.startTiming();Ct.push(setTimeout(()=>{Oe()||Sn||(N("watchdog:11s retryable render timeout"),qt("PayPal Buttons render did not settle within 11000ms.",!0))},el)),A.render(rn).then(()=>{if(N(`render:resolved inactive=${Oe()}`),Gn(),Oe()){ln();return}Sn=!0,ae(!0),ke(!1),Fe.current?.("ready"),B.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),B.performance({stage:"checkout_render",durationMs:B.elapsed(f),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(y=>{let g=y instanceof Error?y.message:"PayPal failed to render.";N(`render:rejected msg=${g.slice(0,120)}`),Gn(),qt(g)})}).catch(s=>{let c=s instanceof Error?s.message:"PayPal SDK failed to load.";N(`loadScript:rejected msg=${c.slice(0,120)}`),qt(c)})},0);return()=>{Pe=!0,clearTimeout(pt),dt&&clearTimeout(dt),Gn(),ln()}},[W,Be,o,m,a,Ie,We,e,J,pe,B]);let mr=le?ia("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=${de} failed=${Z})`,Le.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return Le&&!ue?q?hr("div",{children:Hn}):null:Qo("div",{children:[Hn,Qo("div",{"aria-hidden":De?!0:void 0,style:De?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ho},children:[!J&&!De&&hr("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"}}),hr("div",{ref:ae,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:ho,display:"flex",opacity:J?1:0},"aria-busy":_||u},_e)]},_e),H&&hr("button",{ref:ve,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:On,style:qs,children:"Try PayPal again"})]})}function Po(e){return hr(yi,{...e})}function fi(e){return hr(yi,{...e})}import{FloPayError as Rn,isSetupIntentClientSecret as sl,resolveTheme as ll}from"@flopay/shared";import{Fragment as Pr,jsx as d,jsxs as ze}from"react/jsx-runtime";var In="flopay_stripe_resume",vi="flopay_wallet_resume",Kr="flopay_paypal_resume",cl=250,Ci="Just a moment \u2014 we are finalizing your order. Please press pay again.";function sa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function vo({billingApiUrl:e,sessionId:t,nonce:n,request:s}){if(!(!t||!n))try{await new qn(e,{telemetry:!1}).reportSessionIntentDecline(t,n,s)}catch{}}function dl(e){return e instanceof Rn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ta(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var ul=`
|
|
3
|
+
${Le.join(`
|
|
4
|
+
`)}`]}):null;return Z&&!D?le?Sr("div",{children:mr}):null:ia("div",{children:[mr,ia("div",{"aria-hidden":ue?!0:void 0,style:ue?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Eo},children:[!de&&!ue&&Sr("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"}}),Sr("div",{ref:te,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Eo,display:"flex",opacity:de?1:0},"aria-busy":H||p},pe)]},pe),w&&Sr("button",{ref:Me,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:rt,style:nl,children:"Try PayPal again"})]})}function Ro(e){return Sr(Si,{...e})}function wi(e){return Sr(Si,{...e})}import{jsx as ki,jsxs as ol}from"react/jsx-runtime";function wr({children:e,margin:t,icon:n=!0,styleOverride:r}){return ol("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&&ki("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ki("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 al}from"@flopay/shared";import{useEffect as Zn,useMemo as il,useRef as Ii,useState as Ei}from"react";import{jsx as sl}from"react/jsx-runtime";function _o({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,m]=Ei(e instanceof Promise?null:e),[d,T]=Ei(t instanceof Promise||!t?null:t),h=Ii(null),P=Ii(null),b=Cr(r);Zn(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),Zn(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),Zn(()=>{if(a)return Bt(a)?.subscribe?.(b)},[b,a]),Zn(()=>{if(!(!d||d===a))return Bt(d)?.subscribe?.(b)},[b,a,d]),Zn(()=>{if(!a)return;let p=Bt(a);return h.current=p?.beginCheckout()??p?.now()??0,p?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{p?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),Zn(()=>{let p=!1;return e instanceof Promise?e.then(S=>{p||m(S)},()=>{p||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):m(e),()=>{p=!0}},[b,e]),Zn(()=>{let p=!1;if(!t){T(null);return}return t instanceof Promise?t.then(S=>{p||T(S)},()=>{p||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):T(t),()=>{p=!0}},[b,t]),Zn(()=>{if(!a||P.current===a)return;P.current=a;let p=Bt(a);p?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),p?.performance({stage:"checkout_render",durationMs:p.elapsed(h.current??0),durationMode:"machine"})},[b,a]);let x=al(n?.billingApiUrl),U=il(()=>({flopay:a,paypalFlopay:d,billingApiUrl:x,emitInstrument:b}),[a,d,x,b]);return sl(Pn.Provider,{value:U,children:o})}var To="flopay_recent_completion_";function kr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(To+e,JSON.stringify(t))}catch{}}function la(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(To+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(To+e),!1):!0}catch{return!1}}import{loadFloPay as Ri,PaymentAPI as Ti}from"@flopay/js";import{classifyPaymentRejection as ll,FloPayError as et,isAuthorizationOnlySession as cl,isSetupIntentClientSecret as dl,normalizeCheckoutFailureOutcome as _i}from"@flopay/shared";var Zr="card";async function ul(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:m}=await e.retrieveSetupIntent(t);return{error:m,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 pl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:m,error:d}=await e.confirmCardSetup(t,n);return{error:d,intent:m??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function da(e,t){return Object.assign(e,{checkoutMethod:t})}function $n(e,t){let n=e instanceof et?e:new et(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 Xr(e,t){try{return await e()}catch(n){throw $n(n,t)}}function xi(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 ml(e){return e.status==="succeeded"||e.status==="declined"}async function Ai(e){if(typeof document>"u"||typeof window>"u")throw new et("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new et("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 P=new AbortController,b=()=>P.abort();e.signal?.aborted?P.abort():e.signal?.addEventListener("abort",b);let x=window.setTimeout(()=>P.abort(),r);try{let U=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:P.signal});if(!U.ok)return{status:"unknown"};let p=await U.json().catch(()=>null);return yl(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(x),e.signal?.removeEventListener("abort",b)}},m=document.activeElement instanceof HTMLElement?document.activeElement:null,d=document.createElement("div");d.setAttribute("data-flopay-auto-3ds-overlay","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.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 T=document.createElement("iframe");T.setAttribute("title","Card authentication"),T.setAttribute("allow","payment"),T.tabIndex=0,T.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(";"),T.src=e.nextActionRedirectUrl,d.appendChild(T),document.body.appendChild(d),T.focus();let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}try{let P=await new Promise((b,x)=>{let U=!1,p=0,S=0,ee=0,W=!1,v=()=>{window.clearTimeout(p),window.clearInterval(S),window.clearTimeout(ee),window.removeEventListener("message",ce),T.removeEventListener("load",j),e.signal?.removeEventListener("abort",J)},ye=async()=>{if(!(U||W)){W=!0;try{let Se=await a();if(U||!ml(Se))return;U=!0,v(),b(Se)}finally{W=!1}}},j=()=>{window.clearTimeout(ee),ee=window.setTimeout(()=>{ye()},250)},J=()=>{U||(U=!0,v(),x(new et("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ce=Se=>{if(Se.source!==T.contentWindow||h&&Se.origin!==h)return;let re=Se.data;!re||typeof re!="object"||re.source!=="flopay-vault-3ds-return"||U||(U=!0,v(),b(null))};p=window.setTimeout(()=>{U||(U=!0,v(),x(new et("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),S=window.setInterval(()=>{ye()},n),T.addEventListener("load",j),window.addEventListener("message",ce),e.signal?.addEventListener("abort",J),e.signal?.aborted&&J()});return P||await a()}finally{d.parentNode?.removeChild(d),m?.isConnected&&m.focus()}}function yl(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 Qn(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=Wn(o)??o;return da(new et(a,"api_error",{code:_i(e?.outcome)??_i(e?.type)??e?.gatewayErrorCode}),r)}function ca(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function xo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function fl(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 Mi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||xo(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 d of a)if(typeof d=="string"&&d.length>0&&(!t?.requirePaymentIntentClientSecret||xo(d)))return d;let m=o.gateways;if(m&&typeof m=="object"){let d=m.stripe;if(d&&typeof d=="object"){let T=d,h=[T.stripeClientSecret,T.clientSecret];for(let P of h)if(typeof P=="string"&&P.length>0&&(!t?.requirePaymentIntentClientSecret||xo(P)))return P}}}}async function gl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Mi(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let d=(await new Ti(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(xo(d))return{type:"3ds_required",threeDSecureToken:d}}catch{}return null}async function Ir({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:m}){let d=e.replace(/\/+$/,""),T=t??n.id,h=r??n.clientSecret,P=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",x=n.customer?.firstName??n.accountData?.firstName??"",U=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,S=n.customer?.zip??n.accountData?.zip??void 0,ee=new Ti(d,m===!1?{telemetry:!1}:void 0),W=await fl(()=>ee.processPayment(P,{sessionId:T,nonce:h,tokenizedData:o,accountData:{userId:P,email:b,firstName:x,lastName:U,country:p,zip:S},returnUrl:a??ca(n)}));if(W.ok){let j=typeof W.json=="function"?await W.json().catch(()=>null):null;return cl(n)||j?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof j?.paymentId=="string"?j.paymentId:n.paymentId,sessionId:typeof j?.sessionId=="string"?j.sessionId:T,authorizationExpiresAt:typeof j?.authorizationExpiresAt=="string"?j.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Gr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Gr(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let v;try{v=await W.json()}catch{throw new et("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:W.status})}if(v?.type==="paypal_redirect_required"||v?.type==="3ds_required"){let j=Mi(v);if(!j)throw new et("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:W.status});return{type:v.type,threeDSecureToken:j,paymentMethodId:v.paymentMethodId}}if(v?.gatewayErrorCode==="authentication_required"){let j=await gl({billingApiUrl:d,sessionId:T,nonce:h,responseJson:v});if(j)return j;throw da(new et("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ye=new et(v?.message??"Payment failed. Please try again.","api_error",{code:v?.code??v?.gatewayErrorCode,declineCode:v?.declineCode??v?.gatewayDeclineReason,statusCode:W.status});throw Object.assign(ye,{telemetryOutcome:ll(W.status,v)})}async function Ao(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:m,returnUrl:d,telemetry:T}){let h=t?.getRawProvider();if(!h)throw $n(new et("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw da(new et("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let P=dl(e.threeDSecureToken),b=null,x=e.paymentMethodId,U=await Xr(()=>ul(h,e.threeDSecureToken,P),"card");if(U){if(U.error)throw $n(new et(U.error.message??`Failed to retrieve 3DS ${P?"setup":"payment"} status.`,"api_error",{code:U.error.code}),"card");let S=U.intent;!x&&S?.payment_method&&(typeof S.payment_method=="string"?x=S.payment_method:"id"in S.payment_method&&(x=S.payment_method.id??void 0))}let p=x?await Xr(()=>pl(h,e.threeDSecureToken,{payment_method:x,return_url:d??ca(m)??window.location.href},P),"card"):null;if(p){if(p.error)throw $n(new et(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");b=p.intent}else{let S=await Xr(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(S.error)throw $n(new et(S.error.message??"3DS authentication failed.","api_error",{code:S.error.code}),"card");b=(P?S.setupIntent:S.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let S=await Ir({billingApiUrl:o,sessionId:a,session:m,telemetry:T,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:d});return S.type==="success"?{...S.result,paymentIntentId:S.result.paymentIntentId??b.id,paymentMethodId:S.result.paymentMethodId??x}:Ao(S,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:m,returnUrl:d,telemetry:T})}throw $n(new et("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let P=(n??t)?.getRawProvider();if(!P)throw $n(new et("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:x}=await Xr(()=>P.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(x)throw $n(new et(x.message??"PayPal authorization failed.","api_error",{code:x.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Xr(()=>P.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:d??ca(m)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw $n(new et(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new et("Unsupported payment redirect state.","api_error")}function ur(e){if(e instanceof et){let r=Wn(e.message);return r&&r!==e.message?Object.assign(new et(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=Wn(t)??t;return new et(n,"api_error")}function Mo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new et("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 Bo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[m,d]=await Promise.all([Ri(e,{billingApiUrl:n,locale:r,telemetry:o}),a?Ri(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(T=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",T),null)):Promise.resolve(null)]);return{flopay:m,paypalFlopay:t?a?d:m:null}}import{PaymentAPI as eo,toStripeAppearance as hl}from"@flopay/js";import{COUNTRY_OPTIONS as Pl,classifyPaymentRejection as bl,FloPayError as In,filterStripeMethodsByCountry as vl,getPostalCodeExample as Cl,getPostalCodeLabel as ya,getStateFromPostalCode as Di,getStateLabel as Li,getStateOptions as Sl,getStripeMethodDisplayName as Rr,hasVendoredStripeMethodLogo as wl,isAuthorizationOnlySession as ua,isAVSFieldVisible as Te,isPostalCodeSupported as kl,isSetupIntentClientSecret as Il,isValidPostalCode as El,needsStripeMethodExplicitConfirm as Oi,normalizeCheckoutFailureOutcome as Rl,partitionStripeMethods as _l,resolveAVSConfig as Tl,resolveButtonsLayoutTheme as xl,resolveStripeMethodBrandVariant as Al,resolveTheme as Ml,stripeExpressMethodToOptionKey as Ni}from"@flopay/shared";import{ExpressCheckoutElement as Yi,PaymentElement as Bl,Elements as pr,useElements as ga,useStripe as ha}from"@stripe/react-stripe-js";import Fl,{useCallback as he,useContext as _r,useEffect as lt,useMemo as st,useRef as Ee,useState as ge}from"react";function Bi(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 Fi={alipay:new URL("./payment-logos/alipay.svg",import.meta.url).href,bancontact:new URL("./payment-logos/bancontact.svg",import.meta.url).href,blik:new URL("./payment-logos/blik.svg",import.meta.url).href,eps:new URL("./payment-logos/eps.svg",import.meta.url).href,giropay:new URL("./payment-logos/giropay.svg",import.meta.url).href,ideal:new URL("./payment-logos/ideal.svg",import.meta.url).href,klarna:new URL("./payment-logos/klarna.svg",import.meta.url).href,p24:new URL("./payment-logos/p24.svg",import.meta.url).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",import.meta.url).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",import.meta.url).href};import{Fragment as Er,jsx as u,jsxs as xe}from"react/jsx-runtime";var Bn="flopay_stripe_resume",zi="flopay_wallet_resume";function Gi(e){return e instanceof In&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Do(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 Gi(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Qr="flopay_paypal_resume",Dl=250,Ui="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Pa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Lo({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new eo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Ll(e){return e instanceof In&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function pa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var Ol=`
|
|
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 @@ ${G.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
|
-
`,bo=44;function la(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 pl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},xi={width:"100%",minHeight:bo,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 ml(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Si(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ti(e){return e==="paypal"?"PayPal":br(e)}function yl(e,t){let n=`We couldn't open ${Ti(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Mi(e){let t=Be(0),n=Be(null),s=Be(null),a=Ee((u=s.current)=>{let h=u;h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),i=Ee((u,h)=>{typeof document<"u"&&document.visibilityState!=="visible"||(a(u),u.timer=setTimeout(()=>{u.timer=null,s.current?.generation===u.generation&&(s.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"}))},h))},[a,e]),p=Ee(u=>{u.yieldedControl&&i(u,600)},[i]),l=Ee(u=>{a();let h=t.current+1;t.current=h,n.current=null;let w={generation:h,method:u,timer:null,yieldedControl:!1};return s.current=w,h},[a]),b=Ee(u=>{let h=s.current;return typeof u=="number"&&h?.generation!==u?!1:(a(h),s.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[a]),z=Ee(u=>{let h=s.current,w=u??h?.generation??t.current;(!u||h?.generation===u)&&(a(h),s.current=null),n.current=w},[a]),g=Ee(u=>n.current===(u??t.current),[]),R=Ee(u=>s.current?.generation===u&&n.current!==u,[]),v=Ee(()=>{let u=s.current;u&&p(u)},[p]),A=Ee(()=>{let u=s.current;u&&(u.yieldedControl=!0,a(u))},[a]);return ct(()=>{let u=()=>{document.visibilityState==="visible"?v():A()},h=()=>{A()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",h),window.addEventListener("focus",v),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",h),window.removeEventListener("focus",v),a()}},[a,A,v]),{startAttempt:l,finishAttempt:b,invalidateAttempt:z,isAttemptInvalidated:g,isAttemptCurrent:R}}function fl(e){let t=Zs(e);return`Enter a valid ${ra(e)}${t?` (e.g. ${t})`:""}`}function gl(e,t,n){let s=Xs(e),a=t.trim(),i=n&&s,p=i&&!a,l=i&&!!a&&!Qs(e,a);return{visible:n,supported:s,required:i,empty:p,malformed:l}}function wi(e,t){return t instanceof Rn?t:new Rn(t instanceof Error?t.message:`${ml(e)} before-click hook failed.`,"validation_error")}function na(){return d("style",{children:ul})}function hl(e){return typeof e=="number"?`${e}px`:e}function Ai(e,t){let n=e.availablePaymentMethods;return n&&t.some(s=>n[s])?"ready":"unavailable"}function Bi({state:e,placeholderTestId:t,borderRadius:n=8,children:s}){return e==="unavailable"||e==="load_error"?null:ze("div",{style:{position:"relative",minHeight:44},children:[d("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"}}),d("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:s})]})}function ki(e){return e!=="unavailable"&&e!=="load_error"}function ca(e){return d(bl,{...e})}function Ri({sessionId:e,nonce:t,email:n,billingApiUrl:s,onTokenizedBody:a,onErrorChange:i,isProcessing:p=!1,onButtonClick:l,onDecline:b,onTechnicalFailure:z,runBeforeButtonClick:g,onLoadStateChange:R,placeholderBorderRadius:v}){let A=kn(),u=ia(),h=aa(),[w,I]=ke("loading");ct(()=>{R?.(w)},[w,R]);let[y,he]=ke(!1),F=Be(!1),te=Be(null),be=Be(null),[j,q]=ke(0),[oe,ie]=ke(!1),Ne=Be(!1),f=Be(new Map),{startAttempt:ae,finishAttempt:Fe,invalidateAttempt:ve,isAttemptInvalidated:Re,isAttemptCurrent:J}=Mi((H,P,Q)=>{z?.(H,P,{...Q,popupBlocked:Q?.popupBlocked??jn(P)}),ie(!0),q(We=>We+1)});ct(()=>{oe&&be.current?.focus()},[oe,j]);let le=Ee(()=>{q(H=>H+1)},[]),De=Ee((H,P,Q)=>{ve(Q),z?.("paypal",H,{code:P,popupBlocked:jn(H)}),ie(!0),le()},[ve,z,le]),se=Ee(()=>{window.setTimeout(()=>{(te.current?.querySelector("iframe")??te.current)?.focus()},0)},[]);ct(()=>{Ne.current&&(Ne.current=!1,se())},[se,j]);let _e=Ee(()=>{ie(!1),i?.(null),se()},[se,i]);ct(()=>{if(!u||F.current)return;let H=new URLSearchParams(window.location.search),P=H.get("payment_intent"),Q=H.get("payment_intent_client_secret"),We=H.get("redirect_status");if(!P||!Q)return;F.current=!0;let Le;try{let _=localStorage.getItem(Kr);if(_){let ce=JSON.parse(_);ce.clientSecret===Q&&(Le={...ce.accountPatch?{accountPatch:ce.accountPatch}:{},...ce.sessionId?{sessionId:ce.sessionId}:{},...ce.nonce?{nonce:ce.nonce}:{}})}}catch{}try{localStorage.removeItem(Kr)}catch{}let Z=new URL(window.location.href);Z.searchParams.delete("payment_intent"),Z.searchParams.delete("payment_intent_client_secret"),Z.searchParams.delete("redirect_status"),window.history.replaceState({},"",Z.toString()),(async()=>{try{if(he(!0),We==="failed"){let K="PayPal payment was declined. Please try again.";i?.(K),b?.(It("paypal",K));return}let{paymentIntent:_,error:ce}=await u.retrievePaymentIntent(Q);if(ce){i?.(ce.message??"Failed to retrieve PayPal payment status.");return}if(_&&(_.status==="requires_capture"||_.status==="succeeded")){let K=typeof _.payment_method=="string"?_.payment_method:_.payment_method?.id;a({id:K??_.id,type:"card",threeDSecureActionResultTokenId:_.id,isPaypal:!0},Le)}else{let K="PayPal payment was not completed. Please try again.";i?.(K),b?.(It("paypal",K))}}catch(_){i?.(_ instanceof Error?_.message:"Failed to complete PayPal payment.")}finally{he(!1)}})()},[u,a,i,b]);let Ue=Ee(async H=>{if(p||y){H.reject();return}let P=g?await g("paypal"):{proceed:!0};if(!P.proceed){f.current.delete(j),H.reject();return}let Q=ae("paypal");f.current.set(j,{generation:Q,accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}),ie(!1),l?.("paypal"),H.resolve()},[f,p,l,g,ae,y,j]),xe=Ee(async H=>{if(!u||!h)return;let P=f.current.get(j);if(P&&!J(P.generation)){f.current.delete(j);return}if(!P&&Re()||P&&!Fe(P.generation))return;P||Fe();let Q=P??null;if(f.current.delete(j),!Q&&g){let _=await g("paypal");if(!_.proceed){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Q={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let We=Q?.sessionId??e,Le=Q?.nonce??t,Z=Q?.accountPatch?.email??n;try{if(he(!0),i?.(null),!We||!Z)throw new Error("Missing sessionId or email for PayPal payment");let _=u.createPaymentMethod,{error:ce,paymentMethod:K}=await _({type:"paypal"});if(ce){De(ce,"stripe_paypal_create_payment_method_failed",P?.generation),H.paymentFailed({reason:"fail"});return}let de=await new qn(s).createSessionIntent(We,Le??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:K?.id??null,intentKind:"payment"});if(de.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let et=de.clientSecret,$e={return_url:window.location.href};if(K?.id&&($e.payment_method=K.id),typeof window<"u")try{localStorage.setItem(Kr,JSON.stringify({clientSecret:et,sessionId:We,nonce:Le,accountPatch:Q?.accountPatch}))}catch{}let{error:it,paymentIntent:ue}=await u.confirmPayment({clientSecret:et,confirmParams:$e,redirect:"if_required"});if(it){if(typeof window<"u")try{localStorage.removeItem(Kr)}catch{}if(jr(it)){let tt=it.message??"Your payment was declined.";i?.(tt),b?.(It("paypal",tt,{code:Mn(it),declineCode:gr(it)})),await vo({billingApiUrl:s,sessionId:We,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(it)??"provider_declined"}})}else De(it,"stripe_paypal_confirm_failed",P?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Kr)}catch{}let G=typeof ue?.payment_method=="string"?ue.payment_method:ue?.payment_method?.id;a({id:G??ue?.id,type:"card",threeDSecureActionResultTokenId:ue?.id,isPaypal:!0},{accountPatch:Q?.accountPatch,sessionId:We,nonce:Le});return}catch(_){De(_,"stripe_paypal_failed",P?.generation)}finally{he(!1)}},[u,h,e,t,n,s,a,i,b,g,De,Fe,J,Re,j]);return ze(Pr,{children:[d(Bi,{state:w,placeholderTestId:"flopay-paypal-placeholder",borderRadius:v,children:ze("div",{ref:te,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[oe&&d("button",{ref:be,type:"button","data-testid":"flopay-paypal-retry-button",onClick:_e,style:xi,children:"Try PayPal again"}),d(_i,{onReady:H=>I(Ai(H,["paypal"])),onLoadError:()=>{I("load_error"),sa(At(A),"paypal","paypal")},onClick:Ue,onConfirm:xe,onCancel:()=>{let H=f.current.get(j);f.current.delete(j),At(A)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ve(H?.generation),ie(!1),Ne.current=!0,le()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},j)]})}),y&&d(wn,{status:"processing"})]})}function Ii({sessionId:e,nonce:t,email:n,billingApiUrl:s,intentKind:a,expressMethods:i,onTokenizedBody:p,onErrorChange:l,onButtonClick:b,onDecline:z,onTechnicalFailure:g,runBeforeButtonClick:R,onLoadStateChange:v,placeholderBorderRadius:A}){let u=kn(),h=ia(),w=aa(),[I,y]=ke("loading");ct(()=>{v?.(I)},[I,v]);let[he,F]=ke(!1),te=Be(null),be=Be(null),[j,q]=ke(0),[oe,ie]=ke(!1),[Ne,f]=ke("google_pay"),ae=Be(!1),Fe=Be("google_pay"),ve=Be("google_pay"),Re=Be(new Map),{startAttempt:J,finishAttempt:le,invalidateAttempt:De,isAttemptInvalidated:se,isAttemptCurrent:_e}=Mi((Z,_,ce)=>{g?.(Z,_,{...ce,popupBlocked:ce?.popupBlocked??jn(_)}),f(Z),ie(!0),q(K=>K+1)});ct(()=>{oe&&be.current?.focus()},[oe,j]);let Ue=Ee(()=>{q(Z=>Z+1)},[]),xe=Ee((Z,_,ce,K)=>{De(K),g?.(Z,_,{code:ce,popupBlocked:jn(_)}),f(Z),ie(!0),Ue()},[De,g,Ue]),H=Ee(()=>{window.setTimeout(()=>{(te.current?.querySelector("iframe")??te.current)?.focus()},0)},[]);ct(()=>{ae.current&&(ae.current=!1,H())},[H,j]);let P=Ee(()=>{ie(!1),l?.(null),H()},[H,l]),Q=Ee(async Z=>{if(!h||!w)return;let _=Re.current.get(j);if(_&&!_e(_.generation)){Re.current.delete(j);return}if(!_&&se()||_&&!le(_.generation))return;_||le();let ce=Z.expressPaymentType??_?.method??Fe.current,K=_??null;Re.current.delete(j);let de=Si(ce);if(!K&&R){let G=await R(de);if(!G.proceed){Z.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}K={accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}}let et=de,$e=K?.sessionId??e,it=K?.nonce??t,ue=K?.accountPatch?.email??n;try{F(!0),l?.(null);let{error:G}=await w.submit();if(G){xe(ce,G,"stripe_wallet_submit_failed",_?.generation);return}let{error:tt,paymentMethod:Y}=await h.createPaymentMethod({elements:w});if(tt||!Y){xe(ce,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",_?.generation);return}if(!$e||!ue)throw new Error("Missing sessionId or email for wallet payment");let mt=await new qn(s).createSessionIntent($e,it??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ce??de,paymentMethodId:Y.id,intentKind:a});if(mt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let je=mt.clientSecret,{error:qe,intentId:$t}=sl(je)?await h.confirmCardSetup(je,{payment_method:Y.id}).then(nt=>({error:nt.error,intentId:nt.setupIntent?.id})):await h.confirmCardPayment(je,{payment_method:Y.id}).then(nt=>({error:nt.error,intentId:nt.paymentIntent?.id}));if(qe){if(jr(qe)){let nt=qe.message??"Your payment was declined.";l?.(nt),z?.(It(et,nt,{code:Mn(qe),declineCode:gr(qe)})),await vo({billingApiUrl:s,sessionId:$e,nonce:it,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ce??de,providerDeclineReason:Mn(qe)??"provider_declined"}})}else xe(ce,qe,"stripe_wallet_confirm_failed",_?.generation);return}p({id:Y.id,type:"card",threeDSecureActionResultTokenId:$t},{accountPatch:K?.accountPatch,sessionId:$e,nonce:it})}catch(G){xe(ce,G,"stripe_wallet_failed",_?.generation)}finally{F(!1)}},[h,w,e,t,n,s,a,p,l,z,R,xe,le,_e,se,j]),We=lt(()=>{let Z=["applePay","googlePay","paypal","link","amazonPay","klarna"],_=new Set(["applePay","googlePay"]),ce=new Set(i.map(bi)),K={};for(let de of Z)ce.has(de)?K[de]=_.has(de)?"always":"auto":K[de]="never";return K},[i]),Le=lt(()=>i.map(bi),[i]);return ze(Pr,{children:[d(Bi,{state:I,placeholderTestId:"flopay-wallet-placeholder",borderRadius:A,children:ze("div",{ref:te,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[oe&&ze("button",{ref:be,type:"button","data-testid":"flopay-wallet-retry-button",onClick:P,style:xi,children:["Try ",Ti(Ne)," again"]}),d(_i,{onReady:Z=>{y(Ai(Z,Le))},onLoadError:Z=>{y("load_error"),sa(At(u),"stripe","wallet")},onClick:async Z=>{Fe.current=Z.expressPaymentType,ve.current=Si(Z.expressPaymentType);let _=R?await R(ve.current):{proceed:!0};if(!_.proceed){Re.current.delete(j),Z.reject();return}let ce=J(Z.expressPaymentType);Re.current.set(j,{generation:ce,method:Z.expressPaymentType,accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}),ie(!1),b?.(ve.current),Z.resolve()},onConfirm:Q,onCancel:()=>{let Z=Re.current.get(j);Re.current.delete(j),At(u)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),De(Z?.generation),ie(!1),ae.current=!0,Ue()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:We,layout:{maxColumns:1,overflow:"never"}}},j)]})}),he&&d(wn,{status:"processing"})]})}function Pl({method:e,themeId:t,submitting:n=!1,disabled:s=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:p,backgroundColor:l,borderColor:b,textColor:z,borderRadius:g,fontFamily:R}){let v=nl(e,t),A=ri[e],u=v?.backgroundColor??l??"#ffffff",h=v?.borderColor??b??"#d1d5db",w=v?.textColor??z??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!s&&p()},disabled:n||s,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:bo,padding:"0 1rem",backgroundColor:u,color:w,border:`1px solid ${h}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||s?"not-allowed":"pointer",opacity:s&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${br(e)}\u2026`}):ze(Pr,{children:[ze("span",{style:{display:"inline-flex",alignItems:"center",gap:tl(e)?8:0},children:[A?d("img",{src:A,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):v?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:v.logoSvg}}):null,d("span",{children:br(e)})]}),i&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:w,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:d("path",{d:"M9 18l6-6-6-6"})})]})})}function oa({method:e,sessionId:t,nonce:n,email:s,billingName:a,billingApiUrl:i,onTokenizedBody:p,onErrorChange:l,onDecline:b,onCancel:z,runBeforeButtonClick:g,onButtonClick:R,isProcessing:v,submitButtonColor:A,submitButtonBorderRadius:u,submitButtonStyle:h,errorText:w}){let I=kn(),y=ia(),he=aa(),[F,te]=ke(!1),be=Be(!1),[j,q]=ke(!1),[oe,ie]=ke("loading"),Ne=Ee(async()=>{if(!y||!he||v||be.current||!j)return;be.current=!0,te(!0);let f=g?await g("card"):{proceed:!0};if(!f.proceed){be.current=!1,te(!1);return}R?.("card");let ae=f.sessionId??t,Fe=f.nonce??n,ve=f.accountPatch?.email??s;try{l?.(null);let Re=await he.submit();if(Re.error){l?.(Re.error.message??"Payment failed.");return}let J=await y.createPaymentMethod({elements:he});if(J.error||!J.paymentMethod){l?.(J.error?.message??"Failed to create payment method.");return}let le=J.paymentMethod;if(!ae||!ve)throw new Error("Missing sessionId or email for payment.");let De=le.type||e,se=await new qn(i).createSessionIntent(ae,Fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:De,paymentMethodId:null,intentKind:"payment"});if(se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let _e=se.clientSecret;if(typeof window<"u")try{localStorage.setItem(In,JSON.stringify({clientSecret:_e,sessionId:ae,nonce:Fe,accountPatch:f.accountPatch,paymentMethodId:le.id,paymentMethodType:le.type??e,gateway:"stripe"}))}catch{}let{error:Ue,paymentIntent:xe}=await y.confirmPayment({clientSecret:_e,confirmParams:{return_url:window.location.href,payment_method:le.id},redirect:"if_required"});if(Ue){if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let Q=Ue.message??"Payment failed.";l?.(Q),b?.(It("card",Q,{code:Ue.code})),await vo({billingApiUrl:i,sessionId:ae,nonce:Fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ue.code??"provider_declined"}});return}let H=xe?.status;if(!yo(H)){if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let Q=H==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(Q),b?.(It("card",Q,{code:H??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let P=typeof xe?.payment_method=="string"?xe.payment_method:xe?.payment_method?.id;p({id:P??le.id,type:"card",threeDSecureActionResultTokenId:xe?.id,gateway:"stripe",paymentMethodType:le.type??e},{accountPatch:f.accountPatch,sessionId:ae,nonce:Fe})}catch(Re){l?.(Re instanceof Error?Re.message:"Payment failed. Please try again.")}finally{be.current=!1,te(!1)}},[y,he,v,j,g,R,t,n,s,i,e,p,l,b]);return ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(Vs,{onReady:()=>ie("ready"),onLoadError:()=>{ie("load_error"),sa(At(I),"stripe","apm")},onChange:f=>{q(!!f.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...s?{email:s}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ne()},disabled:!j||F||v||oe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:A,color:"white",border:"none",borderRadius:u,fontSize:"1rem",fontWeight:600,cursor:!j||F||v||oe!=="ready"?"not-allowed":"pointer",opacity:!j||F||v||oe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...h??{}},children:F?"Processing\u2026":`Pay with ${br(e)}`}),w&&d(mr,{margin:"0.75rem 0 0",children:w})]})}function Ei({sessionId:e,nonce:t,email:n,billingName:s,billingApiUrl:a,paymentElementMethods:i,stripeInstance:p,paymentElementBaseOptions:l,onTokenizedBody:b,onErrorChange:z,onButtonClick:g,onDecline:R,runBeforeButtonClick:v,onLoadStateChange:A,isProcessing:u=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:w=8,submitButtonStyle:I,buttonAppearance:y,themeId:he,onExpandApm:F,expandedApmMethod:te}){let[be,j]=ke(null),[q,oe]=ke(null),ie=Be(!1);ct(()=>{i.length>0&&p?A?.("ready"):p||A?.("loading")},[i.length,p,A]);let Ne=Ee(async J=>{if(!p||ie.current||u)return;ie.current=!0,oe(J);let le=v?await v("card"):{proceed:!0};if(!le.proceed){ie.current=!1,oe(null);return}g?.("card");let De=le.sessionId??e,se=le.nonce??t,_e=le.accountPatch?.email??n;try{if(z?.(null),!De||!_e)throw new Error("Missing sessionId or email for payment.");let Ue=await new qn(a).createSessionIntent(De,se??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,paymentMethodId:null,intentKind:"payment"});if(Ue.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let xe=Ue.clientSecret;if(typeof window<"u")try{localStorage.setItem(In,JSON.stringify({clientSecret:xe,sessionId:De,nonce:se,accountPatch:le.accountPatch,paymentMethodType:J,gateway:"stripe"}))}catch{}let{error:H,paymentIntent:P}=await p.confirmPayment({clientSecret:xe,confirmParams:{return_url:window.location.href,payment_method_data:{type:J,billing_details:{name:s&&s.trim().length>=3?s.trim():"FloPay Customer",..._e?{email:_e}:{}}}},redirect:"if_required"});if(H){if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let Le=H.message??"Payment failed.";z?.(Le),R?.(It("card",Le,{code:H.code})),await vo({billingApiUrl:a,sessionId:De,nonce:se,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,providerDeclineReason:H.code??"provider_declined"}});return}let Q=P?.status;if(!yo(Q)){if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let Le=Q==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";z?.(Le),R?.(It("card",Le,{code:Q??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(In)}catch{}let We=typeof P?.payment_method=="string"?P.payment_method:P?.payment_method?.id;b({id:We??P?.id,type:"card",threeDSecureActionResultTokenId:P?.id,gateway:"stripe",paymentMethodType:J},{accountPatch:le.accountPatch,sessionId:De,nonce:se})}catch(Ue){z?.(Ue instanceof Error?Ue.message:"Payment failed. Please try again.")}finally{ie.current=!1,oe(null)}},[p,u,v,g,e,t,n,a,s,b,z,R]),[f,ae]=ke(null),Fe=F?te??null:f,ve=Ee(J=>{ie.current||u||Fe&&Fe!==J||(Pi(J)?F?F(J):ae(J):Ne(J))},[Fe,u,Ne,F]),Re=lt(()=>f?{...l,paymentMethodTypes:[f]}:null,[f,l]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:i.map(J=>{let le=te===J,De=q===J,se=q!==null&&q!==J||te!=null&&te!==J;return ze(al.Fragment,{children:[d(Pl,{method:J,themeId:he,submitting:De,disabled:se,highlighted:le,hasNextStep:Pi(J),onClick:()=>ve(J),backgroundColor:y?.backgroundColor,borderColor:y?.borderColor,textColor:y?.textColor,borderRadius:y?.borderRadius,fontFamily:y?.fontFamily}),!F&&f===J&&Re&&p&&d(nr,{stripe:p,options:Re,children:d(oa,{method:J,sessionId:e,email:n,billingName:s,billingApiUrl:a,onTokenizedBody:b,onErrorChange:z,onDecline:R,onCancel:()=>ae(null),runBeforeButtonClick:v,onButtonClick:g,isProcessing:u,submitButtonColor:h,submitButtonBorderRadius:w,submitButtonStyle:I})},J)]},J)})})}function bl({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,onComplete:i,onError:p,onDecline:l,onTokenizedBody:b,firstName:z,lastName:g,chv:R,className:v,isProcessing:A,error:u,onErrorChange:h,showPayPal:w=!0,showStripe:I=!0,enabledPaymentMethods:y,enabledPaymentMethodCountries:he,showApplePay:F=!0,showGooglePay:te=!0,layout:be="default",theme:j,buttonsTheme:q,buttonsStyles:oe,appearance:ie,cardButtonContent:Ne,cardBackButtonContent:f,cardTitleContent:ae,showSecurityFooter:Fe,onButtonClick:ve,onBeforeButtonClick:Re,enableAVS:J,cardFieldOrder:le,cardPreFormSlot:De,avsLayout:se="row",country:_e,zip:Ue,addressLine1:xe,addressLine2:H,city:P,state:Q,onCountryChange:We,onZipChange:Le,avsCheck:Z,checkoutType:_,checkoutLayout:ce,totalAmount:K=0,currency:de="usd",initialCardOpen:et=!1,directPaypal:$e,isSubscription:it=!1,session:ue,dataAttachmentPending:G=!1,debug:tt=!1}){let Y=kn(),mt=Vo(),je=il(mn),qe=G||je.claimPending===!0,$t=uo(),[nt,en]=ke(!1),[S,pe]=ke(null),[Je,Xe]=ke(_e??"US"),[xt,yt]=ke(Ue??""),[Te,ft]=ke(xe??""),[Ie,tn]=ke(H??""),[Ke,Dn]=ke(P??""),[Jt,fn]=ke(Q??""),[Ln,On]=ke({}),jt=Be(Ue??""),dt=Be(_e??"US"),ln=Be(xe??""),qt=Be(H??""),Kt=Be(P??""),Vt=Be(Q??""),Bt=Be({});ct(()=>{let r=(M,$,re,U,we)=>{if(Bt.current[M])return;let Ae=$?.trim();!Ae||Ae===re.current||(re.current=Ae,U(Ae),we?.(Ae))};r("country",_e,dt,Xe,We),r("zip",Ue,jt,yt,Le),r("addressLine1",xe,ln,ft),r("addressLine2",H,qt,tn),r("city",P,Kt,Dn),r("state",Q,Vt,fn)},[_e,Ue,xe,H,P,Q,We,Le]);let X=lt(()=>Js(J),[J]),zn=X!==null,nn=lt(()=>ea(ue),[ue]),Xt=!!ue?.vault?.html,Hn=!!ue?.gateways?.pcivault,ot=!!(ue?.gateways?.stripe?.enabledPaymentMethods??y)?.includes("card"),He=Xt||ot||Hn,Ve=!!(I&&He&&Y&&e),[Ye,_n]=ke(()=>be!=="buttons"||et?e??null:null),[Nn,ar]=ke(0),gn=be!=="buttons"||et||!!e&&Ye===e,at=lt(()=>!Y||!Ve||!e||!gn?null:Y.cardCapture({sessionId:e,captureMethod:ue?.captureMethod}),[Y,Ve,e,gn,ue?.captureMethod]),Ht=lt(()=>{let r=Je,M=X?Oe(X.postal_code,r):!1;return gl(r,xt,M)},[X,Je,xt]),{avsInvalid:hn,invalidAvsFields:Ct}=lt(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!Ve||!X)return{avsInvalid:!1,invalidAvsFields:r};let M=Je,$=(we,Ae)=>Oe(we,M)&&!Ae.trim(),re={line1:$(X.address_line_1,Te),city:$(X.city,Ke),state:$(X.state,Jt),zip:Ht.empty||Ht.malformed};return{avsInvalid:re.line1||re.city||re.state||re.zip,invalidAvsFields:re}},[Ve,X,Je,Te,Ke,Jt,Ht]),[Lt,cn]=ke(!1),[rn,Qt]=ke(!1),[Zt,Ft]=ke(()=>ta(ue?.vault)),[Se,St]=ke(et&&He?"card":"buttons"),[gt,Pn]=ke(null),ir=Se==="expanding"||Se==="card",Ot=280,on=Be(null),Dt=Ee(r=>{on.current&&clearTimeout(on.current),on.current=setTimeout(()=>{on.current=null,r()},Ot)},[Ot]);ct(()=>()=>{on.current&&clearTimeout(on.current)},[]);let Yn=Ee(()=>{_n(e??null),ar(r=>r+1),St("expanding"),Dt(()=>St("card"))},[Dt,e]),dn=Ee(()=>{St("collapsing"),Dt(()=>St("buttons"))},[Dt]),Un=Ee(r=>{Pn(r),St("apm-expanding"),Dt(()=>St("apm-form"))},[Dt]),zt=Ee(()=>{St("apm-collapsing"),Dt(()=>{St("buttons"),Pn(null)})},[Dt]);ct(()=>{be==="buttons"&&et&&He&&(_n(e??null),St("card"))},[be,et,He,e]);let[bn,Me]=ke(null),k=Be(!1),D=Be(null),L=Be("idle"),[fe,Ce]=ke(null),W=Be(fe);ct(()=>{W.current=fe},[fe]);let m=n||$t,O=u??S,c=lt(()=>ll(j),[j]),o=lt(()=>{let r=c?.buttonsLayout??Ys(q);return oe?{...r,...oe,cardButton:{...r.cardButton,...oe.cardButton},cardFormContainer:{...r.cardFormContainer,...oe.cardFormContainer},backButton:{...r.backButton,...oe.backButton},backButtonIcon:{...r.backButtonIcon,...oe.backButtonIcon},submitButton:{...r.submitButton,...oe.submitButton},title:{...r.title,...oe.title}}:r},[c,q,oe]),E=ie??c?.appearance,ye=lt(()=>Za({appearance:E,buttonsStyles:o,layout:be}),[E,o,be]),Pe=je.inlineSessionPatchProcessing??!1,V=(A??nt)||Pe,Ge=m.replace(/\/+$/,""),x=lt(()=>Wo({userId:a,email:s,firstName:z,lastName:g,country:_e,zip:Ue},Ln),[a,s,z,g,_e,Ue,Ln]),N=[x.firstName,x.lastName].filter(r=>!!r?.trim()).join(" "),C=lt(()=>Y?Y.getRawProvider():null,[Y]),T=lt(()=>mt?mt.getRawProvider():null,[mt]),ne=K||100,vt=lt(()=>E?ol(E):null,[E]),Yt=vt?{appearance:vt}:null,Nt=lt(()=>{let r=vt??{},M=r.rules??{};return{...r,rules:{...M,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...M[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...M[".AccordionItemContents"]??{}}}}},[vt]),Xr=lt(()=>{let r=ci(K);return{...r,currency:de.toLowerCase(),paymentMethodCreation:"manual",...r.mode==="payment"?{captureMethod:"manual"}:{},...Yt}},[K,de,Yt]),ka=lt(()=>({mode:"payment",amount:ne,currency:de.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Yt}),[ne,de,Yt]),me=Ee(r=>{pe(r),h?.(r)},[h]);ct(()=>{!Ve||!at||at.setCardFieldOrder?.(le??null,X==null)},[Ve,at,le,X]),ct(()=>{(Se==="expanding"||Se==="collapsing"||Se==="apm-expanding"||Se==="apm-collapsing")&&me(null)},[Se,me]);let un=Ee((r,M,$)=>{l?.(It(r,M,$))},[l]),sr=Ee((r,M,$)=>{let re=$?.popupBlocked??jn(M),U=yl(r,re),we=er($?.code)??Mn(M)??"external_payment_method_failed",Ae=new Rn(U,"api_error",{code:"external_payment_method_failed",param:r});Me(null),be==="buttons"&&(St("buttons"),Pn(null)),me(U),p?.(Ae),console.error("[FloPay] External payment method failed:",{method:r,code:we,popupBlocked:re})},[be,p,me]);ct(()=>{if(!Ve||!e){Ft(null);return}let r=ta(ue?.vault);if(r){Ft(r);return}if(!gn){Ft(null);return}Ft(null);let M=!0;return new qn(Ge).getVaultCapture(e,t).then($=>{if(!M)return;let re=ta($);re?Ft(re):me("Failed to load the secure card form.")}).catch($=>{M&&me($ instanceof Error?$.message:"Failed to load the secure card form.")}),()=>{M=!1}},[Ve,gn,Nn,e,ue?.vault?.html,ue?.vault?.messageToken,ue?.vault?.expectedOrigin,Ge,t,me]);let vn=Be({onComplete:i,onError:p,updateError:me,emitDecline:un,resolvedAccount:x,avsConfig:X,avsCheckProp:Z,sessionId:e,nonce:t,baseUrl:Ge,captureMethod:ue?.captureMethod,paymentId:ue?.paymentId,authorizationExpiresAt:ue?.authorizationExpiresAt});vn.current={onComplete:i,onError:p,updateError:me,emitDecline:un,resolvedAccount:x,avsConfig:X,avsCheckProp:Z,sessionId:e,nonce:t,baseUrl:Ge,captureMethod:ue?.captureMethod,paymentId:ue?.paymentId,authorizationExpiresAt:ue?.authorizationExpiresAt};let xo=Be(!1),Zi=Ee(()=>{let{resolvedAccount:r,avsConfig:M,avsCheckProp:$}=vn.current,re=dt.current||r.country||"US",U=M?Oe(M.state,re):!1,we=M?Oe(M.address_line_1,re):!1,Ae=M?Oe(M.postal_code,re):!1,st=M?Oe(M.city,re):!1,Pt=M?Oe(M.address_line_2,re):!1,Qe=we&&!U&&Ae?hi(re,(jt.current??"").trim()):null,wt=U?Vt.current:Qe;return{accountData:{userId:r.userId??"",email:r.email??"",firstName:r.firstName??"",lastName:r.lastName??"",...Ae&&jt.current?{zip:jt.current}:{},...st&&Kt.current?{city:Kt.current}:{},...wt?{state:wt}:{},...we&&ln.current?{addressLine1:ln.current}:{},...Pt&&qt.current?{addressLine2:qt.current}:{},country:re},...$!==void 0?{avsCheck:$}:{},...M?{avsConfig:{country:Oe(M.country,re),postal_code:Ae,address_line_1:we,address_line_2:Pt,city:st,state:U}}:{}}},[]),Ra=Be(qe);Ra.current=qe,ct(()=>{qe||O!==Ci||vn.current.updateError(null)},[qe,O]),ct(()=>{!Ve||!at||at.setSubmitGate?.(hn||qe)},[Ve,at,hn,qe]),ct(()=>{if(!Ve||!at)return;xo.current=!1;let r=!1,M=at.on("submitting",()=>{cn(!0),D.current&&clearTimeout(D.current),L.current="validation-window",D.current=setTimeout(()=>{D.current=null,L.current==="validation-window"&&(L.current="processing")},cl),Me("processing");let{baseUrl:Ae,sessionId:st,nonce:Pt,updateError:Qe,onError:wt}=vn.current;!st||!Pt||new qn(Ae).patchAccountSnapshot(st,Pt,Zi(),{telemetryMode:"best_effort"}).catch(ge=>{if(!dl(ge))return;let Tt=ge instanceof Error?ge.message:"Please check your billing address and try again.";Qe(Tt),L.current="idle",Me(null),wt?.(ge instanceof Rn?ge:new Rn(Tt,"api_error"))})}),$=at.on("complete",async Ae=>{if(fr(Ae.sessionId??vn.current.sessionId),L.current="terminal",Me("success"),await new Promise(Qe=>setTimeout(Qe,xn)),xo.current)return;xo.current=!0;let st=vn.current,Pt=ea(st)||Ae.outcome==="authorized";vn.current.onComplete?.(Pt?{status:"authorized",paymentIntentId:Ae.intentId,paymentId:Ae.paymentId??st.paymentId,sessionId:Ae.sessionId??st.sessionId,authorizationExpiresAt:Ae.authorizationExpiresAt??st.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ae.intentId,checkoutMethod:"card"})}),re=at.on("decline",async Ae=>{let{updateError:st,emitDecline:Pt}=vn.current,Qe=Ae.message??"Your payment was declined. Please try another card or contact your bank.";L.current="terminal",st(Qe),Me("error");let wt=Ae.failureOutcome??Hs(Ae.declineReason)??"authorization_declined";Pt("card",Qe,{code:wt,declineCode:wt}),await new Promise(ge=>setTimeout(ge,Sn)),!r&&(L.current="idle",Me(null))}),U=at.on("error",async Ae=>{let{updateError:st,onError:Pt}=vn.current,Qe=Ae.message??"There was a problem processing your payment. Please try again.";L.current="terminal",st(Qe),Me("error"),Pt?.(new Rn(Qe,"api_error",{code:Ae.failureOutcome??"capture_failed"})),await new Promise(wt=>setTimeout(wt,Sn)),!r&&(L.current="idle",Me(null))}),we=at.on("blocked",()=>{if(!Ra.current){cn(!0);return}vn.current.updateError(Ci)});return()=>{r=!0,D.current&&(clearTimeout(D.current),D.current=null),L.current="idle",M(),$(),re(),U(),we()}},[Ve,at]);let Cn=!!$e?.clientId,Er=Array.isArray(y),Qr=Er&&y.length>0,es=Er&&y.includes("paypal"),{expressMethods:Zr,paymentElementMethods:_r}=lt(()=>rl(y,{excludePaypal:Cn}),[y,Cn]),Ia=Cn||!!mt,ts=lt(()=>Ia?Zr.filter(r=>r!=="paypal"):Zr,[Zr,Ia]),ns=lt(()=>{let r=[];return F&&r.push("apple_pay"),te&&r.push("google_pay"),r},[F,te]),eo=Er?ts:ns,rs=I&&eo.length>0,To=zn?Je:_e,to=lt(()=>{let r=To?.trim().toUpperCase();return r?he?_r.filter(M=>{let $=he[M];return!$||$.length===0||$.includes(r)}):el(_r,To):_r},[_r,To,he]),Mo=lt(()=>({mode:"payment",amount:ne,currency:de.toLowerCase(),paymentMethodCreation:"manual",appearance:Nt}),[ne,de,Nt]),[Ea,_a]=ke("loading"),[xa,Ta]=ke("loading"),[Ma,Aa]=ke("loading"),[os,Ao]=ke(!1),[Ba,Bo]=ke("loading"),[no,as]=ke();ct(()=>{as(di())},[]);let Fa=w&&(Cn||(Er?es:no===!1)),Da=I&&rs,xr=!qe&&Fa&&Cn,La=Ba==="retrying"||Ba==="exhausted",Tr=!qe&&Fa&&!!T&&(!Cn||La),Mr=!qe&&Da&&!!C,Ar=!qe&&I&&Qr&&to.length>0&&!!C,is=xr&&!La?os:Tr&&ki(Ea),ss=Mr&&ki(xa),ls=Ar&&Ma!=="load_error",Oa=r=>r==="loading"||r==="ready",za=xr||Tr&&Oa(Ea)||Mr&&Oa(xa)||Ar&&Ma!=="load_error",ro=Be(!1);ct(()=>{if(!ro.current){if(!I&&!w){ro.current=!0;let r=new Rn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");p?.(r),me(r.message)}else if(!I&&w&&!Cn&&!T){ro.current=!0;let r=new Rn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");p?.(r),me(r.message)}else if(no!==void 0&&!qe&&!He&&!za){ro.current=!0;let r=new Rn("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"});p?.(r),me(r.message)}}},[I,w,Cn,T,no,qe,He,za,p,me]);let Na=Be(!1);ct(()=>{if(Na.current||!Qr)return;let r=[];F!==!0&&r.push("showApplePay"),te!==!0&&r.push("showGooglePay"),r.length!==0&&(Na.current=!0,console.warn(`[FloPay] ${r.join(" / ")} ${r.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.`))},[Qr,F,te]);let Ua=Ee((r,M)=>je.applyInlineSessionPatch?je.applyInlineSessionPatch(r).then($=>({error:null,sessionId:$.sessionId||e,nonce:$.session?.clientSecret||t})).catch($=>{let re=wi(M,$);return me(re.message),p?.(re),{error:re,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[je.applyInlineSessionPatch,t,p,e,me]),pn=Ee(async r=>{if(!Re)return{proceed:!0};try{let M=await Re({method:r,sessionId:e||void 0,createSession:je.inlineSessionDraft});if(M===!1)return{proceed:!1};if(M&&typeof M=="object"){M.account&&On(re=>({...re??{},...M.account}));let $=await Ua(M,r);return $.error?{proceed:!1,accountPatch:M.account}:{proceed:!0,accountPatch:M.account,sessionId:$.sessionId,nonce:$.nonce}}return{proceed:!0}}catch(M){let $=wi(r,M);return me($.message),p?.($),{proceed:!1}}},[Ua,je.inlineSessionDraft,Re,p,e,me]),$a=Ee(async(r,M)=>{if(k.current)return;k.current=!0,en(!0),Me("processing"),me(null);let $=M?.sessionId??e,re=M?.nonce??t,U=Wo(x,M?.accountPatch),we=M?.completionPaymentMethodId??$r(r),Ae=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r;try{let Pt=await new qn(Ge).processPayment(U.userId??"",{sessionId:$,nonce:re,tokenizedData:Ae,accountData:{userId:U.userId??"",email:U.email??"",firstName:U.firstName??"",lastName:U.lastName??"",...X?(()=>{let ge=dt.current,Tt=Oe(X.state,ge),Gt=Oe(X.address_line_1,ge),Xn=Oe(X.postal_code,ge),Qn=Gt&&!Tt&&Xn?hi(ge,(jt.current??"").trim()):null,Mt=Tt?Vt.current:Qn;return{country:ge,...Xn&&jt.current?{zip:jt.current}:{},...Oe(X.city,ge)&&Kt.current?{city:Kt.current}:{},...Mt?{state:Mt}:{},...Gt&&ln.current?{addressLine1:ln.current}:{},...Oe(X.address_line_2,ge)&&qt.current?{addressLine2:qt.current}:{}}})():{}},chv:R,avsCheck:Z??!1,checkoutType:_,checkoutLayout:ce,avsConfig:X?{country:Oe(X.country,dt.current),postal_code:Oe(X.postal_code,dt.current),address_line_1:Oe(X.address_line_1,dt.current),address_line_2:Oe(X.address_line_2,dt.current),city:Oe(X.city,dt.current),state:Oe(X.state,dt.current)}:void 0});if(Pt.ok){let ge=Pt.status===204?null:await Pt.json().catch(()=>null),Tt=ea(ue)||ge?.status==="authorized";fr($),Me("success"),Ce(null),await new Promise(Gt=>setTimeout(Gt,xn)),i?.(Tt?{status:"authorized",...typeof ge?.paymentId=="string"?{paymentId:ge.paymentId}:ue?.paymentId?{paymentId:ue.paymentId}:{},sessionId:typeof ge?.sessionId=="string"?ge.sessionId:$,...typeof ge?.authorizationExpiresAt=="string"?{authorizationExpiresAt:ge.authorizationExpiresAt}:ue?.authorizationExpiresAt?{authorizationExpiresAt:ue.authorizationExpiresAt}:{},paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:we,checkoutMethod:r.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:we,checkoutMethod:r.isPaypal?"paypal":"card"});return}let Qe=await Pt.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let ge=Qe.threeDSecureToken,Tt=Qe.paymentMethodId||r.id||"";if(!Y||!ge){Me("error"),me("PayPal authorization required but no token provided.");return}try{let Gt=mt?.getRawProvider();if(!Gt){me("PayPal is not available.");return}let Xn={return_url:window.location.href};Tt&&(Xn.payment_method=Tt);let{error:Qn}=await Gt.confirmPayment({clientSecret:ge,confirmParams:Xn,redirect:"if_required"});if(Qn){Me("error");let Mt=Qn.message??"PayPal payment failed.";me(Mt),un("paypal",Mt,{code:Qn.code})}}catch(Gt){Me("error"),me(Gt instanceof Error?Gt.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let ge=Qe.orderId;if(!ge){Me("error"),me("PayPal retry required but no order id provided.");return}let Tt=W.current?.attempts??0;if(Tt>=2){Me("error"),me("PayPal payment could not be completed after multiple attempts."),un("paypal","paypal_direct_required retry limit exceeded");return}Ao(!1),Bo("loading"),Ce({orderId:ge,attempts:Tt+1}),Me(null);return}Me("error");let wt=Qe?.message??"Payment failed. Please try again.";me(wt),un(r.isPaypal?"paypal":"card",wt,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(ge=>setTimeout(ge,Sn))}catch(st){Me("error"),me(st instanceof Error?st.message:"An unexpected error occurred"),await new Promise(Pt=>setTimeout(Pt,Sn))}finally{en(!1),Me(null),k.current=!1}},[Ge,e,t,x,N,R,Y,mt,ue,i,p,me,un]),an=Ee((r,M)=>{b?b(r):$a(r,M)},[b,$a]),ja=Be(!1);ct(()=>{if(typeof window>"u"||ja.current)return;let r=new URLSearchParams(window.location.search),M=r.get("payment_intent"),$=r.get("payment_intent_client_secret"),re=r.get("redirect_status");if(!M||!$)return;let U=wt=>{let ge=localStorage.getItem(wt);if(!ge)return null;try{return JSON.parse(ge)}catch{return localStorage.removeItem(wt),null}},we=U(In)??U(vi),Ae;if(we?.clientSecret){if(we.clientSecret!==$)return;Ae={...we.accountPatch?{accountPatch:we.accountPatch}:{},...we.sessionId?{sessionId:we.sessionId}:{},...we.nonce?{nonce:we.nonce}:{}}}else if(we?.sessionId&&we.sessionId!==e)return;ja.current=!0,localStorage.removeItem(In),localStorage.removeItem(vi);let st=new URL(window.location.href);st.searchParams.delete("payment_intent"),st.searchParams.delete("payment_intent_client_secret"),st.searchParams.delete("redirect_status"),window.history.replaceState({},"",st.toString());let Pt=we?.paymentMethodType??we?.tokenType??"card",Qe="card";(async()=>{let wt=Y?.getRawProvider();if(!wt){let Mt="Payment is not available \u2014 please refresh and try again.";me(Mt),un(Qe,Mt);return}if(re==="failed"){let Mt="Payment was declined. Please try again.";me(Mt),un(Qe,Mt);return}let{paymentIntent:ge,error:Tt}=await wt.retrievePaymentIntent($);if(Tt){let Mt=Tt.message??"Failed to retrieve payment status.";me(Mt),un(Qe,Mt,{code:Tt.code});return}let Gt=ge?.status,Xn=yo(Gt);if(!ge||!Xn){let Mt=Gt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(Mt),un(Qe,Mt,{code:Gt??"missing_payment_intent"});return}let Qn=typeof ge.payment_method=="string"?ge.payment_method:ge.payment_method?.id;an({id:Qn??we?.paymentMethodId??we?.tokenId??ge.id,type:"card",threeDSecureActionResultTokenId:ge.id,gateway:we?.gateway??"stripe",paymentMethodType:Pt},Ae)})()},[e,an,Y,me,un]);let Fo=Ee(r=>{r.preventDefault()},[]);if(!(Y!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Br=be==="buttons",Wt=E?.variables,cs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Do=Wt?.colorBackground,ds=Do&&!cs.has(Do)?Do:void 0,Fr=o.cardInputBorder??(Br?"#e5e7eb":"#A4A4FF"),Lo=Wt?.colorDanger??"#dc2626",Wn=r=>Lt&&r?Lo:Fr,oo=(Ht.malformed||Ht.empty)&&(rn||Lt),us=oo?Lo:Wn(Ct.zip),Oo=o.cardFormContainer?.backgroundColor??ds??(Br?"white":"#EDEDFF"),Dr=o.cardInputBackground??Wt?.colorBackground??"white",zo=cr(f),qa=cr(ae),lr=o.nameInput,Ka=o.cardInputFontSize??hl(lr?.fontSize)??Wt?.fontSizeBase??"16px",Va=typeof lr?.fontFamily=="string"?lr.fontFamily:Wt?.fontFamily??"Poppins, sans-serif",Ha=Qa(lr?.fontWeight)??400,ps=o.cardInputColor??(typeof lr?.color=="string"?lr.color:void 0)??Wt?.colorText??"#262833",ms=o.cardInputPlaceholderColor??"#9ca3af",ht=Wt?.borderRadius??"8px",Gn=Wt?.borderRadius??o.cardButton?.borderRadius??ht,Jn=Wt?.colorPrimary??"#4A49FF",ys=Wt?.colorPrimaryHover??Or(Jn,.12),No=Wt?.colorText??"#262833",Ya={fontSize:Ka,fontFamily:Va,fontWeight:Ha,color:ps,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},fs={"--flopay-input-placeholder-color":ms,"--flopay-input-font-size":Ka,"--flopay-input-font-family":Va,"--flopay-input-font-weight":String(Ha)},Lr=o.cardFormContainer??{},Uo=Lr.padding??(Br?"0":"1rem"),$o=Lr.borderRadius??ht,gs=at&&Zt?d(jo,{capture:at,html:Zt.html,messageToken:Zt.messageToken,expectedOrigin:Zt.expectedOrigin,theme:ye,onReady:()=>{if(!X||typeof document>"u")return;let r=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};r();let M=0,$=window.setInterval(()=>{M+=1;let re=document.activeElement;!!re&&re.tagName==="IFRAME"&&re.id==="flopay_vault_form_iframe"?(r(),window.clearInterval($)):M>=50&&window.clearInterval($)},100)},onError:r=>me(r),onValidation:r=>{let M=L.current;(M==="idle"||M==="validation-window")&&(me(r),r&&L.current==="validation-window"&&(D.current&&(clearTimeout(D.current),D.current=null),L.current="idle",Me(null)))}}):d("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"}),Wa=ze("div",{style:{backgroundColor:Oo,borderRadius:$o,...Lr,padding:Uo,...fs,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
25
|
+
`,Fo=44;function ba(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 Nl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Wi={width:"100%",minHeight:Fo,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 zl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function $i(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ji(e){return e==="paypal"?"PayPal":Rr(e)}function Ul(e,t){let n=`We couldn't open ${Ji(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Xi(e){let t=Ee(0),n=Ee(null),r=Ee(null),o=he((p=r.current)=>{let S=p;S?.timer&&(clearTimeout(S.timer),S.timer=null)},[]),a=he((p,S)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(p),p.timer=setTimeout(()=>{p.timer=null,r.current?.generation===p.generation&&(r.current=null,n.current=p.generation,e(p.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},S))},[o,e]),m=he(p=>{p.yieldedControl&&a(p,600)},[a]),d=he(p=>{o();let S=t.current+1;t.current=S,n.current=null;let ee={generation:S,method:p,timer:null,yieldedControl:!1};return r.current=ee,S},[o]),T=he(p=>{let S=r.current;return typeof p=="number"&&S?.generation!==p?!1:(o(S),r.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[o]),h=he(p=>{let S=r.current,ee=p??S?.generation??t.current;(!p||S?.generation===p)&&(o(S),r.current=null),n.current=ee},[o]),P=he(p=>n.current===(p??t.current),[]),b=he(p=>r.current?.generation===p&&n.current!==p,[]),x=he(()=>{let p=r.current;p&&m(p)},[m]),U=he(()=>{let p=r.current;p&&(p.yieldedControl=!0,o(p))},[o]);return lt(()=>{let p=()=>{document.visibilityState==="visible"?x():U()},S=()=>{U()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",S),window.addEventListener("focus",x),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",S),window.removeEventListener("focus",x),o()}},[o,U,x]),{startAttempt:d,finishAttempt:T,invalidateAttempt:h,isAttemptInvalidated:P,isAttemptCurrent:b}}function $l(e){let t=Cl(e);return`Enter a valid ${ya(e)}${t?` (e.g. ${t})`:""}`}function ql(e,t,n){let r=kl(e),o=t.trim(),a=n&&r,m=a&&!o,d=a&&!!o&&!El(e,o);return{visible:n,supported:r,required:a,empty:m,malformed:d}}function qi(e,t){return t instanceof In?t:new In(t instanceof Error?t.message:`${zl(e)} before-click hook failed.`,"validation_error")}function ma(){return u("style",{children:Ol})}function jl(e){return typeof e=="number"?`${e}px`:e}function Zi(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Qi({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:xe("div",{style:{position:"relative",minHeight:44},children:[u("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),u("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function ji(e){return e!=="unavailable"&&e!=="load_error"}function va(e){return u(Vl,{...e})}function Ki({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:m=!1,onButtonClick:d,onDecline:T,onTechnicalFailure:h,runBeforeButtonClick:P,onLoadStateChange:b,placeholderBorderRadius:x}){let U=Xn(),{emitInstrument:p}=_r(Pn),S=ha(),ee=ga(),[W,v]=ge("loading");lt(()=>{b?.(W)},[W,b]);let[ye,j]=ge(!1),J=Ee(!1),ce=Ee(null),Se=Ee(null),[re,le]=ge(0),[Ve,Ae]=ge(!1),Ce=Ee(!1),q=Ee(new Map),{startAttempt:B,finishAttempt:te,invalidateAttempt:tt,isAttemptInvalidated:Me,isAttemptCurrent:V}=Xi((O,w,oe)=>{h?.(O,w,{...oe,popupBlocked:oe?.popupBlocked??Jn(w)}),Ae(!0),le(qe=>qe+1)});lt(()=>{Ve&&Se.current?.focus()},[Ve,re]);let de=he(()=>{le(O=>O+1)},[]),ae=he((O,w,oe)=>{tt(oe),h?.("paypal",O,{code:w,popupBlocked:Jn(O)}),Ae(!0),de()},[tt,h,de]),ue=he(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);lt(()=>{Ce.current&&(Ce.current=!1,ue())},[ue,re]);let ke=he(()=>{Ae(!1),a?.(null),ue()},[ue,a]);lt(()=>{if(!S||J.current)return;let O=new URLSearchParams(window.location.search),w=O.get("payment_intent"),oe=O.get("payment_intent_client_secret"),qe=O.get("redirect_status");if(!w||!oe)return;J.current=!0;let De;try{let R=localStorage.getItem(Qr);if(R){let H=JSON.parse(R);H.clientSecret===oe&&(De={...H.accountPatch?{accountPatch:H.accountPatch}:{},...H.sessionId?{sessionId:H.sessionId}:{},...H.nonce?{nonce:H.nonce}:{}})}}catch{}try{localStorage.removeItem(Qr)}catch{}let Z=new URL(window.location.href);Z.searchParams.delete("payment_intent"),Z.searchParams.delete("payment_intent_client_secret"),Z.searchParams.delete("redirect_status"),window.history.replaceState({},"",Z.toString()),(async()=>{try{if(j(!0),qe==="failed"){let $="PayPal payment was declined. Please try again.";a?.($),T?.(Mt("paypal",$));return}let{paymentIntent:R,error:H}=await S.retrievePaymentIntent(oe);if(H){a?.(H.message??"Failed to retrieve PayPal payment status.");return}if(R&&(R.status==="requires_capture"||R.status==="succeeded")){let $=typeof R.payment_method=="string"?R.payment_method:R.payment_method?.id;o({id:$??R.id,type:"card",threeDSecureActionResultTokenId:R.id,isPaypal:!0},De)}else{let $="PayPal payment was not completed. Please try again.";a?.($),T?.(Mt("paypal",$))}}catch(R){a?.(R instanceof Error?R.message:"Failed to complete PayPal payment.")}finally{j(!1)}})()},[S,o,a,T]);let pe=he(async O=>{if(m||ye){O.reject();return}let w=P?await P("paypal"):{proceed:!0};if(!w.proceed){q.current.delete(re),O.reject();return}let oe=B("paypal");q.current.set(re,{generation:oe,accountPatch:w.accountPatch,sessionId:w.sessionId,nonce:w.nonce}),Ae(!1),d?.("paypal"),O.resolve()},[q,m,d,P,B,ye,re]),Re=he(async O=>{if(!S||!ee)return;let w=q.current.get(re);if(w&&!V(w.generation)){q.current.delete(re);return}if(!w&&Me()||w&&!te(w.generation))return;w||te();let oe=w??null;if(q.current.delete(re),!oe&&P){let R=await P("paypal");if(!R.proceed){O.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}oe={accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}}let qe=oe?.sessionId??e,De=oe?.nonce??t,Z=oe?.accountPatch?.email??n;try{if(j(!0),a?.(null),!qe||!Z)throw new Error("Missing sessionId or email for PayPal payment");let R=S.createPaymentMethod,{error:H,paymentMethod:$}=await R({type:"paypal"});if(H){ae(H,"stripe_paypal_create_payment_method_failed",w?.generation),O.paymentFailed({reason:"fail"});return}let Be=await Do(r,p,qe,De??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:$?.id??null,intentKind:"payment"});if(Be.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Ie=Be.clientSecret,We={return_url:window.location.href};if($?.id&&(We.payment_method=$.id),typeof window<"u")try{localStorage.setItem(Qr,JSON.stringify({clientSecret:Ie,sessionId:qe,nonce:De,accountPatch:oe?.accountPatch}))}catch{}let{error:Y,paymentIntent:mt}=await S.confirmPayment({clientSecret:Ie,confirmParams:We,redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(Qr)}catch{}if(Wr(Y)){let Le=Y.message??"Your payment was declined.";a?.(Le),T?.(Mt("paypal",Le,{code:Un(Y),declineCode:vr(Y)})),await Lo({billingApiUrl:r,sessionId:qe,nonce:De,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Un(Y)??"provider_declined"}})}else ae(Y,"stripe_paypal_confirm_failed",w?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Qr)}catch{}let D=typeof mt?.payment_method=="string"?mt.payment_method:mt?.payment_method?.id;o({id:D??mt?.id,type:"card",threeDSecureActionResultTokenId:mt?.id,isPaypal:!0},{accountPatch:oe?.accountPatch,sessionId:qe,nonce:De});return}catch(R){ae(R,"stripe_paypal_failed",w?.generation)}finally{j(!1)}},[S,ee,e,t,n,r,p,o,a,T,P,ae,te,V,Me,re]);return xe(Er,{children:[u(Qi,{state:W,placeholderTestId:"flopay-paypal-placeholder",borderRadius:x,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Ve&&u("button",{ref:Se,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ke,style:Wi,children:"Try PayPal again"}),u(Yi,{onReady:O=>v(Zi(O,["paypal"])),onLoadError:()=>{v("load_error"),Pa(Bt(U),"paypal","paypal")},onClick:pe,onConfirm:Re,onCancel:()=>{let O=q.current.get(re);q.current.delete(re),Bt(U)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),tt(O?.generation),Ae(!1),Ce.current=!0,de()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},re)]})}),ye&&u(Mn,{status:"processing"})]})}function Vi({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:m,onErrorChange:d,onButtonClick:T,onDecline:h,onTechnicalFailure:P,runBeforeButtonClick:b,onLoadStateChange:x,placeholderBorderRadius:U}){let p=Xn(),{emitInstrument:S}=_r(Pn),ee=ha(),W=ga(),[v,ye]=ge("loading");lt(()=>{x?.(v)},[v,x]);let[j,J]=ge(!1),ce=Ee(null),Se=Ee(null),[re,le]=ge(0),[Ve,Ae]=ge(!1),[Ce,q]=ge("google_pay"),B=Ee(!1),te=Ee("google_pay"),tt=Ee("google_pay"),Me=Ee(new Map),{startAttempt:V,finishAttempt:de,invalidateAttempt:ae,isAttemptInvalidated:ue,isAttemptCurrent:ke}=Xi((Z,R,H)=>{P?.(Z,R,{...H,popupBlocked:H?.popupBlocked??Jn(R)}),q(Z),Ae(!0),le($=>$+1)});lt(()=>{Ve&&Se.current?.focus()},[Ve,re]);let pe=he(()=>{le(Z=>Z+1)},[]),Re=he((Z,R,H,$)=>{ae($),P?.(Z,R,{code:H,popupBlocked:Jn(R)}),q(Z),Ae(!0),pe()},[ae,P,pe]),O=he(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);lt(()=>{B.current&&(B.current=!1,O())},[O,re]);let w=he(()=>{Ae(!1),d?.(null),O()},[O,d]),oe=he(async Z=>{if(!ee||!W)return;let R=Me.current.get(re);if(R&&!ke(R.generation)){Me.current.delete(re);return}if(!R&&ue()||R&&!de(R.generation))return;R||de();let H=Z.expressPaymentType??R?.method??te.current,$=R??null;Me.current.delete(re);let Be=$i(H);if(!$&&b){let D=await b(Be);if(!D.proceed){Z.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}$={accountPatch:D.accountPatch,sessionId:D.sessionId,nonce:D.nonce}}let Ie=Be,We=$?.sessionId??e,Y=$?.nonce??t,mt=$?.accountPatch?.email??n;try{J(!0),d?.(null);let{error:D}=await W.submit();if(D){Re(H,D,"stripe_wallet_submit_failed",R?.generation);return}let{error:Le,paymentMethod:Pt}=await ee.createPaymentMethod({elements:W});if(Le||!Pt){Re(H,Le??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",R?.generation);return}if(!We||!mt)throw new Error("Missing sessionId or email for wallet payment");let N=await Do(r,S,We,Y??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H??Be,paymentMethodId:Pt.id,intentKind:o});if(N.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let bt=N.clientSecret,{error:ze,intentId:tn}=Il(bt)?await ee.confirmCardSetup(bt,{payment_method:Pt.id}).then(It=>({error:It.error,intentId:It.setupIntent?.id})):await ee.confirmCardPayment(bt,{payment_method:Pt.id}).then(It=>({error:It.error,intentId:It.paymentIntent?.id}));if(ze){if(Wr(ze)){let It=ze.message??"Your payment was declined.";d?.(It),h?.(Mt(Ie,It,{code:Un(ze),declineCode:vr(ze)})),await Lo({billingApiUrl:r,sessionId:We,nonce:Y,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H??Be,providerDeclineReason:Un(ze)??"provider_declined"}})}else Re(H,ze,"stripe_wallet_confirm_failed",R?.generation);return}m({id:Pt.id,type:"card",threeDSecureActionResultTokenId:tn},{accountPatch:$?.accountPatch,sessionId:We,nonce:Y})}catch(D){Re(H,D,"stripe_wallet_failed",R?.generation)}finally{J(!1)}},[ee,W,e,t,n,r,S,o,m,d,h,b,Re,de,ke,ue,re]),qe=st(()=>{let Z=["applePay","googlePay","paypal","link","amazonPay","klarna"],R=new Set(["applePay","googlePay"]),H=new Set(a.map(Ni)),$={};for(let Be of Z)H.has(Be)?$[Be]=R.has(Be)?"always":"auto":$[Be]="never";return $},[a]),De=st(()=>a.map(Ni),[a]);return xe(Er,{children:[u(Qi,{state:v,placeholderTestId:"flopay-wallet-placeholder",borderRadius:U,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Ve&&xe("button",{ref:Se,type:"button","data-testid":"flopay-wallet-retry-button",onClick:w,style:Wi,children:["Try ",Ji(Ce)," again"]}),u(Yi,{onReady:Z=>{ye(Zi(Z,De))},onLoadError:Z=>{ye("load_error"),Pa(Bt(p),"stripe","wallet")},onClick:async Z=>{te.current=Z.expressPaymentType,tt.current=$i(Z.expressPaymentType);let R=b?await b(tt.current):{proceed:!0};if(!R.proceed){Me.current.delete(re),Z.reject();return}let H=V(Z.expressPaymentType);Me.current.set(re,{generation:H,method:Z.expressPaymentType,accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}),Ae(!1),T?.(tt.current),Z.resolve()},onConfirm:oe,onCancel:()=>{let Z=Me.current.get(re);Me.current.delete(re),Bt(p)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ae(Z?.generation),Ae(!1),B.current=!0,pe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:qe,layout:{maxColumns:1,overflow:"never"}}},re)]})}),j&&u(Mn,{status:"processing"})]})}function Kl({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:m,backgroundColor:d,borderColor:T,textColor:h,borderRadius:P,fontFamily:b}){let x=Al(e,t),U=Fi[e],p=x?.backgroundColor??d??"#ffffff",S=x?.borderColor??T??"#d1d5db",ee=x?.textColor??h??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&m()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Fo,padding:"0 1rem",backgroundColor:p,color:ee,border:`1px solid ${S}`,borderRadius:P??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?u("span",{style:{margin:"0 auto"},children:`Connecting to ${Rr(e)}\u2026`}):xe(Er,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:wl(e)?8:0},children:[U?u("img",{src:U,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):x?.logoSvg?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:x.logoSvg}}):null,u("span",{children:Rr(e)})]}),a&&u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ee,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:u("path",{d:"M9 18l6-6-6-6"})})]})})}function fa({method:e,sessionId:t,nonce:n,email:r,billingName:o,billingApiUrl:a,onTokenizedBody:m,onErrorChange:d,onDecline:T,onCancel:h,runBeforeButtonClick:P,onButtonClick:b,isProcessing:x,submitButtonColor:U,submitButtonBorderRadius:p,submitButtonStyle:S,errorText:ee}){let W=Xn(),{emitInstrument:v}=_r(Pn),ye=ha(),j=ga(),[J,ce]=ge(!1),Se=Ee(!1),[re,le]=ge(!1),[Ve,Ae]=ge("loading"),Ce=he(async()=>{if(!ye||!j||x||Se.current||!re)return;Se.current=!0,ce(!0);let q=P?await P("card"):{proceed:!0};if(!q.proceed){Se.current=!1,ce(!1);return}b?.("card");let B=q.sessionId??t,te=q.nonce??n,tt=q.accountPatch?.email??r;try{d?.(null);let Me=await j.submit();if(Me.error){d?.(Me.error.message??"Payment failed.");return}let V=await ye.createPaymentMethod({elements:j});if(V.error||!V.paymentMethod){d?.(V.error?.message??"Failed to create payment method.");return}let de=V.paymentMethod;if(!B||!tt)throw new Error("Missing sessionId or email for payment.");let ae=de.type||e,ue=await Do(a,v,B,te??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ae,paymentMethodId:null,intentKind:"payment"});if(ue.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ke=ue.clientSecret;if(typeof window<"u")try{localStorage.setItem(Bn,JSON.stringify({clientSecret:ke,sessionId:B,nonce:te,accountPatch:q.accountPatch,paymentMethodId:de.id,paymentMethodType:de.type??e,gateway:"stripe"}))}catch{}let{error:pe,paymentIntent:Re}=await ye.confirmPayment({clientSecret:ke,confirmParams:{return_url:window.location.href,payment_method:de.id},redirect:"if_required"});if(pe){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let oe=pe.message??"Payment failed.";d?.(oe),T?.(Mt("card",oe,{code:pe.code})),await Lo({billingApiUrl:a,sessionId:B,nonce:te,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:pe.code??"provider_declined"}});return}let O=Re?.status;if(!vo(O)){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let oe=O==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";d?.(oe),T?.(Mt("card",oe,{code:O??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let w=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;m({id:w??de.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:de.type??e},{accountPatch:q.accountPatch,sessionId:B,nonce:te})}catch(Me){d?.(Me instanceof Error?Me.message:"Payment failed. Please try again.")}finally{Se.current=!1,ce(!1)}},[ye,j,x,re,P,b,t,n,r,a,v,e,m,d,T]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[u(Bl,{onReady:()=>Ae("ready"),onLoadError:()=>{Ae("load_error"),Pa(Bt(W),"stripe","apm")},onChange:q=>{le(!!q.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...r?{email:r}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ce()},disabled:!re||J||x||Ve!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:U,color:"white",border:"none",borderRadius:p,fontSize:"1rem",fontWeight:600,cursor:!re||J||x||Ve!=="ready"?"not-allowed":"pointer",opacity:!re||J||x||Ve!=="ready"?.5:1,transition:"opacity 120ms ease-out",...S??{}},children:J?"Processing\u2026":`Pay with ${Rr(e)}`}),ee&&u(wr,{margin:"0.75rem 0 0",children:ee})]})}function Hi({sessionId:e,nonce:t,email:n,billingName:r,billingApiUrl:o,paymentElementMethods:a,stripeInstance:m,paymentElementBaseOptions:d,onTokenizedBody:T,onErrorChange:h,onButtonClick:P,onDecline:b,runBeforeButtonClick:x,onLoadStateChange:U,isProcessing:p=!1,submitButtonColor:S="#4A49FF",submitButtonBorderRadius:ee=8,submitButtonStyle:W,buttonAppearance:v,themeId:ye,onExpandApm:j,expandedApmMethod:J}){let{emitInstrument:ce}=_r(Pn),[Se,re]=ge(null),[le,Ve]=ge(null),Ae=Ee(!1);lt(()=>{a.length>0&&m?U?.("ready"):m||U?.("loading")},[a.length,m,U]);let Ce=he(async V=>{if(!m||Ae.current||p)return;Ae.current=!0,Ve(V);let de=x?await x("card"):{proceed:!0};if(!de.proceed){Ae.current=!1,Ve(null);return}P?.("card");let ae=de.sessionId??e,ue=de.nonce??t,ke=de.accountPatch?.email??n;try{if(h?.(null),!ae||!ke)throw new Error("Missing sessionId or email for payment.");let pe=await Do(o,ce,ae,ue??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:V,paymentMethodId:null,intentKind:"payment"});if(pe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=pe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Bn,JSON.stringify({clientSecret:Re,sessionId:ae,nonce:ue,accountPatch:de.accountPatch,paymentMethodType:V,gateway:"stripe"}))}catch{}let{error:O,paymentIntent:w}=await m.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:V,billing_details:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...ke?{email:ke}:{}}}},redirect:"if_required"});if(O){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let De=O.message??"Payment failed.";h?.(De),b?.(Mt("card",De,{code:O.code})),await Lo({billingApiUrl:o,sessionId:ae,nonce:ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:V,providerDeclineReason:O.code??"provider_declined"}});return}let oe=w?.status;if(!vo(oe)){if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let De=oe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(De),b?.(Mt("card",De,{code:oe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Bn)}catch{}let qe=typeof w?.payment_method=="string"?w.payment_method:w?.payment_method?.id;T({id:qe??w?.id,type:"card",threeDSecureActionResultTokenId:w?.id,gateway:"stripe",paymentMethodType:V},{accountPatch:de.accountPatch,sessionId:ae,nonce:ue})}catch(pe){h?.(pe instanceof Error?pe.message:"Payment failed. Please try again.")}finally{Ae.current=!1,Ve(null)}},[m,p,x,P,e,t,n,o,ce,r,T,h,b]),[q,B]=ge(null),te=j?J??null:q,tt=he(V=>{Ae.current||p||te&&te!==V||(Oi(V)?j?j(V):B(V):Ce(V))},[te,p,Ce,j]),Me=st(()=>q?{...d,paymentMethodTypes:[q]}:null,[q,d]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(V=>{let de=J===V,ae=le===V,ue=le!==null&&le!==V||J!=null&&J!==V;return xe(Fl.Fragment,{children:[u(Kl,{method:V,themeId:ye,submitting:ae,disabled:ue,highlighted:de,hasNextStep:Oi(V),onClick:()=>tt(V),backgroundColor:v?.backgroundColor,borderColor:v?.borderColor,textColor:v?.textColor,borderRadius:v?.borderRadius,fontFamily:v?.fontFamily}),!j&&q===V&&Me&&m&&u(pr,{stripe:m,options:Me,children:u(fa,{method:V,sessionId:e,email:n,billingName:r,billingApiUrl:o,onTokenizedBody:T,onErrorChange:h,onDecline:b,onCancel:()=>B(null),runBeforeButtonClick:x,onButtonClick:P,isProcessing:p,submitButtonColor:S,submitButtonBorderRadius:ee,submitButtonStyle:W})},V)]},V)})})}function Vl({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:m,onDecline:d,onTokenizedBody:T,firstName:h,lastName:P,chv:b,className:x,isProcessing:U,error:p,onErrorChange:S,showPayPal:ee=!0,showStripe:W=!0,enabledPaymentMethods:v,enabledPaymentMethodCountries:ye,showApplePay:j=!0,showGooglePay:J=!0,layout:ce="default",theme:Se,buttonsTheme:re,buttonsStyles:le,appearance:Ve,cardButtonContent:Ae,cardBackButtonContent:Ce,cardTitleContent:q,showSecurityFooter:B,onButtonClick:te,onBeforeButtonClick:tt,enableAVS:Me,cardFieldOrder:V,cardPreFormSlot:de,avsLayout:ae="row",country:ue,zip:ke,addressLine1:pe,addressLine2:Re,city:O,state:w,onCountryChange:oe,onZipChange:qe,avsCheck:De,checkoutType:Z,checkoutLayout:R,totalAmount:H=0,currency:$="usd",initialCardOpen:Be=!1,directPaypal:Ie,isSubscription:We=!1,session:Y,dataAttachmentPending:mt=!1,debug:D=!1}){let Le=Xn(),Pt=na(),N=_r(kn),{emitInstrument:bt}=_r(Pn),ze=mt||N.claimPending===!0,tn=Pi(),[It,k]=ge(!1),[se,yt]=ge(null),[Fe,Vt]=ge(ue??"US"),[Xt,Ge]=ge(ke??""),[vt,Je]=ge(pe??""),[Lt,je]=ge(Re??""),[Ht,Et]=ge(O??""),[nn,Nt]=ge(w??""),[En,sn]=ge({}),rt=Ee(ke??""),zt=Ee(ue??"US"),Ke=Ee(pe??""),Rn=Ee(Re??""),ct=Ee(O??""),vn=Ee(w??""),Ut=Ee({});lt(()=>{let i=(_,z,Q,L,fe)=>{if(Ut.current[_])return;let we=z?.trim();!we||we===Q.current||(Q.current=we,L(we),fe?.(we))};i("country",ue,zt,Vt,oe),i("zip",ke,rt,Ge,qe),i("addressLine1",pe,Ke,Je),i("addressLine2",Re,Rn,je),i("city",O,ct,Et),i("state",w,vn,Nt)},[ue,ke,pe,Re,O,w,oe,qe]);let ne=st(()=>Tl(Me),[Me]),Vn=ne!==null,_n=st(()=>ua(Y),[Y]),Tn=!!Y?.vault?.html,xn=!!Y?.gateways?.pcivault,I=!!(Y?.gateways?.stripe?.enabledPaymentMethods??v)?.includes("card"),Xe=Tn||I||xn,Pe=!!(W&&Xe&&Le&&e),[Cn,Oe]=ge(()=>ce!=="buttons"||Be?e??null:null),[Hn,nr]=ge(0),Yt=ce!=="buttons"||Be||!!e&&Cn===e,dt=st(()=>!Le||!Pe||!e||!Yt?null:Le.cardCapture({sessionId:e,captureMethod:Y?.captureMethod}),[Le,Pe,e,Yt,Y?.captureMethod]),Zt=st(()=>{let i=Fe,_=ne?Te(ne.postal_code,i):!1;return ql(i,Xt,_)},[ne,Fe,Xt]),{avsInvalid:Gt,invalidAvsFields:ot}=st(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Pe||!ne)return{avsInvalid:!1,invalidAvsFields:i};let _=Fe,z=(fe,we)=>Te(fe,_)&&!we.trim(),Q={line1:z(ne.address_line_1,vt),city:z(ne.city,Ht),state:z(ne.state,nn),zip:Zt.empty||Zt.malformed};return{avsInvalid:Q.line1||Q.city||Q.state||Q.zip,invalidAvsFields:Q}},[Pe,ne,Fe,vt,Ht,nn,Zt]),[ln,cn]=ge(!1),[Yn,Sn]=ge(!1),[rn,dn]=ge(()=>pa(Y?.vault)),[me,Ct]=ge(Be&&Xe?"card":"buttons"),[at,on]=ge(null),un=me==="expanding"||me==="card",Ln=Y?.gateways?.stripe?"stripe":void 0,pn=he(()=>{bt?.({class:"card_surface",provider:Ln})},[Ln,bt]),$t=280,Wt=Ee(null),Jt=he(i=>{Wt.current&&clearTimeout(Wt.current),Wt.current=setTimeout(()=>{Wt.current=null,i()},$t)},[$t]);lt(()=>()=>{Wt.current&&clearTimeout(Wt.current)},[]);let Gn=he(()=>{pn(),Oe(e??null),nr(i=>i+1),Ct("expanding"),Jt(()=>Ct("card"))},[Jt,pn,e]),On=he(()=>{Ct("collapsing"),Jt(()=>Ct("buttons"))},[Jt]),An=he(i=>{on(i),Ct("apm-expanding"),Jt(()=>Ct("apm-form"))},[Jt]),Nn=he(()=>{Ct("apm-collapsing"),Jt(()=>{Ct("buttons"),on(null)})},[Jt]);lt(()=>{ce==="buttons"&&Be&&Xe&&(Oe(e??null),Ct("card"))},[ce,Be,Xe,e]);let[qt,Ze]=ge(null),mn=Ee(!1),jt=Ee(null),ut=Ee("idle"),[Qt,Rt]=ge(null),rr=Ee(Qt);lt(()=>{rr.current=Qt},[Qt]);let pt=n||tn,l=p??se,s=st(()=>Ml(Se),[Se]),c=st(()=>{let i=s?.buttonsLayout??xl(re);return le?{...i,...le,cardButton:{...i.cardButton,...le.cardButton},cardFormContainer:{...i.cardFormContainer,...le.cardFormContainer},backButton:{...i.backButton,...le.backButton},backButtonIcon:{...i.backButtonIcon,...le.backButtonIcon},submitButton:{...i.submitButton,...le.submitButton},title:{...i.title,...le.title}}:i},[s,re,le]),A=Ve??s?.appearance,K=st(()=>ci({appearance:A,buttonsStyles:c,layout:ce}),[A,c,ce]),F=N.inlineSessionPatchProcessing??!1,C=(U??It)||F,f=pt.replace(/\/+$/,""),y=st(()=>ta({userId:o,email:r,firstName:h,lastName:P,country:ue,zip:ke},En),[o,r,h,P,ue,ke,En]),g=[y.firstName,y.lastName].filter(i=>!!i?.trim()).join(" "),E=st(()=>Le?Le.getRawProvider():null,[Le]),G=st(()=>Pt?Pt.getRawProvider():null,[Pt]),ie=H||100,_e=st(()=>A?hl(A):null,[A]),Ue=_e?{appearance:_e}:null,Tt=st(()=>{let i=_e??{},_=i.rules??{};return{...i,rules:{..._,".AccordionItem":{padding:"10px 14px",boxShadow:"none",..._[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",..._[".AccordionItemContents"]??{}}}}},[_e]),be=st(()=>{let i=gi(H);return{...i,currency:$.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...Ue}},[H,$,Ue]),ve=st(()=>({mode:"payment",amount:ie,currency:$.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Ue}),[ie,$,Ue]),M=he(i=>{yt(i),S?.(i)},[S]);lt(()=>{!Pe||!dt||dt.setCardFieldOrder?.(V??null,ne==null)},[Pe,dt,V,ne]),lt(()=>{(me==="expanding"||me==="collapsing"||me==="apm-expanding"||me==="apm-collapsing")&&M(null)},[me,M]);let St=he((i,_,z)=>{d?.(Mt(i,_,z))},[d]),$e=he((i,_,z)=>{let Q=z?.popupBlocked??Jn(_),L=Ul(i,Q),fe=cr(z?.code)??Un(_)??"external_payment_method_failed",we=new In(L,"api_error",{code:"external_payment_method_failed",param:i});Ze(null),ce==="buttons"&&(Ct("buttons"),on(null)),M(L),m?.(we),console.error("[FloPay] External payment method failed:",{method:i,code:fe,popupBlocked:Q})},[ce,m,M]);lt(()=>{if(!Pe||!e){dn(null);return}let i=pa(Y?.vault);if(i){dn(i);return}if(!Yt){dn(null);return}dn(null);let _=!0;return new eo(f).getVaultCapture(e,t).then(z=>{if(!_)return;let Q=pa(z);Q?dn(Q):M("Failed to load the secure card form.")}).catch(z=>{_&&M(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{_=!1}},[Pe,Yt,Hn,e,Y?.vault?.html,Y?.vault?.messageToken,Y?.vault?.expectedOrigin,f,t,M]);let nt=Ee({onComplete:a,onError:m,updateError:M,emitDecline:St,resolvedAccount:y,avsConfig:ne,avsCheckProp:De,sessionId:e,nonce:t,baseUrl:f,captureMethod:Y?.captureMethod,paymentId:Y?.paymentId,authorizationExpiresAt:Y?.authorizationExpiresAt});nt.current={onComplete:a,onError:m,updateError:M,emitDecline:St,resolvedAccount:y,avsConfig:ne,avsCheckProp:De,sessionId:e,nonce:t,baseUrl:f,captureMethod:Y?.captureMethod,paymentId:Y?.paymentId,authorizationExpiresAt:Y?.authorizationExpiresAt};let or=Ee(!1),Da=he(()=>{let{resolvedAccount:i,avsConfig:_,avsCheckProp:z}=nt.current,Q=zt.current||i.country||"US",L=_?Te(_.state,Q):!1,fe=_?Te(_.address_line_1,Q):!1,we=_?Te(_.postal_code,Q):!1,ft=_?Te(_.city,Q):!1,Kt=_?Te(_.address_line_2,Q):!1,gt=fe&&!L&&we?Di(Q,(rt.current??"").trim()):null,it=L?vn.current:gt;return{accountData:{userId:i.userId??"",email:i.email??"",firstName:i.firstName??"",lastName:i.lastName??"",...we&&rt.current?{zip:rt.current}:{},...ft&&ct.current?{city:ct.current}:{},...it?{state:it}:{},...fe&&Ke.current?{addressLine1:Ke.current}:{},...Kt&&Rn.current?{addressLine2:Rn.current}:{},country:Q},...z!==void 0?{avsCheck:z}:{},..._?{avsConfig:{country:Te(_.country,Q),postal_code:we,address_line_1:fe,address_line_2:Kt,city:ft,state:L}}:{}}},[]),io=Ee(ze);io.current=ze,lt(()=>{ze||l!==Ui||nt.current.updateError(null)},[ze,l]),lt(()=>{!Pe||!dt||dt.setSubmitGate?.(Gt||ze)},[Pe,dt,Gt,ze]),lt(()=>{if(!Pe||!dt)return;or.current=!1;let i=!1,_=dt.on("submitting",()=>{cn(!0),jt.current&&clearTimeout(jt.current),ut.current="validation-window",jt.current=setTimeout(()=>{jt.current=null,ut.current==="validation-window"&&(ut.current="processing")},Dl),Ze("processing");let{baseUrl:we,sessionId:ft,nonce:Kt,updateError:gt,onError:it}=nt.current;!ft||!Kt||new eo(we).patchAccountSnapshot(ft,Kt,Da(),{telemetryMode:"best_effort"}).catch(Ne=>{if(!Ll(Ne))return;let zn=Ne instanceof Error?Ne.message:"Please check your billing address and try again.";gt(zn),ut.current="idle",Ze(null),it?.(Ne instanceof In?Ne:new In(zn,"api_error"))})}),z=dt.on("complete",async we=>{if(kr(we.sessionId??nt.current.sessionId),ut.current="terminal",Ze("success"),await new Promise(gt=>setTimeout(gt,1200)),or.current)return;or.current=!0;let ft=nt.current,Kt=ua(ft)||we.outcome==="authorized";nt.current.onComplete?.(Kt?{status:"authorized",paymentIntentId:we.intentId,paymentId:we.paymentId??ft.paymentId,sessionId:we.sessionId??ft.sessionId,authorizationExpiresAt:we.authorizationExpiresAt??ft.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:we.intentId,checkoutMethod:"card"})}),Q=dt.on("decline",async we=>{let{updateError:ft,emitDecline:Kt}=nt.current,gt=we.message??"Your payment was declined. Please try another card or contact your bank.";ut.current="terminal",ft(gt),Ze("error");let it=we.failureOutcome??Rl(we.declineReason)??"authorization_declined";Kt("card",gt,{code:it,declineCode:it}),await new Promise(Ne=>setTimeout(Ne,1500)),!i&&(ut.current="idle",Ze(null))}),L=dt.on("error",async we=>{let{updateError:ft,onError:Kt}=nt.current,gt=we.message??"There was a problem processing your payment. Please try again.";ut.current="terminal",ft(gt),Ze("error"),Kt?.(new In(gt,"api_error",{code:we.failureOutcome??"capture_failed"})),await new Promise(it=>setTimeout(it,1500)),!i&&(ut.current="idle",Ze(null))}),fe=dt.on("blocked",()=>{if(!io.current){cn(!0);return}nt.current.updateError(Ui)});return()=>{i=!0,jt.current&&(clearTimeout(jt.current),jt.current=null),ut.current="idle",_(),z(),Q(),L(),fe()}},[Pe,dt]);let an=!!Ie?.clientId,Fr=Array.isArray(v),so=Fr&&v.length>0,ds=Fr&&v.includes("paypal"),{expressMethods:lo,paymentElementMethods:Dr}=st(()=>_l(v,{excludePaypal:an}),[v,an]),La=an||!!Pt,us=st(()=>La?lo.filter(i=>i!=="paypal"):lo,[lo,La]),ps=st(()=>{let i=[];return j&&i.push("apple_pay"),J&&i.push("google_pay"),i},[j,J]),co=Fr?us:ps,ms=W&&co.length>0,$o=Vn?Fe:ue,uo=st(()=>{let i=$o?.trim().toUpperCase();return i?ye?Dr.filter(_=>{let z=ye[_];return!z||z.length===0||z.includes(i)}):vl(Dr,$o):Dr},[Dr,$o,ye]),qo=st(()=>({mode:"payment",amount:ie,currency:$.toLowerCase(),paymentMethodCreation:"manual",appearance:Tt}),[ie,$,Tt]),[Oa,Na]=ge("loading"),[za,Ua]=ge("loading"),[$a,qa]=ge("loading"),[ys,jo]=ge(!1),[ja,Ko]=ge("loading"),[po,fs]=ge();lt(()=>{fs(Bi())},[]);let Ka=ee&&(an||(Fr?ds:po===!1)),Va=W&&ms,Lr=!ze&&Ka&&an,Ha=ja==="retrying"||ja==="exhausted",Or=!ze&&Ka&&!!G&&(!an||Ha),Nr=!ze&&Va&&!!E,zr=!ze&&W&&so&&uo.length>0&&!!E,gs=Lr&&!Ha?ys:Or&&ji(Oa),hs=Nr&&ji(za),Ps=zr&&$a!=="load_error",Ya=i=>i==="loading"||i==="ready",Ga=Lr||Or&&Ya(Oa)||Nr&&Ya(za)||zr&&$a!=="load_error",mo=Ee(!1);lt(()=>{if(!mo.current){if(!W&&!ee){mo.current=!0;let i=new In("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");m?.(i),M(i.message)}else if(!W&&ee&&!an&&!G){mo.current=!0;let i=new In("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");m?.(i),M(i.message)}else if(po!==void 0&&!ze&&!Xe&&!Ga){mo.current=!0;let i=new In("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"});m?.(i),M(i.message)}}},[W,ee,an,G,po,ze,Xe,Ga,m,M]);let Wa=Ee(!1);lt(()=>{if(Wa.current||!so)return;let i=[];j!==!0&&i.push("showApplePay"),J!==!0&&i.push("showGooglePay"),i.length!==0&&(Wa.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.`))},[so,j,J]);let Ja=he((i,_)=>N.applyInlineSessionPatch?N.applyInlineSessionPatch(i).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let Q=qi(_,z);return M(Q.message),m?.(Q),{error:Q,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[N.applyInlineSessionPatch,t,m,e,M]),wn=he(async i=>{if(!tt)return{proceed:!0};try{let _=await tt({method:i,sessionId:e||void 0,createSession:N.inlineSessionDraft});if(_===!1)return{proceed:!1};if(_&&typeof _=="object"){_.account&&sn(Q=>({...Q??{},..._.account}));let z=await Ja(_,i);return z.error?{proceed:!1,accountPatch:_.account}:{proceed:!0,accountPatch:_.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(_){let z=qi(i,_);return M(z.message),m?.(z),{proceed:!1}}},[Ja,N.inlineSessionDraft,tt,m,e,M]),Xa=he(async(i,_)=>{if(mn.current)return;mn.current=!0,k(!0),Ze("processing"),M(null);let z=_?.sessionId??e,Q=_?.nonce??t,L=ta(y,_?.accountPatch),fe=_?.completionPaymentMethodId??Gr(i),we=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,ft=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Kt=()=>{bt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ft})};try{let it=await new eo(f).processPayment(L.userId??"",{sessionId:z,nonce:Q,tokenizedData:we,accountData:{userId:L.userId??"",email:L.email??"",firstName:L.firstName??"",lastName:L.lastName??"",...ne?(()=>{let He=zt.current,fn=Te(ne.state,He),gn=Te(ne.address_line_1,He),Ot=Te(ne.postal_code,He),Kr=gn&&!fn&&Ot?Di(He,(rt.current??"").trim()):null,Vr=fn?vn.current:Kr;return{country:He,...Ot&&rt.current?{zip:rt.current}:{},...Te(ne.city,He)&&ct.current?{city:ct.current}:{},...Vr?{state:Vr}:{},...gn&&Ke.current?{addressLine1:Ke.current}:{},...Te(ne.address_line_2,He)&&Rn.current?{addressLine2:Rn.current}:{}}})():{}},chv:b,avsCheck:De??!1,checkoutType:Z,checkoutLayout:R,avsConfig:ne?{country:Te(ne.country,zt.current),postal_code:Te(ne.postal_code,zt.current),address_line_1:Te(ne.address_line_1,zt.current),address_line_2:Te(ne.address_line_2,zt.current),city:Te(ne.city,zt.current),state:Te(ne.state,zt.current)}:void 0});if(it.ok){let He=it.status===204?null:await it.json().catch(()=>null),fn=ua(Y)||He?.status==="authorized";kr(z),Ze("success"),Rt(null),await new Promise(gn=>setTimeout(gn,1200)),a?.(fn?{status:"authorized",...typeof He?.paymentId=="string"?{paymentId:He.paymentId}:Y?.paymentId?{paymentId:Y.paymentId}:{},sessionId:typeof He?.sessionId=="string"?He.sessionId:z,...typeof He?.authorizationExpiresAt=="string"?{authorizationExpiresAt:He.authorizationExpiresAt}:Y?.authorizationExpiresAt?{authorizationExpiresAt:Y.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:fe,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Ne=await it.json().catch(()=>null);if(Ne?.type==="paypal_redirect_required"){let He=Ne.threeDSecureToken,fn=Ne.paymentMethodId||i.id||"";if(!Le||!He){Ze("error"),M("PayPal authorization required but no token provided.");return}try{let gn=Pt?.getRawProvider();if(!gn){M("PayPal is not available.");return}let Ot={return_url:window.location.href};fn&&(Ot.payment_method=fn);let{error:Kr}=await gn.confirmPayment({clientSecret:He,confirmParams:Ot,redirect:"if_required"});if(Kr){Ze("error");let Vr=Kr.message??"PayPal payment failed.";M(Vr),St("paypal",Vr,{code:Kr.code})}}catch(gn){Ze("error"),M(gn instanceof Error?gn.message:"PayPal authorization failed.")}return}if(Ne?.type==="paypal_direct_required"){let He=Ne.orderId;if(!He){Ze("error"),M("PayPal retry required but no order id provided.");return}let fn=rr.current?.attempts??0;if(fn>=2){Ze("error"),M("PayPal payment could not be completed after multiple attempts."),St("paypal","paypal_direct_required retry limit exceeded");return}jo(!1),Ko("loading"),Rt({orderId:He,attempts:fn+1}),Ze(null);return}bl(it.status,Ne)||Kt(),Ze("error");let zn=Ne?.message??"Payment failed. Please try again.";M(zn),St(i.isPaypal?"paypal":"card",zn,{code:Ne?.code??Ne?.gatewayErrorCode,declineCode:Ne?.declineCode??Ne?.gatewayDeclineReason}),await new Promise(He=>setTimeout(He,1500))}catch(gt){Gi(gt)||Kt(),Ze("error"),M(gt instanceof Error?gt.message:"An unexpected error occurred"),await new Promise(it=>setTimeout(it,1500))}finally{k(!1),Ze(null),mn.current=!1}},[f,e,t,y,g,b,Le,Pt,Y,a,m,M,St,bt]),yn=he((i,_)=>{T?T(i):Xa(i,_)},[T,Xa]),Za=Ee(!1);lt(()=>{if(typeof window>"u"||Za.current)return;let i=new URLSearchParams(window.location.search),_=i.get("payment_intent"),z=i.get("payment_intent_client_secret"),Q=i.get("redirect_status");if(!_||!z)return;let L=it=>{let Ne=localStorage.getItem(it);if(!Ne)return null;try{return JSON.parse(Ne)}catch{return localStorage.removeItem(it),null}},fe=L(Bn)??L(zi),we;if(fe?.clientSecret){if(fe.clientSecret!==z)return;we={...fe.accountPatch?{accountPatch:fe.accountPatch}:{},...fe.sessionId?{sessionId:fe.sessionId}:{},...fe.nonce?{nonce:fe.nonce}:{}}}else if(fe?.sessionId&&fe.sessionId!==e)return;Za.current=!0,localStorage.removeItem(Bn),localStorage.removeItem(zi);let ft=new URL(window.location.href);ft.searchParams.delete("payment_intent"),ft.searchParams.delete("payment_intent_client_secret"),ft.searchParams.delete("redirect_status"),window.history.replaceState({},"",ft.toString());let Kt=fe?.paymentMethodType??fe?.tokenType??"card",gt="card";(async()=>{let it=Le?.getRawProvider();if(!it){let Ot="Payment is not available \u2014 please refresh and try again.";M(Ot),St(gt,Ot);return}if(Q==="failed"){let Ot="Payment was declined. Please try again.";M(Ot),St(gt,Ot);return}let{paymentIntent:Ne,error:zn}=await it.retrievePaymentIntent(z);if(zn){let Ot=zn.message??"Failed to retrieve payment status.";M(Ot),St(gt,Ot,{code:zn.code});return}let He=Ne?.status,fn=vo(He);if(!Ne||!fn){let Ot=He==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";M(Ot),St(gt,Ot,{code:He??"missing_payment_intent"});return}let gn=typeof Ne.payment_method=="string"?Ne.payment_method:Ne.payment_method?.id;yn({id:gn??fe?.paymentMethodId??fe?.tokenId??Ne.id,type:"card",threeDSecureActionResultTokenId:Ne.id,gateway:fe?.gateway??"stripe",paymentMethodType:Kt},we)})()},[e,yn,Le,M,St]);let Vo=he(i=>{i.preventDefault()},[]);if(!(Le!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ur=ce==="buttons",en=A?.variables,bs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ho=en?.colorBackground,vs=Ho&&!bs.has(Ho)?Ho:void 0,$r=c.cardInputBorder??(Ur?"#e5e7eb":"#A4A4FF"),Yo=en?.colorDanger??"#dc2626",ar=i=>ln&&i?Yo:$r,yo=(Zt.malformed||Zt.empty)&&(Yn||ln),Cs=yo?Yo:ar(ot.zip),Go=c.cardFormContainer?.backgroundColor??vs??(Ur?"white":"#EDEDFF"),qr=c.cardInputBackground??en?.colorBackground??"white",Wo=fr(Ce),Qa=fr(q),yr=c.nameInput,ei=c.cardInputFontSize??jl(yr?.fontSize)??en?.fontSizeBase??"16px",ti=typeof yr?.fontFamily=="string"?yr.fontFamily:en?.fontFamily??"Poppins, sans-serif",ni=li(yr?.fontWeight)??400,Ss=c.cardInputColor??(typeof yr?.color=="string"?yr.color:void 0)??en?.colorText??"#262833",ws=c.cardInputPlaceholderColor??"#9ca3af",wt=en?.borderRadius??"8px",ir=en?.borderRadius??c.cardButton?.borderRadius??wt,sr=en?.colorPrimary??"#4A49FF",ks=en?.colorPrimaryHover??Hr(sr,.12),Jo=en?.colorText??"#262833",ri={fontSize:ei,fontFamily:ti,fontWeight:ni,color:Ss,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Is={"--flopay-input-placeholder-color":ws,"--flopay-input-font-size":ei,"--flopay-input-font-family":ti,"--flopay-input-font-weight":String(ni)},jr=c.cardFormContainer??{},Xo=jr.padding??(Ur?"0":"1rem"),Zo=jr.borderRadius??wt,Es=dt&&rn?u(Qo,{capture:dt,html:rn.html,messageToken:rn.messageToken,expectedOrigin:rn.expectedOrigin,theme:K,onReady:()=>{if(!ne||typeof document>"u")return;let i=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};i();let _=0,z=window.setInterval(()=>{_+=1;let Q=document.activeElement;!!Q&&Q.tagName==="IFRAME"&&Q.id==="flopay_vault_form_iframe"?(i(),window.clearInterval(z)):_>=50&&window.clearInterval(z)},100)},onError:i=>M(i),onValidation:i=>{let _=ut.current;(_==="idle"||_==="validation-window")&&(M(i),i&&ut.current==="validation-window"&&(jt.current&&(clearTimeout(jt.current),jt.current=null),ut.current="idle",Ze(null)))}}):u("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),oi=xe("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&pn()},style:{backgroundColor:Go,borderRadius:Zo,...jr,padding:Xo,...Is,display:"flex",flexDirection:"column"},children:[u("style",{children:`
|
|
26
26
|
.flopay-shared-input::placeholder {
|
|
27
27
|
color: var(--flopay-input-placeholder-color);
|
|
28
28
|
opacity: 1;
|
|
@@ -30,13 +30,13 @@ ${G.join(`
|
|
|
30
30
|
font-family: var(--flopay-input-font-family);
|
|
31
31
|
font-weight: var(--flopay-input-font-weight);
|
|
32
32
|
}
|
|
33
|
-
`}),
|
|
34
|
-
`)}):null,
|
|
35
|
-
`)}):null,Xa=Se==="apm-expanding"||Se==="apm-form"||Se==="apm-collapsing",io=Se==="apm-expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:Se==="apm-collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,so=gt?{...Mo,paymentMethodTypes:[gt]}:null;if(be==="buttons"){let r=Se==="buttons"||Se==="expanding"||Se==="apm-expanding",M=Se==="expanding"||Se==="card"||Se==="collapsing",$=Ne===void 0?{boxSizing:"border-box",height:bo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},re=Se==="expanding"||Se==="apm-expanding"?`flopay-buttons-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Se==="collapsing"||Se==="apm-collapsing"?`flopay-buttons-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,U=Se==="expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:Se==="collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return ze("form",{onSubmit:Fo,className:v,style:{position:"relative"},children:[d(na,{}),bn&&d(wn,{status:bn,errorMessage:O,authorized:nn}),ze("div",{style:{display:"grid"},children:[ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!re?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!re?pl:{},...re?{animation:re,pointerEvents:"none"}:{}},children:[Ga("flopay-direct-paypal-gate-debug"),Ja("flopay-stripe-gate-debug"),xr&&$e&&ze(Pr,{children:[fe&&d("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."}),d(Po,{sessionId:e,nonce:t,billingApiUrl:m,email:x.email,clientId:$e.clientId,environment:$e.environment,currency:de.toUpperCase(),isSubscription:it,providerObjectType:$e.providerObjectType,onTokenizedBody:an,onComplete:i,onErrorChange:me,onDecline:l,onTechnicalFailure:sr,onButtonClick:ve,runBeforeButtonClick:pn,isProcessing:V,onLoadStateChange:Ao,onInitializationStateChange:Bo,session:ue??null,existingOrderId:fe?.orderId,debug:tt},fe?.orderId??"fresh")]}),Tr&&d(nr,{stripe:T,options:ka,children:d(Ri,{sessionId:e,nonce:t,email:x.email,billingApiUrl:m,onTokenizedBody:an,onErrorChange:me,isProcessing:V,onButtonClick:ve,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:pn,onLoadStateChange:_a,placeholderBorderRadius:Gn})}),Mr?d(nr,{stripe:C,options:Xr,children:d(Ii,{sessionId:e,nonce:t,email:x.email,billingApiUrl:m,intentKind:K>0?"payment":"setup",expressMethods:eo,onTokenizedBody:an,onErrorChange:me,onButtonClick:ve,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:pn,onLoadStateChange:Ta,placeholderBorderRadius:Gn})}):Da?d("div",{style:{height:bo,borderRadius:Gn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Ar&&d(Ei,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:m,paymentElementMethods:to,stripeInstance:C,paymentElementBaseOptions:Mo,onTokenizedBody:an,onErrorChange:me,onButtonClick:ve,onDecline:l,runBeforeButtonClick:pn,onLoadStateChange:Aa,isProcessing:V,submitButtonColor:Jn,submitButtonBorderRadius:ht,submitButtonStyle:o.submitButton,onExpandApm:Un,expandedApmMethod:gt,themeId:j,buttonAppearance:{backgroundColor:o.cardButton?.backgroundColor,borderColor:o.cardInputBorder,textColor:o.cardButton?.color,borderRadius:Gn}}),Ve&&d("button",{type:"button",onClick:async()=>{V||!(await pn("card")).proceed||(ve?.("card"),Yn())},disabled:V,style:{width:"100%",...$,...o.cardButton,...la({themeBundle:c,resolvedPrimaryColor:Jn,resolvedBorderRadius:ht,submitButtonStyle:o.submitButton,explicitPrimaryColor:Wt?.colorPrimary}),fontSize:o.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:V?"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:V?.6:1},onMouseEnter:we=>{!V&&(c||Wt?.colorPrimary)&&(we.currentTarget.style.backgroundColor=ys)},onMouseLeave:we=>{(c||Wt?.colorPrimary)&&(we.currentTarget.style.backgroundColor=Jn)},onMouseDown:we=>{we.currentTarget.style.transform="scale(0.985)"},onMouseUp:we=>{we.currentTarget.style.transform="scale(1)"},children:d(dr,{content:Ne})}),O&&Se==="buttons"&&d(mr,{margin:"0.25rem 0",styleOverride:o.errorBanner,children:O})]}),Ve&&M&&d("div",{style:{gridArea:"1 / 1",...U?{animation:U}:{},...Se==="collapsing"?{pointerEvents:"none"}:{}},children:Wa}),I&&Xa&>&&so&&C&&d("div",{style:{gridArea:"1 / 1",...io?{animation:io}:{},...Se==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:Oo,borderRadius:$o,...Lr,padding:Uo},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:zt,style:{display:"inline-flex",alignItems:"center",gap:zo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:o.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...o.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...o.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(ur,{content:f})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:o.titleFontSize??"1.05rem",color:No,paddingRight:80,...o.title},children:`Pay with ${br(gt)}`})]}),d(nr,{stripe:C,options:so,children:d(oa,{method:gt,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:m,onTokenizedBody:an,onErrorChange:me,onDecline:l,onCancel:zt,runBeforeButtonClick:pn,onButtonClick:ve,isProcessing:V,submitButtonColor:Jn,submitButtonBorderRadius:ht,submitButtonStyle:o.submitButton,errorText:O})},gt)]})})]})]})}return Xa&>&&so&&C&&I?ze("form",{onSubmit:Fo,className:v,style:{position:"relative"},children:[d(na,{}),bn&&d(wn,{status:bn,errorMessage:O,authorized:nn}),d("div",{style:{...io?{animation:io}:{},...Se==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:Oo,borderRadius:$o,...Lr,padding:Uo},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:zt,style:{display:"inline-flex",alignItems:"center",gap:zo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:o.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...o.backButton},"aria-label":"Back to payment methods",children:[d("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...o.backButtonIcon},children:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(ur,{content:f})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:o.titleFontSize??"1.05rem",color:No,paddingRight:80,...o.title},children:`Pay with ${br(gt)}`})]}),d(nr,{stripe:C,options:so,children:d(oa,{method:gt,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:m,onTokenizedBody:an,onErrorChange:me,onDecline:l,onCancel:zt,runBeforeButtonClick:pn,onButtonClick:ve,isProcessing:V,submitButtonColor:Jn,submitButtonBorderRadius:ht,submitButtonStyle:o.submitButton,errorText:O})},gt)]})})]}):ze("form",{onSubmit:Fo,className:v,style:{position:"relative"},children:[d(na,{}),bn&&d(wn,{status:bn,errorMessage:O,authorized:nn}),ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ga("flopay-direct-paypal-gate-debug-default"),Ja("flopay-stripe-gate-debug-default"),xr&&$e&&ze(Pr,{children:[fe&&d("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."}),d(Po,{sessionId:e,nonce:t,billingApiUrl:m,email:x.email,clientId:$e.clientId,environment:$e.environment,currency:de.toUpperCase(),isSubscription:it,providerObjectType:$e.providerObjectType,onTokenizedBody:an,onComplete:i,onErrorChange:me,onDecline:l,onTechnicalFailure:sr,onButtonClick:ve,runBeforeButtonClick:pn,isProcessing:V,onLoadStateChange:Ao,onInitializationStateChange:Bo,session:ue??null,existingOrderId:fe?.orderId,debug:tt},fe?.orderId??"fresh")]}),Tr&&d(nr,{stripe:T,options:ka,children:d(Ri,{sessionId:e,nonce:t,email:x.email,billingApiUrl:m,onTokenizedBody:an,onErrorChange:me,isProcessing:V,onButtonClick:ve,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:pn,onLoadStateChange:_a,placeholderBorderRadius:Gn})}),Mr&&d(nr,{stripe:C,options:Xr,children:d(Ii,{sessionId:e,nonce:t,email:x.email,billingApiUrl:m,intentKind:K>0?"payment":"setup",expressMethods:eo,onTokenizedBody:an,onErrorChange:me,onButtonClick:ve,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:pn,onLoadStateChange:Ta,placeholderBorderRadius:Gn})}),Ar&&d(Ei,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:m,paymentElementMethods:to,stripeInstance:C,paymentElementBaseOptions:Mo,onTokenizedBody:an,onErrorChange:me,onButtonClick:ve,onDecline:l,runBeforeButtonClick:pn,onLoadStateChange:Aa,isProcessing:V,submitButtonColor:Jn,submitButtonBorderRadius:ht,submitButtonStyle:o.submitButton,themeId:j,onExpandApm:Un,expandedApmMethod:gt,buttonAppearance:{backgroundColor:o.cardButton?.backgroundColor,borderColor:o.cardInputBorder,textColor:o.cardButton?.color,borderRadius:Gn}})]}),Ve&&(ss||is||ls)&&ze("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),d("span",{children:"or pay with card"}),d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ve&&Wa]})}import{loadFloPay as Fi,PaymentAPI as Li}from"@flopay/js";import{classifyPaymentRejection as vl,FloPayError as rt,isAuthorizationOnlySession as Cl,isSetupIntentClientSecret as Sl,normalizeCheckoutFailureOutcome as Di}from"@flopay/shared";var Hr="card";async function wl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:p}=await e.retrieveSetupIntent(t);return{error:p,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:s,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:s??null}}async function kl(e,t,n,s){if(s){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:p,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:p??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function ua(e,t){return Object.assign(e,{checkoutMethod:t})}function An(e,t){let n=e instanceof rt?e:new rt(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 Vr(e,t){try{return await e()}catch(n){throw An(n,t)}}function Oi(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 Rl(e){return e.status==="succeeded"||e.status==="declined"}async function zi(e){if(typeof document>"u"||typeof window>"u")throw new rt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,s=15e3,a=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let g=new AbortController,R=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",R);let v=window.setTimeout(()=>g.abort(),s);try{let A=await fetch(a,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!A.ok)return{status:"unknown"};let u=await A.json().catch(()=>null);return Il(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(v),e.signal?.removeEventListener("abort",R)}},p=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.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 b=document.createElement("iframe");b.setAttribute("title","Card authentication"),b.setAttribute("allow","payment"),b.tabIndex=0,b.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(";"),b.src=e.nextActionRedirectUrl,l.appendChild(b),document.body.appendChild(l),b.focus();let z=null;try{z=new URL(e.billingApiUrl,window.location.href).origin}catch{z=null}try{let g=await new Promise((R,v)=>{let A=!1,u=0,h=0,w=0,I=!1,y=()=>{window.clearTimeout(u),window.clearInterval(h),window.clearTimeout(w),window.removeEventListener("message",be),b.removeEventListener("load",F),e.signal?.removeEventListener("abort",te)},he=async()=>{if(!(A||I)){I=!0;try{let j=await i();if(A||!Rl(j))return;A=!0,y(),R(j)}finally{I=!1}}},F=()=>{window.clearTimeout(w),w=window.setTimeout(()=>{he()},250)},te=()=>{A||(A=!0,y(),v(new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},be=j=>{if(j.source!==b.contentWindow||z&&j.origin!==z)return;let q=j.data;!q||typeof q!="object"||q.source!=="flopay-vault-3ds-return"||A||(A=!0,y(),R(null))};u=window.setTimeout(()=>{A||(A=!0,y(),v(new rt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),h=window.setInterval(()=>{he()},n),b.addEventListener("load",F),window.addEventListener("message",be),e.signal?.addEventListener("abort",te),e.signal?.aborted&&te()});return g||await i()}finally{l.parentNode?.removeChild(l),p?.isConnected&&p.focus()}}function Il(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 Kn(e,t="Payment failed. Please try again.",n){let s=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=$n(a)??a;return ua(new rt(i,"api_error",{code:Di(e?.outcome)??Di(e?.type)??e?.gatewayErrorCode}),s)}function da(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Co(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function El(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 Ni(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||Co(a)))return a;let s=e?.data;if(s&&typeof s=="object"){let a=s,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Co(l)))return l;let p=a.gateways;if(p&&typeof p=="object"){let l=p.stripe;if(l&&typeof l=="object"){let b=l,z=[b.stripeClientSecret,b.clientSecret];for(let g of z)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Co(g)))return g}}}}async function _l({billingApiUrl:e,sessionId:t,nonce:n,responseJson:s}){let a=Ni(s,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let l=(await new Li(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Co(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function vr({billingApiUrl:e,sessionId:t,session:n,nonce:s,tokenizedData:a,returnUrl:i,telemetry:p}){let l=e.replace(/\/+$/,""),b=t??n.id,z=s??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",v=n.customer?.firstName??n.accountData?.firstName??"",A=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,h=n.customer?.zip??n.accountData?.zip??void 0,w=new Li(l,p===!1?{telemetry:!1}:void 0),I=await El(()=>w.processPayment(g,{sessionId:b,nonce:z,tokenizedData:a,accountData:{userId:g,email:R,firstName:v,lastName:A,country:u,zip:h},returnUrl:i??da(n)}));if(I.ok){let F=typeof I.json=="function"?await I.json().catch(()=>null):null;return Cl(n)||F?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof F?.paymentId=="string"?F.paymentId:n.paymentId,sessionId:typeof F?.sessionId=="string"?F.sessionId:b,authorizationExpiresAt:typeof F?.authorizationExpiresAt=="string"?F.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:$r(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:a?.threeDSecureActionResultTokenId,paymentMethodId:$r(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}}let y;try{y=await I.json()}catch{throw new rt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:I.status})}if(y?.type==="paypal_redirect_required"||y?.type==="3ds_required"){let F=Ni(y);if(!F)throw new rt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:I.status});return{type:y.type,threeDSecureToken:F,paymentMethodId:y.paymentMethodId}}if(y?.gatewayErrorCode==="authentication_required"){let F=await _l({billingApiUrl:l,sessionId:b,nonce:z,responseJson:y});if(F)return F;throw ua(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let he=new rt(y?.message??"Payment failed. Please try again.","api_error",{code:y?.code??y?.gatewayErrorCode,declineCode:y?.declineCode??y?.gatewayDeclineReason,statusCode:I.status});throw Object.assign(he,{telemetryOutcome:vl(I.status,y)})}async function So(e,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:i,session:p,returnUrl:l,telemetry:b}){let z=t?.getRawProvider();if(!z)throw An(new rt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!s||!e.threeDSecureToken)throw ua(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Sl(e.threeDSecureToken),R=null,v=e.paymentMethodId,A=await Vr(()=>wl(z,e.threeDSecureToken,g),"card");if(A){if(A.error)throw An(new rt(A.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:A.error.code}),"card");let h=A.intent;!v&&h?.payment_method&&(typeof h.payment_method=="string"?v=h.payment_method:"id"in h.payment_method&&(v=h.payment_method.id??void 0))}let u=v?await Vr(()=>kl(z,e.threeDSecureToken,{payment_method:v,return_url:l??da(p)??window.location.href},g),"card"):null;if(u){if(u.error)throw An(new rt(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");R=u.intent}else{let h=await Vr(()=>z.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(h.error)throw An(new rt(h.error.message??"3DS authentication failed.","api_error",{code:h.error.code}),"card");R=(g?h.setupIntent:h.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let h=await vr({billingApiUrl:a,sessionId:i,session:p,telemetry:b,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:l});return h.type==="success"?{...h.result,paymentIntentId:h.result.paymentIntentId??R.id,paymentMethodId:h.result.paymentMethodId??v}:So(h,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:i,session:p,returnUrl:l,telemetry:b})}throw An(new rt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw An(new rt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:v}=await Vr(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(v)throw An(new rt(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await Vr(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??da(p)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(R)throw An(new rt(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new rt("Unsupported payment redirect state.","api_error")}function rr(e){if(e instanceof rt){let s=$n(e.message);return s&&s!==e.message?Object.assign(new rt(s,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=$n(t)??t;return new rt(n,"api_error")}function wo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new rt("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 ko({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:s,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[p,l]=await Promise.all([Fi(e,{billingApiUrl:n,locale:s,telemetry:a}),i?Fi(t,{billingApiUrl:n,locale:s,telemetry:a}).catch(b=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",b),null)):Promise.resolve(null)]);return{flopay:p,paypalFlopay:t?i?l:p:null}}import{Fragment as En,jsx as ee,jsxs as _t}from"react/jsx-runtime";var Cr=44,ba="flopay_checkout_saved_payment_resume",_o=new Map,Io=new Map;function qi(e,t){t.settled&&t.consumers===0&&_o.get(e)===t&&_o.delete(e)}function Fl(e,t,n){let s=Io.get(e);if(s&&(!s.sdkGeneratedIdempotencyKey||!t||s.sdkGeneratedIdempotencyKey===t))return s.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};Io.set(e,i);let p=()=>{Io.get(e)===i&&Io.delete(e)};return a.then(p,p),a}function Yr(e){return new Promise(t=>setTimeout(t,e))}function Eo(e,t,n){let s=lo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Yi,enabled:t!==!1});return s.beginCheckout(n),s}function Wr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ma(e,t,n,s,a){let i=Eo(e,t,n);i.error({errorCode:s,stage:a,paymentMethodCategory:"unknown",...a==="session_read"?{requestCategory:"session_read"}:{}}),Wr(i)}function Dl(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 ha(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ya(e){return!e||e.data.stripe?.publishableKey?!1:!!ha(e)?.clientId}function Fn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Ll(){if(!Fn())return null;try{let e=window.sessionStorage.getItem(ba);return e?JSON.parse(e):null}catch{return null}}function Ki(e){if(Fn())try{window.sessionStorage.setItem(ba,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function fa(){if(Fn())try{window.sessionStorage.removeItem(ba)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var va=":idempotency-key";function Ol(e){if(!Fn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function Vi(e,t,n){if(Fn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(s){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",s)}}function Pa(e){if(Fn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function zl(e){if(Fn())try{return window.sessionStorage.getItem(e+va)??void 0}catch{return}}function Nl(e,t){if(Fn())try{window.sessionStorage.setItem(e+va,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Ul(e){if(Pa(e),!!Fn())try{window.sessionStorage.removeItem(e+va)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function $l(){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 s of t)e.searchParams.has(s)&&(e.searchParams.delete(s),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Hi(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 jl(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function ga(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ca({sessionId:e,nonce:t,createSession:n,billingApiUrl:s,telemetry:a,appearance:i,locale:p,loading:l,error:b,onComplete:z,onError:g,onDecline:R,onCountryChange:v,onZipChange:A,showPayPal:u=!0,showStripe:h=!0,enabledPaymentMethods:w,showApplePay:I=!0,showGooglePay:y=!0,debug:he=!1,layout:F,theme:te,buttonsTheme:be,buttonsStyles:j,cardButtonContent:q,cardBackButtonContent:oe,cardTitleContent:ie,showSecurityFooter:Ne,onButtonClick:f,onBeforeButtonClick:ae,enableAVS:Fe,cardFieldOrder:ve,cardPreFormSlot:Re,avsLayout:J,className:le,initialErrorMessage:De=null,children:se,checkoutMode:_e,confirmLabel:Ue,renderConfirmButton:xe,onSessionCompleted:H}){let P=Ml(s),Q=yn(()=>Wi(te),[te]),We=i??Q?.appearance,Le=n?"embedded_checkout":"standard_checkout",Z=se?"custom_layout":F==="buttons"?"buttons_layout":"default_layout",[_,ce]=bt(null),[K,de]=bt(null),et=Ut(null),[$e,it]=bt(null),ue=Ut(null),[G,tt]=bt(null),[Y,mt]=bt(e??""),je=e??Y,qe=n?"":je,[$t,nt]=bt(!0),[en,S]=bt(null),[pe,Je]=bt("full"),[Xe,xt]=bt(!1),[yt,Te]=bt(De),[ft,Ie]=bt(null),[tn,Ke]=bt(null),[Dn,Jt]=bt(!1),[fn,Ln]=bt(void 0),[On,jt]=bt(""),[dt,ln]=bt(!1),[qt,Kt]=bt(!1),Vt=Ut(0),[Bt,X]=bt("loading"),[zn,nn]=bt(0),Xt=Ut(!1),Hn=Ut(!1),B=Ut(!1),ot=Ut(null),He=yn(()=>({checkoutMode:_e??pe,layout:se?"unknown":F==="buttons"?"buttons":"embedded"}),[_e,se,pe,F]),Ve=Ut(z);Ve.current=z;let Ye=Ut(g);Ye.current=g;let _n=Ut(R);_n.current=R,Bn(()=>{At(K)?.setCheckoutContext(He),$e&&$e!==K&&At($e)?.setCheckoutContext(He)},[K,$e,He]);let Nn=Ut(H);Nn.current=H;let ar=or(k=>{X(k),!(k!=="exhausted"||B.current)&&(B.current=!0,Ye.current?.(new Et("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),gn=or(()=>{X("retrying"),nn(k=>k+1)},[]);Bn(()=>{X("loading"),nn(0),B.current=!1},[je]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Yi,checkout_type:Le,checkout_layout:Z,billing_api_url:P})},[Z,Le,P]);let at=yn(()=>n?Zt(n,!0):"",[n]),Ht=yn(()=>On===at?fn:void 0,[fn,On,at]),hn=yn(()=>n?Yo(n,Ht):void 0,[n,Ht]),Ct=_e??hn?.checkoutMode??"full",Lt=yn(()=>hn?{...hn,checkoutMode:Ct}:void 0,[hn,Ct]);Bn(()=>{Ln(void 0),jt(at)},[at]),Bn(()=>{Te(De)},[De]);let cn=or((k,D,L)=>{ut(()=>{_n.current?.(It(k,D,L))})},[ut]),rn=or(async(k,D)=>{Te(null),Ke(null),Jt(!1),Ie("processing");let L=D?.sessionId??k.id,fe=et.current??ue.current,Ce=At(fe),W=fe?null:Eo(P,a,He),m={log:x=>{Ce?Ce.log(x):W?.log(x)},error:x=>{Ce?Ce.error(x):W?.error(x)},terminal:x=>{Ce?Ce.terminal(x):W?.terminal(x)},performance:x=>{Ce?Ce.performance(x):W?.performance(x)},now:()=>Ce?.now()??W?.now()??0,elapsed:x=>Ce?.elapsed(x)??Math.max(0,(W?.now()??x)-x)},O=m.now(),c=!!(D?.initialAutoProcessingError||D?.initialAutoProcessingPending),o=!1,E,ye=()=>{o||(o=!0,c=!0,E=m.now(),m.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Pe=!1,V=()=>{Pe||(Pe=!0,m.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),m.performance({stage:"processing",durationMs:m.elapsed(O),durationMode:"machine",paymentMethodCategory:"saved"}),E!==void 0&&m.performance({stage:"recovery",durationMs:m.elapsed(E),durationMode:"machine",paymentMethodCategory:"saved"}))};m.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),m.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),c&&ye();let Ge;try{let x=Oi(D?.initialAutoProcessingError),N;if(x)ye(),x.type==="paypal_redirect_required"&&ot.current?.publishableKey&&Ki({sessionId:L,publishableKey:ot.current.publishableKey,paypalPublishableKey:ot.current.paypalPublishableKey}),N=await So(x,{flopay:et.current,paypalFlopay:ue.current,attempt3DS:D?.attempt3DS,billingApiUrl:P,sessionId:L,session:k,telemetry:!1}),x.type==="paypal_redirect_required"&&fa();else if(D?.initialAutoProcessingPending){let ne=(await new Ro(P,{telemetry:!1}).waitForCheckoutSessionCompletion(D.initialAutoProcessingPending.sessionId,{initialDelayMs:D.initialAutoProcessingPending.retryAfterMs})).data.session;if(!yr(ne))throw mo(ne);N=Zn(ne,L)}else{if(D?.initialAutoProcessingError)throw Kn(D.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.initialAutoProcessingError.checkoutMethod});if(D?.fromCreateSession)return D?.fallbackToFull&&(Je("full"),Hi("full")),!1;{let C=await vr({billingApiUrl:P,sessionId:L,session:k,telemetry:!1});C.type==="success"?N=C.result:(ye(),C.type==="paypal_redirect_required"&&ot.current?.publishableKey&&Ki({sessionId:L,publishableKey:ot.current.publishableKey,paypalPublishableKey:ot.current.paypalPublishableKey}),N=await So(C,{flopay:et.current,paypalFlopay:ue.current,attempt3DS:D?.attempt3DS,billingApiUrl:P,sessionId:L,session:k,telemetry:!1}),C.type==="paypal_redirect_required"&&fa())}}L&&fr(L),V(),c&&(m.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),m.terminal({outcome:N.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Jt(N.status==="authorized"),Ie("success"),await Yr(xn),Ge=()=>Ve.current?.(N)}catch(x){let N=rr(x),C=N.checkoutMethod??Hr;Te(N.message),Ke(N.message),Jt(!1),D?.fallbackToFull&&(m.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Je("full"),Hi("full")),V();let T=N.statusCode!==void 0?Bl(N.statusCode,"unknown"):void 0,ne=T==="4xx"?{requestCategory:"process_payment",statusClass:T}:{},vt=T===void 0||T==="4xx";if(vt&&(N.telemetryOutcome==="payment_declined"||!!(N.declineCode||N.code?.toLowerCase().includes("declin"))))m.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ne});else if(vt&&(N.telemetryOutcome==="validation_rejected"||N.type==="validation_error"))m.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ne});else{let Xr=Ui(x,c?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");m.error({...Xr,...N.telemetryFailureCategory?{failureCategory:N.telemetryFailureCategory}:{},stage:c?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:N.telemetryRequestCategory??"process_payment"})}return ut(()=>Ye.current?.(N)),cn(C,N,{code:N.code,declineCode:N.declineCode}),Ie("error"),await Promise.allSettled([Yr(Sn),D?.ensureProvidersReady?D.ensureProvidersReady():Promise.resolve()]),c&&(m.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{V(),W&&Wr(W),Ie(null),Ke(null)}return ut(Ge),!0},[cn,ut,rr,P,a,He]);Bn(()=>{if(typeof window>"u"||Hn.current)return;let k=new URLSearchParams(window.location.search),D=k.get("payment_intent_client_secret");if(!D)return;let L=Ll();L&&(Hn.current=!0,(async()=>{let fe,Ce=0;Te(null),Ke(null),Ie("processing"),xt(!0);try{if(k.get("redirect_status")==="failed")throw Object.assign(new Et("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:W,paypalFlopay:m}=await ko({publishableKey:L.publishableKey,paypalPublishableKey:L.paypalPublishableKey,billingApiUrl:P,locale:p,telemetry:a});fe=At(m??W),Ce=fe?.now()??0,fe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let O=(m??W)?.getRawProvider();if(!O)throw Object.assign(new Et("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:c,error:o}=await O.retrievePaymentIntent(D);if(o)throw Object.assign(new Et(o.message??"Failed to retrieve PayPal payment status.","api_error",{code:o.code}),{checkoutMethod:"paypal"});let E=li(c?.status);if(!c||E==="failed")throw Object.assign(new Et("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let ye=typeof c.payment_method=="string"?c.payment_method:c.payment_method?.id,Pe=E;if(L.sessionId){let x=(await new Ro(P,{telemetry:!1}).getUnifiedCheckoutSession(L.sessionId)).data.session;if(x&&x.status!=="complete"){let N=await vr({billingApiUrl:P,sessionId:L.sessionId,session:x,telemetry:!1,tokenizedData:{id:ye??c.id,type:"card",threeDSecureActionResultTokenId:c.id,isPaypal:!0}});if(N.type!=="success")throw Object.assign(new Et("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Pe=N.result.status}}L.sessionId&&fr(L.sessionId),fe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.performance({stage:"redirect_resume",durationMs:fe.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),fe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ie("success"),await Yr(xn),ut(()=>Ve.current?.({status:Pe,paymentIntentId:c.id,paymentMethodId:ye,checkoutMethod:"paypal"}))}catch(W){let m=rr(W),O=m.checkoutMethod??"paypal",c=!!(m.declineCode||m.code?.toLowerCase().includes("declin"));if(fe)fe.performance({stage:"redirect_resume",durationMs:fe.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),c?fe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):fe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(c){let o=Eo(P,a,He);o.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Wr(o)}else ma(P,a,He,"REDIRECT_RESUME_FAILED","redirect_resume");Te(m.message),Ke(m.message),ut(()=>Ye.current?.(m)),cn(O,m,{code:m.code,declineCode:m.declineCode}),Ie("error"),await Yr(Sn)}finally{fa(),$l(),Ie(null),Ke(null),xt(!1)}})())},[cn,ut,p,rr,P,a]);let Qt=Ut(null);function Zt(k,D=!1){let L=k?.account?.email?.trim().toLowerCase()??"",fe={c:k?.clientId,cur:k?.currency??"",captureMethod:k?.captureMethod??"",a:{e:L,u:L?"":k?.account?.userId??"",country:k?.account?.country??""},successUrl:k?.successUrl,cancelUrl:k?.cancelUrl,p:k?.products?.map(m=>ga(`${m.type??""}:${m.code??m.providerItemId??m.providerPlanId??""}`,m)).sort(),i:k?.items?.map(m=>ga(m.code??m.providerItemId??"",m)).sort(),s:k?.subscriptions?.map(m=>ga(m.code??m.providerPlanId??"",m)).sort(),couponCodes:k?.couponCodes?[...k.couponCodes].sort():void 0,...D?{tagsData:k?.tagsData,utmMetadata:k?.utmMetadata,tokenizedData:k?.tokenizedData,checkoutMode:k?.checkoutMode??"full"}:{}},Ce=JSON.stringify(fe),W=0;for(let m=0;m<Ce.length;m++)W=(W<<5)-W+Ce.charCodeAt(m)|0;return`flopay_session_${Math.abs(W).toString(36)}`}let Ft=yn(()=>Lt?Zt(Lt):"",[Lt]),Se=Ut(Lt);Se.current=Lt,Bn(()=>{mt(e??"")},[e]),Bn(()=>{Xt.current=!1,Te(De),Ke(null),Jt(!1),Ie(null)},[Ft,De,e]);async function St(k,D){let L=Eo(P,a,He),fe=new Ro(P,{telemetry:!1}),Ce=!1;try{let W=k.idempotencyKey!==void 0?ji(k.idempotencyKey):void 0,m=W??zl(D),O,c=!1,o=Ol(D);L.log({name:o?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let E=o?.sid??null,ye=null,Pe;if(E)try{if(ye=await fe.getUnifiedCheckoutSession(E,o?.nonce),ye.data.session?.status==="complete"){if(Go(E))return{sid:E,result:ye};Ul(D),E=null,ye=null,c=!0}}catch{L.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Pa(D),E=null}if(!E){!W&&(c||!m)&&(m=ji(),O=m),m&&Nl(D,m);let V=L.now(),Ge=0;L.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let x={...k,idempotencyKey:m,avsCheck:!!Fe,avsConfig:typeof Fe=="object"?Fe:void 0,checkoutType:"embedded_checkout",checkoutLayout:se?"custom_layout":F==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(x,xl,{configurable:!1,enumerable:!1,value:{onAttempt:T=>{Ge=Math.max(Ge,T)}}});let N=()=>{L.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),L.performance({stage:"session_create",durationMs:L.now()-V,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx"})},C=T=>{let ne=Ui(T,"CHECKOUT_SESSION_CREATE_FAILED","unknown");L.performance({stage:"session_create",durationMs:L.now()-V,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:ne.statusClass}),T instanceof Et&&T.type==="validation_error"?L.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ne.statusClass==="4xx"?L.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):L.error({...ne,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(Tl(x)){let T=await fe.createDetachedSession(x);T.claimed.catch(()=>{}),ye=T.shell,E=T.sessionId,Pe=T.claimed.then(ne=>{let vt=ne.data.session?.id??T.sessionId;return vt&&Vi(D,vt,ne.data.session?.clientSecret??T.nonce),N(),ne},ne=>{throw Pa(D),C(ne),ne}).finally(()=>Wr(L)),Pe.catch(()=>{}),Ce=!0,L.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),L.performance({stage:"session_shell",durationMs:L.now()-V,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx",paymentMethodCategory:"card"})}else ye=await fe.createAndFetchSession(x),N()}catch(T){throw C(T),T}E=ye.data.session?.id??E??"",E&&!Pe&&Vi(D,E,ye.data.session?.clientSecret)}return{sid:E??"",result:ye,sdkGeneratedIdempotencyKey:O,...Pe?{claimed:Pe}:{}}}finally{Ce||Wr(L)}}let gt=or(async(k,D)=>{let L=Se.current;if(!L)throw new Et("createSession is required to bootstrap checkout.","validation_error");let fe=Yo(L,k),Ce=Zt(fe),W=_o.get(Ce);if(!W){let c={promise:St(fe,Ce),consumers:0,settled:!1};W=c,_o.set(Ce,c);let o=()=>{c.settled=!0,qi(Ce,c)};c.promise.then(o,o)}W.consumers+=1;let m=!1,O=()=>{m||(m=!0,W.consumers-=1,qi(Ce,W))};D?.(O);try{let c=await W.promise;Qt.current=Ce,k&&(jt(at),Ln(N=>ai(N,k)));let{sid:o,result:E,claimed:ye}=c;if(ce(E),E.data.session&&tt(E.data.session),o&&mt(o),ye){let N=Vt.current+=1;Kt(!0),ye.then(C=>{Vt.current===N&&(ce(C),C.data.session&&tt(C.data.session),Kt(!1))},C=>{Vt.current===N&&(Kt(!1),S(C instanceof Et?C:new Et(C instanceof Error?C.message:"Failed to create session","api_error")))})}else Vt.current+=1,Kt(!1);let{publishableKey:Pe,paypalPublishableKey:V}=wo(E),{flopay:Ge,paypalFlopay:x}=await ko({publishableKey:Pe,paypalPublishableKey:V,billingApiUrl:P,locale:p,telemetry:a});return et.current=Ge,de(Ge),ue.current=x,it(x),nt(!1),c}catch(c){throw Qt.current===Ce&&(Qt.current=null),c}finally{D||O()}},[p,P,a,He]),Pn=Ut(rn);Pn.current=rn;let ir=Ut(gt);ir.current=gt;let Ot=or(async k=>{if(!jl(k)||dt)return{sessionId:Y,session:G};ln(!0);try{let D=await gt(k);return{sessionId:D.sid,session:D.result.data.session??null}}finally{ln(!1)}},[gt,dt,Y,G]);Bn(()=>{let k=!1,D;if(S(null),Ft){let Ce=Se.current;return Je(Ct),nt(!1),Qt.current===Ft?()=>{k=!0}:(tt(ii(Ce,_e)),(async()=>{let W=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),m=Ct==="auto"&&!Xt.current&&!W;m&&(Te(null),Ke(null),Ie("processing"));try{let O=await ir.current(void 0,ye=>{D=ye}),c=O.result.data.session??null;ot.current=wo(O.result);let o=ya(O.result),E=Go(O.sid||c?.id);if(!k&&m&&c&&!o&&!E){Xt.current=!0,await Fl(Ft,O.sdkGeneratedIdempotencyKey,()=>Pn.current(c,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:O.result.autoProcessingError,initialAutoProcessingPending:O.result.autoProcessingPending,autoProcessingAttempted:O.result.autoProcessingAttempted,sessionId:O.sid||c.id}));return}!k&&m&&((o||E)&&(Xt.current=!0),Ie(null),Ke(null))}catch(O){if(k)return;let c=O instanceof Et||typeof O=="object"&&O!==null&&"code"in O?O.code:void 0;if(m&&c==="session_auto_completed"){Xt.current=!0,Ie("success"),await Yr(xn),k||(ut(()=>{Ve.current?.({status:"succeeded"})}),Ie(null),Ke(null));return}m&&(Ie(null),Ke(null));let o=O instanceof Et?O:new Et(O instanceof Error?O.message:"Failed to create session","api_error");S(o)}finally{D?.(),D=void 0}})(),()=>{k=!0,D?.()})}nt(!0);async function L(){let Ce=!1;try{let m=await new Ro(P,{telemetry:!1}).getUnifiedCheckoutSession(je,t);if(k)return;ce(m);let O=m.data.session??null;if(tt(O),!O)throw new Et("No session data returned","api_error");let c=O.checkoutMode;if(c==="setup")throw new Et("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(O.status==="authorized"){nt(!1),ut(()=>{Ve.current?.(Zn(O,je)),Nn.current?.(O.successUrl??"")});return}if(O.status==="complete"){nt(!1),ut(()=>{Nn.current?.(O.successUrl??"")});return}if(O.status==="expired")throw po(O);Ce=!0;let o=_e??c??"full";Je(o);let E=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ye=ya(m);if(o==="auto"&&!Xt.current&&!E&&!ye){Xt.current=!0;let Pe=fe(m);try{if(await Pn.current(O,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Pe,sessionId:je||O.id}),k)return;await Pe,k||nt(!1);return}catch{if(k)return;await Pe,k||nt(!1);return}}await fe(m),k||nt(!1)}catch(W){if(k)return;W instanceof Et?!Ce&&!Dl(W)&&ma(P,a,He,"NETWORK_REQUEST_FAILED","session_read"):ma(P,a,He,"INTERNAL_SDK_ERROR","checkout_mount");let m=W instanceof Et?W:new Et(W instanceof Error?W.message:"Failed to initialize checkout","api_error");S(m),nt(!1)}}async function fe(Ce){let{publishableKey:W,paypalPublishableKey:m}=wo(Ce);ot.current={publishableKey:W,paypalPublishableKey:m};let{flopay:O,paypalFlopay:c}=await ko({publishableKey:W,paypalPublishableKey:m,billingApiUrl:P,locale:p,telemetry:a});et.current=O,de(O),ue.current=c,it(c)}return L(),()=>{k=!0}},[_e,Ft,Ct,qe,ut,t]);let on=or(async()=>{if(!(Xe||!G)){xt(!0),Te(null);try{await rn(G,{attempt3DS:!0,fallbackToFull:!0,sessionId:je||G.id})}finally{xt(!1)}}},[je,Xe,rn,G]),Dt=ha(_),Yn=ya(_),dn=yn(()=>{if(!_||!G||!_.data.stripe?.publishableKey)return;let k={appearance:We,paymentMethodCreation:"manual",billingApiUrl:P};if(_.data.stripe?.clientSecret)k.clientSecret=_.data.stripe.clientSecret;else{let D=$i(G).total;k.amount=Math.round(D*100)||G.amount,k.currency=G.currency?.toLowerCase()}return k},[_,G,We,P]),Un=!!(n&&!se&&F==="buttons"&&ae&&Ct==="full"),zt=yn(()=>({session:G,loading:$t,error:en,checkoutMode:pe,inlineSessionDraft:Lt,applyInlineSessionPatch:Un?Ot:void 0,inlineSessionPatchProcessing:dt,claimPending:qt}),[G,$t,en,pe,Lt,Un,Ot,dt,qt]),bn=!!n&&F==="buttons"&&!Yn&&(!K||!dn),Me=ft?ee(wn,{status:ft,errorMessage:tn,authorized:Dn}):null;if($t){if(l)return _t(En,{children:[l,Me]});if(F==="buttons"){let k=Q?.buttonsLayout?.cardButton?.borderRadius??Q?.appearance.variables?.borderRadius??8,D=L=>ee("div",{style:{height:L,borderRadius:k,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return _t(En,{children:[_t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[u&&D(Cr),h&&(I||y)&&D(Cr),h&&D(Cr),ee("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Me]})}return _t(En,{children:[_t("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ee("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ee("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Me]})}return en?b?ee(mn.Provider,{value:zt,children:b(en)}):ee(mn.Provider,{value:zt,children:ee("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:en.message})}):bn?_t(En,{children:[ee(mn.Provider,{value:zt,children:ee(Kl,{onButtonClick:f,showPayPal:u,showStripe:h,showApplePay:I,showGooglePay:y,theme:te,buttonsTheme:be,buttonsStyles:j,cardButtonContent:q,cardBackButtonContent:oe,cardTitleContent:ie})}),Me]}):Yn&&G&&Dt?_t(En,{children:[ee(mn.Provider,{value:zt,children:_t("div",{className:le,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[yt&&ee(mr,{icon:!1,children:yt}),Bt==="retrying"&&ee("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Bt==="exhausted"&&_t("div",{role:"alert",children:[ee("div",{children:"PayPal is temporarily unavailable. Please try again."}),ee("button",{type:"button",onClick:gn,children:"Retry PayPal"})]}),Bt!=="exhausted"&&ee("div",{"aria-hidden":Bt==="retrying"?!0:void 0,style:Bt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ee(fi,{sessionId:je,nonce:G.clientSecret||void 0,billingApiUrl:P,email:G.customer?.email,clientId:Dt.clientId,environment:Dt.environment,currency:(G.currency??"usd").toUpperCase(),isSubscription:G.mode==="subscription",providerObjectType:Dt.providerObjectType,onComplete:z,onErrorChange:Te,onDecline:R,onButtonClick:f,onInitializationStateChange:ar,allowAutomaticRetry:zn===0,session:G,telemetry:a,telemetryContext:He,debug:he},`paypal-init-${zn}`)})]})}),Me]}):!K||!dn?ee(En,{children:Me}):pe==="confirm"?_t(En,{children:[ee(mn.Provider,{value:zt,children:ee(co,{flopay:K,paypalFlopay:$e,options:dn,children:_t("div",{className:le,children:[yt&&ee("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:yt}),xe?xe({onConfirm:on,isProcessing:Xe}):ee("button",{type:"button",onClick:on,disabled:Xe,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Xe?"not-allowed":"pointer",opacity:Xe?.6:1},children:Xe?"Processing...":Ue??"Confirm Purchase"})]})})}),Me]}):_t(En,{children:[ee(mn.Provider,{value:zt,children:ee(co,{flopay:K,paypalFlopay:$e,options:dn,children:se?_t(En,{children:[yt&&ee("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:yt}),ee(ql,{sessionId:je,nonce:G?.clientSecret||void 0,billingApiUrl:P,session:G,children:se})]}):ee(ca,{sessionId:je,nonce:G?.clientSecret||void 0,email:G?.customer?.email,userId:G?.customer?.id,firstName:G?.customer?.firstName,lastName:G?.customer?.lastName,totalAmount:G?Math.round($i(G).total*100):0,currency:G?.currency?.toLowerCase()??"usd",onComplete:z,onError:g,onDecline:R,error:yt,onErrorChange:Te,showPayPal:u,showStripe:h,enabledPaymentMethods:w??_?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:_?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:y,layout:F,theme:te,buttonsTheme:be,buttonsStyles:j,appearance:We,cardButtonContent:q,cardBackButtonContent:oe,cardTitleContent:ie,onButtonClick:f,onBeforeButtonClick:ae,enableAVS:Fe,...ve?{cardFieldOrder:ve}:{},...Re?{cardPreFormSlot:Re}:{},avsLayout:J,country:G?.customer?.country,city:G?.customer?.city,state:G?.customer?.state,onCountryChange:v,onZipChange:A,avsCheck:!!Fe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:se?"custom_layout":F==="buttons"?"buttons_layout":"default_layout",className:le,directPaypal:ha(_),isSubscription:G?.mode==="subscription",session:G,dataAttachmentPending:qt,debug:he})})}),Me]})}function ql({sessionId:e,nonce:t,billingApiUrl:n,session:s,children:a}){return ee(En,{children:pa.Children.map(a,i=>{if(!pa.isValidElement(i))return i;let p=i.props,l={};return p.sessionId||(l.sessionId=e),!p.nonce&&t&&(l.nonce=t),p.billingApiUrl||(l.billingApiUrl=n),s?.customer&&(p.email||(l.email=s.customer.email),p.userId||(l.userId=s.customer.id),p.firstName||(l.firstName=s.customer.firstName),p.lastName||(l.lastName=s.customer.lastName)),Object.keys(l).length===0?i:pa.cloneElement(i,l)})})}function Kl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:s,showGooglePay:a,theme:i,buttonsTheme:p,buttonsStyles:l,cardButtonContent:b,cardBackButtonContent:z,cardTitleContent:g}){let[R,v]=bt(!1),A=yn(()=>Wi(i),[i]),u=yn(()=>{let y=A?.buttonsLayout??Al(p);return l?{...y,...l,cardButton:{...y.cardButton,...l.cardButton},cardFormContainer:{...y.cardFormContainer,...l.cardFormContainer},backButton:{...y.backButton,...l.backButton},backButtonIcon:{...y.backButtonIcon,...l.backButtonIcon},submitButton:{...y.submitButton,...l.submitButton},title:{...y.title,...l.title}}:y},[A,p,l]),h=A?.buttonsLayout?.cardButton?.borderRadius??A?.appearance.variables?.borderRadius??8,w=y=>ee("div",{style:{height:y,borderRadius:h,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),I=b===void 0?{boxSizing:"border-box",height:Cr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let y=u.cardInputBorder??"#e5e7eb",he=u.cardInputBackground??"white",F=cr(z),te=cr(g);return _t("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:[_t("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[_t("button",{type:"button",onClick:()=>v(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:F?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:[ee("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:ee("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ee("path",{d:"M15 18l-6-6 6-6"})})}),ee(ur,{content:z})]}),te?ee("div",{style:{flex:1}}):ee("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:ee(Nr,{content:g})})]}),ee("div",{style:{backgroundColor:he,border:`1px solid ${y}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ee("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),_t("div",{style:{display:"flex"},children:[ee("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${y}`,borderLeft:`1px solid ${y}`,borderBottomLeftRadius:8,padding:12,height:45},children:ee("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ee("div",{style:{flex:1,backgroundColor:he,borderTop:"none",borderRight:`1px solid ${y}`,borderBottom:`1px solid ${y}`,borderLeft:`1px solid ${y}`,borderBottomRightRadius:8,padding:12,height:45},children:ee("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ee("div",{style:{backgroundColor:he,border:`1px solid ${y}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ee("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ee("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...u.submitButton,opacity:.5}}),ee("style",{children:`
|
|
33
|
+
`}),Ur&&un&&xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Pe?-2:0},children:[xe("button",{type:"button",onClick:On,style:{display:"inline-flex",alignItems:"center",gap:Wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:c.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...c.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...c.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(hr,{content:Ce})]}),Qa?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...c.title},children:u(Yr,{content:q})})]}),!Ur&&!Qa&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Jo,order:Pe?-3:0,...c.title},children:u(Yr,{content:q})}),ne&&u("div",{style:{order:Pe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Fe,_=(L=!1)=>({backgroundColor:qr,border:`1px solid ${ar(L)}`,borderRadius:wt,marginTop:"0.5rem",padding:"10px"}),z=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ri}),Q=Sl(i);return xe(Er,{children:[Te(ne.address_line_1,i)&&u("div",{style:_(ot.line1),children:u("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:vt,onChange:L=>{Ut.current.addressLine1=!0,Ke.current=L.target.value,Je(L.target.value)},disabled:C,required:!0,"data-testid":"flopay-address-line1",style:z()})}),Te(ne.address_line_2,i)&&u("div",{style:_(),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Lt,onChange:L=>{Ut.current.addressLine2=!0,Rn.current=L.target.value,je(L.target.value)},disabled:C,"data-testid":"flopay-address-line2",style:z()})}),(Te(ne.city,i)||Te(ne.state,i))&&xe("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Te(ne.city,i)&&u("div",{style:{flex:1,backgroundColor:qr,borderTop:`1px solid ${ar(ot.city)}`,borderRight:`1px solid ${ar(ot.city)}`,borderBottom:`1px solid ${ar(ot.city)}`,borderLeft:`1px solid ${ar(ot.city)}`,padding:"10px",borderTopLeftRadius:wt,borderBottomLeftRadius:wt,...Te(ne.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:wt}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ht,onChange:L=>{Ut.current.city=!0,ct.current=L.target.value,Et(L.target.value)},disabled:C,required:!0,"data-testid":"flopay-city",style:z()})}),Te(ne.state,i)&&u("div",{style:{flex:1,backgroundColor:qr,border:`1px solid ${ar(ot.state)}`,padding:"10px",borderTopRightRadius:wt,borderBottomRightRadius:wt,...Te(ne.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:wt}},children:Q?xe("select",{id:"flopay-billing-state",name:"billing-state",value:nn,onChange:L=>{Ut.current.state=!0,vn.current=L.target.value,Nt(L.target.value)},disabled:C,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...z(),cursor:"pointer"},children:[u("option",{value:"",children:Li(i)}),Q.map(L=>u("option",{value:L.code,children:L.name},L.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Li(i),autoComplete:"billing address-level1",value:nn,onChange:L=>{Ut.current.state=!0,vn.current=L.target.value,Nt(L.target.value)},disabled:C,required:!0,"data-testid":"flopay-state",style:z()})})]}),(Te(ne.country,i)||Te(ne.postal_code,i))&&xe("div",{style:{display:"flex",flexDirection:ae==="column"?"column":"row",gap:ae==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Te(ne.country,i)&&u("div",{style:{flex:ae==="row"?1:void 0,backgroundColor:qr,borderTop:`1px solid ${$r}`,borderRight:`1px solid ${$r}`,borderBottom:`1px solid ${$r}`,borderLeft:`1px solid ${$r}`,padding:"10px",...ae==="row"&&Te(ne.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:wt,borderBottomLeftRadius:wt,borderRight:"none"}:{borderRadius:wt}},children:u("select",{id:"flopay-billing-country",name:"billing-country",value:Fe,onChange:L=>{Ut.current.country=!0,zt.current=L.target.value,Vt(L.target.value),oe?.(L.target.value),vn.current="",Nt("")},disabled:C,autoComplete:"billing country","data-testid":"flopay-country",style:{...z(),cursor:"pointer"},children:Pl.map(L=>xe("option",{value:L.code,children:[L.flag," ",L.name]},L.code))})}),Te(ne.postal_code,i)&&u("div",{style:{flex:ae==="row"?1:void 0,backgroundColor:qr,border:`1px solid ${Cs}`,padding:"10px",...ae==="row"&&Te(ne.country,i)?{borderRadius:"0",borderTopRightRadius:wt,borderBottomRightRadius:wt}:{borderRadius:wt}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:ya(Fe),autoComplete:"billing postal-code",value:Xt,onChange:L=>{Ut.current.zip=!0,rt.current=L.target.value,Ge(L.target.value),qe?.(L.target.value)},onBlur:()=>Sn(!0),disabled:C,required:Zt.required,"aria-invalid":yo||void 0,"aria-describedby":yo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:z()})})]}),yo&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Yo,...ri,fontSize:"0.75rem"},children:Zt.empty?`${ya(i)} is required`:$l(i)})]})})()}),Pe&&de&&u("div",{style:{order:-2,width:"100%"},children:de}),Pe&&Es,l&&u(wr,{margin:"0.75rem 0",styleOverride:c.errorBanner,children:l})]}),fo={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"},ai=i=>D?!ee||!an?u("pre",{"data-testid":i,style:fo,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":i,style:fo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ee}`,` directPaypalConfigured=${an}`,` inAppBrowserDetected=${String(po)}`,` shouldRenderDirectPayPal=${Lr}`,` shouldRenderStripePayPal=${Or}`,` hasPaypalStripeInstance=${!!G}`].join(`
|
|
34
|
+
`)}):null,ii=i=>D?!W||!E?u("pre",{"data-testid":i,style:fo,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":i,style:fo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${W}`,` currency=${$}`,` amountInCents=${ie}`,` enabledPaymentMethods: ${JSON.stringify(v??[])}`,` enabledPaymentMethodsProvided=${Fr}`,` hasEnabledMethods=${so}`,` expressMethods: ${JSON.stringify(lo)}`,` walletExpressMethods: ${JSON.stringify(co)}`,` paymentElementMethods: ${JSON.stringify(Dr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(uo)}`,` hasStripeInstance=${!!E}`,` shouldRenderWallets=${Nr}`,` shouldRenderPaymentElement=${zr}`].join(`
|
|
35
|
+
`)}):null,si=me==="apm-expanding"||me==="apm-form"||me==="apm-collapsing",go=me==="apm-expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:me==="apm-collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,ho=at?{...qo,paymentMethodTypes:[at]}:null;if(ce==="buttons"){let i=me==="buttons"||me==="expanding"||me==="apm-expanding",_=me==="expanding"||me==="card"||me==="collapsing",z=Ae===void 0?{boxSizing:"border-box",height:Fo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Q=me==="expanding"||me==="apm-expanding"?`flopay-buttons-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:me==="collapsing"||me==="apm-collapsing"?`flopay-buttons-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,L=me==="expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:me==="collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return xe("form",{onSubmit:Vo,className:x,style:{position:"relative"},children:[u(ma,{}),qt&&u(Mn,{status:qt,errorMessage:l,authorized:_n}),xe("div",{style:{display:"grid"},children:[xe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Q?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Q?Nl:{},...Q?{animation:Q,pointerEvents:"none"}:{}},children:[ai("flopay-direct-paypal-gate-debug"),ii("flopay-stripe-gate-debug"),Lr&&Ie&&xe(Er,{children:[Qt&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(Ro,{sessionId:e,nonce:t,billingApiUrl:pt,email:y.email,clientId:Ie.clientId,environment:Ie.environment,currency:$.toUpperCase(),isSubscription:We,providerObjectType:Ie.providerObjectType,onTokenizedBody:yn,onComplete:a,onErrorChange:M,onDecline:d,onTechnicalFailure:$e,onButtonClick:te,runBeforeButtonClick:wn,isProcessing:C,onLoadStateChange:jo,onInitializationStateChange:Ko,session:Y??null,existingOrderId:Qt?.orderId,debug:D},Qt?.orderId??"fresh")]}),Or&&u(pr,{stripe:G,options:ve,children:u(Ki,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,onTokenizedBody:yn,onErrorChange:M,isProcessing:C,onButtonClick:te,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:wn,onLoadStateChange:Na,placeholderBorderRadius:ir})}),Nr?u(pr,{stripe:E,options:be,children:u(Vi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,intentKind:H>0?"payment":"setup",expressMethods:co,onTokenizedBody:yn,onErrorChange:M,onButtonClick:te,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:wn,onLoadStateChange:Ua,placeholderBorderRadius:ir})}):Va?u("div",{style:{height:Fo,borderRadius:ir,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,zr&&u(Hi,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,paymentElementMethods:uo,stripeInstance:E,paymentElementBaseOptions:qo,onTokenizedBody:yn,onErrorChange:M,onButtonClick:te,onDecline:d,runBeforeButtonClick:wn,onLoadStateChange:qa,isProcessing:C,submitButtonColor:sr,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,onExpandApm:An,expandedApmMethod:at,themeId:Se,buttonAppearance:{backgroundColor:c.cardButton?.backgroundColor,borderColor:c.cardInputBorder,textColor:c.cardButton?.color,borderRadius:ir}}),Pe&&u("button",{type:"button",onClick:async()=>{C||!(await wn("card")).proceed||(te?.("card"),Gn())},disabled:C,style:{width:"100%",...z,...c.cardButton,...ba({themeBundle:s,resolvedPrimaryColor:sr,resolvedBorderRadius:wt,submitButtonStyle:c.submitButton,explicitPrimaryColor:en?.colorPrimary}),fontSize:c.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:C?"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:C?.6:1},onMouseEnter:fe=>{!C&&(s||en?.colorPrimary)&&(fe.currentTarget.style.backgroundColor=ks)},onMouseLeave:fe=>{(s||en?.colorPrimary)&&(fe.currentTarget.style.backgroundColor=sr)},onMouseDown:fe=>{fe.currentTarget.style.transform="scale(0.985)"},onMouseUp:fe=>{fe.currentTarget.style.transform="scale(1)"},children:u(gr,{content:Ae})}),l&&me==="buttons"&&u(wr,{margin:"0.25rem 0",styleOverride:c.errorBanner,children:l})]}),Pe&&_&&u("div",{style:{gridArea:"1 / 1",...L?{animation:L}:{},...me==="collapsing"?{pointerEvents:"none"}:{}},children:oi}),W&&si&&at&&ho&&E&&u("div",{style:{gridArea:"1 / 1",...go?{animation:go}:{},...me==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:Go,borderRadius:Zo,...jr,padding:Xo},children:[xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[xe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:Wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:c.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...c.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...c.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(hr,{content:Ce})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:Jo,paddingRight:80,...c.title},children:`Pay with ${Rr(at)}`})]}),u(pr,{stripe:E,options:ho,children:u(fa,{method:at,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,onTokenizedBody:yn,onErrorChange:M,onDecline:d,onCancel:Nn,runBeforeButtonClick:wn,onButtonClick:te,isProcessing:C,submitButtonColor:sr,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,errorText:l})},at)]})})]})]})}return si&&at&&ho&&E&&W?xe("form",{onSubmit:Vo,className:x,style:{position:"relative"},children:[u(ma,{}),qt&&u(Mn,{status:qt,errorMessage:l,authorized:_n}),u("div",{style:{...go?{animation:go}:{},...me==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:Go,borderRadius:Zo,...jr,padding:Xo},children:[xe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[xe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Nn,style:{display:"inline-flex",alignItems:"center",gap:Wo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:c.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...c.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...c.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(hr,{content:Ce})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:c.titleFontSize??"1.05rem",color:Jo,paddingRight:80,...c.title},children:`Pay with ${Rr(at)}`})]}),u(pr,{stripe:E,options:ho,children:u(fa,{method:at,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,onTokenizedBody:yn,onErrorChange:M,onDecline:d,onCancel:Nn,runBeforeButtonClick:wn,onButtonClick:te,isProcessing:C,submitButtonColor:sr,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,errorText:l})},at)]})})]}):xe("form",{onSubmit:Vo,className:x,style:{position:"relative"},children:[u(ma,{}),qt&&u(Mn,{status:qt,errorMessage:l,authorized:_n}),xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ai("flopay-direct-paypal-gate-debug-default"),ii("flopay-stripe-gate-debug-default"),Lr&&Ie&&xe(Er,{children:[Qt&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(Ro,{sessionId:e,nonce:t,billingApiUrl:pt,email:y.email,clientId:Ie.clientId,environment:Ie.environment,currency:$.toUpperCase(),isSubscription:We,providerObjectType:Ie.providerObjectType,onTokenizedBody:yn,onComplete:a,onErrorChange:M,onDecline:d,onTechnicalFailure:$e,onButtonClick:te,runBeforeButtonClick:wn,isProcessing:C,onLoadStateChange:jo,onInitializationStateChange:Ko,session:Y??null,existingOrderId:Qt?.orderId,debug:D},Qt?.orderId??"fresh")]}),Or&&u(pr,{stripe:G,options:ve,children:u(Ki,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,onTokenizedBody:yn,onErrorChange:M,isProcessing:C,onButtonClick:te,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:wn,onLoadStateChange:Na,placeholderBorderRadius:ir})}),Nr&&u(pr,{stripe:E,options:be,children:u(Vi,{sessionId:e,nonce:t,email:y.email,billingApiUrl:pt,intentKind:H>0?"payment":"setup",expressMethods:co,onTokenizedBody:yn,onErrorChange:M,onButtonClick:te,onDecline:d,onTechnicalFailure:$e,runBeforeButtonClick:wn,onLoadStateChange:Ua,placeholderBorderRadius:ir})}),zr&&u(Hi,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pt,paymentElementMethods:uo,stripeInstance:E,paymentElementBaseOptions:qo,onTokenizedBody:yn,onErrorChange:M,onButtonClick:te,onDecline:d,runBeforeButtonClick:wn,onLoadStateChange:qa,isProcessing:C,submitButtonColor:sr,submitButtonBorderRadius:wt,submitButtonStyle:c.submitButton,themeId:Se,onExpandApm:An,expandedApmMethod:at,buttonAppearance:{backgroundColor:c.cardButton?.backgroundColor,borderColor:c.cardInputBorder,textColor:c.cardButton?.color,borderRadius:ir}})]}),Pe&&(hs||gs||Ps)&&xe("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),u("span",{children:"or pay with card"}),u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Pe&&oi]})}import{Fragment as Dn,jsx as X,jsxs as Dt}from"react/jsx-runtime";var Tr=44,Aa="flopay_checkout_saved_payment_resume",Uo=new Map,No=new Map;function ns(e,t){t.settled&&t.consumers===0&&Uo.get(e)===t&&Uo.delete(e)}function ec(e,t,n){let r=No.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};No.set(e,a);let m=()=>{No.get(e)===a&&No.delete(e)};return o.then(m,m),o}function to(e){return new Promise(t=>setTimeout(t,e))}function zo(e,t,n){let r=ko({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:is,enabled:t!==!1});return r.beginCheckout(n),r}function no(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Sa(e,t,n,r,o){let a=zo(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),no(a)}function tc(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 Ta(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function wa(e){return!e||e.data.stripe?.publishableKey?!1:!!Ta(e)?.clientId}function Kn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function nc(){if(!Kn())return null;try{let e=window.sessionStorage.getItem(Aa);return e?JSON.parse(e):null}catch{return null}}function rs(e){if(Kn())try{window.sessionStorage.setItem(Aa,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ka(){if(Kn())try{window.sessionStorage.removeItem(Aa)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Ma=":idempotency-key";function ss(e,t){if(!Kn())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 Ia(e,t,n,r){if(Kn())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 xa(e,t){if(Kn())try{ss(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ls(e,t){if(!Kn())return null;try{let n=window.sessionStorage.getItem(e+Ma);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 Ea(e,t,n){if(Kn())try{window.sessionStorage.setItem(e+Ma,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Ra(e,t){if(xa(e,t),!!Kn())try{ls(e,t)&&window.sessionStorage.removeItem(e+Ma)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function rc(){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 os(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 oc(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function _a(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ro(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=>_a(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>_a(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>_a(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function ac(e,t=!1){let n=ro(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 ic(e,t){if(!e?.customer||!e.products)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=Zl(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Gl(t.items,t.subscriptions)).map(h=>({type:h.type,code:h.code??h.providerItemId??h.providerPlanId??"",quantity:h.quantity??1,totalAmount:h.totalAmount,overrideAmount:h.overrideAmount??null,currency:(h.currency??o).toUpperCase()})).sort((h,P)=>`${h.code}:${h.type??""}`.localeCompare(`${P.code}:${P.type??""}`)),m=e.products.map(h=>({type:h.type,code:h.code??"",quantity:h.quantity??1,totalAmount:h.totalAmount,overrideAmount:h.overrideAmount??null,currency:(h.currency??e.currency).toUpperCase()})).sort((h,P)=>`${h.code}:${h.type??""}`.localeCompare(`${P.code}:${P.type??""}`));if(a.length!==m.length)return!1;for(let h=0;h<a.length;h+=1){let P=a[h],b=m[h];if(P.code!==b.code||P.type!==void 0&&P.type!==b.type||P.quantity!==b.quantity||P.totalAmount!==b.totalAmount||P.overrideAmount!==b.overrideAmount||P.currency!==b.currency)return!1}let d=[...t.couponCodes??[]].sort(),T=[...e.coupons??[]].sort();return d.length===T.length&&d.every((h,P)=>h===T[P])}function Ba({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:m,loading:d,error:T,onComplete:h,onError:P,onInstrument:b,onDecline:x,onCountryChange:U,onZipChange:p,showPayPal:S=!0,showStripe:ee=!0,enabledPaymentMethods:W,showApplePay:v=!0,showGooglePay:ye=!0,debug:j=!1,layout:J,theme:ce,buttonsTheme:Se,buttonsStyles:re,cardButtonContent:le,cardBackButtonContent:Ve,cardTitleContent:Ae,showSecurityFooter:Ce,onButtonClick:q,onBeforeButtonClick:B,enableAVS:te,cardFieldOrder:tt,cardPreFormSlot:Me,avsLayout:V,className:de,initialErrorMessage:ae=null,children:ue,checkoutMode:ke,confirmLabel:pe,renderConfirmButton:Re,onSessionCompleted:O}){let w=Jl(r),oe=bn(()=>as(ce),[ce]),qe=a??oe?.appearance,De=n?"embedded_checkout":"standard_checkout",Z=ue?"custom_layout":J==="buttons"?"buttons_layout":"default_layout",[R,H]=kt(null),[$,Be]=kt(null),Ie=_t(null),[We,Y]=kt(null),mt=_t(null),[D,Le]=kt(null),Pt=bn(()=>n?ro(n):"",[n]),N=n?`create:${Pt}`:`session:${e??""}`,bt=D?.gateways?.stripe?"stripe":D?.gateways?.paypal?"paypal":void 0,ze=_t(new Set),tn=_t(N),It=_t(N);So(()=>{It.current=N,tn.current!==N&&(tn.current=N,ze.current.clear())},[N]);let k=jn(l=>{if(It.current===N){if(ra.has(l.name)){if(ze.current.has(l.name))return;ze.current.add(l.name)}Qe(()=>b?.(l))}},[N,b]),se=Cr(k,N),yt=_t(!1),Fe=jn(l=>{if(yt.current)return;let s=l.gateway||!bt?l:{...l,gateway:bt};k(s)},[k,bt]);Fn(()=>{se({class:"lifecycle",name:"checkout.mount"})},[se]);let[Vt,Xt]=kt(e??""),Ge=e??Vt,vt=n?"":Ge,[Je,Lt]=kt(!0),[je,Ht]=kt(null),[Et,nn]=kt("full"),[Nt,En]=kt(!1),[sn,rt]=kt(ae),[zt,Ke]=kt(null),[Rn,ct]=kt(null),[vn,Ut]=kt(!1),[ne,Vn]=kt(void 0),[_n,Tn]=kt(""),[xn,mr]=kt(!1),[I,Xe]=kt(!1),Pe=_t(0),[Cn,Oe]=kt("loading"),[Hn,nr]=kt(0),Yt=_t(!1),dt=_t(!1),Zt=_t(!1),Gt=_t(null),ot=bn(()=>({checkoutMode:ke??Et,layout:ue?"unknown":J==="buttons"?"buttons":"embedded"}),[ke,ue,Et,J]),ln=_t(h);ln.current=h;let cn=_t(P);cn.current=P;let Yn=_t(x);Yn.current=x,Fn(()=>{Bt($)?.setCheckoutContext(ot),We&&We!==$&&Bt(We)?.setCheckoutContext(ot)},[$,We,ot]);let Sn=_t(O);Sn.current=O;let rn=jn(l=>{Oe(l),!(l!=="exhausted"||Zt.current)&&(Zt.current=!0,cn.current?.(new Ft("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),dn=jn(()=>{Oe("retrying"),nr(l=>l+1)},[]);Fn(()=>{Oe("loading"),nr(0),Zt.current=!1},[Ge]),Fn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:is,checkout_type:De,checkout_layout:Z,billing_api_url:w})},[Z,De,w]);let me=bn(()=>n?ro(n,!0):"",[n]),Ct=bn(()=>_n===me?ne:void 0,[ne,_n,me]),at=bn(()=>n?ea(n,Ct):void 0,[n,Ct]),on=ke??at?.checkoutMode??"full",un=bn(()=>at?{...at,checkoutMode:on}:void 0,[at,on]);Fn(()=>{Vn(void 0),Tn(me)},[me]),Fn(()=>{rt(ae)},[ae]);let Ln=jn((l,s,c)=>{Qe(()=>{Yn.current?.(Mt(l,s,c))})},[Qe]),pn=jn(async(l,s)=>{rt(null),ct(null),Ut(!1),Ke("processing");let c=s?.sessionId??l.id,A=l.gateways?.stripe?"stripe":l.gateways?.paypal?"paypal":void 0,K=Ie.current??mt.current,F=Bt(K),C=K?null:zo(w,o,ot),f={log:be=>{F?F.log(be):C?.log(be)},error:be=>{F?F.error(be):C?.error(be)},terminal:be=>{F?F.terminal(be):C?.terminal(be)},performance:be=>{F?F.performance(be):C?.performance(be)},now:()=>F?.now()??C?.now()??0,elapsed:be=>F?.elapsed(be)??Math.max(0,(C?.now()??be)-be)},y=f.now(),g=!!(s?.initialAutoProcessingError||s?.initialAutoProcessingPending),E=!1,G,ie=()=>{E||(E=!0,g=!0,G=f.now(),f.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},_e=!1,Ue=()=>{_e||(_e=!0,f.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),f.performance({stage:"processing",durationMs:f.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}),G!==void 0&&f.performance({stage:"recovery",durationMs:f.elapsed(G),durationMode:"machine",paymentMethodCategory:"saved"}))};f.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),yt.current=!0;try{f.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{yt.current=!1}se({class:"lifecycle",name:"payment.processing.started",provider:A}),g&&ie();let Tt;try{let be=xi(s?.initialAutoProcessingError),ve;if(be)ie(),be.type==="paypal_redirect_required"&&Gt.current?.publishableKey&&rs({sessionId:c,publishableKey:Gt.current.publishableKey,paypalPublishableKey:Gt.current.paypalPublishableKey}),ve=await Ao(be,{flopay:Ie.current,paypalFlopay:mt.current,attempt3DS:s?.attempt3DS,billingApiUrl:w,sessionId:c,session:l,telemetry:!1}),be.type==="paypal_redirect_required"&&ka();else if(s?.initialAutoProcessingPending){let $e=(await new Oo(w,{telemetry:!1}).waitForCheckoutSessionCompletion(s.initialAutoProcessingPending.sessionId,{initialDelayMs:s.initialAutoProcessingPending.retryAfterMs})).data.session;if(!br($e))throw bo($e);ve=lr($e,c)}else{if(s?.initialAutoProcessingError)throw Qn(s.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:s.initialAutoProcessingError.checkoutMethod});if(s?.fromCreateSession)return s?.fallbackToFull&&(nn("full"),os("full")),!1;{let M=await Ir({billingApiUrl:w,sessionId:c,session:l,telemetry:!1});M.type==="success"?ve=M.result:(ie(),M.type==="paypal_redirect_required"&&Gt.current?.publishableKey&&rs({sessionId:c,publishableKey:Gt.current.publishableKey,paypalPublishableKey:Gt.current.paypalPublishableKey}),ve=await Ao(M,{flopay:Ie.current,paypalFlopay:mt.current,attempt3DS:s?.attempt3DS,billingApiUrl:w,sessionId:c,session:l,telemetry:!1}),M.type==="paypal_redirect_required"&&ka())}}c&&kr(c),Ue(),g&&(f.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),f.terminal({outcome:ve.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Ut(ve.status==="authorized"),Ke("success"),await to(1200),Tt=()=>ln.current?.(ve)}catch(be){let ve=ur(be),M=ve.checkoutMethod??Zr;rt(ve.message),ct(ve.message),Ut(!1),s?.fallbackToFull&&(f.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),nn("full"),os("full")),Ue();let St=ve.statusCode!==void 0?Ql(ve.statusCode,"unknown"):void 0,$e=St==="4xx"?{requestCategory:"process_payment",statusClass:St}:{},nt=St===void 0||St==="4xx";if(nt&&(ve.telemetryOutcome==="payment_declined"||!!(ve.declineCode||ve.code?.toLowerCase().includes("declin"))))f.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...$e});else if(nt&&(ve.telemetryOutcome==="validation_rejected"||ve.type==="validation_error"))f.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...$e});else{let io=es(be,g?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),an=ve.telemetryRequestCategory??"process_payment";yt.current=!0;try{f.error({...io,...ve.telemetryFailureCategory?{failureCategory:ve.telemetryFailureCategory}:{},stage:g?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:an})}finally{yt.current=!1}se({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:an,provider:A})}return Qe(()=>cn.current?.(ve)),Ln(M,ve,{code:ve.code,declineCode:ve.declineCode}),Ke("error"),await Promise.allSettled([to(1500),s?.ensureProvidersReady?s.ensureProvidersReady():Promise.resolve()]),g&&(f.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ue(),C&&no(C),Ke(null),ct(null)}return Qe(Tt),!0},[Ln,se,Qe,ur,w,o,ot]);Fn(()=>{if(typeof window>"u"||dt.current)return;let l=new URLSearchParams(window.location.search),s=l.get("payment_intent_client_secret");if(!s)return;let c=nc();c&&(dt.current=!0,(async()=>{let A,K=0;rt(null),ct(null),Ke("processing"),En(!0);try{if(l.get("redirect_status")==="failed")throw Object.assign(new Ft("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:F,paypalFlopay:C}=await Bo({publishableKey:c.publishableKey,paypalPublishableKey:c.paypalPublishableKey,billingApiUrl:w,locale:m,telemetry:o});A=Bt(C??F),K=A?.now()??0,A?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),A?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let f=(C??F)?.getRawProvider();if(!f)throw Object.assign(new Ft("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:y,error:g}=await f.retrievePaymentIntent(s);if(g)throw Object.assign(new Ft(g.message??"Failed to retrieve PayPal payment status.","api_error",{code:g.code}),{checkoutMethod:"paypal"});let E=fi(y?.status);if(!y||E==="failed")throw Object.assign(new Ft("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let G=typeof y.payment_method=="string"?y.payment_method:y.payment_method?.id,ie=E;if(c.sessionId){let Tt=(await new Oo(w,{telemetry:!1}).getUnifiedCheckoutSession(c.sessionId)).data.session;if(Tt&&Tt.status!=="complete"){let be=await Ir({billingApiUrl:w,sessionId:c.sessionId,session:Tt,telemetry:!1,tokenizedData:{id:G??y.id,type:"card",threeDSecureActionResultTokenId:y.id,isPaypal:!0}});if(be.type!=="success")throw Object.assign(new Ft("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ie=be.result.status}}c.sessionId&&kr(c.sessionId),A?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),A?.performance({stage:"redirect_resume",durationMs:A.elapsed(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),A?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke("success"),await to(1200),Qe(()=>ln.current?.({status:ie,paymentIntentId:y.id,paymentMethodId:G,checkoutMethod:"paypal"}))}catch(F){let C=ur(F),f=C.checkoutMethod??"paypal",y=!!(C.declineCode||C.code?.toLowerCase().includes("declin"));if(A)A.performance({stage:"redirect_resume",durationMs:A.elapsed(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),y?A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):A.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(y){let g=zo(w,o,ot);g.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),no(g)}else Sa(w,o,ot,"REDIRECT_RESUME_FAILED","redirect_resume");rt(C.message),ct(C.message),Qe(()=>cn.current?.(C)),Ln(f,C,{code:C.code,declineCode:C.declineCode}),Ke("error"),await to(1500)}finally{ka(),rc(),Ke(null),ct(null),En(!1)}})())},[Ln,Qe,m,ur,w,o]);let $t=_t(null),Wt=bn(()=>un?ro(un):"",[un]),Jt=_t(un);Jt.current=un,Fn(()=>{Xt(e??"")},[e]),Fn(()=>{Yt.current=!1,rt(ae),ct(null),Ut(!1),Ke(null)},[Wt,ae,e]);async function Gn(l,s,c){let A=zo(w,o,ot),K=new Oo(w,{telemetry:!1}),F=!1;try{let C=l.idempotencyKey!==void 0?ts(l.idempotencyKey):void 0,f=ss(s,c),y=ls(s,c);f?.canonicalIdentity===c&&y&&y.canonicalIdentity===void 0&&(Ea(s,c,y.idempotencyKey),y={...y,canonicalIdentity:c});let g=C??(y?.canonicalIdentity===c?y.idempotencyKey:void 0),E,G=!1;A.log({name:f?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let ie=f?.sid??null,_e=null,Ue;if(ie)try{_e=await K.getUnifiedCheckoutSession(ie,f?.nonce),f&&f.canonicalIdentity===void 0&&(ic(_e.data.session,l)?(Ia(s,c,ie,f.nonce??_e.data.session?.clientSecret),y&&y.canonicalIdentity===void 0&&(Ea(s,c,y.idempotencyKey),g??(g=y.idempotencyKey))):(Ra(s,c),y=null,g=C,ie=null,_e=null));let Tt=_e?.data.session?.status;if(ie&&_e&&Tt==="complete"){if(la(ie))return{sid:ie,result:_e};Ra(s,c),ie=null,_e=null,G=!0}}catch{A.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),f?.canonicalIdentity===void 0?(Ra(s,c),g=C):xa(s,c),ie=null}if(!ie){!C&&(G||!g)&&(g=ts(),E=g),g&&Ea(s,c,g);let Tt=A.now(),be=0;A.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ve={...l,idempotencyKey:g,avsCheck:!!te,avsConfig:typeof te=="object"?te:void 0,checkoutType:"embedded_checkout",checkoutLayout:ue?"custom_layout":J==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(ve,Hl,{configurable:!1,enumerable:!1,value:{onAttempt:$e=>{be=Math.max(be,$e)}}});let M=()=>{A.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),A.performance({stage:"session_create",durationMs:A.now()-Tt,durationMode:"machine",requestCategory:"session_create",attempt:be,statusClass:"2xx"})},St=$e=>{let nt=es($e,"CHECKOUT_SESSION_CREATE_FAILED","unknown");A.performance({stage:"session_create",durationMs:A.now()-Tt,durationMode:"machine",requestCategory:"session_create",attempt:be,statusClass:nt.statusClass}),$e instanceof Ft&&$e.type==="validation_error"?A.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):nt.statusClass==="4xx"?A.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(A.error({...nt,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),se({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Wl(ve)){let $e=await K.createDetachedSession(ve);$e.claimed.catch(()=>{}),_e=$e.shell,ie=$e.sessionId,Ue=$e.claimed.then(nt=>{let or=nt.data.session?.id??$e.sessionId;return or&&Ia(s,c,or,nt.data.session?.clientSecret??$e.nonce),M(),nt},nt=>{throw xa(s,c),St(nt),nt}).finally(()=>no(A)),Ue.catch(()=>{}),F=!0,A.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),A.performance({stage:"session_shell",durationMs:A.now()-Tt,durationMode:"machine",requestCategory:"session_create",attempt:be,statusClass:"2xx",paymentMethodCategory:"card"})}else _e=await K.createAndFetchSession(ve),M()}catch($e){throw St($e),$e}ie=_e.data.session?.id??ie??"",ie&&!Ue&&Ia(s,c,ie,_e.data.session?.clientSecret)}return{sid:ie??"",result:_e,sdkGeneratedIdempotencyKey:E,...Ue?{claimed:Ue}:{}}}finally{F||no(A)}}let On=jn(async(l,s)=>{let c=Jt.current;if(!c)throw new Ft("createSession is required to bootstrap checkout.","validation_error");let A=ea(c,l),K=ro(A),F=ac(A),C=Uo.get(K);if(!C){let g={canonicalIdentity:K,promise:Gn(A,F,K),consumers:0,settled:!1};C=g,Uo.set(K,g);let E=()=>{g.settled=!0,ns(K,g)};g.promise.then(E,E)}C.consumers+=1;let f=!1,y=()=>{f||(f=!0,C.consumers-=1,ns(K,C))};s?.(y);try{let g=await C.promise;$t.current=K,l&&(Tn(me),Vn(ve=>pi(ve,l)));let{sid:E,result:G,claimed:ie}=g;if(H(G),G.data.session&&Le(G.data.session),E&&Xt(E),ie){Pe.current+=1;let ve=Pe.current;Xe(!0),ie.then(M=>{Pe.current===ve&&(H(M),M.data.session&&Le(M.data.session),Xe(!1))},M=>{Pe.current===ve&&(Xe(!1),Ht(M instanceof Ft?M:new Ft(M instanceof Error?M.message:"Failed to create session","api_error")))})}else Pe.current+=1,Xe(!1);let{publishableKey:_e,paypalPublishableKey:Ue}=Mo(G),{flopay:Tt,paypalFlopay:be}=await Bo({publishableKey:_e,paypalPublishableKey:Ue,billingApiUrl:w,locale:m,telemetry:o});return Ie.current=Tt,Be(Tt),mt.current=be,Y(be),Lt(!1),g}catch(g){throw $t.current===K&&($t.current=null),g}finally{s||y()}},[me,m,w,o,ot]),An=_t(pn);An.current=pn;let Nn=_t(On);Nn.current=On;let qt=jn(async l=>{if(!oc(l)||xn)return{sessionId:Vt,session:D};mr(!0);try{let s=await On(l);return{sessionId:s.sid,session:s.result.data.session??null}}finally{mr(!1)}},[On,xn,Vt,D]);Fn(()=>{let l=!1,s;if(Ht(null),Wt){let K=Jt.current;return nn(on),Lt(!1),$t.current===Wt?()=>{l=!0}:(Le(mi(K,ke)),(async()=>{let F=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),C=on==="auto"&&!Yt.current&&!F;C&&(rt(null),ct(null),Ke("processing"));try{let f=await Nn.current(void 0,G=>{s=G}),y=f.result.data.session??null;Gt.current=Mo(f.result);let g=wa(f.result),E=la(f.sid||y?.id);if(!l&&C&&y&&!g&&!E){Yt.current=!0,await ec(Wt,f.sdkGeneratedIdempotencyKey,()=>An.current(y,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:f.result.autoProcessingError,initialAutoProcessingPending:f.result.autoProcessingPending,autoProcessingAttempted:f.result.autoProcessingAttempted,sessionId:f.sid||y.id}));return}!l&&C&&((g||E)&&(Yt.current=!0),Ke(null),ct(null))}catch(f){if(l)return;let y=f instanceof Ft||typeof f=="object"&&f!==null&&"code"in f?f.code:void 0;if(C&&y==="session_auto_completed"){Yt.current=!0,Ke("success"),await to(1200),l||(Qe(()=>{ln.current?.({status:"succeeded"})}),Ke(null),ct(null));return}C&&(Ke(null),ct(null));let g=f instanceof Ft?f:new Ft(f instanceof Error?f.message:"Failed to create session","api_error");Ht(g)}finally{s?.(),s=void 0}})(),()=>{l=!0,s?.()})}Lt(!0);async function c(){let K=!1;try{let C=await new Oo(w,{telemetry:!1}).getUnifiedCheckoutSession(Ge,t);if(l)return;H(C);let f=C.data.session??null;if(Le(f),!f)throw new Ft("No session data returned","api_error");let y=f.checkoutMode;if(y==="setup")throw new Ft("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(f.status==="authorized"){Lt(!1),Qe(()=>{ln.current?.(lr(f,Ge)),Sn.current?.(f.successUrl??"")});return}if(f.status==="complete"){Lt(!1),Qe(()=>{Sn.current?.(f.successUrl??"")});return}if(f.status==="expired")throw Po(f);K=!0;let g=ke??y??"full";nn(g);let E=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),G=wa(C);if(g==="auto"&&!Yt.current&&!E&&!G){Yt.current=!0;let ie=A(C);try{if(await An.current(f,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ie,sessionId:Ge||f.id}),l)return;await ie,l||Lt(!1);return}catch{if(l)return;await ie,l||Lt(!1);return}}await A(C),l||Lt(!1)}catch(F){if(l)return;K&&se({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),F instanceof Ft?!K&&!tc(F)&&Sa(w,o,ot,"NETWORK_REQUEST_FAILED","session_read"):Sa(w,o,ot,"INTERNAL_SDK_ERROR","checkout_mount");let C=F instanceof Ft?F:new Ft(F instanceof Error?F.message:"Failed to initialize checkout","api_error");Ht(C),Lt(!1)}}async function A(K){let{publishableKey:F,paypalPublishableKey:C}=Mo(K);Gt.current={publishableKey:F,paypalPublishableKey:C};let{flopay:f,paypalFlopay:y}=await Bo({publishableKey:F,paypalPublishableKey:C,billingApiUrl:w,locale:m,telemetry:o});Ie.current=f,Be(f),mt.current=y,Y(y)}return c(),()=>{l=!0}},[ke,Wt,on,vt,Qe,t]);let Ze=jn(async()=>{if(!(Nt||!D)){En(!0),rt(null);try{await pn(D,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ge||D.id})}finally{En(!1)}}},[Ge,Nt,pn,D]),mn=Ta(R),jt=wa(R),ut=bn(()=>{if(!(!R||!D||!R.data.stripe?.publishableKey))return{billingApiUrl:w}},[R,D,w]),Qt=!!(n&&!ue&&J==="buttons"&&B&&on==="full"),Rt=bn(()=>({session:D,loading:Je,error:je,checkoutMode:Et,inlineSessionDraft:un,applyInlineSessionPatch:Qt?qt:void 0,inlineSessionPatchProcessing:xn,claimPending:I}),[D,Je,je,Et,un,Qt,qt,xn,I]),rr=!!n&&J==="buttons"&&!jt&&(!$||!ut),pt=zt?X(Mn,{status:zt,errorMessage:Rn,authorized:vn}):null;if(Je){if(d)return Dt(Dn,{children:[d,pt]});if(J==="buttons"){let l=oe?.buttonsLayout?.cardButton?.borderRadius??oe?.appearance.variables?.borderRadius??8,s=c=>X("div",{style:{height:c,borderRadius:l,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Dt(Dn,{children:[Dt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[S&&s(Tr),ee&&(v||ye)&&s(Tr),ee&&s(Tr),X("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),pt]})}return Dt(Dn,{children:[Dt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[X("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),X("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),pt]})}return je?T?X(kn.Provider,{value:Rt,children:T(je)}):X(kn.Provider,{value:Rt,children:X("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:je.message})}):rr?Dt(Dn,{children:[X(kn.Provider,{value:Rt,children:X(lc,{onButtonClick:q,showPayPal:S,showStripe:ee,showApplePay:v,showGooglePay:ye,theme:ce,buttonsTheme:Se,buttonsStyles:re,cardButtonContent:le,cardBackButtonContent:Ve,cardTitleContent:Ae})}),pt]}):jt&&D&&mn?Dt(Dn,{children:[X(kn.Provider,{value:Rt,children:Dt("div",{className:de,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[sn&&X(wr,{icon:!1,children:sn}),Cn==="retrying"&&X("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Cn==="exhausted"&&Dt("div",{role:"alert",children:[X("div",{children:"PayPal is temporarily unavailable. Please try again."}),X("button",{type:"button",onClick:dn,children:"Retry PayPal"})]}),Cn!=="exhausted"&&X("div",{"aria-hidden":Cn==="retrying"?!0:void 0,style:Cn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:X(wi,{sessionId:Ge,nonce:D.clientSecret||void 0,billingApiUrl:w,email:D.customer?.email,clientId:mn.clientId,environment:mn.environment,currency:(D.currency??"usd").toUpperCase(),isSubscription:D.mode==="subscription",providerObjectType:mn.providerObjectType,onComplete:h,onErrorChange:rt,onDecline:x,onButtonClick:q,onInitializationStateChange:rn,allowAutomaticRetry:Hn===0,session:D,telemetry:o,telemetryContext:ot,onInstrument:Fe,debug:j},`${N}:paypal-init-${Hn}`)})]})}),pt]}):!$||!ut?X(Dn,{children:pt}):Et==="confirm"?Dt(Dn,{children:[X(kn.Provider,{value:Rt,children:X(_o,{flopay:$,paypalFlopay:We,options:ut,onInstrument:Fe,children:Dt("div",{className:de,children:[sn&&X("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:sn}),Re?Re({onConfirm:Ze,isProcessing:Nt}):X("button",{type:"button",onClick:Ze,disabled:Nt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Nt?"not-allowed":"pointer",opacity:Nt?.6:1},children:Nt?"Processing...":pe??"Confirm Purchase"})]})},N)}),pt]}):Dt(Dn,{children:[X(kn.Provider,{value:Rt,children:X(_o,{flopay:$,paypalFlopay:We,options:ut,onInstrument:Fe,children:ue?Dt(Dn,{children:[sn&&X("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:sn}),X(sc,{sessionId:Ge,nonce:D?.clientSecret||void 0,billingApiUrl:w,session:D,children:ue})]}):X(va,{sessionId:Ge,nonce:D?.clientSecret||void 0,email:D?.customer?.email,userId:D?.customer?.id,firstName:D?.customer?.firstName,lastName:D?.customer?.lastName,totalAmount:D?Math.round(Yl(D).total*100):0,currency:D?.currency?.toLowerCase()??"usd",onComplete:h,onError:P,onDecline:x,error:sn,onErrorChange:rt,showPayPal:S,showStripe:ee,enabledPaymentMethods:W??R?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:R?.data.stripe?.enabledPaymentMethodCountries,showApplePay:v,showGooglePay:ye,layout:J,theme:ce,buttonsTheme:Se,buttonsStyles:re,appearance:qe,cardButtonContent:le,cardBackButtonContent:Ve,cardTitleContent:Ae,onButtonClick:q,onBeforeButtonClick:B,enableAVS:te,...tt?{cardFieldOrder:tt}:{},...Me?{cardPreFormSlot:Me}:{},avsLayout:V,country:D?.customer?.country,city:D?.customer?.city,state:D?.customer?.state,onCountryChange:U,onZipChange:p,avsCheck:!!te,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ue?"custom_layout":J==="buttons"?"buttons_layout":"default_layout",className:de,directPaypal:Ta(R),isSubscription:D?.mode==="subscription",session:D,dataAttachmentPending:I,debug:j})},N)}),pt]})}function sc({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return X(Dn,{children:Ca.Children.map(o,a=>{if(!Ca.isValidElement(a))return a;let m=a.props,d={};return m.sessionId||(d.sessionId=e),!m.nonce&&t&&(d.nonce=t),m.billingApiUrl||(d.billingApiUrl=n),r?.customer&&(m.email||(d.email=r.customer.email),m.userId||(d.userId=r.customer.id),m.firstName||(d.firstName=r.customer.firstName),m.lastName||(d.lastName=r.customer.lastName)),Object.keys(d).length===0?a:Ca.cloneElement(a,d)})})}function lc({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:m,buttonsStyles:d,cardButtonContent:T,cardBackButtonContent:h,cardTitleContent:P}){let[b,x]=kt(!1),U=bn(()=>as(a),[a]),p=bn(()=>{let v=U?.buttonsLayout??Xl(m);return d?{...v,...d,cardButton:{...v.cardButton,...d.cardButton},cardFormContainer:{...v.cardFormContainer,...d.cardFormContainer},backButton:{...v.backButton,...d.backButton},backButtonIcon:{...v.backButtonIcon,...d.backButtonIcon},submitButton:{...v.submitButton,...d.submitButton},title:{...v.title,...d.title}}:v},[U,m,d]),S=U?.buttonsLayout?.cardButton?.borderRadius??U?.appearance.variables?.borderRadius??8,ee=v=>X("div",{style:{height:v,borderRadius:S,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),W=T===void 0?{boxSizing:"border-box",height:Tr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let v=p.cardInputBorder??"#e5e7eb",ye=p.cardInputBackground??"white",j=fr(h),J=fr(P);return Dt("div",{style:{backgroundColor:p.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...p.cardFormContainer},children:[Dt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Dt("button",{type:"button",onClick:()=>x(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:j?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...p.backButton},children:[X("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...p.backButtonIcon},children:X("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:X("path",{d:"M15 18l-6-6 6-6"})})}),X(hr,{content:h})]}),J?X("div",{style:{flex:1}}):X("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...p.title},children:X(Yr,{content:P})})]}),X("div",{style:{backgroundColor:ye,border:`1px solid ${v}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:X("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Dt("div",{style:{display:"flex"},children:[X("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomLeftRadius:8,padding:12,height:45},children:X("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),X("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:`1px solid ${v}`,borderBottom:`1px solid ${v}`,borderLeft:`1px solid ${v}`,borderBottomRightRadius:8,padding:12,height:45},children:X("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),X("div",{style:{backgroundColor:ye,border:`1px solid ${v}`,borderRadius:8,marginTop:8,padding:12,height:45},children:X("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),X("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...p.submitButton,opacity:.5}}),X("style",{children:`
|
|
36
36
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
37
37
|
@keyframes flopay-interim-expand {
|
|
38
38
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
39
39
|
40% { opacity: 1; }
|
|
40
40
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
41
41
|
}
|
|
42
|
-
`})]})}return _t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&w(Cr),n&&(s||a)&&w(Cr),n&&ee("button",{type:"button",onClick:()=>{e?.("card"),v(!0)},style:{width:"100%",...I,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:y=>{y.currentTarget.style.transform="scale(0.985)"},onMouseUp:y=>{y.currentTarget.style.transform="scale(1)"},children:ee(dr,{content:b})}),ee("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as Nu}from"@flopay/shared";import{useEffect as Vl,useRef as Gi,useContext as Hl}from"react";import{jsx as Gl}from"react/jsx-runtime";function Ji(e,t){function n({className:s,id:a,style:i,options:p,onChange:l,onReady:b,onFocus:z,onBlur:g,onEscape:R}){let v=Gi(null),A=Gi(null),{elements:u,reportInteractive:h}=Hl(Tn);return Vl(()=>{if(!u||!v.current)return;let w=!0;return(async()=>{let I=u.getElement(e);I||(I=await u.create(e,p)),!(!w||!v.current)&&(I.mount(v.current),A.current=I,l&&I.on("change",l),I.on("ready",()=>{h?.(),b?.()}),z&&I.on("focus",z),g&&I.on("blur",g),R&&I.on("escape",R))})(),()=>{if(w=!1,A.current){try{A.current.unmount()}catch{}A.current=null}}},[u,h]),Gl("div",{ref:v,className:s,id:a,style:i})}return n.displayName=t,n}var Yl=Ji("payment","PaymentElement"),Wl=Ji("address","AddressElement");import{PaymentAPI as Jl}from"@flopay/js";import{FloPayError as Xl}from"@flopay/shared";import{useCallback as Sa,useEffect as Ql,useRef as Zl,useState as Xi}from"react";import{Fragment as tc,jsx as Sr,jsxs as nc}from"react/jsx-runtime";function ec({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,firstName:i,lastName:p,chv:l,onTokenizedBody:b,onComplete:z,onErrorChange:g,isProcessing:R=!1}){let v=kn(),A=Ho(),u=uo(),[h,w]=Xi(!1),[I,y]=Xi(!1),he=Zl(!1),F=(n||u).replace(/\/+$/,""),te=Sa(async q=>{try{let ie=await new Jl(F).processPayment(a??"",{sessionId:e,nonce:t,tokenizedData:q,accountData:{userId:a??"",email:s??"",firstName:i??"",lastName:p??""},chv:l});if(ie.ok){z?.();return}let Ne=await ie.json().catch(()=>null);g?.(Ne?.message??"Payment failed. Please try again.")}catch(oe){g?.(oe instanceof Error?oe.message:"An unexpected error occurred")}},[F,e,t,a,s,i,p,l,z,g]),be=Sa(q=>{b?b(q):te(q)},[b,te]);Ql(()=>{if(!v||he.current)return;let q=new URLSearchParams(window.location.search),oe=q.get("payment_intent"),ie=q.get("payment_intent_client_secret"),Ne=q.get("redirect_status");!oe||!ie||(he.current=!0,(async()=>{try{if(y(!0),Ne==="failed"){g?.("PayPal payment was declined. Please try again.");return}let f=v.getRawProvider();if(!f?.retrievePaymentIntent){g?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ae,error:Fe}=await f.retrievePaymentIntent(ie);if(Fe){g?.(Fe.message??"Failed to retrieve PayPal payment status.");return}if(ae&&(ae.status==="requires_capture"||ae.status==="succeeded")){let ve=typeof ae.payment_method=="string"?ae.payment_method:ae.payment_method?.id;be({id:ve??ae.id,type:"card",threeDSecureActionResultTokenId:ae.id,isPaypal:!0});let Re=new URL(window.location.href);Re.searchParams.delete("payment_intent"),Re.searchParams.delete("payment_intent_client_secret"),Re.searchParams.delete("redirect_status"),window.history.replaceState({},"",Re.toString())}else g?.("PayPal payment was not completed. Please try again.")}catch(f){g?.(f instanceof Error?f.message:"Failed to complete PayPal payment.")}finally{y(!1)}})())},[v,be,g]);let j=Sa(async()=>{if(!(!v||!A))try{if(y(!0),g?.(null),!e||!s)throw new Xl("Missing sessionId or email for PayPal payment","validation_error");let q=await v.confirmPayPalPayment({billingApiUrl:F,sessionId:e,nonce:t,email:s,returnUrl:window.location.href});if(q.error){g?.(q.error.message);return}q.paymentIntentId&&(q.status==="succeeded"||q.status==="processing"||q.status==="requires_capture")&&be({id:q.paymentMethodId??q.paymentIntentId,type:"card",threeDSecureActionResultTokenId:q.paymentIntentId,isPaypal:!0})}catch(q){g?.(q instanceof Error?q.message:"PayPal payment failed. Please try again.")}finally{y(!1)}},[v,A,e,t,s,F,be,g]);return!v||!A?Sr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):nc(tc,{children:[!h&&Sr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),Sr("div",{style:h?{}:{display:"none"},children:Sr("button",{type:"button",onClick:j,disabled:I||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:I||R?"not-allowed":"pointer",opacity:I||R?.6:1},ref:()=>w(!0),children:I?"Processing...":"PayPal"})}),(I||R)&&Sr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:Sr("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}import{useCallback as Vn,useEffect as wr,useMemo as Gr,useRef as kr,useState as Jr}from"react";import{PaymentAPI as wa}from"@flopay/js";import{FloPayError as Ir,resolveBillingApiUrl as rc,resolveButtonsLayoutTheme as oc,resolveTheme as ac}from"@flopay/shared";import{Fragment as uc,jsx as Rr,jsxs as pc}from"react/jsx-runtime";var ic=44;function Qi(e){return new Promise(t=>setTimeout(t,e))}function sc(e,t){return e instanceof Ir?e:new Ir(e instanceof Error?e.message:t,"api_error")}function lc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function cc(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 dc({sessionId:e,nonce:t,createSession:n,paymentMethodId:s,checkoutMethod:a,clientId:i,products:p,items:l,subscriptions:b,account:z,successUrl:g,cancelUrl:R,couponCodes:v,tagsData:A,utmMetadata:u,billingApiUrl:h,locale:w,theme:I,appearance:y,buttonsTheme:he,buttonsStyles:F,onSuccess:te,onError:be,onDecline:j,children:q,disabled:oe=!1,type:ie="button",style:Ne,...f}){let ae=Gr(()=>rc(h),[h]),Fe=Gr(()=>cc({createSession:n,clientId:i,products:p,items:l,subscriptions:b,account:z,successUrl:g,cancelUrl:R,couponCodes:v,tagsData:A,utmMetadata:u}),[z,R,i,v,n,p,l,b,g,A,u]),[ve,Re]=Jr(!1),[J,le]=Jr(null),[De,se]=Jr(null),[_e,Ue]=Jr(!1),[xe,H]=Jr(null),P=kr(!0),Q=kr(null),We=kr(xe),Le=kr(te),Z=kr(be),_=kr(j);wr(()=>{We.current=xe},[xe]),wr(()=>{Le.current=te},[te]),wr(()=>{Z.current=be},[be]),wr(()=>{_.current=j},[j]),wr(()=>(P.current=!0,()=>{P.current=!1,Q.current?.abort()}),[]),wr(()=>{if(typeof window>"u")return;let S=pe=>{pe.key==="Escape"&&H(null)};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[]);let ce=Vn((S,pe=Hr)=>{_.current?.(It(pe,S,{code:S.code,declineCode:S.declineCode}))},[]),K=Vn(async S=>{P.current&&(se(null),Ue(S.result.status==="authorized"),le("success"),await Qi(xn),P.current&&Le.current?.(S))},[]),de=Vn(async(S,pe)=>{P.current&&(Z.current?.(S),pe?.emitDecline&&ce(S,pe.method),se(S.message),Ue(!1),le("error"),await Qi(Sn))},[ce]),et=Vn(async(S,pe,Je)=>{let Xe=S.data.session??null;if(!Xe)throw new Ir("No session data returned","api_error");let xt=Xe.clientSecret||t;if(yr(Xe)){await K({result:Zn(Xe,pe),session:Xe,sessionId:Xe.id||pe,autoCompleted:!1});return}if(Xe.status==="expired")throw po(Xe);try{if(S.autoProcessingPending){let Ie=(await new wa(ae).waitForCheckoutSessionCompletion(S.autoProcessingPending.sessionId,{initialDelayMs:S.autoProcessingPending.retryAfterMs})).data.session;if(!yr(Ie))throw mo(Ie);await K({result:Zn(Ie,pe),session:Ie,sessionId:Ie.id||pe,autoCompleted:!1});return}if(S.autoProcessingError){if(S.autoProcessingError.type==="3ds_required"&&S.autoProcessingError.nextActionRedirectUrl&&pe&&xt){let Te=new AbortController;Q.current=Te;let ft;try{ft=await zi({billingApiUrl:ae,sessionId:pe,nonce:xt,nextActionRedirectUrl:S.autoProcessingError.nextActionRedirectUrl,signal:Te.signal})}finally{Q.current===Te&&(Q.current=null)}if(ft.status==="declined")throw Kn({type:ft.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ft.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:S.autoProcessingError.checkoutMethod});let Ke=(await new wa(ae).waitForCheckoutSessionCompletion(pe,{initialDelayMs:0,nonce:xt})).data.session;if(!yr(Ke))throw Kn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:S.autoProcessingError.checkoutMethod});await K({result:Zn(Ke,pe),session:Ke,sessionId:Ke.id||pe,autoCompleted:!1});return}throw Kn(S.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:S.autoProcessingError.checkoutMethod})}if(Je?.fromCreateSession&&S.autoProcessingAttempted===!0)throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let yt=await vr({billingApiUrl:ae,sessionId:pe??Xe.id,session:Xe,nonce:xt});if(yt.type!=="success")throw Kn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await K({result:yt.result,session:Xe,sessionId:Xe.id||pe,autoCompleted:!1})}catch(yt){let Te=rr(yt),ft=Xe.id||pe;await de(Te,{emitDecline:!0,method:Te.checkoutMethod??Hr}),lc(Te,ft)&&ft&&P.current&&H({sessionId:ft,errorMessage:Te.message,nonce:xt||void 0})}},[t,ae,de,K]),$e=Vn(async S=>{if(f.onClick?.(S),!(S.defaultPrevented||oe||ve)){if(H(null),e&&Fe){let pe=new Ir("Provide either sessionId or create-session props, not both.","validation_error");await de(pe),P.current&&(le(null),se(null));return}if(!e&&!Fe){let pe=new Ir("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await de(pe),P.current&&(le(null),se(null));return}Re(!0),se(null),Ue(!1),le("processing");try{let pe=new wa(ae);if(e){let Je=await pe.getUnifiedCheckoutSession(e,t);await et(Je,e);return}try{let Je=await pe.createAndFetchSession({...Fe});await et(Je,Je.data.session?.id??null,{fromCreateSession:!0})}catch(Je){if(Je instanceof Ir&&Je.code==="session_auto_completed"){await K({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Je}}catch(pe){await de(sc(pe,"Automatic payment failed. Please try again."))}finally{P.current&&(le(null),se(null),Re(!1))}}},[f,Fe,oe,ve,t,et,ae,e,de,K]),it=Vn(S=>{let pe=We.current;H(null),Le.current?.({result:S,session:null,sessionId:pe?.sessionId??null,autoCompleted:!1})},[]),ue=Vn(S=>{Z.current?.(S)},[]),G=Vn(S=>{_.current?.(S)},[]),tt=Gr(()=>ac(I),[I]),Y=Gr(()=>{let S=tt?.buttonsLayout??oc(he);return F?{...S,...F,cardButton:{...S.cardButton,...F.cardButton}}:S},[tt,he,F]),mt=Gr(()=>{let S=tt?.appearance;return y?S?{...S,...y,variables:{...S.variables,...y.variables}}:y:S},[y,tt]),je=mt?.variables,qe=je?.colorPrimary??"#4A49FF",$t=je?.colorPrimaryHover??Or(qe,.12),nt=je?.borderRadius??"8px";return pc(uc,{children:[Rr("button",{...f,type:ie,onClick:$e,disabled:oe||ve,"aria-busy":ve,style:{width:"100%",...q===void 0?{boxSizing:"border-box",height:ic,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Y.cardButton,...la({themeBundle:tt,resolvedPrimaryColor:qe,resolvedBorderRadius:nt,submitButtonStyle:Y.submitButton,explicitPrimaryColor:je?.colorPrimary}),fontSize:Y.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:oe||ve?"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:oe||ve?.6:1,...Ne},onMouseEnter:S=>{f.onMouseEnter?.(S),!S.defaultPrevented&&!oe&&!ve&&(tt||je?.colorPrimary)&&(S.currentTarget.style.backgroundColor=$t)},onMouseLeave:S=>{f.onMouseLeave?.(S),!S.defaultPrevented&&(tt||je?.colorPrimary)&&(S.currentTarget.style.backgroundColor=qe)},onMouseDown:S=>{f.onMouseDown?.(S),S.defaultPrevented||(S.currentTarget.style.transform="scale(0.985)")},onMouseUp:S=>{f.onMouseUp?.(S),S.defaultPrevented||(S.currentTarget.style.transform="scale(1)")},children:Rr(dr,{content:q})}),J&&Rr(wn,{status:J,errorMessage:De,authorized:_e}),xe&&Rr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:S=>{S.target===S.currentTarget&&H(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:Rr("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:Rr(Ca,{sessionId:xe.sessionId,nonce:xe.nonce,checkoutMode:"full",billingApiUrl:ae,locale:w,theme:I,...mt?{appearance:mt}:{},buttonsTheme:he,buttonsStyles:F,initialErrorMessage:xe.errorMessage,cardTitleContent:null,onComplete:it,onError:ue,onDecline:G})})})]})}export{Wl as AddressElement,Po as DirectPayPalButton,dc as FloPayAutomaticPaymentButton,Ps as FloPayCardSetup,hs as FloPayCardSetupError,Ca as FloPayCheckout,co as FloPayProvider,ec as PayPalButton,Yl as PaymentElement,ca as SplitCardForm,jo as VaultCardFields,Nu as dropThirdPartyOnlyError,As as useCheckout,Ho as useElements,kn as useFloPay,Vo as usePayPalFloPay};
|
|
42
|
+
`})]})}return Dt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ee(Tr),n&&(r||o)&&ee(Tr),n&&X("button",{type:"button",onClick:()=>{e?.("card"),x(!0)},style:{width:"100%",...W,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:p.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,...p.cardButton},onMouseDown:v=>{v.currentTarget.style.transform="scale(0.985)"},onMouseUp:v=>{v.currentTarget.style.transform="scale(1)"},children:X(gr,{content:T})}),X("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as hc,jsx as Mr,jsxs as Pc}from"react/jsx-runtime";var pc=44;function cs(e){return new Promise(t=>setTimeout(t,e))}function mc(e,t){return e instanceof Br?e:new Br(e instanceof Error?e.message:t,"api_error")}function yc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function fc(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 gc({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:m,items:d,subscriptions:T,account:h,successUrl:P,cancelUrl:b,couponCodes:x,tagsData:U,utmMetadata:p,billingApiUrl:S,locale:ee,theme:W,appearance:v,buttonsTheme:ye,buttonsStyles:j,onSuccess:J,onError:ce,onDecline:Se,children:re,disabled:le=!1,type:Ve="button",style:Ae,...Ce}){let q=oo(()=>cc(S),[S]),B=oo(()=>fc({createSession:n,clientId:a,products:m,items:d,subscriptions:T,account:h,successUrl:P,cancelUrl:b,couponCodes:x,tagsData:U,utmMetadata:p}),[h,b,a,x,n,m,d,T,P,U,p]),[te,tt]=ao(!1),[Me,V]=ao(null),[de,ae]=ao(null),[ue,ke]=ao(!1),[pe,Re]=ao(null),O=Ar(!0),w=Ar(null),oe=Ar(pe),qe=Ar(J),De=Ar(ce),Z=Ar(Se);xr(()=>{oe.current=pe},[pe]),xr(()=>{qe.current=J},[J]),xr(()=>{De.current=ce},[ce]),xr(()=>{Z.current=Se},[Se]),xr(()=>(O.current=!0,()=>{O.current=!1,w.current?.abort()}),[]),xr(()=>{if(typeof window>"u")return;let k=se=>{se.key==="Escape"&&Re(null)};return window.addEventListener("keydown",k),()=>{window.removeEventListener("keydown",k)}},[]);let R=tr((k,se=Zr)=>{Z.current?.(Mt(se,k,{code:k.code,declineCode:k.declineCode}))},[]),H=tr(async k=>{O.current&&(ae(null),ke(k.result.status==="authorized"),V("success"),await cs(1200),O.current&&qe.current?.(k))},[]),$=tr(async(k,se)=>{O.current&&(De.current?.(k),se?.emitDecline&&R(k,se.method),ae(k.message),ke(!1),V("error"),await cs(1500))},[R]),Be=tr(async(k,se,yt)=>{let Fe=k.data.session??null;if(!Fe)throw new Br("No session data returned","api_error");let Vt=Fe.clientSecret||t;if(br(Fe)){await H({result:lr(Fe,se),session:Fe,sessionId:Fe.id||se,autoCompleted:!1});return}if(Fe.status==="expired")throw Po(Fe);try{if(k.autoProcessingPending){let Je=(await new Fa(q).waitForCheckoutSessionCompletion(k.autoProcessingPending.sessionId,{initialDelayMs:k.autoProcessingPending.retryAfterMs})).data.session;if(!br(Je))throw bo(Je);await H({result:lr(Je,se),session:Je,sessionId:Je.id||se,autoCompleted:!1});return}if(k.autoProcessingError){if(k.autoProcessingError.type==="3ds_required"&&k.autoProcessingError.nextActionRedirectUrl&&se&&Vt){let Ge=new AbortController;w.current=Ge;let vt;try{vt=await Ai({billingApiUrl:q,sessionId:se,nonce:Vt,nextActionRedirectUrl:k.autoProcessingError.nextActionRedirectUrl,signal:Ge.signal})}finally{w.current===Ge&&(w.current=null)}if(vt.status==="declined")throw Qn({type:vt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:vt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:k.autoProcessingError.checkoutMethod});let je=(await new Fa(q).waitForCheckoutSessionCompletion(se,{initialDelayMs:0,nonce:Vt})).data.session;if(!br(je))throw Qn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:k.autoProcessingError.checkoutMethod});await H({result:lr(je,se),session:je,sessionId:je.id||se,autoCompleted:!1});return}throw Qn(k.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:k.autoProcessingError.checkoutMethod})}if(yt?.fromCreateSession&&k.autoProcessingAttempted===!0)throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Xt=await Ir({billingApiUrl:q,sessionId:se??Fe.id,session:Fe,nonce:Vt});if(Xt.type!=="success")throw Qn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await H({result:Xt.result,session:Fe,sessionId:Fe.id||se,autoCompleted:!1})}catch(Xt){let Ge=ur(Xt),vt=Fe.id||se;await $(Ge,{emitDecline:!0,method:Ge.checkoutMethod??Zr}),yc(Ge,vt)&&vt&&O.current&&Re({sessionId:vt,errorMessage:Ge.message,nonce:Vt||void 0})}},[t,q,$,H]),Ie=tr(async k=>{if(Ce.onClick?.(k),!(k.defaultPrevented||le||te)){if(Re(null),e&&B){let se=new Br("Provide either sessionId or create-session props, not both.","validation_error");await $(se),O.current&&(V(null),ae(null));return}if(!e&&!B){let se=new Br("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(se),O.current&&(V(null),ae(null));return}tt(!0),ae(null),ke(!1),V("processing");try{let se=new Fa(q);if(e){let yt=await se.getUnifiedCheckoutSession(e,t);await Be(yt,e);return}try{let yt=await se.createAndFetchSession({...B});await Be(yt,yt.data.session?.id??null,{fromCreateSession:!0})}catch(yt){if(yt instanceof Br&&yt.code==="session_auto_completed"){await H({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw yt}}catch(se){await $(mc(se,"Automatic payment failed. Please try again."))}finally{O.current&&(V(null),ae(null),tt(!1))}}},[Ce,B,le,te,t,Be,q,e,$,H]),We=tr(k=>{let se=oe.current;Re(null),qe.current?.({result:k,session:null,sessionId:se?.sessionId??null,autoCompleted:!1})},[]),Y=tr(k=>{De.current?.(k)},[]),mt=tr(k=>{Z.current?.(k)},[]),D=oo(()=>uc(W),[W]),Le=oo(()=>{let k=D?.buttonsLayout??dc(ye);return j?{...k,...j,cardButton:{...k.cardButton,...j.cardButton}}:k},[D,ye,j]),Pt=oo(()=>{let k=D?.appearance;return v?k?{...k,...v,variables:{...k.variables,...v.variables}}:v:k},[v,D]),N=Pt?.variables,bt=N?.colorPrimary??"#4A49FF",ze=N?.colorPrimaryHover??Hr(bt,.12),tn=N?.borderRadius??"8px";return Pc(hc,{children:[Mr("button",{...Ce,type:Ve,onClick:Ie,disabled:le||te,"aria-busy":te,style:{width:"100%",...re===void 0?{boxSizing:"border-box",height:pc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Le.cardButton,...ba({themeBundle:D,resolvedPrimaryColor:bt,resolvedBorderRadius:tn,submitButtonStyle:Le.submitButton,explicitPrimaryColor:N?.colorPrimary}),fontSize:Le.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:le||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:le||te?.6:1,...Ae},onMouseEnter:k=>{Ce.onMouseEnter?.(k),!k.defaultPrevented&&!le&&!te&&(D||N?.colorPrimary)&&(k.currentTarget.style.backgroundColor=ze)},onMouseLeave:k=>{Ce.onMouseLeave?.(k),!k.defaultPrevented&&(D||N?.colorPrimary)&&(k.currentTarget.style.backgroundColor=bt)},onMouseDown:k=>{Ce.onMouseDown?.(k),k.defaultPrevented||(k.currentTarget.style.transform="scale(0.985)")},onMouseUp:k=>{Ce.onMouseUp?.(k),k.defaultPrevented||(k.currentTarget.style.transform="scale(1)")},children:Mr(gr,{content:re})}),Me&&Mr(Mn,{status:Me,errorMessage:de,authorized:ue}),pe&&Mr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:k=>{k.target===k.currentTarget&&Re(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:Mr("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:Mr(Ba,{sessionId:pe.sessionId,nonce:pe.nonce,checkoutMode:"full",billingApiUrl:q,locale:ee,theme:W,...Pt?{appearance:Pt}:{},buttonsTheme:ye,buttonsStyles:j,initialErrorMessage:pe.errorMessage,cardTitleContent:null,onComplete:We,onError:Y,onDecline:mt})})})]})}export{Ro as DirectPayPalButton,gc as FloPayAutomaticPaymentButton,_s as FloPayCardSetup,Rs as FloPayCardSetupError,Ba as FloPayCheckout,_o as FloPayProvider,va as SplitCardForm,Qo as VaultCardFields,Mu as dropThirdPartyOnlyError,Ls as useCheckout,Xn as useFloPay,na as usePayPalFloPay};
|