@flopay/react 1.4.13 → 1.4.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,12 +1,12 @@
1
- import{useCallback as rs,useEffect as Ar,useState as Do,useMemo as os,useRef as Lo}from"react";import{resolveBillingApiUrl as as}from"@flopay/shared";import{createContext as za}from"react";var Tn=za({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),un=za({session:null,loading:!1,error:null});var Qi=Symbol.for("@flopay/js.telemetry.bridge.v1"),es=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ts(){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 ns(e){let t=ts(),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 Qr(e){let t=globalThis[es];return ns(t?.(e)??{})}function Bt(e){if(e)return e[Qi]}import{jsx as is}from"react/jsx-runtime";function eo({flopay:e,paypalFlopay:t,options:n,children:i}){let[r,a]=Do(e instanceof Promise?null:e),[c,s]=Do(t instanceof Promise||!t?null:t),[C,B]=Do(null),m=Lo(null),k=Lo(null),v=Lo(null);Ar(()=>{if(!r)return;let S=Bt(r);return m.current=S?.beginCheckout()??S?.now()??0,S?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{S?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),Ar(()=>{let S=!1;return e instanceof Promise?e.then(T=>{S||a(T)}):a(e),()=>{S=!0}},[e]),Ar(()=>{let S=!1;if(!t){s(null);return}return t instanceof Promise?t.then(T=>{S||s(T)}):s(t),()=>{S=!0}},[t]),Ar(()=>{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]),Ar(()=>{if(!r||!C||k.current===C)return;k.current=C;let S=Bt(r);S?.log({name:"checkout.rendered",stage:"checkout_render"}),S?.performance({stage:"checkout_render",durationMs:S.elapsed(m.current??0),durationMode:"machine"})},[C,r]);let E=rs(()=>{if(!r||!C||v.current===C)return;v.current=C;let S=Bt(r);S?.log({name:"checkout.interactive",stage:"checkout_interactive"}),S?.performance({stage:"checkout_interactive",durationMs:S.elapsed(m.current??0),durationMode:"machine"})},[C,r]),l=as(n?.billingApiUrl),y=os(()=>({flopay:r,paypalFlopay:c,elements:C,billingApiUrl:l,reportInteractive:E}),[r,c,C,l,E]);return is(Tn.Provider,{value:y,children:i})}import na,{useCallback as nr,useEffect as An,useMemo as pn,useRef as rn,useState as kt}from"react";import{PaymentAPI as go,SESSION_CREATE_TELEMETRY as al}from"@flopay/js";import{SDK_VERSION as _i,FloPayError as At,classifyTelemetryFailure as il,resolveBillingApiUrl as sl,buildCheckoutDisplayData as wi,resolveButtonsLayoutTheme as ll,resolveIdempotencyKey as ki,resolveTheme as xi}from"@flopay/shared";import"react";import{Fragment as cr,jsx as tn,jsxs as Ua}from"react/jsx-runtime";function ss(){return Ua(cr,{children:[Ua("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:[tn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),tn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",tn("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:tn("path",{d:"M9 18l6-6-6-6"})})]})}function ls(){return tn(cr,{children:"Go back"})}function cs(){return tn(cr,{children:"Secure card checkout"})}function ir(e){return e!==void 0&&(e===""||e===null||e===!1)}function sr({content:e}){return tn(cr,{children:e===void 0?tn(ss,{}):e})}function lr({content:e}){return tn(cr,{children:e===void 0?tn(ls,{}):e})}function Fr({content:e}){return tn(cr,{children:e===void 0?tn(cs,{}):e})}import{ExpressCheckoutElement as pi,PaymentElement as Rs,Elements as er,useElements as Jo,useStripe as Xo}from"@stripe/react-stripe-js";import{resolveButtonsLayoutTheme as Is,getPostalCodeLabel as Yo,getStateLabel as ei,getStateOptions as Es,COUNTRY_OPTIONS as _s,resolveAVSConfig as xs,isAVSFieldVisible as Te,getStateFromPostalCode as ti,isPostalCodeSupported as Ts,isValidPostalCode as Ms,getPostalCodeExample as Bs,filterStripeMethodsByCountry as As,getStripeMethodDisplayName as gr,hasVendoredStripeMethodLogo as Fs,needsStripeMethodExplicitConfirm as ni,resolveStripeMethodBrandVariant as Ds,partitionStripeMethods as Ls,stripeExpressMethodToOptionKey as ri}from"@flopay/shared";import{PaymentAPI as zn,toStripeAppearance as Ns}from"@flopay/js";import{useEffect as $a,useRef as Dr}from"react";import{jsx as ds}from"react/jsx-runtime";function No({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:r,containerStyle:a,onReady:c,onError:s,onValidation:C}){let B=Dr(null),m=Dr(c),k=Dr(s),v=Dr(C);m.current=c,k.current=s,v.current=C;let E=Dr(r);return E.current=r,$a(()=>{let l=B.current;if(!l)return;let y=!0,S=!1,T=()=>{!y||S||(S=!0,m.current?.())},f=e.on("ready",()=>{T()}),$=e.on("error",ee=>{k.current?.(ee.message??"There was a problem loading the secure card form.")}),Y=e.on("validation",ee=>{v.current?.(ee.message??null)}),ye={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},...E.current?{theme:E.current}:{}};return e.mount(l,ye).then(()=>{T()}).catch(ee=>{y&&k.current?.(ee instanceof Error?ee.message:"Failed to load the secure card form.")}),()=>{y=!1,f(),$(),Y(),e.unmount()}},[e,t,n,i]),$a(()=>{r&&e.applyTheme?.(r)},[e,r]),ds("div",{ref:B,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as qa,jsxs as us}from"react/jsx-runtime";function dr({children:e,margin:t,icon:n=!0,styleOverride:i}){return us("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&&qa("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:qa("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 ja={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 Os,{useCallback as Se,useContext as zs,useEffect as ft,useMemo as ot,useRef as Le,useState as ve}from"react";import{useContext as Lr}from"react";import{resolveBillingApiUrl as ps}from"@flopay/shared";function vn(){return Lr(Tn).flopay}function Oo(){return Lr(Tn).paypalFlopay??null}function zo(){return Lr(Tn).elements}function ms(){return Lr(un)}function to(){return Lr(Tn).billingApiUrl||ps()}import"react";import{jsx as nn,jsxs as ur}from"react/jsx-runtime";var Mn=1200,Cn=1500;function Sn({status:e,errorMessage:t}){return nn("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:ur("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:[ur("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&ur("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:[nn("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),nn("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&nn("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:ur("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[nn("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),nn("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"&&nn("div",{style:{animation:"flopay-shake 0.4s ease"},children:ur("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[nn("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),nn("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"}})]})})]}),ur("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"&&nn("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&&nn("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),nn("style",{children:`
1
+ import{useCallback as as,useEffect as Fr,useState as Lo,useMemo as is,useRef as No}from"react";import{resolveBillingApiUrl as ss}from"@flopay/shared";import{createContext as $a}from"react";var Tn=$a({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),un=$a({session:null,loading:!1,error:null});var ts=Symbol.for("@flopay/js.telemetry.bridge.v1"),ns=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function rs(){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 os(e){let t=rs(),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 eo(e){let t=globalThis[ns];return os(t?.(e)??{})}function Tt(e){if(e)return e[ts]}import{jsx as ls}from"react/jsx-runtime";function to({flopay:e,paypalFlopay:t,options:n,children:i}){let[r,a]=Lo(e instanceof Promise?null:e),[d,l]=Lo(t instanceof Promise||!t?null:t),[C,T]=Lo(null),y=No(null),k=No(null),b=No(null);Fr(()=>{if(!r)return;let R=Tt(r);return y.current=R?.beginCheckout()??R?.now()??0,R?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{R?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),Fr(()=>{let R=!1;return e instanceof Promise?e.then(x=>{R||a(x)}):a(e),()=>{R=!0}},[e]),Fr(()=>{let R=!1;if(!t){l(null);return}return t instanceof Promise?t.then(x=>{R||l(x)}):l(t),()=>{R=!0}},[t]),Fr(()=>{if(!r){T(null);return}let R=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return T(R),()=>{R.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),Fr(()=>{if(!r||!C||k.current===C)return;k.current=C;let R=Tt(r);R?.log({name:"checkout.rendered",stage:"checkout_render"}),R?.performance({stage:"checkout_render",durationMs:R.elapsed(y.current??0),durationMode:"machine"})},[C,r]);let E=as(()=>{if(!r||!C||b.current===C)return;b.current=C;let R=Tt(r);R?.log({name:"checkout.interactive",stage:"checkout_interactive"}),R?.performance({stage:"checkout_interactive",durationMs:R.elapsed(y.current??0),durationMode:"machine"})},[C,r]),c=ss(n?.billingApiUrl),h=is(()=>({flopay:r,paypalFlopay:d,elements:C,billingApiUrl:c,reportInteractive:E}),[r,d,C,c,E]);return ls(Tn.Provider,{value:h,children:i})}import ra,{useCallback as rr,useEffect as An,useMemo as pn,useRef as jt,useState as wt}from"react";import{PaymentAPI as ho,SESSION_CREATE_TELEMETRY as ll}from"@flopay/js";import{SDK_VERSION as Ti,FloPayError as Mt,classifyTelemetryFailure as cl,resolveBillingApiUrl as dl,buildCheckoutDisplayData as Ri,resolveButtonsLayoutTheme as ul,resolveIdempotencyKey as Ii,resolveTheme as Mi}from"@flopay/shared";import"react";import{Fragment as dr,jsx as nn,jsxs as qa}from"react/jsx-runtime";function cs(){return qa(dr,{children:[qa("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 ds(){return nn(dr,{children:"Go back"})}function us(){return nn(dr,{children:"Secure card checkout"})}function sr(e){return e!==void 0&&(e===""||e===null||e===!1)}function lr({content:e}){return nn(dr,{children:e===void 0?nn(cs,{}):e})}function cr({content:e}){return nn(dr,{children:e===void 0?nn(ds,{}):e})}function Dr({content:e}){return nn(dr,{children:e===void 0?nn(us,{}):e})}import{ExpressCheckoutElement as yi,PaymentElement as Es,Elements as tr,useElements as Xo,useStripe as Zo}from"@stripe/react-stripe-js";import{resolveButtonsLayoutTheme as _s,getPostalCodeLabel as Go,getStateLabel as ni,getStateOptions as xs,COUNTRY_OPTIONS as Ts,resolveAVSConfig as Ms,isAVSFieldVisible as Be,getStateFromPostalCode as ri,isPostalCodeSupported as Bs,isValidPostalCode as As,getPostalCodeExample as Fs,filterStripeMethodsByCountry as Ds,getStripeMethodDisplayName as hr,hasVendoredStripeMethodLogo as Ls,needsStripeMethodExplicitConfirm as oi,resolveStripeMethodBrandVariant as Ns,partitionStripeMethods as Os,stripeExpressMethodToOptionKey as ai}from"@flopay/shared";import{PaymentAPI as On,toStripeAppearance as zs}from"@flopay/js";import{useEffect as ja,useRef as Lr}from"react";import{jsx as ps}from"react/jsx-runtime";function Oo({capture:e,html:t,messageToken:n,expectedOrigin:i,theme:r,containerStyle:a,onReady:d,onError:l,onValidation:C}){let T=Lr(null),y=Lr(d),k=Lr(l),b=Lr(C);y.current=d,k.current=l,b.current=C;let E=Lr(r);return E.current=r,ja(()=>{let c=T.current;if(!c)return;let h=!0,R=!1,x=()=>{!h||R||(R=!0,y.current?.())},f=e.on("ready",()=>{x()}),ae=e.on("error",J=>{k.current?.(J.message??"There was a problem loading the secure card form.")}),O=e.on("validation",J=>{b.current?.(J.message??null)}),le={html:t,...n?{messageToken:n}:{},...i?{expectedOrigin:i}:{},...E.current?{theme:E.current}:{}};return e.mount(c,le).then(()=>{x()}).catch(J=>{h&&k.current?.(J instanceof Error?J.message:"Failed to load the secure card form.")}),()=>{h=!1,f(),ae(),O(),e.unmount()}},[e,t,n,i]),ja(()=>{r&&e.applyTheme?.(r)},[e,r]),ps("div",{ref:T,"data-testid":"flopay-vault-card-fields",style:a})}import"react";import{jsx as Va,jsxs as ms}from"react/jsx-runtime";function ur({children:e,margin:t,icon:n=!0,styleOverride:i}){return ms("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&&Va("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Va("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 Ka={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 Us,{useCallback as we,useContext as $s,useEffect as pt,useMemo as rt,useRef as Fe,useState as ve}from"react";import{useContext as Nr}from"react";import{resolveBillingApiUrl as ys}from"@flopay/shared";function gn(){return Nr(Tn).flopay}function zo(){return Nr(Tn).paypalFlopay??null}function Uo(){return Nr(Tn).elements}function fs(){return Nr(un)}function no(){return Nr(Tn).billingApiUrl||ys()}import"react";import{jsx as rn,jsxs as pr}from"react/jsx-runtime";var Mn=1200,hn=1500;function Pn({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:pr("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:[pr("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&pr("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:pr("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:pr("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"}})]})})]}),pr("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 Mc,isSetupIntentClientSecret as Bc}from"@flopay/shared";function Ka(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 Uo(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 Va(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 $o(e,t){return t?{...e,...t}:e}function wt(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 ys=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Nn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:i}of ys)if(n.test(t))return i;return e}function no(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Ha(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Wa(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 pr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(oo+e,JSON.stringify(t))}catch{}}function qo(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 Ya(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 yt,useMemo as Or,useRef as Ye,useState as Qn}from"react";import{loadScript as gs}from"@paypal/paypal-js";import{PaymentAPI as jo}from"@flopay/js";import{FloPayError as Ga,SDK_VERSION as hs,generateIdempotencyKey as Ps,normalizeGatewayEnvironment as bs}from"@flopay/shared";function mt(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 fs(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Zn(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 Zn(t.code)??Zn(t.type)??Zn(t.name)}function mr(e){if(!(typeof e!="object"||e===null))return Zn(e.decline_code)}function Nr(e){return typeof e!="object"||e===null?!1:Zn(e.type)?.toLowerCase()==="card_error"||mr(e)!==void 0}function On(e){let t=fs(e)?.toLowerCase()??"",i=`${Bn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as yr,jsxs as Ko}from"react/jsx-runtime";var io=45,vs=1e3,Cs=11e3,Ss=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ja="We couldn't open PayPal. Try again or choose another payment method.",ws={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 Xa(e){return e.includes("No ack for postMessage init()")&&Ss.some(t=>e.includes(t))&&e.includes("10000ms")}function ks(e){return e?`${Ja} Allow pop-ups for this site, then try again.`:Ja}function Za({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:r,environment:a,currency:c,isSubscription:s,onTokenizedBody:C,onComplete:B,onErrorChange:m,onDecline:k,onTechnicalFailure:v,isProcessing:E=!1,onLoadStateChange:l,onInitializationStateChange:y,allowAutomaticRetry:S=!0,onButtonClick:T,runBeforeButtonClick:f,session:$,existingOrderId:Y,telemetry:ye,telemetryContext:ee,debug:A=!1}){let J=vn(),q=Or(()=>{if(J)return null;let _=Qr({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:hs,enabled:ye!==!1});return _.setCheckoutContext(ee??{}),_.beginCheckout(ee??{}),_},[n,J,ye,ee?.checkoutMode,ee?.layout]),fe=Or(()=>Bt(J),[J]);yt(()=>()=>{q&&q.flush().catch(()=>{}).finally(()=>q.destroy())},[q]);let D=Or(()=>({error:_=>{fe?fe.error(_):q?.error(_)},log:_=>{fe?fe.log(_):q?.log(_)},performance:_=>{fe?fe.performance(_):q?.performance(_)},terminal:_=>{fe?fe.terminal(_):q?.terminal(_)},startTiming:()=>fe?.now()??q?.now()??0,elapsed:_=>fe?.elapsed(_)??Math.max(0,(q?.now()??_)-_)}),[fe,q]),j=Ye(null),ae=Ye(0),Be=Ye(null),be=Ye(!1),[Pe,X]=Qn(!1),[ge,we]=Qn(!1),[ie,Fe]=Qn(0),_e=Ye(0),[Re,w]=Qn(!1),re=Ye(!1),ce=Ye(!1),[Ne,De]=Qn(!1),[G,x]=Qn(!1),K=Or(()=>n.replace(/\/+$/,""),[n]),de=Or(()=>JSON.stringify([K,r,c,a??"",s,e,Y??""]),[K,r,c,a,Y,s,e]),xe=Ye(de),it=xe.current!==de,[Qe,Ze]=Qn([]),p=_=>{A&&Ze(Je=>[...Je,`${new Date().toISOString().slice(11,23)} ${_}`])},ze=Ye(C),Oe=Ye(B),Ve=Ye(m),Ue=Ye(k),Yt=Ye(v),bt=Ye(T),It=Ye(l),g=Ye(y),Ie=Ye(f),$e=Ye($),st=Ye(i),rt=Ye(t),et=Ye(null),Ge=Ye(0),ke=Ye(null),vt=Ye(null),qe=Ye(new Map),zt=Ye(new Map),Et=Ye(!1);yt(()=>(Et.current=!0,()=>{Et.current=!1}),[]),yt(()=>{ze.current=C},[C]),yt(()=>{Oe.current=B},[B]),yt(()=>{Ve.current=m},[m]),yt(()=>{Ue.current=k},[k]),yt(()=>{Yt.current=v},[v]),yt(()=>{bt.current=T},[T]),yt(()=>{It.current=l},[l]),yt(()=>{g.current=y},[y]),yt(()=>{Ie.current=f},[f]),yt(()=>{$e.current=$},[$]),yt(()=>{st.current=i},[i]),yt(()=>{rt.current=t},[t]),yt(()=>{_e.current=ie},[ie]),yt(()=>{Re&&Be.current?.focus()},[Re,ie]);let mn=ao(()=>{window.setTimeout(()=>{Be.current?.focus()},0)},[]),En=ao(()=>{X(!1),Fe(_=>_+1)},[]),_n=ao(()=>{w(!1),(j.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??j.current)?.focus?.()},[]);yt(()=>{!Pe||!be.current||(be.current=!1,_n())},[_n,Pe,ie]);let jn=ao((_,Je)=>{let Ee=Yt.current;if(Ee){Ee("paypal",_,Je);return}Ve.current?.(ks(Je?.popupBlocked??On(_)))},[]),Pt=()=>{ke.current?.timer&&(clearTimeout(ke.current.timer),ke.current.timer=null)},Ut=()=>{Pt();let _=Ge.current+1;return Ge.current=_,vt.current=null,ke.current={generation:_,timer:null,yieldedControl:!1},w(!1),_},Dt=_=>_!==void 0&&ke.current?.generation!==_?!1:(Pt(),ke.current=null,vt.current=null,!0),Gt=_=>{let Je=_?.generation??ke.current?.generation??Ge.current;(!_?.generation||ke.current?.generation===Je)&&(Pt(),ke.current=null),vt.current=Je,_?.showRetry&&w(!0),_?.remount&&En(),_?.focus!==!1&&mn()},on=_=>ke.current?.generation===_&&vt.current!==_,yn=_=>{typeof document<"u"&&document.visibilityState!=="visible"||(Pt(),_.timer=setTimeout(()=>{ke.current?.generation===_.generation&&(ke.current=null,vt.current=_.generation,jn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),w(!0),En(),mn())},600))},V=()=>{let _=ke.current;_?.yieldedControl&&yn(_)},Dn=()=>{let _=ke.current;_&&(_.yieldedControl=!0,Pt())},fn=_=>{let Je=et.current;return Je&&zt.current.set(_,Je),_};yt(()=>{let _=()=>{document.visibilityState==="visible"?V():Dn()};return document.addEventListener("visibilitychange",_),window.addEventListener("focus",V),window.addEventListener("blur",Dn),()=>{document.removeEventListener("visibilitychange",_),window.removeEventListener("focus",V),window.removeEventListener("blur",Dn),Pt()}},[]),yt(()=>{xe.current!==de&&(xe.current=de,re.current=!1,ce.current=!1,X(!1),we(!1),De(!1),g.current?.("loading"))},[de]),yt(()=>{mt(()=>It.current?.(Pe&&!Ne))},[Pe,Ne]);let $t=bs(a);yt(()=>{let _=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",Je=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(p(`mount clientId=${_} env=${a??"(unset)"}\u2192${$t??"live"} ccy=${c} sub=${s}`),p(`ua=${Je.slice(0,80)}${Je.length>80?"\u2026":""}`),!r){p("FAIL: clientId empty \u2014 gateway misconfigured"),De(!0),D.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(!j.current){p("FAIL: containerRef not attached");return}ae.current=D.startTiming(),D.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ee=!1,Ln=!1,je=()=>Ee||Ln,Kn,gn=!1,hn=()=>{Kn=Ps(),Kn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),gn=!0},tt=null,_t=!1,qt=null,Lt=!1,Jt=()=>{!qt||Lt||(Lt=!0,qt.close().catch(()=>{}))},an=null,xn=()=>{an!==null&&(D.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"overlay_return",durationMs:D.elapsed(an),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),an=null)},Vt=!1,Nt=j.current,Xt=null,Ce=null,gt=[],lt=M=>{if(!M||typeof M.getBoundingClientRect!="function")return"(no rect)";let u=M.getBoundingClientRect();return`${Math.round(u.width)}\xD7${Math.round(u.height)}`},Pn=M=>{if(!M)return"(empty)";try{let u=new URL(M,typeof window<"u"?window.location.href:"https://localhost"),h=u.pathname.toLowerCase();return h.includes("checkcaptcha")||h.includes("captcha")?`CAPTCHA(${u.host}${h})`:h.includes("risk")||h.includes("challenge")?`RISK(${u.host}${h})`:h.includes("smart/buttons")?`smart-buttons(${u.host})`:`${u.host}${h}`.slice(0,100)}catch{return M.slice(0,80)}},Vn=M=>{let u=M.getAttribute("src"),h=M.getAttribute("srcdoc"),pe=M.getAttribute("name"),H=M.getAttribute("sandbox"),Ke=[];return u&&Ke.push(`src=${Pn(u)}`),h&&Ke.push(`srcdoc[${h.length}ch]`),!u&&!h&&Ke.push("src=(empty) srcdoc=(empty)"),pe&&Ke.push(`name=${pe.slice(0,40)}`),H!==null&&Ke.push(`sandbox="${H.slice(0,40)}"`),Ke.join(" ")},Ot=M=>{if(!(M instanceof HTMLIFrameElement))return"";try{let u=M.contentDocument;if(!u)return"cd=null";let h=u.body?.children.length??0,pe=u.body?.innerHTML.length??0,H=u.head?.innerHTML.length??0;return`cd=same-origin readyState=${u.readyState} body[${h}children,${pe}ch] head[${H}ch]`}catch(u){return`cd=cross-origin(${u.message.slice(0,30)})`}},Ht=[],Ct=M=>{if(je())return;let u=M.message??String(M.error??"(no message)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(p(`window:error ${u.slice(0,140)}`),Ht.push(u))},rr=M=>{if(je())return;let u=M.reason instanceof Error?M.reason.message:String(M.reason??"(no reason)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(p(`window:rejection ${u.slice(0,140)}`),Ht.push(u))};A&&typeof window<"u"&&(window.addEventListener("error",Ct),window.addEventListener("unhandledrejection",rr));let Wt={value:0};if(A&&typeof PerformanceObserver<"u")try{Ce=new PerformanceObserver(M=>{if(!je())for(let u of M.getEntries()){if(!u.name.toLowerCase().includes("paypal"))continue;Wt.value+=1;let h=Math.round(u.duration);p(`net ${h}ms ${u.name.slice(0,90)}`)}}),Ce.observe({type:"resource",buffered:!0})}catch{}let R=()=>{for(Xt?.disconnect(),Xt=null,Ce?.disconnect(),Ce=null;gt.length;)clearTimeout(gt.pop());A&&typeof window<"u"&&(window.removeEventListener("error",Ct),window.removeEventListener("unhandledrejection",rr))},O=M=>{if(!M)return!1;let u=M.toLowerCase();return u.includes("zoid destroyed")||u.includes("destroyed all components")||u.includes("window closed")||u.includes("detected container element removed")},W=M=>{if(je()||O(M))return;let u=Nn(M)??M;mt(()=>Ve.current?.(u))},Q=M=>{Ee||(De(!0),M.includes("paypal_ineligible")||D.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",M))},se=(M,u=!1)=>{if(Ee)return;let h=re.current||!S;if(_t)return;_t=!0,Ln=!0,R(),Jt();let pe=u||Xa(M);if(pe&&S&&!re.current){re.current=!0,X(!1),x(!1),we(!0),g.current?.("retrying"),tt=setTimeout(()=>{Ee||Fe(H=>H+1)},vs);return}if(pe||h){if(X(!1),x(!1),we(!1),De(!0),g.current?.("exhausted"),!ce.current){ce.current=!0;let H=Xa(M)?"paypal_init_timeout":u?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",H)}return}Q(M)};De(!1);let N=async(M,u=et.current)=>{if(je())return;let h=u?.sessionId??e;if(ze.current){await ze.current(M,{sessionId:h,accountPatch:u?.accountPatch,nonce:u?.nonce});return}let pe=D.startTiming();D.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let H=()=>{D.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"processing",durationMs:D.elapsed(pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let Ke=$e.current,dt=u?.accountPatch?.email??st.current,jt=u?.accountPatch?.userId??Ke?.customer?.id??Ke?.accountData?.userId??"",ue=await new jo(K,{telemetry:!1}).processPayment(jt,{sessionId:h,nonce:u?.nonce??rt.current,tokenizedData:M,accountData:{userId:jt,email:dt??Ke?.customer?.email??"",firstName:u?.accountPatch?.firstName??Ke?.customer?.firstName??Ke?.accountData?.firstName??"",lastName:u?.accountPatch?.lastName??Ke?.customer?.lastName??Ke?.accountData?.lastName??"",country:u?.accountPatch?.country??Ke?.customer?.country??Ke?.accountData?.country??void 0,zip:u?.accountPatch?.zip??Ke?.customer?.zip??Ke?.accountData?.zip??void 0}});if(ue.ok){if(Ln||Ee&&Et.current)return;H(),D.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),mt(()=>Oe.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(je())return;let me=await ue.json().catch(()=>null),We=me?.message??"PayPal payment failed.",sn=Nn(We)??We;H(),ue.status===400&&(typeof me?.declineCode=="string"||!Array.isArray(me?.fields))?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ue.status===400||ue.status===422?D.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):D.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ue.status>=500?"5xx":ue.status>=400?"4xx":ue.status>=300?"3xx":"unknown",failureCategory:ue.status>=500?"server_error":void 0}),W(sn),mt(()=>Ue.current?.(wt("paypal",sn,{code:me?.code,declineCode:me?.declineCode})));return}catch(Ke){if(je())return;H(),D.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let dt=Ke instanceof Error?Ke.message:"PayPal payment failed.",jt=Nn(dt)??dt;W(jt),mt(()=>Ue.current?.(wt("paypal",jt)));return}},P=()=>new Ga("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Z=M=>je()?Promise.reject(P()):Promise.resolve(M),F=async M=>{if(je())throw P();gn||hn();let u=et.current,h=u?.sessionId??e,pe=u?.nonce??rt.current;D.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let H=await new jo(K,{telemetry:!1}).createSessionIntent(h,pe??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Kn});if(je())throw P();if(H.provider!=="paypal")throw new Error(M);return D.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),H.providerObjectId},le=(M,u)=>{let h=u?.nonce??rt.current;if(!h)return;let pe=u?.sessionId??e,H=mr(M)??Bn(M)??"provider_declined";new jo(K,{telemetry:!1}).reportSessionIntentDecline(pe,h,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:H}).catch(()=>{})},he=ie;p("loadScript:scheduled (deferred 1 tick)");let I=null,ct=setTimeout(()=>{if(Ee){p("loadScript:skipped (cancelled before defer ran)");return}p("loadScript:start");let M=$t==="live"?"production":$t;I=gs({clientId:r,currency:c,intent:s?"subscription":"capture",vault:s?!0:void 0,...M?{environment:M}:{},...M==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),I.then(u=>{if(p(`loadScript:resolved inactive=${je()} ns=${!!u} buttons=${!!u?.Buttons}`),je())return;if(!u?.Buttons){p("FAIL: namespace missing Buttons factory"),se("PayPal SDK did not expose the Buttons factory.");return}D.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"provider_ready",durationMs:D.elapsed(ae.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let h=async He=>{if(je()||_e.current!==he)return;let ue=He.subscriptionID??He.orderID??"",me=ue?zt.current.get(ue):qe.current.get(he);if(!(!me||!on(me.generation))&&Dt(me.generation)){zt.current.delete(ue),qe.current.delete(me.surfaceKey),xn();try{if(x(!0),mt(()=>Ve.current?.(null)),!ue)throw new Ga("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await N({id:ue,isPaypal:!0},me)}catch(We){W(We instanceof Error?We.message:"PayPal capture failed.")}finally{je()||x(!1)}}},pe=u.Buttons({style:{layout:"horizontal",height:io,tagline:!1},onClick:async(He,ue)=>{if(je()){await ue.reject();return}hn();let me=Ie.current,We={};if(me)try{let z=await me("paypal");if(je()){await ue.reject();return}if(!z.proceed){et.current=null,qe.current.delete(he),await ue.reject();return}We={sessionId:z.sessionId,accountPatch:z.accountPatch,nonce:z.nonce}}catch(z){p(`onClick:runBeforeButtonClick rejected msg=${(z instanceof Error?z.message:String(z)).slice(0,120)}`),et.current=null,qe.current.delete(he),await ue.reject();return}mt(()=>bt.current?.("paypal"));let ln={generation:Ut(),surfaceKey:he,...We};et.current=ln,qe.current.set(he,ln),await ue.resolve(),D.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),an=D.startTiming()},createOrder:s?void 0:Y?()=>Z(Y).then(fn):()=>F("Failed to create PayPal order.").then(fn),createSubscription:s?Y?()=>Z(Y).then(fn):()=>F("Failed to create PayPal subscription.").then(fn):void 0,onApprove:h,onCancel:()=>{if(je())return;let He=qe.current.get(he)??et.current;He&&qe.current.delete(He.surfaceKey),et.current=null,xn(),D.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be.current=!0,Gt({generation:He?.generation,remount:!0,focus:!1})},onError:He=>{if(je()||_e.current!==he)return;let ue=He instanceof Error?He.message:"PayPal failed to render.";if(p(`onError rendered=${Vt} msg=${ue.slice(0,120)}`),Vt){let me=qe.current.get(he)??et.current;if(me&&!on(me.generation)||!me&&vt.current===Ge.current)return;if(O(ue)){Dt(me?.generation);return}if(xn(),Nr(He)){D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),le(He,me),mt(()=>Ue.current?.(wt("paypal",ue))),me&&qe.current.delete(me.surfaceKey),et.current=null,Dt(me?.generation);return}let We=ue.toLowerCase();D.error({errorCode:We.includes("popup")&&We.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),me&&qe.current.delete(me.surfaceKey),et.current=null,Gt({generation:me?.generation,remount:!0,showRetry:!0,focus:!0}),jn(He,{code:"paypal_runtime_failed"});return}se(ue)}}),H=pe.isEligible();if(p(`isEligible=${H}`),D.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!H){X(!1),se("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}qt=pe,A&&p(`container:dims ${lt(Nt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),A&&typeof MutationObserver<"u"&&(Xt=new MutationObserver(He=>{if(!je()){for(let ue of He)if(ue.type==="childList")ue.addedNodes.forEach(me=>{if(!(me instanceof Element))return;let We=me.tagName.toLowerCase(),sn=(me.getAttribute("title")??"").slice(0,40),ln=We==="iframe"?` ${Vn(me)}`:"";p(`child+ ${We}${sn?` title="${sn}"`:""}${ln} dims=${lt(me)}`)});else if(ue.type==="attributes"&&ue.target instanceof Element){let me=ue.target;if(me.tagName.toLowerCase()!=="iframe")continue;let We=ue.attributeName;(We==="src"||We==="srcdoc")&&p(`attr~ iframe ${We}=${We==="srcdoc"?`[${(me.getAttribute("srcdoc")??"").length}ch]`:Pn(me.getAttribute("src"))} dims=${lt(me)}`)}}}),Xt.observe(Nt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let dt=He=>{if(je()||Vt)return;let ue=Nt.querySelectorAll("iframe"),me=typeof document<"u"&&"hasStorageAccess"in document;p(`watchdog:${He} container=${lt(Nt)} children=${Nt.childElementCount} iframes=${ue.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${me} paypalNetRequests=${Wt.value}`),ue.forEach((We,sn)=>{let ln=(We.getAttribute("title")??"").slice(0,40);p(` iframe[${sn}] ${lt(We)}${ln?` title="${ln}"`:""} ${Vn(We)}`);let z=Ot(We);z&&p(` ${z}`)}),Ht.length===0&&p(" (no PayPal/zoid window errors captured)")};A&&(gt.push(setTimeout(()=>dt("3s"),3e3)),gt.push(setTimeout(()=>dt("8s"),8e3)),gt.push(setTimeout(()=>dt("15s"),15e3))),p("render:start");let jt=D.startTiming();gt.push(setTimeout(()=>{je()||Vt||(p("watchdog:11s retryable render timeout"),se("PayPal Buttons render did not settle within 11000ms.",!0))},Cs)),pe.render(Nt).then(()=>{if(p(`render:resolved inactive=${je()}`),R(),je()){Jt();return}Vt=!0,X(!0),we(!1),g.current?.("ready"),D.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"checkout_render",durationMs:D.elapsed(jt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(He=>{let ue=He instanceof Error?He.message:"PayPal failed to render.";p(`render:rejected msg=${ue.slice(0,120)}`),R(),se(ue)})}).catch(u=>{let h=u instanceof Error?u.message:"PayPal SDK failed to load.";p(`loadScript:rejected msg=${h.slice(0,120)}`),se(h)})},0);return()=>{Ee=!0,clearTimeout(ct),tt&&clearTimeout(tt),R(),Jt()}},[S,K,r,c,a,s,e,Y,ie,D]);let Ft=A?Ko("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=${Pe} failed=${Ne})`,Qe.length===0?`
6
+ `})]})})}import{FloPayError as Fc,isSetupIntentClientSecret as Dc}from"@flopay/shared";function Ha(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 $o(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 Wa(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,d)=>a+(d.overrideAmount??d.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,d)=>({uuid:`synthetic-${a.type??"item"}-${d}`,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 qo(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 gs=[{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 gs)if(n.test(t))return i;return e}function ro(e){return e==="succeeded"||e==="requires_capture"||e==="processing"}function Ya(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Ga(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function oo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var ao="flopay_recent_completion_";function mr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ao+e,JSON.stringify(t))}catch{}}function jo(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ao+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ao+e),!1):!0}catch{return!1}}function Ja(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 io,useEffect as ut,useMemo as zr,useRef as He,useState as er}from"react";import{loadScript as Ps}from"@paypal/paypal-js";import{PaymentAPI as Vo}from"@flopay/js";import{FloPayError as Xa,SDK_VERSION as bs,generateIdempotencyKey as vs,normalizeGatewayEnvironment as Cs}from"@flopay/shared";function dt(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 hs(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 Qn(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 Qn(t.code)??Qn(t.type)??Qn(t.name)}function yr(e){if(!(typeof e!="object"||e===null))return Qn(e.decline_code)}function Or(e){return typeof e!="object"||e===null?!1:Qn(e.type)?.toLowerCase()==="card_error"||yr(e)!==void 0}function Nn(e){let t=hs(e)?.toLowerCase()??"",i=`${Bn(e)?.toLowerCase()??""} ${t}`;return i.includes("popup")&&i.includes("block")}import{jsx as fr,jsxs as Ko}from"react/jsx-runtime";var so=45,Ss=1e3,ws=11e3,ks=["https://www.paypal.com","https://www.sandbox.paypal.com"],Za="We couldn't open PayPal. Try again or choose another payment method.",Rs={width:"100%",minHeight:so,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()")&&ks.some(t=>e.includes(t))&&e.includes("10000ms")}function Is(e){return e?`${Za} Allow pop-ups for this site, then try again.`:Za}function ei({sessionId:e,nonce:t,billingApiUrl:n,email:i,clientId:r,environment:a,currency:d,isSubscription:l,onTokenizedBody:C,onComplete:T,onErrorChange:y,onDecline:k,onTechnicalFailure:b,isProcessing:E=!1,onLoadStateChange:c,onInitializationStateChange:h,allowAutomaticRetry:R=!0,onButtonClick:x,runBeforeButtonClick:f,session:ae,existingOrderId:O,telemetry:le,telemetryContext:J,debug:M=!1}){let W=gn(),V=zr(()=>{if(W)return null;let S=eo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:bs,enabled:le!==!1});return S.setCheckoutContext(J??{}),S.beginCheckout(J??{}),S},[n,W,le,J?.checkoutMode,J?.layout]),ce=zr(()=>Tt(W),[W]);ut(()=>()=>{V&&V.flush().catch(()=>{}).finally(()=>V.destroy())},[V]);let z=zr(()=>({error:S=>{ce?ce.error(S):V?.error(S)},log:S=>{ce?ce.log(S):V?.log(S)},performance:S=>{ce?ce.performance(S):V?.performance(S)},terminal:S=>{ce?ce.terminal(S):V?.terminal(S)},startTiming:()=>ce?.now()??V?.now()??0,elapsed:S=>ce?.elapsed(S)??Math.max(0,(V?.now()??S)-S)}),[ce,V]),$=He(null),me=He(0),_e=He(null),be=He(!1),[he,X]=er(!1),[Pe,xe]=er(!1),[Z,Ie]=er(0),Me=He(0),[Re,H]=er(!1),I=He(!1),de=He(!1),[Ne,Oe]=er(!1),[ye,w]=er(!1),Q=zr(()=>n.replace(/\/+$/,""),[n]),G=zr(()=>JSON.stringify([Q,r,d,a??"",l,e,O??""]),[Q,r,d,a,O,l,e]),De=He(G),mt=De.current!==G,[Ve,at]=er([]),A=S=>{M&&at(Je=>[...Je,`${new Date().toISOString().slice(11,23)} ${S}`])},F=He(C),Ue=He(T),je=He(y),it=He(k),yt=He(b),Bt=He(x),Gt=He(c),m=He(h),Ce=He(f),We=He(ae),et=He(i),gt=He(t),Ye=He(null),Ze=He(0),Te=He(null),Ge=He(null),At=He(new Map),Ke=He(new Map),qn=He(!1);ut(()=>(qn.current=!0,()=>{qn.current=!1}),[]),ut(()=>{F.current=C},[C]),ut(()=>{Ue.current=T},[T]),ut(()=>{je.current=y},[y]),ut(()=>{it.current=k},[k]),ut(()=>{yt.current=b},[b]),ut(()=>{Bt.current=x},[x]),ut(()=>{Gt.current=c},[c]),ut(()=>{m.current=h},[h]),ut(()=>{Ce.current=f},[f]),ut(()=>{We.current=ae},[ae]),ut(()=>{et.current=i},[i]),ut(()=>{gt.current=t},[t]),ut(()=>{Me.current=Z},[Z]),ut(()=>{Re&&_e.current?.focus()},[Re,Z]);let ht=io(()=>{window.setTimeout(()=>{_e.current?.focus()},0)},[]),wn=io(()=>{X(!1),Ie(S=>S+1)},[]),kn=io(()=>{H(!1),($.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??$.current)?.focus?.()},[]);ut(()=>{!he||!be.current||(be.current=!1,kn())},[kn,he,Z]);let jn=io((S,Je)=>{let ke=yt.current;if(ke){ke("paypal",S,Je);return}je.current?.(Is(Je?.popupBlocked??Nn(S)))},[]),Rt=()=>{Te.current?.timer&&(clearTimeout(Te.current.timer),Te.current.timer=null)},Ft=()=>{Rt();let S=Ze.current+1;return Ze.current=S,Ge.current=null,Te.current={generation:S,timer:null,yieldedControl:!1},H(!1),S},Jt=S=>S!==void 0&&Te.current?.generation!==S?!1:(Rt(),Te.current=null,Ge.current=null,!0),Lt=S=>{let Je=S?.generation??Te.current?.generation??Ze.current;(!S?.generation||Te.current?.generation===Je)&&(Rt(),Te.current=null),Ge.current=Je,S?.showRetry&&H(!0),S?.remount&&wn(),S?.focus!==!1&&ht()},Xt=S=>Te.current?.generation===S&&Ge.current!==S,mn=S=>{typeof document<"u"&&document.visibilityState!=="visible"||(Rt(),S.timer=setTimeout(()=>{Te.current?.generation===S.generation&&(Te.current=null,Ge.current=S.generation,jn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),H(!0),wn(),ht())},600))},ee=()=>{let S=Te.current;S?.yieldedControl&&mn(S)},Vt=()=>{let S=Te.current;S&&(S.yieldedControl=!0,Rt())},Rn=S=>{let Je=Ye.current;return Je&&Ke.current.set(S,Je),S};ut(()=>{let S=()=>{document.visibilityState==="visible"?ee():Vt()};return document.addEventListener("visibilitychange",S),window.addEventListener("focus",ee),window.addEventListener("blur",Vt),()=>{document.removeEventListener("visibilitychange",S),window.removeEventListener("focus",ee),window.removeEventListener("blur",Vt),Rt()}},[]),ut(()=>{De.current!==G&&(De.current=G,I.current=!1,de.current=!1,X(!1),xe(!1),Oe(!1),m.current?.("loading"))},[G]),ut(()=>{dt(()=>Gt.current?.(he&&!Ne))},[he,Ne]);let In=Cs(a);ut(()=>{let S=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",Je=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(A(`mount clientId=${S} env=${a??"(unset)"}\u2192${In??"live"} ccy=${d} sub=${l}`),A(`ua=${Je.slice(0,80)}${Je.length>80?"\u2026":""}`),!r){A("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!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(!$.current){A("FAIL: containerRef not attached");return}me.current=z.startTiming(),z.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let ke=!1,Dn=!1,$e=()=>ke||Dn,Vn,or=!1,Kt=()=>{Vn=vs(),Vn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),or=!0},st=null,Dt=!1,Ht=null,bt=!1,on=()=>{!Ht||bt||(bt=!0,Ht.close().catch(()=>{}))},an=null,yn=()=>{an!==null&&(z.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"overlay_return",durationMs:z.elapsed(an),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),an=null)},sn=!1,It=$.current,Nt=null,Ee=null,tt=[],nt=s=>{if(!s||typeof s.getBoundingClientRect!="function")return"(no rect)";let p=s.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},En=s=>{if(!s)return"(empty)";try{let p=new URL(s,typeof window<"u"?window.location.href:"https://localhost"),se=p.pathname.toLowerCase();return se.includes("checkcaptcha")||se.includes("captcha")?`CAPTCHA(${p.host}${se})`:se.includes("risk")||se.includes("challenge")?`RISK(${p.host}${se})`:se.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${se}`.slice(0,100)}catch{return s.slice(0,80)}},Kn=s=>{let p=s.getAttribute("src"),se=s.getAttribute("srcdoc"),ze=s.getAttribute("name"),j=s.getAttribute("sandbox"),B=[];return p&&B.push(`src=${En(p)}`),se&&B.push(`srcdoc[${se.length}ch]`),!p&&!se&&B.push("src=(empty) srcdoc=(empty)"),ze&&B.push(`name=${ze.slice(0,40)}`),j!==null&&B.push(`sandbox="${j.slice(0,40)}"`),B.join(" ")},Wt=s=>{if(!(s instanceof HTMLIFrameElement))return"";try{let p=s.contentDocument;if(!p)return"cd=null";let se=p.body?.children.length??0,ze=p.body?.innerHTML.length??0,j=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${se}children,${ze}ch] head[${j}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},Ot=[],zt=s=>{if($e())return;let p=s.message??String(s.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(A(`window:error ${p.slice(0,140)}`),Ot.push(p))},_n=s=>{if($e())return;let p=s.reason instanceof Error?s.reason.message:String(s.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(A(`window:rejection ${p.slice(0,140)}`),Ot.push(p))};M&&typeof window<"u"&&(window.addEventListener("error",zt),window.addEventListener("unhandledrejection",_n));let Hn={value:0};if(M&&typeof PerformanceObserver<"u")try{Ee=new PerformanceObserver(s=>{if(!$e())for(let p of s.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;Hn.value+=1;let se=Math.round(p.duration);A(`net ${se}ms ${p.name.slice(0,90)}`)}}),Ee.observe({type:"resource",buffered:!0})}catch{}let Ut=()=>{for(Nt?.disconnect(),Nt=null,Ee?.disconnect(),Ee=null;tt.length;)clearTimeout(tt.pop());M&&typeof window<"u"&&(window.removeEventListener("error",zt),window.removeEventListener("unhandledrejection",_n))},xn=s=>{if(!s)return!1;let p=s.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},Pt=s=>{if($e()||xn(s))return;let p=Ln(s)??s;dt(()=>je.current?.(p))},g=s=>{ke||(Oe(!0),s.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:",s))},D=(s,p=!1)=>{if(ke)return;let se=I.current||!R;if(Dt)return;Dt=!0,Dn=!0,Ut(),on();let ze=p||Qa(s);if(ze&&R&&!I.current){I.current=!0,X(!1),w(!1),xe(!0),m.current?.("retrying"),st=setTimeout(()=>{ke||Ie(j=>j+1)},Ss);return}if(ze||se){if(X(!1),w(!1),xe(!1),Oe(!0),m.current?.("exhausted"),!de.current){de.current=!0;let j=Qa(s)?"paypal_init_timeout":p?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",j)}return}g(s)};Oe(!1);let q=async(s,p=Ye.current)=>{if($e())return;let se=p?.sessionId??e;if(F.current){await F.current(s,{sessionId:se,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let ze=z.startTiming();z.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let j=()=>{z.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"processing",durationMs:z.elapsed(ze),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let B=We.current,K=p?.accountPatch?.email??et.current,vt=p?.accountPatch?.userId??B?.customer?.id??B?.accountData?.userId??"",ie=await new Vo(Q,{telemetry:!1}).processPayment(vt,{sessionId:se,nonce:p?.nonce??gt.current,tokenizedData:s,accountData:{userId:vt,email:K??B?.customer?.email??"",firstName:p?.accountPatch?.firstName??B?.customer?.firstName??B?.accountData?.firstName??"",lastName:p?.accountPatch?.lastName??B?.customer?.lastName??B?.accountData?.lastName??"",country:p?.accountPatch?.country??B?.customer?.country??B?.accountData?.country??void 0,zip:p?.accountPatch?.zip??B?.customer?.zip??B?.accountData?.zip??void 0}});if(ie.ok){if(Dn||ke&&qn.current)return;j(),z.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),dt(()=>Ue.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if($e())return;let pe=await ie.json().catch(()=>null),qe=pe?.message??"PayPal payment failed.",Yt=Ln(qe)??qe;j(),ie.status===400&&(typeof pe?.declineCode=="string"||!Array.isArray(pe?.fields))?z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ie.status===400||ie.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:ie.status>=500?"5xx":ie.status>=400?"4xx":ie.status>=300?"3xx":"unknown",failureCategory:ie.status>=500?"server_error":void 0}),Pt(Yt),dt(()=>it.current?.(St("paypal",Yt,{code:pe?.code,declineCode:pe?.declineCode})));return}catch(B){if($e())return;j(),z.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let K=B instanceof Error?B.message:"PayPal payment failed.",vt=Ln(K)??K;Pt(vt),dt(()=>it.current?.(St("paypal",vt)));return}},ue=()=>new Xa("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),re=s=>$e()?Promise.reject(ue()):Promise.resolve(s),Y=async s=>{if($e())throw ue();or||Kt();let p=Ye.current,se=p?.sessionId??e,ze=p?.nonce??gt.current;z.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let j=await new Vo(Q,{telemetry:!1}).createSessionIntent(se,ze??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Vn});if($e())throw ue();if(j.provider!=="paypal")throw new Error(s);return z.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),j.providerObjectId},v=(s,p)=>{let se=p?.nonce??gt.current;if(!se)return;let ze=p?.sessionId??e,j=yr(s)??Bn(s)??"provider_declined";new Vo(Q,{telemetry:!1}).reportSessionIntentDecline(ze,se,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:j}).catch(()=>{})},_=Z;A("loadScript:scheduled (deferred 1 tick)");let L=null,ge=setTimeout(()=>{if(ke){A("loadScript:skipped (cancelled before defer ran)");return}A("loadScript:start");let s=In==="live"?"production":In;L=Ps({clientId:r,currency:d,intent:l?"subscription":"capture",vault:l?!0:void 0,...s?{environment:s}:{},...s==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),L.then(p=>{if(A(`loadScript:resolved inactive=${$e()} ns=${!!p} buttons=${!!p?.Buttons}`),$e())return;if(!p?.Buttons){A("FAIL: namespace missing Buttons factory"),D("PayPal SDK did not expose the Buttons factory.");return}z.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"provider_ready",durationMs:z.elapsed(me.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let se=async Se=>{if($e()||Me.current!==_)return;let ie=Se.subscriptionID??Se.orderID??"",pe=ie?Ke.current.get(ie):At.current.get(_);if(!(!pe||!Xt(pe.generation))&&Jt(pe.generation)){Ke.current.delete(ie),At.current.delete(pe.surfaceKey),yn();try{if(w(!0),dt(()=>je.current?.(null)),!ie)throw new Xa("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await q({id:ie,isPaypal:!0},pe)}catch(qe){Pt(qe instanceof Error?qe.message:"PayPal capture failed.")}finally{$e()||w(!1)}}},ze=p.Buttons({style:{layout:"horizontal",height:so,tagline:!1},onClick:async(Se,ie)=>{if($e()){await ie.reject();return}Kt();let pe=Ce.current,qe={};if(pe)try{let $t=await pe("paypal");if($e()){await ie.reject();return}if(!$t.proceed){Ye.current=null,At.current.delete(_),await ie.reject();return}qe={sessionId:$t.sessionId,accountPatch:$t.accountPatch,nonce:$t.nonce}}catch($t){A(`onClick:runBeforeButtonClick rejected msg=${($t instanceof Error?$t.message:String($t)).slice(0,120)}`),Ye.current=null,At.current.delete(_),await ie.reject();return}dt(()=>Bt.current?.("paypal"));let ln={generation:Ft(),surfaceKey:_,...qe};Ye.current=ln,At.current.set(_,ln),await ie.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"}),an=z.startTiming()},createOrder:l?void 0:O?()=>re(O).then(Rn):()=>Y("Failed to create PayPal order.").then(Rn),createSubscription:l?O?()=>re(O).then(Rn):()=>Y("Failed to create PayPal subscription.").then(Rn):void 0,onApprove:se,onCancel:()=>{if($e())return;let Se=At.current.get(_)??Ye.current;Se&&At.current.delete(Se.surfaceKey),Ye.current=null,yn(),z.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be.current=!0,Lt({generation:Se?.generation,remount:!0,focus:!1})},onError:Se=>{if($e()||Me.current!==_)return;let ie=Se instanceof Error?Se.message:"PayPal failed to render.";if(A(`onError rendered=${sn} msg=${ie.slice(0,120)}`),sn){let pe=At.current.get(_)??Ye.current;if(pe&&!Xt(pe.generation)||!pe&&Ge.current===Ze.current)return;if(xn(ie)){Jt(pe?.generation);return}if(yn(),Or(Se)){z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),v(Se,pe),dt(()=>it.current?.(St("paypal",ie))),pe&&At.current.delete(pe.surfaceKey),Ye.current=null,Jt(pe?.generation);return}let qe=ie.toLowerCase();z.error({errorCode:qe.includes("popup")&&qe.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),pe&&At.current.delete(pe.surfaceKey),Ye.current=null,Lt({generation:pe?.generation,remount:!0,showRetry:!0,focus:!0}),jn(Se,{code:"paypal_runtime_failed"});return}D(ie)}}),j=ze.isEligible();if(A(`isEligible=${j}`),z.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!j){X(!1),D("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Ht=ze,M&&A(`container:dims ${nt(It)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),M&&typeof MutationObserver<"u"&&(Nt=new MutationObserver(Se=>{if(!$e()){for(let ie of Se)if(ie.type==="childList")ie.addedNodes.forEach(pe=>{if(!(pe instanceof Element))return;let qe=pe.tagName.toLowerCase(),Yt=(pe.getAttribute("title")??"").slice(0,40),ln=qe==="iframe"?` ${Kn(pe)}`:"";A(`child+ ${qe}${Yt?` title="${Yt}"`:""}${ln} dims=${nt(pe)}`)});else if(ie.type==="attributes"&&ie.target instanceof Element){let pe=ie.target;if(pe.tagName.toLowerCase()!=="iframe")continue;let qe=ie.attributeName;(qe==="src"||qe==="srcdoc")&&A(`attr~ iframe ${qe}=${qe==="srcdoc"?`[${(pe.getAttribute("srcdoc")??"").length}ch]`:En(pe.getAttribute("src"))} dims=${nt(pe)}`)}}}),Nt.observe(It,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let K=Se=>{if($e()||sn)return;let ie=It.querySelectorAll("iframe"),pe=typeof document<"u"&&"hasStorageAccess"in document;A(`watchdog:${Se} container=${nt(It)} children=${It.childElementCount} iframes=${ie.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${pe} paypalNetRequests=${Hn.value}`),ie.forEach((qe,Yt)=>{let ln=(qe.getAttribute("title")??"").slice(0,40);A(` iframe[${Yt}] ${nt(qe)}${ln?` title="${ln}"`:""} ${Kn(qe)}`);let $t=Wt(qe);$t&&A(` ${$t}`)}),Ot.length===0&&A(" (no PayPal/zoid window errors captured)")};M&&(tt.push(setTimeout(()=>K("3s"),3e3)),tt.push(setTimeout(()=>K("8s"),8e3)),tt.push(setTimeout(()=>K("15s"),15e3))),A("render:start");let vt=z.startTiming();tt.push(setTimeout(()=>{$e()||sn||(A("watchdog:11s retryable render timeout"),D("PayPal Buttons render did not settle within 11000ms.",!0))},ws)),ze.render(It).then(()=>{if(A(`render:resolved inactive=${$e()}`),Ut(),$e()){on();return}sn=!0,X(!0),xe(!1),m.current?.("ready"),z.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"checkout_render",durationMs:z.elapsed(vt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Se=>{let ie=Se instanceof Error?Se.message:"PayPal failed to render.";A(`render:rejected msg=${ie.slice(0,120)}`),Ut(),D(ie)})}).catch(p=>{let se=p instanceof Error?p.message:"PayPal SDK failed to load.";A(`loadScript:rejected msg=${se.slice(0,120)}`),D(se)})},0);return()=>{ke=!0,clearTimeout(ge),st&&clearTimeout(st),Ut(),on()}},[R,Q,r,d,a,l,e,O,Z,z]);let Zt=M?Ko("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=${he} failed=${Ne})`,Ve.length===0?`
7
7
  (waiting for first lifecycle event\u2026)`:`
8
- ${Qe.join(`
9
- `)}`]}):null;return Ne&&!it?A?yr("div",{children:Ft}):null:Ko("div",{children:[Ft,Ko("div",{"aria-hidden":ge?!0:void 0,style:ge?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:io},children:[!Pe&&!ge&&yr("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"}}),yr("div",{ref:j,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:io,display:"flex",opacity:Pe?1:0},"aria-busy":G||E},ie)]},ie),Re&&yr("button",{ref:Be,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:_n,style:ws,children:"Try PayPal again"})]})}function so(e){return yr(Za,{...e})}function Qa(e){return yr(Za,{...e})}import{FloPayError as wn,isSetupIntentClientSecret as Us,resolveTheme as $s}from"@flopay/shared";import{Fragment as fr,jsx as d,jsxs as Me}from"react/jsx-runtime";var kn="flopay_stripe_resume",oi="flopay_wallet_resume",zr="flopay_paypal_resume";function Zo(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 zn(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function qs(e){return e instanceof wn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ho(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),r=Math.max(0,Math.min(1,1-t)),a=Math.round((i>>16&255)*r),c=Math.round((i>>8&255)*r),s=Math.round((i&255)*r);return`#${(1<<24|a<<16|c<<8|s).toString(16).slice(1)}`}var js=`
8
+ ${Ve.join(`
9
+ `)}`]}):null;return Ne&&!mt?M?fr("div",{children:Zt}):null:Ko("div",{children:[Zt,Ko("div",{"aria-hidden":Pe?!0:void 0,style:Pe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:so},children:[!he&&!Pe&&fr("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"}}),fr("div",{ref:$,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:so,display:"flex",opacity:he?1:0},"aria-busy":ye||E},Z)]},Z),Re&&fr("button",{ref:_e,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:kn,style:Rs,children:"Try PayPal again"})]})}function lo(e){return fr(ei,{...e})}function ti(e){return fr(ei,{...e})}import{FloPayError as bn,isSetupIntentClientSecret as qs,resolveTheme as js}from"@flopay/shared";import{Fragment as gr,jsx as u,jsxs as Ae}from"react/jsx-runtime";var vn="flopay_stripe_resume",ii="flopay_wallet_resume",Ur="flopay_paypal_resume",Vs=250;function Qo(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function po({billingApiUrl:e,sessionId:t,nonce:n,request:i}){if(!(!t||!n))try{await new On(e,{telemetry:!1}).reportSessionIntentDecline(t,n,i)}catch{}}function Ks(e){return e instanceof bn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Wo(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function co(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let i=parseInt(n[1],16),r=Math.max(0,Math.min(1,1-t)),a=Math.round((i>>16&255)*r),d=Math.round((i>>8&255)*r),l=Math.round((i&255)*r);return`#${(1<<24|a<<16|d<<8|l).toString(16).slice(1)}`}var Hs=`
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 @@ ${Qe.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
- `,co=44;function Qo(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 Ks={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},mi={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 Vs(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ai(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function yi(e){return e==="paypal"?"PayPal":gr(e)}function Hs(e,t){let n=`We couldn't open ${yi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function fi(e){let t=Le(0),n=Le(null),i=Le(null),r=Se((l=i.current)=>{let y=l;y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),a=Se((l,y)=>{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"}))},y))},[r,e]),c=Se(l=>{l.yieldedControl&&a(l,600)},[a]),s=Se(l=>{r();let y=t.current+1;t.current=y,n.current=null;let S={generation:y,method:l,timer:null,yieldedControl:!1};return i.current=S,y},[r]),C=Se(l=>{let y=i.current;return typeof l=="number"&&y?.generation!==l?!1:(r(y),i.current=null,(typeof l!="number"||n.current===l)&&(n.current=null),!0)},[r]),B=Se(l=>{let y=i.current,S=l??y?.generation??t.current;(!l||y?.generation===l)&&(r(y),i.current=null),n.current=S},[r]),m=Se(l=>n.current===(l??t.current),[]),k=Se(l=>i.current?.generation===l&&n.current!==l,[]),v=Se(()=>{let l=i.current;l&&c(l)},[c]),E=Se(()=>{let l=i.current;l&&(l.yieldedControl=!0,r(l))},[r]);return ft(()=>{let l=()=>{document.visibilityState==="visible"?v():E()},y=()=>{E()};return document.addEventListener("visibilitychange",l),window.addEventListener("blur",y),window.addEventListener("focus",v),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("blur",y),window.removeEventListener("focus",v),r()}},[r,E,v]),{startAttempt:s,finishAttempt:C,invalidateAttempt:B,isAttemptInvalidated:m,isAttemptCurrent:k}}function Ws(e){let t=Bs(e);return`Enter a valid ${Yo(e)}${t?` (e.g. ${t})`:""}`}function Ys(e,t,n){let i=Ts(e),r=t.trim(),a=n&&i,c=a&&!r,s=a&&!!r&&!Ms(e,r);return{visible:n,supported:i,required:a,empty:c,malformed:s}}function ii(e,t){return t instanceof wn?t:new wn(t instanceof Error?t.message:`${Vs(e)} before-click hook failed.`,"validation_error")}function Wo(){return d("style",{children:js})}function Gs(e){return typeof e=="number"?`${e}px`:e}function si(e){if(typeof e=="number"||typeof e=="string")return e}function gi(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function hi({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 li(e){return e!=="unavailable"&&e!=="load_error"}function ea(e){return d(Xs,{...e})}function ci({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:r,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:C,onTechnicalFailure:B,runBeforeButtonClick:m,onLoadStateChange:k,placeholderBorderRadius:v}){let E=vn(),l=Xo(),y=Jo(),[S,T]=ve("loading");ft(()=>{k?.(S)},[S,k]);let[f,$]=ve(!1),Y=Le(!1),ye=Le(null),ee=Le(null),[A,J]=ve(0),[q,fe]=ve(!1),D=Le(!1),j=Le(new Map),{startAttempt:ae,finishAttempt:Be,invalidateAttempt:be,isAttemptInvalidated:Pe,isAttemptCurrent:X}=fi((w,re,ce)=>{B?.(w,re,{...ce,popupBlocked:ce?.popupBlocked??On(re)}),fe(!0),J(Ne=>Ne+1)});ft(()=>{q&&ee.current?.focus()},[q,A]);let ge=Se(()=>{J(w=>w+1)},[]),we=Se((w,re,ce)=>{be(ce),B?.("paypal",w,{code:re,popupBlocked:On(w)}),fe(!0),ge()},[be,B,ge]),ie=Se(()=>{window.setTimeout(()=>{(ye.current?.querySelector("iframe")??ye.current)?.focus()},0)},[]);ft(()=>{D.current&&(D.current=!1,ie())},[ie,A]);let Fe=Se(()=>{fe(!1),a?.(null),ie()},[ie,a]);ft(()=>{if(!l||Y.current)return;let w=new URLSearchParams(window.location.search),re=w.get("payment_intent"),ce=w.get("payment_intent_client_secret"),Ne=w.get("redirect_status");if(!re||!ce)return;Y.current=!0;let De;try{let x=localStorage.getItem(zr);if(x){let K=JSON.parse(x);K.clientSecret===ce&&(De={...K.accountPatch?{accountPatch:K.accountPatch}:{},...K.sessionId?{sessionId:K.sessionId}:{},...K.nonce?{nonce:K.nonce}:{}})}}catch{}try{localStorage.removeItem(zr)}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($(!0),Ne==="failed"){let de="PayPal payment was declined. Please try again.";a?.(de),C?.(wt("paypal",de));return}let{paymentIntent:x,error:K}=await l.retrievePaymentIntent(ce);if(K){a?.(K.message??"Failed to retrieve PayPal payment status.");return}if(x&&(x.status==="requires_capture"||x.status==="succeeded")){let de=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id;r({id:de??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0},De)}else{let de="PayPal payment was not completed. Please try again.";a?.(de),C?.(wt("paypal",de))}}catch(x){a?.(x instanceof Error?x.message:"Failed to complete PayPal payment.")}finally{$(!1)}})()},[l,r,a,C]);let _e=Se(async w=>{if(c||f){w.reject();return}let re=m?await m("paypal"):{proceed:!0};if(!re.proceed){j.current.delete(A),w.reject();return}let ce=ae("paypal");j.current.set(A,{generation:ce,accountPatch:re.accountPatch,sessionId:re.sessionId,nonce:re.nonce}),fe(!1),s?.("paypal"),w.resolve()},[j,c,s,m,ae,f,A]),Re=Se(async w=>{if(!l||!y)return;let re=j.current.get(A);if(re&&!X(re.generation)){j.current.delete(A);return}if(!re&&Pe()||re&&!Be(re.generation))return;re||Be();let ce=re??null;if(j.current.delete(A),!ce&&m){let x=await m("paypal");if(!x.proceed){w.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ce={accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}}let Ne=ce?.sessionId??e,De=ce?.nonce??t,G=ce?.accountPatch?.email??n;try{if($(!0),a?.(null),!Ne||!G)throw new Error("Missing sessionId or email for PayPal payment");let x=l.createPaymentMethod,{error:K,paymentMethod:de}=await x({type:"paypal"});if(K){we(K,"stripe_paypal_create_payment_method_failed",re?.generation),w.paymentFailed({reason:"fail"});return}let xe=await new zn(i).createSessionIntent(Ne,De??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:de?.id??null,intentKind:"payment"});if(xe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let it=xe.clientSecret,Qe={return_url:window.location.href};if(de?.id&&(Qe.payment_method=de.id),typeof window<"u")try{localStorage.setItem(zr,JSON.stringify({clientSecret:it,sessionId:Ne,nonce:De,accountPatch:ce?.accountPatch}))}catch{}let{error:Ze,paymentIntent:p}=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 Oe=Ze.message??"Your payment was declined.";a?.(Oe),C?.(wt("paypal",Oe,{code:Bn(Ze),declineCode:mr(Ze)})),await uo({billingApiUrl:i,sessionId:Ne,nonce:De,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Bn(Ze)??"provider_declined"}})}else we(Ze,"stripe_paypal_confirm_failed",re?.generation);return}if(typeof window<"u")try{localStorage.removeItem(zr)}catch{}let ze=typeof p?.payment_method=="string"?p.payment_method:p?.payment_method?.id;r({id:ze??p?.id,type:"card",threeDSecureActionResultTokenId:p?.id,isPaypal:!0},{accountPatch:ce?.accountPatch,sessionId:Ne,nonce:De});return}catch(x){we(x,"stripe_paypal_failed",re?.generation)}finally{$(!1)}},[l,y,e,t,n,i,r,a,C,m,we,Be,X,Pe,A]);return Me(fr,{children:[d(hi,{state:S,placeholderTestId:"flopay-paypal-placeholder",borderRadius:v,children:Me("div",{ref:ye,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[q&&d("button",{ref:ee,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Fe,style:mi,children:"Try PayPal again"}),d(pi,{onReady:w=>T(gi(w,["paypal"])),onLoadError:()=>{T("load_error"),Zo(Bt(E),"paypal","paypal")},onClick:_e,onConfirm:Re,onCancel:()=>{let w=j.current.get(A);j.current.delete(A),Bt(E)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be(w?.generation),fe(!1),D.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},A)]})}),f&&d(Sn,{status:"processing"})]})}function di({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:C,onDecline:B,onTechnicalFailure:m,runBeforeButtonClick:k,onLoadStateChange:v,placeholderBorderRadius:E}){let l=vn(),y=Xo(),S=Jo(),[T,f]=ve("loading");ft(()=>{v?.(T)},[T,v]);let[$,Y]=ve(!1),ye=Le(null),ee=Le(null),[A,J]=ve(0),[q,fe]=ve(!1),[D,j]=ve("google_pay"),ae=Le(!1),Be=Le("google_pay"),be=Le("google_pay"),Pe=Le(new Map),{startAttempt:X,finishAttempt:ge,invalidateAttempt:we,isAttemptInvalidated:ie,isAttemptCurrent:Fe}=fi((G,x,K)=>{m?.(G,x,{...K,popupBlocked:K?.popupBlocked??On(x)}),j(G),fe(!0),J(de=>de+1)});ft(()=>{q&&ee.current?.focus()},[q,A]);let _e=Se(()=>{J(G=>G+1)},[]),Re=Se((G,x,K,de)=>{we(de),m?.(G,x,{code:K,popupBlocked:On(x)}),j(G),fe(!0),_e()},[we,m,_e]),w=Se(()=>{window.setTimeout(()=>{(ye.current?.querySelector("iframe")??ye.current)?.focus()},0)},[]);ft(()=>{ae.current&&(ae.current=!1,w())},[w,A]);let re=Se(()=>{fe(!1),s?.(null),w()},[w,s]),ce=Se(async G=>{if(!y||!S)return;let x=Pe.current.get(A);if(x&&!Fe(x.generation)){Pe.current.delete(A);return}if(!x&&ie()||x&&!ge(x.generation))return;x||ge();let K=G.expressPaymentType??x?.method??Be.current,de=x??null;Pe.current.delete(A);let xe=ai(K);if(!de&&k){let ze=await k(xe);if(!ze.proceed){G.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}de={accountPatch:ze.accountPatch,sessionId:ze.sessionId,nonce:ze.nonce}}let it=xe,Qe=de?.sessionId??e,Ze=de?.nonce??t,p=de?.accountPatch?.email??n;try{Y(!0),s?.(null);let{error:ze}=await S.submit();if(ze){Re(K,ze,"stripe_wallet_submit_failed",x?.generation);return}let{error:Oe,paymentMethod:Ve}=await y.createPaymentMethod({elements:S});if(Oe||!Ve){Re(K,Oe??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",x?.generation);return}if(!Qe||!p)throw new Error("Missing sessionId or email for wallet payment");let Ue=await new zn(i).createSessionIntent(Qe,Ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:K??xe,paymentMethodId:Ve.id,intentKind:r});if(Ue.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Yt=Ue.clientSecret,{error:bt,intentId:It}=Us(Yt)?await y.confirmCardSetup(Yt,{payment_method:Ve.id}).then(g=>({error:g.error,intentId:g.setupIntent?.id})):await y.confirmCardPayment(Yt,{payment_method:Ve.id}).then(g=>({error:g.error,intentId:g.paymentIntent?.id}));if(bt){if(Nr(bt)){let g=bt.message??"Your payment was declined.";s?.(g),B?.(wt(it,g,{code:Bn(bt),declineCode:mr(bt)})),await uo({billingApiUrl:i,sessionId:Qe,nonce:Ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:K??xe,providerDeclineReason:Bn(bt)??"provider_declined"}})}else Re(K,bt,"stripe_wallet_confirm_failed",x?.generation);return}c({id:Ve.id,type:"card",threeDSecureActionResultTokenId:It},{accountPatch:de?.accountPatch,sessionId:Qe,nonce:Ze})}catch(ze){Re(K,ze,"stripe_wallet_failed",x?.generation)}finally{Y(!1)}},[y,S,e,t,n,i,r,c,s,B,k,Re,ge,Fe,ie,A]),Ne=ot(()=>{let G=["applePay","googlePay","paypal","link","amazonPay","klarna"],x=new Set(["applePay","googlePay"]),K=new Set(a.map(ri)),de={};for(let xe of G)K.has(xe)?de[xe]=x.has(xe)?"always":"auto":de[xe]="never";return de},[a]),De=ot(()=>a.map(ri),[a]);return Me(fr,{children:[d(hi,{state:T,placeholderTestId:"flopay-wallet-placeholder",borderRadius:E,children:Me("div",{ref:ye,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[q&&Me("button",{ref:ee,type:"button","data-testid":"flopay-wallet-retry-button",onClick:re,style:mi,children:["Try ",yi(D)," again"]}),d(pi,{onReady:G=>{f(gi(G,De))},onLoadError:G=>{f("load_error"),Zo(Bt(l),"stripe","wallet")},onClick:async G=>{Be.current=G.expressPaymentType,be.current=ai(G.expressPaymentType);let x=k?await k(be.current):{proceed:!0};if(!x.proceed){Pe.current.delete(A),G.reject();return}let K=X(G.expressPaymentType);Pe.current.set(A,{generation:K,method:G.expressPaymentType,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),fe(!1),C?.(be.current),G.resolve()},onConfirm:ce,onCancel:()=>{let G=Pe.current.get(A);Pe.current.delete(A),Bt(l)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),we(G?.generation),fe(!1),ae.current=!0,_e()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ne,layout:{maxColumns:1,overflow:"never"}}},A)]})}),$&&d(Sn,{status:"processing"})]})}function Js({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:r=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:C,textColor:B,borderRadius:m,fontFamily:k}){let v=Ds(e,t),E=ja[e],l=v?.backgroundColor??s??"#ffffff",y=v?.borderColor??C??"#d1d5db",S=v?.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:co,padding:"0 1rem",backgroundColor:l,color:S,border:`1px solid ${y}`,borderRadius:m??8,fontSize:"0.95rem",fontWeight:600,fontFamily:k,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 ${gr(e)}\u2026`}):Me(fr,{children:[Me("span",{style:{display:"inline-flex",alignItems:"center",gap:Fs(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"}}):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:gr(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 Go({method:e,sessionId:t,nonce:n,email:i,billingName:r,billingApiUrl:a,onTokenizedBody:c,onErrorChange:s,onDecline:C,onCancel:B,runBeforeButtonClick:m,onButtonClick:k,isProcessing:v,submitButtonColor:E,submitButtonBorderRadius:l,submitButtonStyle:y,errorText:S}){let T=vn(),f=Xo(),$=Jo(),[Y,ye]=ve(!1),ee=Le(!1),[A,J]=ve(!1),[q,fe]=ve("loading"),D=Se(async()=>{if(!f||!$||v||ee.current||!A)return;ee.current=!0,ye(!0);let j=m?await m("card"):{proceed:!0};if(!j.proceed){ee.current=!1,ye(!1);return}k?.("card");let ae=j.sessionId??t,Be=j.nonce??n,be=j.accountPatch?.email??i;try{s?.(null);let Pe=await $.submit();if(Pe.error){s?.(Pe.error.message??"Payment failed.");return}let X=await f.createPaymentMethod({elements:$});if(X.error||!X.paymentMethod){s?.(X.error?.message??"Failed to create payment method.");return}let ge=X.paymentMethod;if(!ae||!be)throw new Error("Missing sessionId or email for payment.");let we=ge.type||e,ie=await new zn(a).createSessionIntent(ae,Be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:we,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(kn,JSON.stringify({clientSecret:Fe,sessionId:ae,nonce:Be,accountPatch:j.accountPatch,paymentMethodId:ge.id,paymentMethodType:ge.type??e,gateway:"stripe"}))}catch{}let{error:_e,paymentIntent:Re}=await f.confirmPayment({clientSecret:Fe,confirmParams:{return_url:window.location.href,payment_method:ge.id},redirect:"if_required"});if(_e){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ce=_e.message??"Payment failed.";s?.(ce),C?.(wt("card",ce,{code:_e.code})),await uo({billingApiUrl:a,sessionId:ae,nonce:Be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:_e.code??"provider_declined"}});return}let w=Re?.status;if(!no(w)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let ce=w==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";s?.(ce),C?.(wt("card",ce,{code:w??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let re=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;c({id:re??ge.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:ge.type??e},{accountPatch:j.accountPatch,sessionId:ae,nonce:Be})}catch(Pe){s?.(Pe instanceof Error?Pe.message:"Payment failed. Please try again.")}finally{ee.current=!1,ye(!1)}},[f,$,v,A,m,k,t,n,i,a,e,c,s,C]);return Me("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(Rs,{onReady:()=>fe("ready"),onLoadError:()=>{fe("load_error"),Zo(Bt(T),"stripe","apm")},onChange:j=>{J(!!j.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:()=>{D()},disabled:!A||Y||v||q!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:E,color:"white",border:"none",borderRadius:l,fontSize:"1rem",fontWeight:600,cursor:!A||Y||v||q!=="ready"?"not-allowed":"pointer",opacity:!A||Y||v||q!=="ready"?.5:1,transition:"opacity 120ms ease-out",...y??{}},children:Y?"Processing\u2026":`Pay with ${gr(e)}`}),S&&d(dr,{margin:"0.75rem 0 0",children:S})]})}function ui({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:a,stripeInstance:c,paymentElementBaseOptions:s,onTokenizedBody:C,onErrorChange:B,onButtonClick:m,onDecline:k,runBeforeButtonClick:v,onLoadStateChange:E,isProcessing:l=!1,submitButtonColor:y="#4A49FF",submitButtonBorderRadius:S=8,submitButtonStyle:T,buttonAppearance:f,themeId:$,onExpandApm:Y,expandedApmMethod:ye}){let[ee,A]=ve(null),[J,q]=ve(null),fe=Le(!1);ft(()=>{a.length>0&&c?E?.("ready"):c||E?.("loading")},[a.length,c,E]);let D=Se(async X=>{if(!c||fe.current||l)return;fe.current=!0,q(X);let ge=v?await v("card"):{proceed:!0};if(!ge.proceed){fe.current=!1,q(null);return}m?.("card");let we=ge.sessionId??e,ie=ge.nonce??t,Fe=ge.accountPatch?.email??n;try{if(B?.(null),!we||!Fe)throw new Error("Missing sessionId or email for payment.");let _e=await new zn(r).createSessionIntent(we,ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=_e.clientSecret;if(typeof window<"u")try{localStorage.setItem(kn,JSON.stringify({clientSecret:Re,sessionId:we,nonce:ie,accountPatch:ge.accountPatch,paymentMethodType:X,gateway:"stripe"}))}catch{}let{error:w,paymentIntent:re}=await c.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:X,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...Fe?{email:Fe}:{}}}},redirect:"if_required"});if(w){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let De=w.message??"Payment failed.";B?.(De),k?.(wt("card",De,{code:w.code})),await uo({billingApiUrl:r,sessionId:we,nonce:ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:w.code??"provider_declined"}});return}let ce=re?.status;if(!no(ce)){if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let De=ce==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";B?.(De),k?.(wt("card",De,{code:ce??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(kn)}catch{}let Ne=typeof re?.payment_method=="string"?re.payment_method:re?.payment_method?.id;C({id:Ne??re?.id,type:"card",threeDSecureActionResultTokenId:re?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:ge.accountPatch,sessionId:we,nonce:ie})}catch(_e){B?.(_e instanceof Error?_e.message:"Payment failed. Please try again.")}finally{fe.current=!1,q(null)}},[c,l,v,m,e,t,n,r,i,C,B,k]),[j,ae]=ve(null),Be=Y?ye??null:j,be=Se(X=>{fe.current||l||Be&&Be!==X||(ni(X)?Y?Y(X):ae(X):D(X))},[Be,l,D,Y]),Pe=ot(()=>j?{...s,paymentMethodTypes:[j]}:null,[j,s]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(X=>{let ge=ye===X,we=J===X,ie=J!==null&&J!==X||ye!=null&&ye!==X;return Me(Os.Fragment,{children:[d(Js,{method:X,themeId:$,submitting:we,disabled:ie,highlighted:ge,hasNextStep:ni(X),onClick:()=>be(X),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!Y&&j===X&&Pe&&c&&d(er,{stripe:c,options:Pe,children:d(Go,{method:X,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:C,onErrorChange:B,onDecline:k,onCancel:()=>ae(null),runBeforeButtonClick:v,onButtonClick:m,isProcessing:l,submitButtonColor:y,submitButtonBorderRadius:S,submitButtonStyle:T})},X)]},X)})})}function Xs({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:a,onError:c,onDecline:s,onTokenizedBody:C,firstName:B,lastName:m,chv:k,className:v,isProcessing:E,error:l,onErrorChange:y,showPayPal:S=!0,showStripe:T=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:$,showApplePay:Y=!0,showGooglePay:ye=!0,layout:ee="default",theme:A,buttonsTheme:J,buttonsStyles:q,appearance:fe,cardButtonContent:D,cardBackButtonContent:j,cardTitleContent:ae,showSecurityFooter:Be,onButtonClick:be,onBeforeButtonClick:Pe,enableAVS:X,cardFieldOrder:ge,cardPreFormSlot:we,avsLayout:ie="row",country:Fe,zip:_e,addressLine1:Re,addressLine2:w,city:re,state:ce,onCountryChange:Ne,onZipChange:De,avsCheck:G,checkoutType:x,checkoutLayout:K,totalAmount:de=0,currency:xe="usd",initialCardOpen:it=!1,directPaypal:Qe,isSubscription:Ze=!1,session:p,debug:ze=!1}){let Oe=vn(),Ve=Oo(),Ue=zs(un),Yt=to(),[bt,It]=ve(!1),[g,Ie]=ve(null),[$e,st]=ve(Fe??"US"),[rt,et]=ve(_e??""),[Ge,ke]=ve(Re??""),[vt,qe]=ve(w??""),[zt,Et]=ve(re??""),[mn,En]=ve(ce??""),[_n,jn]=ve({}),Pt=Le(_e??""),Ut=Le(Fe??"US"),Dt=Le(Re??""),Gt=Le(w??""),on=Le(re??""),yn=Le(ce??""),V=ot(()=>xs(X),[X]),Dn=V!==null,fn=!!p?.vault?.html,$t=!!p?.gateways?.pcivault,_=!!(p?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),Je=fn||_||$t,Ee=!!(T&&Je&&Oe&&e),[Ln,je]=ve(()=>ee!=="buttons"||it?e??null:null),[Kn,gn]=ve(0),hn=ee!=="buttons"||it||!!e&&Ln===e,tt=ot(()=>!Oe||!Ee||!e||!hn?null:Oe.cardCapture({sessionId:e}),[Oe,Ee,e,hn]),_t=ot(()=>{let o=$e,b=V?Te(V.postal_code,o):!1;return Ys(o,rt,b)},[V,$e,rt]),{avsInvalid:qt,invalidAvsFields:Lt}=ot(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!Ee||!V)return{avsInvalid:!1,invalidAvsFields:o};let b=$e,U=(te,Xe)=>Te(te,b)&&!Xe.trim(),oe={line1:U(V.address_line_1,Ge),city:U(V.city,zt),state:U(V.state,mn),zip:_t.empty||_t.malformed};return{avsInvalid:oe.line1||oe.city||oe.state||oe.zip,invalidAvsFields:oe}},[Ee,V,$e,Ge,zt,mn,_t]),[Jt,an]=ve(!1),[xn,Vt]=ve(!1),[Nt,Xt]=ve(()=>Ho(p?.vault)),[Ce,gt]=ve(it&&Je?"card":"buttons"),[lt,Pn]=ve(null),Vn=Ce==="expanding"||Ce==="card",Ot=280,Ht=Le(null),Ct=Se(o=>{Ht.current&&clearTimeout(Ht.current),Ht.current=setTimeout(()=>{Ht.current=null,o()},Ot)},[Ot]);ft(()=>()=>{Ht.current&&clearTimeout(Ht.current)},[]);let rr=Se(()=>{je(e??null),gn(o=>o+1),gt("expanding"),Ct(()=>gt("card"))},[Ct,e]),Wt=Se(()=>{gt("collapsing"),Ct(()=>gt("buttons"))},[Ct]),R=Se(o=>{Pn(o),gt("apm-expanding"),Ct(()=>gt("apm-form"))},[Ct]),O=Se(()=>{gt("apm-collapsing"),Ct(()=>{gt("buttons"),Pn(null)})},[Ct]);ft(()=>{ee==="buttons"&&it&&Je&&(je(e??null),gt("card"))},[ee,it,Je,e]);let[W,Q]=ve(null),se=Le(!1),[N,P]=ve(null),Z=Le(N);ft(()=>{Z.current=N},[N]);let F=n||Yt,le=l??g,he=ot(()=>$s(A),[A]),I=ot(()=>{let o=he?.buttonsLayout??Is(J);return q?{...o,...q,cardButton:{...o.cardButton,...q.cardButton},cardFormContainer:{...o.cardFormContainer,...q.cardFormContainer},backButton:{...o.backButton,...q.backButton},backButtonIcon:{...o.backButtonIcon,...q.backButtonIcon},submitButton:{...o.submitButton,...q.submitButton},title:{...o.title,...q.title}}:o},[he,J,q]),ct=fe??he?.appearance,M=ot(()=>{let o=ct?.variables,b=Xe=>typeof Xe=="string"&&Xe?Xe:void 0,U=I.submitButton,oe=b(o?.colorPrimary)??b(U?.backgroundColor)??"#4A49FF",L=ee==="buttons",te=I.nameInput;return{primaryColor:oe,primaryHoverColor:b(o?.colorPrimaryHover)??lo(oe,.12),inputBackgroundColor:b(I.cardInputBackground)??b(o?.colorBackground)??"#ffffff",textColor:b(I.cardInputColor)??b(te?.color)??b(o?.colorText)??"#262833",borderColor:b(I.cardInputBorder)??(L?"#e5e7eb":"#A4A4FF"),placeholderColor:b(I.cardInputPlaceholderColor)??"#9ca3af",errorColor:b(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:b(te?.fontFamily)??b(o?.fontFamily)??"Poppins, sans-serif",fontSize:b(I.cardInputFontSize)??b(o?.fontSizeBase)??"16px",fontWeight:String(si(te?.fontWeight)??400),borderRadius:b(o?.borderRadius)??"8px"}},[ct,I,ee]),u=Ue.inlineSessionPatchProcessing??!1,h=(E??bt)||u,pe=F.replace(/\/+$/,""),H=ot(()=>$o({userId:r,email:i,firstName:B,lastName:m,country:Fe,zip:_e},_n),[r,i,B,m,Fe,_e,_n]),Ke=[H.firstName,H.lastName].filter(o=>!!o?.trim()).join(" "),dt=ot(()=>Oe?Oe.getRawProvider():null,[Oe]),jt=ot(()=>Ve?Ve.getRawProvider():null,[Ve]),He=de||100,ue=ot(()=>ct?Ns(ct):null,[ct]),me=ue?{appearance:ue}:null,We=ot(()=>{let o=ue??{},b=o.rules??{};return{...o,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[ue]),sn=ot(()=>{let o=Wa(de);return{...o,currency:xe.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...me}},[de,xe,me]),ln=ot(()=>({mode:"payment",amount:He,currency:xe.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...me}),[He,xe,me]),z=Se(o=>{Ie(o),y?.(o)},[y]);ft(()=>{!Ee||!tt||tt.setCardFieldOrder?.(ge??null,V==null)},[Ee,tt,ge,V]),ft(()=>{(Ce==="expanding"||Ce==="collapsing"||Ce==="apm-expanding"||Ce==="apm-collapsing")&&z(null)},[Ce,z]);let cn=Se((o,b,U)=>{s?.(wt(o,b,U))},[s]),or=Se((o,b,U)=>{let oe=U?.popupBlocked??On(b),L=Hs(o,oe),te=Zn(U?.code)??Bn(b)??"external_payment_method_failed",Xe=new wn(L,"api_error",{code:"external_payment_method_failed",param:o});Q(null),ee==="buttons"&&(gt("buttons"),Pn(null)),z(L),c?.(Xe),console.error("[FloPay] External payment method failed:",{method:o,code:te,popupBlocked:oe})},[ee,c,z]);ft(()=>{if(!Ee||!e){Xt(null);return}let o=Ho(p?.vault);if(o){Xt(o);return}if(!hn){Xt(null);return}Xt(null);let b=!0;return new zn(pe).getVaultCapture(e,t).then(U=>{if(!b)return;let oe=Ho(U);oe?Xt(oe):z("Failed to load the secure card form.")}).catch(U=>{b&&z(U instanceof Error?U.message:"Failed to load the secure card form.")}),()=>{b=!1}},[Ee,hn,Kn,e,p?.vault?.html,p?.vault?.messageToken,p?.vault?.expectedOrigin,pe,t,z]);let Hn=Le({onComplete:a,onError:c,updateError:z,emitDecline:cn,resolvedAccount:H,avsConfig:V,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:pe});Hn.current={onComplete:a,onError:c,updateError:z,emitDecline:cn,resolvedAccount:H,avsConfig:V,avsCheckProp:G,sessionId:e,nonce:t,baseUrl:pe};let So=Le(!1),Di=Se(()=>{let{resolvedAccount:o,avsConfig:b,avsCheckProp:U}=Hn.current,oe=Ut.current||o.country||"US",L=b?Te(b.state,oe):!1,te=b?Te(b.address_line_1,oe):!1,Xe=b?Te(b.postal_code,oe):!1,St=b?Te(b.city,oe):!1,xt=b?Te(b.address_line_2,oe):!1,nt=te&&!L&&Xe?ti(oe,(Pt.current??"").trim()):null,Tt=L?yn.current:nt;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...Xe&&Pt.current?{zip:Pt.current}:{},...St&&on.current?{city:on.current}:{},...Tt?{state:Tt}:{},...te&&Dt.current?{addressLine1:Dt.current}:{},...xt&&Gt.current?{addressLine2:Gt.current}:{},country:oe},...U!==void 0?{avsCheck:U}:{},...b?{avsConfig:{country:Te(b.country,oe),postal_code:Xe,address_line_1:te,address_line_2:xt,city:St,state:L}}:{}}},[]);ft(()=>{!Ee||!tt||tt.setSubmitGate?.(qt)},[Ee,tt,qt]),ft(()=>{if(!Ee||!tt)return;So.current=!1;let o=!1,b=tt.on("submitting",()=>{an(!0),Q("processing");let{baseUrl:te,sessionId:Xe,nonce:St,updateError:xt,onError:nt}=Hn.current;!Xe||!St||new zn(te).patchAccountSnapshot(Xe,St,Di(),{telemetryMode:"best_effort"}).catch(Tt=>{if(!qs(Tt))return;let Ae=Tt instanceof Error?Tt.message:"Please check your billing address and try again.";xt(Ae),Q(null),nt?.(Tt instanceof wn?Tt:new wn(Ae,"api_error"))})}),U=tt.on("complete",async te=>{pr(te.sessionId??Hn.current.sessionId),Q("success"),await new Promise(Xe=>setTimeout(Xe,Mn)),!So.current&&(So.current=!0,Hn.current.onComplete?.({status:"succeeded",paymentIntentId:te.intentId,checkoutMethod:"card"}))}),oe=tt.on("decline",async te=>{let{updateError:Xe,emitDecline:St}=Hn.current,xt=te.message??"Your payment was declined. Please try another card or contact your bank.";Xe(xt),Q("error"),St("card",xt,te.declineReason?{declineCode:te.declineReason}:void 0),await new Promise(nt=>setTimeout(nt,Cn)),!o&&Q(null)}),L=tt.on("error",async te=>{let{updateError:Xe,onError:St}=Hn.current,xt=te.message??"There was a problem processing your payment. Please try again.";Xe(xt),Q("error"),St?.(new wn(xt,"api_error")),await new Promise(nt=>setTimeout(nt,Cn)),!o&&Q(null)});return()=>{o=!0,b(),U(),oe(),L()}},[Ee,tt]);let bn=!!Qe?.clientId,wr=Array.isArray(f),jr=wr&&f.length>0,Li=wr&&f.includes("paypal"),{expressMethods:Kr,paymentElementMethods:kr}=ot(()=>Ls(f,{excludePaypal:bn}),[f,bn]),ma=bn||!!Ve,Ni=ot(()=>ma?Kr.filter(o=>o!=="paypal"):Kr,[Kr,ma]),Oi=ot(()=>{let o=[];return Y&&o.push("apple_pay"),ye&&o.push("google_pay"),o},[Y,ye]),Vr=wr?Ni:Oi,zi=T&&Vr.length>0,wo=Dn?$e:Fe,Hr=ot(()=>{let o=wo?.trim().toUpperCase();return o?$?kr.filter(b=>{let U=$[b];return!U||U.length===0||U.includes(o)}):As(kr,wo):kr},[kr,wo,$]),ko=ot(()=>({mode:"payment",amount:He,currency:xe.toLowerCase(),paymentMethodCreation:"manual",appearance:We}),[He,xe,We]),[ya,fa]=ve("loading"),[ga,ha]=ve("loading"),[Pa,ba]=ve("loading"),[Ui,Ro]=ve(!1),[va,Io]=ve("loading"),[Wr,$i]=ve();ft(()=>{$i(Ya())},[]);let Ca=S&&(bn||(wr?Li:Wr===!1)),Sa=T&&zi,Rr=Ca&&bn,wa=va==="retrying"||va==="exhausted",Ir=Ca&&!!jt&&(!bn||wa),Er=Sa&&!!dt,_r=T&&jr&&Hr.length>0&&!!dt,qi=Rr&&!wa?Ui:Ir&&li(ya),ji=Er&&li(ga),Ki=_r&&Pa!=="load_error",ka=o=>o==="loading"||o==="ready",Ra=Rr||Ir&&ka(ya)||Er&&ka(ga)||_r&&Pa!=="load_error",Yr=Le(!1);ft(()=>{if(!Yr.current){if(!T&&!S){Yr.current=!0;let o=new wn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(o),z(o.message)}else if(!T&&S&&!bn&&!jt){Yr.current=!0;let o=new wn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(o),z(o.message)}else if(Wr!==void 0&&!Je&&!Ra){Yr.current=!0;let o=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?.(o),z(o.message)}}},[T,S,bn,jt,Wr,Je,Ra,c,z]);let Ia=Le(!1);ft(()=>{if(Ia.current||!jr)return;let o=[];Y!==!0&&o.push("showApplePay"),ye!==!0&&o.push("showGooglePay"),o.length!==0&&(Ia.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.`))},[jr,Y,ye]);let Ea=Se((o,b)=>Ue.applyInlineSessionPatch?Ue.applyInlineSessionPatch(o).then(U=>({error:null,sessionId:U.sessionId||e,nonce:U.session?.clientSecret||t})).catch(U=>{let oe=ii(b,U);return z(oe.message),c?.(oe),{error:oe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ue.applyInlineSessionPatch,t,c,e,z]),dn=Se(async o=>{if(!Pe)return{proceed:!0};try{let b=await Pe({method:o,sessionId:e||void 0,createSession:Ue.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&jn(oe=>({...oe??{},...b.account}));let U=await Ea(b,o);return U.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:U.sessionId,nonce:U.nonce}}return{proceed:!0}}catch(b){let U=ii(o,b);return z(U.message),c?.(U),{proceed:!1}}},[Ea,Ue.inlineSessionDraft,Pe,c,e,z]),_a=Se(async(o,b)=>{if(se.current)return;se.current=!0,It(!0),Q("processing"),z(null);let U=b?.sessionId??e,oe=b?.nonce??t,L=$o(H,b?.accountPatch),te=b?.completionPaymentMethodId??ro(o),Xe=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let xt=await new zn(pe).processPayment(L.userId??"",{sessionId:U,nonce:oe,tokenizedData:Xe,accountData:{userId:L.userId??"",email:L.email??"",firstName:L.firstName??"",lastName:L.lastName??"",...V?(()=>{let Ae=Ut.current,Qt=Te(V.state,Ae),en=Te(V.address_line_1,Ae),Jn=Te(V.postal_code,Ae),Xn=en&&!Qt&&Jn?ti(Ae,(Pt.current??"").trim()):null,Mt=Qt?yn.current:Xn;return{country:Ae,...Jn&&Pt.current?{zip:Pt.current}:{},...Te(V.city,Ae)&&on.current?{city:on.current}:{},...Mt?{state:Mt}:{},...en&&Dt.current?{addressLine1:Dt.current}:{},...Te(V.address_line_2,Ae)&&Gt.current?{addressLine2:Gt.current}:{}}})():{}},chv:k,avsCheck:G??!1,checkoutType:x,checkoutLayout:K,avsConfig:V?{country:Te(V.country,Ut.current),postal_code:Te(V.postal_code,Ut.current),address_line_1:Te(V.address_line_1,Ut.current),address_line_2:Te(V.address_line_2,Ut.current),city:Te(V.city,Ut.current),state:Te(V.state,Ut.current)}:void 0});if(xt.ok){pr(U),Q("success"),P(null),await new Promise(Ae=>setTimeout(Ae,Mn)),a?.({status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:te,checkoutMethod:o.isPaypal?"paypal":"card"});return}let nt=await xt.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let Ae=nt.threeDSecureToken,Qt=nt.paymentMethodId||o.id||"";if(!Oe||!Ae){Q("error"),z("PayPal authorization required but no token provided.");return}try{let en=Ve?.getRawProvider();if(!en){z("PayPal is not available.");return}let Jn={return_url:window.location.href};Qt&&(Jn.payment_method=Qt);let{error:Xn}=await en.confirmPayment({clientSecret:Ae,confirmParams:Jn,redirect:"if_required"});if(Xn){Q("error");let Mt=Xn.message??"PayPal payment failed.";z(Mt),cn("paypal",Mt,{code:Xn.code})}}catch(en){Q("error"),z(en instanceof Error?en.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let Ae=nt.orderId;if(!Ae){Q("error"),z("PayPal retry required but no order id provided.");return}let Qt=Z.current?.attempts??0;if(Qt>=2){Q("error"),z("PayPal payment could not be completed after multiple attempts."),cn("paypal","paypal_direct_required retry limit exceeded");return}Ro(!1),Io("loading"),P({orderId:Ae,attempts:Qt+1}),Q(null);return}Q("error");let Tt=nt?.message??"Payment failed. Please try again.";z(Tt),cn(o.isPaypal?"paypal":"card",Tt,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(Ae=>setTimeout(Ae,Cn))}catch(St){Q("error"),z(St instanceof Error?St.message:"An unexpected error occurred"),await new Promise(xt=>setTimeout(xt,Cn))}finally{It(!1),Q(null),se.current=!1}},[pe,e,t,H,Ke,k,Oe,Ve,a,c,z,cn]),Zt=Se((o,b)=>{C?C(o):_a(o,b)},[C,_a]),xa=Le(!1);ft(()=>{if(typeof window>"u"||xa.current)return;let o=new URLSearchParams(window.location.search),b=o.get("payment_intent"),U=o.get("payment_intent_client_secret"),oe=o.get("redirect_status");if(!b||!U)return;let L=Tt=>{let Ae=localStorage.getItem(Tt);if(!Ae)return null;try{return JSON.parse(Ae)}catch{return localStorage.removeItem(Tt),null}},te=L(kn)??L(oi),Xe;if(te?.clientSecret){if(te.clientSecret!==U)return;Xe={...te.accountPatch?{accountPatch:te.accountPatch}:{},...te.sessionId?{sessionId:te.sessionId}:{},...te.nonce?{nonce:te.nonce}:{}}}else if(te?.sessionId&&te.sessionId!==e)return;xa.current=!0,localStorage.removeItem(kn),localStorage.removeItem(oi);let St=new URL(window.location.href);St.searchParams.delete("payment_intent"),St.searchParams.delete("payment_intent_client_secret"),St.searchParams.delete("redirect_status"),window.history.replaceState({},"",St.toString());let xt=te?.paymentMethodType??te?.tokenType??"card",nt="card";(async()=>{let Tt=Oe?.getRawProvider();if(!Tt){let Mt="Payment is not available \u2014 please refresh and try again.";z(Mt),cn(nt,Mt);return}if(oe==="failed"){let Mt="Payment was declined. Please try again.";z(Mt),cn(nt,Mt);return}let{paymentIntent:Ae,error:Qt}=await Tt.retrievePaymentIntent(U);if(Qt){let Mt=Qt.message??"Failed to retrieve payment status.";z(Mt),cn(nt,Mt,{code:Qt.code});return}let en=Ae?.status,Jn=no(en);if(!Ae||!Jn){let Mt=en==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";z(Mt),cn(nt,Mt,{code:en??"missing_payment_intent"});return}let Xn=typeof Ae.payment_method=="string"?Ae.payment_method:Ae.payment_method?.id;Zt({id:Xn??te?.paymentMethodId??te?.tokenId??Ae.id,type:"card",threeDSecureActionResultTokenId:Ae.id,gateway:te?.gateway??"stripe",paymentMethodType:xt},Xe)})()},[e,Zt,Oe,z,cn]);let Eo=Se(o=>{o.preventDefault()},[]);if(!(Oe!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let xr=ee==="buttons",Kt=ct?.variables,Vi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),_o=Kt?.colorBackground,Hi=_o&&!Vi.has(_o)?_o:void 0,Tr=I.cardInputBorder??(xr?"#e5e7eb":"#A4A4FF"),xo=Kt?.colorDanger??"#dc2626",Wn=o=>Jt&&o?xo:Tr,Gr=(_t.malformed||_t.empty)&&(xn||Jt),Wi=Gr?xo:Wn(Lt.zip),To=I.cardFormContainer?.backgroundColor??Hi??(xr?"white":"#EDEDFF"),Mr=I.cardInputBackground??Kt?.colorBackground??"white",Mo=ir(j),Ta=ir(ae),ar=I.nameInput,Ma=I.cardInputFontSize??Gs(ar?.fontSize)??Kt?.fontSizeBase??"16px",Ba=typeof ar?.fontFamily=="string"?ar.fontFamily:Kt?.fontFamily??"Poppins, sans-serif",Aa=si(ar?.fontWeight)??400,Yi=I.cardInputColor??(typeof ar?.color=="string"?ar.color:void 0)??Kt?.colorText??"#262833",Gi=I.cardInputPlaceholderColor??"#9ca3af",ht=Kt?.borderRadius??"8px",Yn=Kt?.borderRadius??I.cardButton?.borderRadius??ht,Gn=Kt?.colorPrimary??"#4A49FF",Ji=Kt?.colorPrimaryHover??lo(Gn,.12),Bo=Kt?.colorText??"#262833",Fa={fontSize:Ma,fontFamily:Ba,fontWeight:Aa,color:Yi,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Xi={"--flopay-input-placeholder-color":Gi,"--flopay-input-font-size":Ma,"--flopay-input-font-family":Ba,"--flopay-input-font-weight":String(Aa)},Br=I.cardFormContainer??{},Ao=Br.padding??(xr?"0":"1rem"),Fo=Br.borderRadius??ht,Zi=tt&&Nt?d(No,{capture:tt,html:Nt.html,messageToken:Nt.messageToken,expectedOrigin:Nt.expectedOrigin,theme:M,onReady:()=>{if(!V||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let b=0,U=window.setInterval(()=>{b+=1;let oe=document.activeElement;!!oe&&oe.tagName==="IFRAME"&&oe.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(U)):b>=50&&window.clearInterval(U)},100)},onError:o=>z(o),onValidation:o=>{z(o),o&&Q(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"}),Da=Me("div",{style:{backgroundColor:To,borderRadius:Fo,...Br,padding:Ao,...Xi,display:"flex",flexDirection:"column"},children:[d("style",{children:`
30
+ `,uo=44;function ea(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 Ws={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},fi={width:"100%",minHeight:uo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Ys(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function si(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function gi(e){return e==="paypal"?"PayPal":hr(e)}function Gs(e,t){let n=`We couldn't open ${gi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function hi(e){let t=Fe(0),n=Fe(null),i=Fe(null),r=we((c=i.current)=>{let h=c;h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),a=we((c,h)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(c),c.timer=setTimeout(()=>{c.timer=null,i.current?.generation===c.generation&&(i.current=null,n.current=c.generation,e(c.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},h))},[r,e]),d=we(c=>{c.yieldedControl&&a(c,600)},[a]),l=we(c=>{r();let h=t.current+1;t.current=h,n.current=null;let R={generation:h,method:c,timer:null,yieldedControl:!1};return i.current=R,h},[r]),C=we(c=>{let h=i.current;return typeof c=="number"&&h?.generation!==c?!1:(r(h),i.current=null,(typeof c!="number"||n.current===c)&&(n.current=null),!0)},[r]),T=we(c=>{let h=i.current,R=c??h?.generation??t.current;(!c||h?.generation===c)&&(r(h),i.current=null),n.current=R},[r]),y=we(c=>n.current===(c??t.current),[]),k=we(c=>i.current?.generation===c&&n.current!==c,[]),b=we(()=>{let c=i.current;c&&d(c)},[d]),E=we(()=>{let c=i.current;c&&(c.yieldedControl=!0,r(c))},[r]);return pt(()=>{let c=()=>{document.visibilityState==="visible"?b():E()},h=()=>{E()};return document.addEventListener("visibilitychange",c),window.addEventListener("blur",h),window.addEventListener("focus",b),()=>{document.removeEventListener("visibilitychange",c),window.removeEventListener("blur",h),window.removeEventListener("focus",b),r()}},[r,E,b]),{startAttempt:l,finishAttempt:C,invalidateAttempt:T,isAttemptInvalidated:y,isAttemptCurrent:k}}function Js(e){let t=Fs(e);return`Enter a valid ${Go(e)}${t?` (e.g. ${t})`:""}`}function Xs(e,t,n){let i=Bs(e),r=t.trim(),a=n&&i,d=a&&!r,l=a&&!!r&&!As(e,r);return{visible:n,supported:i,required:a,empty:d,malformed:l}}function li(e,t){return t instanceof bn?t:new bn(t instanceof Error?t.message:`${Ys(e)} before-click hook failed.`,"validation_error")}function Yo(){return u("style",{children:Hs})}function Zs(e){return typeof e=="number"?`${e}px`:e}function ci(e){if(typeof e=="number"||typeof e=="string")return e}function Pi(e,t){let n=e.availablePaymentMethods;return n&&t.some(i=>n[i])?"ready":"unavailable"}function bi({state:e,placeholderTestId:t,borderRadius:n=8,children:i}){return e==="unavailable"||e==="load_error"?null:Ae("div",{style:{position:"relative",minHeight:44},children:[u("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),u("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:i})]})}function di(e){return e!=="unavailable"&&e!=="load_error"}function ta(e){return u(el,{...e})}function ui({sessionId:e,nonce:t,email:n,billingApiUrl:i,onTokenizedBody:r,onErrorChange:a,isProcessing:d=!1,onButtonClick:l,onDecline:C,onTechnicalFailure:T,runBeforeButtonClick:y,onLoadStateChange:k,placeholderBorderRadius:b}){let E=gn(),c=Zo(),h=Xo(),[R,x]=ve("loading");pt(()=>{k?.(R)},[R,k]);let[f,ae]=ve(!1),O=Fe(!1),le=Fe(null),J=Fe(null),[M,W]=ve(0),[V,ce]=ve(!1),z=Fe(!1),$=Fe(new Map),{startAttempt:me,finishAttempt:_e,invalidateAttempt:be,isAttemptInvalidated:he,isAttemptCurrent:X}=hi((H,I,de)=>{T?.(H,I,{...de,popupBlocked:de?.popupBlocked??Nn(I)}),ce(!0),W(Ne=>Ne+1)});pt(()=>{V&&J.current?.focus()},[V,M]);let Pe=we(()=>{W(H=>H+1)},[]),xe=we((H,I,de)=>{be(de),T?.("paypal",H,{code:I,popupBlocked:Nn(H)}),ce(!0),Pe()},[be,T,Pe]),Z=we(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);pt(()=>{z.current&&(z.current=!1,Z())},[Z,M]);let Ie=we(()=>{ce(!1),a?.(null),Z()},[Z,a]);pt(()=>{if(!c||O.current)return;let H=new URLSearchParams(window.location.search),I=H.get("payment_intent"),de=H.get("payment_intent_client_secret"),Ne=H.get("redirect_status");if(!I||!de)return;O.current=!0;let Oe;try{let w=localStorage.getItem(Ur);if(w){let Q=JSON.parse(w);Q.clientSecret===de&&(Oe={...Q.accountPatch?{accountPatch:Q.accountPatch}:{},...Q.sessionId?{sessionId:Q.sessionId}:{},...Q.nonce?{nonce:Q.nonce}:{}})}}catch{}try{localStorage.removeItem(Ur)}catch{}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()),(async()=>{try{if(ae(!0),Ne==="failed"){let G="PayPal payment was declined. Please try again.";a?.(G),C?.(St("paypal",G));return}let{paymentIntent:w,error:Q}=await c.retrievePaymentIntent(de);if(Q){a?.(Q.message??"Failed to retrieve PayPal payment status.");return}if(w&&(w.status==="requires_capture"||w.status==="succeeded")){let G=typeof w.payment_method=="string"?w.payment_method:w.payment_method?.id;r({id:G??w.id,type:"card",threeDSecureActionResultTokenId:w.id,isPaypal:!0},Oe)}else{let G="PayPal payment was not completed. Please try again.";a?.(G),C?.(St("paypal",G))}}catch(w){a?.(w instanceof Error?w.message:"Failed to complete PayPal payment.")}finally{ae(!1)}})()},[c,r,a,C]);let Me=we(async H=>{if(d||f){H.reject();return}let I=y?await y("paypal"):{proceed:!0};if(!I.proceed){$.current.delete(M),H.reject();return}let de=me("paypal");$.current.set(M,{generation:de,accountPatch:I.accountPatch,sessionId:I.sessionId,nonce:I.nonce}),ce(!1),l?.("paypal"),H.resolve()},[$,d,l,y,me,f,M]),Re=we(async H=>{if(!c||!h)return;let I=$.current.get(M);if(I&&!X(I.generation)){$.current.delete(M);return}if(!I&&he()||I&&!_e(I.generation))return;I||_e();let de=I??null;if($.current.delete(M),!de&&y){let w=await y("paypal");if(!w.proceed){H.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}de={accountPatch:w.accountPatch,sessionId:w.sessionId,nonce:w.nonce}}let Ne=de?.sessionId??e,Oe=de?.nonce??t,ye=de?.accountPatch?.email??n;try{if(ae(!0),a?.(null),!Ne||!ye)throw new Error("Missing sessionId or email for PayPal payment");let w=c.createPaymentMethod,{error:Q,paymentMethod:G}=await w({type:"paypal"});if(Q){xe(Q,"stripe_paypal_create_payment_method_failed",I?.generation),H.paymentFailed({reason:"fail"});return}let De=await new On(i).createSessionIntent(Ne,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:G?.id??null,intentKind:"payment"});if(De.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let mt=De.clientSecret,Ve={return_url:window.location.href};if(G?.id&&(Ve.payment_method=G.id),typeof window<"u")try{localStorage.setItem(Ur,JSON.stringify({clientSecret:mt,sessionId:Ne,nonce:Oe,accountPatch:de?.accountPatch}))}catch{}let{error:at,paymentIntent:A}=await c.confirmPayment({clientSecret:mt,confirmParams:Ve,redirect:"if_required"});if(at){if(typeof window<"u")try{localStorage.removeItem(Ur)}catch{}if(Or(at)){let Ue=at.message??"Your payment was declined.";a?.(Ue),C?.(St("paypal",Ue,{code:Bn(at),declineCode:yr(at)})),await po({billingApiUrl:i,sessionId:Ne,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Bn(at)??"provider_declined"}})}else xe(at,"stripe_paypal_confirm_failed",I?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Ur)}catch{}let F=typeof A?.payment_method=="string"?A.payment_method:A?.payment_method?.id;r({id:F??A?.id,type:"card",threeDSecureActionResultTokenId:A?.id,isPaypal:!0},{accountPatch:de?.accountPatch,sessionId:Ne,nonce:Oe});return}catch(w){xe(w,"stripe_paypal_failed",I?.generation)}finally{ae(!1)}},[c,h,e,t,n,i,r,a,C,y,xe,_e,X,he,M]);return Ae(gr,{children:[u(bi,{state:R,placeholderTestId:"flopay-paypal-placeholder",borderRadius:b,children:Ae("div",{ref:le,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[V&&u("button",{ref:J,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ie,style:fi,children:"Try PayPal again"}),u(yi,{onReady:H=>x(Pi(H,["paypal"])),onLoadError:()=>{x("load_error"),Qo(Tt(E),"paypal","paypal")},onClick:Me,onConfirm:Re,onCancel:()=>{let H=$.current.get(M);$.current.delete(M),Tt(E)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),be(H?.generation),ce(!1),z.current=!0,Pe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},M)]})}),f&&u(Pn,{status:"processing"})]})}function pi({sessionId:e,nonce:t,email:n,billingApiUrl:i,intentKind:r,expressMethods:a,onTokenizedBody:d,onErrorChange:l,onButtonClick:C,onDecline:T,onTechnicalFailure:y,runBeforeButtonClick:k,onLoadStateChange:b,placeholderBorderRadius:E}){let c=gn(),h=Zo(),R=Xo(),[x,f]=ve("loading");pt(()=>{b?.(x)},[x,b]);let[ae,O]=ve(!1),le=Fe(null),J=Fe(null),[M,W]=ve(0),[V,ce]=ve(!1),[z,$]=ve("google_pay"),me=Fe(!1),_e=Fe("google_pay"),be=Fe("google_pay"),he=Fe(new Map),{startAttempt:X,finishAttempt:Pe,invalidateAttempt:xe,isAttemptInvalidated:Z,isAttemptCurrent:Ie}=hi((ye,w,Q)=>{y?.(ye,w,{...Q,popupBlocked:Q?.popupBlocked??Nn(w)}),$(ye),ce(!0),W(G=>G+1)});pt(()=>{V&&J.current?.focus()},[V,M]);let Me=we(()=>{W(ye=>ye+1)},[]),Re=we((ye,w,Q,G)=>{xe(G),y?.(ye,w,{code:Q,popupBlocked:Nn(w)}),$(ye),ce(!0),Me()},[xe,y,Me]),H=we(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);pt(()=>{me.current&&(me.current=!1,H())},[H,M]);let I=we(()=>{ce(!1),l?.(null),H()},[H,l]),de=we(async ye=>{if(!h||!R)return;let w=he.current.get(M);if(w&&!Ie(w.generation)){he.current.delete(M);return}if(!w&&Z()||w&&!Pe(w.generation))return;w||Pe();let Q=ye.expressPaymentType??w?.method??_e.current,G=w??null;he.current.delete(M);let De=si(Q);if(!G&&k){let F=await k(De);if(!F.proceed){ye.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}G={accountPatch:F.accountPatch,sessionId:F.sessionId,nonce:F.nonce}}let mt=De,Ve=G?.sessionId??e,at=G?.nonce??t,A=G?.accountPatch?.email??n;try{O(!0),l?.(null);let{error:F}=await R.submit();if(F){Re(Q,F,"stripe_wallet_submit_failed",w?.generation);return}let{error:Ue,paymentMethod:je}=await h.createPaymentMethod({elements:R});if(Ue||!je){Re(Q,Ue??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",w?.generation);return}if(!Ve||!A)throw new Error("Missing sessionId or email for wallet payment");let it=await new On(i).createSessionIntent(Ve,at??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Q??De,paymentMethodId:je.id,intentKind:r});if(it.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let yt=it.clientSecret,{error:Bt,intentId:Gt}=qs(yt)?await h.confirmCardSetup(yt,{payment_method:je.id}).then(m=>({error:m.error,intentId:m.setupIntent?.id})):await h.confirmCardPayment(yt,{payment_method:je.id}).then(m=>({error:m.error,intentId:m.paymentIntent?.id}));if(Bt){if(Or(Bt)){let m=Bt.message??"Your payment was declined.";l?.(m),T?.(St(mt,m,{code:Bn(Bt),declineCode:yr(Bt)})),await po({billingApiUrl:i,sessionId:Ve,nonce:at,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Q??De,providerDeclineReason:Bn(Bt)??"provider_declined"}})}else Re(Q,Bt,"stripe_wallet_confirm_failed",w?.generation);return}d({id:je.id,type:"card",threeDSecureActionResultTokenId:Gt},{accountPatch:G?.accountPatch,sessionId:Ve,nonce:at})}catch(F){Re(Q,F,"stripe_wallet_failed",w?.generation)}finally{O(!1)}},[h,R,e,t,n,i,r,d,l,T,k,Re,Pe,Ie,Z,M]),Ne=rt(()=>{let ye=["applePay","googlePay","paypal","link","amazonPay","klarna"],w=new Set(["applePay","googlePay"]),Q=new Set(a.map(ai)),G={};for(let De of ye)Q.has(De)?G[De]=w.has(De)?"always":"auto":G[De]="never";return G},[a]),Oe=rt(()=>a.map(ai),[a]);return Ae(gr,{children:[u(bi,{state:x,placeholderTestId:"flopay-wallet-placeholder",borderRadius:E,children:Ae("div",{ref:le,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[V&&Ae("button",{ref:J,type:"button","data-testid":"flopay-wallet-retry-button",onClick:I,style:fi,children:["Try ",gi(z)," again"]}),u(yi,{onReady:ye=>{f(Pi(ye,Oe))},onLoadError:ye=>{f("load_error"),Qo(Tt(c),"stripe","wallet")},onClick:async ye=>{_e.current=ye.expressPaymentType,be.current=si(ye.expressPaymentType);let w=k?await k(be.current):{proceed:!0};if(!w.proceed){he.current.delete(M),ye.reject();return}let Q=X(ye.expressPaymentType);he.current.set(M,{generation:Q,method:ye.expressPaymentType,accountPatch:w.accountPatch,sessionId:w.sessionId,nonce:w.nonce}),ce(!1),C?.(be.current),ye.resolve()},onConfirm:de,onCancel:()=>{let ye=he.current.get(M);he.current.delete(M),Tt(c)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),xe(ye?.generation),ce(!1),me.current=!0,Me()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ne,layout:{maxColumns:1,overflow:"never"}}},M)]})}),ae&&u(Pn,{status:"processing"})]})}function Qs({method:e,themeId:t,submitting:n=!1,disabled:i=!1,highlighted:r=!1,hasNextStep:a=!1,onClick:d,backgroundColor:l,borderColor:C,textColor:T,borderRadius:y,fontFamily:k}){let b=Ns(e,t),E=Ka[e],c=b?.backgroundColor??l??"#ffffff",h=b?.borderColor??C??"#d1d5db",R=b?.textColor??T??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!i&&d()},disabled:n||i,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:uo,padding:"0 1rem",backgroundColor:c,color:R,border:`1px solid ${h}`,borderRadius:y??8,fontSize:"0.95rem",fontWeight:600,fontFamily:k,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?u("span",{style:{margin:"0 auto"},children:`Connecting to ${hr(e)}\u2026`}):Ae(gr,{children:[Ae("span",{style:{display:"inline-flex",alignItems:"center",gap:Ls(e)?8:0},children:[E?u("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"}}):b?.logoSvg?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:b.logoSvg}}):null,u("span",{children:hr(e)})]}),a&&u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:R,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:u("path",{d:"M9 18l6-6-6-6"})})]})})}function Jo({method:e,sessionId:t,nonce:n,email:i,billingName:r,billingApiUrl:a,onTokenizedBody:d,onErrorChange:l,onDecline:C,onCancel:T,runBeforeButtonClick:y,onButtonClick:k,isProcessing:b,submitButtonColor:E,submitButtonBorderRadius:c,submitButtonStyle:h,errorText:R}){let x=gn(),f=Zo(),ae=Xo(),[O,le]=ve(!1),J=Fe(!1),[M,W]=ve(!1),[V,ce]=ve("loading"),z=we(async()=>{if(!f||!ae||b||J.current||!M)return;J.current=!0,le(!0);let $=y?await y("card"):{proceed:!0};if(!$.proceed){J.current=!1,le(!1);return}k?.("card");let me=$.sessionId??t,_e=$.nonce??n,be=$.accountPatch?.email??i;try{l?.(null);let he=await ae.submit();if(he.error){l?.(he.error.message??"Payment failed.");return}let X=await f.createPaymentMethod({elements:ae});if(X.error||!X.paymentMethod){l?.(X.error?.message??"Failed to create payment method.");return}let Pe=X.paymentMethod;if(!me||!be)throw new Error("Missing sessionId or email for payment.");let xe=Pe.type||e,Z=await new On(a).createSessionIntent(me,_e??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:xe,paymentMethodId:null,intentKind:"payment"});if(Z.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ie=Z.clientSecret;if(typeof window<"u")try{localStorage.setItem(vn,JSON.stringify({clientSecret:Ie,sessionId:me,nonce:_e,accountPatch:$.accountPatch,paymentMethodId:Pe.id,paymentMethodType:Pe.type??e,gateway:"stripe"}))}catch{}let{error:Me,paymentIntent:Re}=await f.confirmPayment({clientSecret:Ie,confirmParams:{return_url:window.location.href,payment_method:Pe.id},redirect:"if_required"});if(Me){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let de=Me.message??"Payment failed.";l?.(de),C?.(St("card",de,{code:Me.code})),await po({billingApiUrl:a,sessionId:me,nonce:_e,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Me.code??"provider_declined"}});return}let H=Re?.status;if(!ro(H)){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let de=H==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(de),C?.(St("card",de,{code:H??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let I=typeof Re?.payment_method=="string"?Re.payment_method:Re?.payment_method?.id;d({id:I??Pe.id,type:"card",threeDSecureActionResultTokenId:Re?.id,gateway:"stripe",paymentMethodType:Pe.type??e},{accountPatch:$.accountPatch,sessionId:me,nonce:_e})}catch(he){l?.(he instanceof Error?he.message:"Payment failed. Please try again.")}finally{J.current=!1,le(!1)}},[f,ae,b,M,y,k,t,n,i,a,e,d,l,C]);return Ae("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[u(Es,{onReady:()=>ce("ready"),onLoadError:()=>{ce("load_error"),Qo(Tt(x),"stripe","apm")},onChange:$=>{W(!!$.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...i?{email:i}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{z()},disabled:!M||O||b||V!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:E,color:"white",border:"none",borderRadius:c,fontSize:"1rem",fontWeight:600,cursor:!M||O||b||V!=="ready"?"not-allowed":"pointer",opacity:!M||O||b||V!=="ready"?.5:1,transition:"opacity 120ms ease-out",...h??{}},children:O?"Processing\u2026":`Pay with ${hr(e)}`}),R&&u(ur,{margin:"0.75rem 0 0",children:R})]})}function mi({sessionId:e,nonce:t,email:n,billingName:i,billingApiUrl:r,paymentElementMethods:a,stripeInstance:d,paymentElementBaseOptions:l,onTokenizedBody:C,onErrorChange:T,onButtonClick:y,onDecline:k,runBeforeButtonClick:b,onLoadStateChange:E,isProcessing:c=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:R=8,submitButtonStyle:x,buttonAppearance:f,themeId:ae,onExpandApm:O,expandedApmMethod:le}){let[J,M]=ve(null),[W,V]=ve(null),ce=Fe(!1);pt(()=>{a.length>0&&d?E?.("ready"):d||E?.("loading")},[a.length,d,E]);let z=we(async X=>{if(!d||ce.current||c)return;ce.current=!0,V(X);let Pe=b?await b("card"):{proceed:!0};if(!Pe.proceed){ce.current=!1,V(null);return}y?.("card");let xe=Pe.sessionId??e,Z=Pe.nonce??t,Ie=Pe.accountPatch?.email??n;try{if(T?.(null),!xe||!Ie)throw new Error("Missing sessionId or email for payment.");let Me=await new On(r).createSessionIntent(xe,Z??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,paymentMethodId:null,intentKind:"payment"});if(Me.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Re=Me.clientSecret;if(typeof window<"u")try{localStorage.setItem(vn,JSON.stringify({clientSecret:Re,sessionId:xe,nonce:Z,accountPatch:Pe.accountPatch,paymentMethodType:X,gateway:"stripe"}))}catch{}let{error:H,paymentIntent:I}=await d.confirmPayment({clientSecret:Re,confirmParams:{return_url:window.location.href,payment_method_data:{type:X,billing_details:{name:i&&i.trim().length>=3?i.trim():"FloPay Customer",...Ie?{email:Ie}:{}}}},redirect:"if_required"});if(H){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Oe=H.message??"Payment failed.";T?.(Oe),k?.(St("card",Oe,{code:H.code})),await po({billingApiUrl:r,sessionId:xe,nonce:Z,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:X,providerDeclineReason:H.code??"provider_declined"}});return}let de=I?.status;if(!ro(de)){if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Oe=de==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";T?.(Oe),k?.(St("card",Oe,{code:de??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(vn)}catch{}let Ne=typeof I?.payment_method=="string"?I.payment_method:I?.payment_method?.id;C({id:Ne??I?.id,type:"card",threeDSecureActionResultTokenId:I?.id,gateway:"stripe",paymentMethodType:X},{accountPatch:Pe.accountPatch,sessionId:xe,nonce:Z})}catch(Me){T?.(Me instanceof Error?Me.message:"Payment failed. Please try again.")}finally{ce.current=!1,V(null)}},[d,c,b,y,e,t,n,r,i,C,T,k]),[$,me]=ve(null),_e=O?le??null:$,be=we(X=>{ce.current||c||_e&&_e!==X||(oi(X)?O?O(X):me(X):z(X))},[_e,c,z,O]),he=rt(()=>$?{...l,paymentMethodTypes:[$]}:null,[$,l]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:a.map(X=>{let Pe=le===X,xe=W===X,Z=W!==null&&W!==X||le!=null&&le!==X;return Ae(Us.Fragment,{children:[u(Qs,{method:X,themeId:ae,submitting:xe,disabled:Z,highlighted:Pe,hasNextStep:oi(X),onClick:()=>be(X),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!O&&$===X&&he&&d&&u(tr,{stripe:d,options:he,children:u(Jo,{method:X,sessionId:e,email:n,billingName:i,billingApiUrl:r,onTokenizedBody:C,onErrorChange:T,onDecline:k,onCancel:()=>me(null),runBeforeButtonClick:b,onButtonClick:y,isProcessing:c,submitButtonColor:h,submitButtonBorderRadius:R,submitButtonStyle:x})},X)]},X)})})}function el({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,onComplete:a,onError:d,onDecline:l,onTokenizedBody:C,firstName:T,lastName:y,chv:k,className:b,isProcessing:E,error:c,onErrorChange:h,showPayPal:R=!0,showStripe:x=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:ae,showApplePay:O=!0,showGooglePay:le=!0,layout:J="default",theme:M,buttonsTheme:W,buttonsStyles:V,appearance:ce,cardButtonContent:z,cardBackButtonContent:$,cardTitleContent:me,showSecurityFooter:_e,onButtonClick:be,onBeforeButtonClick:he,enableAVS:X,cardFieldOrder:Pe,cardPreFormSlot:xe,avsLayout:Z="row",country:Ie,zip:Me,addressLine1:Re,addressLine2:H,city:I,state:de,onCountryChange:Ne,onZipChange:Oe,avsCheck:ye,checkoutType:w,checkoutLayout:Q,totalAmount:G=0,currency:De="usd",initialCardOpen:mt=!1,directPaypal:Ve,isSubscription:at=!1,session:A,debug:F=!1}){let Ue=gn(),je=zo(),it=$s(un),yt=no(),[Bt,Gt]=ve(!1),[m,Ce]=ve(null),[We,et]=ve(Ie??"US"),[gt,Ye]=ve(Me??""),[Ze,Te]=ve(Re??""),[Ge,At]=ve(H??""),[Ke,qn]=ve(I??""),[ht,wn]=ve(de??""),[kn,jn]=ve({}),Rt=Fe(Me??""),Ft=Fe(Ie??"US"),Jt=Fe(Re??""),Lt=Fe(H??""),Xt=Fe(I??""),mn=Fe(de??""),ee=rt(()=>Ms(X),[X]),Vt=ee!==null,Rn=!!A?.vault?.html,In=!!A?.gateways?.pcivault,S=!!(A?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),Je=Rn||S||In,ke=!!(x&&Je&&Ue&&e),[Dn,$e]=ve(()=>J!=="buttons"||mt?e??null:null),[Vn,or]=ve(0),Kt=J!=="buttons"||mt||!!e&&Dn===e,st=rt(()=>!Ue||!ke||!e||!Kt?null:Ue.cardCapture({sessionId:e}),[Ue,ke,e,Kt]),Dt=rt(()=>{let o=We,P=ee?Be(ee.postal_code,o):!1;return Xs(o,gt,P)},[ee,We,gt]),{avsInvalid:Ht,invalidAvsFields:bt}=rt(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!ke||!ee)return{avsInvalid:!1,invalidAvsFields:o};let P=We,U=(te,Xe)=>Be(te,P)&&!Xe.trim(),oe={line1:U(ee.address_line_1,Ze),city:U(ee.city,Ke),state:U(ee.state,ht),zip:Dt.empty||Dt.malformed};return{avsInvalid:oe.line1||oe.city||oe.state||oe.zip,invalidAvsFields:oe}},[ke,ee,We,Ze,Ke,ht,Dt]),[on,an]=ve(!1),[yn,sn]=ve(!1),[It,Nt]=ve(()=>Wo(A?.vault)),[Ee,tt]=ve(mt&&Je?"card":"buttons"),[nt,En]=ve(null),Kn=Ee==="expanding"||Ee==="card",Wt=280,Ot=Fe(null),zt=we(o=>{Ot.current&&clearTimeout(Ot.current),Ot.current=setTimeout(()=>{Ot.current=null,o()},Wt)},[Wt]);pt(()=>()=>{Ot.current&&clearTimeout(Ot.current)},[]);let _n=we(()=>{$e(e??null),or(o=>o+1),tt("expanding"),zt(()=>tt("card"))},[zt,e]),Hn=we(()=>{tt("collapsing"),zt(()=>tt("buttons"))},[zt]),Ut=we(o=>{En(o),tt("apm-expanding"),zt(()=>tt("apm-form"))},[zt]),xn=we(()=>{tt("apm-collapsing"),zt(()=>{tt("buttons"),En(null)})},[zt]);pt(()=>{J==="buttons"&&mt&&Je&&($e(e??null),tt("card"))},[J,mt,Je,e]);let[Pt,g]=ve(null),D=Fe(!1),q=Fe(null),ue=Fe("idle"),[re,Y]=ve(null),v=Fe(re);pt(()=>{v.current=re},[re]);let _=n||yt,L=c??m,ge=rt(()=>js(M),[M]),s=rt(()=>{let o=ge?.buttonsLayout??_s(W);return V?{...o,...V,cardButton:{...o.cardButton,...V.cardButton},cardFormContainer:{...o.cardFormContainer,...V.cardFormContainer},backButton:{...o.backButton,...V.backButton},backButtonIcon:{...o.backButtonIcon,...V.backButtonIcon},submitButton:{...o.submitButton,...V.submitButton},title:{...o.title,...V.title}}:o},[ge,W,V]),p=ce??ge?.appearance,se=rt(()=>{let o=p?.variables,P=Xe=>typeof Xe=="string"&&Xe?Xe:void 0,U=s.submitButton,oe=P(o?.colorPrimary)??P(U?.backgroundColor)??"#4A49FF",N=J==="buttons",te=s.nameInput;return{primaryColor:oe,primaryHoverColor:P(o?.colorPrimaryHover)??co(oe,.12),inputBackgroundColor:P(s.cardInputBackground)??P(o?.colorBackground)??"#ffffff",textColor:P(s.cardInputColor)??P(te?.color)??P(o?.colorText)??"#262833",borderColor:P(s.cardInputBorder)??(N?"#e5e7eb":"#A4A4FF"),placeholderColor:P(s.cardInputPlaceholderColor)??"#9ca3af",errorColor:P(o?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:P(te?.fontFamily)??P(o?.fontFamily)??"Poppins, sans-serif",fontSize:P(s.cardInputFontSize)??P(o?.fontSizeBase)??"16px",fontWeight:String(ci(te?.fontWeight)??400),borderRadius:P(o?.borderRadius)??"8px"}},[p,s,J]),ze=it.inlineSessionPatchProcessing??!1,j=(E??Bt)||ze,B=_.replace(/\/+$/,""),K=rt(()=>qo({userId:r,email:i,firstName:T,lastName:y,country:Ie,zip:Me},kn),[r,i,T,y,Ie,Me,kn]),vt=[K.firstName,K.lastName].filter(o=>!!o?.trim()).join(" "),Se=rt(()=>Ue?Ue.getRawProvider():null,[Ue]),ie=rt(()=>je?je.getRawProvider():null,[je]),pe=G||100,qe=rt(()=>p?zs(p):null,[p]),Yt=qe?{appearance:qe}:null,ln=rt(()=>{let o=qe??{},P=o.rules??{};return{...o,rules:{...P,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...P[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...P[".AccordionItemContents"]??{}}}}},[qe]),$t=rt(()=>{let o=Ga(G);return{...o,currency:De.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...Yt}},[G,De,Yt]),ya=rt(()=>({mode:"payment",amount:pe,currency:De.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Yt}),[pe,De,Yt]),fe=we(o=>{Ce(o),h?.(o)},[h]);pt(()=>{!ke||!st||st.setCardFieldOrder?.(Pe??null,ee==null)},[ke,st,Pe,ee]),pt(()=>{(Ee==="expanding"||Ee==="collapsing"||Ee==="apm-expanding"||Ee==="apm-collapsing")&&fe(null)},[Ee,fe]);let cn=we((o,P,U)=>{l?.(St(o,P,U))},[l]),ar=we((o,P,U)=>{let oe=U?.popupBlocked??Nn(P),N=Gs(o,oe),te=Qn(U?.code)??Bn(P)??"external_payment_method_failed",Xe=new bn(N,"api_error",{code:"external_payment_method_failed",param:o});g(null),J==="buttons"&&(tt("buttons"),En(null)),fe(N),d?.(Xe),console.error("[FloPay] External payment method failed:",{method:o,code:te,popupBlocked:oe})},[J,d,fe]);pt(()=>{if(!ke||!e){Nt(null);return}let o=Wo(A?.vault);if(o){Nt(o);return}if(!Kt){Nt(null);return}Nt(null);let P=!0;return new On(B).getVaultCapture(e,t).then(U=>{if(!P)return;let oe=Wo(U);oe?Nt(oe):fe("Failed to load the secure card form.")}).catch(U=>{P&&fe(U instanceof Error?U.message:"Failed to load the secure card form.")}),()=>{P=!1}},[ke,Kt,Vn,e,A?.vault?.html,A?.vault?.messageToken,A?.vault?.expectedOrigin,B,t,fe]);let Wn=Fe({onComplete:a,onError:d,updateError:fe,emitDecline:cn,resolvedAccount:K,avsConfig:ee,avsCheckProp:ye,sessionId:e,nonce:t,baseUrl:B});Wn.current={onComplete:a,onError:d,updateError:fe,emitDecline:cn,resolvedAccount:K,avsConfig:ee,avsCheckProp:ye,sessionId:e,nonce:t,baseUrl:B};let wo=Fe(!1),Ni=we(()=>{let{resolvedAccount:o,avsConfig:P,avsCheckProp:U}=Wn.current,oe=Ft.current||o.country||"US",N=P?Be(P.state,oe):!1,te=P?Be(P.address_line_1,oe):!1,Xe=P?Be(P.postal_code,oe):!1,Ct=P?Be(P.city,oe):!1,Et=P?Be(P.address_line_2,oe):!1,Qe=te&&!N&&Xe?ri(oe,(Rt.current??"").trim()):null,_t=N?mn.current:Qe;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",...Xe&&Rt.current?{zip:Rt.current}:{},...Ct&&Xt.current?{city:Xt.current}:{},..._t?{state:_t}:{},...te&&Jt.current?{addressLine1:Jt.current}:{},...Et&&Lt.current?{addressLine2:Lt.current}:{},country:oe},...U!==void 0?{avsCheck:U}:{},...P?{avsConfig:{country:Be(P.country,oe),postal_code:Xe,address_line_1:te,address_line_2:Et,city:Ct,state:N}}:{}}},[]);pt(()=>{!ke||!st||st.setSubmitGate?.(Ht)},[ke,st,Ht]),pt(()=>{if(!ke||!st)return;wo.current=!1;let o=!1,P=st.on("submitting",()=>{an(!0),q.current&&clearTimeout(q.current),ue.current="validation-window",q.current=setTimeout(()=>{q.current=null,ue.current==="validation-window"&&(ue.current="processing")},Vs),g("processing");let{baseUrl:te,sessionId:Xe,nonce:Ct,updateError:Et,onError:Qe}=Wn.current;!Xe||!Ct||new On(te).patchAccountSnapshot(Xe,Ct,Ni(),{telemetryMode:"best_effort"}).catch(_t=>{if(!Ks(_t))return;let Le=_t instanceof Error?_t.message:"Please check your billing address and try again.";Et(Le),ue.current="idle",g(null),Qe?.(_t instanceof bn?_t:new bn(Le,"api_error"))})}),U=st.on("complete",async te=>{mr(te.sessionId??Wn.current.sessionId),ue.current="terminal",g("success"),await new Promise(Xe=>setTimeout(Xe,Mn)),!wo.current&&(wo.current=!0,Wn.current.onComplete?.({status:"succeeded",paymentIntentId:te.intentId,checkoutMethod:"card"}))}),oe=st.on("decline",async te=>{let{updateError:Xe,emitDecline:Ct}=Wn.current,Et=te.message??"Your payment was declined. Please try another card or contact your bank.";ue.current="terminal",Xe(Et),g("error"),Ct("card",Et,te.declineReason?{declineCode:te.declineReason}:void 0),await new Promise(Qe=>setTimeout(Qe,hn)),!o&&(ue.current="idle",g(null))}),N=st.on("error",async te=>{let{updateError:Xe,onError:Ct}=Wn.current,Et=te.message??"There was a problem processing your payment. Please try again.";ue.current="terminal",Xe(Et),g("error"),Ct?.(new bn(Et,"api_error")),await new Promise(Qe=>setTimeout(Qe,hn)),!o&&(ue.current="idle",g(null))});return()=>{o=!0,q.current&&(clearTimeout(q.current),q.current=null),ue.current="idle",P(),U(),oe(),N()}},[ke,st]);let fn=!!Ve?.clientId,kr=Array.isArray(f),Vr=kr&&f.length>0,Oi=kr&&f.includes("paypal"),{expressMethods:Kr,paymentElementMethods:Rr}=rt(()=>Os(f,{excludePaypal:fn}),[f,fn]),fa=fn||!!je,zi=rt(()=>fa?Kr.filter(o=>o!=="paypal"):Kr,[Kr,fa]),Ui=rt(()=>{let o=[];return O&&o.push("apple_pay"),le&&o.push("google_pay"),o},[O,le]),Hr=kr?zi:Ui,$i=x&&Hr.length>0,ko=Vt?We:Ie,Wr=rt(()=>{let o=ko?.trim().toUpperCase();return o?ae?Rr.filter(P=>{let U=ae[P];return!U||U.length===0||U.includes(o)}):Ds(Rr,ko):Rr},[Rr,ko,ae]),Ro=rt(()=>({mode:"payment",amount:pe,currency:De.toLowerCase(),paymentMethodCreation:"manual",appearance:ln}),[pe,De,ln]),[ga,ha]=ve("loading"),[Pa,ba]=ve("loading"),[va,Ca]=ve("loading"),[qi,Io]=ve(!1),[Sa,Eo]=ve("loading"),[Yr,ji]=ve();pt(()=>{ji(Ja())},[]);let wa=R&&(fn||(kr?Oi:Yr===!1)),ka=x&&$i,Ir=wa&&fn,Ra=Sa==="retrying"||Sa==="exhausted",Er=wa&&!!ie&&(!fn||Ra),_r=ka&&!!Se,xr=x&&Vr&&Wr.length>0&&!!Se,Vi=Ir&&!Ra?qi:Er&&di(ga),Ki=_r&&di(Pa),Hi=xr&&va!=="load_error",Ia=o=>o==="loading"||o==="ready",Ea=Ir||Er&&Ia(ga)||_r&&Ia(Pa)||xr&&va!=="load_error",Gr=Fe(!1);pt(()=>{if(!Gr.current){if(!x&&!R){Gr.current=!0;let o=new bn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(o),fe(o.message)}else if(!x&&R&&!fn&&!ie){Gr.current=!0;let o=new bn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(o),fe(o.message)}else if(Yr!==void 0&&!Je&&!Ea){Gr.current=!0;let o=new bn("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"});d?.(o),fe(o.message)}}},[x,R,fn,ie,Yr,Je,Ea,d,fe]);let _a=Fe(!1);pt(()=>{if(_a.current||!Vr)return;let o=[];O!==!0&&o.push("showApplePay"),le!==!0&&o.push("showGooglePay"),o.length!==0&&(_a.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.`))},[Vr,O,le]);let xa=we((o,P)=>it.applyInlineSessionPatch?it.applyInlineSessionPatch(o).then(U=>({error:null,sessionId:U.sessionId||e,nonce:U.session?.clientSecret||t})).catch(U=>{let oe=li(P,U);return fe(oe.message),d?.(oe),{error:oe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[it.applyInlineSessionPatch,t,d,e,fe]),dn=we(async o=>{if(!he)return{proceed:!0};try{let P=await he({method:o,sessionId:e||void 0,createSession:it.inlineSessionDraft});if(P===!1)return{proceed:!1};if(P&&typeof P=="object"){P.account&&jn(oe=>({...oe??{},...P.account}));let U=await xa(P,o);return U.error?{proceed:!1,accountPatch:P.account}:{proceed:!0,accountPatch:P.account,sessionId:U.sessionId,nonce:U.nonce}}return{proceed:!0}}catch(P){let U=li(o,P);return fe(U.message),d?.(U),{proceed:!1}}},[xa,it.inlineSessionDraft,he,d,e,fe]),Ta=we(async(o,P)=>{if(D.current)return;D.current=!0,Gt(!0),g("processing"),fe(null);let U=P?.sessionId??e,oe=P?.nonce??t,N=qo(K,P?.accountPatch),te=P?.completionPaymentMethodId??oo(o),Xe=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let Et=await new On(B).processPayment(N.userId??"",{sessionId:U,nonce:oe,tokenizedData:Xe,accountData:{userId:N.userId??"",email:N.email??"",firstName:N.firstName??"",lastName:N.lastName??"",...ee?(()=>{let Le=Ft.current,en=Be(ee.state,Le),tn=Be(ee.address_line_1,Le),Xn=Be(ee.postal_code,Le),Zn=tn&&!en&&Xn?ri(Le,(Rt.current??"").trim()):null,xt=en?mn.current:Zn;return{country:Le,...Xn&&Rt.current?{zip:Rt.current}:{},...Be(ee.city,Le)&&Xt.current?{city:Xt.current}:{},...xt?{state:xt}:{},...tn&&Jt.current?{addressLine1:Jt.current}:{},...Be(ee.address_line_2,Le)&&Lt.current?{addressLine2:Lt.current}:{}}})():{}},chv:k,avsCheck:ye??!1,checkoutType:w,checkoutLayout:Q,avsConfig:ee?{country:Be(ee.country,Ft.current),postal_code:Be(ee.postal_code,Ft.current),address_line_1:Be(ee.address_line_1,Ft.current),address_line_2:Be(ee.address_line_2,Ft.current),city:Be(ee.city,Ft.current),state:Be(ee.state,Ft.current)}:void 0});if(Et.ok){mr(U),g("success"),Y(null),await new Promise(Le=>setTimeout(Le,Mn)),a?.({status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:te,checkoutMethod:o.isPaypal?"paypal":"card"});return}let Qe=await Et.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let Le=Qe.threeDSecureToken,en=Qe.paymentMethodId||o.id||"";if(!Ue||!Le){g("error"),fe("PayPal authorization required but no token provided.");return}try{let tn=je?.getRawProvider();if(!tn){fe("PayPal is not available.");return}let Xn={return_url:window.location.href};en&&(Xn.payment_method=en);let{error:Zn}=await tn.confirmPayment({clientSecret:Le,confirmParams:Xn,redirect:"if_required"});if(Zn){g("error");let xt=Zn.message??"PayPal payment failed.";fe(xt),cn("paypal",xt,{code:Zn.code})}}catch(tn){g("error"),fe(tn instanceof Error?tn.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let Le=Qe.orderId;if(!Le){g("error"),fe("PayPal retry required but no order id provided.");return}let en=v.current?.attempts??0;if(en>=2){g("error"),fe("PayPal payment could not be completed after multiple attempts."),cn("paypal","paypal_direct_required retry limit exceeded");return}Io(!1),Eo("loading"),Y({orderId:Le,attempts:en+1}),g(null);return}g("error");let _t=Qe?.message??"Payment failed. Please try again.";fe(_t),cn(o.isPaypal?"paypal":"card",_t,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(Le=>setTimeout(Le,hn))}catch(Ct){g("error"),fe(Ct instanceof Error?Ct.message:"An unexpected error occurred"),await new Promise(Et=>setTimeout(Et,hn))}finally{Gt(!1),g(null),D.current=!1}},[B,e,t,K,vt,k,Ue,je,a,d,fe,cn]),Qt=we((o,P)=>{C?C(o):Ta(o,P)},[C,Ta]),Ma=Fe(!1);pt(()=>{if(typeof window>"u"||Ma.current)return;let o=new URLSearchParams(window.location.search),P=o.get("payment_intent"),U=o.get("payment_intent_client_secret"),oe=o.get("redirect_status");if(!P||!U)return;let N=_t=>{let Le=localStorage.getItem(_t);if(!Le)return null;try{return JSON.parse(Le)}catch{return localStorage.removeItem(_t),null}},te=N(vn)??N(ii),Xe;if(te?.clientSecret){if(te.clientSecret!==U)return;Xe={...te.accountPatch?{accountPatch:te.accountPatch}:{},...te.sessionId?{sessionId:te.sessionId}:{},...te.nonce?{nonce:te.nonce}:{}}}else if(te?.sessionId&&te.sessionId!==e)return;Ma.current=!0,localStorage.removeItem(vn),localStorage.removeItem(ii);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 Et=te?.paymentMethodType??te?.tokenType??"card",Qe="card";(async()=>{let _t=Ue?.getRawProvider();if(!_t){let xt="Payment is not available \u2014 please refresh and try again.";fe(xt),cn(Qe,xt);return}if(oe==="failed"){let xt="Payment was declined. Please try again.";fe(xt),cn(Qe,xt);return}let{paymentIntent:Le,error:en}=await _t.retrievePaymentIntent(U);if(en){let xt=en.message??"Failed to retrieve payment status.";fe(xt),cn(Qe,xt,{code:en.code});return}let tn=Le?.status,Xn=ro(tn);if(!Le||!Xn){let xt=tn==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";fe(xt),cn(Qe,xt,{code:tn??"missing_payment_intent"});return}let Zn=typeof Le.payment_method=="string"?Le.payment_method:Le.payment_method?.id;Qt({id:Zn??te?.paymentMethodId??te?.tokenId??Le.id,type:"card",threeDSecureActionResultTokenId:Le.id,gateway:te?.gateway??"stripe",paymentMethodType:Et},Xe)})()},[e,Qt,Ue,fe,cn]);let _o=we(o=>{o.preventDefault()},[]);if(!(Ue!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Tr=J==="buttons",qt=p?.variables,Wi=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),xo=qt?.colorBackground,Yi=xo&&!Wi.has(xo)?xo:void 0,Mr=s.cardInputBorder??(Tr?"#e5e7eb":"#A4A4FF"),To=qt?.colorDanger??"#dc2626",Yn=o=>on&&o?To:Mr,Jr=(Dt.malformed||Dt.empty)&&(yn||on),Gi=Jr?To:Yn(bt.zip),Mo=s.cardFormContainer?.backgroundColor??Yi??(Tr?"white":"#EDEDFF"),Br=s.cardInputBackground??qt?.colorBackground??"white",Bo=sr($),Ba=sr(me),ir=s.nameInput,Aa=s.cardInputFontSize??Zs(ir?.fontSize)??qt?.fontSizeBase??"16px",Fa=typeof ir?.fontFamily=="string"?ir.fontFamily:qt?.fontFamily??"Poppins, sans-serif",Da=ci(ir?.fontWeight)??400,Ji=s.cardInputColor??(typeof ir?.color=="string"?ir.color:void 0)??qt?.colorText??"#262833",Xi=s.cardInputPlaceholderColor??"#9ca3af",ft=qt?.borderRadius??"8px",Gn=qt?.borderRadius??s.cardButton?.borderRadius??ft,Jn=qt?.colorPrimary??"#4A49FF",Zi=qt?.colorPrimaryHover??co(Jn,.12),Ao=qt?.colorText??"#262833",La={fontSize:Aa,fontFamily:Fa,fontWeight:Da,color:Ji,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Qi={"--flopay-input-placeholder-color":Xi,"--flopay-input-font-size":Aa,"--flopay-input-font-family":Fa,"--flopay-input-font-weight":String(Da)},Ar=s.cardFormContainer??{},Fo=Ar.padding??(Tr?"0":"1rem"),Do=Ar.borderRadius??ft,es=st&&It?u(Oo,{capture:st,html:It.html,messageToken:It.messageToken,expectedOrigin:It.expectedOrigin,theme:se,onReady:()=>{if(!ee||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let P=0,U=window.setInterval(()=>{P+=1;let oe=document.activeElement;!!oe&&oe.tagName==="IFRAME"&&oe.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(U)):P>=50&&window.clearInterval(U)},100)},onError:o=>fe(o),onValidation:o=>{let P=ue.current;(P==="idle"||P==="validation-window")&&(fe(o),o&&ue.current==="validation-window"&&(q.current&&(clearTimeout(q.current),q.current=null),ue.current="idle",g(null)))}}):u("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Na=Ae("div",{style:{backgroundColor:Mo,borderRadius:Do,...Ar,padding:Fo,...Qi,display:"flex",flexDirection:"column"},children:[u("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${Qe.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),xr&&Vn&&Me("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ee?-2:0},children:[Me("button",{type:"button",onClick:Wt,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:I.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...I.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",...I.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(lr,{content:j})]}),Ta?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:I.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...I.title},children:d(Fr,{content:ae})})]}),!xr&&!Ta&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Bo,order:Ee?-3:0,...I.title},children:d(Fr,{content:ae})}),V&&d("div",{style:{order:Ee?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let o=$e,b=(L=!1)=>({backgroundColor:Mr,border:`1px solid ${Wn(L)}`,borderRadius:ht,marginTop:"0.5rem",padding:"10px"}),U=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Fa}),oe=Es(o);return Me(fr,{children:[Te(V.address_line_1,o)&&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:L=>{Dt.current=L.target.value,ke(L.target.value)},disabled:h,required:!0,"data-testid":"flopay-address-line1",style:U()})}),Te(V.address_line_2,o)&&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:vt,onChange:L=>{Gt.current=L.target.value,qe(L.target.value)},disabled:h,"data-testid":"flopay-address-line2",style:U()})}),(Te(V.city,o)||Te(V.state,o))&&Me("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Te(V.city,o)&&d("div",{style:{flex:1,backgroundColor:Mr,borderTop:`1px solid ${Wn(Lt.city)}`,borderRight:`1px solid ${Wn(Lt.city)}`,borderBottom:`1px solid ${Wn(Lt.city)}`,borderLeft:`1px solid ${Wn(Lt.city)}`,padding:"10px",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,...Te(V.state,o)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ht}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:zt,onChange:L=>{on.current=L.target.value,Et(L.target.value)},disabled:h,required:!0,"data-testid":"flopay-city",style:U()})}),Te(V.state,o)&&d("div",{style:{flex:1,backgroundColor:Mr,border:`1px solid ${Wn(Lt.state)}`,padding:"10px",borderTopRightRadius:ht,borderBottomRightRadius:ht,...Te(V.city,o)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:ht}},children:oe?Me("select",{id:"flopay-billing-state",name:"billing-state",value:mn,onChange:L=>{yn.current=L.target.value,En(L.target.value)},disabled:h,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...U(),cursor:"pointer"},children:[d("option",{value:"",children:ei(o)}),oe.map(L=>d("option",{value:L.code,children:L.name},L.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:ei(o),autoComplete:"billing address-level1",value:mn,onChange:L=>{yn.current=L.target.value,En(L.target.value)},disabled:h,required:!0,"data-testid":"flopay-state",style:U()})})]}),(Te(V.country,o)||Te(V.postal_code,o))&&Me("div",{style:{display:"flex",flexDirection:ie==="column"?"column":"row",gap:ie==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Te(V.country,o)&&d("div",{style:{flex:ie==="row"?1:void 0,backgroundColor:Mr,borderTop:`1px solid ${Tr}`,borderRight:`1px solid ${Tr}`,borderBottom:`1px solid ${Tr}`,borderLeft:`1px solid ${Tr}`,padding:"10px",...ie==="row"&&Te(V.postal_code,o)?{borderRadius:"0",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,borderRight:"none"}:{borderRadius:ht}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:$e,onChange:L=>{Ut.current=L.target.value,st(L.target.value),Ne?.(L.target.value),yn.current="",En("")},disabled:h,autoComplete:"billing country","data-testid":"flopay-country",style:{...U(),cursor:"pointer"},children:_s.map(L=>Me("option",{value:L.code,children:[L.flag," ",L.name]},L.code))})}),Te(V.postal_code,o)&&d("div",{style:{flex:ie==="row"?1:void 0,backgroundColor:Mr,border:`1px solid ${Wi}`,padding:"10px",...ie==="row"&&Te(V.country,o)?{borderRadius:"0",borderTopRightRadius:ht,borderBottomRightRadius:ht}:{borderRadius:ht}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Yo($e),autoComplete:"billing postal-code",value:rt,onChange:L=>{Pt.current=L.target.value,et(L.target.value),De?.(L.target.value)},onBlur:()=>Vt(!0),disabled:h,required:_t.required,"aria-invalid":Gr||void 0,"aria-describedby":Gr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:U()})})]}),Gr&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:xo,...Fa,fontSize:"0.75rem"},children:_t.empty?`${Yo(o)} is required`:Ws(o)})]})})()}),Ee&&we&&d("div",{style:{order:-2,width:"100%"},children:we}),Ee&&Zi,le&&d(dr,{margin:"0.75rem 0",styleOverride:I.errorBanner,children:le})]}),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"},La=o=>ze?!S||!bn?d("pre",{"data-testid":o,style:Jr,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":o,style:Jr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${S}`,` directPaypalConfigured=${bn}`,` inAppBrowserDetected=${String(Wr)}`,` shouldRenderDirectPayPal=${Rr}`,` shouldRenderStripePayPal=${Ir}`,` hasPaypalStripeInstance=${!!jt}`].join(`
39
- `)}):null,Na=o=>ze?!T||!dt?d("pre",{"data-testid":o,style:Jr,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":o,style:Jr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${T}`,` currency=${xe}`,` amountInCents=${He}`,` enabledPaymentMethods: ${JSON.stringify(f??[])}`,` enabledPaymentMethodsProvided=${wr}`,` hasEnabledMethods=${jr}`,` expressMethods: ${JSON.stringify(Kr)}`,` walletExpressMethods: ${JSON.stringify(Vr)}`,` paymentElementMethods: ${JSON.stringify(kr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Hr)}`,` hasStripeInstance=${!!dt}`,` shouldRenderWallets=${Er}`,` shouldRenderPaymentElement=${_r}`].join(`
40
- `)}):null,Oa=Ce==="apm-expanding"||Ce==="apm-form"||Ce==="apm-collapsing",Xr=Ce==="apm-expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:Ce==="apm-collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Zr=lt?{...ko,paymentMethodTypes:[lt]}:null;if(ee==="buttons"){let o=Ce==="buttons"||Ce==="expanding"||Ce==="apm-expanding",b=Ce==="expanding"||Ce==="card"||Ce==="collapsing",U=D===void 0?{boxSizing:"border-box",height:co,padding:"0 1rem"}:{padding:"0.9rem 1rem"},oe=Ce==="expanding"||Ce==="apm-expanding"?`flopay-buttons-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ce==="collapsing"||Ce==="apm-collapsing"?`flopay-buttons-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,L=Ce==="expanding"?`flopay-card-enter ${Ot}ms cubic-bezier(0, 0, 0.2, 1) both`:Ce==="collapsing"?`flopay-card-exit ${Ot}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Me("form",{onSubmit:Eo,className:v,style:{position:"relative"},children:[d(Wo,{}),W&&d(Sn,{status:W,errorMessage:le}),Me("div",{style:{display:"grid"},children:[Me("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!o&&!oe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!o&&!oe?Ks:{},...oe?{animation:oe,pointerEvents:"none"}:{}},children:[La("flopay-direct-paypal-gate-debug"),Na("flopay-stripe-gate-debug"),Rr&&Qe&&Me(fr,{children:[N&&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:F,email:H.email,clientId:Qe.clientId,environment:Qe.environment,currency:xe.toUpperCase(),isSubscription:Ze,onTokenizedBody:Zt,onComplete:a,onErrorChange:z,onDecline:s,onTechnicalFailure:or,onButtonClick:be,runBeforeButtonClick:dn,isProcessing:h,onLoadStateChange:Ro,onInitializationStateChange:Io,session:p??null,existingOrderId:N?.orderId,debug:ze},N?.orderId??"fresh")]}),Ir&&d(er,{stripe:jt,options:ln,children:d(ci,{sessionId:e,nonce:t,email:H.email,billingApiUrl:F,onTokenizedBody:Zt,onErrorChange:z,isProcessing:h,onButtonClick:be,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:dn,onLoadStateChange:fa,placeholderBorderRadius:Yn})}),Er?d(er,{stripe:dt,options:sn,children:d(di,{sessionId:e,nonce:t,email:H.email,billingApiUrl:F,intentKind:de>0?"payment":"setup",expressMethods:Vr,onTokenizedBody:Zt,onErrorChange:z,onButtonClick:be,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:dn,onLoadStateChange:ha,placeholderBorderRadius:Yn})}):Sa?d("div",{style:{height:co,borderRadius:Yn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,_r&&d(ui,{sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:F,paymentElementMethods:Hr,stripeInstance:dt,paymentElementBaseOptions:ko,onTokenizedBody:Zt,onErrorChange:z,onButtonClick:be,onDecline:s,runBeforeButtonClick:dn,onLoadStateChange:ba,isProcessing:h,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:I.submitButton,onExpandApm:R,expandedApmMethod:lt,themeId:A,buttonAppearance:{backgroundColor:I.cardButton?.backgroundColor,borderColor:I.cardInputBorder,textColor:I.cardButton?.color,borderRadius:Yn}}),Ee&&d("button",{type:"button",onClick:async()=>{h||!(await dn("card")).proceed||(be?.("card"),rr())},disabled:h,style:{width:"100%",...U,...I.cardButton,...Qo({themeBundle:he,resolvedPrimaryColor:Gn,resolvedBorderRadius:ht,submitButtonStyle:I.submitButton,explicitPrimaryColor:Kt?.colorPrimary}),fontSize:I.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:h?"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:h?.6:1},onMouseEnter:te=>{!h&&(he||Kt?.colorPrimary)&&(te.currentTarget.style.backgroundColor=Ji)},onMouseLeave:te=>{(he||Kt?.colorPrimary)&&(te.currentTarget.style.backgroundColor=Gn)},onMouseDown:te=>{te.currentTarget.style.transform="scale(0.985)"},onMouseUp:te=>{te.currentTarget.style.transform="scale(1)"},children:d(sr,{content:D})}),le&&Ce==="buttons"&&d(dr,{margin:"0.25rem 0",styleOverride:I.errorBanner,children:le})]}),Ee&&b&&d("div",{style:{gridArea:"1 / 1",...L?{animation:L}:{},...Ce==="collapsing"?{pointerEvents:"none"}:{}},children:Da}),T&&Oa&&lt&&Zr&&dt&&d("div",{style:{gridArea:"1 / 1",...Xr?{animation:Xr}:{},...Ce==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Me("div",{style:{backgroundColor:To,borderRadius:Fo,...Br,padding:Ao},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:O,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:I.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...I.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",...I.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(lr,{content:j})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:I.titleFontSize??"1.05rem",color:Bo,paddingRight:80,...I.title},children:`Pay with ${gr(lt)}`})]}),d(er,{stripe:dt,options:Zr,children:d(Go,{method:lt,sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:F,onTokenizedBody:Zt,onErrorChange:z,onDecline:s,onCancel:O,runBeforeButtonClick:dn,onButtonClick:be,isProcessing:h,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:I.submitButton,errorText:le})},lt)]})})]})]})}return Oa&&lt&&Zr&&dt&&T?Me("form",{onSubmit:Eo,className:v,style:{position:"relative"},children:[d(Wo,{}),W&&d(Sn,{status:W,errorMessage:le}),d("div",{style:{...Xr?{animation:Xr}:{},...Ce==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Me("div",{style:{backgroundColor:To,borderRadius:Fo,...Br,padding:Ao},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:O,style:{display:"inline-flex",alignItems:"center",gap:Mo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:I.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...I.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",...I.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(lr,{content:j})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:I.titleFontSize??"1.05rem",color:Bo,paddingRight:80,...I.title},children:`Pay with ${gr(lt)}`})]}),d(er,{stripe:dt,options:Zr,children:d(Go,{method:lt,sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:F,onTokenizedBody:Zt,onErrorChange:z,onDecline:s,onCancel:O,runBeforeButtonClick:dn,onButtonClick:be,isProcessing:h,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:I.submitButton,errorText:le})},lt)]})})]}):Me("form",{onSubmit:Eo,className:v,style:{position:"relative"},children:[d(Wo,{}),W&&d(Sn,{status:W,errorMessage:le}),Me("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[La("flopay-direct-paypal-gate-debug-default"),Na("flopay-stripe-gate-debug-default"),Rr&&Qe&&Me(fr,{children:[N&&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:F,email:H.email,clientId:Qe.clientId,environment:Qe.environment,currency:xe.toUpperCase(),isSubscription:Ze,onTokenizedBody:Zt,onComplete:a,onErrorChange:z,onDecline:s,onTechnicalFailure:or,onButtonClick:be,runBeforeButtonClick:dn,isProcessing:h,onLoadStateChange:Ro,onInitializationStateChange:Io,session:p??null,existingOrderId:N?.orderId,debug:ze},N?.orderId??"fresh")]}),Ir&&d(er,{stripe:jt,options:ln,children:d(ci,{sessionId:e,nonce:t,email:H.email,billingApiUrl:F,onTokenizedBody:Zt,onErrorChange:z,isProcessing:h,onButtonClick:be,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:dn,onLoadStateChange:fa,placeholderBorderRadius:Yn})}),Er&&d(er,{stripe:dt,options:sn,children:d(di,{sessionId:e,nonce:t,email:H.email,billingApiUrl:F,intentKind:de>0?"payment":"setup",expressMethods:Vr,onTokenizedBody:Zt,onErrorChange:z,onButtonClick:be,onDecline:s,onTechnicalFailure:or,runBeforeButtonClick:dn,onLoadStateChange:ha,placeholderBorderRadius:Yn})}),_r&&d(ui,{sessionId:e,nonce:t,email:H.email,billingName:[H.firstName,H.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:F,paymentElementMethods:Hr,stripeInstance:dt,paymentElementBaseOptions:ko,onTokenizedBody:Zt,onErrorChange:z,onButtonClick:be,onDecline:s,runBeforeButtonClick:dn,onLoadStateChange:ba,isProcessing:h,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:I.submitButton,themeId:A,onExpandApm:R,expandedApmMethod:lt,buttonAppearance:{backgroundColor:I.cardButton?.backgroundColor,borderColor:I.cardInputBorder,textColor:I.cardButton?.color,borderRadius:Yn}})]}),Ee&&(ji||qi||Ki)&&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"}})]}),Ee&&Da]})}import{loadFloPay as Pi,PaymentAPI as bi}from"@flopay/js";import{FloPayError as at,isSetupIntentClientSecret as Zs}from"@flopay/shared";var Ur="card";async function Qs(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 el(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 Rn(e,t){return Object.assign(e,{checkoutMethod:t})}function vi(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 tl(e){return e.status==="succeeded"||e.status==="declined"}async function Ci(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,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let m=new AbortController,k=()=>m.abort();e.signal?.aborted?m.abort():e.signal?.addEventListener("abort",k);let v=window.setTimeout(()=>m.abort(),i);try{let E=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:m.signal});if(!E.ok)return{status:"unknown"};let l=await E.json().catch(()=>null);return nl(l)}catch{return{status:"unknown"}}finally{window.clearTimeout(v),e.signal?.removeEventListener("abort",k)}},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 C=document.createElement("iframe");C.setAttribute("title","Card authentication"),C.setAttribute("allow","payment"),C.tabIndex=0,C.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(";"),C.src=e.nextActionRedirectUrl,s.appendChild(C),document.body.appendChild(s),C.focus();let B=null;try{B=new URL(e.billingApiUrl,window.location.href).origin}catch{B=null}try{let m=await new Promise((k,v)=>{let E=!1,l=0,y=0,S=0,T=!1,f=()=>{window.clearTimeout(l),window.clearInterval(y),window.clearTimeout(S),window.removeEventListener("message",ee),C.removeEventListener("load",Y),e.signal?.removeEventListener("abort",ye)},$=async()=>{if(!(E||T)){T=!0;try{let A=await a();if(E||!tl(A))return;E=!0,f(),k(A)}finally{T=!1}}},Y=()=>{window.clearTimeout(S),S=window.setTimeout(()=>{$()},250)},ye=()=>{E||(E=!0,f(),v(new at("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ee=A=>{if(A.source!==C.contentWindow||B&&A.origin!==B)return;let J=A.data;!J||typeof J!="object"||J.source!=="flopay-vault-3ds-return"||E||(E=!0,f(),k(null))};l=window.setTimeout(()=>{E||(E=!0,f(),v(new at("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),y=window.setInterval(()=>{$()},n),C.addEventListener("load",Y),window.addEventListener("message",ee),e.signal?.addEventListener("abort",ye),e.signal?.aborted&&ye()});return m||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function nl(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 Un(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=Nn(r)??r;return Rn(new at(a,"api_error",{code:e?.gatewayErrorCode}),i)}function ta(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 rl(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 Si(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||po(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||po(s)))return s;let c=r.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let C=s,B=[C.stripeClientSecret,C.clientSecret];for(let m of B)if(typeof m=="string"&&m.length>0&&(!t?.requirePaymentIntentClientSecret||po(m)))return m}}}}async function ol({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let r=Si(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 bi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(po(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function hr({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:r,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),C=t??n.id,B=i??n.clientSecret,m=n.customer?.id??n.accountData?.userId??"",k=n.customer?.email??n.accountData?.email??"",v=n.customer?.firstName??n.accountData?.firstName??"",E=n.customer?.lastName??n.accountData?.lastName??"",l=n.customer?.country??n.accountData?.country??void 0,y=n.customer?.zip??n.accountData?.zip??void 0,S=new bi(s,c===!1?{telemetry:!1}:void 0),T=await rl(()=>S.processPayment(m,{sessionId:C,nonce:B,tokenizedData:r,accountData:{userId:m,email:k,firstName:v,lastName:E,country:l,zip:y},returnUrl:a??ta(n)}));if(T.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:ro(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}};let f=await T.json().catch(()=>null);if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let $=Si(f);if(!$)throw new at("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:f.type,threeDSecureToken:$,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let $=await ol({billingApiUrl:s,sessionId:C,nonce:B,responseJson:f});if($)return $;throw Rn(new at("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new at(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason})}async function mo(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:C}){let B=t?.getRawProvider();if(!B)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 m=Zs(e.threeDSecureToken),k=null,v=e.paymentMethodId,E=await Qs(B,e.threeDSecureToken,m);if(E){if(E.error)throw Rn(new at(E.error.message??`Failed to retrieve 3DS ${m?"setup":"payment"} status.`,"api_error",{code:E.error.code}),"card");let y=E.intent;!v&&y?.payment_method&&(typeof y.payment_method=="string"?v=y.payment_method:"id"in y.payment_method&&(v=y.payment_method.id??void 0))}let l=v?await el(B,e.threeDSecureToken,{payment_method:v,return_url:s??ta(c)??window.location.href},m):null;if(l){if(l.error)throw Rn(new at(l.error.message??"3DS authentication failed.","api_error",{code:l.error.code}),"card");k=l.intent}else{let y=await B.handleNextAction({clientSecret:e.threeDSecureToken});if(y.error)throw Rn(new at(y.error.message??"3DS authentication failed.","api_error",{code:y.error.code}),"card");k=(m?y.setupIntent:y.paymentIntent)??null}if(k&&(k.status==="requires_capture"||k.status==="succeeded"||k.status==="processing")){let y=await hr({billingApiUrl:r,sessionId:a,session:c,telemetry:C,tokenizedData:{id:k.id,type:"card",threeDSecureActionResultTokenId:k.id},returnUrl:s});return y.type==="success"?{...y.result,paymentIntentId:y.result.paymentIntentId??k.id,paymentMethodId:y.result.paymentMethodId??v}:mo(y,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:c,returnUrl:s,telemetry:C})}throw Rn(new at("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let m=(n??t)?.getRawProvider();if(!m)throw Rn(new at("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:v}=await m.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:k}=await m.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??ta(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(k)throw Rn(new at(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new at("Unsupported payment redirect state.","api_error")}function tr(e){if(e instanceof at){let i=Nn(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=Nn(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:r}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[c,s]=await Promise.all([Pi(e,{billingApiUrl:n,locale:i,telemetry:r}),a?Pi(t,{billingApiUrl:n,locale:i,telemetry:r}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{Fragment as In,jsx as ne,jsxs as Rt}from"react/jsx-runtime";var Pr=44,la="flopay_checkout_saved_payment_resume",vo=new Map,ho=new Map;function Ri(e,t){t.settled&&t.consumers===0&&vo.get(e)===t&&vo.delete(e)}function cl(e,t,n){let i=ho.get(e);if(i&&(!i.sdkGeneratedIdempotencyKey||!t||i.sdkGeneratedIdempotencyKey===t))return i.attempt;let r=n(),a={attempt:r,sdkGeneratedIdempotencyKey:t};ho.set(e,a);let c=()=>{ho.get(e)===a&&ho.delete(e)};return r.then(c,c),r}function $r(e){return new Promise(t=>setTimeout(t,e))}function Po(e,t,n){let i=Qr({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:_i,enabled:t!==!1});return i.beginCheckout(n),i}function bo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ra(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"}:{}}),bo(a)}function dl(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function sa(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function oa(e){return!e||e.data.stripe?.publishableKey?!1:!!sa(e)?.clientId}function Fn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ul(){if(!Fn())return null;try{let e=window.sessionStorage.getItem(la);return e?JSON.parse(e):null}catch{return null}}function Ii(e){if(Fn())try{window.sessionStorage.setItem(la,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function aa(){if(Fn())try{window.sessionStorage.removeItem(la)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ca=":idempotency-key";function pl(e){if(!Fn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function ml(e,t,n){if(Fn())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 Ti(e){if(Fn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function yl(e){if(Fn())try{return window.sessionStorage.getItem(e+ca)??void 0}catch{return}}function fl(e,t){if(Fn())try{window.sessionStorage.setItem(e+ca,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function gl(e){if(Ti(e),!!Fn())try{window.sessionStorage.removeItem(e+ca)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function hl(){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 Ei(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 Pl(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(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function da({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:r,appearance:a,locale:c,loading:s,error:C,onComplete:B,onError:m,onDecline:k,onCountryChange:v,onZipChange:E,showPayPal:l=!0,showStripe:y=!0,showApplePay:S=!0,showGooglePay:T=!0,debug:f=!1,layout:$,theme:Y,buttonsTheme:ye,buttonsStyles:ee,cardButtonContent:A,cardBackButtonContent:J,cardTitleContent:q,showSecurityFooter:fe,onButtonClick:D,onBeforeButtonClick:j,enableAVS:ae,cardFieldOrder:Be,cardPreFormSlot:be,avsLayout:Pe,className:X,initialErrorMessage:ge=null,children:we,checkoutMode:ie,confirmLabel:Fe,renderConfirmButton:_e,onSessionCompleted:Re}){let w=sl(i),re=pn(()=>xi(Y),[Y]),ce=a??re?.appearance,Ne=n?"embedded_checkout":"standard_checkout",De=we?"custom_layout":$==="buttons"?"buttons_layout":"default_layout",[G,x]=kt(null),[K,de]=kt(null),xe=rn(null),[it,Qe]=kt(null),Ze=rn(null),[p,ze]=kt(null),[Oe,Ve]=kt(e??""),Ue=e??Oe,Yt=n?"":Ue,[bt,It]=kt(!0),[g,Ie]=kt(null),[$e,st]=kt("full"),[rt,et]=kt(!1),[Ge,ke]=kt(ge),[vt,qe]=kt(null),[zt,Et]=kt(null),[mn,En]=kt(void 0),[_n,jn]=kt(""),[Pt,Ut]=kt(!1),[Dt,Gt]=kt("loading"),[on,yn]=kt(0),V=rn(!1),Dn=rn(!1),fn=rn(!1),$t=rn(null),Ft=pn(()=>({checkoutMode:ie??$e,layout:we?"unknown":$==="buttons"?"buttons":"embedded"}),[ie,we,$e,$]),_=rn(B);_.current=B;let Je=rn(m);Je.current=m;let Ee=rn(k);Ee.current=k,An(()=>{Bt(K)?.setCheckoutContext(Ft),it&&it!==K&&Bt(it)?.setCheckoutContext(Ft)},[K,it,Ft]);let Ln=rn(Re);Ln.current=Re;let je=nr(R=>{Gt(R),!(R!=="exhausted"||fn.current)&&(fn.current=!0,Je.current?.(new At("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Kn=nr(()=>{Gt("retrying"),yn(R=>R+1)},[]);An(()=>{Gt("loading"),yn(0),fn.current=!1},[Ue]),An(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:_i,checkout_type:Ne,checkout_layout:De,billing_api_url:w})},[De,Ne,w]);let gn=pn(()=>n?xn(n,!0):"",[n]),hn=pn(()=>_n===gn?mn:void 0,[mn,_n,gn]),tt=pn(()=>n?Uo(n,hn):void 0,[n,hn]),_t=ie??tt?.checkoutMode??"full",qt=pn(()=>tt?{...tt,checkoutMode:_t}:void 0,[tt,_t]);An(()=>{En(void 0),jn(gn)},[gn]),An(()=>{ke(ge)},[ge]);let Lt=nr((R,O,W)=>{mt(()=>{Ee.current?.(wt(R,O,W))})},[mt]),Jt=nr(async(R,O)=>{ke(null),Et(null),qe("processing");let W=O?.sessionId??R.id,Q=xe.current??Ze.current,se=Bt(Q),N=Q?null:Po(w,r,Ft),P={log:h=>{se?se.log(h):N?.log(h)},error:h=>{se?se.error(h):N?.error(h)},terminal:h=>{se?se.terminal(h):N?.terminal(h)},performance:h=>{se?se.performance(h):N?.performance(h)},now:()=>se?.now()??N?.now()??0,elapsed:h=>se?.elapsed(h)??Math.max(0,(N?.now()??h)-h)},Z=P.now(),F=!!(O?.initialAutoProcessingError||O?.initialAutoProcessingPending),le=!1,he,I=()=>{le||(le=!0,F=!0,he=P.now(),P.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ct=!1,M=()=>{ct||(ct=!0,P.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),P.performance({stage:"processing",durationMs:P.elapsed(Z),durationMode:"machine",paymentMethodCategory:"saved"}),he!==void 0&&P.performance({stage:"recovery",durationMs:P.elapsed(he),durationMode:"machine",paymentMethodCategory:"saved"}))};P.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),P.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),F&&I();let u;try{let h=vi(O?.initialAutoProcessingError),pe;if(h)I(),h.type==="paypal_redirect_required"&&$t.current?.publishableKey&&Ii({sessionId:W,publishableKey:$t.current.publishableKey,paypalPublishableKey:$t.current.paypalPublishableKey}),pe=await mo(h,{flopay:xe.current,paypalFlopay:Ze.current,attempt3DS:O?.attempt3DS,billingApiUrl:w,sessionId:W,session:R,telemetry:!1}),h.type==="paypal_redirect_required"&&aa();else if(O?.initialAutoProcessingPending){let Ke=await new go(w,{telemetry:!1}).waitForCheckoutSessionCompletion(O.initialAutoProcessingPending.sessionId,{initialDelayMs:O.initialAutoProcessingPending.retryAfterMs});if(Ke.data.session?.status!=="complete")throw new At("Automatic payment failed. Please try again.","api_error",{code:Ke.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});pe={status:"succeeded"}}else{if(O?.initialAutoProcessingError)throw Un(O.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:O.initialAutoProcessingError.checkoutMethod});if(O?.fromCreateSession)return O?.fallbackToFull&&(st("full"),Ei("full")),!1;{let H=await hr({billingApiUrl:w,sessionId:W,session:R,telemetry:!1});H.type==="success"?pe=H.result:(I(),H.type==="paypal_redirect_required"&&$t.current?.publishableKey&&Ii({sessionId:W,publishableKey:$t.current.publishableKey,paypalPublishableKey:$t.current.paypalPublishableKey}),pe=await mo(H,{flopay:xe.current,paypalFlopay:Ze.current,attempt3DS:O?.attempt3DS,billingApiUrl:w,sessionId:W,session:R,telemetry:!1}),H.type==="paypal_redirect_required"&&aa())}}W&&pr(W),M(),F&&(P.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),P.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),qe("success"),await $r(Mn),u=()=>_.current?.(pe)}catch(h){let pe=tr(h),H=pe.checkoutMethod??Ur;return ke(pe.message),Et(pe.message),O?.fallbackToFull&&(P.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),st("full"),Ei("full")),M(),!!(pe.declineCode||pe.code?.toLowerCase().includes("declin"))?P.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):pe.type==="validation_error"?P.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):P.error({errorCode:F?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:F?"recovery":"processing",paymentMethodCategory:"saved"}),mt(()=>Je.current?.(pe)),Lt(H,pe,{code:pe.code,declineCode:pe.declineCode}),qe("error"),await Promise.allSettled([$r(Cn),O?.ensureProvidersReady?O.ensureProvidersReady():Promise.resolve()]),F&&(P.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),P.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{M(),N&&bo(N),qe(null),Et(null)}return mt(u),!0},[Lt,mt,tr,w,r,Ft]);An(()=>{if(typeof window>"u"||Dn.current)return;let R=new URLSearchParams(window.location.search),O=R.get("payment_intent_client_secret");if(!O)return;let W=ul();W&&(Dn.current=!0,(async()=>{let Q,se=0;ke(null),Et(null),qe("processing"),et(!0);try{if(R.get("redirect_status")==="failed")throw Object.assign(new At("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:N,paypalFlopay:P}=await fo({publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey,billingApiUrl:w,locale:c,telemetry:r});Q=Bt(P??N),se=Q?.now()??0,Q?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),Q?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let Z=(P??N)?.getRawProvider();if(!Z)throw Object.assign(new At("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:F,error:le}=await Z.retrievePaymentIntent(O);if(le)throw Object.assign(new At(le.message??"Failed to retrieve PayPal payment status.","api_error",{code:le.code}),{checkoutMethod:"paypal"});let he=Ha(F?.status);if(!F||he==="failed")throw Object.assign(new At("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let I=typeof F.payment_method=="string"?F.payment_method:F.payment_method?.id,ct=he;if(W.sessionId){let h=(await new go(w,{telemetry:!1}).getUnifiedCheckoutSession(W.sessionId)).data.session;if(h&&h.status!=="complete"){let pe=await hr({billingApiUrl:w,sessionId:W.sessionId,session:h,telemetry:!1,tokenizedData:{id:I??F.id,type:"card",threeDSecureActionResultTokenId:F.id,isPaypal:!0}});if(pe.type!=="success")throw Object.assign(new At("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ct=pe.result.status}}W.sessionId&&pr(W.sessionId),Q?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Q?.performance({stage:"redirect_resume",durationMs:Q.elapsed(se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Q?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),qe("success"),await $r(Mn),mt(()=>_.current?.({status:ct,paymentIntentId:F.id,paymentMethodId:I,checkoutMethod:"paypal"}))}catch(N){let P=tr(N),Z=P.checkoutMethod??"paypal",F=!!(P.declineCode||P.code?.toLowerCase().includes("declin"));if(Q)Q.performance({stage:"redirect_resume",durationMs:Q.elapsed(se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),F?Q.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Q.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(F){let le=Po(w,r,Ft);le.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),bo(le)}else ra(w,r,Ft,"REDIRECT_RESUME_FAILED","redirect_resume");ke(P.message),Et(P.message),mt(()=>Je.current?.(P)),Lt(Z,P,{code:P.code,declineCode:P.declineCode}),qe("error"),await $r(Cn)}finally{aa(),hl(),qe(null),Et(null),et(!1)}})())},[Lt,mt,c,tr,w,r]);let an=rn(null);function xn(R,O=!1){let W=R?.account?.email?.trim().toLowerCase()??"",Q={c:R?.clientId,cur:R?.currency??"",a:{e:W,u:W?"":R?.account?.userId??"",country:R?.account?.country??""},successUrl:R?.successUrl,cancelUrl:R?.cancelUrl,p:R?.products?.map(P=>ia(`${P.type??""}:${P.code??P.providerItemId??P.providerPlanId??""}`,P)).sort(),i:R?.items?.map(P=>ia(P.code??P.providerItemId??"",P)).sort(),s:R?.subscriptions?.map(P=>ia(P.code??P.providerPlanId??"",P)).sort(),couponCodes:R?.couponCodes?[...R.couponCodes].sort():void 0,...O?{tagsData:R?.tagsData,utmMetadata:R?.utmMetadata,tokenizedData:R?.tokenizedData,checkoutMode:R?.checkoutMode??"full"}:{}},se=JSON.stringify(Q),N=0;for(let P=0;P<se.length;P++)N=(N<<5)-N+se.charCodeAt(P)|0;return`flopay_session_${Math.abs(N).toString(36)}`}let Vt=pn(()=>qt?xn(qt):"",[qt]),Nt=rn(qt);Nt.current=qt,An(()=>{Ve(e??"")},[e]),An(()=>{V.current=!1,ke(ge),Et(null),qe(null)},[Vt,ge,e]);async function Xt(R,O){let W=Po(w,r,Ft),Q=new go(w,{telemetry:!1});try{let se=R.idempotencyKey!==void 0?ki(R.idempotencyKey):void 0,N=se??yl(O),P,Z=!1,F=pl(O);W.log({name:F?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let le=F?.sid??null,he=null;if(le)try{if(he=await Q.getUnifiedCheckoutSession(le,F?.nonce),he.data.session?.status==="complete"){if(qo(le))return{sid:le,result:he};gl(O),le=null,he=null,Z=!0}}catch{W.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ti(O),le=null}if(!le){!se&&(Z||!N)&&(N=ki(),P=N),N&&fl(O,N);let I=W.now(),ct=0;W.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let M={...R,idempotencyKey:N,avsCheck:!!ae,avsConfig:typeof ae=="object"?ae:void 0,checkoutType:"embedded_checkout",checkoutLayout:we?"custom_layout":$==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(M,al,{configurable:!1,enumerable:!1,value:{onAttempt:u=>{ct=Math.max(ct,u)}}});try{he=await Q.createAndFetchSession(M),W.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),W.performance({stage:"session_create",durationMs:W.now()-I,durationMode:"machine",requestCategory:"session_create",attempt:ct,statusClass:"2xx"})}catch(u){let h=il(u,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw W.performance({stage:"session_create",durationMs:W.now()-I,durationMode:"machine",requestCategory:"session_create",attempt:ct,statusClass:h.statusClass}),u instanceof At&&u.type==="validation_error"?W.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):h.statusClass==="4xx"?W.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):W.error({...h,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),u}le=he.data.session?.id??"",le&&ml(O,le,he.data.session?.clientSecret)}return{sid:le??"",result:he,sdkGeneratedIdempotencyKey:P}}finally{bo(W)}}let Ce=nr(async(R,O)=>{let W=Nt.current;if(!W)throw new At("createSession is required to bootstrap checkout.","validation_error");let Q=Uo(W,R),se=xn(Q),N=vo.get(se);if(!N){let F={promise:Xt(Q,se),consumers:0,settled:!1};N=F,vo.set(se,F);let le=()=>{F.settled=!0,Ri(se,F)};F.promise.then(le,le)}N.consumers+=1;let P=!1,Z=()=>{P||(P=!0,N.consumers-=1,Ri(se,N))};O?.(Z);try{let F=await N.promise;an.current=se,R&&(jn(gn),En(h=>Ka(h,R)));let{sid:le,result:he}=F;x(he),he.data.session&&ze(he.data.session),le&&Ve(le);let{publishableKey:I,paypalPublishableKey:ct}=yo(he),{flopay:M,paypalFlopay:u}=await fo({publishableKey:I,paypalPublishableKey:ct,billingApiUrl:w,locale:c,telemetry:r});return xe.current=M,de(M),Ze.current=u,Qe(u),It(!1),F}catch(F){throw an.current===se&&(an.current=null),F}finally{O||Z()}},[c,w,r,Ft]),gt=nr(async R=>{if(!Pl(R)||Pt)return{sessionId:Oe,session:p};Ut(!0);try{let O=await Ce(R);return{sessionId:O.sid,session:O.result.data.session??null}}finally{Ut(!1)}},[Ce,Pt,Oe,p]);An(()=>{let R=!1,O;if(Ie(null),Vt){let se=Nt.current;return st(_t),It(!1),an.current===Vt?()=>{R=!0}:(ze(Va(se,ie)),(async()=>{let N=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),P=_t==="auto"&&!V.current&&!N;P&&(ke(null),Et(null),qe("processing"));try{let Z=await Ce(void 0,I=>{O=I}),F=Z.result.data.session??null;$t.current=yo(Z.result);let le=oa(Z.result),he=qo(Z.sid||F?.id);if(!R&&P&&F&&!le&&!he){V.current=!0,await cl(Vt,Z.sdkGeneratedIdempotencyKey,()=>Jt(F,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:Z.result.autoProcessingError,initialAutoProcessingPending:Z.result.autoProcessingPending,autoProcessingAttempted:Z.result.autoProcessingAttempted,sessionId:Z.sid||F.id}));return}!R&&P&&((le||he)&&(V.current=!0),qe(null),Et(null))}catch(Z){if(R)return;let F=Z instanceof At||typeof Z=="object"&&Z!==null&&"code"in Z?Z.code:void 0;if(P&&F==="session_auto_completed"){V.current=!0,qe("success"),await $r(Mn),R||(mt(()=>{_.current?.({status:"succeeded"})}),qe(null),Et(null));return}P&&(qe(null),Et(null));let le=Z instanceof At?Z:new At(Z instanceof Error?Z.message:"Failed to create session","api_error");Ie(le)}finally{O?.(),O=void 0}})(),()=>{R=!0,O?.()})}It(!0);async function W(){let se=!1;try{let P=await new go(w,{telemetry:!1}).getUnifiedCheckoutSession(Ue,t);if(R)return;x(P);let Z=P.data.session??null;if(ze(Z),!Z)throw new At("No session data returned","api_error");if(Z.status==="complete"){It(!1),mt(()=>{Ln.current?.(Z.successUrl??"")});return}if(Z.status==="expired")throw new At("Checkout session has expired.","api_error",{code:"checkout_session_expired"});se=!0;let F=ie??Z.checkoutMode??"full";st(F);let le=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),he=oa(P);if(F==="auto"&&!V.current&&!le&&!he){V.current=!0;let I=Q(P);try{if(await Jt(Z,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>I,sessionId:Ue||Z.id}),R)return;await I,R||It(!1);return}catch{if(R)return;await I,R||It(!1);return}}await Q(P),R||It(!1)}catch(N){if(R)return;N instanceof At?!se&&!dl(N)&&ra(w,r,Ft,"NETWORK_REQUEST_FAILED","session_read"):ra(w,r,Ft,"INTERNAL_SDK_ERROR","checkout_mount");let P=N instanceof At?N:new At(N instanceof Error?N.message:"Failed to initialize checkout","api_error");Ie(P),It(!1)}}async function Q(se){let{publishableKey:N,paypalPublishableKey:P}=yo(se);$t.current={publishableKey:N,paypalPublishableKey:P};let{flopay:Z,paypalFlopay:F}=await fo({publishableKey:N,paypalPublishableKey:P,billingApiUrl:w,locale:c,telemetry:r});xe.current=Z,de(Z),Ze.current=F,Qe(F)}return W(),()=>{R=!0}},[Ce,ie,Vt,_t,Yt,mt,t,Jt]);let lt=nr(async()=>{if(!(rt||!p)){et(!0),ke(null);try{await Jt(p,{fallbackToFull:!0,sessionId:Ue||p.id})}finally{et(!1)}}},[Ue,rt,Jt,p]),Pn=sa(G),Vn=oa(G),Ot=pn(()=>{if(!G||!p||!G.data.stripe?.publishableKey)return;let R={appearance:ce,paymentMethodCreation:"manual",billingApiUrl:w};if(G.data.stripe?.clientSecret)R.clientSecret=G.data.stripe.clientSecret;else{let O=wi(p).total;R.amount=Math.round(O*100)||p.amount,R.currency=p.currency?.toLowerCase()}return R},[G,p,ce,w]),Ht=!!(n&&!we&&$==="buttons"&&j&&_t==="full"),Ct=pn(()=>({session:p,loading:bt,error:g,checkoutMode:$e,inlineSessionDraft:qt,applyInlineSessionPatch:Ht?gt:void 0,inlineSessionPatchProcessing:Pt}),[p,bt,g,$e,qt,Ht,gt,Pt]),rr=!!n&&$==="buttons"&&!Vn&&(!K||!Ot),Wt=vt?ne(Sn,{status:vt,errorMessage:zt}):null;if(bt){if(s)return Rt(In,{children:[s,Wt]});if($==="buttons"){let R=re?.buttonsLayout?.cardButton?.borderRadius??re?.appearance.variables?.borderRadius??8,O=W=>ne("div",{style:{height:W,borderRadius:R,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Rt(In,{children:[Rt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[l&&O(Pr),y&&(S||T)&&O(Pr),y&&O(Pr),ne("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Wt]})}return Rt(In,{children:[Rt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ne("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ne("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Wt]})}return g?C?ne(un.Provider,{value:Ct,children:C(g)}):ne(un.Provider,{value:Ct,children:ne("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:g.message})}):rr?Rt(In,{children:[ne(un.Provider,{value:Ct,children:ne(vl,{onButtonClick:D,showPayPal:l,showStripe:y,showApplePay:S,showGooglePay:T,theme:Y,buttonsTheme:ye,buttonsStyles:ee,cardButtonContent:A,cardBackButtonContent:J,cardTitleContent:q})}),Wt]}):Vn&&p&&Pn?Rt(In,{children:[ne(un.Provider,{value:Ct,children:Rt("div",{className:X,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ge&&ne(dr,{icon:!1,children:Ge}),Dt==="retrying"&&ne("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Dt==="exhausted"&&Rt("div",{role:"alert",children:[ne("div",{children:"PayPal is temporarily unavailable. Please try again."}),ne("button",{type:"button",onClick:Kn,children:"Retry PayPal"})]}),Dt!=="exhausted"&&ne("div",{"aria-hidden":Dt==="retrying"?!0:void 0,style:Dt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ne(Qa,{sessionId:Ue,nonce:p.clientSecret||void 0,billingApiUrl:w,email:p.customer?.email,clientId:Pn.clientId,environment:Pn.environment,currency:(p.currency??"usd").toUpperCase(),isSubscription:p.mode==="subscription",onComplete:B,onErrorChange:ke,onDecline:k,onButtonClick:D,onInitializationStateChange:je,allowAutomaticRetry:on===0,session:p,telemetry:r,telemetryContext:Ft,debug:f},`paypal-init-${on}`)})]})}),Wt]}):!K||!Ot?ne(In,{children:Wt}):$e==="confirm"?Rt(In,{children:[ne(un.Provider,{value:Ct,children:ne(eo,{flopay:K,paypalFlopay:it,options:Ot,children:Rt("div",{className:X,children:[Ge&&ne("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ge}),_e?_e({onConfirm:lt,isProcessing:rt}):ne("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...":Fe??"Confirm Purchase"})]})})}),Wt]}):Rt(In,{children:[ne(un.Provider,{value:Ct,children:ne(eo,{flopay:K,paypalFlopay:it,options:Ot,children:we?Rt(In,{children:[Ge&&ne("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ge}),ne(bl,{sessionId:Ue,nonce:p?.clientSecret||void 0,billingApiUrl:w,session:p,children:we})]}):ne(ea,{sessionId:Ue,nonce:p?.clientSecret||void 0,email:p?.customer?.email,userId:p?.customer?.id,firstName:p?.customer?.firstName,lastName:p?.customer?.lastName,totalAmount:p?Math.round(wi(p).total*100):0,currency:p?.currency?.toLowerCase()??"usd",onComplete:B,onError:m,onDecline:k,error:Ge,onErrorChange:ke,showPayPal:l,showStripe:y,enabledPaymentMethods:G?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:G?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:T,layout:$,theme:Y,buttonsTheme:ye,buttonsStyles:ee,appearance:ce,cardButtonContent:A,cardBackButtonContent:J,cardTitleContent:q,onButtonClick:D,onBeforeButtonClick:j,enableAVS:ae,...Be?{cardFieldOrder:Be}:{},...be?{cardPreFormSlot:be}:{},avsLayout:Pe,country:p?.customer?.country,city:p?.customer?.city,state:p?.customer?.state,onCountryChange:v,onZipChange:E,avsCheck:!!ae,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:we?"custom_layout":$==="buttons"?"buttons_layout":"default_layout",className:X,directPaypal:sa(G),isSubscription:p?.mode==="subscription",session:p,debug:f})})}),Wt]})}function bl({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:r}){return ne(In,{children:na.Children.map(r,a=>{if(!na.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:na.cloneElement(a,s)})})}function vl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:r,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:C,cardBackButtonContent:B,cardTitleContent:m}){let[k,v]=kt(!1),E=pn(()=>xi(a),[a]),l=pn(()=>{let f=E?.buttonsLayout??ll(c);return s?{...f,...s,cardButton:{...f.cardButton,...s.cardButton},cardFormContainer:{...f.cardFormContainer,...s.cardFormContainer},backButton:{...f.backButton,...s.backButton},backButtonIcon:{...f.backButtonIcon,...s.backButtonIcon},submitButton:{...f.submitButton,...s.submitButton},title:{...f.title,...s.title}}:f},[E,c,s]),y=E?.buttonsLayout?.cardButton?.borderRadius??E?.appearance.variables?.borderRadius??8,S=f=>ne("div",{style:{height:f,borderRadius:y,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),T=C===void 0?{boxSizing:"border-box",height:Pr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(k){let f=l.cardInputBorder??"#e5e7eb",$=l.cardInputBackground??"white",Y=ir(B),ye=ir(m);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:()=>v(!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:[ne("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...l.backButtonIcon},children:ne("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ne("path",{d:"M15 18l-6-6 6-6"})})}),ne(lr,{content:B})]}),ye?ne("div",{style:{flex:1}}):ne("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...l.title},children:ne(Fr,{content:m})})]}),ne("div",{style:{backgroundColor:$,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ne("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:[ne("div",{style:{flex:1,backgroundColor:$,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomLeftRadius:8,padding:12,height:45},children:ne("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ne("div",{style:{flex:1,backgroundColor:$,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomRightRadius:8,padding:12,height:45},children:ne("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ne("div",{style:{backgroundColor:$,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ne("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ne("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...l.submitButton,opacity:.5}}),ne("style",{children:`
38
+ `}),Tr&&Kn&&Ae("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ke?-2:0},children:[Ae("button",{type:"button",onClick:Hn,style:{display:"inline-flex",alignItems:"center",gap:Bo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:s.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...s.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...s.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(cr,{content:$})]}),Ba?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:s.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...s.title},children:u(Dr,{content:me})})]}),!Tr&&!Ba&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ao,order:ke?-3:0,...s.title},children:u(Dr,{content:me})}),ee&&u("div",{style:{order:ke?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let o=We,P=(N=!1)=>({backgroundColor:Br,border:`1px solid ${Yn(N)}`,borderRadius:ft,marginTop:"0.5rem",padding:"10px"}),U=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...La}),oe=xs(o);return Ae(gr,{children:[Be(ee.address_line_1,o)&&u("div",{style:P(bt.line1),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Ze,onChange:N=>{Jt.current=N.target.value,Te(N.target.value)},disabled:j,required:!0,"data-testid":"flopay-address-line1",style:U()})}),Be(ee.address_line_2,o)&&u("div",{style:P(),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Ge,onChange:N=>{Lt.current=N.target.value,At(N.target.value)},disabled:j,"data-testid":"flopay-address-line2",style:U()})}),(Be(ee.city,o)||Be(ee.state,o))&&Ae("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Be(ee.city,o)&&u("div",{style:{flex:1,backgroundColor:Br,borderTop:`1px solid ${Yn(bt.city)}`,borderRight:`1px solid ${Yn(bt.city)}`,borderBottom:`1px solid ${Yn(bt.city)}`,borderLeft:`1px solid ${Yn(bt.city)}`,padding:"10px",borderTopLeftRadius:ft,borderBottomLeftRadius:ft,...Be(ee.state,o)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ft}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ke,onChange:N=>{Xt.current=N.target.value,qn(N.target.value)},disabled:j,required:!0,"data-testid":"flopay-city",style:U()})}),Be(ee.state,o)&&u("div",{style:{flex:1,backgroundColor:Br,border:`1px solid ${Yn(bt.state)}`,padding:"10px",borderTopRightRadius:ft,borderBottomRightRadius:ft,...Be(ee.city,o)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:ft}},children:oe?Ae("select",{id:"flopay-billing-state",name:"billing-state",value:ht,onChange:N=>{mn.current=N.target.value,wn(N.target.value)},disabled:j,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...U(),cursor:"pointer"},children:[u("option",{value:"",children:ni(o)}),oe.map(N=>u("option",{value:N.code,children:N.name},N.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:ni(o),autoComplete:"billing address-level1",value:ht,onChange:N=>{mn.current=N.target.value,wn(N.target.value)},disabled:j,required:!0,"data-testid":"flopay-state",style:U()})})]}),(Be(ee.country,o)||Be(ee.postal_code,o))&&Ae("div",{style:{display:"flex",flexDirection:Z==="column"?"column":"row",gap:Z==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Be(ee.country,o)&&u("div",{style:{flex:Z==="row"?1:void 0,backgroundColor:Br,borderTop:`1px solid ${Mr}`,borderRight:`1px solid ${Mr}`,borderBottom:`1px solid ${Mr}`,borderLeft:`1px solid ${Mr}`,padding:"10px",...Z==="row"&&Be(ee.postal_code,o)?{borderRadius:"0",borderTopLeftRadius:ft,borderBottomLeftRadius:ft,borderRight:"none"}:{borderRadius:ft}},children:u("select",{id:"flopay-billing-country",name:"billing-country",value:We,onChange:N=>{Ft.current=N.target.value,et(N.target.value),Ne?.(N.target.value),mn.current="",wn("")},disabled:j,autoComplete:"billing country","data-testid":"flopay-country",style:{...U(),cursor:"pointer"},children:Ts.map(N=>Ae("option",{value:N.code,children:[N.flag," ",N.name]},N.code))})}),Be(ee.postal_code,o)&&u("div",{style:{flex:Z==="row"?1:void 0,backgroundColor:Br,border:`1px solid ${Gi}`,padding:"10px",...Z==="row"&&Be(ee.country,o)?{borderRadius:"0",borderTopRightRadius:ft,borderBottomRightRadius:ft}:{borderRadius:ft}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Go(We),autoComplete:"billing postal-code",value:gt,onChange:N=>{Rt.current=N.target.value,Ye(N.target.value),Oe?.(N.target.value)},onBlur:()=>sn(!0),disabled:j,required:Dt.required,"aria-invalid":Jr||void 0,"aria-describedby":Jr?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:U()})})]}),Jr&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:To,...La,fontSize:"0.75rem"},children:Dt.empty?`${Go(o)} is required`:Js(o)})]})})()}),ke&&xe&&u("div",{style:{order:-2,width:"100%"},children:xe}),ke&&es,L&&u(ur,{margin:"0.75rem 0",styleOverride:s.errorBanner,children:L})]}),Xr={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"},Oa=o=>F?!R||!fn?u("pre",{"data-testid":o,style:Xr,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":o,style:Xr,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${R}`,` directPaypalConfigured=${fn}`,` inAppBrowserDetected=${String(Yr)}`,` shouldRenderDirectPayPal=${Ir}`,` shouldRenderStripePayPal=${Er}`,` hasPaypalStripeInstance=${!!ie}`].join(`
39
+ `)}):null,za=o=>F?!x||!Se?u("pre",{"data-testid":o,style:Xr,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":o,style:Xr,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${x}`,` currency=${De}`,` amountInCents=${pe}`,` enabledPaymentMethods: ${JSON.stringify(f??[])}`,` enabledPaymentMethodsProvided=${kr}`,` hasEnabledMethods=${Vr}`,` expressMethods: ${JSON.stringify(Kr)}`,` walletExpressMethods: ${JSON.stringify(Hr)}`,` paymentElementMethods: ${JSON.stringify(Rr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Wr)}`,` hasStripeInstance=${!!Se}`,` shouldRenderWallets=${_r}`,` shouldRenderPaymentElement=${xr}`].join(`
40
+ `)}):null,Ua=Ee==="apm-expanding"||Ee==="apm-form"||Ee==="apm-collapsing",Zr=Ee==="apm-expanding"?`flopay-card-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ee==="apm-collapsing"?`flopay-card-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Qr=nt?{...Ro,paymentMethodTypes:[nt]}:null;if(J==="buttons"){let o=Ee==="buttons"||Ee==="expanding"||Ee==="apm-expanding",P=Ee==="expanding"||Ee==="card"||Ee==="collapsing",U=z===void 0?{boxSizing:"border-box",height:uo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},oe=Ee==="expanding"||Ee==="apm-expanding"?`flopay-buttons-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ee==="collapsing"||Ee==="apm-collapsing"?`flopay-buttons-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,N=Ee==="expanding"?`flopay-card-enter ${Wt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ee==="collapsing"?`flopay-card-exit ${Wt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Ae("form",{onSubmit:_o,className:b,style:{position:"relative"},children:[u(Yo,{}),Pt&&u(Pn,{status:Pt,errorMessage:L}),Ae("div",{style:{display:"grid"},children:[Ae("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!o&&!oe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!o&&!oe?Ws:{},...oe?{animation:oe,pointerEvents:"none"}:{}},children:[Oa("flopay-direct-paypal-gate-debug"),za("flopay-stripe-gate-debug"),Ir&&Ve&&Ae(gr,{children:[re&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(lo,{sessionId:e,nonce:t,billingApiUrl:_,email:K.email,clientId:Ve.clientId,environment:Ve.environment,currency:De.toUpperCase(),isSubscription:at,onTokenizedBody:Qt,onComplete:a,onErrorChange:fe,onDecline:l,onTechnicalFailure:ar,onButtonClick:be,runBeforeButtonClick:dn,isProcessing:j,onLoadStateChange:Io,onInitializationStateChange:Eo,session:A??null,existingOrderId:re?.orderId,debug:F},re?.orderId??"fresh")]}),Er&&u(tr,{stripe:ie,options:ya,children:u(ui,{sessionId:e,nonce:t,email:K.email,billingApiUrl:_,onTokenizedBody:Qt,onErrorChange:fe,isProcessing:j,onButtonClick:be,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:ha,placeholderBorderRadius:Gn})}),_r?u(tr,{stripe:Se,options:$t,children:u(pi,{sessionId:e,nonce:t,email:K.email,billingApiUrl:_,intentKind:G>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:Qt,onErrorChange:fe,onButtonClick:be,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:ba,placeholderBorderRadius:Gn})}):ka?u("div",{style:{height:uo,borderRadius:Gn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,xr&&u(mi,{sessionId:e,nonce:t,email:K.email,billingName:[K.firstName,K.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:_,paymentElementMethods:Wr,stripeInstance:Se,paymentElementBaseOptions:Ro,onTokenizedBody:Qt,onErrorChange:fe,onButtonClick:be,onDecline:l,runBeforeButtonClick:dn,onLoadStateChange:Ca,isProcessing:j,submitButtonColor:Jn,submitButtonBorderRadius:ft,submitButtonStyle:s.submitButton,onExpandApm:Ut,expandedApmMethod:nt,themeId:M,buttonAppearance:{backgroundColor:s.cardButton?.backgroundColor,borderColor:s.cardInputBorder,textColor:s.cardButton?.color,borderRadius:Gn}}),ke&&u("button",{type:"button",onClick:async()=>{j||!(await dn("card")).proceed||(be?.("card"),_n())},disabled:j,style:{width:"100%",...U,...s.cardButton,...ea({themeBundle:ge,resolvedPrimaryColor:Jn,resolvedBorderRadius:ft,submitButtonStyle:s.submitButton,explicitPrimaryColor:qt?.colorPrimary}),fontSize:s.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:j?"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?.6:1},onMouseEnter:te=>{!j&&(ge||qt?.colorPrimary)&&(te.currentTarget.style.backgroundColor=Zi)},onMouseLeave:te=>{(ge||qt?.colorPrimary)&&(te.currentTarget.style.backgroundColor=Jn)},onMouseDown:te=>{te.currentTarget.style.transform="scale(0.985)"},onMouseUp:te=>{te.currentTarget.style.transform="scale(1)"},children:u(lr,{content:z})}),L&&Ee==="buttons"&&u(ur,{margin:"0.25rem 0",styleOverride:s.errorBanner,children:L})]}),ke&&P&&u("div",{style:{gridArea:"1 / 1",...N?{animation:N}:{},...Ee==="collapsing"?{pointerEvents:"none"}:{}},children:Na}),x&&Ua&&nt&&Qr&&Se&&u("div",{style:{gridArea:"1 / 1",...Zr?{animation:Zr}:{},...Ee==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ae("div",{style:{backgroundColor:Mo,borderRadius:Do,...Ar,padding:Fo},children:[Ae("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ae("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:xn,style:{display:"inline-flex",alignItems:"center",gap:Bo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:s.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...s.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...s.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(cr,{content:$})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:s.titleFontSize??"1.05rem",color:Ao,paddingRight:80,...s.title},children:`Pay with ${hr(nt)}`})]}),u(tr,{stripe:Se,options:Qr,children:u(Jo,{method:nt,sessionId:e,nonce:t,email:K.email,billingName:[K.firstName,K.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:_,onTokenizedBody:Qt,onErrorChange:fe,onDecline:l,onCancel:xn,runBeforeButtonClick:dn,onButtonClick:be,isProcessing:j,submitButtonColor:Jn,submitButtonBorderRadius:ft,submitButtonStyle:s.submitButton,errorText:L})},nt)]})})]})]})}return Ua&&nt&&Qr&&Se&&x?Ae("form",{onSubmit:_o,className:b,style:{position:"relative"},children:[u(Yo,{}),Pt&&u(Pn,{status:Pt,errorMessage:L}),u("div",{style:{...Zr?{animation:Zr}:{},...Ee==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ae("div",{style:{backgroundColor:Mo,borderRadius:Do,...Ar,padding:Fo},children:[Ae("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ae("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:xn,style:{display:"inline-flex",alignItems:"center",gap:Bo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:s.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...s.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...s.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(cr,{content:$})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:s.titleFontSize??"1.05rem",color:Ao,paddingRight:80,...s.title},children:`Pay with ${hr(nt)}`})]}),u(tr,{stripe:Se,options:Qr,children:u(Jo,{method:nt,sessionId:e,nonce:t,email:K.email,billingName:[K.firstName,K.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:_,onTokenizedBody:Qt,onErrorChange:fe,onDecline:l,onCancel:xn,runBeforeButtonClick:dn,onButtonClick:be,isProcessing:j,submitButtonColor:Jn,submitButtonBorderRadius:ft,submitButtonStyle:s.submitButton,errorText:L})},nt)]})})]}):Ae("form",{onSubmit:_o,className:b,style:{position:"relative"},children:[u(Yo,{}),Pt&&u(Pn,{status:Pt,errorMessage:L}),Ae("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Oa("flopay-direct-paypal-gate-debug-default"),za("flopay-stripe-gate-debug-default"),Ir&&Ve&&Ae(gr,{children:[re&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(lo,{sessionId:e,nonce:t,billingApiUrl:_,email:K.email,clientId:Ve.clientId,environment:Ve.environment,currency:De.toUpperCase(),isSubscription:at,onTokenizedBody:Qt,onComplete:a,onErrorChange:fe,onDecline:l,onTechnicalFailure:ar,onButtonClick:be,runBeforeButtonClick:dn,isProcessing:j,onLoadStateChange:Io,onInitializationStateChange:Eo,session:A??null,existingOrderId:re?.orderId,debug:F},re?.orderId??"fresh")]}),Er&&u(tr,{stripe:ie,options:ya,children:u(ui,{sessionId:e,nonce:t,email:K.email,billingApiUrl:_,onTokenizedBody:Qt,onErrorChange:fe,isProcessing:j,onButtonClick:be,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:ha,placeholderBorderRadius:Gn})}),_r&&u(tr,{stripe:Se,options:$t,children:u(pi,{sessionId:e,nonce:t,email:K.email,billingApiUrl:_,intentKind:G>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:Qt,onErrorChange:fe,onButtonClick:be,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:ba,placeholderBorderRadius:Gn})}),xr&&u(mi,{sessionId:e,nonce:t,email:K.email,billingName:[K.firstName,K.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:_,paymentElementMethods:Wr,stripeInstance:Se,paymentElementBaseOptions:Ro,onTokenizedBody:Qt,onErrorChange:fe,onButtonClick:be,onDecline:l,runBeforeButtonClick:dn,onLoadStateChange:Ca,isProcessing:j,submitButtonColor:Jn,submitButtonBorderRadius:ft,submitButtonStyle:s.submitButton,themeId:M,onExpandApm:Ut,expandedApmMethod:nt,buttonAppearance:{backgroundColor:s.cardButton?.backgroundColor,borderColor:s.cardInputBorder,textColor:s.cardButton?.color,borderRadius:Gn}})]}),ke&&(Ki||Vi||Hi)&&Ae("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),u("span",{children:"or pay with card"}),u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),ke&&Na]})}import{loadFloPay as vi,PaymentAPI as Ci}from"@flopay/js";import{FloPayError as ot,isSetupIntentClientSecret as tl}from"@flopay/shared";var $r="card";async function nl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:d}=await e.retrieveSetupIntent(t);return{error:d,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 rl(e,t,n,i){if(i){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:d,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:d??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 Cn(e,t){return Object.assign(e,{checkoutMethod:t})}function Si(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 ol(e){return e.status==="succeeded"||e.status==="declined"}async function wi(e){if(typeof document>"u"||typeof window>"u")throw new ot("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new ot("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 y=new AbortController,k=()=>y.abort();e.signal?.aborted?y.abort():e.signal?.addEventListener("abort",k);let b=window.setTimeout(()=>y.abort(),i);try{let E=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:y.signal});if(!E.ok)return{status:"unknown"};let c=await E.json().catch(()=>null);return al(c)}catch{return{status:"unknown"}}finally{window.clearTimeout(b),e.signal?.removeEventListener("abort",k)}},d=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let C=document.createElement("iframe");C.setAttribute("title","Card authentication"),C.setAttribute("allow","payment"),C.tabIndex=0,C.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(";"),C.src=e.nextActionRedirectUrl,l.appendChild(C),document.body.appendChild(l),C.focus();let T=null;try{T=new URL(e.billingApiUrl,window.location.href).origin}catch{T=null}try{let y=await new Promise((k,b)=>{let E=!1,c=0,h=0,R=0,x=!1,f=()=>{window.clearTimeout(c),window.clearInterval(h),window.clearTimeout(R),window.removeEventListener("message",J),C.removeEventListener("load",O),e.signal?.removeEventListener("abort",le)},ae=async()=>{if(!(E||x)){x=!0;try{let M=await a();if(E||!ol(M))return;E=!0,f(),k(M)}finally{x=!1}}},O=()=>{window.clearTimeout(R),R=window.setTimeout(()=>{ae()},250)},le=()=>{E||(E=!0,f(),b(new ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},J=M=>{if(M.source!==C.contentWindow||T&&M.origin!==T)return;let W=M.data;!W||typeof W!="object"||W.source!=="flopay-vault-3ds-return"||E||(E=!0,f(),k(null))};c=window.setTimeout(()=>{E||(E=!0,f(),b(new ot("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),h=window.setInterval(()=>{ae()},n),C.addEventListener("load",O),window.addEventListener("message",J),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return y||await a()}finally{l.parentNode?.removeChild(l),d?.isConnected&&d.focus()}}function al(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"),r=e?.message??t,a=Ln(r)??r;return Cn(new ot(a,"api_error",{code:e?.gatewayErrorCode}),i)}function na(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function mo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function il(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 ki(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||mo(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 l of a)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||mo(l)))return l;let d=r.gateways;if(d&&typeof d=="object"){let l=d.stripe;if(l&&typeof l=="object"){let C=l,T=[C.stripeClientSecret,C.clientSecret];for(let y of T)if(typeof y=="string"&&y.length>0&&(!t?.requirePaymentIntentClientSecret||mo(y)))return y}}}}async function sl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:i}){let r=ki(i,{requirePaymentIntentClientSecret:!0});if(typeof r=="string"&&r.length>0)return{type:"3ds_required",threeDSecureToken:r};if(!t)return null;try{let l=(await new Ci(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(mo(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Pr({billingApiUrl:e,sessionId:t,session:n,nonce:i,tokenizedData:r,returnUrl:a,telemetry:d}){let l=e.replace(/\/+$/,""),C=t??n.id,T=i??n.clientSecret,y=n.customer?.id??n.accountData?.userId??"",k=n.customer?.email??n.accountData?.email??"",b=n.customer?.firstName??n.accountData?.firstName??"",E=n.customer?.lastName??n.accountData?.lastName??"",c=n.customer?.country??n.accountData?.country??void 0,h=n.customer?.zip??n.accountData?.zip??void 0,R=new Ci(l,d===!1?{telemetry:!1}:void 0),x=await il(()=>R.processPayment(y,{sessionId:C,nonce:T,tokenizedData:r,accountData:{userId:y,email:k,firstName:b,lastName:E,country:c,zip:h},returnUrl:a??na(n)}));if(x.ok)return{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:oo(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}};let f=await x.json().catch(()=>null);if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let ae=ki(f);if(!ae)throw new ot("Authentication is required but no redirect token was provided.","api_error",{code:"authentication_required"});return{type:f.type,threeDSecureToken:ae,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let ae=await sl({billingApiUrl:l,sessionId:C,nonce:T,responseJson:f});if(ae)return ae;throw Cn(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}throw new ot(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason})}async function yo(e,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:d,returnUrl:l,telemetry:C}){let T=t?.getRawProvider();if(!T)throw new ot("Payment provider is not available.","api_error");if(e.type==="3ds_required"){if(!i||!e.threeDSecureToken)throw Cn(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let y=tl(e.threeDSecureToken),k=null,b=e.paymentMethodId,E=await nl(T,e.threeDSecureToken,y);if(E){if(E.error)throw Cn(new ot(E.error.message??`Failed to retrieve 3DS ${y?"setup":"payment"} status.`,"api_error",{code:E.error.code}),"card");let h=E.intent;!b&&h?.payment_method&&(typeof h.payment_method=="string"?b=h.payment_method:"id"in h.payment_method&&(b=h.payment_method.id??void 0))}let c=b?await rl(T,e.threeDSecureToken,{payment_method:b,return_url:l??na(d)??window.location.href},y):null;if(c){if(c.error)throw Cn(new ot(c.error.message??"3DS authentication failed.","api_error",{code:c.error.code}),"card");k=c.intent}else{let h=await T.handleNextAction({clientSecret:e.threeDSecureToken});if(h.error)throw Cn(new ot(h.error.message??"3DS authentication failed.","api_error",{code:h.error.code}),"card");k=(y?h.setupIntent:h.paymentIntent)??null}if(k&&(k.status==="requires_capture"||k.status==="succeeded"||k.status==="processing")){let h=await Pr({billingApiUrl:r,sessionId:a,session:d,telemetry:C,tokenizedData:{id:k.id,type:"card",threeDSecureActionResultTokenId:k.id},returnUrl:l});return h.type==="success"?{...h.result,paymentIntentId:h.result.paymentIntentId??k.id,paymentMethodId:h.result.paymentMethodId??b}:yo(h,{flopay:t,paypalFlopay:n,attempt3DS:i,billingApiUrl:r,sessionId:a,session:d,returnUrl:l,telemetry:C})}throw Cn(new ot("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let y=(n??t)?.getRawProvider();if(!y)throw Cn(new ot("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:b}=await y.handleNextAction({clientSecret:e.threeDSecureToken});if(b)throw Cn(new ot(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:k}=await y.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??na(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"});if(k)throw Cn(new ot(k.message??"PayPal authorization failed.","api_error",{code:k.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new ot("Unsupported payment redirect state.","api_error")}function nr(e){if(e instanceof ot){let i=Ln(e.message);return i&&i!==e.message?Object.assign(new ot(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 ot(n,"api_error")}function fo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new ot("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 go({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:i,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[d,l]=await Promise.all([vi(e,{billingApiUrl:n,locale:i,telemetry:r}),a?vi(t,{billingApiUrl:n,locale:i,telemetry:r}).catch(C=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",C),null)):Promise.resolve(null)]);return{flopay:d,paypalFlopay:t?a?l:d:null}}import{Fragment as Sn,jsx as ne,jsxs as kt}from"react/jsx-runtime";var br=44,ca="flopay_checkout_saved_payment_resume",Co=new Map,Po=new Map;function Ei(e,t){t.settled&&t.consumers===0&&Co.get(e)===t&&Co.delete(e)}function pl(e,t,n){let i=Po.get(e);if(i&&(!i.sdkGeneratedIdempotencyKey||!t||i.sdkGeneratedIdempotencyKey===t))return i.attempt;let r=n(),a={attempt:r,sdkGeneratedIdempotencyKey:t};Po.set(e,a);let d=()=>{Po.get(e)===a&&Po.delete(e)};return r.then(d,d),r}function qr(e){return new Promise(t=>setTimeout(t,e))}function bo(e,t,n){let i=eo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ti,enabled:t!==!1});return i.beginCheckout(n),i}function vo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function oa(e,t,n,i,r){let a=bo(e,t,n);a.error({errorCode:i,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),vo(a)}function ml(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 la(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function aa(e){return!e||e.data.stripe?.publishableKey?!1:!!la(e)?.clientId}function Fn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function yl(){if(!Fn())return null;try{let e=window.sessionStorage.getItem(ca);return e?JSON.parse(e):null}catch{return null}}function _i(e){if(Fn())try{window.sessionStorage.setItem(ca,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ia(){if(Fn())try{window.sessionStorage.removeItem(ca)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var da=":idempotency-key";function fl(e){if(!Fn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function gl(e,t,n){if(Fn())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 Bi(e){if(Fn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function hl(e){if(Fn())try{return window.sessionStorage.getItem(e+da)??void 0}catch{return}}function Pl(e,t){if(Fn())try{window.sessionStorage.setItem(e+da,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function bl(e){if(Bi(e),!!Fn())try{window.sessionStorage.removeItem(e+da)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function vl(){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 xi(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 Cl(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 sa(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function ua({sessionId:e,nonce:t,createSession:n,billingApiUrl:i,telemetry:r,appearance:a,locale:d,loading:l,error:C,onComplete:T,onError:y,onDecline:k,onCountryChange:b,onZipChange:E,showPayPal:c=!0,showStripe:h=!0,enabledPaymentMethods:R,showApplePay:x=!0,showGooglePay:f=!0,debug:ae=!1,layout:O,theme:le,buttonsTheme:J,buttonsStyles:M,cardButtonContent:W,cardBackButtonContent:V,cardTitleContent:ce,showSecurityFooter:z,onButtonClick:$,onBeforeButtonClick:me,enableAVS:_e,cardFieldOrder:be,cardPreFormSlot:he,avsLayout:X,className:Pe,initialErrorMessage:xe=null,children:Z,checkoutMode:Ie,confirmLabel:Me,renderConfirmButton:Re,onSessionCompleted:H}){let I=dl(i),de=pn(()=>Mi(le),[le]),Ne=a??de?.appearance,Oe=n?"embedded_checkout":"standard_checkout",ye=Z?"custom_layout":O==="buttons"?"buttons_layout":"default_layout",[w,Q]=wt(null),[G,De]=wt(null),mt=jt(null),[Ve,at]=wt(null),A=jt(null),[F,Ue]=wt(null),[je,it]=wt(e??""),yt=e??je,Bt=n?"":yt,[Gt,m]=wt(!0),[Ce,We]=wt(null),[et,gt]=wt("full"),[Ye,Ze]=wt(!1),[Te,Ge]=wt(xe),[At,Ke]=wt(null),[qn,ht]=wt(null),[wn,kn]=wt(void 0),[jn,Rt]=wt(""),[Ft,Jt]=wt(!1),[Lt,Xt]=wt("loading"),[mn,ee]=wt(0),Vt=jt(!1),Rn=jt(!1),In=jt(!1),Zt=jt(null),S=pn(()=>({checkoutMode:Ie??et,layout:Z?"unknown":O==="buttons"?"buttons":"embedded"}),[Ie,Z,et,O]),Je=jt(T);Je.current=T;let ke=jt(y);ke.current=y;let Dn=jt(k);Dn.current=k,An(()=>{Tt(G)?.setCheckoutContext(S),Ve&&Ve!==G&&Tt(Ve)?.setCheckoutContext(S)},[G,Ve,S]);let $e=jt(H);$e.current=H;let Vn=rr(g=>{Xt(g),!(g!=="exhausted"||In.current)&&(In.current=!0,ke.current?.(new Mt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),or=rr(()=>{Xt("retrying"),ee(g=>g+1)},[]);An(()=>{Xt("loading"),ee(0),In.current=!1},[yt]),An(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ti,checkout_type:Oe,checkout_layout:ye,billing_api_url:I})},[ye,Oe,I]);let Kt=pn(()=>n?sn(n,!0):"",[n]),st=pn(()=>jn===Kt?wn:void 0,[wn,jn,Kt]),Dt=pn(()=>n?$o(n,st):void 0,[n,st]),Ht=Ie??Dt?.checkoutMode??"full",bt=pn(()=>Dt?{...Dt,checkoutMode:Ht}:void 0,[Dt,Ht]);An(()=>{kn(void 0),Rt(Kt)},[Kt]),An(()=>{Ge(xe)},[xe]);let on=rr((g,D,q)=>{dt(()=>{Dn.current?.(St(g,D,q))})},[dt]),an=rr(async(g,D)=>{Ge(null),ht(null),Ke("processing");let q=D?.sessionId??g.id,ue=mt.current??A.current,re=Tt(ue),Y=ue?null:bo(I,r,S),v={log:B=>{re?re.log(B):Y?.log(B)},error:B=>{re?re.error(B):Y?.error(B)},terminal:B=>{re?re.terminal(B):Y?.terminal(B)},performance:B=>{re?re.performance(B):Y?.performance(B)},now:()=>re?.now()??Y?.now()??0,elapsed:B=>re?.elapsed(B)??Math.max(0,(Y?.now()??B)-B)},_=v.now(),L=!!(D?.initialAutoProcessingError||D?.initialAutoProcessingPending),ge=!1,s,p=()=>{ge||(ge=!0,L=!0,s=v.now(),v.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},se=!1,ze=()=>{se||(se=!0,v.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),v.performance({stage:"processing",durationMs:v.elapsed(_),durationMode:"machine",paymentMethodCategory:"saved"}),s!==void 0&&v.performance({stage:"recovery",durationMs:v.elapsed(s),durationMode:"machine",paymentMethodCategory:"saved"}))};v.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),v.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),L&&p();let j;try{let B=Si(D?.initialAutoProcessingError),K;if(B)p(),B.type==="paypal_redirect_required"&&Zt.current?.publishableKey&&_i({sessionId:q,publishableKey:Zt.current.publishableKey,paypalPublishableKey:Zt.current.paypalPublishableKey}),K=await yo(B,{flopay:mt.current,paypalFlopay:A.current,attempt3DS:D?.attempt3DS,billingApiUrl:I,sessionId:q,session:g,telemetry:!1}),B.type==="paypal_redirect_required"&&ia();else if(D?.initialAutoProcessingPending){let Se=await new ho(I,{telemetry:!1}).waitForCheckoutSessionCompletion(D.initialAutoProcessingPending.sessionId,{initialDelayMs:D.initialAutoProcessingPending.retryAfterMs});if(Se.data.session?.status!=="complete")throw new Mt("Automatic payment failed. Please try again.","api_error",{code:Se.data.session?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});K={status:"succeeded"}}else{if(D?.initialAutoProcessingError)throw zn(D.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.initialAutoProcessingError.checkoutMethod});if(D?.fromCreateSession)return D?.fallbackToFull&&(gt("full"),xi("full")),!1;{let vt=await Pr({billingApiUrl:I,sessionId:q,session:g,telemetry:!1});vt.type==="success"?K=vt.result:(p(),vt.type==="paypal_redirect_required"&&Zt.current?.publishableKey&&_i({sessionId:q,publishableKey:Zt.current.publishableKey,paypalPublishableKey:Zt.current.paypalPublishableKey}),K=await yo(vt,{flopay:mt.current,paypalFlopay:A.current,attempt3DS:D?.attempt3DS,billingApiUrl:I,sessionId:q,session:g,telemetry:!1}),vt.type==="paypal_redirect_required"&&ia())}}q&&mr(q),ze(),L&&(v.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),v.terminal({outcome:"payment_succeeded",paymentMethodCategory:"saved"}),Ke("success"),await qr(Mn),j=()=>Je.current?.(K)}catch(B){let K=nr(B),vt=K.checkoutMethod??$r;return Ge(K.message),ht(K.message),D?.fallbackToFull&&(v.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),gt("full"),xi("full")),ze(),!!(K.declineCode||K.code?.toLowerCase().includes("declin"))?v.terminal({outcome:"payment_declined",paymentMethodCategory:"saved"}):K.type==="validation_error"?v.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved"}):v.error({errorCode:L?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED",stage:L?"recovery":"processing",paymentMethodCategory:"saved"}),dt(()=>ke.current?.(K)),on(vt,K,{code:K.code,declineCode:K.declineCode}),Ke("error"),await Promise.allSettled([qr(hn),D?.ensureProvidersReady?D.ensureProvidersReady():Promise.resolve()]),L&&(v.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),v.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{ze(),Y&&vo(Y),Ke(null),ht(null)}return dt(j),!0},[on,dt,nr,I,r,S]);An(()=>{if(typeof window>"u"||Rn.current)return;let g=new URLSearchParams(window.location.search),D=g.get("payment_intent_client_secret");if(!D)return;let q=yl();q&&(Rn.current=!0,(async()=>{let ue,re=0;Ge(null),ht(null),Ke("processing"),Ze(!0);try{if(g.get("redirect_status")==="failed")throw Object.assign(new Mt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Y,paypalFlopay:v}=await go({publishableKey:q.publishableKey,paypalPublishableKey:q.paypalPublishableKey,billingApiUrl:I,locale:d,telemetry:r});ue=Tt(v??Y),re=ue?.now()??0,ue?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ue?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let _=(v??Y)?.getRawProvider();if(!_)throw Object.assign(new Mt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:L,error:ge}=await _.retrievePaymentIntent(D);if(ge)throw Object.assign(new Mt(ge.message??"Failed to retrieve PayPal payment status.","api_error",{code:ge.code}),{checkoutMethod:"paypal"});let s=Ya(L?.status);if(!L||s==="failed")throw Object.assign(new Mt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let p=typeof L.payment_method=="string"?L.payment_method:L.payment_method?.id,se=s;if(q.sessionId){let B=(await new ho(I,{telemetry:!1}).getUnifiedCheckoutSession(q.sessionId)).data.session;if(B&&B.status!=="complete"){let K=await Pr({billingApiUrl:I,sessionId:q.sessionId,session:B,telemetry:!1,tokenizedData:{id:p??L.id,type:"card",threeDSecureActionResultTokenId:L.id,isPaypal:!0}});if(K.type!=="success")throw Object.assign(new Mt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});se=K.result.status}}q.sessionId&&mr(q.sessionId),ue?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ue?.performance({stage:"redirect_resume",durationMs:ue.elapsed(re),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ue?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke("success"),await qr(Mn),dt(()=>Je.current?.({status:se,paymentIntentId:L.id,paymentMethodId:p,checkoutMethod:"paypal"}))}catch(Y){let v=nr(Y),_=v.checkoutMethod??"paypal",L=!!(v.declineCode||v.code?.toLowerCase().includes("declin"));if(ue)ue.performance({stage:"redirect_resume",durationMs:ue.elapsed(re),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),L?ue.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ue.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(L){let ge=bo(I,r,S);ge.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),vo(ge)}else oa(I,r,S,"REDIRECT_RESUME_FAILED","redirect_resume");Ge(v.message),ht(v.message),dt(()=>ke.current?.(v)),on(_,v,{code:v.code,declineCode:v.declineCode}),Ke("error"),await qr(hn)}finally{ia(),vl(),Ke(null),ht(null),Ze(!1)}})())},[on,dt,d,nr,I,r]);let yn=jt(null);function sn(g,D=!1){let q=g?.account?.email?.trim().toLowerCase()??"",ue={c:g?.clientId,cur:g?.currency??"",a:{e:q,u:q?"":g?.account?.userId??"",country:g?.account?.country??""},successUrl:g?.successUrl,cancelUrl:g?.cancelUrl,p:g?.products?.map(v=>sa(`${v.type??""}:${v.code??v.providerItemId??v.providerPlanId??""}`,v)).sort(),i:g?.items?.map(v=>sa(v.code??v.providerItemId??"",v)).sort(),s:g?.subscriptions?.map(v=>sa(v.code??v.providerPlanId??"",v)).sort(),couponCodes:g?.couponCodes?[...g.couponCodes].sort():void 0,...D?{tagsData:g?.tagsData,utmMetadata:g?.utmMetadata,tokenizedData:g?.tokenizedData,checkoutMode:g?.checkoutMode??"full"}:{}},re=JSON.stringify(ue),Y=0;for(let v=0;v<re.length;v++)Y=(Y<<5)-Y+re.charCodeAt(v)|0;return`flopay_session_${Math.abs(Y).toString(36)}`}let It=pn(()=>bt?sn(bt):"",[bt]),Nt=jt(bt);Nt.current=bt,An(()=>{it(e??"")},[e]),An(()=>{Vt.current=!1,Ge(xe),ht(null),Ke(null)},[It,xe,e]);async function Ee(g,D){let q=bo(I,r,S),ue=new ho(I,{telemetry:!1});try{let re=g.idempotencyKey!==void 0?Ii(g.idempotencyKey):void 0,Y=re??hl(D),v,_=!1,L=fl(D);q.log({name:L?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let ge=L?.sid??null,s=null;if(ge)try{if(s=await ue.getUnifiedCheckoutSession(ge,L?.nonce),s.data.session?.status==="complete"){if(jo(ge))return{sid:ge,result:s};bl(D),ge=null,s=null,_=!0}}catch{q.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Bi(D),ge=null}if(!ge){!re&&(_||!Y)&&(Y=Ii(),v=Y),Y&&Pl(D,Y);let p=q.now(),se=0;q.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ze={...g,idempotencyKey:Y,avsCheck:!!_e,avsConfig:typeof _e=="object"?_e:void 0,checkoutType:"embedded_checkout",checkoutLayout:Z?"custom_layout":O==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(ze,ll,{configurable:!1,enumerable:!1,value:{onAttempt:j=>{se=Math.max(se,j)}}});try{s=await ue.createAndFetchSession(ze),q.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),q.performance({stage:"session_create",durationMs:q.now()-p,durationMode:"machine",requestCategory:"session_create",attempt:se,statusClass:"2xx"})}catch(j){let B=cl(j,"CHECKOUT_SESSION_CREATE_FAILED","unknown");throw q.performance({stage:"session_create",durationMs:q.now()-p,durationMode:"machine",requestCategory:"session_create",attempt:se,statusClass:B.statusClass}),j instanceof Mt&&j.type==="validation_error"?q.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):B.statusClass==="4xx"?q.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):q.error({...B,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),j}ge=s.data.session?.id??"",ge&&gl(D,ge,s.data.session?.clientSecret)}return{sid:ge??"",result:s,sdkGeneratedIdempotencyKey:v}}finally{vo(q)}}let tt=rr(async(g,D)=>{let q=Nt.current;if(!q)throw new Mt("createSession is required to bootstrap checkout.","validation_error");let ue=$o(q,g),re=sn(ue),Y=Co.get(re);if(!Y){let L={promise:Ee(ue,re),consumers:0,settled:!1};Y=L,Co.set(re,L);let ge=()=>{L.settled=!0,Ei(re,L)};L.promise.then(ge,ge)}Y.consumers+=1;let v=!1,_=()=>{v||(v=!0,Y.consumers-=1,Ei(re,Y))};D?.(_);try{let L=await Y.promise;yn.current=re,g&&(Rt(Kt),kn(B=>Ha(B,g)));let{sid:ge,result:s}=L;Q(s),s.data.session&&Ue(s.data.session),ge&&it(ge);let{publishableKey:p,paypalPublishableKey:se}=fo(s),{flopay:ze,paypalFlopay:j}=await go({publishableKey:p,paypalPublishableKey:se,billingApiUrl:I,locale:d,telemetry:r});return mt.current=ze,De(ze),A.current=j,at(j),m(!1),L}catch(L){throw yn.current===re&&(yn.current=null),L}finally{D||_()}},[d,I,r,S]),nt=jt(an);nt.current=an;let En=jt(tt);En.current=tt;let Kn=rr(async g=>{if(!Cl(g)||Ft)return{sessionId:je,session:F};Jt(!0);try{let D=await tt(g);return{sessionId:D.sid,session:D.result.data.session??null}}finally{Jt(!1)}},[tt,Ft,je,F]);An(()=>{let g=!1,D;if(We(null),It){let re=Nt.current;return gt(Ht),m(!1),yn.current===It?()=>{g=!0}:(Ue(Wa(re,Ie)),(async()=>{let Y=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),v=Ht==="auto"&&!Vt.current&&!Y;v&&(Ge(null),ht(null),Ke("processing"));try{let _=await En.current(void 0,p=>{D=p}),L=_.result.data.session??null;Zt.current=fo(_.result);let ge=aa(_.result),s=jo(_.sid||L?.id);if(!g&&v&&L&&!ge&&!s){Vt.current=!0,await pl(It,_.sdkGeneratedIdempotencyKey,()=>nt.current(L,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:_.result.autoProcessingError,initialAutoProcessingPending:_.result.autoProcessingPending,autoProcessingAttempted:_.result.autoProcessingAttempted,sessionId:_.sid||L.id}));return}!g&&v&&((ge||s)&&(Vt.current=!0),Ke(null),ht(null))}catch(_){if(g)return;let L=_ instanceof Mt||typeof _=="object"&&_!==null&&"code"in _?_.code:void 0;if(v&&L==="session_auto_completed"){Vt.current=!0,Ke("success"),await qr(Mn),g||(dt(()=>{Je.current?.({status:"succeeded"})}),Ke(null),ht(null));return}v&&(Ke(null),ht(null));let ge=_ instanceof Mt?_:new Mt(_ instanceof Error?_.message:"Failed to create session","api_error");We(ge)}finally{D?.(),D=void 0}})(),()=>{g=!0,D?.()})}m(!0);async function q(){let re=!1;try{let v=await new ho(I,{telemetry:!1}).getUnifiedCheckoutSession(yt,t);if(g)return;Q(v);let _=v.data.session??null;if(Ue(_),!_)throw new Mt("No session data returned","api_error");if(_.status==="complete"){m(!1),dt(()=>{$e.current?.(_.successUrl??"")});return}if(_.status==="expired")throw new Mt("Checkout session has expired.","api_error",{code:"checkout_session_expired"});re=!0;let L=Ie??_.checkoutMode??"full";gt(L);let ge=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),s=aa(v);if(L==="auto"&&!Vt.current&&!ge&&!s){Vt.current=!0;let p=ue(v);try{if(await nt.current(_,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>p,sessionId:yt||_.id}),g)return;await p,g||m(!1);return}catch{if(g)return;await p,g||m(!1);return}}await ue(v),g||m(!1)}catch(Y){if(g)return;Y instanceof Mt?!re&&!ml(Y)&&oa(I,r,S,"NETWORK_REQUEST_FAILED","session_read"):oa(I,r,S,"INTERNAL_SDK_ERROR","checkout_mount");let v=Y instanceof Mt?Y:new Mt(Y instanceof Error?Y.message:"Failed to initialize checkout","api_error");We(v),m(!1)}}async function ue(re){let{publishableKey:Y,paypalPublishableKey:v}=fo(re);Zt.current={publishableKey:Y,paypalPublishableKey:v};let{flopay:_,paypalFlopay:L}=await go({publishableKey:Y,paypalPublishableKey:v,billingApiUrl:I,locale:d,telemetry:r});mt.current=_,De(_),A.current=L,at(L)}return q(),()=>{g=!0}},[Ie,It,Ht,Bt,dt,t]);let Wt=rr(async()=>{if(!(Ye||!F)){Ze(!0),Ge(null);try{await an(F,{attempt3DS:!0,fallbackToFull:!0,sessionId:yt||F.id})}finally{Ze(!1)}}},[yt,Ye,an,F]),Ot=la(w),zt=aa(w),_n=pn(()=>{if(!w||!F||!w.data.stripe?.publishableKey)return;let g={appearance:Ne,paymentMethodCreation:"manual",billingApiUrl:I};if(w.data.stripe?.clientSecret)g.clientSecret=w.data.stripe.clientSecret;else{let D=Ri(F).total;g.amount=Math.round(D*100)||F.amount,g.currency=F.currency?.toLowerCase()}return g},[w,F,Ne,I]),Hn=!!(n&&!Z&&O==="buttons"&&me&&Ht==="full"),Ut=pn(()=>({session:F,loading:Gt,error:Ce,checkoutMode:et,inlineSessionDraft:bt,applyInlineSessionPatch:Hn?Kn:void 0,inlineSessionPatchProcessing:Ft}),[F,Gt,Ce,et,bt,Hn,Kn,Ft]),xn=!!n&&O==="buttons"&&!zt&&(!G||!_n),Pt=At?ne(Pn,{status:At,errorMessage:qn}):null;if(Gt){if(l)return kt(Sn,{children:[l,Pt]});if(O==="buttons"){let g=de?.buttonsLayout?.cardButton?.borderRadius??de?.appearance.variables?.borderRadius??8,D=q=>ne("div",{style:{height:q,borderRadius:g,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return kt(Sn,{children:[kt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[c&&D(br),h&&(x||f)&&D(br),h&&D(br),ne("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Pt]})}return kt(Sn,{children:[kt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ne("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ne("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Pt]})}return Ce?C?ne(un.Provider,{value:Ut,children:C(Ce)}):ne(un.Provider,{value:Ut,children:ne("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ce.message})}):xn?kt(Sn,{children:[ne(un.Provider,{value:Ut,children:ne(wl,{onButtonClick:$,showPayPal:c,showStripe:h,showApplePay:x,showGooglePay:f,theme:le,buttonsTheme:J,buttonsStyles:M,cardButtonContent:W,cardBackButtonContent:V,cardTitleContent:ce})}),Pt]}):zt&&F&&Ot?kt(Sn,{children:[ne(un.Provider,{value:Ut,children:kt("div",{className:Pe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Te&&ne(ur,{icon:!1,children:Te}),Lt==="retrying"&&ne("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Lt==="exhausted"&&kt("div",{role:"alert",children:[ne("div",{children:"PayPal is temporarily unavailable. Please try again."}),ne("button",{type:"button",onClick:or,children:"Retry PayPal"})]}),Lt!=="exhausted"&&ne("div",{"aria-hidden":Lt==="retrying"?!0:void 0,style:Lt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ne(ti,{sessionId:yt,nonce:F.clientSecret||void 0,billingApiUrl:I,email:F.customer?.email,clientId:Ot.clientId,environment:Ot.environment,currency:(F.currency??"usd").toUpperCase(),isSubscription:F.mode==="subscription",onComplete:T,onErrorChange:Ge,onDecline:k,onButtonClick:$,onInitializationStateChange:Vn,allowAutomaticRetry:mn===0,session:F,telemetry:r,telemetryContext:S,debug:ae},`paypal-init-${mn}`)})]})}),Pt]}):!G||!_n?ne(Sn,{children:Pt}):et==="confirm"?kt(Sn,{children:[ne(un.Provider,{value:Ut,children:ne(to,{flopay:G,paypalFlopay:Ve,options:_n,children:kt("div",{className:Pe,children:[Te&&ne("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Te}),Re?Re({onConfirm:Wt,isProcessing:Ye}):ne("button",{type:"button",onClick:Wt,disabled:Ye,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Ye?"not-allowed":"pointer",opacity:Ye?.6:1},children:Ye?"Processing...":Me??"Confirm Purchase"})]})})}),Pt]}):kt(Sn,{children:[ne(un.Provider,{value:Ut,children:ne(to,{flopay:G,paypalFlopay:Ve,options:_n,children:Z?kt(Sn,{children:[Te&&ne("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Te}),ne(Sl,{sessionId:yt,nonce:F?.clientSecret||void 0,billingApiUrl:I,session:F,children:Z})]}):ne(ta,{sessionId:yt,nonce:F?.clientSecret||void 0,email:F?.customer?.email,userId:F?.customer?.id,firstName:F?.customer?.firstName,lastName:F?.customer?.lastName,totalAmount:F?Math.round(Ri(F).total*100):0,currency:F?.currency?.toLowerCase()??"usd",onComplete:T,onError:y,onDecline:k,error:Te,onErrorChange:Ge,showPayPal:c,showStripe:h,enabledPaymentMethods:R??w?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:w?.data.stripe?.enabledPaymentMethodCountries,showApplePay:x,showGooglePay:f,layout:O,theme:le,buttonsTheme:J,buttonsStyles:M,appearance:Ne,cardButtonContent:W,cardBackButtonContent:V,cardTitleContent:ce,onButtonClick:$,onBeforeButtonClick:me,enableAVS:_e,...be?{cardFieldOrder:be}:{},...he?{cardPreFormSlot:he}:{},avsLayout:X,country:F?.customer?.country,city:F?.customer?.city,state:F?.customer?.state,onCountryChange:b,onZipChange:E,avsCheck:!!_e,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Z?"custom_layout":O==="buttons"?"buttons_layout":"default_layout",className:Pe,directPaypal:la(w),isSubscription:F?.mode==="subscription",session:F,debug:ae})})}),Pt]})}function Sl({sessionId:e,nonce:t,billingApiUrl:n,session:i,children:r}){return ne(Sn,{children:ra.Children.map(r,a=>{if(!ra.isValidElement(a))return a;let d=a.props,l={};return d.sessionId||(l.sessionId=e),!d.nonce&&t&&(l.nonce=t),d.billingApiUrl||(l.billingApiUrl=n),i?.customer&&(d.email||(l.email=i.customer.email),d.userId||(l.userId=i.customer.id),d.firstName||(l.firstName=i.customer.firstName),d.lastName||(l.lastName=i.customer.lastName)),Object.keys(l).length===0?a:ra.cloneElement(a,l)})})}function wl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:i,showGooglePay:r,theme:a,buttonsTheme:d,buttonsStyles:l,cardButtonContent:C,cardBackButtonContent:T,cardTitleContent:y}){let[k,b]=wt(!1),E=pn(()=>Mi(a),[a]),c=pn(()=>{let f=E?.buttonsLayout??ul(d);return l?{...f,...l,cardButton:{...f.cardButton,...l.cardButton},cardFormContainer:{...f.cardFormContainer,...l.cardFormContainer},backButton:{...f.backButton,...l.backButton},backButtonIcon:{...f.backButtonIcon,...l.backButtonIcon},submitButton:{...f.submitButton,...l.submitButton},title:{...f.title,...l.title}}:f},[E,d,l]),h=E?.buttonsLayout?.cardButton?.borderRadius??E?.appearance.variables?.borderRadius??8,R=f=>ne("div",{style:{height:f,borderRadius:h,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),x=C===void 0?{boxSizing:"border-box",height:br,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(k){let f=c.cardInputBorder??"#e5e7eb",ae=c.cardInputBackground??"white",O=sr(T),le=sr(y);return kt("div",{style:{backgroundColor:c.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...c.cardFormContainer},children:[kt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[kt("button",{type:"button",onClick:()=>b(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:O?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...c.backButton},children:[ne("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...c.backButtonIcon},children:ne("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ne("path",{d:"M15 18l-6-6 6-6"})})}),ne(cr,{content:T})]}),le?ne("div",{style:{flex:1}}):ne("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...c.title},children:ne(Dr,{content:y})})]}),ne("div",{style:{backgroundColor:ae,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ne("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:[ne("div",{style:{flex:1,backgroundColor:ae,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomLeftRadius:8,padding:12,height:45},children:ne("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ne("div",{style:{flex:1,backgroundColor:ae,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomRightRadius:8,padding:12,height:45},children:ne("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ne("div",{style:{backgroundColor:ae,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ne("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ne("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...c.submitButton,opacity:.5}}),ne("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&&ne("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:f=>{f.currentTarget.style.transform="scale(0.985)"},onMouseUp:f=>{f.currentTarget.style.transform="scale(1)"},children:ne(sr,{content:C})}),ne("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{useEffect as Cl,useRef as Mi,useContext as Sl}from"react";import{jsx as Rl}from"react/jsx-runtime";function Bi(e,t){function n({className:i,id:r,style:a,options:c,onChange:s,onReady:C,onFocus:B,onBlur:m,onEscape:k}){let v=Mi(null),E=Mi(null),{elements:l,reportInteractive:y}=Sl(Tn);return Cl(()=>{if(!l||!v.current)return;let S=!0;return(async()=>{let T=l.getElement(e);T||(T=await l.create(e,c)),!(!S||!v.current)&&(T.mount(v.current),E.current=T,s&&T.on("change",s),T.on("ready",()=>{y?.(),C?.()}),B&&T.on("focus",B),m&&T.on("blur",m),k&&T.on("escape",k))})(),()=>{if(S=!1,E.current){try{E.current.unmount()}catch{}E.current=null}}},[l,y]),Rl("div",{ref:v,className:i,id:r,style:a})}return n.displayName=t,n}var wl=Bi("payment","PaymentElement"),kl=Bi("address","AddressElement");import{PaymentAPI as Il}from"@flopay/js";import{FloPayError as El}from"@flopay/shared";import{useCallback as ua,useEffect as _l,useRef as xl,useState as Ai}from"react";import{Fragment as Ml,jsx as br,jsxs as Bl}from"react/jsx-runtime";function Tl({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,firstName:a,lastName:c,chv:s,onTokenizedBody:C,onComplete:B,onErrorChange:m,isProcessing:k=!1}){let v=vn(),E=zo(),l=to(),[y,S]=Ai(!1),[T,f]=Ai(!1),$=xl(!1),Y=(n||l).replace(/\/+$/,""),ye=ua(async J=>{try{let fe=await new Il(Y).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:J,accountData:{userId:r??"",email:i??"",firstName:a??"",lastName:c??""},chv:s});if(fe.ok){B?.();return}let D=await fe.json().catch(()=>null);m?.(D?.message??"Payment failed. Please try again.")}catch(q){m?.(q instanceof Error?q.message:"An unexpected error occurred")}},[Y,e,t,r,i,a,c,s,B,m]),ee=ua(J=>{C?C(J):ye(J)},[C,ye]);_l(()=>{if(!v||$.current)return;let J=new URLSearchParams(window.location.search),q=J.get("payment_intent"),fe=J.get("payment_intent_client_secret"),D=J.get("redirect_status");!q||!fe||($.current=!0,(async()=>{try{if(f(!0),D==="failed"){m?.("PayPal payment was declined. Please try again.");return}let j=v.getRawProvider();if(!j?.retrievePaymentIntent){m?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ae,error:Be}=await j.retrievePaymentIntent(fe);if(Be){m?.(Be.message??"Failed to retrieve PayPal payment status.");return}if(ae&&(ae.status==="requires_capture"||ae.status==="succeeded")){let be=typeof ae.payment_method=="string"?ae.payment_method:ae.payment_method?.id;ee({id:be??ae.id,type:"card",threeDSecureActionResultTokenId:ae.id,isPaypal:!0});let Pe=new URL(window.location.href);Pe.searchParams.delete("payment_intent"),Pe.searchParams.delete("payment_intent_client_secret"),Pe.searchParams.delete("redirect_status"),window.history.replaceState({},"",Pe.toString())}else m?.("PayPal payment was not completed. Please try again.")}catch(j){m?.(j instanceof Error?j.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[v,ee,m]);let A=ua(async()=>{if(!(!v||!E))try{if(f(!0),m?.(null),!e||!i)throw new El("Missing sessionId or email for PayPal payment","validation_error");let J=await v.confirmPayPalPayment({billingApiUrl:Y,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(J.error){m?.(J.error.message);return}J.paymentIntentId&&(J.status==="succeeded"||J.status==="processing"||J.status==="requires_capture")&&ee({id:J.paymentMethodId??J.paymentIntentId,type:"card",threeDSecureActionResultTokenId:J.paymentIntentId,isPaypal:!0})}catch(J){m?.(J instanceof Error?J.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[v,E,e,t,i,Y,ee,m]);return!v||!E?br("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):Bl(Ml,{children:[!y&&br("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),br("div",{style:y?{}:{display:"none"},children:br("button",{type:"button",onClick:A,disabled:T||k,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:T||k?"not-allowed":"pointer",opacity:T||k?.6:1},ref:()=>S(!0),children:T?"Processing...":"PayPal"})}),(T||k)&&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 $n,useEffect as vr,useMemo as qr,useRef as Cr,useState as Co}from"react";import{PaymentAPI as pa}from"@flopay/js";import{FloPayError as qn,resolveBillingApiUrl as Al,resolveButtonsLayoutTheme as Fl,resolveTheme as Dl}from"@flopay/shared";import{Fragment as $l,jsx as Sr,jsxs as ql}from"react/jsx-runtime";var Ll=44;function Fi(e){return new Promise(t=>setTimeout(t,e))}function Nl(e,t){return e instanceof qn?e:new qn(e instanceof Error?e.message:t,"api_error")}function Ol(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function zl(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 Ul({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:r,clientId:a,products:c,items:s,subscriptions:C,account:B,successUrl:m,cancelUrl:k,couponCodes:v,tagsData:E,utmMetadata:l,billingApiUrl:y,locale:S,theme:T,appearance:f,buttonsTheme:$,buttonsStyles:Y,onSuccess:ye,onError:ee,onDecline:A,children:J,disabled:q=!1,type:fe="button",style:D,...j}){let ae=qr(()=>Al(y),[y]),Be=qr(()=>zl({createSession:n,clientId:a,products:c,items:s,subscriptions:C,account:B,successUrl:m,cancelUrl:k,couponCodes:v,tagsData:E,utmMetadata:l}),[B,k,a,v,n,c,s,C,m,E,l]),[be,Pe]=Co(!1),[X,ge]=Co(null),[we,ie]=Co(null),[Fe,_e]=Co(null),Re=Cr(!0),w=Cr(null),re=Cr(Fe),ce=Cr(ye),Ne=Cr(ee),De=Cr(A);vr(()=>{re.current=Fe},[Fe]),vr(()=>{ce.current=ye},[ye]),vr(()=>{Ne.current=ee},[ee]),vr(()=>{De.current=A},[A]),vr(()=>(Re.current=!0,()=>{Re.current=!1,w.current?.abort()}),[]),vr(()=>{if(typeof window>"u")return;let g=Ie=>{Ie.key==="Escape"&&_e(null)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);let G=$n((g,Ie=Ur)=>{De.current?.(wt(Ie,g,{code:g.code,declineCode:g.declineCode}))},[]),x=$n(async g=>{Re.current&&(ie(null),ge("success"),await Fi(Mn),Re.current&&ce.current?.(g))},[]),K=$n(async(g,Ie)=>{Re.current&&(Ne.current?.(g),Ie?.emitDecline&&G(g,Ie.method),ie(g.message),ge("error"),await Fi(Cn))},[G]),de=$n(async(g,Ie,$e)=>{let st=g.data.session??null;if(!st)throw new qn("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||Ie,autoCompleted:!1});return}if(st.status==="expired")throw new qn("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(g.autoProcessingPending){let vt=(await new pa(ae).waitForCheckoutSessionCompletion(g.autoProcessingPending.sessionId,{initialDelayMs:g.autoProcessingPending.retryAfterMs})).data.session;if(!vt||vt.status!=="complete")throw new qn("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||Ie,autoCompleted:!1});return}if(g.autoProcessingError){if(g.autoProcessingError.type==="3ds_required"&&g.autoProcessingError.nextActionRedirectUrl&&Ie&&rt){let Ge=new AbortController;w.current=Ge;let ke;try{ke=await Ci({billingApiUrl:ae,sessionId:Ie,nonce:rt,nextActionRedirectUrl:g.autoProcessingError.nextActionRedirectUrl,signal:Ge.signal})}finally{w.current===Ge&&(w.current=null)}if(ke.status==="declined")throw Un({type:ke.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:ke.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:g.autoProcessingError.checkoutMethod});let zt=(await new pa(ae).waitForCheckoutSessionCompletion(Ie,{initialDelayMs:0,nonce:rt})).data.session;if(!zt||zt.status!=="complete")throw Un({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:g.autoProcessingError.checkoutMethod});await x({result:{status:"succeeded"},session:zt,sessionId:zt.id||Ie,autoCompleted:!1});return}throw Un(g.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:g.autoProcessingError.checkoutMethod})}if($e?.fromCreateSession&&g.autoProcessingAttempted===!0)throw Un({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let et=await hr({billingApiUrl:ae,sessionId:Ie??st.id,session:st,nonce:rt});if(et.type!=="success")throw Un({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||Ie,autoCompleted:!1})}catch(et){let Ge=tr(et),ke=st.id||Ie;await K(Ge,{emitDecline:!0,method:Ge.checkoutMethod??Ur}),Ol(Ge,ke)&&ke&&Re.current&&_e({sessionId:ke,errorMessage:Ge.message,nonce:rt||void 0})}},[t,ae,K,x]),xe=$n(async g=>{if(j.onClick?.(g),!(g.defaultPrevented||q||be)){if(_e(null),e&&Be){let Ie=new qn("Provide either sessionId or create-session props, not both.","validation_error");await K(Ie),Re.current&&(ge(null),ie(null));return}if(!e&&!Be){let Ie=new qn("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await K(Ie),Re.current&&(ge(null),ie(null));return}Pe(!0),ie(null),ge("processing");try{let Ie=new pa(ae);if(e){let $e=await Ie.getUnifiedCheckoutSession(e,t);await de($e,e);return}try{let $e=await Ie.createAndFetchSession({...Be});await de($e,$e.data.session?.id??null,{fromCreateSession:!0})}catch($e){if($e instanceof qn&&$e.code==="session_auto_completed"){await x({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw $e}}catch(Ie){await K(Nl(Ie,"Automatic payment failed. Please try again."))}finally{Re.current&&(ge(null),ie(null),Pe(!1))}}},[j,Be,q,be,t,de,ae,e,K,x]),it=$n(g=>{let Ie=re.current;_e(null),ce.current?.({result:g,session:null,sessionId:Ie?.sessionId??null,autoCompleted:!1})},[]),Qe=$n(g=>{Ne.current?.(g)},[]),Ze=$n(g=>{De.current?.(g)},[]),p=qr(()=>Dl(T),[T]),ze=qr(()=>{let g=p?.buttonsLayout??Fl($);return Y?{...g,...Y,cardButton:{...g.cardButton,...Y.cardButton}}:g},[p,$,Y]),Oe=qr(()=>{let g=p?.appearance;return f?g?{...g,...f,variables:{...g.variables,...f.variables}}:f:g},[f,p]),Ve=Oe?.variables,Ue=Ve?.colorPrimary??"#4A49FF",Yt=Ve?.colorPrimaryHover??lo(Ue,.12),bt=Ve?.borderRadius??"8px";return ql($l,{children:[Sr("button",{...j,type:fe,onClick:xe,disabled:q||be,"aria-busy":be,style:{width:"100%",...J===void 0?{boxSizing:"border-box",height:Ll,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...ze.cardButton,...Qo({themeBundle:p,resolvedPrimaryColor:Ue,resolvedBorderRadius:bt,submitButtonStyle:ze.submitButton,explicitPrimaryColor:Ve?.colorPrimary}),fontSize:ze.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:q||be?"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:q||be?.6:1,...D},onMouseEnter:g=>{j.onMouseEnter?.(g),!g.defaultPrevented&&!q&&!be&&(p||Ve?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Yt)},onMouseLeave:g=>{j.onMouseLeave?.(g),!g.defaultPrevented&&(p||Ve?.colorPrimary)&&(g.currentTarget.style.backgroundColor=Ue)},onMouseDown:g=>{j.onMouseDown?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(0.985)")},onMouseUp:g=>{j.onMouseUp?.(g),g.defaultPrevented||(g.currentTarget.style.transform="scale(1)")},children:Sr(sr,{content:J})}),X&&Sr(Sn,{status:X,errorMessage:we}),Fe&&Sr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:g=>{g.target===g.currentTarget&&_e(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(da,{sessionId:Fe.sessionId,nonce:Fe.nonce,checkoutMode:"full",billingApiUrl:ae,locale:S,theme:T,...Oe?{appearance:Oe}:{},buttonsTheme:$,buttonsStyles:Y,initialErrorMessage:Fe.errorMessage,cardTitleContent:null,onComplete:it,onError:Qe,onDecline:Ze})})})]})}export{kl as AddressElement,so as DirectPayPalButton,Ul as FloPayAutomaticPaymentButton,da as FloPayCheckout,eo as FloPayProvider,Tl as PayPalButton,wl as PaymentElement,ea as SplitCardForm,No as VaultCardFields,ms as useCheckout,zo as useElements,vn as useFloPay,Oo as usePayPalFloPay};
47
+ `})]})}return kt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&R(br),n&&(i||r)&&R(br),n&&ne("button",{type:"button",onClick:()=>{e?.("card"),b(!0)},style:{width:"100%",...x,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:c.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,...c.cardButton},onMouseDown:f=>{f.currentTarget.style.transform="scale(0.985)"},onMouseUp:f=>{f.currentTarget.style.transform="scale(1)"},children:ne(lr,{content:C})}),ne("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{useEffect as kl,useRef as Ai,useContext as Rl}from"react";import{jsx as _l}from"react/jsx-runtime";function Fi(e,t){function n({className:i,id:r,style:a,options:d,onChange:l,onReady:C,onFocus:T,onBlur:y,onEscape:k}){let b=Ai(null),E=Ai(null),{elements:c,reportInteractive:h}=Rl(Tn);return kl(()=>{if(!c||!b.current)return;let R=!0;return(async()=>{let x=c.getElement(e);x||(x=await c.create(e,d)),!(!R||!b.current)&&(x.mount(b.current),E.current=x,l&&x.on("change",l),x.on("ready",()=>{h?.(),C?.()}),T&&x.on("focus",T),y&&x.on("blur",y),k&&x.on("escape",k))})(),()=>{if(R=!1,E.current){try{E.current.unmount()}catch{}E.current=null}}},[c,h]),_l("div",{ref:b,className:i,id:r,style:a})}return n.displayName=t,n}var Il=Fi("payment","PaymentElement"),El=Fi("address","AddressElement");import{PaymentAPI as xl}from"@flopay/js";import{FloPayError as Tl}from"@flopay/shared";import{useCallback as pa,useEffect as Ml,useRef as Bl,useState as Di}from"react";import{Fragment as Fl,jsx as vr,jsxs as Dl}from"react/jsx-runtime";function Al({sessionId:e,nonce:t,billingApiUrl:n,email:i,userId:r,firstName:a,lastName:d,chv:l,onTokenizedBody:C,onComplete:T,onErrorChange:y,isProcessing:k=!1}){let b=gn(),E=Uo(),c=no(),[h,R]=Di(!1),[x,f]=Di(!1),ae=Bl(!1),O=(n||c).replace(/\/+$/,""),le=pa(async W=>{try{let ce=await new xl(O).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:W,accountData:{userId:r??"",email:i??"",firstName:a??"",lastName:d??""},chv:l});if(ce.ok){T?.();return}let z=await ce.json().catch(()=>null);y?.(z?.message??"Payment failed. Please try again.")}catch(V){y?.(V instanceof Error?V.message:"An unexpected error occurred")}},[O,e,t,r,i,a,d,l,T,y]),J=pa(W=>{C?C(W):le(W)},[C,le]);Ml(()=>{if(!b||ae.current)return;let W=new URLSearchParams(window.location.search),V=W.get("payment_intent"),ce=W.get("payment_intent_client_secret"),z=W.get("redirect_status");!V||!ce||(ae.current=!0,(async()=>{try{if(f(!0),z==="failed"){y?.("PayPal payment was declined. Please try again.");return}let $=b.getRawProvider();if(!$?.retrievePaymentIntent){y?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:me,error:_e}=await $.retrievePaymentIntent(ce);if(_e){y?.(_e.message??"Failed to retrieve PayPal payment status.");return}if(me&&(me.status==="requires_capture"||me.status==="succeeded")){let be=typeof me.payment_method=="string"?me.payment_method:me.payment_method?.id;J({id:be??me.id,type:"card",threeDSecureActionResultTokenId:me.id,isPaypal:!0});let he=new URL(window.location.href);he.searchParams.delete("payment_intent"),he.searchParams.delete("payment_intent_client_secret"),he.searchParams.delete("redirect_status"),window.history.replaceState({},"",he.toString())}else y?.("PayPal payment was not completed. Please try again.")}catch($){y?.($ instanceof Error?$.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[b,J,y]);let M=pa(async()=>{if(!(!b||!E))try{if(f(!0),y?.(null),!e||!i)throw new Tl("Missing sessionId or email for PayPal payment","validation_error");let W=await b.confirmPayPalPayment({billingApiUrl:O,sessionId:e,nonce:t,email:i,returnUrl:window.location.href});if(W.error){y?.(W.error.message);return}W.paymentIntentId&&(W.status==="succeeded"||W.status==="processing"||W.status==="requires_capture")&&J({id:W.paymentMethodId??W.paymentIntentId,type:"card",threeDSecureActionResultTokenId:W.paymentIntentId,isPaypal:!0})}catch(W){y?.(W instanceof Error?W.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[b,E,e,t,i,O,J,y]);return!b||!E?vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):Dl(Fl,{children:[!h&&vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),vr("div",{style:h?{}:{display:"none"},children:vr("button",{type:"button",onClick:M,disabled:x||k,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:x||k?"not-allowed":"pointer",opacity:x||k?.6:1},ref:()=>R(!0),children:x?"Processing...":"PayPal"})}),(x||k)&&vr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:vr("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 Cr,useMemo as jr,useRef as Sr,useState as So}from"react";import{PaymentAPI as ma}from"@flopay/js";import{FloPayError as $n,resolveBillingApiUrl as Ll,resolveButtonsLayoutTheme as Nl,resolveTheme as Ol}from"@flopay/shared";import{Fragment as Vl,jsx as wr,jsxs as Kl}from"react/jsx-runtime";var zl=44;function Li(e){return new Promise(t=>setTimeout(t,e))}function Ul(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 ql(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 jl({sessionId:e,nonce:t,createSession:n,paymentMethodId:i,checkoutMethod:r,clientId:a,products:d,items:l,subscriptions:C,account:T,successUrl:y,cancelUrl:k,couponCodes:b,tagsData:E,utmMetadata:c,billingApiUrl:h,locale:R,theme:x,appearance:f,buttonsTheme:ae,buttonsStyles:O,onSuccess:le,onError:J,onDecline:M,children:W,disabled:V=!1,type:ce="button",style:z,...$}){let me=jr(()=>Ll(h),[h]),_e=jr(()=>ql({createSession:n,clientId:a,products:d,items:l,subscriptions:C,account:T,successUrl:y,cancelUrl:k,couponCodes:b,tagsData:E,utmMetadata:c}),[T,k,a,b,n,d,l,C,y,E,c]),[be,he]=So(!1),[X,Pe]=So(null),[xe,Z]=So(null),[Ie,Me]=So(null),Re=Sr(!0),H=Sr(null),I=Sr(Ie),de=Sr(le),Ne=Sr(J),Oe=Sr(M);Cr(()=>{I.current=Ie},[Ie]),Cr(()=>{de.current=le},[le]),Cr(()=>{Ne.current=J},[J]),Cr(()=>{Oe.current=M},[M]),Cr(()=>(Re.current=!0,()=>{Re.current=!1,H.current?.abort()}),[]),Cr(()=>{if(typeof window>"u")return;let m=Ce=>{Ce.key==="Escape"&&Me(null)};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[]);let ye=Un((m,Ce=$r)=>{Oe.current?.(St(Ce,m,{code:m.code,declineCode:m.declineCode}))},[]),w=Un(async m=>{Re.current&&(Z(null),Pe("success"),await Li(Mn),Re.current&&de.current?.(m))},[]),Q=Un(async(m,Ce)=>{Re.current&&(Ne.current?.(m),Ce?.emitDecline&&ye(m,Ce.method),Z(m.message),Pe("error"),await Li(hn))},[ye]),G=Un(async(m,Ce,We)=>{let et=m.data.session??null;if(!et)throw new $n("No session data returned","api_error");let gt=et.clientSecret||t;if(et.status==="complete"){await w({result:{status:"succeeded"},session:et,sessionId:et.id||Ce,autoCompleted:!1});return}if(et.status==="expired")throw new $n("Checkout session has expired.","api_error",{code:"checkout_session_expired"});try{if(m.autoProcessingPending){let Ge=(await new ma(me).waitForCheckoutSessionCompletion(m.autoProcessingPending.sessionId,{initialDelayMs:m.autoProcessingPending.retryAfterMs})).data.session;if(!Ge||Ge.status!=="complete")throw new $n("Automatic payment failed. Please try again.","api_error",{code:Ge?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"});await w({result:{status:"succeeded"},session:Ge,sessionId:Ge.id||Ce,autoCompleted:!1});return}if(m.autoProcessingError){if(m.autoProcessingError.type==="3ds_required"&&m.autoProcessingError.nextActionRedirectUrl&&Ce&&gt){let Ze=new AbortController;H.current=Ze;let Te;try{Te=await wi({billingApiUrl:me,sessionId:Ce,nonce:gt,nextActionRedirectUrl:m.autoProcessingError.nextActionRedirectUrl,signal:Ze.signal})}finally{H.current===Ze&&(H.current=null)}if(Te.status==="declined")throw zn({type:Te.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Te.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:m.autoProcessingError.checkoutMethod});let Ke=(await new ma(me).waitForCheckoutSessionCompletion(Ce,{initialDelayMs:0,nonce:gt})).data.session;if(!Ke||Ke.status!=="complete")throw zn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:m.autoProcessingError.checkoutMethod});await w({result:{status:"succeeded"},session:Ke,sessionId:Ke.id||Ce,autoCompleted:!1});return}throw zn(m.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:m.autoProcessingError.checkoutMethod})}if(We?.fromCreateSession&&m.autoProcessingAttempted===!0)throw zn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ye=await Pr({billingApiUrl:me,sessionId:Ce??et.id,session:et,nonce:gt});if(Ye.type!=="success")throw zn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await w({result:Ye.result,session:et,sessionId:et.id||Ce,autoCompleted:!1})}catch(Ye){let Ze=nr(Ye),Te=et.id||Ce;await Q(Ze,{emitDecline:!0,method:Ze.checkoutMethod??$r}),$l(Ze,Te)&&Te&&Re.current&&Me({sessionId:Te,errorMessage:Ze.message,nonce:gt||void 0})}},[t,me,Q,w]),De=Un(async m=>{if($.onClick?.(m),!(m.defaultPrevented||V||be)){if(Me(null),e&&_e){let Ce=new $n("Provide either sessionId or create-session props, not both.","validation_error");await Q(Ce),Re.current&&(Pe(null),Z(null));return}if(!e&&!_e){let Ce=new $n("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Q(Ce),Re.current&&(Pe(null),Z(null));return}he(!0),Z(null),Pe("processing");try{let Ce=new ma(me);if(e){let We=await Ce.getUnifiedCheckoutSession(e,t);await G(We,e);return}try{let We=await Ce.createAndFetchSession({..._e});await G(We,We.data.session?.id??null,{fromCreateSession:!0})}catch(We){if(We instanceof $n&&We.code==="session_auto_completed"){await w({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw We}}catch(Ce){await Q(Ul(Ce,"Automatic payment failed. Please try again."))}finally{Re.current&&(Pe(null),Z(null),he(!1))}}},[$,_e,V,be,t,G,me,e,Q,w]),mt=Un(m=>{let Ce=I.current;Me(null),de.current?.({result:m,session:null,sessionId:Ce?.sessionId??null,autoCompleted:!1})},[]),Ve=Un(m=>{Ne.current?.(m)},[]),at=Un(m=>{Oe.current?.(m)},[]),A=jr(()=>Ol(x),[x]),F=jr(()=>{let m=A?.buttonsLayout??Nl(ae);return O?{...m,...O,cardButton:{...m.cardButton,...O.cardButton}}:m},[A,ae,O]),Ue=jr(()=>{let m=A?.appearance;return f?m?{...m,...f,variables:{...m.variables,...f.variables}}:f:m},[f,A]),je=Ue?.variables,it=je?.colorPrimary??"#4A49FF",yt=je?.colorPrimaryHover??co(it,.12),Bt=je?.borderRadius??"8px";return Kl(Vl,{children:[wr("button",{...$,type:ce,onClick:De,disabled:V||be,"aria-busy":be,style:{width:"100%",...W===void 0?{boxSizing:"border-box",height:zl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...F.cardButton,...ea({themeBundle:A,resolvedPrimaryColor:it,resolvedBorderRadius:Bt,submitButtonStyle:F.submitButton,explicitPrimaryColor:je?.colorPrimary}),fontSize:F.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:V||be?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:V||be?.6:1,...z},onMouseEnter:m=>{$.onMouseEnter?.(m),!m.defaultPrevented&&!V&&!be&&(A||je?.colorPrimary)&&(m.currentTarget.style.backgroundColor=yt)},onMouseLeave:m=>{$.onMouseLeave?.(m),!m.defaultPrevented&&(A||je?.colorPrimary)&&(m.currentTarget.style.backgroundColor=it)},onMouseDown:m=>{$.onMouseDown?.(m),m.defaultPrevented||(m.currentTarget.style.transform="scale(0.985)")},onMouseUp:m=>{$.onMouseUp?.(m),m.defaultPrevented||(m.currentTarget.style.transform="scale(1)")},children:wr(lr,{content:W})}),X&&wr(Pn,{status:X,errorMessage:xe}),Ie&&wr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:m=>{m.target===m.currentTarget&&Me(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:wr("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:wr(ua,{sessionId:Ie.sessionId,nonce:Ie.nonce,checkoutMode:"full",billingApiUrl:me,locale:R,theme:x,...Ue?{appearance:Ue}:{},buttonsTheme:ae,buttonsStyles:O,initialErrorMessage:Ie.errorMessage,cardTitleContent:null,onComplete:mt,onError:Ve,onDecline:at})})})]})}export{El as AddressElement,lo as DirectPayPalButton,jl as FloPayAutomaticPaymentButton,ua as FloPayCheckout,to as FloPayProvider,Al as PayPalButton,Il as PaymentElement,ta as SplitCardForm,Oo as VaultCardFields,fs as useCheckout,Uo as useElements,gn as useFloPay,zo as usePayPalFloPay};