@flopay/react 1.4.7 → 1.4.10
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 +56 -23
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.mjs +9 -9
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{useCallback as Hi,useEffect as _r,useState as Eo,useMemo as Ki,useRef as _o}from"react";import{resolveBillingApiUrl as Wi}from"@flopay/shared";import{createContext as xa}from"react";var xn=xa({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),cn=xa({session:null,loading:!1,error:null});var $i=Symbol.for("@flopay/js.telemetry.bridge.v1"),qi=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ji(){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 Vi(e){let t=ji(),n=(r,a)=>r?r.bind(e):a,i=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:i,elapsed:e.elapsed?e.elapsed.bind(e):r=>Math.max(0,i()-r),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 Yr(e){let t=globalThis[qi];return Vi(t?.(e)??{})}function Mt(e){if(e)return e[$i]}import{jsx as Yi}from"react/jsx-runtime";function Gr({flopay:e,paypalFlopay:t,options:n,children:i}){let[r,a]=Eo(e instanceof Promise?null:e),[c,s]=Eo(t instanceof Promise||!t?null:t),[w,B]=Eo(null),p=_o(null),R=_o(null),C=_o(null);_r(()=>{if(!r)return;let S=Mt(r);return p.current=S?.beginCheckout()??S?.now()??0,S?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{S?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),_r(()=>{let S=!1;return e instanceof Promise?e.then(T=>{S||a(T)}):a(e),()=>{S=!0}},[e]),_r(()=>{let S=!1;if(!t){s(null);return}return t instanceof Promise?t.then(T=>{S||s(T)}):s(t),()=>{S=!0}},[t]),_r(()=>{if(!r){B(null);return}let S=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return B(S),()=>{S.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),_r(()=>{if(!r||!w||R.current===w)return;R.current=w;let S=Mt(r);S?.log({name:"checkout.rendered",stage:"checkout_render"}),S?.performance({stage:"checkout_render",durationMs:S.elapsed(p.current??0),durationMode:"machine"})},[w,r]);let E=Hi(()=>{if(!r||!w||C.current===w)return;C.current=w;let S=Mt(r);S?.log({name:"checkout.interactive",stage:"checkout_interactive"}),S?.performance({stage:"checkout_interactive",durationMs:S.elapsed(p.current??0),durationMode:"machine"})},[w,r]),l=Wi(n?.billingApiUrl),f=Ki(()=>({flopay:r,paypalFlopay:c,elements:w,billingApiUrl:l,reportInteractive:E}),[r,c,w,l,E]);return Yi(xn.Provider,{value:f,children:i})}import Wo,{useCallback as Zn,useEffect as Bn,useMemo as dn,useRef as nn,useState as kt}from"react";import{PaymentAPI as uo}from"@flopay/js";import{SDK_VERSION as Pi,FloPayError as Bt,classifyTelemetryFailure as Ws,resolveBillingApiUrl as Ys,buildCheckoutDisplayData as yi,resolveButtonsLayoutTheme as Gs,resolveTheme as bi}from"@flopay/shared";import"react";import{Fragment as rr,jsx as en,jsxs as Ta}from"react/jsx-runtime";function Gi(){return Ta(rr,{children:[Ta("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:[en("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),en("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",en("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:en("path",{d:"M9 18l6-6-6-6"})})]})}function Ji(){return en(rr,{children:"Go back"})}function Xi(){return en(rr,{children:"Secure card checkout"})}function er(e){return e!==void 0&&(e===""||e===null||e===!1)}function tr({content:e}){return en(rr,{children:e===void 0?en(Gi,{}):e})}function nr({content:e}){return en(rr,{children:e===void 0?en(Ji,{}):e})}function xr({content:e}){return en(rr,{children:e===void 0?en(Xi,{}):e})}import{ExpressCheckoutElement as ri,PaymentElement as ms,Elements as Jn,useElements as $o,useStripe as qo}from"@stripe/react-stripe-js";import{resolveButtonsLayoutTheme as ys,getPostalCodeLabel as zo,getStateLabel as Ha,getStateOptions as fs,COUNTRY_OPTIONS as gs,resolveAVSConfig as hs,isAVSFieldVisible as _e,getStateFromPostalCode as Ka,isPostalCodeSupported as Ps,isValidPostalCode as bs,getPostalCodeExample as vs,filterStripeMethodsByCountry as Cs,getStripeMethodDisplayName as dr,hasVendoredStripeMethodLogo as ws,needsStripeMethodExplicitConfirm as Wa,resolveStripeMethodBrandVariant as Ss,partitionStripeMethods as ks,stripeExpressMethodToOptionKey as Ya}from"@flopay/shared";import{PaymentAPI as Nn,toStripeAppearance as Rs}from"@flopay/js";import{useEffect as Ma,useRef as Tr}from"react";import{jsx as Zi}from"react/jsx-runtime";function xo({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:r,containerStyle:a,onReady:c,onError:s,onValidation:w}){let B=Tr(null),p=Tr(c),R=Tr(s),C=Tr(w);p.current=c,R.current=s,C.current=w;let E=Tr(r);return E.current=r,Ma(()=>{let l=B.current;if(!l)return;let f=!0,S=!1,T=()=>{!f||S||(S=!0,p.current?.())},h=e.on("ready",()=>{T()}),q=e.on("error",oe=>{R.current?.(oe.message??"There was a problem loading the secure card form.")}),Y=e.on("validation",oe=>{C.current?.(oe.message??null)}),ce={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},...E.current?{theme:E.current}:{}};return e.mount(l,ce).then(()=>{T()}).catch(oe=>{f&&R.current?.(oe instanceof Error?oe.message:"Failed to load the secure card form.")}),()=>{f=!1,h(),q(),Y(),e.unmount()}},[e,t,n,i]),Ma(()=>{r&&e.applyTheme?.(r)},[e,r]),Zi("div",{ref:B,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as Ba,jsxs as Qi}from"react/jsx-runtime";function or({children:e,margin:t,icon:n=!0,styleOverride:i}){return Qi("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"}:{},...i??{}},children:[n&&Ba("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Ba("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 Aa={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 Is,{useCallback as ge,useContext as Es,useEffect as mt,useMemo as at,useRef as Le,useState as be}from"react";import{useContext as Mr}from"react";import{resolveBillingApiUrl as es}from"@flopay/shared";function Pn(){return Mr(xn).flopay}function To(){return Mr(xn).paypalFlopay??null}function Mo(){return Mr(xn).elements}function ts(){return Mr(cn)}function Jr(){return Mr(xn).billingApiUrl||es()}import"react";import{jsx as tn,jsxs as ar}from"react/jsx-runtime";var Tn=1200,bn=1500;function vn({status:e,errorMessage:t}){return tn("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:ar("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[ar("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&ar("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[tn("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),tn("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&tn("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:ar("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[tn("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),tn("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&tn("div",{style:{animation:"flopay-shake 0.4s ease"},children:ar("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[tn("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),tn("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),ar("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&tn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&tn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),tn("style",{children:`
|
|
1
|
+
import{useCallback as Zi,useEffect as Ar,useState as Ao,useMemo as Qi,useRef as Fo}from"react";import{resolveBillingApiUrl as es}from"@flopay/shared";import{createContext as Da}from"react";var Tn=Da({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),un=Da({session:null,loading:!1,error:null});var Yi=Symbol.for("@flopay/js.telemetry.bridge.v1"),Gi=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ji(){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 Xi(e){let t=Ji(),n=(o,a)=>o?o.bind(e):a,i=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:i,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,i()-o),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 Qr(e){let t=globalThis[Gi];return Xi(t?.(e)??{})}function Mt(e){if(e)return e[Yi]}import{jsx as ts}from"react/jsx-runtime";function eo({flopay:e,paypalFlopay:t,options:n,children:i}){let[o,a]=Ao(e instanceof Promise?null:e),[c,s]=Ao(t instanceof Promise||!t?null:t),[S,M]=Ao(null),p=Fo(null),R=Fo(null),v=Fo(null);Ar(()=>{if(!o)return;let w=Mt(o);return p.current=w?.beginCheckout()??w?.now()??0,w?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{w?.log({name:"checkout.unmount",stage:"unmount"})}},[o]),Ar(()=>{let w=!1;return e instanceof Promise?e.then(T=>{w||a(T)}):a(e),()=>{w=!0}},[e]),Ar(()=>{let w=!1;if(!t){s(null);return}return t instanceof Promise?t.then(T=>{w||s(T)}):s(t),()=>{w=!0}},[t]),Ar(()=>{if(!o){M(null);return}let w=o.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return M(w),()=>{w.destroy()}},[o,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),Ar(()=>{if(!o||!S||R.current===S)return;R.current=S;let w=Mt(o);w?.log({name:"checkout.rendered",stage:"checkout_render"}),w?.performance({stage:"checkout_render",durationMs:w.elapsed(p.current??0),durationMode:"machine"})},[S,o]);let I=Zi(()=>{if(!o||!S||v.current===S)return;v.current=S;let w=Mt(o);w?.log({name:"checkout.interactive",stage:"checkout_interactive"}),w?.performance({stage:"checkout_interactive",durationMs:w.elapsed(p.current??0),durationMode:"machine"})},[S,o]),l=es(n?.billingApiUrl),m=Qi(()=>({flopay:o,paypalFlopay:c,elements:S,billingApiUrl:l,reportInteractive:I}),[o,c,S,l,I]);return ts(Tn.Provider,{value:m,children:i})}import Qo,{useCallback as tr,useEffect as An,useMemo as pn,useRef as on,useState as wt}from"react";import{PaymentAPI as go}from"@flopay/js";import{SDK_VERSION as ki,FloPayError as Bt,classifyTelemetryFailure as el,resolveBillingApiUrl as tl,buildCheckoutDisplayData as vi,resolveButtonsLayoutTheme as nl,resolveTheme as Ri}from"@flopay/shared";import"react";import{Fragment as lr,jsx as nn,jsxs as La}from"react/jsx-runtime";function ns(){return La(lr,{children:[La("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:[nn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),nn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",nn("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:nn("path",{d:"M9 18l6-6-6-6"})})]})}function rs(){return nn(lr,{children:"Go back"})}function os(){return nn(lr,{children:"Secure card checkout"})}function ar(e){return e!==void 0&&(e===""||e===null||e===!1)}function ir({content:e}){return nn(lr,{children:e===void 0?nn(ns,{}):e})}function sr({content:e}){return nn(lr,{children:e===void 0?nn(rs,{}):e})}function Fr({content:e}){return nn(lr,{children:e===void 0?nn(os,{}):e})}import{ExpressCheckoutElement as ci,PaymentElement as vs,Elements as Qn,useElements as Wo,useStripe as Yo}from"@stripe/react-stripe-js";import{resolveButtonsLayoutTheme as Cs,getPostalCodeLabel as Ho,getStateLabel as Xa,getStateOptions as Ss,COUNTRY_OPTIONS as ws,resolveAVSConfig as ks,isAVSFieldVisible as Te,getStateFromPostalCode as Za,isPostalCodeSupported as Rs,isValidPostalCode as Is,getPostalCodeExample as Es,filterStripeMethodsByCountry as _s,getStripeMethodDisplayName as fr,hasVendoredStripeMethodLogo as xs,needsStripeMethodExplicitConfirm as Qa,resolveStripeMethodBrandVariant as Ts,partitionStripeMethods as Ms,stripeExpressMethodToOptionKey as ei}from"@flopay/shared";import{PaymentAPI as On,toStripeAppearance as Bs}from"@flopay/js";import{useEffect as Na,useRef as Dr}from"react";import{jsx as as}from"react/jsx-runtime";function Do({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:o,containerStyle:a,onReady:c,onError:s,onValidation:S}){let M=Dr(null),p=Dr(c),R=Dr(s),v=Dr(S);p.current=c,R.current=s,v.current=S;let I=Dr(o);return I.current=o,Na(()=>{let l=M.current;if(!l)return;let m=!0,w=!1,T=()=>{!m||w||(w=!0,p.current?.())},y=e.on("ready",()=>{T()}),U=e.on("error",X=>{R.current?.(X.message??"There was a problem loading the secure card form.")}),K=e.on("validation",X=>{v.current?.(X.message??null)}),ue={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},...I.current?{theme:I.current}:{}};return e.mount(l,ue).then(()=>{T()}).catch(X=>{m&&R.current?.(X instanceof Error?X.message:"Failed to load the secure card form.")}),()=>{m=!1,y(),U(),K(),e.unmount()}},[e,t,n,i]),Na(()=>{o&&e.applyTheme?.(o)},[e,o]),as("div",{ref:M,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as Oa,jsxs as is}from"react/jsx-runtime";function cr({children:e,margin:t,icon:n=!0,styleOverride:i}){return is("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"}:{},...i??{}},children:[n&&Oa("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Oa("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 za={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 As,{useCallback as Pe,useContext as Fs,useEffect as yt,useMemo as ot,useRef as Oe,useState as ge}from"react";import{useContext as Lr}from"react";import{resolveBillingApiUrl as ss}from"@flopay/shared";function vn(){return Lr(Tn).flopay}function Lo(){return Lr(Tn).paypalFlopay??null}function No(){return Lr(Tn).elements}function ls(){return Lr(un)}function to(){return Lr(Tn).billingApiUrl||ss()}import"react";import{jsx as rn,jsxs as dr}from"react/jsx-runtime";var Mn=1200,Cn=1500;function Sn({status:e,errorMessage:t}){return rn("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:dr("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[dr("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&dr("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[rn("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),rn("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&rn("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:dr("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[rn("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),rn("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&rn("div",{style:{animation:"flopay-shake 0.4s ease"},children:dr("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[rn("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),rn("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),dr("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&"PROCESSING...",e==="success"&&"PAYMENT SUCCESSFUL",e==="error"&&"PAYMENT FAILED"]}),e==="success"&&rn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:"You will be automatically redirected, do not close or navigate away from this window."}),e==="error"&&t&&rn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),rn("style",{children:`
|
|
2
2
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
3
3
|
@keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
|
|
4
4
|
@keyframes flopay-draw { to { stroke-dashoffset: 0; } }
|
|
5
5
|
@keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
|
|
6
|
-
`})]})})}import{FloPayError as yc,isSetupIntentClientSecret as fc}from"@flopay/shared";function Fa(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 Bo(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 Da(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}))],i=n.reduce((a,c)=>a+(c.overrideAmount??c.totalAmount??0),0),r=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(i*100),currency:r,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,c)=>({uuid:`synthetic-${a.type??"item"}-${c}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??r,metadata:a.metadata??null}))}}function Ao(e,t){return t?{...e,...t}:e}function St(e,t,n){let i=typeof t=="string"?t:t.message,r=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:i,...r?{code:r}:{},...a?{declineCode:a}:{}}}var ns=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Dn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of ns)if(n.test(t))return i;return e}function Xr(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function La(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Na(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Zr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Qr="flopay_recent_completion_";function ir(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Qr+e,JSON.stringify(t))}catch{}}function Oa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Qr+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Qr+e),!1):!0}catch{return!1}}function za(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 eo,useEffect as pt,useMemo as Ar,useRef as We,useState as Gn}from"react";import{loadScript as os}from"@paypal/paypal-js";import{PaymentAPI as Fo}from"@flopay/js";import{FloPayError as Ua,SDK_VERSION as as,generateIdempotencyKey as is,normalizeGatewayEnvironment as ss}from"@flopay/shared";function ut(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function rs(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 Yn(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 Yn(t.code)??Yn(t.type)??Yn(t.name)}function sr(e){if(!(typeof e!="object"||e===null))return Yn(e.decline_code)}function Br(e){return typeof e!="object"||e===null?!1:Yn(e.type)?.toLowerCase()==="card_error"||sr(e)!==void 0}function Ln(e){let t=rs(e)?.toLowerCase()??"",i=`${Mn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as lr,jsxs as Do}from"react/jsx-runtime";var to=45,ls=1e3,cs=11e3,ds=["https://www.paypal.com","https://www.sandbox.paypal.com"],$a="We couldn't open PayPal. Try again or choose another payment method.",us={width:"100%",minHeight:to,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 qa(e){return e.includes("No ack for postMessage init()")&&ds.some(t=>e.includes(t))&&e.includes("10000ms")}function ps(e){return e?`${$a} Allow pop-ups for this site, then try again.`:$a}function ja({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:r,environment:a,currency:c,isSubscription:s,onTokenizedBody:w,onComplete:B,onErrorChange:p,onDecline:R,onTechnicalFailure:C,isProcessing:E=!1,onLoadStateChange:l,onInitializationStateChange:f,allowAutomaticRetry:S=!0,onButtonClick:T,runBeforeButtonClick:h,session:q,existingOrderId:Y,telemetry:ce,telemetryContext:oe,debug:D=!1}){let X=Pn(),j=Ar(()=>{if(X)return null;let y=Yr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:as,enabled:ce!==!1});return y.setCheckoutContext(oe??{}),y.beginCheckout(oe??{}),y},[n,X,ce,oe?.checkoutMode,oe?.layout]),de=Ar(()=>Mt(X),[X]);pt(()=>()=>{j&&j.flush().catch(()=>{}).finally(()=>j.destroy())},[j]);let z=Ar(()=>({error:y=>{de?de.error(y):j?.error(y)},log:y=>{de?de.log(y):j?.log(y)},performance:y=>{de?de.performance(y):j?.performance(y)},terminal:y=>{de?de.terminal(y):j?.terminal(y)},startTiming:()=>de?.now()??j?.now()??0,elapsed:y=>de?.elapsed(y)??Math.max(0,(j?.now()??y)-y)}),[de,j]),V=We(null),ae=We(0),Be=We(null),fe=We(!1),[ye,Z]=Gn(!1),[ue,he]=Gn(!1),[ie,Fe]=Gn(0),ke=We(0),[ve,k]=Gn(!1),ne=We(!1),se=We(!1),[Ne,De]=Gn(!1),[G,x]=Gn(!1),H=Ar(()=>n.replace(/\/+$/,""),[n]),le=Ar(()=>JSON.stringify([H,r,c,a??"",s,e,Y??""]),[H,r,c,a,Y,s,e]),Re=We(le),gt=Re.current!==le,[Xe,Je]=Gn([]),m=y=>{D&&Je(Ie=>[...Ie,`${new Date().toISOString().slice(11,23)} ${y}`])},Ue=We(w),Oe=We(B),Ve=We(p),$e=We(R),Kt=We(C),bt=We(T),It=We(l),g=We(f),Ce=We(h),qe=We(q),st=We(i),tt=We(t),Ze=We(null),Ye=We(0),Pe=We(null),vt=We(null),je=We(new Map),Dt=We(new Map),Et=We(!1);pt(()=>(Et.current=!0,()=>{Et.current=!1}),[]),pt(()=>{Ue.current=w},[w]),pt(()=>{Oe.current=B},[B]),pt(()=>{Ve.current=p},[p]),pt(()=>{$e.current=R},[R]),pt(()=>{Kt.current=C},[C]),pt(()=>{bt.current=T},[T]),pt(()=>{It.current=l},[l]),pt(()=>{g.current=f},[f]),pt(()=>{Ce.current=h},[h]),pt(()=>{qe.current=q},[q]),pt(()=>{st.current=i},[i]),pt(()=>{tt.current=t},[t]),pt(()=>{ke.current=ie},[ie]),pt(()=>{ve&&Be.current?.focus()},[ve,ie]);let un=eo(()=>{window.setTimeout(()=>{Be.current?.focus()},0)},[]),Rn=eo(()=>{Z(!1),Fe(y=>y+1)},[]),In=eo(()=>{k(!1),(V.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??V.current)?.focus?.()},[]);pt(()=>{!ye||!fe.current||(fe.current=!1,In())},[In,ye,ie]);let $n=eo((y,Ie)=>{let lt=Kt.current;if(lt){lt("paypal",y,Ie);return}Ve.current?.(ps(Ie?.popupBlocked??Ln(y)))},[]),ht=()=>{Pe.current?.timer&&(clearTimeout(Pe.current.timer),Pe.current.timer=null)},Lt=()=>{ht();let y=Ye.current+1;return Ye.current=y,vt.current=null,Pe.current={generation:y,timer:null,yieldedControl:!1},k(!1),y},Ft=y=>y!==void 0&&Pe.current?.generation!==y?!1:(ht(),Pe.current=null,vt.current=null,!0),Wt=y=>{let Ie=y?.generation??Pe.current?.generation??Ye.current;(!y?.generation||Pe.current?.generation===Ie)&&(ht(),Pe.current=null),vt.current=Ie,y?.showRetry&&k(!0),y?.remount&&Rn(),y?.focus!==!1&&un()},rn=y=>Pe.current?.generation===y&&vt.current!==y,pn=y=>{typeof document<"u"&&document.visibilityState!=="visible"||(ht(),y.timer=setTimeout(()=>{Pe.current?.generation===y.generation&&(Pe.current=null,vt.current=y.generation,$n(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),k(!0),Rn(),un())},600))},K=()=>{let y=Pe.current;y?.yieldedControl&&pn(y)},An=()=>{let y=Pe.current;y&&(y.yieldedControl=!0,ht())},mn=y=>{let Ie=Ze.current;return Ie&&Dt.current.set(y,Ie),y};pt(()=>{let y=()=>{document.visibilityState==="visible"?K():An()};return document.addEventListener("visibilitychange",y),window.addEventListener("focus",K),window.addEventListener("blur",An),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("focus",K),window.removeEventListener("blur",An),ht()}},[]),pt(()=>{Re.current!==le&&(Re.current=le,ne.current=!1,se.current=!1,Z(!1),he(!1),De(!1),g.current?.("loading"))},[le]),pt(()=>{ut(()=>It.current?.(ye&&!Ne))},[ye,Ne]);let Nt=ss(a);pt(()=>{let y=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",Ie=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(m(`mount clientId=${y} env=${a??"(unset)"}\u2192${Nt??"live"} ccy=${c} sub=${s}`),m(`ua=${Ie.slice(0,80)}${Ie.length>80?"\u2026":""}`),!r){m("FAIL: clientId empty \u2014 gateway misconfigured"),De(!0),z.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(!V.current){m("FAIL: containerRef not attached");return}ae.current=z.startTiming(),z.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let lt=!1,En=!1,Ee=()=>lt||En,Fn,yn=!1,qn=()=>{Fn=is(),Fn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),yn=!0},fn=null,Ot=!1,At=null,we=!1,yt=()=>{!At||we||(we=!0,At.close().catch(()=>{}))},rt=null,on=()=>{rt!==null&&(z.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"overlay_return",durationMs:z.elapsed(rt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),rt=null)},Yt=!1,Pt=V.current,jt=null,Ct=null,an=[],gn=A=>{if(!A||typeof A.getBoundingClientRect!="function")return"(no rect)";let P=A.getBoundingClientRect();return`${Math.round(P.width)}\xD7${Math.round(P.height)}`},_n=A=>{if(!A)return"(empty)";try{let P=new URL(A,typeof window<"u"?window.location.href:"https://localhost"),F=P.pathname.toLowerCase();return F.includes("checkcaptcha")||F.includes("captcha")?`CAPTCHA(${P.host}${F})`:F.includes("risk")||F.includes("challenge")?`RISK(${P.host}${F})`:F.includes("smart/buttons")?`smart-buttons(${P.host})`:`${P.host}${F}`.slice(0,100)}catch{return A.slice(0,80)}},hn=A=>{let P=A.getAttribute("src"),F=A.getAttribute("srcdoc"),me=A.getAttribute("name"),Me=A.getAttribute("sandbox"),ze=[];return P&&ze.push(`src=${_n(P)}`),F&&ze.push(`srcdoc[${F.length}ch]`),!P&&!F&&ze.push("src=(empty) srcdoc=(empty)"),me&&ze.push(`name=${me.slice(0,40)}`),Me!==null&&ze.push(`sandbox="${Me.slice(0,40)}"`),ze.join(" ")},Vt=A=>{if(!(A instanceof HTMLIFrameElement))return"";try{let P=A.contentDocument;if(!P)return"cd=null";let F=P.body?.children.length??0,me=P.body?.innerHTML.length??0,Me=P.head?.innerHTML.length??0;return`cd=same-origin readyState=${P.readyState} body[${F}children,${me}ch] head[${Me}ch]`}catch(P){return`cd=cross-origin(${P.message.slice(0,30)})`}},He=[],Ht=A=>{if(Ee())return;let P=A.message??String(A.error??"(no message)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(m(`window:error ${P.slice(0,140)}`),He.push(P))},zt=A=>{if(Ee())return;let P=A.reason instanceof Error?A.reason.message:String(A.reason??"(no reason)");P&&(P.toLowerCase().includes("paypal")||P.toLowerCase().includes("zoid")||P.toLowerCase().includes("postrobot")||P.toLowerCase().includes("storage"))&&(m(`window:rejection ${P.slice(0,140)}`),He.push(P))};D&&typeof window<"u"&&(window.addEventListener("error",Ht),window.addEventListener("unhandledrejection",zt));let Ut={value:0};if(D&&typeof PerformanceObserver<"u")try{Ct=new PerformanceObserver(A=>{if(!Ee())for(let P of A.getEntries()){if(!P.name.toLowerCase().includes("paypal"))continue;Ut.value+=1;let F=Math.round(P.duration);m(`net ${F}ms ${P.name.slice(0,90)}`)}}),Ct.observe({type:"resource",buffered:!0})}catch{}let _=()=>{for(jt?.disconnect(),jt=null,Ct?.disconnect(),Ct=null;an.length;)clearTimeout(an.pop());D&&typeof window<"u"&&(window.removeEventListener("error",Ht),window.removeEventListener("unhandledrejection",zt))},L=A=>{if(!A)return!1;let P=A.toLowerCase();return P.includes("zoid destroyed")||P.includes("destroyed all components")||P.includes("window closed")||P.includes("detected container element removed")},N=A=>{if(Ee()||L(A))return;let P=Dn(A)??A;ut(()=>Ve.current?.(P))},M=A=>{lt||(De(!0),A.includes("paypal_ineligible")||z.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:",A))},u=(A,P=!1)=>{if(lt)return;let F=ne.current||!S;if(Ot)return;Ot=!0,En=!0,_(),yt();let me=P||qa(A);if(me&&S&&!ne.current){ne.current=!0,Z(!1),x(!1),he(!0),g.current?.("retrying"),fn=setTimeout(()=>{lt||Fe(Me=>Me+1)},ls);return}if(me||F){if(Z(!1),x(!1),he(!1),De(!0),g.current?.("exhausted"),!se.current){se.current=!0;let Me=qa(A)?"paypal_init_timeout":P?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",Me)}return}M(A)};De(!1);let $=async(A,P=Ze.current)=>{if(Ee())return;let F=P?.sessionId??e;if(Ue.current){await Ue.current(A,{sessionId:F,accountPatch:P?.accountPatch,nonce:P?.nonce});return}let me=z.startTiming();z.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Me=()=>{z.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"processing",durationMs:z.elapsed(me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let ze=qe.current,sn=P?.accountPatch?.email??st.current,I=P?.accountPatch?.userId??ze?.customer?.id??ze?.accountData?.userId??"",Q=await new Fo(H,{telemetry:!1}).processPayment(I,{sessionId:F,nonce:P?.nonce??tt.current,tokenizedData:A,accountData:{userId:I,email:sn??ze?.customer?.email??"",firstName:P?.accountPatch?.firstName??ze?.customer?.firstName??ze?.accountData?.firstName??"",lastName:P?.accountPatch?.lastName??ze?.customer?.lastName??ze?.accountData?.lastName??"",country:P?.accountPatch?.country??ze?.customer?.country??ze?.accountData?.country??void 0,zip:P?.accountPatch?.zip??ze?.customer?.zip??ze?.accountData?.zip??void 0}});if(Q.ok){if(En||lt&&Et.current)return;Me(),z.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut(()=>Oe.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ee())return;let Se=await Q.json().catch(()=>null),Gt=Se?.message??"PayPal payment failed.",Jt=Dn(Gt)??Gt;Me(),Q.status===400&&(typeof Se?.declineCode=="string"||!Array.isArray(Se?.fields))?z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Q.status===400||Q.status===422?z.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):z.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Q.status>=500?"5xx":Q.status>=400?"4xx":Q.status>=300?"3xx":"unknown",failureCategory:Q.status>=500?"server_error":void 0}),N(Jt),ut(()=>$e.current?.(St("paypal",Jt,{code:Se?.code,declineCode:Se?.declineCode})));return}catch(ze){if(Ee())return;Me(),z.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let sn=ze instanceof Error?ze.message:"PayPal payment failed.",I=Dn(sn)??sn;N(I),ut(()=>$e.current?.(St("paypal",I)));return}},b=()=>new Ua("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Te=A=>Ee()?Promise.reject(b()):Promise.resolve(A),W=async A=>{if(Ee())throw b();yn||qn();let P=Ze.current,F=P?.sessionId??e,me=P?.nonce??tt.current;z.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Me=await new Fo(H,{telemetry:!1}).createSessionIntent(F,me??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Fn});if(Ee())throw b();if(Me.provider!=="paypal")throw new Error(A);return z.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Me.providerObjectId},Ke=(A,P)=>{let F=P?.nonce??tt.current;if(!F)return;let me=P?.sessionId??e,Me=sr(A)??Mn(A)??"provider_declined";new Fo(H,{telemetry:!1}).reportSessionIntentDecline(me,F,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Me}).catch(()=>{})},J=ie;m("loadScript:scheduled (deferred 1 tick)");let $t=null,ot=setTimeout(()=>{if(lt){m("loadScript:skipped (cancelled before defer ran)");return}m("loadScript:start");let A=Nt==="live"?"production":Nt;$t=os({clientId:r,currency:c,intent:s?"subscription":"capture",vault:s?!0:void 0,...A?{environment:A}:{},...A==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),$t.then(P=>{if(m(`loadScript:resolved inactive=${Ee()} ns=${!!P} buttons=${!!P?.Buttons}`),Ee())return;if(!P?.Buttons){m("FAIL: namespace missing Buttons factory"),u("PayPal SDK did not expose the Buttons factory.");return}z.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let F=async I=>{if(Ee()||ke.current!==J)return;let pe=I.subscriptionID??I.orderID??"",Q=pe?Dt.current.get(pe):je.current.get(J);if(!(!Q||!rn(Q.generation))&&Ft(Q.generation)){Dt.current.delete(pe),je.current.delete(Q.surfaceKey),on();try{if(x(!0),ut(()=>Ve.current?.(null)),!pe)throw new Ua("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await $({id:pe,isPaypal:!0},Q)}catch(Se){N(Se instanceof Error?Se.message:"PayPal capture failed.")}finally{Ee()||x(!1)}}},me=P.Buttons({style:{layout:"horizontal",height:to,tagline:!1},onClick:async(I,pe)=>{if(Ee()){await pe.reject();return}qn();let Q=Ce.current,Se={};if(Q)try{let Qe=await Q("paypal");if(Ee()){await pe.reject();return}if(!Qe.proceed){Ze.current=null,je.current.delete(J),await pe.reject();return}Se={sessionId:Qe.sessionId,accountPatch:Qe.accountPatch,nonce:Qe.nonce}}catch(Qe){m(`onClick:runBeforeButtonClick rejected msg=${(Qe instanceof Error?Qe.message:String(Qe)).slice(0,120)}`),Ze.current=null,je.current.delete(J),await pe.reject();return}ut(()=>bt.current?.("paypal"));let Jt={generation:Lt(),surfaceKey:J,...Se};Ze.current=Jt,je.current.set(J,Jt),await pe.resolve(),z.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),z.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),z.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),rt=z.startTiming()},createOrder:s?void 0:Y?()=>Te(Y).then(mn):()=>W("Failed to create PayPal order.").then(mn),createSubscription:s?Y?()=>Te(Y).then(mn):()=>W("Failed to create PayPal subscription.").then(mn):void 0,onApprove:F,onCancel:()=>{if(Ee())return;let I=je.current.get(J)??Ze.current;I&&je.current.delete(I.surfaceKey),Ze.current=null,on(),z.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe.current=!0,Wt({generation:I?.generation,remount:!0,focus:!1})},onError:I=>{if(Ee()||ke.current!==J)return;let pe=I instanceof Error?I.message:"PayPal failed to render.";if(m(`onError rendered=${Yt} msg=${pe.slice(0,120)}`),Yt){let Q=je.current.get(J)??Ze.current;if(Q&&!rn(Q.generation)||!Q&&vt.current===Ye.current)return;if(L(pe)){Ft(Q?.generation);return}if(on(),Br(I)){z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ke(I,Q),ut(()=>$e.current?.(St("paypal",pe))),Q&&je.current.delete(Q.surfaceKey),Ze.current=null,Ft(Q?.generation);return}let Se=pe.toLowerCase();z.error({errorCode:Se.includes("popup")&&Se.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Q&&je.current.delete(Q.surfaceKey),Ze.current=null,Wt({generation:Q?.generation,remount:!0,showRetry:!0,focus:!0}),$n(I,{code:"paypal_runtime_failed"});return}u(pe)}}),Me=me.isEligible();if(m(`isEligible=${Me}`),z.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Me){Z(!1),u("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}At=me,D&&m(`container:dims ${gn(Pt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),D&&typeof MutationObserver<"u"&&(jt=new MutationObserver(I=>{if(!Ee()){for(let pe of I)if(pe.type==="childList")pe.addedNodes.forEach(Q=>{if(!(Q instanceof Element))return;let Se=Q.tagName.toLowerCase(),Gt=(Q.getAttribute("title")??"").slice(0,40),Jt=Se==="iframe"?` ${hn(Q)}`:"";m(`child+ ${Se}${Gt?` title="${Gt}"`:""}${Jt} dims=${gn(Q)}`)});else if(pe.type==="attributes"&&pe.target instanceof Element){let Q=pe.target;if(Q.tagName.toLowerCase()!=="iframe")continue;let Se=pe.attributeName;(Se==="src"||Se==="srcdoc")&&m(`attr~ iframe ${Se}=${Se==="srcdoc"?`[${(Q.getAttribute("srcdoc")??"").length}ch]`:_n(Q.getAttribute("src"))} dims=${gn(Q)}`)}}}),jt.observe(Pt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let sn=I=>{if(Ee()||Yt)return;let pe=Pt.querySelectorAll("iframe"),Q=typeof document<"u"&&"hasStorageAccess"in document;m(`watchdog:${I} container=${gn(Pt)} children=${Pt.childElementCount} iframes=${pe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${Q} paypalNetRequests=${Ut.value}`),pe.forEach((Se,Gt)=>{let Jt=(Se.getAttribute("title")??"").slice(0,40);m(` iframe[${Gt}] ${gn(Se)}${Jt?` title="${Jt}"`:""} ${hn(Se)}`);let Qe=Vt(Se);Qe&&m(` ${Qe}`)}),He.length===0&&m(" (no PayPal/zoid window errors captured)")};D&&(an.push(setTimeout(()=>sn("3s"),3e3)),an.push(setTimeout(()=>sn("8s"),8e3)),an.push(setTimeout(()=>sn("15s"),15e3))),m("render:start"),an.push(setTimeout(()=>{Ee()||Yt||(m("watchdog:11s retryable render timeout"),u("PayPal Buttons render did not settle within 11000ms.",!0))},cs)),me.render(Pt).then(()=>{if(m(`render:resolved inactive=${Ee()}`),_(),Ee()){yt();return}Yt=!0,Z(!0),he(!1),g.current?.("ready"),z.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"provider_ready",durationMs:z.elapsed(ae.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(I=>{let pe=I instanceof Error?I.message:"PayPal failed to render.";m(`render:rejected msg=${pe.slice(0,120)}`),_(),u(pe)})}).catch(P=>{let F=P instanceof Error?P.message:"PayPal SDK failed to load.";m(`loadScript:rejected msg=${F.slice(0,120)}`),u(F)})},0);return()=>{lt=!0,clearTimeout(ot),fn&&clearTimeout(fn),_(),yt()}},[S,H,r,c,a,s,e,Y,ie,z]);let nt=D?Do("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Ne?"#fef2f2":"#f3f4f6",border:`1px solid ${Ne?"#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=${ye} failed=${Ne})`,Xe.length===0?`
|
|
6
|
+
`})]})})}import{FloPayError as Cc,isSetupIntentClientSecret as Sc}from"@flopay/shared";function Ua(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 Oo(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 $a(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}))],i=n.reduce((a,c)=>a+(c.overrideAmount??c.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(i*100),currency:o,status:"open",customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,c)=>({uuid:`synthetic-${a.type??"item"}-${c}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function zo(e,t){return t?{...e,...t}:e}function St(e,t,n){let i=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:i,...o?{code:o}:{},...a?{declineCode:a}:{}}}var cs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Ln(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of cs)if(n.test(t))return i;return e}function no(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function qa(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ja(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function ro(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var oo="flopay_recent_completion_";function ur(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(oo+e,JSON.stringify(t))}catch{}}function Va(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(oo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(oo+e),!1):!0}catch{return!1}}function Ha(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 ao,useEffect as mt,useMemo as Or,useRef as Ye,useState as Zn}from"react";import{loadScript as us}from"@paypal/paypal-js";import{PaymentAPI as Uo}from"@flopay/js";import{FloPayError as Ka,SDK_VERSION as ps,generateIdempotencyKey as ms,normalizeGatewayEnvironment as ys}from"@flopay/shared";function pt(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}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 Xn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Bn(e){if(typeof e!="object"||e===null)return;let t=e;return Xn(t.code)??Xn(t.type)??Xn(t.name)}function pr(e){if(!(typeof e!="object"||e===null))return Xn(e.decline_code)}function Nr(e){return typeof e!="object"||e===null?!1:Xn(e.type)?.toLowerCase()==="card_error"||pr(e)!==void 0}function Nn(e){let t=ds(e)?.toLowerCase()??"",i=`${Bn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as mr,jsxs as $o}from"react/jsx-runtime";var io=45,fs=1e3,gs=11e3,hs=["https://www.paypal.com","https://www.sandbox.paypal.com"],Wa="We couldn't open PayPal. Try again or choose another payment method.",Ps={width:"100%",minHeight:io,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 Ya(e){return e.includes("No ack for postMessage init()")&&hs.some(t=>e.includes(t))&&e.includes("10000ms")}function bs(e){return e?`${Wa} Allow pop-ups for this site, then try again.`:Wa}function Ga({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:o,environment:a,currency:c,isSubscription:s,onTokenizedBody:S,onComplete:M,onErrorChange:p,onDecline:R,onTechnicalFailure:v,isProcessing:I=!1,onLoadStateChange:l,onInitializationStateChange:m,allowAutomaticRetry:w=!0,onButtonClick:T,runBeforeButtonClick:y,session:U,existingOrderId:K,telemetry:ue,telemetryContext:X,debug:B=!1}){let G=vn(),$=Or(()=>{if(G)return null;let E=Qr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:ps,enabled:ue!==!1});return E.setCheckoutContext(X??{}),E.beginCheckout(X??{}),E},[n,G,ue,X?.checkoutMode,X?.layout]),pe=Or(()=>Mt(G),[G]);mt(()=>()=>{$&&$.flush().catch(()=>{}).finally(()=>$.destroy())},[$]);let N=Or(()=>({error:E=>{pe?pe.error(E):$?.error(E)},log:E=>{pe?pe.log(E):$?.log(E)},performance:E=>{pe?pe.performance(E):$?.performance(E)},terminal:E=>{pe?pe.terminal(E):$?.terminal(E)},startTiming:()=>pe?.now()??$?.now()??0,elapsed:E=>pe?.elapsed(E)??Math.max(0,($?.now()??E)-E)}),[pe,$]),q=Ye(null),re=Ye(0),Ae=Ye(null),fe=Ye(!1),[ye,J]=Zn(!1),[me,be]=Zn(!1),[oe,De]=Zn(0),Re=Ye(0),[Se,k]=Zn(!1),ee=Ye(!1),ie=Ye(!1),[ze,Le]=Zn(!1),[W,x]=Zn(!1),j=Or(()=>n.replace(/\/+$/,""),[n]),se=Or(()=>JSON.stringify([j,o,c,a??"",s,e,K??""]),[j,o,c,a,K,s,e]),Ie=Ye(se),it=Ie.current!==se,[Qe,Ze]=Zn([]),u=E=>{B&&Ze(Je=>[...Je,`${new Date().toISOString().slice(11,23)} ${E}`])},$e=Ye(S),Ue=Ye(M),We=Ye(p),qe=Ye(R),Yt=Ye(v),Pt=Ye(T),Rt=Ye(l),f=Ye(m),we=Ye(y),je=Ye(U),st=Ye(i),rt=Ye(t),et=Ye(null),Ge=Ye(0),ve=Ye(null),bt=Ye(null),Ve=Ye(new Map),Ut=Ye(new Map),It=Ye(!1);mt(()=>(It.current=!0,()=>{It.current=!1}),[]),mt(()=>{$e.current=S},[S]),mt(()=>{Ue.current=M},[M]),mt(()=>{We.current=p},[p]),mt(()=>{qe.current=R},[R]),mt(()=>{Yt.current=v},[v]),mt(()=>{Pt.current=T},[T]),mt(()=>{Rt.current=l},[l]),mt(()=>{f.current=m},[m]),mt(()=>{we.current=y},[y]),mt(()=>{je.current=U},[U]),mt(()=>{st.current=i},[i]),mt(()=>{rt.current=t},[t]),mt(()=>{Re.current=oe},[oe]),mt(()=>{Se&&Ae.current?.focus()},[Se,oe]);let mn=ao(()=>{window.setTimeout(()=>{Ae.current?.focus()},0)},[]),En=ao(()=>{J(!1),De(E=>E+1)},[]),_n=ao(()=>{k(!1),(q.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??q.current)?.focus?.()},[]);mt(()=>{!ye||!fe.current||(fe.current=!1,_n())},[_n,ye,oe]);let qn=ao((E,Je)=>{let ke=Yt.current;if(ke){ke("paypal",E,Je);return}We.current?.(bs(Je?.popupBlocked??Nn(E)))},[]),ht=()=>{ve.current?.timer&&(clearTimeout(ve.current.timer),ve.current.timer=null)},$t=()=>{ht();let E=Ge.current+1;return Ge.current=E,bt.current=null,ve.current={generation:E,timer:null,yieldedControl:!1},k(!1),E},Dt=E=>E!==void 0&&ve.current?.generation!==E?!1:(ht(),ve.current=null,bt.current=null,!0),Gt=E=>{let Je=E?.generation??ve.current?.generation??Ge.current;(!E?.generation||ve.current?.generation===Je)&&(ht(),ve.current=null),bt.current=Je,E?.showRetry&&k(!0),E?.remount&&En(),E?.focus!==!1&&mn()},an=E=>ve.current?.generation===E&&bt.current!==E,yn=E=>{typeof document<"u"&&document.visibilityState!=="visible"||(ht(),E.timer=setTimeout(()=>{ve.current?.generation===E.generation&&(ve.current=null,bt.current=E.generation,qn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),k(!0),En(),mn())},600))},V=()=>{let E=ve.current;E?.yieldedControl&&yn(E)},Fn=()=>{let E=ve.current;E&&(E.yieldedControl=!0,ht())},fn=E=>{let Je=et.current;return Je&&Ut.current.set(E,Je),E};mt(()=>{let E=()=>{document.visibilityState==="visible"?V():Fn()};return document.addEventListener("visibilitychange",E),window.addEventListener("focus",V),window.addEventListener("blur",Fn),()=>{document.removeEventListener("visibilitychange",E),window.removeEventListener("focus",V),window.removeEventListener("blur",Fn),ht()}},[]),mt(()=>{Ie.current!==se&&(Ie.current=se,ee.current=!1,ie.current=!1,J(!1),be(!1),Le(!1),f.current?.("loading"))},[se]),mt(()=>{pt(()=>Rt.current?.(ye&&!ze))},[ye,ze]);let qt=ys(a);mt(()=>{let E=o?`${o.slice(0,6)}\u2026(len ${o.length})`:"(empty)",Je=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(u(`mount clientId=${E} env=${a??"(unset)"}\u2192${qt??"live"} ccy=${c} sub=${s}`),u(`ua=${Je.slice(0,80)}${Je.length>80?"\u2026":""}`),!o){u("FAIL: clientId empty \u2014 gateway misconfigured"),Le(!0),N.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(!q.current){u("FAIL: containerRef not attached");return}re.current=N.startTiming(),N.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ke=!1,Dn=!1,He=()=>ke||Dn,jn,gn=!1,hn=()=>{jn=ms(),jn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),gn=!0},tt=null,Et=!1,jt=null,Lt=!1,Jt=()=>{!jt||Lt||(Lt=!0,jt.close().catch(()=>{}))},sn=null,xn=()=>{sn!==null&&(N.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"overlay_return",durationMs:N.elapsed(sn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),sn=null)},Xt=!1,Nt=q.current,Zt=null,he=null,ft=[],lt=F=>{if(!F||typeof F.getBoundingClientRect!="function")return"(no rect)";let h=F.getBoundingClientRect();return`${Math.round(h.width)}\xD7${Math.round(h.height)}`},Pn=F=>{if(!F)return"(empty)";try{let h=new URL(F,typeof window<"u"?window.location.href:"https://localhost"),C=h.pathname.toLowerCase();return C.includes("checkcaptcha")||C.includes("captcha")?`CAPTCHA(${h.host}${C})`:C.includes("risk")||C.includes("challenge")?`RISK(${h.host}${C})`:C.includes("smart/buttons")?`smart-buttons(${h.host})`:`${h.host}${C}`.slice(0,100)}catch{return F.slice(0,80)}},Vn=F=>{let h=F.getAttribute("src"),C=F.getAttribute("srcdoc"),ce=F.getAttribute("name"),H=F.getAttribute("sandbox"),Ke=[];return h&&Ke.push(`src=${Pn(h)}`),C&&Ke.push(`srcdoc[${C.length}ch]`),!h&&!C&&Ke.push("src=(empty) srcdoc=(empty)"),ce&&Ke.push(`name=${ce.slice(0,40)}`),H!==null&&Ke.push(`sandbox="${H.slice(0,40)}"`),Ke.join(" ")},Ot=F=>{if(!(F instanceof HTMLIFrameElement))return"";try{let h=F.contentDocument;if(!h)return"cd=null";let C=h.body?.children.length??0,ce=h.body?.innerHTML.length??0,H=h.head?.innerHTML.length??0;return`cd=same-origin readyState=${h.readyState} body[${C}children,${ce}ch] head[${H}ch]`}catch(h){return`cd=cross-origin(${h.message.slice(0,30)})`}},Ht=[],vt=F=>{if(He())return;let h=F.message??String(F.error??"(no message)");h&&(h.toLowerCase().includes("paypal")||h.toLowerCase().includes("zoid")||h.toLowerCase().includes("postrobot")||h.toLowerCase().includes("storage"))&&(u(`window:error ${h.slice(0,140)}`),Ht.push(h))},nr=F=>{if(He())return;let h=F.reason instanceof Error?F.reason.message:String(F.reason??"(no reason)");h&&(h.toLowerCase().includes("paypal")||h.toLowerCase().includes("zoid")||h.toLowerCase().includes("postrobot")||h.toLowerCase().includes("storage"))&&(u(`window:rejection ${h.slice(0,140)}`),Ht.push(h))};B&&typeof window<"u"&&(window.addEventListener("error",vt),window.addEventListener("unhandledrejection",nr));let Kt={value:0};if(B&&typeof PerformanceObserver<"u")try{he=new PerformanceObserver(F=>{if(!He())for(let h of F.getEntries()){if(!h.name.toLowerCase().includes("paypal"))continue;Kt.value+=1;let C=Math.round(h.duration);u(`net ${C}ms ${h.name.slice(0,90)}`)}}),he.observe({type:"resource",buffered:!0})}catch{}let _=()=>{for(Zt?.disconnect(),Zt=null,he?.disconnect(),he=null;ft.length;)clearTimeout(ft.pop());B&&typeof window<"u"&&(window.removeEventListener("error",vt),window.removeEventListener("unhandledrejection",nr))},Y=F=>{if(!F)return!1;let h=F.toLowerCase();return h.includes("zoid destroyed")||h.includes("destroyed all components")||h.includes("window closed")||h.includes("detected container element removed")},O=F=>{if(He()||Y(F))return;let h=Ln(F)??F;pt(()=>We.current?.(h))},P=F=>{ke||(Le(!0),F.includes("paypal_ineligible")||N.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:",F))},ae=(F,h=!1)=>{if(ke)return;let C=ee.current||!w;if(Et)return;Et=!0,Dn=!0,_(),Jt();let ce=h||Ya(F);if(ce&&w&&!ee.current){ee.current=!0,J(!1),x(!1),be(!0),f.current?.("retrying"),tt=setTimeout(()=>{ke||De(H=>H+1)},fs);return}if(ce||C){if(J(!1),x(!1),be(!1),Le(!0),f.current?.("exhausted"),!ie.current){ie.current=!0;let H=Ya(F)?"paypal_init_timeout":h?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",H)}return}P(F)};Le(!1);let L=async(F,h=et.current)=>{if(He())return;let C=h?.sessionId??e;if($e.current){await $e.current(F,{sessionId:C,accountPatch:h?.accountPatch,nonce:h?.nonce});return}let ce=N.startTiming();N.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let H=()=>{N.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"processing",durationMs:N.elapsed(ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Ke=je.current,ct=h?.accountPatch?.email??st.current,xe=h?.accountPatch?.userId??Ke?.customer?.id??Ke?.accountData?.userId??"",te=await new Uo(j,{telemetry:!1}).processPayment(xe,{sessionId:C,nonce:h?.nonce??rt.current,tokenizedData:F,accountData:{userId:xe,email:ct??Ke?.customer?.email??"",firstName:h?.accountPatch?.firstName??Ke?.customer?.firstName??Ke?.accountData?.firstName??"",lastName:h?.accountPatch?.lastName??Ke?.customer?.lastName??Ke?.accountData?.lastName??"",country:h?.accountPatch?.country??Ke?.customer?.country??Ke?.accountData?.country??void 0,zip:h?.accountPatch?.zip??Ke?.customer?.zip??Ke?.accountData?.zip??void 0}});if(te.ok){if(Dn||ke&&It.current)return;H(),N.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),pt(()=>Ue.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(He())return;let Be=await te.json().catch(()=>null),ln=Be?.message??"PayPal payment failed.",Wt=Ln(ln)??ln;H(),te.status===400&&(typeof Be?.declineCode=="string"||!Array.isArray(Be?.fields))?N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):te.status===400||te.status===422?N.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):N.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:te.status>=500?"5xx":te.status>=400?"4xx":te.status>=300?"3xx":"unknown",failureCategory:te.status>=500?"server_error":void 0}),O(Wt),pt(()=>qe.current?.(St("paypal",Wt,{code:Be?.code,declineCode:Be?.declineCode})));return}catch(Ke){if(He())return;H(),N.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let ct=Ke instanceof Error?Ke.message:"PayPal payment failed.",xe=Ln(ct)??ct;O(xe),pt(()=>qe.current?.(St("paypal",xe)));return}},g=()=>new Ka("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),_e=F=>He()?Promise.reject(g()):Promise.resolve(F),le=async F=>{if(He())throw g();gn||hn();let h=et.current,C=h?.sessionId??e,ce=h?.nonce??rt.current;N.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let H=await new Uo(j,{telemetry:!1}).createSessionIntent(C,ce??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:jn});if(He())throw g();if(H.provider!=="paypal")throw new Error(F);return N.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),H.providerObjectId},Ne=(F,h)=>{let C=h?.nonce??rt.current;if(!C)return;let ce=h?.sessionId??e,H=pr(F)??Bn(F)??"provider_declined";new Uo(j,{telemetry:!1}).reportSessionIntentDecline(ce,C,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:H}).catch(()=>{})},Ee=oe;u("loadScript:scheduled (deferred 1 tick)");let A=null,Ft=setTimeout(()=>{if(ke){u("loadScript:skipped (cancelled before defer ran)");return}u("loadScript:start");let F=qt==="live"?"production":qt;A=us({clientId:o,currency:c,intent:s?"subscription":"capture",vault:s?!0:void 0,...F?{environment:F}:{},...F==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),A.then(h=>{if(u(`loadScript:resolved inactive=${He()} ns=${!!h} buttons=${!!h?.Buttons}`),He())return;if(!h?.Buttons){u("FAIL: namespace missing Buttons factory"),ae("PayPal SDK did not expose the Buttons factory.");return}N.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let C=async xe=>{if(He()||Re.current!==Ee)return;let Ce=xe.subscriptionID??xe.orderID??"",te=Ce?Ut.current.get(Ce):Ve.current.get(Ee);if(!(!te||!an(te.generation))&&Dt(te.generation)){Ut.current.delete(Ce),Ve.current.delete(te.surfaceKey),xn();try{if(x(!0),pt(()=>We.current?.(null)),!Ce)throw new Ka("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await L({id:Ce,isPaypal:!0},te)}catch(Be){O(Be instanceof Error?Be.message:"PayPal capture failed.")}finally{He()||x(!1)}}},ce=h.Buttons({style:{layout:"horizontal",height:io,tagline:!1},onClick:async(xe,Ce)=>{if(He()){await Ce.reject();return}hn();let te=we.current,Be={};if(te)try{let zt=await te("paypal");if(He()){await Ce.reject();return}if(!zt.proceed){et.current=null,Ve.current.delete(Ee),await Ce.reject();return}Be={sessionId:zt.sessionId,accountPatch:zt.accountPatch,nonce:zt.nonce}}catch(zt){u(`onClick:runBeforeButtonClick rejected msg=${(zt instanceof Error?zt.message:String(zt)).slice(0,120)}`),et.current=null,Ve.current.delete(Ee),await Ce.reject();return}pt(()=>Pt.current?.("paypal"));let Wt={generation:$t(),surfaceKey:Ee,...Be};et.current=Wt,Ve.current.set(Ee,Wt),await Ce.resolve(),N.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),sn=N.startTiming()},createOrder:s?void 0:K?()=>_e(K).then(fn):()=>le("Failed to create PayPal order.").then(fn),createSubscription:s?K?()=>_e(K).then(fn):()=>le("Failed to create PayPal subscription.").then(fn):void 0,onApprove:C,onCancel:()=>{if(He())return;let xe=Ve.current.get(Ee)??et.current;xe&&Ve.current.delete(xe.surfaceKey),et.current=null,xn(),N.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe.current=!0,Gt({generation:xe?.generation,remount:!0,focus:!1})},onError:xe=>{if(He()||Re.current!==Ee)return;let Ce=xe instanceof Error?xe.message:"PayPal failed to render.";if(u(`onError rendered=${Xt} msg=${Ce.slice(0,120)}`),Xt){let te=Ve.current.get(Ee)??et.current;if(te&&!an(te.generation)||!te&&bt.current===Ge.current)return;if(Y(Ce)){Dt(te?.generation);return}if(xn(),Nr(xe)){N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ne(xe,te),pt(()=>qe.current?.(St("paypal",Ce))),te&&Ve.current.delete(te.surfaceKey),et.current=null,Dt(te?.generation);return}let Be=Ce.toLowerCase();N.error({errorCode:Be.includes("popup")&&Be.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),te&&Ve.current.delete(te.surfaceKey),et.current=null,Gt({generation:te?.generation,remount:!0,showRetry:!0,focus:!0}),qn(xe,{code:"paypal_runtime_failed"});return}ae(Ce)}}),H=ce.isEligible();if(u(`isEligible=${H}`),N.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!H){J(!1),ae("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}jt=ce,B&&u(`container:dims ${lt(Nt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),B&&typeof MutationObserver<"u"&&(Zt=new MutationObserver(xe=>{if(!He()){for(let Ce of xe)if(Ce.type==="childList")Ce.addedNodes.forEach(te=>{if(!(te instanceof Element))return;let Be=te.tagName.toLowerCase(),ln=(te.getAttribute("title")??"").slice(0,40),Wt=Be==="iframe"?` ${Vn(te)}`:"";u(`child+ ${Be}${ln?` title="${ln}"`:""}${Wt} dims=${lt(te)}`)});else if(Ce.type==="attributes"&&Ce.target instanceof Element){let te=Ce.target;if(te.tagName.toLowerCase()!=="iframe")continue;let Be=Ce.attributeName;(Be==="src"||Be==="srcdoc")&&u(`attr~ iframe ${Be}=${Be==="srcdoc"?`[${(te.getAttribute("srcdoc")??"").length}ch]`:Pn(te.getAttribute("src"))} dims=${lt(te)}`)}}}),Zt.observe(Nt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ct=xe=>{if(He()||Xt)return;let Ce=Nt.querySelectorAll("iframe"),te=typeof document<"u"&&"hasStorageAccess"in document;u(`watchdog:${xe} container=${lt(Nt)} children=${Nt.childElementCount} iframes=${Ce.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${te} paypalNetRequests=${Kt.value}`),Ce.forEach((Be,ln)=>{let Wt=(Be.getAttribute("title")??"").slice(0,40);u(` iframe[${ln}] ${lt(Be)}${Wt?` title="${Wt}"`:""} ${Vn(Be)}`);let zt=Ot(Be);zt&&u(` ${zt}`)}),Ht.length===0&&u(" (no PayPal/zoid window errors captured)")};B&&(ft.push(setTimeout(()=>ct("3s"),3e3)),ft.push(setTimeout(()=>ct("8s"),8e3)),ft.push(setTimeout(()=>ct("15s"),15e3))),u("render:start"),ft.push(setTimeout(()=>{He()||Xt||(u("watchdog:11s retryable render timeout"),ae("PayPal Buttons render did not settle within 11000ms.",!0))},gs)),ce.render(Nt).then(()=>{if(u(`render:resolved inactive=${He()}`),_(),He()){Jt();return}Xt=!0,J(!0),be(!1),f.current?.("ready"),N.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"provider_ready",durationMs:N.elapsed(re.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(xe=>{let Ce=xe instanceof Error?xe.message:"PayPal failed to render.";u(`render:rejected msg=${Ce.slice(0,120)}`),_(),ae(Ce)})}).catch(h=>{let C=h instanceof Error?h.message:"PayPal SDK failed to load.";u(`loadScript:rejected msg=${C.slice(0,120)}`),ae(C)})},0);return()=>{ke=!0,clearTimeout(Ft),tt&&clearTimeout(tt),_(),Jt()}},[w,j,o,c,a,s,e,K,oe,N]);let At=B?$o("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ze?"#fef2f2":"#f3f4f6",border:`1px solid ${ze?"#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=${ye} failed=${ze})`,Qe.length===0?`
|
|
7
7
|
(waiting for first lifecycle event\u2026)`:`
|
|
8
|
-
${
|
|
9
|
-
`)}`]}):null;return
|
|
8
|
+
${Qe.join(`
|
|
9
|
+
`)}`]}):null;return ze&&!it?B?mr("div",{children:At}):null:$o("div",{children:[At,$o("div",{"aria-hidden":me?!0:void 0,style:me?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:io},children:[!ye&&!me&&mr("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"}}),mr("div",{ref:q,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:io,display:"flex",opacity:ye?1:0},"aria-busy":W||I},oe)]},oe),Se&&mr("button",{ref:Ae,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:_n,style:Ps,children:"Try PayPal again"})]})}function so(e){return mr(Ga,{...e})}function Ja(e){return mr(Ga,{...e})}import{FloPayError as wn,isSetupIntentClientSecret as Ds,resolveTheme as Ls}from"@flopay/shared";import{Fragment as yr,jsx as d,jsxs as Me}from"react/jsx-runtime";var kn="flopay_stripe_resume",ti="flopay_wallet_resume",zr="flopay_paypal_resume";function Go(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function uo({billingApiUrl:e,sessionId:t,nonce:n,request:i}){if(!(!t||!n))try{await new On(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function Ns(e){return e instanceof wn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function jo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function lo(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let i=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),a=Math.round((i>>16&255)*o),c=Math.round((i>>8&255)*o),s=Math.round((i&255)*o);return`#${(1<<24|a<<16|c<<8|s).toString(16).slice(1)}`}var Os=`
|
|
10
10
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
11
11
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
12
12
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -27,7 +27,7 @@ ${Xe.join(`
|
|
|
27
27
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
28
28
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
29
29
|
}
|
|
30
|
-
`,oo=44;function Vo(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 Bs={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},oi={width:"100%",minHeight:oo,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 As(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ja(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ai(e){return e==="paypal"?"PayPal":dr(e)}function Fs(e,t){let n=`We couldn't open ${ai(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ii(e){let t=Le(0),n=Le(null),i=Le(null),r=ge((l=i.current)=>{let f=l;f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),a=ge((l,f)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(l),l.timer=setTimeout(()=>{l.timer=null,i.current?.generation===l.generation&&(i.current=null,n.current=l.generation,e(l.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},f))},[r,e]),c=ge(l=>{l.yieldedControl&&a(l,600)},[a]),s=ge(l=>{r();let f=t.current+1;t.current=f,n.current=null;let S={generation:f,method:l,timer:null,yieldedControl:!1};return i.current=S,f},[r]),w=ge(l=>{let f=i.current;return typeof l=="number"&&f?.generation!==l?!1:(r(f),i.current=null,(typeof l!="number"||n.current===l)&&(n.current=null),!0)},[r]),B=ge(l=>{let f=i.current,S=l??f?.generation??t.current;(!l||f?.generation===l)&&(r(f),i.current=null),n.current=S},[r]),p=ge(l=>n.current===(l??t.current),[]),R=ge(l=>i.current?.generation===l&&n.current!==l,[]),C=ge(()=>{let l=i.current;l&&c(l)},[c]),E=ge(()=>{let l=i.current;l&&(l.yieldedControl=!0,r(l))},[r]);return mt(()=>{let l=()=>{document.visibilityState==="visible"?C():E()},f=()=>{E()};return document.addEventListener("visibilitychange",l),window.addEventListener("blur",f),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("blur",f),window.removeEventListener("focus",C),r()}},[r,E,C]),{startAttempt:s,finishAttempt:w,invalidateAttempt:B,isAttemptInvalidated:p,isAttemptCurrent:R}}function Ds(e){let t=vs(e);return`Enter a valid ${zo(e)}${t?` (e.g. ${t})`:""}`}function Ls(e,t,n){let i=Ps(e),r=t.trim(),a=n&&i,c=a&&!r,s=a&&!!r&&!bs(e,r);return{visible:n,supported:i,required:a,empty:c,malformed:s}}function Xa(e,t){return t instanceof Cn?t:new Cn(t instanceof Error?t.message:`${As(e)} before-click hook failed.`,"validation_error")}function Oo(){return d("style",{children:Ms})}function Ns(e){return typeof e=="number"?`${e}px`:e}function Za(e){if(typeof e=="number"||typeof e=="string")return e}function si(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function li({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){return e==="unavailable"||e==="load_error"?null:xe("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:i})]})}function Qa(e){return e!=="unavailable"&&e!=="load_error"}function Ho(e){return d(zs,{...e})}function ei({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:r,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:w,onTechnicalFailure:B,runBeforeButtonClick:p,onLoadStateChange:R,placeholderBorderRadius:C}){let E=Pn(),l=qo(),f=$o(),[S,T]=be("loading");mt(()=>{R?.(S)},[S,R]);let[h,q]=be(!1),Y=Le(!1),ce=Le(null),oe=Le(null),[D,X]=be(0),[j,de]=be(!1),z=Le(!1),V=Le(new Map),{startAttempt:ae,finishAttempt:Be,invalidateAttempt:fe,isAttemptInvalidated:ye,isAttemptCurrent:Z}=ii((k,ne,se)=>{B?.(k,ne,{...se,popupBlocked:se?.popupBlocked??Ln(ne)}),de(!0),X(Ne=>Ne+1)});mt(()=>{j&&oe.current?.focus()},[j,D]);let ue=ge(()=>{X(k=>k+1)},[]),he=ge((k,ne,se)=>{fe(se),B?.("paypal",k,{code:ne,popupBlocked:Ln(k)}),de(!0),ue()},[fe,B,ue]),ie=ge(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);mt(()=>{z.current&&(z.current=!1,ie())},[ie,D]);let Fe=ge(()=>{de(!1),a?.(null),ie()},[ie,a]);mt(()=>{if(!l||Y.current)return;let k=new URLSearchParams(window.location.search),ne=k.get("payment_intent"),se=k.get("payment_intent_client_secret"),Ne=k.get("redirect_status");if(!ne||!se)return;Y.current=!0;let De;try{let x=localStorage.getItem(Fr);if(x){let H=JSON.parse(x);H.clientSecret===se&&(De={...H.accountPatch?{accountPatch:H.accountPatch}:{},...H.sessionId?{sessionId:H.sessionId}:{},...H.nonce?{nonce:H.nonce}:{}})}}catch{}try{localStorage.removeItem(Fr)}catch{}let G=new URL(window.location.href);G.searchParams.delete("payment_intent"),G.searchParams.delete("payment_intent_client_secret"),G.searchParams.delete("redirect_status"),window.history.replaceState({},"",G.toString()),(async()=>{try{if(q(!0),Ne==="failed"){let le="PayPal payment was declined. Please try again.";a?.(le),w?.(St("paypal",le));return}let{paymentIntent:x,error:H}=await l.retrievePaymentIntent(se);if(H){a?.(H.message??"Failed to retrieve PayPal payment status.");return}if(x&&(x.status==="requires_capture"||x.status==="succeeded")){let le=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id;r({id:le??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0},De)}else{let le="PayPal payment was not completed. Please try again.";a?.(le),w?.(St("paypal",le))}}catch(x){a?.(x instanceof Error?x.message:"Failed to complete PayPal payment.")}finally{q(!1)}})()},[l,r,a,w]);let ke=ge(async k=>{if(c||h){k.reject();return}let ne=p?await p("paypal"):{proceed:!0};if(!ne.proceed){V.current.delete(D),k.reject();return}let se=ae("paypal");V.current.set(D,{generation:se,accountPatch:ne.accountPatch,sessionId:ne.sessionId,nonce:ne.nonce}),de(!1),s?.("paypal"),k.resolve()},[V,c,s,p,ae,h,D]),ve=ge(async k=>{if(!l||!f)return;let ne=V.current.get(D);if(ne&&!Z(ne.generation)){V.current.delete(D);return}if(!ne&&ye()||ne&&!Be(ne.generation))return;ne||Be();let se=ne??null;if(V.current.delete(D),!se&&p){let x=await p("paypal");if(!x.proceed){k.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}se={accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}}let Ne=se?.sessionId??e,De=se?.nonce??t,G=se?.accountPatch?.email??n;try{if(q(!0),a?.(null),!Ne||!G)throw new Error("Missing sessionId or email for PayPal payment");let x=l.createPaymentMethod,{error:H,paymentMethod:le}=await x({type:"paypal"});if(H){he(H,"stripe_paypal_create_payment_method_failed",ne?.generation),k.paymentFailed({reason:"fail"});return}let Re=await new Nn(i).createSessionIntent(Ne,De??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:le?.id??null,intentKind:"payment"});if(Re.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let gt=Re.clientSecret,Xe={return_url:window.location.href};if(le?.id&&(Xe.payment_method=le.id),typeof window<"u")try{localStorage.setItem(Fr,JSON.stringify({clientSecret:gt,sessionId:Ne,nonce:De,accountPatch:se?.accountPatch}))}catch{}let{error:Je,paymentIntent:m}=await l.confirmPayment({clientSecret:gt,confirmParams:Xe,redirect:"if_required"});if(Je){if(typeof window<"u")try{localStorage.removeItem(Fr)}catch{}if(Br(Je)){let Oe=Je.message??"Your payment was declined.";a?.(Oe),w?.(St("paypal",Oe,{code:Mn(Je),declineCode:sr(Je)})),await ao({billingApiUrl:i,sessionId:Ne,nonce:De,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Mn(Je)??"provider_declined"}})}else he(Je,"stripe_paypal_confirm_failed",ne?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Fr)}catch{}let Ue=typeof m?.payment_method=="string"?m.payment_method:m?.payment_method?.id;r({id:Ue??m?.id,type:"card",threeDSecureActionResultTokenId:m?.id,isPaypal:!0},{accountPatch:se?.accountPatch,sessionId:Ne,nonce:De});return}catch(x){he(x,"stripe_paypal_failed",ne?.generation)}finally{q(!1)}},[l,f,e,t,n,i,r,a,w,p,he,Be,Z,ye,D]);return xe(cr,{children:[d(li,{state:S,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[j&&d("button",{ref:oe,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Fe,style:oi,children:"Try PayPal again"}),d(ri,{onReady:k=>T(si(k,["paypal"])),onLoadError:()=>{T("load_error"),jo(Mt(E),"paypal","paypal")},onClick:ke,onConfirm:ve,onCancel:()=>{let k=V.current.get(D);V.current.delete(D),Mt(E)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe(k?.generation),de(!1),z.current=!0,ue()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},D)]})}),h&&d(vn,{status:"processing"})]})}function ti({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:w,onDecline:B,onTechnicalFailure:p,runBeforeButtonClick:R,onLoadStateChange:C,placeholderBorderRadius:E}){let l=Pn(),f=qo(),S=$o(),[T,h]=be("loading");mt(()=>{C?.(T)},[T,C]);let[q,Y]=be(!1),ce=Le(null),oe=Le(null),[D,X]=be(0),[j,de]=be(!1),[z,V]=be("google_pay"),ae=Le(!1),Be=Le("google_pay"),fe=Le("google_pay"),ye=Le(new Map),{startAttempt:Z,finishAttempt:ue,invalidateAttempt:he,isAttemptInvalidated:ie,isAttemptCurrent:Fe}=ii((G,x,H)=>{p?.(G,x,{...H,popupBlocked:H?.popupBlocked??Ln(x)}),V(G),de(!0),X(le=>le+1)});mt(()=>{j&&oe.current?.focus()},[j,D]);let ke=ge(()=>{X(G=>G+1)},[]),ve=ge((G,x,H,le)=>{he(le),p?.(G,x,{code:H,popupBlocked:Ln(x)}),V(G),de(!0),ke()},[he,p,ke]),k=ge(()=>{window.setTimeout(()=>{(ce.current?.querySelector("iframe")??ce.current)?.focus()},0)},[]);mt(()=>{ae.current&&(ae.current=!1,k())},[k,D]);let ne=ge(()=>{de(!1),s?.(null),k()},[k,s]),se=ge(async G=>{if(!f||!S)return;let x=ye.current.get(D);if(x&&!Fe(x.generation)){ye.current.delete(D);return}if(!x&&ie()||x&&!ue(x.generation))return;x||ue();let H=G.expressPaymentType??x?.method??Be.current,le=x??null;ye.current.delete(D);let Re=Ja(H);if(!le&&R){let Ue=await R(Re);if(!Ue.proceed){G.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}le={accountPatch:Ue.accountPatch,sessionId:Ue.sessionId,nonce:Ue.nonce}}let gt=Re,Xe=le?.sessionId??e,Je=le?.nonce??t,m=le?.accountPatch?.email??n;try{Y(!0),s?.(null);let{error:Ue}=await S.submit();if(Ue){ve(H,Ue,"stripe_wallet_submit_failed",x?.generation);return}let{error:Oe,paymentMethod:Ve}=await f.createPaymentMethod({elements:S});if(Oe||!Ve){ve(H,Oe??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",x?.generation);return}if(!Xe||!m)throw new Error("Missing sessionId or email for wallet payment");let $e=await new Nn(i).createSessionIntent(Xe,Je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H??Re,paymentMethodId:Ve.id,intentKind:r});if($e.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Kt=$e.clientSecret,{error:bt,intentId:It}=_s(Kt)?await f.confirmCardSetup(Kt,{payment_method:Ve.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await f.confirmCardPayment(Kt,{payment_method:Ve.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(bt){if(Br(bt)){let g=bt.message??"Your payment was declined.";s?.(g),B?.(St(gt,g,{code:Mn(bt),declineCode:sr(bt)})),await ao({billingApiUrl:i,sessionId:Xe,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:H??Re,providerDeclineReason:Mn(bt)??"provider_declined"}})}else ve(H,bt,"stripe_wallet_confirm_failed",x?.generation);return}c({id:Ve.id,type:"card",threeDSecureActionResultTokenId:It},{accountPatch:le?.accountPatch,sessionId:Xe,nonce:Je})}catch(Ue){ve(H,Ue,"stripe_wallet_failed",x?.generation)}finally{Y(!1)}},[f,S,e,t,n,i,r,c,s,B,R,ve,ue,Fe,ie,D]),Ne=at(()=>{let G=["applePay","googlePay","paypal","link","amazonPay","klarna"],x=new Set(["applePay","googlePay"]),H=new Set(a.map(Ya)),le={};for(let Re of G)H.has(Re)?le[Re]=x.has(Re)?"always":"auto":le[Re]="never";return le},[a]),De=at(()=>a.map(Ya),[a]);return xe(cr,{children:[d(li,{state:T,placeholderTestId:"flopay-wallet-placeholder",borderRadius:E,children:xe("div",{ref:ce,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[j&&xe("button",{ref:oe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ne,style:oi,children:["Try ",ai(z)," again"]}),d(ri,{onReady:G=>{h(si(G,De))},onLoadError:G=>{h("load_error"),jo(Mt(l),"stripe","wallet")},onClick:async G=>{Be.current=G.expressPaymentType,fe.current=Ja(G.expressPaymentType);let x=R?await R(fe.current):{proceed:!0};if(!x.proceed){ye.current.delete(D),G.reject();return}let H=Z(G.expressPaymentType);ye.current.set(D,{generation:H,method:G.expressPaymentType,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),de(!1),w?.(fe.current),G.resolve()},onConfirm:se,onCancel:()=>{let G=ye.current.get(D);ye.current.delete(D),Mt(l)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),he(G?.generation),de(!1),ae.current=!0,ke()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ne,layout:{maxColumns:1,overflow:"never"}}},D)]})}),q&&d(vn,{status:"processing"})]})}function Os({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:r=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:w,textColor:B,borderRadius:p,fontFamily:R}){let C=Ss(e,t),E=Aa[e],l=C?.backgroundColor??s??"#ffffff",f=C?.borderColor??w??"#d1d5db",S=C?.textColor??B??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&c()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:oo,padding:"0 1rem",backgroundColor:l,color:S,border:`1px solid ${f}`,borderRadius:p??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||i?"not-allowed":"pointer",opacity:i&&!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:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${dr(e)}\u2026`}):xe(cr,{children:[xe("span",{style:{display:"inline-flex",alignItems:"center",gap:ws(e)?8:0},children:[E?d("img",{src:E,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"}}):C?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,d("span",{children:dr(e)})]}),a&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:S,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:d("path",{d:"M9 18l6-6-6-6"})})]})})}function Uo({method:e,sessionId:t,nonce:n,email:i,billingName:r,billingApiUrl:a,onTokenizedBody:c,onErrorChange:s,onDecline:w,onCancel:B,runBeforeButtonClick:p,onButtonClick:R,isProcessing:C,submitButtonColor:E,submitButtonBorderRadius:l,submitButtonStyle:f,errorText:S}){let T=Pn(),h=qo(),q=$o(),[Y,ce]=be(!1),oe=Le(!1),[D,X]=be(!1),[j,de]=be("loading"),z=ge(async()=>{if(!h||!q||C||oe.current||!D)return;oe.current=!0,ce(!0);let V=p?await p("card"):{proceed:!0};if(!V.proceed){oe.current=!1,ce(!1);return}R?.("card");let ae=V.sessionId??t,Be=V.nonce??n,fe=V.accountPatch?.email??i;try{s?.(null);let ye=await q.submit();if(ye.error){s?.(ye.error.message??"Payment failed.");return}let Z=await h.createPaymentMethod({elements:q});if(Z.error||!Z.paymentMethod){s?.(Z.error?.message??"Failed to create payment method.");return}let ue=Z.paymentMethod;if(!ae||!fe)throw new Error("Missing sessionId or email for payment.");let he=ue.type||e,ie=await new Nn(a).createSessionIntent(ae,Be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:he,paymentMethodId:null,intentKind:"payment"});if(ie.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Fe=ie.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:Fe,sessionId:ae,nonce:Be,accountPatch:V.accountPatch,paymentMethodId:ue.id,paymentMethodType:ue.type??e,gateway:"stripe"}))}catch{}let{error:ke,paymentIntent:ve}=await h.confirmPayment({clientSecret:Fe,confirmParams:{return_url:window.location.href,payment_method:ue.id},redirect:"if_required"});if(ke){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let se=ke.message??"Payment failed.";s?.(se),w?.(St("card",se,{code:ke.code})),await ao({billingApiUrl:a,sessionId:ae,nonce:Be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ke.code??"provider_declined"}});return}let k=ve?.status;if(!Xr(k)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let se=k==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";s?.(se),w?.(St("card",se,{code:k??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let ne=typeof ve?.payment_method=="string"?ve.payment_method:ve?.payment_method?.id;c({id:ne??ue.id,type:"card",threeDSecureActionResultTokenId:ve?.id,gateway:"stripe",paymentMethodType:ue.type??e},{accountPatch:V.accountPatch,sessionId:ae,nonce:Be})}catch(ye){s?.(ye instanceof Error?ye.message:"Payment failed. Please try again.")}finally{oe.current=!1,ce(!1)}},[h,q,C,D,p,R,t,n,i,a,e,c,s,w]);return xe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(ms,{onReady:()=>de("ready"),onLoadError:()=>{de("load_error"),jo(Mt(T),"stripe","apm")},onChange:V=>{X(!!V.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...i?{email:i}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{z()},disabled:!D||Y||C||j!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:E,color:"white",border:"none",borderRadius:l,fontSize:"1rem",fontWeight:600,cursor:!D||Y||C||j!=="ready"?"not-allowed":"pointer",opacity:!D||Y||C||j!=="ready"?.5:1,transition:"opacity 120ms ease-out",...f??{}},children:Y?"Processing\u2026":`Pay with ${dr(e)}`}),S&&d(or,{margin:"0.75rem 0 0",children:S})]})}function ni({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:a,stripeInstance:c,paymentElementBaseOptions:s,onTokenizedBody:w,onErrorChange:B,onButtonClick:p,onDecline:R,runBeforeButtonClick:C,onLoadStateChange:E,isProcessing:l=!1,submitButtonColor:f="#4A49FF",submitButtonBorderRadius:S=8,submitButtonStyle:T,buttonAppearance:h,themeId:q,onExpandApm:Y,expandedApmMethod:ce}){let[oe,D]=be(null),[X,j]=be(null),de=Le(!1);mt(()=>{a.length>0&&c?E?.("ready"):c||E?.("loading")},[a.length,c,E]);let z=ge(async Z=>{if(!c||de.current||l)return;de.current=!0,j(Z);let ue=C?await C("card"):{proceed:!0};if(!ue.proceed){de.current=!1,j(null);return}p?.("card");let he=ue.sessionId??e,ie=ue.nonce??t,Fe=ue.accountPatch?.email??n;try{if(B?.(null),!he||!Fe)throw new Error("Missing sessionId or email for payment.");let ke=await new Nn(r).createSessionIntent(he,ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,paymentMethodId:null,intentKind:"payment"});if(ke.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ve=ke.clientSecret;if(typeof window<"u")try{localStorage.setItem(wn,JSON.stringify({clientSecret:ve,sessionId:he,nonce:ie,accountPatch:ue.accountPatch,paymentMethodType:Z,gateway:"stripe"}))}catch{}let{error:k,paymentIntent:ne}=await c.confirmPayment({clientSecret:ve,confirmParams:{return_url:window.location.href,payment_method_data:{type:Z,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...Fe?{email:Fe}:{}}}},redirect:"if_required"});if(k){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let De=k.message??"Payment failed.";B?.(De),R?.(St("card",De,{code:k.code})),await ao({billingApiUrl:r,sessionId:he,nonce:ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Z,providerDeclineReason:k.code??"provider_declined"}});return}let se=ne?.status;if(!Xr(se)){if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let De=se==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";B?.(De),R?.(St("card",De,{code:se??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(wn)}catch{}let Ne=typeof ne?.payment_method=="string"?ne.payment_method:ne?.payment_method?.id;w({id:Ne??ne?.id,type:"card",threeDSecureActionResultTokenId:ne?.id,gateway:"stripe",paymentMethodType:Z},{accountPatch:ue.accountPatch,sessionId:he,nonce:ie})}catch(ke){B?.(ke instanceof Error?ke.message:"Payment failed. Please try again.")}finally{de.current=!1,j(null)}},[c,l,C,p,e,t,n,r,i,w,B,R]),[V,ae]=be(null),Be=Y?ce??null:V,fe=ge(Z=>{de.current||l||Be&&Be!==Z||(Wa(Z)?Y?Y(Z):ae(Z):z(Z))},[Be,l,z,Y]),ye=at(()=>V?{...s,paymentMethodTypes:[V]}:null,[V,s]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(Z=>{let ue=ce===Z,he=X===Z,ie=X!==null&&X!==Z||ce!=null&&ce!==Z;return xe(Is.Fragment,{children:[d(Os,{method:Z,themeId:q,submitting:he,disabled:ie,highlighted:ue,hasNextStep:Wa(Z),onClick:()=>fe(Z),backgroundColor:h?.backgroundColor,borderColor:h?.borderColor,textColor:h?.textColor,borderRadius:h?.borderRadius,fontFamily:h?.fontFamily}),!Y&&V===Z&&ye&&c&&d(Jn,{stripe:c,options:ye,children:d(Uo,{method:Z,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:w,onErrorChange:B,onDecline:R,onCancel:()=>ae(null),runBeforeButtonClick:C,onButtonClick:p,isProcessing:l,submitButtonColor:f,submitButtonBorderRadius:S,submitButtonStyle:T})},Z)]},Z)})})}function zs({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:a,onError:c,onDecline:s,onTokenizedBody:w,firstName:B,lastName:p,chv:R,className:C,isProcessing:E,error:l,onErrorChange:f,showPayPal:S=!0,showStripe:T=!0,enabledPaymentMethods:h,enabledPaymentMethodCountries:q,showApplePay:Y=!0,showGooglePay:ce=!0,layout:oe="default",theme:D,buttonsTheme:X,buttonsStyles:j,appearance:de,cardButtonContent:z,cardBackButtonContent:V,cardTitleContent:ae,showSecurityFooter:Be,onButtonClick:fe,onBeforeButtonClick:ye,enableAVS:Z,cardFieldOrder:ue,cardPreFormSlot:he,avsLayout:ie="row",country:Fe,zip:ke,addressLine1:ve,addressLine2:k,city:ne,state:se,onCountryChange:Ne,onZipChange:De,avsCheck:G,checkoutType:x,checkoutLayout:H,totalAmount:le=0,currency:Re="usd",initialCardOpen:gt=!1,directPaypal:Xe,isSubscription:Je=!1,session:m,debug:Ue=!1}){let Oe=Pn(),Ve=To(),$e=Es(cn),Kt=Jr(),[bt,It]=be(!1),[g,Ce]=be(null),[qe,st]=be(Fe??"US"),[tt,Ze]=be(ke??""),[Ye,Pe]=be(ve??""),[vt,je]=be(k??""),[Dt,Et]=be(ne??""),[un,Rn]=be(se??""),[In,$n]=be({}),ht=Le(ke??""),Lt=Le(Fe??"US"),Ft=Le(ve??""),Wt=Le(k??""),rn=Le(ne??""),pn=Le(se??""),K=at(()=>hs(Z),[Z]),An=K!==null,mn=!!m?.vault?.html,Nt=!!m?.gateways?.pcivault,nt=mn||Nt,y=!!(T&&nt&&Oe&&e),Ie=at(()=>!Oe||!y||!e?null:Oe.cardCapture({sessionId:e}),[Oe,y,e]),lt=at(()=>{let o=qe,v=K?_e(K.postal_code,o):!1;return Ls(o,tt,v)},[K,qe,tt]),{avsInvalid:En,invalidAvsFields:Ee}=at(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!y||!K)return{avsInvalid:!1,invalidAvsFields:o};let v=qe,U=(ee,Ge)=>_e(ee,v)&&!Ge.trim(),re={line1:U(K.address_line_1,Ye),city:U(K.city,Dt),state:U(K.state,un),zip:lt.empty||lt.malformed};return{avsInvalid:re.line1||re.city||re.state||re.zip,invalidAvsFields:re}},[y,K,qe,Ye,Dt,un,lt]),[Fn,yn]=be(!1),[qn,fn]=be(!1),[Ot,At]=be(()=>No(m?.vault)),[we,yt]=be(gt&&nt?"card":"buttons"),[rt,on]=be(null),Yt=we==="expanding"||we==="card",Pt=280,jt=Le(null),Ct=ge(o=>{jt.current&&clearTimeout(jt.current),jt.current=setTimeout(()=>{jt.current=null,o()},Pt)},[Pt]);mt(()=>()=>{jt.current&&clearTimeout(jt.current)},[]);let an=ge(()=>{yt("expanding"),Ct(()=>yt("card"))},[Ct]),gn=ge(()=>{yt("collapsing"),Ct(()=>yt("buttons"))},[Ct]),_n=ge(o=>{on(o),yt("apm-expanding"),Ct(()=>yt("apm-form"))},[Ct]),hn=ge(()=>{yt("apm-collapsing"),Ct(()=>{yt("buttons"),on(null)})},[Ct]);mt(()=>{oe==="buttons"&>&&nt&&yt("card")},[oe,gt,nt]);let[Vt,He]=be(null),Ht=Le(!1),[zt,Ut]=be(null),_=Le(zt);mt(()=>{_.current=zt},[zt]);let L=n||Kt,N=l??g,M=at(()=>xs(D),[D]),u=at(()=>{let o=M?.buttonsLayout??ys(X);return j?{...o,...j,cardButton:{...o.cardButton,...j.cardButton},cardFormContainer:{...o.cardFormContainer,...j.cardFormContainer},backButton:{...o.backButton,...j.backButton},backButtonIcon:{...o.backButtonIcon,...j.backButtonIcon},submitButton:{...o.submitButton,...j.submitButton},title:{...o.title,...j.title}}:o},[M,X,j]),$=de??M?.appearance,b=at(()=>{let o=$?.variables,v=Ge=>typeof Ge=="string"&&Ge?Ge:void 0,U=u.submitButton,re=v(o?.colorPrimary)??v(U?.backgroundColor)??"#4A49FF",O=oe==="buttons",ee=u.nameInput;return{primaryColor:re,primaryHoverColor:v(o?.colorPrimaryHover)??ro(re,.12),inputBackgroundColor:v(u.cardInputBackground)??v(o?.colorBackground)??"#ffffff",textColor:v(u.cardInputColor)??v(ee?.color)??v(o?.colorText)??"#262833",borderColor:v(u.cardInputBorder)??(O?"#e5e7eb":"#A4A4FF"),placeholderColor:v(u.cardInputPlaceholderColor)??"#9ca3af",errorColor:v(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:v(ee?.fontFamily)??v(o?.fontFamily)??"Poppins, sans-serif",fontSize:v(u.cardInputFontSize)??v(o?.fontSizeBase)??"16px",fontWeight:String(Za(ee?.fontWeight)??400),borderRadius:v(o?.borderRadius)??"8px"}},[$,u,oe]),Te=$e.inlineSessionPatchProcessing??!1,W=(E??bt)||Te,Ke=L.replace(/\/+$/,""),J=at(()=>Ao({userId:r,email:i,firstName:B,lastName:p,country:Fe,zip:ke},In),[r,i,B,p,Fe,ke,In]),$t=[J.firstName,J.lastName].filter(o=>!!o?.trim()).join(" "),ot=at(()=>Oe?Oe.getRawProvider():null,[Oe]),A=at(()=>Ve?Ve.getRawProvider():null,[Ve]),P=le||100,F=at(()=>$?Rs($):null,[$]),me=F?{appearance:F}:null,Me=at(()=>{let o=F??{},v=o.rules??{};return{...o,rules:{...v,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...v[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...v[".AccordionItemContents"]??{}}}}},[F]),ze=at(()=>{let o=Na(le);return{...o,currency:Re.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...me}},[le,Re,me]),sn=at(()=>({mode:"payment",amount:P,currency:Re.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...me}),[P,Re,me]),I=ge(o=>{Ce(o),f?.(o)},[f]);mt(()=>{!y||!Ie||Ie.setCardFieldOrder?.(ue??null,K==null)},[y,Ie,ue,K]),mt(()=>{(we==="expanding"||we==="collapsing"||we==="apm-expanding"||we==="apm-collapsing")&&I(null)},[we,I]);let pe=ge((o,v,U)=>{s?.(St(o,v,U))},[s]),Q=ge((o,v,U)=>{let re=U?.popupBlocked??Ln(v),O=Fs(o,re),ee=Yn(U?.code)??Mn(v)??"external_payment_method_failed",Ge=new Cn(O,"api_error",{code:"external_payment_method_failed",param:o});He(null),oe==="buttons"&&(yt("buttons"),on(null)),I(O),c?.(Ge),console.error("[FloPay] External payment method failed:",{method:o,code:ee,popupBlocked:re})},[oe,c,I]);mt(()=>{if(!y||!e){At(null);return}let o=No(m?.vault);if(o){At(o);return}At(null);let v=!0;return new Nn(Ke).getVaultCapture(e,t).then(U=>{if(!v)return;let re=No(U);re?At(re):I("Failed to load the secure card form.")}).catch(U=>{v&&I(U instanceof Error?U.message:"Failed to load the secure card form.")}),()=>{v=!1}},[y,e,m?.vault?.html,m?.vault?.messageToken,m?.vault?.expectedOrigin,Ke,t,I]);let Se=Le({onComplete:a,onError:c,updateError:I,emitDecline:pe,resolvedAccount:J,avsConfig:K,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:Ke});Se.current={onComplete:a,onError:c,updateError:I,emitDecline:pe,resolvedAccount:J,avsConfig:K,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:Ke};let Gt=Le(!1),Jt=ge(()=>{let{resolvedAccount:o,avsConfig:v,avsCheckProp:U}=Se.current,re=Lt.current||o.country||"US",O=v?_e(v.state,re):!1,ee=v?_e(v.address_line_1,re):!1,Ge=v?_e(v.postal_code,re):!1,wt=v?_e(v.city,re):!1,_t=v?_e(v.address_line_2,re):!1,et=ee&&!O&&Ge?Ka(re,(ht.current??"").trim()):null,xt=O?pn.current:et;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...Ge&&ht.current?{zip:ht.current}:{},...wt&&rn.current?{city:rn.current}:{},...xt?{state:xt}:{},...ee&&Ft.current?{addressLine1:Ft.current}:{},..._t&&Wt.current?{addressLine2:Wt.current}:{},country:re},...U!==void 0?{avsCheck:U}:{},...v?{avsConfig:{country:_e(v.country,re),postal_code:Ge,address_line_1:ee,address_line_2:_t,city:wt,state:O}}:{}}},[]);mt(()=>{!y||!Ie||Ie.setSubmitGate?.(En)},[y,Ie,En]),mt(()=>{if(!y||!Ie)return;Gt.current=!1;let o=!1,v=Ie.on("submitting",()=>{yn(!0),He("processing");let{baseUrl:ee,sessionId:Ge,nonce:wt,updateError:_t,onError:et}=Se.current;!Ge||!wt||new Nn(ee).patchAccountSnapshot(Ge,wt,Jt(),{telemetryMode:"best_effort"}).catch(xt=>{if(!Ts(xt))return;let Ae=xt instanceof Error?xt.message:"Please check your billing address and try again.";_t(Ae),He(null),et?.(xt instanceof Cn?xt:new Cn(Ae,"api_error"))})}),U=Ie.on("complete",async ee=>{ir(ee.sessionId??Se.current.sessionId),He("success"),await new Promise(Ge=>setTimeout(Ge,Tn)),!Gt.current&&(Gt.current=!0,Se.current.onComplete?.({status:"succeeded",paymentIntentId:ee.intentId,checkoutMethod:"card"}))}),re=Ie.on("decline",async ee=>{let{updateError:Ge,emitDecline:wt}=Se.current,_t=ee.message??"Your payment was declined. Please try another card or contact your bank.";Ge(_t),He("error"),wt("card",_t,ee.declineReason?{declineCode:ee.declineReason}:void 0),await new Promise(et=>setTimeout(et,bn)),!o&&He(null)}),O=Ie.on("error",async ee=>{let{updateError:Ge,onError:wt}=Se.current,_t=ee.message??"There was a problem processing your payment. Please try again.";Ge(_t),He("error"),wt?.(new Cn(_t,"api_error")),await new Promise(et=>setTimeout(et,bn)),!o&&He(null)});return()=>{o=!0,v(),U(),re(),O()}},[y,Ie]);let Qe=!!Xe?.clientId,Pr=Array.isArray(h),Or=Pr&&h.length>0,ki=Pr&&h.includes("paypal"),{expressMethods:zr,paymentElementMethods:br}=at(()=>ks(h,{excludePaypal:Qe}),[h,Qe]),ra=Qe||!!Ve,Ri=at(()=>ra?zr.filter(o=>o!=="paypal"):zr,[zr,ra]),Ii=at(()=>{let o=[];return Y&&o.push("apple_pay"),ce&&o.push("google_pay"),o},[Y,ce]),Ur=Pr?Ri:Ii,Ei=T&&Ur.length>0,fo=An?qe:Fe,$r=at(()=>{let o=fo?.trim().toUpperCase();return o?q?br.filter(v=>{let U=q[v];return!U||U.length===0||U.includes(o)}):Cs(br,fo):br},[br,fo,q]),go=at(()=>({mode:"payment",amount:P,currency:Re.toLowerCase(),paymentMethodCreation:"manual",appearance:Me}),[P,Re,Me]),[oa,aa]=be("loading"),[ia,sa]=be("loading"),[la,ca]=be("loading"),[_i,ho]=be(!1),[da,Po]=be("loading"),[qr,xi]=be();mt(()=>{xi(za())},[]);let ua=S&&(Qe||(Pr?ki:qr===!1)),pa=T&&Ei,vr=ua&&Qe,ma=da==="retrying"||da==="exhausted",Cr=ua&&!!A&&(!Qe||ma),wr=pa&&!!ot,Sr=T&&Or&&$r.length>0&&!!ot,Ti=vr&&!ma?_i:Cr&&Qa(oa),Mi=wr&&Qa(ia),Bi=Sr&&la!=="load_error",ya=o=>o==="loading"||o==="ready",fa=vr||Cr&&ya(oa)||wr&&ya(ia)||Sr&&la!=="load_error",jr=Le(!1);mt(()=>{if(!jr.current){if(!T&&!S){jr.current=!0;let o=new Cn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(o),I(o.message)}else if(!T&&S&&!Qe&&!A){jr.current=!0;let o=new Cn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(o),I(o.message)}else if(qr!==void 0&&!nt&&!fa){jr.current=!0;let o=new Cn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(o),I(o.message)}}},[T,S,Qe,A,qr,nt,fa,c,I]);let ga=Le(!1);mt(()=>{if(ga.current||!Or)return;let o=[];Y!==!0&&o.push("showApplePay"),ce!==!0&&o.push("showGooglePay"),o.length!==0&&(ga.current=!0,console.warn(`[FloPay] ${o.join(" / ")} ${o.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.`))},[Or,Y,ce]);let ha=ge((o,v)=>$e.applyInlineSessionPatch?$e.applyInlineSessionPatch(o).then(U=>({error:null,sessionId:U.sessionId||e,nonce:U.session?.clientSecret||t})).catch(U=>{let re=Xa(v,U);return I(re.message),c?.(re),{error:re,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[$e.applyInlineSessionPatch,t,c,e,I]),ln=ge(async o=>{if(!ye)return{proceed:!0};try{let v=await ye({method:o,sessionId:e||void 0,createSession:$e.inlineSessionDraft});if(v===!1)return{proceed:!1};if(v&&typeof v=="object"){v.account&&$n(re=>({...re??{},...v.account}));let U=await ha(v,o);return U.error?{proceed:!1,accountPatch:v.account}:{proceed:!0,accountPatch:v.account,sessionId:U.sessionId,nonce:U.nonce}}return{proceed:!0}}catch(v){let U=Xa(o,v);return I(U.message),c?.(U),{proceed:!1}}},[ha,$e.inlineSessionDraft,ye,c,e,I]),Pa=ge(async(o,v)=>{if(Ht.current)return;Ht.current=!0,It(!0),He("processing"),I(null);let U=v?.sessionId??e,re=v?.nonce??t,O=Ao(J,v?.accountPatch),ee=v?.completionPaymentMethodId??Zr(o),Ge=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let _t=await new Nn(Ke).processPayment(O.userId??"",{sessionId:U,nonce:re,tokenizedData:Ge,accountData:{userId:O.userId??"",email:O.email??"",firstName:O.firstName??"",lastName:O.lastName??"",...K?(()=>{let Ae=Lt.current,Zt=_e(K.state,Ae),Qt=_e(K.address_line_1,Ae),Kn=_e(K.postal_code,Ae),Wn=Qt&&!Zt&&Kn?Ka(Ae,(ht.current??"").trim()):null,Tt=Zt?pn.current:Wn;return{country:Ae,...Kn&&ht.current?{zip:ht.current}:{},..._e(K.city,Ae)&&rn.current?{city:rn.current}:{},...Tt?{state:Tt}:{},...Qt&&Ft.current?{addressLine1:Ft.current}:{},..._e(K.address_line_2,Ae)&&Wt.current?{addressLine2:Wt.current}:{}}})():{}},chv:R,avsCheck:G??!1,checkoutType:x,checkoutLayout:H,avsConfig:K?{country:_e(K.country,Lt.current),postal_code:_e(K.postal_code,Lt.current),address_line_1:_e(K.address_line_1,Lt.current),address_line_2:_e(K.address_line_2,Lt.current),city:_e(K.city,Lt.current),state:_e(K.state,Lt.current)}:void 0});if(_t.ok){ir(U),He("success"),Ut(null),await new Promise(Ae=>setTimeout(Ae,Tn)),a?.({status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:ee,checkoutMethod:o.isPaypal?"paypal":"card"});return}let et=await _t.json().catch(()=>null);if(et?.type==="paypal_redirect_required"){let Ae=et.threeDSecureToken,Zt=et.paymentMethodId||o.id||"";if(!Oe||!Ae){He("error"),I("PayPal authorization required but no token provided.");return}try{let Qt=Ve?.getRawProvider();if(!Qt){I("PayPal is not available.");return}let Kn={return_url:window.location.href};Zt&&(Kn.payment_method=Zt);let{error:Wn}=await Qt.confirmPayment({clientSecret:Ae,confirmParams:Kn,redirect:"if_required"});if(Wn){He("error");let Tt=Wn.message??"PayPal payment failed.";I(Tt),pe("paypal",Tt,{code:Wn.code})}}catch(Qt){He("error"),I(Qt instanceof Error?Qt.message:"PayPal authorization failed.")}return}if(et?.type==="paypal_direct_required"){let Ae=et.orderId;if(!Ae){He("error"),I("PayPal retry required but no order id provided.");return}let Zt=_.current?.attempts??0;if(Zt>=2){He("error"),I("PayPal payment could not be completed after multiple attempts."),pe("paypal","paypal_direct_required retry limit exceeded");return}ho(!1),Po("loading"),Ut({orderId:Ae,attempts:Zt+1}),He(null);return}He("error");let xt=et?.message??"Payment failed. Please try again.";I(xt),pe(o.isPaypal?"paypal":"card",xt,{code:et?.code??et?.gatewayErrorCode,declineCode:et?.declineCode??et?.gatewayDeclineReason}),await new Promise(Ae=>setTimeout(Ae,bn))}catch(wt){He("error"),I(wt instanceof Error?wt.message:"An unexpected error occurred"),await new Promise(_t=>setTimeout(_t,bn))}finally{It(!1),He(null),Ht.current=!1}},[Ke,e,t,J,$t,R,Oe,Ve,a,c,I,pe]),Xt=ge((o,v)=>{w?w(o):Pa(o,v)},[w,Pa]),ba=Le(!1);mt(()=>{if(typeof window>"u"||ba.current)return;let o=new URLSearchParams(window.location.search),v=o.get("payment_intent"),U=o.get("payment_intent_client_secret"),re=o.get("redirect_status");if(!v||!U)return;let O=xt=>{let Ae=localStorage.getItem(xt);if(!Ae)return null;try{return JSON.parse(Ae)}catch{return localStorage.removeItem(xt),null}},ee=O(wn)??O(Ga),Ge;if(ee?.clientSecret){if(ee.clientSecret!==U)return;Ge={...ee.accountPatch?{accountPatch:ee.accountPatch}:{},...ee.sessionId?{sessionId:ee.sessionId}:{},...ee.nonce?{nonce:ee.nonce}:{}}}else if(ee?.sessionId&&ee.sessionId!==e)return;ba.current=!0,localStorage.removeItem(wn),localStorage.removeItem(Ga);let wt=new URL(window.location.href);wt.searchParams.delete("payment_intent"),wt.searchParams.delete("payment_intent_client_secret"),wt.searchParams.delete("redirect_status"),window.history.replaceState({},"",wt.toString());let _t=ee?.paymentMethodType??ee?.tokenType??"card",et="card";(async()=>{let xt=Oe?.getRawProvider();if(!xt){let Tt="Payment is not available \u2014 please refresh and try again.";I(Tt),pe(et,Tt);return}if(re==="failed"){let Tt="Payment was declined. Please try again.";I(Tt),pe(et,Tt);return}let{paymentIntent:Ae,error:Zt}=await xt.retrievePaymentIntent(U);if(Zt){let Tt=Zt.message??"Failed to retrieve payment status.";I(Tt),pe(et,Tt,{code:Zt.code});return}let Qt=Ae?.status,Kn=Xr(Qt);if(!Ae||!Kn){let Tt=Qt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";I(Tt),pe(et,Tt,{code:Qt??"missing_payment_intent"});return}let Wn=typeof Ae.payment_method=="string"?Ae.payment_method:Ae.payment_method?.id;Xt({id:Wn??ee?.paymentMethodId??ee?.tokenId??Ae.id,type:"card",threeDSecureActionResultTokenId:Ae.id,gateway:ee?.gateway??"stripe",paymentMethodType:_t},Ge)})()},[e,Xt,Oe,I,pe]);let bo=ge(o=>{o.preventDefault()},[]);if(!(Oe!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let kr=oe==="buttons",qt=$?.variables,Ai=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),vo=qt?.colorBackground,Fi=vo&&!Ai.has(vo)?vo:void 0,Rr=u.cardInputBorder??(kr?"#e5e7eb":"#A4A4FF"),Co=qt?.colorDanger??"#dc2626",jn=o=>Fn&&o?Co:Rr,Vr=(lt.malformed||lt.empty)&&(qn||Fn),Di=Vr?Co:jn(Ee.zip),wo=u.cardFormContainer?.backgroundColor??Fi??(kr?"white":"#EDEDFF"),Ir=u.cardInputBackground??qt?.colorBackground??"white",So=er(V),va=er(ae),Qn=u.nameInput,Ca=u.cardInputFontSize??Ns(Qn?.fontSize)??qt?.fontSizeBase??"16px",wa=typeof Qn?.fontFamily=="string"?Qn.fontFamily:qt?.fontFamily??"Poppins, sans-serif",Sa=Za(Qn?.fontWeight)??400,Li=u.cardInputColor??(typeof Qn?.color=="string"?Qn.color:void 0)??qt?.colorText??"#262833",Ni=u.cardInputPlaceholderColor??"#9ca3af",ft=qt?.borderRadius??"8px",Vn=qt?.borderRadius??u.cardButton?.borderRadius??ft,Hn=qt?.colorPrimary??"#4A49FF",Oi=qt?.colorPrimaryHover??ro(Hn,.12),ko=qt?.colorText??"#262833",ka={fontSize:Ca,fontFamily:wa,fontWeight:Sa,color:Li,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},zi={"--flopay-input-placeholder-color":Ni,"--flopay-input-font-size":Ca,"--flopay-input-font-family":wa,"--flopay-input-font-weight":String(Sa)},Er=u.cardFormContainer??{},Ro=Er.padding??(kr?"0":"1rem"),Io=Er.borderRadius??ft,Ui=Ie&&Ot?d(xo,{capture:Ie,html:Ot.html,messageToken:Ot.messageToken,expectedOrigin:Ot.expectedOrigin,theme:b,onReady:()=>{if(!K||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let v=0,U=window.setInterval(()=>{v+=1;let re=document.activeElement;!!re&&re.tagName==="IFRAME"&&re.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(U)):v>=50&&window.clearInterval(U)},100)},onError:o=>I(o),onValidation:o=>{I(o),o&&He(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"}),Ra=xe("div",{style:{backgroundColor:wo,borderRadius:Io,...Er,padding:Ro,...zi,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
30
|
+
`,co=44;function Jo(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 zs={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},di={width:"100%",minHeight:co,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 Us(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ni(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ui(e){return e==="paypal"?"PayPal":fr(e)}function $s(e,t){let n=`We couldn't open ${ui(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function pi(e){let t=Oe(0),n=Oe(null),i=Oe(null),o=Pe((l=i.current)=>{let m=l;m?.timer&&(clearTimeout(m.timer),m.timer=null)},[]),a=Pe((l,m)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(l),l.timer=setTimeout(()=>{l.timer=null,i.current?.generation===l.generation&&(i.current=null,n.current=l.generation,e(l.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},m))},[o,e]),c=Pe(l=>{l.yieldedControl&&a(l,600)},[a]),s=Pe(l=>{o();let m=t.current+1;t.current=m,n.current=null;let w={generation:m,method:l,timer:null,yieldedControl:!1};return i.current=w,m},[o]),S=Pe(l=>{let m=i.current;return typeof l=="number"&&m?.generation!==l?!1:(o(m),i.current=null,(typeof l!="number"||n.current===l)&&(n.current=null),!0)},[o]),M=Pe(l=>{let m=i.current,w=l??m?.generation??t.current;(!l||m?.generation===l)&&(o(m),i.current=null),n.current=w},[o]),p=Pe(l=>n.current===(l??t.current),[]),R=Pe(l=>i.current?.generation===l&&n.current!==l,[]),v=Pe(()=>{let l=i.current;l&&c(l)},[c]),I=Pe(()=>{let l=i.current;l&&(l.yieldedControl=!0,o(l))},[o]);return yt(()=>{let l=()=>{document.visibilityState==="visible"?v():I()},m=()=>{I()};return document.addEventListener("visibilitychange",l),window.addEventListener("blur",m),window.addEventListener("focus",v),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("blur",m),window.removeEventListener("focus",v),o()}},[o,I,v]),{startAttempt:s,finishAttempt:S,invalidateAttempt:M,isAttemptInvalidated:p,isAttemptCurrent:R}}function qs(e){let t=Es(e);return`Enter a valid ${Ho(e)}${t?` (e.g. ${t})`:""}`}function js(e,t,n){let i=Rs(e),o=t.trim(),a=n&&i,c=a&&!o,s=a&&!!o&&!Is(e,o);return{visible:n,supported:i,required:a,empty:c,malformed:s}}function ri(e,t){return t instanceof wn?t:new wn(t instanceof Error?t.message:`${Us(e)} before-click hook failed.`,"validation_error")}function Vo(){return d("style",{children:Os})}function Vs(e){return typeof e=="number"?`${e}px`:e}function oi(e){if(typeof e=="number"||typeof e=="string")return e}function mi(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function yi({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){return e==="unavailable"||e==="load_error"?null:Me("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:i})]})}function ai(e){return e!=="unavailable"&&e!=="load_error"}function Xo(e){return d(Ks,{...e})}function ii({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:o,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:S,onTechnicalFailure:M,runBeforeButtonClick:p,onLoadStateChange:R,placeholderBorderRadius:v}){let I=vn(),l=Yo(),m=Wo(),[w,T]=ge("loading");yt(()=>{R?.(w)},[w,R]);let[y,U]=ge(!1),K=Oe(!1),ue=Oe(null),X=Oe(null),[B,G]=ge(0),[$,pe]=ge(!1),N=Oe(!1),q=Oe(new Map),{startAttempt:re,finishAttempt:Ae,invalidateAttempt:fe,isAttemptInvalidated:ye,isAttemptCurrent:J}=pi((k,ee,ie)=>{M?.(k,ee,{...ie,popupBlocked:ie?.popupBlocked??Nn(ee)}),pe(!0),G(ze=>ze+1)});yt(()=>{$&&X.current?.focus()},[$,B]);let me=Pe(()=>{G(k=>k+1)},[]),be=Pe((k,ee,ie)=>{fe(ie),M?.("paypal",k,{code:ee,popupBlocked:Nn(k)}),pe(!0),me()},[fe,M,me]),oe=Pe(()=>{window.setTimeout(()=>{(ue.current?.querySelector("iframe")??ue.current)?.focus()},0)},[]);yt(()=>{N.current&&(N.current=!1,oe())},[oe,B]);let De=Pe(()=>{pe(!1),a?.(null),oe()},[oe,a]);yt(()=>{if(!l||K.current)return;let k=new URLSearchParams(window.location.search),ee=k.get("payment_intent"),ie=k.get("payment_intent_client_secret"),ze=k.get("redirect_status");if(!ee||!ie)return;K.current=!0;let Le;try{let x=localStorage.getItem(zr);if(x){let j=JSON.parse(x);j.clientSecret===ie&&(Le={...j.accountPatch?{accountPatch:j.accountPatch}:{},...j.sessionId?{sessionId:j.sessionId}:{},...j.nonce?{nonce:j.nonce}:{}})}}catch{}try{localStorage.removeItem(zr)}catch{}let W=new URL(window.location.href);W.searchParams.delete("payment_intent"),W.searchParams.delete("payment_intent_client_secret"),W.searchParams.delete("redirect_status"),window.history.replaceState({},"",W.toString()),(async()=>{try{if(U(!0),ze==="failed"){let se="PayPal payment was declined. Please try again.";a?.(se),S?.(St("paypal",se));return}let{paymentIntent:x,error:j}=await l.retrievePaymentIntent(ie);if(j){a?.(j.message??"Failed to retrieve PayPal payment status.");return}if(x&&(x.status==="requires_capture"||x.status==="succeeded")){let se=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id;o({id:se??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0},Le)}else{let se="PayPal payment was not completed. Please try again.";a?.(se),S?.(St("paypal",se))}}catch(x){a?.(x instanceof Error?x.message:"Failed to complete PayPal payment.")}finally{U(!1)}})()},[l,o,a,S]);let Re=Pe(async k=>{if(c||y){k.reject();return}let ee=p?await p("paypal"):{proceed:!0};if(!ee.proceed){q.current.delete(B),k.reject();return}let ie=re("paypal");q.current.set(B,{generation:ie,accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}),pe(!1),s?.("paypal"),k.resolve()},[q,c,s,p,re,y,B]),Se=Pe(async k=>{if(!l||!m)return;let ee=q.current.get(B);if(ee&&!J(ee.generation)){q.current.delete(B);return}if(!ee&&ye()||ee&&!Ae(ee.generation))return;ee||Ae();let ie=ee??null;if(q.current.delete(B),!ie&&p){let x=await p("paypal");if(!x.proceed){k.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}}let ze=ie?.sessionId??e,Le=ie?.nonce??t,W=ie?.accountPatch?.email??n;try{if(U(!0),a?.(null),!ze||!W)throw new Error("Missing sessionId or email for PayPal payment");let x=l.createPaymentMethod,{error:j,paymentMethod:se}=await x({type:"paypal"});if(j){be(j,"stripe_paypal_create_payment_method_failed",ee?.generation),k.paymentFailed({reason:"fail"});return}let Ie=await new On(i).createSessionIntent(ze,Le??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:se?.id??null,intentKind:"payment"});if(Ie.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let it=Ie.clientSecret,Qe={return_url:window.location.href};if(se?.id&&(Qe.payment_method=se.id),typeof window<"u")try{localStorage.setItem(zr,JSON.stringify({clientSecret:it,sessionId:ze,nonce:Le,accountPatch:ie?.accountPatch}))}catch{}let{error:Ze,paymentIntent:u}=await l.confirmPayment({clientSecret:it,confirmParams:Qe,redirect:"if_required"});if(Ze){if(typeof window<"u")try{localStorage.removeItem(zr)}catch{}if(Nr(Ze)){let Ue=Ze.message??"Your payment was declined.";a?.(Ue),S?.(St("paypal",Ue,{code:Bn(Ze),declineCode:pr(Ze)})),await uo({billingApiUrl:i,sessionId:ze,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Bn(Ze)??"provider_declined"}})}else be(Ze,"stripe_paypal_confirm_failed",ee?.generation);return}if(typeof window<"u")try{localStorage.removeItem(zr)}catch{}let $e=typeof u?.payment_method=="string"?u.payment_method:u?.payment_method?.id;o({id:$e??u?.id,type:"card",threeDSecureActionResultTokenId:u?.id,isPaypal:!0},{accountPatch:ie?.accountPatch,sessionId:ze,nonce:Le});return}catch(x){be(x,"stripe_paypal_failed",ee?.generation)}finally{U(!1)}},[l,m,e,t,n,i,o,a,S,p,be,Ae,J,ye,B]);return Me(yr,{children:[d(yi,{state:w,placeholderTestId:"flopay-paypal-placeholder",borderRadius:v,children:Me("div",{ref:ue,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[$&&d("button",{ref:X,type:"button","data-testid":"flopay-paypal-retry-button",onClick:De,style:di,children:"Try PayPal again"}),d(ci,{onReady:k=>T(mi(k,["paypal"])),onLoadError:()=>{T("load_error"),Go(Mt(I),"paypal","paypal")},onClick:Re,onConfirm:Se,onCancel:()=>{let k=q.current.get(B);q.current.delete(B),Mt(I)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe(k?.generation),pe(!1),N.current=!0,me()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},B)]})}),y&&d(Sn,{status:"processing"})]})}function si({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:o,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:S,onDecline:M,onTechnicalFailure:p,runBeforeButtonClick:R,onLoadStateChange:v,placeholderBorderRadius:I}){let l=vn(),m=Yo(),w=Wo(),[T,y]=ge("loading");yt(()=>{v?.(T)},[T,v]);let[U,K]=ge(!1),ue=Oe(null),X=Oe(null),[B,G]=ge(0),[$,pe]=ge(!1),[N,q]=ge("google_pay"),re=Oe(!1),Ae=Oe("google_pay"),fe=Oe("google_pay"),ye=Oe(new Map),{startAttempt:J,finishAttempt:me,invalidateAttempt:be,isAttemptInvalidated:oe,isAttemptCurrent:De}=pi((W,x,j)=>{p?.(W,x,{...j,popupBlocked:j?.popupBlocked??Nn(x)}),q(W),pe(!0),G(se=>se+1)});yt(()=>{$&&X.current?.focus()},[$,B]);let Re=Pe(()=>{G(W=>W+1)},[]),Se=Pe((W,x,j,se)=>{be(se),p?.(W,x,{code:j,popupBlocked:Nn(x)}),q(W),pe(!0),Re()},[be,p,Re]),k=Pe(()=>{window.setTimeout(()=>{(ue.current?.querySelector("iframe")??ue.current)?.focus()},0)},[]);yt(()=>{re.current&&(re.current=!1,k())},[k,B]);let ee=Pe(()=>{pe(!1),s?.(null),k()},[k,s]),ie=Pe(async W=>{if(!m||!w)return;let x=ye.current.get(B);if(x&&!De(x.generation)){ye.current.delete(B);return}if(!x&&oe()||x&&!me(x.generation))return;x||me();let j=W.expressPaymentType??x?.method??Ae.current,se=x??null;ye.current.delete(B);let Ie=ni(j);if(!se&&R){let $e=await R(Ie);if(!$e.proceed){W.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}se={accountPatch:$e.accountPatch,sessionId:$e.sessionId,nonce:$e.nonce}}let it=Ie,Qe=se?.sessionId??e,Ze=se?.nonce??t,u=se?.accountPatch?.email??n;try{K(!0),s?.(null);let{error:$e}=await w.submit();if($e){Se(j,$e,"stripe_wallet_submit_failed",x?.generation);return}let{error:Ue,paymentMethod:We}=await m.createPaymentMethod({elements:w});if(Ue||!We){Se(j,Ue??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",x?.generation);return}if(!Qe||!u)throw new Error("Missing sessionId or email for wallet payment");let qe=await new On(i).createSessionIntent(Qe,Ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j??Ie,paymentMethodId:We.id,intentKind:o});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Yt=qe.clientSecret,{error:Pt,intentId:Rt}=Ds(Yt)?await m.confirmCardSetup(Yt,{payment_method:We.id}).then(f=>({error:f.error,intentId:f.setupIntent?.id})):await m.confirmCardPayment(Yt,{payment_method:We.id}).then(f=>({error:f.error,intentId:f.paymentIntent?.id}));if(Pt){if(Nr(Pt)){let f=Pt.message??"Your payment was declined.";s?.(f),M?.(St(it,f,{code:Bn(Pt),declineCode:pr(Pt)})),await uo({billingApiUrl:i,sessionId:Qe,nonce:Ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:j??Ie,providerDeclineReason:Bn(Pt)??"provider_declined"}})}else Se(j,Pt,"stripe_wallet_confirm_failed",x?.generation);return}c({id:We.id,type:"card",threeDSecureActionResultTokenId:Rt},{accountPatch:se?.accountPatch,sessionId:Qe,nonce:Ze})}catch($e){Se(j,$e,"stripe_wallet_failed",x?.generation)}finally{K(!1)}},[m,w,e,t,n,i,o,c,s,M,R,Se,me,De,oe,B]),ze=ot(()=>{let W=["applePay","googlePay","paypal","link","amazonPay","klarna"],x=new Set(["applePay","googlePay"]),j=new Set(a.map(ei)),se={};for(let Ie of W)j.has(Ie)?se[Ie]=x.has(Ie)?"always":"auto":se[Ie]="never";return se},[a]),Le=ot(()=>a.map(ei),[a]);return Me(yr,{children:[d(yi,{state:T,placeholderTestId:"flopay-wallet-placeholder",borderRadius:I,children:Me("div",{ref:ue,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[$&&Me("button",{ref:X,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ee,style:di,children:["Try ",ui(N)," again"]}),d(ci,{onReady:W=>{y(mi(W,Le))},onLoadError:W=>{y("load_error"),Go(Mt(l),"stripe","wallet")},onClick:async W=>{Ae.current=W.expressPaymentType,fe.current=ni(W.expressPaymentType);let x=R?await R(fe.current):{proceed:!0};if(!x.proceed){ye.current.delete(B),W.reject();return}let j=J(W.expressPaymentType);ye.current.set(B,{generation:j,method:W.expressPaymentType,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),pe(!1),S?.(fe.current),W.resolve()},onConfirm:ie,onCancel:()=>{let W=ye.current.get(B);ye.current.delete(B),Mt(l)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),be(W?.generation),pe(!1),re.current=!0,Re()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ze,layout:{maxColumns:1,overflow:"never"}}},B)]})}),U&&d(Sn,{status:"processing"})]})}function Hs({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:S,textColor:M,borderRadius:p,fontFamily:R}){let v=Ts(e,t),I=za[e],l=v?.backgroundColor??s??"#ffffff",m=v?.borderColor??S??"#d1d5db",w=v?.textColor??M??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&c()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:co,padding:"0 1rem",backgroundColor:l,color:w,border:`1px solid ${m}`,borderRadius:p??8,fontSize:"0.95rem",fontWeight:600,fontFamily:R,cursor:n||i?"not-allowed":"pointer",opacity:i&&!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?d("span",{style:{margin:"0 auto"},children:`Connecting to ${fr(e)}\u2026`}):Me(yr,{children:[Me("span",{style:{display:"inline-flex",alignItems:"center",gap:xs(e)?8:0},children:[I?d("img",{src:I,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:fr(e)})]}),a&&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 Ko({method:e,sessionId:t,nonce:n,email:i,billingName:o,billingApiUrl:a,onTokenizedBody:c,onErrorChange:s,onDecline:S,onCancel:M,runBeforeButtonClick:p,onButtonClick:R,isProcessing:v,submitButtonColor:I,submitButtonBorderRadius:l,submitButtonStyle:m,errorText:w}){let T=vn(),y=Yo(),U=Wo(),[K,ue]=ge(!1),X=Oe(!1),[B,G]=ge(!1),[$,pe]=ge("loading"),N=Pe(async()=>{if(!y||!U||v||X.current||!B)return;X.current=!0,ue(!0);let q=p?await p("card"):{proceed:!0};if(!q.proceed){X.current=!1,ue(!1);return}R?.("card");let re=q.sessionId??t,Ae=q.nonce??n,fe=q.accountPatch?.email??i;try{s?.(null);let ye=await U.submit();if(ye.error){s?.(ye.error.message??"Payment failed.");return}let J=await y.createPaymentMethod({elements:U});if(J.error||!J.paymentMethod){s?.(J.error?.message??"Failed to create payment method.");return}let me=J.paymentMethod;if(!re||!fe)throw new Error("Missing sessionId or email for payment.");let be=me.type||e,oe=await new On(a).createSessionIntent(re,Ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:be,paymentMethodId:null,intentKind:"payment"});if(oe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let De=oe.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:De,sessionId:re,nonce:Ae,accountPatch:q.accountPatch,paymentMethodId:me.id,paymentMethodType:me.type??e,gateway:"stripe"}))}catch{}let{error:Re,paymentIntent:Se}=await y.confirmPayment({clientSecret:De,confirmParams:{return_url:window.location.href,payment_method:me.id},redirect:"if_required"});if(Re){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ie=Re.message??"Payment failed.";s?.(ie),S?.(St("card",ie,{code:Re.code})),await uo({billingApiUrl:a,sessionId:re,nonce:Ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Re.code??"provider_declined"}});return}let k=Se?.status;if(!no(k)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ie=k==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";s?.(ie),S?.(St("card",ie,{code:k??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ee=typeof Se?.payment_method=="string"?Se.payment_method:Se?.payment_method?.id;c({id:ee??me.id,type:"card",threeDSecureActionResultTokenId:Se?.id,gateway:"stripe",paymentMethodType:me.type??e},{accountPatch:q.accountPatch,sessionId:re,nonce:Ae})}catch(ye){s?.(ye instanceof Error?ye.message:"Payment failed. Please try again.")}finally{X.current=!1,ue(!1)}},[y,U,v,B,p,R,t,n,i,a,e,c,s,S]);return Me("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(vs,{onReady:()=>pe("ready"),onLoadError:()=>{pe("load_error"),Go(Mt(T),"stripe","apm")},onChange:q=>{G(!!q.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:o&&o.trim().length>=3?o.trim():"FloPay Customer",...i?{email:i}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{N()},disabled:!B||K||v||$!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:I,color:"white",border:"none",borderRadius:l,fontSize:"1rem",fontWeight:600,cursor:!B||K||v||$!=="ready"?"not-allowed":"pointer",opacity:!B||K||v||$!=="ready"?.5:1,transition:"opacity 120ms ease-out",...m??{}},children:K?"Processing\u2026":`Pay with ${fr(e)}`}),w&&d(cr,{margin:"0.75rem 0 0",children:w})]})}function li({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:o,paymentElementMethods:a,stripeInstance:c,paymentElementBaseOptions:s,onTokenizedBody:S,onErrorChange:M,onButtonClick:p,onDecline:R,runBeforeButtonClick:v,onLoadStateChange:I,isProcessing:l=!1,submitButtonColor:m="#4A49FF",submitButtonBorderRadius:w=8,submitButtonStyle:T,buttonAppearance:y,themeId:U,onExpandApm:K,expandedApmMethod:ue}){let[X,B]=ge(null),[G,$]=ge(null),pe=Oe(!1);yt(()=>{a.length>0&&c?I?.("ready"):c||I?.("loading")},[a.length,c,I]);let N=Pe(async J=>{if(!c||pe.current||l)return;pe.current=!0,$(J);let me=v?await v("card"):{proceed:!0};if(!me.proceed){pe.current=!1,$(null);return}p?.("card");let be=me.sessionId??e,oe=me.nonce??t,De=me.accountPatch?.email??n;try{if(M?.(null),!be||!De)throw new Error("Missing sessionId or email for payment.");let Re=await new On(o).createSessionIntent(be,oe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,paymentMethodId:null,intentKind:"payment"});if(Re.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Se=Re.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:Se,sessionId:be,nonce:oe,accountPatch:me.accountPatch,paymentMethodType:J,gateway:"stripe"}))}catch{}let{error:k,paymentIntent:ee}=await c.confirmPayment({clientSecret:Se,confirmParams:{return_url:window.location.href,payment_method_data:{type:J,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...De?{email:De}:{}}}},redirect:"if_required"});if(k){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Le=k.message??"Payment failed.";M?.(Le),R?.(St("card",Le,{code:k.code})),await uo({billingApiUrl:o,sessionId:be,nonce:oe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:J,providerDeclineReason:k.code??"provider_declined"}});return}let ie=ee?.status;if(!no(ie)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Le=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";M?.(Le),R?.(St("card",Le,{code:ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ze=typeof ee?.payment_method=="string"?ee.payment_method:ee?.payment_method?.id;S({id:ze??ee?.id,type:"card",threeDSecureActionResultTokenId:ee?.id,gateway:"stripe",paymentMethodType:J},{accountPatch:me.accountPatch,sessionId:be,nonce:oe})}catch(Re){M?.(Re instanceof Error?Re.message:"Payment failed. Please try again.")}finally{pe.current=!1,$(null)}},[c,l,v,p,e,t,n,o,i,S,M,R]),[q,re]=ge(null),Ae=K?ue??null:q,fe=Pe(J=>{pe.current||l||Ae&&Ae!==J||(Qa(J)?K?K(J):re(J):N(J))},[Ae,l,N,K]),ye=ot(()=>q?{...s,paymentMethodTypes:[q]}:null,[q,s]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(J=>{let me=ue===J,be=G===J,oe=G!==null&&G!==J||ue!=null&&ue!==J;return Me(As.Fragment,{children:[d(Hs,{method:J,themeId:U,submitting:be,disabled:oe,highlighted:me,hasNextStep:Qa(J),onClick:()=>fe(J),backgroundColor:y?.backgroundColor,borderColor:y?.borderColor,textColor:y?.textColor,borderRadius:y?.borderRadius,fontFamily:y?.fontFamily}),!K&&q===J&&ye&&c&&d(Qn,{stripe:c,options:ye,children:d(Ko,{method:J,sessionId:e,email:n,billingName:i,billingApiUrl:o,onTokenizedBody:S,onErrorChange:M,onDecline:R,onCancel:()=>re(null),runBeforeButtonClick:v,onButtonClick:p,isProcessing:l,submitButtonColor:m,submitButtonBorderRadius:w,submitButtonStyle:T})},J)]},J)})})}function Ks({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:o,onComplete:a,onError:c,onDecline:s,onTokenizedBody:S,firstName:M,lastName:p,chv:R,className:v,isProcessing:I,error:l,onErrorChange:m,showPayPal:w=!0,showStripe:T=!0,enabledPaymentMethods:y,enabledPaymentMethodCountries:U,showApplePay:K=!0,showGooglePay:ue=!0,layout:X="default",theme:B,buttonsTheme:G,buttonsStyles:$,appearance:pe,cardButtonContent:N,cardBackButtonContent:q,cardTitleContent:re,showSecurityFooter:Ae,onButtonClick:fe,onBeforeButtonClick:ye,enableAVS:J,cardFieldOrder:me,cardPreFormSlot:be,avsLayout:oe="row",country:De,zip:Re,addressLine1:Se,addressLine2:k,city:ee,state:ie,onCountryChange:ze,onZipChange:Le,avsCheck:W,checkoutType:x,checkoutLayout:j,totalAmount:se=0,currency:Ie="usd",initialCardOpen:it=!1,directPaypal:Qe,isSubscription:Ze=!1,session:u,debug:$e=!1}){let Ue=vn(),We=Lo(),qe=Fs(un),Yt=to(),[Pt,Rt]=ge(!1),[f,we]=ge(null),[je,st]=ge(De??"US"),[rt,et]=ge(Re??""),[Ge,ve]=ge(Se??""),[bt,Ve]=ge(k??""),[Ut,It]=ge(ee??""),[mn,En]=ge(ie??""),[_n,qn]=ge({}),ht=Oe(Re??""),$t=Oe(De??"US"),Dt=Oe(Se??""),Gt=Oe(k??""),an=Oe(ee??""),yn=Oe(ie??""),V=ot(()=>ks(J),[J]),Fn=V!==null,fn=!!u?.vault?.html,qt=!!u?.gateways?.pcivault,E=!!(u?.gateways?.stripe?.enabledPaymentMethods??y)?.includes("card"),Je=fn||E||qt,ke=!!(T&&Je&&Ue&&e),[Dn,He]=ge(()=>X!=="buttons"||it?e??null:null),[jn,gn]=ge(0),hn=X!=="buttons"||it||!!e&&Dn===e,tt=ot(()=>!Ue||!ke||!e||!hn?null:Ue.cardCapture({sessionId:e}),[Ue,ke,e,hn]),Et=ot(()=>{let r=je,b=V?Te(V.postal_code,r):!1;return js(r,rt,b)},[V,je,rt]),{avsInvalid:jt,invalidAvsFields:Lt}=ot(()=>{let r={line1:!1,city:!1,state:!1,zip:!1};if(!ke||!V)return{avsInvalid:!1,invalidAvsFields:r};let b=je,z=(Z,Xe)=>Te(Z,b)&&!Xe.trim(),ne={line1:z(V.address_line_1,Ge),city:z(V.city,Ut),state:z(V.state,mn),zip:Et.empty||Et.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[ke,V,je,Ge,Ut,mn,Et]),[Jt,sn]=ge(!1),[xn,Xt]=ge(!1),[Nt,Zt]=ge(()=>jo(u?.vault)),[he,ft]=ge(it&&Je?"card":"buttons"),[lt,Pn]=ge(null),Vn=he==="expanding"||he==="card",Ot=280,Ht=Oe(null),vt=Pe(r=>{Ht.current&&clearTimeout(Ht.current),Ht.current=setTimeout(()=>{Ht.current=null,r()},Ot)},[Ot]);yt(()=>()=>{Ht.current&&clearTimeout(Ht.current)},[]);let nr=Pe(()=>{He(e??null),gn(r=>r+1),ft("expanding"),vt(()=>ft("card"))},[vt,e]),Kt=Pe(()=>{ft("collapsing"),vt(()=>ft("buttons"))},[vt]),_=Pe(r=>{Pn(r),ft("apm-expanding"),vt(()=>ft("apm-form"))},[vt]),Y=Pe(()=>{ft("apm-collapsing"),vt(()=>{ft("buttons"),Pn(null)})},[vt]);yt(()=>{X==="buttons"&&it&&Je&&(He(e??null),ft("card"))},[X,it,Je,e]);let[O,P]=ge(null),ae=Oe(!1),[L,g]=ge(null),_e=Oe(L);yt(()=>{_e.current=L},[L]);let le=n||Yt,Ne=l??f,Ee=ot(()=>Ls(B),[B]),A=ot(()=>{let r=Ee?.buttonsLayout??Cs(G);return $?{...r,...$,cardButton:{...r.cardButton,...$.cardButton},cardFormContainer:{...r.cardFormContainer,...$.cardFormContainer},backButton:{...r.backButton,...$.backButton},backButtonIcon:{...r.backButtonIcon,...$.backButtonIcon},submitButton:{...r.submitButton,...$.submitButton},title:{...r.title,...$.title}}:r},[Ee,G,$]),Ft=pe??Ee?.appearance,F=ot(()=>{let r=Ft?.variables,b=Xe=>typeof Xe=="string"&&Xe?Xe:void 0,z=A.submitButton,ne=b(r?.colorPrimary)??b(z?.backgroundColor)??"#4A49FF",D=X==="buttons",Z=A.nameInput;return{primaryColor:ne,primaryHoverColor:b(r?.colorPrimaryHover)??lo(ne,.12),inputBackgroundColor:b(A.cardInputBackground)??b(r?.colorBackground)??"#ffffff",textColor:b(A.cardInputColor)??b(Z?.color)??b(r?.colorText)??"#262833",borderColor:b(A.cardInputBorder)??(D?"#e5e7eb":"#A4A4FF"),placeholderColor:b(A.cardInputPlaceholderColor)??"#9ca3af",errorColor:b(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:b(Z?.fontFamily)??b(r?.fontFamily)??"Poppins, sans-serif",fontSize:b(A.cardInputFontSize)??b(r?.fontSizeBase)??"16px",fontWeight:String(oi(Z?.fontWeight)??400),borderRadius:b(r?.borderRadius)??"8px"}},[Ft,A,X]),h=qe.inlineSessionPatchProcessing??!1,C=(I??Pt)||h,ce=le.replace(/\/+$/,""),H=ot(()=>zo({userId:o,email:i,firstName:M,lastName:p,country:De,zip:Re},_n),[o,i,M,p,De,Re,_n]),Ke=[H.firstName,H.lastName].filter(r=>!!r?.trim()).join(" "),ct=ot(()=>Ue?Ue.getRawProvider():null,[Ue]),xe=ot(()=>We?We.getRawProvider():null,[We]),Ce=se||100,te=ot(()=>Ft?Bs(Ft):null,[Ft]),Be=te?{appearance:te}:null,ln=ot(()=>{let r=te??{},b=r.rules??{};return{...r,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[te]),Wt=ot(()=>{let r=ja(se);return{...r,currency:Ie.toLowerCase(),paymentMethodCreation:"manual",...r.mode==="payment"?{captureMethod:"manual"}:{},...Be}},[se,Ie,Be]),zt=ot(()=>({mode:"payment",amount:Ce,currency:Ie.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Be}),[Ce,Ie,Be]),de=Pe(r=>{we(r),m?.(r)},[m]);yt(()=>{!ke||!tt||tt.setCardFieldOrder?.(me??null,V==null)},[ke,tt,me,V]),yt(()=>{(he==="expanding"||he==="collapsing"||he==="apm-expanding"||he==="apm-collapsing")&&de(null)},[he,de]);let cn=Pe((r,b,z)=>{s?.(St(r,b,z))},[s]),rr=Pe((r,b,z)=>{let ne=z?.popupBlocked??Nn(b),D=$s(r,ne),Z=Xn(z?.code)??Bn(b)??"external_payment_method_failed",Xe=new wn(D,"api_error",{code:"external_payment_method_failed",param:r});P(null),X==="buttons"&&(ft("buttons"),Pn(null)),de(D),c?.(Xe),console.error("[FloPay] External payment method failed:",{method:r,code:Z,popupBlocked:ne})},[X,c,de]);yt(()=>{if(!ke||!e){Zt(null);return}let r=jo(u?.vault);if(r){Zt(r);return}if(!hn){Zt(null);return}Zt(null);let b=!0;return new On(ce).getVaultCapture(e,t).then(z=>{if(!b)return;let ne=jo(z);ne?Zt(ne):de("Failed to load the secure card form.")}).catch(z=>{b&&de(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{b=!1}},[ke,hn,jn,e,u?.vault?.html,u?.vault?.messageToken,u?.vault?.expectedOrigin,ce,t,de]);let Hn=Oe({onComplete:a,onError:c,updateError:de,emitDecline:cn,resolvedAccount:H,avsConfig:V,avsCheckProp:W,sessionId:e,nonce:t,baseUrl:ce});Hn.current={onComplete:a,onError:c,updateError:de,emitDecline:cn,resolvedAccount:H,avsConfig:V,avsCheckProp:W,sessionId:e,nonce:t,baseUrl:ce};let vo=Oe(!1),Ti=Pe(()=>{let{resolvedAccount:r,avsConfig:b,avsCheckProp:z}=Hn.current,ne=$t.current||r.country||"US",D=b?Te(b.state,ne):!1,Z=b?Te(b.address_line_1,ne):!1,Xe=b?Te(b.postal_code,ne):!1,Ct=b?Te(b.city,ne):!1,_t=b?Te(b.address_line_2,ne):!1,nt=Z&&!D&&Xe?Za(ne,(ht.current??"").trim()):null,xt=D?yn.current:nt;return{accountData:{userId:r.userId??"",email:r.email??"",firstName:r.firstName??"",lastName:r.lastName??"",...Xe&&ht.current?{zip:ht.current}:{},...Ct&&an.current?{city:an.current}:{},...xt?{state:xt}:{},...Z&&Dt.current?{addressLine1:Dt.current}:{},..._t&&Gt.current?{addressLine2:Gt.current}:{},country:ne},...z!==void 0?{avsCheck:z}:{},...b?{avsConfig:{country:Te(b.country,ne),postal_code:Xe,address_line_1:Z,address_line_2:_t,city:Ct,state:D}}:{}}},[]);yt(()=>{!ke||!tt||tt.setSubmitGate?.(jt)},[ke,tt,jt]),yt(()=>{if(!ke||!tt)return;vo.current=!1;let r=!1,b=tt.on("submitting",()=>{sn(!0),P("processing");let{baseUrl:Z,sessionId:Xe,nonce:Ct,updateError:_t,onError:nt}=Hn.current;!Xe||!Ct||new On(Z).patchAccountSnapshot(Xe,Ct,Ti(),{telemetryMode:"best_effort"}).catch(xt=>{if(!Ns(xt))return;let Fe=xt instanceof Error?xt.message:"Please check your billing address and try again.";_t(Fe),P(null),nt?.(xt instanceof wn?xt:new wn(Fe,"api_error"))})}),z=tt.on("complete",async Z=>{ur(Z.sessionId??Hn.current.sessionId),P("success"),await new Promise(Xe=>setTimeout(Xe,Mn)),!vo.current&&(vo.current=!0,Hn.current.onComplete?.({status:"succeeded",paymentIntentId:Z.intentId,checkoutMethod:"card"}))}),ne=tt.on("decline",async Z=>{let{updateError:Xe,emitDecline:Ct}=Hn.current,_t=Z.message??"Your payment was declined. Please try another card or contact your bank.";Xe(_t),P("error"),Ct("card",_t,Z.declineReason?{declineCode:Z.declineReason}:void 0),await new Promise(nt=>setTimeout(nt,Cn)),!r&&P(null)}),D=tt.on("error",async Z=>{let{updateError:Xe,onError:Ct}=Hn.current,_t=Z.message??"There was a problem processing your payment. Please try again.";Xe(_t),P("error"),Ct?.(new wn(_t,"api_error")),await new Promise(nt=>setTimeout(nt,Cn)),!r&&P(null)});return()=>{r=!0,b(),z(),ne(),D()}},[ke,tt]);let bn=!!Qe?.clientId,wr=Array.isArray(y),jr=wr&&y.length>0,Mi=wr&&y.includes("paypal"),{expressMethods:Vr,paymentElementMethods:kr}=ot(()=>Ms(y,{excludePaypal:bn}),[y,bn]),ca=bn||!!We,Bi=ot(()=>ca?Vr.filter(r=>r!=="paypal"):Vr,[Vr,ca]),Ai=ot(()=>{let r=[];return K&&r.push("apple_pay"),ue&&r.push("google_pay"),r},[K,ue]),Hr=wr?Bi:Ai,Fi=T&&Hr.length>0,Co=Fn?je:De,Kr=ot(()=>{let r=Co?.trim().toUpperCase();return r?U?kr.filter(b=>{let z=U[b];return!z||z.length===0||z.includes(r)}):_s(kr,Co):kr},[kr,Co,U]),So=ot(()=>({mode:"payment",amount:Ce,currency:Ie.toLowerCase(),paymentMethodCreation:"manual",appearance:ln}),[Ce,Ie,ln]),[da,ua]=ge("loading"),[pa,ma]=ge("loading"),[ya,fa]=ge("loading"),[Di,wo]=ge(!1),[ga,ko]=ge("loading"),[Wr,Li]=ge();yt(()=>{Li(Ha())},[]);let ha=w&&(bn||(wr?Mi:Wr===!1)),Pa=T&&Fi,Rr=ha&&bn,ba=ga==="retrying"||ga==="exhausted",Ir=ha&&!!xe&&(!bn||ba),Er=Pa&&!!ct,_r=T&&jr&&Kr.length>0&&!!ct,Ni=Rr&&!ba?Di:Ir&&ai(da),Oi=Er&&ai(pa),zi=_r&&ya!=="load_error",va=r=>r==="loading"||r==="ready",Ca=Rr||Ir&&va(da)||Er&&va(pa)||_r&&ya!=="load_error",Yr=Oe(!1);yt(()=>{if(!Yr.current){if(!T&&!w){Yr.current=!0;let r=new wn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(r),de(r.message)}else if(!T&&w&&!bn&&!xe){Yr.current=!0;let r=new wn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(r),de(r.message)}else if(Wr!==void 0&&!Je&&!Ca){Yr.current=!0;let r=new wn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(r),de(r.message)}}},[T,w,bn,xe,Wr,Je,Ca,c,de]);let Sa=Oe(!1);yt(()=>{if(Sa.current||!jr)return;let r=[];K!==!0&&r.push("showApplePay"),ue!==!0&&r.push("showGooglePay"),r.length!==0&&(Sa.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.`))},[jr,K,ue]);let wa=Pe((r,b)=>qe.applyInlineSessionPatch?qe.applyInlineSessionPatch(r).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let ne=ri(b,z);return de(ne.message),c?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[qe.applyInlineSessionPatch,t,c,e,de]),dn=Pe(async r=>{if(!ye)return{proceed:!0};try{let b=await ye({method:r,sessionId:e||void 0,createSession:qe.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&qn(ne=>({...ne??{},...b.account}));let z=await wa(b,r);return z.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(b){let z=ri(r,b);return de(z.message),c?.(z),{proceed:!1}}},[wa,qe.inlineSessionDraft,ye,c,e,de]),ka=Pe(async(r,b)=>{if(ae.current)return;ae.current=!0,Rt(!0),P("processing"),de(null);let z=b?.sessionId??e,ne=b?.nonce??t,D=zo(H,b?.accountPatch),Z=b?.completionPaymentMethodId??ro(r),Xe=r.originalPaymentMethodId?{...r,originalPaymentMethodId:void 0}:r;try{let _t=await new On(ce).processPayment(D.userId??"",{sessionId:z,nonce:ne,tokenizedData:Xe,accountData:{userId:D.userId??"",email:D.email??"",firstName:D.firstName??"",lastName:D.lastName??"",...V?(()=>{let Fe=$t.current,en=Te(V.state,Fe),tn=Te(V.address_line_1,Fe),Gn=Te(V.postal_code,Fe),Jn=tn&&!en&&Gn?Za(Fe,(ht.current??"").trim()):null,Tt=en?yn.current:Jn;return{country:Fe,...Gn&&ht.current?{zip:ht.current}:{},...Te(V.city,Fe)&&an.current?{city:an.current}:{},...Tt?{state:Tt}:{},...tn&&Dt.current?{addressLine1:Dt.current}:{},...Te(V.address_line_2,Fe)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:R,avsCheck:W??!1,checkoutType:x,checkoutLayout:j,avsConfig:V?{country:Te(V.country,$t.current),postal_code:Te(V.postal_code,$t.current),address_line_1:Te(V.address_line_1,$t.current),address_line_2:Te(V.address_line_2,$t.current),city:Te(V.city,$t.current),state:Te(V.state,$t.current)}:void 0});if(_t.ok){ur(z),P("success"),g(null),await new Promise(Fe=>setTimeout(Fe,Mn)),a?.({status:"succeeded",paymentIntentId:r.threeDSecureActionResultTokenId,paymentMethodId:Z,checkoutMethod:r.isPaypal?"paypal":"card"});return}let nt=await _t.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let Fe=nt.threeDSecureToken,en=nt.paymentMethodId||r.id||"";if(!Ue||!Fe){P("error"),de("PayPal authorization required but no token provided.");return}try{let tn=We?.getRawProvider();if(!tn){de("PayPal is not available.");return}let Gn={return_url:window.location.href};en&&(Gn.payment_method=en);let{error:Jn}=await tn.confirmPayment({clientSecret:Fe,confirmParams:Gn,redirect:"if_required"});if(Jn){P("error");let Tt=Jn.message??"PayPal payment failed.";de(Tt),cn("paypal",Tt,{code:Jn.code})}}catch(tn){P("error"),de(tn instanceof Error?tn.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let Fe=nt.orderId;if(!Fe){P("error"),de("PayPal retry required but no order id provided.");return}let en=_e.current?.attempts??0;if(en>=2){P("error"),de("PayPal payment could not be completed after multiple attempts."),cn("paypal","paypal_direct_required retry limit exceeded");return}wo(!1),ko("loading"),g({orderId:Fe,attempts:en+1}),P(null);return}P("error");let xt=nt?.message??"Payment failed. Please try again.";de(xt),cn(r.isPaypal?"paypal":"card",xt,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(Fe=>setTimeout(Fe,Cn))}catch(Ct){P("error"),de(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(_t=>setTimeout(_t,Cn))}finally{Rt(!1),P(null),ae.current=!1}},[ce,e,t,H,Ke,R,Ue,We,a,c,de,cn]),Qt=Pe((r,b)=>{S?S(r):ka(r,b)},[S,ka]),Ra=Oe(!1);yt(()=>{if(typeof window>"u"||Ra.current)return;let r=new URLSearchParams(window.location.search),b=r.get("payment_intent"),z=r.get("payment_intent_client_secret"),ne=r.get("redirect_status");if(!b||!z)return;let D=xt=>{let Fe=localStorage.getItem(xt);if(!Fe)return null;try{return JSON.parse(Fe)}catch{return localStorage.removeItem(xt),null}},Z=D(kn)??D(ti),Xe;if(Z?.clientSecret){if(Z.clientSecret!==z)return;Xe={...Z.accountPatch?{accountPatch:Z.accountPatch}:{},...Z.sessionId?{sessionId:Z.sessionId}:{},...Z.nonce?{nonce:Z.nonce}:{}}}else if(Z?.sessionId&&Z.sessionId!==e)return;Ra.current=!0,localStorage.removeItem(kn),localStorage.removeItem(ti);let Ct=new URL(window.location.href);Ct.searchParams.delete("payment_intent"),Ct.searchParams.delete("payment_intent_client_secret"),Ct.searchParams.delete("redirect_status"),window.history.replaceState({},"",Ct.toString());let _t=Z?.paymentMethodType??Z?.tokenType??"card",nt="card";(async()=>{let xt=Ue?.getRawProvider();if(!xt){let Tt="Payment is not available \u2014 please refresh and try again.";de(Tt),cn(nt,Tt);return}if(ne==="failed"){let Tt="Payment was declined. Please try again.";de(Tt),cn(nt,Tt);return}let{paymentIntent:Fe,error:en}=await xt.retrievePaymentIntent(z);if(en){let Tt=en.message??"Failed to retrieve payment status.";de(Tt),cn(nt,Tt,{code:en.code});return}let tn=Fe?.status,Gn=no(tn);if(!Fe||!Gn){let Tt=tn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";de(Tt),cn(nt,Tt,{code:tn??"missing_payment_intent"});return}let Jn=typeof Fe.payment_method=="string"?Fe.payment_method:Fe.payment_method?.id;Qt({id:Jn??Z?.paymentMethodId??Z?.tokenId??Fe.id,type:"card",threeDSecureActionResultTokenId:Fe.id,gateway:Z?.gateway??"stripe",paymentMethodType:_t},Xe)})()},[e,Qt,Ue,de,cn]);let Ro=Pe(r=>{r.preventDefault()},[]);if(!(Ue!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let xr=X==="buttons",Vt=Ft?.variables,Ui=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Io=Vt?.colorBackground,$i=Io&&!Ui.has(Io)?Io:void 0,Tr=A.cardInputBorder??(xr?"#e5e7eb":"#A4A4FF"),Eo=Vt?.colorDanger??"#dc2626",Kn=r=>Jt&&r?Eo:Tr,Gr=(Et.malformed||Et.empty)&&(xn||Jt),qi=Gr?Eo:Kn(Lt.zip),_o=A.cardFormContainer?.backgroundColor??$i??(xr?"white":"#EDEDFF"),Mr=A.cardInputBackground??Vt?.colorBackground??"white",xo=ar(q),Ia=ar(re),or=A.nameInput,Ea=A.cardInputFontSize??Vs(or?.fontSize)??Vt?.fontSizeBase??"16px",_a=typeof or?.fontFamily=="string"?or.fontFamily:Vt?.fontFamily??"Poppins, sans-serif",xa=oi(or?.fontWeight)??400,ji=A.cardInputColor??(typeof or?.color=="string"?or.color:void 0)??Vt?.colorText??"#262833",Vi=A.cardInputPlaceholderColor??"#9ca3af",gt=Vt?.borderRadius??"8px",Wn=Vt?.borderRadius??A.cardButton?.borderRadius??gt,Yn=Vt?.colorPrimary??"#4A49FF",Hi=Vt?.colorPrimaryHover??lo(Yn,.12),To=Vt?.colorText??"#262833",Ta={fontSize:Ea,fontFamily:_a,fontWeight:xa,color:ji,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ki={"--flopay-input-placeholder-color":Vi,"--flopay-input-font-size":Ea,"--flopay-input-font-family":_a,"--flopay-input-font-weight":String(xa)},Br=A.cardFormContainer??{},Mo=Br.padding??(xr?"0":"1rem"),Bo=Br.borderRadius??gt,Wi=tt&&Nt?d(Do,{capture:tt,html:Nt.html,messageToken:Nt.messageToken,expectedOrigin:Nt.expectedOrigin,theme:F,onReady:()=>{if(!V||typeof document>"u")return;let r=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};r();let b=0,z=window.setInterval(()=>{b+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(r(),window.clearInterval(z)):b>=50&&window.clearInterval(z)},100)},onError:r=>de(r),onValidation:r=>{de(r),r&&P(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"}),Ma=Me("div",{style:{backgroundColor:_o,borderRadius:Bo,...Br,padding:Mo,...Ki,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
|
@@ -35,13 +35,13 @@ ${Xe.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,_a=we==="apm-expanding"||we==="apm-form"||we==="apm-collapsing",Kr=we==="apm-expanding"?`flopay-card-enter ${Pt}ms cubic-bezier(0, 0, 0.2, 1) both`:we==="apm-collapsing"?`flopay-card-exit ${Pt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Wr=rt?{...go,paymentMethodTypes:[rt]}:null;if(oe==="buttons"){let o=we==="buttons"||we==="expanding"||we==="apm-expanding",v=we==="expanding"||we==="card"||we==="collapsing",U=z===void 0?{boxSizing:"border-box",height:oo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},re=we==="expanding"||we==="apm-expanding"?`flopay-buttons-exit ${Pt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:we==="collapsing"||we==="apm-collapsing"?`flopay-buttons-enter ${Pt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,O=we==="expanding"?`flopay-card-enter ${Pt}ms cubic-bezier(0, 0, 0.2, 1) both`:we==="collapsing"?`flopay-card-exit ${Pt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return xe("form",{onSubmit:bo,className:C,style:{position:"relative"},children:[d(Oo,{}),Vt&&d(vn,{status:Vt,errorMessage:N}),xe("div",{style:{display:"grid"},children:[xe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!o&&!re?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!o&&!re?Bs:{},...re?{animation:re,pointerEvents:"none"}:{}},children:[Ia("flopay-direct-paypal-gate-debug"),Ea("flopay-stripe-gate-debug"),vr&&Xe&&xe(cr,{children:[zt&&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(no,{sessionId:e,nonce:t,billingApiUrl:L,email:J.email,clientId:Xe.clientId,environment:Xe.environment,currency:Re.toUpperCase(),isSubscription:Je,onTokenizedBody:Xt,onComplete:a,onErrorChange:I,onDecline:s,onTechnicalFailure:Q,onButtonClick:fe,runBeforeButtonClick:ln,isProcessing:W,onLoadStateChange:ho,onInitializationStateChange:Po,session:m??null,existingOrderId:zt?.orderId,debug:Ue},zt?.orderId??"fresh")]}),Cr&&d(Jn,{stripe:A,options:sn,children:d(ei,{sessionId:e,nonce:t,email:J.email,billingApiUrl:L,onTokenizedBody:Xt,onErrorChange:I,isProcessing:W,onButtonClick:fe,onDecline:s,onTechnicalFailure:Q,runBeforeButtonClick:ln,onLoadStateChange:aa,placeholderBorderRadius:Vn})}),wr?d(Jn,{stripe:ot,options:ze,children:d(ti,{sessionId:e,nonce:t,email:J.email,billingApiUrl:L,intentKind:le>0?"payment":"setup",expressMethods:Ur,onTokenizedBody:Xt,onErrorChange:I,onButtonClick:fe,onDecline:s,onTechnicalFailure:Q,runBeforeButtonClick:ln,onLoadStateChange:sa,placeholderBorderRadius:Vn})}):pa?d("div",{style:{height:oo,borderRadius:Vn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Sr&&d(ni,{sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:L,paymentElementMethods:$r,stripeInstance:ot,paymentElementBaseOptions:go,onTokenizedBody:Xt,onErrorChange:I,onButtonClick:fe,onDecline:s,runBeforeButtonClick:ln,onLoadStateChange:ca,isProcessing:W,submitButtonColor:Hn,submitButtonBorderRadius:ft,submitButtonStyle:u.submitButton,onExpandApm:_n,expandedApmMethod:rt,themeId:D,buttonAppearance:{backgroundColor:u.cardButton?.backgroundColor,borderColor:u.cardInputBorder,textColor:u.cardButton?.color,borderRadius:Vn}}),y&&d("button",{type:"button",onClick:async()=>{W||!(await ln("card")).proceed||(fe?.("card"),an())},disabled:W,style:{width:"100%",...U,...u.cardButton,...Vo({themeBundle:M,resolvedPrimaryColor:Hn,resolvedBorderRadius:ft,submitButtonStyle:u.submitButton,explicitPrimaryColor:qt?.colorPrimary}),fontSize:u.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:W?"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:W?.6:1},onMouseEnter:ee=>{!W&&(M||qt?.colorPrimary)&&(ee.currentTarget.style.backgroundColor=Oi)},onMouseLeave:ee=>{(M||qt?.colorPrimary)&&(ee.currentTarget.style.backgroundColor=Hn)},onMouseDown:ee=>{ee.currentTarget.style.transform="scale(0.985)"},onMouseUp:ee=>{ee.currentTarget.style.transform="scale(1)"},children:d(tr,{content:z})}),N&&we==="buttons"&&d(or,{margin:"0.25rem 0",styleOverride:u.errorBanner,children:N})]}),y&&v&&d("div",{style:{gridArea:"1 / 1",...O?{animation:O}:{},...we==="collapsing"?{pointerEvents:"none"}:{}},children:Ra}),T&&_a&&rt&&Wr&&ot&&d("div",{style:{gridArea:"1 / 1",...Kr?{animation:Kr}:{},...we==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:wo,borderRadius:Io,...Er,padding:Ro},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:hn,style:{display:"inline-flex",alignItems:"center",gap:So?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.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",...u.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(nr,{content:V})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:ko,paddingRight:80,...u.title},children:`Pay with ${dr(rt)}`})]}),d(Jn,{stripe:ot,options:Wr,children:d(Uo,{method:rt,sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:L,onTokenizedBody:Xt,onErrorChange:I,onDecline:s,onCancel:hn,runBeforeButtonClick:ln,onButtonClick:fe,isProcessing:W,submitButtonColor:Hn,submitButtonBorderRadius:ft,submitButtonStyle:u.submitButton,errorText:N})},rt)]})})]})]})}return _a&&rt&&Wr&&ot&&T?xe("form",{onSubmit:bo,className:C,style:{position:"relative"},children:[d(Oo,{}),Vt&&d(vn,{status:Vt,errorMessage:N}),d("div",{style:{...Kr?{animation:Kr}:{},...we==="apm-collapsing"?{pointerEvents:"none"}:{}},children:xe("div",{style:{backgroundColor:wo,borderRadius:Io,...Er,padding:Ro},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:hn,style:{display:"inline-flex",alignItems:"center",gap:So?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:u.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...u.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",...u.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(nr,{content:V})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:u.titleFontSize??"1.05rem",color:ko,paddingRight:80,...u.title},children:`Pay with ${dr(rt)}`})]}),d(Jn,{stripe:ot,options:Wr,children:d(Uo,{method:rt,sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:L,onTokenizedBody:Xt,onErrorChange:I,onDecline:s,onCancel:hn,runBeforeButtonClick:ln,onButtonClick:fe,isProcessing:W,submitButtonColor:Hn,submitButtonBorderRadius:ft,submitButtonStyle:u.submitButton,errorText:N})},rt)]})})]}):xe("form",{onSubmit:bo,className:C,style:{position:"relative"},children:[d(Oo,{}),Vt&&d(vn,{status:Vt,errorMessage:N}),xe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ia("flopay-direct-paypal-gate-debug-default"),Ea("flopay-stripe-gate-debug-default"),vr&&Xe&&xe(cr,{children:[zt&&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(no,{sessionId:e,nonce:t,billingApiUrl:L,email:J.email,clientId:Xe.clientId,environment:Xe.environment,currency:Re.toUpperCase(),isSubscription:Je,onTokenizedBody:Xt,onComplete:a,onErrorChange:I,onDecline:s,onTechnicalFailure:Q,onButtonClick:fe,runBeforeButtonClick:ln,isProcessing:W,onLoadStateChange:ho,onInitializationStateChange:Po,session:m??null,existingOrderId:zt?.orderId,debug:Ue},zt?.orderId??"fresh")]}),Cr&&d(Jn,{stripe:A,options:sn,children:d(ei,{sessionId:e,nonce:t,email:J.email,billingApiUrl:L,onTokenizedBody:Xt,onErrorChange:I,isProcessing:W,onButtonClick:fe,onDecline:s,onTechnicalFailure:Q,runBeforeButtonClick:ln,onLoadStateChange:aa,placeholderBorderRadius:Vn})}),wr&&d(Jn,{stripe:ot,options:ze,children:d(ti,{sessionId:e,nonce:t,email:J.email,billingApiUrl:L,intentKind:le>0?"payment":"setup",expressMethods:Ur,onTokenizedBody:Xt,onErrorChange:I,onButtonClick:fe,onDecline:s,onTechnicalFailure:Q,runBeforeButtonClick:ln,onLoadStateChange:sa,placeholderBorderRadius:Vn})}),Sr&&d(ni,{sessionId:e,nonce:t,email:J.email,billingName:[J.firstName,J.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:L,paymentElementMethods:$r,stripeInstance:ot,paymentElementBaseOptions:go,onTokenizedBody:Xt,onErrorChange:I,onButtonClick:fe,onDecline:s,runBeforeButtonClick:ln,onLoadStateChange:ca,isProcessing:W,submitButtonColor:Hn,submitButtonBorderRadius:ft,submitButtonStyle:u.submitButton,themeId:D,onExpandApm:_n,expandedApmMethod:rt,buttonAppearance:{backgroundColor:u.cardButton?.backgroundColor,borderColor:u.cardInputBorder,textColor:u.cardButton?.color,borderRadius:Vn}})]}),y&&(Mi||Ti||Bi)&&xe("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"}})]}),y&&Ra]})}import{loadFloPay as ci,PaymentAPI as di}from"@flopay/js";import{FloPayError as it,isSetupIntentClientSecret as Us}from"@flopay/shared";var Dr="card";async function $s(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:i,error:r}=await e.retrievePaymentIntent(t);return{error:r,intent:i??null}}async function qs(e,t,n,i){if(i){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:r,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:r??null}}function Sn(e,t){return Object.assign(e,{checkoutMethod:t})}function ui(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 js(e){return e.status==="succeeded"||e.status==="declined"}async function pi(e){if(typeof document>"u"||typeof window>"u")throw new it("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new it("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,i=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let p=new AbortController,R=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",R);let C=window.setTimeout(()=>p.abort(),i);try{let E=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:p.signal});if(!E.ok)return{status:"unknown"};let l=await E.json().catch(()=>null);return Vs(l)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",R)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let w=document.createElement("iframe");w.setAttribute("title","Card authentication"),w.setAttribute("allow","payment"),w.tabIndex=0,w.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),w.src=e.nextActionRedirectUrl,s.appendChild(w),document.body.appendChild(s),w.focus();let B=null;try{B=new URL(e.billingApiUrl,window.location.href).origin}catch{B=null}try{let p=await new Promise((R,C)=>{let E=!1,l=0,f=0,S=0,T=!1,h=()=>{window.clearTimeout(l),window.clearInterval(f),window.clearTimeout(S),window.removeEventListener("message",oe),w.removeEventListener("load",Y),e.signal?.removeEventListener("abort",ce)},q=async()=>{if(!(E||T)){T=!0;try{let D=await a();if(E||!js(D))return;E=!0,h(),R(D)}finally{T=!1}}},Y=()=>{window.clearTimeout(S),S=window.setTimeout(()=>{q()},250)},ce=()=>{E||(E=!0,h(),C(new it("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},oe=D=>{if(D.source!==w.contentWindow||B&&D.origin!==B)return;let X=D.data;!X||typeof X!="object"||X.source!=="flopay-vault-3ds-return"||E||(E=!0,h(),R(null))};l=window.setTimeout(()=>{E||(E=!0,h(),C(new it("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),f=window.setInterval(()=>{q()},n),w.addEventListener("load",Y),window.addEventListener("message",oe),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return p||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function Vs(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 On(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,a=Dn(r)??r;return Sn(new it(a,"api_error",{code:e?.gatewayErrorCode}),i)}function Ko(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function io(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Hs(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 r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||io(r)))return r;let i=e?.data;if(i&&typeof i=="object"){let r=i,a=[r.threeDSecureToken,r.clientSecret,r.stripeClientSecret,r.id];for(let s of a)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||io(s)))return s;let c=r.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let w=s,B=[w.stripeClientSecret,w.clientSecret];for(let p of B)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||io(p)))return p}}}}async function Ks({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let r=mi(i,{requirePaymentIntentClientSecret:!0});if(typeof r=="string"&&r.length>0)return{type:"3ds_required",threeDSecureToken:r};if(!t)return null;try{let s=(await new di(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(io(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function ur({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:r,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),w=t??n.id,B=i??n.clientSecret,p=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",C=n.customer?.firstName??n.accountData?.firstName??"",E=n.customer?.lastName??n.accountData?.lastName??"",l=n.customer?.country??n.accountData?.country??void 0,f=n.customer?.zip??n.accountData?.zip??void 0,S=new di(s,c===!1?{telemetry:!1}:void 0),T=await Hs(()=>S.processPayment(p,{sessionId:w,nonce:B,tokenizedData:r,accountData:{userId:p,email:R,firstName:C,lastName:E,country:l,zip:f},returnUrl:a??Ko(n)}));if(T.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:Zr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}};let h=await T.json().catch(()=>null);if(h?.type==="paypal_redirect_required"||h?.type==="3ds_required"){let q=mi(h);if(!q)throw new it("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:h.type,threeDSecureToken:q,paymentMethodId:h.paymentMethodId}}if(h?.gatewayErrorCode==="authentication_required"){let q=await Ks({billingApiUrl:s,sessionId:w,nonce:B,responseJson:h});if(q)return q;throw Sn(new it("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new it(h?.message??"Payment failed. Please try again.","api_error",{code:h?.code??h?.gatewayErrorCode,declineCode:h?.declineCode??h?.gatewayDeclineReason})}async function so(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:w}){let B=t?.getRawProvider();if(!B)throw new it("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw Sn(new it("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let p=Us(e.threeDSecureToken),R=null,C=e.paymentMethodId,E=await $s(B,e.threeDSecureToken,p);if(E){if(E.error)throw Sn(new it(E.error.message??`Failed to retrieve 3DS ${p?"setup":"payment"} status.`,"api_error",{code:E.error.code}),"card");let f=E.intent;!C&&f?.payment_method&&(typeof f.payment_method=="string"?C=f.payment_method:"id"in f.payment_method&&(C=f.payment_method.id??void 0))}let l=C?await qs(B,e.threeDSecureToken,{payment_method:C,return_url:s??Ko(c)??window.location.href},p):null;if(l){if(l.error)throw Sn(new it(l.error.message??"3DS authentication failed.","api_error",{code:l.error.code}),"card");R=l.intent}else{let f=await B.handleNextAction({clientSecret:e.threeDSecureToken});if(f.error)throw Sn(new it(f.error.message??"3DS authentication failed.","api_error",{code:f.error.code}),"card");R=(p?f.setupIntent:f.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let f=await ur({billingApiUrl:r,sessionId:a,session:c,telemetry:w,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:s});return f.type==="success"?{...f.result,paymentIntentId:f.result.paymentIntentId??R.id,paymentMethodId:f.result.paymentMethodId??C}:so(f,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:w})}throw Sn(new it("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let p=(n??t)?.getRawProvider();if(!p)throw Sn(new it("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await p.handleNextAction({clientSecret:e.threeDSecureToken});if(C)throw Sn(new it(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await p.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Ko(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(R)throw Sn(new it(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new it("Unsupported payment redirect state.","api_error")}function Xn(e){if(e instanceof it){let i=Dn(e.message);return i&&i!==e.message?Object.assign(new it(i,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Dn(t)??t;return new it(n,"api_error")}function lo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new it("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 co({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:i,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[c,s]=await Promise.all([ci(e,{billingApiUrl:n,locale:i,telemetry:r}),a?ci(t,{billingApiUrl:n,locale:i,telemetry:r}).catch(w=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",w),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{Fragment as kn,jsx as te,jsxs as Rt}from"react/jsx-runtime";var pr=44,Qo="flopay_checkout_saved_payment_resume",Yo=new Map;function Lr(e){return new Promise(t=>setTimeout(t,e))}function po(e,t,n){let i=Yr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Pi,enabled:t!==!1});return i.beginCheckout(n),i}function mo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Go(e,t,n,i,r){let a=po(e,t,n);a.error({errorCode:i,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),mo(a)}function Js(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 Zo(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function Jo(e){return!e||e.data.stripe?.publishableKey?!1:!!Zo(e)?.clientId}function mr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Xs(){if(!mr())return null;try{let e=window.sessionStorage.getItem(Qo);return e?JSON.parse(e):null}catch{return null}}function fi(e){if(mr())try{window.sessionStorage.setItem(Qo,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Xo(){if(mr())try{window.sessionStorage.removeItem(Qo)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Zs(e){if(!mr())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 Qs(e,t,n){if(mr())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(i){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",i)}}function gi(e){if(mr())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function el(){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 i of t)e.searchParams.has(i)&&(e.searchParams.delete(i),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 tl(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 ea({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:r,appearance:a,locale:c,loading:s,error:w,onComplete:B,onError:p,onDecline:R,onCountryChange:C,onZipChange:E,showPayPal:l=!0,showStripe:f=!0,showApplePay:S=!0,showGooglePay:T=!0,debug:h=!1,layout:q,theme:Y,buttonsTheme:ce,buttonsStyles:oe,cardButtonContent:D,cardBackButtonContent:X,cardTitleContent:j,showSecurityFooter:de,onButtonClick:z,onBeforeButtonClick:V,enableAVS:ae,cardFieldOrder:Be,cardPreFormSlot:fe,avsLayout:ye,className:Z,initialErrorMessage:ue=null,children:he,checkoutMode:ie,confirmLabel:Fe,renderConfirmButton:ke,onSessionCompleted:ve}){let k=Ys(i),ne=dn(()=>bi(Y),[Y]),se=a??ne?.appearance,Ne=n?"embedded_checkout":"standard_checkout",De=he?"custom_layout":q==="buttons"?"buttons_layout":"default_layout",[G,x]=kt(null),[H,le]=kt(null),Re=nn(null),[gt,Xe]=kt(null),Je=nn(null),[m,Ue]=kt(null),[Oe,Ve]=kt(e??""),$e=e??Oe,Kt=n?"":$e,[bt,It]=kt(!0),[g,Ce]=kt(null),[qe,st]=kt("full"),[tt,Ze]=kt(!1),[Ye,Pe]=kt(ue),[vt,je]=kt(null),[Dt,Et]=kt(null),[un,Rn]=kt(void 0),[In,$n]=kt(""),[ht,Lt]=kt(!1),[Ft,Wt]=kt("loading"),[rn,pn]=kt(0),K=nn(!1),An=nn(!1),mn=nn(!1),Nt=nn(null),nt=dn(()=>({checkoutMode:ie??qe,layout:he?"unknown":q==="buttons"?"buttons":"embedded"}),[ie,he,qe,q]),y=nn(B);y.current=B;let Ie=nn(p);Ie.current=p;let lt=nn(R);lt.current=R,Bn(()=>{Mt(H)?.setCheckoutContext(nt),gt&>!==H&&Mt(gt)?.setCheckoutContext(nt)},[H,gt,nt]);let En=nn(ve);En.current=ve;let Ee=Zn(_=>{Wt(_),!(_!=="exhausted"||mn.current)&&(mn.current=!0,Ie.current?.(new Bt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Fn=Zn(()=>{Wt("retrying"),pn(_=>_+1)},[]);Bn(()=>{Wt("loading"),pn(0),mn.current=!1},[$e]),Bn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Pi,checkout_type:Ne,checkout_layout:De,billing_api_url:k})},[De,Ne,k]);let yn=dn(()=>n?on(n):"",[n]),qn=dn(()=>In===yn?un:void 0,[un,In,yn]),fn=dn(()=>n?Bo(n,qn):void 0,[n,qn]),Ot=ie??fn?.checkoutMode??"full",At=dn(()=>fn?{...fn,checkoutMode:Ot}:void 0,[fn,Ot]);Bn(()=>{Rn(void 0),$n(yn)},[yn]),Bn(()=>{Pe(ue)},[ue]);let we=Zn((_,L,N)=>{ut(()=>{lt.current?.(St(_,L,N))})},[ut]),yt=Zn(async(_,L)=>{Pe(null),Et(null),je("processing");let N=L?.sessionId??_.id,M=Re.current??Je.current,u=Mt(M),$=M?null:po(k,r,nt),b={log:F=>{u?u.log(F):$?.log(F)},error:F=>{u?u.error(F):$?.error(F)},terminal:F=>{u?u.terminal(F):$?.terminal(F)},performance:F=>{u?u.performance(F):$?.performance(F)},now:()=>u?.now()??$?.now()??0,elapsed:F=>u?.elapsed(F)??Math.max(0,($?.now()??F)-F)},Te=b.now(),W=!!(L?.initialAutoProcessingError||L?.initialAutoProcessingPending),Ke=!1,J,$t=()=>{Ke||(Ke=!0,W=!0,J=b.now(),b.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ot=!1,A=()=>{ot||(ot=!0,b.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),b.performance({stage:"processing",durationMs:b.elapsed(Te),durationMode:"machine",paymentMethodCategory:"saved"}),J!==void 0&&b.performance({stage:"recovery",durationMs:b.elapsed(J),durationMode:"machine",paymentMethodCategory:"saved"}))};b.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),b.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),W&&$t();let P;try{let F=ui(L?.initialAutoProcessingError),me;if(F)$t(),F.type==="paypal_redirect_required"&&Nt.current?.publishableKey&&fi({sessionId:N,publishableKey:Nt.current.publishableKey,paypalPublishableKey:Nt.current.paypalPublishableKey}),me=await so(F,{flopay:Re.current,paypalFlopay:Je.current,attempt3DS:L?.attempt3DS,billingApiUrl:k,sessionId:N,session:_,telemetry:!1}),F.type==="paypal_redirect_required"&&Xo();else if(L?.initialAutoProcessingPending){let ze=await new uo(k,{telemetry:!1}).waitForCheckoutSessionCompletion(L.initialAutoProcessingPending.sessionId,{initialDelayMs:L.initialAutoProcessingPending.retryAfterMs});if(ze.data.session?.status!=="complete")throw new Bt("Automatic payment failed. Please try again.","api_error",{code:ze.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});me={status:"succeeded"}}else{if(L?.initialAutoProcessingError)throw On(L.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:L.initialAutoProcessingError.checkoutMethod});if(L?.fromCreateSession)return L?.fallbackToFull&&(st("full"),hi("full")),!1;{let Me=await ur({billingApiUrl:k,sessionId:N,session:_,telemetry:!1});Me.type==="success"?me=Me.result:($t(),Me.type==="paypal_redirect_required"&&Nt.current?.publishableKey&&fi({sessionId:N,publishableKey:Nt.current.publishableKey,paypalPublishableKey:Nt.current.paypalPublishableKey}),me=await so(Me,{flopay:Re.current,paypalFlopay:Je.current,attempt3DS:L?.attempt3DS,billingApiUrl:k,sessionId:N,session:_,telemetry:!1}),Me.type==="paypal_redirect_required"&&Xo())}}N&&ir(N),A(),W&&(b.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),b.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),je("success"),await Lr(Tn),P=()=>y.current?.(me)}catch(F){let me=Xn(F),Me=me.checkoutMethod??Dr;return Pe(me.message),Et(me.message),L?.fallbackToFull&&(b.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),st("full"),hi("full")),A(),!!(me.declineCode||me.code?.toLowerCase().includes("declin"))?b.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):me.type==="validation_error"?b.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):b.error({errorCode:W?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:W?"recovery":"processing",paymentMethodCategory:"saved"}),ut(()=>Ie.current?.(me)),we(Me,me,{code:me.code,declineCode:me.declineCode}),je("error"),await Promise.allSettled([Lr(bn),L?.ensureProvidersReady?L.ensureProvidersReady():Promise.resolve()]),W&&(b.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{A(),$&&mo($),je(null),Et(null)}return ut(P),!0},[we,ut,Xn,k,r,nt]);Bn(()=>{if(typeof window>"u"||An.current)return;let _=new URLSearchParams(window.location.search),L=_.get("payment_intent_client_secret");if(!L)return;let N=Xs();N&&(An.current=!0,(async()=>{let M,u=0;Pe(null),Et(null),je("processing"),Ze(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new Bt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:$,paypalFlopay:b}=await co({publishableKey:N.publishableKey,paypalPublishableKey:N.paypalPublishableKey,billingApiUrl:k,locale:c,telemetry:r});M=Mt(b??$),u=M?.now()??0,M?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),M?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Te=(b??$)?.getRawProvider();if(!Te)throw Object.assign(new Bt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:W,error:Ke}=await Te.retrievePaymentIntent(L);if(Ke)throw Object.assign(new Bt(Ke.message??"Failed to retrieve PayPal payment status.","api_error",{code:Ke.code}),{checkoutMethod:"paypal"});let J=La(W?.status);if(!W||J==="failed")throw Object.assign(new Bt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let $t=typeof W.payment_method=="string"?W.payment_method:W.payment_method?.id,ot=J;if(N.sessionId){let F=(await new uo(k,{telemetry:!1}).getUnifiedCheckoutSession(N.sessionId)).data.session;if(F&&F.status!=="complete"){let me=await ur({billingApiUrl:k,sessionId:N.sessionId,session:F,telemetry:!1,tokenizedData:{id:$t??W.id,type:"card",threeDSecureActionResultTokenId:W.id,isPaypal:!0}});if(me.type!=="success")throw Object.assign(new Bt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ot=me.result.status}}N.sessionId&&ir(N.sessionId),M?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),M?.performance({stage:"redirect_resume",durationMs:M.elapsed(u),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),M?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),je("success"),await Lr(Tn),ut(()=>y.current?.({status:ot,paymentIntentId:W.id,paymentMethodId:$t,checkoutMethod:"paypal"}))}catch($){let b=Xn($),Te=b.checkoutMethod??"paypal",W=!!(b.declineCode||b.code?.toLowerCase().includes("declin"));if(M)M.performance({stage:"redirect_resume",durationMs:M.elapsed(u),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),W?M.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):M.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(W){let Ke=po(k,r,nt);Ke.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),mo(Ke)}else Go(k,r,nt,"REDIRECT_RESUME_FAILED","redirect_resume");Pe(b.message),Et(b.message),ut(()=>Ie.current?.(b)),we(Te,b,{code:b.code,declineCode:b.declineCode}),je("error"),await Lr(bn)}finally{Xo(),el(),je(null),Et(null),Ze(!1)}})())},[we,ut,c,Xn,k,r]);let rt=nn(null);function on(_){let L=JSON.stringify({c:_?.clientId,cur:_?.currency??"",a:{e:_?.account?.email?.trim().toLowerCase()??"",country:_?.account?.country??""},successUrl:_?.successUrl,cancelUrl:_?.cancelUrl,p:_?.products?.map(M=>`${M.type??""}:${M.code??M.providerItemId??M.providerPlanId??""}:${M.totalAmount??""}:${M.overrideAmount??""}:${M.quantity??1}`).sort(),i:_?.items?.map(M=>`${M.code??M.providerItemId??""}:${M.totalAmount??""}:${M.overrideAmount??""}:${M.quantity??1}`).sort(),s:_?.subscriptions?.map(M=>`${M.code??M.providerPlanId??""}:${M.totalAmount??""}:${M.overrideAmount??""}:${M.quantity??1}`).sort(),couponCodes:_?.couponCodes,tagsData:_?.tagsData,utmMetadata:_?.utmMetadata,tokenizedData:_?.tokenizedData,m:_?.checkoutMode??"full"}),N=0;for(let M=0;M<L.length;M++)N=(N<<5)-N+L.charCodeAt(M)|0;return`flopay_session_${Math.abs(N).toString(36)}`}let Yt=dn(()=>At?on(At):"",[At]),Pt=nn(At);Pt.current=At,Bn(()=>{Ve(e??"")},[e]),Bn(()=>{K.current=!1,Pe(ue),Et(null),je(null)},[Yt,ue,e]);async function jt(_,L){let N=po(k,r,nt),M=new uo(k,{telemetry:!1});try{let u=Zs(L);N.log({name:u?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let $=u?.sid??null,b=null;if($)try{if(b=await M.getUnifiedCheckoutSession($,u?.nonce),b.data.session?.status==="complete"){if(Oa($))return{sid:$,result:b};gi(L),$=null,b=null}}catch{N.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),gi(L),$=null}if(!$){let Te=N.now();N.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let W={..._,avsCheck:!!ae,avsConfig:typeof ae=="object"?ae:void 0,checkoutType:"embedded_checkout",checkoutLayout:he?"custom_layout":q==="buttons"?"buttons_layout":"default_layout"};try{b=await M.createAndFetchSession(W),N.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),N.performance({stage:"session_create",durationMs:N.now()-Te,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(Ke){let J=Ws(Ke,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw N.performance({stage:"session_create",durationMs:N.now()-Te,durationMode:"machine",requestCategory:"session_create",statusClass:J.statusClass}),Ke instanceof Bt&&Ke.type==="validation_error"?N.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):J.statusClass==="4xx"?N.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):N.error({...J,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Ke}$=b.data.session?.id??"",$&&Qs(L,$,b.data.session?.clientSecret)}return{sid:$??"",result:b}}finally{mo(N)}}let Ct=Zn(async _=>{let L=Pt.current;if(!L)throw new Bt("createSession is required to bootstrap checkout.","validation_error");let N=Bo(L,_),M=on(N),u=Yo.get(M);u||(u=jt(N,M),Yo.set(M,u));let $;try{$=await u}finally{Yo.delete(M)}rt.current=M;try{_&&($n(yn),Rn(ot=>Fa(ot,_)));let{sid:b,result:Te}=$;x(Te),Te.data.session&&Ue(Te.data.session),b&&Ve(b);let{publishableKey:W,paypalPublishableKey:Ke}=lo(Te),{flopay:J,paypalFlopay:$t}=await co({publishableKey:W,paypalPublishableKey:Ke,billingApiUrl:k,locale:c,telemetry:r});Re.current=J,le(J),Je.current=$t,Xe($t),It(!1)}catch(b){throw rt.current===M&&(rt.current=null),b}return $},[c,k,r,nt]),an=Zn(async _=>{if(!tl(_)||ht)return{sessionId:Oe,session:m};Lt(!0);try{let L=await Ct(_);return{sessionId:L.sid,session:L.result.data.session??null}}finally{Lt(!1)}},[Ct,ht,Oe,m]);Bn(()=>{let _=!1;if(Ce(null),Yt){let M=Pt.current;return st(Ot),It(!1),rt.current===Yt?()=>{_=!0}:(Ue(Da(M,ie)),(async()=>{let u=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),$=Ot==="auto"&&!K.current&&!u;$&&(Pe(null),Et(null),je("processing"));try{let b=await Ct(),Te=b.result.data.session??null;Nt.current=lo(b.result);let W=Jo(b.result);if(!_&&$&&Te&&!W){K.current=!0,await yt(Te,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:b.result.autoProcessingError,initialAutoProcessingPending:b.result.autoProcessingPending,autoProcessingAttempted:b.result.autoProcessingAttempted,sessionId:b.sid||Te.id});return}!_&&$&&(W&&(K.current=!0),je(null),Et(null))}catch(b){if(_)return;let Te=b instanceof Bt||typeof b=="object"&&b!==null&&"code"in b?b.code:void 0;if($&&Te==="session_auto_completed"){K.current=!0,je("success"),await Lr(Tn),_||(ut(()=>{y.current?.({status:"succeeded"})}),je(null),Et(null));return}$&&(je(null),Et(null));let W=b instanceof Bt?b:new Bt(b instanceof Error?b.message:"Failed to create session","api_error");Ce(W)}})(),()=>{_=!0})}It(!0);async function L(){let M=!1;try{let $=await new uo(k,{telemetry:!1}).getUnifiedCheckoutSession($e,t);if(_)return;x($);let b=$.data.session??null;if(Ue(b),!b)throw new Bt("No session data returned","api_error");if(b.status==="complete"){It(!1),ut(()=>{En.current?.(b.successUrl??"")});return}if(b.status==="expired")throw new Bt("Checkout session has expired.","api_error",{code:"checkout_session_expired"});M=!0;let Te=ie??b.checkoutMode??"full";st(Te);let W=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ke=Jo($);if(Te==="auto"&&!K.current&&!W&&!Ke){K.current=!0;let J=N($);try{if(await yt(b,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>J,sessionId:$e||b.id}),_)return;await J,_||It(!1);return}catch{if(_)return;await J,_||It(!1);return}}await N($),_||It(!1)}catch(u){if(_)return;u instanceof Bt?!M&&!Js(u)&&Go(k,r,nt,"NETWORK_REQUEST_FAILED","session_read"):Go(k,r,nt,"INTERNAL_SDK_ERROR","checkout_mount");let $=u instanceof Bt?u:new Bt(u instanceof Error?u.message:"Failed to initialize checkout","api_error");Ce($),It(!1)}}async function N(M){let{publishableKey:u,paypalPublishableKey:$}=lo(M);Nt.current={publishableKey:u,paypalPublishableKey:$};let{flopay:b,paypalFlopay:Te}=await co({publishableKey:u,paypalPublishableKey:$,billingApiUrl:k,locale:c,telemetry:r});Re.current=b,le(b),Je.current=Te,Xe(Te)}return L(),()=>{_=!0}},[Ct,ie,Yt,Ot,Kt,ut,t,yt]);let gn=Zn(async()=>{if(!(tt||!m)){Ze(!0),Pe(null);try{await yt(m,{fallbackToFull:!0,sessionId:$e||m.id})}finally{Ze(!1)}}},[$e,tt,yt,m]),_n=Zo(G),hn=Jo(G),Vt=dn(()=>{if(!G||!m||!G.data.stripe?.publishableKey)return;let _={appearance:se,paymentMethodCreation:"manual",billingApiUrl:k};if(G.data.stripe?.clientSecret)_.clientSecret=G.data.stripe.clientSecret;else{let L=yi(m).total;_.amount=Math.round(L*100)||m.amount,_.currency=m.currency?.toLowerCase()}return _},[G,m,se,k]),He=!!(n&&!he&&q==="buttons"&&V&&Ot==="full"),Ht=dn(()=>({session:m,loading:bt,error:g,checkoutMode:qe,inlineSessionDraft:At,applyInlineSessionPatch:He?an:void 0,inlineSessionPatchProcessing:ht}),[m,bt,g,qe,At,He,an,ht]),zt=!!n&&q==="buttons"&&!hn&&(!H||!Vt),Ut=vt?te(vn,{status:vt,errorMessage:Dt}):null;if(bt){if(s)return Rt(kn,{children:[s,Ut]});if(q==="buttons"){let _=ne?.buttonsLayout?.cardButton?.borderRadius??ne?.appearance.variables?.borderRadius??8,L=N=>te("div",{style:{height:N,borderRadius:_,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Rt(kn,{children:[Rt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[l&&L(pr),f&&(S||T)&&L(pr),f&&L(pr),te("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ut]})}return Rt(kn,{children:[Rt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[te("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),te("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ut]})}return g?w?te(cn.Provider,{value:Ht,children:w(g)}):te(cn.Provider,{value:Ht,children:te("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:g.message})}):zt?Rt(kn,{children:[te(cn.Provider,{value:Ht,children:te(rl,{onButtonClick:z,showPayPal:l,showStripe:f,showApplePay:S,showGooglePay:T,theme:Y,buttonsTheme:ce,buttonsStyles:oe,cardButtonContent:D,cardBackButtonContent:X,cardTitleContent:j})}),Ut]}):hn&&m&&_n?Rt(kn,{children:[te(cn.Provider,{value:Ht,children:Rt("div",{className:Z,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ye&&te(or,{icon:!1,children:Ye}),Ft==="retrying"&&te("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ft==="exhausted"&&Rt("div",{role:"alert",children:[te("div",{children:"PayPal is temporarily unavailable. Please try again."}),te("button",{type:"button",onClick:Fn,children:"Retry PayPal"})]}),Ft!=="exhausted"&&te("div",{"aria-hidden":Ft==="retrying"?!0:void 0,style:Ft==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:te(Va,{sessionId:$e,nonce:m.clientSecret||void 0,billingApiUrl:k,email:m.customer?.email,clientId:_n.clientId,environment:_n.environment,currency:(m.currency??"usd").toUpperCase(),isSubscription:m.mode==="subscription",onComplete:B,onErrorChange:Pe,onDecline:R,onButtonClick:z,onInitializationStateChange:Ee,allowAutomaticRetry:rn===0,session:m,telemetry:r,telemetryContext:nt,debug:h},`paypal-init-${rn}`)})]})}),Ut]}):!H||!Vt?te(kn,{children:Ut}):qe==="confirm"?Rt(kn,{children:[te(cn.Provider,{value:Ht,children:te(Gr,{flopay:H,paypalFlopay:gt,options:Vt,children:Rt("div",{className:Z,children:[Ye&&te("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ye}),ke?ke({onConfirm:gn,isProcessing:tt}):te("button",{type:"button",onClick:gn,disabled:tt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:tt?"not-allowed":"pointer",opacity:tt?.6:1},children:tt?"Processing...":Fe??"Confirm Purchase"})]})})}),Ut]}):Rt(kn,{children:[te(cn.Provider,{value:Ht,children:te(Gr,{flopay:H,paypalFlopay:gt,options:Vt,children:he?Rt(kn,{children:[Ye&&te("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ye}),te(nl,{sessionId:$e,nonce:m?.clientSecret||void 0,billingApiUrl:k,session:m,children:he})]}):te(Ho,{sessionId:$e,nonce:m?.clientSecret||void 0,email:m?.customer?.email,userId:m?.customer?.id,firstName:m?.customer?.firstName,lastName:m?.customer?.lastName,totalAmount:m?Math.round(yi(m).total*100):0,currency:m?.currency?.toLowerCase()??"usd",onComplete:B,onError:p,onDecline:R,error:Ye,onErrorChange:Pe,showPayPal:l,showStripe:f,enabledPaymentMethods:G?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:G?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:T,layout:q,theme:Y,buttonsTheme:ce,buttonsStyles:oe,appearance:se,cardButtonContent:D,cardBackButtonContent:X,cardTitleContent:j,onButtonClick:z,onBeforeButtonClick:V,enableAVS:ae,...Be?{cardFieldOrder:Be}:{},...fe?{cardPreFormSlot:fe}:{},avsLayout:ye,country:m?.customer?.country,city:m?.customer?.city,state:m?.customer?.state,onCountryChange:C,onZipChange:E,avsCheck:!!ae,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:he?"custom_layout":q==="buttons"?"buttons_layout":"default_layout",className:Z,directPaypal:Zo(G),isSubscription:m?.mode==="subscription",session:m,debug:h})})}),Ut]})}function nl({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:r}){return te(kn,{children:Wo.Children.map(r,a=>{if(!Wo.isValidElement(a))return a;let c=a.props,s={};return c.sessionId||(s.sessionId=e),!c.nonce&&t&&(s.nonce=t),c.billingApiUrl||(s.billingApiUrl=n),i?.customer&&(c.email||(s.email=i.customer.email),c.userId||(s.userId=i.customer.id),c.firstName||(s.firstName=i.customer.firstName),c.lastName||(s.lastName=i.customer.lastName)),Object.keys(s).length===0?a:Wo.cloneElement(a,s)})})}function rl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:r,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:w,cardBackButtonContent:B,cardTitleContent:p}){let[R,C]=kt(!1),E=dn(()=>bi(a),[a]),l=dn(()=>{let h=E?.buttonsLayout??Gs(c);return s?{...h,...s,cardButton:{...h.cardButton,...s.cardButton},cardFormContainer:{...h.cardFormContainer,...s.cardFormContainer},backButton:{...h.backButton,...s.backButton},backButtonIcon:{...h.backButtonIcon,...s.backButtonIcon},submitButton:{...h.submitButton,...s.submitButton},title:{...h.title,...s.title}}:h},[E,c,s]),f=E?.buttonsLayout?.cardButton?.borderRadius??E?.appearance.variables?.borderRadius??8,S=h=>te("div",{style:{height:h,borderRadius:f,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),T=w===void 0?{boxSizing:"border-box",height:pr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let h=l.cardInputBorder??"#e5e7eb",q=l.cardInputBackground??"white",Y=er(B),ce=er(p);return Rt("div",{style:{backgroundColor:l.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...l.cardFormContainer},children:[Rt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Rt("button",{type:"button",onClick:()=>C(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Y?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...l.backButton},children:[te("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...l.backButtonIcon},children:te("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:te("path",{d:"M15 18l-6-6 6-6"})})}),te(nr,{content:B})]}),ce?te("div",{style:{flex:1}}):te("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...l.title},children:te(xr,{content:p})})]}),te("div",{style:{backgroundColor:q,border:`1px solid ${h}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:te("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Rt("div",{style:{display:"flex"},children:[te("div",{style:{flex:1,backgroundColor:q,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomLeftRadius:8,padding:12,height:45},children:te("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),te("div",{style:{flex:1,backgroundColor:q,borderTop:"none",borderRight:`1px solid ${h}`,borderBottom:`1px solid ${h}`,borderLeft:`1px solid ${h}`,borderBottomRightRadius:8,padding:12,height:45},children:te("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),te("div",{style:{backgroundColor:q,border:`1px solid ${h}`,borderRadius:8,marginTop:8,padding:12,height:45},children:te("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),te("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...l.submitButton,opacity:.5}}),te("style",{children:`
|
|
38
|
+
`}),xr&&Vn&&Me("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ke?-2:0},children:[Me("button",{type:"button",onClick:Kt,style:{display:"inline-flex",alignItems:"center",gap:xo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:A.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...A.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",...A.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(sr,{content:q})]}),Ia?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...A.title},children:d(Fr,{content:re})})]}),!xr&&!Ia&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:To,order:ke?-3:0,...A.title},children:d(Fr,{content:re})}),V&&d("div",{style:{order:ke?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let r=je,b=(D=!1)=>({backgroundColor:Mr,border:`1px solid ${Kn(D)}`,borderRadius:gt,marginTop:"0.5rem",padding:"10px"}),z=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ta}),ne=Ss(r);return Me(yr,{children:[Te(V.address_line_1,r)&&d("div",{style:b(Lt.line1),children:d("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:Ge,onChange:D=>{Dt.current=D.target.value,ve(D.target.value)},disabled:C,required:!0,"data-testid":"flopay-address-line1",style:z()})}),Te(V.address_line_2,r)&&d("div",{style:b(),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:bt,onChange:D=>{Gt.current=D.target.value,Ve(D.target.value)},disabled:C,"data-testid":"flopay-address-line2",style:z()})}),(Te(V.city,r)||Te(V.state,r))&&Me("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Te(V.city,r)&&d("div",{style:{flex:1,backgroundColor:Mr,borderTop:`1px solid ${Kn(Lt.city)}`,borderRight:`1px solid ${Kn(Lt.city)}`,borderBottom:`1px solid ${Kn(Lt.city)}`,borderLeft:`1px solid ${Kn(Lt.city)}`,padding:"10px",borderTopLeftRadius:gt,borderBottomLeftRadius:gt,...Te(V.state,r)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:gt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ut,onChange:D=>{an.current=D.target.value,It(D.target.value)},disabled:C,required:!0,"data-testid":"flopay-city",style:z()})}),Te(V.state,r)&&d("div",{style:{flex:1,backgroundColor:Mr,border:`1px solid ${Kn(Lt.state)}`,padding:"10px",borderTopRightRadius:gt,borderBottomRightRadius:gt,...Te(V.city,r)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:gt}},children:ne?Me("select",{id:"flopay-billing-state",name:"billing-state",value:mn,onChange:D=>{yn.current=D.target.value,En(D.target.value)},disabled:C,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...z(),cursor:"pointer"},children:[d("option",{value:"",children:Xa(r)}),ne.map(D=>d("option",{value:D.code,children:D.name},D.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Xa(r),autoComplete:"billing address-level1",value:mn,onChange:D=>{yn.current=D.target.value,En(D.target.value)},disabled:C,required:!0,"data-testid":"flopay-state",style:z()})})]}),(Te(V.country,r)||Te(V.postal_code,r))&&Me("div",{style:{display:"flex",flexDirection:oe==="column"?"column":"row",gap:oe==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Te(V.country,r)&&d("div",{style:{flex:oe==="row"?1:void 0,backgroundColor:Mr,borderTop:`1px solid ${Tr}`,borderRight:`1px solid ${Tr}`,borderBottom:`1px solid ${Tr}`,borderLeft:`1px solid ${Tr}`,padding:"10px",...oe==="row"&&Te(V.postal_code,r)?{borderRadius:"0",borderTopLeftRadius:gt,borderBottomLeftRadius:gt,borderRight:"none"}:{borderRadius:gt}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:je,onChange:D=>{$t.current=D.target.value,st(D.target.value),ze?.(D.target.value),yn.current="",En("")},disabled:C,autoComplete:"billing country","data-testid":"flopay-country",style:{...z(),cursor:"pointer"},children:ws.map(D=>Me("option",{value:D.code,children:[D.flag," ",D.name]},D.code))})}),Te(V.postal_code,r)&&d("div",{style:{flex:oe==="row"?1:void 0,backgroundColor:Mr,border:`1px solid ${qi}`,padding:"10px",...oe==="row"&&Te(V.country,r)?{borderRadius:"0",borderTopRightRadius:gt,borderBottomRightRadius:gt}:{borderRadius:gt}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Ho(je),autoComplete:"billing postal-code",value:rt,onChange:D=>{ht.current=D.target.value,et(D.target.value),Le?.(D.target.value)},onBlur:()=>Xt(!0),disabled:C,required:Et.required,"aria-invalid":Gr||void 0,"aria-describedby":Gr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:z()})})]}),Gr&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Eo,...Ta,fontSize:"0.75rem"},children:Et.empty?`${Ho(r)} is required`:qs(r)})]})})()}),ke&&be&&d("div",{style:{order:-2,width:"100%"},children:be}),ke&&Wi,Ne&&d(cr,{margin:"0.75rem 0",styleOverride:A.errorBanner,children:Ne})]}),Jr={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"},Ba=r=>$e?!w||!bn?d("pre",{"data-testid":r,style:Jr,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":r,style:Jr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${w}`,` directPaypalConfigured=${bn}`,` inAppBrowserDetected=${String(Wr)}`,` shouldRenderDirectPayPal=${Rr}`,` shouldRenderStripePayPal=${Ir}`,` hasPaypalStripeInstance=${!!xe}`].join(`
|
|
39
|
+
`)}):null,Aa=r=>$e?!T||!ct?d("pre",{"data-testid":r,style:Jr,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":r,style:Jr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${T}`,` currency=${Ie}`,` amountInCents=${Ce}`,` enabledPaymentMethods: ${JSON.stringify(y??[])}`,` enabledPaymentMethodsProvided=${wr}`,` hasEnabledMethods=${jr}`,` expressMethods: ${JSON.stringify(Vr)}`,` walletExpressMethods: ${JSON.stringify(Hr)}`,` paymentElementMethods: ${JSON.stringify(kr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Kr)}`,` hasStripeInstance=${!!ct}`,` shouldRenderWallets=${Er}`,` shouldRenderPaymentElement=${_r}`].join(`
|
|
40
|
+
`)}):null,Fa=he==="apm-expanding"||he==="apm-form"||he==="apm-collapsing",Xr=he==="apm-expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:he==="apm-collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Zr=lt?{...So,paymentMethodTypes:[lt]}:null;if(X==="buttons"){let r=he==="buttons"||he==="expanding"||he==="apm-expanding",b=he==="expanding"||he==="card"||he==="collapsing",z=N===void 0?{boxSizing:"border-box",height:co,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=he==="expanding"||he==="apm-expanding"?`flopay-buttons-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:he==="collapsing"||he==="apm-collapsing"?`flopay-buttons-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,D=he==="expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:he==="collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Me("form",{onSubmit:Ro,className:v,style:{position:"relative"},children:[d(Vo,{}),O&&d(Sn,{status:O,errorMessage:Ne}),Me("div",{style:{display:"grid"},children:[Me("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!r&&!ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!r&&!ne?zs:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[Ba("flopay-direct-paypal-gate-debug"),Aa("flopay-stripe-gate-debug"),Rr&&Qe&&Me(yr,{children:[L&&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(so,{sessionId:e,nonce:t,billingApiUrl:le,email:H.email,clientId:Qe.clientId,environment:Qe.environment,currency:Ie.toUpperCase(),isSubscription:Ze,onTokenizedBody:Qt,onComplete:a,onErrorChange:de,onDecline:s,onTechnicalFailure:rr,onButtonClick:fe,runBeforeButtonClick:dn,isProcessing:C,onLoadStateChange:wo,onInitializationStateChange:ko,session:u??null,existingOrderId:L?.orderId,debug:$e},L?.orderId??"fresh")]}),Ir&&d(Qn,{stripe:xe,options:zt,children:d(ii,{sessionId:e,nonce:t,email:H.email,billingApiUrl:le,onTokenizedBody:Qt,onErrorChange:de,isProcessing:C,onButtonClick:fe,onDecline:s,onTechnicalFailure:rr,runBeforeButtonClick:dn,onLoadStateChange:ua,placeholderBorderRadius:Wn})}),Er?d(Qn,{stripe:ct,options:Wt,children:d(si,{sessionId:e,nonce:t,email:H.email,billingApiUrl:le,intentKind:se>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:Qt,onErrorChange:de,onButtonClick:fe,onDecline:s,onTechnicalFailure:rr,runBeforeButtonClick:dn,onLoadStateChange:ma,placeholderBorderRadius:Wn})}):Pa?d("div",{style:{height:co,borderRadius:Wn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,_r&&d(li,{sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:le,paymentElementMethods:Kr,stripeInstance:ct,paymentElementBaseOptions:So,onTokenizedBody:Qt,onErrorChange:de,onButtonClick:fe,onDecline:s,runBeforeButtonClick:dn,onLoadStateChange:fa,isProcessing:C,submitButtonColor:Yn,submitButtonBorderRadius:gt,submitButtonStyle:A.submitButton,onExpandApm:_,expandedApmMethod:lt,themeId:B,buttonAppearance:{backgroundColor:A.cardButton?.backgroundColor,borderColor:A.cardInputBorder,textColor:A.cardButton?.color,borderRadius:Wn}}),ke&&d("button",{type:"button",onClick:async()=>{C||!(await dn("card")).proceed||(fe?.("card"),nr())},disabled:C,style:{width:"100%",...z,...A.cardButton,...Jo({themeBundle:Ee,resolvedPrimaryColor:Yn,resolvedBorderRadius:gt,submitButtonStyle:A.submitButton,explicitPrimaryColor:Vt?.colorPrimary}),fontSize:A.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:Z=>{!C&&(Ee||Vt?.colorPrimary)&&(Z.currentTarget.style.backgroundColor=Hi)},onMouseLeave:Z=>{(Ee||Vt?.colorPrimary)&&(Z.currentTarget.style.backgroundColor=Yn)},onMouseDown:Z=>{Z.currentTarget.style.transform="scale(0.985)"},onMouseUp:Z=>{Z.currentTarget.style.transform="scale(1)"},children:d(ir,{content:N})}),Ne&&he==="buttons"&&d(cr,{margin:"0.25rem 0",styleOverride:A.errorBanner,children:Ne})]}),ke&&b&&d("div",{style:{gridArea:"1 / 1",...D?{animation:D}:{},...he==="collapsing"?{pointerEvents:"none"}:{}},children:Ma}),T&&Fa&<&&Zr&&ct&&d("div",{style:{gridArea:"1 / 1",...Xr?{animation:Xr}:{},...he==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Me("div",{style:{backgroundColor:_o,borderRadius:Bo,...Br,padding:Mo},children:[Me("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Me("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Y,style:{display:"inline-flex",alignItems:"center",gap:xo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:A.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...A.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",...A.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(sr,{content:q})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:To,paddingRight:80,...A.title},children:`Pay with ${fr(lt)}`})]}),d(Qn,{stripe:ct,options:Zr,children:d(Ko,{method:lt,sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:le,onTokenizedBody:Qt,onErrorChange:de,onDecline:s,onCancel:Y,runBeforeButtonClick:dn,onButtonClick:fe,isProcessing:C,submitButtonColor:Yn,submitButtonBorderRadius:gt,submitButtonStyle:A.submitButton,errorText:Ne})},lt)]})})]})]})}return Fa&<&&Zr&&ct&&T?Me("form",{onSubmit:Ro,className:v,style:{position:"relative"},children:[d(Vo,{}),O&&d(Sn,{status:O,errorMessage:Ne}),d("div",{style:{...Xr?{animation:Xr}:{},...he==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Me("div",{style:{backgroundColor:_o,borderRadius:Bo,...Br,padding:Mo},children:[Me("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Me("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Y,style:{display:"inline-flex",alignItems:"center",gap:xo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:A.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...A.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",...A.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(sr,{content:q})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:A.titleFontSize??"1.05rem",color:To,paddingRight:80,...A.title},children:`Pay with ${fr(lt)}`})]}),d(Qn,{stripe:ct,options:Zr,children:d(Ko,{method:lt,sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:le,onTokenizedBody:Qt,onErrorChange:de,onDecline:s,onCancel:Y,runBeforeButtonClick:dn,onButtonClick:fe,isProcessing:C,submitButtonColor:Yn,submitButtonBorderRadius:gt,submitButtonStyle:A.submitButton,errorText:Ne})},lt)]})})]}):Me("form",{onSubmit:Ro,className:v,style:{position:"relative"},children:[d(Vo,{}),O&&d(Sn,{status:O,errorMessage:Ne}),Me("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ba("flopay-direct-paypal-gate-debug-default"),Aa("flopay-stripe-gate-debug-default"),Rr&&Qe&&Me(yr,{children:[L&&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(so,{sessionId:e,nonce:t,billingApiUrl:le,email:H.email,clientId:Qe.clientId,environment:Qe.environment,currency:Ie.toUpperCase(),isSubscription:Ze,onTokenizedBody:Qt,onComplete:a,onErrorChange:de,onDecline:s,onTechnicalFailure:rr,onButtonClick:fe,runBeforeButtonClick:dn,isProcessing:C,onLoadStateChange:wo,onInitializationStateChange:ko,session:u??null,existingOrderId:L?.orderId,debug:$e},L?.orderId??"fresh")]}),Ir&&d(Qn,{stripe:xe,options:zt,children:d(ii,{sessionId:e,nonce:t,email:H.email,billingApiUrl:le,onTokenizedBody:Qt,onErrorChange:de,isProcessing:C,onButtonClick:fe,onDecline:s,onTechnicalFailure:rr,runBeforeButtonClick:dn,onLoadStateChange:ua,placeholderBorderRadius:Wn})}),Er&&d(Qn,{stripe:ct,options:Wt,children:d(si,{sessionId:e,nonce:t,email:H.email,billingApiUrl:le,intentKind:se>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:Qt,onErrorChange:de,onButtonClick:fe,onDecline:s,onTechnicalFailure:rr,runBeforeButtonClick:dn,onLoadStateChange:ma,placeholderBorderRadius:Wn})}),_r&&d(li,{sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:le,paymentElementMethods:Kr,stripeInstance:ct,paymentElementBaseOptions:So,onTokenizedBody:Qt,onErrorChange:de,onButtonClick:fe,onDecline:s,runBeforeButtonClick:dn,onLoadStateChange:fa,isProcessing:C,submitButtonColor:Yn,submitButtonBorderRadius:gt,submitButtonStyle:A.submitButton,themeId:B,onExpandApm:_,expandedApmMethod:lt,buttonAppearance:{backgroundColor:A.cardButton?.backgroundColor,borderColor:A.cardInputBorder,textColor:A.cardButton?.color,borderRadius:Wn}})]}),ke&&(Oi||Ni||zi)&&Me("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"}})]}),ke&&Ma]})}import{loadFloPay as fi,PaymentAPI as gi}from"@flopay/js";import{FloPayError as at,isSetupIntentClientSecret as Ws}from"@flopay/shared";var Ur="card";async function Ys(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:i,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:i??null}}async function Gs(e,t,n,i){if(i){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Rn(e,t){return Object.assign(e,{checkoutMethod:t})}function hi(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 Js(e){return e.status==="succeeded"||e.status==="declined"}async function Pi(e){if(typeof document>"u"||typeof window>"u")throw new at("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new at("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,i=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let p=new AbortController,R=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",R);let v=window.setTimeout(()=>p.abort(),i);try{let I=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:p.signal});if(!I.ok)return{status:"unknown"};let l=await I.json().catch(()=>null);return Xs(l)}catch{return{status:"unknown"}}finally{window.clearTimeout(v),e.signal?.removeEventListener("abort",R)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let S=document.createElement("iframe");S.setAttribute("title","Card authentication"),S.setAttribute("allow","payment"),S.tabIndex=0,S.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),S.src=e.nextActionRedirectUrl,s.appendChild(S),document.body.appendChild(s),S.focus();let M=null;try{M=new URL(e.billingApiUrl,window.location.href).origin}catch{M=null}try{let p=await new Promise((R,v)=>{let I=!1,l=0,m=0,w=0,T=!1,y=()=>{window.clearTimeout(l),window.clearInterval(m),window.clearTimeout(w),window.removeEventListener("message",X),S.removeEventListener("load",K),e.signal?.removeEventListener("abort",ue)},U=async()=>{if(!(I||T)){T=!0;try{let B=await a();if(I||!Js(B))return;I=!0,y(),R(B)}finally{T=!1}}},K=()=>{window.clearTimeout(w),w=window.setTimeout(()=>{U()},250)},ue=()=>{I||(I=!0,y(),v(new at("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},X=B=>{if(B.source!==S.contentWindow||M&&B.origin!==M)return;let G=B.data;!G||typeof G!="object"||G.source!=="flopay-vault-3ds-return"||I||(I=!0,y(),R(null))};l=window.setTimeout(()=>{I||(I=!0,y(),v(new at("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),m=window.setInterval(()=>{U()},n),S.addEventListener("load",K),window.addEventListener("message",X),e.signal?.addEventListener("abort",ue),e.signal?.aborted&&ue()});return p||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function Xs(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 zn(e,t="Payment failed. Please try again.",n){let i=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=Ln(o)??o;return Rn(new at(a,"api_error",{code:e?.gatewayErrorCode}),i)}function Zo(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function po(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Zs(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 bi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||po(o)))return o;let i=e?.data;if(i&&typeof i=="object"){let o=i,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let s of a)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||po(s)))return s;let c=o.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let S=s,M=[S.stripeClientSecret,S.clientSecret];for(let p of M)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||po(p)))return p}}}}async function Qs({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let o=bi(i,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let s=(await new gi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(po(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function gr({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:o,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),S=t??n.id,M=i??n.clientSecret,p=n.customer?.id??n.accountData?.userId??"",R=n.customer?.email??n.accountData?.email??"",v=n.customer?.firstName??n.accountData?.firstName??"",I=n.customer?.lastName??n.accountData?.lastName??"",l=n.customer?.country??n.accountData?.country??void 0,m=n.customer?.zip??n.accountData?.zip??void 0,w=new gi(s,c===!1?{telemetry:!1}:void 0),T=await Zs(()=>w.processPayment(p,{sessionId:S,nonce:M,tokenizedData:o,accountData:{userId:p,email:R,firstName:v,lastName:I,country:l,zip:m},returnUrl:a??Zo(n)}));if(T.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:ro(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}};let y=await T.json().catch(()=>null);if(y?.type==="paypal_redirect_required"||y?.type==="3ds_required"){let U=bi(y);if(!U)throw new at("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:y.type,threeDSecureToken:U,paymentMethodId:y.paymentMethodId}}if(y?.gatewayErrorCode==="authentication_required"){let U=await Qs({billingApiUrl:s,sessionId:S,nonce:M,responseJson:y});if(U)return U;throw Rn(new at("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new at(y?.message??"Payment failed. Please try again.","api_error",{code:y?.code??y?.gatewayErrorCode,declineCode:y?.declineCode??y?.gatewayDeclineReason})}async function mo(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:o,sessionId:a,session:c,returnUrl:s,telemetry:S}){let M=t?.getRawProvider();if(!M)throw new at("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw Rn(new at("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let p=Ws(e.threeDSecureToken),R=null,v=e.paymentMethodId,I=await Ys(M,e.threeDSecureToken,p);if(I){if(I.error)throw Rn(new at(I.error.message??`Failed to retrieve 3DS ${p?"setup":"payment"} status.`,"api_error",{code:I.error.code}),"card");let m=I.intent;!v&&m?.payment_method&&(typeof m.payment_method=="string"?v=m.payment_method:"id"in m.payment_method&&(v=m.payment_method.id??void 0))}let l=v?await Gs(M,e.threeDSecureToken,{payment_method:v,return_url:s??Zo(c)??window.location.href},p):null;if(l){if(l.error)throw Rn(new at(l.error.message??"3DS authentication failed.","api_error",{code:l.error.code}),"card");R=l.intent}else{let m=await M.handleNextAction({clientSecret:e.threeDSecureToken});if(m.error)throw Rn(new at(m.error.message??"3DS authentication failed.","api_error",{code:m.error.code}),"card");R=(p?m.setupIntent:m.paymentIntent)??null}if(R&&(R.status==="requires_capture"||R.status==="succeeded"||R.status==="processing")){let m=await gr({billingApiUrl:o,sessionId:a,session:c,telemetry:S,tokenizedData:{id:R.id,type:"card",threeDSecureActionResultTokenId:R.id},returnUrl:s});return m.type==="success"?{...m.result,paymentIntentId:m.result.paymentIntentId??R.id,paymentMethodId:m.result.paymentMethodId??v}:mo(m,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:o,sessionId:a,session:c,returnUrl:s,telemetry:S})}throw Rn(new at("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let p=(n??t)?.getRawProvider();if(!p)throw Rn(new at("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:v}=await p.handleNextAction({clientSecret:e.threeDSecureToken});if(v)throw Rn(new at(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:R}=await p.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Zo(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(R)throw Rn(new at(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new at("Unsupported payment redirect state.","api_error")}function er(e){if(e instanceof at){let i=Ln(e.message);return i&&i!==e.message?Object.assign(new at(i,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Ln(t)??t;return new at(n,"api_error")}function yo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new at("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 fo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:i,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[c,s]=await Promise.all([fi(e,{billingApiUrl:n,locale:i,telemetry:o}),a?fi(t,{billingApiUrl:n,locale:i,telemetry:o}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{Fragment as In,jsx as Q,jsxs as kt}from"react/jsx-runtime";var hr=44,aa="flopay_checkout_saved_payment_resume",ea=new Map;function $r(e){return new Promise(t=>setTimeout(t,e))}function ho(e,t,n){let i=Qr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ki,enabled:t!==!1});return i.beginCheckout(n),i}function Po(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ta(e,t,n,i,o){let a=ho(e,t,n);a.error({errorCode:i,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Po(a)}function rl(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 oa(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function na(e){return!e||e.data.stripe?.publishableKey?!1:!!oa(e)?.clientId}function Pr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ol(){if(!Pr())return null;try{let e=window.sessionStorage.getItem(aa);return e?JSON.parse(e):null}catch{return null}}function Ci(e){if(Pr())try{window.sessionStorage.setItem(aa,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ra(){if(Pr())try{window.sessionStorage.removeItem(aa)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function al(e){if(!Pr())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 il(e,t,n){if(Pr())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(i){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",i)}}function Si(e){if(Pr())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function sl(){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 i of t)e.searchParams.has(i)&&(e.searchParams.delete(i),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function wi(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 ll(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 ia({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:o,appearance:a,locale:c,loading:s,error:S,onComplete:M,onError:p,onDecline:R,onCountryChange:v,onZipChange:I,showPayPal:l=!0,showStripe:m=!0,showApplePay:w=!0,showGooglePay:T=!0,debug:y=!1,layout:U,theme:K,buttonsTheme:ue,buttonsStyles:X,cardButtonContent:B,cardBackButtonContent:G,cardTitleContent:$,showSecurityFooter:pe,onButtonClick:N,onBeforeButtonClick:q,enableAVS:re,cardFieldOrder:Ae,cardPreFormSlot:fe,avsLayout:ye,className:J,initialErrorMessage:me=null,children:be,checkoutMode:oe,confirmLabel:De,renderConfirmButton:Re,onSessionCompleted:Se}){let k=tl(i),ee=pn(()=>Ri(K),[K]),ie=a??ee?.appearance,ze=n?"embedded_checkout":"standard_checkout",Le=be?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",[W,x]=wt(null),[j,se]=wt(null),Ie=on(null),[it,Qe]=wt(null),Ze=on(null),[u,$e]=wt(null),[Ue,We]=wt(e??""),qe=e??Ue,Yt=n?"":qe,[Pt,Rt]=wt(!0),[f,we]=wt(null),[je,st]=wt("full"),[rt,et]=wt(!1),[Ge,ve]=wt(me),[bt,Ve]=wt(null),[Ut,It]=wt(null),[mn,En]=wt(void 0),[_n,qn]=wt(""),[ht,$t]=wt(!1),[Dt,Gt]=wt("loading"),[an,yn]=wt(0),V=on(!1),Fn=on(!1),fn=on(!1),qt=on(null),At=pn(()=>({checkoutMode:oe??je,layout:be?"unknown":U==="buttons"?"buttons":"embedded"}),[oe,be,je,U]),E=on(M);E.current=M;let Je=on(p);Je.current=p;let ke=on(R);ke.current=R,An(()=>{Mt(j)?.setCheckoutContext(At),it&&it!==j&&Mt(it)?.setCheckoutContext(At)},[j,it,At]);let Dn=on(Se);Dn.current=Se;let He=tr(_=>{Gt(_),!(_!=="exhausted"||fn.current)&&(fn.current=!0,Je.current?.(new Bt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),jn=tr(()=>{Gt("retrying"),yn(_=>_+1)},[]);An(()=>{Gt("loading"),yn(0),fn.current=!1},[qe]),An(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ki,checkout_type:ze,checkout_layout:Le,billing_api_url:k})},[Le,ze,k]);let gn=pn(()=>n?xn(n):"",[n]),hn=pn(()=>_n===gn?mn:void 0,[mn,_n,gn]),tt=pn(()=>n?Oo(n,hn):void 0,[n,hn]),Et=oe??tt?.checkoutMode??"full",jt=pn(()=>tt?{...tt,checkoutMode:Et}:void 0,[tt,Et]);An(()=>{En(void 0),qn(gn)},[gn]),An(()=>{ve(me)},[me]);let Lt=tr((_,Y,O)=>{pt(()=>{ke.current?.(St(_,Y,O))})},[pt]),Jt=tr(async(_,Y)=>{ve(null),It(null),Ve("processing");let O=Y?.sessionId??_.id,P=Ie.current??Ze.current,ae=Mt(P),L=P?null:ho(k,o,At),g={log:C=>{ae?ae.log(C):L?.log(C)},error:C=>{ae?ae.error(C):L?.error(C)},terminal:C=>{ae?ae.terminal(C):L?.terminal(C)},performance:C=>{ae?ae.performance(C):L?.performance(C)},now:()=>ae?.now()??L?.now()??0,elapsed:C=>ae?.elapsed(C)??Math.max(0,(L?.now()??C)-C)},_e=g.now(),le=!!(Y?.initialAutoProcessingError||Y?.initialAutoProcessingPending),Ne=!1,Ee,A=()=>{Ne||(Ne=!0,le=!0,Ee=g.now(),g.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ft=!1,F=()=>{Ft||(Ft=!0,g.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),g.performance({stage:"processing",durationMs:g.elapsed(_e),durationMode:"machine",paymentMethodCategory:"saved"}),Ee!==void 0&&g.performance({stage:"recovery",durationMs:g.elapsed(Ee),durationMode:"machine",paymentMethodCategory:"saved"}))};g.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),g.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),le&&A();let h;try{let C=hi(Y?.initialAutoProcessingError),ce;if(C)A(),C.type==="paypal_redirect_required"&&qt.current?.publishableKey&&Ci({sessionId:O,publishableKey:qt.current.publishableKey,paypalPublishableKey:qt.current.paypalPublishableKey}),ce=await mo(C,{flopay:Ie.current,paypalFlopay:Ze.current,attempt3DS:Y?.attempt3DS,billingApiUrl:k,sessionId:O,session:_,telemetry:!1}),C.type==="paypal_redirect_required"&&ra();else if(Y?.initialAutoProcessingPending){let Ke=await new go(k,{telemetry:!1}).waitForCheckoutSessionCompletion(Y.initialAutoProcessingPending.sessionId,{initialDelayMs:Y.initialAutoProcessingPending.retryAfterMs});if(Ke.data.session?.status!=="complete")throw new Bt("Automatic payment failed. Please try again.","api_error",{code:Ke.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});ce={status:"succeeded"}}else{if(Y?.initialAutoProcessingError)throw zn(Y.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Y.initialAutoProcessingError.checkoutMethod});if(Y?.fromCreateSession)return Y?.fallbackToFull&&(st("full"),wi("full")),!1;{let H=await gr({billingApiUrl:k,sessionId:O,session:_,telemetry:!1});H.type==="success"?ce=H.result:(A(),H.type==="paypal_redirect_required"&&qt.current?.publishableKey&&Ci({sessionId:O,publishableKey:qt.current.publishableKey,paypalPublishableKey:qt.current.paypalPublishableKey}),ce=await mo(H,{flopay:Ie.current,paypalFlopay:Ze.current,attempt3DS:Y?.attempt3DS,billingApiUrl:k,sessionId:O,session:_,telemetry:!1}),H.type==="paypal_redirect_required"&&ra())}}O&&ur(O),F(),le&&(g.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),g.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ve("success"),await $r(Mn),h=()=>E.current?.(ce)}catch(C){let ce=er(C),H=ce.checkoutMethod??Ur;return ve(ce.message),It(ce.message),Y?.fallbackToFull&&(g.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),st("full"),wi("full")),F(),!!(ce.declineCode||ce.code?.toLowerCase().includes("declin"))?g.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):ce.type==="validation_error"?g.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):g.error({errorCode:le?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:le?"recovery":"processing",paymentMethodCategory:"saved"}),pt(()=>Je.current?.(ce)),Lt(H,ce,{code:ce.code,declineCode:ce.declineCode}),Ve("error"),await Promise.allSettled([$r(Cn),Y?.ensureProvidersReady?Y.ensureProvidersReady():Promise.resolve()]),le&&(g.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{F(),L&&Po(L),Ve(null),It(null)}return pt(h),!0},[Lt,pt,er,k,o,At]);An(()=>{if(typeof window>"u"||Fn.current)return;let _=new URLSearchParams(window.location.search),Y=_.get("payment_intent_client_secret");if(!Y)return;let O=ol();O&&(Fn.current=!0,(async()=>{let P,ae=0;ve(null),It(null),Ve("processing"),et(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new Bt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:L,paypalFlopay:g}=await fo({publishableKey:O.publishableKey,paypalPublishableKey:O.paypalPublishableKey,billingApiUrl:k,locale:c,telemetry:o});P=Mt(g??L),ae=P?.now()??0,P?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),P?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let _e=(g??L)?.getRawProvider();if(!_e)throw Object.assign(new Bt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:le,error:Ne}=await _e.retrievePaymentIntent(Y);if(Ne)throw Object.assign(new Bt(Ne.message??"Failed to retrieve PayPal payment status.","api_error",{code:Ne.code}),{checkoutMethod:"paypal"});let Ee=qa(le?.status);if(!le||Ee==="failed")throw Object.assign(new Bt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let A=typeof le.payment_method=="string"?le.payment_method:le.payment_method?.id,Ft=Ee;if(O.sessionId){let C=(await new go(k,{telemetry:!1}).getUnifiedCheckoutSession(O.sessionId)).data.session;if(C&&C.status!=="complete"){let ce=await gr({billingApiUrl:k,sessionId:O.sessionId,session:C,telemetry:!1,tokenizedData:{id:A??le.id,type:"card",threeDSecureActionResultTokenId:le.id,isPaypal:!0}});if(ce.type!=="success")throw Object.assign(new Bt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Ft=ce.result.status}}O.sessionId&&ur(O.sessionId),P?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),P?.performance({stage:"redirect_resume",durationMs:P.elapsed(ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),P?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ve("success"),await $r(Mn),pt(()=>E.current?.({status:Ft,paymentIntentId:le.id,paymentMethodId:A,checkoutMethod:"paypal"}))}catch(L){let g=er(L),_e=g.checkoutMethod??"paypal",le=!!(g.declineCode||g.code?.toLowerCase().includes("declin"));if(P)P.performance({stage:"redirect_resume",durationMs:P.elapsed(ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),le?P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):P.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(le){let Ne=ho(k,o,At);Ne.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Po(Ne)}else ta(k,o,At,"REDIRECT_RESUME_FAILED","redirect_resume");ve(g.message),It(g.message),pt(()=>Je.current?.(g)),Lt(_e,g,{code:g.code,declineCode:g.declineCode}),Ve("error"),await $r(Cn)}finally{ra(),sl(),Ve(null),It(null),et(!1)}})())},[Lt,pt,c,er,k,o]);let sn=on(null);function xn(_){let Y=JSON.stringify({c:_?.clientId,cur:_?.currency??"",a:{e:_?.account?.email?.trim().toLowerCase()??"",country:_?.account?.country??""},successUrl:_?.successUrl,cancelUrl:_?.cancelUrl,p:_?.products?.map(P=>`${P.type??""}:${P.code??P.providerItemId??P.providerPlanId??""}:${P.totalAmount??""}:${P.overrideAmount??""}:${P.quantity??1}`).sort(),i:_?.items?.map(P=>`${P.code??P.providerItemId??""}:${P.totalAmount??""}:${P.overrideAmount??""}:${P.quantity??1}`).sort(),s:_?.subscriptions?.map(P=>`${P.code??P.providerPlanId??""}:${P.totalAmount??""}:${P.overrideAmount??""}:${P.quantity??1}`).sort(),couponCodes:_?.couponCodes,tagsData:_?.tagsData,utmMetadata:_?.utmMetadata,tokenizedData:_?.tokenizedData,m:_?.checkoutMode??"full"}),O=0;for(let P=0;P<Y.length;P++)O=(O<<5)-O+Y.charCodeAt(P)|0;return`flopay_session_${Math.abs(O).toString(36)}`}let Xt=pn(()=>jt?xn(jt):"",[jt]),Nt=on(jt);Nt.current=jt,An(()=>{We(e??"")},[e]),An(()=>{V.current=!1,ve(me),It(null),Ve(null)},[Xt,me,e]);async function Zt(_,Y){let O=ho(k,o,At),P=new go(k,{telemetry:!1});try{let ae=al(Y);O.log({name:ae?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let L=ae?.sid??null,g=null;if(L)try{if(g=await P.getUnifiedCheckoutSession(L,ae?.nonce),g.data.session?.status==="complete"){if(Va(L))return{sid:L,result:g};Si(Y),L=null,g=null}}catch{O.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Si(Y),L=null}if(!L){let _e=O.now();O.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let le={..._,avsCheck:!!re,avsConfig:typeof re=="object"?re:void 0,checkoutType:"embedded_checkout",checkoutLayout:be?"custom_layout":U==="buttons"?"buttons_layout":"default_layout"};try{g=await P.createAndFetchSession(le),O.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),O.performance({stage:"session_create",durationMs:O.now()-_e,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"})}catch(Ne){let Ee=el(Ne,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw O.performance({stage:"session_create",durationMs:O.now()-_e,durationMode:"machine",requestCategory:"session_create",statusClass:Ee.statusClass}),Ne instanceof Bt&&Ne.type==="validation_error"?O.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Ee.statusClass==="4xx"?O.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):O.error({...Ee,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Ne}L=g.data.session?.id??"",L&&il(Y,L,g.data.session?.clientSecret)}return{sid:L??"",result:g}}finally{Po(O)}}let he=tr(async _=>{let Y=Nt.current;if(!Y)throw new Bt("createSession is required to bootstrap checkout.","validation_error");let O=Oo(Y,_),P=xn(O),ae=ea.get(P);ae||(ae=Zt(O,P),ea.set(P,ae));let L;try{L=await ae}finally{ea.delete(P)}sn.current=P;try{_&&(qn(gn),En(Ft=>Ua(Ft,_)));let{sid:g,result:_e}=L;x(_e),_e.data.session&&$e(_e.data.session),g&&We(g);let{publishableKey:le,paypalPublishableKey:Ne}=yo(_e),{flopay:Ee,paypalFlopay:A}=await fo({publishableKey:le,paypalPublishableKey:Ne,billingApiUrl:k,locale:c,telemetry:o});Ie.current=Ee,se(Ee),Ze.current=A,Qe(A),Rt(!1)}catch(g){throw sn.current===P&&(sn.current=null),g}return L},[c,k,o,At]),ft=tr(async _=>{if(!ll(_)||ht)return{sessionId:Ue,session:u};$t(!0);try{let Y=await he(_);return{sessionId:Y.sid,session:Y.result.data.session??null}}finally{$t(!1)}},[he,ht,Ue,u]);An(()=>{let _=!1;if(we(null),Xt){let P=Nt.current;return st(Et),Rt(!1),sn.current===Xt?()=>{_=!0}:($e($a(P,oe)),(async()=>{let ae=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),L=Et==="auto"&&!V.current&&!ae;L&&(ve(null),It(null),Ve("processing"));try{let g=await he(),_e=g.result.data.session??null;qt.current=yo(g.result);let le=na(g.result);if(!_&&L&&_e&&!le){V.current=!0,await Jt(_e,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:g.result.autoProcessingError,initialAutoProcessingPending:g.result.autoProcessingPending,autoProcessingAttempted:g.result.autoProcessingAttempted,sessionId:g.sid||_e.id});return}!_&&L&&(le&&(V.current=!0),Ve(null),It(null))}catch(g){if(_)return;let _e=g instanceof Bt||typeof g=="object"&&g!==null&&"code"in g?g.code:void 0;if(L&&_e==="session_auto_completed"){V.current=!0,Ve("success"),await $r(Mn),_||(pt(()=>{E.current?.({status:"succeeded"})}),Ve(null),It(null));return}L&&(Ve(null),It(null));let le=g instanceof Bt?g:new Bt(g instanceof Error?g.message:"Failed to create session","api_error");we(le)}})(),()=>{_=!0})}Rt(!0);async function Y(){let P=!1;try{let L=await new go(k,{telemetry:!1}).getUnifiedCheckoutSession(qe,t);if(_)return;x(L);let g=L.data.session??null;if($e(g),!g)throw new Bt("No session data returned","api_error");if(g.status==="complete"){Rt(!1),pt(()=>{Dn.current?.(g.successUrl??"")});return}if(g.status==="expired")throw new Bt("Checkout session has expired.","api_error",{code:"checkout_session_expired"});P=!0;let _e=oe??g.checkoutMode??"full";st(_e);let le=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ne=na(L);if(_e==="auto"&&!V.current&&!le&&!Ne){V.current=!0;let Ee=O(L);try{if(await Jt(g,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Ee,sessionId:qe||g.id}),_)return;await Ee,_||Rt(!1);return}catch{if(_)return;await Ee,_||Rt(!1);return}}await O(L),_||Rt(!1)}catch(ae){if(_)return;ae instanceof Bt?!P&&!rl(ae)&&ta(k,o,At,"NETWORK_REQUEST_FAILED","session_read"):ta(k,o,At,"INTERNAL_SDK_ERROR","checkout_mount");let L=ae instanceof Bt?ae:new Bt(ae instanceof Error?ae.message:"Failed to initialize checkout","api_error");we(L),Rt(!1)}}async function O(P){let{publishableKey:ae,paypalPublishableKey:L}=yo(P);qt.current={publishableKey:ae,paypalPublishableKey:L};let{flopay:g,paypalFlopay:_e}=await fo({publishableKey:ae,paypalPublishableKey:L,billingApiUrl:k,locale:c,telemetry:o});Ie.current=g,se(g),Ze.current=_e,Qe(_e)}return Y(),()=>{_=!0}},[he,oe,Xt,Et,Yt,pt,t,Jt]);let lt=tr(async()=>{if(!(rt||!u)){et(!0),ve(null);try{await Jt(u,{fallbackToFull:!0,sessionId:qe||u.id})}finally{et(!1)}}},[qe,rt,Jt,u]),Pn=oa(W),Vn=na(W),Ot=pn(()=>{if(!W||!u||!W.data.stripe?.publishableKey)return;let _={appearance:ie,paymentMethodCreation:"manual",billingApiUrl:k};if(W.data.stripe?.clientSecret)_.clientSecret=W.data.stripe.clientSecret;else{let Y=vi(u).total;_.amount=Math.round(Y*100)||u.amount,_.currency=u.currency?.toLowerCase()}return _},[W,u,ie,k]),Ht=!!(n&&!be&&U==="buttons"&&q&&Et==="full"),vt=pn(()=>({session:u,loading:Pt,error:f,checkoutMode:je,inlineSessionDraft:jt,applyInlineSessionPatch:Ht?ft:void 0,inlineSessionPatchProcessing:ht}),[u,Pt,f,je,jt,Ht,ft,ht]),nr=!!n&&U==="buttons"&&!Vn&&(!j||!Ot),Kt=bt?Q(Sn,{status:bt,errorMessage:Ut}):null;if(Pt){if(s)return kt(In,{children:[s,Kt]});if(U==="buttons"){let _=ee?.buttonsLayout?.cardButton?.borderRadius??ee?.appearance.variables?.borderRadius??8,Y=O=>Q("div",{style:{height:O,borderRadius:_,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return kt(In,{children:[kt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[l&&Y(hr),m&&(w||T)&&Y(hr),m&&Y(hr),Q("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Kt]})}return kt(In,{children:[kt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[Q("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),Q("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Kt]})}return f?S?Q(un.Provider,{value:vt,children:S(f)}):Q(un.Provider,{value:vt,children:Q("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:f.message})}):nr?kt(In,{children:[Q(un.Provider,{value:vt,children:Q(dl,{onButtonClick:N,showPayPal:l,showStripe:m,showApplePay:w,showGooglePay:T,theme:K,buttonsTheme:ue,buttonsStyles:X,cardButtonContent:B,cardBackButtonContent:G,cardTitleContent:$})}),Kt]}):Vn&&u&&Pn?kt(In,{children:[Q(un.Provider,{value:vt,children:kt("div",{className:J,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ge&&Q(cr,{icon:!1,children:Ge}),Dt==="retrying"&&Q("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Dt==="exhausted"&&kt("div",{role:"alert",children:[Q("div",{children:"PayPal is temporarily unavailable. Please try again."}),Q("button",{type:"button",onClick:jn,children:"Retry PayPal"})]}),Dt!=="exhausted"&&Q("div",{"aria-hidden":Dt==="retrying"?!0:void 0,style:Dt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:Q(Ja,{sessionId:qe,nonce:u.clientSecret||void 0,billingApiUrl:k,email:u.customer?.email,clientId:Pn.clientId,environment:Pn.environment,currency:(u.currency??"usd").toUpperCase(),isSubscription:u.mode==="subscription",onComplete:M,onErrorChange:ve,onDecline:R,onButtonClick:N,onInitializationStateChange:He,allowAutomaticRetry:an===0,session:u,telemetry:o,telemetryContext:At,debug:y},`paypal-init-${an}`)})]})}),Kt]}):!j||!Ot?Q(In,{children:Kt}):je==="confirm"?kt(In,{children:[Q(un.Provider,{value:vt,children:Q(eo,{flopay:j,paypalFlopay:it,options:Ot,children:kt("div",{className:J,children:[Ge&&Q("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ge}),Re?Re({onConfirm:lt,isProcessing:rt}):Q("button",{type:"button",onClick:lt,disabled:rt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:rt?"not-allowed":"pointer",opacity:rt?.6:1},children:rt?"Processing...":De??"Confirm Purchase"})]})})}),Kt]}):kt(In,{children:[Q(un.Provider,{value:vt,children:Q(eo,{flopay:j,paypalFlopay:it,options:Ot,children:be?kt(In,{children:[Ge&&Q("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ge}),Q(cl,{sessionId:qe,nonce:u?.clientSecret||void 0,billingApiUrl:k,session:u,children:be})]}):Q(Xo,{sessionId:qe,nonce:u?.clientSecret||void 0,email:u?.customer?.email,userId:u?.customer?.id,firstName:u?.customer?.firstName,lastName:u?.customer?.lastName,totalAmount:u?Math.round(vi(u).total*100):0,currency:u?.currency?.toLowerCase()??"usd",onComplete:M,onError:p,onDecline:R,error:Ge,onErrorChange:ve,showPayPal:l,showStripe:m,enabledPaymentMethods:W?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:W?.data.stripe?.enabledPaymentMethodCountries,showApplePay:w,showGooglePay:T,layout:U,theme:K,buttonsTheme:ue,buttonsStyles:X,appearance:ie,cardButtonContent:B,cardBackButtonContent:G,cardTitleContent:$,onButtonClick:N,onBeforeButtonClick:q,enableAVS:re,...Ae?{cardFieldOrder:Ae}:{},...fe?{cardPreFormSlot:fe}:{},avsLayout:ye,country:u?.customer?.country,city:u?.customer?.city,state:u?.customer?.state,onCountryChange:v,onZipChange:I,avsCheck:!!re,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:be?"custom_layout":U==="buttons"?"buttons_layout":"default_layout",className:J,directPaypal:oa(W),isSubscription:u?.mode==="subscription",session:u,debug:y})})}),Kt]})}function cl({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:o}){return Q(In,{children:Qo.Children.map(o,a=>{if(!Qo.isValidElement(a))return a;let c=a.props,s={};return c.sessionId||(s.sessionId=e),!c.nonce&&t&&(s.nonce=t),c.billingApiUrl||(s.billingApiUrl=n),i?.customer&&(c.email||(s.email=i.customer.email),c.userId||(s.userId=i.customer.id),c.firstName||(s.firstName=i.customer.firstName),c.lastName||(s.lastName=i.customer.lastName)),Object.keys(s).length===0?a:Qo.cloneElement(a,s)})})}function dl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:o,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:S,cardBackButtonContent:M,cardTitleContent:p}){let[R,v]=wt(!1),I=pn(()=>Ri(a),[a]),l=pn(()=>{let y=I?.buttonsLayout??nl(c);return s?{...y,...s,cardButton:{...y.cardButton,...s.cardButton},cardFormContainer:{...y.cardFormContainer,...s.cardFormContainer},backButton:{...y.backButton,...s.backButton},backButtonIcon:{...y.backButtonIcon,...s.backButtonIcon},submitButton:{...y.submitButton,...s.submitButton},title:{...y.title,...s.title}}:y},[I,c,s]),m=I?.buttonsLayout?.cardButton?.borderRadius??I?.appearance.variables?.borderRadius??8,w=y=>Q("div",{style:{height:y,borderRadius:m,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),T=S===void 0?{boxSizing:"border-box",height:hr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(R){let y=l.cardInputBorder??"#e5e7eb",U=l.cardInputBackground??"white",K=ar(M),ue=ar(p);return kt("div",{style:{backgroundColor:l.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...l.cardFormContainer},children:[kt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[kt("button",{type:"button",onClick:()=>v(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:K?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...l.backButton},children:[Q("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...l.backButtonIcon},children:Q("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:Q("path",{d:"M15 18l-6-6 6-6"})})}),Q(sr,{content:M})]}),ue?Q("div",{style:{flex:1}}):Q("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...l.title},children:Q(Fr,{content:p})})]}),Q("div",{style:{backgroundColor:U,border:`1px solid ${y}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:Q("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),kt("div",{style:{display:"flex"},children:[Q("div",{style:{flex:1,backgroundColor:U,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${y}`,borderLeft:`1px solid ${y}`,borderBottomLeftRadius:8,padding:12,height:45},children:Q("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Q("div",{style:{flex:1,backgroundColor:U,borderTop:"none",borderRight:`1px solid ${y}`,borderBottom:`1px solid ${y}`,borderLeft:`1px solid ${y}`,borderBottomRightRadius:8,padding:12,height:45},children:Q("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),Q("div",{style:{backgroundColor:U,border:`1px solid ${y}`,borderRadius:8,marginTop:8,padding:12,height:45},children:Q("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Q("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...l.submitButton,opacity:.5}}),Q("style",{children:`
|
|
41
41
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
42
|
@keyframes flopay-interim-expand {
|
|
43
43
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
44
|
40% { opacity: 1; }
|
|
45
45
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
46
|
}
|
|
47
|
-
`})]})}return Rt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&S(pr),n&&(i||r)&&S(pr),n&&te("button",{type:"button",onClick:()=>{e?.("card"),C(!0)},style:{width:"100%",...T,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:l.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,...l.cardButton},onMouseDown:h=>{h.currentTarget.style.transform="scale(0.985)"},onMouseUp:h=>{h.currentTarget.style.transform="scale(1)"},children:te(tr,{content:w})}),te("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{useEffect as ol,useRef as vi,useContext as al}from"react";import{jsx as ll}from"react/jsx-runtime";function Ci(e,t){function n({className:i,id:r,style:a,options:c,onChange:s,onReady:w,onFocus:B,onBlur:p,onEscape:R}){let C=vi(null),E=vi(null),{elements:l,reportInteractive:f}=al(xn);return ol(()=>{if(!l||!C.current)return;let S=!0;return(async()=>{let T=l.getElement(e);T||(T=await l.create(e,c)),!(!S||!C.current)&&(T.mount(C.current),E.current=T,s&&T.on("change",s),T.on("ready",()=>{f?.(),w?.()}),B&&T.on("focus",B),p&&T.on("blur",p),R&&T.on("escape",R))})(),()=>{if(S=!1,E.current){try{E.current.unmount()}catch{}E.current=null}}},[l,f]),ll("div",{ref:C,className:i,id:r,style:a})}return n.displayName=t,n}var il=Ci("payment","PaymentElement"),sl=Ci("address","AddressElement");import{PaymentAPI as cl}from"@flopay/js";import{FloPayError as dl}from"@flopay/shared";import{useCallback as ta,useEffect as ul,useRef as pl,useState as wi}from"react";import{Fragment as yl,jsx as yr,jsxs as fl}from"react/jsx-runtime";function ml({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,firstName:a,lastName:c,chv:s,onTokenizedBody:w,onComplete:B,onErrorChange:p,isProcessing:R=!1}){let C=Pn(),E=Mo(),l=Jr(),[f,S]=wi(!1),[T,h]=wi(!1),q=pl(!1),Y=(n||l).replace(/\/+$/,""),ce=ta(async X=>{try{let de=await new cl(Y).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:X,accountData:{userId:r??"",email:i??"",firstName:a??"",lastName:c??""},chv:s});if(de.ok){B?.();return}let z=await de.json().catch(()=>null);p?.(z?.message??"Payment failed. Please try again.")}catch(j){p?.(j instanceof Error?j.message:"An unexpected error occurred")}},[Y,e,t,r,i,a,c,s,B,p]),oe=ta(X=>{w?w(X):ce(X)},[w,ce]);ul(()=>{if(!C||q.current)return;let X=new URLSearchParams(window.location.search),j=X.get("payment_intent"),de=X.get("payment_intent_client_secret"),z=X.get("redirect_status");!j||!de||(q.current=!0,(async()=>{try{if(h(!0),z==="failed"){p?.("PayPal payment was declined. Please try again.");return}let V=C.getRawProvider();if(!V?.retrievePaymentIntent){p?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ae,error:Be}=await V.retrievePaymentIntent(de);if(Be){p?.(Be.message??"Failed to retrieve PayPal payment status.");return}if(ae&&(ae.status==="requires_capture"||ae.status==="succeeded")){let fe=typeof ae.payment_method=="string"?ae.payment_method:ae.payment_method?.id;oe({id:fe??ae.id,type:"card",threeDSecureActionResultTokenId:ae.id,isPaypal:!0});let ye=new URL(window.location.href);ye.searchParams.delete("payment_intent"),ye.searchParams.delete("payment_intent_client_secret"),ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",ye.toString())}else p?.("PayPal payment was not completed. Please try again.")}catch(V){p?.(V instanceof Error?V.message:"Failed to complete PayPal payment.")}finally{h(!1)}})())},[C,oe,p]);let D=ta(async()=>{if(!(!C||!E))try{if(h(!0),p?.(null),!e||!i)throw new dl("Missing sessionId or email for PayPal payment","validation_error");let X=await C.confirmPayPalPayment({billingApiUrl:Y,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(X.error){p?.(X.error.message);return}X.paymentIntentId&&(X.status==="succeeded"||X.status==="processing"||X.status==="requires_capture")&&oe({id:X.paymentMethodId??X.paymentIntentId,type:"card",threeDSecureActionResultTokenId:X.paymentIntentId,isPaypal:!0})}catch(X){p?.(X instanceof Error?X.message:"PayPal payment failed. Please try again.")}finally{h(!1)}},[C,E,e,t,i,Y,oe,p]);return!C||!E?yr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):fl(yl,{children:[!f&&yr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),yr("div",{style:f?{}:{display:"none"},children:yr("button",{type:"button",onClick:D,disabled:T||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:T||R?"not-allowed":"pointer",opacity:T||R?.6:1},ref:()=>S(!0),children:T?"Processing...":"PayPal"})}),(T||R)&&yr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:yr("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 zn,useEffect as fr,useMemo as Nr,useRef as gr,useState as yo}from"react";import{PaymentAPI as na}from"@flopay/js";import{FloPayError as Un,resolveBillingApiUrl as gl,resolveButtonsLayoutTheme as hl,resolveTheme as Pl}from"@flopay/shared";import{Fragment as kl,jsx as hr,jsxs as Rl}from"react/jsx-runtime";var bl=44;function Si(e){return new Promise(t=>setTimeout(t,e))}function vl(e,t){return e instanceof Un?e:new Un(e instanceof Error?e.message:t,"api_error")}function Cl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function wl(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 Sl({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:r,clientId:a,products:c,items:s,subscriptions:w,account:B,successUrl:p,cancelUrl:R,couponCodes:C,tagsData:E,utmMetadata:l,billingApiUrl:f,locale:S,theme:T,appearance:h,buttonsTheme:q,buttonsStyles:Y,onSuccess:ce,onError:oe,onDecline:D,children:X,disabled:j=!1,type:de="button",style:z,...V}){let ae=Nr(()=>gl(f),[f]),Be=Nr(()=>wl({createSession:n,clientId:a,products:c,items:s,subscriptions:w,account:B,successUrl:p,cancelUrl:R,couponCodes:C,tagsData:E,utmMetadata:l}),[B,R,a,C,n,c,s,w,p,E,l]),[fe,ye]=yo(!1),[Z,ue]=yo(null),[he,ie]=yo(null),[Fe,ke]=yo(null),ve=gr(!0),k=gr(null),ne=gr(Fe),se=gr(ce),Ne=gr(oe),De=gr(D);fr(()=>{ne.current=Fe},[Fe]),fr(()=>{se.current=ce},[ce]),fr(()=>{Ne.current=oe},[oe]),fr(()=>{De.current=D},[D]),fr(()=>(ve.current=!0,()=>{ve.current=!1,k.current?.abort()}),[]),fr(()=>{if(typeof window>"u")return;let g=Ce=>{Ce.key==="Escape"&&ke(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let G=zn((g,Ce=Dr)=>{De.current?.(St(Ce,g,{code:g.code,declineCode:g.declineCode}))},[]),x=zn(async g=>{ve.current&&(ie(null),ue("success"),await Si(Tn),ve.current&&se.current?.(g))},[]),H=zn(async(g,Ce)=>{ve.current&&(Ne.current?.(g),Ce?.emitDecline&&G(g,Ce.method),ie(g.message),ue("error"),await Si(bn))},[G]),le=zn(async(g,Ce,qe)=>{let st=g.data.session??null;if(!st)throw new Un("No session data returned","api_error");let tt=st.clientSecret||t;if(st.status==="complete"){await x({result:{status:"succeeded"},session:st,sessionId:st.id||Ce,autoCompleted:!1});return}if(st.status==="expired")throw new Un("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(g.autoProcessingPending){let vt=(await new na(ae).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!vt||vt.status!=="complete")throw new Un("Automatic payment failed. Please try again.","api_error",{code:vt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await x({result:{status:"succeeded"},session:vt,sessionId:vt.id||Ce,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&Ce&&tt){let Ye=new AbortController;k.current=Ye;let Pe;try{Pe=await pi({billingApiUrl:ae,sessionId:Ce,nonce:tt,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:Ye.signal})}finally{k.current===Ye&&(k.current=null)}if(Pe.status==="declined")throw On({type:Pe.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Pe.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let Dt=(await new na(ae).waitForCheckoutSessionCompletion(Ce,{initialDelayMs:0,nonce:tt})).data.session;if(!Dt||Dt.status!=="complete")throw On({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await x({result:{status:"succeeded"},session:Dt,sessionId:Dt.id||Ce,autoCompleted:!1});return}throw On(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if(qe?.fromCreateSession&&g.autoProcessingAttempted===!0)throw On({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ze=await ur({billingApiUrl:ae,sessionId:Ce??st.id,session:st,nonce:tt});if(Ze.type!=="success")throw On({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await x({result:Ze.result,session:st,sessionId:st.id||Ce,autoCompleted:!1})}catch(Ze){let Ye=Xn(Ze),Pe=st.id||Ce;await H(Ye,{emitDecline:!0,method:Ye.checkoutMethod??Dr}),Cl(Ye,Pe)&&Pe&&ve.current&&ke({sessionId:Pe,errorMessage:Ye.message,nonce:tt||void 0})}},[t,ae,H,x]),Re=zn(async g=>{if(V.onClick?.(g),!(g.defaultPrevented||j||fe)){if(ke(null),e&&Be){let Ce=new Un("Provide either sessionId or create-session props, not both.","validation_error");await H(Ce),ve.current&&(ue(null),ie(null));return}if(!e&&!Be){let Ce=new Un("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await H(Ce),ve.current&&(ue(null),ie(null));return}ye(!0),ie(null),ue("processing");try{let Ce=new na(ae);if(e){let qe=await Ce.getUnifiedCheckoutSession(e,t);await le(qe,e);return}try{let qe=await Ce.createAndFetchSession({...Be});await le(qe,qe.data.session?.id??null,{fromCreateSession:!0})}catch(qe){if(qe instanceof Un&&qe.code==="session_auto_completed"){await x({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw qe}}catch(Ce){await H(vl(Ce,"Automatic payment failed. Please try again."))}finally{ve.current&&(ue(null),ie(null),ye(!1))}}},[V,Be,j,fe,t,le,ae,e,H,x]),gt=zn(g=>{let Ce=ne.current;ke(null),se.current?.({result:g,session:null,sessionId:Ce?.sessionId??null,autoCompleted:!1})},[]),Xe=zn(g=>{Ne.current?.(g)},[]),Je=zn(g=>{De.current?.(g)},[]),m=Nr(()=>Pl(T),[T]),Ue=Nr(()=>{let g=m?.buttonsLayout??hl(q);return Y?{...g,...Y,cardButton:{...g.cardButton,...Y.cardButton}}:g},[m,q,Y]),Oe=Nr(()=>{let g=m?.appearance;return h?g?{...g,...h,variables:{...g.variables,...h.variables}}:h:g},[h,m]),Ve=Oe?.variables,$e=Ve?.colorPrimary??"#4A49FF",Kt=Ve?.colorPrimaryHover??ro($e,.12),bt=Ve?.borderRadius??"8px";return Rl(kl,{children:[hr("button",{...V,type:de,onClick:Re,disabled:j||fe,"aria-busy":fe,style:{width:"100%",...X===void 0?{boxSizing:"border-box",height:bl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ue.cardButton,...Vo({themeBundle:m,resolvedPrimaryColor:$e,resolvedBorderRadius:bt,submitButtonStyle:Ue.submitButton,explicitPrimaryColor:Ve?.colorPrimary}),fontSize:Ue.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:j||fe?"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:j||fe?.6:1,...z},onMouseEnter:g=>{V.onMouseEnter?.(g),!g.defaultPrevented&&!j&&!fe&&(m||Ve?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Kt)},onMouseLeave:g=>{V.onMouseLeave?.(g),!g.defaultPrevented&&(m||Ve?.colorPrimary)&&(g.currentTarget.style.backgroundColor=$e)},onMouseDown:g=>{V.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{V.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:hr(tr,{content:X})}),Z&&hr(vn,{status:Z,errorMessage:he}),Fe&&hr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&ke(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:hr("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:hr(ea,{sessionId:Fe.sessionId,nonce:Fe.nonce,checkoutMode:"full",billingApiUrl:ae,locale:S,theme:T,...Oe?{appearance:Oe}:{},buttonsTheme:q,buttonsStyles:Y,initialErrorMessage:Fe.errorMessage,cardTitleContent:null,onComplete:gt,onError:Xe,onDecline:Je})})})]})}export{sl as AddressElement,no as DirectPayPalButton,Sl as FloPayAutomaticPaymentButton,ea as FloPayCheckout,Gr as FloPayProvider,ml as PayPalButton,il as PaymentElement,Ho as SplitCardForm,xo as VaultCardFields,ts as useCheckout,Mo as useElements,Pn as useFloPay,To as usePayPalFloPay};
|
|
47
|
+
`})]})}return kt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&w(hr),n&&(i||o)&&w(hr),n&&Q("button",{type:"button",onClick:()=>{e?.("card"),v(!0)},style:{width:"100%",...T,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:l.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,...l.cardButton},onMouseDown:y=>{y.currentTarget.style.transform="scale(0.985)"},onMouseUp:y=>{y.currentTarget.style.transform="scale(1)"},children:Q(ir,{content:S})}),Q("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{useEffect as ul,useRef as Ii,useContext as pl}from"react";import{jsx as fl}from"react/jsx-runtime";function Ei(e,t){function n({className:i,id:o,style:a,options:c,onChange:s,onReady:S,onFocus:M,onBlur:p,onEscape:R}){let v=Ii(null),I=Ii(null),{elements:l,reportInteractive:m}=pl(Tn);return ul(()=>{if(!l||!v.current)return;let w=!0;return(async()=>{let T=l.getElement(e);T||(T=await l.create(e,c)),!(!w||!v.current)&&(T.mount(v.current),I.current=T,s&&T.on("change",s),T.on("ready",()=>{m?.(),S?.()}),M&&T.on("focus",M),p&&T.on("blur",p),R&&T.on("escape",R))})(),()=>{if(w=!1,I.current){try{I.current.unmount()}catch{}I.current=null}}},[l,m]),fl("div",{ref:v,className:i,id:o,style:a})}return n.displayName=t,n}var ml=Ei("payment","PaymentElement"),yl=Ei("address","AddressElement");import{PaymentAPI as gl}from"@flopay/js";import{FloPayError as hl}from"@flopay/shared";import{useCallback as sa,useEffect as Pl,useRef as bl,useState as _i}from"react";import{Fragment as Cl,jsx as br,jsxs as Sl}from"react/jsx-runtime";function vl({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:o,firstName:a,lastName:c,chv:s,onTokenizedBody:S,onComplete:M,onErrorChange:p,isProcessing:R=!1}){let v=vn(),I=No(),l=to(),[m,w]=_i(!1),[T,y]=_i(!1),U=bl(!1),K=(n||l).replace(/\/+$/,""),ue=sa(async G=>{try{let pe=await new gl(K).processPayment(o??"",{sessionId:e,nonce:t,tokenizedData:G,accountData:{userId:o??"",email:i??"",firstName:a??"",lastName:c??""},chv:s});if(pe.ok){M?.();return}let N=await pe.json().catch(()=>null);p?.(N?.message??"Payment failed. Please try again.")}catch($){p?.($ instanceof Error?$.message:"An unexpected error occurred")}},[K,e,t,o,i,a,c,s,M,p]),X=sa(G=>{S?S(G):ue(G)},[S,ue]);Pl(()=>{if(!v||U.current)return;let G=new URLSearchParams(window.location.search),$=G.get("payment_intent"),pe=G.get("payment_intent_client_secret"),N=G.get("redirect_status");!$||!pe||(U.current=!0,(async()=>{try{if(y(!0),N==="failed"){p?.("PayPal payment was declined. Please try again.");return}let q=v.getRawProvider();if(!q?.retrievePaymentIntent){p?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:re,error:Ae}=await q.retrievePaymentIntent(pe);if(Ae){p?.(Ae.message??"Failed to retrieve PayPal payment status.");return}if(re&&(re.status==="requires_capture"||re.status==="succeeded")){let fe=typeof re.payment_method=="string"?re.payment_method:re.payment_method?.id;X({id:fe??re.id,type:"card",threeDSecureActionResultTokenId:re.id,isPaypal:!0});let ye=new URL(window.location.href);ye.searchParams.delete("payment_intent"),ye.searchParams.delete("payment_intent_client_secret"),ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",ye.toString())}else p?.("PayPal payment was not completed. Please try again.")}catch(q){p?.(q instanceof Error?q.message:"Failed to complete PayPal payment.")}finally{y(!1)}})())},[v,X,p]);let B=sa(async()=>{if(!(!v||!I))try{if(y(!0),p?.(null),!e||!i)throw new hl("Missing sessionId or email for PayPal payment","validation_error");let G=await v.confirmPayPalPayment({billingApiUrl:K,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(G.error){p?.(G.error.message);return}G.paymentIntentId&&(G.status==="succeeded"||G.status==="processing"||G.status==="requires_capture")&&X({id:G.paymentMethodId??G.paymentIntentId,type:"card",threeDSecureActionResultTokenId:G.paymentIntentId,isPaypal:!0})}catch(G){p?.(G instanceof Error?G.message:"PayPal payment failed. Please try again.")}finally{y(!1)}},[v,I,e,t,i,K,X,p]);return!v||!I?br("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):Sl(Cl,{children:[!m&&br("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),br("div",{style:m?{}:{display:"none"},children:br("button",{type:"button",onClick:B,disabled:T||R,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:T||R?"not-allowed":"pointer",opacity:T||R?.6:1},ref:()=>w(!0),children:T?"Processing...":"PayPal"})}),(T||R)&&br("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:br("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 Un,useEffect as vr,useMemo as qr,useRef as Cr,useState as bo}from"react";import{PaymentAPI as la}from"@flopay/js";import{FloPayError as $n,resolveBillingApiUrl as wl,resolveButtonsLayoutTheme as kl,resolveTheme as Rl}from"@flopay/shared";import{Fragment as Ml,jsx as Sr,jsxs as Bl}from"react/jsx-runtime";var Il=44;function xi(e){return new Promise(t=>setTimeout(t,e))}function El(e,t){return e instanceof $n?e:new $n(e instanceof Error?e.message:t,"api_error")}function _l(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function xl(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 Tl({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:o,clientId:a,products:c,items:s,subscriptions:S,account:M,successUrl:p,cancelUrl:R,couponCodes:v,tagsData:I,utmMetadata:l,billingApiUrl:m,locale:w,theme:T,appearance:y,buttonsTheme:U,buttonsStyles:K,onSuccess:ue,onError:X,onDecline:B,children:G,disabled:$=!1,type:pe="button",style:N,...q}){let re=qr(()=>wl(m),[m]),Ae=qr(()=>xl({createSession:n,clientId:a,products:c,items:s,subscriptions:S,account:M,successUrl:p,cancelUrl:R,couponCodes:v,tagsData:I,utmMetadata:l}),[M,R,a,v,n,c,s,S,p,I,l]),[fe,ye]=bo(!1),[J,me]=bo(null),[be,oe]=bo(null),[De,Re]=bo(null),Se=Cr(!0),k=Cr(null),ee=Cr(De),ie=Cr(ue),ze=Cr(X),Le=Cr(B);vr(()=>{ee.current=De},[De]),vr(()=>{ie.current=ue},[ue]),vr(()=>{ze.current=X},[X]),vr(()=>{Le.current=B},[B]),vr(()=>(Se.current=!0,()=>{Se.current=!1,k.current?.abort()}),[]),vr(()=>{if(typeof window>"u")return;let f=we=>{we.key==="Escape"&&Re(null)};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[]);let W=Un((f,we=Ur)=>{Le.current?.(St(we,f,{code:f.code,declineCode:f.declineCode}))},[]),x=Un(async f=>{Se.current&&(oe(null),me("success"),await xi(Mn),Se.current&&ie.current?.(f))},[]),j=Un(async(f,we)=>{Se.current&&(ze.current?.(f),we?.emitDecline&&W(f,we.method),oe(f.message),me("error"),await xi(Cn))},[W]),se=Un(async(f,we,je)=>{let st=f.data.session??null;if(!st)throw new $n("No session data returned","api_error");let rt=st.clientSecret||t;if(st.status==="complete"){await x({result:{status:"succeeded"},session:st,sessionId:st.id||we,autoCompleted:!1});return}if(st.status==="expired")throw new $n("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(f.autoProcessingPending){let bt=(await new la(re).waitForCheckoutSessionCompletion(f.autoProcessingPending.sessionId,{initialDelayMs:f.autoProcessingPending.retryAfterMs})).data.session;if(!bt||bt.status!=="complete")throw new $n("Automatic payment failed. Please try again.","api_error",{code:bt?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await x({result:{status:"succeeded"},session:bt,sessionId:bt.id||we,autoCompleted:!1});return}if(f.autoProcessingError){if(f.autoProcessingError.type==="3ds_required"&&f.autoProcessingError.nextActionRedirectUrl&&we&&rt){let Ge=new AbortController;k.current=Ge;let ve;try{ve=await Pi({billingApiUrl:re,sessionId:we,nonce:rt,nextActionRedirectUrl:f.autoProcessingError.nextActionRedirectUrl,signal:Ge.signal})}finally{k.current===Ge&&(k.current=null)}if(ve.status==="declined")throw zn({type:ve.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ve.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:f.autoProcessingError.checkoutMethod});let Ut=(await new la(re).waitForCheckoutSessionCompletion(we,{initialDelayMs:0,nonce:rt})).data.session;if(!Ut||Ut.status!=="complete")throw zn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:f.autoProcessingError.checkoutMethod});await x({result:{status:"succeeded"},session:Ut,sessionId:Ut.id||we,autoCompleted:!1});return}throw zn(f.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.autoProcessingError.checkoutMethod})}if(je?.fromCreateSession&&f.autoProcessingAttempted===!0)throw zn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let et=await gr({billingApiUrl:re,sessionId:we??st.id,session:st,nonce:rt});if(et.type!=="success")throw zn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await x({result:et.result,session:st,sessionId:st.id||we,autoCompleted:!1})}catch(et){let Ge=er(et),ve=st.id||we;await j(Ge,{emitDecline:!0,method:Ge.checkoutMethod??Ur}),_l(Ge,ve)&&ve&&Se.current&&Re({sessionId:ve,errorMessage:Ge.message,nonce:rt||void 0})}},[t,re,j,x]),Ie=Un(async f=>{if(q.onClick?.(f),!(f.defaultPrevented||$||fe)){if(Re(null),e&&Ae){let we=new $n("Provide either sessionId or create-session props, not both.","validation_error");await j(we),Se.current&&(me(null),oe(null));return}if(!e&&!Ae){let we=new $n("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await j(we),Se.current&&(me(null),oe(null));return}ye(!0),oe(null),me("processing");try{let we=new la(re);if(e){let je=await we.getUnifiedCheckoutSession(e,t);await se(je,e);return}try{let je=await we.createAndFetchSession({...Ae});await se(je,je.data.session?.id??null,{fromCreateSession:!0})}catch(je){if(je instanceof $n&&je.code==="session_auto_completed"){await x({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw je}}catch(we){await j(El(we,"Automatic payment failed. Please try again."))}finally{Se.current&&(me(null),oe(null),ye(!1))}}},[q,Ae,$,fe,t,se,re,e,j,x]),it=Un(f=>{let we=ee.current;Re(null),ie.current?.({result:f,session:null,sessionId:we?.sessionId??null,autoCompleted:!1})},[]),Qe=Un(f=>{ze.current?.(f)},[]),Ze=Un(f=>{Le.current?.(f)},[]),u=qr(()=>Rl(T),[T]),$e=qr(()=>{let f=u?.buttonsLayout??kl(U);return K?{...f,...K,cardButton:{...f.cardButton,...K.cardButton}}:f},[u,U,K]),Ue=qr(()=>{let f=u?.appearance;return y?f?{...f,...y,variables:{...f.variables,...y.variables}}:y:f},[y,u]),We=Ue?.variables,qe=We?.colorPrimary??"#4A49FF",Yt=We?.colorPrimaryHover??lo(qe,.12),Pt=We?.borderRadius??"8px";return Bl(Ml,{children:[Sr("button",{...q,type:pe,onClick:Ie,disabled:$||fe,"aria-busy":fe,style:{width:"100%",...G===void 0?{boxSizing:"border-box",height:Il,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...$e.cardButton,...Jo({themeBundle:u,resolvedPrimaryColor:qe,resolvedBorderRadius:Pt,submitButtonStyle:$e.submitButton,explicitPrimaryColor:We?.colorPrimary}),fontSize:$e.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:$||fe?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:$||fe?.6:1,...N},onMouseEnter:f=>{q.onMouseEnter?.(f),!f.defaultPrevented&&!$&&!fe&&(u||We?.colorPrimary)&&(f.currentTarget.style.backgroundColor=Yt)},onMouseLeave:f=>{q.onMouseLeave?.(f),!f.defaultPrevented&&(u||We?.colorPrimary)&&(f.currentTarget.style.backgroundColor=qe)},onMouseDown:f=>{q.onMouseDown?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(0.985)")},onMouseUp:f=>{q.onMouseUp?.(f),f.defaultPrevented||(f.currentTarget.style.transform="scale(1)")},children:Sr(ir,{content:G})}),J&&Sr(Sn,{status:J,errorMessage:be}),De&&Sr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:f=>{f.target===f.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:Sr("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:Sr(ia,{sessionId:De.sessionId,nonce:De.nonce,checkoutMode:"full",billingApiUrl:re,locale:w,theme:T,...Ue?{appearance:Ue}:{},buttonsTheme:U,buttonsStyles:K,initialErrorMessage:De.errorMessage,cardTitleContent:null,onComplete:it,onError:Qe,onDecline:Ze})})})]})}export{yl as AddressElement,so as DirectPayPalButton,Tl as FloPayAutomaticPaymentButton,ia as FloPayCheckout,eo as FloPayProvider,vl as PayPalButton,ml as PaymentElement,Xo as SplitCardForm,Do as VaultCardFields,ls as useCheckout,No as useElements,vn as useFloPay,Lo as usePayPalFloPay};
|